Skip to main content

gunnar_ssh/
admission.rs

1//! **Admission control for git transfers**: an explicit, countable
2//! ceiling in place of the accidental one.
3//!
4//! # What the accidental ceiling was
5//!
6//! Every git transfer occupies one tokio **blocking-pool** thread for its whole
7//! duration (`gunnar-cli`'s `WireTransport::serve` bridges an async duplex into
8//! `gunnar-wire`'s blocking `BufRead`/`Write` through `SyncIoBridge`). Nothing
9//! bounded how many of those could exist at once, so the real limit was
10//! `tokio`'s default of 512 blocking threads, a number nobody chose. Past it,
11//! transfers queued **silently**: no log, no counter, no error. The failure an
12//! operator saw was "git is slow", with nothing anywhere to look at.
13//!
14//! # Why this refuses instead of queueing
15//!
16//! This gate **refuses** over the limit rather than queueing behind it, and the
17//! reasoning is not "refusing is simpler":
18//!
19//! * **A git client retries; a git client cannot see a queue.** `git` reports
20//!   whatever the server says and the user (or CI) runs it again. A refusal that
21//!   arrives in milliseconds with a sentence in it is strictly better
22//!   information than a socket that goes quiet for a minute.
23//! * **Queueing keeps the expensive things alive.** A queued transfer still
24//!   holds a TCP socket, a russh session, its channel and its key material. That
25//!   is the resource a fork-bomb of clones is trying to exhaust, and a queue
26//!   hands it to them for free.
27//! * **The two existing timeouts fight a queue.** `inactivity_timeout` (600 s)
28//!   and `exec_grace` (60 s) both measure a session that is not making progress.
29//!   A transfer parked in a queue looks exactly like one of those, so a long
30//!   wait ends in a disconnect anyway, after having occupied the slot for the
31//!   whole wait.
32//! * **A queue makes saturation invisible again.** The whole point of the ceiling is
33//!   that the ceiling must be *visible*. A refusal is an event with a number
34//!   attached; a wait is the thing that was already happening.
35//!
36//! So: [`Admission::try_admit`] never blocks and never waits. It either returns
37//! a guard or a [`Refusal`], and both outcomes move a counter.
38//!
39//! # Two limits, because one is not enough
40//!
41//! [`SshConfig::max_concurrent_transfers`](crate::SshConfig::max_concurrent_transfers)
42//! is the server-wide ceiling. On its own it is still exhaustible by a *single*
43//! misbehaving client, which would then deny service to everybody else, so
44//! [`SshConfig::max_transfers_per_principal`](crate::SshConfig::max_transfers_per_principal)
45//! caps what any one identity can hold at once. Identity is the principal id,
46//! not the peer address: gunnar authenticates keys, and a per-IP limit would
47//! punish everyone behind one CI runner's NAT while a botnet walked past it.
48//!
49//! # The per-principal limit is a SHARE, not a wall
50//!
51//! The second limit used to be an unconditional ceiling, and that was wrong in
52//! a way nobody could see from the code. **Measured on a 32-core desktop with
53//! the shipped defaults, 2026-08-03:**
54//!
55//! | load | served | refused |
56//! |---|---|---|
57//! | 1 principal, 64 clients  |  32 | 32 (per-principal) |
58//! | 32 principals, 320 clients | 256 | the rest |
59//!
60//! A client holding **one** key could never reach the advertised 256; that took
61//! eight identities. Every single-team appliance — which is what gunnar is —
62//! silently got one eighth of the capacity written on the box, and the gate that
63//! did it was binding on an **empty server**, where there was nobody to be fair
64//! to.
65//!
66//! The fairness mechanism itself is right: one identity must not be able to take
67//! a shared host away from everybody else. So the ceiling is now **max-min
68//! fair** — it applies only under contention, and what it applies is a share:
69//!
70//! ```text
71//! contended  = occupied (this candidate included) ≥ CONTENTION_PERCENT % of the server-wide limit
72//! ceiling(p) = if !contended { the server-wide limit }
73//!              else          { max(configured, server_wide / active principals) }
74//! admit      = server-wide gate has room  AND  p holds < ceiling(p)
75//! ```
76//!
77//! * **Idle server, one identity** → not contended, so the only ceiling is the
78//!   server-wide one. 64 clients on one key now get 64 slots, and 256 clients
79//!   get 256. That is the half the old gate got wrong.
80//! * **Contended server, many identities** → each gets `server_wide / active`,
81//!   with the configured number as a **floor** nobody drops below however many
82//!   identities show up. A greedy principal is held to its share exactly as
83//!   before.
84//! * **Work-conserving.** Enforcing the share only above the contention
85//!   threshold is what stops "two identities, one of them idle" from costing the
86//!   busy one half the server for no benefit. Below the threshold there are
87//!   free slots, so refusing anything would refuse work the box could do.
88//!
89//! `active principals` is the number of identities holding at least one
90//! transfer *right now* (the candidate included), which is the only demand
91//! signal an admission gate has. It is exact, not sampled: it is the length of
92//! the same map the counts live in, read under the same lock.
93//!
94//! # The ANONYMOUS ceiling: the one caller the share above cannot hold
95//!
96//! Everything above is keyed on a principal id, and that is deliberate: gunnar
97//! authenticates keys, so the fair share divides the server between *identities*
98//! and a greedy one is held to its slice. Anonymous read then opened a door with no key
99//! behind it. Every unauthenticated reader of a public repository arrives as the
100//! single principal [`gunnar_core::ANONYMOUS_PRINCIPAL_ID`] — the id is refused
101//! at registration ([`gunnar_core::Principal::new`]) so nothing else can ever
102//! claim it — which *looks* like the whole internet already sharing one row of
103//! the map above, and therefore already bounded.
104//!
105//! It is not, and the reason is the paragraph before it: **the share is
106//! work-conserving on purpose.** Below [`CONTENTION_PERCENT`] of the governed
107//! limit the share does not bind at all and every principal's ceiling is the
108//! whole server. That rule was measured and is right for a keyed identity —
109//! refusing a lone team its own idle appliance is the exact mistake the 2026-08-03
110//! table above records. Applied to a stranger it says: *an idle box may be taken
111//! entirely by anonymous traffic.* An operator arriving into that does not even
112//! get a clean refusal; they get [`Admission::admit_within`]'s wait, because
113//! nothing evicts a transfer already in flight.
114//!
115//! So anonymous gets a **second, different kind of ceiling**, and the ways it
116//! differs from the per-principal share are the whole design:
117//!
118//! * **Hard, not a share.** It binds on an empty server. There is no
119//!   contention threshold, because the thing being rationed is not fairness
120//!   between identities — it is the blast radius of a caller gunnar cannot name,
121//!   bill, revoke or ring up. Work-conserving is the right instinct for a tenant
122//!   and the wrong one for a stranger.
123//! * **Small in absolute terms**, not a fraction. Five
124//!   ([`DEFAULT_MAX_ANONYMOUS_TRANSFERS`]) against a keyed floor of 32 and a
125//!   server-wide 256. Anonymous can therefore never be more than ~2 % of the
126//!   box, which is what makes "an operator is never held up by an anonymous
127//!   flood" a *structural* statement rather than a hope about timing.
128//! * **Refused instantly, never parked.** [`Admission::admit_within`]'s wait
129//!   exists because a refused keyed client reconnects, and one parked future is
130//!   cheaper than that reconnect. For anonymous the arithmetic inverts: parking
131//!   holds the TCP socket, the russh session and its key material, which is
132//!   precisely the resource a clone fork-bomb is trying to exhaust. So an
133//!   `AnonymousAtCapacity` refusal is final at the first ask.
134//! * **Counted separately** ([`AdmissionStats::refused_anonymous`]). Folded into
135//!   `refused_per_principal` it would be indistinguishable from a CI runner
136//!   hitting its share, and the two demand opposite operator actions: one says
137//!   *raise the limit*, the other says *you are being scraped*.
138//!
139//! ## The keyed reserve: the other half of the same door (D23b)
140//!
141//! The ceiling above is **absolute**, and the box it is a share of is **not**.
142//! [`Governor`]'s CoDel controller sheds the governed limit down its band
143//! whenever the machine is queueing, and the shed was measured reaching a
144//! limit of 19. Five out of 19 is a quarter of the machine, held by a caller
145//! that cannot be named — and held at exactly the moment there is least to go
146//! round. The `~2 %` in the bullet above is a statement about an *unshed* box.
147//! The same arithmetic undoes an operator who raised the ceiling on purpose for
148//! a browse replica: the number they raised bears no relation to the number the
149//! controller is enforcing an hour later.
150//!
151//! So the top of the box is **keyed-only**. An anonymous read is admitted only
152//! while occupancy is *below* [`CONTENTION_PERCENT`] of the governed limit;
153//! from there up it is refused with [`Refusal::KeyedReserve`], instantly, and
154//! counted as [`AdmissionStats::refused_keyed_reserve`]. What that reserves is
155//! [`Admission::keyed_reserve`] slots — 65 of the shipped 256, 2 of a shed 4 —
156//! and a keyed caller can therefore never be refused *by a stranger's
157//! acquisition*.
158//!
159//! Three things about it are decisions rather than defaults:
160//!
161//! * **The threshold is `CONTENTION_PERCENT`, not a fourth number.** That
162//!   constant is *defined* as the occupancy at which gunnar starts asking keyed
163//!   identities to share with each other. The moment it does that is exactly the
164//!   moment it should stop asking them to share with strangers. A second
165//!   threshold would be a second opinion about when the box is busy, and the
166//!   order between the two would be an accident of arithmetic.
167//! * **It refuses an acquisition; it does not evict.** Taking a slot back from
168//!   a transfer already running throws away every byte of pack already built,
169//!   hands a legitimate visitor a torn stream that `git` reports as a network
170//!   error (indistinguishable from a broken repository), and does not even
171//!   reliably give the slot to the keyed caller that triggered it — the
172//!   `slot_freed` wakeup goes to whoever is parked. It would make a
173//!   stranger cost *more* than serving it, because the evicted client comes back
174//!   and redoes the work. Refusing before the first byte costs one
175//!   compare-and-swap.
176//! * **It is enforced inside the claim's compare-and-swap**
177//!   ([`Governor::claim_reserving`](crate::governor::Governor::claim_reserving)),
178//!   not checked around it. Both orderings of "read occupancy, then claim" were
179//!   measured and both leak — the failures are quoted in
180//!   `tests/keyed_reserve.rs`. A limit checked outside the atomic that enforces
181//!   it is not a limit.
182//!
183//! ### What that does and does not promise
184//!
185//! Stated exactly, because the exact statement is weaker than the slogan and the
186//! difference is where somebody would otherwise be surprised. A stranger
187//! admitted onto a *quiet* box is still holding its slot if the box fills a
188//! moment later, and this gate will not take it back. So "a keyed caller is
189//! never refused while a stranger holds anything" is **not** true, and the only
190//! way to make it true is the eviction ruled out above.
191//!
192//! What is true is a **ratchet**. From the moment occupancy reaches
193//! `CONTENTION_PERCENT`, no stranger is admitted again, so anonymous occupancy
194//! from there on only ever falls: every anonymous transfer that finishes hands
195//! its slot to the keyed side and cannot take it back. A flood therefore cannot
196//! hold a busy box at its anonymous maximum — it decays to zero at the rate
197//! transfers complete, and `SshConfig::inactivity_timeout` bounds that rate from
198//! above. The residue is bounded too, at `min(anonymous ceiling, limit −
199//! reserve)`, which on the shipped appliance is 5 of 256. That is the number a
200//! keyed caller could in the worst case be queued behind, and it is the number
201//! the ceiling was chosen to make small.
202//!
203//! What anonymous keeps is therefore the *whole* allowance on a box that is not
204//! busy, which is the ordinary state of an appliance and the only state a public
205//! repository is interesting in. If keyed demand is permanently above
206//! `CONTENTION_PERCENT` the public door is permanently shut — and that is
207//! accepted, deliberately: a box that is three-quarters full of paid-for work
208//! has nothing to spend on a stranger, the refusal is instant and names its own
209//! rule so the operator can see it happening, and the two answers (a bigger
210//! limit, or a browse replica) are both things an operator does rather than
211//! things gunnar should guess. It is not a livelock: nothing is parked, nothing
212//! is retried on gunnar's side, and a stranger costs a string compare.
213//!
214//! ## Why there is no priority WAKE order
215//!
216//! The obvious third mechanism — when a slot frees, wake keyed waiters before
217//! anonymous ones — is not implemented because it would be a no-op.
218//! [`Admission::admit_within`]'s queue **has no anonymous waiters in it**: every
219//! refusal that names anonymity short-circuits the wait, so the only callers
220//! parked on the gate's own `slot_freed` notify are keyed ones already. Adding
221//! a priority queue would mean adding a data structure and a lock in order to
222//! sort a queue with one class in it.
223//!
224//! ## Why not queue the overflow instead
225//!
226//! Same answer as the module's opening section, only more so. A bounded queue
227//! of anonymous readers is a bounded pile of held sockets, and an unbounded one
228//! is a slower outage with worse diagnostics. Refusing in milliseconds with a
229//! sentence in it is the strictly better outcome for a `git` that will retry
230//! anyway, and it is the only outcome that keeps the cost of an anonymous
231//! request proportional to what gunnar is willing to spend on it.
232//!
233//! ## Fairness *among* anonymous readers
234//!
235//! There is none, and there cannot be: telling two strangers apart requires an
236//! identity, and not having one is the definition of this caller. What bounds a
237//! single greedy anonymous client is therefore not a share but the **time** any
238//! one permit can be held — which is already bounded by
239//! `SshConfig::inactivity_timeout` and by the transfer finishing. The ceiling's
240//! job is to cap the total, and the existing timeouts recycle it.
241//!
242//! An operator who wants the old behaviour — a hard per-identity cap that binds
243//! whether or not anyone else is there, e.g. a multi-tenant host that bills by
244//! identity — sets
245//! [`SshConfig::per_principal_limit_is_hard`](crate::SshConfig::per_principal_limit_is_hard).
246//! The configured numbers keep their meaning either way.
247//!
248//! # Saturation is observable, by construction
249//!
250//! [`AdmissionStats`] is a snapshot of five monotonic-or-live counters, reachable
251//! from [`BoundServer::admission`](crate::BoundServer::admission). Every refusal
252//! is also logged at `warn` with the limit that was hit and what was in flight.
253//! `tests/admission.rs` drives a server past its cap and asserts the counter
254//! moved, not merely that nothing crashed.
255//!
256//! # The server-wide limit is a GOVERNOR now, not a constant
257//!
258//! `max_concurrent_transfers` used to be the number of permits in a semaphore,
259//! and a fixed number is wrong in both directions at once: too high and the box
260//! is already thrashing before anything is refused, too low and it refuses work
261//! it could have done. It is also unknowable in advance — the right number
262//! depends on the repositories, the disks and the other tenants.
263//!
264//! So the constant is **replaced** — not joined by a second mechanism — with
265//! [`crate::governor::Governor`], and the operator's number becomes the band's
266//! ceiling rather than the limit itself. Two gates, in this order, both of them
267//! *at admission* and before anything has been allocated:
268//!
269//! 1. **time** — a CoDel controller that measures how long operations *waited*,
270//!    per class, and moves one shared limit;
271//! 2. **space** — a memory reservation the server owns, rather than a
272//!    measurement of the machine it is taken from.
273//!
274//! `crate::governor` sets out why sojourn rather than queue length, why the
275//! minimum rather than the average, why the target is per class, and what the
276//! memory estimate does *not* yet bound. Everything below — the per-principal
277//! max-min share, the counters, the refusal messages — is unchanged and now
278//! divides the *governed* limit instead of the configured one, which is the
279//! right divisor: a share of capacity the server does not have is not a share.
280//!
281//! # The usage share (`admit-share`): a class from `edda_admit`, a share from here
282//!
283//! With the `admit-share` feature the gate asks
284//! [`edda_admit::Admit::plan`] for every **keyed** transfer, with the
285//! namespace's rolling-window bytes out of the flow ledger
286//! ([`gunnar_core::FlowLedger::window_bytes`]) as the usage. The plan's class
287//! maps onto a share this gate already has:
288//!
289//! * `Full` → the per-principal max-min share, exactly as above;
290//! * `Reduced` / `Floor` → **the anonymous ceiling**: a hard cap that binds on
291//!   an idle box, plus the keyed reserve. An over-budget namespace is still
292//!   served — at a stranger's width — and refused FAST, with
293//!   [`Refusal::ReducedShare`], never parked in [`Admission::admit_within`]'s
294//!   wait: the same reasoning that refuses anonymous instead of queueing it
295//!   applies to anybody held to the anonymous share.
296//!
297//! `record` is fed when the guard drops, with the transfer's wire bytes in each
298//! direction, so the estimate `Usage.AdmitPlan` shows learns per kind. The
299//! policy's own slot shares are not configured here — this gate is the share.
300//!
301//! **Without the feature there is no policy field, no call and no branch on
302//! the path**: the admission decision is today's, and `tests/admission.rs`,
303//! `anonymous_ceiling.rs` and `keyed_reserve.rs` run unchanged to prove it.
304//!
305//! # What this is NOT
306//!
307//! It is not intra-request parallelism, and it is deliberately the *opposite*
308//! decision. gatling has no shared pool, so fanning a clone out inside the
309//! request at forge concurrency spawns tens of thousands of OS threads, and
310//! the measured deflate curve is already
311//! *slower* at 64 threads than at 32. Throughput at the load target comes from
312//! serving many requests at once, each costing about one core, which is exactly
313//! what this gate meters.
314
315use std::collections::HashMap;
316use std::sync::atomic::{AtomicU64, Ordering};
317use std::sync::{Arc, Mutex};
318
319use std::time::Duration;
320
321use crate::governor::{
322    Claim, Governor, Growth, Lane, LimitBand, OpClass, ServiceMark, Shed, DEFAULT_ADMISSION_WAIT,
323    DEFAULT_MEMORY_BUDGET_BYTES, WIRE_MEMORY_DENOMINATOR, WIRE_MEMORY_NUMERATOR, WIRE_RESERVE_STEP,
324};
325
326/// Why a transfer was not admitted.
327///
328/// Every variant carries the number that was hit, because a refusal an operator
329/// cannot tie to a number is a mystery rather than a signal.
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub enum Refusal {
332    /// The server-wide concurrent-transfer limit is full.
333    AtCapacity {
334        /// The server-wide limit **in force at the moment of the refusal**.
335        ///
336        /// The *governed* limit, not the configured one: the configured number
337        /// is the ceiling of
338        /// [`LimitBand`](crate::governor::LimitBand), and what actually refuses
339        /// is wherever the CoDel controller has moved to inside it. Reported
340        /// rather than assumed, for the same reason the per-principal share is:
341        /// an operator who read one number out of a config file and a different
342        /// one out of a log would conclude the gate was broken.
343        limit: usize,
344    },
345    /// This principal already holds its share of the server-wide limit.
346    PrincipalAtCapacity {
347        /// The per-principal limit **in force at the moment of the refusal**.
348        ///
349        /// Under [`SshConfig::per_principal_limit_is_hard`] that is the
350        /// configured number. Otherwise it is the max-min share —
351        /// `max(configured, server_wide / active)` — which is why it is
352        /// reported rather than assumed: an operator who read the configured
353        /// number out of a file and a different number out of a log would
354        /// conclude the gate was broken.
355        ///
356        /// [`SshConfig::per_principal_limit_is_hard`]: crate::SshConfig::per_principal_limit_is_hard
357        limit: usize,
358        /// How many identities held a transfer when this one was refused.
359        ///
360        /// `1` means the refusal came from a hard configured cap: a share is
361        /// never smaller than the whole server when there is only one claimant.
362        /// Without this an operator cannot tell "you are being throttled
363        /// because the box is shared" from "you are being throttled because
364        /// somebody pinned a number".
365        active_principals: usize,
366    },
367    /// This operation's **lane** is full while the rest of the server is held
368    /// by the other lanes' floors (gate 1b, [`Lane::floor`]).
369    ///
370    /// Its own variant because the operator action is different: "the box is
371    /// full" says raise the budget, and this one says a *write* storm is being
372    /// held to five eighths of the box on purpose so that reads still land.
373    LaneAtCapacity {
374        /// The lane that was full.
375        lane: Lane,
376        /// What that lane may hold right now.
377        ceiling: usize,
378        /// The governed server-wide limit it is a share of.
379        limit: usize,
380    },
381    /// The **anonymous** caller is already holding its whole ceiling.
382    ///
383    /// Its own variant, and not [`Refusal::PrincipalAtCapacity`] with the
384    /// anonymous id in it, because the operator action is different in kind. A
385    /// per-principal refusal names a client that can be found, telephoned or
386    /// given a bigger share; this one says *strangers are at their cap*, which
387    /// is either normal (a popular public repository) or the first sign of a
388    /// scrape, and in neither case is the answer "raise the concurrency limit".
389    /// It also carries no `active_principals`, because there is exactly one
390    /// anonymous principal and dividing anything by it would be theatre.
391    AnonymousAtCapacity {
392        /// The anonymous ceiling in force, i.e.
393        /// [`Admission::max_anonymous`]. Unlike every other limit reported
394        /// here this one is *not* governed or shared — it is the operator's
395        /// number, unmodified — which is exactly why it is worth printing:
396        /// an operator who sees a refusal against 5 on a box with 200 free
397        /// slots must be able to see immediately that a different knob did it.
398        limit: usize,
399    },
400    /// The stranger asked for a slot inside the part of the box that only a
401    /// **keyed** identity may hold (D23b).
402    ///
403    /// Its own variant, and specifically **not**
404    /// [`Refusal::AnonymousAtCapacity`], because the two say opposite things
405    /// about the machine and are fixed by opposite knobs. `AnonymousAtCapacity`
406    /// means *strangers are at their cap* — it can fire on an idle box, and the
407    /// only number that changes it is `--max-anonymous-transfers`. This one
408    /// means *the box is too busy to spend any of itself on a stranger*: the
409    /// anonymous ceiling is nowhere near reached, and lowering it would do
410    /// nothing at all. The knob here is the server-wide limit, or the size of
411    /// the box, or a browse replica.
412    ///
413    /// It also carries no principal and no share, because it is not a statement
414    /// about this caller at all: it is a statement about occupancy, and the only
415    /// thing about the caller that entered into it was that it has no key.
416    KeyedReserve {
417        /// Slots occupied as the gate's own compare-and-swap observed them —
418        /// the reserve rides inside that atomic
419        /// ([`Governor::claim_reserving`](crate::governor::Governor::claim_reserving)),
420        /// so this is the number that actually made the decision and not a
421        /// second reading taken nearby. Reported so an operator can see the
422        /// decision rather than reconstruct it: `occupied + reserve >= limit`
423        /// is the whole rule, visible in one line of log.
424        occupied: usize,
425        /// The **governed** server-wide limit those slots are out of, i.e.
426        /// wherever the CoDel controller has moved to inside its band. The
427        /// configured number would be actively misleading here: the whole
428        /// reason this gate exists is that the governed limit moves and the
429        /// anonymous ceiling does not.
430        limit: usize,
431        /// How many slots at the top of that limit are keyed-only, i.e.
432        /// [`Admission::keyed_reserve`]. Printed because it is derived
433        /// ([`CONTENTION_PERCENT`]) and therefore appears in no config file an
434        /// operator could look it up in.
435        reserve: usize,
436    },
437    /// The server's **memory budget** is already spoken for (gate 2).
438    ///
439    /// A third reason, kept separate from [`Refusal::AtCapacity`] on purpose: an
440    /// operator who reads "at capacity" raises the concurrency limit, and doing
441    /// that here makes the problem worse. The numbers travel so the log says
442    /// which knob to turn.
443    MemoryBudget {
444        /// The class whose estimate did not fit.
445        class: OpClass,
446        /// What [`OpClass::estimated_bytes`] asked for.
447        wanted: u64,
448        /// What was reserved by operations already in flight.
449        reserved: u64,
450        /// The configured budget.
451        budget: u64,
452    },
453    /// **The gate is PAUSED** — every transfer is refused, not for want of a
454    /// slot but because the server asked for a quiet moment: the runtime
455    /// data-set growth drains the box before it unmounts `/data`
456    /// (`DATA-SET-GROWTH-FLOW.md` §3 step 5, T1/T12). Carries no number
457    /// because no number was hit; carries the reason, whose words the client
458    /// reads. Set and cleared by [`Admission::pause`] / [`Admission::unpause`]
459    /// — one gate, so all three git fronts pause together.
460    Paused {
461        /// Why, and in which words.
462        pause: Pause,
463    },
464    /// **This namespace is over its usage budget** (`admit-share`), so the
465    /// transfer was held to the anonymous share and that share was full.
466    ///
467    /// Its own variant, and neither [`Refusal::AnonymousAtCapacity`] nor
468    /// [`Refusal::KeyedReserve`], because the caller HAS a key and the operator
469    /// action is different again: the tenant's budget (`--admit-limit`), or the
470    /// tenant waiting for the window to move. The plan's sentence ("100 GB/30d
471    /// used 112 GB; this clone ~1.2 GB; Reduced") is in the `warn` row beside it.
472    #[cfg(feature = "admit-share")]
473    ReducedShare {
474        /// The anonymous ceiling the namespace is held to.
475        ceiling: usize,
476        /// `true` when the box was past `CONTENTION_PERCENT` and the keyed
477        /// reserve refused it; `false` when its own ceiling was full.
478        busy: bool,
479    },
480}
481
482/// **Why the admission gate is paused** — the reason, and the sentence the
483/// client is handed for it. An enum rather than a `String` so [`Refusal`]
484/// stays `Copy` and the words are fixed in one place, where a test can hold
485/// them.
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub enum Pause {
488    /// The data set is being grown at runtime: drained, unmounted, grown,
489    /// mounted again — minutes, and the box stays up throughout.
490    Growing,
491}
492
493impl Pause {
494    /// The client's sentence. **The word `growing` is load-bearing** the way
495    /// `starting` is in [`crate::STARTING_MESSAGE`]: it is what tells a
496    /// person, a CI script and the bench that this is a planned pause with an
497    /// end, not a broken repository and not a full box.
498    pub const fn words(self) -> &'static str {
499        match self {
500            Pause::Growing => GROWING_MESSAGE,
501        }
502    }
503    /// The log's `reason` field.
504    pub const fn reason(self) -> &'static str {
505        match self {
506            Pause::Growing => "paused-growing",
507        }
508    }
509}
510
511/// What a client is told while the data set grows. The contract's words
512/// (`DATA-SET-GROWTH-FLOW.md` §0, ruling 1; the drain design note in
513/// `.nornir/data-set-grow-drain.md`), verbatim.
514///
515/// It names no estate: the same build serves gunnar.rs, test2 and every sold estate, and a
516/// test2 push told "gunnar.rs is growing" was told about somebody else's server (2026-10-09).
517pub const GROWING_MESSAGE: &str = "The server is growing its storage to make room for new \
518                                   members. Pushes are paused — please try again in a few \
519                                   minutes.";
520
521impl Refusal {
522    /// What the client is told, in its own protocol.
523    ///
524    /// Says *try again* explicitly. "Server busy" with no instruction reads as a
525    /// permanent failure to a human and to a CI log alike, and this one is
526    /// transient by definition.
527    pub fn client_message(&self) -> String {
528        match self {
529            Refusal::AtCapacity { limit } => format!(
530                "the server is already serving its limit of {limit} concurrent git transfers; \
531                 try again in a moment"
532            ),
533            // Both arms must keep the words "per-principal limit", and neither
534            // may contain "concurrent git transfers": `installtest`'s
535            // `refusals_in_log` tells the two refusals apart by exactly those
536            // substrings, because the log records the refusal by its `Display`
537            // — the same sentence the client is handed. Two witnesses of one
538            // event only agree if they are reading the same string.
539            Refusal::PrincipalAtCapacity {
540                limit,
541                active_principals,
542            } if *active_principals > 1 => format!(
543                "you already have {limit} git transfers in flight, which is your fair share of \
544                 this server while {active_principals} identities are using it; that is the \
545                 per-principal limit in force right now, and it rises again as the server \
546                 empties; try again in a moment"
547            ),
548            Refusal::PrincipalAtCapacity { limit, .. } => format!(
549                "you already have {limit} git transfers in flight on this server, which is the \
550                 per-principal limit; try again in a moment"
551            ),
552            // Shares neither "concurrent git transfers" nor "per-principal
553            // limit": `installtest`'s `refusals_in_log` tells refusals apart by
554            // exactly those, and a fourth reason that collided with either
555            // would be counted as the wrong one.
556            Refusal::LaneAtCapacity {
557                lane,
558                ceiling,
559                limit,
560            } => format!(
561                "this server is holding {lane} operations to {ceiling} of its {limit} slots so \
562                 that the other kinds of request still land; try again in a moment"
563            ),
564            // Shares neither "concurrent git transfers" nor "per-principal
565            // limit", for the reason given twice above. It says *unauthenticated*
566            // in the first clause so a human reading it in a `git` output knows
567            // instantly that the fix is a key, not patience: this is the one
568            // refusal on the box that a caller can make go away by logging in.
569            Refusal::AnonymousAtCapacity { limit } => format!(
570                "this server is already serving {limit} unauthenticated readers, which is all it \
571                 offers without a key; try again in a moment, or push a key and clone as \
572                 yourself"
573            ),
574            // Shares neither "concurrent git transfers" nor "per-principal
575            // limit", for the reason given twice above — and it must not be the
576            // same sentence as `AnonymousAtCapacity` either, because the two
577            // are fixed by different knobs. It says *with a key* so the human
578            // holding the `git` prompt learns the same thing the operator does:
579            // this refusal is about not having one.
580            Refusal::KeyedReserve {
581                occupied,
582                limit,
583                reserve,
584            } => format!(
585                "this server is {occupied} of {limit} slots busy and keeps its last {reserve} for \
586                 callers with a key; try again in a moment, or push a key and clone as yourself"
587            ),
588            // Deliberately shares neither of the two substrings above:
589            // `installtest`'s `refusals_in_log` tells refusals apart by
590            // "concurrent git transfers" and "per-principal limit", and a third
591            // reason that collided with either would be counted as the wrong
592            // one. It says *memory* so the operator raises the budget rather
593            // than the concurrency limit.
594            Refusal::MemoryBudget {
595                class,
596                wanted,
597                reserved,
598                budget,
599            } => format!(
600                "this server holds a memory budget of {} MiB for git operations in flight, {} MiB \
601                 of it is reserved, and a {class} needs {} MiB more than is left; try again in a \
602                 moment",
603                budget / (1024 * 1024),
604                reserved / (1024 * 1024),
605                wanted / (1024 * 1024),
606            ),
607            // Its own words entirely (see `Pause::words`): none of the three
608            // substrings the other refusals are told apart by, and a
609            // sentence that says WHY and for how long.
610            Refusal::Paused { pause } => pause.words().to_owned(),
611            // Shares neither "concurrent git transfers" nor "per-principal
612            // limit" (`installtest`'s `refusals_in_log`), and says *budget* so
613            // the human at the prompt learns it is about their usage, not the box.
614            #[cfg(feature = "admit-share")]
615            Refusal::ReducedShare { ceiling, busy } => format!(
616                "this namespace is over its transfer budget for the window, so it is served at \
617                 the reduced share of {ceiling} git transfers at once{}; try again in a moment, \
618                 or ask for a larger budget",
619                if *busy { ", and none while the server is this busy" } else { "" }
620            ),
621        }
622    }
623
624    /// The **machine-readable** reason, for a log's `reason` field.
625    ///
626    /// The sentence above is for the person holding the `git` prompt; this is
627    /// for the operator filtering a log, and they need different things. Until
628    /// the anonymous ceiling existed every refusal here was fairly described by
629    /// one string — the box was out of *something* server-wide — and both
630    /// fronts hard-coded `admission-gate-full` accordingly. That string is now
631    /// actively misleading on the one refusal that can fire with the box nearly
632    /// empty: an operator who greps `admission-gate-full`, sees a hit, and
633    /// looks at 59 free slots concludes the gate is broken, which is exactly
634    /// the "the limit exists but produces no signal an operator can act on"
635    /// failure the unbounded listener was about, wearing a different hat.
636    ///
637    /// Only the fronts that can actually *see* an anonymous caller use this.
638    /// The gRPC control plane keeps its literal, because
639    /// [`gunnar_grpc::auth`] refuses the anonymous principal outright: a
640    /// `reason` there that could report anonymity would be describing a state
641    /// that crate makes unreachable.
642    pub const fn reason(&self) -> &'static str {
643        match self {
644            Refusal::AtCapacity { .. } => "admission-gate-full",
645            Refusal::LaneAtCapacity { .. } => "admission-lane-full",
646            Refusal::PrincipalAtCapacity { .. } => "admission-principal-share",
647            Refusal::AnonymousAtCapacity { .. } => "admission-anonymous-ceiling",
648            Refusal::KeyedReserve { .. } => "admission-keyed-reserve",
649            Refusal::MemoryBudget { .. } => "admission-memory-budget",
650            Refusal::Paused { pause } => pause.reason(),
651            #[cfg(feature = "admit-share")]
652            Refusal::ReducedShare { .. } => "admission-reduced-share",
653        }
654    }
655}
656
657impl std::fmt::Display for Refusal {
658    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
659        f.write_str(&self.client_message())
660    }
661}
662
663/// A snapshot of the gate's counters.
664///
665/// Taken atomically field by field rather than under a lock: these are a
666/// **signal**, and a signal that costs a mutex on the request path would be
667/// paid for by the thing it is measuring.
668#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
669pub struct AdmissionStats {
670    /// Transfers let through since the server started.
671    pub admitted: u64,
672    /// Transfers refused because the server-wide limit was full.
673    pub refused_at_capacity: u64,
674    /// Transfers refused because one principal held its whole share.
675    pub refused_per_principal: u64,
676    /// Transfers refused because the **memory budget** was spoken for (gate 2).
677    pub refused_memory: u64,
678    /// Reads refused because the **anonymous ceiling** was full.
679    ///
680    /// Deliberately not folded into
681    /// [`refused_per_principal`](Self::refused_per_principal): that counter
682    /// moving means a client gunnar knows about is being throttled, and this one
683    /// moving means strangers are at their cap. A dashboard that added them
684    /// together would show one number that can be entirely benign (a popular
685    /// public repository, working exactly as designed) or entirely alarming (a
686    /// keyed CI fleet starved of its share) with no way to tell which.
687    pub refused_anonymous: u64,
688    /// Reads refused because the slot they wanted was inside the **keyed
689    /// reserve** (D23b).
690    ///
691    /// Deliberately not folded into
692    /// [`refused_anonymous`](Self::refused_anonymous), which is the other half
693    /// of the same door and means the opposite thing. `refused_anonymous`
694    /// moving on an otherwise quiet box is *normal* — a popular public
695    /// repository, the ceiling doing its job — and the operator response is
696    /// none. This counter moving means the box was over
697    /// [`CONTENTION_PERCENT`] full of real work at the moment a stranger
698    /// asked, which is a **capacity** signal: it is the public door being shut
699    /// by load, and it will keep being shut until either the load falls or the
700    /// box grows. Summed together the two would show one number that means
701    /// "everything is fine" and "your public repositories are effectively
702    /// offline" with no way to tell which.
703    pub refused_keyed_reserve: u64,
704    /// Transfers refused at the **reduced share** (`admit-share`): a namespace
705    /// over its usage budget, held to the anonymous width.
706    #[cfg(feature = "admit-share")]
707    pub refused_reduced: u64,
708    /// Transfers refused because the gate was **paused** ([`Pause`]): the
709    /// data set was being grown. Its own counter, because this one moving is
710    /// neither load nor strangers — it is a planned window, and an operator
711    /// reading it wants to know how many clients met the window, not to
712    /// raise any limit.
713    pub refused_paused: u64,
714    /// Transfers in flight right now.
715    pub in_flight: u64,
716    /// The most that were ever in flight at once. This is the number that says
717    /// how close to the ceiling a server has actually been; `in_flight` alone
718    /// never shows it, because a sampler always misses the peak.
719    pub peak_in_flight: u64,
720    /// The **governed** server-wide limit right now, i.e. where the CoDel
721    /// controller has moved to inside its band. `0` when there is no limit.
722    ///
723    /// Without this the shed is invisible: an operator seeing refusals against a
724    /// configured 100 has no way to know the governor has taken it to 37, which
725    /// is the same "the limit exists but produces no signal" the unbounded listener was
726    /// written about.
727    pub limit: usize,
728    /// Bytes reserved by operations in flight, against
729    /// [`memory_budget`](Admission::memory_budget).
730    pub reserved_bytes: u64,
731    /// Operations that were admitted only after **waiting** for a slot
732    /// ([`DEFAULT_ADMISSION_WAIT`]).
733    ///
734    /// This is the queue made countable. It is not a failure count: every one
735    /// of these was served, and every one of them would have been a refusal
736    /// before 2026-08-30.
737    pub admitted_after_wait: u64,
738    /// Milliseconds spent waiting, summed over every operation that waited.
739    pub waited_ms_total: u64,
740    /// The longest single admission wait, in milliseconds. The number that says
741    /// whether the bound is doing anything.
742    pub peak_wait_ms: u64,
743    /// Waits that ran out and became refusals.
744    pub refused_after_wait: u64,
745    /// Refusals because the operation's **lane** was at its ceiling while the
746    /// other lanes' floors held the rest.
747    pub refused_lane: u64,
748    /// Transfers whose reservation grew past the memory budget while they ran.
749    /// Nonzero means one transfer is now keeping new ones out — which is the
750    /// budget working, not failing.
751    pub overdrawn: u64,
752    /// Bytes charged by running transfers over and above their admission
753    /// reservations.
754    pub grown_bytes: u64,
755    /// Milliseconds between admission and the transfer's work actually
756    /// starting, summed over every transfer that reported it.
757    ///
758    /// **Observed, not controlled.** Until 2026-08-30 this gap *was* the CoDel
759    /// controller's input, and that was the defect: it is the tokio ready queue
760    /// plus the blocking-pool handoff, which is set by how many clients are
761    /// connected and doing crypto, not by how many transfers are admitted. A
762    /// refused client reconnects, so shedding made this number worse and the
763    /// controller shed until it hit its floor — the `limit of 19`
764    /// measured. It is kept as a *counter* because it is a real and useful
765    /// symptom of a box that is out of CPU; it is no longer a control input.
766    pub handoff_ms_total: u64,
767    /// The longest single admission-to-work gap, in milliseconds.
768    pub peak_handoff_ms: u64,
769    /// Transfers that finished **without ever reporting that their work
770    /// started**, so they contributed no sojourn sample.
771    ///
772    /// A blindness counter, not a health one. The CoDel controller only sees
773    /// what [`AdmissionGuard::entered_service`] files; a caller that forgets to
774    /// call it leaves the controller with no samples at all, and a controller
775    /// with no samples grows to the top of its band and stays there — a gate
776    /// that looks like it is working and is not. This number must be 0 on any
777    /// path that is actually governed.
778    pub unmeasured_sojourn: u64,
779}
780
781impl AdmissionStats {
782    /// Every refusal, however it was refused.
783    pub fn refused(&self) -> u64 {
784        self.refused_at_capacity
785            + self.refused_lane
786            + self.refused_per_principal
787            + self.refused_memory
788            + self.refused_anonymous
789            + self.refused_keyed_reserve
790            + self.refused_paused
791            + self.refused_reduced()
792    }
793
794    #[cfg(feature = "admit-share")]
795    fn refused_reduced(&self) -> u64 {
796        self.refused_reduced
797    }
798
799    #[cfg(not(feature = "admit-share"))]
800    fn refused_reduced(&self) -> u64 {
801        0
802    }
803
804    /// The mean admission wait over the operations that waited, in
805    /// milliseconds. `0` when nothing has ever waited.
806    pub fn mean_wait_ms(&self) -> u64 {
807        self.waited_ms_total
808            .checked_div(self.admitted_after_wait.max(1))
809            .unwrap_or(0)
810    }
811}
812
813#[derive(Debug, Default)]
814struct Counters {
815    admitted: AtomicU64,
816    refused_at_capacity: AtomicU64,
817    refused_lane: AtomicU64,
818    refused_per_principal: AtomicU64,
819    refused_memory: AtomicU64,
820    /// Reads refused by the anonymous ceiling.
821    refused_anonymous: AtomicU64,
822    /// Reads refused by the keyed reserve (D23b).
823    refused_keyed_reserve: AtomicU64,
824    /// Transfers refused while the gate was paused ([`Pause`]).
825    refused_paused: AtomicU64,
826    /// Transfers refused at the reduced share (`admit-share`).
827    #[cfg(feature = "admit-share")]
828    refused_reduced: AtomicU64,
829    in_flight: AtomicU64,
830    peak_in_flight: AtomicU64,
831    unmeasured_sojourn: AtomicU64,
832    /// Admissions that had to wait for a slot at all.
833    admitted_after_wait: AtomicU64,
834    /// Milliseconds spent waiting, summed over every operation that waited.
835    waited_ms_total: AtomicU64,
836    /// The longest single wait, in milliseconds.
837    peak_wait_ms: AtomicU64,
838    /// Waits that ran out and became refusals.
839    refused_after_wait: AtomicU64,
840    /// Transfers whose growing reservation went past the budget
841    /// ([`Growth::Overdrawn`]).
842    overdrawn: AtomicU64,
843    /// Bytes charged to the ledger by running transfers, over and above their
844    /// admission reservations.
845    grown_bytes: AtomicU64,
846    /// Milliseconds between admission and the transfer's work starting, summed.
847    handoff_ms_total: AtomicU64,
848    /// The longest single admission-to-work gap, in milliseconds.
849    peak_handoff_ms: AtomicU64,
850}
851
852/// How full the server-wide gate must be, in percent, before the per-principal
853/// share is enforced at all.
854///
855/// **Chosen from the measurement, not picked round.** With the shipped defaults
856/// (256 server-wide, 32 per principal) 75 % is 192 in flight, which leaves 64
857/// free slots — exactly **twice** the configured per-principal floor — as
858/// headroom in which a newly arriving identity is never asked about fairness.
859/// Two floors rather than one, so a second identity can arrive *and* be
860/// throttled to its floor without the first having to give anything back.
861///
862/// Below the threshold there are free slots by definition, and refusing a
863/// transfer there refuses work the box could actually do: that is the exact
864/// mistake the old unconditional cap made, where 32 clients on one key were
865/// refused against 224 idle slots. 192 in flight is also already 6× the core
866/// count of the 32-core box the defaults were sized for
867/// (Measurement 3 — 63 % efficiency at 32
868/// threads), so the machine is deep into queueing before fairness engages, and
869/// fairness is only interesting once queueing has started.
870///
871/// It is deliberately **not** configurable. A third number to get wrong is how
872/// the first two ended up unexamined for four sessions; the two an operator
873/// sizes are the limit and the floor.
874pub const CONTENTION_PERCENT: usize = 75;
875
876/// **How many git reads the server will serve without a key at all.**
877///
878/// Five. Chosen small and chosen *absolute*, and both halves are the decision:
879///
880/// * **Small.** Against the shipped 256 server-wide this is under 2 % of the
881///   box. That number is not a guess at demand, it is a statement about
882///   *liability*: it is the most an operator can lose to a caller who cannot be
883///   named, revoked, billed or telephoned. Everything above five anonymous
884///   readers is served by them coming back a moment later, which git clients do
885///   by themselves; nothing above five is worth an operator's console being
886///   slow.
887/// * **Absolute, not a fraction of the limit.** A percentage would grow the
888///   stranger's allowance every time an operator bought a bigger box, which is
889///   exactly backwards — a bigger appliance is bought to serve *the team*
890///   better, and the untrusted share should stay where it was. It also keeps
891///   this ceiling meaningful when the CoDel controller has shed the governed
892///   limit right down: a fraction of a shrinking limit shrinks with it, and the
893///   moment the box is in trouble is the moment this cap most needs to hold
894///   still.
895///
896/// It is far below [`DEFAULT_MAX_TRANSFERS_PER_PRINCIPAL`] (32), which is the
897/// number *one keyed identity is guaranteed*, and that ordering is asserted by
898/// `tests/anonymous_ceiling.rs` rather than left to two constants drifting
899/// apart. It is well above 1, because a public repository that can only ever be
900/// cloned by one person at a time is not public in any useful sense — and
901/// because a ceiling of 1 turns every ordinary CI runner pair into a refusal.
902///
903/// Raise it on a box whose *purpose* is public serving (a browse replica, see
904/// [`crate::control::AnonymousPolicy`]); lower it to 0 — or close the door with
905/// [`SshConfig::without_anonymous_access`](crate::SshConfig::without_anonymous_access)
906/// — on one whose purpose is not.
907///
908/// [`DEFAULT_MAX_TRANSFERS_PER_PRINCIPAL`]: crate::config::DEFAULT_MAX_TRANSFERS_PER_PRINCIPAL
909pub const DEFAULT_MAX_ANONYMOUS_TRANSFERS: usize = 5;
910
911/// How long a parked admission sleeps before re-asking, when nothing wakes it.
912///
913/// A waiter is normally woken by a guard being dropped
914/// ([`Admission::slot_freed`]). This bound exists for the other way the answer
915/// changes: the CoDel limit grows by one every window
916/// ([`crate::governor::INTERVAL`], 100 ms) whose delay was under target, so a
917/// server that is not finishing anything can still have room a moment later.
918/// One window is therefore exactly the right period — sleeping longer would
919/// hold clients past the moment their slot existed, shorter would poll for no
920/// new information.
921const RETRY_INTERVAL: Duration = crate::governor::INTERVAL;
922
923/// How often the `git.transfer.waited` row may be written, in milliseconds.
924///
925/// One second. See [`Admission::wait_row_due`]: the fact that clients are
926/// waiting is worth a row, and one row per waiting client is worth none because
927/// it is the only thing left on the screen.
928const WAIT_ROW_INTERVAL_MS: u64 = 1000;
929
930/// Whether an admission attempt that fails should move a refusal counter.
931///
932/// A wait loop asks the same door many times for one operation; only the last
933/// answer is a refusal. See [`Admission::attempt`].
934#[derive(Debug, Clone, Copy, PartialEq, Eq)]
935enum Count {
936    /// This ask is final: a refusal is a refusal.
937    Yes,
938    /// This ask is a retry inside a wait: a refusal here is a poll.
939    No,
940}
941
942impl Count {
943    fn bump(self, counter: &AtomicU64) {
944        if self == Count::Yes {
945            counter.fetch_add(1, Ordering::Relaxed);
946        }
947    }
948}
949
950/// The gate itself.
951///
952/// Cheap to clone by `Arc`; it holds one semaphore and one small map.
953#[derive(Debug)]
954pub struct Admission {
955    /// Both gates, or `None` when the operator turned the server-wide limit
956    /// off. That is a legitimate configuration (an appliance behind its own
957    /// front door), and it is spelled as an `Option` rather than as `usize::MAX`
958    /// so a log can say "unlimited" and mean it. Unlimited means unlimited: no
959    /// concurrency band and no memory budget, because a budget that binds on a
960    /// gate the operator switched off is a limit they did not ask for.
961    governor: Option<Governor>,
962    max_concurrent: Option<usize>,
963    max_per_principal: Option<usize>,
964    /// When `true`, `max_per_principal` binds unconditionally — the behaviour
965    /// before max-min fairness. `false` (the default) makes it the **floor** of
966    /// a share that only applies under contention.
967    hard_per_principal: bool,
968    /// The **anonymous** ceiling: the most reads
969    /// [`gunnar_core::ANONYMOUS_PRINCIPAL_ID`] may hold at once, or `None` to
970    /// let anonymous take the same max-min share as any keyed identity.
971    ///
972    /// Kept as its own field rather than as an entry in some per-principal
973    /// override map, because a map would invite a second override and the
974    /// second override is a policy engine. There is exactly one caller that has
975    /// no identity, so there is exactly one number here.
976    anonymous_ceiling: Option<usize>,
977    /// Only ever holds principals with a transfer in flight; an entry is removed
978    /// when its count reaches zero, so an idle server carries an empty map
979    /// however many identities have ever connected.
980    ///
981    /// Its **length** is therefore the live count of active identities, which is
982    /// what the max-min share divides by. Keeping the map free of zero entries
983    /// is no longer only hygiene: a leaked entry would shrink everybody's share.
984    per_principal: Mutex<HashMap<String, usize>>,
985    counters: Arc<Counters>,
986    /// Woken every time a guard is dropped, so a waiting admission learns of a
987    /// free slot the instant there is one rather than by polling.
988    ///
989    /// `tokio::sync::Notify` and not a semaphore: the thing being waited for is
990    /// not one permit but *the three gates agreeing*, and only
991    /// [`Admission::try_admit`] knows whether they do. A waiter is woken, it
992    /// re-asks, and if the answer is still no it waits again — which is also
993    /// why a lost wakeup is impossible here: the `Notified` future is created
994    /// **before** the try, so a release that lands in between is still seen.
995    slot_freed: tokio::sync::Notify,
996    /// How long an operation may wait for a slot before it is refused. Zero
997    /// restores the instant refusal exactly.
998    wait: Duration,
999    /// How long a **keyed** (authenticated) caller may wait, when longer than
1000    /// [`Admission::wait`]. `None`: the same wait as everybody. See
1001    /// [`crate::governor::DEFAULT_KEYED_ADMISSION_WAIT`].
1002    keyed_wait: Option<Duration>,
1003    /// When this gate was built, so [`Admission::wait_row_due`] can hold a
1004    /// deadline in one atomic instead of a lock.
1005    epoch: std::time::Instant,
1006    /// Milliseconds since [`Admission::epoch`] at which the next `waited` row
1007    /// may be written.
1008    next_wait_row_ms: AtomicU64,
1009    /// **The pause** ([`Pause`]), `0` for none, else `1 + Pause as u8`. One
1010    /// atomic read on every admission and nothing else on the hot path; set
1011    /// by [`Self::pause`] from the runtime growth's drain, cleared by
1012    /// [`Self::unpause`] when `/data` is back — or when the growth aborted.
1013    pause: std::sync::atomic::AtomicU8,
1014    /// **The per-namespace flow ledger, when the server wired one.**
1015    ///
1016    /// `None` in every test in this crate and in any build with no control
1017    /// store behind it, which is why it is an `Option` rather than something
1018    /// this crate constructs: the gate must work on a bare `Admission::new`,
1019    /// and a ledger it invented would count into a store nobody reads.
1020    ///
1021    /// It is here rather than at the three doors that call [`Self::try_admit`]
1022    /// — the SSH exec line, the smart-HTTP handler and the gRPC transfer gate —
1023    /// because those three converge on [`Self::count_refusal`] and a refusal
1024    /// counted at each of them would be the same event counted three ways, one
1025    /// of which would go stale the first time a fourth door was added.
1026    flow: Option<Arc<gunnar_core::FlowLedger>>,
1027    /// **The admission policy** (`admit-share`): asked for a keyed transfer's
1028    /// class. [`edda_admit::PassThrough`] until the server hands it the
1029    /// configured one ([`Admission::with_policy`]), so a gate built by a test
1030    /// that never heard of budgets decides exactly as before.
1031    #[cfg(feature = "admit-share")]
1032    policy: Policy,
1033}
1034
1035/// `Arc<dyn Admit>` with a `Debug` that names the policy, so [`Admission`]
1036/// keeps its derive.
1037#[cfg(feature = "admit-share")]
1038#[derive(Clone)]
1039struct Policy(Arc<dyn edda_admit::Admit>);
1040
1041#[cfg(feature = "admit-share")]
1042impl std::fmt::Debug for Policy {
1043    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1044        f.write_str(self.0.policy())
1045    }
1046}
1047
1048/// **The `edda_admit` kind of work an [`OpClass`] is.** Estimates learn per kind.
1049pub fn work_kind(class: OpClass) -> edda_admit::WorkKind {
1050    match class {
1051        OpClass::Clone => edda_admit::WorkKind::Clone,
1052        OpClass::Fetch => edda_admit::WorkKind::Fetch,
1053        OpClass::Push => edda_admit::WorkKind::Push,
1054        OpClass::LsRemote | OpClass::Gc => edda_admit::WorkKind::Other,
1055    }
1056}
1057
1058impl Admission {
1059    /// Build a gate from the two configured limits, with the per-principal one
1060    /// as a max-min **share** (see the module docs), the server-wide one as the
1061    /// ceiling of the governor's band, and the default memory budget.
1062    pub fn new(max_concurrent: Option<usize>, max_per_principal: Option<usize>) -> Admission {
1063        Admission::with_memory_budget(
1064            max_concurrent,
1065            max_per_principal,
1066            DEFAULT_MEMORY_BUDGET_BYTES,
1067        )
1068    }
1069
1070    /// **Give the gate a flow ledger**, so a refusal is charged to the
1071    /// namespace that met it and not only to the box's own counters.
1072    ///
1073    /// Builder-style and optional for [`Admission::flow`]'s reason. A gate
1074    /// without one refuses exactly as it always did and simply reports the
1075    /// refusal nowhere but its own `AdmissionStats`, which is what every build
1076    /// before the flow ledger existed did.
1077    pub fn with_flow(mut self, flow: Arc<gunnar_core::FlowLedger>) -> Admission {
1078        self.flow = Some(flow);
1079        self
1080    }
1081
1082    /// **The flow ledger this gate was given**, or `None`.
1083    ///
1084    /// Handed out because this crate's other tenant-facing door — the exec line
1085    /// that denies a principal who holds no grant on the repository it named —
1086    /// needs to charge that tenant and has nowhere else in this crate to reach
1087    /// a ledger. One handle, wired once by the server, rather than a second
1088    /// field on `Shared` that a future constructor could forget to fill.
1089    pub fn flow(&self) -> Option<&Arc<gunnar_core::FlowLedger>> {
1090        self.flow.as_ref()
1091    }
1092
1093    /// The same gate with the memory budget (gate 2) chosen explicitly.
1094    ///
1095    /// The budget has to be an operator's number: by the OS-less law this code
1096    /// cannot read the machine's RAM, so
1097    /// [`DEFAULT_MEMORY_BUDGET_BYTES`](crate::governor::DEFAULT_MEMORY_BUDGET_BYTES)
1098    /// is a constant with a measurement behind it rather than a fit to the box.
1099    pub fn with_memory_budget(
1100        max_concurrent: Option<usize>,
1101        max_per_principal: Option<usize>,
1102        memory_budget: u64,
1103    ) -> Admission {
1104        Admission {
1105            governor: max_concurrent
1106                .map(|budget| Governor::new(LimitBand::for_budget(budget), memory_budget)),
1107            max_concurrent,
1108            max_per_principal,
1109            hard_per_principal: false,
1110            // On by default, because the anonymous door is open by default: a limit
1111            // that has to be switched on is not protecting the configuration
1112            // anybody actually runs.
1113            anonymous_ceiling: Some(DEFAULT_MAX_ANONYMOUS_TRANSFERS),
1114            per_principal: Mutex::new(HashMap::new()),
1115            counters: Arc::new(Counters::default()),
1116            slot_freed: tokio::sync::Notify::new(),
1117            wait: DEFAULT_ADMISSION_WAIT,
1118            keyed_wait: None,
1119            epoch: std::time::Instant::now(),
1120            next_wait_row_ms: AtomicU64::new(0),
1121            pause: std::sync::atomic::AtomicU8::new(0),
1122            flow: None,
1123            #[cfg(feature = "admit-share")]
1124            policy: Policy(Arc::new(edda_admit::PassThrough::new())),
1125        }
1126    }
1127
1128    /// **Give the gate its admission policy** (`admit-share`) — the one built
1129    /// from `--admit-limit` ([`edda_admit::Settings::build`]; `none` is
1130    /// PassThrough).
1131    #[cfg(feature = "admit-share")]
1132    pub fn with_policy(mut self, policy: Arc<dyn edda_admit::Admit>) -> Admission {
1133        self.policy = Policy(policy);
1134        self
1135    }
1136
1137    /// **The admission policy in force**, for `Usage.AdmitPlan`.
1138    ///
1139    /// Without `admit-share` the gate has none, and this is a fresh
1140    /// [`edda_admit::PassThrough`] — every kind `Full`, no budget, nothing
1141    /// learnt — which is the truth about that build.
1142    pub fn admit_policy(&self) -> Arc<dyn edda_admit::Admit> {
1143        #[cfg(feature = "admit-share")]
1144        {
1145            Arc::clone(&self.policy.0)
1146        }
1147        #[cfg(not(feature = "admit-share"))]
1148        {
1149            Arc::new(edda_admit::PassThrough::new())
1150        }
1151    }
1152
1153    /// **The usage `Usage.AdmitPlan` reports for `namespace`** — a READ for
1154    /// the admin view, never on the admission path.
1155    ///
1156    /// A policy with a budget answers from its own table (the same figure the
1157    /// gate plans with). Without one — PassThrough, or a build without
1158    /// `admit-share` — the flow ledger's window is summed directly, so the
1159    /// view still shows what moved; a gate with no ledger counted nothing and
1160    /// says zero.
1161    pub fn admit_usage(&self, policy: &dyn edda_admit::Admit, namespace: &str) -> edda_admit::Usage {
1162        if policy.limit().is_some() {
1163            return policy.usage(&edda_admit::Consumer::Namespace(namespace.to_owned()));
1164        }
1165        let window = edda_admit::DEFAULT_WINDOW_DAYS;
1166        let bytes = match &self.flow {
1167            Some(flow) if !namespace.is_empty() => {
1168                flow.window_bytes(namespace, gunnar_core::now_ms(), window)
1169            }
1170            _ => 0,
1171        };
1172        edda_admit::Usage::new(bytes, window)
1173    }
1174
1175    /// **The flow ledger as a seed** for a policy's table: a namespace's
1176    /// bytes per UTC day over the window, read ONCE per namespace on first
1177    /// sight. See [`gunnar_core::FlowLedger::moved`].
1178    pub fn flow_seed(flow: Arc<gunnar_core::FlowLedger>) -> Arc<dyn edda_admit::Seed> {
1179        Arc::new(move |who: &edda_admit::Consumer, first_day: u64, today: u64| {
1180            let edda_admit::Consumer::Namespace(namespace) = who else {
1181                return Vec::new();
1182            };
1183            let days = u32::try_from(today.saturating_sub(first_day) + 1).unwrap_or(u32::MAX);
1184            let now = gunnar_core::now_ms();
1185            flow.moved(namespace, now, days)
1186                .into_iter()
1187                .filter_map(|(day, bytes)| u64::try_from(day).ok().map(|d| (d, bytes)))
1188                .collect()
1189        })
1190    }
1191
1192    /// **The plan for a keyed transfer** (`admit-share`); `None` for the
1193    /// anonymous principal, which has its own ceiling and no namespace budget.
1194    #[cfg(feature = "admit-share")]
1195    fn plan(&self, principal: &str, namespace: &str, class: OpClass) -> Option<edda_admit::Plan> {
1196        if principal == gunnar_core::ANONYMOUS_PRINCIPAL_ID {
1197            return None;
1198        }
1199        let policy = &*self.policy.0;
1200        let who = edda_admit::Consumer::Namespace(namespace.to_owned());
1201        // The policy's own table: lock-free loads for a namespace already
1202        // seen, seeded ONCE from the flow ledger on first sight
1203        // (`GunnarSsh::with_flow`). PassThrough answers without a table.
1204        let usage = policy.usage(&who);
1205        Some(policy.plan(&edda_admit::Work::new(work_kind(class), None), &who, &usage))
1206    }
1207
1208    /// The same gate with `max_per_principal` as an **unconditional** ceiling.
1209    ///
1210    /// The escape hatch for a host where an identity is a tenant and the cap is
1211    /// what is being sold, rather than an appliance where the identities are all
1212    /// the same team. Selected by
1213    /// [`SshConfig::per_principal_limit_is_hard`](crate::SshConfig::per_principal_limit_is_hard).
1214    pub fn hard_capped(
1215        max_concurrent: Option<usize>,
1216        max_per_principal: Option<usize>,
1217    ) -> Admission {
1218        Admission {
1219            hard_per_principal: true,
1220            ..Admission::new(max_concurrent, max_per_principal)
1221        }
1222    }
1223
1224    /// The same gate with a different memory budget (gate 2).
1225    ///
1226    /// A builder rather than a fourth constructor argument, so the two
1227    /// concurrency numbers keep the shape every existing caller passes them in.
1228    /// Only meaningful before the gate has admitted anything: it replaces the
1229    /// governor, and a governor holds live occupancy.
1230    pub fn with_budget(self, memory_budget: u64) -> Admission {
1231        Admission {
1232            governor: self
1233                .max_concurrent
1234                .map(|budget| Governor::new(LimitBand::for_budget(budget), memory_budget)),
1235            ..self
1236        }
1237    }
1238
1239    /// A gate with no limits at all; every request is admitted.
1240    ///
1241    /// **Including the anonymous ceiling.** "Unlimited" has to mean unlimited or
1242    /// it is a trap: every test that reaches for this gate does so to take the
1243    /// admission gate *out* of the picture, and one surviving ceiling would make
1244    /// those tests fail for a reason that has nothing to do with what they are
1245    /// about. An operator who wants only the anonymous ceiling builds a real
1246    /// gate and passes `None` for the other two.
1247    pub fn unlimited() -> Admission {
1248        Admission {
1249            anonymous_ceiling: None,
1250            ..Admission::new(None, None)
1251        }
1252    }
1253
1254    /// The same gate with the **anonymous ceiling** set explicitly;
1255    /// `None` switches it off and lets anonymous take a keyed identity's share.
1256    ///
1257    /// A builder and not a fourth constructor argument for the same reason
1258    /// [`Admission::with_budget`] is one: the two concurrency numbers keep the
1259    /// shape every existing caller already passes them in, and a gate built by
1260    /// a test that has never heard of the anonymous door still gets the default ceiling rather
1261    /// than silently getting none.
1262    pub fn with_anonymous_ceiling(self, anonymous_ceiling: Option<usize>) -> Admission {
1263        Admission {
1264            anonymous_ceiling,
1265            ..self
1266        }
1267    }
1268
1269    /// The anonymous ceiling in force, or `None` when anonymous is held
1270    /// only by the ordinary per-principal share.
1271    pub fn max_anonymous(&self) -> Option<usize> {
1272        self.anonymous_ceiling
1273    }
1274
1275    /// **How many slots at the top of the box are keyed-only** right now
1276    /// (D23b), or `0` on a gate with no server-wide limit to reserve out of.
1277    ///
1278    /// Derived, never configured. It is whatever is left of the **governed**
1279    /// limit above [`CONTENTION_PERCENT`], so it moves with the CoDel
1280    /// controller — which is the entire point: the anonymous ceiling is an
1281    /// absolute number and the box it is a share of is not, and a stranger
1282    /// holding five of a shed nineteen is holding a quarter of the machine at
1283    /// the moment the machine has least to give.
1284    ///
1285    /// Reusing `CONTENTION_PERCENT` rather than inventing a fourth number is
1286    /// the decision, not a shortcut. That constant is *defined* as the
1287    /// occupancy at which gunnar starts asking keyed identities to share with
1288    /// each other; the moment it does that is exactly the moment it should stop
1289    /// asking them to share with strangers. Two thresholds would be two
1290    /// opinions about when the box is busy, and the order between them would be
1291    /// an accident of arithmetic rather than a decision.
1292    ///
1293    /// At least `1` whenever there is a limit at all: a reserve that rounded to
1294    /// zero on a small box would be an empty guarantee at exactly the size where
1295    /// a single stranger is the whole problem.
1296    pub fn keyed_reserve(&self) -> usize {
1297        let Some(governor) = &self.governor else {
1298            return 0;
1299        };
1300        let limit = governor.limit();
1301        // The largest occupancy still BELOW contention is
1302        // `ceil(limit * P / 100) - 1`; everything from there up is reserved.
1303        // Integer throughout — a float threshold would put the boundary
1304        // somewhere an operator cannot reproduce with a calculator.
1305        limit - limit.saturating_mul(CONTENTION_PERCENT).div_ceil(100) + 1
1306    }
1307
1308    /// Whether the per-principal limit binds unconditionally.
1309    pub fn per_principal_is_hard(&self) -> bool {
1310        self.hard_per_principal
1311    }
1312
1313    /// The server-wide limit, if there is one.
1314    pub fn max_concurrent(&self) -> Option<usize> {
1315        self.max_concurrent
1316    }
1317
1318    /// The per-principal limit, if there is one.
1319    pub fn max_per_principal(&self) -> Option<usize> {
1320        self.max_per_principal
1321    }
1322
1323    /// The **governed** server-wide limit right now. `None` when unlimited.
1324    pub fn governed_limit(&self) -> Option<usize> {
1325        self.governor.as_ref().map(Governor::limit)
1326    }
1327
1328    /// The memory budget (gate 2). `None` when unlimited.
1329    pub fn memory_budget(&self) -> Option<u64> {
1330        self.governor.as_ref().map(|g| g.memory().budget())
1331    }
1332
1333    /// The governor, for a caller that wants the controller's own counters.
1334    pub fn governor(&self) -> Option<&Governor> {
1335        self.governor.as_ref()
1336    }
1337
1338    /// Take a slot for `principal` running an operation of `class`, or say why
1339    /// not. **Never blocks.**
1340    ///
1341    /// This is the ONE door. Every user-level git operation — clone, fetch,
1342    /// push, ls-remote, gc — passes through here and through nothing else, so
1343    /// there is a single place where "the server cannot keep up" is decided and
1344    /// a single place a counter has to be trusted.
1345    ///
1346    /// Three gates, in this order, all of them **before any of the operation's
1347    /// work is allocated**:
1348    ///
1349    /// 1. **time** — the governed concurrency limit, moved by the per-class
1350    ///    CoDel controller;
1351    /// 2. **space** — the memory reservation for `class`;
1352    /// 3. **fairness** — the per-principal max-min share.
1353    ///
1354    /// Time and space come first because they are facts about the *server*, and
1355    /// a server that cannot serve anybody should not spend a lock working out
1356    /// whose turn it was. The returned guard releases everything when it is
1357    /// dropped — slot, reservation and principal count — so no error path, and
1358    /// no panic, can skip it. That is how a leaked permit turns a working limit
1359    /// into a server that refuses everything an hour after start-up.
1360    ///
1361    /// The caller **must** call [`AdmissionGuard::entered_service`] when the
1362    /// operation's work actually begins, or the controller gets no sojourn
1363    /// sample from it and [`AdmissionStats::unmeasured_sojourn`] counts it.
1364    /// `namespace` is the repository's namespace, for the flow ledger; `""`
1365    /// where the door does not know one, which charges the refusal to the box
1366    /// alone rather than inventing a tenant for it.
1367    pub fn try_admit(
1368        self: &Arc<Self>,
1369        principal: &str,
1370        namespace: &str,
1371        class: OpClass,
1372    ) -> Result<AdmissionGuard, Refusal> {
1373        self.attempt(principal, namespace, class, Count::Yes)
1374    }
1375
1376    /// [`Admission::try_admit`], told whether this ask is the **final** one.
1377    ///
1378    /// [`Admission::admit_within`] asks many times for one operation while it
1379    /// waits, and a refusal counter that moved on every ask would say 21 where
1380    /// one client was refused once. So the wait loop asks with [`Count::No`]
1381    /// and counts once, at the end, when the refusal is final.
1382    fn attempt(
1383        self: &Arc<Self>,
1384        principal: &str,
1385        namespace: &str,
1386        class: OpClass,
1387        counting: Count,
1388    ) -> Result<AdmissionGuard, Refusal> {
1389        let outcome = self.attempt_inner(principal, namespace, class, counting);
1390        // **The per-namespace half of a FINAL refusal**, and the second of the
1391        // two places it is charged from — see [`Self::charge_flow`] for why
1392        // there are two and not one.
1393        //
1394        // RED when this was missing: `attempt` counts the box's own refusal
1395        // counters INLINE (`counting.bump`, six sites) and never calls
1396        // [`Self::count_refusal`], which only [`Self::admit_within`] reaches.
1397        // So the SSH exec line charged the tenant and the two doors that call
1398        // [`Self::try_admit`] — smart HTTP and the gRPC transfer gate — charged
1399        // nobody. The compiler said so out loud (`unused variable: namespace`)
1400        // and the claim that all three doors converged on one counting point
1401        // was simply false.
1402        if counting == Count::Yes && outcome.is_err() {
1403            self.charge_flow(namespace);
1404        }
1405        outcome
1406    }
1407
1408    /// **Charge one admission refusal to the namespace that met it.**
1409    ///
1410    /// The one writer, called from the two places a refusal becomes FINAL:
1411    /// [`Self::attempt`] for the doors that do not wait
1412    /// ([`Self::try_admit`] — smart HTTP and the gRPC transfer gate), and
1413    /// [`Self::count_refusal`] for the door that does
1414    /// ([`Self::admit_within`] — the SSH exec line, which asks many times for
1415    /// one operation and must charge exactly once, at the end).
1416    ///
1417    /// Two call sites and not one because "final" means two different moments
1418    /// on those two paths, and that is the same distinction [`Count`] already
1419    /// exists to draw. What must not be two is the ARITHMETIC, and it is not.
1420    fn charge_flow(&self, namespace: &str) {
1421        if let Some(flow) = &self.flow {
1422            flow.refuse(namespace, gunnar_core::now_ms(), gunnar_core::Refusal::Admission);
1423        }
1424    }
1425
1426    fn attempt_inner(
1427        self: &Arc<Self>,
1428        principal: &str,
1429        namespace: &str,
1430        class: OpClass,
1431        counting: Count,
1432    ) -> Result<AdmissionGuard, Refusal> {
1433        // ── D23b: is this caller allowed the last slots? ───────────────────
1434        //
1435        // `true` only for the one principal that has no key behind it, so on the
1436        // path that carries essentially all traffic this is a string compare
1437        // against a `&'static str` and then nothing at all. Computed here rather
1438        // than after the claim because it has to ride INSIDE the claim's
1439        // compare-and-swap; see `Governor::claim_reserving` for the race that
1440        // taught us so, and `Admission::keyed_reserve` for where the number
1441        // comes from.
1442        //
1443        // Skipped when the ceiling is off (the operator opted out of anonymous read
1444        // entirely, and `Admission::unlimited` must mean unlimited) and when it
1445        // is 0 (the door is shut at every occupancy, and `AnonymousAtCapacity`
1446        // is the truer sentence for that).
1447        //
1448        // ── the PAUSE, before any slot is looked at ─────────────────────
1449        // A paused gate refuses everybody with the pause's words; nothing is
1450        // claimed, so nothing has to be released, and the in-flight count
1451        // keeps meaning "transfers that were admitted before the pause" —
1452        // which is exactly what the drain waits on.
1453        if let Some(pause) = self.paused() {
1454            counting.bump(&self.counters.refused_paused);
1455            return Err(Refusal::Paused { pause });
1456        }
1457        // ── admit-share: a keyed namespace over its budget takes the anonymous
1458        // share (module docs). Without the feature this block does not exist
1459        // and `reduced` is the constant `false`.
1460        #[cfg(feature = "admit-share")]
1461        let plan = self.plan(principal, namespace, class);
1462        #[cfg(feature = "admit-share")]
1463        let reduced = plan.as_ref().is_some_and(|p| {
1464            matches!(p.class, edda_admit::Class::Reduced | edda_admit::Class::Floor)
1465        });
1466        #[cfg(not(feature = "admit-share"))]
1467        let (reduced, _) = (false, namespace);
1468        let anonymous_ceiling = self
1469            .anonymous_ceiling
1470            .filter(|_| principal == gunnar_core::ANONYMOUS_PRINCIPAL_ID || reduced);
1471        let reserve = match anonymous_ceiling {
1472            Some(cap) if cap > 0 => self.keyed_reserve(),
1473            _ => 0,
1474        };
1475
1476        // The server-wide gates first: they are the resources that actually run
1477        // out, and taking them first means the per-principal map is only ever
1478        // touched by a request that could have run.
1479        let counts = counting == Count::Yes;
1480        let claim = match &self.governor {
1481            Some(governor) => match governor.claim_reserving(class, reserve, counts) {
1482                Ok(claim) => Some(claim),
1483                Err(Shed::Reserved {
1484                    occupied,
1485                    limit,
1486                    reserve,
1487                }) => {
1488                    #[cfg(feature = "admit-share")]
1489                    if reduced {
1490                        counting.bump(&self.counters.refused_reduced);
1491                        self.warn_reduced(plan.as_ref(), namespace);
1492                        return Err(Refusal::ReducedShare {
1493                            ceiling: anonymous_ceiling.unwrap_or(0),
1494                            busy: true,
1495                        });
1496                    }
1497                    counting.bump(&self.counters.refused_keyed_reserve);
1498                    return Err(Refusal::KeyedReserve {
1499                        occupied,
1500                        limit,
1501                        reserve,
1502                    });
1503                }
1504                Err(Shed::Concurrency { limit, .. }) => {
1505                    counting.bump(&self.counters.refused_at_capacity);
1506                    return Err(Refusal::AtCapacity { limit });
1507                }
1508                Err(Shed::LaneFull {
1509                    lane,
1510                    ceiling,
1511                    limit,
1512                }) => {
1513                    counting.bump(&self.counters.refused_lane);
1514                    return Err(Refusal::LaneAtCapacity {
1515                        lane,
1516                        ceiling,
1517                        limit,
1518                    });
1519                }
1520                Err(Shed::Memory {
1521                    class,
1522                    wanted,
1523                    reserved,
1524                    budget,
1525                }) => {
1526                    counting.bump(&self.counters.refused_memory);
1527                    return Err(Refusal::MemoryBudget {
1528                        class,
1529                        wanted,
1530                        reserved,
1531                        budget,
1532                    });
1533                }
1534            },
1535            None => None,
1536        };
1537
1538        // The absolute anonymous ceiling, which is a different question
1539        // from the reserve above — that one asked *may this caller take the
1540        // slots that are left*, and this one asks *how many may this caller ever
1541        // hold at once*. Consulted here rather than before the claim because it
1542        // needs the per-principal map, and the map is only ever touched by a
1543        // request that could have run.
1544        if self.max_per_principal.is_some() || anonymous_ceiling.is_some() {
1545            let mut held = self.per_principal.lock().unwrap_or_else(|e| e.into_inner());
1546
1547            // Everything the decision needs, read once under the one lock the
1548            // counts live under. `active` includes this candidate whether or
1549            // not it already has an entry, because a share divided by the
1550            // claimants that are already in is not this claimant's share.
1551            let already_active = held.contains_key(principal);
1552            let active = held.len() + usize::from(!already_active);
1553            let count = held.entry(principal.to_string()).or_insert(0);
1554
1555            // The anonymous ceiling REPLACES the share for the anonymous
1556            // principal; it does not combine with it. Not `min` of the two,
1557            // because the two numbers answer different questions and a `min`
1558            // would let the max-min rule's contention threshold leak in: on an
1559            // idle server the share evaluates to the whole box, so `min` would
1560            // read 5 — correct by accident — while under contention it could
1561            // evaluate lower and the refusal would then be reported as a
1562            // *share*, sending the operator to the wrong knob. One caller, one
1563            // rule, one number in the log.
1564            let (ceiling, anonymous) = match anonymous_ceiling {
1565                Some(cap) => (cap, true),
1566                // Unreachable with `None`: the `if` above is exactly the
1567                // disjunction "there is a per-principal limit OR an anonymous
1568                // ceiling", and this arm is the half where the second is off.
1569                None => (
1570                    self.ceiling_for(self.max_per_principal.unwrap_or(usize::MAX), active),
1571                    false,
1572                ),
1573            };
1574            if *count >= ceiling {
1575                // Do not leave a zero entry behind for a principal that was
1576                // refused: `or_insert` may have just created one. This matters
1577                // more than it used to — a stale entry inflates `active` and
1578                // shrinks everyone's share.
1579                if *count == 0 {
1580                    held.remove(principal);
1581                }
1582                drop(held);
1583                // Hand the slot AND the memory reservation straight back. The
1584                // guard is what normally does this, and there is no guard yet.
1585                if let (Some(governor), Some(claim)) = (&self.governor, &claim) {
1586                    governor.release(claim, 0);
1587                }
1588                #[cfg(feature = "admit-share")]
1589                if anonymous && reduced {
1590                    counting.bump(&self.counters.refused_reduced);
1591                    self.warn_reduced(plan.as_ref(), namespace);
1592                    return Err(Refusal::ReducedShare {
1593                        ceiling,
1594                        busy: false,
1595                    });
1596                }
1597                if anonymous {
1598                    counting.bump(&self.counters.refused_anonymous);
1599                    return Err(Refusal::AnonymousAtCapacity { limit: ceiling });
1600                }
1601                counting.bump(&self.counters.refused_per_principal);
1602                return Err(Refusal::PrincipalAtCapacity {
1603                    limit: ceiling,
1604                    active_principals: active,
1605                });
1606            }
1607            *count += 1;
1608        }
1609
1610        self.counters.admitted.fetch_add(1, Ordering::Relaxed);
1611        let in_flight = self.counters.in_flight.fetch_add(1, Ordering::Relaxed) + 1;
1612        self.counters
1613            .peak_in_flight
1614            .fetch_max(in_flight, Ordering::Relaxed);
1615
1616        // admit-share: the policy's own slot shares are not configured here
1617        // (this gate IS the share), so its `admit` cannot refuse a namespace;
1618        // should a policy ever do so, the gate's decision above stands and the
1619        // transfer simply teaches the estimate nothing.
1620        #[cfg(feature = "admit-share")]
1621        let admitted = plan.and_then(|plan| self.policy.0.admit(&plan).ok());
1622        Ok(AdmissionGuard {
1623            #[cfg(feature = "admit-share")]
1624            admitted,
1625            gate: Arc::clone(self),
1626            // Some **exactly when** the block above incremented a count, so the
1627            // guard's `Drop` decrements precisely what was incremented. The two
1628            // conditions have to be the same expression: an anonymous
1629            // admission counted under a gate with no per-principal limit and
1630            // released by `self.max_per_principal.map(..)` would never be
1631            // released, and the ceiling would fall by one per anonymous clone
1632            // until the door was shut for good.
1633            principal: (self.max_per_principal.is_some() || anonymous_ceiling.is_some())
1634                .then(|| principal.to_string()),
1635            claim,
1636            marked: ServiceMark::default(),
1637            wire: AtomicU64::new(0),
1638            grown: AtomicU64::new(0),
1639        })
1640    }
1641
1642    /// The `warn` row for a reduced-share refusal, carrying the plan's sentence
1643    /// — the one thing a `Copy` [`Refusal`] cannot.
1644    #[cfg(feature = "admit-share")]
1645    fn warn_reduced(&self, plan: Option<&edda_admit::Plan>, namespace: &str) {
1646        tracing::warn!(
1647            target: "gunnar::git",
1648            event = "git.admission.reduced",
1649            namespace,
1650            why = plan.map_or("", |p| p.why.as_str()),
1651            "a namespace over its transfer budget met a full reduced share"
1652        );
1653    }
1654
1655    /// The same gate with a different **admission wait**.
1656    ///
1657    /// `Duration::ZERO` is the pre-2026-08-30 gate exactly: refuse on the spot.
1658    /// See [`DEFAULT_ADMISSION_WAIT`] for why waiting is cheaper than refusing
1659    /// once the client's reconnect is counted.
1660    pub fn with_wait(self, wait: Duration) -> Admission {
1661        Admission { wait, ..self }
1662    }
1663
1664    /// How long this gate lets an operation wait for a slot.
1665    pub fn wait(&self) -> Duration {
1666        self.wait
1667    }
1668
1669    /// The same gate with a **keyed wait**: how long an authenticated caller
1670    /// may be queued for a slot ([`crate::governor::DEFAULT_KEYED_ADMISSION_WAIT`]).
1671    /// `None` gives keyed callers the ordinary [`Admission::wait`].
1672    pub fn with_keyed_wait(self, keyed_wait: Option<Duration>) -> Admission {
1673        Admission { keyed_wait, ..self }
1674    }
1675
1676    /// **How long `principal` may wait for a slot.** Anonymous: the ordinary
1677    /// wait. A keyed identity: the keyed wait when it is longer — a refused
1678    /// key reconnects (git-lfs's pure-SSH transfer cannot even do that: it
1679    /// falls back to `git-lfs-authenticate` and fails the push), while the
1680    /// parked future costs one session the key's own share already bounds. A
1681    /// zero wait (`--admission-wait-ms 0`) is "refuse on the spot" for all.
1682    pub fn wait_for(&self, principal: &str) -> Duration {
1683        if self.wait.is_zero() || principal == gunnar_core::ANONYMOUS_PRINCIPAL_ID {
1684            return self.wait;
1685        }
1686        self.keyed_wait.map_or(self.wait, |k| k.max(self.wait))
1687    }
1688
1689    /// **Take a slot, waiting up to [`Admission::wait`] for one.**
1690    ///
1691    /// The door every transport goes through. It is
1692    /// [`Admission::try_admit`] in a bounded loop, and everything that decides
1693    /// admission still lives there — this adds only the bound and the counters
1694    /// that make the bound visible.
1695    ///
1696    /// Returns the guard and **how long it waited**, which is the number the
1697    /// caller logs and the number the CoDel controller is fed
1698    /// ([`Governor::record_sojourn`](crate::governor::Governor::record_sojourn)):
1699    /// the wait in *this* queue is the one signal the gate has authority over,
1700    /// because shedding is exactly what shortens it.
1701    ///
1702    /// A refusal after the wait is the same [`Refusal`] the instant path
1703    /// returns, with the same sentence — a client must not be able to tell "the
1704    /// server refused at once" from "the server tried for two seconds first"
1705    /// by the shape of the failure, only by the log.
1706    ///
1707    /// # Cancellation
1708    ///
1709    /// Safe to drop at any await point: nothing is held across one. The slot is
1710    /// taken by the *last* `try_admit`, and either it returns a guard (which
1711    /// owns the release) or it took nothing at all.
1712    pub async fn admit_within(
1713        self: &Arc<Self>,
1714        principal: &str,
1715        namespace: &str,
1716        class: OpClass,
1717    ) -> Result<(AdmissionGuard, Duration), Refusal> {
1718        let started = std::time::Instant::now();
1719        let wait = self.wait_for(principal);
1720        let mut refusal = match self.attempt(principal, namespace, class, Count::No) {
1721            Ok(guard) => {
1722                // A wait of zero is a sample too, and it is the one that grows
1723                // the limit back on a server that is coping.
1724                self.record_wait(class, Duration::ZERO);
1725                return Ok((guard, Duration::ZERO));
1726            }
1727            Err(refusal) => refusal,
1728        };
1729        // No wait configured — or the caller is anonymous and was refused for
1730        // being anonymous, which are the refusals this door never parks.
1731        //
1732        // The wait exists because a refused *keyed* client reconnects, and one
1733        // parked future is cheaper than the reconnect. For anonymous that trade
1734        // inverts: the parked future is holding the TCP socket, the russh
1735        // session and its key material for up to `self.wait`, and those are
1736        // exactly the resources a clone fork-bomb is spending gunnar's box to
1737        // acquire. Parking N anonymous readers to protect them from a reconnect
1738        // hands an attacker N held sessions for free — the queue becomes the
1739        // attack. It is also pointless on its own terms: the ceiling is small
1740        // and hard, so unlike a governed limit it will not have grown by the
1741        // time the waiter re-asks; only a transfer finishing can free it, and
1742        // a stranger has no claim on being first in line for that.
1743        //
1744        // `KeyedReserve` (D23b) is parked no more than `AnonymousAtCapacity` is,
1745        // for the same reason twice over. The socket-and-session argument is
1746        // unchanged. And what a parked stranger would be waiting for here is the
1747        // box falling back below `CONTENTION_PERCENT` — which is a KEYED caller
1748        // finishing. Parking a stranger to wait for that is queueing it for a
1749        // slot the whole rule exists to deny it, and every millisecond it spends
1750        // in that queue it is holding the resources the rule was protecting.
1751        //
1752        // `Paused` is never parked either: the pause lasts minutes, not the
1753        // milliseconds a wait covers, and a client parked into a growth is a
1754        // client holding a session across an unmount for nothing.
1755        if wait.is_zero()
1756            || matches!(
1757                refusal,
1758                Refusal::AnonymousAtCapacity { .. }
1759                    | Refusal::KeyedReserve { .. }
1760                    | Refusal::Paused { .. }
1761            )
1762            || is_reduced(&refusal)
1763        {
1764            self.count_refusal(namespace, &refusal);
1765            return Err(refusal);
1766        }
1767        // Parked, and COUNTED as parked: the count is the demand signal
1768        // `Governor::lane_ceiling` reserves other lanes' floors from, and the
1769        // guard pairs the decrement onto every exit including a cancelled
1770        // future.
1771        let _parked = Parked::new(self.governor.as_ref(), class.lane());
1772        loop {
1773            let remaining = match wait.checked_sub(started.elapsed()) {
1774                Some(remaining) if !remaining.is_zero() => remaining,
1775                _ => {
1776                    self.counters
1777                        .refused_after_wait
1778                        .fetch_add(1, Ordering::Relaxed);
1779                    // The refusal is final now, so it is counted now — once,
1780                    // not once per poll.
1781                    self.count_refusal(namespace, &refusal);
1782                    // A wait that ran out is the strongest evidence of a
1783                    // standing queue there is; file it before refusing.
1784                    self.record_wait(class, wait);
1785                    return Err(refusal);
1786                }
1787            };
1788            // Registered BEFORE the retry, so a slot freed between the retry
1789            // and the wait is not a lost wakeup.
1790            let freed = self.slot_freed.notified();
1791            match self.attempt(principal, namespace, class, Count::No) {
1792                Ok(guard) => {
1793                    let waited = started.elapsed();
1794                    let ms = u64::try_from(waited.as_millis()).unwrap_or(u64::MAX);
1795                    self.counters
1796                        .admitted_after_wait
1797                        .fetch_add(1, Ordering::Relaxed);
1798                    self.counters
1799                        .waited_ms_total
1800                        .fetch_add(ms, Ordering::Relaxed);
1801                    self.counters.peak_wait_ms.fetch_max(ms, Ordering::Relaxed);
1802                    self.record_wait(class, waited);
1803                    return Ok((guard, waited));
1804                }
1805                // The same rule inside the loop, for the caller whose FIRST
1806                // refusal was a full server and whose next one is the anonymous
1807                // ceiling: a parked stranger must stop being parked the moment
1808                // the reason becomes "you are a stranger". Without this arm the
1809                // short-circuit above would be defeated by ordering alone.
1810                Err(
1811                    again @ (Refusal::AnonymousAtCapacity { .. } | Refusal::KeyedReserve { .. }),
1812                ) => {
1813                    self.count_refusal(namespace, &again);
1814                    self.record_wait(class, started.elapsed());
1815                    return Err(again);
1816                }
1817                // The reduced share is never parked either (module docs).
1818                Err(again) if is_reduced(&again) => {
1819                    self.count_refusal(namespace, &again);
1820                    self.record_wait(class, started.elapsed());
1821                    return Err(again);
1822                }
1823                Err(again) => refusal = again,
1824            }
1825            // A timeout as well as a notification, because the thing being
1826            // waited for is not only a released slot: the CoDel limit grows on
1827            // its own, and a server whose limit came back while nothing was
1828            // finishing would otherwise keep everybody parked until it did.
1829            let _ = tokio::time::timeout(remaining.min(RETRY_INTERVAL), freed).await;
1830        }
1831    }
1832
1833    /// Move the counter this refusal belongs to. Called exactly once per
1834    /// refused operation, however many times the wait loop asked.
1835    fn count_refusal(&self, namespace: &str, refusal: &Refusal) {
1836        // The tenant's number and the box's number are taken off the one event,
1837        // so they cannot disagree about how many times the door was shut.
1838        self.charge_flow(namespace);
1839        let counter = match refusal {
1840            Refusal::AtCapacity { .. } => &self.counters.refused_at_capacity,
1841            Refusal::LaneAtCapacity { .. } => &self.counters.refused_lane,
1842            Refusal::PrincipalAtCapacity { .. } => &self.counters.refused_per_principal,
1843            Refusal::AnonymousAtCapacity { .. } => &self.counters.refused_anonymous,
1844            Refusal::KeyedReserve { .. } => &self.counters.refused_keyed_reserve,
1845            Refusal::MemoryBudget { .. } => &self.counters.refused_memory,
1846            Refusal::Paused { .. } => &self.counters.refused_paused,
1847            #[cfg(feature = "admit-share")]
1848            Refusal::ReducedShare { .. } => &self.counters.refused_reduced,
1849        };
1850        counter.fetch_add(1, Ordering::Relaxed);
1851    }
1852
1853    /// **May a `waited` row be written now?** At most one per
1854    /// [`WAIT_ROW_INTERVAL`].
1855    ///
1856    /// A row per waiting transfer is a row per *client* under load: the
1857    /// 256-client shape produced 5411 of them in one run, which on the
1858    /// appliance's twenty-row console is the whole screen and nothing else.
1859    /// The fact still has to be visible, so what is emitted is one row per
1860    /// second carrying the AGGREGATE (`admitted_after_wait`, `peak_wait_ms`),
1861    /// which is the shape an operator can actually read. The per-transfer
1862    /// detail stays at `debug`.
1863    ///
1864    /// One compare-and-swap on a deadline, so a hundred racing waiters produce
1865    /// one row and not a hundred.
1866    pub fn wait_row_due(&self) -> bool {
1867        let now = self.epoch.elapsed().as_millis() as u64;
1868        self.next_wait_row_ms
1869            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |due| {
1870                (now >= due).then_some(now + WAIT_ROW_INTERVAL_MS)
1871            })
1872            .is_ok()
1873    }
1874
1875    /// File one admission wait against the controller.
1876    fn record_wait(&self, class: OpClass, waited: Duration) {
1877        if let Some(governor) = &self.governor {
1878            governor.record_sojourn(class, waited);
1879        }
1880    }
1881
1882    /// How many transfers this principal may hold **right now**.
1883    ///
1884    /// The whole max-min rule, in one place, so there is exactly one writer of
1885    /// it and a test can call it directly instead of inferring it from a
1886    /// refusal. Called with the per-principal lock held and the candidate's own
1887    /// server-wide permit already taken.
1888    ///
1889    /// `configured` is the operator's number and `active` counts the identities
1890    /// holding a transfer, this candidate included.
1891    fn ceiling_for(&self, configured: usize, active: usize) -> usize {
1892        // A pinned cap, or no server-wide limit to take a share OF. In the
1893        // second case `max_per_principal` is the only limit there is, so it has
1894        // to bind unconditionally or it means nothing.
1895        let (Some(governor), false) = (&self.governor, self.hard_per_principal) else {
1896            return configured;
1897        };
1898
1899        // The share divides the **governed** limit, not the configured ceiling.
1900        // A share of capacity the governor has already decided the box does not
1901        // have is not a share; dividing the configured 100 while the controller
1902        // is holding 37 would hand every identity a ceiling above the whole
1903        // server.
1904        let server_wide = governor.limit();
1905
1906        // Occupancy read from the governor rather than from `in_flight`: our own
1907        // slot is already taken, and so is the slot of every other request
1908        // currently between `try_claim` and its `in_flight` increment. The
1909        // counter would miss those and read the server as emptier than it is,
1910        // which is the direction that lets a burst past the share.
1911        let occupied = governor.occupied();
1912
1913        // Integer form of `occupied >= CONTENTION_PERCENT% of server_wide`, so
1914        // there is no float and no rounding to argue about.
1915        let contended =
1916            occupied.saturating_mul(100) >= server_wide.saturating_mul(CONTENTION_PERCENT);
1917        if !contended {
1918            // Free slots exist; the server-wide gate is the only thing that
1919            // should be able to refuse. This is the case the old code got
1920            // wrong.
1921            return server_wide;
1922        }
1923
1924        // Max-min: an equal share of the server, but never less than the
1925        // configured floor — an appliance that promised 32 keeps promising 32
1926        // however many identities turn up, and the server-wide semaphore is
1927        // what stops the floors from over-committing the box.
1928        configured.max(server_wide / active.max(1))
1929    }
1930
1931    /// **Pause the gate**: from here until [`Self::unpause`] every transfer
1932    /// on every front door is refused with `pause.words()`, and nothing new
1933    /// takes a slot. Idempotent; a second pause replaces the first's reason.
1934    pub fn pause(&self, pause: Pause) {
1935        self.pause.store(1 + pause as u8, Ordering::SeqCst);
1936        tracing::warn!(
1937            target: "gunnar::limits",
1938            event = "admission.paused",
1939            reason = pause.reason(),
1940            in_flight = self.counters.in_flight.load(Ordering::Relaxed),
1941            "the admission gate is PAUSED: every new git transfer is refused with `{}` until the \
1942             gate is unpaused; transfers already admitted run to completion",
1943            pause.words()
1944        );
1945    }
1946
1947    /// **Unpause the gate.** Idempotent; an unpaused gate stays unpaused.
1948    pub fn unpause(&self) {
1949        if self.pause.swap(0, Ordering::SeqCst) != 0 {
1950            tracing::info!(
1951                target: "gunnar::limits",
1952                event = "admission.unpaused",
1953                refused_while_paused = self.counters.refused_paused.load(Ordering::Relaxed),
1954                "the admission gate is open again"
1955            );
1956        }
1957    }
1958
1959    /// Count a refusal the session gave at the paused door BEFORE reaching
1960    /// [`Self::admit_within`] (the door answers before the command is
1961    /// resolved, so the gate never sees the request).
1962    pub fn note_refused_paused(&self) {
1963        self.counters.refused_paused.fetch_add(1, Ordering::Relaxed);
1964    }
1965
1966    /// The pause in force, if any.
1967    pub fn paused(&self) -> Option<Pause> {
1968        match self.pause.load(Ordering::SeqCst) {
1969            0 => None,
1970            n if n == 1 + Pause::Growing as u8 => Some(Pause::Growing),
1971            _ => None,
1972        }
1973    }
1974
1975    /// Transfers in flight right now — the number the drain waits to see
1976    /// reach zero. A snapshot of one atomic.
1977    pub fn in_flight(&self) -> u64 {
1978        self.counters.in_flight.load(Ordering::Relaxed)
1979    }
1980
1981    /// Everything the gate knows, as of now.
1982    pub fn stats(&self) -> AdmissionStats {
1983        AdmissionStats {
1984            admitted: self.counters.admitted.load(Ordering::Relaxed),
1985            refused_at_capacity: self.counters.refused_at_capacity.load(Ordering::Relaxed),
1986            refused_per_principal: self.counters.refused_per_principal.load(Ordering::Relaxed),
1987            refused_memory: self.counters.refused_memory.load(Ordering::Relaxed),
1988            refused_anonymous: self.counters.refused_anonymous.load(Ordering::Relaxed),
1989            refused_keyed_reserve: self.counters.refused_keyed_reserve.load(Ordering::Relaxed),
1990            refused_paused: self.counters.refused_paused.load(Ordering::Relaxed),
1991            #[cfg(feature = "admit-share")]
1992            refused_reduced: self.counters.refused_reduced.load(Ordering::Relaxed),
1993            in_flight: self.counters.in_flight.load(Ordering::Relaxed),
1994            peak_in_flight: self.counters.peak_in_flight.load(Ordering::Relaxed),
1995            limit: self.governor.as_ref().map_or(0, Governor::limit),
1996            reserved_bytes: self.governor.as_ref().map_or(0, |g| g.memory().reserved()),
1997            unmeasured_sojourn: self.counters.unmeasured_sojourn.load(Ordering::Relaxed),
1998            admitted_after_wait: self.counters.admitted_after_wait.load(Ordering::Relaxed),
1999            waited_ms_total: self.counters.waited_ms_total.load(Ordering::Relaxed),
2000            peak_wait_ms: self.counters.peak_wait_ms.load(Ordering::Relaxed),
2001            refused_after_wait: self.counters.refused_after_wait.load(Ordering::Relaxed),
2002            refused_lane: self.counters.refused_lane.load(Ordering::Relaxed),
2003            overdrawn: self.counters.overdrawn.load(Ordering::Relaxed),
2004            grown_bytes: self.counters.grown_bytes.load(Ordering::Relaxed),
2005            handoff_ms_total: self.counters.handoff_ms_total.load(Ordering::Relaxed),
2006            peak_handoff_ms: self.counters.peak_handoff_ms.load(Ordering::Relaxed),
2007        }
2008    }
2009
2010    fn release(&self, principal: Option<&str>) {
2011        if let Some(principal) = principal {
2012            let mut held = self.per_principal.lock().unwrap_or_else(|e| e.into_inner());
2013            if let Some(count) = held.get_mut(principal) {
2014                *count = count.saturating_sub(1);
2015                if *count == 0 {
2016                    held.remove(principal);
2017                }
2018            }
2019        }
2020        self.counters.in_flight.fetch_sub(1, Ordering::Relaxed);
2021    }
2022}
2023
2024/// Whether `refusal` is the reduced share — the one `admit_within` must not
2025/// park. The constant `false` without `admit-share`.
2026fn is_reduced(refusal: &Refusal) -> bool {
2027    #[cfg(feature = "admit-share")]
2028    {
2029        matches!(refusal, Refusal::ReducedShare { .. })
2030    }
2031    #[cfg(not(feature = "admit-share"))]
2032    {
2033        let _ = refusal;
2034        false
2035    }
2036}
2037
2038/// A held transfer slot **and** its memory reservation. Releasing both is
2039/// [`Drop`], not a method, so no error path — and no panic — can skip it.
2040///
2041/// That is the whole answer to "an operation that ERRORS must still release":
2042/// there is no release call to forget, because unwinding runs `Drop`.
2043#[derive(Debug)]
2044pub struct AdmissionGuard {
2045    gate: Arc<Admission>,
2046    /// `None` when there is no per-principal limit, so the map is never touched
2047    /// and never grown by a configuration that does not use it.
2048    principal: Option<String>,
2049    /// `None` on an unlimited gate, where there is neither a slot nor a
2050    /// reservation to give back.
2051    claim: Option<Claim>,
2052    marked: ServiceMark,
2053    /// Bytes seen on this transfer's wire, in both directions.
2054    wire: AtomicU64,
2055    /// What has been charged to the ledger on top of [`Claim::bytes`]. The
2056    /// guard owns this so [`Drop`] releases exactly what was taken.
2057    grown: AtomicU64,
2058    /// The policy's guard (`admit-share`), handed to `record` on drop with
2059    /// [`AdmissionGuard::wire`] as the cost — the counter the memory gate
2060    /// already keeps, so recording adds nothing per byte.
2061    #[cfg(feature = "admit-share")]
2062    admitted: Option<edda_admit::Guard>,
2063}
2064
2065impl AdmissionGuard {
2066    /// **The operation's work has actually started.** Files this item's sojourn
2067    /// against its class's window.
2068    ///
2069    /// Called by the caller and not by the gate, because only the caller knows
2070    /// when the waiting stopped. In `crate::server` that is the first line of
2071    /// the spawned transfer task: everything between admission and there is the
2072    /// runtime's ready queue and the blocking-pool handoff, which is exactly the
2073    /// invisible queue this whole module exists to make visible.
2074    ///
2075    /// One-shot: a second call is ignored rather than filing a second, longer
2076    /// sample for the same item.
2077    pub fn entered_service(&self) {
2078        let (Some(_governor), Some(claim)) = (&self.gate.governor, &self.claim) else {
2079            return;
2080        };
2081        if self.marked.claim() {
2082            let handoff = claim.enqueued.elapsed();
2083            let ms = u64::try_from(handoff.as_millis()).unwrap_or(u64::MAX);
2084            self.gate
2085                .counters
2086                .handoff_ms_total
2087                .fetch_add(ms, Ordering::Relaxed);
2088            self.gate
2089                .counters
2090                .peak_handoff_ms
2091                .fetch_max(ms, Ordering::Relaxed);
2092        }
2093    }
2094
2095    /// The class this operation was admitted as.
2096    pub fn class(&self) -> Option<OpClass> {
2097        self.claim.as_ref().map(|claim| claim.class)
2098    }
2099
2100    /// **Charge this transfer for `bytes` more on the wire.**
2101    ///
2102    /// Called by the transport as bytes actually move, in either direction, and
2103    /// this is what makes the memory gate cost-based rather than flat: the
2104    /// admission reservation ([`OpClass::admission_bytes`]) is the entry cost,
2105    /// and everything proportional to the transfer arrives here.
2106    ///
2107    /// Charges [`WIRE_MEMORY_NUMERATOR`]/[`WIRE_MEMORY_DENOMINATOR`] of the
2108    /// bytes, in steps of [`WIRE_RESERVE_STEP`], so a per-byte quantity never
2109    /// becomes a per-byte decision. Returns `Some(Growth)` on the calls that
2110    /// actually charged and `None` in between, so a caller can log the
2111    /// overdraw without testing for it.
2112    ///
2113    /// It cannot refuse — see [`Growth`]. What an overdraw does is stop *new*
2114    /// admissions until this transfer finishes.
2115    pub fn reserve_more(&self, bytes: u64) -> Option<Growth> {
2116        let (Some(governor), Some(_)) = (&self.gate.governor, &self.claim) else {
2117            return None;
2118        };
2119        let wire = self.wire.fetch_add(bytes, Ordering::Relaxed) + bytes;
2120        let want = wire * WIRE_MEMORY_NUMERATOR / WIRE_MEMORY_DENOMINATOR / WIRE_RESERVE_STEP
2121            * WIRE_RESERVE_STEP;
2122        let held = self.grown.load(Ordering::Relaxed);
2123        if want <= held {
2124            return None;
2125        }
2126        let extra = want - held;
2127        // `fetch_max`, not a store: two directions can be metering at once and
2128        // the ledger must be charged once per step, not once per racer.
2129        if self.grown.fetch_max(want, Ordering::Relaxed) >= want {
2130            return None;
2131        }
2132        self.gate
2133            .counters
2134            .grown_bytes
2135            .fetch_add(extra, Ordering::Relaxed);
2136        let growth = governor.charge(want, extra);
2137        if matches!(growth, Growth::Overdrawn { .. }) {
2138            self.gate.counters.overdrawn.fetch_add(1, Ordering::Relaxed);
2139        }
2140        Some(growth)
2141    }
2142}
2143
2144impl Drop for AdmissionGuard {
2145    fn drop(&mut self) {
2146        // ONE record per transfer, here, off the stream: the wire total is the
2147        // counter `reserve_more` already keeps for the memory gate, and its
2148        // direction is the class's — a push's bytes came in, everything
2149        // else's went out. Nothing was added to the per-byte path for it.
2150        #[cfg(feature = "admit-share")]
2151        if let Some(admitted) = self.admitted.take() {
2152            let wire = self.wire.load(Ordering::Relaxed);
2153            let push = matches!(self.claim.as_ref().map(|c| c.class), Some(OpClass::Push));
2154            self.gate.policy.0.record(
2155                admitted,
2156                &edda_admit::Cost {
2157                    net_in: if push { wire } else { 0 },
2158                    net_out: if push { 0 } else { wire },
2159                    ..edda_admit::Cost::default()
2160                },
2161            );
2162        }
2163        if let (Some(governor), Some(claim)) = (&self.gate.governor, &self.claim) {
2164            governor.release(claim, self.grown.load(Ordering::Relaxed));
2165            // A transfer that never said its work started gave the controller
2166            // nothing. Counted rather than guessed at: filing the whole
2167            // lifetime as a "sojourn" here would be worse than filing nothing,
2168            // because service time is not wait time and every long clone would
2169            // read as a standing queue.
2170            if !self.marked.claimed() {
2171                self.gate
2172                    .counters
2173                    .unmeasured_sojourn
2174                    .fetch_add(1, Ordering::Relaxed);
2175            }
2176        }
2177        self.gate.release(self.principal.as_deref());
2178        // The slot is free now, so anybody parked in `admit_within` should
2179        // re-ask. `notify_waiters` wakes everyone parked *at this moment* and
2180        // stores nothing for a future waiter, which is right: a waiter that
2181        // arrives later runs `try_admit` itself before it ever parks.
2182        self.gate.slot_freed.notify_waiters();
2183    }
2184}
2185
2186/// One operation's presence in [`Governor::waiting_in`], released on every
2187/// path — return, refusal, or a dropped future.
2188struct Parked<'a> {
2189    governor: Option<&'a Governor>,
2190    lane: Lane,
2191}
2192
2193impl<'a> Parked<'a> {
2194    fn new(governor: Option<&'a Governor>, lane: Lane) -> Parked<'a> {
2195        if let Some(governor) = governor {
2196            governor.entered_wait(lane);
2197        }
2198        Parked { governor, lane }
2199    }
2200}
2201
2202impl Drop for Parked<'_> {
2203    fn drop(&mut self) {
2204        if let Some(governor) = self.governor {
2205            governor.left_wait(self.lane);
2206        }
2207    }
2208}
2209
2210/// **The wire meter**: an `AsyncRead + AsyncWrite` that charges its
2211/// [`AdmissionGuard`] for every byte that crosses it.
2212///
2213/// This is the other half of cost-based admission. [`OpClass::admission_bytes`]
2214/// is what an operation reserves before anybody knows how big it is; this is
2215/// how the ledger finds out. It wraps the same duplex the transport was already
2216/// given, so there is no second copy of the bytes and no second place where a
2217/// transfer's size is known.
2218///
2219/// Both directions are metered through one counter: a push's cost is the pack
2220/// coming in and a clone's is the pack going out, and the ledger does not care
2221/// which way a byte was travelling when it made the server hold something.
2222///
2223/// Zero cost when it is not doing anything: [`AdmissionGuard::reserve_more`]
2224/// returns on an integer comparison until a whole [`WIRE_RESERVE_STEP`] has
2225/// gone by.
2226pub struct Metered<S> {
2227    inner: S,
2228    guard: Arc<AdmissionGuard>,
2229}
2230
2231impl<S> Metered<S> {
2232    /// Meter `inner` against `guard`.
2233    pub fn new(inner: S, guard: Arc<AdmissionGuard>) -> Metered<S> {
2234        Metered { inner, guard }
2235    }
2236
2237    /// Charge for `bytes`, and say so once when the charge did not fit.
2238    fn charge(&self, bytes: usize) {
2239        let Some(growth) = self.guard.reserve_more(bytes as u64) else {
2240            return;
2241        };
2242        if let Growth::Overdrawn {
2243            held,
2244            reserved,
2245            budget,
2246        } = growth
2247        {
2248            tracing::warn!(
2249                target: "gunnar::git",
2250                event = "git.transfer.overdrawn",
2251                held_bytes = held,
2252                reserved_bytes = reserved,
2253                budget_bytes = budget,
2254                "this transfer has now charged the memory budget past its limit; it finishes, \
2255                 and NEW transfers are refused by name until it does"
2256            );
2257        }
2258    }
2259}
2260
2261impl<S: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for Metered<S> {
2262    fn poll_read(
2263        mut self: std::pin::Pin<&mut Self>,
2264        cx: &mut std::task::Context<'_>,
2265        buf: &mut tokio::io::ReadBuf<'_>,
2266    ) -> std::task::Poll<std::io::Result<()>> {
2267        let before = buf.filled().len();
2268        let polled = std::pin::Pin::new(&mut self.inner).poll_read(cx, buf);
2269        if polled.is_ready() {
2270            let read = buf.filled().len().saturating_sub(before);
2271            if read > 0 {
2272                self.charge(read);
2273            }
2274        }
2275        polled
2276    }
2277}
2278
2279impl<S: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for Metered<S> {
2280    fn poll_write(
2281        mut self: std::pin::Pin<&mut Self>,
2282        cx: &mut std::task::Context<'_>,
2283        buf: &[u8],
2284    ) -> std::task::Poll<std::io::Result<usize>> {
2285        let polled = std::pin::Pin::new(&mut self.inner).poll_write(cx, buf);
2286        if let std::task::Poll::Ready(Ok(written)) = &polled {
2287            let written = *written;
2288            if written > 0 {
2289                self.charge(written);
2290            }
2291        }
2292        polled
2293    }
2294
2295    fn poll_flush(
2296        mut self: std::pin::Pin<&mut Self>,
2297        cx: &mut std::task::Context<'_>,
2298    ) -> std::task::Poll<std::io::Result<()>> {
2299        std::pin::Pin::new(&mut self.inner).poll_flush(cx)
2300    }
2301
2302    fn poll_shutdown(
2303        mut self: std::pin::Pin<&mut Self>,
2304        cx: &mut std::task::Context<'_>,
2305    ) -> std::task::Poll<std::io::Result<()>> {
2306        std::pin::Pin::new(&mut self.inner).poll_shutdown(cx)
2307    }
2308}
2309
2310#[cfg(test)]
2311mod tests {
2312    use super::*;
2313
2314    /// **A keyed caller is QUEUED past the short wait; a stranger is not.**
2315    ///
2316    /// gunnar.rs, 2026-10-25: every lane pushes and fetches as one key, and
2317    /// git-lfs cannot retry a refused pure-SSH `git-lfs-transfer` — it falls
2318    /// back to `git-lfs-authenticate` and fails the whole push ("batch
2319    /// request: exec request failed"). So an authenticated identity waits for
2320    /// a slot up to the keyed wait (30 s on the appliance, under `exec_grace`'s
2321    /// 60 s), while anonymous keeps the short wait and its never-park rules.
2322    #[tokio::test]
2323    async fn a_keyed_caller_waits_out_the_keyed_bound_and_a_stranger_does_not() {
2324        let gate = Arc::new(
2325            Admission::new(Some(1), None)
2326                .with_wait(Duration::from_millis(50))
2327                .with_keyed_wait(Some(Duration::from_secs(5))),
2328        );
2329        assert_eq!(gate.wait_for("admin"), Duration::from_secs(5));
2330        assert_eq!(gate.wait_for(gunnar_core::ANONYMOUS_PRINCIPAL_ID), Duration::from_millis(50));
2331        let holder = gate.try_admit("other", "team", OpClass::Fetch).expect("the one slot");
2332
2333        // The slot frees after 400 ms: well past the short wait, inside the keyed one.
2334        let freer = tokio::spawn(async move {
2335            tokio::time::sleep(Duration::from_millis(400)).await;
2336            drop(holder);
2337        });
2338        let started = std::time::Instant::now();
2339        let (guard, waited) = gate
2340            .admit_within("admin", "team", OpClass::Fetch)
2341            .await
2342            .expect("a keyed caller is queued for the slot, not refused after 50 ms");
2343        assert!(waited >= Duration::from_millis(300), "it really waited: {waited:?}");
2344        assert!(started.elapsed() < Duration::from_secs(5));
2345        freer.await.unwrap();
2346
2347        // The slot is held again: a stranger is refused at the short bound.
2348        let started = std::time::Instant::now();
2349        gate.admit_within(gunnar_core::ANONYMOUS_PRINCIPAL_ID, "team", OpClass::Fetch)
2350            .await
2351            .expect_err("anonymous is never queued for the keyed bound");
2352        assert!(started.elapsed() < Duration::from_secs(1), "{:?}", started.elapsed());
2353        drop(guard);
2354
2355        // `--admission-wait-ms 0` still means "refuse on the spot" for everyone.
2356        let instant = Admission::new(Some(1), None).with_wait(Duration::ZERO).with_keyed_wait(Some(Duration::from_secs(30)));
2357        assert_eq!(instant.wait_for("admin"), Duration::ZERO);
2358        // No keyed bound configured: the keyed caller gets the ordinary wait.
2359        let plain = Admission::new(Some(1), None).with_wait(Duration::from_millis(50));
2360        assert_eq!(plain.wait_for("admin"), Duration::from_millis(50));
2361    }
2362
2363    /// **The drain's door** (`DATA-SET-GROWTH-FLOW.md` §3 step 5, T1/T12):
2364    /// a paused gate refuses every new transfer with the growing sentence,
2365    /// takes no slot, counts the refusal under its own counter, never parks
2366    /// the caller, and leaves what was already admitted in flight — which
2367    /// is the number the drain waits on. Unpaused, it admits again.
2368    #[tokio::test]
2369    async fn a_paused_gate_refuses_with_the_growing_words_and_keeps_in_flight_honest() {
2370        let gate = Arc::new(Admission::new(Some(4), None).with_wait(Duration::from_secs(5)));
2371        let running = gate
2372            .try_admit("one", "team", OpClass::Push)
2373            .expect("admitted before the pause");
2374        assert_eq!(gate.in_flight(), 1);
2375        assert_eq!(gate.paused(), None);
2376
2377        gate.pause(Pause::Growing);
2378        assert_eq!(gate.paused(), Some(Pause::Growing));
2379        let refused = gate
2380            .try_admit("two", "team", OpClass::Clone)
2381            .expect_err("paused: refused");
2382        assert_eq!(refused, Refusal::Paused { pause: Pause::Growing });
2383        assert_eq!(refused.client_message(), GROWING_MESSAGE);
2384        assert!(refused.client_message().contains("growing"), "the word is load-bearing");
2385        assert!(refused.client_message().contains("try again"));
2386        // ★ Every estate says it, not only gunnar.rs (the UpCloud mockup, 2026-10-09: test2's
2387        // pushes were told "gunnar.rs is growing its storage"): no estate's domain is spelled.
2388        assert!(!refused.client_message().contains("gunnar.rs"), "a test2 push was told gunnar.rs is growing: {}", refused.client_message());
2389        assert!(refused.client_message().starts_with("The server is growing its storage"), "{}", refused.client_message());
2390        assert_eq!(refused.reason(), "paused-growing");
2391        for other in ["concurrent git transfers", "per-principal limit", "unauthenticated"] {
2392            assert!(!refused.client_message().contains(other), "shares no substring with {other}");
2393        }
2394        // The waiting door does not park a paused caller: it answers at once.
2395        let started = std::time::Instant::now();
2396        let parked = gate
2397            .admit_within("three", "team", OpClass::Fetch)
2398            .await
2399            .expect_err("paused: refused, not parked");
2400        assert!(matches!(parked, Refusal::Paused { .. }));
2401        assert!(started.elapsed() < Duration::from_secs(1), "not parked for the wait");
2402        // Counted under its own counter, in the total, and no slot was taken.
2403        let stats = gate.stats();
2404        assert_eq!(stats.refused_paused, 2);
2405        assert_eq!(stats.refused(), 2);
2406        assert_eq!(stats.in_flight, 1, "the pre-pause transfer is still what is in flight");
2407        gate.pause(Pause::Growing);
2408        assert_eq!(gate.paused(), Some(Pause::Growing), "idempotent");
2409
2410        drop(running);
2411        assert_eq!(gate.in_flight(), 0, "the drain sees zero once the last one finishes");
2412        gate.unpause();
2413        gate.unpause();
2414        assert_eq!(gate.paused(), None);
2415        let _again = gate
2416            .try_admit("two", "team", OpClass::Clone)
2417            .expect("unpaused: admitted");
2418        assert_eq!(gate.in_flight(), 1);
2419    }
2420
2421    #[test]
2422    fn the_server_wide_limit_refuses_and_counts() {
2423        let gate = Arc::new(Admission::new(Some(2), None));
2424        let a = gate
2425            .try_admit("one", "team", OpClass::LsRemote)
2426            .expect("the first is admitted");
2427        let b = gate
2428            .try_admit("two", "team", OpClass::LsRemote)
2429            .expect("the second is admitted");
2430        let refused = gate
2431            .try_admit("three", "team", OpClass::LsRemote)
2432            .expect_err("the third is refused");
2433        assert_eq!(refused, Refusal::AtCapacity { limit: 2 });
2434
2435        let stats = gate.stats();
2436        assert_eq!(stats.admitted, 2, "two got in");
2437        assert_eq!(stats.refused_at_capacity, 1, "the refusal must be COUNTED");
2438        assert_eq!(stats.in_flight, 2);
2439        assert_eq!(stats.peak_in_flight, 2);
2440
2441        // …and the slot comes back, so this is a limit and not a budget.
2442        drop(a);
2443        assert_eq!(gate.stats().in_flight, 1);
2444        let c = gate
2445            .try_admit("three", "team", OpClass::LsRemote)
2446            .expect("a freed slot is reusable");
2447        assert_eq!(gate.stats().in_flight, 2);
2448        assert_eq!(
2449            gate.stats().peak_in_flight,
2450            2,
2451            "the peak is a high-water mark, not the current value"
2452        );
2453        drop((b, c));
2454        assert_eq!(gate.stats().in_flight, 0);
2455    }
2456
2457    /// **Direction A of the max-min bar.** A single principal must be able to
2458    /// reach the *server-wide* limit on an otherwise idle server.
2459    ///
2460    /// This is the bug, at the shipped ratio. Before the fix the per-principal
2461    /// number was a wall, so this run stopped at 32 with the rest of the server
2462    /// free, and the whole limit needed eight identities to reach.
2463    ///
2464    /// # What the governor changed here, and what it did not
2465    ///
2466    /// The number a lone principal can reach is now the **governed** limit —
2467    /// the top of [`LimitBand::for_ceiling`] of the configured ceiling — and not
2468    /// the configured ceiling itself. With the shipped
2469    /// `DEFAULT_MAX_CONCURRENT_TRANSFERS` of 256 that is
2470    /// [`MAX_LIMIT`](crate::governor::MAX_LIMIT), 100: 256 concurrent git
2471    /// transfers is the sort of number the governor exists to stop a server
2472    /// from believing about itself.
2473    ///
2474    /// The property under test is unchanged and is still the one that matters:
2475    /// **the per-principal number is a floor, not a wall**, so one identity on
2476    /// an idle server reaches the whole of whatever the server-wide limit
2477    /// currently is. It is asserted against `governed` rather than a literal so
2478    /// it cannot drift away from the band.
2479    #[test]
2480    fn one_principal_alone_reaches_the_server_wide_limit() {
2481        use crate::config::{
2482            DEFAULT_MAX_CONCURRENT_TRANSFERS as CONFIGURED,
2483            DEFAULT_MAX_TRANSFERS_PER_PRINCIPAL as FLOOR,
2484        };
2485        let gate = Arc::new(Admission::new(Some(CONFIGURED), Some(FLOOR)));
2486        let governed = gate.governed_limit().expect("a governed limit");
2487        // The top of the band is the CONFIGURED ceiling, not the design's
2488        // default. This assertion read `MAX_LIMIT` while the band was capped at
2489        // 100, which made a server told 256 serve 100 and called it correct —
2490        // the test agreed with the bug because both had the same number in them.
2491        assert_eq!(
2492            governed, CONFIGURED,
2493            "a fresh governor starts at the top of its band, and the top is what \
2494             the operator configured"
2495        );
2496        assert!(
2497            governed > FLOOR,
2498            "a test where the governed limit is not above the per-principal floor cannot tell a \
2499             floor from a wall"
2500        );
2501
2502        let held: Vec<_> = (0..governed)
2503            .map(|i| {
2504                gate.try_admit("solo", "team", OpClass::LsRemote)
2505                    .unwrap_or_else(|refusal| {
2506                        panic!(
2507                            "transfer {i} of {governed} was refused on an EMPTY server holding \
2508                             one identity: {refusal}. The per-principal number is a floor, not a \
2509                             wall; a single-key client that stops at {FLOOR} is the old invisible ceiling, back"
2510                        )
2511                    })
2512            })
2513            .collect();
2514        assert_eq!(held.len(), governed);
2515
2516        let stats = gate.stats();
2517        assert_eq!(
2518            stats.admitted, governed as u64,
2519            "the server-wide limit in force must be reachable by ONE identity"
2520        );
2521        assert_eq!(
2522            stats.refused_per_principal, 0,
2523            "not one of these {governed} may be refused for fairness: there was nobody to be \
2524             fair to"
2525        );
2526        assert_eq!(stats.peak_in_flight, governed as u64);
2527        assert_eq!(stats.limit, governed, "the stats must report what refuses");
2528
2529        // …and the server-wide gate is still a gate. Without this the test
2530        // above would also pass on an Admission that had lost both limits.
2531        let full = gate
2532            .try_admit("solo", "team", OpClass::LsRemote)
2533            .expect_err("one past the governed limit");
2534        assert_eq!(full, Refusal::AtCapacity { limit: governed });
2535        drop(held);
2536    }
2537
2538    /// **Direction B of the max-min bar.** Once the server IS contended, a
2539    /// greedy principal is held to its share and a quiet one is still served.
2540    ///
2541    /// `(4, 1)` so the contention threshold (75 % → 3 of 4) is reachable in a
2542    /// handful of admissions, and so the share (`4 / 2 = 2`) is strictly above
2543    /// the configured floor of 1 — a share equal to the floor could not tell
2544    /// max-min fairness from the old wall.
2545    #[test]
2546    fn a_greedy_principal_is_held_to_its_share_once_the_server_is_contended() {
2547        let gate = Arc::new(Admission::new(Some(4), Some(1)));
2548
2549        // The quiet one arrives first, so it is *active* and has a claim.
2550        let _polite = gate
2551            .try_admit("polite", "team", OpClass::LsRemote)
2552            .expect("polite's first");
2553        // Greedy takes its share: 4 slots / 2 identities = 2.
2554        let _g1 = gate
2555            .try_admit("greedy", "team", OpClass::LsRemote)
2556            .expect("greedy's first");
2557        let _g2 = gate
2558            .try_admit("greedy", "team", OpClass::LsRemote)
2559            .expect("greedy's second is still its share");
2560
2561        // Three of four are held, so the server is over the 75 % threshold and
2562        // fairness is in force. Greedy has its two.
2563        let refused = gate
2564            .try_admit("greedy", "team", OpClass::LsRemote)
2565            .expect_err("greedy's third is past its share of a contended server");
2566        assert_eq!(
2567            refused,
2568            Refusal::PrincipalAtCapacity {
2569                limit: 2,
2570                active_principals: 2
2571            },
2572            "the refusal must name the SHARE in force (4/2), not the configured floor (1), or an \
2573             operator reads a number that matches nothing they set"
2574        );
2575        assert!(
2576            refused.client_message().contains("per-principal limit"),
2577            "installtest's `refusals_in_log` tells the two refusals apart by this exact phrase; \
2578             losing it silently zeroes the server-side witness: {}",
2579            refused.client_message()
2580        );
2581
2582        // The whole reason fairness exists: the fourth slot was NOT taken by
2583        // greedy, and it is there for somebody else.
2584        let _other = gate
2585            .try_admit("polite", "team", OpClass::LsRemote)
2586            .expect("the slot greedy was refused must be available to the quiet principal");
2587
2588        let stats = gate.stats();
2589        assert_eq!(stats.refused_per_principal, 1);
2590        assert_eq!(
2591            stats.refused_at_capacity, 0,
2592            "the server had a free slot; attributing this to capacity sends an operator to raise \
2593             the wrong number"
2594        );
2595        assert_eq!(stats.in_flight, 4);
2596    }
2597
2598    /// The share is *work-conserving*: two identities on a server that is
2599    /// nowhere near full do not each get half of it.
2600    ///
2601    /// Without the contention threshold this is what max-min fairness costs —
2602    /// a busy principal capped at `server_wide / active` while most of the box
2603    /// sits idle, which is the same "binds when there is nobody to be fair to"
2604    /// mistake in a smaller costume.
2605    #[test]
2606    fn fairness_does_not_bind_while_there_are_free_slots() {
2607        let gate = Arc::new(Admission::new(Some(100), Some(1)));
2608        let _quiet = gate
2609            .try_admit("quiet", "team", OpClass::LsRemote)
2610            .expect("one transfer from a quiet identity");
2611
2612        // An equal share of 100 between 2 identities is 50. The server is only
2613        // going to 74 % full, so the share must not be enforced at all.
2614        let busy: Vec<_> = (0..73)
2615            .map(|i| {
2616                gate.try_admit("busy", "team", OpClass::LsRemote)
2617                    .unwrap_or_else(|r| panic!("transfer {i} refused at {}% full: {r}", i + 2))
2618            })
2619            .collect();
2620        assert_eq!(
2621            busy.len(),
2622            73,
2623            "74 of 100 held, so nothing may be refused yet"
2624        );
2625        assert_eq!(gate.stats().refused_per_principal, 0);
2626
2627        // The very next one crosses the threshold — 75 of 100 occupied — and
2628        // the share engages at once: 100/2 = 50, and `busy` is already at 73.
2629        let refused = gate.try_admit("busy", "team", OpClass::LsRemote).expect_err(
2630            "the transfer that makes the server 75% full is the first one weighed \
2631                         against the share",
2632        );
2633        assert_eq!(
2634            refused,
2635            Refusal::PrincipalAtCapacity {
2636                limit: 50,
2637                active_principals: 2
2638            }
2639        );
2640    }
2641
2642    /// The pinned mode: an operator who wants the old wall still has it.
2643    #[test]
2644    fn a_hard_cap_binds_on_an_empty_server() {
2645        let fair = Arc::new(Admission::new(Some(64), Some(2)));
2646        let _a = fair.try_admit("solo", "team", OpClass::LsRemote).expect("first");
2647        let _b = fair.try_admit("solo", "team", OpClass::LsRemote).expect("second");
2648        fair.try_admit("solo", "team", OpClass::LsRemote)
2649            .expect("a fair gate lets a lone principal past its floor on an idle server");
2650
2651        let hard = Arc::new(Admission::hard_capped(Some(64), Some(2)));
2652        let _c = hard.try_admit("solo", "team", OpClass::LsRemote).expect("first");
2653        let _d = hard.try_admit("solo", "team", OpClass::LsRemote).expect("second");
2654        let refused = hard
2655            .try_admit("solo", "team", OpClass::LsRemote)
2656            .expect_err("a pinned cap binds whether or not anyone else is there");
2657        assert_eq!(
2658            refused,
2659            Refusal::PrincipalAtCapacity {
2660                limit: 2,
2661                active_principals: 1
2662            }
2663        );
2664        assert!(
2665            !refused.client_message().contains("fair share"),
2666            "a pinned cap is not a share and must not be explained as one: {}",
2667            refused.client_message()
2668        );
2669        assert_eq!(hard.stats().refused_per_principal, 1);
2670        assert_eq!(fair.stats().refused_per_principal, 0);
2671    }
2672
2673    #[test]
2674    fn a_refused_transfer_does_not_leak_a_server_wide_slot() {
2675        // The subtle one: the server-wide permit is taken BEFORE the
2676        // per-principal check, so a per-principal refusal must give it back. If
2677        // it did not, a client hammering its own limit would drain the server.
2678        //
2679        // Driven through the *fair* path rather than a hard cap, because that
2680        // is what ships: `polite` first so the server is contended and greedy's
2681        // share (4/2 = 2) is what it hammers.
2682        let gate = Arc::new(Admission::new(Some(4), Some(1)));
2683        let _polite = gate
2684            .try_admit("polite", "team", OpClass::LsRemote)
2685            .expect("polite is active");
2686        let _g1 = gate
2687            .try_admit("greedy", "team", OpClass::LsRemote)
2688            .expect("greedy's share is 2");
2689        let _g2 = gate
2690            .try_admit("greedy", "team", OpClass::LsRemote)
2691            .expect("greedy's share is 2");
2692        for _ in 0..100 {
2693            gate.try_admit("greedy", "team", OpClass::LsRemote)
2694                .expect_err("refused every time");
2695        }
2696        // Three slots are held; the fourth must still be free for anybody at all.
2697        let _other = gate
2698            .try_admit("somebody-else", "team", OpClass::LsRemote)
2699            .expect("the fourth slot survived 100 refusals");
2700        assert_eq!(gate.stats().in_flight, 4);
2701        assert_eq!(gate.stats().refused_per_principal, 100);
2702    }
2703
2704    /// A principal that finishes its work must give its share back to the
2705    /// others, or the map's length — the divisor of every share — is a
2706    /// high-water mark rather than a live count.
2707    #[test]
2708    fn a_departed_principal_stops_shrinking_everybody_elses_share() {
2709        let gate = Arc::new(Admission::new(Some(4), Some(1)));
2710        let leaving = gate
2711            .try_admit("leaving", "team", OpClass::LsRemote)
2712            .expect("two identities are active");
2713        let _g1 = gate.try_admit("stayer", "team", OpClass::LsRemote).expect("first");
2714        let _g2 = gate
2715            .try_admit("stayer", "team", OpClass::LsRemote)
2716            .expect("share of 2 with 2 active");
2717        gate.try_admit("stayer", "team", OpClass::LsRemote)
2718            .expect_err("held to 2 while `leaving` is still there");
2719
2720        drop(leaving);
2721        // Now one identity is active, so the share is the whole server again.
2722        let _g3 = gate
2723            .try_admit("stayer", "team", OpClass::LsRemote)
2724            .expect("with the other identity gone the share must widen back out");
2725        let _g4 = gate
2726            .try_admit("stayer", "team", OpClass::LsRemote)
2727            .expect("all four slots are reachable by the only identity left");
2728        assert_eq!(gate.stats().in_flight, 4);
2729    }
2730
2731    #[test]
2732    fn the_map_does_not_grow_with_every_principal_ever_seen() {
2733        let gate = Arc::new(Admission::new(Some(4), Some(1)));
2734        for i in 0..500 {
2735            let guard = gate
2736                .try_admit(&format!("principal-{i}"), "team", OpClass::LsRemote)
2737                .expect("admitted");
2738            drop(guard);
2739        }
2740        // Read through the gate's own lock rather than a counter, because the
2741        // thing being asserted is that the MAP is empty; a counter could agree
2742        // while the map leaked.
2743        let held = gate.per_principal.lock().expect("the per-principal map");
2744        assert!(
2745            held.is_empty(),
2746            "the per-principal map kept {} entries for principals with nothing in flight",
2747            held.len()
2748        );
2749    }
2750
2751    /// The three refusals must stay **tellable apart by their words**, because
2752    /// that is how the only cross-process witness of them counts.
2753    ///
2754    /// `installtest`'s `refusals_in_log` reads the server log and sorts
2755    /// refusals by the substrings `"concurrent git transfers"` and
2756    /// `"per-principal limit"` — the log records a refusal by its `Display`,
2757    /// which is the same sentence the client is handed. A third reason that
2758    /// collided with either phrase would be silently counted as the wrong one,
2759    /// and an operator would raise the wrong number: the concurrency limit,
2760    /// when the thing that ran out was memory.
2761    ///
2762    /// # Seen red
2763    ///
2764    /// By giving `Refusal::MemoryBudget` the natural wording, "the server is
2765    /// already serving its limit of N concurrent git transfers within its
2766    /// memory budget". Failure:
2767    ///
2768    /// ```text
2769    /// the memory refusal contains "concurrent git transfers", which
2770    /// installtest counts as a CAPACITY refusal; an operator reading that
2771    /// raises the concurrency limit and makes the memory problem worse
2772    /// ```
2773    #[test]
2774    fn the_three_refusals_do_not_borrow_each_others_words() {
2775        let capacity = Refusal::AtCapacity { limit: 37 }.client_message();
2776        let principal = Refusal::PrincipalAtCapacity {
2777            limit: 4,
2778            active_principals: 3,
2779        }
2780        .client_message();
2781        let memory = Refusal::MemoryBudget {
2782            class: OpClass::Clone,
2783            wanted: 2048 * 1024 * 1024,
2784            reserved: 6144 * 1024 * 1024,
2785            budget: 8192 * 1024 * 1024,
2786        }
2787        .client_message();
2788
2789        assert!(capacity.contains("concurrent git transfers"));
2790        assert!(!capacity.contains("per-principal limit"));
2791        assert!(principal.contains("per-principal limit"));
2792        assert!(!principal.contains("concurrent git transfers"));
2793
2794        assert!(
2795            !memory.contains("concurrent git transfers"),
2796            "the memory refusal contains \"concurrent git transfers\", which installtest counts \
2797             as a CAPACITY refusal; an operator reading that raises the concurrency limit and \
2798             makes the memory problem worse: {memory}"
2799        );
2800        assert!(
2801            !memory.contains("per-principal limit"),
2802            "the memory refusal contains \"per-principal limit\", so installtest counts a \
2803             server-wide memory exhaustion as one identity's fairness throttle: {memory}"
2804        );
2805        assert!(
2806            memory.contains("memory budget"),
2807            "the memory refusal must name the knob to turn: {memory}"
2808        );
2809        // All three are transient and every one of them must say so, or a CI
2810        // log reads a busy server as a broken one.
2811        for message in [&capacity, &principal, &memory] {
2812            assert!(
2813                message.contains("try again"),
2814                "a transient refusal that does not say `try again` reads as permanent: {message}"
2815            );
2816        }
2817    }
2818
2819    /// The work an operation would do, if it were admitted.
2820    ///
2821    /// Deliberately something with an **observable cost**: it allocates, and it
2822    /// records that it allocated. "No work was performed" asserted against a
2823    /// bool nobody sets is a hollow guard; asserted against a
2824    /// byte count that a real `Vec` really pushed into is not.
2825    #[derive(Default)]
2826    struct Work {
2827        runs: AtomicU64,
2828        bytes_allocated: AtomicU64,
2829    }
2830
2831    impl Work {
2832        /// One operation's buffer. A clone's real one is proportional to the
2833        /// pack; this stands in for it at a size a test can afford.
2834        fn perform(&self) -> Vec<u8> {
2835            let buffer = vec![0u8; 1024 * 1024];
2836            self.runs.fetch_add(1, Ordering::Relaxed);
2837            self.bytes_allocated
2838                .fetch_add(buffer.len() as u64, Ordering::Relaxed);
2839            buffer
2840        }
2841
2842        fn runs(&self) -> u64 {
2843            self.runs.load(Ordering::Relaxed)
2844        }
2845
2846        fn bytes(&self) -> u64 {
2847            self.bytes_allocated.load(Ordering::Relaxed)
2848        }
2849    }
2850
2851    /// **A denial happens AT admission, and nothing the operation would have
2852    /// done gets done.**
2853    ///
2854    /// This is the entire value of the gate. A refusal that arrives after the
2855    /// buffer has been built is not load shedding, it is a slower way of paying
2856    /// the same cost — and for the clone class that cost is gigabytes
2857    /// (2314 MB peak RSS, measured 2026-08-13).
2858    ///
2859    /// Both gates are driven, because they refuse on different paths and each
2860    /// could grow a bug the other's test would not see.
2861    ///
2862    /// # Seen red
2863    ///
2864    /// By moving `Work::perform` above the `try_admit` in the loop below, which
2865    /// is precisely the mistake a real caller makes when it opens the pack
2866    /// before asking whether it may. Failure:
2867    ///
2868    /// ```text
2869    /// 30 operations were refused, but the work ran 40 times and allocated
2870    /// 41943040 bytes. A refusal after the allocation is not load shedding
2871    /// ```
2872    #[test]
2873    fn a_denial_is_paid_for_by_nobody() {
2874        // Gate 1: the concurrency limit. A pinned band of 10, so the refusals
2875        // are the governor's and not the memory ledger's.
2876        let gate = Arc::new(Admission::new(Some(10), None));
2877        let work = Work::default();
2878        let mut held = Vec::new();
2879        let mut refused = 0;
2880        for _ in 0..40 {
2881            match gate.try_admit("solo", "team", OpClass::LsRemote) {
2882                Ok(guard) => held.push((guard, work.perform())),
2883                Err(_) => refused += 1,
2884            }
2885        }
2886        assert_eq!(refused, 30, "10 of 40 fit under the limit");
2887        assert_eq!(
2888            work.runs(),
2889            10,
2890            "{refused} operations were refused, but the work ran {} times and allocated {} \
2891             bytes. A refusal after the allocation is not load shedding",
2892            work.runs(),
2893            work.bytes()
2894        );
2895        assert_eq!(work.bytes(), 10 * 1024 * 1024);
2896
2897        // Gate 2: the memory budget. Four clones' worth, and eight arrivals.
2898        let clone = OpClass::Clone.admission_bytes();
2899        let gate = Arc::new(Admission::new(None, None).with_budget(clone * 4));
2900        assert!(
2901            gate.memory_budget().is_none(),
2902            "an unlimited concurrency gate has no budget to attach one to; the memory gate must \
2903             ride on the same governor or a configuration could get one without the other"
2904        );
2905
2906        let gate = Arc::new(Admission::with_memory_budget(Some(100), None, clone * 4));
2907        let work = Work::default();
2908        let mut held = Vec::new();
2909        let mut refused = Vec::new();
2910        for _ in 0..8 {
2911            match gate.try_admit("solo", "team", OpClass::Clone) {
2912                Ok(guard) => held.push((guard, work.perform())),
2913                Err(refusal) => refused.push(refusal),
2914            }
2915        }
2916        assert_eq!(work.runs(), 4, "a 4-clone budget admits 4 clones");
2917        assert_eq!(
2918            work.bytes(),
2919            4 * 1024 * 1024,
2920            "the 4 refused clones allocated {} bytes between them, which is 4 more than a \
2921             refusal at admission can possibly cost",
2922            work.bytes() - 4 * 1024 * 1024
2923        );
2924        assert_eq!(refused.len(), 4);
2925        assert!(
2926            refused.iter().all(|r| matches!(
2927                r,
2928                Refusal::MemoryBudget {
2929                    class: OpClass::Clone,
2930                    ..
2931                }
2932            )),
2933            "the refusals must name MEMORY, or an operator raises the concurrency limit and \
2934             makes it worse: {refused:?}"
2935        );
2936        let stats = gate.stats();
2937        assert_eq!(stats.refused_memory, 4);
2938        assert_eq!(
2939            stats.refused_at_capacity, 0,
2940            "the limit was 100 and 4 were held"
2941        );
2942        assert_eq!(stats.reserved_bytes, clone * 4);
2943    }
2944
2945    /// **An operation that ERRORS — or panics — still releases both its slot
2946    /// and its reservation.**
2947    ///
2948    /// Leak this and the server wedges after N failures: a budget that only
2949    /// comes back on the happy path is a budget that drains to zero the first
2950    /// time a client hangs up mid-clone, which is the single most ordinary
2951    /// thing a git client does.
2952    ///
2953    /// # Seen red
2954    ///
2955    /// By making `AdmissionGuard::drop` release only on the success path —
2956    /// `if !std::thread::panicking() { … }` around the governor release, which
2957    /// is exactly how a hand-written release-on-completion would behave.
2958    /// Failure:
2959    ///
2960    /// ```text
2961    /// 6 operations ended in an error or a panic and 6442450944 bytes are still
2962    /// reserved of 8589934592; the 7th would be refused, so the server has
2963    /// wedged
2964    /// ```
2965    ///
2966    /// Three panics, 2 GiB each: three quarters of the whole budget gone to
2967    /// operations that no longer exist.
2968    #[test]
2969    fn an_operation_that_fails_still_gives_its_reservation_back() {
2970        let clone = OpClass::Clone.admission_bytes();
2971        let gate = Arc::new(Admission::with_memory_budget(Some(100), None, clone * 4));
2972
2973        for _ in 0..3 {
2974            // The error path: a guard that goes out of scope through `?`-style
2975            // early return rather than through completion.
2976            let outcome: Result<(), &str> = (|| {
2977                let _guard = gate
2978                    .try_admit("solo", "team", OpClass::Clone)
2979                    .map_err(|_| "refused")?;
2980                Err("the transport died mid-pack")
2981            })();
2982            assert!(outcome.is_err());
2983        }
2984        for _ in 0..3 {
2985            // The panic path, which no explicit release call survives.
2986            let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2987                let _guard = gate
2988                    .try_admit("solo", "team", OpClass::Clone)
2989                    .expect("admitted before the panic");
2990                panic!("the pack walk blew up");
2991            }));
2992            assert!(panicked.is_err());
2993        }
2994
2995        let stats = gate.stats();
2996        assert_eq!(
2997            stats.reserved_bytes,
2998            0,
2999            "6 operations ended in an error or a panic and {} bytes are still reserved of {}; \
3000             the 7th would be refused, so the server has wedged",
3001            stats.reserved_bytes,
3002            gate.memory_budget().unwrap_or(0)
3003        );
3004        assert_eq!(stats.in_flight, 0);
3005        assert_eq!(
3006            gate.governor().expect("a governor").occupied(),
3007            0,
3008            "the concurrency slots leaked even though the reservations did not"
3009        );
3010
3011        // The applied output: the budget is genuinely reusable, four times over.
3012        let held: Vec<_> = (0..4)
3013            .map(|i| {
3014                gate.try_admit("solo", "team", OpClass::Clone)
3015                    .unwrap_or_else(|r| panic!("clone {i} after 6 failures was refused: {r}"))
3016            })
3017            .collect();
3018        assert_eq!(held.len(), 4);
3019    }
3020
3021    /// A transfer that never reports entering service is COUNTED, not guessed
3022    /// at.
3023    ///
3024    /// The controller only sees what [`AdmissionGuard::entered_service`] files.
3025    /// A caller that forgets leaves it with no samples, and a CoDel controller
3026    /// with no samples sits at the top of its band forever — a gate that looks
3027    /// like it works and does not. This is the counter that makes that visible,
3028    /// and `tests/admission.rs` is where the real SSH path is held to zero.
3029    ///
3030    /// # Seen red
3031    ///
3032    /// By making `AdmissionGuard::drop` increment the counter unconditionally
3033    /// instead of only when the mark was never claimed. Failure:
3034    ///
3035    /// ```text
3036    /// assertion `left == right` failed: a transfer that DID report entering
3037    /// service was counted as unmeasured: 2
3038    ///   left: 2
3039    ///  right: 1
3040    /// ```
3041    #[test]
3042    fn a_transfer_that_never_enters_service_is_counted_as_unmeasured() {
3043        let gate = Arc::new(Admission::new(Some(100), None));
3044
3045        drop(gate.try_admit("solo", "team", OpClass::LsRemote).expect("admitted"));
3046        assert_eq!(
3047            gate.stats().unmeasured_sojourn,
3048            1,
3049            "a transfer that never said its work started filed no sojourn sample and must be \
3050             counted; a controller starved of samples grows to its ceiling and stays there"
3051        );
3052
3053        let guard = gate.try_admit("solo", "team", OpClass::LsRemote).expect("admitted");
3054        guard.entered_service();
3055        drop(guard);
3056        assert_eq!(
3057            gate.stats().unmeasured_sojourn,
3058            1,
3059            "a transfer that DID report entering service was counted as unmeasured: {}",
3060            gate.stats().unmeasured_sojourn
3061        );
3062
3063        // …and the sample really reached the controller's window, rather than
3064        // merely flipping a flag. One sample opens a window; nothing has closed
3065        // one yet, so the limit has not moved and the class's window is live.
3066        let governor = gate.governor().expect("a governor");
3067        assert_eq!(governor.codel().shrinks() + governor.codel().grows(), 0);
3068        let guard = gate.try_admit("solo", "team", OpClass::LsRemote).expect("admitted");
3069        guard.entered_service();
3070        drop(guard);
3071        assert_eq!(
3072            gate.stats().unmeasured_sojourn,
3073            1,
3074            "the one-shot mark must not turn a second measured transfer into an unmeasured one"
3075        );
3076    }
3077
3078    #[test]
3079    fn an_unlimited_gate_admits_everything_and_still_counts() {
3080        let gate = Arc::new(Admission::unlimited());
3081        let mut held = Vec::new();
3082        for _ in 0..1000 {
3083            held.push(
3084                gate.try_admit("anyone", "team", OpClass::LsRemote)
3085                    .expect("no limit means no refusal"),
3086            );
3087        }
3088        let stats = gate.stats();
3089        assert_eq!(stats.admitted, 1000);
3090        assert_eq!(stats.refused(), 0);
3091        assert_eq!(stats.in_flight, 1000);
3092        assert_eq!(stats.peak_in_flight, 1000);
3093    }
3094}