Skip to main content

moq_net/model/
group.rs

1//! A group is a stream of frames, split into a [Producer] and [Consumer] handle.
2//!
3//! A [Producer] writes an ordered stream of frames.
4//! Frames can be written all at once ([Producer::write_frame]), or in chunks
5//! ([Producer::create_frame]).
6//!
7//! A [Consumer] reads an ordered stream of frames.
8//! The reader can be cloned, in which case each reader receives a copy of each frame. (fanout)
9//!
10//! Frames are numbered from 0 in write order. A group can be short at its front or its
11//! back but never in the middle: `Producer::start_at` starts it later, so a handle can
12//! carry the tail of a group whose leading frames came from somewhere else, and
13//! [Producer::finish] ends it wherever writing stopped. [Consumer::with_range] bounds a reader to a sub-range the same way [`track::Subscriber`]
14//! bounds group keys.
15//!
16//! A group has no size cap. Each copy holds at most its newest 32 MiB, less
17//! under the cache pool's memory pressure, and sheds whole frames from its front to stay
18//! there. A reader that reaches a shed frame rides a flight when the track has a
19//! [`track::Requests`] handler: a separate copy from that frame, paced by its fastest
20//! reader, which it leaves for the copy ahead once that holds its frame within reach.
21//! Otherwise reading a shed frame is [`Error::Evicted`].
22//!
23//! The stream is closed with [Error] when all writers or readers are dropped.
24use super::flate;
25use super::idle::Idle;
26use super::pace::Pace;
27use super::resume::Cause;
28mod content;
29use crate::cache;
30use crate::frame::{self, Cached, FrameBuf, Payload};
31use crate::{Timescale, stats, track, util::SendCell};
32use bytes::Bytes;
33#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
34pub(crate) use content::StorageBench;
35pub(super) use content::{Content, Contents, Key as ContentKey};
36use content::{Input, Spec};
37use std::collections::VecDeque;
38use std::mem::MaybeUninit;
39use std::ops::RangeBounds;
40use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
41use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
42use std::task::{Poll, ready};
43
44use crate::{Error, Result, StreamError, Timestamp};
45
46/// Maximum size of a group copy's live tail, and of one frame.
47///
48/// A group has no size cap: a write that takes the frames held past this sheds whole
49/// frames from the copy's front until it fits, and a compressed group's inflated copy
50/// sheds the same way. A reader that reaches a shed frame rides a flight, or gets
51/// [`Error::Evicted`] when nothing serves one (see the module docs). A larger declared
52/// frame size is [`Error::FrameTooLarge`] before allocating.
53pub(crate) const MAX_CACHE_BYTES: u64 = 32 * 1024 * 1024; // 32 MB
54
55/// How far behind a copy's fastest reader a reader may board it: half the live tail, less
56/// the most one shed frees at once, since the other half may be all ahead of that reader.
57pub(super) const ADMIT: u64 = super::pace::AHEAD - kio::log::Writer::<Entry>::SEGMENT_HEAP as u64;
58
59/// Heap one cached group costs beyond its frame payloads, excluding the track-side
60/// bookkeeping in [`track::CACHE_OVERHEAD`].
61///
62/// A group is one kio channel (allocated whether or not anything ever parks on it), the
63/// `Arc<Alive>` its writer and observers share, and its frame log with the first segment
64/// of slots the first frame allocates; each later segment is charged as it is allocated.
65/// Half of [`cache::ENTRY_OVERHEAD`]; see it for why this is derived rather than measured.
66pub(super) const CACHE_OVERHEAD: u64 = (kio::Producer::<GroupState>::HEAP
67	// `Alive` behind an `Arc`'s two reference counts, which it is pointer-aligned to sit
68	// straight after.
69	+ 2 * size_of::<usize>()
70	+ size_of::<Alive>()
71	// The `Pace` its writer and readers share, behind its own `Arc`.
72	+ 2 * size_of::<usize>()
73	+ size_of::<Pace>()
74	+ kio::log::Writer::<Entry>::HEAP) as u64;
75
76/// A group's identity: where it starts, in its track's timescale.
77///
78/// A group's start is its key on the track: starts strictly increase along a track, so no
79/// two groups share one, and a later group never starts earlier. A group a local producer
80/// writes starts at its first frame's timestamp; one received over a wire that numbers
81/// groups starts at that wire's group ID, verbatim. On a scale-less track (no
82/// [`track::Info::timescale`]) a start is a bare number in no known unit.
83#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
84pub struct Info {
85	/// Where the group starts, in its track's timescale.
86	pub start: u64,
87}
88
89impl Info {
90	/// Create a producer for this group on a millisecond track.
91	///
92	/// Test-only: real groups are created via [`track::Producer`], which
93	/// supplies the parent track's [`track::Info`].
94	#[cfg(test)]
95	pub(crate) fn produce(self) -> Producer {
96		Producer::new(
97			self,
98			track::Info::default().with_timescale(Timescale::MILLI),
99			Default::default(),
100		)
101	}
102
103	/// Create a producer for this group on an untimed track. Test-only, like [`Self::produce`].
104	#[cfg(test)]
105	pub(super) fn produce_untimed(self) -> Producer {
106		Producer::new(self, track::Info::default(), Default::default())
107	}
108}
109
110impl From<usize> for Info {
111	fn from(start: usize) -> Self {
112		Self { start: start as u64 }
113	}
114}
115
116impl From<u64> for Info {
117	fn from(start: u64) -> Self {
118		Self { start }
119	}
120}
121
122impl From<u32> for Info {
123	fn from(start: u32) -> Self {
124		Self { start: start as u64 }
125	}
126}
127
128impl From<u16> for Info {
129	fn from(start: u16) -> Self {
130		Self { start: start as u64 }
131	}
132}
133
134/// The in-flight (tail) frame being written. At most one exists at a time, since a
135/// group is a single ordered stream.
136pub(super) struct Partial {
137	timestamp: Timestamp,
138	fields: Option<Arc<super::object::Fields>>,
139	buf: FrameBuf,
140	// How much of `buf` has been charged to the cache so far.
141	charged: u64,
142	// A received DEFLATE slice's inflated size, on a compressed group.
143	inflated: Option<u64>,
144	// Plain bytes a local producer streams into a compressed group: compressed when the
145	// frame commits, so no reader sees them, and uncharged until then.
146	scratch: bool,
147}
148
149/// What [`Producer::write_stored`] writes as one whole frame.
150enum Stored {
151	/// A payload frame's bytes.
152	Payload(Bytes),
153	/// A metadata copy's frame header: its declared plain size, and the object fields it
154	/// arrived with.
155	Header {
156		size: u64,
157		fields: Option<Arc<super::object::Fields>>,
158	},
159}
160
161/// A completed frame as a group stores it, with what egress needs beside it.
162pub(super) struct Entry {
163	owner: Mutex<Option<frame::Shared>>,
164	frame: Cached,
165	// The IETF object fields it arrived with, for a relay to forward.
166	fields: Option<Arc<super::object::Fields>>,
167	// A compressed group's inflated size of the stored slice, or a metadata copy's declared
168	// frame size beside its empty payload; zero on a plain group.
169	inflated: u64,
170	// Where the frame ends on its copy's [`Pace`] scale, set as it enters the log.
171	end: u64,
172}
173
174impl Clone for Entry {
175	fn clone(&self) -> Self {
176		Self {
177			owner: Mutex::new(self.owner.lock().unwrap_or_else(PoisonError::into_inner).clone()),
178			frame: self.frame.clone(),
179			fields: self.fields.clone(),
180			inflated: self.inflated,
181			end: self.end,
182		}
183	}
184}
185
186impl Entry {
187	/// Where the frame sits on its copy's [`Pace`] scale: its payload, metadata, and slot,
188	/// as the live tail charges it, so a paced writer of tiny frames is bounded too.
189	fn cost(&self) -> u64 {
190		let metadata = self.fields.as_ref().map_or(0, |fields| fields.heap());
191		self.frame.payload.len() as u64 + metadata + size_of::<Entry>() as u64
192	}
193
194	/// A frame without object fields.
195	fn plain(frame: Cached, inflated: u64) -> Self {
196		Self {
197			owner: Mutex::new(None),
198			frame,
199			fields: None,
200			inflated,
201			end: 0,
202		}
203	}
204
205	/// The header and whole payload a reader gets: on a `sized` group (compressed, or a
206	/// metadata copy), the stored slice with its declared plain size.
207	fn read(&self, sized: bool) -> (frame::Header, frame::Source) {
208		let info = frame::Info {
209			size: self.frame.payload.len() as u64,
210			timestamp: self.frame.timestamp,
211		};
212		let header = frame::Header {
213			info,
214			fields: self.fields.clone(),
215			inflated: sized.then_some(self.inflated),
216		};
217		(header, frame::Source::Complete(self.frame.payload.clone()))
218	}
219}
220
221/// The frames carried by one transport copy; `end` is exclusive, not the group's end.
222#[derive(Clone, Copy, Debug, Default)]
223pub(crate) struct Bounds {
224	pub start: u64,
225	pub end: Option<u64>,
226}
227
228/// Shared group state. Model-visible so [`frame`] handles can observe its outcome
229/// while streaming a partial frame.
230#[derive(Default)]
231pub(super) struct GroupState {
232	content: Option<Arc<Content>>,
233	// Completed frames, each a contiguous payload, from where this copy started (see
234	// [`Producer::start_at`]). Its end is one past the last frame fully written. Cursors
235	// read it without this state's lock. A compressed group stores DEFLATE slices here.
236	log: kio::log::Writer<Entry>,
237	// Frames adopted from below the log's first, up to it (see [`Handle::adopt_head`]).
238	// Shedding pops them first, so they start at `offset` until the group sheds.
239	front: VecDeque<Entry>,
240	// IETF relay state, boxed so a group that never carries any pays one pointer.
241	relay: Option<Box<Relay>>,
242	// Compressed-track state, boxed so a plain group pays one pointer.
243	flate: Option<Box<Flate>>,
244	// Whether this is a metadata copy: each frame its header alone, an empty payload with
245	// its declared size beside it (see [`Producer::write_header`]).
246	meta: bool,
247
248	// The single in-flight frame, if one is open.
249	pub(super) partial: Option<Partial>,
250
251	// Index of the first frame this handle holds: any the group deliberately started
252	// past (see [`Producer::start_at`]). The frames are not here: reading below it
253	// fetches them (see [`Consumer::fetches_from`]) or is [`Error::Lagged`]. Frames shed from the front since sit between it and
254	// [`Self::held`], and reading them is [`Error::Evicted`].
255	pub(super) offset: usize,
256
257	// The index the next frame written will get. Tracked separately from `frames` so it
258	// survives the cache being released: a route taking the track over needs to know where
259	// production stopped, and an abort is exactly when it asks.
260	next_index: usize,
261
262	// Exclusive cap on `next_index`, set when the track ends inside this group: a write
263	// past the track's end is refused rather than served as content that does not exist.
264	limit: Option<usize>,
265	// A transport stopped this copy here; FIN does not declare the original group complete.
266	range_end: Option<usize>,
267
268	// The total size (in bytes) of all cached frames plus what the in-flight frame has
269	// written so far.
270	pub(super) cache: u64,
271
272	// Bills payload and frame-slot growth to the track's shared cache pool, so its bytes count
273	// against the byte budget tracks evict toward.
274	charge: cache::Charge,
275
276	// Where the group sits in presentation time, settled by its first frame. Kept here
277	// rather than read off `frames` so an abort doesn't erase it.
278	timeline: Timeline,
279
280	// How the track judged the start against its neighbors' when frame 0 landed.
281	origin: Origin,
282
283	// Whether a timed frame 0 must sit at the group's key: a group handed out empty, whose
284	// writer stamps frame 0 itself (see [`Producer::keyed`]).
285	keyed: bool,
286
287	// How the group ended, if it did. The finished count outlives an abort that frees the
288	// cache. Mirrored into `Alive::fall` by the one abort path, `Handle::commit_abort`:
289	// anything else ending it would leave track scans reading a group as live.
290	pub(super) outcome: Outcome,
291
292	// The readers that could resume this group on another route. A release that is no
293	// cache policy moves the frames to them rather than dropping them.
294	handoff: Mutex<Weak<Handoff>>,
295
296	// Whether this copy's ingest wrote a frame itself, which it does only after settling the
297	// relay state; adopted frames (see [`Handle::adopt_head`]) prove nothing about it.
298	wrote: bool,
299
300	// Whether an adopted head (see [`Handle::adopt_head`]) begins at the group's first
301	// object, for a wire header that arrives after it.
302	adopted: Option<bool>,
303
304	// How far readers got, which each frame entering the log is measured against.
305	pace: Arc<Pace>,
306
307	// The highest timestamp among the frames shed from the front, in its track's timescale, which
308	// a stream resumed past them still raises a lower frame to (see [`Consumer::highest_below`]).
309	// Kept as a bare value, as the frames' timestamps hold their track's scale.
310	shed_high: u64,
311
312	// Set under this lock once a reader first holds the group, after it counts as one, so a
313	// writer that reads it before the count sees the reader in one or the other: until then
314	// the group is owed to the cursors that admit it (see [`Handle::poll_unowed`]). Atomic only
315	// so a read guard sets it without waking every consumer.
316	held: AtomicBool,
317}
318
319/// How far a group got toward its end; each step replaces the last.
320#[derive(Clone, Debug, Default)]
321pub(super) enum Outcome {
322	/// Frames may still be written.
323	#[default]
324	Open,
325	/// Finished with this many frames, and where it ends in its track's timescale when its
326	/// producer said it is whole: `None` when it finished without an end (see [`Producer::finish`]).
327	Finished(usize, Option<u64>),
328	/// Finished with this many frames and the end it finished at, then aborted to free its
329	/// cache: a reader that took every frame got every frame the group finished with, and one
330	/// short of it gets the error.
331	Released(usize, Option<u64>, Abort),
332	/// Aborted before it finished.
333	Aborted(Abort),
334}
335
336impl Outcome {
337	/// The total number of frames, once finished.
338	pub(super) fn frames(&self) -> Option<usize> {
339		match self {
340			Self::Finished(frames, _) | Self::Released(frames, ..) => Some(*frames),
341			Self::Open | Self::Aborted(_) => None,
342		}
343	}
344
345	/// The error the group was aborted with, before or after it finished.
346	pub(super) fn error(&self) -> Option<&Error> {
347		match self {
348			Self::Released(.., abort) | Self::Aborted(abort) => Some(abort.error()),
349			Self::Open | Self::Finished(..) => None,
350		}
351	}
352
353	/// Whether the pool evicted this copy, so a reader short of its end is owed the frames
354	/// it freed, which a flight of the group brings.
355	pub(super) fn evicted(&self) -> bool {
356		matches!(self, Self::Released(.., Abort::Evicted) | Self::Aborted(Abort::Evicted))
357	}
358}
359
360/// Why a copy was aborted: recorded where the abort is decided, so a reader never tells the
361/// pool's eviction from a failure by the error it reads.
362#[derive(Clone, Debug)]
363pub(super) enum Abort {
364	/// The pool evicted it, read as [`Error::Evicted`].
365	Evicted,
366	/// Anything else: the copy failed, was given up, or aged out.
367	Failed(Error),
368}
369
370// What a reader of an evicted copy reads, borrowed like any other abort's error.
371static EVICTED: Error = Error::Evicted;
372
373impl Abort {
374	fn error(&self) -> &Error {
375		match self {
376			Self::Evicted => &EVICTED,
377			Self::Failed(err) => err,
378		}
379	}
380}
381
382impl From<Error> for Abort {
383	fn from(err: Error) -> Self {
384		Self::Failed(err)
385	}
386}
387
388/// Whether and why a group was aborted, as track scans read it without taking the group
389/// lock: one atomic phase in [`Alive`], so a scan never sees part of an abort.
390#[derive(Clone, Copy, Debug, PartialEq, Eq)]
391#[repr(u8)]
392enum Fall {
393	/// Not aborted.
394	Live,
395	/// Freed by cache policy (`Old`, `Timeout`, `Evicted`), or after it finished: it aged
396	/// out of a cache rather than failed.
397	Released,
398	/// Given up deliberately: a reader cancelling, a lagged copy, or the upstream's own
399	/// cache policy. It failed, but readers never see a cut.
400	Abandoned,
401	/// The publisher gave it up, with the error in [`Alive::cut`].
402	Cut,
403}
404
405impl Fall {
406	fn from_u8(phase: u8) -> Self {
407		match phase {
408			0 => Self::Live,
409			1 => Self::Released,
410			2 => Self::Abandoned,
411			_ => Self::Cut,
412		}
413	}
414}
415
416/// A head [`Handle::take_head`] adopted, still to settle with the track and the cache; see
417/// [`Handle::settle_head`].
418#[must_use]
419pub(super) struct Adopted {
420	now: Option<u64>,
421	latest: Option<Timestamp>,
422	first: bool,
423}
424
425/// The frames a copy of a group holds, from where it starts, which a successor copy of
426/// the same group on another route adopts below where it starts.
427pub(super) struct Head {
428	content: Option<Arc<Content>>,
429	start: usize,
430	// Whether `start` is the group's first object.
431	first_object: bool,
432	entries: Vec<Entry>,
433	// Whether `entries` are a compressed group's stored slices.
434	compressed: bool,
435	// Whether `entries` are a metadata copy's headers, which no payload copy adopts.
436	meta: bool,
437}
438
439/// A copy's [`Head`], shared by every reader that could resume its group elsewhere.
440///
441/// Read from the copy while it holds its frames. Once it fails, its release moves them
442/// here instead, so a plain consumer of the failed copy still reads the abort and pins
443/// nothing, and the frames go with the last reader holding this. A loan (see
444/// [`Self::lent`]) holds a head with no copy behind it.
445pub(super) struct Handoff {
446	state: Option<kio::ConsumerPassive<GroupState>>,
447	salvaged: Mutex<Option<Salvage>>,
448}
449
450/// A failed copy's head, billed to its pool while held; see [`cache::Track::hold`].
451struct Salvage {
452	head: Arc<Head>,
453	bill: cache::Bill,
454}
455
456impl Handoff {
457	/// The copy's head, if it holds any frames, or held them when it failed.
458	pub(super) fn head(&self) -> Option<Arc<Head>> {
459		// The group's lock first, in `release`'s order: under it the frames are either
460		// still in the copy or already moved here, never in neither.
461		let state = self.state.as_ref().map(|state| state.read());
462		let salvaged = (self.salvaged.lock().unwrap_or_else(PoisonError::into_inner))
463			.as_ref()
464			.map(|salvage| salvage.head.clone());
465		salvaged.or_else(|| state?.head().map(Arc::new))
466	}
467
468	/// Hold `head` for a copy of its group still to arrive, which adopts it then, billed to
469	/// that copy's pool and reclaimed like a failed copy's head: under capacity pressure, or
470	/// once idle. `None` when the pool has no room for it.
471	pub(super) fn lent(head: Arc<Head>, cache: &Arc<cache::Track>) -> Option<Arc<Self>> {
472		let bill = cache.hold(head.bytes())?;
473		let handoff = Arc::new(Self {
474			state: None,
475			salvaged: Mutex::new(Some(Salvage { head, bill })),
476		});
477		cache.pool().hold_head(&handoff);
478		Some(handoff)
479	}
480
481	/// Drop the held head when `reclaim`, or once the pool's idle window passed, returning
482	/// whether none is held any more.
483	pub(super) fn expire(&self, reclaim: bool) -> bool {
484		let mut salvaged = self.salvaged.lock().unwrap_or_else(PoisonError::into_inner);
485		if salvaged
486			.as_ref()
487			.is_some_and(|salvage| reclaim || salvage.bill.expired())
488		{
489			*salvaged = None;
490		}
491		salvaged.is_none()
492	}
493}
494
495impl Head {
496	/// How many frames it holds from the group's first, or `None` when it starts later.
497	pub(super) fn frames_from_first(&self) -> Option<u64> {
498		(self.start == 0 && !self.entries.is_empty()).then_some(self.entries.len() as u64)
499	}
500
501	/// Roughly what holding it costs: payloads, fields, and their slots.
502	fn bytes(&self) -> u64 {
503		let payload: u64 = self.entries.iter().map(|entry| entry.frame.payload.len() as u64).sum();
504		let fields: u64 = self
505			.entries
506			.iter()
507			.filter_map(|entry| entry.fields.as_ref())
508			.map(|fields| fields.heap())
509			.sum();
510		self.content.as_ref().map_or(payload, |_| 0) + fields + (self.entries.len() * size_of::<Entry>()) as u64
511	}
512}
513
514/// What an IETF relay keeps beside a group's frames.
515#[derive(Default)]
516struct Relay {
517	// Known before frames arrive.
518	wire: Option<Wire>,
519	// The terminal object, learned at the stream tail.
520	end_object: Option<Arc<super::object::Fields>>,
521	// The newest object ID before the terminal object, which a publisher's Largest names
522	// instead of the terminal object it sends past it.
523	last_before_end: Option<u64>,
524	// Heap charged for this box, its frames' fields, and the terminal object.
525	bytes: u64,
526}
527
528/// What a compressed group keeps beside its stored DEFLATE slices.
529struct Flate {
530	// A pending inflater belongs to this delivery even when its Plain is shared.
531	release: Option<Arc<Release>>,
532	// Compresses a local producer's frames, created by its first write. A received group
533	// stores what arrived and never recompresses.
534	encoder: Option<flate::Encoder>,
535	// The inflated copy every plain reader shares, built on first demand.
536	plain: Arc<Plain>,
537}
538
539struct Release {
540	error: Mutex<Option<Error>>,
541	bill: cache::Extra,
542}
543
544impl Release {
545	fn new(bill: cache::Extra) -> Arc<Self> {
546		bill.add(Flate::RELEASE_HEAP);
547		Arc::new(Self {
548			error: Mutex::default(),
549			bill,
550		})
551	}
552}
553
554impl Flate {
555	const RELEASE_HEAP: u64 = (2 * size_of::<usize>() + size_of::<Release>()) as u64;
556
557	fn new(plain: Arc<Plain>, bill: cache::Extra) -> Self {
558		Self {
559			release: Some(Release::new(bill)),
560			encoder: None,
561			plain,
562		}
563	}
564
565	/// Compress a locally written frame, returning its stored slice.
566	fn deflate(&mut self, payload: &[u8]) -> Bytes {
567		let plain = &self.plain;
568		let encoder = self.encoder.get_or_insert_with(|| plain.bill.take_encoder());
569		encoder.frame(payload)
570	}
571
572	/// Park the encoder once no frame follows at `fin`, and drop the decoder if its readers
573	/// already inflated every frame.
574	fn finish(&mut self, fin: Option<usize>) {
575		if let Some(encoder) = self.encoder.take() {
576			self.plain.bill.park_encoder(encoder);
577		}
578		let Some(fin) = fin else {
579			return;
580		};
581		let mut plain = self.plain.lock();
582		plain.fin = Some(fin);
583		if plain.base + plain.frames.len() == fin {
584			self.plain.drop_decoder(&mut plain);
585		}
586	}
587
588	/// Drop everything but how the group is read, failing a late inflater with `err`.
589	fn release(&mut self, err: Error, shared: bool) {
590		// Wait for at most the frame currently inflating, just as Plain::release did.
591		if let Some(release) = self.release.take() {
592			*release.error.lock().unwrap_or_else(PoisonError::into_inner) = Some(err.clone());
593		}
594		if !shared {
595			self.encoder = None;
596			self.plain.release(err);
597			return;
598		}
599		if self.encoder.take().is_some() {
600			self.plain.bill.sub_state(flate::ENCODER_HEAP);
601		}
602	}
603}
604
605/// A compressed group's inflated copy, shared by its plain readers.
606///
607/// A reader takes the slices it needs under the group's guard and inflates them under
608/// only this lock ([`Inflate`]), so a cold read never holds up the group's writer.
609struct Plain {
610	// Frames inflated so far, shed or not, so a reader under the group's guard takes only the slices
611	// past it without waiting on an inflater.
612	len: AtomicUsize,
613	// The inflated bytes and the group's codec state, counted toward its eviction size
614	// once they exist. Changed only under `state`, or the group's lock for the encoder.
615	bill: cache::Extra,
616	state: Mutex<PlainState>,
617}
618
619#[derive(Default)]
620struct PlainState {
621	// Inflates the stored slices in order. Dropped once a finished group is fully inflated.
622	decoder: Option<flate::Decoder>,
623	// Inflated frames, from the group's first not shed, each with the timestamp and fields
624	// its slice arrived with, so a reader still gets them once the slice is shed.
625	frames: VecDeque<Entry>,
626	// The index of the first frame in `frames`: those before it were shed.
627	base: usize,
628	// What `frames` costs (see [`Plain::cost`]), shed from the front past
629	// [`MAX_CACHE_BYTES`].
630	bytes: u64,
631	// The group's frame count once finished, so the decoder drops after the last frame.
632	// Kept here rather than taken with the slices, which may predate the finish.
633	fin: Option<usize>,
634	// The first failure, sticky: every later frame builds on the one that failed.
635	err: Option<Error>,
636	// The first frame each inflate job in flight still needs, which no shed passes: the job
637	// reads its frames back only after the group's guard is released.
638	pins: Vec<usize>,
639	// Why the group released its frames, failing a late inflater rather than billing past
640	// the release.
641	released: Option<Error>,
642}
643
644impl PlainState {
645	/// The lowest frame an inflate job in flight still needs, or none.
646	fn pinned(&self) -> usize {
647		self.pins.iter().copied().min().unwrap_or(usize::MAX)
648	}
649}
650
651impl Plain {
652	fn new(bill: cache::Extra) -> Self {
653		Self {
654			len: AtomicUsize::new(0),
655			bill,
656			state: Mutex::default(),
657		}
658	}
659
660	fn lock(&self) -> MutexGuard<'_, PlainState> {
661		self.state.lock().unwrap_or_else(PoisonError::into_inner)
662	}
663
664	/// Drop `state`'s decoder, which no frame needs any more.
665	fn drop_decoder(&self, state: &mut PlainState) {
666		if state.decoder.take().is_some() {
667			self.bill.sub_state(flate::DECODER_HEAP);
668		}
669	}
670
671	/// Inflated local frame `local`, or why it is not.
672	fn get(&self, local: usize) -> Result<Bytes> {
673		let state = self.lock();
674		if let Some(err) = &state.released {
675			return Err(err.clone());
676		}
677		let Some(at) = local.checked_sub(state.base) else {
678			return Err(Error::Evicted);
679		};
680		match state.frames.get(at) {
681			Some(entry) => Ok(entry.frame.payload.contiguous(0)),
682			None => Err(state.err.clone().unwrap_or(Error::Dropped)),
683		}
684	}
685
686	/// Whether inflated frame `local` is held.
687	fn holds(&self, local: usize) -> bool {
688		let state = self.lock();
689		state.released.is_none() && (state.base..state.base + state.frames.len()).contains(&local)
690	}
691
692	/// Whether inflated frame `local` was shed, so no plain read can take it again.
693	fn shed_past(&self, local: usize) -> bool {
694		let state = self.lock();
695		state.released.is_none() && local < state.base
696	}
697
698	/// Push the inflated frames held in `local..end` into `prefetch`, returning how many.
699	fn fill(&self, prefetch: &mut Prefetch, local: usize, end: usize) -> usize {
700		let state = self.lock();
701		if state.released.is_some() {
702			return 0;
703		}
704		// Shed since the caller checked it held `local`.
705		let Some(start) = local
706			.checked_sub(state.base)
707			.filter(|start| *start < state.frames.len())
708		else {
709			return 0;
710		};
711		for entry in state.frames.range(start..).take(end.saturating_sub(local)) {
712			prefetch.push(entry, false);
713		}
714		prefetch.len()
715	}
716
717	/// Shed the oldest inflated frames past [`MAX_CACHE_BYTES`], keeping the newest, once
718	/// the frames a read asked for were taken out.
719	fn trim(&self) {
720		let mut state = self.lock();
721		while state.bytes > MAX_CACHE_BYTES && state.frames.len() > 1 {
722			self.pop(&mut state);
723		}
724	}
725
726	/// Inflated frame `local` as a ready source, if held.
727	fn source(&self, local: usize) -> Option<Source> {
728		let state = self.lock();
729		let entry = state.frames.get(local.checked_sub(state.base)?)?;
730		let (header, source) = entry.read(false);
731		Some(Source::Ready(header, source))
732	}
733
734	/// What holding an inflated frame costs: its payload, its slot, and its fields.
735	fn cost(entry: &Entry) -> u64 {
736		let fields = entry.fields.as_ref().map_or(0, |fields| fields.heap());
737		entry.frame.payload.len() as u64 + size_of::<Entry>() as u64 + fields
738	}
739
740	/// Shed the oldest inflated frame, returning what it cost.
741	fn pop(&self, state: &mut PlainState) -> u64 {
742		let bytes = state.frames.pop_front().map_or(0, |entry| Self::cost(&entry));
743		state.base += 1;
744		state.bytes -= bytes;
745		self.bill.sub(bytes);
746		bytes
747	}
748
749	/// Shed inflated frames from the front toward `debt`, freeing at most about `cap`, as
750	/// [`GroupState::shed`] does, keeping the newest when `open`.
751	fn shed(&self, debt: u64, cap: u64, open: bool) -> u64 {
752		let mut state = self.lock();
753		let keep = usize::from(open);
754		let mut freed = 0;
755		while state.frames.len() > keep
756			&& freed < cap
757			&& state
758				.frames
759				.front()
760				.is_some_and(|entry| Self::cost(entry) <= debt - freed)
761		{
762			freed += self.pop(&mut state);
763		}
764		// Each frame billed its slot, not the deque's spare room: free that too once empty.
765		if state.frames.is_empty() {
766			state.frames = VecDeque::new();
767		}
768		freed
769	}
770
771	/// Shed the oldest inflated frames a reader took, those ending at or below `read` on the
772	/// group copy's pace scale, as [`GroupState::shed_taken`] does for the slices. Stops short of
773	/// frame `held`, whose slice is still stored, and of every frame an inflate job in flight
774	/// has yet to take.
775	fn shed_taken(&self, read: u64, held: usize) {
776		let mut state = self.lock();
777		while state.base < held.min(state.pinned())
778			&& state
779				.frames
780				.front()
781				.is_some_and(|entry| entry.end != 0 && entry.end <= read)
782		{
783			self.pop(&mut state);
784		}
785		if state.frames.is_empty() {
786			state.frames = VecDeque::new();
787		}
788	}
789
790	/// Whether inflating failed on the group's content, rather than its release.
791	fn malformed(&self) -> bool {
792		let state = self.lock();
793		state.released.is_none() && state.err.is_some()
794	}
795
796	fn release(&self, err: Error) {
797		let mut state = self.lock();
798		state.decoder = None;
799		state.frames = VecDeque::new();
800		state.bytes = 0;
801		state.released = Some(err);
802		self.len.store(0, Ordering::Release);
803		self.bill.clear();
804	}
805}
806
807/// The stored slices a plain read of a compressed group inflates once the group's guard
808/// is released.
809struct Inflate {
810	release: Arc<Release>,
811	plain: Arc<Plain>,
812	// The group copy's reader progress, told when inflating lets a reclaim shed more slices.
813	pace: Arc<Pace>,
814	// Local index of the first slice: the copy's inflated length when the read took them.
815	from: usize,
816	// The first frame the read needs, pinned in `plain` until this job drops, so no shed of
817	// the inflated copy passes it.
818	keep: usize,
819	// Each stored slice, with its declared inflated size.
820	slices: Vec<Entry>,
821}
822
823impl Inflate {
824	/// Inflate the slices, skipping any a concurrent reader already did, then read local
825	/// frames back with [`Self::get`]. `meter` counts the bytes this read inflated.
826	///
827	/// Locks per frame, so a release waits on at most one frame's inflation. Call with no
828	/// lock held, since settling the debt takes the track's.
829	fn run(&self, meter: &stats::Meter) {
830		let advanced = self.inflate(meter);
831		// Slices a raw reader took that a taken-frame shed kept for this copy may go now.
832		self.pace.retake();
833		// The inflated copy is shared by every copy of the group, the live edge's too.
834		if advanced {
835			self.pace.decoded();
836		}
837		// The inflated bytes are written like a producer's, so they pay the pool's debt the
838		// same way: a finished track has no writer left to settle it.
839		self.plain.bill.settle();
840	}
841
842	/// [`Self::run`] without settling the pool's debt, so the group's guard may be held.
843	///
844	/// The inflated copy keeps at most [`MAX_CACHE_BYTES`], shedding its oldest frames past
845	/// that, but never one an inflate job in flight needs, this one's [`Self::keep`] on.
846	/// Returns whether it inflated a frame.
847	fn inflate(&self, meter: &stats::Meter) -> bool {
848		let mut advanced = false;
849		for (index, slice) in (self.from..).zip(&self.slices) {
850			let released = self.release.error.lock().unwrap_or_else(PoisonError::into_inner);
851			if released.is_some() {
852				break;
853			}
854			let mut state = self.plain.lock();
855			if state.released.is_some() || state.err.is_some() {
856				break;
857			}
858			if state.base + state.frames.len() > index {
859				continue;
860			}
861			let frame = usize::try_from(slice.inflated)
862				.map_err(|_| Error::FrameTooLarge)
863				.and_then(|size| {
864					let bill = &self.plain.bill;
865					let decoder = state.decoder.get_or_insert_with(|| {
866						bill.add_state(flate::DECODER_HEAP);
867						flate::Decoder::new()
868					});
869					decoder.frame(&slice.frame.payload.contiguous(0), size)
870				});
871			match frame {
872				Ok(frame) => {
873					meter.inflated(frame.len() as u64);
874					let entry = Entry {
875						owner: Mutex::new(None),
876						frame: Cached {
877							payload: frame.into(),
878							..slice.frame.clone()
879						},
880						fields: slice.fields.clone(),
881						inflated: 0,
882						end: slice.end,
883					};
884					let cost = Plain::cost(&entry);
885					self.plain.bill.add(cost);
886					state.bytes += cost;
887					state.frames.push_back(entry);
888					advanced = true;
889					while state.bytes > MAX_CACHE_BYTES && state.base < state.pinned().min(index) {
890						self.plain.pop(&mut state);
891					}
892					let len = state.base + state.frames.len();
893					self.plain.len.store(len, Ordering::Release);
894					if state.fin == Some(len) {
895						self.plain.drop_decoder(&mut state);
896					}
897				}
898				Err(err) => {
899					state.err = Some(err);
900					self.plain.drop_decoder(&mut state);
901					break;
902				}
903			}
904		}
905		advanced
906	}
907
908	/// Inflated local frame `local`, or why it is not.
909	fn get(&self, local: usize) -> Result<Bytes> {
910		let released = self.release.error.lock().unwrap_or_else(PoisonError::into_inner);
911		if let Some(err) = released.as_ref() {
912			return Err(err.clone());
913		}
914		self.plain.get(local)
915	}
916}
917
918impl Drop for Inflate {
919	fn drop(&mut self) {
920		let held_back = {
921			let mut state = self.plain.lock();
922			if let Some(at) = state.pins.iter().position(|pin| *pin == self.keep) {
923				state.pins.swap_remove(at);
924			}
925			// A reclaim that visited the copy meanwhile left the frames this job pinned, and with
926			// the slices shed there is nothing else to list it for.
927			state.base < state.pinned()
928				&& state
929					.frames
930					.front()
931					.is_some_and(|entry| entry.end != 0 && entry.end <= self.pace.read())
932		};
933		if held_back {
934			self.pace.retake_inflated();
935		}
936	}
937}
938
939/// A frame resolved under the group's guard, by [`GroupState::poll_frame_source`].
940enum Source {
941	/// Ready to hand out.
942	Ready(frame::Header, frame::Source),
943	/// A plain read of a compressed group: local frame `local` once `job` inflates it.
944	Inflate {
945		job: Inflate,
946		local: usize,
947		timestamp: Timestamp,
948		fields: Option<Arc<super::object::Fields>>,
949	},
950}
951
952/// The IETF header state that cannot be inferred from a plain frame list.
953#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
954#[derive(Clone, Debug)]
955pub(crate) struct Wire {
956	/// Object IDs differ from the public frame ordinals, so ordinal recovery cannot stitch.
957	pub sparse: bool,
958	pub first_object: bool,
959	pub first_id: u64,
960	pub extensions: bool,
961	pub has_end: bool,
962	/// The first frame of an ordinal copy that follows an Object ID it lacks with no gap mark.
963	/// The frames before it keep their place in the group; it and every frame after don't.
964	pub hole: Option<u64>,
965	pub last: Option<u64>,
966}
967
968#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
969impl Wire {
970	/// Whether every Object ID this copy lacks is accounted for, so a FETCH of any part of it
971	/// gets what upstream would answer.
972	pub fn fetchable(&self) -> bool {
973		self.hole.is_none()
974	}
975}
976
977/// Where a group sits in presentation time.
978///
979/// Its first frame settles which: an empty group has not presented anything yet, which
980/// is a different answer from a group on an untimed track, whose frames carry no time.
981#[derive(Clone, Copy, Debug, Default)]
982enum Timeline {
983	/// No frame opened yet.
984	#[default]
985	Empty,
986	/// The track is untimed, so the group has no place in media time.
987	Untimed,
988	/// `start` is the first frame's timestamp, never revised. `latest` is the highest
989	/// frame's: the group's presentation end so far, which a reader that has taken
990	/// every frame sits at and a drift budget measures it against.
991	Timed { start: Timestamp, latest: Timestamp },
992}
993
994/// How a timed group's start was checked against its neighbors' (see
995/// [`track::Neighbors`]), which decides whether it bounds theirs.
996#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
997pub(super) enum Origin {
998	/// Not checked: untimed, started past frame 0, written with no open track, or received
999	/// from a session. A start read off a later frame is not where the group began, and a
1000	/// received one may not be media time, so it bounds nothing.
1001	#[default]
1002	Unchecked,
1003	/// Frame 0 fit between its neighbors, so its start bounds theirs.
1004	Bound,
1005	/// Frame 0 landed at or below the track's eviction watermark, where its lower bound
1006	/// may be gone. Accepted so backfill keeps working, but it neither bounds a neighbor
1007	/// nor drives media-time expiry.
1008	Unverified,
1009}
1010
1011impl GroupState {
1012	/// Refuse a write that would advance the group to `next_index`, past the track's end.
1013	fn admit(&self, next_index: usize) -> Result<()> {
1014		match self.limit {
1015			Some(limit) if next_index > limit => Err(Error::Closed),
1016			_ => Ok(()),
1017		}
1018	}
1019
1020	/// One past the last frame that was fully written. Trails `next_index` while a chunked
1021	/// frame is in flight, which is the frame a replacement route has to redeliver: only
1022	/// its opener saw the payload, and only partly. Outlives the frames' release.
1023	fn committed(&self) -> usize {
1024		self.log.end() as usize
1025	}
1026
1027	/// The index of the first committed frame this copy still holds: `offset`, unless its
1028	/// front was shed.
1029	fn held(&self) -> usize {
1030		self.log.base() as usize - self.front.len()
1031	}
1032
1033	/// Refuse a read at `index`: below where the copy started, or shed from its front. A
1034	/// plain read of a compressed group still finds a shed slice's frame in the inflated
1035	/// copy, while that holds it, and loses one the inflated copy shed even while the slice
1036	/// stays.
1037	fn check_read(&self, index: usize, raw: bool) -> Result<()> {
1038		if index < self.offset {
1039			return Err(Error::Lagged);
1040		}
1041		let plain = self.plain(raw);
1042		let shed = match index < self.held() {
1043			true => plain.is_none_or(|plain| !plain.holds(index)),
1044			false => plain.is_some_and(|plain| plain.shed_past(index)),
1045		};
1046		if shed {
1047			return Err(self.outcome.error().cloned().unwrap_or(Error::Evicted));
1048		}
1049		Ok(())
1050	}
1051
1052	/// The inflated copy a plain read of a compressed group takes frames from.
1053	fn plain(&self, raw: bool) -> Option<&Plain> {
1054		self.flate.as_ref().filter(|_| !raw).map(|flate| &*flate.plain)
1055	}
1056
1057	/// The committed frame at `index`, while this copy holds it.
1058	fn entry(&self, index: usize) -> Option<&Entry> {
1059		let index = index as u64;
1060		if index < self.log.base() {
1061			return self
1062				.front
1063				.get(usize::try_from(index.checked_sub(self.held() as u64)?).ok()?);
1064		}
1065		self.log.get(index)
1066	}
1067
1068	/// Each frame's moq-timestamp Object ID and timestamp value in order, from frame 0 through
1069	/// any in flight, for the group starting at `start`; `None` once this copy no longer holds
1070	/// frame 0. Stops before [`Self::unproven`].
1071	///
1072	/// Derived from timestamps alone, so every copy holding frame 0 agrees on them, while a
1073	/// copy without it cannot know where a run of tied timestamps pushed the IDs.
1074	/// `timestamp_ids` says whether a relayed copy's wire Object IDs are timestamp IDs.
1075	#[cfg(feature = "async")]
1076	fn timed_ids(&self, start: u64, timestamp_ids: bool) -> Option<impl Iterator<Item = (u64, u64)> + '_> {
1077		let whole = match self.wire() {
1078			None => true,
1079			// Timestamp IDs skip ticks with no gap mark, so only a copy from the group's first
1080			// object whose IDs match the derived ones vouches for holding every frame.
1081			Some(wire) if timestamp_ids => wire.first_object && !wire.sparse,
1082			// Ordinal IDs declare each skipped ID with a gap, so the frames before the first ID
1083			// a copy lacks unaccounted, its head's included, are every frame up to there.
1084			Some(_) => true,
1085		};
1086		if self.held() != 0 || !whole {
1087			return None;
1088		}
1089		let proven = self.unproven(timestamp_ids).map_or(usize::MAX, |hole| hole as usize);
1090		let partial = self.partial.as_ref().map(|partial| partial.timestamp);
1091		let stamps = self.entries(0, self.committed()).map(|entry| entry.frame.timestamp);
1092		let mut prior: Option<(u64, u64)> = None;
1093		Some(stamps.chain(partial).take(proven).map(move |timestamp| {
1094			// A lower timestamp, which only a lite-05/06 copy holds, rides at the highest before
1095			// it, as on lite-07 (see `lite::Clock::encode_delta`).
1096			let dts = prior.map_or(timestamp.value(), |(_, high)| high.max(timestamp.value()));
1097			let (id, _) = crate::ietf::object::timestamp_object_id(start, prior.map(|(id, _)| id), dts);
1098			prior = Some((id, dts));
1099			(id, dts)
1100		}))
1101	}
1102
1103	/// The first frame whose moq-timestamp Object ID this ordinal copy can't derive: the
1104	/// [hole](Wire::hole) after an Object ID it lacks unaccounted, which may have pushed the
1105	/// IDs after it higher. `None` for a copy missing nothing, or one whose wire IDs are
1106	/// timestamp IDs, which judges its head by its first ID instead.
1107	#[cfg(feature = "async")]
1108	fn unproven(&self, timestamp_ids: bool) -> Option<u64> {
1109		self.wire().filter(|_| !timestamp_ids)?.hole
1110	}
1111
1112	/// The committed frames held in `start..end`, in order.
1113	fn entries(&self, start: usize, end: usize) -> impl Iterator<Item = &Entry> {
1114		(start.max(self.held())..end.min(self.committed())).map_while(|index| self.entry(index))
1115	}
1116
1117	/// What holding `entry` charges the group: its payload unless canonical content owns
1118	/// it, and its fields' heap.
1119	fn entry_bytes(&self, entry: &Entry) -> u64 {
1120		let payload = entry.frame.payload.len() as u64;
1121		let fields = entry.fields.as_ref().map_or(0, |fields| fields.heap());
1122		let payload = if self.content.is_none() { payload } else { 0 };
1123		payload + fields
1124	}
1125
1126	/// The bytes the live tail holds: every committed frame, their fields, and the
1127	/// in-flight frame at its declared size.
1128	fn tail(&self) -> u64 {
1129		self.cache + self.relay.as_ref().map_or(0, |relay| relay.bytes) + self.unwritten()
1130	}
1131
1132	/// The frame slots the tail holds beyond the log's first segment, so a group of empty
1133	/// frames is bounded too.
1134	fn slots(&self) -> u64 {
1135		let log = self.log.heap().saturating_sub(kio::log::Writer::<Entry>::HEAP);
1136		(log + self.front.capacity() * size_of::<Entry>()) as u64
1137	}
1138
1139	/// Stop counting a shed frame's bytes, returning what it charged.
1140	fn unhold(&mut self, entry: &Entry) -> u64 {
1141		let fields = entry.fields.as_ref().map_or(0, |fields| fields.heap());
1142		self.forget(entry.frame.payload.len() as u64, fields);
1143		self.entry_bytes(entry)
1144	}
1145
1146	/// Stop counting `payload` and `fields` bytes of shed frames.
1147	fn forget(&mut self, payload: u64, fields: u64) {
1148		self.cache -= payload;
1149		if let Some(relay) = &mut self.relay {
1150			relay.bytes -= fields;
1151		}
1152	}
1153
1154	/// Shed every committed frame held below `end`, oldest first, and return the bytes
1155	/// that frees.
1156	///
1157	/// A compressed group whose plain copy started inflates the slices first, so its plain
1158	/// readers carry on past them; one that never started never will.
1159	fn shed_to(&mut self, end: usize) -> u64 {
1160		self.shed_frames(end, true)
1161	}
1162
1163	/// [`Self::shed_to`], inflating the slices for the plain copy first only when `inflate`:
1164	/// not when that copy is about to be shed too.
1165	fn shed_frames(&mut self, end: usize, inflate: bool) -> u64 {
1166		let end = end.min(self.committed());
1167		if end <= self.held() {
1168			return 0;
1169		}
1170		if inflate
1171			&& let Some(flate) = &self.flate
1172			&& flate.plain.len.load(Ordering::Acquire) > 0
1173			&& let Ok(job) = self.inflate(flate, end - 1, end - 1)
1174		{
1175			// Inflated under the guard: the slices are gone once it is released. Settled by
1176			// the next write, which takes the track's lock first.
1177			job.inflate(&stats::Meter::default());
1178		}
1179		let mut freed = 0;
1180		while self.held() < end
1181			&& let Some(entry) = self.front.pop_front()
1182		{
1183			self.shed_high = self.shed_high.max(entry.frame.timestamp.value());
1184			freed += self.unhold(&entry);
1185		}
1186		// An adopted head's slots were billed by capacity, so the emptied deque frees them.
1187		if self.front.is_empty() && self.front.capacity() > 0 {
1188			freed += (self.front.capacity() * size_of::<Entry>()) as u64;
1189			self.front = VecDeque::new();
1190		}
1191		let base = self.log.base() as usize;
1192		if base < end {
1193			let (mut charged, mut payload, mut fields, mut shed) = (0, 0, 0, 0);
1194			for entry in (base..end).map(|index| self.log.get(index as u64).expect("committed below the end")) {
1195				self.shed_high = self.shed_high.max(entry.frame.timestamp.value());
1196				shed = entry.end;
1197				charged += self.entry_bytes(entry);
1198				payload += entry.frame.payload.len() as u64;
1199				fields += entry.fields.as_ref().map_or(0, |fields| fields.heap());
1200			}
1201			self.forget(payload, fields);
1202			self.pace.shed(shed);
1203			let heap = kio::log::Writer::<Entry>::HEAP;
1204			let before = self.log.heap().max(heap);
1205			self.evict_log(end as u64);
1206			freed += charged + (before - self.log.heap().max(heap)) as u64;
1207		}
1208		self.charge.sub(freed);
1209		freed
1210	}
1211
1212	/// Evict the log below `end`, letting go of each frame's canonical content now.
1213	///
1214	/// The log drops an evicted entry only once epoch reclamation runs, which reads on any
1215	/// other thread can hold back, so content billed until its last holder drops would stay
1216	/// billed that long, past the eviction that was meant to free it.
1217	fn evict_log(&mut self, end: u64) {
1218		for index in self.log.base()..end.min(self.log.end()) {
1219			let entry = self.log.get(index).expect("committed below the end");
1220			let owner = entry.owner.lock().unwrap_or_else(PoisonError::into_inner).take();
1221			drop(owner);
1222		}
1223		self.log.evict(end);
1224	}
1225
1226	/// Shed the oldest committed frames until `extra` more bytes fit the live tail
1227	/// ([`MAX_CACHE_BYTES`]) with their slots, returning whether the bytes do.
1228	///
1229	/// Slots free a segment at a time, so each shed frame counts as one slot's worth.
1230	fn trim(&mut self, extra: u64) -> bool {
1231		let mut tail = self.tail().saturating_add(extra);
1232		let mut slots = self.slots();
1233		if tail.saturating_add(slots) <= MAX_CACHE_BYTES {
1234			return true;
1235		}
1236		let mut end = self.held();
1237		while tail.saturating_add(slots) > MAX_CACHE_BYTES
1238			&& let Some(entry) = self.entry(end)
1239		{
1240			tail -= entry.frame.payload.len() as u64 + entry.fields.as_ref().map_or(0, |fields| fields.heap());
1241			slots = slots.saturating_sub(size_of::<Entry>() as u64);
1242			end += 1;
1243		}
1244		self.shed_to(end);
1245		tail <= MAX_CACHE_BYTES
1246	}
1247
1248	/// Shed whole frames from the front toward `debt`, freeing at most about `cap`, and
1249	/// return the bytes freed.
1250	///
1251	/// An open group keeps its newest committed frame, for the reader about to take it. A
1252	/// frame larger than what is left of `debt` stays, and so does everything after it,
1253	/// carrying the debt over as a whole group does. A compressed group's plain copy sheds
1254	/// its front the same way.
1255	fn shed(&mut self, debt: u64, cap: u64) -> u64 {
1256		if self.outcome.error().is_some() {
1257			return 0;
1258		}
1259		let last = match self.outcome.frames() {
1260			Some(_) => self.committed(),
1261			None => self.committed().saturating_sub(1),
1262		};
1263		let mut end = self.held();
1264		let mut size = 0u64;
1265		while end < last
1266			&& size < cap
1267			&& let Some(entry) = self.entry(end)
1268		{
1269			let bytes = self.entry_bytes(entry);
1270			if bytes > debt - size {
1271				break;
1272			}
1273			size += bytes;
1274			end += 1;
1275		}
1276		let mut freed = self.shed_to(end);
1277		if let Some(flate) = &self.flate
1278			&& freed < cap
1279			&& freed < debt
1280		{
1281			freed += flate
1282				.plain
1283				.shed(debt - freed, cap - freed, self.outcome.frames().is_none());
1284		}
1285		freed
1286	}
1287
1288	/// Shed every committed frame, an open group's newest too, keeping the timeline the
1289	/// frames presented. A reader of a shed frame reads it as [`Error::Evicted`].
1290	///
1291	/// A received compressed group inflates nothing to do it. When that sheds slices its plain
1292	/// copy has not inflated yet, the copy can never inflate past them, so it is released too,
1293	/// decoder included, and its readers read the rest as evicted. Otherwise, and in a group a
1294	/// local producer is still compressing into, the plain copy keeps going, as any shed does:
1295	/// nothing it would decode next is gone.
1296	fn shed_all(&mut self) {
1297		if self.outcome.error().is_some() {
1298			return;
1299		}
1300		let compressing = self.flate.as_ref().is_some_and(|flate| flate.encoder.is_some());
1301		let (held, end) = (self.held(), self.committed());
1302		self.shed_frames(end, compressing);
1303		if let Some(flate) = &self.flate {
1304			let stranded = !compressing && held < end && flate.plain.len.load(Ordering::Acquire) < end;
1305			match stranded {
1306				true => flate.plain.release(Error::Evicted),
1307				false => {
1308					flate.plain.shed(u64::MAX, u64::MAX, false);
1309				}
1310			}
1311		}
1312	}
1313
1314	/// Shed the front frames the fastest reader took, those ending at or below `read` on the
1315	/// pace scale: a reader on the group loses nothing it has yet to take, though a slower one
1316	/// falls off as after any shed. Frames adopted from a head are off that scale, so the shed
1317	/// stops at them. So does a started plain copy's inflated prefix: inflating slices to shed
1318	/// them would bill the session more than it frees.
1319	///
1320	/// The plain copy's own front goes with them: each inflated frame whose slice that reader
1321	/// took, by the `end` it kept. A long group's tail shed leaves inflated frames past `read`
1322	/// to the plain reader owed them, so the slice front does not bound this. A copy whose
1323	/// content other copies share leaves them: those readers' progress is not on its scale.
1324	fn shed_taken(&mut self, read: u64) {
1325		if self.outcome.error().is_some() {
1326			return;
1327		}
1328		let inflated = match &self.flate {
1329			Some(flate) => match flate.plain.len.load(Ordering::Acquire) {
1330				0 => usize::MAX,
1331				len => len,
1332			},
1333			None => usize::MAX,
1334		};
1335		let mut end = self.held();
1336		while end < inflated
1337			&& let Some(entry) = self.entry(end)
1338			&& entry.end != 0
1339			&& entry.end <= read
1340		{
1341			end += 1;
1342		}
1343		self.shed_frames(end, false);
1344		if let Some(flate) = &self.flate
1345			&& self.content.is_none()
1346		{
1347			flate.plain.shed_taken(read, self.held());
1348		}
1349	}
1350
1351	/// Whether a frame still arriving bills the session: its payload or its header's fields.
1352	fn arriving(&self) -> bool {
1353		self.partial
1354			.as_ref()
1355			.is_some_and(|partial| !partial.scratch && (partial.charged > 0 || partial.fields.is_some()))
1356	}
1357
1358	/// Whether this copy holds no committed frame.
1359	fn is_empty(&self) -> bool {
1360		self.front.is_empty() && self.log.base() == self.log.end()
1361	}
1362
1363	/// Append a completed frame, returning the slot growth it charged.
1364	fn push(&mut self, mut entry: Entry) -> u64 {
1365		let slots = self.reserve_frame();
1366		entry.end = self.pace.commit(entry.cost());
1367		self.log.push(entry);
1368		slots
1369	}
1370
1371	/// Store a whole frame: count its bytes, extend the timeline, and charge its slot plus,
1372	/// unless canonical content already owns the payload, its bytes.
1373	///
1374	/// Returns the coarse tick it stamped, like [`cache::Charge::add`].
1375	fn commit(&mut self, entry: Entry) -> Option<u64> {
1376		let size = entry.frame.payload.len() as u64;
1377		self.cache += size;
1378		self.stamp(entry.frame.timestamp);
1379		let slots = self.push(entry);
1380		self.charge.add(slots + if self.content.is_none() { size } else { 0 })
1381	}
1382
1383	/// Whether a compressed group's content failed to inflate.
1384	fn malformed(&self) -> bool {
1385		self.flate.as_ref().is_some_and(|flate| flate.plain.malformed())
1386	}
1387
1388	/// Whether the first frame opened, or the group ended without one.
1389	#[cfg(debug_assertions)]
1390	fn started(&self) -> bool {
1391		!matches!(self.timeline, Timeline::Empty) || self.outcome.frames().is_some() || self.outcome.error().is_some()
1392	}
1393
1394	/// The bytes the in-flight frame declared but has not written yet, which its open
1395	/// already admitted.
1396	fn unwritten(&self) -> u64 {
1397		self.partial
1398			.as_ref()
1399			.map_or(0, |partial| partial.buf.size() as u64 - partial.charged)
1400	}
1401
1402	/// Content still available to a reader of this group.
1403	///
1404	/// Counts the in-flight frame at its declared size, like [`Self::content_range`]: a
1405	/// reader that skips it misses the whole frame, however much has arrived.
1406	fn content(&self) -> stats::Content {
1407		stats::Content {
1408			bytes: self.cache + self.unwritten(),
1409			frames: self.next_index.saturating_sub(self.held()) as u64,
1410			groups: 1,
1411		}
1412	}
1413
1414	/// Content in the half-open frame range that is still cached here.
1415	pub(super) fn content_range(&self, start: usize, end: usize) -> stats::Content {
1416		let start = start.max(self.held());
1417		let end = end.min(self.next_index);
1418		if start >= end {
1419			return stats::Content::default();
1420		}
1421
1422		let mut bytes = self
1423			.entries(start, end)
1424			.map(|entry| entry.frame.payload.len() as u64)
1425			.sum();
1426		let committed = self.committed();
1427		if start <= committed
1428			&& committed < end
1429			&& let Some(partial) = &self.partial
1430		{
1431			bytes += partial.buf.size() as u64;
1432		}
1433
1434		stats::Content {
1435			bytes,
1436			frames: (end - start) as u64,
1437			groups: 0,
1438		}
1439	}
1440
1441	/// The slices a plain read of a compressed group still needs inflated to reach frame
1442	/// `last`, to inflate once the guard is released. The inflated copy sheds nothing from
1443	/// `first` on while it runs, so the reader gets every frame it asked for.
1444	///
1445	/// [`Error::Lagged`] when the group started past frame 0: its first slice builds on
1446	/// frames it never held. [`Error::Evicted`] when the slices it needs were shed first.
1447	fn inflate(&self, flate: &Flate, first: usize, last: usize) -> Result<Inflate> {
1448		if self.offset != 0 {
1449			return Err(Error::Lagged);
1450		}
1451		let from = flate.plain.len.load(Ordering::Acquire).min(last + 1);
1452		// The slices the plain copy needs next were shed before it inflated them.
1453		if from <= last && from < self.held() {
1454			return Err(self.outcome.error().cloned().unwrap_or(Error::Evicted));
1455		}
1456		let release = flate
1457			.release
1458			.clone()
1459			.ok_or_else(|| self.outcome.error().cloned().unwrap_or(Error::Dropped))?;
1460		// Under the group's guard, so a shed that takes it sees the pin or finds no job.
1461		flate.plain.lock().pins.push(first);
1462		Ok(Inflate {
1463			release,
1464			plain: flate.plain.clone(),
1465			pace: self.pace.clone(),
1466			from,
1467			keep: first,
1468			slices: self.entries(from, last + 1).cloned().collect(),
1469		})
1470	}
1471
1472	/// Resolve the source for the frame at `index`: a completed frame (whole) or the
1473	/// in-flight tail (streamed). Used by [`Consumer::poll_next_frame`].
1474	///
1475	/// A compressed group hands a plain reader each frame whole once it completes, as the
1476	/// slices to inflate, and a `raw` one the stored slice, streaming one still arriving.
1477	/// A frame handed out counts as taken, pacing the writer (see [`Pace`]).
1478	fn poll_frame_source(&self, index: usize, raw: bool) -> Poll<Result<Option<Source>>> {
1479		self.check_read(index, raw)?;
1480		if index < self.held()
1481			&& let Some(plain) = self.plain(raw)
1482		{
1483			self.charge.refresh();
1484			return Poll::Ready(plain.source(index).map(Some).ok_or(Error::Evicted));
1485		}
1486		if let Some(entry) = self.entry(index) {
1487			// A frame read is a cache access: stamp it so expiry and the eviction
1488			// walk spare a group a consumer is actively draining.
1489			self.charge.refresh();
1490			if let Some(flate) = self.flate.as_ref().filter(|_| !raw) {
1491				self.pace.took(entry.end);
1492				return Poll::Ready(Ok(Some(Source::Inflate {
1493					job: self.inflate(flate, index, index)?,
1494					local: index,
1495					timestamp: entry.frame.timestamp,
1496					fields: entry.fields.clone(),
1497				})));
1498			}
1499			let (header, source) = entry.read(self.sized());
1500			self.pace.took(entry.end);
1501			return Poll::Ready(Ok(Some(Source::Ready(header, source))));
1502		}
1503		if index == self.committed()
1504			&& let Some(p) = &self.partial
1505			&& !p.scratch
1506			&& (raw || self.flate.is_none())
1507		{
1508			self.charge.refresh();
1509			// A reader streaming the open frame is at the writer's edge.
1510			self.pace.took_committed();
1511			let info = frame::Info {
1512				size: p.buf.size() as u64,
1513				timestamp: p.timestamp,
1514			};
1515			return Poll::Ready(Ok(Some(Source::Ready(
1516				frame::Header {
1517					info,
1518					fields: p.fields.clone(),
1519					inflated: p.inflated,
1520				},
1521				frame::Source::Partial(p.buf.clone()),
1522			))));
1523		}
1524		ready!(self.poll_terminal(index))?;
1525		Poll::Ready(Ok(None))
1526	}
1527
1528	/// Resolve the group's terminal state for a reader positioned at `index`.
1529	///
1530	/// A finished group is still aborted once its frames are released to free memory
1531	/// (idle past the cache pool's expiry window, or evicted under its byte target). A reader
1532	/// that already consumed every frame is missing nothing, so it gets the clean end of
1533	/// group; one that fell short sees the abort rather than a silently truncated stream.
1534	/// A copy cut short at the back holds nothing past its cut, which a reader reaches only
1535	/// with its cap past it (one capped there ends before asking), so the frames it wants
1536	/// are missing rather than the group ended.
1537	fn poll_terminal(&self, index: usize) -> Poll<Result<()>> {
1538		if self.past_cut(index) {
1539			return Poll::Ready(Err(Error::Evicted));
1540		}
1541		match &self.outcome {
1542			Outcome::Released(total, _, abort) if index < *total => Poll::Ready(Err(abort.error().clone())),
1543			Outcome::Finished(..) | Outcome::Released(..) => Poll::Ready(Ok(())),
1544			Outcome::Aborted(abort) => Poll::Ready(Err(abort.error().clone())),
1545			Outcome::Open => {
1546				// Waiting on frames the writer has yet to commit, wherever the reader skipped
1547				// to, so it holds the writer back from none of them.
1548				if index >= self.committed() {
1549					self.pace.took_committed();
1550				}
1551				Poll::Pending
1552			}
1553		}
1554	}
1555
1556	/// Where this copy settled at the back cut its transport bound made. One that finished
1557	/// short of its bound holds the whole group, which ends there.
1558	fn cut(&self) -> Option<usize> {
1559		self.outcome.frames().filter(|&frames| self.range_end == Some(frames))
1560	}
1561
1562	/// Whether this copy settled at its back cut, with `index` at or past it.
1563	fn past_cut(&self, index: usize) -> bool {
1564		self.cut().is_some_and(|cut| index >= cut)
1565	}
1566
1567	/// The relay state once the ingest has settled it, which it does before the first frame,
1568	/// the end object, or the close: a group is visible before its header is read.
1569	#[cfg(feature = "async")]
1570	fn poll_wire(&self) -> Poll<Result<Option<Wire>>> {
1571		let settled = self.wrote
1572			|| self.partial.is_some()
1573			|| self.relay.as_ref().is_some_and(|relay| relay.end_object.is_some())
1574			|| !matches!(self.outcome, Outcome::Open);
1575		match settled {
1576			true => Poll::Ready(Ok(self.wire().cloned())),
1577			false => Poll::Pending,
1578		}
1579	}
1580
1581	/// The first time the group can't yet place: none once finished, else its newest frame's
1582	/// timestamp, or 0 with no timed frame. A frame past a time puts the group's End past it
1583	/// too, and an aborted copy may have lost the End its group was sent with.
1584	fn unplaced_from(&self) -> Option<u64> {
1585		match (self.poll_outcome(), &self.timeline) {
1586			(Poll::Ready(Ok(())), _) => None,
1587			(_, Timeline::Timed { latest, .. }) => Some(latest.value()),
1588			_ => Some(0),
1589		}
1590	}
1591
1592	/// Whether the group places `time`; see [`Self::unplaced_from`].
1593	fn places(&self, time: u64) -> bool {
1594		self.unplaced_from().is_none_or(|from| time < from)
1595	}
1596
1597	/// The group's outcome once final: `Ok` once finished, which a later abort only frees
1598	/// the cache of, or the abort error.
1599	fn poll_outcome(&self) -> Poll<Result<()>> {
1600		match &self.outcome {
1601			Outcome::Finished(..) | Outcome::Released(..) => Poll::Ready(Ok(())),
1602			Outcome::Aborted(abort) => Poll::Ready(Err(abort.error().clone())),
1603			Outcome::Open => Poll::Pending,
1604		}
1605	}
1606
1607	/// Resolve whether a reader at `index`, which already prefetched the frames below
1608	/// `unread`, can still make progress, answering the same question as a read without
1609	/// consuming anything.
1610	/// A cut short of the reader's cap `end` leaves the frames past it missing, whatever
1611	/// the reader reads before it.
1612	fn poll_end(&self, index: usize, unread: usize, raw: bool, end: Option<usize>) -> Poll<Result<()>> {
1613		self.check_read(unread, raw)?;
1614		if self.cut().is_some_and(|cut| end.is_none_or(|end| end > cut)) {
1615			return Poll::Ready(Err(Error::Evicted));
1616		}
1617		self.poll_terminal(index)
1618	}
1619
1620	/// Check the next frame's `timestamp`, returning how to record the group's start.
1621	///
1622	/// A group's timestamps never decrease, so lite-07 carries them as unsigned deltas and a
1623	/// moq-transport Object ID as their offset from the group's start: a frame below its
1624	/// predecessor is [`Error::TimestampMismatch`].
1625	///
1626	/// On a [keyed](Producer::keyed) group, a timed frame 0 off the group's `key` is
1627	/// [`Error::TimestampMismatch`] too, since lite-07 could not carry it.
1628	///
1629	/// Frame 0 is also checked against the track's `neighbors`. Anything but a timed frame 0
1630	/// checked under an open local track is unchecked, including a relayed copy's first object
1631	/// when it starts mid-group.
1632	fn check_frame(&self, neighbors: Option<&track::Neighbors>, key: u64, timestamp: Timestamp) -> Result<Origin> {
1633		if let Timeline::Timed { latest, .. } = self.timeline
1634			&& timestamp.value() < latest.value()
1635		{
1636			return Err(Error::TimestampMismatch);
1637		}
1638		let first = self.next_index == 0 && !self.wire().is_some_and(|wire| !wire.first_object);
1639		match (neighbors, timestamp.timed()) {
1640			(_, Some(start)) if first && self.keyed && start.value() != key => Err(Error::TimestampMismatch),
1641			(Some(neighbors), Some(start)) if first => neighbors.admit(start),
1642			_ => Ok(self.origin),
1643		}
1644	}
1645
1646	/// Settle how the group holds its start, returning it if frame 0 just became a bound.
1647	fn settle(&mut self, origin: Origin) -> Option<Timestamp> {
1648		let bound = origin == Origin::Bound && self.origin != Origin::Bound;
1649		self.origin = origin;
1650		match self.timeline {
1651			Timeline::Timed { start, .. } if bound => Some(start),
1652			_ => None,
1653		}
1654	}
1655
1656	/// Record a frame's place in presentation time: the first frame starts the group,
1657	/// and later frames can extend a timed group's end. Every frame matches its track
1658	/// ([`track::Info::rescale`]), so a group never mixes the two.
1659	fn stamp(&mut self, timestamp: Timestamp) {
1660		self.timeline = match (self.timeline, timestamp.timed()) {
1661			(Timeline::Timed { start, latest }, Some(timestamp)) => Timeline::Timed {
1662				start,
1663				latest: latest.later(timestamp),
1664			},
1665			(_, Some(start)) => Timeline::Timed { start, latest: start },
1666			(_, None) => Timeline::Untimed,
1667		};
1668	}
1669
1670	/// The relay state, charging its box the first time a group needs it.
1671	fn relay(&mut self) -> &mut Relay {
1672		let charge = &mut self.charge;
1673		self.relay.get_or_insert_with(|| {
1674			let bytes = size_of::<Relay>() as u64;
1675			charge.add(bytes);
1676			Box::new(Relay {
1677				bytes,
1678				..Default::default()
1679			})
1680		})
1681	}
1682
1683	pub(super) fn wire(&self) -> Option<&Wire> {
1684		self.relay.as_ref()?.wire.as_ref()
1685	}
1686
1687	/// See [`Handle::last_data_object`].
1688	fn last_data_object(&self) -> Option<u64> {
1689		match self.wire() {
1690			Some(wire) => match self.relay.as_ref().filter(|relay| relay.end_object.is_some()) {
1691				Some(relay) => relay.last_before_end,
1692				None => wire.last,
1693			},
1694			None => (self.next_index as u64).checked_sub(1),
1695		}
1696	}
1697
1698	fn wire_mut(&mut self) -> Option<&mut Wire> {
1699		self.relay.as_mut()?.wire.as_mut()
1700	}
1701
1702	/// Record a relayed object's wire `id` at frame `index` of the group starting at `start`.
1703	///
1704	/// A copy stays ordinal-aligned while each ID is its ordinal, or, on a track whose Object
1705	/// IDs are timestamps (`timestamp_ids`), the moq-timestamp ID its timestamp takes after the
1706	/// previous object's (see [`crate::ietf::object::timestamp_object_id`]): either way the
1707	/// same frame has the same ID on every copy from frame 0. Anything else, or a copy whose
1708	/// first object is not the group's, is sparse.
1709	fn relayed(&mut self, id: u64, index: u64, start: u64, timestamp: Timestamp, timestamp_ids: bool) {
1710		let offset = self.offset;
1711		let Some(wire) = self.wire_mut() else {
1712			return;
1713		};
1714		let prior = wire.last.replace(id);
1715		let timed = timestamp_ids && id == crate::ietf::object::timestamp_object_id(start, prior, timestamp.value()).0;
1716		if offset == 0 {
1717			wire.sparse |= (id != index && !timed) || (!wire.first_object && wire.first_id > 0);
1718		} else if !timestamp_ids {
1719			wire.sparse |= id != index;
1720		}
1721	}
1722
1723	fn canonicalize(&self, index: usize, entry: &mut Entry) -> Result<()> {
1724		let Some(content) = &self.content else {
1725			return Ok(());
1726		};
1727		let key = Content::key(index, entry.fields.as_deref(), self.wire().is_some());
1728		let input = match entry.owner.lock().unwrap_or_else(PoisonError::into_inner).clone() {
1729			Some(row) => Input::Adopt(row),
1730			None => Input::Whole(entry.frame.payload.clone()),
1731		};
1732		let row = content.row(
1733			Spec {
1734				key,
1735				size: entry.frame.payload.len() as u64,
1736				inflated: self.sized().then_some(entry.inflated),
1737			},
1738			input,
1739			&self.charge,
1740			None,
1741		)?;
1742		entry.frame.payload = row.freeze();
1743		*entry.owner.lock().unwrap_or_else(PoisonError::into_inner) = Some(row);
1744		Ok(())
1745	}
1746
1747	/// The cache account of the track this copy belongs to, kept after its frames are freed.
1748	pub(super) fn account(&self) -> Option<&Arc<cache::Track>> {
1749		self.charge.account()
1750	}
1751
1752	/// Whether each entry carries a declared plain size beside its stored payload: a
1753	/// compressed group's slices, or a metadata copy's headers.
1754	fn sized(&self) -> bool {
1755		self.flate.is_some() || self.meta
1756	}
1757
1758	/// Whether Object IDs left the frame ordinals, so ordinal recovery cannot stitch.
1759	pub(super) fn sparse(&self) -> bool {
1760		self.wire().is_some_and(|wire| wire.sparse)
1761	}
1762
1763	/// Reserve the next completed frame's slot, returning growth not covered by the fixed
1764	/// overhead, which holds the log's first segment.
1765	fn reserve_frame(&mut self) -> u64 {
1766		let heap = kio::log::Writer::<Entry>::HEAP;
1767		let before = self.log.heap().max(heap);
1768		self.log.reserve();
1769		(self.log.heap().max(heap) - before) as u64
1770	}
1771
1772	/// Charge the in-flight frame's bytes written since its last charge, as a write access.
1773	///
1774	/// Returns the coarse tick it stamped, like [`cache::Charge::add`].
1775	fn charge_partial(&mut self) -> Option<u64> {
1776		let written = match &mut self.partial {
1777			// Scratch is charged as the slice it commits as.
1778			Some(partial) if partial.scratch => 0,
1779			Some(partial) => {
1780				let written = partial.buf.written(Ordering::Acquire) as u64;
1781				written - std::mem::replace(&mut partial.charged, written)
1782			}
1783			None => 0,
1784		};
1785		self.cache += written;
1786		let slots = match &self.partial {
1787			Some(_) => self.reserve_frame(),
1788			None => 0,
1789		};
1790		self.charge
1791			.add(slots + if self.content.is_none() { written } else { 0 })
1792	}
1793
1794	/// Whether the frames held start at the group's first object.
1795	fn first_object(&self) -> bool {
1796		self.wire().map_or(self.offset == 0, |wire| wire.first_object)
1797	}
1798
1799	/// The committed frames, for a successor copy to adopt. Sparse Object IDs refuse
1800	/// ordinal recovery, so they lend nothing.
1801	fn head(&self) -> Option<Head> {
1802		if self.is_empty() || self.sparse() {
1803			return None;
1804		}
1805		let start = self.held();
1806		Some(Head {
1807			content: self.content.clone(),
1808			start,
1809			first_object: start == self.offset && self.first_object(),
1810			entries: self.entries(start, self.committed()).cloned().collect(),
1811			compressed: self.flate.is_some(),
1812			meta: self.meta,
1813		})
1814	}
1815
1816	/// Drop the cached frames (and any in-flight tail) and release their pool charge.
1817	///
1818	/// With `salvage`, the committed frames move to the readers that could resume the
1819	/// group elsewhere, if any are left, instead of being dropped.
1820	///
1821	/// The log frees its frames once no read already running can reach them, whether or
1822	/// not a cursor ever reads again.
1823	fn release(&mut self, salvage: bool) {
1824		let handoff = match salvage && !self.is_empty() && !self.sparse() {
1825			true => self.handoff.lock().unwrap_or_else(PoisonError::into_inner).upgrade(),
1826			false => None,
1827		};
1828		let head = handoff.as_ref().and_then(|_| self.head());
1829		let shared = self.content.is_some();
1830		if let Some(flate) = &mut self.flate {
1831			flate.release(self.outcome.error().cloned().unwrap_or(Error::Dropped), shared);
1832		}
1833		self.front = VecDeque::new();
1834		self.evict_log(self.log.end());
1835		self.partial = None;
1836		let content = self.content.take();
1837		if let Some(content) = &content {
1838			content.detach(self.outcome.error().cloned().unwrap_or(Error::Dropped));
1839		}
1840		self.cache = 0;
1841		self.charge.clear();
1842		// Frames this copy wrote first may be what a live sibling still holds.
1843		if let Some(content) = content {
1844			content.siblings.update(&self.charge);
1845		}
1846		// The header state and terminal object outlive the frames.
1847		if let Some(relay) = &mut self.relay {
1848			relay.bytes = size_of::<Relay>() as u64 + relay.end_object.as_ref().map_or(0, |fields| fields.heap());
1849			self.charge.add(relay.bytes);
1850		}
1851		// Billed once the group's own charge is gone, so the head only takes its place.
1852		if let (Some(handoff), Some(head)) = (handoff, head)
1853			&& let Some(track) = self.charge.account()
1854			&& let Some(bill) = track.hold(head.bytes())
1855		{
1856			let salvage = Salvage {
1857				head: Arc::new(head),
1858				bill,
1859			};
1860			*handoff.salvaged.lock().unwrap_or_else(PoisonError::into_inner) = Some(salvage);
1861			// Only once it is held: a sweep finding the hand-off empty forgets it.
1862			track.pool().hold_head(&handoff);
1863		}
1864	}
1865}
1866
1867impl Drop for GroupState {
1868	fn drop(&mut self) {
1869		if let Some(content) = self.content.take() {
1870			content.detach(Error::Dropped);
1871			self.charge.clear();
1872			content.siblings.update(&self.charge);
1873		}
1874	}
1875}
1876
1877fn modify(state: &kio::Producer<GroupState>) -> Result<kio::Mut<'_, GroupState>> {
1878	state
1879		.write()
1880		.map_err(|r| r.outcome.error().cloned().unwrap_or(Error::Dropped))
1881}
1882
1883/// Writes frames to a group in order.
1884///
1885/// Each group is delivered independently over a QUIC stream.
1886/// Use [Self::write_frame] for simple single-buffer frames,
1887/// or [Self::create_frame] for multi-chunk streaming writes.
1888///
1889/// The writer cannot be cloned; move it to its next owner instead.
1890///
1891/// ```compile_fail
1892/// # fn cannot_clone(producer: moq_net::group::Producer) {
1893/// let _: moq_net::group::Producer = producer.clone();
1894/// # }
1895/// ```
1896#[must_use = "dropping an unfinished group aborts it with `Dropped`"]
1897pub struct Producer {
1898	handle: Handle,
1899	stats: stats::Meter,
1900}
1901
1902/// Shared group state without permission to write frames or finish the group.
1903#[derive(Clone)]
1904// Sessions need an abortable observer while public callers use Demand.
1905pub(crate) struct Handle {
1906	// The group's frames reach its track and cache account, so the cell proves `Send`
1907	// once here instead of inside every session machine holding a group.
1908	state: SendCell<kio::Producer<GroupState>>,
1909	info: Info,
1910	track: track::Info,
1911	cache: Arc<cache::Track>,
1912	alive: Arc<Alive>,
1913}
1914
1915/// A group the track no longer caches, held without keeping it open or allocated, so a
1916/// track abort can still end it while its writer adds to it.
1917pub(super) struct Detached {
1918	state: SendCell<kio::Weak<GroupState>>,
1919	info: Info,
1920	track: track::Info,
1921	cache: Arc<cache::Track>,
1922	alive: Arc<Alive>,
1923}
1924
1925impl Detached {
1926	/// The group, while it is neither finished nor aborted.
1927	pub(super) fn writing(&self) -> Option<Handle> {
1928		let handle = Handle {
1929			state: SendCell::new(self.state.upgrade()?),
1930			info: self.info,
1931			track: self.track.clone(),
1932			cache: self.cache.clone(),
1933			alive: self.alive.clone(),
1934		};
1935		(!handle.is_settled()).then_some(handle)
1936	}
1937
1938	/// The group, while anything still holds it and it is not aborted.
1939	pub(super) fn held(&self) -> Option<Handle> {
1940		let handle = Handle {
1941			state: SendCell::new(self.state.upgrade()?),
1942			info: self.info,
1943			track: self.track.clone(),
1944			cache: self.cache.clone(),
1945			alive: self.alive.clone(),
1946		};
1947		(!handle.is_aborted()).then_some(handle)
1948	}
1949}
1950
1951/// Whether a group failed, without holding it open or pinning its frames.
1952pub(super) struct Fate(Arc<Alive>);
1953
1954impl Alive {
1955	/// The abort's phase. Acquire pairs with the abort's release, so a [`Fall::Cut`] finds
1956	/// its error in [`Self::cut`].
1957	fn fall(&self) -> Fall {
1958		Fall::from_u8(self.fall.load(Ordering::Acquire))
1959	}
1960}
1961
1962impl Fate {
1963	/// Whether the group was aborted other than by cache policy (`Old`, `Timeout`,
1964	/// `Evicted`): it failed or was given up, rather than aged out of a cache.
1965	pub(super) fn failed(&self) -> bool {
1966		matches!(self.0.fall(), Fall::Abandoned | Fall::Cut)
1967	}
1968}
1969
1970struct Alive {
1971	// Monotone mirror of an aborted `GroupState::outcome`, with why, for track scans that
1972	// already hold the track lock. Set once, whole: an unset one only hands out a group
1973	// that is concurrently aborting, and it is set after the outcome, so it can never hide
1974	// a live group. Readable through [`Fate`] once the group is gone.
1975	//
1976	// Only ever read on its own. A decision that pairs the abort with something else
1977	// out of `GroupState` has to read both under one guard, or the two halves can
1978	// straddle the abort: see `Handle::live_first_frame`.
1979	//
1980	// A [`Fall`] as one atomic phase rather than a `OnceLock`, whose first set takes a
1981	// slow path on every released group.
1982	fall: AtomicU8,
1983	// The publisher's error once `fall` reads [`Fall::Cut`]: set before that phase is
1984	// published, so a scan reading it finds the error.
1985	cut: OnceLock<Error>,
1986	// Set once frame 0's rewind check ran, so later writes skip the track lock it takes. A
1987	// stale false only takes that lock once more.
1988	checked: AtomicBool,
1989	// Monotone mirror of `GroupState::started` for the first frame or the finish, set under
1990	// the group lock after `timeline`/`outcome` is updated and before the lock is released:
1991	// no reader can observe `GroupState::started()` true (so `poll_started` skips registering)
1992	// while seeing a stale false here.
1993	started: AtomicBool,
1994	// Set once a final drop of this group waits on this copy, a fetched head still filling:
1995	// an abort before it finishes makes the drop the group's cut, so cut watchers hear it.
1996	carries_drop: AtomicBool,
1997	// The cache stamp `GroupState::charge` maintains, held here as well so the
1998	// eviction and expiry walks can weigh a candidate without taking the group lock
1999	// they already hold the track lock over.
2000	access: Arc<cache::Access>,
2001	// A reader of the frame log, cloned into each cursor so it reads frames without the
2002	// group lock.
2003	log: kio::log::Reader<Entry>,
2004	// The `GroupState::pace` cursors report their reads to.
2005	pace: Arc<Pace>,
2006	// When the group was created here, on the ambient clock; see [`Consumer::created`].
2007	created: crate::time::Instant,
2008	// Whether this is a metadata copy, mirroring `GroupState::meta` for reads without its lock.
2009	meta: bool,
2010}
2011
2012impl Drop for Producer {
2013	fn drop(&mut self) {
2014		if let Ok(state) = self.handle.state.write() {
2015			if !matches!(state.outcome, Outcome::Open) {
2016				return;
2017			}
2018			tracing::warn!(key = self.start, "group::Producer dropped without finish() or abort()");
2019			self.handle.commit_abort(state, Error::Dropped);
2020		}
2021	}
2022}
2023
2024impl std::ops::Deref for Handle {
2025	type Target = Info;
2026
2027	fn deref(&self) -> &Self::Target {
2028		&self.info
2029	}
2030}
2031
2032impl std::ops::Deref for Producer {
2033	type Target = Info;
2034
2035	fn deref(&self) -> &Self::Target {
2036		&self.handle.info
2037	}
2038}
2039
2040impl Producer {
2041	#[cfg(feature = "async")]
2042	pub(crate) fn wire(&self) -> Option<Wire> {
2043		self.handle.wire()
2044	}
2045
2046	#[cfg(feature = "async")]
2047	pub(crate) fn set_wire(&self, wire: Wire) -> Result<()> {
2048		self.handle.set_wire(wire)
2049	}
2050
2051	#[cfg(feature = "async")]
2052	pub(crate) fn mark_gap(&self, id: u64, gap: Option<u64>) -> Result<()> {
2053		self.handle.mark_gap(id, gap)
2054	}
2055
2056	#[cfg(all(test, feature = "async"))]
2057	pub(crate) fn set_end_object(&self, fields: super::object::Fields) -> Result<()> {
2058		self.handle.set_end_object(fields)
2059	}
2060
2061	/// Create a group producer bound to its parent track's [`track::Info`] and cache
2062	/// account.
2063	///
2064	/// Crate-private: groups are only constructed via [`track::Producer`], which
2065	/// threads both down so properties like the timescale are inherited rather than
2066	/// passed in. Every frame added to this group is normalized to the track's
2067	/// timescale by [`Self::create_frame`].
2068	///
2069	/// Charges the group into `cache`, so its cached bytes count against the budget the
2070	/// track evicts toward under memory pressure.
2071	pub(super) fn new(info: Info, track: track::Info, cache: Arc<cache::Track>) -> Self {
2072		Self::create(info, track, cache, false)
2073	}
2074
2075	/// [`Self::new`] for a metadata copy, which holds each frame's header alone, written with
2076	/// [`Self::write_header`]. It stores no compressed stream whatever its track declares,
2077	/// since it holds no payload to compress.
2078	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2079	pub(super) fn new_meta(info: Info, track: track::Info, cache: Arc<cache::Track>) -> Self {
2080		Self::create(info, track, cache, true)
2081	}
2082
2083	fn create(info: Info, track: track::Info, cache: Arc<cache::Track>, meta: bool) -> Self {
2084		let state = kio::Producer::<GroupState>::default();
2085		let charge = cache.charge();
2086		let access = charge.access();
2087		let (log, pace) = {
2088			let mut state = state.write().ok().expect("a new group is open");
2089			state.meta = meta;
2090			if track.compressed() && !meta {
2091				state.flate = Some(Box::new(Flate::new(
2092					Arc::new(Plain::new(charge.extra())),
2093					charge.extra(),
2094				)));
2095			}
2096			if let Some(report) = cache.report(&charge) {
2097				state.pace.report(report);
2098			}
2099			state.charge = charge;
2100			(state.log.reader(), state.pace.clone())
2101		};
2102		let alive = Arc::new(Alive {
2103			fall: AtomicU8::new(Fall::Live as u8),
2104			cut: OnceLock::new(),
2105			checked: AtomicBool::new(false),
2106			started: AtomicBool::new(false),
2107			carries_drop: AtomicBool::new(false),
2108			access,
2109			log,
2110			pace,
2111			created: super::clock::now(),
2112			meta,
2113		});
2114		Self {
2115			handle: Handle {
2116				info,
2117				state: SendCell::new(state),
2118				track,
2119				cache,
2120				alive,
2121			},
2122			stats: stats::Meter::default(),
2123		}
2124	}
2125
2126	/// Refuse a timed frame 0 that is not at the group's key, for a group handed out empty to a
2127	/// writer that stamps frame 0 itself: every other path creates the group from frame 0.
2128	pub(super) fn keyed(self) -> Self {
2129		if let Ok(mut state) = modify(&self.handle.state) {
2130			state.keyed = true;
2131		}
2132		self
2133	}
2134
2135	/// Attach an ingress payload meter, counting this as one delivered group.
2136	/// Called by a tagged [`track::Producer`] when it creates the group.
2137	pub(super) fn with_meter(mut self, meter: stats::Meter) -> Self {
2138		meter.group();
2139		self.stats = meter;
2140		self
2141	}
2142
2143	/// The parent track's timescale, or `None` when it declared no timeline.
2144	pub fn timescale(&self) -> Option<Timescale> {
2145		self.handle.track.timescale
2146	}
2147
2148	/// Whether the parent track compresses and this is no metadata copy, so a received frame
2149	/// arrives as a stored slice with its inflated size ([`frame::Header::inflated`]).
2150	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2151	pub(crate) fn compressed(&self) -> bool {
2152		self.handle.compressed()
2153	}
2154
2155	/// The track to check this group's start against, while frame 0 may still be unwritten.
2156	///
2157	/// The caller holds its lock until the frame is recorded, so the check and the stamp are
2158	/// one step against every other group's (locks are ordered track then group). Only a
2159	/// timed group not yet checked pays for it, once.
2160	fn first_frame_track(&self) -> Option<kio::Producer<track::TrackState>> {
2161		if self.handle.track.timescale.is_none() || self.handle.alive.checked.load(Ordering::Relaxed) {
2162			return None;
2163		}
2164		self.handle.cache.track()
2165	}
2166
2167	/// Start the group at frame `index` rather than 0, so the first frame written lands
2168	/// there.
2169	///
2170	/// A group can be short at its front or its back, never in the middle: this trims
2171	/// the front. Transport cuts at the back also retain their incomplete provenance.
2172	/// The frames below `index` are not a gap this handle will ever fill. They belong to
2173	/// whoever produced the head of the group, typically another route serving the same
2174	/// track (see [`crate::track::Subscriber`]), so a reader positioned below it fetches
2175	/// them from there: a front recovers them from a route, or the track's
2176	/// [`crate::track::Requests`] handlers serve them. With neither, the read is
2177	/// [`Error::Lagged`]; a failed fetch fails it with the fetch's error.
2178	///
2179	/// The counterpart of [`Consumer::with_range`], which positions a *reader* the same
2180	/// way. Where the group begins is part of its shape, so this must come before the
2181	/// first frame; afterwards it returns [`Error::Closed`]. A second call may raise the
2182	/// start but not lower it, since the frame log's first index never moves back.
2183	pub(crate) fn start_at(&mut self, index: u64) -> Result<()> {
2184		let index = usize::try_from(index).map_err(|_| Error::BoundsExceeded(crate::coding::BoundsExceeded))?;
2185		if index == usize::MAX {
2186			return Err(Error::BoundsExceeded(crate::coding::BoundsExceeded));
2187		}
2188
2189		let mut state = modify(&self.handle.state)?;
2190		// Every write advances `next_index` past `offset`, so this is "nothing written
2191		// yet".
2192		if state.outcome.frames().is_some() || state.next_index != state.offset || index < state.offset {
2193			return Err(Error::Closed);
2194		}
2195		state.offset = index;
2196		state.next_index = index;
2197		state.log.evict(index as u64);
2198		Ok(())
2199	}
2200
2201	/// Apply transport bounds before this copy is published to the cache.
2202	pub(crate) fn bound(&mut self, frames: Bounds) -> Result<()> {
2203		self.start_at(frames.start)?;
2204		if let Some(end) = frames.end {
2205			let end = usize::try_from(end).map_err(|_| Error::BoundsExceeded(crate::coding::BoundsExceeded))?;
2206			let mut state = modify(&self.handle.state)?;
2207			if end < state.offset {
2208				return Err(Error::InvalidRange);
2209			}
2210			state.range_end = Some(end);
2211			state.limit = Some(state.limit.map_or(end, |limit| limit.min(end)));
2212		}
2213		Ok(())
2214	}
2215
2216	/// Write a whole `frame`, its payload one contiguous buffer.
2217	///
2218	/// If you want to write multiple chunks, use [Self::create_frame] to get a frame producer.
2219	/// But an upfront size is required.
2220	///
2221	/// Its timestamp is converted into the parent track's timescale. On a scale-less track it
2222	/// is [`Timestamp::unscaled`] at this group's start; a frame that doesn't match its track
2223	/// is [`Error::TimestampMismatch`]. So is one below the previous frame's timestamp: a
2224	/// group's timestamps never decrease, so a stream with B-frames stamps decode time and
2225	/// carries presentation time in its payload. The frame's [`frame::Frame::created`] is
2226	/// replaced with when it enters this group, so a frame copied from another group is restamped.
2227	pub fn write_frame(&mut self, frame: frame::Frame) -> Result<()> {
2228		// A metadata copy holds no payload, so nothing writes one into it.
2229		if self.handle.alive.meta {
2230			return Err(Error::Unsupported);
2231		}
2232		self.write_stored(frame.timestamp, Stored::Payload(frame.payload))
2233	}
2234
2235	/// Write the `header` of a frame of `header.info.size` plain bytes into a metadata copy
2236	/// (see [`Self::new_meta`]), as a metadata subscription delivers it: no payload, and no
2237	/// frame or byte billed. Its object fields are kept for a relay to forward.
2238	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2239	pub(crate) fn write_header(&mut self, header: frame::Header) -> Result<()> {
2240		if !self.handle.alive.meta {
2241			return Err(Error::Unsupported);
2242		}
2243		let stored = Stored::Header {
2244			size: header.info.size,
2245			fields: header.fields,
2246		};
2247		self.write_stored(header.info.timestamp, stored)
2248	}
2249
2250	/// Write one whole frame as the group stores it: a payload, or a metadata copy's empty
2251	/// one with its declared size beside it.
2252	fn write_stored(&mut self, timestamp: Timestamp, stored: Stored) -> Result<()> {
2253		let (payload, declared, fields) = match stored {
2254			Stored::Payload(payload) => (payload, None, None),
2255			Stored::Header { size, fields } => (Bytes::new(), Some(size), fields),
2256		};
2257		let timestamp = self.handle.track.rescale_in(timestamp, self.handle.info.start)?;
2258		if payload.len() as u64 > MAX_CACHE_BYTES {
2259			return Err(Error::FrameTooLarge);
2260		}
2261
2262		let producer = self.first_frame_track();
2263		let track = producer.as_ref().map(|track| track.read());
2264		let neighbors = track.as_ref().map(|track| track.neighbors(self.handle.info.start));
2265		let mut state = modify(&self.handle.state)?;
2266		if state.outcome.frames().is_some() {
2267			return Err(Error::Closed);
2268		}
2269		debug_assert!(state.partial.is_none(), "a frame is already open");
2270		let next_index = state
2271			.next_index
2272			.checked_add(1)
2273			.ok_or(Error::BoundsExceeded(crate::coding::BoundsExceeded))?;
2274		state.admit(next_index)?;
2275		let origin = state.check_frame(neighbors.as_ref(), self.handle.info.start, timestamp)?;
2276		debug_assert!(state.partial.is_none(), "a frame is already open");
2277		let inflated = declared.unwrap_or(payload.len() as u64);
2278		let payload = match &mut state.flate {
2279			Some(flate) => flate.deflate(&payload),
2280			None => payload,
2281		};
2282		let size = payload.len() as u64;
2283		let metadata_bytes = fields.as_ref().map_or(0, |fields| fields.heap());
2284		if !state.trim(size.saturating_add(metadata_bytes)) {
2285			return Err(self.abort_too_large(state));
2286		}
2287		let inflated = if state.sized() { inflated } else { 0 };
2288		let frame = Cached {
2289			timestamp,
2290			payload: payload.into(),
2291			created: super::clock::now(),
2292		};
2293		let object_id = fields.as_ref().map_or(state.next_index as u64, |fields| fields.id);
2294		let mut entry = Entry {
2295			fields,
2296			..Entry::plain(frame, inflated)
2297		};
2298		// Checked here too, so a group without shared content skips the call.
2299		if state.content.is_some()
2300			&& let Err(err) = state.canonicalize(state.next_index, &mut entry)
2301		{
2302			return Err(self.abort_conflict(state, err));
2303		}
2304		if metadata_bytes > 0 {
2305			state.relay().bytes += metadata_bytes;
2306			state.charge.add(metadata_bytes);
2307		}
2308		let index = state.next_index as u64;
2309		let timestamp_ids = self.handle.track.timestamp_ids() == Some(true);
2310		state.relayed(object_id, index, self.handle.info.start, timestamp, timestamp_ids);
2311		let now = state.commit(entry);
2312		state.next_index = next_index;
2313		state.wrote = true;
2314		let bound = state.settle(origin);
2315		self.handle.alive.checked.store(true, Ordering::Relaxed);
2316		let first = self.handle.mark_started();
2317		self.advance_largest(&state);
2318		drop(state);
2319		// The group's lock is released first: indexing reads it back through its slot.
2320		if let Some(track) = &track {
2321			track.first_frame(self.handle.info.start, bound);
2322		}
2323		drop(track);
2324		if first {
2325			self.handle.reveal_started(producer);
2326		}
2327
2328		// With the group lock released (lock order is track then group), settle
2329		// eviction debt if enough has been written since the track last paid.
2330		self.handle.cache.settle(now);
2331		// An untimed frame presents nothing, so it can expire no read.
2332		if let Some(timestamp) = timestamp.timed() {
2333			self.handle.cache.wakes().presented(timestamp);
2334		}
2335
2336		// Ingress payload: one whole frame written. A header alone delivers no frame.
2337		if declared.is_none() {
2338			self.stats.frames(1);
2339			self.stats.bytes(size);
2340		}
2341		Ok(())
2342	}
2343
2344	/// Write a whole batch of frames at once, draining `frames`.
2345	///
2346	/// One lock covers the batch, so an ingest with several frames in hand pays the
2347	/// group mutex and the track's eviction settle once rather than per frame. Build
2348	/// the batch with [`frame::Buffer::push`].
2349	///
2350	/// The batch is validated before anything is written, so a rejected frame leaves
2351	/// both the group and the buffer exactly as they were, ready to retry or redirect,
2352	/// unless it fails the group: too large, or held differently by another copy.
2353	#[cfg(any(test, feature = "fuzz"))]
2354	pub(crate) fn write_frames<const N: usize>(&mut self, frames: &mut frame::Buffer<N>) -> Result<()> {
2355		if self.handle.alive.meta {
2356			return Err(Error::Unsupported);
2357		}
2358		let mut prev: Option<Timestamp> = None;
2359		for frame in frames.filled() {
2360			let timestamp = self.handle.track.rescale_in(frame.timestamp, self.handle.info.start)?;
2361			// The group checks the first against its own frames; the rest are checked here.
2362			if prev.is_some_and(|prev| timestamp.value() < prev.value()) {
2363				return Err(Error::TimestampMismatch);
2364			}
2365			prev = Some(timestamp);
2366			if frame.payload.len() as u64 > MAX_CACHE_BYTES {
2367				return Err(Error::FrameTooLarge);
2368			}
2369		}
2370
2371		let count = frames.len();
2372		let bytes: u64 = frames.filled().iter().map(|frame| frame.payload.len() as u64).sum();
2373		let producer = self.first_frame_track();
2374		let track = producer.as_ref().map(|track| track.read());
2375		let neighbors = track.as_ref().map(|track| track.neighbors(self.handle.info.start));
2376		let mut state = modify(&self.handle.state)?;
2377		if state.outcome.frames().is_some() {
2378			return Err(Error::Closed);
2379		}
2380		debug_assert!(state.partial.is_none(), "a frame is already open");
2381		let next_index = state
2382			.next_index
2383			.checked_add(count)
2384			.ok_or(Error::BoundsExceeded(crate::coding::BoundsExceeded))?;
2385		state.admit(next_index)?;
2386		let first = frames.filled().first().map(|frame| frame.timestamp);
2387		let origin = match first {
2388			Some(timestamp) => state.check_frame(
2389				neighbors.as_ref(),
2390				self.handle.info.start,
2391				self.handle
2392					.track
2393					.rescale_in(timestamp, self.handle.info.start)
2394					.expect("timestamp scale checked above"),
2395			)?,
2396			None => state.origin,
2397		};
2398		// A compressed group stores slices, compressed aside so a refused batch is untouched.
2399		let mut deflated = arrayvec::ArrayVec::<Bytes, N>::new();
2400		if let Some(flate) = &mut state.flate {
2401			deflated.extend(frames.filled().iter().map(|frame| flate.deflate(&frame.payload)));
2402		}
2403		let stored = match state.flate.is_some() {
2404			true => deflated.iter().map(|slice| slice.len() as u64).sum(),
2405			false => bytes,
2406		};
2407		// Room for the batch and its slots, or for as much of it as fits: its own front
2408		// sheds once committed.
2409		let slots = (count * size_of::<Entry>()) as u64;
2410		state.trim(stored.saturating_add(slots).min(MAX_CACHE_BYTES));
2411
2412		// The last frame's tick, reused below so settling does not re-read the clock.
2413		let mut now = None;
2414		let mut latest: Option<Timestamp> = None;
2415		let mut deflated = deflated.into_iter();
2416		let created = super::clock::now();
2417		// Validation is done, so the batch is taken by value: a conflict below fails the group,
2418		// which the buffer need not survive, and moving each payload spares a refcount round trip.
2419		// Only shared canonical content can refuse a frame, so only a group holding it prepares
2420		// the whole batch before storing any; any other stores each frame as it goes.
2421		let canonical = state.content.is_some();
2422		let mut prepared = arrayvec::ArrayVec::<Entry, N>::new();
2423		for (index, frame) in frames.drain().enumerate() {
2424			let timestamp = self
2425				.handle
2426				.track
2427				.rescale_in(frame.timestamp, self.handle.info.start)
2428				.expect("timestamp scale checked above");
2429			let (payload, inflated) = match state.flate.is_some() {
2430				true => (
2431					deflated.next().expect("one slice per frame"),
2432					frame.payload.len() as u64,
2433				),
2434				false => (frame.payload, 0),
2435			};
2436			let mut entry = Entry::plain(
2437				Cached {
2438					timestamp,
2439					payload: payload.into(),
2440					created,
2441				},
2442				inflated,
2443			);
2444			latest = match (latest, timestamp.timed()) {
2445				(Some(latest), Some(timestamp)) => Some(latest.later(timestamp)),
2446				(latest, timestamp) => latest.or(timestamp),
2447			};
2448			if !canonical {
2449				now = state.commit(entry);
2450				continue;
2451			}
2452			if let Err(err) = state.canonicalize(state.next_index + index, &mut entry) {
2453				return Err(self.abort_conflict(state, err));
2454			}
2455			prepared.push(entry);
2456		}
2457		for entry in prepared {
2458			now = state.commit(entry);
2459		}
2460		// A batch past the tail on its own, payloads or slots, sheds its own front.
2461		state.trim(0);
2462		state.next_index = next_index;
2463		state.wrote = true;
2464		let bound = state.settle(origin);
2465		let first = if count > 0 {
2466			self.handle.alive.checked.store(true, Ordering::Relaxed);
2467			let first = self.handle.mark_started();
2468			self.advance_largest(&state);
2469			first
2470		} else {
2471			false
2472		};
2473		drop(state);
2474		// The group's lock is released first: indexing reads it back through its slot.
2475		if let Some(track) = &track {
2476			track.first_frame(self.handle.info.start, bound);
2477		}
2478		drop(track);
2479		if first {
2480			self.handle.reveal_started(producer);
2481		}
2482
2483		self.handle.cache.settle(now);
2484		if let Some(latest) = latest {
2485			self.handle.cache.wakes().presented(latest);
2486		}
2487		self.stats.frames(count as u64);
2488		self.stats.bytes(stored);
2489		Ok(())
2490	}
2491
2492	/// Create a frame with an upfront size and presentation timestamp, streamed in
2493	/// chunks. The returned [`frame::Producer`] takes this writer, so only one frame is
2494	/// open at a time; its [`finish`](frame::Producer::finish) hands the writer back.
2495	/// Use [`Self::write_frame`] for a frame already in one buffer.
2496	///
2497	/// The `timestamp` is converted into the parent track's timescale, so the scale you
2498	/// build it with doesn't have to match the track. A frame the group cannot take
2499	/// aborts the group with the error: [`Error::FrameTooLarge`] if the declared size
2500	/// exceeds 32 MiB, what a copy holds (refused before allocating),
2501	/// [`Error::TimestampMismatch`] if the timestamp can't be converted or falls below the
2502	/// previous frame's, or [`Error::Closed`] once the group finished.
2503	///
2504	/// The declared size is allocated up front while the frames in flight through the
2505	/// origin handle fit its budget, and grows with the bytes written past that, so a
2506	/// peer's declaration cannot commit memory it never sends.
2507	pub fn create_frame(self, frame: frame::Info) -> Result<frame::Producer> {
2508		self.create_object(frame.into())
2509	}
2510
2511	/// [`Self::create_frame`] with the moq-transport object fields a relay forwards.
2512	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2513	pub(crate) fn create_object(mut self, frame: frame::Header) -> Result<frame::Producer> {
2514		let meter = self.chunk_meter(frame.inflated);
2515		// A metadata copy holds no payload, so nothing streams one into it.
2516		let opened = match self.handle.alive.meta {
2517			true => Err(Error::Unsupported),
2518			false => self.open_frame(frame),
2519		};
2520		let (info, buf, admission) = match opened {
2521			Ok(opened) => opened,
2522			Err(err) => {
2523				let _ = self.handle.abort(err.clone());
2524				return Err(err);
2525			}
2526		};
2527		Ok(frame::Producer::new(self, buf, info, admission).with_meter(meter))
2528	}
2529
2530	/// The meter a streamed frame's chunks bump: none for a plain frame a compressed group
2531	/// compresses on commit, which counts its stored slice then, as `bytes` counts payload
2532	/// as stored.
2533	fn chunk_meter(&self, inflated: Option<u64>) -> stats::Meter {
2534		match self.handle.track.compressed() && inflated.is_none() {
2535			true => stats::Meter::default(),
2536			false => self.stats.clone(),
2537		}
2538	}
2539
2540	/// Open `buf` as the in-flight frame, returning its header in the track's timescale.
2541	///
2542	/// Its bytes are charged to the cache as they are written, not here: the declared
2543	/// size is only a promise until they arrive.
2544	fn open_frame(&mut self, header: frame::Header) -> Result<(frame::Info, FrameBuf, Option<frame::Admission>)> {
2545		let frame = header.info;
2546		let timestamp = self.handle.track.rescale_in(frame.timestamp, self.handle.info.start)?;
2547		if frame.size > MAX_CACHE_BYTES || header.inflated.is_some_and(|inflated| inflated > MAX_CACHE_BYTES) {
2548			return Err(Error::FrameTooLarge);
2549		}
2550		// Only a compressed group takes a stored slice, and every frame a local producer
2551		// streams into one is plain until it commits.
2552		if header.inflated.is_some() && !self.handle.track.compressed() {
2553			return Err(Error::ProtocolViolation);
2554		}
2555		let scratch = self.handle.track.compressed() && header.inflated.is_none();
2556
2557		let producer = self.first_frame_track();
2558		let track = producer.as_ref().map(|track| track.read());
2559		let neighbors = track.as_ref().map(|track| track.neighbors(self.handle.info.start));
2560		let mut state = modify(&self.handle.state)?;
2561		if state.outcome.frames().is_some() {
2562			return Err(Error::Closed);
2563		}
2564		debug_assert!(state.partial.is_none(), "a frame is already open");
2565		let next_index = state
2566			.next_index
2567			.checked_add(1)
2568			.ok_or(Error::BoundsExceeded(crate::coding::BoundsExceeded))?;
2569		state.admit(next_index)?;
2570		let origin = state.check_frame(neighbors.as_ref(), self.handle.info.start, timestamp)?;
2571		// Only one frame is ever in flight, so the declared size is the most the cache
2572		// can grow by before the next check.
2573		let metadata_bytes = header.fields.as_ref().map_or(0, |fields| fields.heap());
2574		if !state.trim(frame.size.saturating_add(metadata_bytes)) {
2575			return Err(self.abort_too_large(state));
2576		}
2577		let (buf, admission) = match state.content.as_ref().filter(|_| !scratch) {
2578			Some(content) => {
2579				let key = Content::key(state.next_index, header.fields.as_deref(), state.wire().is_some());
2580				let row = content.row(
2581					Spec {
2582						key,
2583						size: frame.size,
2584						inflated: header.inflated,
2585					},
2586					Input::Stream(None),
2587					&state.charge,
2588					None,
2589				)?;
2590				let buf = row.fork();
2591				buf.bill_view(state.charge.extra());
2592				let admission = buf.admit(self.handle.cache.frames());
2593				(buf, admission)
2594			}
2595			None => FrameBuf::admitted(frame.size as usize, self.handle.cache.frames()),
2596		};
2597		let now = state.charge.record_write();
2598		state.partial = Some(Partial {
2599			timestamp,
2600			fields: header.fields,
2601			buf: buf.clone(),
2602			charged: 0,
2603			inflated: header.inflated,
2604			scratch,
2605		});
2606		if metadata_bytes > 0 {
2607			state.relay().bytes += metadata_bytes;
2608			state.charge.add(metadata_bytes);
2609		}
2610		let object_id = state
2611			.partial
2612			.as_ref()
2613			.and_then(|partial| partial.fields.as_ref())
2614			.map_or(state.next_index as u64, |fields| fields.id);
2615		let timestamp_ids = self.handle.track.timestamp_ids() == Some(true);
2616		state.relayed(
2617			object_id,
2618			(next_index - 1) as u64,
2619			self.handle.info.start,
2620			timestamp,
2621			timestamp_ids,
2622		);
2623		state.next_index = next_index;
2624		state.wrote = true;
2625		// Opening the frame is enough: the header carries the timestamp, so the group's
2626		// place in time is known before a single payload byte streams in.
2627		state.stamp(timestamp);
2628		let bound = state.settle(origin);
2629		self.handle.alive.checked.store(true, Ordering::Relaxed);
2630		let first = self.handle.mark_started();
2631		drop(state);
2632		// The group's lock is released first: indexing reads it back through its slot.
2633		if let Some(track) = &track {
2634			track.first_frame(self.handle.info.start, bound);
2635		}
2636		drop(track);
2637		if first {
2638			self.handle.reveal_started(producer);
2639		}
2640
2641		// With the group lock released (lock order is track then group), settle
2642		// eviction debt if enough has been written since the track last paid.
2643		self.handle.cache.settle(now);
2644		// An untimed frame presents nothing, so it can expire no read.
2645		if let Some(timestamp) = timestamp.timed() {
2646			self.handle.cache.wakes().presented(timestamp);
2647		}
2648
2649		// Ingress payload: one frame opened; its bytes are counted per chunk as the
2650		// producer writes them.
2651		self.stats.frames(1);
2652
2653		Ok((
2654			frame::Info {
2655				size: frame.size,
2656				timestamp,
2657			},
2658			buf,
2659			admission,
2660		))
2661	}
2662
2663	/// Wake consumers parked on the group channel (called after a partial write).
2664	pub(super) fn frame_notify(&self) {
2665		// The chunk that was just written is charged, and is a write access: restart the
2666		// retention clock so a straggler group streaming a large frame isn't expired
2667		// mid-write. `charge_partial` takes `&mut`, which marks the guard modified: kio
2668		// only notifies on a mutably-accessed guard's release, and that notify is what
2669		// delivers the chunk to parked readers.
2670		let now = self
2671			.handle
2672			.state
2673			.write()
2674			.ok()
2675			.and_then(|mut state| state.charge_partial());
2676		// A long streamed frame also counts as track activity for the independent
2677		// expiry time gate.
2678		self.handle.cache.settle(now);
2679	}
2680
2681	/// Commit the in-flight frame as a completed frame (called by [`frame::Producer::finish`]).
2682	pub(super) fn frame_commit(&mut self, frame: Cached) -> Result<()> {
2683		let mut state = modify(&self.handle.state)?;
2684		// Completing the frame charges whatever it wrote since the last notify, and is a
2685		// write access like any chunk, and the only one the payload is guaranteed to get:
2686		// the wire ingest defers its chunk notifications to the poll boundary, so a tail
2687		// that arrives and completes in one turn never reaches [`Self::frame_notify`].
2688		// Without this, a group whose payload streamed in across an idle gap would expire
2689		// the instant it finished.
2690		let mut now = state.charge_partial();
2691		let partial = state.partial.take();
2692		let mut frame = frame;
2693		let mut inflated = 0;
2694		if partial.as_ref().is_some_and(|partial| partial.scratch) {
2695			let flate = state.flate.as_mut().expect("scratch only opens on a compressed group");
2696			inflated = frame.payload.len() as u64;
2697			frame.payload = flate.deflate(&frame.payload.contiguous(0)).into();
2698			let size = frame.payload.len() as u64;
2699			// Admitted at its declared plain size, which the slice rarely passes.
2700			state.trim(size);
2701			state.cache += size;
2702			let charged = if state.content.is_none() { size } else { 0 };
2703			now = state.charge.add(charged);
2704			self.stats.bytes(size);
2705		} else if let Some(size) = partial.as_ref().and_then(|partial| partial.inflated) {
2706			// Declared when it opened.
2707			inflated = size;
2708		}
2709		// Stamped once readable, so a slow DEFLATE above counts against its lateness.
2710		frame.created = super::clock::now();
2711		let owner = partial
2712			.as_ref()
2713			.filter(|partial| !partial.scratch && state.content.is_some())
2714			.map(|partial| partial.buf.shared());
2715		let owned = owner.is_some();
2716		let fields = partial.and_then(|partial| partial.fields);
2717		let mut entry = Entry {
2718			owner: Mutex::new(owner),
2719			frame,
2720			fields,
2721			inflated,
2722			end: 0,
2723		};
2724		if !owned && state.content.is_some() {
2725			state.canonicalize(state.next_index - 1, &mut entry)?;
2726		}
2727		// The slot was reserved and charged by `charge_partial` above.
2728		state.push(entry);
2729		debug_assert_eq!(
2730			state.committed(),
2731			state.next_index,
2732			"the in-flight frame was the last opened"
2733		);
2734		self.advance_largest(&state);
2735		drop(state);
2736
2737		// With the group lock released (lock order is track then group), settle
2738		// eviction debt and age idle content out, reusing the tick above.
2739		self.handle.cache.settle(now);
2740		Ok(())
2741	}
2742
2743	/// Raise the track's largest to the last committed frame.
2744	fn advance_largest(&self, state: &GroupState) {
2745		self.handle.cache.advance_largest(track::Position {
2746			group: self.handle.info.start,
2747			frame: (state.committed() - 1) as u64,
2748		});
2749	}
2750
2751	/// Fail the group because an in-flight frame couldn't complete (called by
2752	/// [`frame::Producer::abort`] / its drop).
2753	pub(super) fn frame_abort(&mut self, err: Error) {
2754		let _ = self.handle.close_aborted(err);
2755	}
2756
2757	/// End the group whole at `end`, the exclusive end of its presentation in its track's
2758	/// timescale, returning the [`Finished`] group: no more frames can be written, but it can
2759	/// still be read or aborted.
2760	///
2761	/// A finished group's own end bounds how long it stays fresh, so the last group of a
2762	/// paused or finished track ages out without a successor (see
2763	/// [`track::Info::max_age`]). Its span, from its start to `end`, holds no other group's
2764	/// start, so no successor may start before `end`. An `end` below the group's start or
2765	/// below any of its frames' timestamps is [`Error::TimestampMismatch`], which aborts the
2766	/// group; one equal to either is a group that presents no further. Fails with the abort
2767	/// error if the group was already aborted.
2768	pub fn finish_at(self, end: u64) -> Result<Finished> {
2769		if let Err(err) = self.check_end(end) {
2770			let _ = self.handle.close_aborted(err.clone());
2771			return Err(err);
2772		}
2773		self.end(Some(end))
2774	}
2775
2776	/// Whether [`Self::finish_at`] takes `end`: [`Error::TimestampMismatch`] below the
2777	/// group's start or below its highest frame timestamp, in its track's timescale.
2778	pub(crate) fn check_end(&self, end: u64) -> Result<()> {
2779		let highest = match self.handle.state.read().timeline {
2780			Timeline::Timed { latest, .. } => latest.value(),
2781			Timeline::Empty | Timeline::Untimed => 0,
2782		};
2783		match end < self.start.max(highest) {
2784			true => Err(Error::TimestampMismatch),
2785			false => Ok(()),
2786		}
2787	}
2788
2789	/// End the group without saying where it ends, returning the [`Finished`] group: every
2790	/// frame written still reaches its readers, but they can't tell the group is whole, since
2791	/// only [`Self::finish_at`] declares the end a media reader checks against.
2792	/// What a producer that doesn't know its group's end calls, and how a relay ends a
2793	/// group that expired or arrived partial. Fails with the abort error if the group was
2794	/// already aborted.
2795	pub fn finish(self) -> Result<Finished> {
2796		self.end(None)
2797	}
2798
2799	fn end(self, end: Option<u64>) -> Result<Finished> {
2800		let mut state = modify(&self.handle.state)?;
2801		debug_assert!(state.partial.is_none(), "a frame is already open");
2802		let fin = state.next_index;
2803		state.outcome = Outcome::Finished(fin, end);
2804		// No frame follows to compress.
2805		let original_fin = state.range_end.is_none().then_some(fin);
2806		// Finished short of its transport bound, a bounded copy reached the group's own end too.
2807		let whole = state.range_end.is_none_or(|bound| fin < bound);
2808		state.charge.finish(whole);
2809		if let Some(content) = &state.content {
2810			content.siblings.update(&state.charge);
2811		}
2812		if let Some(flate) = &mut state.flate {
2813			flate.finish(original_fin);
2814		}
2815		let first = self.handle.mark_started();
2816		drop(state);
2817		// An empty group counts as content once it ends.
2818		if first {
2819			self.handle.reveal_started(None);
2820		}
2821		// A finished group can no longer raise the track's largest, which may end its stream.
2822		// A copy a transport bound cut short finished only its own range.
2823		if original_fin.is_some() {
2824			self.handle.cache.finish_largest(self.start);
2825		}
2826		Ok(Finished {
2827			handle: self.handle.clone(),
2828		})
2829	}
2830
2831	/// Abort the group with the given error.
2832	///
2833	/// Consumes the writer. Drops the cached frames so a stale [`Consumer`] can't pin
2834	/// their buffers in memory forever; consumers that haven't drained yet surface the
2835	/// abort error instead of the leftover cache.
2836	pub fn abort(self, err: Error) -> Result<()> {
2837		self.handle.close_aborted(err)
2838	}
2839
2840	/// Abort a write that shedding the front could not make room for, holding the lock
2841	/// already taken for that write so nothing else lands in between.
2842	fn abort_too_large(&self, state: kio::Mut<'_, GroupState>) -> Error {
2843		self.handle.commit_abort(state, Error::GroupTooLarge);
2844		Error::GroupTooLarge
2845	}
2846
2847	/// Fail the group with a whole frame that another copy of it holds differently. A
2848	/// compressed group already took the frame into its history, which no reader gets.
2849	fn abort_conflict(&self, state: kio::Mut<'_, GroupState>, err: Error) -> Error {
2850		self.handle.commit_abort(state, err.clone());
2851		err
2852	}
2853
2854	/// Resolves once a reader holds the group and the next frame, described by `frame`, fits
2855	/// within 16 MB past the end of the last frame its fastest reader took, so a local writer
2856	/// runs no further ahead than the live tail keeps behind that reader.
2857	///
2858	/// Ready once the group is closed, so the next write surfaces why. A reader that took
2859	/// every committed frame is waiting on the writer, so it never holds the writer back, even
2860	/// for a frame larger than the window, and one whose next frame was shed has fallen off
2861	/// the group and is not waited on. Writing without waiting never fails: the group sheds
2862	/// its front instead.
2863	#[cfg_attr(feature = "async", kio::wrapper)]
2864	pub fn poll_ready(&self, waiter: &kio::Waiter, frame: &frame::Info) -> Poll<()> {
2865		ready!(self.poll_paced(waiter, frame.size, super::pace::AHEAD));
2866		// A closed group reports `Closed`, which is ready too.
2867		self.handle.state.poll_wanted_changed(waiter, false).map(|_| ())
2868	}
2869
2870	/// Poll until the writer may take more from upstream, `partial` bytes into a frame
2871	/// it has not committed: until it is at most `window` bytes past the end of the last
2872	/// frame its fastest reader took. Ingest passes its stream's receive credit (see
2873	/// [`super::pace::window`]); a local writer passes [`super::pace::AHEAD`].
2874	///
2875	/// Ready at once while no reader is owed the group (see [`Handle::poll_unowed`]), so a
2876	/// group nobody watches keeps writing and sheds its front, and once it is closed, so the
2877	/// next write surfaces why.
2878	/// A reader that took every committed frame is waiting on the writer, so a frame
2879	/// larger than the window never stalls it, and one whose next frame was shed has
2880	/// fallen off the group and is not waited on.
2881	///
2882	/// A session's ingest waits on this; a local writer waits on [`Self::poll_ready`].
2883	pub(crate) fn poll_paced(&self, waiter: &kio::Waiter, partial: u64, window: u64) -> Poll<()> {
2884		let pace = &self.handle.alive.pace;
2885		if !pace.ahead(partial, window) {
2886			return Poll::Ready(());
2887		}
2888		// Either wakes the writer: nobody left to read the rest, or the group closing.
2889		if self.handle.poll_unowed(waiter).is_ready() || self.handle.state.poll_closed(waiter).is_ready() {
2890			return Poll::Ready(());
2891		}
2892		match pace.paced(pace.park(waiter), partial, window) {
2893			true => Poll::Pending,
2894			false => Poll::Ready(()),
2895		}
2896	}
2897
2898	/// How many more bytes the writer, `partial` bytes into a frame it has not committed, may
2899	/// take before [`Self::poll_paced`] holds it at `window`, or `None` once nothing would;
2900	/// see [`super::pace::Pace::room`].
2901	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2902	pub(crate) fn room(&self, partial: u64, window: u64) -> Option<u64> {
2903		if self.handle.state.is_closed() {
2904			return None;
2905		}
2906		self.handle.alive.pace.room(partial, window, || self.handle.owed())
2907	}
2908
2909	/// The non-writing observer used by the cache and built-in sessions.
2910	// Sessions need an abortable observer while public callers use Demand.
2911	pub(crate) fn handle(&self) -> Handle {
2912		self.handle.clone()
2913	}
2914
2915	/// One past the index of the last frame written (completed or in-flight), which is
2916	/// also the index the next frame will get.
2917	///
2918	/// Counts any frames the group started past, so it's the group's
2919	/// logical length rather than the number of frames this handle holds.
2920	pub fn frame_count(&self) -> usize {
2921		self.handle.frame_count()
2922	}
2923
2924	/// The highest timestamp written so far, or `None` before a timed frame.
2925	///
2926	/// A group's timestamps never decrease, so a timed frame below it is refused.
2927	pub fn latest(&self) -> Option<Timestamp> {
2928		match self.handle.state.read().timeline {
2929			Timeline::Timed { latest, .. } => Some(latest),
2930			_ => None,
2931		}
2932	}
2933
2934	/// Whether the group has been aborted (including pool eviction). The track's
2935	/// read paths treat an aborted cached group as absent.
2936	///
2937	/// Reads the mirror rather than the group's state, so a track scan holding the
2938	/// track lock never takes the group's. Monotone, and only ever conservative: a
2939	/// concurrent abort can still read as live for the length of [`Self::abort`],
2940	/// which hands out a group whose consumer then surfaces the abort.
2941	pub(crate) fn is_aborted(&self) -> bool {
2942		self.handle.is_aborted()
2943	}
2944
2945	/// Create a new consumer for the group.
2946	pub fn consume(&self) -> Consumer {
2947		self.handle.consume()
2948	}
2949
2950	/// Resolves once the group's outcome is final: `Ok` once finished, or the abort error,
2951	/// including eviction.
2952	#[cfg_attr(feature = "async", kio::wrapper)]
2953	pub fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
2954		self.handle.poll_closed(waiter)
2955	}
2956
2957	/// Watch reader demand without keeping the group alive, such as for a paced flight to see
2958	/// its riders leave. [`track::FillGroups::poll_unwanted`] resolves as soon as readers take the group.
2959	pub fn demand(&self) -> Demand {
2960		self.handle.demand()
2961	}
2962}
2963
2964/// A group whose writer [finished](Producer::finish) it: every frame is written, and it can
2965/// still be read or aborted, but not written to.
2966///
2967/// Dropping it leaves the group finished.
2968///
2969/// ```compile_fail,E0599
2970/// # fn cannot_write(group: moq_net::group::Finished) {
2971/// group.write_frame(moq_net::frame::Frame::new(moq_net::Timestamp::ZERO, b"late".as_slice())).unwrap();
2972/// # }
2973/// ```
2974pub struct Finished {
2975	handle: Handle,
2976}
2977
2978impl std::ops::Deref for Finished {
2979	type Target = Info;
2980
2981	fn deref(&self) -> &Self::Target {
2982		&self.handle.info
2983	}
2984}
2985
2986impl Finished {
2987	#[cfg(all(test, feature = "async"))]
2988	pub(crate) fn handle(&self) -> Handle {
2989		self.handle.clone()
2990	}
2991
2992	/// Release the group's cached frames, reporting `err` to readers that have not drained it.
2993	///
2994	/// The group stays finished: a reader that took every frame still ends cleanly.
2995	pub fn abort(self, err: Error) -> Result<()> {
2996		self.handle.close_aborted(err)
2997	}
2998
2999	/// The number of frames the group holds, counting any it started past.
3000	pub fn frame_count(&self) -> usize {
3001		self.handle.frame_count()
3002	}
3003
3004	/// Create a new consumer for the group.
3005	pub fn consume(&self) -> Consumer {
3006		self.handle.consume()
3007	}
3008}
3009
3010impl Handle {
3011	#[cfg(feature = "async")]
3012	pub(crate) fn wire(&self) -> Option<Wire> {
3013		self.state.read().wire().cloned()
3014	}
3015
3016	#[cfg(feature = "async")]
3017	pub(crate) fn set_wire(&self, mut wire: Wire) -> Result<()> {
3018		let mut state = modify(&self.state)?;
3019		// A head adopted before the header arrived holds the objects below the stream's.
3020		if let Some(first_object) = state.adopted {
3021			wire.first_object = first_object;
3022			wire.first_id = state.offset as u64;
3023			wire.last = wire.last.or((state.next_index as u64).checked_sub(1));
3024		}
3025		state.relay().wire = Some(wire);
3026		Ok(())
3027	}
3028
3029	#[cfg(feature = "async")]
3030	pub(crate) fn mark_gap(&self, id: u64, gap: Option<u64>) -> Result<()> {
3031		if gap.is_some_and(|gap| gap > id) {
3032			return Err(Error::MalformedTrack);
3033		}
3034		let mut state = modify(&self.state)?;
3035		let offset = state.offset as u64;
3036		// Called before the frame carrying `id` is written, so it lands here.
3037		let next = state.next_index as u64;
3038		if let Some(wire) = state.wire_mut() {
3039			let missing = match wire.last {
3040				None => id.checked_sub(offset).ok_or(Error::MalformedTrack)?,
3041				Some(prior) => id
3042					.checked_sub(prior)
3043					.and_then(|step| step.checked_sub(1))
3044					.ok_or(Error::MalformedTrack)?,
3045			};
3046			if wire.last.is_some() && gap.is_some_and(|gap| gap > missing) {
3047				return Err(Error::MalformedTrack);
3048			}
3049			// A first object's gap may also cover IDs below where this copy starts. Timestamp
3050			// Object IDs skip the ticks between frames with no Prior Object ID Gap, so a FETCH
3051			// judges such a copy's missing head by its first ID instead (`ietf::publisher`).
3052			if self.track.timestamp_ids() != Some(true) && missing > 0 && gap.is_none_or(|gap| gap < missing) {
3053				wire.hole.get_or_insert(next);
3054			}
3055		}
3056		Ok(())
3057	}
3058
3059	#[cfg(feature = "async")]
3060	pub(crate) fn set_end_object(&self, fields: super::object::Fields) -> Result<()> {
3061		let mut state = modify(&self.state)?;
3062		if state.outcome.frames().is_some() || state.relay.as_ref().is_some_and(|relay| relay.end_object.is_some()) {
3063			return Err(Error::MalformedTrack);
3064		}
3065		let bytes = fields.heap();
3066		if !state.trim(bytes) {
3067			return Err(Error::GroupTooLarge);
3068		}
3069		state.charge.add(bytes);
3070		let relay = state.relay();
3071		relay.bytes += bytes;
3072		if let Some(wire) = &mut relay.wire {
3073			relay.last_before_end = wire.last;
3074			wire.last = Some(fields.id);
3075		}
3076		relay.end_object = Some(Arc::new(fields));
3077		Ok(())
3078	}
3079
3080	/// Whether `reader` may ride this copy at its frame: it holds the frame, no further
3081	/// than [`ADMIT`] behind the end of the last frame its fastest reader took, so the
3082	/// front shedding as the writer runs a whole window ahead still leaves it in place.
3083	pub(super) fn admits(&self, reader: &Consumer) -> bool {
3084		let index = reader.cursor.index;
3085		let state = self.state.read();
3086		// Frames adopted below the log sit off this copy's pace scale.
3087		if state.outcome.error().is_some() || (index as u64) < state.log.base() {
3088			return false;
3089		}
3090		// A plain read of a compressed copy inflates its frame from every slice since the
3091		// last one inflated, which must all still be held, from frame 0.
3092		if let Some(plain) = state.plain(reader.cursor.raw)
3093			&& (state.offset != 0
3094				|| plain.len.load(Ordering::Acquire).min(index) < state.held()
3095				|| plain.shed_past(index))
3096		{
3097			return false;
3098		}
3099		let start = match state.log.get(index as u64) {
3100			Some(entry) => entry.end - entry.cost(),
3101			None if index == state.committed() => state.pace.written(),
3102			None => return false,
3103		};
3104		state.pace.read().saturating_sub(start) <= ADMIT
3105	}
3106
3107	/// One past the last frame this copy committed: how far its writer got.
3108	pub(super) fn committed(&self) -> usize {
3109		self.state.read().committed()
3110	}
3111
3112	/// Whether `reader` reads this copy.
3113	pub(super) fn is_read_by(&self, reader: &Consumer) -> bool {
3114		Arc::ptr_eq(&self.alive, &reader.cursor.alive)
3115	}
3116
3117	/// Whether `other` is a handle of this same copy.
3118	pub(super) fn is_copy(&self, other: &Handle) -> bool {
3119		Arc::ptr_eq(&self.alive, &other.alive)
3120	}
3121
3122	/// Abort the group without taking ownership of its writer.
3123	// Sessions cancel a group while its writer is in a frame.
3124	pub(crate) fn abort(&self, err: Error) -> Result<()> {
3125		self.close_aborted(err)
3126	}
3127
3128	/// Abort the group with `err` unless it already holds every frame: the publisher gave
3129	/// up a group still arriving, while one that finished here stays whole.
3130	// Sessions cancel an unfinished FETCH while its writer belongs to its data stream.
3131	pub(crate) fn abort_open(&self, err: Error) {
3132		if let Ok(state) = self.state.write()
3133			&& state.outcome.frames().is_none()
3134		{
3135			self.commit_abort(state, err);
3136		}
3137	}
3138
3139	pub(super) fn content(&self) -> Option<Arc<Content>> {
3140		self.state.read().content.clone()
3141	}
3142
3143	pub(super) fn activate_content(&self) -> Result<Option<Arc<Content>>> {
3144		let Ok(mut state) = self.state.write() else {
3145			return Ok(None);
3146		};
3147		if state.outcome.error().is_some() {
3148			return Ok(None);
3149		}
3150		if let Some(content) = &state.content {
3151			return Ok(Some(content.clone()));
3152		}
3153		let content = Content::new(&state.charge, state.flate.as_ref().map(|flate| flate.plain.clone()));
3154		content.attach(&state.charge);
3155		state.content = Some(content.clone());
3156		let loaded = (|| -> Result<()> {
3157			let entries: Vec<_> = state.entries(state.held(), state.committed()).cloned().collect();
3158			for (index, entry) in (state.held()..).zip(entries) {
3159				let key = Content::key(index, entry.fields.as_deref(), state.wire().is_some());
3160				let transferred = state.charge.transfer(entry.frame.payload.len() as u64);
3161				let shared = content.row(
3162					Spec {
3163						key,
3164						size: entry.frame.payload.len() as u64,
3165						inflated: state.flate.as_ref().map(|_| entry.inflated),
3166					},
3167					Input::Whole(entry.frame.payload),
3168					&state.charge,
3169					Some(transferred),
3170				)?;
3171				*state
3172					.entry(index)
3173					.expect("entry remains under the group guard")
3174					.owner
3175					.lock()
3176					.unwrap_or_else(PoisonError::into_inner) = Some(shared);
3177			}
3178			if state.partial.as_ref().is_some_and(|partial| !partial.scratch) {
3179				let partial = state.partial.as_ref().expect("checked above");
3180				let key = Content::key(state.next_index - 1, partial.fields.as_deref(), state.wire().is_some());
3181				let (buf, inflated, charged) = (partial.buf.clone(), partial.inflated, partial.charged);
3182				let transferred = state.charge.transfer(charged);
3183				buf.bill_view(state.charge.extra());
3184				content.row(
3185					Spec {
3186						key,
3187						size: buf.size() as u64,
3188						inflated,
3189					},
3190					Input::Stream(Some(buf)),
3191					&state.charge,
3192					Some(transferred),
3193				)?;
3194			}
3195			Ok(())
3196		})();
3197		if let Err(err) = loaded {
3198			self.commit_abort(state, err.clone());
3199			return Err(err);
3200		}
3201		Ok(Some(content))
3202	}
3203
3204	pub(super) fn register_content(&self, contents: &Contents) {
3205		let state = self.state.read();
3206		if let Some(content) = &state.content {
3207			contents.insert(self.start, content, &state.charge);
3208		}
3209	}
3210
3211	pub(super) fn share_content(&self, content: Arc<Content>) {
3212		let Ok(mut state) = self.state.write() else {
3213			return;
3214		};
3215		debug_assert!(state.partial.is_none() && state.next_index == state.offset);
3216		let plain = content.attach(&state.charge);
3217		if let Some(old) = state.content.replace(content) {
3218			old.detach(Error::Dropped);
3219		}
3220		if let (Some(flate), Some(plain)) = (&mut state.flate, plain) {
3221			flate.plain = plain;
3222		}
3223	}
3224
3225	pub(super) fn same_content(&self, other: &Self) -> bool {
3226		match (self.content(), other.content()) {
3227			(Some(a), Some(b)) => Arc::ptr_eq(&a, &b),
3228			_ => false,
3229		}
3230	}
3231
3232	/// Shed whole frames from the front toward `debt`, freeing at most about `cap`, and
3233	/// return the bytes freed: see [`GroupState::shed`]. Takes the group's lock, under the
3234	/// track's.
3235	pub(super) fn shed(&self, debt: u64, cap: u64) -> u64 {
3236		match self.state.write() {
3237			Ok(mut state) => state.shed(debt, cap),
3238			Err(_) => 0,
3239		}
3240	}
3241
3242	/// Shed like [`Self::shed`] while the group still grows: a finished live edge is pinned,
3243	/// what a new reader starts from.
3244	pub(super) fn shed_growing(&self, debt: u64, cap: u64) -> u64 {
3245		match self.state.write() {
3246			Ok(mut state) if state.outcome.frames().is_none() => state.shed(debt, cap),
3247			_ => 0,
3248		}
3249	}
3250
3251	/// Shed every frame this copy holds, as [`GroupState::shed_all`] does. A frame still
3252	/// arriving cannot be shed, so a copy holding one is aborted with [`Error::Evicted`]
3253	/// instead: only a publisher leaving frames unfinished loses the group itself.
3254	pub(super) fn shed_all(&self) {
3255		let Ok(mut state) = self.state.write() else {
3256			return;
3257		};
3258		state.shed_all();
3259		if state.arriving() {
3260			self.commit_abort(state, Abort::Evicted);
3261		}
3262	}
3263
3264	/// Shed the frames this copy's fastest reader took, see [`GroupState::shed_taken`]. A copy
3265	/// no reader holds keeps the rest: one not yet handed out is still owed downstream.
3266	pub(super) fn shed_taken(&self) {
3267		let Ok(mut state) = self.state.write() else {
3268			return;
3269		};
3270		state.shed_taken(self.alive.pace.read());
3271	}
3272
3273	pub(super) fn delivery_size(&self) -> u64 {
3274		let state = self.state.read();
3275		state.charge.size()
3276			+ state
3277				.flate
3278				.as_ref()
3279				.and_then(|flate| flate.release.as_ref())
3280				.map_or(0, |release| release.bill.size())
3281			+ state.partial.as_ref().map_or(0, |partial| partial.buf.view_size())
3282	}
3283
3284	/// Adopt the frames of `head` below where this copy starts, so it holds the group
3285	/// from `head`'s start, as if this route had delivered them.
3286	///
3287	/// A no-op unless `head` starts below this copy and reaches it, the copy shed nothing,
3288	/// and the frames fit beside its live tail. Readers keep their positions, since frames keep their indices. A
3289	/// compressed group adopts only a compressed head, taking its inflated sizes beside the
3290	/// slices, so its plain readers inflate from the adopted frames.
3291	pub(super) fn adopt_head(&self, head: &Head) {
3292		if let Some(adopted) = self.take_head(head) {
3293			self.settle_head(adopted);
3294		}
3295	}
3296
3297	/// The part of [`Self::adopt_head`] that touches only this group, so a track can run it
3298	/// under its own lock before any reader sees the group: then [`Self::settle_head`], with
3299	/// that lock released.
3300	pub(super) fn take_head(&self, head: &Head) -> Option<Adopted> {
3301		let Ok(mut state) = self.state.write() else {
3302			return None;
3303		};
3304		let offset = state.offset;
3305		let reaches = head.start.saturating_add(head.entries.len()) >= offset;
3306		let same_form = head.compressed == state.flate.is_some() && head.meta == state.meta;
3307		// A copy that shed its front holds no run from `offset` for the head to precede.
3308		let shed = state.held() != offset;
3309		if state.outcome.error().is_some() || state.sparse() || !same_form || shed || head.start >= offset || !reaches {
3310			return None;
3311		}
3312		let count = offset - head.start;
3313		let entries = &head.entries[..count];
3314		let payload: u64 = entries.iter().map(|entry| entry.frame.payload.len() as u64).sum();
3315		let metadata: u64 = entries
3316			.iter()
3317			.filter_map(|entry| entry.fields.as_ref())
3318			.map(|fields| fields.heap())
3319			.sum();
3320		// Only a head that fits beside the live tail with both their slots, which nothing is
3321		// shed to make room for.
3322		let slots = state.slots() + (count * size_of::<Entry>()) as u64;
3323		if state.tail().saturating_add(payload + metadata + slots) > MAX_CACHE_BYTES {
3324			return None;
3325		}
3326		let mut adopted = Vec::with_capacity(count);
3327		for (index, entry) in (head.start..).zip(entries) {
3328			let mut entry = entry.clone();
3329			if state.canonicalize(index, &mut entry).is_err() {
3330				return None;
3331			}
3332			// Below the log, so off this copy's pace scale: taking it reports nothing.
3333			entry.end = 0;
3334			adopted.push(entry);
3335		}
3336		// Below the log's first frame, so these never enter it: readers find them here.
3337		let before = state.front.capacity();
3338		state.front.reserve(count);
3339		let growth = ((state.front.capacity() - before) * size_of::<Entry>()) as u64;
3340
3341		for entry in adopted.into_iter().rev() {
3342			state.front.push_front(entry);
3343		}
3344		if metadata > 0 {
3345			state.relay().bytes += metadata;
3346		}
3347		state.offset = head.start;
3348		state.cache += payload;
3349		let start = entries.iter().find_map(|entry| entry.frame.timestamp.timed());
3350		let head_latest = entries
3351			.iter()
3352			.filter_map(|entry| entry.frame.timestamp.timed())
3353			.reduce(Timestamp::later);
3354		state.timeline = match (state.timeline, start) {
3355			(Timeline::Timed { latest, .. }, Some(start)) => Timeline::Timed {
3356				start,
3357				latest: latest.later(head_latest.unwrap_or(start)),
3358			},
3359			(Timeline::Empty, Some(start)) => Timeline::Timed {
3360				start,
3361				latest: head_latest.unwrap_or(start),
3362			},
3363			(Timeline::Empty, None) => Timeline::Untimed,
3364			(timeline, _) => timeline,
3365		};
3366		state.adopted = Some(head.first_object);
3367		if let Some(relay) = state.relay.as_mut()
3368			&& let Some(wire) = &mut relay.wire
3369		{
3370			wire.first_object = head.first_object;
3371			wire.first_id = head.start as u64;
3372			wire.last = wire.last.or(Some(offset as u64 - 1));
3373			// A terminal object held before any frame leaves the head's last as the newest data.
3374			if relay.end_object.is_some() {
3375				relay.last_before_end = relay.last_before_end.or(Some(offset as u64 - 1));
3376			}
3377		}
3378		let first = self.mark_started();
3379		let extra = metadata + growth + if state.content.is_none() { payload } else { 0 };
3380		Some(Adopted {
3381			now: state.charge.add(extra),
3382			latest: head_latest,
3383			first,
3384		})
3385	}
3386
3387	/// Settle a head [`Self::take_head`] adopted with the track and the cache: the group
3388	/// counts as content now, as a first frame would make it.
3389	pub(super) fn settle_head(&self, adopted: Adopted) {
3390		if adopted.first {
3391			self.reveal_started(None);
3392		}
3393		self.cache.settle(adopted.now);
3394		if let Some(latest) = adopted.latest {
3395			self.cache.wakes().presented(latest);
3396		}
3397	}
3398
3399	/// One past the index of the last frame written (completed or in-flight), which is
3400	/// also the index the next frame will get.
3401	///
3402	/// Counts any frames the group started past, so it's the group's
3403	/// logical length rather than the number of frames this handle holds.
3404	// Sessions observe a group while its sole writer belongs to a frame.
3405	pub(crate) fn frame_count(&self) -> usize {
3406		self.state.read().next_index
3407	}
3408
3409	/// Whether this copy stores compressed slices; see [`Producer::compressed`].
3410	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3411	pub(crate) fn compressed(&self) -> bool {
3412		self.track.compressed() && !self.alive.meta
3413	}
3414
3415	/// Whether this is a metadata copy, holding each frame's header alone.
3416	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3417	pub(crate) fn is_meta(&self) -> bool {
3418		self.alive.meta
3419	}
3420
3421	/// The newest object's ID, by its moq-transport object ID when the group carries one,
3422	/// else its frame index; `None` before the first frame. A terminal object does not
3423	/// count: a publisher's Largest never names the END_OF_GROUP it sends past the last.
3424	pub(crate) fn last_data_object(&self) -> Option<u64> {
3425		self.state.read().last_data_object()
3426	}
3427
3428	/// Cap the group at `frames`, for a track end inside it, or lift the cap with `None`:
3429	/// later writes past the cap are [`Error::Closed`]. A frame already at or past the cap is
3430	/// [`Error::ProtocolViolation`]. An aborted group gets no more frames, so it takes no cap.
3431	pub(super) fn limit(&self, frames: Option<u64>) -> Result<()> {
3432		let Ok(mut state) = self.state.write() else {
3433			return Ok(());
3434		};
3435		let frames = frames.map(|frames| usize::try_from(frames).unwrap_or(usize::MAX));
3436		if frames.is_some_and(|frames| state.next_index > frames) {
3437			return Err(Error::ProtocolViolation);
3438		}
3439		state.limit = frames;
3440		Ok(())
3441	}
3442
3443	/// Abort with `err` only while nothing consumes the group, returning whether it is
3444	/// closed. Consumer creation and the check share a lock, so a reader arriving after
3445	/// [`poll_unwanted`](Self::poll_unwanted) keeps the group alive instead of reading the abort.
3446	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3447	pub(crate) fn abort_unwanted(&self, err: Error) -> bool {
3448		match self.state.write_unwanted() {
3449			kio::Unwanted::Idle(guard) => {
3450				self.commit_abort(guard, err);
3451				true
3452			}
3453			kio::Unwanted::Closed => true,
3454			kio::Unwanted::Wanted => false,
3455		}
3456	}
3457
3458	pub(super) fn close_aborted(&self, abort: impl Into<Abort>) -> Result<()> {
3459		self.commit_abort(modify(&self.state)?, abort);
3460		Ok(())
3461	}
3462
3463	fn commit_abort(&self, mut guard: kio::Mut<'_, GroupState>, abort: impl Into<Abort>) {
3464		let abort = abort.into();
3465		let err = abort.error();
3466		let policy = matches!(err, Error::Old | Error::Timeout | Error::Evicted);
3467		// Cache policy frees the frames, as does an oversized group whichever write found
3468		// it; a copy that failed or was given up lends them on.
3469		let salvage = !policy && !matches!(err, Error::GroupTooLarge);
3470		let fall = match guard.outcome {
3471			// A finished group's outcome is settled: an abort only releases its cache, so it
3472			// neither failed nor was cut.
3473			Outcome::Finished(..) => Fall::Released,
3474			_ if policy => Fall::Released,
3475			// A reset carrying a policy code is the upstream's cache policy, a cancel is a
3476			// reader no longer wanting the group, and a fill refused as unfetchable abandons
3477			// backfill: deliberate holes, never a cut readers see. The publisher giving the
3478			// group up is.
3479			_ if matches!(
3480				err,
3481				Error::Cancel
3482					| Error::Lagged | Error::Stream(
3483					StreamError::Cancel
3484						| StreamError::Old | StreamError::Evicted
3485						| StreamError::DeliveryTimeout
3486						| StreamError::TooFarBehind
3487				)
3488			) =>
3489			{
3490				Fall::Abandoned
3491			}
3492			_ => Fall::Cut,
3493		};
3494		let cut = fall == Fall::Cut;
3495		if cut {
3496			let _ = self.alive.cut.set(err.clone());
3497		}
3498		let finished = guard.outcome.frames().is_some();
3499		guard.outcome = match guard.outcome {
3500			Outcome::Finished(frames, end) => Outcome::Released(frames, end, abort),
3501			_ => Outcome::Aborted(abort),
3502		};
3503		// After the outcome exists, so a scan reading the mirror never hides a live group.
3504		// The group lock admits one abort, so this is the only store.
3505		self.alive.fall.store(fall as u8, Ordering::Release);
3506		guard.release(salvage);
3507		guard.close();
3508		// Pairs with the fence after the track's `give_up` ended the live copy: either it sees
3509		// this abort, or this sees its flag and that copy ended, so the drop riding on this
3510		// copy is announced once it is the cut. Cache policy announces nothing, as it cuts
3511		// nothing: it runs under the track guard, which a woken cursor would take. The fence
3512		// runs only on an abort that could carry a drop, so a released group pays nothing.
3513		let carried = !finished && !policy && {
3514			std::sync::atomic::fence(Ordering::SeqCst);
3515			self.alive.carries_drop.load(Ordering::Relaxed)
3516		};
3517		self.cache.aborted(self.start, cut || carried);
3518	}
3519
3520	/// Mark that a final drop of this group waits on this copy, so a failure before it
3521	/// finishes is announced to cut watchers as a cut would be. An abort racing this is the
3522	/// caller's to announce; see the fence in [`Self::commit_abort`].
3523	pub(super) fn carry_drop(&self) {
3524		self.alive.carries_drop.store(true, Ordering::Relaxed);
3525	}
3526
3527	/// Whether the group has been aborted (including pool eviction). The track's
3528	/// read paths treat an aborted cached group as absent.
3529	///
3530	/// Reads the mirror rather than the group's state, so a track scan holding the
3531	/// track lock never takes the group's. Monotone, and only ever conservative: a
3532	/// concurrent abort can still read as live for the length of [`Self::abort`],
3533	/// which hands out a group whose consumer then surfaces the abort.
3534	pub(crate) fn is_aborted(&self) -> bool {
3535		self.alive.fall() != Fall::Live
3536	}
3537
3538	/// Whether the group was aborted only to free its cache, by cache policy or after it
3539	/// finished, rather than failed. Reads the mirror, like [`Self::is_aborted`].
3540	pub(super) fn is_released(&self) -> bool {
3541		self.alive.fall() == Fall::Released
3542	}
3543
3544	/// Why the publisher gave this group up, once it did, rather than cache policy
3545	/// skipping it.
3546	///
3547	/// Reads the mirror, like [`Self::is_aborted`], so a track scan never takes the group lock.
3548	pub(super) fn cut_error(&self) -> Option<&Error> {
3549		match self.alive.fall() {
3550			Fall::Cut => self.alive.cut.get(),
3551			Fall::Live | Fall::Released | Fall::Abandoned => None,
3552		}
3553	}
3554
3555	/// This group as [`Detached`], for the track to end once it stops caching it.
3556	pub(super) fn detach(&self) -> Detached {
3557		Detached {
3558			state: SendCell::new(self.state.downgrade()),
3559			info: self.info,
3560			track: self.track.clone(),
3561			cache: self.cache.clone(),
3562			alive: self.alive.clone(),
3563		}
3564	}
3565
3566	/// This group's [`Fate`], readable after the group and its frames are gone.
3567	pub(super) fn fate(&self) -> Fate {
3568		Fate(self.alive.clone())
3569	}
3570
3571	/// Whether a transport-bounded copy may answer these requested frames.
3572	pub(super) fn covers(&self, frames: Bounds) -> bool {
3573		let state = self.state.read();
3574		state.outcome.error().is_none()
3575			&& state.offset as u64 <= frames.start
3576			&& match (state.range_end, frames.end) {
3577				(None, _) => true,
3578				(Some(cap), Some(end)) => end <= cap as u64,
3579				(Some(_), None) => false,
3580			}
3581	}
3582
3583	/// Mark this copy as back-cut at its current frame count (e.g., a lite-07 stream closed
3584	/// with bare FIN at a Position End without GROUP_END), so whole-group fetches do not treat
3585	/// it as covering frames past its current end.
3586	#[cfg(feature = "async")]
3587	pub(crate) fn bound_back(&self) {
3588		if let Ok(mut state) = modify(&self.state)
3589			&& state.range_end.is_none()
3590		{
3591			state.range_end = Some(state.next_index);
3592		}
3593	}
3594
3595	/// Whether this copy was cut short at the back by its transport request.
3596	pub(super) fn back_cut(&self) -> bool {
3597		self.state.read().range_end.is_some()
3598	}
3599
3600	/// Whether the writer finished this copy, which a transport bound may end short of the
3601	/// group's end.
3602	pub(super) fn is_settled(&self) -> bool {
3603		self.state.read().outcome.frames().is_some()
3604	}
3605
3606	/// Where the group ends in its track's timescale, once its producer finished it whole
3607	/// (see [`Producer::finish_at`]).
3608	pub(crate) fn end(&self) -> Option<u64> {
3609		match self.state.read().outcome {
3610			Outcome::Finished(_, end) | Outcome::Released(_, end, _) => end,
3611			_ => None,
3612		}
3613	}
3614
3615	/// Whether the group was finished: it holds every frame it will ever have.
3616	pub(crate) fn is_finished(&self) -> bool {
3617		{
3618			let state = self.state.read();
3619			state.outcome.frames().is_some() && state.range_end.is_none()
3620		}
3621	}
3622
3623	/// The index of the first frame this group still holds, or `None` once it has been
3624	/// aborted. Non-zero when the group started later (see [`Self::start_at`]); a reader
3625	/// positioned below it fetches the frames it lacks or fails with [`Error::Lagged`].
3626	///
3627	/// One guard for both halves, deliberately. The track asks this to decide whether a
3628	/// cached slot can still answer a request, and reading the abort and the offset
3629	/// separately lets the abort land between them: the slot reads live, then hands
3630	/// back an offset it only has because it is dead. The mirror
3631	/// ([`Self::is_aborted`]) is for scans that ask about the abort alone.
3632	pub(super) fn live_first_frame(&self) -> Option<usize> {
3633		let state = self.state.read();
3634		state.outcome.error().is_none().then_some(state.offset)
3635	}
3636
3637	/// One past the last frame committed to an unfinished group, when that is past its
3638	/// first: where a replacement route resumes. `None` once the group is finished, or
3639	/// while it holds nothing a replacement could continue.
3640	///
3641	/// The *committed* count, not the written one: a route dying midway through a
3642	/// chunked frame leaves that frame unusable, so the replacement has to send it
3643	/// again rather than start after it. Answered under one guard so the count can't be
3644	/// weighed against an offset from a different moment.
3645	///
3646	/// An aborted group still answers: readers that already consumed its head want the
3647	/// tail, and the count outlives the released cache.
3648	pub(super) fn resume_frame(&self) -> Option<usize> {
3649		let state = self.state.read();
3650		if (state.outcome.frames().is_some() && state.range_end.is_none()) || state.sparse() {
3651			return None;
3652		}
3653		(state.committed() > state.offset).then_some(state.committed())
3654	}
3655
3656	/// Whether `other` is a handle to this same group.
3657	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3658	pub(super) fn is_clone(&self, other: &Self) -> bool {
3659		self.state.is_clone(&other.state)
3660	}
3661
3662	/// Whether the group opened its first frame or finished, so the track counts it as
3663	/// content. An aborted group is not content either way.
3664	///
3665	/// Reads the mirror rather than the group's state, so a track scan holding the track
3666	/// lock never takes the group's.
3667	pub(super) fn is_started(&self) -> bool {
3668		self.alive.started.load(Ordering::Acquire)
3669	}
3670
3671	/// Record the first frame opening or the group finishing under the group lock, before
3672	/// dropping the guard wakes `poll_started`. Returns `true` the first time, telling the
3673	/// caller to notify the track with [`Self::reveal_started`] once the group lock is released.
3674	fn mark_started(&self) -> bool {
3675		!self.alive.started.swap(true, Ordering::Release)
3676	}
3677
3678	/// The first frame opened or the group finished: tell the track once, so it re-judges
3679	/// the reads that skipped this group while it was frameless. Called with the group
3680	/// lock released, since the track's is taken first.
3681	///
3682	/// `track` is the track a first frame already reached, so stamping a group upgrades
3683	/// its link once.
3684	fn reveal_started(&self, track: Option<kio::Producer<track::TrackState>>) {
3685		let Some(track) = track.or_else(|| self.cache.track()) else {
3686			return;
3687		};
3688		let answers = track.read().reveal(self);
3689		if answers && let Ok(mut state) = track.write() {
3690			state.shown(self.start);
3691		}
3692	}
3693
3694	/// Where the group starts in presentation time: its first frame's timestamp, or
3695	/// `None` while no frame has been opened or when that frame is untimed.
3696	///
3697	/// Stamped once, when the group's first frame arrives, so it measures the group's
3698	/// place in the media timeline rather than when it happened to be delivered. That
3699	/// is what lets the track tell a burst of old content apart from live content (see
3700	/// [`track::Subscriber`]).
3701	///
3702	/// `None` for a group accepted unverified below the track's eviction watermark too:
3703	/// nothing proves where it starts, so it drives no media-time expiry.
3704	pub(super) fn timestamp(&self) -> Option<Timestamp> {
3705		let state = self.state.read();
3706		match state.timeline {
3707			Timeline::Timed { start, .. } if state.origin != Origin::Unverified => Some(start),
3708			_ => None,
3709		}
3710	}
3711
3712	/// The start this group lends its neighbors' rewind check: its first frame's timestamp,
3713	/// once frame 0 was checked to fit between theirs.
3714	pub(super) fn bound(&self) -> Option<Timestamp> {
3715		let state = self.state.read();
3716		match state.timeline {
3717			Timeline::Timed { start, .. } if state.origin == Origin::Bound => Some(start),
3718			_ => None,
3719		}
3720	}
3721
3722	/// Highest PTS among this group's timed frames, or `None` while it is empty or untimed.
3723	///
3724	/// The newest servable group's highest PTS drives presentation-time drift.
3725	/// Decode-order B-frames cannot move that edge backwards.
3726	pub(super) fn latest(&self) -> Option<Timestamp> {
3727		let state = self.state.read();
3728		match state.timeline {
3729			Timeline::Timed { latest, .. } if state.origin != Origin::Unverified => Some(latest),
3730			_ => None,
3731		}
3732	}
3733
3734	/// The group's full cached footprint (payload plus fixed overhead, and a compressed
3735	/// group's inflated copy as far as it is built), used by the track to size this group
3736	/// as an eviction victim.
3737	pub(super) fn cache_size(&self) -> u64 {
3738		let state = self.state.read();
3739		state.charge.size()
3740			+ state
3741				.flate
3742				.as_ref()
3743				.and_then(|flate| flate.release.as_ref())
3744				.map_or(0, |release| release.bill.size())
3745			+ state.content.as_ref().map_or_else(
3746				|| state.flate.as_ref().map_or(0, |flate| flate.plain.bill.size()),
3747				|content| content.size(),
3748			) + state.partial.as_ref().map_or(0, |partial| partial.buf.view_size())
3749	}
3750
3751	/// Whether the payload cached after the first frame exceeds `ratio` times the first
3752	/// frame: what [`track::Info::refresh`] judges a join by. A group holding no first
3753	/// frame (one started past it, or not written yet) has nothing to compare against,
3754	/// unless it shed it, which a joiner could only read as [`Error::Evicted`].
3755	pub(super) fn over_refresh(&self, ratio: u32) -> bool {
3756		let state = self.state.read();
3757		if state.offset != 0 {
3758			return false;
3759		}
3760		let Some(first) = state.entry(0) else {
3761			return state.outcome.error().is_none() && state.held() > 0;
3762		};
3763		let first = first.frame.payload.len() as u64;
3764		state.cache.saturating_sub(first) > first.saturating_mul(ratio.into())
3765	}
3766
3767	/// Tick of the group's last cache access, driving eviction protection and age
3768	/// expiry (see [`cache::Pool::average`]).
3769	pub(super) fn cache_accessed(&self) -> u64 {
3770		self.alive.access.get()
3771	}
3772
3773	/// Coarse clock tick of the group's last cache access, used by age expiry.
3774	pub(super) fn cache_accessed_tick(&self, now: Option<u64>) -> Option<u64> {
3775		self.alive.access.tick(now)
3776	}
3777
3778	/// Enter the group into the evictable population: demoted from the live edge,
3779	/// or inserted behind it. Idempotent; a no-op once the group is closed.
3780	pub(super) fn cache_demote(&self) {
3781		if let Ok(mut state) = self.state.write() {
3782			state.charge.demote();
3783			if let Some(content) = &state.content {
3784				content.siblings.demote();
3785			}
3786		}
3787	}
3788
3789	/// Stop billing the session for this copy as it leaves the cache, though it lives on for
3790	/// its holders, unless a sibling copy sharing its frames is still the live edge.
3791	pub(super) fn cache_leave_edge(&self) {
3792		if let Ok(mut state) = self.state.write() {
3793			state.charge.leave_edge();
3794			if let Some(content) = &state.content {
3795				content.siblings.update(&state.charge);
3796			}
3797		}
3798	}
3799
3800	/// Bill the group to its session's live edges: its track's newest, which eviction never
3801	/// takes. Idempotent; a no-op once demoted or closed.
3802	pub(super) fn cache_promote(&self) {
3803		if let Ok(mut state) = self.state.write() {
3804			state.charge.promote();
3805			if let Some(content) = &state.content {
3806				content.siblings.update(&state.charge);
3807			}
3808		}
3809	}
3810
3811	/// Pin the group while a fill holds it for a reader, or stop: see [`cache::Charge::hold`].
3812	/// Through a read guard, so holding wakes no consumer.
3813	pub(super) fn cache_hold(&self, held: bool) {
3814		let state = self.state.read();
3815		state.charge.hold(held);
3816		// Frames a sibling copy wrote first bill that copy, so it is held with this one.
3817		if let Some(content) = &state.content {
3818			content.siblings.update(&state.charge);
3819		}
3820	}
3821
3822	/// Record a cache access (delivery to a subscriber, a FETCH hit, or a fetched
3823	/// backfill's birth), protecting the group from eviction and restarting its
3824	/// expiry clock. Stamps through a read guard, whose release never notifies, so
3825	/// delivery can't wake every consumer parked on the group. Harmless on a
3826	/// closed group: its charge is already cleared.
3827	pub(super) fn cache_refresh(&self) {
3828		self.state.read().charge.refresh();
3829	}
3830
3831	/// Create a new consumer for the group.
3832	// Sessions observe a group while its sole writer belongs to a frame.
3833	pub(crate) fn consume(&self) -> Consumer {
3834		let state = self.state.consume();
3835		self.hold();
3836		self.consumer(state)
3837	}
3838
3839	/// Create a consumer, or `None` once the group is aborted. Paired with
3840	/// [`abort_unwanted`](Self::abort_unwanted): the closed check and the count share its
3841	/// lock, so a consumer either exists in time to decline the abort or is never made.
3842	pub(super) fn try_consume(&self) -> Option<Consumer> {
3843		let state = self.state.passive().try_consume()?;
3844		self.hold();
3845		Some(self.consumer(state))
3846	}
3847
3848	/// Mark the group held by a reader that already counts, so its readers all leaving means
3849	/// nobody is owed the rest.
3850	fn hold(&self) {
3851		self.state.read().held.store(true, Ordering::Relaxed);
3852	}
3853
3854	/// Whether a reader ever held the group.
3855	fn held(&self) -> bool {
3856		self.state.read().held.load(Ordering::Relaxed)
3857	}
3858
3859	fn consumer(&self, state: kio::Consumer<GroupState>) -> Consumer {
3860		Consumer {
3861			info: self.info,
3862			delivery: Arc::new(Delivery {
3863				timescale: self.track.timescale,
3864				#[cfg(feature = "async")]
3865				ietf: self.track.ietf(),
3866				#[cfg(feature = "async")]
3867				timestamp_ids: self.track.timestamp_ids(),
3868				created: self.alive.created,
3869				stale_counted: AtomicBool::new(false),
3870				stale_under: std::sync::OnceLock::new(),
3871			}),
3872			cursor: Cursor {
3873				state,
3874				log: self.alive.log.clone(),
3875				index: 0,
3876				end: None,
3877				prefetch: Prefetch::default(),
3878				raw: false,
3879				partial: false,
3880				compressed: self.track.compressed() && !self.alive.meta,
3881				cache: self.cache.clone(),
3882				alive: self.alive.clone(),
3883				refreshed: self.cache.pool().now(),
3884			},
3885			// Untagged: a tagged track attaches the egress meter via `with_meter`
3886			// when it hands the consumer to a subscriber/fetch.
3887			stats: stats::Meter::default(),
3888			expiry: None,
3889			expired: false,
3890			adopted: false,
3891			carry: None,
3892			idle: None,
3893			parked: false,
3894		}
3895	}
3896
3897	/// Register for the group's first frame, which settles its [`Self::timestamp`], while
3898	/// none has been opened.
3899	pub(super) fn poll_started(&self, waiter: &kio::Waiter) -> Poll<()> {
3900		match self.state.poll(waiter, |state| {
3901			let started = self.is_started() || self.is_aborted();
3902			#[cfg(debug_assertions)]
3903			debug_assert_eq!(
3904				started,
3905				state.started(),
3906				"Alive::started/fall mirror diverged from GroupState::started()"
3907			);
3908			let _ = state;
3909			if started { Poll::Ready(()) } else { Poll::Pending }
3910		}) {
3911			Poll::Ready(_) => Poll::Ready(()),
3912			Poll::Pending => Poll::Pending,
3913		}
3914	}
3915
3916	/// Poll until the group's outcome is final: `Ok` once finished, or the abort error.
3917	// Sessions observe a group while its sole writer belongs to a frame.
3918	pub(crate) fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
3919		settle(self.state.poll_ref(waiter, |state| state.poll_outcome()))
3920	}
3921
3922	/// Poll until the group places `time` (see [`Self::unplaced_from`]): a frame past the time
3923	/// puts its End past the time too, so it contains the time whatever it ends at. Fails with
3924	/// the abort when the group aborts first, which proves nothing of where it ends.
3925	pub(crate) fn poll_past(&self, waiter: &kio::Waiter, time: u64) -> Poll<Result<()>> {
3926		let placed = |state: &GroupState| match state.places(time) {
3927			true => Poll::Ready(Ok(())),
3928			false => state.poll_outcome(),
3929		};
3930		Poll::Ready(match ready!(self.state.poll_ref(waiter, |state| placed(state))) {
3931			Ok(outcome) => outcome,
3932			Err(closed) => match placed(&closed) {
3933				Poll::Ready(outcome) => outcome,
3934				Poll::Pending => Err(Error::Dropped),
3935			},
3936		})
3937	}
3938
3939	/// The first time the group can't place now, `None` once it finished: it places a time
3940	/// it holds a timed frame past, which puts its End past the time too. An aborted copy
3941	/// proves nothing of where its group ends.
3942	pub(crate) fn unplaced_from(&self) -> Option<u64> {
3943		self.state.read().unplaced_from()
3944	}
3945
3946	/// Poll until the group is aborted, including by eviction and after it finished; ready
3947	/// with the cause. Finishing alone does not end it.
3948	// Sessions and track scans watch for an abort that frees a group, finished or not.
3949	pub(crate) fn poll_aborted(&self, waiter: &kio::Waiter) -> Poll<Error> {
3950		self.state.poll_closed(waiter).map(|()| self.abort_reason())
3951	}
3952
3953	/// Watch reader demand without keeping the group alive.
3954	// Sessions observe a group while its sole writer belongs to a frame.
3955	pub(crate) fn demand(&self) -> Demand {
3956		Demand {
3957			key: self.info.start,
3958			state: self.state.passive(),
3959			prev: None,
3960		}
3961	}
3962
3963	/// Poll for the group becoming unwanted (every consumer dropped).
3964	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3965	pub(crate) fn poll_unwanted(&self, waiter: &kio::Waiter) -> Poll<()> {
3966		self.state.poll_wanted_changed(waiter, true).map(drop)
3967	}
3968
3969	/// Whether a reader is owed the rest of the group: one holds it, or none has yet and some
3970	/// cursor of its track admits it.
3971	fn owed(&self) -> bool {
3972		// Held before counted: a reader is marked only once it counts, so seeing the mark first
3973		// means its count shows too, unless it already left.
3974		let held = self.held();
3975		self.state.wanted() || (!held && self.cache.admits().admits(self.info.start))
3976	}
3977
3978	/// Poll until no reader is owed the rest of the group: none holds it, and either one did
3979	/// and left, or none has yet and no cursor of its track admits it, the track gone or
3980	/// closed included. Ready once the group closes too.
3981	///
3982	/// A group not yet handed out is owed to the cursors that admit it, since a session ingests
3983	/// only groups some reader asked for, and the first to pick it up reads from the start:
3984	/// reading on before then would hold more than a window, or shed what that reader wants.
3985	/// One every cursor passes over, outside its ranges or past its cap, is owed to nobody.
3986	fn poll_unowed(&self, waiter: &kio::Waiter) -> Poll<()> {
3987		loop {
3988			// Read before the count, as in `owed`.
3989			let held = self.held();
3990			if self.state.wanted() {
3991				match self.state.poll_wanted_changed(waiter, true) {
3992					Poll::Pending => return Poll::Pending,
3993					Poll::Ready(Ok(_)) => continue,
3994					Poll::Ready(Err(_)) => return Poll::Ready(()),
3995				}
3996			}
3997			if held {
3998				return Poll::Ready(());
3999			}
4000			// The track gone or closed leaves nobody to hand it to.
4001			let Some(track) = self.cache.track() else {
4002				return Poll::Ready(());
4003			};
4004			if track.poll_closed(waiter).is_ready() {
4005				return Poll::Ready(());
4006			}
4007			if self.cache.admits().poll_passed(self.info.start, waiter).is_ready() {
4008				return Poll::Ready(());
4009			}
4010			match self.state.poll_wanted_changed(waiter, false) {
4011				Poll::Ready(Ok(_)) => continue,
4012				Poll::Ready(Err(_)) => return Poll::Ready(()),
4013				// A reader that arrived and left before that registered shows only here.
4014				// One that arrived since is still counted, and its arrival wakes `waiter`.
4015				Poll::Pending => {
4016					return if self.held() && !self.state.wanted() {
4017						Poll::Ready(())
4018					} else {
4019						Poll::Pending
4020					};
4021				}
4022			}
4023		}
4024	}
4025
4026	/// The recorded abort reason, or [`Error::Dropped`] if the group closed without one.
4027	fn abort_reason(&self) -> Error {
4028		self.state.read().outcome.error().cloned().unwrap_or(Error::Dropped)
4029	}
4030}
4031
4032/// The outcome of a group's state polled from a handle: the channel closing short of one
4033/// (every writer gone without a finish or abort) reads as [`Error::Dropped`].
4034fn settle(poll: Poll<std::result::Result<Result<()>, kio::Ref<'_, GroupState>>>) -> Poll<Result<()>> {
4035	Poll::Ready(match ready!(poll) {
4036		Ok(outcome) => outcome,
4037		Err(closed) => match closed.poll_outcome() {
4038			Poll::Ready(outcome) => outcome,
4039			Poll::Pending => Err(Error::Dropped),
4040		},
4041	})
4042}
4043
4044/// A cloneable, watch-only handle to a group's readers.
4045///
4046/// A paced flight watches it to stop once its riders leave.
4047/// A frame being read counts as a reader of its group, and a group a track subscription
4048/// or fetch handed out keeps that track wanted until a reader reads its end
4049/// ([`track::Demand`]).
4050/// Once every handle to a finished group is gone, demand waits end with
4051/// [`Error::Dropped`]; an aborted group's keep its abort reason. Each clone watches on
4052/// its own, so its first [`poll_wanted_changed`](Self::poll_wanted_changed) reports the
4053/// current value.
4054pub struct Demand {
4055	key: u64,
4056	state: kio::ProducerPassive<GroupState>,
4057	// The value `poll_wanted_changed` last returned, or `None` before it returned any.
4058	prev: Option<bool>,
4059}
4060
4061impl Clone for Demand {
4062	fn clone(&self) -> Self {
4063		Self {
4064			key: self.key,
4065			state: self.state.clone(),
4066			prev: None,
4067		}
4068	}
4069}
4070
4071impl Demand {
4072	/// The start of the group this handle watches.
4073	pub fn start(&self) -> u64 {
4074		self.key
4075	}
4076
4077	/// Whether the group is open and has readers right now.
4078	pub fn wanted(&self) -> bool {
4079		!self.state.is_closed() && self.state.wanted()
4080	}
4081
4082	/// [`wanted`](Self::wanted) once it differs from what this handle last returned:
4083	/// immediately on the first call, then on each change. Errors once the group is closed.
4084	#[cfg_attr(feature = "async", kio::wrapper)]
4085	pub fn poll_wanted_changed(&mut self, waiter: &kio::Waiter) -> Poll<Result<bool>> {
4086		loop {
4087			if self.state.is_closed() {
4088				return Poll::Ready(Err(self.abort_reason()));
4089			}
4090			let wanted = self.state.wanted();
4091			if self.prev != Some(wanted) {
4092				self.prev = Some(wanted);
4093				return Poll::Ready(Ok(wanted));
4094			}
4095			// Closing fails the wait, which errors above.
4096			let _ = ready!(self.state.poll_wanted_changed(waiter, wanted));
4097		}
4098	}
4099
4100	/// Resolves once the group's outcome is final: `Ok` once finished, or the abort error.
4101	#[cfg_attr(feature = "async", kio::wrapper)]
4102	pub fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
4103		settle(self.state.consume_passive().poll(waiter, |state| state.poll_outcome()))
4104	}
4105
4106	fn abort_reason(&self) -> Error {
4107		self.state.read().outcome.error().cloned().unwrap_or(Error::Dropped)
4108	}
4109}
4110
4111/// A small batch of completed frames, drained from the shared group state under one
4112/// lock and then handed out without re-locking.
4113///
4114/// Each [`Consumer::read_frame`] otherwise takes the group mutex and allocates a
4115/// waker just to clone one `Bytes`; draining a batch amortizes both across `CAP`
4116/// frames. Storage is uninitialized and allocated by the first non-empty fill, so a
4117/// consumer that never reads whole frames, or drains through a higher-level buffer,
4118/// pays nothing. Inline storage would triple the size of every [`Consumer`], which
4119/// moves by value through each layer that hands out a group.
4120///
4121/// The frame buffer's allocation also holds its cursor and optional metadata pointers,
4122/// keeping an empty prefetch to one pointer without another allocation on the first fill.
4123/// Slots hold the public [`frame::Frame`], with a segmented payload set aside in `chains`,
4124/// so a whole read of a small frame moves it out of its slot as it did before segments.
4125#[derive(Default)]
4126struct Prefetch {
4127	batch: Option<Box<Batch>>,
4128}
4129
4130struct Batch {
4131	// Initialized, not-yet-taken frames are `frames[pos..len]`; the rest are uninitialized.
4132	// A slot whose frame is in `chains` holds an empty payload.
4133	frames: [MaybeUninit<frame::Frame>; Prefetch::CAP],
4134	// Segmented payloads for `frames`, allocated by the first batch that carries one.
4135	chains: Option<Box<[Option<frame::Chain>; Prefetch::CAP]>>,
4136	// Relay metadata for `frames`, allocated by the first batch that carries any.
4137	fields: Option<Box<[Option<Arc<super::object::Fields>>; Prefetch::CAP]>>,
4138	// Inflated sizes for `frames`, filled only by a batch of a compressed group's stored slices.
4139	inflated: Option<Box<[u64; Prefetch::CAP]>>,
4140	pos: usize,
4141	len: usize,
4142}
4143
4144impl Prefetch {
4145	const CAP: usize = 8;
4146
4147	/// The inflated size of the stored slice [`Self::pop`] just returned.
4148	fn take_inflated(&self) -> Option<u64> {
4149		let batch = self.batch.as_ref()?;
4150		batch.inflated.as_ref()?.get(batch.pos.checked_sub(1)?).copied()
4151	}
4152
4153	/// Take the next buffered frame whole, copying a segmented payload into one buffer.
4154	// Every small-frame read comes through here, so the chain copy stays out of line:
4155	// with it inline, this measured ~30 more instructions a frame on `group_read_frames`.
4156	#[inline(always)]
4157	fn pop(&mut self) -> Option<frame::Frame> {
4158		let mut frame = self.take()?;
4159		if self.batch.as_ref().is_some_and(|batch| batch.chains.is_some()) {
4160			self.join_chain(&mut frame);
4161		}
4162		Some(frame)
4163	}
4164
4165	#[cold]
4166	#[inline(never)]
4167	fn join_chain(&mut self, frame: &mut frame::Frame) {
4168		if let Some(chain) = self.take_chain() {
4169			frame.payload = chain.concat();
4170		}
4171	}
4172
4173	/// Take the next buffered frame as stored, keeping a segmented payload in segments.
4174	fn pop_cached(&mut self) -> Option<Cached> {
4175		let frame = self.take()?;
4176		Some(Cached {
4177			timestamp: frame.timestamp,
4178			payload: self.take_chain().map_or(Payload::Whole(frame.payload), Payload::Chain),
4179			created: frame.created,
4180		})
4181	}
4182
4183	#[inline]
4184	fn take(&mut self) -> Option<frame::Frame> {
4185		let batch = self.batch.as_mut()?;
4186		if batch.pos == batch.len {
4187			return None;
4188		}
4189		// SAFETY: `pos < len`, so this slot was written by `fill` and not yet taken.
4190		let frame = unsafe { batch.frames[batch.pos].assume_init_read() };
4191		batch.pos += 1;
4192		Some(frame)
4193	}
4194
4195	/// The segmented payload of the frame [`Self::take`] just returned.
4196	#[inline]
4197	fn take_chain(&mut self) -> Option<frame::Chain> {
4198		let batch = self.batch.as_mut()?;
4199		batch.chains.as_mut()?.get_mut(batch.pos.checked_sub(1)?)?.take()
4200	}
4201
4202	/// The relay metadata of the frame [`Self::pop`] just returned.
4203	fn take_fields(&mut self) -> Option<Arc<super::object::Fields>> {
4204		let batch = self.batch.as_mut()?;
4205		batch.fields.as_mut()?.get_mut(batch.pos.checked_sub(1)?)?.take()
4206	}
4207
4208	/// Empty a drained batch (`pop` returned `None`) for a refill, which keeps inflated
4209	/// sizes beside its frames when it reads a compressed group's stored slices.
4210	fn reset(&mut self, inflated: bool) {
4211		let Some(batch) = &mut self.batch else {
4212			return;
4213		};
4214		debug_assert_eq!(batch.pos, batch.len, "a refill of a non-empty batch would leak frames");
4215		batch.pos = 0;
4216		batch.len = 0;
4217		if !inflated {
4218			batch.inflated = None;
4219		}
4220	}
4221
4222	fn len(&self) -> usize {
4223		self.batch.as_ref().map_or(0, |batch| batch.len)
4224	}
4225
4226	/// Whether every buffered frame was taken.
4227	fn is_drained(&self) -> bool {
4228		self.batch.as_ref().is_none_or(|batch| batch.pos == batch.len)
4229	}
4230
4231	/// Buffer `entry` at the end of the batch, with its inflated size if `inflated`,
4232	/// returning where it ends on the group's pace scale.
4233	fn push(&mut self, entry: &Entry, inflated: bool) -> u64 {
4234		let batch = self.batch.get_or_insert_with(|| {
4235			Box::new(Batch {
4236				frames: [const { MaybeUninit::uninit() }; Self::CAP],
4237				chains: None,
4238				fields: None,
4239				inflated: None,
4240				pos: 0,
4241				len: 0,
4242			})
4243		});
4244		let at = batch.len;
4245		let payload = match (&entry.frame.payload, &mut batch.chains) {
4246			(Payload::Whole(bytes), Some(slots)) => {
4247				slots[at] = None;
4248				bytes.clone()
4249			}
4250			(Payload::Whole(bytes), None) => bytes.clone(),
4251			(Payload::Chain(chain), slots) => {
4252				slots.get_or_insert_default()[at] = Some(chain.clone());
4253				Bytes::new()
4254			}
4255		};
4256		batch.frames[at].write(frame::Frame {
4257			timestamp: entry.frame.timestamp,
4258			payload,
4259			created: entry.frame.created,
4260		});
4261		// Plain frames never allocate the metadata table.
4262		match (&entry.fields, &mut batch.fields) {
4263			(Some(fields), slots) => slots.get_or_insert_default()[at] = Some(fields.clone()),
4264			(None, Some(slots)) => slots[at] = None,
4265			(None, None) => {}
4266		}
4267		if inflated {
4268			batch.inflated.get_or_insert_default()[at] = entry.inflated;
4269		}
4270		batch.len += 1;
4271		entry.end
4272	}
4273
4274	/// Refill with up to `budget` of the completed frames from `index` on, under the
4275	/// group's guard.
4276	///
4277	/// A compressed group fills its stored slices, with `raw` their inflated sizes beside
4278	/// them, and otherwise returns the job [`Self::inflate`] runs once the guard is released.
4279	fn fill(&mut self, state: &GroupState, index: usize, budget: usize, raw: bool) -> Result<Option<Inflate>> {
4280		let sized = state.sized();
4281		self.reset(sized && (raw || state.meta));
4282		let end = index.saturating_add(budget.min(Self::CAP));
4283		// Below the stored slices, a plain read takes the inflated copy's frames as they are.
4284		if index < state.held()
4285			&& let Some(plain) = state.plain(raw)
4286		{
4287			return match plain.fill(self, index, end.min(state.held())) {
4288				0 => Err(Error::Evicted),
4289				_ => Ok(None),
4290			};
4291		}
4292		// A plain read of a compressed group takes at most one tail's worth of inflated
4293		// bytes, which the inflated copy holds until the batch takes them out.
4294		let mut inflated = 0u64;
4295		let count = state
4296			.entries(index, end)
4297			.enumerate()
4298			.take_while(|(at, entry)| {
4299				inflated = inflated.saturating_add(entry.inflated);
4300				*at == 0 || raw || state.meta || inflated <= MAX_CACHE_BYTES
4301			})
4302			.count();
4303		// Taken before any slot is written, so a refusal leaves the batch empty.
4304		let job = match &state.flate {
4305			Some(flate) if !raw && count > 0 => Some(state.inflate(flate, index, index + count - 1)?),
4306			_ => None,
4307		};
4308		let mut end = 0;
4309		for entry in state.entries(index, index + count) {
4310			end = self.push(entry, sized && (raw || state.meta));
4311		}
4312		// The batch is the reader's whatever the group sheds, so it counts as taken.
4313		state.pace.took(end);
4314		Ok(job)
4315	}
4316
4317	/// Refill with up to `budget` of the completed frames from `index` on, reading the
4318	/// log without the group's guard, and return how many. A plain read of a `compressed`
4319	/// group inflates under the guard instead, through [`Self::fill`].
4320	///
4321	/// The batch is the reader's whatever the group sheds, so it reports it taken to `pace`.
4322	fn fill_log(
4323		&mut self,
4324		log: &mut kio::log::Reader<Entry>,
4325		pace: &Pace,
4326		index: usize,
4327		budget: usize,
4328		compressed: bool,
4329	) -> usize {
4330		self.reset(compressed);
4331		let mut read = log.read();
4332		let mut end = 0;
4333		for index in (index as u64..=u64::MAX).take(budget.min(Self::CAP)) {
4334			// Evicted or not yet committed: the guard resolves which.
4335			let Ok(Some(entry)) = read.get(index) else {
4336				break;
4337			};
4338			end = self.push(entry, compressed);
4339		}
4340		pace.took(end);
4341		self.len()
4342	}
4343
4344	/// Replace a filled batch's stored slices, from local frame `local`, with their inflated
4345	/// frames. A frame that fails to inflate ends the batch, failing it if first.
4346	fn inflate(&mut self, job: &Inflate, local: usize, meter: &stats::Meter) -> Result<()> {
4347		job.run(meter);
4348		let Some(batch) = &mut self.batch else {
4349			return Ok(());
4350		};
4351		for i in batch.pos..batch.len {
4352			match job.get(local + i) {
4353				Ok(payload) => {
4354					// SAFETY: slots in `pos..len` are initialized (written by `fill`, not yet popped).
4355					unsafe { batch.frames[i].assume_init_mut() }.payload = payload;
4356					if let Some(chains) = &mut batch.chains {
4357						chains[i] = None;
4358					}
4359				}
4360				Err(err) => {
4361					for slot in &mut batch.frames[i..batch.len] {
4362						// SAFETY: as above, and `len` drops below them right after.
4363						unsafe { slot.assume_init_drop() };
4364					}
4365					batch.len = i;
4366					job.plain.trim();
4367					return if i == batch.pos { Err(err) } else { Ok(()) };
4368				}
4369			}
4370		}
4371		// Taken out, so the inflated copy may shed them past its tail.
4372		job.plain.trim();
4373		Ok(())
4374	}
4375
4376	/// `(frame count, total payload bytes)` of the buffered, not-yet-taken frames.
4377	/// Read once per fill to bump the egress payload counters for the whole batch.
4378	fn buffered(&self) -> (u64, u64) {
4379		let mut bytes = 0u64;
4380		let Some(batch) = &self.batch else {
4381			return (0, 0);
4382		};
4383		for slot in &batch.frames[batch.pos..batch.len] {
4384			// SAFETY: slots in `pos..len` are initialized (written by `fill`, not yet popped).
4385			bytes += unsafe { slot.assume_init_ref() }.payload.len() as u64;
4386		}
4387		if let Some(chains) = &batch.chains {
4388			bytes += chains[batch.pos..batch.len]
4389				.iter()
4390				.flatten()
4391				.map(|chain| chain.len() as u64)
4392				.sum::<u64>();
4393		}
4394		((batch.len - batch.pos) as u64, bytes)
4395	}
4396}
4397
4398impl Drop for Batch {
4399	fn drop(&mut self) {
4400		for slot in &mut self.frames[self.pos..self.len] {
4401			// SAFETY: slots in `pos..len` are initialized and were never taken.
4402			unsafe { slot.assume_init_drop() };
4403		}
4404	}
4405}
4406
4407/// Consume a group, frame-by-frame.
4408///
4409/// A read's error belongs to this group alone, whatever it says: the track reads on, so a
4410/// reader moves to the next group rather than matching the error. Only the track's own reads
4411/// report that the track ended.
4412pub struct Consumer {
4413	cursor: Cursor,
4414
4415	// Immutable stream state.
4416	info: Info,
4417
4418	// Cold metadata shares the allocation that deduplicates expiry across clones.
4419	delivery: Arc<Delivery>,
4420
4421	// Egress payload meter, set by a tagged track via [`Self::with_meter`]. Empty
4422	// (no-op) for an untagged group. Also owns unread content discarded by expiry.
4423	stats: stats::Meter,
4424
4425	// Subscriber-specific drift policy. A group can become stale after the track
4426	// hands it out, while its reader is waiting for the first or next frame.
4427	expiry: Option<Arc<dyn Expiry>>,
4428	expired: bool,
4429	// A replacement copy was adopted and has not yet returned a frame that matches. Its
4430	// ordinals match this group's only while its Object IDs do.
4431	adopted: bool,
4432	// Carries the read across route changes and onto flights. Boxed: it is the rare case.
4433	carry: Option<Box<Carry>>,
4434	// The frame read that last parked, answered again without the read path until something
4435	// it parked on fires, once a read parks twice in a row; see [`Self::poll_read_as`].
4436	idle: Option<Box<Idle<()>>>,
4437	// The last frame read parked with no gate set up yet.
4438	parked: bool,
4439}
4440
4441// Poll layers repeatedly move this value; keep cold state shared or lazy.
4442#[cfg(target_pointer_width = "64")]
4443const _: () = assert!(size_of::<Consumer>() <= 184);
4444
4445/// Drop an end check's held copy once the reader moved to another copy itself.
4446fn drop_finishing(carry: &mut Option<Box<Carry>>) {
4447	if let Some(carry) = carry {
4448		carry.finishing = None;
4449	}
4450}
4451
4452/// What carries a read past the copy it reads; see [`Consumer::with_recover`] and
4453/// [`track::board`].
4454#[derive(Default)]
4455struct Carry {
4456	// Handed out from a front's logical track: carries the read across route changes.
4457	recover: Option<super::resume::Recover>,
4458	// Boarding or riding a flight, once the copy read shed the frame read next.
4459	ride: Option<Ride>,
4460	// The copy an end check waits on past the frames this reader prefetched, with the frame
4461	// it reads that copy from: held between polls so the copy keeps this reader's demand.
4462	finishing: Option<(usize, Consumer)>,
4463	// What ended the read once a copy closed the group below the frames already read: no
4464	// route change after undoes it.
4465	failed: Option<Error>,
4466	// The frames up to the cursor this reader skipped rather than read: where it started, or
4467	// where a skip moved it, until it reads on. A copy closing inside them took no frame back.
4468	unread: std::ops::Range<usize>,
4469}
4470
4471impl Clone for Carry {
4472	fn clone(&self) -> Self {
4473		Self {
4474			recover: self.recover.clone(),
4475			// A clone reads in parallel, so it boards for itself.
4476			ride: self.ride.as_ref().map(|ride| Ride {
4477				boarding: None,
4478				..*ride
4479			}),
4480			finishing: None,
4481			failed: self.failed.clone(),
4482			unread: self.unread.clone(),
4483		}
4484	}
4485}
4486
4487/// A reader's flight: a separate copy of its group, from a frame the copy it read shed.
4488struct Ride {
4489	// The flight asked for, until its copy is accepted.
4490	boarding: Option<track::Boarding>,
4491	// Whether the copy read is a flight, which the reader hands over from.
4492	aboard: bool,
4493	// Frames still to read and drop before the reader's own: a compressed flight starts at
4494	// frame 0, and its rider inflates its way to the frame it boarded at.
4495	skip: usize,
4496}
4497
4498impl Ride {
4499	/// Reading the copy boarded, a flight when `flight`, with `skip` frames to drop first.
4500	fn aboard(flight: bool, skip: usize) -> Self {
4501		Self {
4502			boarding: None,
4503			aboard: flight,
4504			skip,
4505		}
4506	}
4507}
4508
4509/// Per-delivery state shared by a consumer's clones and its frame readers.
4510/// Kept across replacement copies, so provenance and arrival remain the original's.
4511pub(super) struct Delivery {
4512	timescale: Option<Timescale>,
4513	#[cfg(feature = "async")]
4514	ietf: Option<crate::ietf::Version>,
4515	#[cfg(feature = "async")]
4516	timestamp_ids: Option<bool>,
4517	created: crate::time::Instant,
4518	// Whichever reader observes expiry first records its unread tail only once.
4519	pub(super) stale_counted: AtomicBool,
4520	// The budget the first verdict judged the group stale under.
4521	stale_under: std::sync::OnceLock<std::time::Duration>,
4522}
4523
4524/// Subscriber-specific policy for a group after it was handed out: when it expires, and
4525/// the track demand its readers hold until they read its end.
4526///
4527/// Unwind safe so the [`Consumer`] holding it is, and so the published
4528/// [`track::Fetching`] that holds a consumer stays unwind safe too.
4529pub(super) trait Expiry: Send + Sync + std::panic::UnwindSafe + std::panic::RefUnwindSafe {
4530	/// A reader read the group's end, so it no longer keeps the track wanted.
4531	fn ended(&self) {}
4532
4533	/// The budget the group was judged stale under, `Duration::MAX` for the publisher's max
4534	/// age, or `None` while it is not stale, registering `waiter` for anything that could
4535	/// change the answer while the group remains live.
4536	/// A logical reader's `recover` supplies its current budget after the original copy is
4537	/// gone, asked only once a verdict needs it.
4538	fn is_expired(&self, recover: Option<&super::resume::Recover>, waiter: &kio::Waiter)
4539	-> Option<std::time::Duration>;
4540
4541	/// Whether the group has aged past `budget`, held to the publisher's max age, as
4542	/// [`Self::is_expired`] judges its own, registering `waiter` for anything that could change
4543	/// the answer while it has not.
4544	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
4545	fn aged(&self, budget: std::time::Duration, recover: Option<&super::resume::Recover>, waiter: &kio::Waiter)
4546	-> bool;
4547
4548	/// Keep the reader's budget and cap while following a replacement track's edge.
4549	fn for_track(&self, track: &track::Consumer) -> Arc<dyn Expiry>;
4550
4551	/// What the reader asks a fill with, such as the flight it boards.
4552	fn asking(&self) -> super::track::Asking;
4553}
4554
4555/// What a reader under `expiry` asks a fill with: its subscription's or fetch's, else the
4556/// defaults.
4557pub(super) fn asking(expiry: Option<&Arc<dyn Expiry>>) -> track::Asking {
4558	expiry.map_or(
4559		track::Asking {
4560			priority: 0,
4561			order: super::subscription::Order::Ascending,
4562		},
4563		|expiry| expiry.asking(),
4564	)
4565}
4566
4567/// The read cursor over a [`Producer`]'s shared state.
4568struct Cursor {
4569	// Shared state with the producer.
4570	state: kio::Consumer<GroupState>,
4571
4572	// Reads committed frames without the state's lock, which only the edge, the adopted
4573	// front, and a compressed group's plain reads still take.
4574	log: kio::log::Reader<Entry>,
4575
4576	// The index of the next frame to read.
4577	// NOTE: Cloned readers inherit this offset, but then run in parallel.
4578	index: usize,
4579
4580	// Exclusive cap on `index`, set by [`Consumer::with_range`]. Reads end cleanly at it.
4581	end: Option<usize>,
4582
4583	// A batch of completed frames drained ahead under one lock (whole-frame reads only).
4584	prefetch: Prefetch,
4585
4586	// Read a compressed group's stored slices rather than its inflated copy.
4587	raw: bool,
4588
4589	// Whether the last frame handed out to stream from this copy was still being written,
4590	// until a skip past it or a header read gives up its payload. Left uncommitted when the
4591	// copy fails, it is torn. A whole read
4592	// after it follows its commit, so it can leave this set.
4593	partial: bool,
4594
4595	// Whether the group is compressed, so a plain read inflates under the state's lock.
4596	compressed: bool,
4597
4598	// Record prefetched reads without entering the group's state on every frame, through
4599	// the group's access stamp, and report the frames taken to its pace.
4600	cache: Arc<cache::Track>,
4601	alive: Arc<Alive>,
4602	refreshed: u64,
4603}
4604
4605impl Clone for Cursor {
4606	fn clone(&self) -> Self {
4607		// A clone shares the channel and inherits `index`, but starts with an empty
4608		// prefetch: it re-reads its batch from the shared state, in parallel.
4609		Self {
4610			state: self.state.clone(),
4611			log: self.log.clone(),
4612			index: self.index,
4613			end: self.end,
4614			prefetch: Prefetch::default(),
4615			raw: self.raw,
4616			partial: self.partial,
4617			compressed: self.compressed,
4618			cache: self.cache.clone(),
4619			alive: self.alive.clone(),
4620			refreshed: self.refreshed,
4621		}
4622	}
4623}
4624
4625impl Clone for Consumer {
4626	fn clone(&self) -> Self {
4627		Self {
4628			cursor: self.cursor.clone(),
4629			info: self.info,
4630			delivery: self.delivery.clone(),
4631			// Inherit the meter without re-counting the group: the original already
4632			// counted it when the track handed it out.
4633			stats: self.stats.clone(),
4634			expiry: self.expiry.clone(),
4635			expired: self.expired,
4636			adopted: self.adopted,
4637			carry: self.carry.clone(),
4638			// A clone reads in parallel, so it parks for itself.
4639			idle: None,
4640			parked: false,
4641		}
4642	}
4643}
4644
4645impl std::ops::Deref for Consumer {
4646	type Target = Info;
4647
4648	fn deref(&self) -> &Self::Target {
4649		&self.info
4650	}
4651}
4652
4653impl Consumer {
4654	/// The final frame count once the group has settled (finished or released), or `None`
4655	/// while frames may still arrive.
4656	#[cfg(feature = "async")]
4657	pub(crate) fn settled_frames(&self) -> Option<usize> {
4658		self.cursor.state.read().outcome.frames()
4659	}
4660
4661	/// Whether this copy settled at its transport back-cut at or before `index`.
4662	pub(super) fn past_cut(&self, index: usize) -> bool {
4663		self.cursor.state.read().past_cut(index)
4664	}
4665
4666	/// The last object's ID, the terminal one included, as a relay preserves it for Largest.
4667	#[cfg(feature = "async")]
4668	pub(crate) fn last_object(&self) -> Option<u64> {
4669		let state = self.cursor.state.read();
4670		match state.wire() {
4671			Some(wire) => wire.last,
4672			None => (state.next_index as u64).checked_sub(1),
4673		}
4674	}
4675
4676	/// The last data object's ID, as [`Handle::last_data_object`]: never the terminal object.
4677	#[cfg(feature = "async")]
4678	pub(crate) fn last_data_object(&self) -> Option<u64> {
4679		self.cursor.state.read().last_data_object()
4680	}
4681
4682	/// The ordinal of the last frame written, which a dense Object ID equals.
4683	#[cfg(feature = "async")]
4684	pub(crate) fn last_frame(&self) -> Option<u64> {
4685		(self.cursor.state.read().next_index as u64).checked_sub(1)
4686	}
4687
4688	/// The moq-timestamp Object ID of frame `index` (see [`GroupState::timed_ids`]), or `None`
4689	/// when it is not written yet or this copy no longer holds frame 0.
4690	#[cfg(feature = "async")]
4691	pub(crate) fn timed_id(&self, index: u64) -> Option<u64> {
4692		let index = usize::try_from(index).ok()?;
4693		self.cursor
4694			.state
4695			.read()
4696			.timed_ids(self.start, self.timestamp_ids() == Some(true))?
4697			.nth(index)
4698			.map(|(id, _)| id)
4699	}
4700
4701	/// Frame `index`'s moq-timestamp Object ID and the timestamp value it goes out at, as
4702	/// [`Self::timed_id`]: the highest through it, since a lite-05/06 copy may hold a lower one.
4703	#[cfg(feature = "async")]
4704	pub(crate) fn timed_entry(&self, index: u64) -> Option<(u64, u64)> {
4705		let index = usize::try_from(index).ok()?;
4706		self.cursor
4707			.state
4708			.read()
4709			.timed_ids(self.start, self.timestamp_ids() == Some(true))?
4710			.nth(index)
4711	}
4712
4713	/// The highest timestamp of the frames below `index` this copy held, shed ones included, in
4714	/// its track's timescale: what a stream resumed at `index` raises a lower frame to, so a frame
4715	/// goes out at one time whatever its stream's start. Only a lite-05/06 copy holds a decrease.
4716	#[cfg(feature = "async")]
4717	pub(crate) fn highest_below(&self, index: u64) -> Option<Timestamp> {
4718		let index = usize::try_from(index).ok()?;
4719		let state = self.cursor.state.read();
4720		let shed = (state.held() > state.offset && state.held() <= index)
4721			.then(|| match self.timescale() {
4722				Some(scale) => Timestamp::new(state.shed_high, scale).ok(),
4723				None => Some(Timestamp::unscaled(state.shed_high)),
4724			})
4725			.flatten();
4726		(state.entries(0, index).map(|entry| entry.frame.timestamp))
4727			.chain(shed)
4728			.reduce(Timestamp::later)
4729	}
4730
4731	/// The moq-timestamp Object ID of the last frame written. A copy that no longer holds
4732	/// frame 0 answers the last timestamp's offset from the start, which the ID is never below.
4733	#[cfg(feature = "async")]
4734	pub(crate) fn last_timed_id(&self) -> Option<u64> {
4735		let state = self.cursor.state.read();
4736		let last = state.next_index.checked_sub(1)?;
4737		if let Some((id, _)) = state
4738			.timed_ids(self.start, self.timestamp_ids() == Some(true))
4739			.and_then(|mut ids| ids.nth(last))
4740		{
4741			return Some(id);
4742		}
4743		match state.timeline {
4744			Timeline::Timed { latest, .. } => Some(latest.value().saturating_sub(self.start)),
4745			Timeline::Empty | Timeline::Untimed => None,
4746		}
4747	}
4748
4749	/// The first frame whose moq-timestamp Object ID is at least `id`, or the next frame to be
4750	/// written when none is yet; `None` when this copy no longer holds frame 0, or can't derive
4751	/// the IDs that far ([`Self::unproven`]).
4752	#[cfg(feature = "async")]
4753	pub(crate) fn timed_frame(&self, id: u64) -> Option<u64> {
4754		let state = self.cursor.state.read();
4755		let timestamp_ids = self.timestamp_ids() == Some(true);
4756		let mut ids = state.timed_ids(self.start, timestamp_ids)?;
4757		match ids.position(|(timed, _)| timed >= id) {
4758			Some(index) => Some(index as u64),
4759			None if state.unproven(timestamp_ids).is_some() => None,
4760			None => Some(state.next_index as u64),
4761		}
4762	}
4763
4764	/// The first frame whose moq-timestamp Object ID this copy can't derive, though it holds
4765	/// frame 0: an ordinal copy's frame after an Object ID it lacks with no gap mark, or the
4766	/// frame count when that ID comes last. The frames before it keep their IDs.
4767	#[cfg(feature = "async")]
4768	pub(crate) fn unproven(&self) -> Option<u64> {
4769		self.cursor.state.read().unproven(self.timestamp_ids() == Some(true))
4770	}
4771
4772	/// Whether the group finished with every frame written, not cut short by its transport.
4773	#[cfg(feature = "async")]
4774	pub(crate) fn is_finished(&self) -> bool {
4775		let state = self.cursor.state.read();
4776		state.outcome.frames().is_some() && state.range_end.is_none()
4777	}
4778
4779	#[cfg(feature = "async")]
4780	pub(crate) fn wire(&self) -> Option<Wire> {
4781		self.cursor.state.read().wire().cloned()
4782	}
4783
4784	/// The relay state an egress header describes, once the ingest has set it, or
4785	/// [`Error::Old`] once the drift budget gives up on the group first.
4786	#[cfg(feature = "async")]
4787	pub(crate) fn poll_wire(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Wire>>> {
4788		// A dropped producer settled whatever it was going to.
4789		let res = self
4790			.cursor
4791			.poll(waiter, |state| state.poll_wire())
4792			.map(|res| Ok(res.unwrap_or_else(|_| self.wire())));
4793		self.poll_expired_if_blocked(waiter, res)
4794	}
4795
4796	/// Read a compressed group's stored DEFLATE slices instead of plain frames, with each
4797	/// frame's inflated size beside it ([`frame::Object::inflated`],
4798	/// [`frame::Consumer::inflated`]), for egress that carries compression. A no-op on a
4799	/// plain group.
4800	pub(crate) fn compressed(mut self) -> Self {
4801		Idle::disarm(&mut self.idle);
4802		self.cursor.raw = true;
4803		self.cursor.prefetch = Prefetch::default();
4804		self
4805	}
4806
4807	/// Resolves once the group's outcome is final, wherever this cursor is: `Ok` once
4808	/// finished, or the abort error.
4809	pub(crate) fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
4810		self.cursor.poll(waiter, |state| state.poll_outcome())
4811	}
4812
4813	/// The index of the first frame the group holds (see `Producer::start_at`).
4814	pub(crate) fn first_frame(&self) -> u64 {
4815		self.cursor.state.read().offset as u64
4816	}
4817
4818	#[cfg(feature = "async")]
4819	pub(crate) fn end_object(&self) -> Option<Arc<super::object::Fields>> {
4820		self.cursor.state.read().relay.as_ref()?.end_object.clone()
4821	}
4822
4823	/// Fill a private batch without losing metadata through the public frame view.
4824	#[cfg(feature = "async")]
4825	pub(crate) fn poll_read_objects<const N: usize>(
4826		&mut self,
4827		waiter: &kio::Waiter,
4828		out: &mut arrayvec::ArrayVec<frame::Object, N>,
4829	) -> Poll<Result<usize>> {
4830		out.clear();
4831		while !out.is_full() {
4832			match self.poll_read_object(waiter) {
4833				Poll::Ready(Ok(Some(frame))) => out.push(frame),
4834				Poll::Ready(Ok(None)) => break,
4835				Poll::Ready(Err(err)) if out.is_empty() => return Poll::Ready(Err(err)),
4836				Poll::Ready(Err(_)) => break,
4837				Poll::Pending if out.is_empty() => return Poll::Pending,
4838				Poll::Pending => break,
4839			}
4840		}
4841		Poll::Ready(Ok(out.len()))
4842	}
4843
4844	/// Snapshot the content this cursor would discard if its group were skipped.
4845	pub(super) fn content(&self) -> stats::Content {
4846		self.cursor.state.read().content()
4847	}
4848
4849	/// Attach an egress payload meter, counting this as one delivered group.
4850	/// Called by a tagged track when it hands the consumer to a subscriber or fetch.
4851	pub(crate) fn with_meter(mut self, meter: stats::Meter) -> Self {
4852		meter.group();
4853		self.stats = meter;
4854		self
4855	}
4856
4857	/// Hand this consumer's payload counts, and its clones' made after, to a wire writer that
4858	/// bills them as the transport delivers them. See [`stats::Meter::delegate`].
4859	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
4860	pub(crate) fn delegate(&mut self) -> stats::Meter {
4861		self.stats.delegate()
4862	}
4863
4864	/// Keep applying this subscription's drift budget while the group is read.
4865	pub(super) fn with_expiry(mut self, expiry: Arc<dyn Expiry>) -> Self {
4866		Idle::disarm(&mut self.idle);
4867		self.expiry = Some(expiry);
4868		self
4869	}
4870
4871	/// What this reader asks a fill with: its subscription's or fetch's, else the defaults.
4872	pub(super) fn asking(&self) -> super::track::Asking {
4873		asking(self.expiry.as_ref())
4874	}
4875
4876	/// The hand-off of this copy's head, shared by every reader that could resume it
4877	/// elsewhere.
4878	pub(super) fn handoff(&self) -> Arc<Handoff> {
4879		let state = self.cursor.state.read();
4880		let mut handoff = state.handoff.lock().unwrap_or_else(PoisonError::into_inner);
4881		if let Some(handoff) = handoff.upgrade() {
4882			return handoff;
4883		}
4884		let shared = Arc::new(Handoff {
4885			state: Some(self.cursor.state.passive()),
4886			salvaged: Mutex::default(),
4887		});
4888		*handoff = Arc::downgrade(&shared);
4889		shared
4890	}
4891
4892	/// Carry this group across a front's route changes; see [`super::resume`].
4893	pub(super) fn with_recover(mut self, recover: super::resume::Recover) -> Self {
4894		Idle::disarm(&mut self.idle);
4895		let index = self.position();
4896		let carry = self.carry.get_or_insert_default();
4897		carry.recover = Some(recover);
4898		carry.unread = 0..index;
4899		self
4900	}
4901
4902	/// The frame this reader reads next: the cursor, plus the frames a compressed flight it
4903	/// boarded still inflates and drops to get back there.
4904	fn position(&self) -> usize {
4905		let skip = self
4906			.carry
4907			.as_ref()
4908			.and_then(|carry| carry.ride.as_ref())
4909			.map_or(0, |ride| ride.skip);
4910		self.cursor.index.saturating_add(skip)
4911	}
4912
4913	/// Note that the read moved from position `from` to where it is without reading the frames
4914	/// between.
4915	fn skipped(&mut self, from: usize) {
4916		let to = self.position();
4917		if let Some(carry) = self.carry.as_mut().filter(|carry| carry.recover.is_some())
4918			&& to > from
4919		{
4920			match carry.unread.end == from {
4921				true => carry.unread.end = to,
4922				false => carry.unread = from..to,
4923			}
4924		}
4925	}
4926
4927	/// Run `read`, and once this copy fails with its route, stalls while a newer route serves,
4928	/// or closes the group short after a newer route took over, continue from the serving
4929	/// route's copy at the same frame and read again.
4930	///
4931	/// `read` ends with `None` only at the end of the group as this copy holds it.
4932	fn poll_resumed<T>(
4933		&mut self,
4934		waiter: &kio::Waiter,
4935		mut read: impl FnMut(&mut Self, &kio::Waiter) -> Poll<Result<Option<T>>>,
4936	) -> Poll<Result<Option<T>>> {
4937		loop {
4938			if let Some(err) = self.carry.as_ref().and_then(|carry| carry.failed.clone()) {
4939				return Poll::Ready(Err(err));
4940			}
4941			let res = read(self, waiter);
4942			// The reader's own budget gave up on it: that is no route's doing.
4943			if self.expired {
4944				return res;
4945			}
4946			let index = self.cursor.index;
4947			let short = matches!(res, Poll::Ready(Ok(None))) && self.closed_short();
4948			// A copy taken over mid-group may close it below the frames already read from the
4949			// copy before it, so its close cannot be where this read ends. One below only frames
4950			// the read skipped still ends it cleanly, as an empty range does.
4951			let past = short && self.closed_past();
4952			let Some(recover) = self.carry.as_mut().and_then(|carry| carry.recover.as_mut()) else {
4953				return res;
4954			};
4955			let cause = match &res {
4956				Poll::Ready(Ok(Some(_))) => {
4957					recover.resumed();
4958					// The old copy was dense through this frame, so the replacement must be too.
4959					// The refusal stays: a batch that already holds frames swallows one error.
4960					if self.adopted {
4961						if self.cursor.state.read().sparse() {
4962							// `read_frame` pops prefetched frames without coming back here.
4963							self.cursor.prefetch = Prefetch::default();
4964							return Poll::Ready(Err(Error::Unsupported));
4965						}
4966						self.adopted = false;
4967					}
4968					return res;
4969				}
4970				// Closed short of a known end: a route that replaced this copy may hold more.
4971				Poll::Ready(Ok(None)) if short => Cause::Closed,
4972				// Read to its end: no route is needed for it any more.
4973				Poll::Ready(Ok(None)) => {
4974					self.let_go();
4975					return res;
4976				}
4977				// Content that failed to inflate is the group's under its name, so no copy fixes it.
4978				Poll::Ready(Err(err)) if !self.cursor.raw && self.cursor.state.read().malformed() => {
4979					recover.failed(index, err);
4980					return res;
4981				}
4982				// A lite-07 Position End cap cut this copy short at `range_end`: distinct from
4983				// ordinary cache eviction so route switch-back recovers the missing suffix.
4984				Poll::Ready(Err(Error::Evicted)) if self.cursor.state.read().past_cut(index) => Cause::Cut,
4985				Poll::Ready(Err(err)) => Cause::Failed(err.clone()),
4986				Poll::Pending => Cause::Stalled,
4987			};
4988			if !recover.wants(&cause, waiter) {
4989				match &cause {
4990					Cause::Failed(err) => recover.failed(index, err),
4991					Cause::Cut => recover.failed(index, &Error::Evicted),
4992					// The copy being read still serves and holds no more than was read, so
4993					// nothing continues the group.
4994					Cause::Closed if past => {
4995						recover.failed(index, &Error::NotFound);
4996						return Poll::Ready(Err(self.fail(Error::NotFound)));
4997					}
4998					// The copy being read still serves, so its close is the group's end.
4999					Cause::Closed => self.let_go(),
5000					Cause::Stalled => {}
5001				}
5002				return res;
5003			}
5004			recover.recovering(index, &cause);
5005			// A close stands only where the read is.
5006			let closed = short && !past;
5007			let replacement = match self.replacement(cause, waiter) {
5008				Poll::Ready(Ok(replacement)) => replacement,
5009				Poll::Ready(Err(err)) => {
5010					if let Some(recover) = self.recover_mut() {
5011						recover.failed(index, &err);
5012					}
5013					// Gone stale while waiting, named by the budget that judged it as
5014					// `poll_expiry` does.
5015					if let Some(budget) = self.recover().and_then(|recover| recover.stale_under()) {
5016						let _ = self.delivery.stale_under.set(budget);
5017						if !self.delivery.stale_counted.swap(true, Ordering::Relaxed) {
5018							self.stats.stale(self.cursor.unread_content());
5019						}
5020					}
5021					// Nothing continues a group closed short, so it ends where it closed.
5022					if closed {
5023						self.let_go();
5024						return res;
5025					}
5026					if past {
5027						return Poll::Ready(Err(self.fail(err)));
5028					}
5029					return Poll::Ready(Err(err));
5030				}
5031				// The reader's budget bounds the wait for the rest, as it does a stall, and
5032				// ends the group where it closed, if that close stands.
5033				Poll::Pending
5034					if short
5035						&& self
5036							.expiry
5037							.as_ref()
5038							.is_some_and(|e| e.is_expired(self.recover(), waiter).is_some()) =>
5039				{
5040					if !closed {
5041						// Named by the budget that judged it, as `poll_expiry` records it.
5042						let budget =
5043							(self.expiry.as_ref()).and_then(|expiry| expiry.is_expired(self.recover(), waiter));
5044						if let Some(budget) = budget {
5045							let _ = self.delivery.stale_under.set(budget);
5046						}
5047						return Poll::Ready(Err(self.fail(Error::Old)));
5048					}
5049					self.let_go();
5050					return res;
5051				}
5052				Poll::Pending => return Poll::Pending,
5053			};
5054			let recover = (self.carry.as_mut().and_then(|carry| carry.recover.as_mut()))
5055				.expect("a replacement comes from recovery");
5056			// Same frames by index, so only the channel changes; read progress and the
5057			// cap stay this cursor's.
5058			let (index, end, raw) = (self.cursor.index, self.cursor.end, self.cursor.raw);
5059			// Another read, such as `poll_finished`, may move the cursor while a frame read
5060			// is parked on the old copy.
5061			Idle::disarm(&mut self.idle);
5062			recover.adopt(&replacement);
5063			self.expiry = self.expiry.as_ref().map(|expiry| expiry.for_track(&replacement.copy));
5064			self.cursor = replacement.group.cursor;
5065			self.cursor.index = index;
5066			self.cursor.end = end;
5067			self.cursor.raw = raw;
5068			self.adopted = true;
5069			drop_finishing(&mut self.carry);
5070		}
5071	}
5072
5073	/// The serving route's copy to continue this group from once its copy looks past itself for
5074	/// `cause`, or the error that ends the read instead.
5075	fn replacement(&mut self, cause: Cause, waiter: &kio::Waiter) -> Poll<Result<super::resume::Replacement>> {
5076		// An ordinal FETCH would request different content after an Object ID gap.
5077		if self.cursor.state.read().sparse() {
5078			return Poll::Ready(Err(Error::Unsupported));
5079		}
5080		let index = self.cursor.index as u64;
5081		let recover = self.recover_mut().expect("only a recovering group needs a replacement");
5082		let replacement = ready!(recover.poll(index, &cause, waiter))?;
5083		let failed = match cause {
5084			Cause::Failed(err) => Some(err),
5085			Cause::Stalled | Cause::Closed | Cause::Cut => None,
5086		};
5087		// A plain read inflates from frame 0, which a replacement starting later lacks
5088		// when the failed route's head was not lent to it.
5089		if !self.cursor.raw
5090			&& replacement.group.first_frame() > 0
5091			&& replacement.group.cursor.state.read().flate.is_some()
5092		{
5093			return Poll::Ready(Err(failed.unwrap_or(Error::Lagged)));
5094		}
5095		// A copy that shed the frame read next can't continue it, and recovering onto it
5096		// again would only fail the same way. One that starts past it lags only itself.
5097		if let Err(err) = replacement
5098			.group
5099			.cursor
5100			.state
5101			.read()
5102			.check_read(self.cursor.index, self.cursor.raw)
5103			&& !matches!(err, Error::Lagged)
5104		{
5105			return Poll::Ready(Err(failed.unwrap_or(err)));
5106		}
5107		Poll::Ready(Ok(replacement))
5108	}
5109
5110	/// Whether the subscription this group was handed out under has given up on it, waking
5111	/// once it does.
5112	///
5113	/// A publisher still writing the group polls this while it waits on its own transport,
5114	/// which the group's reads cannot see: once the `max` of the live joins reaching it
5115	/// ([`Start::Live`](crate::track::Start::Live)) expires the group, it abandons
5116	/// the stream, even with every frame already read off. It abandons it too once
5117	/// [`Self::poll_finished`] fails. Stays `true` once set.
5118	#[cfg(any(feature = "async", test))]
5119	pub(crate) fn poll_expired(&mut self, waiter: &kio::Waiter) -> bool {
5120		self.poll_expiry(waiter, true)
5121	}
5122
5123	/// Whether the group has aged past `budget` under the subscription it was handed out
5124	/// under, waking once it does: a range wanting it for that long stops wanting it then,
5125	/// though another may still. `false` for a group handed out under none.
5126	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
5127	pub(crate) fn poll_aged(&self, budget: std::time::Duration, waiter: &kio::Waiter) -> bool {
5128		(self.expiry.as_ref()).is_some_and(|expiry| expiry.aged(budget, self.recover(), waiter))
5129	}
5130
5131	/// Apply the drift budget to a read that found nothing and is about to park, failing
5132	/// it with [`Error::Old`] once the budget gives up.
5133	///
5134	/// A group with frames in hand is always drained to its end: the budget bounds a
5135	/// group that has *stalled* while the live edge moved on, not one whose reader is
5136	/// merely slower than the wire. Judging every read instead would truncate the tail
5137	/// of every group, since the arrival of the next group is exactly what makes the
5138	/// current one no longer newest.
5139	///
5140	/// A reader that took every frame still fails: the producer never finished the
5141	/// group, so a clean end would pass the prefix off as the whole group to anyone it
5142	/// is served to.
5143	///
5144	/// Keeping it off the ready path also keeps it off the hot path: evaluating the
5145	/// policy walks the track's group cache under its lock, which is shared by every
5146	/// subscriber of that track.
5147	fn poll_expired_if_blocked<T>(&mut self, waiter: &kio::Waiter, res: Poll<Result<T>>) -> Poll<Result<T>> {
5148		match res.is_pending() && self.poll_expiry(waiter, false) {
5149			true => Poll::Ready(Err(Error::Old)),
5150			false => res,
5151		}
5152	}
5153
5154	/// Apply the drift budget, judging even a group whose cursor has nothing left to
5155	/// discard when `held`, since its reader still holds data from it.
5156	fn poll_expiry(&mut self, waiter: &kio::Waiter, held: bool) -> bool {
5157		if !self.expired
5158			&& (held || self.expiry_pending())
5159			&& let Some(budget) = (self.expiry.as_ref()).and_then(|expiry| expiry.is_expired(self.recover(), waiter))
5160		{
5161			self.expired = true;
5162			let _ = self.delivery.stale_under.set(budget);
5163			// Another read, such as `poll_expired`, may judge a frame read parked before it.
5164			Idle::disarm(&mut self.idle);
5165			if !self.delivery.stale_counted.swap(true, Ordering::Relaxed) {
5166				self.stats.stale(self.cursor.unread_content());
5167			}
5168		}
5169		self.expired
5170	}
5171
5172	/// The budget this group was judged stale under, `Duration::MAX` for the publisher's max
5173	/// age, or `None` while it was not.
5174	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
5175	pub(crate) fn expired_under(&self) -> Option<std::time::Duration> {
5176		self.delivery.stale_under.get().copied()
5177	}
5178
5179	/// Whether expiry can still discard content or unblock a group that may grow.
5180	fn expiry_pending(&self) -> bool {
5181		self.cursor.expiry_pending()
5182	}
5183
5184	/// Mark the group as still being read, so a slow batch drain does not expire it.
5185	pub(crate) fn keep_alive(&self) {
5186		self.cursor.state.read().charge.refresh();
5187	}
5188
5189	/// Record a cache access from the consumer side: a parked group re-offered to
5190	/// its subscriber. Same stamp as [`Producer::cache_refresh`].
5191	pub(super) fn cache_refresh(&self) {
5192		self.keep_alive();
5193	}
5194
5195	/// The parent track's timescale, or `None` when it declared no timeline.
5196	pub fn timescale(&self) -> Option<Timescale> {
5197		self.delivery.timescale
5198	}
5199
5200	/// When the group was created at this hop, before its first frame, on the ambient clock:
5201	/// when its header was received, or when it was fetched or created here.
5202	///
5203	/// Fixed for the consumer's life, so a reader that pulls the group late still measures
5204	/// from when it landed, as [`frame::Frame::created`] does for each frame. A consumer
5205	/// resumed onto a replacement copy keeps the original group's arrival.
5206	pub fn created(&self) -> crate::time::Instant {
5207		self.delivery.created
5208	}
5209
5210	/// The draft the parent track's moq-transport publisher spoke, which serialized every
5211	/// object's properties, or `None` for a moq-lite one.
5212	#[cfg(feature = "async")]
5213	pub(crate) fn ietf(&self) -> Option<crate::ietf::Version> {
5214		self.delivery.ietf
5215	}
5216
5217	/// Whether the parent track's moq-transport publisher declared `ID_TIMESCALE`, so its
5218	/// Object IDs are moq-timestamp IDs, or `None` for a moq-lite one.
5219	#[cfg(feature = "async")]
5220	pub(crate) fn timestamp_ids(&self) -> Option<bool> {
5221		self.delivery.timestamp_ids
5222	}
5223
5224	/// The index of the next frame this consumer will return.
5225	///
5226	/// Starts at 0, or at the group's first available frame once [`Self::with_range`] has
5227	/// clamped it, and advances by one per frame read.
5228	pub fn index(&self) -> u64 {
5229		self.cursor.index as u64
5230	}
5231
5232	/// Limit subsequent reads to these frame indices without rewinding read progress,
5233	/// returning `self` for chaining.
5234	///
5235	/// `2..=5` includes frames 2 through 5; `2..5` excludes frame 5, and `..0` is the empty
5236	/// range. The start skips ahead, clamped *up* to the group's first available frame:
5237	/// frames the group never held (see `Producer::start_at`) can't be returned, so read
5238	/// [`Self::index`] back to learn where the cursor landed. A start below the cursor is
5239	/// ignored, since those frames may already have been handed out. The end is assigned:
5240	/// reads past it end cleanly (`None`), as if the group finished there, and an omitted
5241	/// end removes the cap. Raising the cap re-offers frames that are still cached.
5242	pub fn with_range(mut self, frames: impl RangeBounds<u64>) -> Self {
5243		Idle::disarm(&mut self.idle);
5244		let (start, end) = super::subscription::key_bounds(frames);
5245		let from = self.position();
5246		self.cursor.start_at(start);
5247		self.skipped(from);
5248		self.cursor.end = end.map(|end| usize::try_from(end).unwrap_or(usize::MAX));
5249		self
5250	}
5251
5252	/// Cap reads before frame `end`, or remove the cap with `None`, without moving the
5253	/// start, which [`Self::with_range`] would clamp up to the first available frame.
5254	pub(crate) fn with_end(mut self, end: impl Into<Option<u64>>) -> Self {
5255		self.end_at(end);
5256		self
5257	}
5258
5259	/// [`Self::with_end`] in place.
5260	pub(crate) fn end_at(&mut self, end: impl Into<Option<u64>>) {
5261		Idle::disarm(&mut self.idle);
5262		self.cursor.end = end.into().map(|end| usize::try_from(end).unwrap_or(usize::MAX));
5263	}
5264
5265	/// Advance the read cursor to `index`, skipping every frame below it.
5266	///
5267	/// Unlike [`Self::with_range`], this does not clamp past a requested frame the group
5268	/// never held. A `Producer::start_at` floor above `index` makes a read fetch the
5269	/// frames below it, from a front's route or the track's [`crate::track::Requests`]
5270	/// handlers, and surfaces as [`Error::Lagged`] when neither can serve them.
5271	pub fn skip_to(&mut self, index: u64) {
5272		Idle::disarm(&mut self.idle);
5273		let from = self.position();
5274		self.cursor.skip_to(index);
5275		self.skipped(from);
5276	}
5277
5278	/// The number of frames written so far (completed plus any in-flight), independent of
5279	/// how many this consumer has read. The final total once the group is finished.
5280	pub fn frame_count(&self) -> usize {
5281		let state = self.cursor.state.read();
5282		state.outcome.frames().unwrap_or(state.next_index)
5283	}
5284
5285	/// Where the group ends in its track's timescale, once its producer finished it whole
5286	/// with [`Producer::finish_at`], kept after its cache is released: `None` while it is open,
5287	/// when it was aborted unfinished, or when it finished without an end.
5288	pub fn end(&self) -> Option<u64> {
5289		match self.cursor.state.read().outcome {
5290			Outcome::Finished(_, end) | Outcome::Released(_, end, _) => end,
5291			_ => None,
5292		}
5293	}
5294
5295	/// The next frame, as a consumer for chunked reading.
5296	///
5297	/// Returns None if the group is finished and the index is out of range, or the cursor
5298	/// passed the [`Self::with_range`] cap.
5299	#[cfg_attr(feature = "async", kio::wrapper)]
5300	pub fn poll_next_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Consumer>>> {
5301		let res = match !self.resumes() {
5302			true => match self.poll_next_frame_once(waiter) {
5303				// A frame still arriving loses its rest if the pool evicts the copy, which a
5304				// flight of the group from that frame brings instead.
5305				Poll::Ready(Ok(Some(frame))) if self.cursor.partial => {
5306					let index = self.cursor.index as u64 - 1;
5307					Poll::Ready(Ok(Some(frame.with_flight(self.start, index))))
5308				}
5309				res => self.ended_on(res),
5310			},
5311			false => match (self.poll_resumed(waiter, Self::poll_next_frame_once), self.recover()) {
5312				// A frame read from a copy that may fail too carries on the same way.
5313				(Poll::Ready(Ok(Some(frame))), Some(recover)) => Poll::Ready(Ok(Some(
5314					frame.with_recover(recover.clone(), self.cursor.index as u64 - 1),
5315				))),
5316				(res, _) => self.ended_on(res),
5317			},
5318		};
5319		// The cursor moved past a frame that may still be arriving, which a whole-frame read
5320		// parked on it waits out: that read never hears of the move.
5321		if let Poll::Ready(Ok(Some(_))) = &res {
5322			Idle::disarm(&mut self.idle);
5323		}
5324		res
5325	}
5326
5327	/// Give up the payload of the frame last handed out, as a header-only read does, so a copy
5328	/// failing partway through that frame tears nothing and the read goes on from another route.
5329	pub(crate) fn forget_payload(&mut self) {
5330		self.cursor.partial = false;
5331	}
5332
5333	/// Pass a read through, releasing the track demand once it reached the group's end,
5334	/// or asking for a new group once it reached a frame the copy shed.
5335	fn ended_on<T>(&self, res: Poll<Result<Option<T>>>) -> Poll<Result<Option<T>>> {
5336		match res {
5337			Poll::Ready(Ok(None)) => self.release_if_finished(),
5338			Poll::Ready(Err(Error::Evicted)) => {
5339				if let Some(track) = self.cursor.cache.track() {
5340					track::TrackState::shed_read(track.read(), self.info.start);
5341				}
5342			}
5343			_ => {}
5344		}
5345		res
5346	}
5347
5348	/// Release the track demand this group holds once it finished, since the track owes it
5349	/// nothing more. A range cap ends only this reader, and can be raised, so it keeps it.
5350	fn release_if_finished(&self) {
5351		if let Some(expiry) = &self.expiry
5352			&& self.cursor.state.read().outcome.frames().is_some()
5353		{
5354			expiry.ended();
5355		}
5356	}
5357
5358	fn poll_next_frame_once(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Consumer>>> {
5359		self.poll_flown(waiter, Self::poll_next_frame_copy)
5360	}
5361
5362	fn poll_next_frame_copy(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Consumer>>> {
5363		if self.expired {
5364			return Poll::Ready(Err(Error::Old));
5365		}
5366		let stats = self.stats.clone();
5367		let expiry = self
5368			.expiry
5369			.as_ref()
5370			.map(|policy| frame::Expiry::new(policy.clone(), stats.clone(), self.delivery.clone()));
5371		let res = self.cursor.poll_next_frame(waiter, &stats, expiry);
5372		self.poll_expired_if_blocked(waiter, res)
5373	}
5374
5375	/// Read the next frame (timestamp and payload) all at once, without blocking.
5376	pub fn poll_read_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Frame>>> {
5377		self.poll_read_as(waiter, Prefetch::pop)
5378	}
5379
5380	/// Read the next frame as stored, so a frame in segments stays in them.
5381	#[cfg(feature = "async")]
5382	fn poll_read_cached(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Cached>>> {
5383		self.poll_read_as(waiter, Prefetch::pop_cached)
5384	}
5385
5386	/// Read the next frame through the prefetch with `take`, which picks its form.
5387	///
5388	/// A read that parked is answered again with `Pending` until something it parked on
5389	/// fires: the group, its expiry, the reader's subscription, or the route. A read parks
5390	/// only with its prefetch drained, so `take` does not change that answer.
5391	///
5392	/// The gate is set up once a read parks twice in a row, as it does for a task that polls
5393	/// it whenever another reader wakes, and arms on the read after: a group read whose next
5394	/// poll is its own wake, as one task per group has it, never pays for one.
5395	fn poll_read_as<T>(
5396		&mut self,
5397		waiter: &kio::Waiter,
5398		take: impl Fn(&mut Prefetch) -> Option<T> + Copy,
5399	) -> Poll<Result<Option<T>>> {
5400		// Most reads of a backlog: kept off the read path below, whose bookkeeping costs
5401		// every frame drained more than the pop.
5402		if let Some(frame) = self.take_prefetched(take) {
5403			return Poll::Ready(Ok(Some(frame)));
5404		}
5405		if Idle::parked(&self.idle, (), waiter) {
5406			return Poll::Pending;
5407		}
5408		let mut gate = self.idle.is_some().then(|| Idle::start(&mut self.idle, waiter));
5409		let read = gate.as_mut().map_or(waiter, |gate| gate.waiter());
5410		// Read once, carried across route changes when the group came from a front. One call
5411		// site keeps the read inline: a second costs every frame drained a call frame.
5412		let res = match !self.resumes() {
5413			true => self.poll_read_frame_once(read, take),
5414			false => self.poll_resumed(read, |this, waiter| this.poll_read_frame_once(waiter, take)),
5415		};
5416		let parked = res.is_pending();
5417		match gate {
5418			Some(gate) => gate.finish(&mut self.idle, (), parked),
5419			None => {
5420				if parked && self.parked {
5421					// Parked twice in a row: the next read parks through a gate. Unarmed, since
5422					// this read registered on the task's own waiter, not the gate's.
5423					Idle::start(&mut self.idle, waiter).finish(&mut self.idle, (), false);
5424				}
5425				self.parked = parked;
5426			}
5427		}
5428		self.ended_on(res)
5429	}
5430
5431	/// Read the next frame with its relay metadata, for wire egress.
5432	#[cfg(feature = "async")]
5433	pub(crate) fn poll_read_object(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Object>>> {
5434		// Every frame is served through the cursor's prefetch, which holds its fields.
5435		let frame = ready!(self.poll_read_cached(waiter))?;
5436		Poll::Ready(Ok(frame.map(|frame| frame::Object {
5437			frame,
5438			fields: self.cursor.prefetch.take_fields(),
5439			inflated: self.cursor.prefetch.take_inflated(),
5440		})))
5441	}
5442
5443	fn poll_read_frame_once<T>(
5444		&mut self,
5445		waiter: &kio::Waiter,
5446		take: impl Fn(&mut Prefetch) -> Option<T> + Copy,
5447	) -> Poll<Result<Option<T>>> {
5448		self.poll_flown(waiter, |this, waiter| this.poll_read_frame_copy(waiter, take))
5449	}
5450
5451	/// Read through `read` from the copy the cursor reads, carried onto a flight once that
5452	/// copy shed the frame read next, and from a flight onto a copy further along once one
5453	/// admits the reader (see [`track::board`]).
5454	fn poll_flown<T>(
5455		&mut self,
5456		waiter: &kio::Waiter,
5457		mut read: impl FnMut(&mut Self, &kio::Waiter) -> Poll<Result<Option<T>>>,
5458	) -> Poll<Result<Option<T>>> {
5459		let mut boarded = false;
5460		loop {
5461			ready!(self.poll_boarding(waiter))?;
5462			if let Some(ride) = self.ride_mut()
5463				&& ride.aboard
5464				&& self.cursor.prefetch.is_drained()
5465				&& let Some(track) = self.cursor.cache.track()
5466				&& let Some((copy, flight)) = track::hand_over(&track, self)
5467			{
5468				let skip = self.ride_mut().map_or(0, |ride| ride.skip);
5469				self.adopt_copy(copy);
5470				self.set_ride((flight || skip > 0).then(|| Ride::aboard(flight, skip)));
5471			}
5472			let res = read(self, waiter);
5473			if let Poll::Ready(Ok(Some(_))) = &res
5474				&& let Some(ride) = self.ride_mut()
5475				&& ride.skip > 0
5476			{
5477				ride.skip -= 1;
5478				continue;
5479			}
5480			if !matches!(res, Poll::Ready(Err(_))) {
5481				return res;
5482			}
5483			if ready!(self.poll_successor(waiter))? {
5484				continue;
5485			}
5486			if !self.board(&mut boarded) {
5487				return res;
5488			}
5489		}
5490	}
5491
5492	/// Board a flight, or a copy riding one, for the frames the copy read next shed or lost.
5493	/// Returns whether it did. `boarded` says it already did in this read: the copy just
5494	/// boarded shed the frame before the reader took it, so pool debt outruns the reader, and
5495	/// boarding again now would fare no better.
5496	fn board(&mut self, boarded: &mut bool) -> bool {
5497		if !self.shed_next() || std::mem::replace(boarded, true) {
5498			return false;
5499		}
5500		let Some(track) = self.cursor.cache.track() else {
5501			return false;
5502		};
5503		// A rider still skipping to its frame keeps what it has left to skip.
5504		let skip = self.ride_mut().map_or(0, |ride| ride.skip);
5505		match track::board(&track, self) {
5506			None => return false,
5507			Some(track::Board::Ride(copy, flight)) => {
5508				self.adopt_copy(copy);
5509				self.set_ride(Some(Ride::aboard(flight, skip)));
5510			}
5511			Some(track::Board::Wait(boarding)) => self.set_ride(Some(Ride {
5512				boarding: Some(boarding),
5513				aboard: true,
5514				skip,
5515			})),
5516		}
5517		true
5518	}
5519
5520	/// Wait for the flight this reader is boarding, if any, and move onto it. Fails with
5521	/// [`Error::Evicted`] when nothing serves the frame, so the shed read stands, or
5522	/// [`Error::Old`] when its handler judged the group stale or the reader's budget gave up
5523	/// on the wait. A reader capped where it stands needs nothing from the flight, so it
5524	/// waits only once its cap is raised.
5525	fn poll_boarding(&mut self, waiter: &kio::Waiter) -> Poll<Result<()>> {
5526		if self.cursor.capped() {
5527			return Poll::Ready(Ok(()));
5528		}
5529		let Some(ride) = self.ride_mut() else {
5530			return Poll::Ready(Ok(()));
5531		};
5532		// Frames still to drop when the flight boarded, before the ones it starts below the
5533		// reader.
5534		let pending = ride.skip;
5535		let Some(boarding) = &mut ride.boarding else {
5536			return Poll::Ready(Ok(()));
5537		};
5538		let copy = match boarding.poll(waiter) {
5539			Poll::Ready(Ok(copy)) => copy,
5540			Poll::Ready(Err(err)) => {
5541				self.set_ride(None);
5542				return Poll::Ready(Err(track::flight_failed(err)));
5543			}
5544			// The copy read brings the reader nothing more, even one its pool evicted, which
5545			// leaves no frame to expire: the budget judges the wait itself.
5546			Poll::Pending => {
5547				return match self.poll_expiry(waiter, true) {
5548					true => Poll::Ready(Err(Error::Old)),
5549					false => Poll::Pending,
5550				};
5551			}
5552		};
5553		let start = usize::try_from(boarding.frame()).unwrap_or(usize::MAX);
5554		let start = start.min(self.cursor.index);
5555		let skip = pending + (self.cursor.index - start);
5556		self.adopt_copy(copy);
5557		self.cursor.index = start;
5558		self.set_ride(Some(Ride::aboard(true, skip)));
5559		Poll::Ready(Ok(()))
5560	}
5561
5562	/// Continue on another copy of this group in the same track once the copy read failed or
5563	/// ended at a cut short of the reader's cap, such as a re-offer held while that copy was
5564	/// still arriving (see [`track::successor`]).
5565	/// Returns whether the reader moved to one, or [`Error::Old`] once its budget gives up
5566	/// on the wait.
5567	fn poll_successor(&mut self, waiter: &kio::Waiter) -> Poll<Result<bool>> {
5568		let Some(copy) = ready!(self.poll_successor_at(waiter, self.cursor.index))? else {
5569			return Poll::Ready(Ok(false));
5570		};
5571		self.adopt_copy(copy);
5572		Poll::Ready(Ok(true))
5573	}
5574
5575	/// The copy that continues this reader from frame `index`, at or past its cursor, once
5576	/// the copy read failed or ended at a cut short of its cap; see [`Self::poll_successor`].
5577	fn poll_successor_at(&mut self, waiter: &kio::Waiter, index: usize) -> Poll<Result<Option<Consumer>>> {
5578		{
5579			let state = self.cursor.state.read();
5580			// Only a delivery failure: content that failed to inflate is the group's under its
5581			// name, and a frame this reader took from the copy partly is lost with it. Ordinals
5582			// stand for frames only on a dense copy. A copy cut short at the back that the
5583			// reader's raised cap passed lacks the rest, like a failed one.
5584			if self.expired
5585				|| self.carry.as_ref().is_some_and(|carry| carry.ride.is_some())
5586				|| (state.outcome.error().is_none() && !state.past_cut(index))
5587				|| (!self.cursor.raw && state.malformed())
5588				|| (self.cursor.partial && state.committed() < self.cursor.index)
5589				|| state.sparse()
5590			{
5591				return Poll::Ready(Ok(None));
5592			}
5593		}
5594		let Some(track) = self.cursor.cache.track() else {
5595			return Poll::Ready(Ok(None));
5596		};
5597		match track::successor(&track, self, index, waiter) {
5598			Poll::Ready(copy) => Poll::Ready(Ok(copy)),
5599			// A stall the budget bounds, though the copy read can receive nothing more.
5600			Poll::Pending => match self.poll_expiry(waiter, true) {
5601				true => Poll::Ready(Err(Error::Old)),
5602				false => Poll::Pending,
5603			},
5604		}
5605	}
5606
5607	/// Whether this copy can continue `reader` from frame `index`.
5608	pub(super) fn continues(&self, reader: &Consumer, index: usize) -> bool {
5609		let raw = reader.cursor.raw;
5610		let state = self.cursor.state.read();
5611		// A plain read inflates from frame 0, and a copy that shed the frame can't serve it.
5612		!state.sparse()
5613			&& (raw || state.flate.is_none() || state.offset == 0)
5614			&& state.check_read(index, raw).is_ok()
5615			// Inflating a frame past the inflated ones needs every slice since, so none shed.
5616			&& state.plain(raw).is_none_or(|plain| {
5617				let len = plain.len.load(Ordering::Acquire);
5618				len > index || len >= state.held()
5619			})
5620	}
5621
5622	fn recover(&self) -> Option<&super::resume::Recover> {
5623		self.carry.as_ref()?.recover.as_ref()
5624	}
5625
5626	/// Drop the recovery once the group ended: no route is needed for it any more.
5627	fn let_go(&mut self) {
5628		if let Some(carry) = &mut self.carry {
5629			carry.recover = None;
5630		}
5631	}
5632
5633	/// Whether this reader read to the end of a copy that closed the group short of a known
5634	/// end, as a FIN without GROUP_END does, below the reader's own cap: the group may hold
5635	/// more than this copy got.
5636	fn closed_short(&self) -> bool {
5637		!self.cursor.capped()
5638			&& matches!(
5639				self.cursor.state.read().outcome,
5640				Outcome::Finished(frames, None) | Outcome::Released(frames, None, _) if self.cursor.index >= frames
5641			)
5642	}
5643
5644	/// End every later read with `err`, which a route change no longer undoes, and return it.
5645	/// The recovery goes, so no replaced copy stays subscribed for a read that ended.
5646	fn fail(&mut self, err: Error) -> Error {
5647		let carry = self.carry.get_or_insert_default();
5648		carry.recover = None;
5649		carry.failed = Some(err.clone());
5650		err
5651	}
5652
5653	/// Whether reads go through [`Self::poll_resumed`]: the group carries on across route
5654	/// changes, or a failure that ended it stands.
5655	fn resumes(&self) -> bool {
5656		self.carry
5657			.as_ref()
5658			.is_some_and(|carry| carry.recover.is_some() || carry.failed.is_some())
5659	}
5660
5661	/// Whether the copy read closed the group short below a frame this reader read, from the
5662	/// copy before it: not only below frames it skipped.
5663	fn closed_past(&self) -> bool {
5664		let index = self.position();
5665		let unread = self.carry.as_ref().map_or(0..0, |carry| carry.unread.clone());
5666		self.cursor
5667			.state
5668			.read()
5669			.outcome
5670			.frames()
5671			.is_some_and(|frames| index > frames && !(unread.start <= frames && unread.end >= index))
5672	}
5673
5674	fn recover_mut(&mut self) -> Option<&mut super::resume::Recover> {
5675		self.carry.as_mut()?.recover.as_mut()
5676	}
5677
5678	fn ride_mut(&mut self) -> Option<&mut Ride> {
5679		self.carry.as_mut()?.ride.as_mut()
5680	}
5681
5682	fn set_ride(&mut self, ride: Option<Ride>) {
5683		match (&mut self.carry, ride) {
5684			(Some(carry), ride) => carry.ride = ride,
5685			(None, Some(ride)) => {
5686				self.carry = Some(Box::new(Carry {
5687					recover: None,
5688					ride: Some(ride),
5689					finishing: None,
5690					failed: None,
5691					unread: 0..0,
5692				}))
5693			}
5694			(None, None) => {}
5695		}
5696	}
5697
5698	/// Whether the copy read lacks the frame read next, having shed it or started past it,
5699	/// rather than failing. Ordinals stand for frames only on a dense group, so only one
5700	/// boards a flight. A plain read of a compressed copy also loses a frame its inflated copy
5701	/// shed, which the decoder, already past it, cannot inflate again. A group handed out
5702	/// from a front recovers a frame its copy started past from a route instead. A copy the
5703	/// pool evicted, such as with a frame still arriving, lacks every frame from the reader's
5704	/// on, as if shed: the reader is owed the rest of the group, which a flight brings.
5705	fn shed_next(&self) -> bool {
5706		let state = self.cursor.state.read();
5707		let index = self.cursor.index;
5708		if state.sparse() {
5709			return false;
5710		}
5711		if state.outcome.evicted() {
5712			return true;
5713		}
5714		if state.outcome.error().is_some() {
5715			return false;
5716		}
5717		if index < state.offset {
5718			return self.recover().is_none();
5719		}
5720		index < state.held() || state.plain(self.cursor.raw).is_some_and(|plain| plain.shed_past(index))
5721	}
5722
5723	/// Whether reading from frame `index` can fetch the frames below where this copy starts:
5724	/// a front recovers them from a route, and a track's [`track::Requests`] handlers serve
5725	/// them as a flight. A failed or refused fetch fails the read.
5726	pub(crate) fn fetches_from(&self, index: u64) -> bool {
5727		let state = self.cursor.state.read();
5728		if index >= state.offset as u64 {
5729			return true;
5730		}
5731		if state.outcome.error().is_some() || state.sparse() {
5732			return false;
5733		}
5734		drop(state);
5735		self.recover().is_some() || self.cursor.cache.track().is_some_and(|track| track::flies(&track))
5736	}
5737
5738	/// Start reads at frame `index`, even below the first frame this copy holds, which a read
5739	/// then fetches (see [`Self::fetches_from`]). A start below the cursor is ignored.
5740	#[cfg(feature = "async")]
5741	pub(crate) fn fetching_from(mut self, index: u64) -> Self {
5742		self.skip_to(index);
5743		self
5744	}
5745
5746	/// Read the same frames from `copy` from here on, keeping this reader's place and cap.
5747	fn adopt_copy(&mut self, copy: Consumer) {
5748		let (index, end, raw) = (self.cursor.index, self.cursor.end, self.cursor.raw);
5749		// Another read may move the cursor while a frame read is parked on the old copy.
5750		Idle::disarm(&mut self.idle);
5751		self.cursor = copy.cursor;
5752		self.cursor.index = index;
5753		self.cursor.end = end;
5754		self.cursor.raw = raw;
5755		drop_finishing(&mut self.carry);
5756	}
5757
5758	/// The frames this reader has yet to read from `index` on: up to its cap.
5759	pub(super) fn unread(&self, index: usize) -> Bounds {
5760		Bounds {
5761			start: index as u64,
5762			end: self.cursor.end.map(|end| end as u64),
5763		}
5764	}
5765
5766	/// One past the last frame the copy read committed.
5767	pub(super) fn committed(&self) -> usize {
5768		self.cursor.state.read().committed()
5769	}
5770
5771	fn poll_read_frame_copy<T>(
5772		&mut self,
5773		waiter: &kio::Waiter,
5774		take: impl Fn(&mut Prefetch) -> Option<T> + Copy,
5775	) -> Poll<Result<Option<T>>> {
5776		if self.expired {
5777			return Poll::Ready(Err(Error::Old));
5778		}
5779		let res = self.cursor.poll_read_frame(waiter, &self.stats, take);
5780		self.poll_expired_if_blocked(waiter, res)
5781	}
5782
5783	/// Read the next frame (timestamp and payload) all at once.
5784	#[cfg(feature = "async")]
5785	pub async fn read_frame(&mut self) -> Result<Option<frame::Frame>> {
5786		// Without building a future or allocating a waker.
5787		if let Some(frame) = self.take_prefetched(Prefetch::pop) {
5788			return Ok(Some(frame));
5789		}
5790		kio::wait(|waiter| self.poll_read_frame(waiter)).await
5791	}
5792
5793	/// The next frame from the prefetched batch, through `take`. A read parks only with its
5794	/// batch drained, so neither the drift budget, which judges only a read that would park,
5795	/// nor the idle gate, nor a route applies: one adopted onto a new copy starts empty.
5796	fn take_prefetched<T>(&mut self, take: impl Fn(&mut Prefetch) -> Option<T>) -> Option<T> {
5797		if self.expired || self.cursor.capped() {
5798			return None;
5799		}
5800		let frame = take(&mut self.cursor.prefetch)?;
5801		self.cursor.refresh_if_stale();
5802		self.cursor.index += 1;
5803		Some(frame)
5804	}
5805
5806	/// Fill `out` with every frame that is ready, up to its capacity, without blocking.
5807	///
5808	/// This is a short read: it returns as soon as anything is ready rather than
5809	/// waiting for `out` to fill. A zero count means the group ended when the buffer
5810	/// has non-zero capacity.
5811	#[cfg(feature = "async")]
5812	#[cfg(any(test, feature = "fuzz"))]
5813	pub(crate) fn poll_read_frames<const N: usize>(
5814		&mut self,
5815		waiter: &kio::Waiter,
5816		out: &mut frame::Buffer<N>,
5817	) -> Poll<Result<usize>> {
5818		out.clear();
5819		if out.capacity() == 0 {
5820			return Poll::Ready(Ok(0));
5821		}
5822
5823		while !out.is_full() {
5824			match self.poll_read_frame(waiter) {
5825				Poll::Ready(Ok(Some(frame))) => out.push(frame).expect("buffer capacity checked"),
5826				Poll::Ready(Ok(None)) => break,
5827				Poll::Ready(Err(err)) => {
5828					if out.is_empty() {
5829						return Poll::Ready(Err(err));
5830					}
5831					break;
5832				}
5833				Poll::Pending if !out.is_empty() => break,
5834				Poll::Pending => return Poll::Pending,
5835			}
5836		}
5837
5838		Poll::Ready(Ok(out.len()))
5839	}
5840
5841	/// Fill `out` with every frame that is ready, blocking until a frame arrives or
5842	/// the group ends. Returns the current batch, empty only at the end of the group.
5843	#[cfg(feature = "async")]
5844	#[cfg(any(test, feature = "fuzz"))]
5845	pub(crate) async fn read_frames<'a, const N: usize>(
5846		&mut self,
5847		out: &'a mut frame::Buffer<N>,
5848	) -> Result<&'a mut [frame::Frame]> {
5849		kio::wait(|waiter| self.poll_read_frames(waiter, out)).await?;
5850		Ok(out.filled_mut())
5851	}
5852
5853	/// This cursor's next frame index once the group terminates, or this cursor reaches
5854	/// the end of its range.
5855	///
5856	/// This answers for the cursor, not the group: a reader that drained every frame gets the
5857	/// clean end even if the group was aborted afterwards to release its cache, while one that
5858	/// stopped short gets that abort. A prior [`Self::skip_to`] contributes to the index even
5859	/// though those frames were not read. Use [`Self::frame_count`] for the producer's total.
5860	///
5861	/// An error means the frames this cursor has yet to read are gone (evicted, cut, or
5862	/// failed upstream) and no route will continue them.
5863	#[cfg_attr(feature = "async", kio::wrapper)]
5864	pub fn poll_finished(&mut self, waiter: &kio::Waiter) -> Poll<Result<u64>> {
5865		let res = match !self.resumes() {
5866			true => self.poll_finished_once(waiter),
5867			// A reader at the end of a copy that closed the group short reads on from the route
5868			// that replaced it, as a frame read does, so its end is that copy's.
5869			false => self
5870				.poll_resumed(waiter, |this, waiter| {
5871					this.poll_finished_once(waiter)
5872						.map(|res| res.map(|index| (!this.closed_short()).then_some(index)))
5873				})
5874				.map(|res| res.map(|index| index.unwrap_or(self.position() as u64))),
5875		};
5876		if let Poll::Ready(Ok(_)) = res {
5877			self.release_if_finished();
5878		}
5879		res
5880	}
5881
5882	/// Like a frame read, a failed copy's end waits out a re-offer held for the group and
5883	/// reports the end of the copy that took it over (see [`Self::poll_successor`]), or of
5884	/// the flight that brings the frames the copy shed or lost.
5885	fn poll_finished_once(&mut self, waiter: &kio::Waiter) -> Poll<Result<u64>> {
5886		let mut boarded = false;
5887		loop {
5888			ready!(self.poll_boarding(waiter))?;
5889			let res = self.poll_finished_copy(waiter);
5890			if !matches!(res, Poll::Ready(Err(_))) {
5891				return res;
5892			}
5893			// Frames this reader already prefetched, and those a copy cut short of its cap
5894			// still holds up to the cut, are read before a successor is needed, so the end is
5895			// judged past them, without leaving them behind.
5896			let mut drained = self.cursor.index + self.cursor.prefetch.buffered().0 as usize;
5897			{
5898				let state = self.cursor.state.read();
5899				if let Some(cut) = state.cut()
5900					&& self.cursor.end.is_none_or(|end| end > cut)
5901					&& state.check_read(drained, self.cursor.raw).is_ok()
5902				{
5903					drained = drained.max(cut);
5904				}
5905			}
5906			if drained > self.cursor.index {
5907				return self.poll_finished_past(waiter, drained, res);
5908			}
5909			if !ready!(self.poll_successor(waiter))? && !self.board(&mut boarded) {
5910				return res;
5911			}
5912		}
5913	}
5914
5915	/// This reader's end once it drained its prefetch up to `drained`: its cap's, if
5916	/// that comes first, else the end of the copy that continues it from there, judged on a
5917	/// copy of the reader so its cursor stays on the frames still to drain. `failed` is the
5918	/// copy's own answer, which stands without one.
5919	fn poll_finished_past(
5920		&mut self,
5921		waiter: &kio::Waiter,
5922		drained: usize,
5923		failed: Poll<Result<u64>>,
5924	) -> Poll<Result<u64>> {
5925		let index = self.position() as u64;
5926		if self.cursor.end.is_some_and(|end| drained >= end) {
5927			return Poll::Ready(Ok(index));
5928		}
5929		let kept = self.carry.as_mut().and_then(|carry| carry.finishing.take());
5930		let mut next = match kept {
5931			// It hands over to a later copy itself, should it fail too. A cap or mode changed
5932			// since asks again: the copy kept may not cover the new range.
5933			Some((at, next))
5934				if at == drained && next.cursor.end == self.cursor.end && next.cursor.raw == self.cursor.raw =>
5935			{
5936				next
5937			}
5938			_ => {
5939				let copy = ready!(self.poll_successor_at(waiter, drained))?;
5940				let mut next = self.clone();
5941				next.cursor.index = drained;
5942				match copy {
5943					Some(copy) => {
5944						next.adopt_copy(copy);
5945						next.cursor.index = drained;
5946					}
5947					// Nothing replaced the copy, so the frames past the prefetch come on a
5948					// flight, as they would for the reader once it drains that far.
5949					None if next.board(&mut false) => {}
5950					None => return failed,
5951				}
5952				next
5953			}
5954		};
5955		match next.poll_finished_once(waiter) {
5956			Poll::Ready(res) => {
5957				// The failed copy holds no end, so the copy that answered releases the demand.
5958				if res.is_ok() {
5959					next.release_if_finished();
5960				}
5961				Poll::Ready(res.map(|_| index))
5962			}
5963			Poll::Pending => {
5964				// Dropped, it would leave the copy unwanted, and a fetch could abandon it.
5965				self.carry.get_or_insert_default().finishing = Some((drained, next));
5966				match self.poll_expiry(waiter, true) {
5967					true => Poll::Ready(Err(Error::Old)),
5968					false => Poll::Pending,
5969				}
5970			}
5971		}
5972	}
5973
5974	fn poll_finished_copy(&mut self, waiter: &kio::Waiter) -> Poll<Result<u64>> {
5975		if self.expired {
5976			return Poll::Ready(Err(Error::Old));
5977		}
5978		let index = self.cursor.index;
5979		// Where the reader stands, past the frames a compressed flight it boarded still
5980		// inflates from frame 0 and drops.
5981		let position = self.position() as u64;
5982		// Reads end cleanly at the range's end, whatever becomes of the frames past it.
5983		if self.cursor.capped() {
5984			return Poll::Ready(Ok(position));
5985		}
5986		let (raw, end) = (self.cursor.raw, self.cursor.end);
5987		// Frames already prefetched are this cursor's whatever the group sheds since, so
5988		// only the first one past them can be evicted.
5989		let mut unread = index + self.cursor.prefetch.buffered().0 as usize;
5990		// The frames below where this copy starts come from a flight, and the group ends
5991		// where this copy does.
5992		let offset = self.cursor.state.read().offset;
5993		if unread < offset && self.recover().is_none() && self.fetches_from(unread as u64) {
5994			unread = offset;
5995		}
5996		let res = self
5997			.cursor
5998			.poll(waiter, |state| state.poll_end(index, unread, raw, end))
5999			.map(|res| res.map(|()| position));
6000		self.poll_expired_if_blocked(waiter, res)
6001	}
6002}
6003
6004impl Cursor {
6005	/// Whether this cursor still has unread content or may receive another frame.
6006	fn expiry_pending(&self) -> bool {
6007		if self.capped() {
6008			return false;
6009		}
6010
6011		let state = self.state.read();
6012		state.outcome.error().is_none() && state.outcome.frames().is_none_or(|fin| self.index < fin)
6013	}
6014
6015	/// Content this cursor has neither returned nor already counted in a prefetch batch.
6016	fn unread_content(&self) -> stats::Content {
6017		let prefetched = self.prefetch.buffered().0 as usize;
6018		let start = self.index.saturating_add(prefetched);
6019		let end = self.end.unwrap_or(usize::MAX);
6020		self.state.read().content_range(start, end)
6021	}
6022
6023	/// Record prefetched reads, updating the eviction rank once per sampled tick.
6024	fn refresh_if_stale(&mut self) {
6025		self.alive.access.touch();
6026		let tick = self.cache.pool().now();
6027		if tick != self.refreshed {
6028			self.state.read().charge.refresh();
6029			self.refreshed = tick;
6030		}
6031	}
6032
6033	// A helper to automatically apply Dropped if the state is closed without an error.
6034	fn poll<F, R>(&self, waiter: &kio::Waiter, f: F) -> Poll<Result<R>>
6035	where
6036		F: Fn(&kio::Ref<'_, GroupState>) -> Poll<Result<R>>,
6037	{
6038		Poll::Ready(match ready!(self.state.poll(waiter, f)) {
6039			Ok(res) => res,
6040			// We try to clone abort just in case the function forgot to check for terminal state.
6041			Err(state) => Err(state.outcome.error().cloned().unwrap_or(Error::Dropped)),
6042		})
6043	}
6044
6045	/// Whether the cursor has passed the `end_at` cap.
6046	fn capped(&self) -> bool {
6047		self.end.is_some_and(|end| self.index >= end)
6048	}
6049
6050	fn start_at(&mut self, index: u64) {
6051		let index = usize::try_from(index).unwrap_or(usize::MAX);
6052		let index = index.max(self.state.read().offset);
6053		if index <= self.index {
6054			return;
6055		}
6056		self.index = index;
6057		// The batch was drained from below the new cursor, so it can't be reused.
6058		self.prefetch = Prefetch::default();
6059		self.partial = false;
6060	}
6061
6062	fn skip_to(&mut self, index: u64) {
6063		let index = usize::try_from(index).unwrap_or(usize::MAX);
6064		if index <= self.index {
6065			return;
6066		}
6067		self.index = index;
6068		self.prefetch = Prefetch::default();
6069		// The frame handed out partly is given up below the skip, so a failure tears nothing.
6070		self.partial = false;
6071	}
6072
6073	fn poll_next_frame(
6074		&mut self,
6075		waiter: &kio::Waiter,
6076		stats: &stats::Meter,
6077		expiry: Option<frame::Expiry>,
6078	) -> Poll<Result<Option<frame::Consumer>>> {
6079		if self.capped() {
6080			return Poll::Ready(Ok(None));
6081		}
6082		let end = self.end.unwrap_or(usize::MAX);
6083
6084		// Hand out any frames a prior read_frame prefetched before touching the tail.
6085		// Their bytes were already counted at the batch fill, so the frame::Consumer
6086		// carries no meter.
6087		if let Some(frame) = self.prefetch.pop_cached() {
6088			self.refresh_if_stale();
6089			self.index += 1;
6090			self.partial = false;
6091			let tail = self.index.saturating_add(self.prefetch.buffered().0 as usize)..end;
6092			let info = frame::Info {
6093				size: frame.payload.len() as u64,
6094				timestamp: frame.timestamp,
6095			};
6096			let source = frame::Source::Complete(frame.payload);
6097			let header = frame::Header {
6098				info,
6099				fields: self.prefetch.take_fields(),
6100				inflated: self.prefetch.take_inflated(),
6101			};
6102			let frame = frame::Consumer::new(self.state.clone(), header, source);
6103			return Poll::Ready(Ok(Some(match expiry {
6104				Some(expiry) => frame.with_expiry(expiry.for_frame(tail, false)),
6105				None => frame,
6106			})));
6107		}
6108
6109		let (index, raw) = (self.index, self.raw);
6110		// A committed frame comes from the log without the lock, unless a plain read of a
6111		// compressed group has to inflate it under the lock.
6112		let committed = match !self.compressed || raw {
6113			true => self.log.read().get(index as u64).ok().flatten().map(|entry| {
6114				self.alive.pace.took(entry.end);
6115				entry.read(self.compressed || self.alive.meta)
6116			}),
6117			false => None,
6118		};
6119		let (info, source) = match committed {
6120			Some(read) => {
6121				self.refresh_if_stale();
6122				read
6123			}
6124			None => match ready!(self.poll(waiter, |state| state.poll_frame_source(index, raw))?) {
6125				None => return Poll::Ready(Ok(None)),
6126				Some(Source::Ready(info, source)) => (info, source),
6127				// Inflated with the group's guard released.
6128				Some(Source::Inflate {
6129					job,
6130					local,
6131					timestamp,
6132					fields,
6133				}) => {
6134					job.run(stats);
6135					let payload = job.get(local);
6136					job.plain.trim();
6137					let payload = payload?;
6138					let info = frame::Info {
6139						size: payload.len() as u64,
6140						timestamp,
6141					};
6142					let header = frame::Header {
6143						info,
6144						fields,
6145						inflated: None,
6146					};
6147					(header, frame::Source::Complete(payload.into()))
6148				}
6149			},
6150		};
6151
6152		self.index += 1;
6153		self.partial = matches!(source, frame::Source::Partial(_));
6154		// A direct read (not prefetched): count the frame here; the frame::Consumer
6155		// counts its bytes per chunk as they're read out.
6156		stats.frames(1);
6157		let frame = frame::Consumer::new(self.state.clone(), info, source).with_meter(stats.clone());
6158		Poll::Ready(Ok(Some(match expiry {
6159			Some(expiry) => frame.with_expiry(expiry.for_frame(self.index..end, true)),
6160			None => frame,
6161		})))
6162	}
6163
6164	fn poll_read_frame<T>(
6165		&mut self,
6166		waiter: &kio::Waiter,
6167		stats: &stats::Meter,
6168		take: impl Fn(&mut Prefetch) -> Option<T> + Copy,
6169	) -> Poll<Result<Option<T>>> {
6170		if self.capped() {
6171			return Poll::Ready(Ok(None));
6172		}
6173
6174		// Fast path: serve from the prefetched batch without locking or allocating a waker.
6175		if let Some(frame) = take(&mut self.prefetch) {
6176			self.refresh_if_stale();
6177			self.index += 1;
6178			return Poll::Ready(Ok(Some(frame)));
6179		}
6180
6181		let index = self.index;
6182		// Never buffer past the cap: `end_at` can be raised later, and those frames must
6183		// come from the shared state then, not from a batch drained under the old cap.
6184		let budget = self.end.map_or(usize::MAX, |end| end.saturating_sub(index));
6185
6186		// The batch is drained: refill it from the log without the lock, unless a plain
6187		// read of a compressed group has to inflate under it.
6188		if (!self.compressed || self.raw)
6189			&& self.prefetch.fill_log(
6190				&mut self.log,
6191				&self.alive.pace,
6192				index,
6193				budget,
6194				self.compressed || self.alive.meta,
6195			) > 0
6196		{
6197			self.refresh_if_stale();
6198			let (frames, bytes) = self.prefetch.buffered();
6199			stats.frames(frames);
6200			stats.bytes(bytes);
6201			return Poll::Ready(Ok(take(&mut self.prefetch).inspect(|_| {
6202				self.index += 1;
6203			})));
6204		}
6205
6206		// Nothing committed at `index` in the log: refill under a single lock, registering
6207		// the waiter if nothing is ready. Borrow the two fields disjointly so the closure
6208		// can fill.
6209		let prefetch = &mut self.prefetch;
6210		let raw = self.raw;
6211		let res = self.state.poll(waiter, |state| {
6212			state.check_read(index, raw)?;
6213			// Frames committed since the log was read, or adopted below it. `fill` always
6214			// resets the batch, so an empty one leaves `len == 0` and the terminal checks
6215			// below resolve abort/fin/pending.
6216			let job = prefetch.fill(state, index, budget, raw)?;
6217			if prefetch.len() > 0 {
6218				// One stamp covers the whole batch: frames popped from the prefetch
6219				// don't re-stamp until the next refill, which `CAP` bounds.
6220				state.charge.refresh();
6221				return Poll::Ready(Ok(job));
6222			}
6223			// Nothing completed at `index`: an in-flight tail waits, otherwise resolve
6224			// the terminal state (whole-frame reads never stream the partial).
6225			state.poll_terminal(index).map_ok(|()| None)
6226		});
6227
6228		match ready!(res) {
6229			// Inflated with the group's guard released. Only a group from frame 0 inflates.
6230			Ok(Ok(Some(job))) => self.prefetch.inflate(&job, index, stats)?,
6231			Ok(Ok(None)) => {}
6232			Ok(Err(err)) => return Poll::Ready(Err(err)),
6233			Err(state) => return Poll::Ready(Err(state.outcome.error().cloned().unwrap_or(Error::Dropped))),
6234		}
6235
6236		// The refill already updated the eviction rank under the group lock.
6237		self.refreshed = self.cache.pool().now();
6238
6239		// A fresh batch was just filled (empty only on a clean end). Count the whole
6240		// batch once here, under no lock, so the drained pops that follow stay free.
6241		let (frames, bytes) = self.prefetch.buffered();
6242		stats.frames(frames);
6243		stats.bytes(bytes);
6244
6245		Poll::Ready(Ok(take(&mut self.prefetch).inspect(|_| {
6246			self.index += 1;
6247		})))
6248	}
6249}
6250
6251/// Options for a one-shot [`track::Consumer::fetch_group`] of a past group.
6252#[derive(Clone, Debug, Default)]
6253#[non_exhaustive]
6254pub struct Fetch {
6255	/// Delivery priority for the fetched group's stream, higher first. Defaults to 0.
6256	pub priority: i8,
6257
6258	/// Index of the first frame to fetch within the group. Defaults to 0, the whole group.
6259	///
6260	/// Only a route change sets it, filling the hole after a head another route already
6261	/// delivered. An application always fetches from a group's first frame, since a group is
6262	/// the unit of decodability, and skips frames locally with [`Consumer::with_range`].
6263	///
6264	/// There is no public matching end. Private transport caps retain incomplete cache
6265	/// provenance, so a bounded reply never answers a later whole-group fetch.
6266	pub(crate) frame_start: u64,
6267}
6268
6269impl Fetch {
6270	/// Set the delivery priority, returning `self` for chaining.
6271	pub fn with_priority(mut self, priority: i8) -> Self {
6272		self.priority = priority;
6273		self
6274	}
6275}
6276
6277#[cfg(test)]
6278impl Producer {
6279	/// This group's key read as milliseconds: a first frame there starts the group where its
6280	/// key says, so test groups start in key order on a millisecond track.
6281	pub(crate) fn key_time(&self) -> Timestamp {
6282		Timestamp::from_millis(self.start).expect("a test key fits a timestamp")
6283	}
6284}
6285
6286#[cfg(test)]
6287mod test {
6288	use super::*;
6289	use crate::frame::Frame;
6290	use crate::test_tracing::count_drop_warnings;
6291	use bytes::Bytes;
6292	#[cfg(feature = "async")]
6293	use futures::FutureExt;
6294
6295	/// A group's timestamps never decrease: a frame below its predecessor is refused where it
6296	/// is created, by every write path, and a tie is fine.
6297	#[test]
6298	fn a_frame_below_its_predecessor_is_refused() {
6299		let ms = |ms| Timestamp::from_millis(ms).unwrap();
6300		for mode in 0..3 {
6301			for (start, timestamps, refused) in [
6302				(0, [0, 40, 40], None),
6303				(0, [0, 80, 40], Some(2)),
6304				(10, [15, 12, 20], Some(1)),
6305			] {
6306				let mut group = Some(Info { start }.produce());
6307				let consumer = group.as_ref().unwrap().consume();
6308				let timestamps = timestamps.map(ms);
6309				let res = match mode {
6310					1 => {
6311						let mut frames = frame::Buffer::<3>::new();
6312						for timestamp in timestamps {
6313							frames.push(Frame::new(timestamp, Bytes::new())).unwrap();
6314						}
6315						group.as_mut().unwrap().write_frames(&mut frames)
6316					}
6317					_ => timestamps.into_iter().try_for_each(|timestamp| match mode {
6318						0 => group.as_mut().unwrap().write_frame(Frame::new(timestamp, Bytes::new())),
6319						_ => {
6320							let frame = group.take().unwrap().create_frame(frame::Info { size: 0, timestamp })?;
6321							group = Some(frame.finish()?);
6322							Ok(())
6323						}
6324					}),
6325				};
6326				let label = format!("mode {mode}, start {start}");
6327				match refused {
6328					None => res.unwrap(),
6329					Some(_) => assert!(matches!(res, Err(Error::TimestampMismatch)), "{label}: {res:?}"),
6330				}
6331				// A refused batch writes none of it.
6332				let written = match (mode, refused) {
6333					(1, Some(_)) => 0,
6334					(_, refused) => refused.unwrap_or(3),
6335				};
6336				assert_eq!(consumer.frame_count(), written, "{label}");
6337			}
6338		}
6339	}
6340
6341	#[test]
6342	fn adopted_heads_keep_the_highest_pts_beside_the_tail() {
6343		let head = Head {
6344			content: None,
6345			start: 0,
6346			first_object: true,
6347			entries: [0, 80, 40]
6348				.into_iter()
6349				.map(|ms| Entry::plain(Frame::new(Timestamp::from_millis(ms).unwrap(), Bytes::new()).into(), 0))
6350				.collect(),
6351			compressed: false,
6352			meta: false,
6353		};
6354		for tail in [None, Some(20), Some(120)] {
6355			let mut group = Info { start: 0 }.produce();
6356			group.start_at(3).unwrap();
6357			if let Some(ms) = tail {
6358				group
6359					.write_frame(Frame::new(Timestamp::from_millis(ms).unwrap(), Bytes::new()))
6360					.unwrap();
6361			}
6362			group.handle.adopt_head(&head);
6363			let Timeline::Timed { start, latest } = group.handle.state.read().timeline else {
6364				panic!("adopted timestamps are timed")
6365			};
6366			assert_eq!(start, Timestamp::from_millis(0).unwrap());
6367			assert_eq!(
6368				latest,
6369				Timestamp::from_millis(tail.unwrap_or(0).max(80)).unwrap(),
6370				"tail {tail:?}"
6371			);
6372			group.finish().unwrap();
6373		}
6374	}
6375
6376	#[test]
6377	fn a_zero_group_pts_keeps_its_track_scale_and_untimed_stays_unstamped() {
6378		let mut timed = Producer::new(
6379			Info { start: 0 },
6380			track::Info::default().with_timescale(Timescale::MICRO),
6381			Default::default(),
6382		);
6383		timed
6384			.write_frame(Frame::new(Timestamp::from_micros(0).unwrap(), Bytes::new()))
6385			.unwrap();
6386		assert_eq!(timed.handle.latest(), Some(Timestamp::from_micros(0).unwrap()));
6387		timed.finish().unwrap();
6388		let mut untimed = Info { start: 0 }.produce_untimed();
6389		assert_eq!(untimed.handle.latest(), None);
6390		untimed
6391			.write_frame(Frame::new(crate::Timestamp::unscaled(untimed.start), Bytes::new()))
6392			.unwrap();
6393		assert_eq!(untimed.handle.latest(), None);
6394		untimed.finish().unwrap();
6395	}
6396
6397	/// Fields sit beside the frames only from the first fielded one, so every read path
6398	/// must line them up by index across plain frames and prefetch batches.
6399	#[test]
6400	#[cfg(feature = "async")]
6401	fn object_fields_follow_their_frames_through_every_read() {
6402		let pool = cache::Pool::unbounded();
6403		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
6404		let mut group = Producer::new(Info::from(0u64), track::Info::default(), cache);
6405		group
6406			.write_frame(Frame::new(
6407				crate::Timestamp::unscaled(group.start),
6408				Bytes::from_static(b"p"),
6409			))
6410			.unwrap();
6411		let plain = pool.used();
6412		// Ten fielded frames span two prefetch batches, then plain frames follow.
6413		for id in 1..=10u64 {
6414			let header = frame::Header {
6415				info: frame::Info {
6416					size: 1,
6417					timestamp: Timestamp::unscaled(0),
6418				},
6419				fields: Some(Arc::new(super::super::object::Fields {
6420					id: id * 10,
6421					properties: Default::default(),
6422				})),
6423				inflated: None,
6424			};
6425			let mut frame = group.create_object(header).unwrap();
6426			frame.write(Bytes::from_static(b"f")).unwrap();
6427			group = frame.finish().unwrap();
6428		}
6429		assert!(pool.used() > plain + 10, "the metadata table is charged");
6430		for _ in 0..Prefetch::CAP {
6431			group
6432				.write_frame(Frame::new(
6433					crate::Timestamp::unscaled(group.start),
6434					Bytes::from_static(b"p"),
6435				))
6436				.unwrap();
6437		}
6438		let group = group.finish().unwrap();
6439		let expected = |index: u64| (1..=10).contains(&index).then_some(index * 10);
6440
6441		let mut objects = group.consume();
6442		let waiter = kio::Waiter::noop();
6443		for index in 0..(11 + Prefetch::CAP as u64) {
6444			let Poll::Ready(Ok(Some(object))) = objects.poll_read_object(&waiter) else {
6445				panic!("frame {index} is ready");
6446			};
6447			assert_eq!(object.fields.map(|fields| fields.id), expected(index), "frame {index}");
6448		}
6449
6450		// A public read leaves the batch's fields for a later streamed read to find.
6451		let mut mixed = group.consume();
6452		mixed.read_frame().now_or_never().unwrap().unwrap().unwrap();
6453		for index in 1..Prefetch::CAP as u64 {
6454			let frame = mixed.next_frame().now_or_never().unwrap().unwrap().unwrap();
6455			assert_eq!(
6456				frame.fields.as_ref().map(|fields| fields.id),
6457				expected(index),
6458				"frame {index}"
6459			);
6460		}
6461		// Public reads never take a batch's fields, so a plain batch after them must not
6462		// hand the stale ones to a wire read.
6463		for _ in 0..Prefetch::CAP {
6464			mixed.read_frame().now_or_never().unwrap().unwrap().unwrap();
6465		}
6466		for index in (2 * Prefetch::CAP as u64)..(11 + Prefetch::CAP as u64) {
6467			let Poll::Ready(Ok(Some(object))) = mixed.poll_read_object(&waiter) else {
6468				panic!("frame {index} is ready");
6469			};
6470			assert_eq!(object.fields.map(|fields| fields.id), None, "frame {index}");
6471		}
6472
6473		drop((objects, mixed));
6474		group.abort(Error::Cancel).unwrap();
6475		assert_eq!(pool.used(), 0);
6476	}
6477
6478	/// A metadata copy keeps each header's object fields, so a relay forwards sparse object
6479	/// IDs and properties from it as it would from a payload copy.
6480	#[test]
6481	#[cfg(feature = "async")]
6482	fn metadata_headers_keep_their_object_fields() {
6483		let pool = cache::Pool::unbounded();
6484		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
6485		let mut group = Producer::new_meta(Info::from(0u64), track::Info::default(), cache);
6486		group
6487			.set_wire(Wire {
6488				sparse: false,
6489				first_object: true,
6490				first_id: 0,
6491				extensions: true,
6492				has_end: true,
6493				hole: None,
6494				last: None,
6495			})
6496			.unwrap();
6497		for (id, size) in [(0, 5), (7, 3)] {
6498			group
6499				.write_header(frame::Header {
6500					info: frame::Info {
6501						size,
6502						timestamp: Timestamp::unscaled(0),
6503					},
6504					fields: (id != 0).then(|| {
6505						Arc::new(super::super::object::Fields {
6506							id,
6507							properties: Default::default(),
6508						})
6509					}),
6510					inflated: None,
6511				})
6512				.unwrap();
6513		}
6514		let wire = group.wire().unwrap();
6515		assert!(wire.sparse, "object 7 at index 1 is sparse");
6516		assert_eq!(wire.last, Some(7));
6517
6518		let group = group.finish().unwrap();
6519		let mut objects = group.consume();
6520		let waiter = kio::Waiter::noop();
6521		for (id, size) in [(None, 5), (Some(7), 3)] {
6522			let Poll::Ready(Ok(Some(object))) = objects.poll_read_object(&waiter) else {
6523				panic!("object {id:?} is ready");
6524			};
6525			assert_eq!(object.fields.map(|fields| fields.id), id);
6526			assert_eq!(object.inflated, Some(size));
6527			assert!(object.frame.payload.is_empty());
6528		}
6529		drop(objects);
6530		group.abort(Error::Cancel).unwrap();
6531		assert_eq!(pool.used(), 0);
6532	}
6533
6534	#[test]
6535	#[cfg(feature = "async")]
6536	fn terminal_metadata_stays_charged_after_frames_are_released() {
6537		let pool = cache::Pool::unbounded();
6538		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
6539		let mut group = Producer::new(Info::from(0u64), track::Info::default(), cache);
6540		group
6541			.write_frame(Frame::new(
6542				crate::Timestamp::unscaled(group.start),
6543				Bytes::from_static(b"payload"),
6544			))
6545			.unwrap();
6546		let fields = super::super::object::Fields {
6547			id: 4,
6548			properties: Default::default(),
6549		};
6550		let charged = size_of::<Relay>() as u64 + fields.heap();
6551		group.set_end_object(fields.clone()).unwrap();
6552		assert!(matches!(group.set_end_object(fields), Err(Error::MalformedTrack)));
6553		let group = group.finish().unwrap();
6554		let consumer = group.consume();
6555		group.abort(Error::Cancel).unwrap();
6556		assert_eq!(consumer.end_object().unwrap().id, 4);
6557		assert_eq!(pool.used(), charged);
6558		drop(consumer);
6559		assert_eq!(pool.used(), 0);
6560	}
6561
6562	#[test]
6563	#[cfg(feature = "async")]
6564	fn a_leading_gap_may_reach_below_where_the_copy_starts() {
6565		for (gap, fetchable) in [(Some(6), true), (Some(4), true), (Some(3), false), (None, false)] {
6566			let mut group = Info { start: 0 }.produce();
6567			group.start_at(2).unwrap();
6568			group
6569				.set_wire(Wire {
6570					sparse: true,
6571					first_object: false,
6572					first_id: 6,
6573					extensions: true,
6574					has_end: true,
6575					hole: None,
6576					last: None,
6577				})
6578				.unwrap();
6579			group.mark_gap(6, gap).unwrap();
6580			assert_eq!(group.wire().unwrap().fetchable(), fetchable, "{gap:?}");
6581		}
6582	}
6583
6584	#[test]
6585	fn demand_watches_readers_without_keeping_the_group_alive() {
6586		let waiter = kio::Waiter::noop();
6587		let producer = Info { start: 7 }.produce();
6588		let mut demand = producer.demand();
6589		assert_eq!(demand.start(), 7);
6590		assert!(!demand.wanted());
6591		assert!(matches!(demand.poll_wanted_changed(&waiter), Poll::Ready(Ok(false))));
6592		assert!(demand.poll_wanted_changed(&waiter).is_pending());
6593
6594		let first = producer.consume();
6595		let second = first.clone();
6596		assert!(demand.wanted());
6597		assert!(matches!(demand.poll_wanted_changed(&waiter), Poll::Ready(Ok(true))));
6598		drop(first);
6599		assert!(demand.poll_wanted_changed(&waiter).is_pending());
6600
6601		// A clone reports the current value first, whatever the original last returned.
6602		let mut clone = demand.clone();
6603		assert!(matches!(clone.poll_wanted_changed(&waiter), Poll::Ready(Ok(true))));
6604
6605		drop(second);
6606		assert!(matches!(demand.poll_wanted_changed(&waiter), Poll::Ready(Ok(false))));
6607		drop(producer);
6608		assert!(!demand.wanted());
6609		assert!(matches!(
6610			demand.poll_wanted_changed(&waiter),
6611			Poll::Ready(Err(Error::Dropped))
6612		));
6613	}
6614
6615	/// The fixed overhead covers the first segment of frame slots, and each later segment
6616	/// is charged when it is allocated, whichever way the frame is written. All of it is
6617	/// released with the frames.
6618	#[test]
6619	fn frame_slots_are_charged_and_released() {
6620		for mode in 0..3 {
6621			let pool = cache::Pool::unbounded();
6622			let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
6623			let mut group = Producer::new(Info::from(0u64), track::Info::timed(), cache);
6624			let mut grew = Vec::new();
6625			// Segments double from one slot: the first is in the fixed overhead, and the
6626			// second and fourth frames each allocate the next.
6627			for _ in 0..5 {
6628				let heap = group
6629					.handle
6630					.state
6631					.read()
6632					.log
6633					.heap()
6634					.max(kio::log::Writer::<Entry>::HEAP);
6635				let before = pool.used();
6636				match mode {
6637					0 => group
6638						.write_frame(Frame::new(group.key_time(), bytes::Bytes::new()))
6639						.unwrap(),
6640					1 => {
6641						let mut buffer = frame::Buffer::<1>::new();
6642						buffer.push(Frame::new(Timestamp::ZERO, bytes::Bytes::new())).unwrap();
6643						group.write_frames(&mut buffer).unwrap();
6644					}
6645					_ => {
6646						let frame = group
6647							.create_frame(frame::Info {
6648								size: 0,
6649								timestamp: Timestamp::ZERO,
6650							})
6651							.unwrap();
6652						group = frame.finish().unwrap();
6653					}
6654				}
6655				let grown = group.handle.state.read().log.heap() - heap;
6656				assert_eq!(pool.used() - before, grown as u64);
6657				grew.push(grown > 0);
6658			}
6659			assert_eq!(grew, [false, true, false, true, false]);
6660			let consumer = group.consume();
6661			let before = consumer.cursor.state.read().log.heap();
6662			group.abort(Error::Cancel).unwrap();
6663			assert!(
6664				consumer.cursor.state.read().log.heap() < before,
6665				"the segments are freed"
6666			);
6667			assert!(consumer.cursor.state.read().is_empty());
6668		}
6669	}
6670
6671	#[test]
6672	#[cfg(feature = "async")]
6673	fn basic_frame_reading() {
6674		let mut producer = Info { start: 0 }.produce();
6675		producer
6676			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"frame0")))
6677			.unwrap();
6678		producer
6679			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"frame1")))
6680			.unwrap();
6681		let producer = producer.finish().unwrap();
6682
6683		let mut consumer = producer.consume();
6684		let f0 = consumer.next_frame().now_or_never().unwrap().unwrap().unwrap();
6685		assert_eq!(f0.size, 6);
6686		let f1 = consumer.next_frame().now_or_never().unwrap().unwrap().unwrap();
6687		assert_eq!(f1.size, 6);
6688		let end = consumer.next_frame().now_or_never().unwrap().unwrap();
6689		assert!(end.is_none());
6690	}
6691
6692	#[test]
6693	#[cfg(feature = "async")]
6694	fn read_frame_preserves_timestamp() {
6695		let mut producer = Info { start: 0 }.produce();
6696		let timestamp = Timestamp::from_micros(20_000).unwrap();
6697		producer
6698			.write_frame(Frame::new(timestamp, Bytes::from_static(b"hello")))
6699			.unwrap();
6700		let producer = producer.finish().unwrap();
6701
6702		let mut consumer = producer.consume();
6703		let frame = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
6704		assert_eq!(frame.timestamp.as_micros().unwrap(), 20_000);
6705		assert_eq!(frame.payload, Bytes::from_static(b"hello"));
6706	}
6707
6708	/// An untimed frame reads back untimed, and still counts as the group's first frame:
6709	/// an empty group and a group on an untimed track are different answers.
6710	#[test]
6711	#[cfg(feature = "async")]
6712	fn an_untimed_frame_still_starts_the_group() {
6713		let mut producer = Info { start: 0 }.produce_untimed();
6714		let waiter = kio::Waiter::noop();
6715		assert!(
6716			producer.handle.poll_started(&waiter).is_pending(),
6717			"nothing presented yet"
6718		);
6719
6720		producer
6721			.write_frame(Frame::new(
6722				crate::Timestamp::unscaled(producer.start),
6723				Bytes::from_static(b"hello"),
6724			))
6725			.unwrap();
6726		let producer = producer.finish().unwrap();
6727
6728		assert!(producer.handle.poll_started(&waiter).is_ready());
6729		assert_eq!(producer.handle.timestamp(), None);
6730		assert_eq!(producer.handle.latest(), None);
6731
6732		let mut consumer = producer.consume();
6733		let frame = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
6734		assert_eq!(frame.timestamp, Timestamp::unscaled(0));
6735		assert_eq!(frame.payload, Bytes::from_static(b"hello"));
6736	}
6737
6738	/// `is_started()` must already be true by the moment `poll_started` wakes its waiter, across
6739	/// every path that starts a group: a reader woken on `GroupState` release would otherwise see
6740	/// `is_started() == false` while `poll_started` sees the started state and skips registering.
6741	#[test]
6742	fn is_started_is_visible_when_poll_started_wakes() {
6743		use std::sync::atomic::{AtomicBool, Ordering};
6744		use std::task::{Wake, Waker};
6745
6746		struct Observe {
6747			handle: Handle,
6748			woken: AtomicBool,
6749			started_on_wake: AtomicBool,
6750		}
6751
6752		impl Wake for Observe {
6753			fn wake(self: Arc<Self>) {
6754				self.wake_by_ref();
6755			}
6756
6757			fn wake_by_ref(self: &Arc<Self>) {
6758				self.woken.store(true, Ordering::SeqCst);
6759				if self.handle.is_started() {
6760					self.started_on_wake.store(true, Ordering::SeqCst);
6761				}
6762			}
6763		}
6764
6765		let check = |label: &str, handle: &Handle, start: Box<dyn FnOnce()>| {
6766			let obs = Arc::new(Observe {
6767				handle: handle.clone(),
6768				woken: AtomicBool::new(false),
6769				started_on_wake: AtomicBool::new(false),
6770			});
6771			let waiter = kio::Waiter::new(Waker::from(obs.clone()));
6772			assert!(handle.poll_started(&waiter).is_pending(), "{label}: starts pending");
6773			start();
6774			assert!(obs.woken.load(Ordering::SeqCst), "{label}: poll_started waiter woke");
6775			assert!(
6776				obs.started_on_wake.load(Ordering::SeqCst),
6777				"{label}: is_started() was false when poll_started woke"
6778			);
6779			assert!(
6780				handle.poll_started(&kio::Waiter::noop()).is_ready(),
6781				"{label}: ready after start"
6782			);
6783		};
6784
6785		// 1. write_frame
6786		let mut producer = Info { start: 0 }.produce();
6787		let handle = producer.handle.clone();
6788		check(
6789			"write_frame",
6790			&handle,
6791			Box::new(move || {
6792				producer
6793					.write_frame(Frame::new(
6794						Timestamp::from_millis(10).unwrap(),
6795						Bytes::from_static(b"a"),
6796					))
6797					.unwrap();
6798			}),
6799		);
6800
6801		// 2. write_frames
6802		let mut producer = Info { start: 0 }.produce();
6803		let handle = producer.handle.clone();
6804		check(
6805			"write_frames",
6806			&handle,
6807			Box::new(move || {
6808				let mut frames = frame::Buffer::<1>::new();
6809				frames
6810					.push(Frame::new(
6811						Timestamp::from_millis(10).unwrap(),
6812						Bytes::from_static(b"a"),
6813					))
6814					.unwrap();
6815				producer.write_frames(&mut frames).unwrap();
6816			}),
6817		);
6818
6819		// 3. create_frame (create_object)
6820		let producer = Info { start: 0 }.produce();
6821		let handle = producer.handle.clone();
6822		check(
6823			"create_frame",
6824			&handle,
6825			Box::new(move || {
6826				let frame = producer
6827					.create_frame(frame::Info {
6828						size: 1,
6829						timestamp: Timestamp::from_millis(10).unwrap(),
6830					})
6831					.unwrap();
6832				drop(frame);
6833			}),
6834		);
6835
6836		// 4. finish on an empty group
6837		let producer = Info { start: 0 }.produce();
6838		let handle = producer.handle.clone();
6839		check(
6840			"finish",
6841			&handle,
6842			Box::new(move || {
6843				let _ = producer.finish().unwrap();
6844			}),
6845		);
6846
6847		// 5. adopt_head (take_head / settle_head)
6848		let mut donor = Info { start: 0 }.produce();
6849		donor
6850			.write_frame(Frame::new(
6851				Timestamp::from_millis(10).unwrap(),
6852				Bytes::from_static(b"a"),
6853			))
6854			.unwrap();
6855		let handoff = donor.consume().handoff();
6856		donor.abort(Error::Cancel).unwrap();
6857		let head = handoff.head().expect("salvaged head");
6858
6859		let mut successor = Info { start: 0 }.produce();
6860		successor.start_at(1).unwrap();
6861		let handle = successor.handle.clone();
6862		check(
6863			"adopt_head",
6864			&handle,
6865			Box::new(move || {
6866				successor.handle.adopt_head(&head);
6867			}),
6868		);
6869	}
6870
6871	/// A track is all timed or all untimed, so a frame that doesn't match it is refused.
6872	#[test]
6873	fn a_mismatched_frame_is_refused() {
6874		let time = |timed| match timed {
6875			true => Timestamp::ZERO,
6876			false => Timestamp::unscaled(0),
6877		};
6878		for timed in [false, true] {
6879			let mut group = if timed {
6880				Info { start: 0 }.produce()
6881			} else {
6882				Info { start: 0 }.produce_untimed()
6883			};
6884			let mut frames = frame::Buffer::<2>::new();
6885			frames.push(Frame::new(time(timed), Bytes::from_static(b"a"))).unwrap();
6886			frames.push(Frame::new(time(!timed), Bytes::from_static(b"b"))).unwrap();
6887			assert!(matches!(group.write_frames(&mut frames), Err(Error::TimestampMismatch)));
6888			assert_eq!(frames.len(), 2, "a refused tail leaves the whole batch intact");
6889			assert_eq!(group.frame_count(), 0, "a refused tail publishes no prefix");
6890			assert!(!group.is_aborted(), "a bad timestamp does not fail the group");
6891			group.finish().unwrap();
6892		}
6893
6894		let mut untimed = Info { start: 0 }.produce_untimed();
6895		assert!(matches!(
6896			untimed.write_frame(Frame::new(untimed.key_time(), Bytes::from_static(b"x"))),
6897			Err(Error::TimestampMismatch)
6898		));
6899
6900		let mut timed = Info { start: 0 }.produce();
6901		assert!(matches!(
6902			timed.write_frame(Frame::new(
6903				crate::Timestamp::unscaled(timed.start),
6904				Bytes::from_static(b"x")
6905			)),
6906			Err(Error::TimestampMismatch)
6907		));
6908		// A scale-less frame carries its group's key, so another key is a mismatch.
6909		assert!(matches!(
6910			untimed.write_frame(Frame::new(Timestamp::unscaled(1), Bytes::from_static(b"x"))),
6911			Err(Error::TimestampMismatch)
6912		));
6913		assert!(matches!(
6914			timed.create_frame(frame::Info {
6915				size: 1,
6916				timestamp: Timestamp::unscaled(0)
6917			}),
6918			Err(Error::TimestampMismatch)
6919		));
6920	}
6921
6922	/// A keyed group's timed frame 0 sits at its key on every write path, or lite-07 could not carry
6923	/// it; later frames only never decrease.
6924	#[test]
6925	fn a_timed_frame_0_off_its_key_is_refused() {
6926		let at = |ms| Timestamp::from_millis(ms).unwrap();
6927		let mut group = Info { start: 100 }.produce().keyed();
6928		assert!(matches!(
6929			group.write_frame(Frame::new(at(101), Bytes::from_static(b"x"))),
6930			Err(Error::TimestampMismatch)
6931		));
6932		let mut frames = frame::Buffer::<1>::new();
6933		frames.push(Frame::new(at(99), Bytes::from_static(b"x"))).unwrap();
6934		assert!(matches!(group.write_frames(&mut frames), Err(Error::TimestampMismatch)));
6935		assert!(matches!(
6936			Info { start: 100 }.produce().keyed().create_frame(frame::Info {
6937				size: 1,
6938				timestamp: at(101)
6939			}),
6940			Err(Error::TimestampMismatch)
6941		));
6942		assert_eq!(group.frame_count(), 0);
6943		group
6944			.write_frame(Frame::new(at(100), Bytes::from_static(b"x")))
6945			.unwrap();
6946		group
6947			.write_frame(Frame::new(at(150), Bytes::from_static(b"y")))
6948			.unwrap();
6949		group.finish().unwrap();
6950	}
6951
6952	#[test]
6953	#[cfg(feature = "async")]
6954	fn chunked_frame_reads_whole() {
6955		let producer = Info { start: 0 }.produce();
6956		let mut frame = producer
6957			.create_frame(frame::Info {
6958				size: 10,
6959				timestamp: Timestamp::ZERO,
6960			})
6961			.unwrap();
6962		frame.write(Bytes::from_static(b"hello")).unwrap();
6963		frame.write(Bytes::from_static(b"world")).unwrap();
6964		let producer = frame.finish().unwrap();
6965		let producer = producer.finish().unwrap();
6966
6967		// Frame data is held in a single per-frame buffer; a whole-frame read returns
6968		// the full contents in one slice.
6969		let mut consumer = producer.consume();
6970		let frame = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
6971		assert_eq!(frame.payload, Bytes::from_static(b"helloworld"));
6972	}
6973
6974	#[test]
6975	#[cfg(feature = "async")]
6976	fn chunked_frame_streams_partial() {
6977		let producer = Info { start: 0 }.produce();
6978		let mut consumer = producer.consume();
6979
6980		let mut frame = producer
6981			.create_frame(frame::Info {
6982				size: 6,
6983				timestamp: Timestamp::ZERO,
6984			})
6985			.unwrap();
6986		frame.write(Bytes::from_static(b"foo")).unwrap();
6987
6988		// A consumer can stream the in-flight tail before it's finished.
6989		let mut f = consumer.next_frame().now_or_never().unwrap().unwrap().unwrap();
6990		let c1 = f.read_chunk().now_or_never().unwrap().unwrap();
6991		assert_eq!(c1, Some(Bytes::from_static(b"foo")));
6992		assert!(f.read_chunk().now_or_never().is_none());
6993
6994		frame.write(Bytes::from_static(b"bar")).unwrap();
6995		let _producer = frame.finish().unwrap();
6996
6997		let c2 = f.read_chunk().now_or_never().unwrap().unwrap();
6998		assert_eq!(c2, Some(Bytes::from_static(b"bar")));
6999		let c3 = f.read_chunk().now_or_never().unwrap().unwrap();
7000		assert_eq!(c3, None);
7001	}
7002
7003	#[test]
7004	#[cfg(feature = "async")]
7005	fn group_finish_returns_none() {
7006		let producer = Info { start: 0 }.produce();
7007		let producer = producer.finish().unwrap();
7008
7009		let mut consumer = producer.consume();
7010		let end = consumer.next_frame().now_or_never().unwrap().unwrap();
7011		assert!(end.is_none());
7012	}
7013
7014	/// Draining the first parked group must not enter an unrelated group's lock.
7015	/// Holding an unrelated group guard makes a backlog walk deadlock.
7016	#[test]
7017	fn draining_a_parked_group_does_not_lock_the_backlog() {
7018		let broadcast = super::super::broadcast::Producer::new(Default::default());
7019		let track = broadcast.create_track("parked", track::Info::timed()).unwrap();
7020		let mut subscriber =
7021			track.subscribe(track::Subscription::default().with_max(std::time::Duration::from_secs(3600)));
7022		let groups: Vec<_> = (0..3)
7023			.map(|key| {
7024				let mut group = track.create_empty(Info { start: key }).unwrap();
7025				group.write_frame(Frame::new(group.key_time(), b"f".as_ref())).unwrap();
7026				group.finish().unwrap()
7027			})
7028			.collect();
7029		subscriber.set_range(..0);
7030		let waiter = kio::Waiter::noop();
7031		assert!(subscriber.poll_recv_group(&waiter).is_pending());
7032		subscriber.set_range(..1);
7033		let _unrelated = groups[2].handle.state.read();
7034		let Poll::Ready(Ok(Some(group))) = subscriber.poll_recv_group(&waiter) else {
7035			panic!("group zero is in range")
7036		};
7037		assert_eq!(group.start, 0);
7038	}
7039
7040	#[test]
7041	#[cfg(feature = "async")]
7042	fn abort_propagates() {
7043		let producer = Info { start: 0 }.produce();
7044		let mut consumer = producer.consume();
7045		producer.abort(crate::Error::Cancel).unwrap();
7046
7047		let result = consumer.next_frame().now_or_never().unwrap();
7048		assert!(matches!(result, Err(crate::Error::Cancel)));
7049	}
7050
7051	#[test]
7052	fn abort_unwanted_pairs_with_try_consume() {
7053		let producer = Info { start: 0 }.produce();
7054
7055		let consumer = producer.handle.try_consume().expect("open");
7056		assert!(
7057			!producer.handle.abort_unwanted(crate::Error::Cancel),
7058			"a reader declines the abort"
7059		);
7060		drop(consumer);
7061
7062		assert!(producer.handle.abort_unwanted(crate::Error::Cancel));
7063		assert!(
7064			producer.handle.try_consume().is_none(),
7065			"an aborted group mints no reader"
7066		);
7067	}
7068
7069	#[test]
7070	fn abort_clears_cached_frames() {
7071		let mut producer = Info { start: 0 }.produce();
7072		producer
7073			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"data")))
7074			.unwrap();
7075
7076		// A stale consumer that never reads must not pin the cached frames.
7077		let _consumer = producer.consume();
7078		assert_eq!(producer.handle.state.read().entries(0, usize::MAX).count(), 1);
7079
7080		producer.handle().abort(crate::Error::Cancel).unwrap();
7081
7082		let state = producer.handle.state.read();
7083		assert!(state.is_empty(), "cached frames should be dropped on abort");
7084		assert_eq!(state.cache, 0);
7085	}
7086
7087	/// A failed copy moves its frames to the readers that could resume it, so they outlive
7088	/// the release only as long as one of those readers does; cache policy and an oversized
7089	/// group keep nothing.
7090	#[test]
7091	fn an_abort_hands_the_head_to_its_resumers() {
7092		for (err, kept) in [
7093			(Error::Cancel, true),
7094			(Error::Evicted, false),
7095			(Error::GroupTooLarge, false),
7096		] {
7097			let pool = cache::Pool::unbounded();
7098			let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7099			let mut producer = Producer::new(Info::from(0u64), track::Info::default(), cache);
7100			producer
7101				.write_frame(Frame::new(
7102					crate::Timestamp::unscaled(producer.start),
7103					Bytes::from_static(b"a"),
7104				))
7105				.unwrap();
7106			producer
7107				.write_frame(Frame::new(
7108					crate::Timestamp::unscaled(producer.start),
7109					Bytes::from_static(b"b"),
7110				))
7111				.unwrap();
7112			let handoff = producer.consume().handoff();
7113			assert_eq!(handoff.head().map(|head| head.entries.len()), Some(2), "read live");
7114
7115			producer.handle().abort(err.clone()).unwrap();
7116			assert!(producer.handle.state.read().is_empty(), "{err}: released");
7117			assert_eq!(pool.used() > 0, kept, "{err}: billed only while held");
7118			let head = handoff.head();
7119			assert_eq!(head.is_some(), kept, "{err}");
7120			if let Some(head) = head {
7121				assert_eq!((head.start, head.first_object, head.entries.len()), (0, true, 2));
7122				let held = Arc::downgrade(&head);
7123				drop((head, handoff));
7124				assert!(held.upgrade().is_none(), "freed with the last resumer");
7125				assert_eq!(pool.used(), 0, "unbilled with it");
7126			}
7127		}
7128	}
7129
7130	/// A resuming reader that stops polling holds a failed copy's head no longer than an
7131	/// idle group stays cached.
7132	#[test]
7133	fn a_held_head_expires_with_the_pool_window() {
7134		let pool = cache::Pool::new(cache::Config::default().with_expiry(std::time::Duration::from_secs(1)));
7135		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7136		let mut producer = Producer::new(Info::from(0u64), track::Info::default(), cache);
7137		producer
7138			.write_frame(Frame::new(
7139				crate::Timestamp::unscaled(producer.start),
7140				Bytes::from_static(b"a"),
7141			))
7142			.unwrap();
7143		let handoff = producer.consume().handoff();
7144		producer.handle().abort(Error::Cancel).unwrap();
7145		drop(producer);
7146		assert!(handoff.head().is_some());
7147
7148		pool.step(std::time::Duration::from_secs(2));
7149		pool.sweep();
7150		assert!(handoff.head().is_none(), "the sweep drops a held head past the window");
7151		assert_eq!(pool.used(), 0);
7152	}
7153
7154	/// A head lent to a copy for a group still to arrive is billed to that copy's pool like a
7155	/// failed copy's held head, and reclaimed the same way: refused when the pool is full, and
7156	/// dropped once idle past the window.
7157	#[test]
7158	fn a_lent_head_is_billed_and_expires_with_the_pool_window() {
7159		let source = cache::Track::new(
7160			cache::Pool::unbounded(),
7161			Default::default(),
7162			Default::default(),
7163			kio::Weak::new(),
7164		);
7165		let mut producer = Producer::new(Info::from(0u64), track::Info::default(), source);
7166		producer
7167			.write_frame(Frame::new(
7168				crate::Timestamp::unscaled(producer.start),
7169				Bytes::from_static(b"a"),
7170			))
7171			.unwrap();
7172		let head = producer.consume().handoff().head().unwrap();
7173
7174		let pool = cache::Pool::new(cache::Config::default().with_expiry(std::time::Duration::from_secs(1)));
7175		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7176		let loan = Handoff::lent(head.clone(), &cache).expect("room for it");
7177		assert!(pool.used() > 0, "billed while lent");
7178		pool.step(std::time::Duration::from_secs(2));
7179		pool.sweep();
7180		assert!(loan.head().is_none(), "the sweep drops an idle loan");
7181		assert_eq!(pool.used(), 0);
7182
7183		let full = cache::Pool::new(cache::Config::default().with_capacity(1));
7184		let cache = cache::Track::new(full, Default::default(), Default::default(), kio::Weak::new());
7185		assert!(Handoff::lent(head, &cache).is_none(), "a full pool lends nothing");
7186	}
7187
7188	/// The registry the sweep expires held heads from grows with the heads held, not with
7189	/// every group that failed, and gives back what a burst grew it to once they expire.
7190	#[test]
7191	fn the_held_registry_follows_the_heads_held() {
7192		const BURST: usize = 64;
7193		let pool = cache::Pool::new(cache::Config::default().with_expiry(std::time::Duration::from_secs(1)));
7194		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7195		let fail = |key: u64| {
7196			let mut producer = Producer::new(Info::from(key), track::Info::default(), cache.clone());
7197			producer
7198				.write_frame(Frame::new(
7199					crate::Timestamp::unscaled(producer.start),
7200					Bytes::from_static(b"a"),
7201				))
7202				.unwrap();
7203			let handoff = producer.consume().handoff();
7204			producer.abort(Error::Cancel).unwrap();
7205			handoff
7206		};
7207
7208		// Recovery adopts each head as soon as its group fails.
7209		for key in 0..BURST as u64 {
7210			drop(fail(key));
7211		}
7212		assert!(pool.held_capacity() < BURST, "adopted hand-offs pinned the registry");
7213
7214		// Readers that stop polling hold every head until the window passes.
7215		let held: Vec<_> = (0..BURST as u64).map(fail).collect();
7216		assert!(pool.held_capacity() >= BURST);
7217		pool.step(std::time::Duration::from_secs(2));
7218		pool.sweep();
7219		assert!(held.iter().all(|handoff| handoff.head().is_none()));
7220		assert!(pool.held_capacity() < BURST, "the sweep kept a burst's allocation");
7221	}
7222
7223	/// A failed copy's head is held only while the pool has room for it.
7224	#[test]
7225	fn a_full_pool_holds_no_head() {
7226		let pool = cache::Pool::new(cache::Config::default().with_capacity(1));
7227		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7228		let mut producer = Producer::new(Info::from(0u64), track::Info::default(), cache);
7229		producer
7230			.write_frame(Frame::new(
7231				crate::Timestamp::unscaled(producer.start),
7232				Bytes::from_static(b"a"),
7233			))
7234			.unwrap();
7235		let handoff = producer.consume().handoff();
7236		producer.handle().abort(Error::Cancel).unwrap();
7237		assert!(handoff.head().is_none());
7238		assert_eq!(pool.used(), 0);
7239	}
7240
7241	/// The in-flight frame's unwritten remainder counts against the live tail, so an
7242	/// adoption cannot take the group past it once the frame finishes streaming.
7243	#[test]
7244	fn an_open_frame_reserves_its_remainder_from_adoption() {
7245		let pool = cache::Pool::unbounded();
7246		let cache = cache::Track::new(pool, Default::default(), Default::default(), kio::Weak::new());
7247		let mut tail = Producer::new(Info::from(0u64), track::Info::default(), cache);
7248		tail.start_at(1).unwrap();
7249		let adopter = tail.handle();
7250		let _frame = tail
7251			.create_frame(frame::Info {
7252				size: MAX_CACHE_BYTES - 1,
7253				timestamp: Timestamp::unscaled(0),
7254			})
7255			.unwrap();
7256		let head = Head {
7257			content: None,
7258			start: 0,
7259			first_object: true,
7260			entries: vec![Entry::plain(
7261				Frame::new(Timestamp::unscaled(0), Bytes::from_static(b"ab")).into(),
7262				0,
7263			)],
7264			compressed: false,
7265			meta: false,
7266		};
7267		adopter.adopt_head(&head);
7268		assert_eq!(
7269			adopter.state.read().offset,
7270			1,
7271			"the head does not fit beside the open frame"
7272		);
7273	}
7274
7275	/// A head's slots count against the live tail, so a head of empty frames that would
7276	/// take the group's slots past it is not adopted.
7277	#[test]
7278	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
7279	fn an_adopted_head_counts_its_slots() {
7280		let pool = cache::Pool::unbounded();
7281		let cache = cache::Track::new(pool, Default::default(), Default::default(), kio::Weak::new());
7282		let mut tail = Producer::new(Info::from(0u64), track::Info::default(), cache);
7283		let count = MAX_CACHE_BYTES as usize / size_of::<Entry>() + 1;
7284		tail.start_at(count as u64).unwrap();
7285		let adopter = tail.handle();
7286		let entry = Entry::plain(Frame::new(Timestamp::unscaled(0), Bytes::new()).into(), 0);
7287		let head = Head {
7288			content: None,
7289			start: 0,
7290			first_object: true,
7291			entries: vec![entry; count],
7292			compressed: false,
7293			meta: false,
7294		};
7295		adopter.adopt_head(&head);
7296		assert_eq!(adopter.state.read().offset, count, "the head's slots do not fit");
7297	}
7298
7299	/// An adopted head leads the fields and the wire header, whether the header was set
7300	/// before the adoption or arrives after it.
7301	#[test]
7302	#[cfg(feature = "async")]
7303	fn an_adopted_head_keeps_fields_and_the_wire_aligned() {
7304		let fields = |id| {
7305			Some(Arc::new(super::super::object::Fields {
7306				id,
7307				properties: Default::default(),
7308			}))
7309		};
7310		let head = Head {
7311			content: None,
7312			start: 0,
7313			first_object: true,
7314			entries: vec![
7315				Entry::plain(Frame::new(Timestamp::unscaled(0), Bytes::from_static(b"a")).into(), 0),
7316				Entry {
7317					owner: Mutex::new(None),
7318					frame: Frame::new(Timestamp::unscaled(0), Bytes::from_static(b"b")).into(),
7319					fields: fields(1),
7320					inflated: 0,
7321					end: 0,
7322				},
7323			],
7324			compressed: false,
7325			meta: false,
7326		};
7327		let wire = Wire {
7328			sparse: false,
7329			first_object: false,
7330			first_id: 2,
7331			extensions: true,
7332			has_end: true,
7333			hole: None,
7334			last: None,
7335		};
7336		for wired_first in [true, false] {
7337			let pool = cache::Pool::unbounded();
7338			let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7339			let mut tail = Producer::new(Info::from(0u64), track::Info::default(), cache);
7340			tail.start_at(2).unwrap();
7341			if wired_first {
7342				tail.set_wire(wire.clone()).unwrap();
7343			}
7344			let mut reader = tail.consume().with_range(2..);
7345			let before = pool.used();
7346			tail.handle.adopt_head(&head);
7347			assert!(pool.used() >= before + 2, "the adopted frames are charged");
7348			if !wired_first {
7349				tail.set_wire(wire.clone()).unwrap();
7350			}
7351			let written = tail.handle.state.read().wire().cloned().unwrap();
7352			assert_eq!(
7353				(written.first_object, written.first_id, written.last),
7354				(true, 0, Some(1))
7355			);
7356			tail.mark_gap(2, None).unwrap();
7357			assert!(
7358				tail.handle.state.read().wire().unwrap().fetchable(),
7359				"no gap below the stream"
7360			);
7361			tail.write_frame(Frame::new(
7362				crate::Timestamp::unscaled(tail.start),
7363				Bytes::from_static(b"c"),
7364			))
7365			.unwrap();
7366			let tail = tail.finish().unwrap();
7367
7368			let waiter = kio::Waiter::noop();
7369			let mut whole = tail.consume();
7370			let mut read = Vec::new();
7371			while let Poll::Ready(Ok(Some(object))) = whole.poll_read_object(&waiter) {
7372				read.push((
7373					object.frame.payload.contiguous(0),
7374					object.fields.map(|fields| fields.id),
7375				));
7376			}
7377			assert_eq!(
7378				read,
7379				[
7380					(Bytes::from_static(b"a"), None),
7381					(Bytes::from_static(b"b"), Some(1)),
7382					(Bytes::from_static(b"c"), None)
7383				]
7384			);
7385			let next = reader.read_frame().now_or_never().unwrap().unwrap();
7386			assert_eq!(
7387				next.map(|frame| frame.payload),
7388				Some(Bytes::from_static(b"c")),
7389				"a reader keeps its place"
7390			);
7391		}
7392	}
7393
7394	/// A head adopted into a copy that already holds its terminal object, and no frame,
7395	/// leaves the head's last object as the newest data object, not the terminal one.
7396	#[test]
7397	#[cfg(feature = "async")]
7398	fn an_adopted_head_below_a_terminal_object_is_the_last_data() {
7399		let head = Head {
7400			content: None,
7401			start: 0,
7402			first_object: true,
7403			entries: vec![
7404				Entry::plain(Frame::new(Timestamp::unscaled(0), Bytes::from_static(b"a")).into(), 0),
7405				Entry::plain(Frame::new(Timestamp::unscaled(0), Bytes::from_static(b"b")).into(), 0),
7406			],
7407			compressed: false,
7408			meta: false,
7409		};
7410		let pool = cache::Pool::unbounded();
7411		let cache = cache::Track::new(pool, Default::default(), Default::default(), kio::Weak::new());
7412		let mut tail = Producer::new(Info::from(0u64), track::Info::default(), cache);
7413		tail.start_at(2).unwrap();
7414		tail.set_wire(Wire {
7415			sparse: false,
7416			first_object: false,
7417			first_id: 2,
7418			extensions: false,
7419			has_end: true,
7420			hole: None,
7421			last: None,
7422		})
7423		.unwrap();
7424		tail.set_end_object(super::super::object::Fields {
7425			id: 2,
7426			properties: Default::default(),
7427		})
7428		.unwrap();
7429		assert_eq!(tail.handle.last_data_object(), None, "no data object yet");
7430		tail.handle.adopt_head(&head);
7431		assert_eq!(tail.handle.state.read().offset, 0, "the head is adopted");
7432		assert_eq!(tail.handle.last_data_object(), Some(1));
7433	}
7434
7435	#[test]
7436	#[cfg(feature = "async")]
7437	fn drop_unfinished_clears_cached_frames() {
7438		let mut writer = Info { start: 0 }.produce();
7439		let producer = writer.handle();
7440		writer
7441			.write_frame(Frame::new(writer.key_time(), Bytes::from_static(b"data")))
7442			.unwrap();
7443
7444		// A stale consumer keeps the channel (and thus the cache) alive.
7445		let mut consumer = producer.consume();
7446		assert_eq!(producer.state.read().entries(0, usize::MAX).count(), 1);
7447
7448		// Drop every producer without finishing: the cache is released.
7449		drop(writer);
7450		drop(producer);
7451
7452		let result = consumer.next_frame().now_or_never().unwrap();
7453		assert!(matches!(result, Err(crate::Error::Dropped)));
7454	}
7455
7456	#[test]
7457	fn drop_after_abort_does_not_warn() {
7458		let warns = count_drop_warnings("group::Producer dropped without finish", || {
7459			let mut writer = Info { start: 0 }.produce();
7460			let keep = writer.handle();
7461			let producer = writer.handle();
7462			writer
7463				.write_frame(Frame::new(writer.key_time(), Bytes::from_static(b"data")))
7464				.unwrap();
7465			let _consumer = producer.consume();
7466			writer.abort(crate::Error::Cancel).unwrap();
7467			drop(keep);
7468		});
7469		assert_eq!(warns, 0, "abort-then-drop must not emit unfinished-producer WARN");
7470	}
7471
7472	#[test]
7473	fn drop_unfinished_warns() {
7474		let warns = count_drop_warnings("group::Producer dropped without finish", || {
7475			let mut writer = Info { start: 0 }.produce();
7476			let producer = writer.handle();
7477			writer
7478				.write_frame(Frame::new(writer.key_time(), Bytes::from_static(b"data")))
7479				.unwrap();
7480			let _consumer = producer.consume();
7481			drop(writer);
7482			drop(producer);
7483		});
7484		assert_eq!(warns, 1, "unfinished drop must emit one unfinished-producer WARN");
7485	}
7486
7487	#[test]
7488	#[cfg(feature = "async")]
7489	fn drop_finished_keeps_cached_frames() {
7490		let mut producer = Info { start: 0 }.produce();
7491		producer
7492			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"data")))
7493			.unwrap();
7494		let producer = producer.finish().unwrap();
7495
7496		let mut consumer = producer.consume();
7497		drop(producer);
7498
7499		// A cleanly finished group keeps its cache so the consumer can still drain.
7500		let frame = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7501		assert_eq!(frame.payload, Bytes::from_static(b"data"));
7502	}
7503
7504	#[test]
7505	#[cfg(feature = "async")]
7506	fn pending_then_ready() {
7507		let mut producer = Info { start: 0 }.produce();
7508		let mut consumer = producer.consume();
7509
7510		// Consumer blocks because no frames yet.
7511		assert!(consumer.next_frame().now_or_never().is_none());
7512
7513		producer
7514			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"data")))
7515			.unwrap();
7516		producer.finish().unwrap();
7517
7518		let frame = consumer.next_frame().now_or_never().unwrap().unwrap().unwrap();
7519		assert_eq!(frame.size, 4);
7520	}
7521
7522	/// `count` frames of 1 MiB, each naming its index and incompressible.
7523	#[cfg(feature = "async")]
7524	fn mebibytes(count: usize) -> Vec<Bytes> {
7525		let mut seed = 0x9e37_79b9_7f4a_7c15u64;
7526		(0..count)
7527			.map(|index| {
7528				let mut frame = Vec::with_capacity(1 << 20);
7529				frame.extend_from_slice(&(index as u64).to_le_bytes());
7530				while frame.len() < 1 << 20 {
7531					seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
7532					frame.extend_from_slice(&seed.to_le_bytes());
7533				}
7534				Bytes::from(frame)
7535			})
7536			.collect()
7537	}
7538
7539	/// A group grows past its live tail by shedding whole frames from its front: a reader
7540	/// that keeps up reads every frame, a late one gets `Evicted`, and nothing aborts.
7541	#[test]
7542	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
7543	#[cfg(feature = "async")]
7544	fn a_long_group_sheds_its_front() {
7545		let pool = cache::Pool::unbounded();
7546		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7547		let mut producer = Producer::new(Info::from(0u64), track::Info::default(), cache);
7548		let mut live = producer.consume();
7549		let mut late = producer.consume();
7550		let mut finished = producer.consume();
7551
7552		let frames = mebibytes(48);
7553		for (index, frame) in frames.iter().enumerate() {
7554			producer
7555				.write_frame(Frame::new(crate::Timestamp::unscaled(producer.start), frame.clone()))
7556				.unwrap();
7557			let read = live.read_frame().now_or_never().unwrap().unwrap().unwrap();
7558			assert_eq!(read.payload, *frame, "frame {index}");
7559			assert!(pool.used() <= MAX_CACHE_BYTES + (1 << 20), "{} bytes held", pool.used());
7560		}
7561		{
7562			let state = producer.handle.state.read();
7563			assert!(state.outcome.error().is_none());
7564			assert_eq!(state.offset, 0);
7565			assert!((48 - 32..48 - 30).contains(&state.held()), "held from {}", state.held());
7566		}
7567		assert!(matches!(late.read_frame().now_or_never().unwrap(), Err(Error::Evicted)));
7568		assert!(matches!(late.next_frame().now_or_never().unwrap(), Err(Error::Evicted)));
7569		assert!(matches!(
7570			finished.finished().now_or_never().unwrap(),
7571			Err(Error::Evicted)
7572		));
7573
7574		producer.finish().unwrap();
7575		assert!(live.read_frame().now_or_never().unwrap().unwrap().is_none());
7576	}
7577
7578	/// Empty frames still cost their slot, so a group of them sheds its front too.
7579	#[test]
7580	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
7581	fn empty_frames_shed_by_their_slots() {
7582		let mut producer = Info { start: 0 }.produce();
7583		let slot = size_of::<Entry>();
7584		let count = 2 * MAX_CACHE_BYTES as usize / slot;
7585		for _ in 0..count {
7586			producer.write_frame(Frame::new(Timestamp::ZERO, Bytes::new())).unwrap();
7587		}
7588		let state = producer.handle.state.read();
7589		assert!(state.held() > 0, "the front was shed");
7590		assert!(state.slots() <= MAX_CACHE_BYTES, "{} bytes of slots", state.slots());
7591		assert!(state.outcome.error().is_none());
7592	}
7593
7594	/// Batches of empty frames count their new slots too, so they shed the front as
7595	/// single writes do.
7596	#[test]
7597	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
7598	fn empty_frame_batches_shed_by_their_slots() {
7599		let mut producer = Info { start: 0 }.produce();
7600		let count = 2 * MAX_CACHE_BYTES as usize / size_of::<Entry>();
7601		for _ in 0..count / 64 {
7602			let mut batch = frame::Buffer::<64>::new();
7603			for _ in 0..64 {
7604				batch.push(Frame::new(Timestamp::ZERO, Bytes::new())).unwrap();
7605			}
7606			producer.write_frames(&mut batch).unwrap();
7607		}
7608		let state = producer.handle.state.read();
7609		assert!(state.held() > 0, "the front was shed");
7610		// Slots free a segment at a time, so the oldest segment may linger part-shed.
7611		let segment = 64 * size_of::<Entry>() as u64;
7612		assert!(
7613			state.slots() <= MAX_CACHE_BYTES + segment,
7614			"{} bytes of slots",
7615			state.slots()
7616		);
7617		assert!(state.outcome.error().is_none());
7618	}
7619
7620	/// A frame count past the old 8192-frame cap is held whole while it fits the tail.
7621	#[test]
7622	#[cfg_attr(miri, ignore = "each write takes Miri ~30 ms, so 10,000 run past its SLOW mark")]
7623	fn a_group_has_no_frame_cap() {
7624		let mut producer = Info { start: 0 }.produce();
7625		for _ in 0..10_000 {
7626			producer
7627				.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"x")))
7628				.unwrap();
7629		}
7630		let producer = producer.finish().unwrap();
7631
7632		let state = producer.handle.state.read();
7633		assert_eq!(state.offset, 0);
7634		assert_eq!(state.entries(0, usize::MAX).count(), 10_000);
7635		assert!(state.outcome.error().is_none());
7636	}
7637
7638	/// Pool debt sheds a group's front, keeping an open group's newest frame for the
7639	/// reader about to take it.
7640	#[test]
7641	fn debt_sheds_the_front_but_not_the_newest_frame() {
7642		let mut producer = Info { start: 0 }.produce();
7643		// Small frames keep Miri's per-byte cost down; shedding is per frame, not per byte.
7644		for index in 0..4u8 {
7645			producer
7646				.write_frame(Frame::new(Timestamp::ZERO, Bytes::from(vec![index; 1024])))
7647				.unwrap();
7648		}
7649		let freed = producer.handle.shed(u64::MAX, u64::MAX);
7650		assert!(freed >= 3 * 1024, "freed {freed}");
7651		assert_eq!(producer.handle.state.read().held(), 3);
7652
7653		let producer = producer.finish().unwrap();
7654		producer.handle.shed(u64::MAX, u64::MAX);
7655		assert!(producer.handle.state.read().is_empty());
7656		assert_eq!(producer.handle.state.read().cache, 0);
7657	}
7658
7659	#[test]
7660	#[cfg(feature = "async")]
7661	fn clone_consumer_independent() {
7662		let mut producer = Info { start: 0 }.produce();
7663		producer
7664			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
7665			.unwrap();
7666
7667		let mut c1 = producer.consume();
7668		// Read one frame from c1
7669		let _ = c1.next_frame().now_or_never().unwrap().unwrap().unwrap();
7670
7671		// Clone c1, inheriting its index (past first frame).
7672		let mut c2 = c1.clone();
7673
7674		producer
7675			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"b")))
7676			.unwrap();
7677		producer.finish().unwrap();
7678
7679		// c2 should get the second frame (inherited index)
7680		let f = c2.next_frame().now_or_never().unwrap().unwrap().unwrap();
7681		assert_eq!(f.size, 1); // "b"
7682
7683		let end = c2.next_frame().now_or_never().unwrap().unwrap();
7684		assert!(end.is_none());
7685	}
7686
7687	#[cfg(feature = "async")]
7688	fn prefetched_consumer(pool: &cache::Pool, max_age: std::time::Duration) -> (Finished, Consumer) {
7689		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
7690		let track = track::Info::timed().with_max_age(max_age);
7691		let mut producer = Producer::new(Info { start: 0 }, track, cache);
7692		producer
7693			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
7694			.unwrap();
7695		producer
7696			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"b")))
7697			.unwrap();
7698		let producer = producer.finish().unwrap();
7699
7700		let mut consumer = producer.consume();
7701		consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7702		(producer, consumer)
7703	}
7704
7705	#[test]
7706	#[cfg(feature = "async")]
7707	fn keep_alive_restarts_expiry_within_one_sampled_tick() {
7708		let pool = cache::Pool::new(cache::Config::default().with_expiry(std::time::Duration::from_secs(1)));
7709		let (producer, consumer) = prefetched_consumer(&pool, std::time::Duration::MAX);
7710		consumer.keep_alive();
7711		let stamp = producer.handle.cache_accessed();
7712		assert_eq!(producer.handle.cache_accessed_tick(Some(pool.now())), Some(pool.now()));
7713		consumer.keep_alive();
7714		assert_eq!(
7715			producer.handle.cache_accessed(),
7716			stamp,
7717			"same-tick reads do not inflate eviction rank"
7718		);
7719		assert_eq!(
7720			producer.handle.cache_accessed_tick(None),
7721			None,
7722			"every frame resets the idle clock"
7723		);
7724	}
7725
7726	#[test]
7727	#[cfg(feature = "async")]
7728	fn keep_alive_keeps_the_counted_access_mean_balanced() {
7729		let pool = cache::Pool::new(cache::Config::default().with_capacity(1_000_000));
7730		let (producer, consumer) = prefetched_consumer(&pool, std::time::Duration::MAX);
7731		producer.handle.cache_demote();
7732		consumer.keep_alive();
7733		assert_eq!(pool.average(), Some(producer.handle.cache_accessed()));
7734		let before = producer.handle.cache_accessed();
7735		pool.step(std::time::Duration::from_millis(100));
7736		consumer.keep_alive();
7737		assert!(producer.handle.cache_accessed() > before);
7738		assert_eq!(pool.average(), Some(producer.handle.cache_accessed()));
7739		producer.abort(Error::Cancel).unwrap();
7740		assert_eq!(
7741			pool.average(),
7742			None,
7743			"removal subtracts the same sample that was inserted"
7744		);
7745	}
7746
7747	#[test]
7748	#[cfg(feature = "async")]
7749	fn prefetch_refresh_honors_pool_expiry() {
7750		let config = cache::Config::default().with_expiry(std::time::Duration::from_secs(1));
7751		let pool = cache::Pool::new(config);
7752		let (producer, mut consumer) = prefetched_consumer(&pool, std::time::Duration::MAX);
7753		let before = producer.handle.cache_accessed();
7754
7755		pool.step(std::time::Duration::from_millis(600));
7756		consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7757
7758		assert!(producer.handle.cache_accessed() > before, "the pool cadence is used");
7759	}
7760
7761	#[test]
7762	#[cfg(feature = "async")]
7763	fn prefetch_refresh_honors_track_max_age() {
7764		let config = cache::Config::default().with_expiry(std::time::Duration::from_secs(30));
7765		let pool = cache::Pool::new(config);
7766		let (producer, mut consumer) = prefetched_consumer(&pool, std::time::Duration::from_secs(1));
7767		let before = producer.handle.cache_accessed();
7768
7769		pool.step(std::time::Duration::from_millis(600));
7770		consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7771
7772		assert!(
7773			producer.handle.cache_accessed() > before,
7774			"the track cadence remains in force"
7775		);
7776	}
7777
7778	/// Reading more than one prefetch batch drains every frame in order across the
7779	/// batch boundary (the refill starts exactly where the previous batch ended).
7780	#[test]
7781	#[cfg(feature = "async")]
7782	fn read_frame_crosses_prefetch_batches() {
7783		let n = Prefetch::CAP * 3 + 5;
7784		let mut producer = Info { start: 0 }.produce();
7785		for i in 0..n {
7786			producer
7787				.write_frame(Frame::new(Timestamp::ZERO, Bytes::from(vec![i as u8; 4])))
7788				.unwrap();
7789		}
7790		let producer = producer.finish().unwrap();
7791
7792		let mut consumer = producer.consume();
7793		for i in 0..n {
7794			let frame = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7795			assert_eq!(frame.payload, Bytes::from(vec![i as u8; 4]));
7796		}
7797		assert!(consumer.read_frame().now_or_never().unwrap().unwrap().is_none());
7798	}
7799
7800	/// A group places a time once it holds a frame past it or finishes, never by aborting: an
7801	/// aborted copy may have lost the End its group was sent with.
7802	#[test]
7803	fn a_group_places_a_time_only_once_it_passes_it_or_finishes() {
7804		let frame = |producer: &mut Producer, millis| {
7805			producer
7806				.write_frame(Frame::new(
7807					Timestamp::from_millis(millis).unwrap(),
7808					Bytes::from_static(b"x"),
7809				))
7810				.unwrap();
7811		};
7812		let mut open = Info { start: 1000 }.produce();
7813		assert_eq!(open.handle().unplaced_from(), Some(0), "no frame");
7814		frame(&mut open, 1000);
7815		assert_eq!(open.handle().unplaced_from(), Some(1000));
7816		frame(&mut open, 1800);
7817		assert_eq!(open.handle().unplaced_from(), Some(1800), "places 1700, not 1800");
7818
7819		let mut aborted = Info { start: 1000 }.produce();
7820		frame(&mut aborted, 1000);
7821		let handle = aborted.handle();
7822		aborted.abort(Error::Cancel).unwrap();
7823		assert_eq!(handle.unplaced_from(), Some(1000), "aborted");
7824
7825		let mut finished = Info { start: 1000 }.produce();
7826		frame(&mut finished, 1000);
7827		let handle = finished.handle();
7828		drop(finished.finish().unwrap());
7829		assert_eq!(handle.unplaced_from(), None, "finished");
7830	}
7831
7832	/// A finished group is still aborted once its frames are released to free memory (the
7833	/// cache pool's expiry window or byte target). A reader that already drained every frame
7834	/// is missing nothing, so it must see the clean end of group, and where it ends, rather
7835	/// than the abort.
7836	#[test]
7837	#[cfg(feature = "async")]
7838	fn abort_after_finish_keeps_the_clean_end_for_a_drained_reader() {
7839		let mut producer = Info { start: 0 }.produce();
7840		producer
7841			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"hello")))
7842			.unwrap();
7843		let producer = producer.finish_at(1).unwrap();
7844
7845		let mut drained = producer.consume();
7846		let mut behind = producer.consume();
7847		let frame = drained.read_frame().now_or_never().unwrap().unwrap().unwrap();
7848		assert_eq!(frame.payload, Bytes::from_static(b"hello"));
7849
7850		producer.abort(Error::Old).unwrap();
7851
7852		// Drained everything before the abort: nothing is missing.
7853		assert!(drained.read_frame().now_or_never().unwrap().unwrap().is_none());
7854		assert!(drained.next_frame().now_or_never().unwrap().unwrap().is_none());
7855		assert_eq!(drained.end(), Some(1));
7856
7857		// Never read the frame, and its bytes are gone: a truncated stream, not a clean end.
7858		assert!(matches!(behind.read_frame().now_or_never().unwrap(), Err(Error::Old)));
7859	}
7860
7861	/// `finished` answers for the cursor: a drained reader gets the clean end even after the
7862	/// abort that released the cache, and one that stopped short gets that abort. The
7863	/// producer's total stays available on `frame_count`.
7864	#[test]
7865	#[cfg(feature = "async")]
7866	fn finished_answers_for_the_cursor() {
7867		let mut producer = Info { start: 0 }.produce();
7868		producer
7869			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
7870			.unwrap();
7871		producer
7872			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"b")))
7873			.unwrap();
7874		let producer = producer.finish().unwrap();
7875
7876		let mut drained = producer.consume();
7877		let mut behind = producer.consume();
7878		while drained.read_frame().now_or_never().unwrap().unwrap().is_some() {}
7879		behind.read_frame().now_or_never().unwrap().unwrap().unwrap();
7880
7881		producer.abort(Error::Old).unwrap();
7882
7883		assert_eq!(drained.finished().now_or_never().unwrap().unwrap(), 2);
7884		assert!(matches!(behind.finished().now_or_never().unwrap(), Err(Error::Old)));
7885		assert_eq!(behind.frame_count(), 2);
7886	}
7887
7888	/// Frames a cursor already prefetched are its own, so shedding them from the group
7889	/// does not make `finished` report the cursor evicted.
7890	#[test]
7891	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
7892	#[cfg(feature = "async")]
7893	fn finished_counts_prefetched_frames_as_read() {
7894		let mut producer = Info { start: 0 }.produce();
7895		let frames = mebibytes(36);
7896		for frame in &frames[..8] {
7897			producer
7898				.write_frame(Frame::new(Timestamp::ZERO, frame.clone()))
7899				.unwrap();
7900		}
7901		let mut consumer = producer.consume();
7902		consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7903		for frame in &frames[8..] {
7904			producer
7905				.write_frame(Frame::new(Timestamp::ZERO, frame.clone()))
7906				.unwrap();
7907		}
7908		let held = producer.handle.state.read().held();
7909		assert!((2..=8).contains(&held), "shed into the prefetch: {held}");
7910		assert!(consumer.finished().now_or_never().is_none(), "still pending");
7911		for frame in &frames[1..8] {
7912			let read = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7913			assert_eq!(&read.payload, frame);
7914		}
7915	}
7916
7917	/// `next_frame` drains frames a prior `read_frame` prefetched, preserving order.
7918	#[test]
7919	#[cfg(feature = "async")]
7920	fn interleave_read_and_next_frame() {
7921		let mut producer = Info { start: 0 }.produce();
7922		for i in 0..5u8 {
7923			producer
7924				.write_frame(Frame::new(Timestamp::ZERO, Bytes::from(vec![i; 1])))
7925				.unwrap();
7926		}
7927		let producer = producer.finish().unwrap();
7928
7929		let mut consumer = producer.consume();
7930		// The first whole-frame read prefetches all five frames into the batch.
7931		let f0 = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7932		assert_eq!(f0.payload, Bytes::from(vec![0u8; 1]));
7933
7934		// next_frame must continue from the batch, not skip ahead or repeat.
7935		for i in 1..5u8 {
7936			let mut f = consumer.next_frame().now_or_never().unwrap().unwrap().unwrap();
7937			let data = f.read_all().now_or_never().unwrap().unwrap();
7938			assert_eq!(data, Bytes::from(vec![i; 1]));
7939		}
7940		assert!(consumer.next_frame().now_or_never().unwrap().unwrap().is_none());
7941	}
7942
7943	/// A `read_frame` whose index sits past the buffered frames (cleared by an abort)
7944	/// must surface the error, not panic on an out-of-range `range(local..)`.
7945	#[test]
7946	#[cfg(feature = "async")]
7947	fn read_frame_past_cleared_frames_does_not_panic() {
7948		let mut producer = Info { start: 0 }.produce();
7949		producer
7950			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
7951			.unwrap();
7952		producer
7953			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"b")))
7954			.unwrap();
7955
7956		let mut consumer = producer.consume();
7957		consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7958		consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7959
7960		// Abort clears the cached frames but leaves the consumer's index (2) past them, so the
7961		// refill's `local` (2) exceeds `frames.len()` (0).
7962		producer.abort(Error::Cancel).unwrap();
7963
7964		let result = consumer.read_frame().now_or_never().unwrap();
7965		assert!(matches!(result, Err(Error::Cancel)), "expected Cancel, got {result:?}");
7966	}
7967
7968	/// Dropping a consumer mid-batch must drop the buffered-but-untaken frames
7969	/// (exercises the `MaybeUninit` Drop path; run under miri to catch leaks/UB).
7970	#[test]
7971	#[cfg(feature = "async")]
7972	fn drop_with_partial_batch() {
7973		let mut producer = Info { start: 0 }.produce();
7974		for _ in 0..Prefetch::CAP {
7975			producer
7976				.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"x")))
7977				.unwrap();
7978		}
7979		let producer = producer.finish().unwrap();
7980
7981		let mut consumer = producer.consume();
7982		// Take one frame so the batch is filled but only partially drained.
7983		let _ = consumer.read_frame().now_or_never().unwrap().unwrap().unwrap();
7984		drop(consumer);
7985	}
7986
7987	/// A parked chunk reader is woken by each chunk write. kio only notifies when
7988	/// a write guard was mutably accessed, so `frame_notify` must mark the guard
7989	/// modified; a guard dropped untouched wakes nobody and the reader would
7990	/// stall until the frame completed.
7991	#[kio::test]
7992	#[cfg(feature = "async")]
7993	async fn chunk_write_wakes_parked_reader() {
7994		let producer = Info { start: 0 }.produce();
7995		let mut consumer = producer.consume();
7996		let mut frame = producer
7997			.create_frame(frame::Info {
7998				size: 6,
7999				timestamp: Timestamp::ZERO,
8000			})
8001			.unwrap();
8002		let mut f = consumer.next_frame().await.unwrap().unwrap();
8003		let handle = kio::clock::sim::spawn(async move { f.read_chunk().await });
8004		// Let the reader park on the empty partial before the chunk lands.
8005		kio::clock::sleep(std::time::Duration::from_millis(50)).await;
8006		frame.write(Bytes::from_static(b"foo")).unwrap();
8007		let chunk = kio::clock::timeout(std::time::Duration::from_secs(2), handle)
8008			.await
8009			.expect("parked chunk reader was never woken by the chunk write")
8010			.unwrap()
8011			.unwrap();
8012		assert_eq!(chunk, Some(Bytes::from_static(b"foo")));
8013	}
8014
8015	/// Each frame is stamped when its last byte lands, whichever way it is written, and
8016	/// readers see that stamp however late they read.
8017	#[kio::test]
8018	#[cfg(feature = "async")]
8019	async fn frames_carry_when_they_landed() {
8020		use std::time::Duration;
8021
8022		let start = kio::clock::now();
8023		let mut producer = Info { start: 0 }.produce();
8024		producer
8025			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
8026			.unwrap();
8027
8028		kio::clock::sleep(Duration::from_millis(10)).await;
8029		let mut chunked = producer
8030			.create_frame(frame::Info {
8031				size: 2,
8032				timestamp: Timestamp::ZERO,
8033			})
8034			.unwrap();
8035		chunked.write(Bytes::from_static(b"b")).unwrap();
8036		kio::clock::sleep(Duration::from_millis(10)).await;
8037		chunked.write(Bytes::from_static(b"c")).unwrap();
8038		producer = chunked.finish().unwrap();
8039
8040		kio::clock::sleep(Duration::from_millis(10)).await;
8041		let mut batch = frame::Buffer::<2>::new();
8042		batch
8043			.push(Frame::new(Timestamp::ZERO, Bytes::from_static(b"d")))
8044			.unwrap();
8045		kio::clock::sleep(Duration::from_millis(10)).await;
8046		batch
8047			.push(Frame::new(Timestamp::ZERO, Bytes::from_static(b"e")))
8048			.unwrap();
8049		producer.write_frames(&mut batch).unwrap();
8050		let producer = producer.finish().unwrap();
8051
8052		kio::clock::sleep(Duration::from_secs(1)).await;
8053		let mut consumer = producer.consume();
8054		let mut created = Vec::new();
8055		while let Some(frame) = consumer.read_frame().await.unwrap() {
8056			created.push(frame.created.duration_since(start).as_millis());
8057		}
8058		assert_eq!(created, [0, 20, 40, 40], "stamped on completion, a batch at its write");
8059	}
8060
8061	/// A group is stamped when it is created here, and a reader pulling it late from its track
8062	/// still sees that stamp.
8063	#[kio::test]
8064	#[cfg(feature = "async")]
8065	async fn groups_carry_when_they_landed() {
8066		let start = kio::clock::now();
8067		let alone = Info { start: 0 }.produce();
8068		let track = crate::broadcast::Info::new()
8069			.produce()
8070			.create_track("test", None)
8071			.unwrap();
8072		let mut subscriber = track.subscribe(None);
8073		let live = track.create_empty(Info { start: 0 }).unwrap();
8074
8075		kio::clock::sleep(std::time::Duration::from_secs(1)).await;
8076		assert_eq!(alone.consume().created(), start);
8077		let group = subscriber.recv_group().await.unwrap().expect("the live group");
8078		assert_eq!(group.created(), start);
8079		assert_eq!(group.clone().created(), start, "a clone keeps it");
8080
8081		alone.finish().unwrap();
8082		live.finish().unwrap();
8083	}
8084
8085	/// A frame whose timestamp is at a different scale is converted to the group's
8086	/// scale by `create_frame`.
8087	#[test]
8088	fn create_frame_converts_mismatched_scale() {
8089		use crate::{Timescale, Timestamp};
8090
8091		let producer = Producer::new(
8092			Info { start: 0 },
8093			track::Info::default().with_timescale(Timescale::MICRO),
8094			Default::default(),
8095		);
8096		let frame = frame::Info {
8097			size: 3,
8098			timestamp: Timestamp::from_millis(1).unwrap(), // 1ms -> 1000µs
8099		};
8100		let writer = producer.create_frame(frame).unwrap();
8101		assert_eq!(writer.timestamp.scale(), Some(Timescale::MICRO));
8102		assert_eq!(writer.timestamp.value(), 1000);
8103	}
8104
8105	/// A group can start partway in, so a route can serve the tail of a group whose
8106	/// head came from somewhere else.
8107	#[test]
8108	#[cfg(feature = "async")]
8109	fn start_at_starts_the_group_later() {
8110		let mut producer = Info { start: 0 }.produce();
8111		producer.start_at(3).unwrap();
8112		producer
8113			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"d")))
8114			.unwrap();
8115		let producer = producer.finish().unwrap();
8116
8117		// The frame landed at index 3, so the group's length counts the missing head.
8118		assert_eq!(producer.frame_count(), 4);
8119
8120		let mut consumer = producer.consume();
8121		assert_eq!(consumer.frame_count(), 4);
8122
8123		// A reader positioned at the start is missing the head, and `finished` answers
8124		// for that cursor.
8125		assert!(matches!(
8126			consumer.finished().now_or_never().unwrap(),
8127			Err(Error::Lagged)
8128		));
8129		assert!(matches!(
8130			consumer.read_frame().now_or_never().unwrap(),
8131			Err(Error::Lagged)
8132		));
8133	}
8134
8135	/// Seeking to the group's first available frame is how a front's pump picks up
8136	/// the tail; a lower index clamps up rather than failing.
8137	#[test]
8138	#[cfg(feature = "async")]
8139	fn start_at_clamps_up_to_the_first_frame() {
8140		let mut producer = Info { start: 0 }.produce();
8141		producer.start_at(3).unwrap();
8142		producer
8143			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"d")))
8144			.unwrap();
8145		let producer = producer.finish().unwrap();
8146
8147		let mut consumer = producer.consume().with_range(1..);
8148		assert_eq!(consumer.index(), 3, "clamped up to the first frame that exists");
8149		assert_eq!(
8150			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload,
8151			Bytes::from_static(b"d")
8152		);
8153	}
8154
8155	/// `end_at` ends the read cleanly at the cap, and raising it re-offers the frames
8156	/// still cached behind it.
8157	#[test]
8158	#[cfg(feature = "async")]
8159	fn end_at_caps_and_reopens() {
8160		let mut producer = Info { start: 0 }.produce();
8161		for i in 0..4u8 {
8162			producer
8163				.write_frame(Frame::new(Timestamp::ZERO, Bytes::from(vec![i])))
8164				.unwrap();
8165		}
8166		let producer = producer.finish().unwrap();
8167
8168		let mut consumer = producer.consume();
8169		consumer = consumer.with_range(..2);
8170		assert_eq!(
8171			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload[0],
8172			0
8173		);
8174		assert_eq!(
8175			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload[0],
8176			1
8177		);
8178		assert!(
8179			consumer.read_frame().now_or_never().unwrap().unwrap().is_none(),
8180			"capped reads end cleanly"
8181		);
8182
8183		consumer = consumer.with_range(..);
8184		assert_eq!(
8185			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload[0],
8186			2
8187		);
8188	}
8189
8190	#[test]
8191	#[cfg(feature = "async")]
8192	fn frame_ranges_preserve_progress_and_make_inclusion_explicit() {
8193		let mut producer = Info { start: 0 }.produce();
8194		for i in 0..4u8 {
8195			producer
8196				.write_frame(Frame::new(Timestamp::ZERO, Bytes::from(vec![i])))
8197				.unwrap();
8198		}
8199		let producer = producer.finish().unwrap();
8200		let mut consumer = producer.consume();
8201		consumer = consumer.with_range(1..=1);
8202		assert_eq!(
8203			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload[0],
8204			1
8205		);
8206		assert!(consumer.read_frame().now_or_never().unwrap().unwrap().is_none());
8207		consumer = consumer.with_range(..3);
8208		assert_eq!(
8209			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload[0],
8210			2
8211		);
8212		assert!(consumer.read_frame().now_or_never().unwrap().unwrap().is_none());
8213		consumer = consumer.with_range(0..=3);
8214		assert_eq!(
8215			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload[0],
8216			3
8217		);
8218	}
8219
8220	/// An exclusive cap at 0 is the empty range: no frame is delivered, and raising
8221	/// it re-offers the held frames.
8222	#[test]
8223	#[cfg(feature = "async")]
8224	fn end_at_zero_is_empty() {
8225		let mut producer = Info { start: 0 }.produce();
8226		producer
8227			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"x")))
8228			.unwrap();
8229		let producer = producer.finish().unwrap();
8230
8231		let mut consumer = producer.consume();
8232		consumer = consumer.with_range(..0);
8233		assert!(
8234			consumer.read_frame().now_or_never().unwrap().unwrap().is_none(),
8235			"empty cap delivers nothing"
8236		);
8237
8238		consumer = consumer.with_range(..1);
8239		assert_eq!(
8240			consumer.read_frame().now_or_never().unwrap().unwrap().unwrap().payload,
8241			Bytes::from_static(b"x")
8242		);
8243	}
8244
8245	/// Where the group begins is part of its shape, so it can't move once frames exist.
8246	#[test]
8247	fn start_at_rejected_after_a_frame() {
8248		let mut producer = Info { start: 0 }.produce();
8249		// Re-declaring before the first frame is fine; the shape isn't committed yet.
8250		producer.start_at(2).unwrap();
8251		producer.start_at(3).unwrap();
8252		assert!(
8253			matches!(producer.start_at(2), Err(Error::Closed)),
8254			"the start never moves back"
8255		);
8256
8257		producer
8258			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
8259			.unwrap();
8260		assert!(matches!(producer.start_at(4), Err(Error::Closed)));
8261		assert_eq!(producer.frame_count(), 4, "the frame landed at index 3");
8262	}
8263
8264	/// The start must leave room for at least one frame index.
8265	#[test]
8266	fn start_at_rejects_the_largest_index() {
8267		let mut producer = Info { start: 0 }.produce();
8268		assert!(matches!(
8269			producer.start_at(usize::MAX as u64),
8270			Err(Error::BoundsExceeded(_))
8271		));
8272	}
8273
8274	/// The per-frame size cap (the group byte budget) is enforced before allocating.
8275	#[test]
8276	fn create_frame_rejects_oversized() {
8277		let producer = Info { start: 0 }.produce();
8278		let result = producer.create_frame(frame::Info {
8279			size: MAX_CACHE_BYTES + 1,
8280			timestamp: Timestamp::ZERO,
8281		});
8282		assert!(matches!(result, Err(Error::FrameTooLarge)));
8283	}
8284
8285	fn sized(size: u64) -> frame::Info {
8286		frame::Info {
8287			size,
8288			timestamp: Timestamp::ZERO,
8289		}
8290	}
8291
8292	/// A declared size costs the peer nothing, so the pool is charged as the bytes
8293	/// arrive. Charging the declaration would let a peer evict the cache without
8294	/// sending anything.
8295	#[test]
8296	fn frame_is_charged_as_written() {
8297		let pool = cache::Pool::unbounded();
8298		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
8299		let producer = Producer::new(Info { start: 0 }, track::Info::timed(), cache);
8300		let before = pool.used();
8301
8302		let observing = producer.handle();
8303		let mut frame = producer.create_frame(sized(MAX_CACHE_BYTES)).unwrap();
8304		assert_eq!(pool.used(), before, "the declared size was charged");
8305
8306		frame.write_deferred(Bytes::from(vec![0u8; 100])).unwrap();
8307		assert_eq!(pool.used(), before, "charged before the write was published");
8308		frame.notify();
8309		assert_eq!(pool.used(), before + 100);
8310		assert_eq!(observing.state.read().cache, 100);
8311		// A reader skipping the group still misses the whole declared frame.
8312		assert_eq!(observing.state.read().content().bytes, MAX_CACHE_BYTES);
8313
8314		// Aborting releases what was charged.
8315		frame.abort(Error::Cancel).unwrap();
8316		assert_eq!(observing.state.read().cache, 0);
8317		assert!(pool.used() <= before);
8318	}
8319
8320	/// An open frame still reads its group: which one it is, how many frames it holds,
8321	/// and whether anyone reads it. Finishing the frame hands the same writer back.
8322	#[test]
8323	#[cfg(feature = "async")]
8324	fn an_open_frame_reads_its_group() {
8325		let mut producer = Info { start: 3 }.produce();
8326		producer
8327			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
8328			.unwrap();
8329		let mut consumer = producer.consume();
8330
8331		let mut frame = producer.create_frame(sized(1)).unwrap();
8332		let group = frame.group();
8333		assert_eq!(group.start, 3);
8334		assert_eq!(group.frame_count(), 2, "the open frame counts");
8335		assert!(group.demand().wanted());
8336		assert!(group.poll_closed(&kio::Waiter::noop()).is_pending());
8337
8338		frame.write(Bytes::from_static(b"b")).unwrap();
8339		let producer = frame.finish().unwrap();
8340		producer.finish().unwrap();
8341		let mut read = || consumer.read_frame().now_or_never().unwrap().unwrap();
8342		assert_eq!(read().unwrap().payload, Bytes::from_static(b"a"));
8343		assert_eq!(read().unwrap().payload, Bytes::from_static(b"b"));
8344		assert!(read().is_none());
8345	}
8346
8347	#[test]
8348	fn refused_frame_aborts_with_its_error() {
8349		let producer = Info { start: 0 }.produce();
8350		let handle = producer.handle();
8351		assert!(matches!(
8352			producer.create_frame(sized(MAX_CACHE_BYTES + 1)),
8353			Err(Error::FrameTooLarge)
8354		));
8355		assert!(matches!(
8356			handle.poll_closed(&kio::Waiter::noop()),
8357			Poll::Ready(Err(Error::FrameTooLarge))
8358		));
8359	}
8360
8361	/// `closed` settles on a finish, and an abort after it only frees the cache: the
8362	/// outcome stays clean, a drained reader ends cleanly, and nothing records a cut.
8363	#[test]
8364	fn abort_after_finish_keeps_the_clean_outcome() {
8365		let mut producer = Info { start: 0 }.produce();
8366		let handle = producer.handle();
8367		let demand = producer.demand();
8368		let mut consumer = producer.consume();
8369		let waiter = kio::Waiter::noop();
8370		assert!(producer.poll_closed(&waiter).is_pending());
8371		assert!(demand.poll_closed(&waiter).is_pending());
8372
8373		producer
8374			.write_frame(Frame::new(Timestamp::ZERO, Bytes::from_static(b"a")))
8375			.unwrap();
8376		let producer = producer.finish().unwrap();
8377		assert!(matches!(handle.poll_closed(&waiter), Poll::Ready(Ok(()))));
8378		assert!(matches!(demand.poll_closed(&waiter), Poll::Ready(Ok(()))));
8379		assert!(
8380			handle.poll_aborted(&waiter).is_pending(),
8381			"a finish alone frees nothing"
8382		);
8383		assert!(matches!(consumer.poll_read_frame(&waiter), Poll::Ready(Ok(Some(_)))));
8384
8385		producer.abort(Error::Cancel).unwrap();
8386		assert!(matches!(handle.poll_closed(&waiter), Poll::Ready(Ok(()))));
8387		assert!(matches!(demand.poll_closed(&waiter), Poll::Ready(Ok(()))));
8388		assert!(matches!(handle.poll_aborted(&waiter), Poll::Ready(Error::Cancel)));
8389		assert!(handle.cut_error().is_none());
8390		assert!(!handle.fate().failed());
8391		assert!(matches!(consumer.poll_read_frame(&waiter), Poll::Ready(Ok(None))));
8392	}
8393
8394	/// An abort before the finish is the outcome, on every observer.
8395	#[test]
8396	fn abort_before_finish_is_the_outcome() {
8397		let producer = Info { start: 0 }.produce();
8398		let handle = producer.handle();
8399		let demand = producer.demand();
8400		producer.abort(Error::Timeout).unwrap();
8401		let waiter = kio::Waiter::noop();
8402		assert!(matches!(handle.poll_closed(&waiter), Poll::Ready(Err(Error::Timeout))));
8403		assert!(matches!(demand.poll_closed(&waiter), Poll::Ready(Err(Error::Timeout))));
8404	}
8405
8406	/// Completing a frame charges whatever it wrote since the last notify.
8407	#[test]
8408	fn frame_commit_charges_the_tail() {
8409		let pool = cache::Pool::unbounded();
8410		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
8411		let producer = Producer::new(Info { start: 0 }, track::Info::timed(), cache);
8412		let before = pool.used();
8413
8414		let observing = producer.handle();
8415		let mut frame = producer.create_frame(sized(300)).unwrap();
8416		frame.write(Bytes::from(vec![0u8; 100])).unwrap();
8417		frame.write_deferred(Bytes::from(vec![0u8; 200])).unwrap();
8418		let _producer = frame.finish().unwrap();
8419		assert_eq!(pool.used(), before + 300);
8420		assert_eq!(observing.state.read().cache, 300);
8421	}
8422
8423	/// Frames within their origin's budget allocate their declared size up front; past
8424	/// it, a frame's buffer holds only what has arrived. A frame hands its share back
8425	/// once it ends.
8426	#[test]
8427	fn frame_budget_bounds_upfront_allocation() {
8428		let budget = frame::Budget::new(1024);
8429		let pool = cache::Pool::unbounded();
8430		let group = |key| {
8431			let cache = cache::Track::new(pool.clone(), budget.clone(), Default::default(), kio::Weak::new());
8432			Producer::new(Info { start: key }, track::Info::timed(), cache)
8433		};
8434		let a = group(0);
8435		let b = group(1);
8436
8437		let mut first = a.create_frame(sized(1024)).unwrap();
8438		first.write(Bytes::from_static(b"x")).unwrap();
8439		assert_eq!(first.allocated(), 1024, "a frame within budget is allocated up front");
8440
8441		let mut second = b.create_frame(sized(MAX_CACHE_BYTES)).unwrap();
8442		second.write(Bytes::from(vec![0u8; 100])).unwrap();
8443		assert_eq!(
8444			second.allocated(),
8445			100,
8446			"a frame past budget allocated its declared size"
8447		);
8448		second.abort(Error::Cancel).unwrap();
8449
8450		first.write(Bytes::from(vec![0u8; 1023])).unwrap();
8451		let a = first.finish().unwrap();
8452		a.finish().unwrap();
8453
8454		let a = group(2);
8455		let mut third = a.create_frame(sized(1024)).unwrap();
8456		third.write(Bytes::from_static(b"x")).unwrap();
8457		assert_eq!(third.allocated(), 1024, "the finished frame did not return its share");
8458	}
8459
8460	/// A frame past one segment reserves and allocates a segment rather than its declared
8461	/// size, so a peer declaring the largest frame commits no more than a small one.
8462	#[test]
8463	fn a_large_frame_allocates_one_segment_ahead() {
8464		let budget = frame::Budget::new(2 * frame::SEGMENT);
8465		let pool = cache::Pool::unbounded();
8466		let group = |key| {
8467			let cache = cache::Track::new(pool.clone(), budget.clone(), Default::default(), kio::Weak::new());
8468			Producer::new(Info { start: key }, track::Info::timed(), cache)
8469		};
8470
8471		let frames: Vec<_> = (0..2)
8472			.map(|key| {
8473				let mut frame = group(key).create_frame(sized(MAX_CACHE_BYTES)).unwrap();
8474				frame.write(Bytes::from_static(b"x")).unwrap();
8475				frame
8476			})
8477			.collect();
8478		for frame in &frames {
8479			assert_eq!(frame.allocated(), frame::SEGMENT, "reserved other than one segment");
8480		}
8481	}
8482
8483	/// A prefetched batch mixing small and segmented frames hands each one out intact,
8484	/// whether it is read whole, streamed, or read as stored for the wire.
8485	#[test]
8486	#[cfg(feature = "async")]
8487	fn a_batch_mixes_segmented_frames() {
8488		let mut group = Info { start: 0 }.produce();
8489		let payloads: Vec<Bytes> = (0..Prefetch::CAP)
8490			.map(|i| match i % 2 {
8491				0 => Bytes::from(vec![i as u8; 3]),
8492				_ => Bytes::from(frame::pattern(i, 2 * frame::SEGMENT + 7)),
8493			})
8494			.collect();
8495		for payload in &payloads {
8496			let mut frame = group
8497				.create_frame(frame::Info {
8498					size: payload.len() as u64,
8499					timestamp: Timestamp::ZERO,
8500				})
8501				.unwrap();
8502			// Written in pieces, so the large ones chain.
8503			for piece in payload.chunks(300_000) {
8504				frame.write(payload.slice_ref(piece)).unwrap();
8505			}
8506			group = frame.finish().unwrap();
8507		}
8508		let group = group.finish().unwrap();
8509
8510		let mut whole = group.consume();
8511		for (i, payload) in payloads.iter().enumerate() {
8512			let frame = whole.read_frame().now_or_never().unwrap().unwrap().unwrap();
8513			assert_eq!(&frame.payload, payload, "whole frame {i}");
8514		}
8515
8516		// The first read prefetches the batch, so the streamed rest come out of it.
8517		let mut mixed = group.consume();
8518		mixed.read_frame().now_or_never().unwrap().unwrap().unwrap();
8519		for (i, payload) in payloads.iter().enumerate().skip(1) {
8520			let mut frame = mixed.next_frame().now_or_never().unwrap().unwrap().unwrap();
8521			let first = frame.read_chunk().now_or_never().unwrap().unwrap().unwrap();
8522			assert_eq!(
8523				first.len(),
8524				payload.len().min(frame::SEGMENT),
8525				"streamed frame {i} lost its segments"
8526			);
8527			let rest = frame.read_all().now_or_never().unwrap().unwrap();
8528			assert_eq!([first, rest].concat(), payload[..], "streamed frame {i}");
8529		}
8530
8531		let mut objects = group.consume();
8532		let waiter = kio::Waiter::noop();
8533		for (i, payload) in payloads.iter().enumerate() {
8534			let Poll::Ready(Ok(Some(object))) = objects.poll_read_object(&waiter) else {
8535				panic!("frame {i} is ready");
8536			};
8537			let chained = matches!(object.frame.payload, Payload::Chain(_));
8538			assert_eq!(chained, payload.len() > frame::SEGMENT, "stored frame {i}");
8539			assert_eq!(object.frame.payload.contiguous(0), payload, "stored frame {i}");
8540		}
8541	}
8542
8543	/// A repetitive frame DEFLATE shrinks, distinct per index.
8544	fn verbose(index: usize) -> Bytes {
8545		Bytes::from(format!("{index}:{}", "moq".repeat(300)))
8546	}
8547
8548	/// A scale-less frame of `size` bytes in group 0.
8549	fn untimed(size: usize) -> frame::Info {
8550		frame::Info {
8551			size: size as u64,
8552			timestamp: Timestamp::unscaled(0),
8553		}
8554	}
8555
8556	fn compressed_group(pool: &cache::Pool) -> Producer {
8557		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
8558		Producer::new(
8559			Info::from(0u64),
8560			track::Info::default().with_compression(crate::track::Compression::Deflate),
8561			cache,
8562		)
8563	}
8564
8565	fn read_plain(consumer: &mut Consumer) -> Result<Option<Bytes>> {
8566		match consumer.poll_read_frame(&kio::Waiter::noop()) {
8567			Poll::Ready(res) => res.map(|frame| frame.map(|frame| frame.payload)),
8568			Poll::Pending => panic!("the frame is ready"),
8569		}
8570	}
8571
8572	/// A compressed group sheds its stored slices like a plain one. Its plain copy inflates
8573	/// them first once a plain reader started, so that reader carries on past the shed
8574	/// front, and sheds its own front past the tail; a plain or raw reader that starts after
8575	/// frame 0 was shed gets `Evicted`.
8576	#[test]
8577	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
8578	#[cfg(feature = "async")]
8579	fn a_long_compressed_group_sheds_its_front() {
8580		let pool = cache::Pool::unbounded();
8581		let mut group = compressed_group(&pool);
8582		let mut plain = group.consume();
8583		let mut raw = group.consume().compressed();
8584
8585		let frames = mebibytes(80);
8586		group
8587			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), frames[0].clone()))
8588			.unwrap();
8589		assert_eq!(read_plain(&mut plain).unwrap().unwrap(), frames[0]);
8590		// 34 frames behind, past the stored tail but within the inflated one: the slices it
8591		// needs inflate before they go.
8592		for frame in &frames[1..35] {
8593			group
8594				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), frame.clone()))
8595				.unwrap();
8596		}
8597		for (index, frame) in frames.iter().enumerate().skip(35) {
8598			group
8599				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), frame.clone()))
8600				.unwrap();
8601			let read = read_plain(&mut plain).unwrap().unwrap();
8602			assert_eq!(read, frames[index - 34], "frame {}", index - 34);
8603			assert!(pool.used() <= 3 * MAX_CACHE_BYTES, "{} bytes held", pool.used());
8604		}
8605		assert!(group.handle.state.read().held() > 1, "the slices were shed");
8606
8607		let mut late = group.consume();
8608		assert!(matches!(read_plain(&mut late), Err(Error::Evicted)));
8609		assert!(matches!(raw.read_frame().now_or_never().unwrap(), Err(Error::Evicted)));
8610	}
8611
8612	/// A compressed copy that shed its front slices before any plain read inflated them
8613	/// continues no plain reader, even past them: inflating its frame needs them. A raw
8614	/// reader takes the stored slice.
8615	#[test]
8616	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
8617	#[cfg(feature = "async")]
8618	fn a_copy_shed_before_inflating_continues_no_plain_reader() {
8619		let pool = cache::Pool::unbounded();
8620		let mut group = compressed_group(&pool);
8621		for frame in &mebibytes(40) {
8622			group
8623				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), frame.clone()))
8624				.unwrap();
8625		}
8626		let held = group.handle.state.read().held();
8627		assert!(held > 1, "the slices were shed");
8628		let copy = group.consume();
8629		let mut plain = group.consume();
8630		plain.skip_to(held as u64);
8631		assert!(!copy.continues(&plain, held));
8632		assert!(
8633			matches!(read_plain(&mut plain), Err(Error::Evicted)),
8634			"inflating needs them"
8635		);
8636		assert!(copy.continues(&group.consume().compressed(), held));
8637	}
8638
8639	/// The inflated copy charges each frame's slot, so empty frames count toward its tail.
8640	#[test]
8641	#[cfg(feature = "async")]
8642	fn the_inflated_copy_charges_its_slots() {
8643		let pool = cache::Pool::unbounded();
8644		let mut group = compressed_group(&pool);
8645		let mut plain = group.consume();
8646		for _ in 0..1_000 {
8647			group
8648				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), Bytes::new()))
8649				.unwrap();
8650			assert!(read_plain(&mut plain).unwrap().unwrap().is_empty());
8651		}
8652		let flate = group.handle.state.read().flate.as_ref().unwrap().plain.clone();
8653		assert!(flate.lock().bytes >= 1_000 * size_of::<Entry>() as u64);
8654	}
8655
8656	/// A group of four frames whose slices are all inflated, with the pace each frame ends at.
8657	/// No reader took any, so nothing is owed to the pace yet.
8658	#[cfg(feature = "async")]
8659	fn inflated_group(pool: &cache::Pool) -> (Producer, Arc<Plain>, Vec<u64>) {
8660		let mut group = compressed_group(pool);
8661		for index in 0..4 {
8662			group
8663				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(index)))
8664				.unwrap();
8665		}
8666		take_slices(&group.handle, 3).run(&stats::Meter::default());
8667		let state = group.handle.state.read();
8668		let ends = (0..4).map(|index| state.entry(index).unwrap().end).collect();
8669		let copy = state.flate.as_ref().unwrap().plain.clone();
8670		drop(state);
8671		assert_eq!(copy.len.load(Ordering::Acquire), 4, "every slice inflated");
8672		(group, copy, ends)
8673	}
8674
8675	/// A taken-frame shed drops the inflated frames of the slices a reader took along with the
8676	/// slices, and stops at the first frame that reader has yet to take.
8677	#[test]
8678	#[cfg(feature = "async")]
8679	fn a_taken_shed_drops_the_inflated_frames_a_reader_took() {
8680		let pool = cache::Pool::unbounded();
8681		let (group, plain, ends) = inflated_group(&pool);
8682		let billed = plain.bill.size();
8683		// Frames 0 and 1 are all that is held of the slices, as after a long group's tail shed.
8684		group.handle.state.write().ok().unwrap().shed_frames(2, true);
8685		group.handle.state.read().pace.took(ends[0]);
8686
8687		group.handle.shed_taken();
8688		assert_eq!(plain.lock().base, 1, "only the frame its reader took went");
8689		assert!(plain.bill.size() < billed, "the inflated frame was billed");
8690		assert_eq!(plain.get(1).unwrap(), verbose(1), "an owed frame stayed");
8691
8692		group.handle.state.read().pace.took(ends[3]);
8693		group.handle.shed_taken();
8694		let state = plain.lock();
8695		assert_eq!(
8696			(state.base, state.frames.len()),
8697			(4, 0),
8698			"every frame a reader took went"
8699		);
8700		assert_eq!(state.bytes, 0);
8701		drop(state);
8702		assert!(matches!(plain.get(0), Err(Error::Evicted)));
8703		assert_eq!(group.handle.state.read().held(), 4, "the slices went too");
8704	}
8705
8706	/// A copy whose content other copies share leaves the inflated frames alone: a sibling's
8707	/// reader, on its own pace scale, may still be owed them, and cannot inflate them again.
8708	#[test]
8709	#[cfg(feature = "async")]
8710	fn a_taken_shed_leaves_inflated_frames_shared_content_holds() {
8711		let pool = cache::Pool::unbounded();
8712		let (group, plain, ends) = inflated_group(&pool);
8713		group.handle.activate_content().unwrap().unwrap();
8714		group.handle.state.read().pace.took(ends[3]);
8715
8716		group.handle.shed_taken();
8717		assert_eq!(plain.lock().base, 0, "a shared inflated copy was shed");
8718		assert_eq!(group.handle.state.read().held(), 4, "the slices still went");
8719	}
8720
8721	/// Once a job that pinned frames from a reclaim is done, the edge lists again for them, even
8722	/// when every slice they came from is shed and its reader's progress shows nothing new.
8723	#[test]
8724	#[cfg(feature = "async")]
8725	fn a_finished_job_relists_the_frames_it_pinned() {
8726		let pool = cache::Pool::unbounded();
8727		let cache = cache::Track::new(
8728			pool.clone(),
8729			Default::default(),
8730			cache::Edges::new(Some(1 << 30)),
8731			kio::Weak::new(),
8732		);
8733		let mut group = Producer::new(
8734			Info::from(0u64),
8735			track::Info::default().with_compression(crate::track::Compression::Deflate),
8736			cache.clone(),
8737		);
8738		for index in 0..4 {
8739			group
8740				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(index)))
8741				.unwrap();
8742		}
8743		// Inflated without telling the session, so only the job's drop can list the edge.
8744		take_slices(&group.handle, 3).inflate(&stats::Meter::default());
8745		let end = group.handle.state.read().entry(3).unwrap().end;
8746		// Taken before the copy is the live edge, so it lists nothing; a reclaim that visited
8747		// it meanwhile would have left it unlisted the same way.
8748		group.handle.state.read().pace.took(end);
8749		group.handle.state.write().ok().unwrap().charge.promote();
8750		assert!(!cache.listed());
8751
8752		let job = take_slices(&group.handle, 2);
8753		assert!(!cache.listed(), "a job in flight listed the edge");
8754		drop(job);
8755		assert!(cache.listed(), "the pinned frames went unreported");
8756	}
8757
8758	/// A taken-frame shed never passes the frames an inflate job in flight has yet to take: the
8759	/// job reads them back once the group's guard is released, after its slices were counted
8760	/// taken, and a later reader reaches the rest only once the job is done.
8761	#[test]
8762	#[cfg(feature = "async")]
8763	fn a_taken_shed_leaves_the_frames_of_a_job_in_flight() {
8764		let pool = cache::Pool::unbounded();
8765		let (group, plain, ends) = inflated_group(&pool);
8766		let job = take_slices(&group.handle, 2);
8767		group.handle.state.read().pace.took(ends[3]);
8768
8769		group.handle.shed_taken();
8770		assert_eq!(plain.lock().base, 2, "a frame the job needs went");
8771		job.run(&stats::Meter::default());
8772		assert_eq!(job.get(2).unwrap(), verbose(2));
8773		assert_eq!(job.get(3).unwrap(), verbose(3));
8774
8775		drop(job);
8776		group.handle.shed_taken();
8777		assert_eq!(plain.lock().base, 4, "the finished job still pinned its frames");
8778	}
8779
8780	/// A batch of large frames that deflate to almost nothing stays within one tail of
8781	/// inflated bytes, and the copy sheds what the reader took past its tail.
8782	#[test]
8783	#[cfg_attr(miri, ignore = "fills the 32 MiB group tail, past Miri's 15-minute cap")]
8784	#[cfg(feature = "async")]
8785	fn a_batch_of_large_compressible_frames_stays_in_the_tail() {
8786		let pool = cache::Pool::unbounded();
8787		let mut group = compressed_group(&pool);
8788		let frame = Bytes::from(vec![7u8; 31 << 20]);
8789		for _ in 0..8 {
8790			group
8791				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), frame.clone()))
8792				.unwrap();
8793		}
8794		let group = group.finish().unwrap();
8795		let mut plain = group.consume();
8796		for _ in 0..8 {
8797			assert_eq!(read_plain(&mut plain).unwrap().unwrap(), frame);
8798		}
8799		drop(plain);
8800		let flate = group.handle.state.read().flate.as_ref().unwrap().plain.clone();
8801		assert!(
8802			flate.lock().bytes <= MAX_CACHE_BYTES,
8803			"{} inflated bytes held",
8804			flate.lock().bytes
8805		);
8806	}
8807
8808	/// Every group starts cold even when a finished encoder is reused. Open groups
8809	/// keep independent windows, and aborting one does not consume another's spare.
8810	#[test]
8811	#[cfg(feature = "async")]
8812	fn reused_encoders_start_independent_group_streams() {
8813		let pool = cache::Pool::unbounded();
8814		let account = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
8815		let info = track::Info::default().with_compression(crate::track::Compression::Deflate);
8816		let mut concurrent = Producer::new(0u64.into(), info.clone(), account.clone());
8817		concurrent
8818			.write_frame(Frame::new(crate::Timestamp::unscaled(concurrent.start), verbose(0)))
8819			.unwrap();
8820		for key in 1..5u64 {
8821			let mut group = Producer::new(key.into(), info.clone(), account.clone());
8822			let mut reference = flate::Encoder::new();
8823			let frames = [verbose(0), Bytes::new(), verbose(key as usize)];
8824			let slices: Vec<_> = frames.iter().map(|frame| reference.frame(frame)).collect();
8825			for frame in &frames {
8826				group
8827					.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), frame.clone()))
8828					.unwrap();
8829			}
8830			let group = group.finish().unwrap();
8831			let mut raw = group.consume().compressed();
8832			let mut decoder = flate::Decoder::new();
8833			for (frame, expected) in frames.iter().zip(&slices) {
8834				let Poll::Ready(Ok(Some(object))) = raw.poll_read_object(&kio::Waiter::noop()) else {
8835					panic!("a stored slice is ready");
8836				};
8837				let slice = object.frame.payload.contiguous(0);
8838				assert_eq!(slice, *expected, "reuse must emit a cold stream");
8839				assert_eq!(decoder.frame(&slice, frame.len()).unwrap(), *frame);
8840			}
8841		}
8842		concurrent
8843			.write_frame(Frame::new(crate::Timestamp::unscaled(concurrent.start), verbose(1)))
8844			.unwrap();
8845		let mut reader = concurrent.consume();
8846		assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(0));
8847		assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(1));
8848		concurrent.abort(Error::Cancel).unwrap();
8849		drop(reader);
8850		assert_eq!(pool.used(), flate::ENCODER_HEAP, "the spare survives a sibling's abort");
8851		drop(account);
8852		assert_eq!(pool.used(), 0);
8853	}
8854
8855	/// A compressed group stores DEFLATE slices, hands plain readers the frames as written
8856	/// from one shared inflated copy, and hands egress the slices with their sizes.
8857	#[test]
8858	#[cfg(feature = "async")]
8859	fn compressed_group_stores_slices_and_inflates_once() {
8860		let pool = cache::Pool::unbounded();
8861		let mut group = compressed_group(&pool);
8862		group
8863			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(0)))
8864			.unwrap();
8865		// A chunked frame is invisible until its last chunk, then compressed whole.
8866		let mut frame = group.create_frame(untimed(verbose(1).len())).unwrap();
8867		for chunk in verbose(1).chunks(100) {
8868			frame.write(Bytes::copy_from_slice(chunk)).unwrap();
8869		}
8870		group = frame.finish().unwrap();
8871		group
8872			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(2)))
8873			.unwrap();
8874		let group = group.finish().unwrap();
8875
8876		let plain: usize = (0..3).map(|index| verbose(index).len()).sum();
8877		let stored = pool.used();
8878		let uncompressed = cache::Pool::unbounded();
8879		let mut reference = Producer::new(
8880			Info::from(0u64),
8881			track::Info::default(),
8882			cache::Track::new(
8883				uncompressed.clone(),
8884				Default::default(),
8885				Default::default(),
8886				kio::Weak::new(),
8887			),
8888		);
8889		for index in 0..3 {
8890			reference
8891				.write_frame(Frame::new(crate::Timestamp::unscaled(reference.start), verbose(index)))
8892				.unwrap();
8893		}
8894		let _reference = reference.finish().unwrap();
8895		assert!(
8896			stored - flate::ENCODER_HEAP + (plain as u64) / 2 < uncompressed.used(),
8897			"slices are stored: {stored} against {}",
8898			uncompressed.used()
8899		);
8900
8901		let mut first = group.consume();
8902		let mut second = group.consume();
8903		for index in 0..3 {
8904			assert_eq!(
8905				read_plain(&mut first).unwrap().unwrap(),
8906				verbose(index),
8907				"frame {index}"
8908			);
8909		}
8910		let inflated = pool.used();
8911		assert!(inflated >= stored + plain as u64, "the inflated copy is billed");
8912		for index in 0..3 {
8913			assert_eq!(
8914				read_plain(&mut second).unwrap().unwrap(),
8915				verbose(index),
8916				"frame {index}"
8917			);
8918		}
8919		assert_eq!(pool.used(), inflated, "a second reader shares the inflated copy");
8920		assert!(read_plain(&mut first).unwrap().is_none());
8921
8922		let mut raw = group.consume().compressed();
8923		let mut decoder = flate::Decoder::new();
8924		for index in 0..3 {
8925			let Poll::Ready(Ok(Some(object))) = raw.poll_read_object(&kio::Waiter::noop()) else {
8926				panic!("frame {index} is ready");
8927			};
8928			let size = object.inflated.expect("a stored slice carries its size");
8929			assert_eq!(size, verbose(index).len() as u64);
8930			let frame = decoder
8931				.frame(&object.frame.payload.contiguous(0), size as usize)
8932				.unwrap();
8933			assert_eq!(frame, verbose(index), "slice {index}");
8934		}
8935
8936		drop((first, second, raw));
8937		drop(group);
8938		assert_eq!(pool.used(), 0, "the inflated copy is released with the group");
8939	}
8940
8941	/// A compressed successor adopts a failed compressed copy's slices with their inflated
8942	/// sizes, so its plain readers inflate the group from its first frame; a plain head is
8943	/// not its form and stays out.
8944	#[test]
8945	#[cfg(feature = "async")]
8946	fn a_compressed_group_adopts_a_compressed_head() {
8947		let pool = cache::Pool::unbounded();
8948		let fail = |group: &mut Producer| {
8949			group
8950				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(0)))
8951				.unwrap();
8952			group
8953				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(1)))
8954				.unwrap();
8955			let handoff = group.consume().handoff();
8956			group.handle().abort(Error::Cancel).unwrap();
8957			handoff.head().expect("held for its resumers")
8958		};
8959		let successor = || {
8960			let mut group = compressed_group(&pool);
8961			group.start_at(2).unwrap();
8962			group
8963		};
8964
8965		let plain = fail(&mut Producer::new(
8966			Info::from(0u64),
8967			track::Info::default(),
8968			cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new()),
8969		));
8970		let refused = successor();
8971		refused.handle.adopt_head(&plain);
8972		assert_eq!(refused.handle.state.read().offset, 2, "a plain head stays out");
8973
8974		let head = fail(&mut compressed_group(&pool));
8975		let group = successor();
8976		group.handle.adopt_head(&head);
8977		let group = group.finish().unwrap();
8978		let mut reader = group.consume();
8979		for index in 0..2 {
8980			assert_eq!(
8981				read_plain(&mut reader).unwrap().unwrap(),
8982				verbose(index),
8983				"frame {index}"
8984			);
8985		}
8986		assert!(read_plain(&mut reader).unwrap().is_none());
8987	}
8988
8989	/// The slices a plain read up to local frame `last` takes under the group's guard.
8990	fn take_slices(group: &Handle, last: usize) -> Inflate {
8991		let state = group.state.read();
8992		state.inflate(state.flate.as_ref().unwrap(), last, last).unwrap()
8993	}
8994
8995	/// Plain readers inflate with the group's guard released, into one shared copy: a reader
8996	/// that took the same slices skips what another inflated, the bytes count toward the
8997	/// group's eviction size and the inflating reader's stats once, and a reader that took
8998	/// its slices before a release bills nothing after it.
8999	#[test]
9000	#[cfg(feature = "async")]
9001	fn inflation_is_shared_and_stops_at_release() {
9002		let registry = stats::Registry::new(stats::Config::new());
9003		let meter = registry.publisher_meter(crate::Path::from_static("demo"), &stats::Tier::default());
9004		let inflated = || {
9005			registry
9006				.snapshot()
9007				.traffic()
9008				.into_iter()
9009				.find(|(_, role, _)| *role == stats::Role::Publisher)
9010				.map_or(0, |(_, _, traffic)| traffic.inflated)
9011		};
9012		let plain: u64 = (0..3).map(|index| verbose(index).len() as u64).sum();
9013		let pool = cache::Pool::unbounded();
9014		let write = || {
9015			let mut group = compressed_group(&pool);
9016			for index in 0..3 {
9017				group
9018					.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(index)))
9019					.unwrap();
9020			}
9021			group.finish().unwrap()
9022		};
9023
9024		let group = write();
9025		let (stored, used) = (group.handle.cache_size(), pool.used());
9026		let (first, second) = (take_slices(&group.handle, 2), take_slices(&group.handle, 2));
9027		first.run(&meter);
9028		// The inflated copy bills each frame's slot beside its bytes.
9029		let copy = plain + 3 * size_of::<Entry>() as u64;
9030		assert_eq!(
9031			group.handle.cache_size(),
9032			stored + copy,
9033			"the copy counts toward eviction once built"
9034		);
9035		assert_eq!(pool.used(), used + copy);
9036		second.run(&meter);
9037		assert_eq!(
9038			group.handle.cache_size(),
9039			stored + copy,
9040			"the second reader inflates nothing"
9041		);
9042		assert_eq!(second.get(1).unwrap(), verbose(1));
9043		assert_eq!(inflated(), plain, "each inflated byte counts once");
9044
9045		let group = write();
9046		let late = take_slices(&group.handle, 1);
9047		group.handle().abort(Error::Evicted).unwrap();
9048		let used = pool.used();
9049		late.run(&meter);
9050		assert!(matches!(late.get(0), Err(Error::Evicted)));
9051		assert_eq!(pool.used(), used, "a late inflater bills nothing past the release");
9052		assert_eq!(inflated(), plain);
9053		// A job belongs to its delivery even when another copy keeps the canonical
9054		// inflated cache alive. Releasing one must not make its pending read succeed.
9055		let cache = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
9056		let info = track::Info::default().with_compression(crate::track::Compression::Deflate);
9057		let mut released = Producer::new(Info::from(0u64), info.clone(), cache.clone());
9058		released.bound(Bounds { start: 0, end: Some(2) }).unwrap();
9059		for index in 0..2 {
9060			released
9061				.write_frame(Frame::new(crate::Timestamp::unscaled(released.start), verbose(index)))
9062				.unwrap();
9063		}
9064		let released = released.finish().unwrap();
9065		let content = released.handle.activate_content().unwrap().unwrap();
9066		let mut survivor = Producer::new(Info::from(0u64), info, cache);
9067		survivor.handle.share_content(content);
9068		for index in 0..3 {
9069			survivor
9070				.write_frame(Frame::new(crate::Timestamp::unscaled(survivor.start), verbose(index)))
9071				.unwrap();
9072		}
9073		let survivor = survivor.finish().unwrap();
9074		let late = take_slices(&released.handle, 1);
9075		released.handle().abort(Error::Evicted).unwrap();
9076		let used = pool.used();
9077		late.run(&stats::Meter::default());
9078		assert!(
9079			matches!(late.get(0), Err(Error::Evicted)),
9080			"a released delivery cannot read through another copy's inflation"
9081		);
9082		assert_eq!(pool.used(), used, "a released job creates no inflation charge");
9083		let mut reader = survivor.consume();
9084		for index in 0..3 {
9085			assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(index));
9086		}
9087		assert!(
9088			matches!(late.get(0), Err(Error::Evicted)),
9089			"the other copy's completion cannot revive this read"
9090		);
9091	}
9092
9093	/// A compressed group meters `bytes` as stored, whether a frame is written whole, in a
9094	/// batch, or in chunks.
9095	#[test]
9096	#[cfg(feature = "async")]
9097	fn compressed_writes_meter_the_stored_bytes() {
9098		let registry = stats::Registry::new(stats::Config::new());
9099		let metered = || {
9100			registry
9101				.snapshot()
9102				.traffic()
9103				.into_iter()
9104				.find(|(_, role, _)| *role == stats::Role::Publisher)
9105				.map_or(0, |(_, _, traffic)| traffic.bytes)
9106		};
9107		let pool = cache::Pool::unbounded();
9108		let meter = registry.publisher_meter(crate::Path::from_static("demo"), &stats::Tier::default());
9109		let mut group = compressed_group(&pool).with_meter(meter);
9110
9111		group
9112			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(0)))
9113			.unwrap();
9114		let mut batch = frame::Buffer::<2>::new();
9115		for index in 1..3 {
9116			batch.push(Frame::new(Timestamp::unscaled(0), verbose(index))).unwrap();
9117		}
9118		group.write_frames(&mut batch).unwrap();
9119		let mut frame = group.create_frame(untimed(verbose(3).len())).unwrap();
9120		for chunk in verbose(3).chunks(100) {
9121			frame.write(Bytes::copy_from_slice(chunk)).unwrap();
9122		}
9123		group = frame.finish().unwrap();
9124		let group = group.finish().unwrap();
9125
9126		let stored: u64 = (group.handle.state.read().entries(0, usize::MAX))
9127			.map(|entry| entry.frame.payload.len() as u64)
9128			.sum();
9129		let plain: u64 = (0..4).map(|index| verbose(index).len() as u64).sum();
9130		assert!(stored < plain, "the frames compressed");
9131		assert_eq!(metered(), stored);
9132	}
9133
9134	/// Shedding every inflated frame frees the deque that held them, keeping the decoder
9135	/// for the frames still to come.
9136	#[test]
9137	#[cfg(feature = "async")]
9138	fn shedding_every_inflated_frame_frees_its_slots() {
9139		let pool = cache::Pool::unbounded();
9140		let mut group = compressed_group(&pool);
9141		for index in 0..2 {
9142			group
9143				.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(index)))
9144				.unwrap();
9145		}
9146		let mut reader = group.consume();
9147		assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(0));
9148		let plain = group.handle.state.read().flate.as_ref().unwrap().plain.clone();
9149		assert!(plain.lock().frames.capacity() > 0);
9150
9151		group.handle.shed_all();
9152		assert_eq!(plain.lock().frames.capacity(), 0);
9153		assert!(plain.lock().decoder.is_some(), "the open group still decodes");
9154	}
9155
9156	/// Shedding an adopted head frees the slots it was billed by capacity, empty frames too.
9157	#[test]
9158	fn shedding_an_adopted_head_frees_its_slots() {
9159		let pool = cache::Pool::unbounded();
9160		let cache = cache::Track::new(pool, Default::default(), Default::default(), kio::Weak::new());
9161		let mut tail = Producer::new(Info::from(0u64), track::Info::default(), cache);
9162		tail.start_at(64).unwrap();
9163		let adopter = tail.handle();
9164		let entry = Entry::plain(Frame::new(Timestamp::unscaled(0), Bytes::new()).into(), 0);
9165		let head = Head {
9166			content: None,
9167			start: 0,
9168			first_object: true,
9169			entries: vec![entry; 64],
9170			compressed: false,
9171			meta: false,
9172		};
9173		let before = adopter.state.read().charge.size();
9174		adopter.adopt_head(&head);
9175		assert_eq!(adopter.state.read().offset, 0, "the head was adopted");
9176		assert!(adopter.state.read().charge.size() > before);
9177
9178		adopter.shed_all();
9179		assert_eq!(adopter.state.read().front.capacity(), 0);
9180		assert_eq!(adopter.state.read().charge.size(), before);
9181		drop(tail);
9182	}
9183
9184	/// The codec state counts toward the pool while it lives: the encoder moves to its
9185	/// track when the group finishes, and a decoder drops when the last frame inflates.
9186	#[test]
9187	#[cfg(feature = "async")]
9188	fn codec_state_is_billed_while_held() {
9189		let pool = cache::Pool::unbounded();
9190		let mut group = compressed_group(&pool);
9191		group
9192			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(0)))
9193			.unwrap();
9194		let stored = group.handle.state.read().charge.size() + Flate::RELEASE_HEAP;
9195		assert_eq!(group.handle.cache_size(), stored + flate::ENCODER_HEAP);
9196		group
9197			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(1)))
9198			.unwrap();
9199
9200		// The read inflates both frames ahead, but the open group may still get a third.
9201		let mut reader = group.consume();
9202		assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(0));
9203		// The inflated copy bills each frame's slot beside its bytes.
9204		let inflated = (verbose(0).len() + verbose(1).len() + 2 * size_of::<Entry>()) as u64;
9205		let stored = group.handle.state.read().charge.size() + Flate::RELEASE_HEAP;
9206		let held = stored + flate::ENCODER_HEAP + flate::DECODER_HEAP + inflated;
9207		assert_eq!(group.handle.cache_size(), held, "an open group keeps both");
9208
9209		let group = group.finish().unwrap();
9210		assert_eq!(
9211			group.handle.cache_size(),
9212			stored + inflated,
9213			"finishing releases both from the group"
9214		);
9215		assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(1));
9216
9217		// A finished group's decoder goes with the last frame it inflates.
9218		let mut group = compressed_group(&pool);
9219		group
9220			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(0)))
9221			.unwrap();
9222		let mut reader = group.consume();
9223		assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(0));
9224		group
9225			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(1)))
9226			.unwrap();
9227		let group = group.finish().unwrap();
9228		let stored = group.handle.state.read().charge.size() + Flate::RELEASE_HEAP;
9229		assert_eq!(read_plain(&mut reader).unwrap().unwrap(), verbose(1));
9230		assert_eq!(group.handle.cache_size(), stored + inflated);
9231
9232		// So does one whose reader took the last slice before the group finished.
9233		let mut group = compressed_group(&pool);
9234		group
9235			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(0)))
9236			.unwrap();
9237		group
9238			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(1)))
9239			.unwrap();
9240		let job = take_slices(&group.handle, 1);
9241		let group = group.finish().unwrap();
9242		job.run(&stats::Meter::default());
9243		let stored = group.handle.state.read().charge.size() + Flate::RELEASE_HEAP;
9244		assert_eq!(group.handle.cache_size(), stored + inflated, "the decoder is dropped");
9245	}
9246
9247	/// A plain read of a compressed group that started past frame 0 lags on every read,
9248	/// never handing out the stored slices it cannot inflate.
9249	#[test]
9250	fn a_plain_read_past_frame_zero_lags() {
9251		let pool = cache::Pool::unbounded();
9252		let mut group = compressed_group(&pool);
9253		group.start_at(1).unwrap();
9254		group
9255			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(1)))
9256			.unwrap();
9257		let group = group.finish().unwrap();
9258
9259		let mut consumer = group.consume().with_range(1..);
9260		assert!(matches!(read_plain(&mut consumer), Err(Error::Lagged)));
9261		assert!(matches!(read_plain(&mut consumer), Err(Error::Lagged)));
9262	}
9263
9264	/// A conflict with shared content fails the whole group, including when a batch's
9265	/// prefix matched. A compressed copy cannot continue with its advanced encoder.
9266	#[test]
9267	fn a_refused_shared_write_fails_the_group() {
9268		for compression in [crate::track::Compression::None, crate::track::Compression::Deflate] {
9269			let cache = cache::Track::new(
9270				cache::Pool::unbounded(),
9271				Default::default(),
9272				Default::default(),
9273				kio::Weak::new(),
9274			);
9275			let info = track::Info::default().with_compression(compression);
9276			let mut first = Producer::new(Info::from(0u64), info.clone(), cache.clone());
9277			first
9278				.write_frame(Frame::new(crate::Timestamp::unscaled(first.start), verbose(0)))
9279				.unwrap();
9280			first
9281				.write_frame(Frame::new(crate::Timestamp::unscaled(first.start), verbose(1)))
9282				.unwrap();
9283			let content = first.handle.activate_content().unwrap().unwrap();
9284			let copy = || {
9285				let copy = Producer::new(Info::from(0u64), info.clone(), cache.clone());
9286				copy.handle.share_content(content.clone());
9287				copy
9288			};
9289
9290			let mut whole = copy();
9291			assert!(matches!(
9292				whole.write_frame(Frame::new(crate::Timestamp::unscaled(whole.start), verbose(10))),
9293				Err(Error::ProtocolViolation)
9294			));
9295			assert!(whole.handle.is_aborted());
9296
9297			let mut batch = copy();
9298			let mut frames = frame::Buffer::<2>::new();
9299			frames.push(Frame::new(Timestamp::unscaled(0), verbose(0))).unwrap();
9300			frames.push(Frame::new(Timestamp::unscaled(0), verbose(10))).unwrap();
9301			assert!(matches!(batch.write_frames(&mut frames), Err(Error::ProtocolViolation)));
9302			assert!(batch.handle.is_aborted());
9303		}
9304	}
9305
9306	/// A received slice that inflates to other than its declared size fails the read.
9307	#[test]
9308	fn a_received_size_mismatch_fails_the_read() {
9309		let pool = cache::Pool::unbounded();
9310		let group = compressed_group(&pool);
9311		let slice = flate::Encoder::new().frame(&verbose(0));
9312		let header = frame::Header {
9313			info: untimed(slice.len()),
9314			fields: None,
9315			inflated: Some(verbose(0).len() as u64 + 1),
9316		};
9317		let mut frame = group.create_object(header).unwrap();
9318		frame.write(slice).unwrap();
9319		let group = frame.finish().unwrap();
9320		let group = group.finish().unwrap();
9321
9322		assert!(matches!(read_plain(&mut group.consume()), Err(Error::WrongSize)));
9323	}
9324
9325	/// A declared inflated size past the cache budget is refused before anything inflates,
9326	/// and only a compressed track takes one.
9327	#[test]
9328	fn an_inflated_size_is_checked_on_open() {
9329		let header = |inflated| frame::Header {
9330			info: untimed(1),
9331			fields: None,
9332			inflated: Some(inflated),
9333		};
9334		let pool = cache::Pool::unbounded();
9335		let res = compressed_group(&pool).create_object(header(MAX_CACHE_BYTES + 1));
9336		assert!(matches!(res, Err(Error::FrameTooLarge)));
9337
9338		let res = Info::from(0u64).produce_untimed().create_object(header(1));
9339		assert!(matches!(res, Err(Error::ProtocolViolation)));
9340	}
9341
9342	/// A budget that gives up exactly when the test says so, waking the reads it judged as
9343	/// a real budget does.
9344	#[derive(Clone, Default)]
9345	struct Switch(Arc<(AtomicBool, Mutex<kio::WaiterList>)>);
9346
9347	impl Switch {
9348		fn set(&self, expired: bool) {
9349			self.0.0.store(expired, Ordering::Relaxed);
9350			self.0.1.lock().unwrap().wake();
9351		}
9352	}
9353
9354	impl Expiry for Switch {
9355		fn is_expired(
9356			&self,
9357			_: Option<&crate::model::resume::Recover>,
9358			waiter: &kio::Waiter,
9359		) -> Option<std::time::Duration> {
9360			waiter.register(&mut self.0.1.lock().unwrap());
9361			self.0.0.load(Ordering::Relaxed).then_some(std::time::Duration::ZERO)
9362		}
9363
9364		fn aged(
9365			&self,
9366			_: std::time::Duration,
9367			recover: Option<&crate::model::resume::Recover>,
9368			waiter: &kio::Waiter,
9369		) -> bool {
9370			self.is_expired(recover, waiter).is_some()
9371		}
9372
9373		fn for_track(&self, _: &track::Consumer) -> Arc<dyn Expiry> {
9374			Arc::new(self.clone())
9375		}
9376
9377		fn asking(&self) -> crate::model::track::Asking {
9378			crate::model::track::Asking {
9379				priority: 0,
9380				order: crate::model::subscription::Order::Ascending,
9381			}
9382		}
9383	}
9384
9385	/// A reader that took every frame of an unfinished group still fails with `Old` when
9386	/// the budget gives up: the producer never finished it, so a clean end would pass the
9387	/// prefix off as the whole group.
9388	#[test]
9389	fn a_drained_unfinished_group_expires_as_old() {
9390		let mut producer = Info { start: 0 }.produce();
9391		producer
9392			.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(b"a")))
9393			.unwrap();
9394
9395		let expired = Switch::default();
9396		let mut group = producer.consume().with_expiry(Arc::new(expired.clone()));
9397		let waiter = kio::Waiter::noop();
9398		assert!(matches!(group.poll_read_frame(&waiter), Poll::Ready(Ok(Some(_)))));
9399		assert!(group.poll_read_frame(&waiter).is_pending(), "parked at the tail");
9400		assert!(group.poll_read_frame(&waiter).is_pending(), "and parks again");
9401
9402		expired.set(true);
9403		let mut next = group.clone();
9404		let mut finished = group.clone();
9405		assert!(matches!(group.poll_read_frame(&waiter), Poll::Ready(Err(Error::Old))));
9406		assert!(
9407			matches!(group.poll_read_frame(&waiter), Poll::Ready(Err(Error::Old))),
9408			"and stays failed when probed again"
9409		);
9410		assert!(matches!(next.poll_next_frame(&waiter), Poll::Ready(Err(Error::Old))));
9411		assert!(matches!(finished.poll_finished(&waiter), Poll::Ready(Err(Error::Old))));
9412	}
9413
9414	/// Records a wake.
9415	#[derive(Default)]
9416	struct Woken(AtomicBool);
9417
9418	impl std::task::Wake for Woken {
9419		fn wake(self: Arc<Self>) {
9420			self.0.store(true, Ordering::Relaxed);
9421		}
9422	}
9423
9424	impl Woken {
9425		fn take(&self) -> bool {
9426			self.0.swap(false, Ordering::Relaxed)
9427		}
9428	}
9429
9430	/// A frame read that found nothing parks again at once until the group changes, but
9431	/// parks anew for another task, which the next frame then wakes instead.
9432	#[test]
9433	fn an_idle_frame_read_parks_for_the_task_polling_it() {
9434		let mut producer = Info { start: 0 }.produce();
9435		producer
9436			.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(b"a")))
9437			.unwrap();
9438		let mut group = producer.consume();
9439		let first = Arc::new(Woken::default());
9440		let waiter = kio::Waiter::new(first.clone().into());
9441		assert!(matches!(group.poll_read_frame(&waiter), Poll::Ready(Ok(Some(_)))));
9442		for _ in 0..3 {
9443			assert!(group.poll_read_frame(&waiter).is_pending(), "nothing fired");
9444		}
9445		assert!(!first.take());
9446
9447		let other = Arc::new(Woken::default());
9448		let moved = kio::Waiter::new(other.clone().into());
9449		assert!(group.poll_read_frame(&moved).is_pending());
9450		producer
9451			.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(b"b")))
9452			.unwrap();
9453		assert!(other.take(), "the next frame wakes the task that polled last");
9454		assert!(matches!(group.poll_read_frame(&moved), Poll::Ready(Ok(Some(_)))));
9455	}
9456
9457	/// A read that parks once and is then woken by its next frame never sets up a gate.
9458	#[test]
9459	fn a_read_woken_by_its_frame_takes_no_gate() {
9460		let mut producer = Info { start: 0 }.produce();
9461		let mut group = producer.consume();
9462		let waiter = kio::Waiter::new(Arc::new(Woken::default()).into());
9463		for payload in [b"a", b"b", b"c"] {
9464			assert!(group.poll_read_frame(&waiter).is_pending());
9465			producer
9466				.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(payload)))
9467				.unwrap();
9468			assert!(matches!(group.poll_read_frame(&waiter), Poll::Ready(Ok(Some(_)))));
9469		}
9470		assert!(group.idle.is_none(), "a reader its own wake polls paid for a gate");
9471	}
9472
9473	/// A chunked read that takes the frame a whole-frame read parked on moves the cursor, so
9474	/// that read looks again rather than waiting out a frame it no longer reads.
9475	#[test]
9476	fn a_chunked_read_moves_a_parked_frame_read_on() {
9477		let producer = Info { start: 0 }.produce();
9478		let mut group = producer.consume().with_range(0..1);
9479		let mut frame = producer
9480			.create_frame(frame::Info {
9481				size: 6,
9482				timestamp: Timestamp::ZERO,
9483			})
9484			.unwrap();
9485		frame.write(Bytes::from_static(b"foo")).unwrap();
9486		let waiter = kio::Waiter::noop();
9487		for _ in 0..3 {
9488			assert!(
9489				group.poll_read_frame(&waiter).is_pending(),
9490				"the frame is still arriving"
9491			);
9492		}
9493		assert!(matches!(group.poll_next_frame(&waiter), Poll::Ready(Ok(Some(_)))));
9494		assert!(
9495			matches!(group.poll_read_frame(&waiter), Poll::Ready(Ok(None))),
9496			"past the cap"
9497		);
9498	}
9499
9500	/// A reader capped by its range finishes there cleanly whatever becomes of the frames past
9501	/// it, so a publisher that served the range keeps its stream when the rest fails upstream.
9502	#[test]
9503	fn a_capped_reader_finishes_at_its_range_end() {
9504		let mut producer = Info { start: 0 }.produce();
9505		for payload in [b"a", b"b"] {
9506			producer
9507				.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(payload)))
9508				.unwrap();
9509		}
9510		let waiter = kio::Waiter::noop();
9511		let mut capped = producer.consume().with_range(..1);
9512		let mut whole = producer.consume();
9513		assert!(capped.poll_finished(&waiter).is_pending(), "its frame is still unread");
9514		for reader in [&mut capped, &mut whole] {
9515			assert!(matches!(reader.poll_read_frame(&waiter), Poll::Ready(Ok(Some(_)))));
9516		}
9517
9518		producer.abort(Error::Cancel).unwrap();
9519		assert!(matches!(capped.poll_finished(&waiter), Poll::Ready(Ok(1))));
9520		assert!(matches!(whole.poll_finished(&waiter), Poll::Ready(Err(Error::Cancel))));
9521	}
9522
9523	/// A copy its transport bound at frame 4 that finishes after frame 2 ends there: the group
9524	/// holds two frames, so a reader past them reads a clean end rather than a cut.
9525	#[test]
9526	fn a_bounded_copy_finished_short_of_its_bound_ends_cleanly() {
9527		let mut producer = Info { start: 0 }.produce();
9528		producer.bound(Bounds { start: 0, end: Some(4) }).unwrap();
9529		let mut reader = producer.consume();
9530		for payload in [b"a", b"b"] {
9531			producer
9532				.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(payload)))
9533				.unwrap();
9534		}
9535		producer.finish().unwrap();
9536		reader.skip_to(4);
9537		let waiter = kio::Waiter::noop();
9538		let res = reader.poll_read_frame(&waiter);
9539		assert!(matches!(res, Poll::Ready(Ok(None))), "{res:?}");
9540		let res = reader.poll_finished(&waiter);
9541		assert!(matches!(res, Poll::Ready(Ok(4))), "{res:?}");
9542	}
9543
9544	/// A bounded copy finishing short of its bound reached the group's own end, which makes its
9545	/// siblings whole too; one finishing at its bound finished only the range it was cut to.
9546	#[test]
9547	fn a_copy_finished_short_of_its_bound_is_whole() {
9548		for (frames, whole) in [(2, true), (4, false)] {
9549			let mut producer = Info { start: 0 }.produce();
9550			producer.bound(Bounds { start: 0, end: Some(4) }).unwrap();
9551			let handle = producer.handle();
9552			for _ in 0..frames {
9553				producer
9554					.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(b"x")))
9555					.unwrap();
9556			}
9557			producer.finish().unwrap();
9558			assert_eq!(handle.state.read().charge.is_whole(), whole, "{frames} frames");
9559		}
9560	}
9561
9562	/// A publisher that read every frame of a finished group still learns when the budget
9563	/// gives up on it, so it can abandon the stream it is still writing.
9564	#[test]
9565	fn a_fully_read_group_still_reports_its_expiry() {
9566		let mut producer = Info { start: 0 }.produce();
9567		producer
9568			.write_frame(Frame::new(crate::Timestamp::ZERO, Bytes::from_static(b"a")))
9569			.unwrap();
9570		let producer = producer.finish().unwrap();
9571
9572		let expired = Switch::default();
9573		let mut group = producer.consume().with_expiry(Arc::new(expired.clone()));
9574		let waiter = kio::Waiter::noop();
9575		assert!(matches!(group.poll_read_frame(&waiter), Poll::Ready(Ok(Some(_)))));
9576		assert!(
9577			matches!(group.poll_read_frame(&waiter), Poll::Ready(Ok(None))),
9578			"read whole"
9579		);
9580		assert!(!group.poll_expired(&waiter));
9581
9582		expired.set(true);
9583		assert!(group.poll_expired(&waiter), "the writer abandons its stream");
9584		expired.set(false);
9585		assert!(group.poll_expired(&waiter), "and the verdict stands");
9586	}
9587	/// A captured job owns its release guard independently of the cached delivery.
9588	#[test]
9589	fn inflater_release_guard_charge_follows_its_last_job() {
9590		let pool = cache::Pool::unbounded();
9591		let mut group = compressed_group(&pool);
9592		group
9593			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), verbose(0)))
9594			.unwrap();
9595		let group = group.finish().unwrap();
9596		let job = take_slices(&group.handle, 0);
9597		let retained = job.release.clone();
9598		group.abort(Error::Evicted).unwrap();
9599		assert_eq!(
9600			pool.used(),
9601			Flate::RELEASE_HEAP + flate::ENCODER_HEAP,
9602			"the job owns its guard, and the account owns its spare"
9603		);
9604		assert!(matches!(job.get(0), Err(Error::Evicted)));
9605		drop(job);
9606		assert_eq!(
9607			pool.used(),
9608			Flate::RELEASE_HEAP + flate::ENCODER_HEAP,
9609			"clones share one intrinsic charge"
9610		);
9611		drop(retained);
9612		assert_eq!(pool.used(), 0, "the final guard also releases its account's spare");
9613	}
9614}