gunnar_ssh/governor.rs
1//! **The two load-shedding gates**: a CoDel delay governor (time) and a memory
2//! reservation ledger (space). Both refuse *at admission*, before a single byte
3//! of the operation's work has been allocated.
4//!
5//! [`Admission`](crate::Admission) is the one door; this module is the pair of
6//! locks on it. An operation is admitted only if **both** pass:
7//!
8//! ```text
9//! admit(class):
10//! if occupied >= governed_limit -> DENY (time: the queue is standing)
11//! if reserved + est(class) > budget -> DENY (space: the budget is spoken for)
12//! occupied += 1; reserved += est(class) // released by Drop, on every path
13//! ```
14//!
15//! # Gate 1 — CoDel, because it is the one that does not oscillate
16//!
17//! ## Sojourn, not queue length
18//!
19//! Queue *length* is not a saturation signal. A hundred-deep queue draining in
20//! a millisecond is a healthy server doing its job; a three-deep queue that has
21//! not moved in a second is a server that has stopped. What separates them is
22//! how long an item **waited**, so that is what is measured: the interval
23//! between admission (enqueue) and the moment the operation's work actually
24//! starts running ([`AdmissionGuard::entered_service`](crate::AdmissionGuard::entered_service)).
25//!
26//! In gunnar that interval is a real queue and not a bookkeeping fiction. Every
27//! transfer is `tokio::spawn`ed and then bridged onto a blocking-pool thread
28//! (`crate::admission` module docs); the gap between "admitted" and "the task is
29//! running" is the runtime's own ready queue plus the blocking-pool handoff.
30//! That is the *invisible* ceiling behind the unbounded listener, measured directly
31//! instead of inferred.
32//!
33//! ## Minimum, not average
34//!
35//! Over each [`INTERVAL`] window the controller keeps the **minimum** sojourn
36//! per class, never the mean. One item that got through quickly is proof the
37//! queue is not standing — it proves a path existed. An average is moved by a
38//! single outlier, so an averaging controller shrinks on noise, then grows back
39//! when the outlier ages out, then shrinks again: the oscillation CoDel exists
40//! to remove.
41//!
42//! ## Per class, and this is the crux
43//!
44//! **One queue. One shared limit. Sojourn measured per class.**
45//!
46//! The trap is head-of-line blocking of the *signal*, not of the queue. Hold
47//! one target for everything and a 25-minute `linux.git` clone — which does not
48//! care about a 150 ms wait and whose client would never notice one — reads as a
49//! catastrophically standing queue against a 5 ms bar, and the controller sheds
50//! load that the box could have served. The clone poisons the delay signal for
51//! the 10 ms `ls-remote` sharing its queue.
52//!
53//! So each class carries its own [`OpClass::target`], and the rule that sets it
54//! is **half the class's measured median service time** — a client may be made
55//! to wait at most long enough to add 50 % to its own latency. Those medians are
56//! measured, not picked round: the reference desktop, 2026-08-13, gunnar in an
57//! 8 GiB / 8-cpu cgroup.
58//!
59//! | class | measured median | target | note |
60//! |---|---:|---:|---|
61//! | ls-remote | 9–12 ms | **5 ms** | the base [`TARGET`] falls out of the measurement |
62//! | fetch | 90 ms | 45 ms | `fetch`/`diverge` |
63//! | push | 340 ms | 170 ms | `push`/`base` |
64//! | clone | 372 ms | 186 ms | `clone`/`large`; xl was 4350 ms |
65//! | gc | **NOT MEASURED** | 186 ms | no bakeoff row; borrows clone's, and says so |
66//!
67//! `ls-remote` is therefore the canary: it trips first, at exactly the 5 ms the
68//! design asked for, and the slower classes trip only when the wait is large
69//! enough to matter *to them*.
70//!
71//! ## The control law
72//!
73//! When a class's window closes, that class's window-minimum decides, and what
74//! it moves is the **one shared limit**:
75//!
76//! * minimum above the class's target for the whole window → the queue is
77//! standing → shrink multiplicatively, `limit -= max(limit/8, 1)`;
78//! * otherwise → grow additively, `limit += 1`.
79//!
80//! Clamped to [`LimitBand`]: **[10, 100]** when no ceiling is configured, and
81//! **[10, ceiling]** when one is — an operator's explicit number is never
82//! lowered to the design's default. The `max(_, 1)` is
83//! not cosmetic: without it a limit below 8 has an integer shrink step of zero
84//! and the controller can never come down again.
85//!
86//! It starts at the top of the band. A load shedder has nothing to shed on an
87//! idle server, and starting at the floor would make a cold server refuse work
88//! it could do for the ~90 intervals (9 s) the additive climb takes.
89//!
90//! # Gate 2 — memory as a RESERVATION you own, not a measurement you take
91//!
92//! [`MemoryLedger`] is a budget and a counter. It does not ask the operating
93//! system anything, and that is the design rather than a limitation of it:
94//!
95//! * a free-memory reading is **stale the instant you take it**; a reservation
96//! you own is exact;
97//! * it denies **before** the allocation, which is the whole principle — asking
98//! "is memory low?" after an operation has built a multi-gigabyte buffer is
99//! asking after the damage;
100//! * it is the fixed-pool shape: admission is "is a slab free?".
101//!
102//! ## Why this gate is not theoretical for gunnar — measured
103//!
104//! From the same bakeoff table, peak anonymous RSS on `vs_forge_clone`, on
105//! identical wire bytes: **gunnar 2314 MB, gitea 122 MB, Forgejo 167 MB**.
106//! Memory is the resource gunnar actually exhausts. The cause is known —
107//! `EmitEntry.stored` in `znippy-plugin-git/src/pack_walk.rs:931` is an owned
108//! `Vec<u8>` per object, so a clone materialises the whole pack in RAM before
109//! writing a byte — and it is being fixed elsewhere. It is not fixed here.
110//!
111//! ## The honest limitation, stated rather than papered over
112//!
113//! **A memory budget is only meaningful when an operation's footprint is bounded
114//! and predictable, and a clone's is neither today.** It is proportional to the
115//! pack, and for `linux.git` that is ~6.4 GB across ~27.6 M allocations. So
116//! [`OpClass::estimated_bytes`] is a per-class **constant**, and for
117//! [`OpClass::Clone`] that constant is a **guess** — the marginal figure from
118//! one corpus, not a bound. Until `stored` becomes an extent into the mapped
119//! archive rather than an owned copy, this gate does not bound clone memory
120//! correctly, and nothing here should be read as claiming it does. What it does
121//! do today is stop *unbounded concurrency* of a heavyweight class, which is a
122//! smaller but real property.
123//!
124//! # OS-less, by law
125//!
126//! No `/proc`, no `sysinfo`, no `getrusage`, no CPU/disk/memory probing. The
127//! only inputs are [`std::time::Instant`] and in-process counters, so this works
128//! on bare metal and in a container with equal honesty. The corollary is stated
129//! plainly on [`DEFAULT_MEMORY_BUDGET_BYTES`]: this code **cannot** know how much
130//! RAM the box has, so the default is a constant an operator on a small machine
131//! must lower.
132//!
133//! No rayon, no thread pool, no allocation on the decision path (the multicore
134//! rule: gatling, never rayon): the
135//! per-class windows are a fixed `[ClassWindow; OpClass::COUNT]` array behind one
136//! mutex touched once per transfer, not once per byte.
137
138use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
139use std::sync::Mutex;
140use std::time::{Duration, Instant};
141
142use crate::command::GitService;
143use gunnar_lfs::Operation;
144
145/// The base sojourn a queue may stand at before it counts as standing: the
146/// target for the *fastest* class, [`OpClass::LsRemote`], whose measured median
147/// service time is 9–12 ms.
148///
149/// Every other class scales off its own measurement; see [`OpClass::target`].
150pub const TARGET: Duration = Duration::from_millis(5);
151
152/// How long a class's minimum sojourn must stay above its target before the
153/// shared limit moves.
154///
155/// One window, one decision. Shorter and the controller reacts to a single slow
156/// scheduling turn; longer and a genuinely standing queue keeps standing while
157/// the controller thinks about it.
158pub const INTERVAL: Duration = Duration::from_millis(100);
159
160/// The floor the governed limit may never go below.
161///
162/// A load shedder that can shed itself to zero is a self-inflicted outage. Ten
163/// concurrent git operations is a server that is still a server.
164pub const MIN_LIMIT: usize = 10;
165
166/// The ceiling the governed limit may never go above **when no budget was
167/// declared**. A declared budget is its own ceiling; see
168/// [`LimitBand::for_budget`].
169pub const MAX_LIMIT: usize = 100;
170
171/// A declared budget's floor is `budget / this`.
172///
173/// Half. The governor may shed a saturated box down to half of what the box was
174/// measured to be able to hold, and no further: the budget's three terms —
175/// cores, descriptors, `MemAvailable` — are hard resources, and a controller
176/// reading a *latency* signal has no evidence about them. Below half, the
177/// honest answer to a client is to serve it.
178pub const BUDGET_FLOOR_DENOMINATOR: usize = 2;
179
180/// The default self-imposed memory budget for admitted operations: 8 GiB.
181///
182/// **This is a number about gunnar, not about the machine.** By the OS-less law
183/// this code cannot read the box's RAM, so it cannot size itself; 8 GiB is the
184/// cgroup the bakeoff measurement above was taken in
185/// (measured 2026-08-13), which makes it the one
186/// figure with evidence behind it rather than a round guess.
187///
188/// An operator on a smaller box **must** lower it, and one on a larger box
189/// should raise it. It covers only the footprints of operations admitted through
190/// this gate: gunnar's resident baseline (~330 MB, the `ls-remote` rows, which
191/// send no pack at all) sits outside the budget and must be left as headroom.
192pub const DEFAULT_MEMORY_BUDGET_BYTES: u64 = 8 * 1024 * 1024 * 1024;
193
194const MIB: u64 = 1024 * 1024;
195
196/// How long an operation may **wait** for a slot before it is refused.
197///
198/// # Why there is a wait at all, when this module argued there must not be
199///
200/// The original text (still above, and still right about *unbounded* queues)
201/// said a git client cannot see a queue, so a fast refusal beats a silent
202/// wait. Two of its four premises did not survive measurement:
203///
204/// * **"Queueing keeps the expensive things alive."** So does refusing. A
205/// refused client does not go away: it reconnects, and a reconnect is a
206/// *whole* SSH handshake — a new TCP connection, a new key exchange, a new
207/// signature verification — where a wait is one parked future. MEASURED on
208/// the rig (2026-08-30): at 64 concurrent clients the refusal arm
209/// spent more CPU per **served** operation than the waiting arm, because
210/// three quarters of the handshakes bought nothing.
211/// * **"A queue makes saturation invisible again."** Only an *unmeasured* one
212/// does. This queue is bounded, counted
213/// ([`crate::AdmissionStats::admitted_after_wait`],
214/// [`crate::AdmissionStats::peak_wait_ms`]) and it is the CoDel controller's
215/// input, so it is strictly more visible than the refusal it replaces.
216///
217/// Two seconds because that is well under what a client pays to retry — git
218/// itself has no backoff, so the retry is the user's or CI's, in whole seconds
219/// — and well under [`crate::SshConfig::exec_grace`] (60 s) and
220/// [`crate::SshConfig::inactivity_timeout`] (600 s), so a waiting session can
221/// never be disconnected by the timeouts that exist to kill idle ones.
222///
223/// `Duration::ZERO` restores the 2026-08-05 behaviour exactly: refuse on the
224/// spot. That is what `--admission-wait-ms 0` is for, and it is the arm the
225/// before/after table was measured against.
226pub const DEFAULT_ADMISSION_WAIT: Duration = Duration::from_secs(2);
227
228/// The share of a transfer's **wire bytes** charged to the memory budget as it
229/// moves ([`crate::AdmissionGuard::reserve_more`]).
230///
231/// A quarter. MEASURED, not guessed: the spool bounds mean the pushed pack
232/// itself is spooled past 64 MiB and read back as a read-only mmap (page cache,
233/// reclaimable, and `MemAvailable` counts it as free), so what a transfer
234/// really holds is the per-object bookkeeping — the walk's entry table
235/// (~56 B/object), the closure check's offset set (~16 B), gunnar-wire's
236/// visited sets (~100 B) — which came to ~2.5 GB against `linux.git`'s 8.58 GiB
237/// pack (the memory limit). 2.5 / 8.58 is 0.29; a quarter
238/// is that, rounded to a shift.
239///
240/// It is a *charge*, not a prediction. Its job is that a transfer which turns
241/// out to be enormous stops **new** admissions long before the box is in
242/// trouble, without a three-object push-create having to pay for the
243/// possibility.
244pub const WIRE_MEMORY_NUMERATOR: u64 = 1;
245/// The denominator of [`WIRE_MEMORY_NUMERATOR`].
246pub const WIRE_MEMORY_DENOMINATOR: u64 = 4;
247
248/// How many bytes must cross the wire between two reservation top-ups.
249///
250/// The ledger is one atomic compare-and-swap, so this is not about the cost of
251/// the call; it is about not turning a per-byte quantity into a per-byte
252/// *decision*. 16 MiB is a quarter of the 64 MiB spool threshold, so a
253/// transfer that is about to spool has already told the ledger about itself
254/// three times.
255pub const WIRE_RESERVE_STEP: u64 = 16 * MIB;
256
257/// The three cost shapes a transfer can have, and the thing a lane floor
258/// protects.
259///
260/// See [`OpClass::lane`] for why the split exists at all, and
261/// [`Governor::lane_ceiling`] for what a floor actually reserves.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
263pub enum Lane {
264 /// A ref advertisement: no pack, milliseconds, 4 MiB.
265 Cheap,
266 /// A pack **out** of the store — clone and fetch. Mostly page cache.
267 Read,
268 /// A pack **in**, and the indexer behind it — push and gc.
269 Write,
270}
271
272impl Lane {
273 /// Every lane, in index order; the per-lane arrays are sized from this.
274 pub const ALL: [Lane; 3] = [Lane::Cheap, Lane::Read, Lane::Write];
275 /// How many lanes there are.
276 pub const COUNT: usize = Lane::ALL.len();
277
278 /// Index into the per-lane arrays.
279 pub const fn index(self) -> usize {
280 match self {
281 Lane::Cheap => 0,
282 Lane::Read => 1,
283 Lane::Write => 2,
284 }
285 }
286
287 /// The name a log or a counter uses.
288 pub const fn name(self) -> &'static str {
289 match self {
290 Lane::Cheap => "cheap",
291 Lane::Read => "read",
292 Lane::Write => "write",
293 }
294 }
295
296 /// The slots of the governed limit this lane is **guaranteed**, as
297 /// `limit * numerator / denominator`, never below [`Lane::floor_min`].
298 ///
299 /// An eighth for `cheap` and a quarter for `read`: a `write` storm can take
300 /// at most five eighths of the box, so an `ls-remote` and a clone always
301 /// have somewhere to land. `write` reserves nothing, because it is the lane
302 /// that would starve the others and it is never the one that is starved —
303 /// whatever the other two are not using is its.
304 pub const fn floor_share(self) -> (usize, usize) {
305 match self {
306 Lane::Cheap => (1, 8),
307 Lane::Read => (1, 4),
308 Lane::Write => (0, 1),
309 }
310 }
311
312 /// The smallest floor a lane keeps however small the limit is.
313 ///
314 /// Two, not one: one slot means a single stuck operation closes the lane,
315 /// and a lane floor exists precisely so that a lane cannot be closed by
316 /// what is happening in another one.
317 pub const fn floor_min(self) -> usize {
318 match self {
319 Lane::Cheap | Lane::Read => 2,
320 Lane::Write => 0,
321 }
322 }
323
324 /// This lane's guaranteed slots under a governed limit of `limit`.
325 pub fn floor(self, limit: usize) -> usize {
326 let (n, d) = self.floor_share();
327 (limit * n / d).max(self.floor_min()).min(limit)
328 }
329}
330
331/// Which kind of user-level git operation is being admitted.
332///
333/// The classes exist for **one** reason: a sojourn measured across a mixed queue
334/// is a number about whichever operation happened to be slowest, so the delay
335/// signal must be split even though the queue is not.
336#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
337pub enum OpClass {
338 /// A ref advertisement and nothing else. The canary: fastest, cheapest, and
339 /// the first to notice a queue that has started to stand.
340 LsRemote,
341 /// An incremental fetch — a negotiated pack over an existing history.
342 Fetch,
343 /// A full clone. The expensive one, in time and (today, badly) in memory.
344 Clone,
345 /// A push, including LFS upload.
346 Push,
347 /// Repository maintenance.
348 Gc,
349}
350
351impl OpClass {
352 /// Every class, in index order. The per-class arrays are sized from this,
353 /// so a new variant that is not added here fails to compile rather than
354 /// silently sharing another class's window.
355 pub const ALL: [OpClass; 5] = [
356 OpClass::LsRemote,
357 OpClass::Fetch,
358 OpClass::Clone,
359 OpClass::Push,
360 OpClass::Gc,
361 ];
362
363 /// How many classes there are; the width of every per-class array here.
364 pub const COUNT: usize = OpClass::ALL.len();
365
366 /// Index into the per-class arrays.
367 pub const fn index(self) -> usize {
368 match self {
369 OpClass::LsRemote => 0,
370 OpClass::Fetch => 1,
371 OpClass::Clone => 2,
372 OpClass::Push => 3,
373 OpClass::Gc => 4,
374 }
375 }
376
377 /// The name a log or a counter uses.
378 pub const fn name(self) -> &'static str {
379 match self {
380 OpClass::LsRemote => "ls-remote",
381 OpClass::Fetch => "fetch",
382 OpClass::Clone => "clone",
383 OpClass::Push => "push",
384 OpClass::Gc => "gc",
385 }
386 }
387
388 /// The sojourn **this class** may stand at before the shared limit shrinks.
389 ///
390 /// Half the class's measured median service time
391 /// (measured on the reference desktop,
392 /// 2026-08-13): a client of
393 /// this class may be made to wait at most long enough to add 50 % to its own
394 /// latency. That rule, not a table of round numbers, is what stops a slow
395 /// class from shrinking the limit on a fast class's behalf — and it lands
396 /// [`OpClass::LsRemote`] exactly on [`TARGET`], because its measured median
397 /// is 10 ms.
398 pub const fn target(self) -> Duration {
399 match self {
400 // measured 9–12 ms → 5 ms, which IS `TARGET`.
401 OpClass::LsRemote => TARGET,
402 // measured 90 ms (`fetch`/`diverge`).
403 OpClass::Fetch => Duration::from_millis(45),
404 // measured 372 ms (`clone`/`large`; `xl` was 4350 ms, so this is the
405 // conservative end of the measured range).
406 OpClass::Clone => Duration::from_millis(186),
407 // measured 340 ms (`push`/`base`).
408 OpClass::Push => Duration::from_millis(170),
409 // NOT MEASURED: the bakeoff run of 2026-08-13 has no `vs_forge_gc`
410 // row, so this borrows clone's rather than inventing a figure. Say
411 // so here rather than let a reader assume it was measured.
412 OpClass::Gc => Duration::from_millis(186),
413 }
414 }
415
416 /// What this class reserves **at admission**, before it knows its size.
417 ///
418 /// # This used to be the whole footprint, and that was the ceiling
419 ///
420 /// Until 2026-08-30 this returned a per-class **constant equal to the whole
421 /// operation's measured peak** — 320 MiB for a push, 2 GiB for a clone —
422 /// and [`MemoryLedger`] refused anything that did not fit in
423 /// [`DEFAULT_MEMORY_BUDGET_BYTES`]. That is an arithmetic ceiling nobody
424 /// chose: 8 GiB / 320 MiB = **25 concurrent pushes on any box**, whatever
425 /// its RAM, and a three-object push-create reserved exactly as much as a
426 /// `linux.git` mirror.
427 ///
428 /// MEASURED on the native desktop rig (gunnar-solo pinned to 4 cpus / 8 GiB,
429 /// 2026-08-30): 500 push-creates at 64 concurrent clients → **118–132 of
430 /// them refused `MemoryBudget`** while the server's RSS never passed
431 /// 1.6 GB of its 8 GiB. The gate was refusing three quarters of the work to
432 /// protect a budget that was 20 % used.
433 ///
434 /// # So the reservation starts small and GROWS with the bytes on the wire
435 ///
436 /// This is the *entry* cost — the session, the state machine, the ref
437 /// advertisement, the first buffers — and it is what admission is decided
438 /// on. Everything proportional to the transfer is added afterwards by
439 /// [`crate::AdmissionGuard::reserve_more`], which the transport calls as
440 /// the pack actually arrives ([`WIRE_MEMORY_NUMERATOR`]). A gate that
441 /// charges a small push for a large one refuses work the box can do; a
442 /// gate that never charges the large one takes the box down. Charging what
443 /// has actually moved is the only rule that is right in both directions.
444 ///
445 /// The numbers below are marginal RSS per concurrent transfer, measured on
446 /// the same rig by walking the concurrency up with the gate wide open
447 /// (`rss-slope.tsv`, a scratch capture outside the repository), rounded up
448 /// to the next power of
449 /// two.
450 pub const fn admission_bytes(self) -> u64 {
451 match self {
452 // No pack at all — the ref advertisement and its framing.
453 OpClass::LsRemote => 4 * MIB,
454 // A negotiation and the first window of a pack.
455 OpClass::Fetch => 16 * MIB,
456 // Same entry cost as a fetch; a clone's real footprint is its pack,
457 // and its pack is charged as it is written.
458 OpClass::Clone => 16 * MIB,
459 // The receive state machine plus the first spool window. MEASURED
460 // 39 MB marginal per concurrent tiny push-create on the rig.
461 OpClass::Push => 32 * MIB,
462 // NOT MEASURED — no bakeoff row, no rig row. Sized at a push's,
463 // and flagged rather than asserted.
464 OpClass::Gc => 32 * MIB,
465 }
466 }
467
468 /// The **lane** this class is metered in.
469 ///
470 /// One queue is still one queue, but a lane may not be starved by another:
471 /// an `ls-remote` that costs 4 MiB and 10 ms must not wait behind an 8 GiB
472 /// mirror push, and on a saturated box it did — every class shared one
473 /// counter against one limit, so a push storm took every slot.
474 ///
475 /// Three lanes, because there are three cost shapes: the ref advertisement
476 /// (no pack), a read (a pack out of the store, mostly page cache), and a
477 /// write (a pack in, plus the indexer behind it).
478 pub const fn lane(self) -> Lane {
479 match self {
480 OpClass::LsRemote => Lane::Cheap,
481 OpClass::Fetch | OpClass::Clone => Lane::Read,
482 OpClass::Push | OpClass::Gc => Lane::Write,
483 }
484 }
485
486 /// The class an SSH `exec` request belongs to.
487 ///
488 /// # What SSH cannot tell you, and it matters
489 ///
490 /// `clone`, `fetch` and `ls-remote` are **the same exec line**:
491 /// `git-upload-pack '<path>'`. Which of the three it turns out to be is
492 /// decided later, by the protocol-v2 command the client sends inside the
493 /// stream (`ls-refs` versus `fetch`), and by whether the client had any
494 /// history to negotiate from. The admission gate runs before any of that,
495 /// by design — the entire value of this gate is refusing before the cost is
496 /// paid.
497 ///
498 /// So over SSH, `git-upload-pack` is classified [`OpClass::Fetch`]: the
499 /// middle of the three, chosen deliberately rather than by accident.
500 /// Classifying it as `Clone` would give every `ls-remote` a 2 GiB
501 /// reservation and a 186 ms delay target; as `LsRemote` it would give every
502 /// clone a 4 MiB reservation and a 5 ms target, which is the poisoned signal
503 /// this module exists to avoid.
504 ///
505 /// Callers that **do** know — the HTTP smart transport, which sees
506 /// `GET /info/refs` separately from `POST /git-upload-pack`, and `gunnar gc`,
507 /// which is not a transport at all — pass the exact class to
508 /// [`Admission::try_admit`](crate::Admission::try_admit) instead of going
509 /// through this function.
510 pub fn for_ssh_service(service: GitService) -> OpClass {
511 match service {
512 GitService::UploadPack => OpClass::Fetch,
513 GitService::ReceivePack => OpClass::Push,
514 GitService::LfsTransfer(Operation::Upload) => OpClass::Push,
515 GitService::LfsTransfer(Operation::Download) => OpClass::Fetch,
516 }
517 }
518}
519
520impl std::fmt::Display for Lane {
521 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
522 f.write_str(self.name())
523 }
524}
525
526impl std::fmt::Display for OpClass {
527 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528 f.write_str(self.name())
529 }
530}
531
532/// The range the governed limit is clamped to.
533///
534/// Spelled as a type rather than two constants because it has to be **narrowed
535/// by an operator's configured ceiling**: a server told `--max-concurrent-transfers 4`
536/// must serve 4, not the design's floor of 10. See [`LimitBand::for_ceiling`].
537#[derive(Debug, Clone, Copy, PartialEq, Eq)]
538pub struct LimitBand {
539 /// The smallest the controller may shrink to.
540 pub min: usize,
541 /// The largest it may grow to, and where it starts.
542 pub max: usize,
543}
544
545impl LimitBand {
546 /// The design's band: **[10, 100]**.
547 pub const DEFAULT: LimitBand = LimitBand {
548 min: MIN_LIMIT,
549 max: MAX_LIMIT,
550 };
551
552 /// The band for a server whose operator pinned a hard ceiling.
553 ///
554 /// The operator's number is the ceiling, and the FLOOR is clamped under it:
555 /// pinning 4 gives `[4, 4]`, a governor that cannot move, which is exactly
556 /// what "I told you 4" should mean. A configured ceiling below
557 /// [`MIN_LIMIT`] must not be silently RAISED — a gate admitting more than
558 /// it was told to is the one failure mode a limit may not have.
559 ///
560 /// **The ceiling is NOT capped at [`MAX_LIMIT`], and that was a bug.** The
561 /// first form did `MAX_LIMIT.min(ceiling)`, so a server configured with the
562 /// shipped default of 256 got a band of `[10, 100]` and quietly served 100.
563 /// Lowering an operator's explicit number is the same defect as raising it,
564 /// in the other direction: both mean the configured value is not the value.
565 /// `MAX_LIMIT` is the design's default for a server that has NOT been told a
566 /// number — it is not an opinion that outranks one that has.
567 pub fn for_ceiling(ceiling: usize) -> LimitBand {
568 LimitBand {
569 min: MIN_LIMIT.min(ceiling),
570 max: ceiling,
571 }
572 }
573
574 /// The band for a server whose ceiling is a **declared, measured budget**
575 /// rather than a round number an operator typed.
576 ///
577 /// # Why the floor moves with the ceiling — MEASURED
578 ///
579 /// [`LimitBand::for_ceiling`] pins the floor at [`MIN_LIMIT`] = 10. With the
580 /// shipped ceiling of 256 that is a band of `[10, 256]`, and the controller
581 /// walks the whole of it: multiplicative decrease is `limit -= limit/8`, so
582 /// 256 → 224 → 196 → … → 24 → 21 → **19** → 17 … On the appliance under a
583 /// 64-client push storm every 100 ms window stands, and the measurement
584 /// took the gate refusing by name at exactly that — `already serving its
585 /// limit of 19`, 268 of 1000 push-creates admitted. **19 was not a constant
586 /// anybody chose; it is a point on a descent.**
587 ///
588 /// The descent does not stop because shedding does not fix what the
589 /// controller is measuring. The sojourn it reads was the gap between
590 /// admission and the spawned task's first line — the tokio ready queue and
591 /// the blocking-pool handoff — and that gap is set by how many clients are
592 /// *connected and doing crypto*, not by how many transfers are admitted. A
593 /// refused client reconnects, so a refusal makes the input worse. A
594 /// controller with no authority over its own input runs to its floor.
595 ///
596 /// Both halves are fixed here. The controller's input is now the
597 /// **admission wait** — the queue this gate actually owns
598 /// ([`DEFAULT_ADMISSION_WAIT`]) — and its floor is a share of the budget
599 /// rather than a constant: below [`BUDGET_FLOOR_DENOMINATOR`]`⁻¹` of a
600 /// number derived from cores, descriptors and `MemAvailable`, the box is
601 /// provably not the bottleneck and refusing costs more than serving.
602 pub fn for_budget(budget: usize) -> LimitBand {
603 LimitBand {
604 min: (budget / BUDGET_FLOOR_DENOMINATOR).clamp(MIN_LIMIT.min(budget), budget),
605 max: budget,
606 }
607 }
608
609 fn clamp(self, limit: usize) -> usize {
610 limit.clamp(self.min, self.max)
611 }
612}
613
614/// One class's sliding window.
615///
616/// `opened` is `None` until the first sample, so construction never reads the
617/// clock and a test can drive the whole controller off `Instant`s of its own.
618#[derive(Debug, Clone, Copy)]
619struct ClassWindow {
620 opened: Option<Instant>,
621 /// The **minimum** sojourn seen since the window opened. Never a sum, never
622 /// a count: an average would let one outlier shrink the limit.
623 min: Option<Duration>,
624}
625
626impl ClassWindow {
627 const EMPTY: ClassWindow = ClassWindow {
628 opened: None,
629 min: None,
630 };
631}
632
633/// The CoDel controller: per-class delay windows, one shared limit.
634#[derive(Debug)]
635pub struct Codel {
636 band: LimitBand,
637 /// The one shared limit. Read on every admission, written once per closed
638 /// window.
639 limit: AtomicUsize,
640 /// Fixed-size and preallocated: no map, no allocation, no growth.
641 windows: Mutex<[ClassWindow; OpClass::COUNT]>,
642 shrinks: AtomicU64,
643 grows: AtomicU64,
644}
645
646impl Codel {
647 /// A controller starting at the top of its band.
648 pub fn new(band: LimitBand) -> Codel {
649 Codel {
650 band,
651 limit: AtomicUsize::new(band.max),
652 windows: Mutex::new([ClassWindow::EMPTY; OpClass::COUNT]),
653 shrinks: AtomicU64::new(0),
654 grows: AtomicU64::new(0),
655 }
656 }
657
658 /// The band this controller is clamped to.
659 pub fn band(&self) -> LimitBand {
660 self.band
661 }
662
663 /// The shared limit right now.
664 pub fn limit(&self) -> usize {
665 self.limit.load(Ordering::Relaxed)
666 }
667
668 /// How many times a standing queue has shrunk the limit.
669 pub fn shrinks(&self) -> u64 {
670 self.shrinks.load(Ordering::Relaxed)
671 }
672
673 /// How many times a draining queue has grown it.
674 pub fn grows(&self) -> u64 {
675 self.grows.load(Ordering::Relaxed)
676 }
677
678 /// Record one item's sojourn, and adjust the shared limit if this closed
679 /// `class`'s window.
680 pub fn record(&self, class: OpClass, sojourn: Duration) {
681 self.record_at(class, sojourn, Instant::now());
682 }
683
684 /// [`Codel::record`] with the clock supplied.
685 ///
686 /// The seam a test drives: `Instant` cannot be constructed, but it can be
687 /// offset, so a test captures one `Instant::now()` and hands this window
688 /// boundaries to the microsecond instead of sleeping for them.
689 pub fn record_at(&self, class: OpClass, sojourn: Duration, now: Instant) {
690 let mut windows = self.windows.lock().unwrap_or_else(|e| e.into_inner());
691 let window = &mut windows[class.index()];
692
693 let opened = *window.opened.get_or_insert(now);
694 window.min = Some(match window.min {
695 Some(previous) => previous.min(sojourn),
696 None => sojourn,
697 });
698
699 if now.saturating_duration_since(opened) < INTERVAL {
700 return;
701 }
702
703 // The window is closed. Its MINIMUM decides, against THIS class's
704 // target — the head-of-line guard, in one line.
705 let standing = window.min.is_some_and(|min| min > class.target());
706 *window = ClassWindow {
707 opened: Some(now),
708 min: None,
709 };
710 drop(windows);
711
712 if standing {
713 self.shrink();
714 } else {
715 self.grow();
716 }
717 }
718
719 /// Multiplicative decrease: `limit -= max(limit/8, 1)`.
720 ///
721 /// The `max(_, 1)` is load-bearing. `limit/8` is integer division, so at a
722 /// limit of 7 the step would be 0 and a standing queue could never bring the
723 /// limit down — the controller would be dead in exactly the state it exists
724 /// for.
725 fn shrink(&self) {
726 let band = self.band;
727 let _ = self
728 .limit
729 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |limit| {
730 Some(band.clamp(limit.saturating_sub((limit / 8).max(1))))
731 });
732 self.shrinks.fetch_add(1, Ordering::Relaxed);
733 }
734
735 /// Additive increase: `limit += 1`.
736 fn grow(&self) {
737 let band = self.band;
738 let _ = self
739 .limit
740 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |limit| {
741 Some(band.clamp(limit.saturating_add(1)))
742 });
743 self.grows.fetch_add(1, Ordering::Relaxed);
744 }
745}
746
747/// Gate 2: a budget and a counter. Never a probe.
748#[derive(Debug)]
749pub struct MemoryLedger {
750 budget: u64,
751 reserved: AtomicU64,
752}
753
754impl MemoryLedger {
755 /// A ledger with `budget` bytes to give out.
756 pub fn new(budget: u64) -> MemoryLedger {
757 MemoryLedger {
758 budget,
759 reserved: AtomicU64::new(0),
760 }
761 }
762
763 /// The budget.
764 pub fn budget(&self) -> u64 {
765 self.budget
766 }
767
768 /// Bytes currently reserved by operations in flight.
769 pub fn reserved(&self) -> u64 {
770 self.reserved.load(Ordering::Relaxed)
771 }
772
773 /// Reserve `bytes`, or refuse.
774 ///
775 /// A compare-and-swap loop rather than "load, check, add": between a load
776 /// and an add, two concurrent admissions both see room and both take it, and
777 /// a budget that can be exceeded by the number of racing threads is not a
778 /// budget. Nothing is allocated here and nothing is allocated by the caller
779 /// before here — the refusal arrives before the cost.
780 pub fn try_reserve(&self, bytes: u64) -> bool {
781 self.reserved
782 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |reserved| {
783 let wanted = reserved.saturating_add(bytes);
784 (wanted <= self.budget).then_some(wanted)
785 })
786 .is_ok()
787 }
788
789 /// Charge `bytes` **whether or not they fit**, and say which it was.
790 ///
791 /// The reserve path for an operation that is already running: see
792 /// [`Growth`] for why this cannot refuse. The counter is allowed to exceed
793 /// the budget, and while it does, [`MemoryLedger::try_reserve`] refuses
794 /// every new admission — which is the whole mechanism by which one enormous
795 /// transfer quiets the box instead of taking it down.
796 pub fn charge(&self, bytes: u64) -> bool {
797 let before = self.reserved.fetch_add(bytes, Ordering::Relaxed);
798 before.saturating_add(bytes) <= self.budget
799 }
800
801 /// Give `bytes` back.
802 ///
803 /// Saturating, because a ledger that can go negative under a double release
804 /// would hand out the whole budget twice.
805 pub fn release(&self, bytes: u64) {
806 let _ = self
807 .reserved
808 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |reserved| {
809 Some(reserved.saturating_sub(bytes))
810 });
811 }
812}
813
814/// Why the governor shed an operation.
815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
816pub enum Shed {
817 /// Gate 1: the governed concurrency limit is full.
818 Concurrency {
819 /// The limit in force at the moment of the refusal — the *governed*
820 /// one, which is not the configured one and moves on its own. Reported
821 /// rather than assumed, or an operator reads a number in a log that
822 /// matches nothing in a config file.
823 limit: usize,
824 /// How many operations were in flight.
825 in_flight: usize,
826 },
827 /// Gate 1b: this operation's **lane** is full, though the server as a
828 /// whole is not. The other lanes' floors are what is holding the slots; see
829 /// [`Lane::floor`].
830 LaneFull {
831 /// The lane that was full.
832 lane: Lane,
833 /// What that lane may hold under the governed limit right now.
834 ceiling: usize,
835 /// The governed server-wide limit.
836 limit: usize,
837 },
838 /// Gate 1c: the claim asked for a slot the caller had told this governor to
839 /// **hold back** ([`Governor::claim_reserving`]), though the server as a
840 /// whole is not full.
841 ///
842 /// Its own variant rather than [`Shed::Concurrency`] with a smaller `limit`
843 /// in it, because reporting a reduced limit as *the* limit is the exact
844 /// failure the unbounded listener is about: an operator would read `limit: 2` out of a log
845 /// on a box configured for 256 and conclude the gate was broken. Both
846 /// numbers travel, and the caller that supplied the reserve is the one that
847 /// gets to name the rule.
848 Reserved {
849 /// Operations in flight when the claim failed.
850 occupied: usize,
851 /// The **governed** server-wide limit — the real one, unreduced.
852 limit: usize,
853 /// How many slots of it the caller asked to be held back from this
854 /// claim.
855 reserve: usize,
856 },
857 /// Gate 2: the memory budget is spoken for.
858 Memory {
859 /// The class whose estimate did not fit.
860 class: OpClass,
861 /// What [`OpClass::estimated_bytes`] asked for.
862 wanted: u64,
863 /// What was already reserved.
864 reserved: u64,
865 /// The budget.
866 budget: u64,
867 },
868}
869
870/// What an admitted operation holds: a concurrency slot and a memory
871/// reservation, plus the instant it was admitted.
872///
873/// Deliberately **not** a `Drop` guard. The one guard is
874/// [`AdmissionGuard`](crate::AdmissionGuard), which owns this; two `Drop`s over
875/// one reservation is how a ledger comes to be released twice.
876#[derive(Debug, Clone, Copy)]
877pub struct Claim {
878 /// The class, needed to release the right reservation and to file the
879 /// sojourn under the right window.
880 pub class: OpClass,
881 /// What was reserved **at admission** ([`OpClass::admission_bytes`]).
882 /// Everything charged afterwards is counted by the guard that owns this
883 /// claim, so the release is `bytes + grown` and cannot drift.
884 pub bytes: u64,
885 /// Enqueue time — when the operation first asked for a slot, before any
886 /// wait. The sojourn is measured from here.
887 pub enqueued: Instant,
888}
889
890/// What a top-up of a claim's reservation did.
891///
892/// It is deliberately not a `Result`: an operation that is already running
893/// cannot be refused, and pretending otherwise would put a failure on a path
894/// with nothing to do about it. What an overdraw does instead is close the door
895/// behind it — `reserved > budget` makes [`MemoryLedger::try_reserve`] refuse
896/// every *new* admission until this transfer finishes, which is the graceful
897/// degradation the budget exists for.
898#[derive(Debug, Clone, Copy, PartialEq, Eq)]
899pub enum Growth {
900 /// The charge fitted inside the budget.
901 Fitted {
902 /// What this transfer now holds.
903 held: u64,
904 },
905 /// The charge did not fit and was taken anyway. New admissions are refused
906 /// until it is given back.
907 Overdrawn {
908 /// What this transfer now holds.
909 held: u64,
910 /// What the whole server now holds.
911 reserved: u64,
912 /// The budget it is over.
913 budget: u64,
914 },
915}
916
917/// Both gates, and the occupancy they meter.
918#[derive(Debug)]
919pub struct Governor {
920 codel: Codel,
921 memory: MemoryLedger,
922 /// Operations in flight. This *is* the queue occupancy — incremented inside
923 /// the same compare-and-swap that checks the limit, so there is no window in
924 /// which two admissions both see room.
925 occupied: AtomicUsize,
926 /// The same count, split by [`Lane`], so a lane floor can be enforced.
927 /// Fixed-size and preallocated: no map, no allocation on the decision path.
928 per_lane: [AtomicUsize; Lane::COUNT],
929 /// How many operations of each lane are **parked** in
930 /// [`crate::Admission::admit_within`] right now.
931 ///
932 /// This is the demand signal, and it is the whole reason lane floors are
933 /// work-conserving rather than a second wall: see
934 /// [`Governor::lane_ceiling`].
935 waiting: [AtomicUsize; Lane::COUNT],
936 shed_concurrency: AtomicU64,
937 shed_lane: AtomicU64,
938 shed_memory: AtomicU64,
939 overdrawn: AtomicU64,
940}
941
942impl Governor {
943 /// A governor over `band` with `budget` bytes of memory to give out.
944 pub fn new(band: LimitBand, budget: u64) -> Governor {
945 Governor {
946 codel: Codel::new(band),
947 memory: MemoryLedger::new(budget),
948 occupied: AtomicUsize::new(0),
949 per_lane: [const { AtomicUsize::new(0) }; Lane::COUNT],
950 waiting: [const { AtomicUsize::new(0) }; Lane::COUNT],
951 shed_concurrency: AtomicU64::new(0),
952 shed_lane: AtomicU64::new(0),
953 shed_memory: AtomicU64::new(0),
954 overdrawn: AtomicU64::new(0),
955 }
956 }
957
958 /// The delay controller.
959 pub fn codel(&self) -> &Codel {
960 &self.codel
961 }
962
963 /// The memory ledger.
964 pub fn memory(&self) -> &MemoryLedger {
965 &self.memory
966 }
967
968 /// The governed limit right now.
969 pub fn limit(&self) -> usize {
970 self.codel.limit()
971 }
972
973 /// Operations in flight right now.
974 pub fn occupied(&self) -> usize {
975 self.occupied.load(Ordering::Relaxed)
976 }
977
978 /// Operations in flight in one lane.
979 pub fn occupied_in(&self, lane: Lane) -> usize {
980 self.per_lane[lane.index()].load(Ordering::Relaxed)
981 }
982
983 /// **How many slots `lane` may hold right now**: the governed limit, less
984 /// the part of every *other* lane's floor that somebody is actually
985 /// **waiting** for.
986 ///
987 /// # A floor that reserves an idle lane's slots is the old bug again
988 ///
989 /// The per-principal cap used to bind unconditionally, and measured on the
990 /// 32-core desktop that meant 32 served and 32 refused against
991 /// **224 idle slots**
992 /// (`crate::admission`). A lane floor that reserved an eighth of the box for
993 /// `ls-remote` whether or not any `ls-remote` existed would be the same
994 /// mistake with a different noun: it would refuse a push the box could
995 /// serve, to keep a slot warm for a request nobody had made.
996 ///
997 /// So the floor is claimed **on demand**, and demand is now observable:
998 /// since 2026-08-30 an operation over the limit *parks*
999 /// ([`crate::Admission::admit_within`]) instead of being refused, so the
1000 /// number of parked operations per lane is a live, exact count of who is
1001 /// asking. A lane with nobody waiting reserves nothing; the instant one
1002 /// `ls-remote` parks, one slot of the cheap floor is held back and the next
1003 /// release goes to it rather than to the push storm that would otherwise
1004 /// take every slot for as long as it lasted.
1005 ///
1006 /// `min(floor, waiting)` is what makes it a floor and not a queue: a lane
1007 /// can never reserve more than [`Lane::floor`] however many of its
1008 /// operations are waiting, so `cheap` cannot starve `write` either.
1009 pub fn lane_ceiling(&self, lane: Lane, limit: usize) -> usize {
1010 let reserved_elsewhere: usize = Lane::ALL
1011 .iter()
1012 .filter(|other| **other != lane)
1013 .map(|other| other.floor(limit).min(self.waiting_in(*other)))
1014 .sum();
1015 limit.saturating_sub(reserved_elsewhere).max(1)
1016 }
1017
1018 /// Operations of `lane` parked waiting for a slot right now.
1019 pub fn waiting_in(&self, lane: Lane) -> usize {
1020 self.waiting[lane.index()].load(Ordering::Relaxed)
1021 }
1022
1023 /// Say that one operation of `lane` has started waiting.
1024 ///
1025 /// Paired with [`Governor::left_wait`] by
1026 /// [`crate::Admission::admit_within`], which is the only caller and which
1027 /// pairs them on every path including cancellation.
1028 pub fn entered_wait(&self, lane: Lane) {
1029 self.waiting[lane.index()].fetch_add(1, Ordering::Relaxed);
1030 }
1031
1032 /// Say that one operation of `lane` has stopped waiting.
1033 pub fn left_wait(&self, lane: Lane) {
1034 let _ = self.waiting[lane.index()].fetch_update(
1035 Ordering::Relaxed,
1036 Ordering::Relaxed,
1037 |waiting| Some(waiting.saturating_sub(1)),
1038 );
1039 }
1040
1041 /// Refusals by gate: (concurrency, lane, memory).
1042 pub fn shed_counts(&self) -> (u64, u64, u64) {
1043 (
1044 self.shed_concurrency.load(Ordering::Relaxed),
1045 self.shed_lane.load(Ordering::Relaxed),
1046 self.shed_memory.load(Ordering::Relaxed),
1047 )
1048 }
1049
1050 /// How many transfers have charged the ledger past its budget while
1051 /// running ([`Growth::Overdrawn`]).
1052 pub fn overdrawn(&self) -> u64 {
1053 self.overdrawn.load(Ordering::Relaxed)
1054 }
1055
1056 /// **The admission decision.** Time first, then the lane, then space, then
1057 /// take all three.
1058 ///
1059 /// Nothing is allocated on any refusal path, and nothing the operation
1060 /// needs is allocated on the success path either: a [`Claim`] is three
1061 /// `Copy` words. That is the point of the gate — the refusal has to arrive
1062 /// before the cost, or it is only a slower way of paying it.
1063 pub fn try_claim(&self, class: OpClass) -> Result<Claim, Shed> {
1064 self.claim(class, 0, true)
1065 }
1066
1067 /// [`Governor::try_claim`] or [`Governor::attempt`], chosen by the caller.
1068 pub fn claim_for(&self, class: OpClass, count: bool) -> Result<Claim, Shed> {
1069 self.claim(class, 0, count)
1070 }
1071
1072 /// [`Governor::claim_for`] against a limit `reserve` slots **lower** than
1073 /// the governed one, so that this claim can never take one of the last
1074 /// `reserve` slots.
1075 ///
1076 /// # Why the reserve is enforced here and not by the caller
1077 ///
1078 /// A caller can read [`Governor::occupied`], compare it to a threshold and
1079 /// only then ask for a claim — and that is a race, for exactly the reason
1080 /// written over the compare-and-swap below: `N` racing admissions all read
1081 /// the same occupancy and all decide they fit. Measured, on a four-slot gate
1082 /// with two hundred anonymous readers: strangers holding *transient* claims
1083 /// while they made that decision filled the server-wide gate, and a keyed
1084 /// caller arriving into that window was refused by gate 1 with
1085 /// `AtCapacity` — the reserve that existed to protect it having never been
1086 /// consulted. A limit that is checked outside the atomic that enforces it is
1087 /// not a limit.
1088 ///
1089 /// So the reserve rides in the same `fetch_update`. `N` racing strangers can
1090 /// then no more collectively exceed `limit - reserve` than they can exceed
1091 /// `limit`, and a refused one never holds a slot at all — which matters
1092 /// twice, because the refusal path of a flood is the path an attacker is
1093 /// trying to make expensive.
1094 ///
1095 /// # Why this moves no shed counter
1096 ///
1097 /// The three [`Governor::shed_counts`] counters count *this* governor's own
1098 /// gates — the limit it controls, the lane floors it computes, the ledger it
1099 /// keeps. The reserve is none of those: it is a number the caller handed in,
1100 /// for a policy the caller owns, and the caller counts it
1101 /// (`AdmissionStats::refused_keyed_reserve`). Counting it here as a
1102 /// concurrency shed would tell an operator the CoDel limit was full when it
1103 /// was nowhere near, and counting it here under a fourth name would give the
1104 /// same event two owners.
1105 pub fn claim_reserving(
1106 &self,
1107 class: OpClass,
1108 reserve: usize,
1109 count: bool,
1110 ) -> Result<Claim, Shed> {
1111 self.claim(class, reserve, count)
1112 }
1113
1114 /// [`Governor::try_claim`] without moving the shed counters.
1115 ///
1116 /// The retry inside [`crate::Admission::admit_within`] asks this door many
1117 /// times for **one** operation. Counting every ask would make
1118 /// `shed_concurrency` a count of *polls* rather than of refusals — the
1119 /// counter would read 21 where one client was refused once, which is worse
1120 /// than no counter. So the wait loop attempts without counting and counts
1121 /// once, at the end, when the refusal is final.
1122 pub fn attempt(&self, class: OpClass) -> Result<Claim, Shed> {
1123 self.claim(class, 0, false)
1124 }
1125
1126 fn claim(&self, class: OpClass, reserve: usize, count: bool) -> Result<Claim, Shed> {
1127 let limit = self.codel.limit();
1128 // What THIS claim may take. `reserve` is 0 for every ordinary caller,
1129 // in which case the two are the same number and nothing below changes.
1130 // See [`Governor::claim_reserving`] for why the reserve is applied here
1131 // rather than checked by the caller beforehand.
1132 let available = limit.saturating_sub(reserve);
1133 // Check and take in ONE compare-and-swap. "Load, compare, then add"
1134 // lets N racing admissions all read `occupied == limit - 1`.
1135 let taken = self
1136 .occupied
1137 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |occupied| {
1138 (occupied < available).then_some(occupied + 1)
1139 });
1140 if let Err(occupied) = taken {
1141 if reserve > 0 {
1142 // The caller's rule refused this, not the governor's, so the
1143 // governor's counters do not move and the governor's variant is
1144 // not used — even when the box happens to ALSO be full. Reported
1145 // this way round on purpose: a caller that supplied a reserve
1146 // has a policy reason for it, and a refusal that flipped between
1147 // two reasons depending on how full the box happened to be would
1148 // be unreadable in a log and, in `Admission`'s case, would decide
1149 // whether the caller gets parked.
1150 return Err(Shed::Reserved {
1151 occupied,
1152 limit,
1153 reserve,
1154 });
1155 }
1156 if count {
1157 self.shed_concurrency.fetch_add(1, Ordering::Relaxed);
1158 }
1159 return Err(Shed::Concurrency {
1160 limit,
1161 in_flight: occupied,
1162 });
1163 }
1164
1165 // The lane, second: the server-wide limit is the resource that actually
1166 // runs out, and a lane floor is only interesting once it does.
1167 let lane = class.lane();
1168 let ceiling = self.lane_ceiling(lane, limit);
1169 let lane_taken = self.per_lane[lane.index()].fetch_update(
1170 Ordering::Relaxed,
1171 Ordering::Relaxed,
1172 |held| (held < ceiling).then_some(held + 1),
1173 );
1174 if lane_taken.is_err() {
1175 self.occupied.fetch_sub(1, Ordering::Relaxed);
1176 if count {
1177 self.shed_lane.fetch_add(1, Ordering::Relaxed);
1178 }
1179 return Err(Shed::LaneFull {
1180 lane,
1181 ceiling,
1182 limit,
1183 });
1184 }
1185
1186 let bytes = class.admission_bytes();
1187 if !self.memory.try_reserve(bytes) {
1188 // Hand the concurrency slot AND the lane slot straight back: a slot
1189 // leaked on the memory path is a server that refuses everything an
1190 // hour after start-up.
1191 self.per_lane[lane.index()].fetch_sub(1, Ordering::Relaxed);
1192 self.occupied.fetch_sub(1, Ordering::Relaxed);
1193 if count {
1194 self.shed_memory.fetch_add(1, Ordering::Relaxed);
1195 }
1196 return Err(Shed::Memory {
1197 class,
1198 wanted: bytes,
1199 reserved: self.memory.reserved(),
1200 budget: self.memory.budget(),
1201 });
1202 }
1203
1204 Ok(Claim {
1205 class,
1206 bytes,
1207 enqueued: Instant::now(),
1208 })
1209 }
1210
1211 /// **Charge a running transfer for what has actually crossed the wire.**
1212 ///
1213 /// Called by [`crate::AdmissionGuard::reserve_more`] and by nothing else,
1214 /// so the guard stays the single owner of "what this operation holds" and
1215 /// the release cannot drift. See [`Growth`] for why it cannot refuse and
1216 /// [`WIRE_MEMORY_NUMERATOR`] for what fraction of the wire is charged.
1217 pub fn charge(&self, held_after: u64, extra: u64) -> Growth {
1218 if self.memory.charge(extra) {
1219 Growth::Fitted { held: held_after }
1220 } else {
1221 self.overdrawn.fetch_add(1, Ordering::Relaxed);
1222 Growth::Overdrawn {
1223 held: held_after,
1224 reserved: self.memory.reserved(),
1225 budget: self.memory.budget(),
1226 }
1227 }
1228 }
1229
1230 /// Give a claim's slot and reservation back. Called from exactly one place:
1231 /// [`AdmissionGuard`](crate::AdmissionGuard)'s `Drop`, which passes what it
1232 /// grew the reservation to on top of [`Claim::bytes`].
1233 pub fn release(&self, claim: &Claim, grown: u64) {
1234 self.memory.release(claim.bytes.saturating_add(grown));
1235 let lane = claim.class.lane();
1236 let _ = self.per_lane[lane.index()].fetch_update(
1237 Ordering::Relaxed,
1238 Ordering::Relaxed,
1239 |held| Some(held.saturating_sub(1)),
1240 );
1241 let _ = self
1242 .occupied
1243 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |occupied| {
1244 Some(occupied.saturating_sub(1))
1245 });
1246 }
1247
1248 /// File one **admission wait** against its class's window.
1249 ///
1250 /// This is the controller's input, and the change of input is the point:
1251 /// see [`LimitBand::for_budget`] for what it used to be (the runtime's
1252 /// spawn-to-run gap) and why a controller that cannot move its own input
1253 /// runs to its floor. A wait of zero — the ordinary case on an unloaded
1254 /// server — is a sample too, and it is the one that grows the limit back.
1255 pub fn record_sojourn(&self, class: OpClass, sojourn: Duration) {
1256 self.codel.record(class, sojourn);
1257 }
1258}
1259
1260/// A one-shot latch for "this operation's work has actually started".
1261///
1262/// Its own type so the "was the sojourn ever measured?" question has one
1263/// answer-holder rather than a bool copied into two structs.
1264#[derive(Debug, Default)]
1265pub struct ServiceMark(AtomicBool);
1266
1267impl ServiceMark {
1268 /// Claim the mark. `true` the first time, `false` for every later call, so a
1269 /// caller that marks twice files one sample rather than two.
1270 pub fn claim(&self) -> bool {
1271 !self.0.swap(true, Ordering::Relaxed)
1272 }
1273
1274 /// Whether the mark was ever claimed.
1275 pub fn claimed(&self) -> bool {
1276 self.0.load(Ordering::Relaxed)
1277 }
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282 use super::*;
1283
1284 /// Drive `class` through exactly one closed window at `sojourn`.
1285 ///
1286 /// Two samples: one to open the window, one at `INTERVAL` later to close it.
1287 /// Returns the instant the window closed, so a caller can chain windows.
1288 fn one_window(codel: &Codel, class: OpClass, sojourn: Duration, from: Instant) -> Instant {
1289 codel.record_at(class, sojourn, from);
1290 let closed = from + INTERVAL;
1291 codel.record_at(class, sojourn, closed);
1292 closed
1293 }
1294
1295 /// **A standing queue shrinks the limit.**
1296 ///
1297 /// # Seen red
1298 ///
1299 /// By changing `Codel::record_at`'s decision to
1300 /// `let standing = window.min.is_some_and(|min| min > INTERVAL);` — i.e.
1301 /// comparing the window minimum against the window length instead of the
1302 /// class's target, the natural "off by one constant" of this controller.
1303 /// Failure:
1304 ///
1305 /// ```text
1306 /// a queue standing at 50ms against a 5ms target did not shrink the limit:
1307 /// it is still 100 after 8 closed windows (shrinks=0)
1308 /// ```
1309 #[test]
1310 fn a_standing_queue_shrinks_the_limit() {
1311 let codel = Codel::new(LimitBand::DEFAULT);
1312 assert_eq!(
1313 codel.limit(),
1314 MAX_LIMIT,
1315 "a governor starts at the top of its band"
1316 );
1317
1318 // Ten times the ls-remote target, for eight windows.
1319 let mut at = Instant::now();
1320 for _ in 0..8 {
1321 at = one_window(&codel, OpClass::LsRemote, Duration::from_millis(50), at);
1322 }
1323
1324 assert!(
1325 codel.limit() < MAX_LIMIT,
1326 "a queue standing at 50ms against a {:?} target did not shrink the limit: it is \
1327 still {} after 8 closed windows (shrinks={})",
1328 OpClass::LsRemote.target(),
1329 codel.limit(),
1330 codel.shrinks()
1331 );
1332 assert_eq!(
1333 codel.shrinks(),
1334 8,
1335 "every closed standing window must shrink"
1336 );
1337 // 100 → 88 → 78 → 69 → 61 → 54 → 48 → 42 → 37: multiplicative, not -8.
1338 assert_eq!(
1339 codel.limit(),
1340 37,
1341 "the decrease must be MULTIPLICATIVE (limit -= limit/8); an additive one would \
1342 leave a different number here and would not back off fast enough to matter"
1343 );
1344 assert_eq!(codel.grows(), 0);
1345 }
1346
1347 /// **A draining queue grows the limit.**
1348 ///
1349 /// # Seen red
1350 ///
1351 /// By making `Codel::grow` a no-op (`fn grow(&self) { }`). Failure:
1352 ///
1353 /// ```text
1354 /// a queue draining at 1ms did not grow the limit: 10 after 20 closed
1355 /// windows, and a controller that only shrinks is a ratchet
1356 /// ```
1357 #[test]
1358 fn a_draining_queue_grows_the_limit() {
1359 let codel = Codel::new(LimitBand::DEFAULT);
1360 // Start from the floor so growth is visible: shrink it there first.
1361 let mut at = Instant::now();
1362 for _ in 0..40 {
1363 at = one_window(&codel, OpClass::LsRemote, Duration::from_millis(50), at);
1364 }
1365 assert_eq!(
1366 codel.limit(),
1367 MIN_LIMIT,
1368 "the standing phase must reach the floor"
1369 );
1370
1371 for _ in 0..20 {
1372 at = one_window(&codel, OpClass::LsRemote, Duration::from_millis(1), at);
1373 }
1374 assert!(
1375 codel.limit() > MIN_LIMIT,
1376 "a queue draining at 1ms did not grow the limit: {} after 20 closed windows, and a \
1377 controller that only shrinks is a ratchet",
1378 codel.limit()
1379 );
1380 assert_eq!(
1381 codel.limit(),
1382 MIN_LIMIT + 20,
1383 "growth must be ADDITIVE, one per closed draining window"
1384 );
1385 }
1386
1387 /// **The limit never leaves its band**, in either direction, however long
1388 /// the load runs.
1389 ///
1390 /// # Seen red
1391 ///
1392 /// By dropping the clamp from `Codel::shrink`
1393 /// (`Some(limit.saturating_sub((limit / 8).max(1)))`). Failure:
1394 ///
1395 /// ```text
1396 /// the limit left the band: 9 is outside [10, 100]
1397 /// ```
1398 ///
1399 /// It fails on the FIRST step past the floor, not after drifting to zero,
1400 /// which is what makes the assertion inside the loop worth having: a check
1401 /// only at the end would report `0` and hide when it started.
1402 #[test]
1403 fn the_limit_never_leaves_the_band() {
1404 let codel = Codel::new(LimitBand::DEFAULT);
1405 let mut at = Instant::now();
1406
1407 // Far past the floor.
1408 for _ in 0..200 {
1409 at = one_window(&codel, OpClass::LsRemote, Duration::from_secs(1), at);
1410 let limit = codel.limit();
1411 assert!(
1412 (MIN_LIMIT..=MAX_LIMIT).contains(&limit),
1413 "the limit left the band: {limit} is outside [{MIN_LIMIT}, {MAX_LIMIT}]"
1414 );
1415 }
1416 assert_eq!(codel.limit(), MIN_LIMIT);
1417
1418 // …and far past the ceiling.
1419 for _ in 0..500 {
1420 at = one_window(&codel, OpClass::LsRemote, Duration::from_micros(1), at);
1421 let limit = codel.limit();
1422 assert!(
1423 (MIN_LIMIT..=MAX_LIMIT).contains(&limit),
1424 "the limit left the band: {limit} is outside [{MIN_LIMIT}, {MAX_LIMIT}]"
1425 );
1426 }
1427 assert_eq!(codel.limit(), MAX_LIMIT);
1428 }
1429
1430 /// **THE HEAD-OF-LINE TEST.** A slow class does not shrink the limit on a
1431 /// fast class's behalf.
1432 ///
1433 /// A `linux.git` clone waiting 150 ms is a clone that has not noticed. An
1434 /// `ls-remote` waiting 150 ms has had its latency multiplied by fifteen.
1435 /// One number cannot say both, so the target is per class — and this test is
1436 /// the difference between the two designs.
1437 ///
1438 /// # Seen red
1439 ///
1440 /// By replacing the per-class bar in `Codel::record_at` with the single
1441 /// shared one the naive design has:
1442 /// `let standing = window.min.is_some_and(|min| min > TARGET);`
1443 /// Failure:
1444 ///
1445 /// ```text
1446 /// a clone waiting 150ms — well inside its own 186ms target, and a wait its
1447 /// client cannot perceive — shrank the shared limit to 42. That is the
1448 /// slow class poisoning the fast class's delay signal, which is the exact
1449 /// trap per-class sojourn exists to close (shrinks=8)
1450 /// ```
1451 #[test]
1452 fn a_slow_class_does_not_shrink_the_limit_on_a_fast_class_behalf() {
1453 let codel = Codel::new(LimitBand::DEFAULT);
1454 let mut at = Instant::now();
1455
1456 // Eight windows of clones waiting 150 ms — thirty times the ls-remote
1457 // target, and comfortably INSIDE clone's own 186 ms target.
1458 assert!(Duration::from_millis(150) > OpClass::LsRemote.target());
1459 assert!(Duration::from_millis(150) < OpClass::Clone.target());
1460 for _ in 0..8 {
1461 at = one_window(&codel, OpClass::Clone, Duration::from_millis(150), at);
1462 }
1463 assert_eq!(
1464 codel.limit(),
1465 MAX_LIMIT,
1466 "a clone waiting 150ms — well inside its own {:?} target, and a wait its client \
1467 cannot perceive — shrank the shared limit to {}. That is the slow class poisoning \
1468 the fast class's delay signal, which is the exact trap per-class sojourn exists to \
1469 close (shrinks={})",
1470 OpClass::Clone.target(),
1471 codel.limit(),
1472 codel.shrinks()
1473 );
1474 assert_eq!(codel.shrinks(), 0);
1475
1476 // The other half of the bar, or the test above would also pass on a
1477 // controller that had simply stopped shrinking: the SAME 150 ms, filed
1478 // under ls-remote, must shrink hard.
1479 for _ in 0..8 {
1480 at = one_window(&codel, OpClass::LsRemote, Duration::from_millis(150), at);
1481 }
1482 assert!(
1483 codel.limit() < MAX_LIMIT,
1484 "150ms of ls-remote sojourn is thirty times its {:?} target and MUST shed load; a \
1485 controller that shrinks for nobody is not a controller",
1486 OpClass::LsRemote.target()
1487 );
1488 assert_eq!(codel.shrinks(), 8);
1489
1490 // …and the clone class is still healthy while the shared limit came
1491 // down. One queue, one limit, two signals.
1492 let before = codel.limit();
1493 let shrinks_before = codel.shrinks();
1494 for _ in 0..4 {
1495 at = one_window(&codel, OpClass::Clone, Duration::from_millis(150), at);
1496 }
1497 assert!(
1498 codel.limit() > before,
1499 "the clone class must still read as DRAINING and grow the shared limit back from \
1500 {before}, even though its absolute sojourn is thirty times the ls-remote target; \
1501 it is {} instead",
1502 codel.limit()
1503 );
1504 assert_eq!(
1505 codel.shrinks(),
1506 shrinks_before,
1507 "not one of those clone windows may be read as standing"
1508 );
1509 }
1510
1511 /// Each class keeps its **own** window: a sample filed under one class may
1512 /// not open, close or lower another's.
1513 ///
1514 /// # Seen red
1515 ///
1516 /// By indexing every class into slot 0 in `Codel::record_at`
1517 /// (`&mut windows[0]`). Failure:
1518 ///
1519 /// ```text
1520 /// assertion `left == right` failed: push's own windows must close and grow
1521 /// left: 10
1522 /// right: 9
1523 /// ```
1524 ///
1525 /// The tenth growth is the ls-remote sample's own window being closed by a
1526 /// push, which is exactly the crossing this test forbids — one class's
1527 /// sample opening and closing another's window.
1528 #[test]
1529 fn a_sample_lands_in_its_own_class_window_only() {
1530 let codel = Codel::new(LimitBand::DEFAULT);
1531 let at = Instant::now();
1532
1533 // Open ls-remote's window, then push a full INTERVAL of PUSH samples
1534 // through. Nothing may close ls-remote's window but an ls-remote sample.
1535 codel.record_at(OpClass::LsRemote, Duration::from_millis(50), at);
1536 for step in 0..10 {
1537 codel.record_at(
1538 OpClass::Push,
1539 Duration::from_millis(1),
1540 at + INTERVAL * (step + 1),
1541 );
1542 }
1543 // Push closed its own windows and they were healthy, so it GREW.
1544 assert_eq!(codel.grows(), 9, "push's own windows must close and grow");
1545 assert_eq!(
1546 codel.shrinks(),
1547 0,
1548 "a push sample closed the ls-remote window: shrinks={} grows={} after one ls-remote \
1549 sample that could not have closed anything",
1550 codel.shrinks(),
1551 codel.grows()
1552 );
1553 }
1554
1555 /// **Reserving up to the budget admits; the next operation is denied.**
1556 ///
1557 /// # Seen red
1558 ///
1559 /// By making `MemoryLedger::try_reserve` compare `reserved` rather than
1560 /// `reserved + bytes` against the budget — the classic off-by-one-operation
1561 /// budget check, which lets the last admission overshoot by a whole
1562 /// estimate. Failure:
1563 ///
1564 /// ```text
1565 /// the ledger admitted 5 clones against a 4-clone budget: 10737418240
1566 /// reserved of 8589934592
1567 /// ```
1568 #[test]
1569 fn the_budget_admits_up_to_itself_and_then_denies() {
1570 let clone = OpClass::Clone.admission_bytes();
1571 let ledger = MemoryLedger::new(clone * 4);
1572
1573 let mut admitted = 0;
1574 while ledger.try_reserve(clone) {
1575 admitted += 1;
1576 assert!(
1577 admitted <= 4,
1578 "the ledger admitted {admitted} clones against a 4-clone budget: {} reserved of {}",
1579 ledger.reserved(),
1580 ledger.budget()
1581 );
1582 }
1583 assert_eq!(admitted, 4, "a 4-clone budget must admit exactly 4 clones");
1584 assert_eq!(ledger.reserved(), ledger.budget());
1585
1586 // …and a SMALLER operation still fits nowhere, which is the property a
1587 // "there is some room" check would lose.
1588 assert!(
1589 !ledger.try_reserve(1),
1590 "a full ledger handed out one more byte"
1591 );
1592 }
1593
1594 /// **A completed operation releases its reservation and the next one is
1595 /// then admitted.**
1596 ///
1597 /// # Seen red
1598 ///
1599 /// By making `MemoryLedger::release` a no-op. Failure:
1600 ///
1601 /// ```text
1602 /// the 4th clone finished and gave its 2147483648 bytes back, but the next
1603 /// clone was still refused: 8589934592 reserved of 8589934592. A budget
1604 /// that is never released is a server that wedges after N operations
1605 /// ```
1606 #[test]
1607 fn a_completed_operation_releases_its_reservation() {
1608 let clone = OpClass::Clone.admission_bytes();
1609 let ledger = MemoryLedger::new(clone * 4);
1610 for _ in 0..4 {
1611 assert!(ledger.try_reserve(clone));
1612 }
1613 assert!(!ledger.try_reserve(clone), "the budget is full");
1614
1615 ledger.release(clone);
1616 assert!(
1617 ledger.try_reserve(clone),
1618 "the 4th clone finished and gave its {clone} bytes back, but the next clone was \
1619 still refused: {} reserved of {}. A budget that is never released is a server that \
1620 wedges after N operations",
1621 ledger.reserved(),
1622 ledger.budget()
1623 );
1624 }
1625
1626 /// **The budget is never exceeded, however hard it is raced.**
1627 ///
1628 /// # This test was HOLLOW twice, and both failures are worth keeping
1629 ///
1630 /// 1. First written as 64 `thread::spawn`s in a loop, it **passed against a
1631 /// deliberately broken `try_reserve`**: spawning a thread costs orders of
1632 /// magnitude more than the three instructions being raced, so the racers
1633 /// arrived one at a time. A concurrency test whose threads never overlap
1634 /// is a test of `thread::spawn`.
1635 /// 2. Adding a `Barrier` was not enough either — five runs, still green.
1636 /// One release of 64 threads gives the bug exactly one chance to happen
1637 /// inside a window a few nanoseconds wide.
1638 ///
1639 /// What makes it fail is **many chances at the boundary**: a budget of four
1640 /// slabs, every thread cycling reserve/release, so the "is there room for
1641 /// one more" edge is crossed millions of times instead of once. The
1642 /// invariant is checked by the racers themselves, not after the fact.
1643 ///
1644 /// # Seen red
1645 ///
1646 /// By rewriting `try_reserve` as load / compare / `fetch_add`, which is what
1647 /// it looks like it could be. On the reference desktop, 2026-08-14:
1648 ///
1649 /// ```text
1650 /// 32 racers cycling 20000 times each drove the ledger to 23068672 bytes
1651 /// against a budget of 4194304: it was exceeded by 18874368 bytes, which
1652 /// is a budget that the number of concurrent admissions can walk straight
1653 /// past
1654 /// ```
1655 ///
1656 /// Five and a half times the budget. The naive version does not overshoot
1657 /// by one slab, it overshoots by however many threads are in the window.
1658 #[test]
1659 fn the_budget_is_not_exceeded_by_racing_admissions() {
1660 use std::sync::{Arc, Barrier};
1661
1662 let slab = 1024 * 1024u64;
1663 let slabs = 4u64;
1664 let racers = 32;
1665 let rounds = 20_000;
1666 let budget = slab * slabs;
1667 let ledger = Arc::new(MemoryLedger::new(budget));
1668 // The high-water mark any racer ever SAW, which is the applied output:
1669 // a budget is not a budget if a reader can observe it exceeded.
1670 let peak = Arc::new(AtomicU64::new(0));
1671 let gate = Arc::new(Barrier::new(racers));
1672
1673 // Plain std threads: these are one-shot racers, not data-parallel work,
1674 // so there is nothing for gatling to rotate over and rayon is forbidden
1675 // outright (the multicore rule: gatling, never rayon).
1676 let threads: Vec<_> = (0..racers)
1677 .map(|_| {
1678 let ledger = Arc::clone(&ledger);
1679 let peak = Arc::clone(&peak);
1680 let gate = Arc::clone(&gate);
1681 std::thread::spawn(move || {
1682 gate.wait();
1683 for _ in 0..rounds {
1684 if ledger.try_reserve(slab) {
1685 peak.fetch_max(ledger.reserved(), Ordering::Relaxed);
1686 ledger.release(slab);
1687 }
1688 }
1689 })
1690 })
1691 .collect();
1692 for thread in threads {
1693 thread.join().expect("racer");
1694 }
1695
1696 assert_eq!(
1697 ledger.reserved(),
1698 0,
1699 "every reservation was released, so the ledger must be empty"
1700 );
1701 assert!(
1702 peak.load(Ordering::Relaxed) <= budget,
1703 "{} racers cycling {rounds} times each drove the ledger to {} bytes against a budget \
1704 of {budget}: it was exceeded by {} bytes, which is a budget that the number of \
1705 concurrent admissions can walk straight past",
1706 racers,
1707 peak.load(Ordering::Relaxed),
1708 peak.load(Ordering::Relaxed) - budget
1709 );
1710 // …and the racers really did reach the boundary, or the assertion above
1711 // passed on a ledger nobody ever filled.
1712 assert_eq!(
1713 peak.load(Ordering::Relaxed),
1714 budget,
1715 "the ledger never actually filled ({} of {budget}), so the boundary this test is \
1716 about was never crossed",
1717 peak.load(Ordering::Relaxed)
1718 );
1719 }
1720
1721 /// A memory refusal must give the **concurrency** slot straight back.
1722 ///
1723 /// # Seen red
1724 ///
1725 /// By deleting the `self.occupied.fetch_sub(1, ...)` from the memory arm of
1726 /// `Governor::try_claim`. Failure:
1727 ///
1728 /// ```text
1729 /// 40 memory refusals leaked 40 concurrency slots: occupied is 44 with 4
1730 /// operations actually in flight, so the gate now refuses on TIME for a
1731 /// reason that has nothing to do with time
1732 /// ```
1733 #[test]
1734 fn a_memory_refusal_does_not_leak_a_concurrency_slot() {
1735 let clone = OpClass::Clone.admission_bytes();
1736 let governor = Governor::new(LimitBand::DEFAULT, clone * 4);
1737 let held: Vec<_> = (0..4)
1738 .map(|i| {
1739 governor
1740 .try_claim(OpClass::Clone)
1741 .unwrap_or_else(|shed| panic!("clone {i} of 4 was shed: {shed:?}"))
1742 })
1743 .collect();
1744
1745 for _ in 0..40 {
1746 let shed = governor
1747 .try_claim(OpClass::Clone)
1748 .expect_err("the budget is full");
1749 assert!(matches!(shed, Shed::Memory { .. }), "{shed:?}");
1750 }
1751 assert_eq!(
1752 governor.occupied(),
1753 4,
1754 "40 memory refusals leaked {} concurrency slots: occupied is {} with 4 operations \
1755 actually in flight, so the gate now refuses on TIME for a reason that has nothing \
1756 to do with time",
1757 governor.occupied() - 4,
1758 governor.occupied()
1759 );
1760
1761 for claim in &held {
1762 governor.release(claim, 0);
1763 }
1764 assert_eq!(governor.occupied(), 0);
1765 assert_eq!(governor.memory().reserved(), 0);
1766 }
1767
1768 /// The operator's ceiling is the upper bound of the whole band, floor
1769 /// included.
1770 ///
1771 /// # Seen red
1772 ///
1773 /// By writing `LimitBand::for_ceiling` as `{ min: MIN_LIMIT, max: MAX_LIMIT.min(ceiling) }`
1774 /// — the obvious version. Failure:
1775 ///
1776 /// ```text
1777 /// assertion `left == right` failed: a server told to serve 4 has a band of
1778 /// [10, 4] and a limit of 4: the governor admits more than the operator
1779 /// configured
1780 /// left: LimitBand { min: 10, max: 4 }
1781 /// right: LimitBand { min: 4, max: 4 }
1782 /// ```
1783 ///
1784 /// An inverted band — `min` above `max` — which `usize::clamp` panics on
1785 /// the moment the controller tries to move. The band has to be well formed
1786 /// at construction, not corrected later.
1787 #[test]
1788 fn a_configured_ceiling_below_the_floor_is_still_the_ceiling() {
1789 let band = LimitBand::for_ceiling(4);
1790 assert_eq!(
1791 band,
1792 LimitBand { min: 4, max: 4 },
1793 "a server told to serve 4 has a band of [{}, {}] and a limit of {}: the governor \
1794 admits more than the operator configured",
1795 band.min,
1796 band.max,
1797 Codel::new(band).limit()
1798 );
1799 assert_eq!(Codel::new(band).limit(), 4);
1800
1801 // ★ A ceiling ABOVE the design default is honoured, not capped.
1802 //
1803 // The first form did `MAX_LIMIT.min(ceiling)`, so the shipped default of
1804 // 256 became a band of [10, 100] and the server quietly served 100.
1805 // Lowering an operator's explicit number is the same defect as raising
1806 // it. Seen RED by restoring that `.min()`: left `LimitBand { min: 10,
1807 // max: 100 }`, right `LimitBand { min: 10, max: 256 }`.
1808 assert_eq!(
1809 LimitBand::for_ceiling(256),
1810 LimitBand { min: 10, max: 256 },
1811 "a configured ceiling of 256 was lowered to the design's default"
1812 );
1813 assert_eq!(LimitBand::for_ceiling(32), LimitBand { min: 10, max: 32 });
1814 // With no ceiling configured, the design's band still applies.
1815 assert_eq!(LimitBand::DEFAULT, LimitBand { min: 10, max: 100 });
1816 }
1817
1818 /// Every class has a distinct index, or two classes share a window and the
1819 /// head-of-line guard is silently off.
1820 #[test]
1821 fn every_class_has_its_own_window_slot() {
1822 let mut seen = [false; OpClass::COUNT];
1823 for class in OpClass::ALL {
1824 assert!(
1825 !std::mem::replace(&mut seen[class.index()], true),
1826 "{class} shares window slot {} with another class",
1827 class.index()
1828 );
1829 }
1830 assert!(seen.iter().all(|&s| s));
1831 }
1832
1833 /// The service mark is one-shot, so a caller that marks twice files one
1834 /// sojourn sample rather than two.
1835 #[test]
1836 fn the_service_mark_is_one_shot() {
1837 let mark = ServiceMark::default();
1838 assert!(!mark.claimed());
1839 assert!(mark.claim(), "the first claim wins");
1840 assert!(!mark.claim(), "the second claim must not");
1841 assert!(mark.claimed());
1842 }
1843}