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 ba45a03693..640480f6e8 100644 --- a/seaweed-block/core/frontend/durable/cut_loop_fence_test.go +++ b/seaweed-block/core/frontend/durable/cut_loop_fence_test.go @@ -2,10 +2,15 @@ package durable import ( "context" + "fmt" + "os" + "path/filepath" + "strings" "sync/atomic" "testing" "time" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -46,3 +51,75 @@ func TestChunkLoop_EndsWhenTheLayerIsFenced(t *testing.T) { t.Fatal("the cut loop kept running after the layer was fenced") } } + +// refusingLayer refuses every cut with err. +type refusingLayer struct { + storage.ChunkLayer // unused methods panic + err error + cuts atomic.Int32 +} + +func (l *refusingLayer) Fenced() bool { return false } +func (l *refusingLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} } +func (l *refusingLayer) Cut(context.Context) (storage.ChunkCutResult, error) { + l.cuts.Add(1) + return storage.ChunkCutResult{}, l.err +} + +// The timer holds a host ticket while a refusal is a wait, and gives it up, +// with the reason in status, on a refusal that waiting cannot fix. +func TestChunkLoop_TicketKeptForAWaitDroppedOtherwise(t *testing.T) { + c := hostlimit.DefaultConfig(t.TempDir()) + lim, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer lim.Close() + tickets := func() int { + ents, _ := os.ReadDir(filepath.Join(c.Directory, "tickets")) + return len(ents) + } + for _, tc := range []struct { + name string + err error + keep bool + dropText string + }{ + {"wait", fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrNotHead), true, ""}, + {"oversized payload", fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrBusy), false, "no background slot"}, + } { + t.Run(tc.name, func(t *testing.T) { + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkBudget: lim}} + layer := &refusingLayer{err: tc.err} + wait := &cutWaitSlot{} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go p.chunkLoop(ctx, "v1", layer, done, wait, nil) + stop := 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") + } + } + t.Cleanup(stop) // every path, a failing assertion too + for deadline := time.Now().Add(5 * time.Second); layer.cuts.Load() < 3; time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("the loop did not try") + } + } + st := wait.status(0) + if tc.keep && (tickets() != 1 || st.TicketDueHostNs == 0) { + t.Fatalf("a wait must keep one ticket: files=%d status=%+v", tickets(), st) + } + if !tc.keep && (st.TicketDueHostNs != 0 || !strings.Contains(st.TicketDropReason, tc.dropText)) { + t.Fatalf("a refusal that waiting cannot fix must drop the ticket with its reason: %+v", st) + } + stop() + if tickets() != 0 { + t.Fatalf("%d ticket files left after the loop ended", tickets()) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/cut_loop_ticket_order_test.go b/seaweed-block/core/frontend/durable/cut_loop_ticket_order_test.go new file mode 100644 index 0000000000..dbb2e8bb52 --- /dev/null +++ b/seaweed-block/core/frontend/durable/cut_loop_ticket_order_test.go @@ -0,0 +1,195 @@ +package durable + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// recordingBudget is a real limiter that records each ticket's due time, and +// can fail ticket creation. +type recordingBudget struct { + *hostlimit.Limiter + mu sync.Mutex + dues []int64 + fail error +} + +func (b *recordingBudget) TakeTicket(due int64) (*hostlimit.Ticket, error) { + b.mu.Lock() + fail := b.fail + b.mu.Unlock() + if fail != nil { + return nil, fail + } + t, err := b.Limiter.TakeTicket(due) + if err == nil { + b.mu.Lock() + b.dues = append(b.dues, due) + b.mu.Unlock() + } + return t, err +} + +func (b *recordingBudget) taken() []int64 { + b.mu.Lock() + defer b.mu.Unlock() + return append([]int64(nil), b.dues...) +} + +// admittingLayer admits each cut through the budget (the limiter consumes +// its ticket), stages a chunk and then fails, as a cut that fails after +// staging does; admissions counts the admissions it made. +type admittingLayer struct { + storage.ChunkLayer // unused methods panic + budget storage.Budget + cuts, admissions atomic.Int32 + staged atomic.Uint64 +} + +func (l *admittingLayer) Fenced() bool { return false } +func (l *admittingLayer) Stats() storage.ChunkLayerStats { + return storage.ChunkLayerStats{StagedChunks: l.staged.Load()} +} +func (l *admittingLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { + l.cuts.Add(1) + id, err := l.budget.Admit(ctx, 1, nil) + if err != nil { + return storage.ChunkCutResult{}, err + } + l.admissions.Add(1) + l.budget.Release(id) + l.staged.Add(1) + return storage.ChunkCutResult{}, errors.New("test: the cut failed after staging") +} + +// startLoop runs the cut loop and registers its end: cancel, then a bounded +// join, on every path of the test. +func startLoop(t *testing.T, p *DurableProvider, layer storage.ChunkLayer) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go p.chunkLoop(ctx, "v1", layer, done, &cutWaitSlot{}, 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") + } + }) +} + +func newRecordingBudget(t *testing.T) *recordingBudget { + t.Helper() + lim, err := hostlimit.New(hostlimit.DefaultConfig(t.TempDir())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(lim.Close) + return &recordingBudget{Limiter: lim} +} + +// A cut admitted on its ticket that then fails is retried on a fresh ticket +// at the back of the queue (the host's now), never again at its old due +// time, which would put it ahead of every cut that waited meanwhile. +func TestChunkLoop_AConsumedAttemptRetriesAtTheBack(t *testing.T) { + b := newRecordingBudget(t) + layer := &admittingLayer{budget: b} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkBudget: b}} + startLoop(t, p, layer) + for deadline := time.Now().Add(5 * time.Second); len(b.taken()) < 2; time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("the loop took %d tickets, want a retry's second one", len(b.taken())) + } + } + dues := b.taken() + if dues[1] <= dues[0] { + t.Fatalf("the retry's ticket is due at %d, not after its first one at %d: it re-entered at its old place", dues[1], dues[0]) + } +} + +// A timer cut that cannot take a ticket does not cut un-ticketed (it would +// pass every earlier ticket): it waits and tries again at the next poll. +func TestChunkLoop_NoTicketNoCut(t *testing.T) { + b := newRecordingBudget(t) + b.fail = errors.New("test: the tickets directory is unavailable") + layer := &admittingLayer{budget: b} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkBudget: b}} + startLoop(t, p, layer) + time.Sleep(300 * time.Millisecond) + if n := layer.cuts.Load(); n != 0 { + t.Fatalf("the loop cut %d times without a ticket", n) + } +} + +// scriptLayer: its first cut is admitted (consuming the ticket) and fails +// after staging; its second is refused as a wait (not the head) and then the +// layer reconciles briefly, which drops the held ticket; every later cut is +// admitted and succeeds. +type scriptLayer struct { + storage.ChunkLayer // unused methods panic + budget storage.Budget + cuts atomic.Int32 + staged atomic.Uint64 + mu sync.Mutex + reconcileUntil time.Time +} + +func (l *scriptLayer) Fenced() bool { return false } +func (l *scriptLayer) Stats() storage.ChunkLayerStats { + l.mu.Lock() + rec := time.Now().Before(l.reconcileUntil) + l.mu.Unlock() + return storage.ChunkLayerStats{StagedChunks: l.staged.Load(), Reconciling: rec} +} +func (l *scriptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { + switch l.cuts.Add(1) { + case 1: + id, err := l.budget.Admit(ctx, 1, nil) + if err != nil { + return storage.ChunkCutResult{}, err + } + l.budget.Release(id) + l.staged.Add(1) + return storage.ChunkCutResult{}, errors.New("test: the cut failed after staging") + case 2: + l.mu.Lock() + l.reconcileUntil = time.Now().Add(300 * time.Millisecond) + l.mu.Unlock() + return storage.ChunkCutResult{}, fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrNotHead) + } + id, err := l.budget.Admit(ctx, 1, nil) + if err != nil { + return storage.ChunkCutResult{}, err + } + l.budget.Release(id) + return storage.ChunkCutResult{}, nil +} + +// Once a cut was admitted and failed, every later ticket of that turn is at +// the back: a wait that keeps the ticket, then a drop (here a reconcile) and +// a new ticket, never brings back the schedule's old due time, which would +// pass every cut that queued meanwhile. +func TestChunkLoop_ARequeuedTurnStaysAtTheBackAcrossAWaitAndADrop(t *testing.T) { + b := newRecordingBudget(t) + layer := &scriptLayer{budget: b} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkBudget: b}} + startLoop(t, p, layer) + for deadline := time.Now().Add(5 * time.Second); len(b.taken()) < 3; time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("the loop took %d tickets, want 3 (first, the retry's, and one after the drop)", len(b.taken())) + } + } + dues := b.taken() + if dues[1] <= dues[0] || dues[2] < dues[1] { + t.Fatalf("ticket dues %d, %d, %d: after the first admission each new ticket must be at the back", dues[0], dues[1], dues[2]) + } +} diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index c6bfad5f8e..df17df8579 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -6,7 +6,6 @@ package durable import ( "errors" "fmt" - "math/rand/v2" "testing" "time" @@ -213,14 +212,12 @@ func TestCutPolicy_TimerRunsOnObservationTime(t *testing.T) { } // 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. +// no minimum spacing, the timer is not reset, and the retry is due at the +// next poll (admission order is the host ticket order). 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) + busy := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrNotHead) s := cutSchedule{lastSuccess: t0} now := at(30 * time.Second) for i := 0; i < 5; i++ { @@ -228,12 +225,9 @@ func TestCutPolicy_HostSlotBusyIsAWaitNotAFailure(t *testing.T) { 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) + now = now.Add(chunkSchedulePoll) if _, ok := pol.dueNR(s, now); !ok { - t.Fatalf("busy retry %d not due after its delay", i) + t.Fatalf("busy retry %d not due at the next poll", i) } } if s.slotWaits != 5 || !s.slotWaitSince.Equal(at(30*time.Second)) { @@ -254,11 +248,10 @@ func TestCutPolicy_HostSlotBusyIsAWaitNotAFailure(t *testing.T) { } // 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) { +// wait; the count is kept, and the next timer cut is due one interval later. +func TestCutPolicy_SuccessDuringSlotWaitEndsTheWait(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) @@ -267,7 +260,7 @@ func TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry(t *testing.T) { 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") + t.Fatal("next timer cut not due one interval after the explicit cut") } } @@ -275,90 +268,96 @@ func TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry(t *testing.T) { // 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)}) + w.record(cutSchedule{seenSeq: 5, slotWaits: 3, slotWaitSince: at(time.Second)}, nil) 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) + w.dropped("storage: chunk capture refused: budget admission: hostlimit: no background slot") + if st := w.status(6); st.TicketDropReason == "" { + t.Fatalf("drop reason not reported: %+v", st) } } // 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 +// cut) and wait in ticket order (earliest due first), every volume due at +// the same instant, and one urgent cut takes the slot mid-round. No volume +// waits longer than (V-1) x (T + poll) plus the urgent work; with V x T <= c +// every volume keeps the interval, and with V x T > c (overload) every +// volume still cuts in every round: none is starved. +func TestCutPolicy_TicketOrderWaitBound(t *testing.T) { + for _, tc := range []struct { + name string + T time.Duration + }{{"V x T <= c", 1400 * time.Millisecond}, {"overload V x T > c", 8 * time.Second}} { + t.Run(tc.name, func(t *testing.T) { + const ( + V = 10 + urgent = 3 * time.Second + runFor = 20 * time.Minute + ) + interval := time.Minute + poll := chunkSchedulePoll + busy := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrNotHead) + pol := cutPolicy{interval: interval, minSpacing: chunkCutMinSpacing, backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax} + ss := make([]cutSchedule, V) + cuts := make([]int, V) + for i := range ss { + ss[i] = cutSchedule{lastSuccess: t0} } - 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)) + dueOf := func(i int) time.Time { return ss[i].lastSuccess.Add(interval) } + holder, start, seq := -1, time.Time{}, uint64(0) + urgentAt, urgentUntil := t0.Add(interval+30*time.Second), time.Time{} + var worst time.Duration + for now := t0; now.Before(t0.Add(runFor)); now = now.Add(poll) { + if holder >= 0 && holder < V && !now.Before(start.Add(tc.T)) { + seq++ + ss[holder] = pol.after(ss[holder], start, start.Add(tc.T), nil, seq) + cuts[holder]++ + holder = -1 + } + if holder < 0 && !urgentAt.IsZero() && !now.Before(urgentAt) { + holder, urgentUntil, urgentAt = V, now.Add(urgent), time.Time{} + } + if holder == V && !now.Before(urgentUntil) { + holder = -1 + } + head := -1 + for i := range ss { + if _, ok := pol.dueNR(ss[i], now); ok && i != holder && (head < 0 || dueOf(i).Before(dueOf(head))) { + head = i + } + } + for i := range ss { + if i == holder { + continue + } + if _, ok := pol.dueNR(ss[i], now); !ok { + continue + } + if i == head && holder < 0 { + if !ss[i].slotWaitSince.IsZero() { + worst = max(worst, now.Sub(ss[i].slotWaitSince)) + } + holder, start = i, now + continue + } + ss[i] = pol.after(ss[i], now, now, busy, seq) } - holder, start = i, now - continue } - ss[i] = pols[i].after(ss[i], now, now, busy, seq) - } + bound := (V-1)*(tc.T+poll) + urgent + poll + if worst > bound { + t.Fatalf("a volume waited %s for the slot; bound %s", worst, bound) + } + round := max(interval, time.Duration(V)*(tc.T+poll)) + for i, n := range cuts { + if n < int(runFor/(round+tc.T))-2 { + t.Fatalf("volume %d cut %d times in %s (round about %s)", i, n, runFor, round) + } + } + t.Logf("worst slot wait %s (bound %s); cuts per volume %v", worst, bound, cuts) + }) } - 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 index db8b14e11d..384db69cdf 100644 --- a/seaweed-block/core/frontend/durable/host_slot_wait_test.go +++ b/seaweed-block/core/frontend/durable/host_slot_wait_test.go @@ -138,8 +138,8 @@ func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { if h := c.head(t); 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) + if cs := chunkStatus(t, p).CutSchedule; cs == nil || cs.HostSlotWaits == 0 || cs.HostSlotWaitSinceNs == 0 || cs.TicketDueHostNs == 0 { + t.Fatalf("waiting for a host slot (with its ticket) is not reported: %+v", cs) } before := len(lim.snapshot()) @@ -172,7 +172,7 @@ func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { } budget = eventBudget(t) for deadline := time.Now().Add(budget); ; time.Sleep(10 * time.Millisecond) { - if cs := chunkStatus(t, p).CutSchedule; cs != nil && cs.HostSlotWaitSinceNs == 0 && cs.HostSlotWaits >= uint64(len(refusals)) { + if cs := chunkStatus(t, p).CutSchedule; cs != nil && cs.HostSlotWaitSinceNs == 0 && cs.TicketDueHostNs == 0 && cs.HostSlotWaits >= uint64(len(refusals)) { break } if time.Now().After(deadline) { diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index d623459fd9..ff4927c411 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -439,6 +439,9 @@ type ChunkStatus struct { 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 + 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 } // 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 a47cf57d84..6bc826195b 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "log" - "math/rand/v2" "strings" "sync" "sync/atomic" @@ -803,7 +802,6 @@ const ( chunkCutMinSpacing = time.Second chunkCutBackoffMin = time.Second chunkCutBackoffMax = 30 * time.Second - chunkSlotDelayMax = 200 * time.Millisecond chunkZeroProgressLimit = 3 // yield an unfinished session to cleaning after this many stalled attempts ) @@ -822,29 +820,11 @@ const ( // no-op cut and an explicit cut included) clears the backoff and // restarts the timer; // - an automatic cut refused because every host slot is held ran -// nothing: it is retried after a random delay 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. +// nothing: it is retried at the next poll, with no backoff and no +// minimum spacing, holding its host ticket so that waiting cuts are +// admitted in due order; 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 @@ -915,11 +895,7 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq u 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) + s.retryAt = end return s } s.lastAuto = start @@ -980,12 +956,32 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer 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 } + // A due cut waits for a host slot in due order: it holds a ticket from + // its first attempt until it is admitted, a cut succeeds, the refusal + // is not a wait, or the loop ends. + taker, _ := p.cfg.ChunkBudget.(interface { + TakeTicket(dueHostNs int64) (*hostlimit.Ticket, error) + }) + var ticket *hostlimit.Ticket + // requeue: an attempt of this turn was admitted on its ticket and then + // failed, so every later ticket of the turn goes to the back of the queue + // (the host's now), never back to the schedule's due time ahead of the + // cuts that waited. Only a success ends the turn; a wait, a refusal or a + // dropped ticket leaves it set. + requeue := false + dropTicket := func(reason string) { + if ticket != nil { + ticket.Close() + ticket = nil + wait.dropped(reason) + } + } + defer dropTicket("") t := time.NewTicker(chunkSchedulePoll) defer t.Stop() for { @@ -999,13 +995,43 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } ls := layer.Stats() start := time.Now() + seen := s.seenSeq s = s.observe(ls.CutSeq, start) - wait.record(s) + if s.seenSeq != seen { + dropTicket("") // a cut succeeded: the wait is over + } + wait.record(s, ticket) reason, ok := pol.due(s, start, ls.Reconciling) if !ok { + // Not attempting (backoff, spacing, reconciling): a ticket held + // now would make other volumes wait for a cut that does not come. + dropTicket("") continue } cutCtx, cancel := p.chunkCutContext(ctx) + if taker != nil && ticket == nil { + dueAt := s.lastSuccess.Add(pol.interval) + if !s.firstDue.IsZero() { + dueAt = s.firstDue + } + due := hostlimit.HostTime(dueAt) + if requeue { + due = hostlimit.HostNow() + } + tk, terr := taker.TakeTicket(due) + if terr != nil { + // No place in the queue: no cut, which would pass every + // earlier ticket; status says why, and the next poll tries + // again. + wait.dropped("no ticket: " + terr.Error()) + cancel() + continue + } + ticket = tk + } + if ticket != nil { + cutCtx = hostlimit.WithTicket(cutCtx, ticket) + } trace := p.testChunkLoopTrace if trace != nil { trace("due", ls.LastCutNs, false) @@ -1024,6 +1050,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer attempted(ls, layer.Stats(), nil) } cancel() + dropTicket("") continue } } else { @@ -1033,12 +1060,30 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } } cancel() + consumed := ticket != nil && ticket.Consumed() + if consumed { + ticket = nil // admitted: the limiter consumed it, whatever the cut did after + } + switch { + case err == nil: + requeue = false + case consumed: + requeue = true + } + switch { + case err == nil: + dropTicket("") // admitted: the limiter consumed it + case errors.Is(err, hostlimit.ErrSlotsHeld): + // a wait: keep the place + default: + dropTicket(err.Error()) + } after := layer.Stats() if attempted != nil { attempted(ls, after, err) } s = pol.afterStaging(s, start, time.Now(), err, after.CutSeq, after.StagedChunks-ls.StagedChunks) - wait.record(s) + wait.record(s, ticket) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && 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) @@ -1953,17 +1998,35 @@ type cutWaitSlot struct { waitSeq uint64 } -func (w *cutWaitSlot) record(s cutSchedule) { +func (w *cutWaitSlot) record(s cutSchedule, ticket *hostlimit.Ticket) { if w == nil { return } - st := CutScheduleStatus{HostSlotWaits: s.slotWaits} + w.mu.Lock() + defer w.mu.Unlock() + st := CutScheduleStatus{HostSlotWaits: s.slotWaits, TicketDropReason: w.st.TicketDropReason} if !s.slotWaitSince.IsZero() { st.HostSlotWaitSinceNs = s.slotWaitSince.UnixNano() } - w.mu.Lock() + if ticket != nil { + st.TicketDueHostNs = ticket.Due() + st.TicketsSkipped = ticket.Skipped() + } w.st, w.waitSeq = st, s.seenSeq - w.mu.Unlock() +} + +// dropped records why the timer's ticket was given up ("" for the normal +// end of a wait: admitted, or a cut succeeded). +func (w *cutWaitSlot) dropped(reason string) { + if w == nil { + return + } + w.mu.Lock() + defer w.mu.Unlock() + w.st.TicketDueHostNs, w.st.TicketsSkipped = 0, 0 + if reason != "" { + w.st.TicketDropReason = reason + } } // status is the recorded state as of the layer's current CutSeq. diff --git a/seaweed-block/core/hostlimit/hostclock_unix.go b/seaweed-block/core/hostlimit/hostclock_unix.go new file mode 100644 index 0000000000..eaa6940056 --- /dev/null +++ b/seaweed-block/core/hostlimit/hostclock_unix.go @@ -0,0 +1,15 @@ +//go:build !windows + +package hostlimit + +import "golang.org/x/sys/unix" + +// hostMonoNs reads the host's monotonic clock, shared by every process on +// the host; it is never compared across hosts or reboots. +func hostMonoNs() int64 { + var ts unix.Timespec + if unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts) != nil { + return 0 + } + return ts.Nano() +} diff --git a/seaweed-block/core/hostlimit/hostclock_windows.go b/seaweed-block/core/hostlimit/hostclock_windows.go new file mode 100644 index 0000000000..97810950d4 --- /dev/null +++ b/seaweed-block/core/hostlimit/hostclock_windows.go @@ -0,0 +1,9 @@ +//go:build windows + +package hostlimit + +import "golang.org/x/sys/windows" + +// hostMonoNs reads the host's monotonic clock (time since boot), shared by +// every process on the host; it is never compared across hosts or reboots. +func hostMonoNs() int64 { return int64(windows.DurationSinceBoot()) } diff --git a/seaweed-block/core/hostlimit/launch.go b/seaweed-block/core/hostlimit/launch.go index 85ecfc07ac..249ec7c532 100644 --- a/seaweed-block/core/hostlimit/launch.go +++ b/seaweed-block/core/hostlimit/launch.go @@ -11,9 +11,10 @@ import ( // CheckLaunch refuses a host-limit configuration whose premises do not // hold, before the process uses it. The directory must exist as a real -// directory, outside temporary directories that cleaners empty, on a local -// file system (kernel file locks are not shared reliably over network -// file systems), and a configuration already published there by other +// directory, outside temporary directories that cleaners empty, not on a +// remote file system (kernel file locks and the host monotonic clock that +// orders tickets belong to one host), and a configuration already published +// there by other // processes must equal this one. The premise that every process on the // host uses the same directory cannot be checked from one process. func CheckLaunch(c Config) error { @@ -39,7 +40,7 @@ func checkLaunch(c Config, tempRoots []string, remote func(string) (string, bool } } if fs, isRemote := remote(dir); isRemote { - return fmt.Errorf("hostlimit: --host-limit-dir %s is on %s, a network file system; slot locks need a local one", dir, fs) + return fmt.Errorf("hostlimit: --host-limit-dir %s is on %s, a remote file system; slot locks and ticket order need a file system local to this host: use a local directory (for example under /run or /var/lib)", dir, fs) } existing, err := os.ReadFile(filepath.Join(dir, "configuration.json")) if errors.Is(err, os.ErrNotExist) { diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index d449a4d1c9..4b60b65831 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -82,7 +82,25 @@ type Stats struct { FallbackActive bool AdmissionNs, MaxHoldNs uint64 SkippedByClass [4]uint64 - LastPoolError string + LastPoolError string // the last pool error; cleared by the next admission through the pool + // UrgentPendingUnheld counts urgent admissions that went on without the + // urgent-pending hold: it stayed held exclusively for 200 ms (a waiter + // stalled in its probe). + UrgentPendingUnheld uint64 + // SlotsHeldSinceNs maps each slot file seen held at the last snapshot to + // the wall time its current holder took it, as that holder recorded in + // the file. A slot held far longer than MaxHold points to a stopped or + // hung holder, which only its supervisor can remove; SlotHolders names it. + SlotsHeldSinceNs map[string]int64 `json:",omitempty"` + // SlotHolders maps each slot file seen held to the process id its holder + // recorded (0 when the record is missing, for example a holder from an + // older build). + SlotHolders map[string]int `json:",omitempty"` + // UrgentPendingHeldSinceNs is the wall time urgent-pending was first seen + // held at consecutive snapshots (0 when free). A stop or other urgent + // work that hangs keeps Normal admissions refused for as long as it + // lives; this shows since when. + UrgentPendingHeldSinceNs int64 `json:",omitempty"` } type lease struct { file *os.File @@ -101,23 +119,41 @@ type Limiter struct { testBeforeConfigWrite func() // test-only crash boundary; immutable before first admission testBeforeConfigLock func(*os.File) // test-only fault boundary; immutable before first admission testExpireRace func() // tests: runs as a hold's expiry decides, under the limiter's lock + testAfterTicketCreate func(string) // test-only: between a ticket's create and its lock + testSkipAfter time.Duration // test-only TicketSkipAfter override cfg Config // base is the limiter's monotonic origin: a hold's progress stamp is // time.Since(base), so the window never reads the wall clock. base time.Time // leases is the live set for Progress, which never takes mu (admission // holds mu across file-system work): id -> *lease, kept with live. - leases sync.Map - mu sync.Mutex - admitWG sync.WaitGroup - next uint64 - live map[uint64]*lease - stats Stats - closed bool - wake chan struct{} - done chan struct{} - nextUpload time.Time - fallback bool + leases sync.Map + mu sync.Mutex + admitWG sync.WaitGroup + next uint64 + live map[uint64]*lease + stats Stats + closed bool + wake chan struct{} + done chan struct{} + nextUpload time.Time + fallback bool + heldSlots int // normal and urgent slots held on the host at the last count + bytesSinceCount int64 // payload bytes paced since that count + heldSince map[string]time.Time + urgentHeldSince time.Time + + // skipMu guards stalled: the earlier tickets this process judged stalled + // by the skip rule. It is never taken with mu held, nor mu under it. + skipMu sync.Mutex + stalled map[string]bool +} + +func (l *Limiter) skipAfter() time.Duration { + if l.testSkipAfter > 0 { + return l.testSkipAfter + } + return TicketSkipAfter } func New(c Config) (*Limiter, error) { @@ -141,7 +177,7 @@ func Phase(volume string, period time.Duration) time.Duration { // pool checks the immutable configuration under a separate OS lock. Slot files // are never unlinked: replacing them could create a second set of live permits. -func (l *Limiter) pool(c Class) (*os.File, error) { +func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) { info, err := os.Lstat(l.cfg.Directory) if err != nil { return nil, err @@ -156,6 +192,14 @@ func (l *Limiter) pool(c Class) (*os.File, error) { } return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) } + // A ticketed Normal admission first checks its place in the queue. The + // ticket files synchronise through their own locks, so this runs outside + // the configuration lock and does not lengthen it. + if c == Normal && t != nil { + if err := t.headCheck(l.normalSlotFree(), l.urgentFree()); err != nil { + return nil, err + } + } guard, err := open("configuration.lock") if err != nil { return nil, err @@ -164,7 +208,7 @@ func (l *Limiter) pool(c Class) (*os.File, error) { if l.testBeforeConfigLock != nil { l.testBeforeConfigLock(guard) } - if err = tryLock(guard); err != nil { + if err = lockGuard(guard); err != nil { return nil, err } expected, _ := json.Marshal(l.cfg) @@ -181,12 +225,14 @@ func (l *Limiter) pool(c Class) (*os.File, error) { return nil, ErrConfig } if c == Normal { + // The probe is held until the slot try-lock below has been made, so + // no Normal admission completes after urgent work became pending. probe, err := open(urgentPendingFile) if err != nil { return nil, err } + defer probe.Close() err = tryLock(probe) - _ = probe.Close() if errors.Is(err, ErrBusy) { return nil, ErrUrgentPending } @@ -219,6 +265,7 @@ func (l *Limiter) pool(c Class) (*os.File, error) { return nil, e } if e = tryLock(f); e == nil { + writeHolder(f) return f, nil } _ = f.Close() @@ -229,6 +276,28 @@ func (l *Limiter) pool(c Class) (*os.File, error) { return nil, ErrSlotsHeld } +// guardWait bounds how long an admission waits for configuration.lock. +// Another admission holds it only while it checks the configuration and +// tries its slots. +const guardWait = 50 * time.Millisecond + +// lockGuard takes configuration.lock, retrying for up to guardWait. Still +// held after that, the answer is ErrSlotsHeld: a wait, like every held slot, +// never a refusal of urgent work. +func lockGuard(f *os.File) error { + deadline := time.Now().Add(guardWait) + for { + err := tryLock(f) + if !errors.Is(err, ErrBusy) { + return err + } + if time.Now().After(deadline) { + return fmt.Errorf("%w: configuration lock held for %s", ErrSlotsHeld, guardWait) + } + time.Sleep(time.Millisecond) + } +} + // publishConfig runs under the configuration OS lock. A killed initializer // leaves an ignored temporary file, never a partially visible configuration. func (l *Limiter) publishConfig(path string, data []byte) error { @@ -284,11 +353,28 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) ( if c > Idle || (c >= BackgroundFill && payload != 0) { return 0, ErrBusy } - f, err := l.pool(c) + var t *Ticket + if c == Normal { + t = ticketFrom(ctx) + } + f, err := l.pool(c, t) + var pending *os.File + if err == nil && c == Urgent { + // Bounded: a waiter stalled in its probe must not block urgent work. + var held bool + if pending, held, _ = holdSharedBounded(filepath.Join(l.cfg.Directory, urgentPendingFile)); !held { + l.mu.Lock() + l.stats.UrgentPendingUnheld++ + l.mu.Unlock() + } + } if errors.Is(err, ErrBusy) { l.mu.Lock() l.stats.Skipped++ l.stats.SkippedByClass[c]++ + // A busy answer is the pool answering: a pool error reported + // earlier is over. + l.stats.LastPoolError = "" l.mu.Unlock() return 0, err } @@ -318,6 +404,10 @@ 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 !fallback { + // The pool answered: a pool error reported earlier is over. + l.stats.LastPoolError = "" + } 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++ @@ -325,6 +415,9 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) ( if f != nil { _ = f.Close() } + if pending != nil { + _ = pending.Close() // an urgent cut refused here holds no Normal admission back + } switch { case closed: return 0, ErrRevoked @@ -335,11 +428,8 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) ( } l.next++ id := l.next - x := &lease{file: f, started: time.Now(), class: c, fallback: fallback, payload: payload, abort: abort} - if c == Urgent && !fallback { - // Best effort: an urgent cut that cannot signal still runs. - x.pending, _ = holdShared(filepath.Join(l.cfg.Directory, urgentPendingFile)) - } + x := &lease{file: f, pending: pending, started: time.Now(), class: c, fallback: fallback, payload: payload, abort: abort} + t.Close() // admitted: the ticket's place is used up l.live[id] = x l.stats.Admitted++ l.stats.PayloadReserved += payload @@ -502,19 +592,180 @@ func (l *Limiter) releaseLoop() { } } } -func (l *Limiter) Snapshot() any { l.mu.Lock(); defer l.mu.Unlock(); return l.stats } +func (l *Limiter) Snapshot() any { + held := l.slotFilesHeld() + urgentHeld := held != nil && !l.urgentFree() + l.mu.Lock() + defer l.mu.Unlock() + st := l.stats + switch { + case !urgentHeld: + l.urgentHeldSince = time.Time{} + case l.urgentHeldSince.IsZero(): + l.urgentHeldSince = time.Now() + } + if !l.urgentHeldSince.IsZero() { + st.UrgentPendingHeldSinceNs = l.urgentHeldSince.UnixNano() + } + if held != nil { + now := time.Now() + if l.heldSince == nil { + l.heldSince = map[string]time.Time{} + } + st.SlotsHeldSinceNs = map[string]int64{} + st.SlotHolders = map[string]int{} + for name := range l.heldSince { + if !held[name] { + delete(l.heldSince, name) + } + } + for name := range held { + pid, since, ok := readHolder(filepath.Join(l.cfg.Directory, name)) + if !ok { + // No record: the time this process first saw it held. + if _, seen := l.heldSince[name]; !seen { + l.heldSince[name] = now + } + since = l.heldSince[name].UnixNano() + } + st.SlotsHeldSinceNs[name] = since + st.SlotHolders[name] = pid + } + } + return st +} + +// writeHolder records in a slot file just locked who holds it and since +// when ("pid= since_ns="). Slot files carry nothing else and +// are never unlinked; a failed write leaves only the status less exact. +func writeHolder(f *os.File) { + rec := fmt.Sprintf("pid=%d since_ns=%d\n", os.Getpid(), time.Now().UnixNano()) + if f.Truncate(0) == nil { + _, _ = f.WriteAt([]byte(rec), 0) + } +} + +// readHolder reads a slot file's holder record. +func readHolder(path string) (pid int, sinceNs int64, ok bool) { + b, err := os.ReadFile(path) + if err != nil { + return 0, 0, false + } + if n, _ := fmt.Sscanf(string(b), "pid=%d since_ns=%d", &pid, &sinceNs); n != 2 || sinceNs <= 0 { + return 0, 0, false + } + return pid, sinceNs, true +} + +// slotNames lists the slot files of the given classes. +func (l *Limiter) slotNames(urgent, normal, others bool) []string { + var names []string + add := func(prefix string, n int) { + for i := 0; i < n; i++ { + names = append(names, fmt.Sprintf("%s-%d", prefix, i)) + } + } + if urgent { + add("urgent", l.cfg.UrgentSlots) + } + if normal { + add("normal", l.cfg.NormalSlots) + } + if others { + add("fill", l.cfg.FillSlots) + add("idle", l.cfg.IdleSlots) + } + return names +} + +// probeHeld reports whether the slot file is held by any process. The probe +// is a shared non-blocking lock, released at once; it can make another +// process's exclusive admission attempt fail once (a wait, by rule). +func (l *Limiter) probeHeld(name string) (held, ok bool) { + path := filepath.Join(l.cfg.Directory, name) + f, err := os.OpenFile(path, os.O_RDWR, 0o600) + if err != nil { + return false, errors.Is(err, os.ErrNotExist) + } + defer f.Close() + err = tryLockShared(f) + if errors.Is(err, ErrBusy) { + return true, true + } + return false, err == nil +} + +// slotFilesHeld maps every held slot file to true (nil if the pool cannot +// be read). +func (l *Limiter) slotFilesHeld() map[string]bool { + if _, err := os.Stat(l.cfg.Directory); err != nil { + return nil + } + held := map[string]bool{} + for _, name := range l.slotNames(true, true, true) { + if h, _ := l.probeHeld(name); h { + held[name] = true + } + } + return held +} + +// normalSlotFree reports whether some normal slot file is free now. +func (l *Limiter) normalSlotFree() bool { + for _, name := range l.slotNames(false, true, false) { + if h, ok := l.probeHeld(name); ok && !h { + return true + } + } + return false +} + +// urgentFree reports whether no urgent work holds urgent-pending now. +func (l *Limiter) urgentFree() bool { + f, err := os.OpenFile(filepath.Join(l.cfg.Directory, urgentPendingFile), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return false + } + defer f.Close() + return tryLock(f) == nil +} + +// heldCodedSlots counts the normal and urgent slots held on the host, the +// classes that pace on the upload budget. +func (l *Limiter) heldCodedSlots() int { + n := 0 + for _, name := range l.slotNames(true, true, false) { + if h, _ := l.probeHeld(name); h { + n++ + } + } + return n +} // WaitUpload paces background payload PUTs, including parallel uploader workers. -// One process spaces reservations by the previous payload/rate. Its first -// payload is immediate; debt survives its leases but resets on a new process. -// For a constant share r and maximum payload B, one process reserves at most -// r*T+B bytes over T. Fresh processes each add a new B; neither process/slot -// churn nor uncoordinated fallback has a fixed host-rate bound. Wire overhead -// is excluded. Local WAL flushing, COW reads and demand hydration bypass it. +// The rate is the budget divided by the normal and urgent slots held on the +// host (counted by probing their files), re-counted once per PayloadBytes of +// this process's uploads: a lone transfer gets the whole budget. After the +// held count changes, each process may pace up to one payload at its old +// rate. One process spaces reservations by the previous payload/rate; its +// first payload is immediate; debt survives its leases but resets on a new +// process. Uncoordinated fallback keeps a per-process divisor and has no +// host-rate bound. Wire overhead is excluded. Local WAL flushing, COW reads +// and demand hydration bypass it. func (l *Limiter) WaitUpload(ctx context.Context, n int) error { if n < 0 { return ErrBusy } + l.mu.Lock() + recount := l.heldSlots == 0 || l.bytesSinceCount >= l.cfg.PayloadBytes + l.bytesSinceCount += int64(n) + l.mu.Unlock() + if recount { + h := l.heldCodedSlots() + l.mu.Lock() + l.heldSlots, l.bytesSinceCount = h, int64(n) + l.mu.Unlock() + } for { if err := ctx.Err(); err != nil { return err @@ -536,7 +787,9 @@ func (l *Limiter) WaitUpload(ctx context.Context, n int) error { l.mu.Unlock() return nil } - div := l.cfg.NormalSlots + l.cfg.UrgentSlots + // The budget is shared by the normal and urgent slots held on the + // host (counted above): a lone transfer gets all of it. + div := max(1, l.heldSlots) rate := l.cfg.BytesPerSecond / int64(div) if rate < 1 { rate = 1 diff --git a/seaweed-block/core/hostlimit/limiter_test.go b/seaweed-block/core/hostlimit/limiter_test.go index cf31575272..b314d479aa 100644 --- a/seaweed-block/core/hostlimit/limiter_test.go +++ b/seaweed-block/core/hostlimit/limiter_test.go @@ -677,7 +677,10 @@ func TestFallbackDoesNotUnpaceAHealthyLease(t *testing.T) { t.Fatalf("healthy normal admission after the pool came back: %v", err) } defer l.Release(normal) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) + // Paced at the budget over the one held coded slot (the fallback lease + // holds none): a second 16 MiB upload waits about a second, which does + // not fit in this deadline; an unpaced one would return at once. + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() if err := l.WaitUpload(ctx, 16<<20); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/hostlimit/lock_unix.go b/seaweed-block/core/hostlimit/lock_unix.go index 09d8670651..ea3d6c09f3 100644 --- a/seaweed-block/core/hostlimit/lock_unix.go +++ b/seaweed-block/core/hostlimit/lock_unix.go @@ -16,8 +16,11 @@ func tryLock(f *os.File) error { return err } -// lockShared waits for a shared lock on f. An exclusive holder keeps it -// only for a non-blocking probe, so the wait is short. -func lockShared(f *os.File) error { - return syscall.Flock(int(f.Fd()), syscall.LOCK_SH) +// tryLockShared takes a shared lock on f without waiting. +func tryLockShared(f *os.File) error { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_SH|syscall.LOCK_NB) + if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) { + return ErrBusy + } + return err } diff --git a/seaweed-block/core/hostlimit/lock_windows.go b/seaweed-block/core/hostlimit/lock_windows.go index bb108914ca..3870ad922c 100644 --- a/seaweed-block/core/hostlimit/lock_windows.go +++ b/seaweed-block/core/hostlimit/lock_windows.go @@ -16,8 +16,11 @@ func tryLock(f *os.File) error { return err } -// lockShared waits for a shared lock on f. An exclusive holder keeps it -// only for a non-blocking probe, so the wait is short. -func lockShared(f *os.File) error { - return windows.LockFileEx(windows.Handle(f.Fd()), 0, 0, 1, 0, &windows.Overlapped{}) +// tryLockShared takes a shared lock on f without waiting. +func tryLockShared(f *os.File) error { + err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{}) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return ErrBusy + } + return err } diff --git a/seaweed-block/core/hostlimit/pending.go b/seaweed-block/core/hostlimit/pending.go index 40643ff396..1e4fd0b986 100644 --- a/seaweed-block/core/hostlimit/pending.go +++ b/seaweed-block/core/hostlimit/pending.go @@ -1,33 +1,61 @@ package hostlimit import ( + "errors" + "log" "os" "path/filepath" + "time" ) +// urgentHoldWait bounds how long urgent work waits for its shared hold on +// urgent-pending. A waiter holds the file exclusively only from its probe +// to its slot try-lock; one that stalled there must not block urgent work. +const urgentHoldWait = 200 * time.Millisecond + // HoldUrgentPending tells every limiter using dir that urgent work is // pending on the host: until release is called, Normal admissions there // are refused with ErrUrgentPending. Callers hold it across a stop or a -// drain, so background cuts do not take slots the stop is waiting for. -func HoldUrgentPending(dir string) (release func(), err error) { - f, err := holdShared(filepath.Join(dir, urgentPendingFile)) +// drain. If the hold cannot be taken within 200 ms (a waiter stalled in its +// probe), held is false and release does nothing: the caller proceeds +// without it, since the slots themselves are the exclusion. +func HoldUrgentPending(dir string) (release func(), held bool, err error) { + f, held, err := holdSharedBounded(filepath.Join(dir, urgentPendingFile)) if err != nil { - return nil, err + return nil, false, err } - return func() { _ = f.Close() }, nil + if !held { + log.Printf("hostlimit: urgent-pending in %s stayed held exclusively for %s; proceeding without the hold", dir, urgentHoldWait) + return func() {}, false, nil + } + return func() { _ = f.Close() }, true, nil } -func holdShared(path string) (*os.File, error) { +// holdSharedBounded opens path and takes a shared lock on it, retrying for +// up to urgentHoldWait. It reports held=false (and no error) when the lock +// stayed taken exclusively for that long. +func holdSharedBounded(path string) (*os.File, bool, error) { if i, err := os.Lstat(path); err == nil && !i.Mode().IsRegular() { - return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrInvalid} + return nil, false, &os.PathError{Op: "open", Path: path, Err: os.ErrInvalid} } f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) if err != nil { - return nil, err + return nil, false, err } - if err = lockShared(f); err != nil { - _ = f.Close() - return nil, err + deadline := time.Now().Add(urgentHoldWait) + for { + err = tryLockShared(f) + if err == nil { + return f, true, nil + } + if !errors.Is(err, ErrBusy) { + _ = f.Close() + return nil, false, err + } + if time.Now().After(deadline) { + _ = f.Close() + return nil, false, nil + } + time.Sleep(5 * time.Millisecond) } - return f, nil } diff --git a/seaweed-block/core/hostlimit/pending_test.go b/seaweed-block/core/hostlimit/pending_test.go index 2e59361431..d8dceb4840 100644 --- a/seaweed-block/core/hostlimit/pending_test.go +++ b/seaweed-block/core/hostlimit/pending_test.go @@ -15,9 +15,9 @@ import ( func TestNormalWaitsWhileUrgentPendingIsHeld(t *testing.T) { c := testConfig(t) l := newTest(t, c) - release, err := HoldUrgentPending(c.Directory) - if err != nil { - t.Fatal(err) + release, held, err := HoldUrgentPending(c.Directory) + if err != nil || !held { + t.Fatalf("hold: held=%t err=%v", held, err) } if id, err := l.Acquire(context.Background(), Normal, nil); id != 0 || !errors.Is(err, ErrUrgentPending) || !errors.Is(err, ErrSlotsHeld) { t.Fatalf("normal admission with an urgent pending: id=%d err=%v", id, err) @@ -75,7 +75,8 @@ func TestCheckLaunch(t *testing.T) { }{ "missing": {DefaultConfig(filepath.Join(c.Directory, "missing")), nil, local, "missing"}, "temp root": {c, []string{filepath.Dir(c.Directory)}, local, "temporary-file cleaners"}, - "remote": {c, nil, func(string) (string, bool) { return "NFS", true }, "network file system"}, + "remote": {c, nil, func(string) (string, bool) { return "NFS", true }, "on NFS, a remote file system"}, + "9p": {c, nil, func(string) (string, bool) { return "9p", true }, "on 9p, a remote file system"}, } file := filepath.Join(t.TempDir(), "f") if err := os.WriteFile(file, nil, 0o600); err != nil { diff --git a/seaweed-block/core/hostlimit/remotefs_linux.go b/seaweed-block/core/hostlimit/remotefs_linux.go index 972d1faee5..67939bf096 100644 --- a/seaweed-block/core/hostlimit/remotefs_linux.go +++ b/seaweed-block/core/hostlimit/remotefs_linux.go @@ -4,7 +4,12 @@ package hostlimit import "syscall" -// remoteFS names the network file system dir is on, if it is on one. +// remoteFS names the remote file system dir is on, if it is on one. The +// host-limit directory needs local flock semantics, which every local file +// system gives (tmpfs and overlay included); a remote one (NFS, CIFS/SMB, +// FUSE such as glusterfs, 9p, CephFS) can share the directory between +// hosts, whose tickets would then compare two monotonic clocks. Unknown +// types are accepted. func remoteFS(dir string) (string, bool) { var st syscall.Statfs_t if syscall.Statfs(dir, &st) != nil { @@ -17,8 +22,14 @@ func remoteFS(dir string) (string, bool) { return "CIFS", true case 0xFE534D42: return "SMB2", true + case 0x517B: + return "SMB", true case 0x65735546: return "FUSE", true + case 0x01021997: + return "9p", true + case 0x00C36400: + return "CephFS", true } return "", false } diff --git a/seaweed-block/core/hostlimit/remotefs_other.go b/seaweed-block/core/hostlimit/remotefs_other.go index c19a5b490a..a33cc84e8f 100644 --- a/seaweed-block/core/hostlimit/remotefs_other.go +++ b/seaweed-block/core/hostlimit/remotefs_other.go @@ -2,5 +2,5 @@ package hostlimit -// remoteFS reports no network file system where it cannot tell. +// remoteFS reports no remote file system where it cannot tell. func remoteFS(string) (string, bool) { return "", false } diff --git a/seaweed-block/core/hostlimit/tickets.go b/seaweed-block/core/hostlimit/tickets.go new file mode 100644 index 0000000000..c8990e4c7a --- /dev/null +++ b/seaweed-block/core/hostlimit/tickets.go @@ -0,0 +1,320 @@ +package hostlimit + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +// ErrNotHead refuses a Normal admission whose ticket is not the earliest +// live, unskipped ticket on the host. It is an ErrSlotsHeld: a wait. +var ErrNotHead = fmt.Errorf("%w: an earlier ticket is waiting", ErrSlotsHeld) + +const ticketsDir = "tickets" + +// TicketSkipAfter is how long a waiter must observe the same earlier ticket +// ahead of it, with a normal slot free and no urgent work pending, before +// it treats that ticket's holder as stalled and passes it. The observation +// can be wrong about a slow holder; ticket order is fairness only, the slot +// lock is the exclusion. +const TicketSkipAfter = 2 * time.Second + +// HostNow is the host's monotonic clock in nanoseconds (shared by every +// process on the host). +func HostNow() int64 { return hostMonoNs() } + +// HostTime converts an in-process time to the host monotonic clock. +func HostTime(t time.Time) int64 { return hostMonoNs() - time.Since(t).Nanoseconds() } + +// A Ticket is a timer cut's place in the host queue: a file in the pool's +// tickets directory, held with an exclusive lock while the cut waits, named +// by its due time on the host monotonic clock. Admission consumes it; Close +// gives it up. The kernel drops the lock of an exiting process, and other +// waiters then remove the file. +type Ticket struct { + l *Limiter + due int64 + name string + path string + + mu sync.Mutex + f *os.File + done bool + observed map[string]*observation // earlier tickets observed for the skip rule + skipped uint64 +} + +type ticketKey struct{} + +// WithTicket carries t to the Normal admission made under ctx. +func WithTicket(ctx context.Context, t *Ticket) context.Context { + return context.WithValue(ctx, ticketKey{}, t) +} + +func ticketFrom(ctx context.Context) *Ticket { + t, _ := ctx.Value(ticketKey{}).(*Ticket) + return t +} + +var ticketSeq struct { + sync.Mutex + n uint64 +} + +// TakeTicket queues a timer cut due at dueHostNs (host monotonic clock). +// The file is created, locked, and kept only if its path still names the +// locked file (a prober may have removed it before the lock); otherwise it +// is created again. +func (l *Limiter) TakeTicket(dueHostNs int64) (*Ticket, error) { + // A ticket needs the host monotonic clock: without it, due 0 would put + // the ticket at the head and the skip rule could never measure. + if hostMonoNs() == 0 { + return nil, errors.New("hostlimit: the host monotonic clock is unreadable; no ticket") + } + // The pool directory is never created here: one that was removed while + // cuts held its slots must not come back as a second lock domain beside + // the old holders. Only its tickets directory is created. + if info, err := os.Lstat(l.cfg.Directory); err != nil { + return nil, err + } else if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return nil, errors.New("hostlimit: pool must be a local directory") + } + dir := filepath.Join(l.cfg.Directory, ticketsDir) + if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return nil, err + } + for attempt := 0; attempt < 8; attempt++ { + ticketSeq.Lock() + ticketSeq.n++ + seq := ticketSeq.n + ticketSeq.Unlock() + name := fmt.Sprintf("%020d-%d-%d", max(dueHostNs, 0), os.Getpid(), seq) + path := filepath.Join(dir, name) + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + if hook := l.testAfterTicketCreate; hook != nil { + hook(path) + } + if err = lockRetry(f); err != nil { + _ = f.Close() + return nil, err + } + if samePath(path, f) { + return &Ticket{l: l, due: dueHostNs, name: name, path: path, f: f, observed: map[string]*observation{}}, nil + } + _ = f.Close() // removed before our lock: take a new one + } + return nil, errors.New("hostlimit: ticket kept disappearing before it was locked") +} + +// lockRetry takes an exclusive lock that a prober may hold for an instant. +func lockRetry(f *os.File) error { + for i := 0; ; i++ { + err := tryLock(f) + if !errors.Is(err, ErrBusy) || i >= 200 { + return err + } + time.Sleep(time.Millisecond) + } +} + +// samePath reports whether path still names the file open as f. +func samePath(path string, f *os.File) bool { + pi, err := os.Stat(path) + if err != nil { + return false + } + fi, err := f.Stat() + return err == nil && os.SameFile(pi, fi) +} + +// Due is the ticket's due time on the host monotonic clock. +func (t *Ticket) Due() int64 { return t.due } + +// Skipped counts the earlier tickets this ticket passed by the skip rule. +func (t *Ticket) Skipped() uint64 { t.mu.Lock(); defer t.mu.Unlock(); return t.skipped } + +// Consumed reports whether the ticket was given up, by an admission or by +// Close. +func (t *Ticket) Consumed() bool { + if t == nil { + return false + } + t.mu.Lock() + defer t.mu.Unlock() + return t.done +} + +// Close gives the place up: the file is removed if its path still names +// it, then unlocked. Close is idempotent. +func (t *Ticket) Close() { + if t == nil { + return + } + t.mu.Lock() + defer t.mu.Unlock() + if t.done { + return + } + t.done = true + if samePath(t.path, t.f) { + _ = os.Remove(t.path) + } + _ = t.f.Close() +} + +// headCheck runs before the configuration lock; ticket files synchronise +// through their own locks. Earlier tickets whose lock can be taken belong to +// exited processes and are removed (lock, re-check the path, unlink, +// unlock). Only the earliest live earlier ticket not yet judged stalled is +// observed: it blocks t until t has seen it stay ahead for TicketSkipAfter +// of time with a normal slot free and no urgent work pending, counted +// across polls (busy periods pause the count, they do not reset it). Then t's limiter judges it stalled and keeps that judgement, for +// this and its later tickets, until the file disappears; the next earlier +// ticket is the one observed. +func (t *Ticket) headCheck(slotFree, urgentFree bool) error { + t.mu.Lock() + defer t.mu.Unlock() + if t.done { + return errors.New("hostlimit: the ticket was closed") + } + dir := filepath.Dir(t.path) + ents, err := os.ReadDir(dir) + if err != nil { + return err + } + type tk struct { + name string + due int64 + } + var earlier []tk + for _, e := range ents { + n := e.Name() + if n == t.name { + continue + } + due, ok := ticketDue(n) + if !ok || due > t.due || (due == t.due && n > t.name) { + continue + } + earlier = append(earlier, tk{n, due}) + } + sort.Slice(earlier, func(i, j int) bool { return earlier[i].due < earlier[j].due }) + now := hostMonoNs() + present := map[string]bool{} + for _, e := range ents { + present[e.Name()] = true + } + stalled := t.l.stalledTickets(present) + seen := map[string]bool{} + blocked := false + passed := 0 + for _, e := range earlier { + path := filepath.Join(dir, e.name) + if reap(path) { + continue + } + seen[e.name] = true + if stalled[e.name] { + passed++ // judged stalled earlier: ignored until its file goes + continue + } + o := t.observed[e.name] + if o == nil { + o = &observation{last: now} + t.observed[e.name] = o + } + free := slotFree && urgentFree + if free && o.lastFree { + o.freeNs += now - o.last + } + o.last, o.lastFree = now, free + if time.Duration(o.freeNs) < t.l.skipAfter() { + blocked = true + break + } + t.l.markStalled(e.name) // observed long enough: the skip rule + delete(t.observed, e.name) + passed++ + } + for n := range t.observed { + if !seen[n] { + delete(t.observed, n) + } + } + if blocked { + return ErrNotHead + } + t.skipped += uint64(passed) + return nil +} + +// observation is how long a waiter has seen an earlier ticket stay ahead +// while it could have run: the free-slot time summed between consecutive +// polls that both saw a normal slot free and no urgent work pending. +type observation struct { + freeNs int64 + last int64 + lastFree bool +} + +// stalledTickets returns the tickets this limiter judged stalled, after +// forgetting those whose file is gone (present: the tickets directory now). +func (l *Limiter) stalledTickets(present map[string]bool) map[string]bool { + l.skipMu.Lock() + defer l.skipMu.Unlock() + out := map[string]bool{} + for n := range l.stalled { + if present[n] { + out[n] = true + } else { + delete(l.stalled, n) + } + } + return out +} + +func (l *Limiter) markStalled(name string) { + l.skipMu.Lock() + defer l.skipMu.Unlock() + if l.stalled == nil { + l.stalled = map[string]bool{} + } + l.stalled[name] = true +} + +// reap removes the ticket at path if its holder has exited: it takes the +// lock, re-checks that the path still names the locked file, unlinks it, +// then unlocks. It reports whether the ticket was dead (or already gone). +func reap(path string) bool { + f, err := os.OpenFile(path, os.O_RDWR, 0o600) + if err != nil { + return errors.Is(err, os.ErrNotExist) + } + defer f.Close() + if tryLock(f) != nil { + return false + } + if samePath(path, f) { + _ = os.Remove(path) + } + return true +} + +func ticketDue(name string) (int64, bool) { + i := strings.IndexByte(name, '-') + if i <= 0 { + return 0, false + } + d, err := strconv.ParseInt(name[:i], 10, 64) + return d, err == nil +} diff --git a/seaweed-block/core/hostlimit/tickets_test.go b/seaweed-block/core/hostlimit/tickets_test.go new file mode 100644 index 0000000000..17dc571926 --- /dev/null +++ b/seaweed-block/core/hostlimit/tickets_test.go @@ -0,0 +1,607 @@ +package hostlimit + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "sync" + "testing" + "time" +) + +// admitWith tries one Normal admission carrying t. +func admitWith(l *Limiter, t *Ticket) (uint64, error) { + return l.Admit(WithTicket(WithClass(context.Background(), Normal), t), 1, nil) +} + +// With one slot, tickets are admitted in due order whatever order their +// holders poll in. +func TestTicketsAdmitInDueOrder(t *testing.T) { + c := testConfig(t) + a, b, d := newTest(t, c), newTest(t, c), newTest(t, c) + holder := newTest(t, c) + hold, err := holder.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + now := HostNow() + t1, _ := a.TakeTicket(now - 3e9) + t2, _ := b.TakeTicket(now - 2e9) + t3, _ := d.TakeTicket(now - 1e9) + defer t1.Close() + defer t2.Close() + defer t3.Close() + holder.Release(hold) + settled(t, holder) + order := []struct { + l *Limiter + t *Ticket + }{{d, t3}, {b, t2}, {a, t1}} + var admitted []*Ticket + for round := 0; round < 3; round++ { + for _, w := range order { + if containsTicket(admitted, w.t) { + continue + } + id, err := admitWith(w.l, w.t) + if err != nil { + if !errors.Is(err, ErrSlotsHeld) { + t.Fatalf("refusal that is not a wait: %v", err) + } + continue + } + admitted = append(admitted, w.t) + w.l.Release(id) + settled(t, w.l) + break + } + } + if len(admitted) != 3 || admitted[0] != t1 || admitted[1] != t2 || admitted[2] != t3 { + t.Fatalf("admission order %v, want t1, t2, t3", dues(admitted)) + } +} + +func containsTicket(ts []*Ticket, t *Ticket) bool { + for _, x := range ts { + if x == t { + return true + } + } + return false +} + +func dues(ts []*Ticket) []int64 { + var d []int64 + for _, x := range ts { + d = append(d, x.Due()) + } + return d +} + +// An earlier ticket whose holder exited (its lock dropped, its file left) +// is removed by the next waiter, which is then admitted. +func TestDeadEarlierTicketIsRemoved(t *testing.T) { + c := testConfig(t) + a, b := newTest(t, c), newTest(t, c) + now := HostNow() + dead, _ := a.TakeTicket(now - 2e9) + late, _ := b.TakeTicket(now - 1e9) + defer late.Close() + _ = dead.f.Close() // the kernel drops an exited process's lock; the file stays + id, err := admitWith(b, late) + if err != nil { + t.Fatalf("waiter behind a dead ticket: %v", err) + } + b.Release(id) + if _, err := os.Stat(dead.path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("dead ticket left in place: %v", err) + } +} + +// A live earlier ticket whose holder never polls (stopped) blocks a later +// waiter only until the later one has seen it ahead, with the slot free and +// no urgent work, for the skip time. +func TestStalledEarlierTicketIsSkipped(t *testing.T) { + c := testConfig(t) + a, b := newTest(t, c), newTest(t, c) + b.testSkipAfter = 300 * time.Millisecond + now := HostNow() + stalled, _ := a.TakeTicket(now - 2e9) + defer stalled.Close() + late, _ := b.TakeTicket(now - 1e9) + defer late.Close() + start := time.Now() + var id uint64 + var err error + for { + if id, err = admitWith(b, late); err == nil { + break + } + if !errors.Is(err, ErrNotHead) { + t.Fatalf("refusal: %v", err) + } + if time.Since(start) > 3*time.Second { + t.Fatal("never passed the stalled ticket") + } + time.Sleep(20 * time.Millisecond) + } + el := time.Since(start) + b.Release(id) + if el < 300*time.Millisecond || el > 700*time.Millisecond { + t.Fatalf("passed the stalled ticket after %s; want the skip time plus a poll", el) + } + if late.Skipped() != 1 { + t.Fatalf("skipped %d tickets", late.Skipped()) + } + if _, err := os.Stat(stalled.path); err != nil { + t.Fatalf("the skipped ticket must keep its file: %v", err) + } +} + +// While the slot is held the skip observation does not run: a stalled head +// keeps its place as long as there is nothing to hand over. +func TestNoSkipWhileTheSlotIsHeld(t *testing.T) { + c := testConfig(t) + a, b, holder := newTest(t, c), newTest(t, c), newTest(t, c) + b.testSkipAfter = 100 * time.Millisecond + hold, err := holder.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + now := HostNow() + head, _ := a.TakeTicket(now - 2e9) + defer head.Close() + late, _ := b.TakeTicket(now - 1e9) + defer late.Close() + for i := 0; i < 15; i++ { + if _, err := admitWith(b, late); !errors.Is(err, ErrSlotsHeld) { + t.Fatalf("poll %d with the slot held: %v", i, err) + } + time.Sleep(20 * time.Millisecond) + } + holder.Release(hold) + settled(t, holder) + if _, err := admitWith(b, late); !errors.Is(err, ErrNotHead) { + t.Fatalf("first poll after the slot freed must still respect the head: %v", err) + } +} + +// A prober that removes a ticket between its create and its lock does not +// lose the creator's place: the creator re-checks the path and creates a +// new ticket. +func TestTicketRemovedBeforeItsLockIsRetaken(t *testing.T) { + c := testConfig(t) + l := newTest(t, c) + raced := false + l.testAfterTicketCreate = func(path string) { + if !raced { + raced = true + if !reap(path) { + t.Error("the unlocked new ticket was not removable") + } + } + } + tk, err := l.TakeTicket(HostNow()) + if err != nil { + t.Fatal(err) + } + defer tk.Close() + if !raced || !samePath(tk.path, tk.f) { + t.Fatalf("raced=%t; the kept ticket must be the one the path names", raced) + } + ents, _ := os.ReadDir(filepath.Join(c.Directory, ticketsDir)) + if len(ents) != 1 { + t.Fatalf("%d ticket files, want 1", len(ents)) + } +} + +// Urgent work waits at most a bounded time for its shared hold: a waiter +// stalled while holding its exclusive probe neither refuses nor blocks it. +func TestUrgentProceedsPastAStalledProbe(t *testing.T) { + c := testConfig(t) + l := newTest(t, c) + probe, err := os.OpenFile(filepath.Join(c.Directory, urgentPendingFile), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + defer probe.Close() + if err := tryLock(probe); err != nil { + t.Fatal(err) + } + start := time.Now() + id, err := l.Acquire(context.Background(), Urgent, nil) + if err != nil { + t.Fatalf("urgent admission behind a stalled probe: %v", err) + } + el := time.Since(start) + l.Release(id) + if el < urgentHoldWait || el > urgentHoldWait+300*time.Millisecond { + t.Fatalf("urgent admission took %s; want about %s", el, urgentHoldWait) + } + if st := l.Snapshot().(Stats); st.UrgentPendingUnheld != 1 { + t.Fatalf("UrgentPendingUnheld = %d", st.UrgentPendingUnheld) + } + release, held, err := HoldUrgentPending(c.Directory) + if err != nil || held { + t.Fatalf("HoldUrgentPending behind a stalled probe: held=%t err=%v", held, err) + } + release() +} + +// Pacing divides the budget by the normal and urgent slots held on the +// host: a lone transfer gets all of it; with a second slot held, half. +func TestPacingUsesTheBudgetOverHeldSlots(t *testing.T) { + c := testConfig(t) + c.BytesPerSecond = 1 << 20 + c.PayloadBytes = 256 << 10 + a, b := newTest(t, c), newTest(t, c) + id, err := a.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer a.Release(id) + ctx := context.Background() + if err := a.WaitUpload(ctx, 256<<10); err != nil { // reserves 0.25 s at the full budget + t.Fatal(err) + } + start := time.Now() + if err := a.WaitUpload(ctx, 256<<10); err != nil { + t.Fatal(err) + } + if el := time.Since(start); el < 200*time.Millisecond || el > 450*time.Millisecond { + t.Fatalf("lone transfer waited %s; want about 0.25 s (the whole budget)", el) + } + other, err := b.Acquire(ctx, Urgent, nil) + if err != nil { + t.Fatal(err) + } + defer b.Release(other) + if err := a.WaitUpload(ctx, 256<<10); err != nil { // re-counts: two held + t.Fatal(err) + } + start = time.Now() + if err := a.WaitUpload(ctx, 256<<10); err != nil { + t.Fatal(err) + } + if el := time.Since(start); el < 400*time.Millisecond || el > 800*time.Millisecond { + t.Fatalf("with two slots held waited %s; want about 0.5 s (half the budget)", el) + } +} + +// Status shows since when each slot file has been seen held, whoever holds +// it, so a stopped holder can be found. +func TestSnapshotShowsSlotsHeldSince(t *testing.T) { + c := testConfig(t) + a, b := newTest(t, c), newTest(t, c) + before := time.Now().UnixNano() + id, err := a.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + st := b.Snapshot().(Stats) + since, ok := st.SlotsHeldSinceNs["normal-0"] + if !ok || since < before { + t.Fatalf("held slots %v; want normal-0 since the admission", st.SlotsHeldSinceNs) + } + time.Sleep(20 * time.Millisecond) + if again := b.Snapshot().(Stats).SlotsHeldSinceNs["normal-0"]; again != since { + t.Fatalf("hold start moved from %d to %d", since, again) + } + a.Release(id) + settled(t, a) + if st := b.Snapshot().(Stats); len(st.SlotsHeldSinceNs) != 0 { + t.Fatalf("released slot still reported: %v", st.SlotsHeldSinceNs) + } +} + +// Status shows since when urgent-pending has been held (a hung stop keeps +// Normal admissions refused while it lives), and clears once it is free. +func TestSnapshotShowsUrgentPendingHeldSince(t *testing.T) { + c := testConfig(t) + l := newTest(t, c) + if st := l.Snapshot().(Stats); st.UrgentPendingHeldSinceNs != 0 { + t.Fatalf("free urgent-pending reported held: %d", st.UrgentPendingHeldSinceNs) + } + before := time.Now().UnixNano() + release, held, err := HoldUrgentPending(c.Directory) + if err != nil || !held { + t.Fatalf("hold: %v %v", held, err) + } + since := l.Snapshot().(Stats).UrgentPendingHeldSinceNs + if since < before { + t.Fatalf("held since %d, want >= %d", since, before) + } + time.Sleep(20 * time.Millisecond) + if again := l.Snapshot().(Stats).UrgentPendingHeldSinceNs; again != since { + t.Fatalf("hold start moved from %d to %d", since, again) + } + release() + if st := l.Snapshot().(Stats); st.UrgentPendingHeldSinceNs != 0 { + t.Fatalf("released urgent-pending still reported: %d", st.UrgentPendingHeldSinceNs) + } +} + +// A pool error is reported until the next admission through the pool, which +// clears it: status then shows no stale error. +func TestPoolErrorClearsOnTheNextGoodAdmission(t *testing.T) { + c := testConfig(t) + missing := c + missing.Directory = filepath.Join(c.Directory, "missing") + l := newTest(t, missing) + if _, err := l.Acquire(context.Background(), Normal, nil); err == nil { + t.Fatal("admission through a missing pool") + } + if st := l.Snapshot().(Stats); st.LastPoolError == "" { + t.Fatal("the pool error is not reported") + } + if err := os.MkdirAll(missing.Directory, 0o700); err != nil { + t.Fatal(err) + } + id, err := l.Acquire(context.Background(), Normal, nil) + if err != nil { + t.Fatalf("admission once the pool exists: %v", err) + } + l.Release(id) + if st := l.Snapshot().(Stats); st.LastPoolError != "" { + t.Fatalf("stale pool error after a good admission: %q", st.LastPoolError) + } +} + +// holdGuard takes configuration.lock from another descriptor, as another +// admission does while it checks the configuration, until release. +func holdGuard(t *testing.T, dir string) (release func()) { + t.Helper() + f, err := os.OpenFile(filepath.Join(dir, "configuration.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + if err := tryLock(f); err != nil { + t.Fatal(err) + } + var once bool + release = func() { + if !once { + once = true + _ = f.Close() + } + } + t.Cleanup(release) + return release +} + +// An urgent admission that meets another admission's configuration lock +// waits for it briefly and is admitted once it is released; it is never +// refused for it. +func TestUrgentWaitsBrieflyForTheConfigurationLock(t *testing.T) { + c := testConfig(t) + l := newTest(t, c) + release := holdGuard(t, c.Directory) + go func() { time.Sleep(20 * time.Millisecond); release() }() + id, err := l.Acquire(context.Background(), Urgent, nil) + if err != nil { + t.Fatalf("urgent admission behind a briefly held configuration lock: %v", err) + } + l.Release(id) + if st := l.Snapshot().(Stats); st.Fallback != 0 || st.LastPoolError != "" { + t.Fatalf("a held configuration lock was taken for a pool fault: %+v", st) + } +} + +// Held past the bound, the configuration lock is a wait (ErrSlotsHeld, the +// typed retryable answer), for urgent work and for a ticketed timer cut, +// which keeps its ticket. +func TestConfigurationLockHeldPastTheBoundIsAWait(t *testing.T) { + c := testConfig(t) + u, n := newTest(t, c), newTest(t, c) + holdGuard(t, c.Directory) + start := time.Now() + if _, err := u.Acquire(context.Background(), Urgent, nil); !errors.Is(err, ErrSlotsHeld) { + t.Fatalf("urgent admission behind a held configuration lock: %v; want ErrSlotsHeld", err) + } + if el := time.Since(start); el > time.Second { + t.Fatalf("the urgent admission waited %s; want about %s", el, guardWait) + } + tk, err := n.TakeTicket(HostNow()) + if err != nil { + t.Fatal(err) + } + defer tk.Close() + if _, err := admitWith(n, tk); !errors.Is(err, ErrSlotsHeld) { + t.Fatalf("ticketed admission behind a held configuration lock: %v; want ErrSlotsHeld", err) + } + if _, err := os.Stat(tk.path); err != nil { + t.Fatalf("the waiting ticket lost its file: %v", err) + } + for _, l := range []*Limiter{u, n} { + if st := l.Snapshot().(Stats); st.Fallback != 0 || st.LastPoolError != "" { + t.Fatalf("a held configuration lock was taken for a pool fault: %+v", st) + } + } +} + +// One stalled ticket costs one skip, not one per hand-off. Three live +// waiters behind it poll concurrently, as volumes on one host do, and keep +// polling while another holds the slot. After the first skip each hand-off +// takes at most a few polls, never another skip time, and the waiters are +// admitted in due order. +func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) { + c := testConfig(t) + stall := newTest(t, c) + now := HostNow() + stalled, err := stall.TakeTicket(now - 10e9) + if err != nil { + t.Fatal(err) + } + defer stalled.Close() + const skip, cut, poll = 500 * time.Millisecond, 50 * time.Millisecond, 20 * time.Millisecond + type admission struct { + due int64 + at, done time.Time + } + var mu sync.Mutex + var log []admission + stop := make(chan struct{}) + var wg sync.WaitGroup + var finishOnce sync.Once + finish := func() { // every path, a failing setup too: stop the workers, then a bounded join + finishOnce.Do(func() { + close(stop) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("the ticket workers did not end within 5 s") + } + }) + } + t.Cleanup(finish) + for i := 0; i < 3; i++ { + l := newTest(t, c) + l.testSkipAfter = skip + tk, err := l.TakeTicket(now - int64(9-i)*1e9) + if err != nil { + t.Fatal(err) + } + wg.Add(1) + go func() { + defer wg.Done() + defer func() { tk.Close() }() + for { + select { + case <-stop: + return + case <-time.After(poll): + } + id, err := admitWith(l, tk) + if err != nil { + if !errors.Is(err, ErrSlotsHeld) { + t.Errorf("refusal that is not a wait: %v", err) + return + } + continue + } + at := time.Now() + time.Sleep(cut) + l.Release(id) + mu.Lock() + log = append(log, admission{tk.Due(), at, time.Now()}) + mu.Unlock() + if tk, err = l.TakeTicket(HostNow()); err != nil { // the next cycle's cut + t.Error(err) + return + } + } + }() + } + deadline := time.Now().Add(10 * time.Second) + for { + mu.Lock() + n := len(log) + mu.Unlock() + if n >= 6 || time.Now().After(deadline) { + break + } + time.Sleep(poll) + } + finish() + if len(log) < 6 { + t.Fatalf("only %d admissions in 10 s", len(log)) + } + for i := 1; i < len(log); i++ { + if log[i].due <= log[i-1].due { + t.Fatalf("admissions out of due order at %d", i) + } + if gap := log[i].at.Sub(log[i-1].done); gap > 200*time.Millisecond { + t.Fatalf("hand-off %d idled %s after the release; one stalled ticket must not cost every hand-off a skip (%s)", i, gap.Round(time.Millisecond), skip) + } + } +} + +// A ticket never recreates a pool directory that was removed: that would +// start a second set of slots beside the holders of the old one. +func TestTakeTicketDoesNotRecreateARemovedPool(t *testing.T) { + c := DefaultConfig(filepath.Join(t.TempDir(), "pool")) + c.NormalSlots, c.UrgentSlots = 1, 1 + if err := os.Mkdir(c.Directory, 0o700); err != nil { + t.Fatal(err) + } + l := newTest(t, c) + tk, err := l.TakeTicket(HostNow()) + if err != nil { + t.Fatal(err) + } + tk.Close() + if err := os.RemoveAll(c.Directory); err != nil { + t.Fatal(err) + } + if _, err := l.TakeTicket(HostNow()); err == nil { + t.Fatal("a ticket was taken in a removed pool directory") + } + if _, err := os.Stat(c.Directory); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the removed pool directory came back: %v", err) + } +} + +// "Held since" is the current holder's own record, not a streak of +// observations: when the slot is handed from one cut to the next between two +// snapshots, the time moves to the new holder's take and names its process. +func TestSnapshotHeldSinceFollowsTheHolderAcrossAHandOff(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows file locks are mandatory: another process cannot read a held slot file") + } + c := testConfig(t) + a, b, observer := newTest(t, c), newTest(t, c), newTest(t, c) + first, err := a.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + st := observer.Snapshot().(Stats) + sinceA := st.SlotsHeldSinceNs["normal-0"] + if sinceA == 0 || st.SlotHolders["normal-0"] != os.Getpid() { + t.Fatalf("first holder not recorded: %+v %+v", st.SlotsHeldSinceNs, st.SlotHolders) + } + time.Sleep(20 * time.Millisecond) + a.Release(first) + settled(t, a) + took := time.Now().UnixNano() + second, err := b.Admit(context.Background(), 1, nil) // the next cut, before any snapshot saw the gap + if err != nil { + t.Fatal(err) + } + defer b.Release(second) + sinceB := observer.Snapshot().(Stats).SlotsHeldSinceNs["normal-0"] + if sinceB < took { + t.Fatalf("held since %d after the hand-off; want the second holder's take (>= %d), not the first's %d", sinceB, took, sinceA) + } +} + +// A busy answer is the pool answering: a pool error reported earlier is +// cleared by it, not only by the next admission. +func TestABusyAnswerClearsAnEarlierPoolError(t *testing.T) { + c := DefaultConfig(filepath.Join(t.TempDir(), "pool")) + c.NormalSlots, c.UrgentSlots = 1, 1 + l, holder := newTest(t, c), newTest(t, c) + if _, err := l.Admit(context.Background(), 1, nil); err == nil { + t.Fatal("admitted through a missing pool directory") + } + if l.Snapshot().(Stats).LastPoolError == "" { + t.Fatal("the missing pool directory was not reported") + } + if err := os.Mkdir(c.Directory, 0o700); err != nil { + t.Fatal(err) + } + id, err := holder.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer holder.Release(id) + if _, err := l.Admit(context.Background(), 1, nil); !errors.Is(err, ErrSlotsHeld) { + t.Fatalf("admission with the slot held: %v; want ErrSlotsHeld", err) + } + if e := l.Snapshot().(Stats).LastPoolError; e != "" { + t.Fatalf("a busy answer left the old pool error %q", e) + } +} diff --git a/seaweed-block/core/hostlimit/urgent_refusal_test.go b/seaweed-block/core/hostlimit/urgent_refusal_test.go new file mode 100644 index 0000000000..73fd89edc5 --- /dev/null +++ b/seaweed-block/core/hostlimit/urgent_refusal_test.go @@ -0,0 +1,53 @@ +package hostlimit + +import ( + "context" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" +) + +// cancelledAfterFirstCheck is a context whose first Err check passes and +// every later one reports cancellation: a cancel that lands between the +// admission's pool step and its final check. +type cancelledAfterFirstCheck struct { + context.Context + checks atomic.Int32 +} + +func (c *cancelledAfterFirstCheck) Err() error { + if c.checks.Add(1) == 1 { + return nil + } + return context.Canceled +} + +// An urgent admission refused after it took its urgent-pending hold (here: a +// cancel at its final check) gives the hold back: no Normal admission stays +// refused for an urgent cut that never ran. +func TestRefusedUrgentAdmissionReleasesItsPendingHold(t *testing.T) { + c := testConfig(t) + l := newTest(t, c) + ctx := &cancelledAfterFirstCheck{Context: WithClass(context.Background(), Urgent)} + if _, err := l.Admit(ctx, 1, nil); err == nil { + t.Fatal("the control needs an urgent admission refused at its final check") + } + probe, err := os.OpenFile(filepath.Join(c.Directory, urgentPendingFile), os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer probe.Close() + deadline := time.Now().Add(time.Second) + for { + err = tryLock(probe) + if err == nil { + return + } + if time.Now().After(deadline) { + t.Fatalf("the urgent-pending file is still held after the refused admission: %v", err) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ebf6f921ad..d1ee250300 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -509,7 +509,15 @@ snapshot lifetime; local persistence does not bypass it. ### M7. Host background-cut admission -`free -> admitted -> draining -> joined -> released`; process death releases its OS slot. 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. 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. 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. + +**Urgent-pending.** Urgent work holds `urgent-pending` shared for its lease, taken with a bounded 200 ms wait and otherwise not taken (counted): the hold only keeps new Normal admissions away. A waiter probes it exclusively from just before its slot try-lock until that try-lock is made. Urgent work is a seal, a detach, a named or scheduled snapshot and a cut with a minimum LSN. An explicit cut without one is Normal: it takes no ticket, is not ordered with timer cuts, and takes no urgent fallback when the pool is unusable. The configuration lock is taken with a bounded wait (50 ms); held longer, the answer is ErrSlotsHeld, a wait. + +**Pacing.** Payload uploads are paced at the budget divided by the normal and urgent slots held on the host, counted by shared non-blocking probes once per PayloadBytes of a process's uploads; after a change of the held count each process may send one payload at its old rate. Fallback leases keep a per-process divisor. + +**Premise.** A live process that holds a lock runs its timers; M7 cannot break a kernel lock held by a live process. A stopped or hung slot holder keeps its slot, and a stalled holder of urgent-pending (a hung stop) keeps Normal admissions refused, until it exits; both are removed by their supervisor. Status reports since when each slot file and urgent-pending have been seen held. ### M8. Attached-volume maintenance @@ -999,10 +1007,16 @@ Notes: | `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 | | `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE | -| `INV-HOST-URGENT-PENDING-001` | While an urgent cut holds its slot, or a caller holds HoldUrgentPending, every Normal admission on the host is refused with ErrUrgentPending (a held-slot wait); urgent admissions still run. | M7 host cut admission (Normal before a slot) | `core/hostlimit/limiter.go` `pool`, `Admit`; `core/hostlimit/pending.go` `HoldUrgentPending` | `TestNormalWaitsWhileUrgentPendingIsHeld`, `TestUrgentLeaseHoldsThePendingSignal` (`core/hostlimit/pending_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | +| `INV-HOST-URGENT-PENDING-001` | While urgent work holds urgent-pending (its slot's lease or HoldUrgentPending), Normal admissions on the host are refused with ErrUrgentPending, a wait. Urgent work waits at most 200 ms for that hold and otherwise proceeds without it; a probe never blocks it. | M7 host cut admission (Normal before a slot) | `core/hostlimit/limiter.go` `pool`, `Admit`; `core/hostlimit/pending.go` `HoldUrgentPending` | `TestNormalWaitsWhileUrgentPendingIsHeld`, `TestUrgentLeaseHoldsThePendingSignal` (`core/hostlimit/pending_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | | `INV-HOST-LAUNCH-CHECK-001` | blockvolume refuses to start with a --host-limit-dir that is missing or not a directory, under a temporary directory, on a network file system, or already in use with different host-limit flags. | M7 host cut admission (process start) | `core/hostlimit/launch.go` `CheckLaunch`; `core/hostlimit/remotefs_linux.go`; `cmd/blockvolume/main.go` | `TestCheckLaunch` (`core/hostlimit/pending_test.go`) | — | ACTIVE | | `INV-LOCAL-HEADROOM-001` | blockvolume refuses to create a volume when the durable root's free space is below the volume size plus its WAL, naming both numbers, before it creates the store, WAL or fresh marker, and warns at start when an existing volume's remaining sparse growth plus the WAL exceed the free space. | M1 open/create (durable provider start) | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `createFresh`, `openExisting` | `TestCreateRefusesWithoutLocalHeadroom`, `TestOpenWarnsWithoutLocalHeadroom` (`core/frontend/durable/headroom_test.go`) | A lab build (tag `swblock_lab_bigvol`, scale rehearsals only) warns instead of refusing (`TestLabBuildCreatesWithoutLocalHeadroom`); CI keeps the tag out of every image and release build (`.github/scripts/lab-tag-check.sh`) | ACTIVE | | `INV-CREATE-MAX-SIZE-001` | blockmaster refuses a new volume above `geometry.MaxNewVolumeBytes` at CreateVolume (InvalidArgument) and at a `--cluster-spec` start, with `ErrVolumeTooLarge` naming the size and the maximum, before any record or store exists. An existing volume keeps opening under `MaxVolumeBytes`. | create admission (CreateVolume, cluster-spec import) | `core/geometry/volume_size.go` `ValidateNewVolumeSize`; `core/lifecycle/store.go` `CreateVolume`; `cmd/blockmaster/cluster_spec.go` `loadClusterSpec`; `core/host/master/services.go` `CreateVolume` (restore geometry) | `TestCreateVolumeRefusesAVolumeAboveTheMaximum` (`core/host/master`), `TestClusterSpecRefusesAVolumeAboveTheMaximum` (`cmd/blockmaster`), `TestValidateNewVolumeSizeAtAndAboveTheMaximum` (`core/geometry`), `TestCreateVolumeRejectsBeyondUint32LBACap` (`core/lifecycle`) | In a lab build (tag `swblock_lab_bigvol`, scale rehearsals only) `MaxNewVolumeBytes` is `MaxVolumeBytes` (`TestLabBuildLiftsTheCreateCap`); a release build keeps 256 GiB (`TestReleaseBuildKeepsTheCreateCap`), and CI keeps the tag out of every image (`.github/scripts/lab-tag-check.sh`, `scripts/refuse-lab-binary.sh`) | ACTIVE | +| `INV-HOST-TICKET-ORDER-001` | A waiting timer cut is admitted only when no earlier ticket on the host is live and not stalled; dead tickets are removed, stalled ones (head free for 2 s) skipped. A volume waits at most (V-1) x T_cut,max plus the window's urgent work plus one poll per hand-off. | M7 waiting → admitted (reason: under random retry, 9 of 20 volumes on one host made zero cuts in 720 s) | `core/hostlimit/tickets.go` `TakeTicket`, `headCheck`, `reap`; `core/hostlimit/limiter.go` `pool`, `Admit`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestTicketsAdmitInDueOrder`, `TestDeadEarlierTicketIsRemoved`, `TestStalledEarlierTicketIsSkipped`, `TestNoSkipWhileTheSlotIsHeld`, `TestTicketRemovedBeforeItsLockIsRetaken`, `TestOneStalledTicketCostsOneSkipNotEveryHandoff`, `TestConfigurationLockHeldPastTheBoundIsAWait`, `TestTakeTicketDoesNotRecreateARemovedPool` (`core/hostlimit/tickets_test.go`); `TestCutPolicy_TicketOrderWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestChunkLoop_TicketKeptForAWaitDroppedOtherwise` (`core/frontend/durable/cut_loop_fence_test.go`) | `HostTickets` OrderedAdmission, BoundedWait, NoLostTicket, SingleHolder | ACTIVE | +| `INV-HOST-TICKET-REENTRY-001` | A timer cut never cuts without a ticket (a failed ticket creation waits for the next poll), and once an attempt of a turn was admitted and failed, every later ticket of that turn is at the back of the queue, never at the schedule's earlier due time. | M7 waiting → admitted | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkLoop_AConsumedAttemptRetriesAtTheBack`, `TestChunkLoop_NoTicketNoCut`, `TestChunkLoop_ARequeuedTurnStaysAtTheBackAcrossAWaitAndADrop` (`core/frontend/durable/cut_loop_ticket_order_test.go`) | SlotShareN (a cut that yields or retries takes a new ticket at the back) | ACTIVE | +| `INV-HOST-CUT-PACING-HOST-001` | Coordinated cut transfers on one host upload at most the budget in total, plus at most H x PayloadBytes once per change of H (H = held normal and urgent slots); a lone transfer may use the whole budget. Fallback leases are excluded. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload`, `heldCodedSlots` | `TestPacingUsesTheBudgetOverHeldSlots` (`core/hostlimit/tickets_test.go`); `TestPacingDebtSurvivesOwnLeaseTurnover` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | +| `INV-HOST-SLOT-HOLD-VISIBLE-001` | M7 cannot break a lock held by a live process: a stalled slot holder keeps its slot, a stalled urgent-pending holder keeps Normal admissions refused. A slot holder records its pid and take time in the slot file, and status reports them, so the supervisor can find and remove it. | M7 admitted | `core/hostlimit/limiter.go` `Snapshot`, `slotFilesHeld`, `writeHolder` | `TestSnapshotShowsSlotsHeldSince`, `TestSnapshotHeldSinceFollowsTheHolderAcrossAHandOff`, `TestSnapshotShowsUrgentPendingHeldSince` (`core/hostlimit/tickets_test.go`) | — | ACTIVE | +| `INV-HOST-URGENT-NOT-BLOCKED-001` | Urgent work (a seal, a detach, a snapshot, a cut with a minimum LSN) is never refused for a waiter: it waits at most 200 ms for its urgent-pending hold and 50 ms for the configuration lock, then proceeds without the hold (counted) or answers ErrSlotsHeld (retryable). | M7 idle → admitted (Urgent) | `core/hostlimit/pending.go` `holdSharedBounded`, `HoldUrgentPending`; `core/hostlimit/limiter.go` `Admit` | `TestUrgentProceedsPastAStalledProbe`, `TestUrgentWaitsBrieflyForTheConfigurationLock`, `TestConfigurationLockHeldPastTheBoundIsAWait` (`core/hostlimit/tickets_test.go`); `TestRefusedUrgentAdmissionReleasesItsPendingHold` (`core/hostlimit/urgent_refusal_test.go`) | `HostTickets` UrgentNotBlocked, UrgentNotRefused | ACTIVE | +| `INV-HOST-POOL-ERROR-CURRENT-001` | A pool error the limiter reports (LastPoolError) is cleared by the next admission through the pool, so status shows a pool error only while it still holds. | M7 free → admitted | `core/hostlimit/limiter.go` `Admit` | `TestPoolErrorClearsOnTheNextGoodAdmission` (`core/hostlimit/tickets_test.go`) | — | ACTIVE | | `INV-HOST-SLOT-BUSY-CODE-001` | The chunk control API refuses a cut, snapshot or detach that host admission refused because every slot is held (or urgent work is pending) with 503 host_slot_busy, retryable; every other capture refusal keeps capture_refused. | M7 free → admitted (refused, wait) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestHostSlotHeldHasItsOwnCode` (`core/host/volume/chunk_host_slot_code_test.go`) | — | ACTIVE | | `INV-CUT-INTENT-FIRST-001` | A cut or staging round begins (or replays) its holder session before any chunk or segment PUT. All upload waves use that session until commit. Payload I/O and pacing hold no adapter lock, so independent uploads and HEAD reads proceed. | M5 Begin → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Begin` | `TestSession_BegunBeforeFirstUploadAndClosedByCommit`, `TestSession_FailedBeginUploadsNothing` (`core/storage/chunk_layer_session_test.go`); `TestCutPayloadSessionBeginsIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`); `TestLayoutRemoteUploadsOverlapWithoutBlockingHead`, `TestLayoutRemoteHeadReadDoesNotWaitForUpload` (`core/frontend/chunkstore/layout_upload_concurrency_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-INTENT-CLOSE-001` | The session lives as long as the staged uploads: it is aborted only when they are dropped (Close, fenced, a HEAD moved past the commit's base, a settled proposal), never while a proposal's commit is unresolved; a refused cut that keeps its uploads keeps its session for the retry. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `discardStaged`, `requeueCut` | `TestChunkCloseAbortsTheOpenSessionUnlessACommitIsUnresolved` (`core/storage/chunk_review271_test.go`); `TestSession_AdmissionRefusedBeforeCommitKeepsReusableUploads` (`core/storage/chunk_layer_session_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsSessionAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE | @@ -1012,7 +1026,7 @@ Notes: | `INV-CHUNK-LOCAL-BEFORE-FETCH-001` | A block that reaches the extent while its chunk is absent is local to the chunk layer before any fetch can install over it: a store opened for chunk use drains nothing to the extent and takes no BASE until its chunk layer attaches. | M4 Holder (lazy restore) | `core/frontend/durable/provider.go` (open and create of `walstore-chunk`, before Recover); `core/storage/walstore.go` `HoldExtentDrainUntilChunkLayer`, `writeExtentUnlocked` (refuses while held, the backstop); `core/storage/flusher.go` `flushOnceInternal` (every drain, the stop's included, checked with the snapshot under `store.mu`); `core/storage/base_install_v3.go` `BeginBaseInstall`; `core/storage/chunk_layer.go` `attachChunkLayerImpl` (releases the hold) | `TestReplayedWriteIsNotDrainedBeforeTheChunkLayerAttaches`, `TestACycleStartedBeforeTheHoldDoesNotDrainTheRecoveredWrite`, `TestAStopBeforeAttachDrainsNothing`, `TestABaseInstallIsRefusedWhileTheDrainIsHeld`, `TestAHeldStoreRefusesAnyExtentWriteUntilAttached`, `TestExtentWritersAreEnumerated` (`core/storage/chunk_replay_before_attach_test.go`); `TestProviderHoldsTheDrainOfAChunkStoreOnCreateAndOpen` (`core/frontend/durable/provider_drain_hold_test.go`) | — | 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 | +| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused for held host slots, pending urgent work or an earlier ticket is a wait, not a failure: no backoff or minimum spacing; it retries at the next poll in ticket order, 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_SuccessDuringSlotWaitEndsTheWait`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestCutPolicy_TicketOrderWaitBound` (`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-CLI-CHUNK-LOOP-001` | Above the per-request bound, sw-block ops chunk snapshot\|cut\|detach repeats the SAME request (same name and request id) only after a retryable or outcome_unknown answer. | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody`, `TestChunkSnapshotLoopReusesTheGeneratedRequestID`, `TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable` (`cmd/sw-block`) | — | ACTIVE | | `INV-CLI-CHUNK-LOOP-002` | Above the per-request bound, sw-block ops chunk snapshot\|cut\|detach stops at the first definite answer (success or non-retryable refusal). | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop` | `TestChunkLoopStopsOnANonRetryableRefusal`, `TestChunkDetachOutcomeUnknownSettles` (`cmd/sw-block`) | — | ACTIVE | | `INV-CLI-CHUNK-LOOP-003` | Above the per-request bound, sw-block ops chunk snapshot\|cut\|detach never starts a request once --timeout has passed and refuses a non-positive --timeout. | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkLoopEndsAtTheTimeout`, `TestChunkLoopHeldProgressReadSendsNoRequestAfterTheTimeout`, `TestChunkLoopSlowAnswersAreBoundedByTheTimeout`, `TestChunkNonPositiveTimeoutIsRefused` (`cmd/sw-block`) | — | ACTIVE | diff --git a/seaweed-block/docs/spec/HostTickets.tla b/seaweed-block/docs/spec/HostTickets.tla new file mode 100644 index 0000000000..8e21c80810 --- /dev/null +++ b/seaweed-block/docs/spec/HostTickets.tla @@ -0,0 +1,172 @@ +---------------------------- MODULE HostTickets ---------------------------- +\* M7 waiting -> admitted: timer cuts wait for the one normal slot in order of +\* their tickets (flock-held files in the pool directory, ordered by due time). +\* +\* - Processes may die at any step (the kernel drops their locks; their files +\* stay) or stall at any step, the probe included (they take no further step +\* and keep their locks). +\* - A ticket is taken by create, lock, then an inode re-check (path still +\* names the locked file). A prober removes a ticket in two steps: it locks a +\* lockable ticket, then unlinks it only if the path still names it, and +\* unlocks. A creator that meets the prober's lock retries the lock. +\* - Skip rule: a waiter may pass any earlier ticket while the slot is free and +\* no urgent hold is seen. This over-approximates "the same ticket stayed +\* ahead for T_skip", false skips of a slow live head included. Ticket order +\* is fairness only; the slot lock is the exclusion. +\* - The waiter's exclusive probe of urgent-pending is held from the probe to +\* the slot try-lock. Urgent work takes urgent-pending shared with a bounded +\* wait and, if the probe is still held, proceeds without the hold. +\* +\* Mutants (constants set TRUE must violate): +\* NoSkip -> BoundedWait (a stalled head blocks every waiter) +\* NoInodeCheck -> NoLostTicket (a creator keeps a lock on an unlinked file) +\* ExclusiveRefuses -> UrgentNotRefused (a probe refuses an urgent admission) +\* UrgentBlocksForever -> UrgentNotBlocked (a stalled prober blocks urgent work for ever) +EXTENDS Integers, FiniteSets, TLC +CONSTANTS N, MaxGen, NoSkip, NoInodeCheck, ExclusiveRefuses, UrgentBlocksForever, Faults + +Procs == 1..N +Due(p) == p \* distinct due times: lower runs first +FileIds == {<> : p \in Procs, g \in 1..MaxGen} +DueOf(f) == Due(f[1]) +None == <<0, 0>> + +VARIABLES + dir, \* ticket files present in the directory + lockOf, \* file -> locking process (0: unlocked) + pc, \* process step + mine, \* the process's current ticket file (or None) + reaping, \* the file a process has locked to remove it (or None) + gen, \* tickets created so far by the process + alive, stalled, + slot, \* holder of the one normal slot (0: free) + probing, \* processes holding the exclusive urgent-pending probe + upc, \* urgent work: idle, trying, held (with urgent-pending), nohold, done + urgentRefused, + outOfOrder, \* history: an admission passed an earlier live ticket + outOfOrderBadly, \* history: ... while the slot was taken or an urgent hold was seen + faults +vars == <> + +Init == /\ dir = {} /\ lockOf = [f \in FileIds |-> 0] + /\ pc = [p \in Procs |-> "idle"] /\ mine = [p \in Procs |-> None] + /\ reaping = [p \in Procs |-> None] /\ gen = [p \in Procs |-> 0] + /\ alive = [p \in Procs |-> TRUE] /\ stalled = [p \in Procs |-> FALSE] + /\ slot = 0 /\ probing = {} /\ upc = "idle" /\ urgentRefused = FALSE + /\ outOfOrder = FALSE /\ outOfOrderBadly = FALSE /\ faults = 0 + +Live(p) == alive[p] /\ ~stalled[p] +UrgentHold == upc = "held" +Rest == <> + +\* ---- taking a ticket: create, lock (retry while a prober holds it), re-check +Create(p) == /\ Live(p) /\ pc[p] = "idle" /\ gen[p] < MaxGen /\ reaping[p] = None + /\ LET f == <> IN + /\ dir' = dir \cup {f} /\ mine' = [mine EXCEPT ![p] = f] + /\ gen' = [gen EXCEPT ![p] = @ + 1] + /\ pc' = [pc EXCEPT ![p] = "created"] + /\ UNCHANGED <> +Lock(p) == /\ Live(p) /\ pc[p] = "created" /\ lockOf[mine[p]] = 0 + /\ lockOf' = [lockOf EXCEPT ![mine[p]] = p] + /\ pc' = [pc EXCEPT ![p] = "locked"] + /\ UNCHANGED <> /\ UNCHANGED Rest +Recheck(p) == /\ Live(p) /\ pc[p] = "locked" + /\ IF mine[p] \in dir \/ NoInodeCheck + THEN /\ pc' = [pc EXCEPT ![p] = "waiting"] + /\ UNCHANGED <> + ELSE /\ lockOf' = [lockOf EXCEPT ![mine[p]] = 0] \* path gone: start over + /\ mine' = [mine EXCEPT ![p] = None] + /\ pc' = [pc EXCEPT ![p] = "idle"] + /\ UNCHANGED <> /\ UNCHANGED Rest + +\* ---- a waiter removes a ticket it can lock, in two steps +ReapLock(q, f) == /\ Live(q) /\ pc[q] = "waiting" /\ reaping[q] = None + /\ f \in dir /\ f # mine[q] /\ lockOf[f] = 0 + /\ lockOf' = [lockOf EXCEPT ![f] = q] /\ reaping' = [reaping EXCEPT ![q] = f] + /\ UNCHANGED <> /\ UNCHANGED Rest +ReapFinish(q) == /\ Live(q) /\ reaping[q] # None + /\ LET f == reaping[q] IN + /\ dir' = IF f \in dir THEN dir \ {f} ELSE dir \* unlink only if the path still names it + /\ lockOf' = [lockOf EXCEPT ![f] = 0] + /\ reaping' = [reaping EXCEPT ![q] = None] + /\ UNCHANGED <> /\ UNCHANGED Rest + +\* ---- admission: head (or skip), probe held until the slot try-lock, slot +Earlier(p) == {f \in dir : DueOf(f) < Due(p)} +LiveEarlier(p) == {f \in Earlier(p) : lockOf[f] # 0 /\ lockOf[f] # p /\ alive[lockOf[f]] /\ reaping[lockOf[f]] # f} +CanSkip == ~NoSkip /\ slot = 0 /\ ~UrgentHold +Head(p) == LiveEarlier(p) = {} \/ CanSkip +BeginProbe(p) == /\ Live(p) /\ pc[p] = "waiting" /\ reaping[p] = None /\ mine[p] \in dir + /\ ~UrgentHold /\ Head(p) /\ slot = 0 + /\ \A f \in Earlier(p) : lockOf[f] # 0 \/ f = mine[p] \* dead (unlocked) tickets are reaped first + /\ probing' = probing \cup {p} /\ pc' = [pc EXCEPT ![p] = "probing"] + \* the order decision is made here; a ticket that appears after it is not passed + /\ outOfOrder' = (outOfOrder \/ LiveEarlier(p) # {}) + /\ outOfOrderBadly' = (outOfOrderBadly \/ (LiveEarlier(p) # {} /\ ~CanSkip)) + /\ UNCHANGED <> + /\ UNCHANGED <> +Admit(p) == /\ Live(p) /\ pc[p] = "probing" + /\ probing' = probing \ {p} + /\ IF slot = 0 /\ ~UrgentHold + THEN /\ slot' = p /\ pc' = [pc EXCEPT ![p] = "admitted"] + /\ dir' = dir \ {mine[p]} + /\ lockOf' = [lockOf EXCEPT ![mine[p]] = 0] + /\ mine' = [mine EXCEPT ![p] = None] + ELSE /\ pc' = [pc EXCEPT ![p] = "waiting"] + /\ UNCHANGED <> + /\ UNCHANGED <> +Release(p) == /\ Live(p) /\ pc[p] = "admitted" /\ slot = p + /\ slot' = 0 /\ pc' = [pc EXCEPT ![p] = "done"] + /\ UNCHANGED <> /\ UNCHANGED Rest + +\* ---- urgent work (one episode): bounded wait for the shared hold, then on without it +UrgentStart == /\ upc = "idle" /\ upc' = "trying" + /\ UNCHANGED <> +UrgentHoldIt == /\ upc = "trying" /\ probing = {} + /\ upc' = "held" + /\ UNCHANGED <> +UrgentBusy == /\ upc = "trying" /\ probing # {} + /\ IF ExclusiveRefuses + THEN /\ urgentRefused' = TRUE /\ upc' = "done" + ELSE /\ ~UrgentBlocksForever \* bounded wait over: proceed without the hold + /\ upc' = "nohold" /\ UNCHANGED urgentRefused + /\ UNCHANGED <> +UrgentEnd == /\ upc \in {"held", "nohold"} /\ upc' = "done" + /\ UNCHANGED <> +UrgentStep == UrgentHoldIt \/ UrgentBusy \/ UrgentEnd + +\* ---- faults: death drops every kernel lock of the process; a stall keeps them. +\* A stalled slot holder is outside M7 (the supervisor's premise). +Die(p) == /\ alive[p] /\ faults < Faults + /\ alive' = [alive EXCEPT ![p] = FALSE] /\ faults' = faults + 1 + /\ lockOf' = [f \in FileIds |-> IF lockOf[f] = p THEN 0 ELSE lockOf[f]] + /\ slot' = IF slot = p THEN 0 ELSE slot + /\ probing' = probing \ {p} + /\ reaping' = [reaping EXCEPT ![p] = None] + /\ UNCHANGED <> +Stall(p) == /\ Live(p) /\ slot # p /\ faults < Faults + /\ stalled' = [stalled EXCEPT ![p] = TRUE] /\ faults' = faults + 1 + /\ UNCHANGED <> + +Step(p) == Create(p) \/ Lock(p) \/ Recheck(p) \/ BeginProbe(p) \/ Admit(p) \/ Release(p) + \/ ReapFinish(p) \/ (\E f \in FileIds : ReapLock(p, f)) +Next == (\E p \in Procs : Step(p) \/ Die(p) \/ Stall(p)) \/ UrgentStart \/ UrgentStep +Spec == Init /\ [][Next]_vars /\ (\A p \in Procs : WF_vars(Step(p))) /\ WF_vars(UrgentStep) + +\* ---- properties +TypeOK == slot \in 0..N /\ probing \subseteq Procs +\* The slot lock is the exclusion: at most one live holder, and it is the slot's owner. +SingleHolder == \A p, q \in Procs : (alive[p] /\ alive[q] /\ pc[p] = "admitted" /\ pc[q] = "admitted") => p = q +\* Ticket order is fairness only: an admission passes an earlier live ticket +\* only through the skip rule (slot free, no urgent hold seen). +OrderedAdmission == ~outOfOrderBadly +\* A creator that passed its re-check is visible to every prober. +NoLostTicket == \A p \in Procs : (alive[p] /\ pc[p] \in {"waiting", "probing"}) => mine[p] \in dir +UrgentNotRefused == ~urgentRefused +\* Urgent work always gets going, whatever the waiters do. +UrgentNotBlocked == (upc = "trying") ~> (upc \in {"held", "nohold", "done"}) +\* Every live waiter is eventually admitted (or stops being live). +BoundedWait == \A p \in Procs : (pc[p] = "waiting" /\ Live(p)) ~> (pc[p] \in {"admitted", "done"} \/ ~Live(p)) +\* Witness (expected violated): a skip past a live earlier ticket is reachable. +NoFalseSkip == ~outOfOrder +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 5324452ef9..b373a136fa 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -135,6 +135,7 @@ configurations and the counterexamples. | `FrozenDetachBudget.tla` | `cfg/FrozenDetachBudget.cfg` | one externally frozen attempt; time in tenths of a second | 439 | physical latency; the external controller's re-freeze limit; fencing and CAS races during the cut | | `GCClockSkew.tla` | `GCClockSkew_safe.cfg` | G=3, S=1, Q=1, Born=10, MaxT=17 | 96 | the root scan, copy settlement and higher-epoch guards; clocks outside the configured skew | | `GCDeleteProgress.tla` | `GCDeleteProgress_safe.cfg` | three ordered candidates, the first DELETE rejected | 4 | root and epoch admission; elapsed coverage; persistence | +| `HostTickets.tla` | `cfg/HostTickets_safe_big_safety.cfg` | N=4 processes, MaxGen=2 tickets each, Faults=2 (deaths or stalls, the probe included), one urgent episode, one normal slot; false skips of a live head are modelled; invariants SingleHolder, OrderedAdmission, NoLostTicket, UrgentNotRefused (the temporal BoundedWait and UrgentNotBlocked are checked complete in `cfg/HostTickets_safe.cfg`, N=3, 1 fault: 178,200 states) | 26,577,796 | a stalled slot holder (the supervisor premise); the time length of T_skip and of the urgent bounded wait; pacing; more than one normal slot | | `HeadReopenBelt.tla` | `cfg/HeadReopenBelt.cfg` | one HEAD, one old server-held CAS, one reopen, one new acknowledged image, one nonempty base | 12 | storage I/O and durability; WAL recovery; an empty root with a delayed first exclusive create | | `PlainDetach.tla` | `cfg/PlainDetach.cfg` | up to two I/O readers, frontend close | 10 | HEAD publication; authority; physical I/O; wall-clock bounds; failure settlement | | `PlainSealReplay.tla` | `cfg/PlainSealReplay.cfg` | one seal request, process memory kept or lost, seven read observations of HEAD | 42 | the controller's pending record and its boot refusal; the hand-over; RPC delivery | diff --git a/seaweed-block/docs/spec/cfg/HostTickets_red_exclusiveProbe.cfg b/seaweed-block/docs/spec/cfg/HostTickets_red_exclusiveProbe.cfg new file mode 100644 index 0000000000..f9a6d9212d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_red_exclusiveProbe.cfg @@ -0,0 +1,10 @@ +CONSTANTS +N=3 +MaxGen=2 +Faults=1 +NoSkip=FALSE +NoInodeCheck=FALSE +ExclusiveRefuses=TRUE +UrgentBlocksForever=FALSE +SPECIFICATION Spec +INVARIANTS TypeOK SingleHolder OrderedAdmission NoLostTicket UrgentNotRefused diff --git a/seaweed-block/docs/spec/cfg/HostTickets_red_noInodeCheck.cfg b/seaweed-block/docs/spec/cfg/HostTickets_red_noInodeCheck.cfg new file mode 100644 index 0000000000..7ccdac3d77 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_red_noInodeCheck.cfg @@ -0,0 +1,10 @@ +CONSTANTS +N=3 +MaxGen=2 +Faults=1 +NoSkip=FALSE +NoInodeCheck=TRUE +ExclusiveRefuses=FALSE +UrgentBlocksForever=FALSE +SPECIFICATION Spec +INVARIANTS TypeOK SingleHolder OrderedAdmission NoLostTicket UrgentNotRefused diff --git a/seaweed-block/docs/spec/cfg/HostTickets_red_noSkip.cfg b/seaweed-block/docs/spec/cfg/HostTickets_red_noSkip.cfg new file mode 100644 index 0000000000..7064d491c4 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_red_noSkip.cfg @@ -0,0 +1,11 @@ +CONSTANTS +N=3 +MaxGen=2 +Faults=1 +NoSkip=TRUE +NoInodeCheck=FALSE +ExclusiveRefuses=FALSE +UrgentBlocksForever=FALSE +SPECIFICATION Spec +INVARIANTS TypeOK SingleHolder OrderedAdmission NoLostTicket UrgentNotRefused +PROPERTIES BoundedWait diff --git a/seaweed-block/docs/spec/cfg/HostTickets_red_urgentBlocksForever.cfg b/seaweed-block/docs/spec/cfg/HostTickets_red_urgentBlocksForever.cfg new file mode 100644 index 0000000000..7097edfad3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_red_urgentBlocksForever.cfg @@ -0,0 +1,11 @@ +CONSTANTS +N=3 +MaxGen=2 +Faults=1 +NoSkip=FALSE +NoInodeCheck=FALSE +ExclusiveRefuses=FALSE +UrgentBlocksForever=TRUE +SPECIFICATION Spec +INVARIANTS TypeOK SingleHolder OrderedAdmission NoLostTicket UrgentNotRefused +PROPERTIES UrgentNotBlocked diff --git a/seaweed-block/docs/spec/cfg/HostTickets_safe.cfg b/seaweed-block/docs/spec/cfg/HostTickets_safe.cfg new file mode 100644 index 0000000000..bc4e28ab68 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_safe.cfg @@ -0,0 +1,11 @@ +CONSTANTS +N=3 +MaxGen=2 +Faults=1 +NoSkip=FALSE +NoInodeCheck=FALSE +ExclusiveRefuses=FALSE +UrgentBlocksForever=FALSE +SPECIFICATION Spec +INVARIANTS TypeOK SingleHolder OrderedAdmission NoLostTicket UrgentNotRefused +PROPERTIES BoundedWait UrgentNotBlocked diff --git a/seaweed-block/docs/spec/cfg/HostTickets_safe_big.cfg b/seaweed-block/docs/spec/cfg/HostTickets_safe_big.cfg new file mode 100644 index 0000000000..f479cf95c4 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_safe_big.cfg @@ -0,0 +1,11 @@ +CONSTANTS +N=4 +MaxGen=2 +Faults=2 +NoSkip=FALSE +NoInodeCheck=FALSE +ExclusiveRefuses=FALSE +UrgentBlocksForever=FALSE +SPECIFICATION Spec +INVARIANTS TypeOK SingleHolder OrderedAdmission NoLostTicket UrgentNotRefused +PROPERTIES BoundedWait UrgentNotBlocked diff --git a/seaweed-block/docs/spec/cfg/HostTickets_safe_big_safety.cfg b/seaweed-block/docs/spec/cfg/HostTickets_safe_big_safety.cfg new file mode 100644 index 0000000000..7479110ae3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_safe_big_safety.cfg @@ -0,0 +1,10 @@ +CONSTANTS +N=4 +MaxGen=2 +Faults=2 +NoSkip=FALSE +NoInodeCheck=FALSE +ExclusiveRefuses=FALSE +UrgentBlocksForever=FALSE +SPECIFICATION Spec +INVARIANTS TypeOK SingleHolder OrderedAdmission NoLostTicket UrgentNotRefused diff --git a/seaweed-block/docs/spec/cfg/HostTickets_wit_falseSkip.cfg b/seaweed-block/docs/spec/cfg/HostTickets_wit_falseSkip.cfg new file mode 100644 index 0000000000..11166ba31c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostTickets_wit_falseSkip.cfg @@ -0,0 +1,10 @@ +CONSTANTS +N=3 +MaxGen=2 +Faults=1 +NoSkip=FALSE +NoInodeCheck=FALSE +ExclusiveRefuses=FALSE +UrgentBlocksForever=FALSE +SPECIFICATION Spec +INVARIANTS NoFalseSkip diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 06c7e844f3..8c5ea8b651 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -30,6 +30,7 @@ case $cfg in R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;; S9_*) spec=RetentionGCTiming ;; + HostTickets_*) spec=HostTickets ;; *) echo "run.sh: no spec for config '$cfg'" >&2; exit 2 ;; esac diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 8d0d4a6f22..c646dd92df 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -336,6 +336,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `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[].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[].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) |