Skip to main content

moq_net/model/
cache.rs

1//! A shared byte budget for cached groups, repaid by write-time eviction.
2//!
3//! Every group charges its cached bytes into a [`Pool`] through a crate-internal
4//! `Charge`, billed to its track's `Track` account. The pool itself never evicts: it is
5//! a handful of atomic counters. While the pool is over capacity, each track accrues
6//! eviction debt as it writes (`accrue`),
7//! sized proportionally to what it wrote, and pays that debt by aborting its own oldest
8//! groups with [`Error::Evicted`](crate::Error::Evicted). Reclamation is therefore
9//! distributed across every writing track and converges on the capacity without any
10//! global eviction task. A capacity below what the pool pins (each live track's newest
11//! group) converges on the pins instead: nothing owes debt for bytes no eviction can free.
12//!
13//! Cross-track ordering comes from one statistic: the mean last-access time of the
14//! evictable population (every cached group except each live track's protected latest).
15//! A group accessed more recently than that mean is never evicted, so freshly read
16//! or fetched content in one track can't die while another track holds staler
17//! content, and a track
18//! whose oldest group is staler than the mean accrues debt at double rate. Evicting
19//! old entries and inserting new ones both advance the mean, so the eviction
20//! frontier moves with cache turnover on its own.
21//!
22//! The pool also owns the wall-clock LRU window ([`Pool::expiry`]): a group that
23//! nobody has read or written for that long is reclaimed, no matter what retention
24//! its track advertises. Only a live track's latest group is exempt: once a track
25//! ends, a stale consumer can't pin any of it. Track retention
26//! ([`max_age`](crate::track::Info::max_age)) decides which groups readers skip as
27//! stale; the pool's expiry is the orthogonal bound that frees the bytes of content
28//! nobody touches.
29//!
30//! Expiry is driven by [`Pool::poll`], also called by each origin driver.
31//! Reads and writes clear the expiration timestamp without reading a clock.
32//! The next cleanup pass dates that activity at its supplied instant. Delayed
33//! cleanup extends retention; standalone pools must call `poll` too.
34//! Byte-pressure eviction still runs inline on writes.
35//!
36//! The pool never evicts a live track's latest group, so a session's live-edge budget
37//! (`session::Limits::live_edges`) bounds what those hold in bytes: every track a session
38//! ingests bills its live edge there, and a session past its budget pays with its own
39//! live edges in delivery's priority order, never another session's.
40//!
41//! A bare pool is inert by default ([`Pool::unbounded`]): publishers and subscribers
42//! that never set a capacity or expiry pay only a couple of atomic counters, and
43//! register nothing. A standalone [`origin`](crate::origin::Config) enables
44//! [`DEFAULT_EXPIRY`], while a relay creates one configured pool and shares it across
45//! every origin so the whole process caches into a single policy.
46
47use crate::util::SendCell;
48use std::collections::BTreeMap;
49use std::ops::Bound;
50use std::sync::Mutex;
51use std::sync::atomic::{AtomicBool, AtomicI8, AtomicI64, AtomicU64, AtomicUsize, Ordering};
52use std::sync::{Arc, OnceLock, PoisonError, Weak};
53use std::task::{Poll, ready};
54use std::time::Duration;
55
56use super::track::{self, Position, TrackState};
57use super::{aborts, expiry, flate, group};
58
59/// Fixed bookkeeping charged per cached group on top of its frame payload bytes.
60///
61/// A group that holds one small frame is almost entirely bookkeeping: the kio channel
62/// carrying its state, the containers the track indexes it by, and the frame slots
63/// themselves dwarf a chat-sized payload. Billing payload alone lets such a track cache
64/// millions of groups while the pool believes it is inside budget, so the process is
65/// killed before anything is evicted.
66///
67/// Derived from `size_of` rather than pasted from a measured process, so it follows the
68/// structs instead of rotting: each half lives beside the types it sizes, in
69/// [`group::CACHE_OVERHEAD`] and [`track::CACHE_OVERHEAD`]. It excludes allocator rounding. Frame-slot growth past the initial capacity is
70/// charged separately as each group grows.
71///
72/// Also bounds the live group count (`used / ENTRY_OVERHEAD`), which keeps the
73/// access-time sum below u64 (see [`TICK_MS`]).
74pub(super) const ENTRY_OVERHEAD: u64 = group::CACHE_OVERHEAD + track::CACHE_OVERHEAD;
75
76/// Sub-tick boosts applied to the last-access stamp, breaking ties within one
77/// coarse tick: a frame write outranks merely-inserted content, and a read (a
78/// delivered or fetched group, a frame read, a backfill's birth) outranks both.
79const WRITE_BOOST: u64 = 1;
80const READ_BOOST: u64 = 2;
81const ACCESS_SHIFT: u32 = 2;
82
83/// Milliseconds per tick of the coarse clock behind access timestamps.
84///
85/// Coarse ticks keep the count-weighted timestamp sum far from u64 overflow: the
86/// sum is bounded by `elapsed_ticks * live_groups`, plus two low tie-breaking
87/// bits. Live groups are bounded by `used / ENTRY_OVERHEAD`, and twenty years of
88/// ticks (6.3e9) times a 64 GiB target's worst case of ~70M groups is ~1.8e18 after
89/// that encoding, a tenth of `u64::MAX`. A byte-weighted mean would overflow u64
90/// even at whole-second ticks, which is why the mean is count-weighted.
91const TICK_MS: u64 = 100;
92
93/// Default idle window for standalone origins and relays.
94pub const DEFAULT_EXPIRY: Duration = Duration::from_secs(30);
95
96/// The initial policy for a [`Pool`].
97///
98/// The default is inert: no byte target and no idle expiry. Use
99/// [`Self::with_capacity`] and [`Self::with_expiry`] before creating the pool.
100#[derive(Clone, Debug, Default)]
101pub struct Config {
102	capacity: Option<u64>,
103	expiry: Option<Duration>,
104}
105
106impl Config {
107	/// Set the initial byte target. `None` leaves it unbounded.
108	pub fn with_capacity(mut self, capacity: impl Into<Option<u64>>) -> Self {
109		self.capacity = capacity.into();
110		self
111	}
112
113	/// Set the wall-clock LRU window. `None` disables idle reclamation.
114	///
115	/// A cached group (other than a live track's latest) that nobody reads or writes
116	/// for this long is reclaimed, surfacing to any remaining reader as
117	/// [`Error::Old`](crate::Error::Old). This is independent of track retention:
118	/// [`max_age`](crate::track::Info::max_age) decides what readers skip, while this
119	/// window keeps idle content from pinning memory. Reclaiming without a write behind
120	/// it needs [`Pool::poll`] called periodically (origins do this automatically).
121	/// The value is fixed when the
122	/// pool is created. Values are rounded up to the pool's 100 ms clock tick, with
123	/// 100 ms as the minimum effective window.
124	pub fn with_expiry(mut self, expiry: impl Into<Option<Duration>>) -> Self {
125		self.expiry = expiry.into();
126		self
127	}
128}
129
130/// A shared cache policy and byte budget; cloning shares both.
131///
132/// The pool tracks how many payload bytes are cached across every registered group,
133/// plus the mean last-access time of the evictable groups. It never
134/// evicts on its own: tracks accrue eviction debt as they write and evict their own
135/// oldest groups to pay it. Idle expiration runs during [`Self::poll`]. The capacity is
136/// therefore a target usage converges toward, not a hard limit: carried debt, capped
137/// payments, and the always-protected live edge all let usage transiently exceed it.
138#[derive(Clone)]
139pub struct Pool {
140	// Every track and handoff registry reaches back into group state, so the cell
141	// proves `Send` once here instead of inside every origin and broadcast handle.
142	inner: Arc<SendCell<Inner>>,
143}
144
145impl Default for Pool {
146	fn default() -> Self {
147		Self::unbounded()
148	}
149}
150
151struct Inner {
152	// Total bytes currently charged, including per-entry overhead.
153	used: AtomicU64,
154	// u64::MAX means unbounded.
155	capacity: AtomicU64,
156	// The part of `used` no eviction can reclaim while its track lives: each track's live
157	// edge (see [`Footprint`]) and spare encoder. Signed: a footprint that flips while one of its bytes is
158	// mid-update pins it an instant early or late, which may dip this below zero.
159	pinned: AtomicI64,
160	// The part of `used` fills hold for their readers, apart from `pinned`: only spared while
161	// it fits the capacity beside the pins (see [`Pool::holds_fit`]). Signed as `pinned` is.
162	fill_held: AtomicI64,
163	// The part of `used` readers' records and tails bill.
164	recorded: AtomicU64,
165	// Wall-clock LRU window in milliseconds; u64::MAX means never expire by idleness.
166	expiry: u64,
167	// Reference point for the coarse tick clock.
168	clock: Mutex<Option<Clock>>,
169	tick: AtomicU64,
170	// Sum and count of last-access ticks across the evictable population, giving a
171	// count-weighted mean. Tracks add a group when it becomes evictable (demoted
172	// from the live edge, or inserted behind it) and remove it when it leaves.
173	access_sum: AtomicU64,
174	access_count: AtomicU64,
175	// Live track accounts, so [`Pool::sweep`] can expire idle groups in a track that
176	// has stopped writing. Empty and never touched when expiry is disabled: the byte
177	// budget needs no registry, since a track that never writes never grows the pool.
178	// Weak, because a track owns its account and the account must not outlive it.
179	tracks: kio::Lock<slab::Slab<Weak<Track>>>,
180	// The first instant a driver supplied, and the latest as micros past it, so reading
181	// the wall clock never runs behind the time the drivers keep; see [`Pool::now_wall`].
182	// Unset until a driver collects, which is also what arms wall-clock deadlines.
183	wall_epoch: OnceLock<crate::time::Instant>,
184	wall_micros: AtomicU64,
185	// Tracks with reads parked on a wall-clock deadline, by their earliest one.
186	wall: kio::Lock<WallDeadlines>,
187	// Hand-offs holding a failed group's head for a successor route, oldest first. The
188	// heads sit outside every track's eviction order, so the pool reclaims them itself:
189	// first under capacity pressure, and once its idle window passes.
190	held: Mutex<Vec<Weak<group::Handoff>>>,
191}
192
193/// The pool-wide index of wall-clock deadlines that [`Pool::poll`] fires.
194///
195/// One entry per track and earliest deadline: the reads themselves park in the track's
196/// own `expiry::Wakes`, so arming one takes this lock only when it moves its track's
197/// earliest deadline forward in time, never per read.
198#[derive(Default)]
199struct WallDeadlines {
200	// Keyed by the track account's address too, so tracks sharing an instant coexist.
201	due: BTreeMap<(crate::time::Instant, usize), Weak<Track>>,
202	// The drivers collecting this pool, woken when a deadline earlier than any they
203	// were told about is armed.
204	drivers: kio::WaiterList,
205	// Reads that met a deadline before any driver collected, woken by the first
206	// collection to arm it. Holds live waiters only, so an undriven pool stays bounded.
207	undriven: kio::WaiterList,
208}
209
210struct Clock {
211	epoch: crate::time::Instant,
212	now: crate::time::Instant,
213	sweep: Option<crate::time::Instant>,
214}
215
216impl Pool {
217	/// Create a pool from an initial policy.
218	///
219	/// The budget counts frame payload bytes plus a fixed cost per cached group, which
220	/// is most of what a group carrying one small frame occupies. It is not process
221	/// RSS, and it is a convergence target rather than a hard limit; leave headroom
222	/// when sizing it from real memory. The expiry is fixed, while the capacity can
223	/// later be changed with [`Self::resize`].
224	pub fn new(config: Config) -> Self {
225		let expiry = config.expiry.map_or(u64::MAX, |expiry| {
226			let ms = u64::try_from(expiry.as_millis()).unwrap_or(u64::MAX);
227			if ms == u64::MAX {
228				return u64::MAX;
229			}
230			ms.max(1).div_ceil(TICK_MS).saturating_mul(TICK_MS)
231		});
232		Self {
233			inner: Arc::new(SendCell::new(Inner {
234				used: AtomicU64::new(0),
235				capacity: AtomicU64::new(config.capacity.unwrap_or(u64::MAX)),
236				pinned: AtomicI64::new(0),
237				fill_held: AtomicI64::new(0),
238				recorded: AtomicU64::new(0),
239				expiry,
240				clock: Mutex::new(None),
241				tick: AtomicU64::new(0),
242				access_sum: AtomicU64::new(0),
243				access_count: AtomicU64::new(0),
244				tracks: kio::Lock::new(slab::Slab::new()),
245				wall_epoch: OnceLock::new(),
246				wall_micros: AtomicU64::new(0),
247				wall: kio::Lock::default(),
248				held: Mutex::default(),
249			})),
250		}
251	}
252
253	/// Create a pool that never evicts. This is the [`Default`].
254	pub fn unbounded() -> Self {
255		Self::new(Config::default())
256	}
257
258	/// The configured byte target, or `None` when unbounded.
259	pub fn capacity(&self) -> Option<u64> {
260		match self.inner.capacity.load(Ordering::Relaxed) {
261			u64::MAX => None,
262			capacity => Some(capacity),
263		}
264	}
265
266	/// Bytes currently cached across every registered group.
267	pub fn used(&self) -> u64 {
268		self.inner.used.load(Ordering::Relaxed)
269	}
270
271	/// Bytes no eviction can reclaim while their tracks live: every live track's newest group
272	/// and spare encoder.
273	pub(crate) fn pinned(&self) -> u64 {
274		self.inner.pinned.load(Ordering::Relaxed).max(0).unsigned_abs()
275	}
276
277	/// Bytes fills hold for their readers, apart from what live edges pin.
278	pub(super) fn held(&self) -> u64 {
279		self.inner.fill_held.load(Ordering::Relaxed).max(0).unsigned_abs()
280	}
281
282	/// Count `n` bytes into, or out of, the counter for `class`.
283	fn count(&self, class: Class, n: u64, add: bool) {
284		let counter = match class {
285			Class::Pinned => &self.inner.pinned,
286			Class::Held => &self.inner.fill_held,
287			Class::Free => return,
288		};
289		match add {
290			true => counter.fetch_add(n.cast_signed(), Ordering::Relaxed),
291			false => counter.fetch_sub(n.cast_signed(), Ordering::Relaxed),
292		};
293	}
294
295	/// Whether what fills hold fits the capacity beside the pins, so eviction spares it. Past
296	/// that, a held group is evicted like any other: holds never keep the pool past its
297	/// capacity.
298	pub(super) fn holds_fit(&self) -> bool {
299		self.pinned().saturating_add(self.held()) <= self.inner.capacity.load(Ordering::Relaxed)
300	}
301
302	/// Whether a fill could hold one more group of `size` bytes: it fits the capacity beside
303	/// the pins and every hold.
304	pub(super) fn hold_room(&self, size: u64) -> bool {
305		self.pinned().saturating_add(self.held()).saturating_add(size) <= self.inner.capacity.load(Ordering::Relaxed)
306	}
307
308	/// What eviction spares: the pins, and the holds while they fit.
309	fn spared(&self) -> u64 {
310		match self.holds_fit() {
311			true => self.pinned().saturating_add(self.held()),
312			false => self.pinned(),
313		}
314	}
315
316	/// What eviction could ever free: everything it does not spare.
317	pub(super) fn reclaimable(&self) -> u64 {
318		self.used().saturating_sub(self.spared())
319	}
320
321	/// How far readers' records and tails, beside what eviction spares, are past the target:
322	/// the most their debt stands for. The rest of any excess is cached groups, however
323	/// fresh, which their tracks pay by evicting as they age, never by ending a reader.
324	fn records_over(&self) -> u64 {
325		let recorded = self.inner.recorded.load(Ordering::Relaxed);
326		self.spared().saturating_add(recorded).saturating_sub(self.target())
327	}
328
329	/// What readers' records and tails bill in all.
330	#[cfg(all(test, feature = "async"))]
331	pub(super) fn recorded(&self) -> u64 {
332		self.inner.recorded.load(Ordering::Relaxed)
333	}
334
335	/// What usage converges toward: the capacity, or the pinned bytes when they are more,
336	/// since nothing can reclaim those. Holds never raise it: they fit within the capacity.
337	fn target(&self) -> u64 {
338		self.inner.capacity.load(Ordering::Relaxed).max(self.pinned())
339	}
340
341	/// How far usage is past [`Self::target`], if it is: all that eviction, shedding, and
342	/// readers folding could still free toward it.
343	pub(super) fn excess(&self) -> Option<u64> {
344		self.used().checked_sub(self.target()).filter(|excess| *excess > 0)
345	}
346
347	/// Change the capacity. `None` makes the pool unbounded.
348	///
349	/// Takes effect as tracks write: a shrink leaves the pool over budget, which every
350	/// subsequent write pays down proportionally. Nothing is reclaimed synchronously.
351	pub fn resize(&self, capacity: impl Into<Option<u64>>) {
352		let capacity = capacity.into().unwrap_or(u64::MAX);
353		self.inner.capacity.store(capacity, Ordering::Relaxed);
354	}
355
356	/// The wall-clock LRU window, or `None` when idle content is never reclaimed.
357	pub fn expiry(&self) -> Option<Duration> {
358		match self.inner.expiry {
359			u64::MAX => None,
360			ms => Some(Duration::from_millis(ms)),
361		}
362	}
363
364	/// The LRU window in coarse ticks; effectively infinite when disabled.
365	pub(super) fn expiry_ticks(&self) -> u64 {
366		match self.inner.expiry {
367			u64::MAX => u64::MAX,
368			ms => ms / TICK_MS,
369		}
370	}
371
372	/// Sample recency periodically while either cache policy is enabled.
373	///
374	/// Expiry is approximate: activity is dated on the following cleanup pass,
375	/// and passes run at half the idle window.
376	pub(super) fn sweep_interval(&self) -> Option<Duration> {
377		self.expiry()
378			.or_else(|| self.capacity().map(|_| DEFAULT_EXPIRY))
379			.map(|window| window / 2)
380	}
381
382	/// Have the pool drop `handoff`'s held head under capacity pressure, oldest first, or
383	/// once its idle window passes.
384	pub(super) fn hold_head(&self, handoff: &Arc<group::Handoff>) {
385		let mut held = self.inner.held.lock().unwrap_or_else(PoisonError::into_inner);
386		// Forget the hand-offs done with before growing, so a burst of failed groups whose
387		// heads recovery adopts at once grows the registry no further than the heads held.
388		if held.len() == held.capacity() {
389			self.prune_held(&mut held);
390		}
391		held.push(Arc::downgrade(handoff));
392	}
393
394	/// Drop held heads, oldest first, while the pool is past its target.
395	pub(super) fn reclaim_held(&self) {
396		if self.excess().is_some() {
397			let mut held = self.inner.held.lock().unwrap_or_else(PoisonError::into_inner);
398			self.prune_held(&mut held);
399		}
400	}
401
402	/// Drop the held heads past the idle window, then the oldest while the pool is past its
403	/// target, and forget the hand-offs holding none.
404	fn prune_held(&self, held: &mut Vec<Weak<group::Handoff>>) {
405		held.retain(|handoff| {
406			let Some(handoff) = handoff.upgrade() else {
407				return false;
408			};
409			!handoff.expire(self.excess().is_some())
410		});
411	}
412
413	#[cfg(test)]
414	pub(super) fn held_capacity(&self) -> usize {
415		self.inner
416			.held
417			.lock()
418			.unwrap_or_else(PoisonError::into_inner)
419			.capacity()
420	}
421
422	/// Expire idle groups and held heads across the registered tracks.
423	pub(super) fn sweep(&self) {
424		{
425			let mut held = self.inner.held.lock().unwrap_or_else(PoisonError::into_inner);
426			self.prune_held(&mut held);
427			// Give back what a burst of held heads grew it to, which the pool no longer bills.
428			let len = held.len();
429			held.shrink_to(len * 2);
430		}
431		// Upgrade outside each track's lock: dropping its last account unregisters it.
432		let tracks: Vec<_> = self
433			.inner
434			.tracks
435			.lock()
436			.iter()
437			.filter_map(|(_, track)| track.upgrade())
438			.collect();
439		for track in tracks {
440			track.sweep();
441		}
442	}
443
444	/// Collect idle cache entries and return the next cleanup time, like
445	/// [`Driver::poll`](crate::time::Driver::poll).
446	///
447	/// Call at the returned deadline, and again whenever `waiter` wakes, including when
448	/// idle. Calls before that deadline only advance the pool's sampled clock. A due
449	/// pass visits every cached group, dating accesses since the last pass and
450	/// reclaiming idle groups except each live track's latest. Delayed calls extend
451	/// retention. Shared pools use the latest supplied instant.
452	///
453	/// `None` means both cache policies are disabled and no read waits on a wall-clock
454	/// deadline. After enabling a capacity
455	/// with [`Self::resize`], call this again to resume periodic clock sampling.
456	///
457	/// It also releases reads parked on a wall-clock deadline (a group's successor
458	/// arriving plus the reader's budget), so the returned deadline includes the earliest
459	/// of those, and `waiter` wakes when a read arms one earlier than it. Until a pool is
460	/// first collected, no deadline fires; that first collection wakes the reads waiting
461	/// on one so they arm it.
462	pub fn poll(&self, now: crate::time::Instant, waiter: &kio::Waiter) -> Option<crate::time::Instant> {
463		self.advance(now, true, Some(waiter))
464	}
465
466	fn advance(
467		&self,
468		now: crate::time::Instant,
469		sweep: bool,
470		driver: Option<&kio::Waiter>,
471	) -> Option<crate::time::Instant> {
472		let first;
473		let next = {
474			// Shared origins must not run overlapping collection passes.
475			let mut clock = self.inner.clock.lock().unwrap_or_else(PoisonError::into_inner);
476			let clock = clock.get_or_insert(Clock {
477				epoch: now,
478				now,
479				sweep: None,
480			});
481			let now = now.max(clock.now);
482			let tick = u64::try_from(now.duration_since(clock.epoch).as_millis() / u128::from(TICK_MS))
483				.expect("cache clock overflow");
484			self.inner.tick.store(tick, Ordering::Relaxed);
485			clock.now = now;
486			// Collection passes are serialized by the clock lock, so only one sees the first.
487			first = self.inner.wall_epoch.get().is_none();
488			let epoch = *self.inner.wall_epoch.get_or_init(|| now);
489			let micros = u64::try_from(now.duration_since(epoch).as_micros()).unwrap_or(u64::MAX);
490			// The clock lock already orders drivers and clamps their supplied time.
491			self.inner.wall_micros.store(micros, Ordering::Relaxed);
492			if self.sweep_interval().is_none() {
493				clock.sweep = None;
494			} else if sweep && clock.sweep.is_none_or(|at| at <= now) {
495				self.sweep();
496				clock.sweep = self.sweep_interval().and_then(|interval| now.checked_add(interval));
497			}
498			clock.sweep
499		};
500		if first {
501			let mut undriven = self.inner.wall.lock().undriven.take();
502			undriven.wake();
503		}
504		let wall = self.release_due(driver);
505		next.into_iter().chain(wall).min()
506	}
507
508	/// Wake every read whose wall-clock deadline has passed, returning the
509	/// earliest left and registering `driver` to hear of an earlier one.
510	fn release_due(&self, driver: Option<&kio::Waiter>) -> Option<crate::time::Instant> {
511		let mut wall = self.inner.wall.lock();
512		if wall.due.is_empty() {
513			if let Some(driver) = driver {
514				driver.register(&mut wall.drivers);
515			}
516			return None;
517		}
518		// With no parked read there is nothing to age. Otherwise the ambient clock
519		// still matters, even when a caller supplies an instant behind its deadline.
520		// Keep one sample across tracks that rearm while this pass releases them.
521		let now = self.now_wall();
522		loop {
523			let mut due = Vec::new();
524			while let Some(entry) = wall.due.first_entry()
525				&& entry.key().0 <= now
526			{
527				due.push(entry.remove());
528			}
529			if due.is_empty() {
530				if let Some(driver) = driver {
531					driver.register(&mut wall.drivers);
532				}
533				return wall.due.first_key_value().map(|((at, _), _)| *at);
534			}
535			drop(wall);
536			// Outside the lock: a track re-arms its next deadline here.
537			for track in due.iter().filter_map(Weak::upgrade) {
538				if let Some(next) = track.wakes.release_wall(now) {
539					self.schedule(next, None, &track);
540				}
541			}
542			wall = self.inner.wall.lock();
543		}
544	}
545
546	/// The instant wall-clock staleness is judged at: the model's clock, never behind the
547	/// latest instant a driver collected this pool at.
548	///
549	/// Both, because the clock alone runs behind a driver that is supplied time some other
550	/// way (a paused test runtime), which would leave a read woken at a deadline judging
551	/// it not yet reached and parking on it again.
552	pub(super) fn now_wall(&self) -> crate::time::Instant {
553		let wall = super::clock::wall();
554		match self.inner.wall_epoch.get() {
555			Some(epoch) => {
556				let driven =
557					epoch.saturating_add(Duration::from_micros(self.inner.wall_micros.load(Ordering::Relaxed)));
558				wall.max(driven)
559			}
560			None => wall,
561		}
562	}
563
564	/// Whether a driver collects this pool, so a wall-clock deadline armed in it fires.
565	/// If not, `waiter` wakes on the first collection, to arm its deadline then.
566	fn watch_driven(&self, waiter: &kio::Waiter) -> bool {
567		// Checked under the lock the first collection drains under, so none slips between.
568		let mut wall = self.inner.wall.lock();
569		if self.inner.wall_epoch.get().is_some() {
570			return true;
571		}
572		waiter.register(&mut wall.undriven);
573		false
574	}
575
576	/// Index `track`'s earliest wall-clock deadline `at` in place of `replaced`, waking the
577	/// drivers if it is now the pool's earliest.
578	fn schedule(&self, at: crate::time::Instant, replaced: Option<crate::time::Instant>, track: &Arc<Track>) {
579		let mut wall = self.inner.wall.lock();
580		let address = Arc::as_ptr(track) as usize;
581		if let Some(replaced) = replaced {
582			wall.due.remove(&(replaced, address));
583		}
584		let key = (at, address);
585		wall.due.insert(key, Arc::downgrade(track));
586		if wall.due.first_key_value().is_some_and(|(first, _)| *first == key) {
587			let mut drivers = std::mem::take(&mut wall.drivers);
588			drop(wall);
589			drivers.wake();
590		}
591	}
592
593	/// Move the pool's sampled clock forward by `duration`, dating accesses on either
594	/// side without collecting, as if that much time passed between two passes.
595	#[cfg(test)]
596	pub(super) fn step(&self, duration: Duration) {
597		let now = self
598			.inner
599			.clock
600			.lock()
601			.unwrap_or_else(PoisonError::into_inner)
602			.as_ref()
603			.map(|clock| clock.now);
604		let now = now.unwrap_or_else(super::clock::wall);
605		self.date(now);
606		self.date(now.saturating_add(duration));
607	}
608
609	#[cfg(test)]
610	fn date(&self, now: crate::time::Instant) {
611		self.advance(now, false, None);
612		let tracks: Vec<_> = self
613			.inner
614			.tracks
615			.lock()
616			.iter()
617			.filter_map(|(_, track)| track.upgrade())
618			.collect();
619		for track in tracks {
620			if let Some(state) = track.state.upgrade() {
621				state.read().date_cache_accesses(self.now());
622			}
623		}
624	}
625
626	/// Enter a track account into the sweep registry, returning its key. `None` when
627	/// idle reclamation is off, which is what keeps a bare pool free of bookkeeping.
628	fn register(&self, track: &Arc<Track>) -> Option<usize> {
629		self.expiry()?;
630		Some(self.inner.tracks.lock().insert(Arc::downgrade(track)))
631	}
632
633	/// Drop a track account from the sweep registry.
634	fn unregister(&self, key: usize) {
635		self.inner.tracks.lock().remove(key);
636	}
637
638	/// Returns true if both handles share the same underlying pool.
639	#[cfg(test)]
640	pub(super) fn same_pool(&self, other: &Self) -> bool {
641		Arc::ptr_eq(&self.inner, &other.inner)
642	}
643
644	/// A handle that reaches this budget without keeping it alive.
645	pub fn downgrade(&self) -> PoolWeak {
646		PoolWeak {
647			inner: Arc::downgrade(&self.inner),
648		}
649	}
650
651	/// Charge `n` more cached bytes.
652	pub(super) fn add(&self, n: u64) {
653		self.inner.used.fetch_add(n, Ordering::Relaxed);
654	}
655
656	/// Release `n` cached bytes.
657	pub(super) fn sub(&self, n: u64) {
658		self.inner.used.fetch_sub(n, Ordering::Relaxed);
659	}
660
661	/// Coarse ticks since the first cleanup call.
662	pub(super) fn now(&self) -> u64 {
663		self.inner.tick.load(Ordering::Relaxed)
664	}
665
666	/// Encode the current clock tick and an access-priority tie breaker.
667	fn stamp(&self, boost: u64) -> u64 {
668		self.now().saturating_mul(1 << ACCESS_SHIFT).saturating_add(boost)
669	}
670
671	/// Mean last-access tick across the evictable population, or `None` when it is
672	/// empty. The sum and count are read separately, so the mean is approximate
673	/// under concurrent updates; eviction only needs a rough frontier.
674	pub(super) fn average(&self) -> Option<u64> {
675		let count = self.inner.access_count.load(Ordering::Relaxed);
676		if count == 0 {
677			return None;
678		}
679		Some(self.inner.access_sum.load(Ordering::Relaxed) / count)
680	}
681
682	/// A group with last-access tick `ts` joined the evictable population.
683	pub(super) fn access_insert(&self, ts: u64) {
684		self.inner.access_sum.fetch_add(ts, Ordering::Relaxed);
685		self.inner.access_count.fetch_add(1, Ordering::Relaxed);
686	}
687
688	/// A group with last-access tick `ts` left the evictable population.
689	pub(super) fn access_remove(&self, ts: u64) {
690		self.inner.access_sum.fetch_sub(ts, Ordering::Relaxed);
691		self.inner.access_count.fetch_sub(1, Ordering::Relaxed);
692	}
693
694	/// An evictable group's last-access tick moved from `old` to `new` (a FETCH hit).
695	pub(super) fn access_refresh(&self, old: u64, new: u64) {
696		// A single wrapping add keeps the sum exact even under racing refreshes.
697		self.inner
698			.access_sum
699			.fetch_add(new.wrapping_sub(old), Ordering::Relaxed);
700	}
701
702	/// The eviction debt a track takes on by writing `written` bytes, or `None` while
703	/// the pool is within its [`Self::target`] (the caller should forget any outstanding
704	/// debt).
705	///
706	/// The debt is `written * used / target`, so paying it evicts slightly more
707	/// than was written and the overshoot decays toward the target. Tracks double
708	/// it when their oldest content is staler than [`Self::average`]. Saturates: a
709	/// tiny capacity must not wrap a huge debt into a small one.
710	pub(super) fn accrue(&self, written: u64) -> Option<u64> {
711		let used = self.used();
712		let target = self.target();
713		if used <= target {
714			return None;
715		}
716		let debt = written as u128 * used as u128 / target.max(1) as u128;
717		Some(u64::try_from(debt).unwrap_or(u64::MAX))
718	}
719}
720
721impl std::fmt::Debug for Pool {
722	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
723		f.debug_struct("Pool")
724			.field("used", &self.used())
725			.field("capacity", &self.capacity())
726			.field("expiry", &self.expiry())
727			.finish()
728	}
729}
730
731/// A handle to a [`Pool`] that does not keep the budget alive.
732///
733/// [`upgrade`](Self::upgrade) stops returning a [`Pool`] once every strong handle has
734/// dropped, which is how a background resizer learns the budget it manages is gone and
735/// nothing can cache into it any more.
736#[derive(Clone)]
737pub struct PoolWeak {
738	inner: std::sync::Weak<SendCell<Inner>>,
739}
740
741impl PoolWeak {
742	/// Recover a [`Pool`], or `None` once every strong handle has dropped.
743	pub fn upgrade(&self) -> Option<Pool> {
744		self.inner.upgrade().map(|inner| Pool { inner })
745	}
746}
747
748impl std::fmt::Debug for PoolWeak {
749	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
750		match self.upgrade() {
751			Some(pool) => pool.fmt(f),
752			None => f.debug_struct("PoolWeak").finish_non_exhaustive(),
753		}
754	}
755}
756
757/// Entries the live-edge order keeps for edges that moved on before it drops them.
758const EDGE_SLACK: usize = 64;
759
760/// What one session's tracks may keep of their live edges, which the [`Pool`] never evicts.
761///
762/// Each track a session ingests bills its live edge here: the newest group, which a live
763/// track keeps whatever the pool's budget, so a publisher holding many quiet tracks would
764/// otherwise hold one group each past any capacity. A frame write that leaves the session
765/// past its limit sheds its live edges in the order delivery would give up on them: the
766/// lowest priority first, as delivery ranks a track (its subscriber's priority, then its
767/// publisher's), and among equals the edge that moved longest ago, so the cost stays with
768/// the session causing it. Each edge first sheds the frames its readers took, then
769/// everything; the one being written keeps its newest frame. The default is unbounded and
770/// costs nothing.
771#[derive(Clone, Default)]
772pub(crate) struct Edges(Option<Arc<EdgesInner>>);
773
774/// Where a live edge pays in its session's order: its track's rank, lowest first, then the
775/// session's count of edge moves when it last moved, oldest first.
776type EdgeKey = (i64, u64);
777
778struct EdgesInner {
779	limit: u64,
780	// Bytes billed by the live edges of this session's tracks. Signed: a footprint that flips
781	// while one of its bytes is mid-update bills the session an instant early or late, which
782	// may dip it below zero, never a reason to reclaim.
783	used: AtomicI64,
784	// The tracks in the order their live edges pay, each with the move it was queued at. An
785	// entry whose track moved on or changed rank since is stale, and skipped.
786	order: Mutex<BTreeMap<EdgeKey, (Weak<Track>, u64)>>,
787	// The moves of every live edge in this session, ordering edges of equal rank.
788	moves: AtomicU64,
789	// The tracks billing here, so the order knows how many of its entries can be current.
790	tracks: AtomicUsize,
791	// The tracks whose readers took a frame their groups still hold, in the order their edges
792	// pay, each listed once until a reclaim visits it: what a reclaim's first pass sheds,
793	// without looking at an edge that has nothing taken. A track's entry moves with its
794	// rank and age, under this lock.
795	taken: Mutex<BTreeMap<TakenKey, Weak<Track>>>,
796	// Held through a reclaim, so one that finds no taken frame listed never sheds a whole
797	// edge while another is still shedding the taken frames it popped.
798	reclaiming: Mutex<()>,
799	// Run once when a reclaim's whole-edge pass starts, so a test can move edges mid-pass.
800	#[cfg(test)]
801	started: Mutex<Option<Box<dyn FnOnce() + Send>>>,
802}
803
804/// A track's place among its session's edges with taken frames: its [`EdgeKey`], then its
805/// account's address, which keeps two tracks at one key apart.
806type TakenKey = (EdgeKey, usize);
807
808impl Edges {
809	/// A budget of `limit` bytes, or unbounded for `None`.
810	pub(crate) fn new(limit: Option<u64>) -> Self {
811		Self(limit.map(|limit| {
812			Arc::new(EdgesInner {
813				limit,
814				used: AtomicI64::new(0),
815				order: Mutex::default(),
816				moves: AtomicU64::new(0),
817				tracks: AtomicUsize::new(0),
818				taken: Mutex::default(),
819				reclaiming: Mutex::default(),
820				#[cfg(test)]
821				started: Mutex::default(),
822			})
823		}))
824	}
825
826	/// Whether a reclaim holds the session's reclaim lock now.
827	#[cfg(all(test, feature = "async"))]
828	pub(super) fn reclaiming(&self) -> bool {
829		self.0
830			.as_ref()
831			.is_some_and(|inner| inner.reclaiming.try_lock().is_err())
832	}
833
834	/// Run `hook` once the next reclaim's whole-edge pass starts.
835	#[cfg(all(test, feature = "async"))]
836	pub(super) fn on_pass(&self, hook: impl FnOnce() + Send + 'static) {
837		if let Some(inner) = &self.0 {
838			*inner.started.lock().unwrap() = Some(Box::new(hook));
839		}
840	}
841
842	/// Bytes the session's live edges bill now.
843	#[cfg(any(test, feature = "fuzz"))]
844	pub(super) fn used(&self) -> u64 {
845		self.0
846			.as_ref()
847			.map_or(0, |inner| inner.used.load(Ordering::Relaxed).max(0).unsigned_abs())
848	}
849
850	fn add(&self, n: u64) {
851		if let Some(inner) = &self.0 {
852			inner.used.fetch_add(n.cast_signed(), Ordering::Relaxed);
853		}
854	}
855
856	fn sub(&self, n: u64) {
857		if let Some(inner) = &self.0 {
858			inner.used.fetch_sub(n.cast_signed(), Ordering::Relaxed);
859		}
860	}
861
862	/// How far past its limit the session is, if it is.
863	fn excess(&self) -> Option<u64> {
864		let inner = self.0.as_ref()?;
865		let used = inner.used.load(Ordering::Relaxed).max(0).unsigned_abs();
866		used.checked_sub(inner.limit).filter(|excess| *excess > 0)
867	}
868
869	/// Pay the session's excess with its live edges in order, lowest rank and oldest first,
870	/// in two passes. The first sheds the frames readers took, which no reader is owed,
871	/// visiting only the edges a reader took one of since a reclaim last visited them. Only
872	/// once none is left does the second shed every frame of an edge (aborting a copy still
873	/// receiving one), which then leaves the order until it grows again. `writer`'s edge,
874	/// being written, instead sheds its older frames in its turn and stays queued.
875	/// Takes track locks: call with none held.
876	fn reclaim(&self, writer: &Track) {
877		let Some(inner) = &self.0 else {
878			return;
879		};
880		// Opened first, so it drops last: a shed's wakes go out once the lock is released,
881		// since a woken task polled inline may settle a write here and reclaim again.
882		let _hold = kio::hold();
883		let _reclaiming = inner.reclaiming.lock().unwrap_or_else(PoisonError::into_inner);
884		while self.excess().is_some() {
885			let track = {
886				let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner);
887				let Some((_, track)) = taken.pop_first() else {
888					break;
889				};
890				let Some(track) = track.upgrade() else {
891					continue;
892				};
893				// Unlisted before the shed, so a frame a reader takes during it lists the
894				// track again.
895				*track.listed.lock().unwrap_or_else(PoisonError::into_inner) = None;
896				track.taken.store(false, Ordering::SeqCst);
897				track
898			};
899			track.shed_taken();
900		}
901		// The writer pays in its turn, or after every queued edge when it has no entry.
902		let mut paid = false;
903		// Each step resumes after the last key, so an entry is visited once. The pass covers
904		// only the edges that last moved before it started: one a publisher moves meanwhile
905		// sorts after its own, so publishing faster than this pass could otherwise keep it, and
906		// the lock, going, or use up its visits on empty new groups. Visits are also bounded by
907		// the entries present now, since a rerank requeues an edge at its old age.
908		let (mut offers, start) = {
909			let order = inner.order.lock().unwrap_or_else(PoisonError::into_inner);
910			(order.len(), inner.moves.load(Ordering::Relaxed))
911		};
912		#[cfg(test)]
913		if let Some(hook) = inner.started.lock().unwrap().take() {
914			hook();
915		}
916		let mut from = Bound::Unbounded;
917		while offers > 0
918			&& self.excess().is_some()
919			&& let Some((key, track, moves)) = self.next(from)
920		{
921			// Moved since the pass started, as has every later edge at its rank.
922			if key.1 >= start {
923				from = Bound::Included((key.0 + 1, 0));
924				continue;
925			}
926			offers -= 1;
927			from = Bound::Excluded(key);
928			if std::ptr::eq(Arc::as_ptr(&track), writer) {
929				paid = true;
930				writer.shed_own(self);
931				continue;
932			}
933			let Some(state) = track.state.upgrade() else {
934				continue;
935			};
936			let Ok(mut state) = state.write() else {
937				continue;
938			};
939			// Unqueued before the shed, so whatever the edge bills after it queues it again.
940			inner.order.lock().unwrap_or_else(PoisonError::into_inner).remove(&key);
941			track.queued.store(false, Ordering::Relaxed);
942			state.shed_edge_all(moves);
943		}
944		if !paid {
945			writer.shed_own(self);
946		}
947	}
948
949	/// List `track` as having taken frames to shed, or with `again`, move its entry to its
950	/// current rank and age if it has one. Its `taken` flag changes only here, with the entry,
951	/// so the two always agree. Drops the entries of tracks gone since once they clearly
952	/// outnumber the live ones, as [`Self::queue`] does.
953	fn list(&self, track: &Arc<Track>, again: bool) {
954		let Some(inner) = &self.0 else {
955			return;
956		};
957		let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner);
958		let mut listed = track.listed.lock().unwrap_or_else(PoisonError::into_inner);
959		let at = Arc::as_ptr(track) as usize;
960		match (*listed, again) {
961			(Some(key), true) => {
962				taken.remove(&(key, at));
963			}
964			(None, false) => {}
965			_ => return,
966		}
967		let key = (track.rank(), track.seq.load(Ordering::Relaxed));
968		taken.insert((key, at), Arc::downgrade(track));
969		*listed = Some(key);
970		track.taken.store(true, Ordering::SeqCst);
971		drop(listed);
972		if taken.len() > 2 * inner.tracks.load(Ordering::Relaxed) + EDGE_SLACK {
973			taken.retain(|_, track| track.strong_count() > 0);
974		}
975	}
976
977	/// The first current entry in the order from `from` on, dropping the stale ones before it.
978	fn next(&self, mut from: Bound<EdgeKey>) -> Option<(EdgeKey, Arc<Track>, u64)> {
979		let inner = self.0.as_ref()?;
980		let mut order = inner.order.lock().unwrap_or_else(PoisonError::into_inner);
981		loop {
982			let (key, (weak, moves)) = order.range((from, Bound::Unbounded)).next()?;
983			let (key, moves) = (*key, *moves);
984			match weak.upgrade().filter(|track| track.queued_at(key, moves)) {
985				Some(track) => return Some((key, track, moves)),
986				None => {
987					order.remove(&key);
988					from = Bound::Excluded(key);
989				}
990			}
991		}
992	}
993
994	/// Queue `track`'s live edge at its rank and last move, replacing nothing: an entry it
995	/// left at another rank or move turns stale.
996	fn queue(&self, track: &Arc<Track>) {
997		let Some(inner) = &self.0 else {
998			return;
999		};
1000		let mut order = inner.order.lock().unwrap_or_else(PoisonError::into_inner);
1001		// Read under the lock a move updates them under, so the two always match.
1002		let moves = track.moves.load(Ordering::Relaxed);
1003		let key = (track.rank(), track.seq.load(Ordering::Relaxed));
1004		order.insert(key, (Arc::downgrade(track), moves));
1005		// Each move or rank change leaves its track's earlier entry behind: drop those once
1006		// they clearly outnumber the current ones, which costs a constant per change.
1007		if order.len() > 2 * inner.tracks.load(Ordering::Relaxed) + EDGE_SLACK {
1008			order.retain(|key, (track, moves)| track.upgrade().is_some_and(|track| track.queued_at(*key, *moves)));
1009		}
1010		drop(order);
1011		// A listed edge with taken frames moves with it, so they pay in its new turn.
1012		if track.taken.load(Ordering::SeqCst) {
1013			self.list(track, true);
1014		}
1015	}
1016
1017	/// Move `track`'s live edge to a newer group, queued as the session's newest.
1018	fn moved(&self, track: &Arc<Track>) {
1019		let Some(inner) = &self.0 else {
1020			track.moves.fetch_add(1, Ordering::Relaxed);
1021			return;
1022		};
1023		// Under the order's lock, so a concurrent queue never pairs this move with the last one's
1024		// age, or overwrites this entry with the last move's.
1025		let order = inner.order.lock().unwrap_or_else(PoisonError::into_inner);
1026		track
1027			.seq
1028			.store(inner.moves.fetch_add(1, Ordering::Relaxed), Ordering::Relaxed);
1029		track.moves.fetch_add(1, Ordering::Relaxed);
1030		drop(order);
1031		self.unlist(track);
1032		self.queue(track);
1033	}
1034
1035	/// Drop `track`'s listing, if it has one: the edge whose readers took frames left it.
1036	fn unlist(&self, track: &Arc<Track>) {
1037		let Some(inner) = &self.0 else {
1038			return;
1039		};
1040		if !track.taken.load(Ordering::SeqCst) {
1041			return;
1042		}
1043		let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner);
1044		if let Some(key) = track.listed.lock().unwrap_or_else(PoisonError::into_inner).take() {
1045			taken.remove(&(key, Arc::as_ptr(track) as usize));
1046		}
1047		track.taken.store(false, Ordering::SeqCst);
1048	}
1049}
1050
1051impl std::fmt::Debug for Edges {
1052	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1053		match &self.0 {
1054			Some(inner) => f
1055				.debug_struct("Edges")
1056				.field("used", &inner.used.load(Ordering::Relaxed))
1057				.field("limit", &inner.limit)
1058				.finish(),
1059			None => f.debug_struct("Edges").finish_non_exhaustive(),
1060		}
1061	}
1062}
1063
1064/// Tells a group's session when its readers take frames it still holds, while the copy is
1065/// itself the live edge, so a reclaim past the session's budget visits only edges with taken
1066/// frames: a sibling that bills the edge from outside its slot is never visited.
1067pub(super) struct Report {
1068	track: Arc<Track>,
1069	footprint: Arc<Footprint>,
1070}
1071
1072impl Report {
1073	/// A reader took a frame the group still holds.
1074	pub(super) fn took(&self) {
1075		if self.footprint.slot() {
1076			self.track.took();
1077		}
1078	}
1079
1080	/// The group's inflated copy grew, which a sibling that is the live edge shares. A copy that
1081	/// is itself the edge reports it through [`Self::took`] instead, as its readers' progress
1082	/// decides whether it has anything to shed.
1083	pub(super) fn decoded(&self) {
1084		if !self.footprint.slot() {
1085			self.track.took();
1086		}
1087	}
1088}
1089
1090/// Gross bytes a track writes before a frame write settles its eviction debt itself,
1091/// so a track appending frames to open groups (never inserting another group) still
1092/// pays. Coarse: the cost is one track-state lock per threshold crossing.
1093const WRITE_CHARGE_THRESHOLD: u64 = 256 * 1024;
1094
1095/// Maximum cadence for write-driven expiry scans, in the pool's coarse ticks.
1096///
1097/// Byte debt settles only after enough data accumulates, but expiry is a time
1098/// policy and must also run for low-bitrate tracks. Limiting that extra track lock
1099/// to once per second keeps the write hot path cheap while a bounded scan drains
1100/// stale backlogs steadily.
1101const EXPIRY_SCAN_TICKS: u64 = 1000 / TICK_MS;
1102
1103/// One track's account against the [`Pool`], shared with every group it creates.
1104///
1105/// Groups charge their bytes here (through a [`Charge`]) rather than straight into the
1106/// pool, so the track can drain what its own groups wrote into eviction debt and pay it
1107/// off by evicting them. The link back to the track is a [`kio::Weak`] because the track
1108/// owns its cached groups and each of those owns this account: anything stronger would
1109/// make a track's cache immortal.
1110///
1111/// The default account is detached: an unbounded pool and no track, so every operation
1112/// is a no-op.
1113#[derive(Default)]
1114pub(super) struct Track {
1115	pool: Pool,
1116
1117	// Gross bytes charged by this track's groups (payload plus overhead), never
1118	// decremented here: the track swaps it out as it accrues debt.
1119	written: AtomicU64,
1120
1121	// Earliest coarse tick when a frame write may run another expiry scan.
1122	next_expiry: AtomicU64,
1123
1124	// Rotating position of the expiry scan over the track's eviction order.
1125	expiry_cursor: AtomicUsize,
1126
1127	// The track that pays this account off, holding the groups being charged.
1128	state: kio::Weak<TrackState>,
1129
1130	// This account's slot in the pool's sweep registry, absent when the pool has no
1131	// expiry window (nothing is registered) or for the detached default account.
1132	sweep: OnceLock<usize>,
1133
1134	// The track's reads parked on their drift budget. Here because this account is the
1135	// link every group's frame writes already follow back to the track.
1136	wakes: expiry::Wakes,
1137	// Allocated only when a subscriber parks groups behind a serving cap.
1138	aborts: OnceLock<Arc<aborts::Aborts>>,
1139
1140	// Here rather than on the track state so a frame write advances it without the track
1141	// lock, and wakes only the readers following it.
1142	largest: kio::Shared<Largest>,
1143
1144	// Whether the track ever declared an end, set under the track lock and never cleared,
1145	// so a reader looking for one skips that lock until there is one to read.
1146	declared: AtomicBool,
1147
1148	// What the frames this track's groups are still receiving may allocate up front,
1149	// shared with every track minted from the same origin handle.
1150	frames: super::frame::Budget,
1151
1152	// What the session ingesting this track may keep of its tracks' live edges, which this
1153	// track's undemoted groups bill.
1154	edges: Edges,
1155	// How many times the live edge moved to a newer group, naming its entry in `edges`.
1156	moves: AtomicU64,
1157	// The session's count of edge moves when this live edge last moved, its age in `edges`.
1158	seq: AtomicU64,
1159	// The most urgent priority a subscriber asks with, `i8::MIN` while none does, and the
1160	// publisher's: the track's rank in `edges`, as delivery ranks it.
1161	subscriber: AtomicI8,
1162	publisher: AtomicI8,
1163	// Whether the live edge has an entry in its session's order, so one that a reclaim shed
1164	// queues again once it grows.
1165	queued: AtomicBool,
1166	// Whether the session lists this track among its edges with taken frames, so a reader
1167	// lists it once. Changed only under that list's lock, with `listed`.
1168	taken: AtomicBool,
1169	// Where the session lists this track among its edges with taken frames, if it does.
1170	// Changed only under that list's lock.
1171	listed: Mutex<Option<EdgeKey>>,
1172
1173	// One finished local group's encoder, kept until another group needs it or the
1174	// account drops. Raw codec only: an Extra here would keep this account alive.
1175	encoder: Mutex<Option<flate::Encoder>>,
1176
1177	// What this track's readers' records and tail ledgers bill, and the eviction debt the
1178	// track could not pay itself, which those readers pay; see [`Reader`].
1179	readers: Readers,
1180
1181	// What the track's cursors admit, which a group's paced writer asks without the track
1182	// lock.
1183	admits: track::Admits,
1184}
1185
1186/// What a track's readers bill for their records, and the debt they owe.
1187#[derive(Default)]
1188struct Readers {
1189	bytes: AtomicU64,
1190	debt: AtomicU64,
1191}
1192
1193/// The greatest location a track has written or its source reported, followed by the track
1194/// handles' `largest`: each new group at its head, then each frame written to it.
1195#[derive(Default)]
1196struct Largest {
1197	position: Option<Position>,
1198	// The largest group's content may still grow: no copy of the whole group finished. An
1199	// aborted one stays open, since it can be recreated or fetched.
1200	open: bool,
1201	// The track ended, so no newer position can follow.
1202	ended: bool,
1203}
1204
1205impl Track {
1206	/// Raise the track's largest location to `position`, waking only its own waiters.
1207	pub(super) fn advance_largest(&self, position: Position) {
1208		let mut largest = self.largest.lock();
1209		if largest.position.is_none_or(|current| position > current) {
1210			largest.position = Some(position);
1211			largest.open = true;
1212		}
1213	}
1214
1215	/// Group `key` holds every frame it will have: a whole copy finished. A group name
1216	/// fixes its content, so no legal write raises the largest past it.
1217	pub(super) fn finish_largest(&self, key: u64) {
1218		let mut largest = self.largest.lock();
1219		if largest.position.is_some_and(|position| position.group == key) {
1220			largest.open = false;
1221		}
1222	}
1223
1224	/// The greatest location written or reported, without waiting.
1225	pub(super) fn largest(&self) -> Option<Position> {
1226		self.largest.read().position
1227	}
1228
1229	/// Whether the largest group's content may still grow; see [`Self::finish_largest`].
1230	pub(super) fn largest_open(&self) -> bool {
1231		self.largest.read().open
1232	}
1233
1234	/// Whether `position` is the largest and its group ended there; see [`Self::finish_largest`].
1235	pub(super) fn largest_finished(&self, position: Position) -> bool {
1236		let largest = self.largest.read();
1237		largest.position == Some(position) && !largest.open
1238	}
1239
1240	/// The source reported `position` as its largest, its group ended there when `finished`.
1241	pub(super) fn report_largest(&self, position: Position, finished: bool) {
1242		let mut largest = self.largest.lock();
1243		if largest.position.is_none_or(|current| position > current) {
1244			largest.position = Some(position);
1245			largest.open = true;
1246		}
1247		if finished && largest.position == Some(position) {
1248			largest.open = false;
1249		}
1250	}
1251
1252	/// End the largest stream once the track ends: no newer frame can follow.
1253	pub(super) fn end_largest(&self) {
1254		let mut largest = self.largest.lock();
1255		if !largest.ended {
1256			largest.ended = true;
1257		}
1258	}
1259
1260	/// Poll for a largest location within `bounds` newer than `seen`, recording it there.
1261	/// `None` once the track ended with nothing newer.
1262	pub(super) fn poll_largest(
1263		&self,
1264		seen: &mut Option<Position>,
1265		bounds: track::Bounds,
1266		waiter: &kio::Waiter,
1267	) -> Poll<Option<Position>> {
1268		let newer = |largest: &Largest| {
1269			largest
1270				.position
1271				.filter(|position| bounds.contains(position.group) && seen.is_none_or(|seen| *position > seen))
1272		};
1273		let largest = ready!(
1274			self.largest
1275				.poll(waiter, |largest| match newer(largest).is_some() || largest.ended {
1276					true => Poll::Ready(()),
1277					false => Poll::Pending,
1278				})
1279		);
1280		let next = newer(&largest);
1281		if next.is_some() {
1282			*seen = next;
1283		}
1284		Poll::Ready(next)
1285	}
1286
1287	/// The largest frame within `bounds` newer than `seen` without waiting, recording it there.
1288	pub(super) fn take_largest(&self, seen: &mut Option<Position>, bounds: track::Bounds) -> Option<Position> {
1289		let next = self
1290			.largest
1291			.read()
1292			.position
1293			.filter(|position| bounds.contains(position.group) && seen.is_none_or(|seen| *position > seen));
1294		if next.is_some() {
1295			*seen = next;
1296		}
1297		next
1298	}
1299
1300	/// Open an account against `pool` for the track behind `state`, its frames
1301	/// allocating up front within `frames` and its live edge billed to `edges`.
1302	pub(super) fn new(
1303		pool: Pool,
1304		frames: super::frame::Budget,
1305		edges: Edges,
1306		state: kio::Weak<TrackState>,
1307	) -> Arc<Self> {
1308		if let Some(inner) = &edges.0 {
1309			inner.tracks.fetch_add(1, Ordering::Relaxed);
1310		}
1311		let track = Arc::new(Self {
1312			pool,
1313			frames,
1314			edges,
1315			moves: AtomicU64::new(0),
1316			seq: AtomicU64::new(0),
1317			subscriber: AtomicI8::new(i8::MIN),
1318			publisher: AtomicI8::new(0),
1319			queued: AtomicBool::new(false),
1320			taken: AtomicBool::new(false),
1321			listed: Mutex::default(),
1322			written: AtomicU64::new(0),
1323			next_expiry: AtomicU64::new(0),
1324			expiry_cursor: AtomicUsize::new(0),
1325			state,
1326			sweep: OnceLock::new(),
1327			wakes: Default::default(),
1328			aborts: OnceLock::new(),
1329			largest: Default::default(),
1330			declared: AtomicBool::new(false),
1331			encoder: Mutex::default(),
1332			readers: Readers::default(),
1333			admits: track::Admits::default(),
1334		});
1335		if let Some(key) = track.pool.register(&track) {
1336			let _ = track.sweep.set(key);
1337		}
1338		track
1339	}
1340
1341	/// What the track's cursors admit.
1342	pub(super) fn admits(&self) -> &track::Admits {
1343		&self.admits
1344	}
1345
1346	/// The pool this track caches into.
1347	pub(super) fn pool(&self) -> &Pool {
1348		&self.pool
1349	}
1350
1351	/// What this track's frames may allocate up front.
1352	pub(super) fn frames(&self) -> &super::frame::Budget {
1353		&self.frames
1354	}
1355
1356	/// The track holding this account's groups, while it is still open.
1357	pub(super) fn track(&self) -> Option<kio::Producer<TrackState>> {
1358		self.state.upgrade()
1359	}
1360
1361	/// The live edge moved to a newer group: queue it as its session's newest. Called under
1362	/// the track lock, which orders the moves.
1363	pub(super) fn edge_moved(self: &Arc<Self>) {
1364		self.queued.store(true, Ordering::Relaxed);
1365		self.edges.moved(self);
1366	}
1367
1368	/// The live edge billed more: queue it again, at the age it had, if a reclaim took its
1369	/// entry.
1370	fn edge_grew(self: &Arc<Self>) {
1371		if !self.queued.swap(true, Ordering::Relaxed) {
1372			self.edges.queue(self);
1373		}
1374	}
1375
1376	/// The most urgent priority the track's subscribers ask with now, `None` with none.
1377	pub(super) fn set_subscriber(self: &Arc<Self>, priority: Option<i8>) {
1378		self.rerank(&self.subscriber, priority.unwrap_or(i8::MIN));
1379	}
1380
1381	/// The publisher's priority for the track.
1382	pub(super) fn set_publisher(self: &Arc<Self>, priority: i8) {
1383		self.rerank(&self.publisher, priority);
1384	}
1385
1386	/// Store one half of the rank, moving the live edge to its new place in the session's
1387	/// order if it has one. Queued even if a reclaim took its entry: an edge with nothing
1388	/// left to shed costs that reclaim one look.
1389	fn rerank(self: &Arc<Self>, half: &AtomicI8, priority: i8) {
1390		if half.swap(priority, Ordering::Relaxed) != priority && self.moves.load(Ordering::Relaxed) > 0 {
1391			self.edges.queue(self);
1392		}
1393	}
1394
1395	/// The track's rank among its session's live edges, packed as delivery ranks its
1396	/// subscription (the subscriber's priority always dominates the publisher's): higher
1397	/// pays later.
1398	fn rank(&self) -> i64 {
1399		i64::from(self.subscriber.load(Ordering::Relaxed)) * 256 + i64::from(self.publisher.load(Ordering::Relaxed))
1400	}
1401
1402	/// Whether the live edge still sits at `key` after its `moves`th move.
1403	fn queued_at(&self, key: EdgeKey, moves: u64) -> bool {
1404		self.edge_is(moves) && self.rank() == key.0
1405	}
1406
1407	/// Pay the session's excess with this track's own live edge, being written: its older
1408	/// frames, keeping the newest of an open group.
1409	fn shed_own(&self, edges: &Edges) {
1410		let Some(excess) = edges.excess() else {
1411			return;
1412		};
1413		let Some(state) = self.state.upgrade() else {
1414			return;
1415		};
1416		let Ok(mut state) = state.write() else {
1417			return;
1418		};
1419		state.shed_edge(excess);
1420	}
1421
1422	/// A reader took a frame the live edge still holds: list the track with its session, once
1423	/// until a reclaim visits it or the edge moves.
1424	fn took(self: &Arc<Self>) {
1425		// SeqCst pairs with the fence in `shed_taken`: either this sees the track unlisted,
1426		// or that shed sees the reader's progress.
1427		if !self.taken.load(Ordering::SeqCst) {
1428			self.edges.list(self, false);
1429		}
1430	}
1431
1432	/// Shed the frames readers took of this track's live edge, which a reclaim unlisted first.
1433	fn shed_taken(&self) {
1434		std::sync::atomic::fence(Ordering::SeqCst);
1435		let Some(state) = self.state.upgrade() else {
1436			return;
1437		};
1438		let Ok(mut state) = state.write() else {
1439			return;
1440		};
1441		state.shed_edge_taken(self.moves.load(Ordering::Relaxed));
1442	}
1443
1444	/// Whether the session lists this track as having taken frames to shed.
1445	#[cfg(all(test, feature = "async"))]
1446	pub(super) fn listed(&self) -> bool {
1447		self.taken.load(Ordering::SeqCst)
1448	}
1449
1450	/// How many times the live edge moved.
1451	#[cfg(all(test, feature = "async"))]
1452	pub(super) fn moves(&self) -> u64 {
1453		self.moves.load(Ordering::Relaxed)
1454	}
1455
1456	/// Whether the live edge is still the one its `moves`th move queued.
1457	pub(super) fn edge_is(&self, moves: u64) -> bool {
1458		self.moves.load(Ordering::Relaxed) == moves
1459	}
1460
1461	/// The track's reads parked on their drift budget.
1462	pub(super) fn wakes(&self) -> &expiry::Wakes {
1463		&self.wakes
1464	}
1465
1466	/// The track declared an end. Called under the track lock.
1467	pub(super) fn declare_end(&self) {
1468		self.declared.store(true, Ordering::Release);
1469	}
1470
1471	/// Whether the track ever declared an end, so the end may be worth the track lock.
1472	pub(super) fn end_declared(&self) -> bool {
1473		self.declared.load(Ordering::Acquire)
1474	}
1475
1476	/// Watch every group the publisher cuts, rather than chosen keys.
1477	pub(super) fn watch_cuts(&self) -> aborts::Watch {
1478		self.aborts.get_or_init(Arc::default).watch_cuts()
1479	}
1480
1481	/// Notify watchers that group `key` aborted, if the publisher cut it.
1482	pub(super) fn aborted(&self, key: u64, cut: bool) {
1483		if cut && let Some(aborts) = self.aborts.get() {
1484			aborts.notify(key);
1485		}
1486	}
1487
1488	/// Park `waiter` until the pool's wall clock reaches `at`. While no driver collects the
1489	/// pool, nothing would release it, so `waiter` parks on the first collection instead.
1490	pub(super) fn watch_wall(self: &Arc<Self>, at: crate::time::Instant, waiter: &kio::Waiter) {
1491		if !self.pool.watch_driven(waiter) {
1492			return;
1493		}
1494		if let Some(replaced) = self.wakes.watch_wall(at, waiter) {
1495			self.pool.schedule(at, replaced, self);
1496		}
1497	}
1498
1499	/// Charge a new group's fixed overhead, returning its [`Charge`].
1500	/// How a group's reader progress reaches this track's session, `None` while it has no
1501	/// live-edge budget to shed taken frames toward.
1502	pub(super) fn report(self: &Arc<Self>, charge: &Charge) -> Option<Report> {
1503		self.edges.0.as_ref()?;
1504		Some(Report {
1505			track: self.clone(),
1506			footprint: charge.footprint.clone(),
1507		})
1508	}
1509
1510	pub(super) fn charge(self: &Arc<Self>) -> Charge {
1511		self.pool.add(ENTRY_OVERHEAD);
1512		self.written.fetch_add(ENTRY_OVERHEAD, Ordering::Relaxed);
1513		let access = Arc::new(Access::new(self.pool.stamp(0)));
1514		Charge {
1515			track: Some(self.clone()),
1516			bytes: ENTRY_OVERHEAD,
1517			access,
1518			counted: false,
1519			footprint: Arc::new(Footprint {
1520				content: AtomicU64::new(0),
1521				fixed: AtomicU64::new(ENTRY_OVERHEAD),
1522				slot: AtomicBool::new(false),
1523			}),
1524			content: 0,
1525			whole: false,
1526			held: AtomicBool::new(false),
1527		}
1528	}
1529
1530	/// Open an empty bill against this account, for bookkeeping the track keeps beside its
1531	/// groups, such as its drop set.
1532	pub(super) fn extra(self: &Arc<Self>) -> Extra {
1533		Extra {
1534			track: Some(self.clone()),
1535			footprint: None,
1536			bytes: AtomicU64::new(0),
1537			state: AtomicU64::new(0),
1538		}
1539	}
1540
1541	/// Open an empty bill against this account for one reader's record, or a subscription's
1542	/// tail ledger.
1543	pub(super) fn reader(self: &Arc<Self>) -> Reader {
1544		Reader {
1545			track: self.clone(),
1546			bytes: 0,
1547		}
1548	}
1549
1550	/// Hand the part of `debt` this track could not pay to its readers, up to what their
1551	/// records and tails bill beyond what they already owe.
1552	pub(super) fn owe_readers(&self, debt: &mut u64) {
1553		let readers = &self.readers;
1554		let mut shifted = 0;
1555		let over = self.pool.records_over();
1556		let _ = readers.debt.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |owed| {
1557			let billed = readers.bytes.load(Ordering::Relaxed);
1558			let room = billed.min(over).saturating_sub(owed);
1559			shifted = room.min(*debt);
1560			(shifted > 0).then_some(owed + shifted)
1561		});
1562		*debt -= shifted;
1563	}
1564
1565	/// Bill `bytes` of a failed group's head while a hand-off holds it for a successor route.
1566	///
1567	/// Readers that stop polling can hold a hand-off indefinitely, so the head is billed
1568	/// like cached content and bounded the same way: `None` when it would take the pool past
1569	/// its target, and [`Pool::hold_head`] has the pool reclaim it like idle content.
1570	pub(super) fn hold(self: &Arc<Self>, bytes: u64) -> Option<Bill> {
1571		if self.pool.used().saturating_add(bytes) > self.pool.target() {
1572			return None;
1573		}
1574		self.pool.add(bytes);
1575		Some(Bill {
1576			track: self.clone(),
1577			bytes,
1578			at: self.pool.now(),
1579		})
1580	}
1581
1582	/// Take everything written since the last call, to be turned into eviction debt.
1583	pub(super) fn take_written(&self) -> u64 {
1584		self.written.swap(0, Ordering::Relaxed)
1585	}
1586
1587	/// Settle eviction debt and expire idle groups from a frame write.
1588	///
1589	/// Called with no group lock held (locks are ordered track then group). Cheap
1590	/// until the byte or time gate crosses: relaxed atomics plus a coarse clock read
1591	/// when expiry is enabled. This is what makes a track that only appends frames to
1592	/// open groups, never inserting another group, still pay its debt and age its
1593	/// idle content out.
1594	///
1595	/// `now` is the coarse tick a cache access on this path just sampled (see
1596	/// [`Charge::add`]), reused so a frame write reads the clock once instead of
1597	/// twice. `None` leaves the gate to sample it, and only if it needs it.
1598	pub(super) fn settle(&self, now: Option<u64>) {
1599		self.settle_inner(now, false);
1600	}
1601
1602	/// Settle eviction debt now if the pool is past its target, without waiting for the
1603	/// write threshold: a reader's record grows by runs, never by enough bytes to cross it.
1604	/// Takes the track lock: call with none held.
1605	pub(super) fn charge_over(&self) {
1606		if self.pool.excess().is_none() {
1607			return;
1608		}
1609		if let Some(state) = self.state.upgrade()
1610			&& let Ok(mut state) = state.write()
1611		{
1612			state.charge_debt();
1613		}
1614	}
1615
1616	/// Settle from [`Pool::sweep`], dating activity and expiring every idle candidate.
1617	pub(super) fn sweep(&self) {
1618		self.settle_inner(None, true);
1619	}
1620
1621	fn settle_inner(&self, now: Option<u64>, full: bool) {
1622		if self.edges.excess().is_some() {
1623			self.edges.reclaim(self);
1624		}
1625		let settle_debt = self.written.load(Ordering::Relaxed) >= WRITE_CHARGE_THRESHOLD;
1626		let scan_expiry = if full {
1627			self.pool.expiry().is_some()
1628		} else {
1629			self.expiry_due(now)
1630		};
1631		if !settle_debt && !scan_expiry {
1632			return;
1633		}
1634		// Counts as a producer while it lives, which is why `track::Producer` gates
1635		// its teardown on its own clone count rather than the state's.
1636		let Some(state) = self.state.upgrade() else {
1637			// An ended track's channel is closed, but a stale consumer can still hold its
1638			// groups: the sweep expires them in place, or they would never go.
1639			if full && scan_expiry {
1640				self.state.read(|state| state.expire_closed(state.expiry_scan_drain()));
1641			}
1642			return;
1643		};
1644		let expiry = if scan_expiry {
1645			let state = state.read();
1646			let scan = if full {
1647				state.expiry_scan_drain()
1648			} else {
1649				state.expiry_scan()
1650			};
1651			state.expiry_mutation_due(scan).then_some(scan)
1652		} else {
1653			None
1654		};
1655		if !settle_debt && expiry.is_none() {
1656			return;
1657		}
1658		if let Ok(mut state) = state.write() {
1659			if settle_debt {
1660				state.charge_debt();
1661			}
1662			if let Some(scan) = expiry {
1663				state.evict_expired_scan(scan);
1664			}
1665		}
1666	}
1667
1668	/// Claim the next rotating window in the track's eviction order.
1669	pub(super) fn next_expiry_scan(&self, width: usize) -> usize {
1670		self.expiry_cursor.fetch_add(width, Ordering::Relaxed)
1671	}
1672
1673	/// Claim the next write-driven expiry scan when its time gate is due.
1674	fn expiry_due(&self, now: Option<u64>) -> bool {
1675		let expiry = self.pool.expiry_ticks();
1676		if expiry == u64::MAX {
1677			return false;
1678		}
1679
1680		// Sampled here, below the gate: a pool with no expiry window returns above
1681		// without ever reading the clock, whether or not a caller had a tick.
1682		let now = now.unwrap_or_else(|| self.pool.now());
1683		let interval = expiry.clamp(1, EXPIRY_SCAN_TICKS);
1684		let deadline = now.saturating_add(interval);
1685		let next = self.next_expiry.load(Ordering::Relaxed);
1686		if now < next {
1687			return false;
1688		}
1689
1690		self.next_expiry
1691			.compare_exchange(next, deadline, Ordering::Relaxed, Ordering::Relaxed)
1692			.is_ok()
1693	}
1694}
1695
1696impl Drop for Track {
1697	fn drop(&mut self) {
1698		if let Some(inner) = &self.edges.0 {
1699			inner.tracks.fetch_sub(1, Ordering::Relaxed);
1700		}
1701		if self
1702			.encoder
1703			.get_mut()
1704			.unwrap_or_else(PoisonError::into_inner)
1705			.take()
1706			.is_some()
1707		{
1708			self.pool.sub(flate::ENCODER_HEAP);
1709			self.pool.count(Class::Pinned, flate::ENCODER_HEAP, false);
1710		}
1711		if let Some(key) = self.sweep.get() {
1712			self.pool.unregister(*key);
1713		}
1714		// Its deadline would otherwise linger in a shared pool until it came due.
1715		if let Some(at) = self.wakes.wall_armed() {
1716			let address = std::ptr::from_ref::<Self>(self) as usize;
1717			self.pool.inner.wall.lock().due.remove(&(at, address));
1718		}
1719	}
1720}
1721
1722/// The bytes a held head of a failed group bills to its track's
1723/// pool, released on drop.
1724pub(super) struct Bill {
1725	track: Arc<Track>,
1726	bytes: u64,
1727	// The coarse tick it was billed at.
1728	at: u64,
1729}
1730
1731impl Bill {
1732	/// Whether the pool's idle window passed since it was billed.
1733	pub(super) fn expired(&self) -> bool {
1734		let pool = &self.track.pool;
1735		pool.now().saturating_sub(self.at) >= pool.expiry_ticks()
1736	}
1737}
1738
1739impl Drop for Bill {
1740	fn drop(&mut self) {
1741		self.track.pool.sub(self.bytes);
1742	}
1743}
1744
1745/// The flag bit in a [`Footprint`]'s counts: set while its bytes are its track's live edge.
1746const EDGE: u64 = 1 << 63;
1747/// The flag bit in a [`Footprint`]'s content: set once its group finished.
1748const FINAL: u64 = 1 << 62;
1749/// The flag bit in a [`Footprint`]'s counts: set while a fill holds its group for a reader.
1750const HELD: u64 = 1 << 61;
1751/// The byte count under a [`Footprint`]'s flags.
1752const BYTES: u64 = !(EDGE | FINAL | HELD);
1753
1754/// Which of the [`Pool`]'s counters a byte counts in, if any.
1755#[derive(Clone, Copy, PartialEq, Eq)]
1756enum Class {
1757	/// A live edge's, which no eviction reclaims while its track lives.
1758	Pinned,
1759	/// A group a fill holds for a reader, spared only while the holds fit.
1760	Held,
1761	/// Anything eviction may take.
1762	Free,
1763}
1764
1765/// Which counter content counted under `flags` falls in: a whole live edge's is pinned, and
1766/// any other held group's held.
1767fn content_class(flags: u64) -> Class {
1768	if flags & (EDGE | FINAL) == EDGE | FINAL {
1769		Class::Pinned
1770	} else if flags & HELD != 0 {
1771		Class::Held
1772	} else {
1773		Class::Free
1774	}
1775}
1776
1777/// Which counter fixed bytes counted under `flags` fall in: a live edge's are pinned, and any
1778/// other held group's held.
1779fn fixed_class(flags: u64) -> Class {
1780	if flags & EDGE != 0 {
1781		Class::Pinned
1782	} else if flags & HELD != 0 {
1783		Class::Held
1784	} else {
1785		Class::Free
1786	}
1787}
1788
1789/// The bytes one cached group bills, across its [`Charge`] and the [`Extra`]s it hands out
1790/// (shared content, inflated copies, codec state), and whether they are its track's live
1791/// edge, which its session's [`Edges`] bill and the [`Pool`] pins.
1792///
1793/// Its content bills the session, and is pinned once its group finished: a live edge still
1794/// growing sheds its front under pool debt, while a whole one is what a new reader starts
1795/// from. Its fixed costs, the [`ENTRY_OVERHEAD`] and codec state, are always pinned and
1796/// never bill the session: they scale with the tracks a session holds, which its stream
1797/// credit bounds, and shedding can never free them.
1798///
1799/// Each count is one atomic holding its flags in its top bits (no group bills 2^62 bytes),
1800/// so a byte added while a flag flips is counted exactly once, by whichever came last.
1801#[derive(Default)]
1802pub(super) struct Footprint {
1803	content: AtomicU64,
1804	fixed: AtomicU64,
1805	// Whether this copy is itself its track's cached live edge, not billed for a sibling that
1806	// is. Atomic so a reader's progress can check it outside the group's lock.
1807	slot: AtomicBool,
1808}
1809
1810impl Footprint {
1811	/// Whether this copy is itself its track's cached live edge.
1812	fn slot(&self) -> bool {
1813		self.slot.load(Ordering::Relaxed)
1814	}
1815
1816	/// Count `n` more content bytes, returning whether they bill the session.
1817	fn add(&self, track: &Track, n: u64) -> bool {
1818		let prior = self.content.fetch_add(n, Ordering::Relaxed);
1819		let edge = prior & EDGE != 0;
1820		if edge {
1821			track.edges.add(n);
1822		}
1823		track.pool.count(content_class(prior), n, true);
1824		edge
1825	}
1826
1827	/// Count `n` fewer content bytes, no more than it holds.
1828	fn sub(&self, track: &Track, n: u64) {
1829		let (prior, taken) = Self::take(&self.content, n);
1830		if prior & EDGE != 0 {
1831			track.edges.sub(taken);
1832		}
1833		track.pool.count(content_class(prior), taken, false);
1834	}
1835
1836	/// Count `n` more fixed bytes.
1837	fn add_fixed(&self, track: &Track, n: u64) {
1838		let prior = self.fixed.fetch_add(n, Ordering::Relaxed);
1839		track.pool.count(fixed_class(prior), n, true);
1840	}
1841
1842	/// Count `n` fewer fixed bytes, no more than it holds.
1843	fn sub_fixed(&self, track: &Track, n: u64) {
1844		let (prior, taken) = Self::take(&self.fixed, n);
1845		track.pool.count(fixed_class(prior), taken, false);
1846	}
1847
1848	/// The group finished, so its content no longer grows.
1849	fn finish(&self, track: &Track) {
1850		self.flag_content(track, FINAL, true);
1851	}
1852
1853	fn promote(&self, track: &Track) {
1854		self.flag(track, EDGE, true);
1855	}
1856
1857	fn demote(&self, track: &Track) {
1858		self.flag(track, EDGE, false);
1859	}
1860
1861	/// Count every byte held while a fill holds the group for a reader, or stop.
1862	fn hold(&self, track: &Track, held: bool) {
1863		self.flag(track, HELD, held);
1864	}
1865
1866	/// Set or clear `flag` on both counts, moving their bytes between the session's edges and
1867	/// the pool's counters as they change.
1868	fn flag(&self, track: &Track, flag: u64, on: bool) {
1869		self.flag_content(track, flag, on);
1870		let prior = Self::set(&self.fixed, flag, on);
1871		let now = Self::flagged(prior, flag, on);
1872		Self::reclass(track, prior & BYTES, fixed_class(prior), fixed_class(now));
1873	}
1874
1875	/// Move `bytes` from the pool's counter for `from` to the one for `to`.
1876	fn reclass(track: &Track, bytes: u64, from: Class, to: Class) {
1877		if from != to {
1878			track.pool.count(from, bytes, false);
1879			track.pool.count(to, bytes, true);
1880		}
1881	}
1882
1883	fn flag_content(&self, track: &Track, flag: u64, on: bool) {
1884		let prior = Self::set(&self.content, flag, on);
1885		let now = Self::flagged(prior, flag, on);
1886		let bytes = prior & BYTES;
1887		match (prior & EDGE != 0, now & EDGE != 0) {
1888			(false, true) => track.edges.add(bytes),
1889			(true, false) => track.edges.sub(bytes),
1890			_ => {}
1891		}
1892		Self::reclass(track, bytes, content_class(prior), content_class(now));
1893	}
1894
1895	/// Set or clear `flag` on `count`, returning its prior value.
1896	fn set(count: &AtomicU64, flag: u64, on: bool) -> u64 {
1897		match on {
1898			true => count.fetch_or(flag, Ordering::Relaxed),
1899			false => count.fetch_and(!flag, Ordering::Relaxed),
1900		}
1901	}
1902
1903	fn flagged(prior: u64, flag: u64, on: bool) -> u64 {
1904		match on {
1905			true => prior | flag,
1906			false => prior & !flag,
1907		}
1908	}
1909
1910	/// Take up to `n` from `count`, returning its prior value and what it took.
1911	fn take(count: &AtomicU64, n: u64) -> (u64, u64) {
1912		let mut taken = 0;
1913		let prior = count
1914			.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |prior| {
1915				taken = n.min(prior & BYTES);
1916				Some(prior - taken)
1917			})
1918			.expect("always updates");
1919		(prior, taken)
1920	}
1921}
1922
1923/// The [`Footprint`]s of every copy of one group that shares its content, which bill one
1924/// another's frames: a frame bills whichever copy wrote it first, and any copy may hold it.
1925///
1926/// So they bill the session together: while one copy is itself its track's cached live
1927/// edge, they all do, a copy that aborted included, since its frames may still be what the
1928/// live copy holds; once none is, none does. Once one finished the whole group, they are all
1929/// whole. While a fill holds one, they are all held, for the same reason.
1930#[derive(Default)]
1931pub(super) struct Siblings(Mutex<Vec<Sibling>>);
1932
1933struct Sibling {
1934	track: Arc<Track>,
1935	footprint: Arc<Footprint>,
1936	// Whether this copy is itself the live edge, not billed for a sibling.
1937	edge: bool,
1938	// Whether this copy finished the whole group, not just a range a transport bound cut.
1939	whole: bool,
1940	// Whether a fill holds this copy itself, not pinned for a sibling.
1941	held: bool,
1942}
1943
1944impl Siblings {
1945	/// Record whether `charge`'s copy is itself the live edge, adding it if new, and bill
1946	/// every copy to match: after a copy joins, is promoted, leaves the cache, or is cleared.
1947	pub(super) fn update(&self, charge: &Charge) {
1948		let Some(track) = &charge.track else {
1949			return;
1950		};
1951		let mut siblings = self.0.lock().unwrap_or_else(PoisonError::into_inner);
1952		match siblings
1953			.iter_mut()
1954			.find(|sibling| Arc::ptr_eq(&sibling.footprint, &charge.footprint))
1955		{
1956			Some(sibling) => {
1957				sibling.edge = charge.footprint.slot();
1958				sibling.whole = charge.whole;
1959				sibling.held = charge.is_held();
1960			}
1961			None => siblings.push(Sibling {
1962				track: track.clone(),
1963				footprint: charge.footprint.clone(),
1964				edge: charge.footprint.slot(),
1965				whole: charge.whole,
1966				held: charge.is_held(),
1967			}),
1968		}
1969		Self::bill(&mut siblings);
1970	}
1971
1972	/// Stop billing every copy to the session: one leaving the live edge, as its slot does,
1973	/// takes them all.
1974	pub(super) fn demote(&self) {
1975		let mut siblings = self.0.lock().unwrap_or_else(PoisonError::into_inner);
1976		for sibling in siblings.iter_mut() {
1977			sibling.edge = false;
1978		}
1979		Self::bill(&mut siblings);
1980	}
1981
1982	/// Bill every copy while any is the live edge, pin every copy's content once any finished
1983	/// the whole group, and count every byte held while a fill holds any, since a copy's frames
1984	/// may be what that sibling holds. Forgets copies nothing bills any more.
1985	fn bill(siblings: &mut Vec<Sibling>) {
1986		siblings.retain(|sibling| Arc::strong_count(&sibling.footprint) > 1);
1987		let edge = siblings.iter().any(|sibling| sibling.edge);
1988		let held = siblings.iter().any(|sibling| sibling.held);
1989		if siblings.iter().any(|sibling| sibling.whole) {
1990			for sibling in siblings.iter() {
1991				sibling.footprint.finish(&sibling.track);
1992			}
1993		}
1994		for sibling in siblings.iter() {
1995			match edge {
1996				true => sibling.footprint.promote(&sibling.track),
1997				false => sibling.footprint.demote(&sibling.track),
1998			}
1999			sibling.footprint.hold(&sibling.track, held);
2000		}
2001	}
2002}
2003
2004/// The RAII byte accounting for one cached group, owned by the group's state.
2005///
2006/// `add`/`sub` mirror the group's cached payload bytes into the pool with plain
2007/// atomics, and every charged byte (overhead included) is also accumulated into the
2008/// track's account, which the track drains into eviction debt on its next write. The
2009/// charge also owns the group's sample in the pool's access mean, so the sample lives
2010/// exactly as long as the cached bytes do: aborting or dropping the group removes both,
2011/// no matter who does it or when. The default charge is detached: it belongs to no
2012/// account and every operation is a no-op.
2013#[derive(Default)]
2014pub(super) struct Charge {
2015	track: Option<Arc<Track>>,
2016	// Bytes currently charged, including ENTRY_OVERHEAD, released on drop.
2017	bytes: u64,
2018	// The group's last-access stamp, shared with the handles that read it during a
2019	// track scan. Only ever written here, under the group's state lock.
2020	access: Arc<Access>,
2021	// Whether `access` is currently a sample in the pool's access mean, i.e. the
2022	// group is in the evictable population. A plain bool: it is only read while
2023	// updating the mean, which the owning state's lock already serializes.
2024	counted: bool,
2025	// Every byte the group bills, its extras' included, and whether they bill its session's
2026	// live edges.
2027	footprint: Arc<Footprint>,
2028	// The part of `bytes` in `footprint`: content, its fixed overhead left out.
2029	content: u64,
2030	// Whether this copy finished the whole group, which makes its siblings whole too.
2031	whole: bool,
2032	// Whether a fill holds this copy for a reader, which holds its siblings too. Atomic, since a
2033	// hold goes through a shared guard.
2034	held: AtomicBool,
2035}
2036
2037/// The tick of one cached group's last cache access: its creation, every write, and
2038/// every read (group delivery, frame reads, FETCH hits, a fetched backfill's birth).
2039/// Eviction protection and age expiry both key off it.
2040///
2041/// Shared, so a track scan can read it without entering the group's state. The
2042/// eviction and expiry walks run under the track lock and weigh every candidate
2043/// against [`Pool::average`], so reaching this through the group lock would nest one
2044/// lock inside the other once per candidate.
2045///
2046/// Atomic for a second reason on the write side: a kio write guard's release notifies
2047/// every parked consumer, and a mere cache access must not wake anyone, so [`Charge`]
2048/// stamps this through a shared guard.
2049#[derive(Default)]
2050pub(super) struct Access {
2051	stamp: AtomicU64,
2052	expires: AtomicU64,
2053}
2054
2055impl Access {
2056	fn new(stamp: u64) -> Self {
2057		Self {
2058			stamp: AtomicU64::new(stamp),
2059			expires: AtomicU64::new(u64::MAX),
2060		}
2061	}
2062
2063	/// The stamp, tie-breaking bits included.
2064	pub(super) fn get(&self) -> u64 {
2065		self.stamp.load(Ordering::Relaxed)
2066	}
2067
2068	/// Clear the expiration timestamp until a cleanup pass observes this access.
2069	pub(super) fn touch(&self) {
2070		self.expires.store(u64::MAX, Ordering::Relaxed);
2071	}
2072
2073	/// The last access tick, assigning undated activity only during cleanup.
2074	pub(super) fn tick(&self, now: Option<u64>) -> Option<u64> {
2075		let tick = match now {
2076			Some(now) => match self
2077				.expires
2078				.compare_exchange(u64::MAX, now, Ordering::Relaxed, Ordering::Relaxed)
2079			{
2080				Ok(_) => now,
2081				Err(tick) => tick,
2082			},
2083			None => self.expires.load(Ordering::Relaxed),
2084		};
2085		(tick != u64::MAX).then_some(tick)
2086	}
2087
2088	/// Advance to `target` if it is newer, returning the previous stamp.
2089	fn bump(&self, target: u64) -> u64 {
2090		// `fetch_max` keeps the stamp monotone, and its prior value makes the
2091		// paired mean update exact even for back-to-back accesses.
2092		self.stamp.fetch_max(target, Ordering::Relaxed)
2093	}
2094}
2095
2096impl Charge {
2097	/// Charge `n` more payload bytes, counting them as written.
2098	///
2099	/// A write is also an access: it restarts the retention clock and keeps an
2100	/// actively-growing group (a straggler or backfill still being filled) from
2101	/// being evicted or expired mid-write, even within the same coarse tick as
2102	/// content that was merely inserted.
2103	///
2104	/// Returns the coarse tick it stamped, which the caller hands to
2105	/// [`Track::settle`] so the write path reads the clock once rather than twice.
2106	/// `None` when the charge is detached and stamped nothing.
2107	pub(super) fn add(&mut self, n: u64) -> Option<u64> {
2108		if let Some(track) = &self.track {
2109			track.pool.add(n);
2110			track.written.fetch_add(n, Ordering::Relaxed);
2111			if self.footprint.add(track, n) {
2112				track.edge_grew();
2113			}
2114			self.bytes += n;
2115			self.content += n;
2116		}
2117		self.touch(WRITE_BOOST)
2118	}
2119
2120	/// Release `n` charged bytes the group dropped while still cached, without an access.
2121	pub(super) fn sub(&mut self, n: u64) {
2122		if let Some(track) = &self.track {
2123			let n = n.min(self.bytes);
2124			track.pool.sub(n);
2125			let content = n.min(self.content);
2126			self.footprint.sub(track, content);
2127			self.footprint.sub_fixed(track, n - content);
2128			self.content -= content;
2129			self.bytes -= n;
2130		}
2131	}
2132
2133	/// The group's full cached footprint: payload bytes plus overhead.
2134	pub(super) fn size(&self) -> u64 {
2135		self.bytes
2136	}
2137
2138	/// Move already-accounted payload to a shared content owner without recording a write.
2139	pub(super) fn transfer(&mut self, bytes: u64) -> Extra {
2140		if self.track.is_none() {
2141			return Extra::default();
2142		}
2143		self.bytes = self
2144			.bytes
2145			.checked_sub(bytes)
2146			.expect("transferred payload must already be charged");
2147		// Still in the footprint, now through the extra.
2148		self.content = self.content.saturating_sub(bytes);
2149		Extra {
2150			track: self.track.clone(),
2151			footprint: Some(self.footprint.clone()),
2152			bytes: AtomicU64::new(bytes),
2153			state: AtomicU64::new(0),
2154		}
2155	}
2156
2157	/// The shared handle to this group's last-access stamp, so the group can read it
2158	/// without taking the state lock this charge lives behind.
2159	pub(super) fn access(&self) -> Arc<Access> {
2160		self.access.clone()
2161	}
2162
2163	/// An [`Extra`] against this charge's account, detached when the charge is.
2164	pub(super) fn extra(&self) -> Extra {
2165		Extra {
2166			track: self.track.clone(),
2167			footprint: Some(self.footprint.clone()),
2168			bytes: AtomicU64::new(0),
2169			state: AtomicU64::new(0),
2170		}
2171	}
2172
2173	/// Tick of the group's last cache access.
2174	pub(super) fn accessed(&self) -> u64 {
2175		self.access.get()
2176	}
2177
2178	/// Enter the group into the evictable population (demoted from the live edge,
2179	/// or inserted behind it), sampling its access time into the pool's mean.
2180	/// Idempotent.
2181	pub(super) fn demote(&mut self) {
2182		if let Some(track) = &self.track
2183			&& !self.counted
2184		{
2185			track.pool.access_insert(self.accessed());
2186			self.counted = true;
2187		}
2188		self.leave_edge();
2189	}
2190
2191	/// Stop billing the session, as the group leaves the cache, without entering the
2192	/// evictable population it is no longer part of.
2193	pub(super) fn leave_edge(&mut self) {
2194		if let Some(track) = &self.track {
2195			self.footprint.demote(track);
2196		}
2197		self.footprint.slot.store(false, Ordering::Relaxed);
2198	}
2199
2200	/// Bill the group, its extras included, to its session's [`Edges`] as its track's cached
2201	/// live edge, which eviction never takes while the track lives. Idempotent; a no-op once
2202	/// demoted.
2203	pub(super) fn promote(&mut self) {
2204		if let Some(track) = &self.track
2205			&& !self.counted
2206		{
2207			self.footprint.promote(track);
2208			self.footprint.slot.store(true, Ordering::Relaxed);
2209		}
2210	}
2211
2212	/// Count every byte the group bills held while a fill holds it for a reader, which eviction
2213	/// and shedding pass over until the reader takes it, while the holds fit, or stop. Frames a sibling copy wrote first
2214	/// bill that copy, so update its [`Siblings`] after.
2215	pub(super) fn hold(&self, held: bool) {
2216		self.held.store(held, Ordering::Relaxed);
2217		if let Some(track) = &self.track {
2218			self.footprint.hold(track, held);
2219		}
2220	}
2221
2222	/// Whether a fill holds this copy for a reader.
2223	fn is_held(&self) -> bool {
2224		self.held.load(Ordering::Relaxed)
2225	}
2226
2227	/// This copy finished, the `whole` group or only a range a transport bound cut: pin its
2228	/// content while it is the live edge, which no longer grows.
2229	pub(super) fn finish(&mut self, whole: bool) {
2230		if let Some(track) = &self.track {
2231			self.footprint.finish(track);
2232		}
2233		self.whole |= whole;
2234	}
2235
2236	/// Whether this copy finished the whole group.
2237	#[cfg(test)]
2238	pub(super) fn is_whole(&self) -> bool {
2239		self.whole
2240	}
2241
2242	/// Record a cache read: a delivered or fetched group, a frame read, or a
2243	/// fetched backfill's birth. `&self` so the read paths can stamp through a
2244	/// shared guard without waking parked consumers.
2245	pub(super) fn refresh(&self) {
2246		self.touch(READ_BOOST);
2247	}
2248
2249	/// Record a write that charges no new bytes (a chunk written into an
2250	/// already-charged in-flight frame): restarts the retention clock like any
2251	/// other write. `&mut self` deliberately: reaching it through a kio write
2252	/// guard marks the guard modified, so its release wakes parked readers. Returns
2253	/// the stamped tick like [`Self::add`].
2254	pub(super) fn record_write(&mut self) -> Option<u64> {
2255		self.touch(WRITE_BOOST)
2256	}
2257
2258	/// Advance the last-access stamp to the current clock tick with `boost` priority.
2259	///
2260	/// The boost breaks ties within one coarse tick: written content outranks
2261	/// merely-inserted content, and explicitly read content outranks both, so a
2262	/// same-tick access still reads as strictly newer than the population mean of
2263	/// weaker accesses. Idempotent within a tick (monotone, never regressing), so
2264	/// repeated accesses remain idempotent without advancing the expiry clock.
2265	/// Returns the tick it read, or `None` when the charge is detached.
2266	fn touch(&self, boost: u64) -> Option<u64> {
2267		let track = self.track.as_ref()?;
2268		// Cleanup assigns the next supplied timestamp to this access.
2269		self.access.touch();
2270		let target = track.pool.stamp(boost);
2271		let prev = self.access.bump(target);
2272		if target > prev && self.counted {
2273			track.pool.access_refresh(prev, target);
2274		}
2275		Some(target >> ACCESS_SHIFT)
2276	}
2277
2278	/// The track account this charge bills, unless it is detached.
2279	pub(super) fn account(&self) -> Option<&Arc<Track>> {
2280		self.track.as_ref()
2281	}
2282
2283	/// Release everything this charge holds: bytes, overhead, a fill's hold, and the
2284	/// access sample. Idempotent; used when the group aborts and clears its frames.
2285	pub(super) fn clear(&mut self) {
2286		self.leave_edge();
2287		self.hold(false);
2288		if let Some(track) = &self.track {
2289			self.footprint.sub(track, self.content);
2290			self.footprint.sub_fixed(track, self.bytes - self.content);
2291			self.content = 0;
2292			track.pool.sub(self.bytes);
2293			self.bytes = 0;
2294			if self.counted {
2295				track.pool.access_remove(self.accessed());
2296				self.counted = false;
2297			}
2298		}
2299	}
2300}
2301
2302impl Drop for Charge {
2303	fn drop(&mut self) {
2304		self.clear();
2305	}
2306}
2307
2308/// What one reader's record, or one subscription's tail ledger, bills to its track's account,
2309/// and its share of the debt the track could not pay, which each pays by folding. Released
2310/// on drop.
2311pub(crate) struct Reader {
2312	track: Arc<Track>,
2313	bytes: u64,
2314}
2315
2316impl Reader {
2317	/// Bill `bytes` in all, settling the track's debt after a growth: call with no track lock
2318	/// held.
2319	pub(crate) fn set(&mut self, bytes: u64) {
2320		if bytes == self.bytes {
2321			return;
2322		}
2323		let readers = &self.track.readers;
2324		let billed = &readers.bytes;
2325		if bytes > self.bytes {
2326			let grown = bytes - self.bytes;
2327			billed.fetch_add(grown, Ordering::Relaxed);
2328			self.track.pool.inner.recorded.fetch_add(grown, Ordering::Relaxed);
2329			self.track.pool.add(grown);
2330			self.track.written.fetch_add(grown, Ordering::Relaxed);
2331			self.bytes = bytes;
2332			self.track.charge_over();
2333		} else {
2334			// Whatever a record frees pays toward its readers' debt, however it shrank.
2335			let shrunk = self.bytes - bytes;
2336			billed.fetch_sub(shrunk, Ordering::Relaxed);
2337			let _ = readers.debt.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |debt| {
2338				(debt > 0).then(|| debt.saturating_sub(shrunk))
2339			});
2340			self.track.pool.inner.recorded.fetch_sub(shrunk, Ordering::Relaxed);
2341			self.track.pool.sub(shrunk);
2342			self.bytes = bytes;
2343		}
2344	}
2345
2346	/// The debt the track's readers owe, never more than records and tails are over the
2347	/// target, and forgiven once they are not: nothing needs the room from them any more.
2348	pub(crate) fn debt(&self) -> u64 {
2349		let readers = &self.track.readers;
2350		let over = self.track.pool.records_over();
2351		if over == 0 {
2352			readers.debt.store(0, Ordering::Relaxed);
2353			return 0;
2354		}
2355		readers.debt.load(Ordering::Relaxed).min(over)
2356	}
2357}
2358
2359impl std::fmt::Debug for Reader {
2360	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2361		f.debug_struct("Reader")
2362			.field("bytes", &self.bytes)
2363			.finish_non_exhaustive()
2364	}
2365}
2366
2367impl Drop for Reader {
2368	fn drop(&mut self) {
2369		self.set(0);
2370	}
2371}
2372
2373/// Bytes a group keeps beside its cached frames, billed to the same pool and account as
2374/// its [`Charge`] but reachable outside the group's write lock: a compressed group's
2375/// inflated copy, which its readers build, and its codec state. Released on [`Self::clear`] or drop.
2376///
2377/// Its owner serializes the changes; the count is atomic so the eviction walk can size
2378/// the group without that owner's lock.
2379#[derive(Default)]
2380pub(super) struct Extra {
2381	track: Option<Arc<Track>>,
2382	// The footprint of the group it was opened from, so its bytes bill that group's live
2383	// edge; `None` for the track's own bookkeeping.
2384	footprint: Option<Arc<Footprint>>,
2385	bytes: AtomicU64,
2386	// The part of `bytes` that is codec state rather than content, kept out of the footprint:
2387	// a fixed cost per group, like its entry overhead, so it bills the pool but not the
2388	// session's live edges, which shedding could never bring back under budget.
2389	state: AtomicU64,
2390}
2391
2392impl Extra {
2393	/// Count `n` content bytes in, or out of, the owning group's footprint.
2394	fn footprint(&self, track: &Arc<Track>, n: u64, add: bool) {
2395		if let Some(footprint) = &self.footprint {
2396			match add {
2397				true => {
2398					if footprint.add(track, n) {
2399						track.edge_grew();
2400					}
2401				}
2402				false => footprint.sub(track, n),
2403			}
2404		}
2405	}
2406
2407	/// Count `n` bytes of codec state in, or out of, the owning group's footprint.
2408	fn footprint_fixed(&self, track: &Track, n: u64, add: bool) {
2409		if let Some(footprint) = &self.footprint {
2410			match add {
2411				true => footprint.add_fixed(track, n),
2412				false => footprint.sub_fixed(track, n),
2413			}
2414		}
2415	}
2416
2417	/// Take this track's spare encoder with its charge, or bill a new one.
2418	pub(super) fn take_encoder(&self) -> flate::Encoder {
2419		if let Some(track) = &self.track {
2420			let encoder = track.encoder.lock().unwrap_or_else(PoisonError::into_inner).take();
2421			if let Some(mut encoder) = encoder {
2422				// Moving existing heap is not a write and must not accrue eviction debt.
2423				self.bytes.fetch_add(flate::ENCODER_HEAP, Ordering::Relaxed);
2424				self.state.fetch_add(flate::ENCODER_HEAP, Ordering::Relaxed);
2425				track.pool.count(Class::Pinned, flate::ENCODER_HEAP, false);
2426				self.footprint_fixed(track, flate::ENCODER_HEAP, true);
2427				encoder.reset();
2428				return encoder;
2429			}
2430		}
2431		self.add_state(flate::ENCODER_HEAP);
2432		flate::Encoder::new()
2433	}
2434
2435	/// Park a finished encoder and its charge, dropping it if the track has a spare.
2436	pub(super) fn park_encoder(&self, encoder: flate::Encoder) {
2437		if let Some(track) = &self.track {
2438			let mut spare = track.encoder.lock().unwrap_or_else(PoisonError::into_inner);
2439			if spare.is_none() {
2440				self.bytes.fetch_sub(flate::ENCODER_HEAP, Ordering::Relaxed);
2441				self.state.fetch_sub(flate::ENCODER_HEAP, Ordering::Relaxed);
2442				self.footprint_fixed(track, flate::ENCODER_HEAP, false);
2443				// Only the track's end frees a spare.
2444				track.pool.count(Class::Pinned, flate::ENCODER_HEAP, true);
2445				*spare = Some(encoder);
2446				return;
2447			}
2448		}
2449		self.sub_state(flate::ENCODER_HEAP);
2450	}
2451
2452	/// Bill `n` more bytes of codec state, which the session's live edges do not count.
2453	pub(super) fn add_state(&self, n: u64) {
2454		if let Some(track) = &self.track {
2455			track.pool.add(n);
2456			track.written.fetch_add(n, Ordering::Relaxed);
2457			self.bytes.fetch_add(n, Ordering::Relaxed);
2458			self.state.fetch_add(n, Ordering::Relaxed);
2459			self.footprint_fixed(track, n, true);
2460		}
2461	}
2462
2463	/// Release `n` billed bytes of codec state.
2464	pub(super) fn sub_state(&self, n: u64) {
2465		if let Some(track) = &self.track {
2466			let prior = self
2467				.state
2468				.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |state| {
2469					Some(state.saturating_sub(n))
2470				})
2471				.expect("always updates");
2472			self.bytes.fetch_sub(prior.min(n), Ordering::Relaxed);
2473			track.pool.sub(prior.min(n));
2474			self.footprint_fixed(track, prior.min(n), false);
2475		}
2476	}
2477
2478	/// Bill `n` more bytes.
2479	pub(super) fn add(&self, n: u64) {
2480		if let Some(track) = &self.track {
2481			track.pool.add(n);
2482			track.written.fetch_add(n, Ordering::Relaxed);
2483			self.bytes.fetch_add(n, Ordering::Relaxed);
2484			self.footprint(track, n, true);
2485		}
2486	}
2487
2488	/// Count `n` more bytes that what an eviction freed paid for already, so they accrue no
2489	/// debt of their own.
2490	pub(super) fn add_paid(&self, n: u64) {
2491		if let Some(track) = &self.track {
2492			track.pool.add(n);
2493			self.bytes.fetch_add(n, Ordering::Relaxed);
2494			self.footprint(track, n, true);
2495		}
2496	}
2497
2498	/// Settle the track's eviction debt, taking its lock: call with no group lock held.
2499	pub(super) fn settle(&self) {
2500		if let Some(track) = &self.track {
2501			track.settle(None);
2502		}
2503	}
2504
2505	/// Bytes currently billed.
2506	pub(super) fn size(&self) -> u64 {
2507		self.bytes.load(Ordering::Relaxed)
2508	}
2509
2510	/// Release `n` billed bytes.
2511	pub(super) fn sub(&self, n: u64) {
2512		if let Some(track) = &self.track {
2513			let prior = self
2514				.bytes
2515				.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |bytes| {
2516					Some(bytes.saturating_sub(n))
2517				})
2518				.expect("always updates");
2519			track.pool.sub(prior.min(n));
2520			self.footprint(track, prior.min(n), false);
2521		}
2522	}
2523
2524	/// Release every billed byte.
2525	pub(super) fn clear(&self) {
2526		if let Some(track) = &self.track {
2527			let bytes = self.bytes.swap(0, Ordering::Relaxed);
2528			let state = self.state.swap(0, Ordering::Relaxed);
2529			track.pool.sub(bytes);
2530			self.footprint(track, bytes.saturating_sub(state), false);
2531			self.footprint_fixed(track, state, false);
2532		}
2533	}
2534}
2535
2536impl Drop for Extra {
2537	fn drop(&mut self) {
2538		self.clear();
2539	}
2540}
2541
2542#[cfg(test)]
2543mod test {
2544	use super::*;
2545
2546	fn charge(pool: &Pool) -> Charge {
2547		// No track behind the account: nothing here settles debt, it just accounts.
2548		Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new()).charge()
2549	}
2550
2551	fn bounded(capacity: u64) -> Pool {
2552		let config = Config::default().with_capacity(capacity).with_expiry(DEFAULT_EXPIRY);
2553		Pool::new(config)
2554	}
2555
2556	/// Reuse transfers existing heap, concurrent users allocate separately, and only
2557	/// one finished encoder stays parked until the account's final owner drops.
2558	#[test]
2559	fn encoder_spare_transfers_its_charge_without_write_debt() {
2560		let pool = Pool::unbounded();
2561		let charge = charge(&pool);
2562		let first = charge.extra();
2563		let second = charge.extra();
2564		let account = charge.track.as_ref().unwrap();
2565		account.take_written();
2566		let encoder = first.take_encoder();
2567		let concurrent = second.take_encoder();
2568		assert_eq!(pool.used(), ENTRY_OVERHEAD + 2 * flate::ENCODER_HEAP);
2569		assert_eq!(account.take_written(), 2 * flate::ENCODER_HEAP);
2570
2571		first.park_encoder(encoder);
2572		assert_eq!(first.size(), 0);
2573		assert_eq!(pool.used(), ENTRY_OVERHEAD + 2 * flate::ENCODER_HEAP);
2574		let encoder = first.take_encoder();
2575		assert_eq!(first.size(), flate::ENCODER_HEAP);
2576		assert_eq!(account.take_written(), 0, "reuse must not inflate write debt");
2577		first.park_encoder(encoder);
2578		second.park_encoder(concurrent);
2579		assert_eq!(second.size(), 0);
2580		assert_eq!(pool.used(), ENTRY_OVERHEAD + flate::ENCODER_HEAP, "only one spare");
2581
2582		// A group and its inflated copy may outlive the track. They still own its
2583		// account, so the parked encoder stays billed until that last owner drops.
2584		drop(charge);
2585		assert_eq!(pool.used(), flate::ENCODER_HEAP);
2586		drop(first);
2587		assert_eq!(pool.used(), flate::ENCODER_HEAP);
2588		drop(second);
2589		assert_eq!(pool.used(), 0);
2590	}
2591
2592	struct Flag(std::sync::atomic::AtomicBool);
2593
2594	impl std::task::Wake for Flag {
2595		fn wake(self: Arc<Self>) {
2596			self.0.store(true, Ordering::SeqCst);
2597		}
2598	}
2599
2600	fn flag() -> (Arc<Flag>, kio::Waiter) {
2601		let flag = Arc::new(Flag(Default::default()));
2602		let waiter = kio::Waiter::new(std::task::Waker::from(flag.clone()));
2603		(flag, waiter)
2604	}
2605
2606	/// A wall-clock deadline armed after the driver collected wakes it to collect again by
2607	/// then, and that collection releases the read parked on it. Before any collection,
2608	/// nothing would release it, so the read waits for the first one to arm it then.
2609	#[test]
2610	fn wall_deadlines_wake_the_driver_and_then_the_read() {
2611		let pool = Pool::unbounded();
2612		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2613		let now = super::super::clock::wall();
2614		let at = now.saturating_add(Duration::from_secs(1));
2615		let (read, reading) = flag();
2616		track.watch_wall(at, &reading);
2617
2618		let (driver, driving) = flag();
2619		assert_eq!(pool.poll(now, &driving), None, "an undriven pool indexes nothing");
2620		assert!(
2621			read.0.load(Ordering::SeqCst),
2622			"the first collection never woke the read"
2623		);
2624		read.0.store(false, Ordering::SeqCst);
2625		track.watch_wall(at, &reading);
2626		assert!(
2627			driver.0.load(Ordering::SeqCst),
2628			"the driver slept through an earlier deadline"
2629		);
2630		assert_eq!(pool.poll(now, &driving), Some(at));
2631
2632		pool.poll(at.saturating_sub(Duration::from_millis(1)), &driving);
2633		assert!(!read.0.load(Ordering::SeqCst), "released early");
2634		assert_eq!(pool.poll(at, &driving), None);
2635		assert!(read.0.load(Ordering::SeqCst), "the read was never released");
2636	}
2637
2638	/// A fresh driver must hear deadlines armed after an empty collection, including
2639	/// after the previous driver was dropped or a prior deadline drained its wake list.
2640	#[test]
2641	fn replacement_drivers_hear_new_deadlines() {
2642		let pool = Pool::unbounded();
2643		let now = super::super::clock::wall();
2644		pool.poll(now, &kio::Waiter::noop());
2645		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2646		let (read, reading) = flag();
2647		let (driver, driving) = flag();
2648		assert_eq!(pool.poll(now, &driving), None);
2649		let at = now.saturating_add(Duration::from_secs(1));
2650		track.watch_wall(at, &reading);
2651		assert!(driver.0.swap(false, Ordering::SeqCst));
2652		assert_eq!(pool.poll(at, &driving), None);
2653		assert!(read.0.swap(false, Ordering::SeqCst));
2654		track.watch_wall(at.saturating_add(Duration::from_secs(1)), &reading);
2655		assert!(driver.0.load(Ordering::SeqCst), "the drained list was never rearmed");
2656	}
2657
2658	/// Wall time can lead a lagging driver's sample, while another driver can supply
2659	/// future time. Neither a new driver nor a backward sample may rewind expiration.
2660	#[kio::test]
2661	async fn wall_deadlines_use_the_later_of_ambient_and_driven_time() {
2662		let pool = Pool::unbounded();
2663		let now = kio::clock::now();
2664		let waiter = kio::Waiter::noop();
2665		pool.poll(now, &waiter);
2666		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2667		let (read, reading) = flag();
2668		let at = now.saturating_add(Duration::from_secs(1));
2669		track.watch_wall(at, &reading);
2670		kio::clock::sleep(Duration::from_secs(1)).await;
2671		assert_eq!(pool.poll(now, &waiter), None);
2672		assert!(read.0.swap(false, Ordering::SeqCst), "ambient time was ignored");
2673
2674		let future = at.saturating_add(Duration::from_secs(1));
2675		track.watch_wall(future, &reading);
2676		assert_eq!(pool.poll(future, &waiter), None);
2677		assert!(read.0.swap(false, Ordering::SeqCst), "driven time was ignored");
2678		let tick = pool.now();
2679		pool.poll(now, &waiter);
2680		assert_eq!(pool.now_wall(), future);
2681		assert_eq!(pool.now(), tick);
2682	}
2683
2684	/// A track indexes one wall-clock deadline, its earliest, and takes it along when dropped.
2685	#[test]
2686	fn a_dropped_track_leaves_the_wall_index() {
2687		let pool = Pool::unbounded();
2688		let now = super::super::clock::wall();
2689		pool.poll(now, &kio::Waiter::noop());
2690		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2691		let (_read, reading) = flag();
2692		track.watch_wall(now.saturating_add(Duration::from_secs(2)), &reading);
2693		track.watch_wall(now.saturating_add(Duration::from_secs(1)), &reading);
2694		assert_eq!(pool.inner.wall.lock().due.len(), 1, "the later deadline lingers");
2695
2696		drop(track);
2697		assert!(pool.inner.wall.lock().due.is_empty(), "the dropped track lingers");
2698	}
2699
2700	#[test]
2701	fn unbounded_never_accrues() {
2702		let pool = Pool::unbounded();
2703		let mut charge = charge(&pool);
2704		charge.add(1 << 40);
2705		assert_eq!(pool.accrue(1 << 30), None);
2706		assert_eq!(pool.used(), (1 << 40) + ENTRY_OVERHEAD);
2707		drop(charge);
2708		assert_eq!(pool.used(), 0);
2709	}
2710
2711	#[test]
2712	fn weak_follows_the_last_strong_handle() {
2713		let pool = bounded(1000);
2714		let clone = pool.clone();
2715		let weak = pool.downgrade();
2716
2717		drop(pool);
2718		let upgraded = weak.upgrade().expect("a strong handle remains");
2719		assert!(upgraded.same_pool(&clone));
2720
2721		drop(upgraded);
2722		drop(clone);
2723		assert!(weak.upgrade().is_none());
2724	}
2725
2726	#[test]
2727	fn accrue_none_under_capacity() {
2728		let pool = bounded(ENTRY_OVERHEAD + 1000);
2729		let mut charge = charge(&pool);
2730		charge.add(500);
2731		assert_eq!(pool.accrue(100), None);
2732	}
2733
2734	#[test]
2735	fn accrue_proportional_over_capacity() {
2736		let pool = bounded(1000);
2737		let mut charge = charge(&pool);
2738		charge.add(2000 - ENTRY_OVERHEAD); // used = 2000, twice the capacity
2739
2740		// Debt exceeds what was written by the overshoot ratio, so the pool drains.
2741		assert_eq!(pool.accrue(100), Some(200));
2742		// Zero written accrues zero: an idle track takes on no debt.
2743		assert_eq!(pool.accrue(0), Some(0));
2744	}
2745
2746	#[test]
2747	fn average_tracks_evictable_population() {
2748		let pool = bounded(1000);
2749		assert_eq!(pool.average(), None);
2750
2751		pool.access_insert(10);
2752		pool.access_insert(20);
2753		assert_eq!(pool.average(), Some(15));
2754
2755		// A refresh moves one member's contribution, exactly.
2756		pool.access_refresh(10, 40);
2757		assert_eq!(pool.average(), Some(30));
2758
2759		pool.access_remove(40);
2760		assert_eq!(pool.average(), Some(20));
2761		pool.access_remove(20);
2762		assert_eq!(pool.average(), None);
2763	}
2764
2765	#[test]
2766	fn charge_raii() {
2767		let pool = bounded(1000);
2768		let mut charge = charge(&pool);
2769		assert_eq!(pool.used(), ENTRY_OVERHEAD);
2770
2771		charge.add(100);
2772		assert_eq!(pool.used(), ENTRY_OVERHEAD + 100);
2773
2774		charge.clear();
2775		assert_eq!(pool.used(), 0);
2776		// Idempotent: a second clear (and the eventual drop) releases nothing more.
2777		charge.clear();
2778		drop(charge);
2779		assert_eq!(pool.used(), 0);
2780	}
2781
2782	#[test]
2783	fn detached_charge_is_noop() {
2784		let mut charge = Charge::default();
2785		charge.add(123);
2786		charge.clear();
2787	}
2788
2789	#[test]
2790	fn accrue_saturates() {
2791		// A huge overshoot against a tiny capacity must saturate, not wrap.
2792		let pool = bounded(1);
2793		let mut c = charge(&pool);
2794		c.add(1 << 40);
2795		assert_eq!(pool.accrue(1 << 40), Some(u64::MAX));
2796	}
2797
2798	/// A live edge pins its fixed costs at once and its content once it finished, moving the
2799	/// pins with every byte it or its extras gain or shed, until it is demoted. A pool held past
2800	/// its capacity by pins alone has no excess, and no room to give.
2801	#[test]
2802	fn a_live_edge_pins_what_no_eviction_reclaims() {
2803		let pool = bounded(0);
2804		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2805
2806		let mut charge = track.charge();
2807		charge.add(1_000);
2808		assert_eq!(pool.pinned(), 0, "not the live edge yet");
2809		charge.promote();
2810		assert_eq!(
2811			pool.pinned(),
2812			ENTRY_OVERHEAD,
2813			"a growing edge may still shed its content"
2814		);
2815		let extra = charge.extra();
2816		extra.add(500);
2817		extra.add_state(100);
2818		assert_eq!(pool.pinned(), ENTRY_OVERHEAD + 100);
2819		charge.finish(true);
2820		assert_eq!(pool.pinned(), ENTRY_OVERHEAD + 1_600);
2821		assert_eq!(pool.pinned(), pool.used());
2822		assert_eq!(pool.excess(), None, "held past its capacity by pins alone");
2823		assert!(!pool.hold_room(1), "no room for a hold");
2824		assert_eq!(pool.accrue(1_000), None);
2825
2826		charge.sub(400);
2827		extra.sub_state(100);
2828		assert_eq!(pool.pinned(), ENTRY_OVERHEAD + 1_100);
2829		let mut cold = track.charge();
2830		cold.add(200);
2831		cold.demote();
2832		assert_eq!(
2833			pool.excess(),
2834			Some(ENTRY_OVERHEAD + 200),
2835			"only what eviction can reclaim"
2836		);
2837
2838		charge.demote();
2839		assert_eq!(pool.pinned(), 0);
2840		drop(extra);
2841		drop(charge);
2842		drop(cold);
2843		assert_eq!(pool.used(), 0);
2844		assert_eq!(pool.pinned(), 0);
2845	}
2846
2847	/// A copy's content pins once any sibling sharing it finished the whole group, since its
2848	/// frames may be what the finished copy holds; a copy a transport bound cut does not.
2849	#[test]
2850	fn a_finished_sibling_pins_the_shared_content() {
2851		let pool = bounded(0);
2852		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2853		let siblings = Siblings::default();
2854		let mut live = track.charge();
2855		live.add(1_000);
2856		live.promote();
2857		siblings.update(&live);
2858		let mut head = track.charge();
2859		siblings.update(&head);
2860		assert_eq!(pool.pinned(), 2 * ENTRY_OVERHEAD, "the shared frames still grow");
2861		head.finish(false);
2862		siblings.update(&head);
2863		assert_eq!(
2864			pool.pinned(),
2865			2 * ENTRY_OVERHEAD,
2866			"a copy a transport bound cut finished only its range"
2867		);
2868		head.finish(true);
2869		siblings.update(&head);
2870		assert_eq!(pool.pinned(), 2 * ENTRY_OVERHEAD + 1_000);
2871		assert_eq!(pool.excess(), None);
2872	}
2873
2874	/// A held copy holds the frames it shares with a sibling that wrote them first, which still
2875	/// bills them after leaving the cache, and stops once the hold ends. Holds never raise the
2876	/// pool's target: past the capacity, they are what is over.
2877	#[test]
2878	fn a_held_sibling_holds_the_shared_content() {
2879		let pool = bounded(0);
2880		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2881		let siblings = Siblings::default();
2882		let mut evicted = track.charge();
2883		evicted.add(1_000);
2884		let shared = evicted.transfer(1_000);
2885		siblings.update(&evicted);
2886		evicted.clear();
2887		siblings.update(&evicted);
2888		let held = track.charge();
2889		siblings.update(&held);
2890		held.hold(true);
2891		siblings.update(&held);
2892		assert_eq!(
2893			pool.held(),
2894			ENTRY_OVERHEAD + 1_000,
2895			"the shared frames are what it holds"
2896		);
2897		assert_eq!(pool.pinned(), 0, "a hold pins nothing");
2898		assert!(!pool.holds_fit(), "nor fits a capacity of nothing");
2899		assert_eq!(pool.excess(), Some(pool.used()));
2900
2901		held.hold(false);
2902		siblings.update(&held);
2903		assert_eq!(pool.held(), 0);
2904		drop((shared, evicted, held));
2905		assert_eq!(pool.used(), 0);
2906	}
2907
2908	/// A live edge bills its session for every byte it holds, its extras included (shared
2909	/// content a transfer moved out, inflated copies, codec state), whichever order they and
2910	/// the promotion come in, and stops on demotion or abort, its extras outliving it or not.
2911	#[test]
2912	fn a_live_edge_bills_its_extras_to_the_session() {
2913		let edges = Edges::new(Some(1 << 30));
2914		let track = Track::new(Pool::unbounded(), Default::default(), edges.clone(), kio::Weak::new());
2915
2916		let mut charge = track.charge();
2917		charge.add(100);
2918		let early = charge.extra();
2919		early.add(10);
2920		assert_eq!(edges.used(), 0, "not the live edge yet");
2921		charge.promote();
2922		assert_eq!(edges.used(), 110, "the overhead is left out");
2923		let shared = charge.transfer(60);
2924		let late = charge.extra();
2925		late.add(5);
2926		assert_eq!(edges.used(), 115, "a transfer keeps its bytes billed");
2927		shared.sub(20);
2928		assert_eq!(edges.used(), 95);
2929		charge.demote();
2930		assert_eq!(edges.used(), 0);
2931		drop((shared, late));
2932		assert_eq!(edges.used(), 0);
2933
2934		// Aborted while its extras live on: they stop billing with it.
2935		let mut charge = track.charge();
2936		let extra = charge.extra();
2937		extra.add(10);
2938		charge.promote();
2939		charge.clear();
2940		assert_eq!(edges.used(), 0);
2941		drop(extra);
2942		assert_eq!(edges.used(), 0);
2943	}
2944
2945	#[test]
2946	fn charge_counts_gross_writes() {
2947		let track = Track::new(bounded(1000), Default::default(), Default::default(), kio::Weak::new());
2948		let mut c = track.charge();
2949		c.add(100);
2950		assert_eq!(track.take_written(), ENTRY_OVERHEAD + 100);
2951		assert_eq!(track.take_written(), 0, "taking it drains the counter");
2952	}
2953
2954	#[test]
2955	fn charge_owns_access_sample() {
2956		let pool = bounded(1000);
2957		let mut c = charge(&pool);
2958		assert_eq!(pool.average(), None, "not evictable until demoted");
2959
2960		c.demote();
2961		c.demote(); // idempotent
2962		assert!(pool.average().is_some());
2963
2964		// Clearing (an abort, from anyone) removes the sample with the bytes.
2965		c.clear();
2966		assert_eq!(pool.average(), None, "aborted groups leave no ghost sample");
2967		drop(c);
2968		assert_eq!(pool.average(), None);
2969	}
2970
2971	#[test]
2972	fn refresh_updates_a_counted_sample() {
2973		let pool = bounded(1000);
2974		let mut c = charge(&pool);
2975		c.demote();
2976		c.refresh();
2977		// The sample in the pool mean moved with the stamp, so releasing the charge
2978		// removes exactly what was inserted and leaves no residue.
2979		assert_eq!(pool.average(), Some(c.accessed()));
2980		c.clear();
2981		assert_eq!(pool.average(), None);
2982	}
2983
2984	#[test]
2985	fn refresh_protects_within_a_tick() {
2986		let pool = bounded(1000);
2987		let mut c = charge(&pool);
2988		c.demote();
2989		let average = pool.average().unwrap();
2990		// A refresh in the same coarse tick still lifts the group above the mean.
2991		c.refresh();
2992		assert!(c.accessed() > average);
2993		assert_eq!(c.access().tick(None), None, "undated access is protected until cleanup");
2994		assert_eq!(
2995			c.access().tick(Some(pool.now())),
2996			Some(pool.now()),
2997			"cleanup dates the access"
2998		);
2999		// Repeated same-tick refreshes are idempotent, not runaway.
3000		let stamped = c.accessed();
3001		c.refresh();
3002		assert_eq!(c.accessed(), stamped);
3003	}
3004
3005	#[test]
3006	fn expiry_config() {
3007		// A bare pool preserves the unbounded contract in both dimensions.
3008		let pool = Pool::unbounded();
3009		assert_eq!(pool.expiry(), None);
3010
3011		let pool = Pool::new(Config::default().with_expiry(Duration::from_secs(1)));
3012		assert_eq!(pool.expiry(), Some(Duration::from_secs(1)));
3013		assert_eq!(pool.expiry_ticks(), 10);
3014
3015		let pool = Pool::new(Config::default().with_expiry(Duration::from_millis(1)));
3016		assert_eq!(pool.expiry(), Some(Duration::from_millis(TICK_MS)));
3017		assert_eq!(pool.expiry_ticks(), 1);
3018
3019		// Disabled: never reclaimed by idleness, but readers still re-stamp on a
3020		// bounded cadence for byte-eviction protection.
3021		let pool = Pool::new(Config::default());
3022		assert_eq!(pool.expiry(), None);
3023		assert_eq!(pool.expiry_ticks(), u64::MAX);
3024	}
3025
3026	#[test]
3027	fn expiry_gate_reuses_a_supplied_tick() {
3028		let pool = Pool::new(Config::default().with_expiry(Duration::from_secs(1)));
3029		let track = Track::new(pool, Default::default(), Default::default(), kio::Weak::new());
3030		// A supplied tick drives the gate on its own: claimed immediately, closed
3031		// until the interval elapses, claimable again on the tick it reopens.
3032		assert!(track.expiry_due(Some(0)));
3033		assert!(!track.expiry_due(Some(9)));
3034		assert!(track.expiry_due(Some(10)));
3035		// Without one the gate samples the pool clock, frozen here at tick 0, so it
3036		// stays closed rather than inheriting the caller's tick 10.
3037		assert!(!track.expiry_due(None));
3038	}
3039
3040	#[test]
3041	fn sweep_interval_is_half_the_window() {
3042		assert_eq!(Pool::unbounded().sweep_interval(), None);
3043		let pool = Pool::new(Config::default().with_expiry(Duration::from_secs(4)));
3044		assert_eq!(pool.sweep_interval(), Some(Duration::from_secs(2)));
3045	}
3046
3047	#[test]
3048	fn the_sweep_registry_follows_account_lifetime() {
3049		let pool = bounded(1000);
3050		assert!(pool.inner.tracks.lock().is_empty());
3051
3052		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
3053		assert_eq!(pool.inner.tracks.lock().len(), 1);
3054
3055		// A registered account whose track is already gone is swept harmlessly.
3056		pool.sweep();
3057
3058		drop(track);
3059		assert!(pool.inner.tracks.lock().is_empty(), "a dropped account leaves no entry");
3060	}
3061
3062	#[test]
3063	fn an_inert_pool_registers_nothing() {
3064		// No window means no sweep, so a bare pool pays no registry cost.
3065		let pool = Pool::unbounded();
3066		let track = Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
3067		assert!(pool.inner.tracks.lock().is_empty());
3068		pool.sweep();
3069		drop(track);
3070	}
3071
3072	#[test]
3073	fn expiry_gate_stays_closed_without_a_window() {
3074		// No window means no time gate, and no clock read to reach it.
3075		let track = Track::new(
3076			Pool::unbounded(),
3077			Default::default(),
3078			Default::default(),
3079			kio::Weak::new(),
3080		);
3081		assert!(!track.expiry_due(None));
3082		assert!(!track.expiry_due(Some(u64::MAX)));
3083	}
3084
3085	#[test]
3086	fn collecting_before_the_deadline_does_not_postpone_it() {
3087		let pool = Pool::new(Config::default().with_expiry(Duration::from_secs(2)));
3088		let now = crate::time::Instant::now();
3089		let deadline = pool.poll(now, &kio::Waiter::noop());
3090		assert_eq!(
3091			pool.poll(now.saturating_add(Duration::from_millis(500)), &kio::Waiter::noop()),
3092			deadline
3093		);
3094	}
3095
3096	#[test]
3097	fn bounded_pools_sample_recency_without_expiration() {
3098		let pool = Pool::unbounded();
3099		let now = crate::time::Instant::now();
3100		assert_eq!(pool.poll(now, &kio::Waiter::noop()), None);
3101		pool.resize(1024);
3102		assert_eq!(
3103			pool.poll(now, &kio::Waiter::noop()),
3104			Some(now.saturating_add(DEFAULT_EXPIRY / 2))
3105		);
3106		pool.poll(now.saturating_add(DEFAULT_EXPIRY), &kio::Waiter::noop());
3107		assert!(pool.now() > 0);
3108		pool.resize(None);
3109		assert_eq!(
3110			pool.poll(now.saturating_add(DEFAULT_EXPIRY), &kio::Waiter::noop()),
3111			None
3112		);
3113	}
3114
3115	#[test]
3116	fn resize() {
3117		let pool = Pool::unbounded();
3118		assert_eq!(pool.capacity(), None);
3119
3120		let mut charge = charge(&pool);
3121		charge.add(1000);
3122
3123		// Shrinking doesn't reclaim anything synchronously; writers accrue debt instead.
3124		pool.resize(100);
3125		assert_eq!(pool.capacity(), Some(100));
3126		assert!(pool.used() > 100);
3127		assert!(pool.accrue(50).unwrap() > 50);
3128
3129		pool.resize(None);
3130		assert_eq!(pool.capacity(), None);
3131		assert_eq!(pool.accrue(50), None);
3132	}
3133}