Skip to main content

moq_mux/container/
consumer.rs

1use std::collections::VecDeque;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicUsize, Ordering};
4use std::task::{Poll, ready};
5
6use kio::clock::Instant;
7use moq_net::Timestamp;
8
9use super::{Container, Frame, Read, TimestampRewind, time};
10
11/// Media and group boundaries in delivery order.
12pub(crate) enum Event {
13	/// A media frame, with when the wire frame carrying it landed in this node's cache
14	/// ([`moq_net::frame::Frame::created`]).
15	Frame { frame: Frame, arrived: Instant },
16	/// An endpoint marker. `opens` when no media precedes it in its group: a declared stop
17	/// (a marker group or an audio terminal) rather than the previous frame's duration.
18	FrameEnd { end: Timestamp, opens: bool },
19	/// The group finished cleanly.
20	GroupEnd,
21	/// The group was lost upstream partway, so nothing more of it arrives. The gap it leaves is
22	/// read once the next group resumes the track. `observed` is when the loss was read.
23	Cut { observed: Instant },
24}
25
26/// Read items and exporter-only boundaries in delivery order.
27pub(crate) enum Item {
28	/// [`Read::Frame`], with when it landed as [`Event::Frame`] has.
29	Frame {
30		group: u64,
31		frame: Frame,
32		arrived: Instant,
33	},
34	/// [`Read::Gap`].
35	Gap {
36		timestamp: Timestamp,
37		duration: std::time::Duration,
38	},
39	/// [`Read::End`].
40	End {
41		group: u64,
42		end: Timestamp,
43	},
44	FrameEnd(Timestamp),
45	GroupEnd,
46	Cut {
47		observed: Instant,
48	},
49}
50
51/// Decode a moq-lite track into a stream of media [`Frame`]s in age-bounded
52/// presentation order.
53///
54/// `Consumer` reads a [`moq_net::track::Subscriber`] through its
55/// [`Ordered`](moq_net::track::Ordered) reader and decodes it with a [`Container`] format
56/// implementation, typically [`catalog::hang::Wire`](crate::catalog::hang::Wire).
57/// Yields decoded frames via [`poll_read`](Self::poll_read).
58///
59/// ## Ordering & age skipping
60///
61/// Groups can arrive on the wire out of order. The [`Ordered`](moq_net::track::Ordered) reader
62/// hands them out by start and decides every missing one: it waits for a group the track still
63/// owes until everything it could still present (bounded by where the next group begins) falls
64/// [`Delay::max`] behind the newest content, and reports what it gives up as a gap. With the
65/// default max delay of zero it gives up at once: any group that has a newer alternative is
66/// dropped. [`Delay::min`] only sets where the reader starts. A run the publisher declared
67/// skipped ([`skip_groups`](moq_net::track::Producer::skip_groups), which appending does) holds no
68/// group, and the consumer steps over it at once, as it does over keys the subscription's ranges
69/// leave out.
70///
71/// Within a group the consumer reads frames in arrival order. A group already handed out that
72/// stalls behind newer ones is skipped by the same budget, measured from where the next group
73/// begins.
74///
75/// Delivery starts at the first group the ordered reader hands out: the publisher resolved a
76/// live join [`Delay::min`] plus any [`Playout::warmup`] behind the live edge, and the ordered
77/// reader waits for the groups below it that the feed owes. Until the first item, the start also
78/// moves past each group whose first frame trails the newest content by more than the max delay
79/// plus the warmup, as `@moq/hang`'s consumer measures, unless that group covers the live edge
80/// less the min delay and the warmup: a backlog that landed whole would otherwise play from its
81/// oldest group, since nothing blocks, and stay that far behind. From there the same budget is
82/// the one rule that catches the consumer up to the live edge.
83///
84/// A stalled group is also skipped early, regardless of the max delay budget, once it has
85/// presented up to where the next group begins. CMAF frames carry a per-sample duration,
86/// so a group whose most recent frame ends (timestamp + duration) at or past the next
87/// group's first timestamp has nothing left worth waiting for. Containers without a
88/// duration report zero, which disables this check and falls back to the max delay budget.
89///
90/// Put the initial [`Delay`] on the [`moq_net::track::Subscription`] with
91/// [`Delay::subscription`] before subscribing. [`new`](Self::new) inherits it, taking the min
92/// from the furthest live join among its ranges and reading none as zero, and
93/// [`set_delay`](Self::set_delay) changes the whole [`Delay`] while reading. To build one at a
94/// delay the subscription does not carry, or with a catalog `warmup`, use a [`Playout`].
95///
96/// ## Gaps and ends
97///
98/// [`poll_read`](Self::poll_read) yields [`Read::Gap`] wherever media after an item already read
99/// will never arrive: a latency skip, an evicted current group, or keys between two groups the
100/// publisher did not declare skipped whose boundary is not contiguous within 1 ms. The later group
101/// continues the earlier when any of its frames presents by where the earlier ended, so an open
102/// GOP's leading pictures count, and its first frame waits until one shows it, at most as many frames
103/// as the track has reordered. Frames without a duration end one picture past the highest: the
104/// largest step between the group's latest presentation times. A local track
105/// owes nothing, so there a discontinuous run is a gap the moment the group past it lands. Whatever is lost before the first item is no
106/// gap, since nothing was read before it. A marker group (no decodable frames: one empty
107/// payload, or on a data track one object with no bytes) is the publisher declaring a stop,
108/// read as [`Read::End`]; nothing is missing. A data track's marker carries no timestamp, so
109/// it ends at the furthest point read, and reads as nothing before the first item.
110/// Empty groups (zero objects) mean nothing. Errors come in delivery order: a payload that fails
111/// to decode, or a group below an earlier group's start, ends the reader where it sits, and a
112/// failed track once the groups already here drain. A skip returns the error of a malformed group
113/// it already read rather than a gap; a group dropped unread is not validated, since decoding data
114/// that is thrown away is work a peer could force. After an error the reader reads as finished.
115///
116/// ## Memory
117///
118/// Decoded frames waiting to be read are charged to a byte cap, one group at the transport's size cap,
119/// counting the whole wire payload they share, along with each buffered frame's and group's own
120/// overhead. Once it is full the consumer stops
121/// decoding ahead and stops pulling new groups past one successor to the cursor's group, so the
122/// undecoded rest stays in the transport's cache, which bounds it. The group the cursor is on still decodes a wire frame whenever it holds nothing, so
123/// reading never waits on its own lookahead. If that group stalls while the cap is full, the cursor
124/// moves on to the next group like a skip past a slow group, read or not: the consumer can hold no
125/// more of what it would wait behind.
126pub struct Consumer<F: Container> {
127	reader: Reader<F::Error>,
128	name: std::sync::Arc<str>,
129
130	format: F,
131
132	// The current group that we want to read from
133	current: u64,
134
135	// Groups that we are monitoring, sorted by sequence ascending.
136	pending: VecDeque<GroupBuffer<F>>,
137
138	// The last group whose input finished, so watching EOF never rescans that prefix.
139	received: Option<u64>,
140
141	// Reap unread evictions only after metadata doubles, charging each sweep to new handles.
142	collect_at: usize,
143
144	// What the pending groups hold, against the max buffer.
145	memory: Memory,
146
147	// The last pull stopped at a full max buffer rather than at the track, so nothing wakes the reader
148	// once a skip refunds room: it pulls again itself.
149	gated: bool,
150
151	// How the cursor chooses its first group.
152	startup: Startup,
153
154	// How far behind the live edge the reader plays, before the warmup: see `Delay::min`. The start
155	// skip keeps the group covering the live edge less it, reading `None` as zero.
156	min_delay: Option<std::time::Duration>,
157
158	// How much further than the min delay the start reaches: see `Playout`.
159	warmup: std::time::Duration,
160
161	// Where the warming ends: the warmup past the first frame delivered. `None` before it.
162	warmed: Option<std::time::Duration>,
163
164	// How far we may drift from the live edge before skipping a group.
165	max_delay: std::time::Duration,
166
167	// The furthest presentation point delivered so far: max(timestamp + duration), endpoints
168	// included. `None` until the first item, so a loss before it is no gap.
169	edge: Option<std::time::Duration>,
170
171	// The first frame delivered from the latest group, and that group. Group starts never go
172	// backwards, so a later group with a frame below this is malformed.
173	start: Option<(u64, Timestamp)>,
174
175	// The start of the group the cursor most recently left. A frame below it is a rewind. Every
176	// frame also presents after that group's content, which a reader assumes rather than checks.
177	floor: Option<Timestamp>,
178
179	// Presentation end of the group we most recently advanced past, for the 1 ms
180	// contiguity check on a delivered hole.
181	presented_end: Option<std::time::Duration>,
182
183	// How the groups read so far run, for judging an unproven step.
184	cadence: Cadence,
185
186	// The cursor's group's frames read so far.
187	pictures: Pictures,
188
189	// Media went missing since the last item read, so the next one is preceded by a gap.
190	gap: bool,
191
192	// The cursor stepped over keys nothing declared skipped, so whether they held media is judged
193	// once the group it landed on shows where it starts: its first frame is held until then.
194	unproven: bool,
195
196	// The item a gap was returned ahead of.
197	next: Option<Item>,
198
199	// The group the last event came from.
200	group: u64,
201
202	// When the wire frame behind the last frame read landed in this node's cache.
203	arrived: Option<Instant>,
204
205	// The newest group the publisher's largest named so far.
206	largest: Option<u64>,
207
208	// The publisher's largest group as the start was decided: one at or below it was produced
209	// before the subscription, so dropping it unread skips the join's backlog.
210	joined: Option<u64>,
211
212	// When the latest backlog group dropped without delivering all of it landed.
213	backlog: Option<Instant>,
214}
215
216/// Whether a [`Consumer`] still reads its subscription.
217enum Reader<E> {
218	/// Receiving groups.
219	Reading(moq_net::track::Ordered),
220	/// The track failed, so no group can arrive. The error is returned once the groups already here
221	/// drain.
222	Failed(moq_net::track::Ordered, E),
223	/// An error ended the reader, which reads as finished from then on. The subscription is
224	/// released, and the publisher's demand with it.
225	Ended,
226	/// The track's own failure ended the reader once its groups drained, as [`Self::Ended`] does.
227	Lost,
228}
229
230/// How a [`Consumer`]'s cursor chooses its first group.
231#[derive(Clone, Copy)]
232enum Startup {
233	/// The first group the ordered reader hands out.
234	Earliest,
235	/// The newest group, discarding what arrived below it.
236	Newest,
237	/// The cursor is on its first group or past it.
238	Started,
239}
240
241/// Two adjacent groups are timeline-contiguous when the next start is within this slack
242/// of the current end. Per-sample durations and base-decode-times round to microseconds
243/// independently, so a genuine boundary can be off by ~1 µs; a real missing group spans
244/// about one group duration.
245const CONTIGUITY_TOLERANCE: std::time::Duration = std::time::Duration::from_millis(1);
246
247/// The default decoded-byte cap: one group at the transport's size cap.
248pub(crate) const DEFAULT_MAX_BUFFER: usize = 32 * 1024 * 1024;
249
250/// The decoded bytes a consumer's groups hold, shared with each group so one dropped by any path
251/// refunds what it held.
252#[derive(Clone)]
253struct Memory(Arc<MemoryState>);
254
255struct MemoryState {
256	used: AtomicUsize,
257	max: AtomicUsize,
258}
259
260impl Memory {
261	fn new(max: usize) -> Self {
262		Self(Arc::new(MemoryState {
263			used: AtomicUsize::new(0),
264			max: AtomicUsize::new(max),
265		}))
266	}
267
268	fn used(&self) -> usize {
269		self.0.used.load(Ordering::Relaxed)
270	}
271
272	fn full(&self) -> bool {
273		self.used() >= self.0.max.load(Ordering::Relaxed)
274	}
275
276	#[cfg(test)]
277	fn set_max(&self, max: usize) {
278		self.0.max.store(max, Ordering::Relaxed);
279	}
280
281	fn charge(&self, bytes: usize) {
282		self.0.used.fetch_add(bytes, Ordering::Relaxed);
283	}
284
285	fn refund(&self, bytes: usize) {
286		self.0.used.fetch_sub(bytes, Ordering::Relaxed);
287	}
288}
289
290fn pts_contiguous(end: Option<std::time::Duration>, next_start: std::time::Duration) -> bool {
291	end.is_some_and(|end| next_start <= end.saturating_add(CONTIGUITY_TOLERANCE))
292}
293
294/// The deepest reordering a codec allows, in pictures: H.264 and HEVC hold at most 16 frames, so 32
295/// fields. A reader measures a track's reordering and its last picture's duration within this many of
296/// a group's latest presentation times.
297const REORDER_MAX: usize = 32;
298
299/// How the groups read so far run, for judging a step over keys nothing declared skipped.
300#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
301pub(crate) struct Cadence {
302	/// One picture, for a group whose frames carry no duration: its highest timestamp is where its
303	/// last picture starts, not ends. The largest step between its latest presentation times, so a
304	/// field/frame mix allows a frame. Zero once a group's end was exact.
305	slack: std::time::Duration,
306	/// The most frames that decoded ahead of a frame they present after, in any group read: an open
307	/// GOP's leading pictures decode after the keyframe, so its lowest picture comes within that many.
308	depth: usize,
309}
310
311/// Where the groups a reader read through ended, so a later reader of the track continues there.
312#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
313pub(crate) struct Reached {
314	end: Option<std::time::Duration>,
315	cadence: Cadence,
316}
317
318/// The cursor's group's frames read so far.
319#[derive(Default)]
320struct Pictures {
321	/// The group's latest presentation times, ascending, at most [`REORDER_MAX`].
322	latest: Vec<std::time::Duration>,
323}
324
325impl Pictures {
326	/// Note a frame presenting `at`, returning how many frames read before it present after it.
327	fn read(&mut self, at: std::time::Duration) -> usize {
328		let below = self.latest.partition_point(|&t| t <= at);
329		let after = self.latest.len() - below;
330		match self.latest.len() < REORDER_MAX {
331			true => self.latest.insert(below, at),
332			// Full: the earliest leaves, unless this frame presents before every time kept.
333			false if below > 0 => {
334				self.latest.remove(0);
335				self.latest.insert(below - 1, at);
336			}
337			false => {}
338		}
339		after
340	}
341
342	/// The largest step between the latest presentation times read, zero for fewer than two.
343	fn step(&self) -> std::time::Duration {
344		(self.latest.windows(2))
345			.map(|pair| pair[1] - pair[0])
346			.max()
347			.unwrap_or_default()
348	}
349
350	/// The highest presentation time read.
351	fn highest(&self) -> Option<std::time::Duration> {
352		self.latest.last().copied()
353	}
354}
355
356/// A gap from the delivered `edge` to `resume`, in the resume's scale. Refused for an unscaled
357/// `resume`, which has no time to resume at.
358fn gap(edge: std::time::Duration, resume: Timestamp) -> Result<Item, moq_net::Error> {
359	let scale = resume.scale().ok_or(moq_net::Error::TimestampMismatch)?;
360	// A next group may start before the edge (an overlapping endpoint), so the span bottoms out at zero.
361	let start = edge
362		.as_nanos()
363		.saturating_mul(scale.as_u64() as u128)
364		.div_euclid(1_000_000_000)
365		.min(resume.value() as u128) as u64;
366	let timestamp = Timestamp::new(start, scale).expect("at or below a valid timestamp");
367	let duration = resume
368		.checked_sub(timestamp)
369		.expect("at or below the resume, in its scale");
370	let duration = std::time::Duration::try_from(duration).expect("a scaled span");
371	Ok(Item::Gap { timestamp, duration })
372}
373
374/// How far behind the live edge a media reader plays: where it starts, and how late it may fall.
375///
376/// The default states no minimum and a zero maximum, which reaches back as far as the max allows
377/// and skips a superseded group at once.
378#[derive(Clone, Copy, Debug, PartialEq, Eq)]
379pub struct Delay {
380	/// The playout delay held behind the live edge, or `None` when the reader did not state one.
381	///
382	/// Each subscription range starting at [`Start::Oldest`](moq_net::track::Start::Oldest)
383	/// joins live this far behind the live edge instead, as a
384	/// [`Start::Live`](moq_net::track::Start::Live) `min`, so a player's buffer arrives full; a
385	/// range with a time start keeps it. Unstated, the join reaches back as far as [`Self::max`]
386	/// allows. A reader also keeps the group covering the live edge less this as it starts,
387	/// reading an unstated one as zero. A missing group is given up by [`Self::max`] alone,
388	/// whatever the minimum.
389	pub min: Option<std::time::Duration>,
390	/// How long a superseded group stays worth delivering, or `None` for as long as the publisher
391	/// keeps it: each live join's [`Start::Live`](moq_net::track::Start::Live) `max`. With no
392	/// [`Self::min`] either, a range starting at the oldest group stays history, delivered in full.
393	pub max: Option<std::time::Duration>,
394}
395
396impl Default for Delay {
397	fn default() -> Self {
398		Self {
399			min: None,
400			max: Some(std::time::Duration::ZERO),
401		}
402	}
403}
404
405impl Delay {
406	/// Set [`Self::min`], returning `self` for chaining.
407	pub fn with_min(mut self, min: impl Into<Option<std::time::Duration>>) -> Self {
408		self.min = min.into();
409		self
410	}
411
412	/// Set [`Self::max`], returning `self` for chaining.
413	pub fn with_max(mut self, max: impl Into<Option<std::time::Duration>>) -> Self {
414		self.max = max.into();
415		self
416	}
417
418	/// `subscription` at this delay: each range starting at the oldest group joins live
419	/// [`Self::min`] behind the live edge, or [`Self::max`] when only that is stated, and each
420	/// live join takes [`Self::max`] as its own. A time start stays history.
421	///
422	/// [`Subscription::default`](moq_net::track::Subscription::default) is already a live join,
423	/// at the latest group, so a range this delay should place starts at
424	/// [`Range::ALL`](moq_net::track::Range::ALL) instead.
425	pub fn subscription(&self, subscription: moq_net::track::Subscription) -> moq_net::track::Subscription {
426		use moq_net::track::{Range, Start};
427		let ranges: Vec<Range> = subscription
428			.ranges
429			.iter()
430			.map(|range| {
431				let start = match (range.start, self.min.or(self.max)) {
432					(Start::Oldest, Some(min)) => Start::Live {
433						min: Some(min),
434						max: self.max,
435					},
436					(Start::Live { min, .. }, _) => Start::Live { min, max: self.max },
437					(start, _) => start,
438				};
439				Range { start, ..*range }
440			})
441			.collect();
442		subscription.with_ranges(ranges)
443	}
444
445	/// [`Self::subscription`] as an update to `current`, the subscription it replaces: a range
446	/// starting at the oldest group that `current` already joins live with the same end keeps
447	/// that join's `min` and takes the new [`Self::max`], so changing [`Self::min`] places only
448	/// the ranges it adds. A live join that already resolved stays where it started, as
449	/// [`Consumer::set_delay`] leaves it.
450	pub fn update(
451		&self,
452		current: &moq_net::track::Subscription,
453		subscription: moq_net::track::Subscription,
454	) -> moq_net::track::Subscription {
455		use moq_net::track::Start;
456		let starts: Vec<_> = subscription
457			.ranges
458			.iter()
459			.map(|range| (range.start, range.end))
460			.collect();
461		let mut updated = self.subscription(subscription);
462		for (range, (start, end)) in updated.ranges.iter_mut().zip(starts) {
463			if start != Start::Oldest {
464				continue;
465			}
466			// For a caller whose own ranges start at the oldest group or a time, as the bindings'
467			// do, a live join in `current` is one a delay placed.
468			let held = current.ranges.iter().find_map(|held| match held.start {
469				Start::Live { min, .. } if held.end == end => Some(min),
470				_ => None,
471			});
472			if let Some(min) = held {
473				range.start = Start::Live { min, max: self.max };
474			}
475		}
476		updated
477	}
478}
479
480/// The playout delay `subscription` states: the furthest back any of its ranges joins live, or
481/// `None` when none does. A join with no lag limit states none.
482fn stated(subscription: &moq_net::track::Subscription) -> Option<std::time::Duration> {
483	subscription
484		.ranges
485		.iter()
486		.filter_map(|range| match range.start {
487			moq_net::track::Start::Live { min, .. } => min,
488			_ => None,
489		})
490		.max()
491}
492
493/// The longest any range of `subscription` keeps a superseded group: `None` while a history range
494/// is asked for or a live join has no `max`.
495fn widest(subscription: &moq_net::track::Subscription) -> Option<std::time::Duration> {
496	let mut widest = Some(std::time::Duration::ZERO);
497	for range in &subscription.ranges {
498		let max = match range.start {
499			moq_net::track::Start::Live { max, .. } => max,
500			moq_net::track::Start::Oldest | moq_net::track::Start::Time(_) => None,
501		};
502		widest = widest.zip(max).map(|(widest, max)| widest.max(max));
503	}
504	widest
505}
506
507/// A [`Consumer`]'s [`Delay`] and the catalog rendition's warmup, applied together.
508///
509/// The warmup is how much media a decoder needs before its output is clean, such as an Opus
510/// decoder's pre-roll: pass the catalog audio rendition's `warmup`. Subscribe with
511/// [`subscription`](Self::subscription), then build the consumer with [`consumer`](Self::consumer).
512///
513/// The subscription carries the min and max delay plus the warmup: the publisher starts a live
514/// join that far back, and it and the transport skip what falls outside that budget, while the
515/// consumer skips at the max delay alone.
516///
517/// A live join starts at the group covering the live edge less [`Delay::min`] and the warmup,
518/// which the publisher resolves, and the ordered reader waits for the groups from there. Until the
519/// reader is the warmup past its first frame, the skip also tolerates the warmup, so the media
520/// leading up to the start is not dropped as stale.
521#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
522pub struct Playout {
523	/// The delay the consumer plays at, and skips past.
524	pub delay: Delay,
525	/// How much further back than [`Delay::min`] the start reaches, at most 10 s.
526	pub warmup: std::time::Duration,
527}
528
529/// The longest playout delay: it caps a reader's latency and how far catalog `warmup` reaches back,
530/// so a publisher cannot hold a reader's media without bound. Mirrored by `@moq/hang`'s `DELAY_MAX`.
531pub const DELAY_MAX: std::time::Duration = std::time::Duration::from_secs(10);
532
533/// The delay a subscription carries for a reader starting `warmup` further back than `delay`:
534/// both bounds widened, so a live join reaches back far enough and the budget keeps what it reaches.
535fn warmed(delay: Delay, warmup: std::time::Duration) -> Delay {
536	Delay {
537		// An unstated minimum already reaches back as far as the max delay allows, further than
538		// any live join, so it stays unstated.
539		min: delay.min.map(|min| min.saturating_add(warmup)),
540		max: delay.max.map(|max| max.saturating_add(warmup)),
541	}
542}
543
544impl Playout {
545	/// Play at `delay`, starting `warmup` further back.
546	pub fn new(delay: Delay, warmup: std::time::Duration) -> Self {
547		Self { delay, warmup }
548	}
549
550	/// `subscription` with this playout's delay, both bounds widened by the warmup: see
551	/// [`Delay::subscription`].
552	pub fn subscription(&self, subscription: moq_net::track::Subscription) -> moq_net::track::Subscription {
553		self.subscribed().subscription(subscription)
554	}
555
556	/// Decode `track` as `format` at this playout.
557	///
558	/// Subscribe `track` with [`subscription`](Self::subscription): the publisher may already
559	/// have skipped what a narrower one left out, and the live join starts where it was
560	/// subscribed. A track subscribed otherwise has its max delay set here, widened or narrowed.
561	pub fn consumer<F: Container>(&self, track: moq_net::track::Subscriber, format: F) -> Consumer<F> {
562		let mut consumer = Consumer::new(track, format);
563		consumer.warmup = self.reach();
564		consumer.set_delay(self.delay);
565		consumer
566	}
567
568	/// The delay the subscription carries.
569	fn subscribed(&self) -> Delay {
570		warmed(self.delay, self.reach())
571	}
572
573	/// The warmup, capped at [`DELAY_MAX`].
574	fn reach(&self) -> std::time::Duration {
575		self.warmup.min(DELAY_MAX)
576	}
577}
578
579impl<F: Container> Consumer<F> {
580	/// Create a Consumer wrapping the given moq-lite consumer, decoding `format`.
581	///
582	/// The ordering window inherits the widest live join `max` the subscriber asks, none while
583	/// it asks for history, clamped to the track's max age. Put that budget on the
584	/// [`moq_net::track::Subscription`] before awaiting the subscription, so the
585	/// publisher preserves the same replay window.
586	pub fn new(track: moq_net::track::Subscriber, format: F) -> Self {
587		let subscription = track.subscription();
588		// The budget is clamped to the track's max age, since a group the publisher already marks
589		// stale can't be waited for and would otherwise stall the catch-up by the excess.
590		let max_delay = widest(&subscription)
591			.unwrap_or(std::time::Duration::MAX)
592			.min(track.info().max_age.unwrap_or(std::time::Duration::MAX));
593		Self {
594			name: track.name().into(),
595			reader: Reader::Reading(track.ordered()),
596			format,
597			current: 0,
598			pending: VecDeque::new(),
599			received: None,
600			collect_at: 1,
601			memory: Memory::new(DEFAULT_MAX_BUFFER),
602			gated: false,
603			startup: Startup::Earliest,
604			min_delay: stated(&subscription),
605			warmup: std::time::Duration::ZERO,
606			warmed: None,
607			max_delay,
608			edge: None,
609			start: None,
610			floor: None,
611			presented_end: None,
612			cadence: Cadence::default(),
613			pictures: Pictures::default(),
614			gap: false,
615			unproven: false,
616			next: None,
617			group: 0,
618			arrived: None,
619			largest: None,
620			joined: None,
621			backlog: None,
622		}
623	}
624
625	/// Continue groups an earlier reader of this track read up to `reached`: the first group
626	/// starting there reads as continuing them rather than past a hole.
627	pub(crate) fn continuing(mut self, reached: Reached) -> Self {
628		self.presented_end = reached.end;
629		self.cadence = reached.cadence;
630		self
631	}
632
633	/// Where the groups read through ended, for [`Self::continuing`].
634	pub(crate) fn reached(&self) -> Reached {
635		Reached {
636			end: self.presented_end,
637			cadence: self.cadence,
638		}
639	}
640
641	/// Start at the newest group, the live edge, rather than the floor or the oldest group the
642	/// publisher serves: the publisher's largest when it reports one past what has arrived. The
643	/// subscription keeps its budget, so every group after the start arrives as it would for any
644	/// reader; what arrived below the start is discarded.
645	pub(crate) fn live(mut self) -> Self {
646		self.startup = Startup::Newest;
647		self
648	}
649
650	/// When the wire frame behind the latest frame read landed in this node's cache
651	/// ([`moq_net::frame::Frame::created`]), or `None` before the first frame.
652	///
653	/// A gap or an end leaves it at the frame before. A frame from cache, such as a join on a
654	/// track that already holds groups, reports when it landed, not when it was read. Frames
655	/// packed into one wire frame, as a CMAF fragment packs its samples, share its arrival.
656	pub fn arrival(&self) -> Option<Instant> {
657		self.arrived
658	}
659
660	/// When the latest backlog group this reader dropped without delivering all of it landed in
661	/// this node's cache, or `None` before the first.
662	///
663	/// Backlog is a group at or below the publisher's largest when the subscription began, so it
664	/// was produced before. Its frames were never read, so a caller timing
665	/// [`arrival`](Self::arrival)s learns when a join's backlog finished arriving even when the
666	/// reader skipped it: one the ordered reader gave up as stale or late (see
667	/// [`Item::Gap`](moq_net::track::Item::Gap)'s `landed`), or one a skip here passed over. A gap
668	/// reaching past the join counts for none of it, since its landing may be a later group's.
669	pub fn backlog(&self) -> Option<Instant> {
670		self.backlog
671	}
672
673	/// The group sequence of the last event read.
674	pub(crate) fn group(&self) -> u64 {
675		self.group
676	}
677
678	/// The track's name.
679	pub(crate) fn name(&self) -> &str {
680		&self.name
681	}
682
683	/// Read the next frame from the track.
684	///
685	/// This method handles timestamp decoding, group ordering, and age management
686	/// automatically. It will skip groups that are too far behind to maintain the
687	/// configured max delay.
688	///
689	/// Returns `None` when the track has ended, and after an error. See [`Read`] for the items between frames;
690	/// an undeclared forward timestamp jump is not a gap, since nothing says media is missing.
691	#[cfg_attr(feature = "async", kio::wrapper)]
692	pub fn poll_read(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Read>, F::Error>> {
693		loop {
694			let read = match ready!(self.poll_item(waiter))? {
695				Some(Item::Frame { group, frame, arrived }) => {
696					self.arrived = Some(arrived);
697					Read::Frame { group, frame }
698				}
699				Some(Item::Gap { timestamp, duration }) => Read::Gap { timestamp, duration },
700				Some(Item::End { group, end }) => Read::End { group, end },
701				Some(Item::FrameEnd(_) | Item::GroupEnd | Item::Cut { .. }) => continue,
702				None => return Poll::Ready(Ok(None)),
703			};
704			return Poll::Ready(Ok(Some(read)));
705		}
706	}
707
708	/// The next frame, passing over gaps and ends.
709	#[cfg(test)]
710	pub(crate) async fn read_frame(&mut self) -> Result<Option<Frame>, F::Error> {
711		loop {
712			match self.read().await? {
713				Some(Read::Frame { frame, .. }) => return Ok(Some(frame)),
714				Some(Read::Gap { .. } | Read::End { .. }) => continue,
715				None => return Ok(None),
716			}
717		}
718	}
719
720	/// Read items while preserving boundaries needed to finish exporter fragments.
721	pub(crate) fn poll_item(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Item>, F::Error>> {
722		if let Some(item) = self.next.take() {
723			return Poll::Ready(Ok(Some(item)));
724		}
725		let edge = self.edge;
726		let event = ready!(self.poll_event(waiter))?;
727		let (item, resume) = match event {
728			Some(Event::Frame { frame, arrived }) => {
729				let resume = frame.timestamp;
730				let group = self.group;
731				(Item::Frame { group, frame, arrived }, resume)
732			}
733			Some(Event::FrameEnd { end, opens: true }) => (Item::End { group: self.group, end }, end),
734			Some(Event::FrameEnd { end, opens: false }) => return Poll::Ready(Ok(Some(Item::FrameEnd(end)))),
735			Some(Event::GroupEnd) => return Poll::Ready(Ok(Some(Item::GroupEnd))),
736			Some(Event::Cut { observed }) => return Poll::Ready(Ok(Some(Item::Cut { observed }))),
737			None => return Poll::Ready(Ok(None)),
738		};
739		if std::mem::take(&mut self.gap)
740			&& let Some(edge) = edge
741		{
742			self.next = Some(item);
743			return Poll::Ready(Ok(Some(gap(edge, resume)?)));
744		}
745		Poll::Ready(Ok(Some(item)))
746	}
747
748	/// Whether the error that ended the reader was its track's own failure, rather than its media.
749	pub(crate) fn lost(&self) -> bool {
750		matches!(self.reader, Reader::Lost)
751	}
752
753	/// Read media or a clean group boundary without waiting for a successor group.
754	pub(crate) fn poll_event(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Event>, F::Error>> {
755		// An error ended the reader, which reads as finished from then on: a decode error has
756		// already consumed the frame it came from, so reading on would skip it.
757		if let Reader::Ended | Reader::Lost = self.reader {
758			return Poll::Ready(Ok(None));
759		}
760		let event = ready!(self.poll_event_inner(waiter));
761		if event.is_err() {
762			// Nothing more is read, so release the subscription and the groups it holds rather
763			// than pin the publisher's demand and cache for as long as the caller keeps this.
764			if !matches!(self.reader, Reader::Lost) {
765				self.reader = Reader::Ended;
766			}
767			self.pending.clear();
768		}
769		Poll::Ready(event)
770	}
771
772	fn poll_event_inner(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Event>, F::Error>> {
773		loop {
774			match self.poll_event_once(waiter) {
775				// A skip refunded room for groups the max buffer held back, so pull them.
776				Poll::Pending if std::mem::take(&mut self.gated) && !self.pull_gated() => continue,
777				res => return res,
778			}
779		}
780	}
781
782	fn poll_event_once(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Event>, F::Error>> {
783		// Where the publisher stood as the subscription began, read as soon as its answer reports a
784		// largest, before a group the reader waits on lets later ones raise it. A largest not yet in
785		// range takes the first one that is.
786		if self.joined.is_none() {
787			self.join(waiter);
788		}
789		// Grab any new groups from the track, recording whether the track is finished.
790		let finished = self.poll_read_finish(waiter).is_ready();
791
792		match self.startup {
793			// The ordered reader already waited for the groups below its first that the feed owes.
794			Startup::Earliest => {
795				if let Some(front) = self.pending.front() {
796					self.current = front.start;
797					self.join(waiter);
798					self.startup = Startup::Started;
799				}
800			}
801			Startup::Newest => {
802				// NOTE: poll_min_timestamp buffers at least one frame per group and registers the
803				// waiter on the ones still empty. Any wire frame counts, so a paused track whose only
804				// group is a marker still reads its end. The oldest buffers past a full max buffer, so
805				// a start is always found.
806				let any_frame = self.pending.iter_mut().enumerate().any(|(i, group)| {
807					let _ = group.poll_min_timestamp(waiter, &self.format, i == 0);
808					!group.is_empty()
809				});
810				if any_frame {
811					// A live reader takes the newest group, though its frames may still be on their
812					// way, and discards the older ones the budget also delivers. The publisher's
813					// largest names it before its stream lands.
814					self.poll_largest(waiter);
815					let back = self.pending.back().expect("a group has a frame").start;
816					let start = back.max(self.largest.unwrap_or(back));
817					self.join(waiter);
818					// Nothing has been read, so discarding what lies below the start is no gap.
819					self.discard(|group| group.start < start)?;
820					self.current = start;
821					self.startup = Startup::Started;
822				}
823			}
824			Startup::Started => {}
825		}
826
827		loop {
828			// Until the first item, a backlog that landed whole starts within the budget: nothing
829			// blocks, so the skip below would play it from its oldest group and stay that far behind
830			// for good. The start moves past each group whose first frame trails the newest content
831			// by more than the budget, as `@moq/hang`'s consumer measures, unless that group covers
832			// the live edge less the reach (see `Playout`), which the start promises.
833			if self.edge.is_none() && self.start_skip(waiter)? {
834				continue;
835			}
836
837			// Keys stepped over below the cursor's group lost media unless the group continues where
838			// the content read so far ended, which may take frames after its first to show: an open
839			// GOP's leading pictures decode after its keyframe but present before it. The group holds
840			// its first frame until it shows, so a gap is still read ahead of it.
841			let mut held = false;
842			if self.unproven
843				&& let Some(group) = self.pending.front_mut()
844				&& group.start <= self.current
845			{
846				// Before the first item nothing was read to lose, so there is nothing to wait for.
847				let bound = self.edge.and(self.presented_end).map(|end| end + self.cadence.slack);
848				match group.poll_continues(waiter, &self.format, bound, self.cadence.depth) {
849					Poll::Ready(Some(true)) => self.unproven = false,
850					Poll::Ready(Some(false)) => self.lose(),
851					// An endpoint, the group's end, or its failure comes first and is judged as it is read.
852					Poll::Ready(None) => {}
853					Poll::Pending => held = true,
854				}
855			}
856
857			// Return the next frame from the current group if possible.
858			// If the current group is finished or errored, advance to the next group.
859			if !held
860				&& let Some(group) = self.pending.front_mut()
861				&& group.start <= self.current
862			{
863				match group.poll_read(waiter, &self.format) {
864					Poll::Ready(Ok(Some(Event::Frame { frame, arrived }))) => {
865						let seq = group.group.start;
866						let ts = frame.timestamp;
867						let first = time(ts).ok_or(moq_net::Error::TimestampMismatch)?;
868						if let Some(floor) = self.floor
869							&& time(floor).is_some_and(|floor| first.as_micros() < floor.as_micros())
870						{
871							return Poll::Ready(Err(TimestampRewind { timestamp: ts, floor }.into()));
872						}
873						if self.start.is_none_or(|(start, _)| start != seq) {
874							self.start = Some((seq, ts));
875							self.pictures.latest.clear();
876						}
877						let reordered = self.pictures.read(first);
878						self.cadence.depth = self.cadence.depth.max(reordered);
879						self.warmed.get_or_insert_with(|| first.saturating_add(self.warmup));
880						let end = first + frame.duration.and_then(time).unwrap_or_default();
881						self.advance(end);
882						self.group = seq;
883						return Poll::Ready(Ok(Some(Event::Frame { frame, arrived })));
884					}
885					Poll::Ready(Ok(Some(Event::FrameEnd { end, opens }))) => {
886						self.group = group.group.start;
887						let at = time(end).ok_or(moq_net::Error::TimestampMismatch)?;
888						let bound = self.presented_end.map(|end| end + self.cadence.slack);
889						if std::mem::take(&mut self.unproven) && !pts_contiguous(bound, at) {
890							self.lose();
891						}
892						self.advance(at);
893						return Poll::Ready(Ok(Some(Event::FrameEnd { end, opens })));
894					}
895					Poll::Ready(Ok(Some(event))) => return Poll::Ready(Ok(Some(event))),
896					// Still blocked on this group, don't skip it yet.
897					Poll::Pending => {}
898					// A decode error is real and the caller must see it, not have the group
899					// silently dropped.
900					Poll::Ready(Err(Failure::Decode(e))) => {
901						tracing::warn!(
902							track = &*self.name,
903							group = group.group.start,
904							error = ?e,
905							"group payload failed to decode; ending the reader"
906						);
907						return Poll::Ready(Err(e));
908					}
909					Poll::Ready(Err(Failure::Lost(e))) => {
910						// The group aged out of the relay cache (`Error::Old`) or was otherwise
911						// aborted. Any sequences between it and the next buffered group were
912						// evicted alongside it, so jump straight to that group instead of
913						// stepping one-by-one and then blocking on a sequence gap of groups
914						// that will never arrive.
915						tracing::warn!(
916							track = &*self.name,
917							group = group.group.start,
918							error = ?e,
919							"current group evicted; skipping to next buffered group"
920						);
921						// Whatever the group still held is lost, so this is a skip like any other.
922						self.lose();
923						let current = self.current;
924						self.discard(|group| group.start <= current)?;
925						self.current = self.pending.front().map_or(self.current + 1, |g| g.start);
926						// Said now rather than with the gap, which waits for the next group: what
927						// the caller holds of this one need not wait for a successor.
928						return Poll::Ready(Ok(Some(Event::Cut {
929							observed: kio::clock::now(),
930						})));
931					}
932					// Cleanly finished group: advance past its key.
933					Poll::Ready(Ok(None)) => {
934						// A data track's marker carries no timestamp, so it ends where this reader
935						// got to. Before the first item there is nothing to end.
936						if let Content::Bare { ended } = &mut group.content
937							&& !std::mem::replace(ended, true)
938							&& let Some(edge) = self.edge
939						{
940							let end = u64::try_from(edge.as_micros())
941								.ok()
942								.and_then(|micros| Timestamp::from_micros(micros).ok())
943								.ok_or(moq_net::Error::Decode(moq_net::DecodeError::BoundsExceeded))?;
944							self.group = group.group.start;
945							// It has no timestamp to prove the keys stepped over below it held nothing.
946							if std::mem::take(&mut self.unproven) {
947								self.lose();
948							}
949							return Poll::Ready(Ok(Some(Event::FrameEnd { end, opens: true })));
950						}
951						// A group its producer finished whole presents up to its end, which can pass
952						// what its frames reach when they carry no duration.
953						let whole = group
954							.group
955							.end()
956							.zip(group.group.timescale())
957							.and_then(|(end, scale)| Timestamp::new(end, scale).ok())
958							.and_then(time);
959						if let Some(end) = group.max_end.max(whole) {
960							self.presented_end = Some(end);
961							// Frames it carried say where its last picture ends: exactly when a duration
962							// or its end reaches past them, otherwise one picture past the highest.
963							if self.start.is_some_and(|(seq, _)| seq == group.group.start) {
964								let step = self.pictures.step();
965								if self.pictures.highest().is_some_and(|highest| end > highest) {
966									self.cadence.slack = std::time::Duration::ZERO;
967								} else if !step.is_zero() {
968									self.cadence.slack = step;
969								}
970							}
971						}
972						self.pending.pop_front();
973						self.current += 1;
974						self.note_group_edge();
975						return Poll::Ready(Ok(Some(Event::GroupEnd)));
976					}
977				}
978			}
979
980			// The ordered reader hands out a group only once it resolved every key below it: a
981			// declared skip, one the ranges leave out, or one it gave up on. So the cursor steps to
982			// the next group at once, past one aborted before anything of it was read.
983			if let Some(front) = self.pending.front_mut()
984				&& front.start > self.current
985			{
986				if front.reapable(waiter) {
987					self.discard_front(1)?;
988					continue;
989				}
990				let next = front.start;
991				// Keys the publisher declared skipped hold no group. Any other run lost media unless
992				// the group past it continues the timeline, which its first frame shows.
993				if !self.is_skipped(self.current..next) {
994					self.unproven = true;
995				}
996				self.current = next;
997				self.note_group_edge();
998				continue;
999			}
1000
1001			// Reap later aborts only when delivery blocks. An aborted group past the current one
1002			// must not hold its buffer. Buffered frames and faults stay in delivery order; the
1003			// current group has its eviction path above. Live groups register the waiter here so a
1004			// later abort wakes the reader.
1005			let current = self.current;
1006			self.discard(|group| group.start > current && group.reapable(waiter))?;
1007
1008			// The current group's furthest presentation point (timestamp + duration).
1009			let current_end = if let Some(current) = self.pending.front_mut()
1010				&& current.start <= self.current
1011			{
1012				let polled = current.poll_min_timestamp(waiter, &self.format, true);
1013				// A frame that landed since the read above is delivered, not judged: its end can
1014				// reach the next group, and skipping there would throw it away as lost. A held frame
1015				// waits on frames still to come instead.
1016				if current.ready() && !held {
1017					continue;
1018				}
1019				match polled {
1020					Poll::Ready(Some(_)) => current.max_end,
1021					_ => None,
1022				}
1023			} else {
1024				None
1025			};
1026
1027			// The first newer group with data (our skip target) and where it starts, and the newest
1028			// content past the cursor.
1029			let next_group = self.poll_next_group(waiter);
1030			let max_timestamp = self.poll_newest(waiter);
1031
1032			// The current group is blocking. Everything it could still present ends
1033			// where the next group begins, so skip once that reach falls a full budget
1034			// behind the newest content, the same measure as a missing group. Its own
1035			// first frame is no bound once reading began: a group longer than the budget
1036			// would be cut short whenever it blocks behind a newer one racing ahead on its
1037			// own stream. Only the start, above, measures the first frame. Skip early too
1038			// once it has presented up to where the next group begins (duration
1039			// coverage), since nothing is left worth waiting for.
1040			// While the reader warms, the start reached the warmup further back than the max delay.
1041			let budget = match self.warming() {
1042				true => self.max_delay.saturating_add(self.warmup),
1043				false => self.max_delay,
1044			};
1045			let should_skip = next_group.is_some_and(|(_, next_start)| {
1046				max_timestamp.saturating_sub(next_start) >= budget || current_end.is_some_and(|end| end >= next_start)
1047			});
1048			let target = match should_skip {
1049				true => next_group.map(|(i, start)| (i, Some(start))),
1050				// Looking at the later groups can fill the max buffer while the cursor's group holds its
1051				// first frame, which it then judges by what it holds and reads, as any group holding a
1052				// frame does rather than be skipped. One still holding nothing is skipped below.
1053				false if held && self.memory.full() && self.pending.front().is_some_and(GroupBuffer::ready) => continue,
1054				// Once the later groups fill the max buffer, no more of them can be held while it waits,
1055				// so move on to the next group even with nothing of it read yet: it reads as the
1056				// cursor's group, and each such skip refunds what the group left behind held.
1057				false if self.memory.full() => self
1058					.pending
1059					.iter()
1060					.position(|group| group.start > self.current)
1061					.map(|i| (i, self.pending[i].min_timestamp.and_then(time))),
1062				false => None,
1063			};
1064
1065			if let Some((new_idx, next_start)) = target {
1066				self.skip_to(new_idx, next_start, current_end)?;
1067				continue;
1068			}
1069
1070			if finished && self.pending.is_empty() {
1071				if let Reader::Failed(..) = self.reader
1072					&& let Reader::Failed(_, err) = std::mem::replace(&mut self.reader, Reader::Lost)
1073				{
1074					// The caller only gets the bare error, with nothing to say which track died.
1075					tracing::warn!(track = &*self.name, error = ?err, "track failed; ending the reader");
1076					return Poll::Ready(Err(err));
1077				}
1078				return Poll::Ready(Ok(None));
1079			}
1080
1081			return Poll::Pending;
1082		}
1083	}
1084
1085	// Before the first item, move the cursor past its group when that group's first frame trails the
1086	// newest content by more than the budget and the next group still starts at or before the live
1087	// edge less the reach, so it is not what the start covers, and repeat for the group it lands on.
1088	// Returns whether it moved.
1089	fn start_skip(&mut self, waiter: &kio::Waiter) -> Result<bool, F::Error> {
1090		// The newest content lies in the highest group with a timestamp, which a skip never drops, so
1091		// one read serves every skip and a long backlog is walked once.
1092		let mut newest = None;
1093		let mut moved = false;
1094		while let Some(group) = self.pending.front_mut() {
1095			if group.start > self.current {
1096				break;
1097			}
1098			let _ = group.poll_min_timestamp(waiter, &self.format, true);
1099			let Some(first) = group.buffered.front().and_then(|(frame, ..)| time(frame.timestamp)) else {
1100				break;
1101			};
1102			let current_end = group.max_end;
1103			// The next group that arrived, even one whose first frame is still in flight: that frame
1104			// may land within the budget, so skipping on to a later group could drop the one the start
1105			// belongs on. Until it lands, nothing is skipped, as `@moq/hang`'s consumer waits on its
1106			// successor's start.
1107			let Some(idx) = self.pending.iter().position(|group| group.start > self.current) else {
1108				break;
1109			};
1110			let Poll::Ready(Some(next_start)) = self.pending[idx].poll_min_timestamp(waiter, &self.format, false)
1111			else {
1112				break;
1113			};
1114			let Some(next_start) = time(next_start) else {
1115				break;
1116			};
1117			let newest = *newest.get_or_insert_with(|| self.poll_newest(waiter));
1118			// Nothing has been read, so the reader still warms.
1119			if newest.saturating_sub(first) <= self.max_delay.saturating_add(self.warmup) {
1120				break;
1121			}
1122			// The group the start reaches back to is kept: the next one begins past that point.
1123			let reach = self
1124				.min_delay
1125				.unwrap_or_default()
1126				.min(self.max_delay)
1127				.saturating_add(self.warmup);
1128			if !reach.is_zero() && next_start > newest.saturating_sub(reach) {
1129				break;
1130			}
1131			self.skip_to(idx, Some(next_start), current_end)?;
1132			moved = true;
1133		}
1134		Ok(moved)
1135	}
1136
1137	// The first group past the cursor with a timestamp, the skip target, and where it starts.
1138	fn poll_next_group(&mut self, waiter: &kio::Waiter) -> Option<(usize, std::time::Duration)> {
1139		for (i, group) in self.pending.iter_mut().enumerate() {
1140			if group.start <= self.current {
1141				continue;
1142			}
1143
1144			if let Poll::Ready(Some(ts)) = group.poll_min_timestamp(waiter, &self.format, false)
1145				&& let Some(ts) = time(ts)
1146			{
1147				return Some((i, ts));
1148			}
1149		}
1150		None
1151	}
1152
1153	// The max timestamp across the groups past the cursor, or zero without one.
1154	fn poll_newest(&mut self, waiter: &kio::Waiter) -> std::time::Duration {
1155		for group in self.pending.iter_mut().rev() {
1156			if group.start <= self.current {
1157				break;
1158			}
1159
1160			// Older groups won't be newer than this.
1161			if let Poll::Ready(Some(ts)) = group.poll_max_timestamp(waiter, &self.format)
1162				&& let Some(ts) = time(ts)
1163			{
1164				return ts;
1165			}
1166		}
1167		std::time::Duration::ZERO
1168	}
1169
1170	// Move the cursor to the pending group at `new_idx`, dropping what lies below it. `next_start` is
1171	// where that group begins, if read, and `current_end` how far the group left behind presented.
1172	fn skip_to(
1173		&mut self,
1174		new_idx: usize,
1175		next_start: Option<std::time::Duration>,
1176		current_end: Option<std::time::Duration>,
1177	) -> Result<(), F::Error> {
1178		// Without a start read yet, nothing proves the timeline continues.
1179		let hole = next_start.is_none_or(|start| !pts_contiguous(current_end.or(self.presented_end), start));
1180		let had_marker = self.pending.iter().take(new_idx).any(GroupBuffer::marker);
1181		// Buffered frames are thrown away, and `current_end` counts them, so contiguity alone would hide them.
1182		let discarded = self
1183			.pending
1184			.iter()
1185			.take(new_idx)
1186			.any(|group| !group.buffered.is_empty());
1187		// `pending` is in sequence order, so what lies below the target is its prefix.
1188		self.discard_front(new_idx)?;
1189		if hole || had_marker || discarded {
1190			self.lose();
1191		}
1192		let new_current = self.pending.front().map(|g| g.start).unwrap();
1193
1194		tracing::debug!(old = self.current, new = new_current, "skipping slow groups");
1195
1196		self.current = new_current;
1197		self.note_group_edge();
1198		Ok(())
1199	}
1200
1201	// The reader has not yet read the warmup past its first frame.
1202	fn warming(&self) -> bool {
1203		self.warmed
1204			.is_none_or(|warmed| self.edge.is_none_or(|edge| edge < warmed))
1205	}
1206
1207	// The subscription, which only an error ending the reader drops.
1208	fn subscriber(&mut self) -> &mut moq_net::track::Ordered {
1209		match &mut self.reader {
1210			Reader::Reading(track) | Reader::Failed(track, _) => track,
1211			Reader::Ended | Reader::Lost => unreachable!("read only until an error ends the reader"),
1212		}
1213	}
1214
1215	// Media this reader will never deliver: the next item is preceded by a gap.
1216	fn lose(&mut self) {
1217		self.gap = true;
1218		self.unproven = false;
1219	}
1220
1221	fn advance(&mut self, end: std::time::Duration) {
1222		if self.edge.is_none_or(|edge| end > edge) {
1223			self.edge = Some(end);
1224		}
1225	}
1226
1227	fn note_group_edge(&mut self) {
1228		if let Some((_, ts)) = self.start {
1229			self.floor = Some(ts);
1230		}
1231	}
1232
1233	/// Receive group handles and wait for the track and every received group to finish.
1234	pub(crate) fn poll_received(&mut self, waiter: &kio::Waiter) -> Poll<()> {
1235		if let Reader::Ended | Reader::Lost = self.reader {
1236			return Poll::Ready(());
1237		}
1238		ready!(self.poll_read_finish(waiter));
1239		if let Reader::Failed(..) = self.reader {
1240			return Poll::Pending;
1241		}
1242		let first = self
1243			.pending
1244			.partition_point(|group| self.received.is_some_and(|last| group.start <= last));
1245		for group in self.pending.range_mut(first..) {
1246			if !matches!(group.group.poll_finished(waiter), Poll::Ready(Ok(_))) {
1247				return Poll::Pending;
1248			}
1249			self.received = Some(group.start);
1250		}
1251		Poll::Ready(())
1252	}
1253
1254	// Reads any new groups from the track until it finished or failed.
1255	//
1256	// Returns Pending until all groups have been consumed.
1257	fn poll_read_finish(&mut self, waiter: &kio::Waiter) -> Poll<()> {
1258		self.collect_pending(waiter);
1259		self.gated = false;
1260		if let Reader::Failed(..) = self.reader {
1261			return Poll::Ready(());
1262		}
1263		loop {
1264			// Past the max buffer, later groups wait in the transport's cache.
1265			if self.pull_gated() {
1266				self.gated = true;
1267				return Poll::Pending;
1268			}
1269			let next = match ready!(self.subscriber().poll_next_item(waiter)) {
1270				Ok(next) => next,
1271				Err(err) => {
1272					if let Reader::Reading(track) = std::mem::replace(&mut self.reader, Reader::Ended) {
1273						self.reader = Reader::Failed(track, err.into());
1274					}
1275					return Poll::Ready(());
1276				}
1277			};
1278			// Any item shows the subscription answered, so the publisher's largest now says where it
1279			// stood as it began.
1280			self.join(waiter);
1281
1282			let group = match next {
1283				Some(moq_net::track::Item::Group(group)) => group,
1284				// What the ordered reader gave up was never read, so it is backlog when produced before
1285				// the subscription. Its landing is the latest group's, so a gap reaching past the join
1286				// may report one produced since, and folds nothing.
1287				Some(moq_net::track::Item::Gap { range, landed, .. }) => {
1288					if self.joined.is_some_and(|joined| range.end.saturating_sub(1) <= joined) {
1289						self.backlog = self.backlog.max(landed);
1290					}
1291					continue;
1292				}
1293				// An item this version does not know is not a group to read.
1294				Some(_) => continue,
1295				// Track is finished.
1296				None => return Poll::Ready(()),
1297			};
1298
1299			let reader = GroupBuffer::new(group, self.memory.clone());
1300			// Groups come in key order, so only a live start, which jumped to the newest, leaves any
1301			// below the cursor.
1302			if reader.start < self.current {
1303				tracing::debug!(old = ?reader.start, current = ?self.current, "skipping old group");
1304				Self::skip(self.joined, &mut self.backlog, &reader);
1305				continue;
1306			}
1307			self.pending.push_back(reader);
1308			self.collect_pending(waiter);
1309		}
1310	}
1311
1312	fn collect_pending(&mut self, waiter: &kio::Waiter) {
1313		if self.pending.len() < self.collect_at {
1314			return;
1315		}
1316		let current = self.current;
1317		self.pending.retain_mut(|group| {
1318			// Keep the cursor's gap and anything already decoded, including markers and faults.
1319			// A never-read evicted group holds no event that its missing sequence cannot say.
1320			group.start == current || !group.is_empty() || !group.poll_aborted(waiter)
1321		});
1322		self.collect_at = self.pending.len().saturating_mul(2).max(1);
1323	}
1324
1325	// Whether the max buffer holds back the next group: it is full, and the cursor's group already has a
1326	// successor to move on to, so however small the cap, a stalled group can always be skipped.
1327	fn pull_gated(&self) -> bool {
1328		self.memory.full() && self.pending.len() >= 2
1329	}
1330
1331	// Note `group` dropped without delivering all of it: backlog when the publisher's largest at the
1332	// subscription's start reached it. One above was produced since, such as an outage's.
1333	fn skip(joined: Option<u64>, backlog: &mut Option<Instant>, group: &GroupBuffer<F>) {
1334		if joined.is_some_and(|joined| group.start <= joined) {
1335			*backlog = (*backlog).max(Some(group.group.created()));
1336		}
1337	}
1338
1339	// Take every largest the publisher reported since the last poll.
1340	fn poll_largest(&mut self, waiter: &kio::Waiter) {
1341		while let Poll::Ready(Some(largest)) = self.subscriber().poll_largest(waiter) {
1342			self.largest = self.largest.max(Some(largest.group));
1343		}
1344	}
1345
1346	// Where the publisher stood as the subscription began, taken once: after its answer rather than
1347	// from a group that raced it, and at the latest as the start is decided, before anything is
1348	// dropped against it.
1349	fn join(&mut self, waiter: &kio::Waiter) {
1350		if self.joined.is_some() {
1351			return;
1352		}
1353		self.poll_largest(waiter);
1354		self.joined = self.largest;
1355	}
1356
1357	// Drop the pending groups `pick` selects without delivering them. A drop must not hide what
1358	// was already found, so the lowest one holding a fault, or with frames below the start of the
1359	// latest delivered group, ends the reader instead. What was never read stays unread: decoding
1360	// data only to throw it away is work a peer could force.
1361	fn discard(&mut self, mut pick: impl FnMut(&mut GroupBuffer<F>) -> bool) -> Result<(), F::Error> {
1362		let start = self.start;
1363		let mut fault = None;
1364		let (joined, backlog) = (self.joined, &mut self.backlog);
1365		self.pending.retain_mut(|group| {
1366			if !pick(group) {
1367				return true;
1368			}
1369			Self::skip(joined, backlog, group);
1370			if fault.is_none() {
1371				fault = Self::discard_fault(start, group);
1372			}
1373			false
1374		});
1375		self.discarded(fault)
1376	}
1377
1378	// `discard` of the lowest `count` pending groups, in time proportional to them rather than to every
1379	// pending group, so a start that skips a long backlog one group at a time stays linear.
1380	fn discard_front(&mut self, count: usize) -> Result<(), F::Error> {
1381		let start = self.start;
1382		let mut fault = None;
1383		for mut group in self.pending.drain(..count) {
1384			Self::skip(self.joined, &mut self.backlog, &group);
1385			if fault.is_none() {
1386				fault = Self::discard_fault(start, &mut group);
1387			}
1388		}
1389		self.discarded(fault)
1390	}
1391
1392	// The fault a discarded group would hide: its own, or frames below the latest delivered start.
1393	fn discard_fault(start: Option<(u64, Timestamp)>, group: &mut GroupBuffer<F>) -> Option<F::Error> {
1394		match (start, group.min_timestamp) {
1395			(Some((prev, floor)), Some(min))
1396				if group.start > prev
1397					&& time(min)
1398						.zip(time(floor))
1399						.is_some_and(|(min, floor)| min.as_micros() < floor.as_micros()) =>
1400			{
1401				Some(TimestampRewind { timestamp: min, floor }.into())
1402			}
1403			_ => group.fault.take(),
1404		}
1405	}
1406
1407	fn discarded(&self, fault: Option<F::Error>) -> Result<(), F::Error> {
1408		match fault {
1409			Some(err) => {
1410				tracing::warn!(track = &*self.name, error = ?err, "discarded a malformed group; ending the reader");
1411				Err(err)
1412			}
1413			None => Ok(()),
1414		}
1415	}
1416
1417	/// Whether the publisher declared every group start in `groups` skipped, so no group lies
1418	/// there; see [`moq_net::track::Ordered::is_skipped`]. A group with nothing possible
1419	/// below it is its track's first. False once an error ended the reader.
1420	pub fn is_skipped(&self, groups: std::ops::Range<u64>) -> bool {
1421		match &self.reader {
1422			Reader::Reading(track) | Reader::Failed(track, _) => track.is_skipped(groups),
1423			Reader::Ended | Reader::Lost => false,
1424		}
1425	}
1426
1427	/// Set the [`Delay`], mid-stream or before the first read.
1428	///
1429	/// [`Delay::max`] is clamped to the track's max age like [`new`](Self::new). The
1430	/// subscription keeps the requested max verbatim, plus any [`Playout::warmup`]; its ranges
1431	/// keep the live join they were subscribed with (see [`Delay::subscription`]). A
1432	/// [`Delay::min`] moves where this reader keeps a start still to come, reading an unstated one
1433	/// as zero. A min past the max starts at the max, since the publisher serves nothing older. A
1434	/// missing group is given up by the subscription's max alone.
1435	pub fn set_delay(&mut self, delay: Delay) {
1436		self.set_skip(delay);
1437		// An ended reader has no subscription left to tune.
1438		let (Reader::Reading(track) | Reader::Failed(track, _)) = &mut self.reader else {
1439			return;
1440		};
1441		// The transport enforces the same budget on the subscription itself, so a
1442		// tolerance set here has to reach it: otherwise moq-net skips the very groups
1443		// this consumer was told to wait for, before they ever get here. It keeps the
1444		// warmup too, as [`Playout::subscription`] does.
1445		// Only each live join's max, retuned in place: a replaced range resolves again, so the
1446		// ranges keep the join they were subscribed with, and history stays history.
1447		let max = warmed(delay, self.warmup).max;
1448		let current = track.subscription();
1449		let mut subscription = current.clone();
1450		for range in &mut subscription.ranges {
1451			if let moq_net::track::Start::Live { max: held, .. } = &mut range.start {
1452				*held = max;
1453			}
1454		}
1455		if subscription != current {
1456			let _ = track.update(subscription);
1457		}
1458	}
1459
1460	/// Skip at `delay`, clamped like [`set_delay`](Self::set_delay), leaving the subscription's
1461	/// delay as it is. A delay past the subscription's skips nothing later, since the transport
1462	/// drops a group first.
1463	pub(crate) fn skipping_at(mut self, delay: Delay) -> Self {
1464		self.set_skip(delay);
1465		self
1466	}
1467
1468	// Wait and skip at `delay`, its max clamped to the track's max age.
1469	fn set_skip(&mut self, delay: Delay) {
1470		if let Reader::Reading(track) | Reader::Failed(track, _) = &self.reader {
1471			self.min_delay = delay.min;
1472			self.max_delay = delay
1473				.max
1474				.unwrap_or(std::time::Duration::MAX)
1475				.min(track.info().max_age.unwrap_or(std::time::Duration::MAX));
1476		}
1477	}
1478
1479	/// Cap the bytes of decoded frames held ahead of the reader, counting the wire payload they share
1480	/// and each frame's and group's own overhead (default [`DEFAULT_MAX_BUFFER`]). Past it the consumer stops decoding ahead
1481	/// and pulling new groups; see the type docs.
1482	#[cfg(test)]
1483	pub(crate) fn set_max_buffer(&mut self, bytes: usize) {
1484		self.memory.set_max(bytes);
1485	}
1486
1487	/// The bytes currently charged against [`set_max_buffer`](Self::set_max_buffer).
1488	#[cfg(test)]
1489	pub(crate) fn buffered_bytes(&self) -> usize {
1490		self.memory.used()
1491	}
1492}
1493
1494/// Why a group stopped buffering.
1495enum Failure<E> {
1496	/// A consumed payload failed to decode, so the track is malformed.
1497	Decode(E),
1498	/// The transport aborted or evicted the group before its next frame arrived.
1499	Lost(E),
1500}
1501
1502/// Internal reader for a group of frames.
1503///
1504/// Handles two-phase frame reading (get FrameConsumer, then read all data),
1505/// timestamp parsing, and min/max timestamp tracking for age decisions.
1506struct GroupBuffer<F: Container> {
1507	group: moq_net::group::Consumer,
1508
1509	// The current frame index within the group.
1510	index: usize,
1511
1512	content: Content,
1513
1514	// A decode error found while looking ahead, delivered after the frames buffered before it.
1515	fault: Option<F::Error>,
1516
1517	// Read frames that haven't been consumed yet, each with when its wire frame landed.
1518	// Each with when it arrived and what it holds against the max buffer.
1519	buffered: VecDeque<(Frame, Instant, usize)>,
1520	markers: VecDeque<(usize, Timestamp)>,
1521	delivered: usize,
1522
1523	// The consumer's max buffer, and how much of it this group holds, refunded when it drops.
1524	memory: Memory,
1525	charged: usize,
1526
1527	// The minimum timestamp in the group.
1528	min_timestamp: Option<Timestamp>,
1529
1530	// The maximum timestamp in the group.
1531	max_timestamp: Option<Timestamp>,
1532
1533	// The furthest presentation point reached so far, i.e. max(timestamp + duration).
1534	// Equals the max timestamp when the container carries no per-frame duration.
1535	// Stored as a wall-clock duration so cross-scale comparisons are cheap.
1536	max_end: Option<std::time::Duration>,
1537}
1538
1539/// What a group has carried so far.
1540enum Content {
1541	/// No wire frame: an empty group means nothing.
1542	Empty,
1543	/// Wire frames but no media, so a marker once it finishes.
1544	Marker,
1545	/// A data track's marker: one object with no bytes. `ended` once it was read as an end,
1546	/// since it has no timestamp of its own.
1547	Bare { ended: bool },
1548	/// A decodable (non-marker) frame was buffered.
1549	Media,
1550}
1551
1552impl<F: Container> GroupBuffer<F> {
1553	fn new(group: moq_net::group::Consumer, memory: Memory) -> Self {
1554		let mut this = Self {
1555			group,
1556			index: 0,
1557			content: Content::Empty,
1558			fault: None,
1559			buffered: VecDeque::new(),
1560			markers: VecDeque::new(),
1561			delivered: 0,
1562			max_timestamp: None,
1563			min_timestamp: None,
1564			max_end: None,
1565			memory,
1566			charged: 0,
1567		};
1568		this.charge(std::mem::size_of::<Self>());
1569		this
1570	}
1571
1572	/// Poll for the next frame from this group.
1573	/// Whether [`Self::poll_read`] would hand out an item without reading the wire: a frame
1574	/// looked ahead, or a marker it reached.
1575	fn ready(&self) -> bool {
1576		!self.buffered.is_empty() || self.markers.front().is_some_and(|(index, _)| *index <= self.delivered)
1577	}
1578
1579	fn poll_read(&mut self, waiter: &kio::Waiter, format: &F) -> Poll<Result<Option<Event>, Failure<F::Error>>> {
1580		loop {
1581			if self.markers.front().is_some_and(|(index, _)| *index <= self.delivered) {
1582				let (index, end) = self.markers.pop_front().unwrap();
1583				self.refund(MARKER_COST);
1584				return Poll::Ready(Ok(Some(Event::FrameEnd { end, opens: index == 0 })));
1585			}
1586			if let Some((frame, arrived, cost)) = self.buffered.pop_front() {
1587				self.delivered += 1;
1588				self.refund(cost);
1589				return Poll::Ready(Ok(Some(Event::Frame { frame, arrived })));
1590			}
1591			if !ready!(self.buffer_once(waiter, format)?) {
1592				return Poll::Ready(Ok(None));
1593			}
1594		}
1595	}
1596
1597	/// Whether this group, landed on past keys nothing declared skipped, continues the content read
1598	/// before it: a frame of it presents by `bound`, within one millisecond. Its lowest picture
1599	/// decodes within `depth` frames of its first, so it looks no further, nor past its end, its
1600	/// failure, or a full max buffer. `None` while it holds no frame, when an endpoint, its end, or a
1601	/// failure comes first.
1602	fn poll_continues(
1603		&mut self,
1604		waiter: &kio::Waiter,
1605		format: &F,
1606		bound: Option<std::time::Duration>,
1607		depth: usize,
1608	) -> Poll<Option<bool>> {
1609		// Nothing proves a step with nowhere to continue from, so the first frame decides.
1610		let depth = if bound.is_some() { depth } else { 0 };
1611		loop {
1612			if self.buffered.is_empty() && self.ready() {
1613				return Poll::Ready(None);
1614			}
1615			let continues = (self.buffered.iter().take(depth + 1))
1616				.any(|(frame, ..)| time(frame.timestamp).is_some_and(|at| pts_contiguous(bound, at)));
1617			if continues {
1618				return Poll::Ready(Some(true));
1619			}
1620			if self.buffered.len() > depth {
1621				return Poll::Ready(Some(false));
1622			}
1623			// A group holding nothing buffers past a full max buffer, as the cursor's does. One holding
1624			// a frame judges by what it holds, since only reading frames frees the buffer.
1625			let lead = self.buffered.is_empty();
1626			if !lead && self.memory.full() {
1627				return Poll::Ready(Some(false));
1628			}
1629			if !ready!(self.look_once(waiter, format, !lead)) {
1630				return Poll::Ready((!self.buffered.is_empty()).then_some(false));
1631			}
1632		}
1633	}
1634
1635	// Add one more frame to the buffer if possible, first returning a decode error the lookahead kept.
1636	//
1637	// Returns false if the group is finished.
1638	fn buffer_once(&mut self, waiter: &kio::Waiter, format: &F) -> Poll<Result<bool, Failure<F::Error>>> {
1639		if let Some(err) = self.fault.take() {
1640			return Poll::Ready(Err(Failure::Decode(err)));
1641		}
1642		// A failed read is the transport's, while a failed decode is the payload's: an abort of
1643		// the tail behind a malformed frame must not hide that frame.
1644		let wire = match ready!(self.group.poll_read_frame(waiter)) {
1645			Ok(Some(wire)) => wire,
1646			Ok(None) => return Poll::Ready(Ok(false)),
1647			Err(err) if self.poll_aborted(waiter) => return Poll::Ready(Err(Failure::Lost(err.into()))),
1648			Err(err) => return Poll::Ready(Err(Failure::Decode(err.into()))),
1649		};
1650		if matches!(self.content, Content::Empty) {
1651			self.content = Content::Marker;
1652		}
1653		let arrived = wire.created;
1654		let size = wire.payload.len();
1655		let frames = format.decode(wire).map_err(Failure::Decode)?;
1656		if format.kind() == super::Kind::Data {
1657			// A data track's marker is one object with no bytes, alone in its group.
1658			match (&self.content, frames.is_empty()) {
1659				(Content::Bare { .. }, _) | (Content::Media, true) => {
1660					let err = moq_net::Error::Decode(moq_net::DecodeError::ExpectedEnd).into();
1661					return Poll::Ready(Err(Failure::Decode(err)));
1662				}
1663				(_, true) => self.content = Content::Bare { ended: false },
1664				(_, false) => {}
1665			}
1666		}
1667
1668		// Decoded payloads are views of the wire payload, which stays allocated while any of them is
1669		// held, so the last one read also holds whatever of it the views leave out, such as a header.
1670		let mut views = 0;
1671		let first = self.buffered.len();
1672		// Media is timed: a scale-less track's unscaled keys carry no time to present at.
1673		let unscaled = || Failure::Decode(moq_net::Error::TimestampMismatch.into());
1674		for mut frame in frames {
1675			if let Some(bound) = format.end(&frame) {
1676				let end = time(bound).ok_or_else(unscaled)?;
1677				self.note_end(end);
1678				self.markers.push_back((self.index, bound));
1679				self.charge(MARKER_COST);
1680				continue;
1681			}
1682			let at = time(frame.timestamp).ok_or_else(unscaled)?;
1683			let duration = frame
1684				.duration
1685				.map(|duration| time(duration).ok_or_else(unscaled))
1686				.transpose()?;
1687
1688			// Every buffered timestamp has a time, so any two of them compare.
1689			self.min_timestamp = Some(match self.min_timestamp {
1690				Some(existing) if existing <= frame.timestamp => existing,
1691				_ => frame.timestamp,
1692			});
1693
1694			self.max_timestamp = Some(match self.max_timestamp {
1695				Some(existing) if existing > frame.timestamp => existing,
1696				_ => frame.timestamp,
1697			});
1698
1699			// Furthest presentation point, in wall-clock terms so timestamp and
1700			// duration can be at different scales without extra conversions. A frame
1701			// with no duration contributes only its timestamp.
1702			self.note_end(at);
1703			if let Some(duration) = duration {
1704				self.note_end(at + duration);
1705			}
1706
1707			// First frame of a group is always a keyframe by protocol invariant; trust
1708			// the container's flag otherwise so CMAF mid-group keyframes survive.
1709			frame.keyframe = frame.keyframe || self.index == 0;
1710			self.index += 1;
1711			self.content = Content::Media;
1712
1713			let cost = frame_cost(&frame);
1714			views += frame.payload.len();
1715			self.charge(cost);
1716			self.buffered.push_back((frame, arrived, cost));
1717		}
1718		// Views that leave out more than they keep are copied out, freeing the wire payload, so
1719		// whoever holds a frame after the reader retains at most twice its payload.
1720		let rest = size.saturating_sub(views);
1721		if rest > views {
1722			for (frame, ..) in self.buffered.range_mut(first..) {
1723				frame.payload = bytes::Bytes::copy_from_slice(&frame.payload);
1724			}
1725		} else if self.buffered.len() > first
1726			&& rest > 0
1727			&& let Some((_, _, cost)) = self.buffered.back_mut()
1728		{
1729			*cost += rest;
1730			self.charge(rest);
1731		}
1732
1733		Poll::Ready(Ok(true))
1734	}
1735
1736	// Buffer one more frame ahead of the cursor. Nothing here hands an error to a caller, so a
1737	// decode error is kept for the reader rather than dropped with the frame it consumed; a
1738	// transport abort is left for the cursor to find.
1739	//
1740	// Returns false once this group can buffer nothing more. When `capped`, pends without registering
1741	// the waiter while the max buffer is full: only the reader taking frames frees it.
1742	fn look_once(&mut self, waiter: &kio::Waiter, format: &F, capped: bool) -> Poll<bool> {
1743		if self.fault.is_some() {
1744			return Poll::Ready(false);
1745		}
1746		if capped && self.memory.full() {
1747			return Poll::Pending;
1748		}
1749		match ready!(self.buffer_once(waiter, format)) {
1750			Ok(more) => Poll::Ready(more),
1751			Err(Failure::Decode(err)) => {
1752				self.fault = Some(err);
1753				Poll::Ready(false)
1754			}
1755			Err(Failure::Lost(_)) => Poll::Ready(false),
1756		}
1757	}
1758
1759	fn look_all(&mut self, waiter: &kio::Waiter, format: &F) -> Poll<()> {
1760		while ready!(self.look_once(waiter, format, true)) {}
1761		Poll::Ready(())
1762	}
1763
1764	/// Poll for the maximum timestamp in this group, or `None` if it ended without one.
1765	fn poll_max_timestamp(&mut self, waiter: &kio::Waiter, format: &F) -> Poll<Option<Timestamp>> {
1766		// Keep reading more frames just to advance the max timestamp.
1767		let looked = self.look_all(waiter, format);
1768
1769		if let Some(max) = self.max_timestamp {
1770			return Poll::Ready(Some(max));
1771		}
1772		// Frames left unread behind a full max buffer may still carry one.
1773		ready!(looked);
1774		self.poll_ended(waiter)
1775	}
1776
1777	/// Poll for the minimum timestamp in this group, or `None` if it ended without one. A `lead` group
1778	/// buffers past a full max buffer only while it holds nothing, endpoint markers included.
1779	fn poll_min_timestamp(&mut self, waiter: &kio::Waiter, format: &F, lead: bool) -> Poll<Option<Timestamp>> {
1780		// A wire frame can decode to no media frames, so keep going until one is buffered.
1781		let mut looked = Poll::Ready(());
1782		while self.buffered.is_empty() {
1783			let capped = !lead || !self.markers.is_empty();
1784			match self.look_once(waiter, format, capped) {
1785				Poll::Ready(true) => continue,
1786				Poll::Ready(false) => break,
1787				Poll::Pending => {
1788					looked = Poll::Pending;
1789					break;
1790				}
1791			}
1792		}
1793
1794		if let Some(min) = self.min_timestamp {
1795			return Poll::Ready(Some(min));
1796		}
1797		// Frames left unread behind a full max buffer may still carry one.
1798		ready!(looked);
1799		self.poll_ended(waiter)
1800	}
1801
1802	// Ready with no timestamp once the group can no longer produce one: it ended or failed to decode.
1803	fn poll_ended(&mut self, waiter: &kio::Waiter) -> Poll<Option<Timestamp>> {
1804		if self.fault.is_some() || self.group.poll_finished(waiter).is_ready() {
1805			return Poll::Ready(None);
1806		}
1807		Poll::Pending
1808	}
1809
1810	/// True if the transport can no longer deliver the frame this group is stopped on:
1811	/// the stream was reset (evicted, `Old`, cancelled, oversized, ...).
1812	fn poll_aborted(&mut self, waiter: &kio::Waiter) -> bool {
1813		matches!(self.group.poll_finished(waiter), Poll::Ready(Err(_)))
1814	}
1815
1816	/// True if this group holds nothing to deliver and never will: aborted with nothing
1817	/// buffered, no endpoint decoded, and no fault to report.
1818	fn reapable(&mut self, waiter: &kio::Waiter) -> bool {
1819		self.buffered.is_empty() && self.markers.is_empty() && self.fault.is_none() && self.poll_aborted(waiter)
1820	}
1821
1822	fn note_end(&mut self, end: std::time::Duration) {
1823		self.max_end = Some(self.max_end.map_or(end, |existing| existing.max(end)));
1824	}
1825
1826	fn marker(&self) -> bool {
1827		matches!(self.content, Content::Marker | Content::Bare { .. })
1828	}
1829
1830	/// The group has carried no wire frame.
1831	fn is_empty(&self) -> bool {
1832		matches!(self.content, Content::Empty)
1833	}
1834
1835	fn charge(&mut self, bytes: usize) {
1836		self.charged += bytes;
1837		self.memory.charge(bytes);
1838	}
1839
1840	fn refund(&mut self, bytes: usize) {
1841		self.charged -= bytes;
1842		self.memory.refund(bytes);
1843	}
1844}
1845
1846impl<F: Container> Drop for GroupBuffer<F> {
1847	fn drop(&mut self) {
1848		self.memory.refund(self.charged);
1849	}
1850}
1851
1852/// What a buffered endpoint marker holds against the max buffer.
1853const MARKER_COST: usize = std::mem::size_of::<(usize, Timestamp)>();
1854
1855/// What a buffered frame holds against the max buffer: its payload and its own entry.
1856pub(crate) fn frame_cost(frame: &Frame) -> usize {
1857	std::mem::size_of::<(Frame, Instant, usize)>() + frame.payload.len()
1858}
1859
1860impl<F: Container> std::ops::Deref for GroupBuffer<F> {
1861	type Target = moq_net::group::Consumer;
1862
1863	fn deref(&self) -> &Self::Target {
1864		&self.group
1865	}
1866}
1867
1868#[cfg(test)]
1869mod tests {
1870	use super::Container as ContainerTrait;
1871	use super::*;
1872	use crate::catalog::hang::Wire;
1873	use crate::container::test_util::Lazy;
1874
1875	/// The subscription a consumer still reads.
1876	fn subscribed<F: ContainerTrait>(consumer: &Consumer<F>) -> &moq_net::track::Ordered {
1877		match &consumer.reader {
1878			Reader::Reading(track) | Reader::Failed(track, _) => track,
1879			Reader::Ended | Reader::Lost => panic!("the reader ended"),
1880		}
1881	}
1882	use std::time::Duration;
1883
1884	use bytes::Bytes;
1885
1886	/// A track published at one origin and read from another over a lite-07 session: a received
1887	/// copy, whose ordered reader waits for a group the feed still owes, as a player's does. A
1888	/// locally produced track owes nothing, so a hole there is stepped over at once.
1889	struct Received {
1890		track: moq_net::track::Producer,
1891		remote: moq_net::broadcast::Consumer,
1892		_route: moq_net::origin::Route,
1893		_link: crate::container::test_util::Link,
1894	}
1895
1896	impl Received {
1897		async fn new() -> Self {
1898			Self::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await
1899		}
1900
1901		async fn with_info(info: moq_net::track::Info) -> Self {
1902			use crate::container::test_util::{Link, origin};
1903
1904			let (publisher, subscriber) = (origin(), origin());
1905			let link = Link::new(&publisher, &subscriber).await;
1906			let route = publisher
1907				.route("room", moq_net::origin::RouteOptions::hidden())
1908				.unwrap();
1909			let track = route.broadcast().create_track("data", info).unwrap();
1910			route.announce().unwrap();
1911			let remote = subscriber
1912				.consume()
1913				.follow("room", None)
1914				.unwrap()
1915				.available()
1916				.await
1917				.unwrap()
1918				.unwrap();
1919			Self {
1920				track,
1921				remote,
1922				_route: route,
1923				_link: link,
1924			}
1925		}
1926
1927		/// Subscribe to the copy at `delay`.
1928		async fn subscribe(&self, delay: Delay) -> moq_net::track::Subscriber {
1929			self.subscribe_with(
1930				delay.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL])),
1931			)
1932			.await
1933		}
1934
1935		async fn subscribe_with(&self, subscription: moq_net::track::Subscription) -> moq_net::track::Subscriber {
1936			self.remote
1937				.track("data")
1938				.unwrap()
1939				.subscribe(subscription)
1940				.await
1941				.unwrap()
1942		}
1943
1944		/// A reader of the copy at `delay`.
1945		async fn reader(&self, delay: Delay) -> Consumer<Wire> {
1946			Consumer::new(self.subscribe(delay).await, Wire::legacy(crate::container::Kind::Data))
1947		}
1948	}
1949
1950	/// Let the session carry what was written to the copy, without moving the clock.
1951	async fn carried() {
1952		for _ in 0..64 {
1953			tokio::task::yield_now().await;
1954		}
1955	}
1956
1957	/// A millisecond track: the frames written here carry timestamps. It sets no publisher max
1958	/// age, so the test's delay budget alone decides which superseded groups are read.
1959	fn timed() -> moq_net::track::Info {
1960		moq_net::track::Info::default()
1961			.with_timescale(moq_net::Timescale::MILLI)
1962			.with_max_age(None)
1963	}
1964
1965	/// Mint a standalone track for tests via a throwaway broadcast, since tracks are
1966	/// born from their broadcast (no public `track::Producer::new`).
1967	fn track_producer(
1968		name: impl Into<std::sync::Arc<str>>,
1969		info: impl Into<Option<moq_net::track::Info>>,
1970	) -> moq_net::track::Producer {
1971		moq_net::broadcast::Info::new()
1972			.produce()
1973			.create_track(name, info)
1974			.unwrap()
1975	}
1976
1977	fn ts(micros: u64) -> Timestamp {
1978		Timestamp::from_micros(micros).unwrap()
1979	}
1980
1981	/// Test-only container that round-trips a per-sample duration on the wire, so the
1982	/// duration-based skip can be exercised without building a real CMAF init segment.
1983	/// Each frame is `[timestamp_us: u64 LE][duration_us: u64 LE][payload]`.
1984	struct DurationWire;
1985
1986	/// Encode a `[timestamp][duration][payload]` DurationWire frame.
1987	fn encode_duration_frame(timestamp: Timestamp, duration: Timestamp) -> Vec<u8> {
1988		let mut buf = Vec::with_capacity(18);
1989		buf.extend_from_slice(&(timestamp.as_micros().unwrap() as u64).to_le_bytes());
1990		buf.extend_from_slice(&(duration.as_micros().unwrap() as u64).to_le_bytes());
1991		buf.extend_from_slice(&[0xDE, 0xAD]);
1992		buf
1993	}
1994
1995	impl ContainerTrait for DurationWire {
1996		type Error = crate::Error;
1997
1998		fn write(&self, group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
1999			// The duration tests write frames directly via `write_duration_frame`;
2000			// this path just preserves the timestamp with an unknown duration.
2001			for frame in frames {
2002				group.write_frame(frame.timestamp, encode_duration_frame(frame.timestamp, ts(0)))?;
2003			}
2004			Ok(())
2005		}
2006
2007		fn decode(&self, frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
2008			use bytes::Buf;
2009
2010			let mut data = frame.payload;
2011			let timestamp = ts(data.get_u64_le());
2012			let duration = ts(data.get_u64_le());
2013			let payload = data.copy_to_bytes(data.remaining());
2014
2015			Ok(vec![Frame {
2016				timestamp,
2017				decode: None,
2018				payload,
2019				keyframe: false,
2020				duration: Some(duration),
2021			}])
2022		}
2023	}
2024
2025	/// Write one DurationWire frame (timestamp and duration in µs) into a group.
2026	fn write_duration_frame(group: &mut Lazy, timestamp: Timestamp, duration: Timestamp) {
2027		group
2028			.write_frame(timestamp, encode_duration_frame(timestamp, duration))
2029			.unwrap();
2030	}
2031
2032	/// Each presentation time with a decode time that never decreases: the latest so far, which
2033	/// Legacy's prefix leaves the presentation time to.
2034	fn decoded(timestamps: &[Timestamp]) -> Vec<(Timestamp, Option<Timestamp>)> {
2035		let mut latest: Option<Timestamp> = None;
2036		timestamps
2037			.iter()
2038			.map(|&timestamp| {
2039				let decode = latest.filter(|latest| *latest > timestamp);
2040				latest = Some(decode.unwrap_or(timestamp));
2041				(timestamp, decode)
2042			})
2043			.collect()
2044	}
2045
2046	/// Append a finished group keyed by its first frame's time, as a container producer keys
2047	/// them, so a live join measures it in the track's timescale and the publisher says no group
2048	/// starts between it and the last (Wire::legacy(crate::container::Kind::Data) format).
2049	fn append_timed(track: &mut moq_net::track::Producer, timestamps: &[Timestamp]) {
2050		let mut group = Lazy::appending(track);
2051		for (timestamp, decode) in decoded(timestamps) {
2052			let frame = Frame {
2053				timestamp,
2054				decode,
2055				payload: Bytes::from_static(&[0xDE, 0xAD]),
2056				keyframe: false,
2057				duration: None,
2058			};
2059			Wire::legacy(crate::container::Kind::Data)
2060				.write(&mut group.writer(), &[frame])
2061				.unwrap();
2062		}
2063		group.finish().unwrap();
2064	}
2065
2066	/// Write a Legacy frame of `payload` at `timestamp`, creating `group` with it when it is the first.
2067	fn write_hang(group: &mut Lazy, timestamp: Timestamp, payload: Bytes) {
2068		let mut buf = bytes::BytesMut::new();
2069		hang::container::Frame { timestamp, payload }.encode(&mut buf).unwrap();
2070		let mut writer = group.writer();
2071		// The prefix keeps the presentation time, and the transport the newest so far.
2072		let transport = writer
2073			.latest()
2074			.filter(|latest| timestamp < *latest)
2075			.unwrap_or(timestamp);
2076		writer.write_frame(transport, buf.freeze()).unwrap();
2077	}
2078
2079	/// A group whose first Legacy data frame, at `timestamp`, is still in flight: write the bytes
2080	/// returned to land it.
2081	fn in_flight(track: &moq_net::track::Producer, timestamp: Timestamp) -> (moq_net::frame::Producer, Bytes) {
2082		let mut buf = bytes::BytesMut::new();
2083		hang::container::Frame {
2084			timestamp,
2085			payload: Bytes::from_static(&[0xDE, 0xAD]),
2086		}
2087		.encode(&mut buf)
2088		.unwrap();
2089		let size = buf.len() as u64;
2090		let frame = track.create_frame(moq_net::frame::Info { timestamp, size }).unwrap();
2091		(frame, buf.freeze())
2092	}
2093
2094	/// Write a finished group of `timestamps`, keyed by the first, with nothing between it and the
2095	/// newest group the track holds (Wire::legacy(crate::container::Kind::Data) format).
2096	fn write_group(track: &mut moq_net::track::Producer, timestamps: &[Timestamp]) {
2097		skip_to(track, timestamps[0]);
2098		write_group_after_gap(track, timestamps);
2099	}
2100
2101	/// Say no group starts between the newest the track holds and `timestamp`.
2102	fn skip_to(track: &moq_net::track::Producer, timestamp: Timestamp) {
2103		let key = crate::start::key(track, timestamp).unwrap();
2104		let from = track.largest().map_or(0, |largest| largest.group + 1);
2105		if from < key {
2106			track.skip_groups(from..key);
2107		}
2108	}
2109
2110	/// [`write_group`], leaving the starts between it and the newest group unproduced: a hole.
2111	fn write_group_after_gap(track: &mut moq_net::track::Producer, timestamps: &[Timestamp]) {
2112		let mut group = Lazy::new(track);
2113		for (timestamp, decode) in decoded(timestamps) {
2114			let frame = Frame {
2115				timestamp,
2116				decode,
2117				payload: Bytes::from_static(&[0xDE, 0xAD]),
2118				keyframe: false,
2119				duration: None,
2120			};
2121			Wire::legacy(crate::container::Kind::Data)
2122				.write(&mut group.writer(), &[frame])
2123				.unwrap();
2124		}
2125		group.finish().unwrap();
2126	}
2127
2128	/// Drain all available frames with a per-read timeout.
2129	async fn read_all(consumer: &mut Consumer<Wire>) -> Result<Vec<Frame>, crate::Error> {
2130		let mut frames = Vec::new();
2131		loop {
2132			match kio::clock::timeout(Duration::from_millis(200), consumer.read_frame()).await {
2133				Ok(Ok(Some(frame))) => frames.push(frame),
2134				Ok(Ok(None)) => break,
2135				Ok(Err(e)) => return Err(e),
2136				Err(_) => panic!(
2137					"read_all: Consumer::read timed out after 200ms ({} frames collected so far)",
2138					frames.len()
2139				),
2140			}
2141		}
2142		Ok(frames)
2143	}
2144
2145	/// Read a continuous sequence, refusing gaps and declared stops.
2146	async fn continuous_frames<F: ContainerTrait>(consumer: &mut Consumer<F>) -> Vec<Frame>
2147	where
2148		F::Error: std::fmt::Debug,
2149	{
2150		let mut frames = Vec::new();
2151		while let Some(read) = consumer.read().await.unwrap() {
2152			let Read::Frame { frame, .. } = read else {
2153				panic!("unexpected break: {read:?}")
2154			};
2155			frames.push(frame);
2156		}
2157		frames
2158	}
2159
2160	/// Wrap `track` so only the container consumer performs age skips. The
2161	/// transport gets the media track's full max age and hands over every
2162	/// fresh group; what the container does with them is what the test measures.
2163	///
2164	/// Both layers enforce the same budget, and normally should: the transport skipping
2165	/// a group the consumer was going to skip anyway just saves the bandwidth. These
2166	/// tests are the exception, since they are about the consumer's half of it.
2167	fn container_max_delay_only(track: moq_net::track::Subscriber, max_delay: std::time::Duration) -> Consumer<Wire> {
2168		let control = track.control();
2169		let mut consumer = Consumer::new(track, Wire::legacy(crate::container::Kind::Data));
2170		consumer.set_delay(Delay {
2171			max: Some(max_delay),
2172			..Delay::default()
2173		});
2174		control
2175			.update(
2176				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2177					moq_net::track::Start::Live {
2178						min: Some(Duration::from_secs(30)),
2179						max: Some(Duration::from_secs(30)),
2180					},
2181				)]),
2182			)
2183			.unwrap();
2184		consumer
2185	}
2186
2187	// ---- Basic Reading ----
2188
2189	#[kio::test]
2190	async fn read_single_group() {
2191		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2192		let consumer_track =
2193			track.subscribe(
2194				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2195					moq_net::track::Start::Live {
2196						min: Some(Duration::from_millis(500)),
2197						max: Some(Duration::from_millis(500)),
2198					},
2199				)]),
2200			);
2201		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
2202
2203		write_group(&mut track, &[ts(0)]);
2204		let _track = track.finish().unwrap();
2205
2206		let frames = read_all(&mut consumer).await.unwrap();
2207		assert_eq!(frames.len(), 1);
2208		assert_eq!(frames[0].timestamp, ts(0));
2209		assert!(frames[0].keyframe);
2210
2211		// Next read returns None (track ended)
2212		assert!(consumer.read().await.unwrap().is_none());
2213	}
2214
2215	/// Write a marker group at `timestamp`, with nothing between it and the newest group.
2216	fn write_marker_group(track: &mut moq_net::track::Producer, timestamp: Timestamp) {
2217		skip_to(track, timestamp);
2218		write_marker_group_after_gap(track, timestamp);
2219	}
2220
2221	/// [`write_marker_group`], leaving a hole before it.
2222	fn write_marker_group_after_gap(track: &mut moq_net::track::Producer, timestamp: Timestamp) {
2223		let mut group = Lazy::new(track);
2224		Wire::legacy(crate::container::Kind::Audio)
2225			.write(
2226				&mut group.writer(),
2227				&[Frame {
2228					timestamp,
2229					decode: None,
2230					payload: Bytes::new(),
2231					keyframe: false,
2232					duration: None,
2233				}],
2234			)
2235			.unwrap();
2236		group.finish().unwrap();
2237	}
2238
2239	/// Every item until the track ends: a frame as its timestamp in µs, a gap as its start and
2240	/// span in µs, or an end.
2241	async fn items(consumer: &mut Consumer<Wire>) -> Vec<String> {
2242		let mut items = Vec::new();
2243		while let Some(read) = consumer.read().await.unwrap() {
2244			items.push(match read {
2245				Read::Frame { frame, .. } => frame.timestamp.as_micros().unwrap().to_string(),
2246				Read::Gap { timestamp, duration } => {
2247					format!("gap {}+{}", timestamp.as_micros().unwrap(), duration.as_micros())
2248				}
2249				Read::End { end, .. } => format!("end {}", end.as_micros().unwrap()),
2250			});
2251		}
2252		items
2253	}
2254
2255	/// An endpoint looked ahead in the next group is delivered though that group then aborts: it is
2256	/// decoded, so only a group holding nothing at all is reaped.
2257	#[kio::test]
2258	async fn a_looked_ahead_endpoint_outlives_its_groups_abort() {
2259		let track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
2260		let subscription =
2261			track.subscribe(
2262				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2263					moq_net::track::Start::Live {
2264						min: Some(Duration::from_secs(10)),
2265						max: Some(Duration::from_secs(10)),
2266					},
2267				)]),
2268			);
2269		let mut consumer = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Audio));
2270		let mut head = Lazy::following(&track);
2271		Wire::legacy(crate::container::Kind::Audio)
2272			.write(
2273				&mut head.writer(),
2274				&[Frame {
2275					timestamp: ts(0),
2276					decode: None,
2277					payload: Bytes::from_static(&[0xDE, 0xAD]),
2278					keyframe: true,
2279					duration: None,
2280				}],
2281			)
2282			.unwrap();
2283		assert!(matches!(
2284			consumer.read().await.unwrap(),
2285			Some(Read::Frame { group: 0, .. })
2286		));
2287		let mut next = Lazy::following(&track);
2288		write_marker(&mut next, ts(20_000));
2289		// Group 0 is still open, so the read blocks and looks ahead into group 1.
2290		assert!(consumer.poll_read(&kio::Waiter::noop()).is_pending());
2291		next.abort(moq_net::Error::Cancel).unwrap();
2292		assert!(consumer.poll_read(&kio::Waiter::noop()).is_pending());
2293		head.finish().unwrap();
2294		let _track = track.finish().unwrap();
2295		assert_eq!(items(&mut consumer).await, ["end 20000"]);
2296	}
2297
2298	/// Joining a paused track, whose only served group is a marker, reads the end without
2299	/// waiting for media to resume.
2300	#[tokio::test(start_paused = true)]
2301	async fn a_join_on_a_marker_group_reads_its_end() {
2302		let mut track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
2303		let subscription =
2304			track.subscribe(
2305				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2306					moq_net::track::Start::Live {
2307						min: Some(Duration::from_secs(10)),
2308						max: Some(Duration::from_secs(10)),
2309					},
2310				)]),
2311			);
2312		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Audio));
2313		write_marker_group_after_gap(&mut track, ts(1_000_000));
2314
2315		let mut read = async || {
2316			kio::clock::timeout(Duration::from_secs(1), reader.read())
2317				.await
2318				.expect("the end is read while the track stays open")
2319				.unwrap()
2320		};
2321		assert!(matches!(read().await, Some(Read::End { group: 1_000_000, end }) if end == ts(1_000_000)));
2322	}
2323
2324	/// A data track's marker carries no timestamp, so it reads as an end at the furthest point
2325	/// read rather than as a gap, and as nothing before the first item.
2326	#[tokio::test(start_paused = true)]
2327	async fn a_data_marker_reads_as_an_end_at_the_edge() {
2328		let hour = Duration::from_secs(3600);
2329		let info = hang::container::track_info(hang::catalog::PRIORITY.audio).with_max_age(hour);
2330		let track = track_producer("data", info);
2331		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range {
2332			start: moq_net::track::Start::Time(0),
2333			end: None,
2334			..Default::default()
2335		}]);
2336		let mut reader = Consumer::new(
2337			track.subscribe(subscription),
2338			Wire::legacy(crate::container::Kind::Data),
2339		);
2340		let mut producer = crate::container::Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2341		let frame = |micros, payload: &'static [u8]| Frame {
2342			timestamp: ts(micros),
2343			decode: None,
2344			payload: Bytes::from_static(payload),
2345			keyframe: true,
2346			duration: None,
2347		};
2348
2349		producer.discontinuity().unwrap();
2350		producer.write(frame(0, b"a")).unwrap();
2351		producer.write(frame(10_000, b"")).unwrap();
2352		producer.discontinuity().unwrap();
2353		producer.write(frame(2_405_070_000, b"b")).unwrap();
2354		let _finished = producer.finish().unwrap();
2355
2356		assert_eq!(items(&mut reader).await, ["0", "10000", "end 10000", "2405070000"]);
2357	}
2358
2359	/// A data marker has no timestamp, so a group missing between the content read and the marker's
2360	/// start is lost, not covered by the break it declares.
2361	#[tokio::test(start_paused = true)]
2362	async fn a_hole_before_a_terminal_data_marker_is_a_gap() {
2363		let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.audio));
2364		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range {
2365			start: moq_net::track::Start::Time(0),
2366			end: None,
2367			..Default::default()
2368		}]);
2369		let mut reader = Consumer::new(
2370			track.subscribe(subscription),
2371			Wire::legacy(crate::container::Kind::Data),
2372		);
2373		write_group(&mut track, &[ts(0), ts(10_000)]);
2374		let mut group = Lazy::new(&track);
2375		group.write_frame(ts(20_000), Bytes::new()).unwrap();
2376		group.finish().unwrap();
2377		let _track = track.finish().unwrap();
2378
2379		assert_eq!(items(&mut reader).await, ["0", "10000", "gap 10000+0", "end 10000"]);
2380	}
2381
2382	/// A missing group before a marker on a paused track is given up by the max delay's wall clock,
2383	/// since no newer media will age it out, and wakes the reader when it is.
2384	#[tokio::test(start_paused = true)]
2385	async fn a_sequence_hole_before_a_paused_data_marker_expires() {
2386		for budget in [Duration::ZERO, Duration::from_millis(100)] {
2387			let mut copy = Received::new().await;
2388			let mut reader = copy.reader(Delay::default().with_min(None).with_max(budget)).await;
2389			write_group(&mut copy.track, &[ts(10_000)]);
2390			assert!(matches!(reader.read().await.unwrap(), Some(Read::Frame { .. })));
2391			let mut marker = Lazy::new(&copy.track);
2392			marker.write_frame(ts(20_000), Bytes::new()).unwrap();
2393			marker.finish().unwrap();
2394			carried().await;
2395
2396			if !budget.is_zero() {
2397				assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2398				tokio::time::advance(budget - Duration::from_millis(1)).await;
2399				assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2400				let before = kio::clock::now();
2401				let read = kio::clock::timeout(Duration::from_millis(2), reader.read())
2402					.await
2403					.unwrap()
2404					.unwrap();
2405				assert!(matches!(read, Some(Read::Gap { .. })));
2406				assert_eq!(
2407					before.elapsed(),
2408					Duration::from_millis(1),
2409					"the budget wakes the reader"
2410				);
2411			} else {
2412				let read = kio::clock::timeout(Duration::ZERO, reader.read())
2413					.await
2414					.unwrap()
2415					.unwrap();
2416				assert!(matches!(read, Some(Read::Gap { .. })));
2417			}
2418			assert!(
2419				matches!(reader.poll_read(&kio::Waiter::noop()), Poll::Ready(Ok(Some(Read::End { group: 20_000, end }))) if end == ts(10_000))
2420			);
2421			let _track = copy.track.finish().unwrap();
2422		}
2423	}
2424
2425	#[tokio::test(start_paused = true)]
2426	async fn a_filled_sequence_hole_gives_the_next_hole_a_fresh_budget() {
2427		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
2428		let subscriber = copy
2429			.subscribe_with(
2430				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2431					moq_net::track::Start::Live {
2432						min: Some(Duration::from_millis(100)),
2433						max: Some(Duration::from_millis(100)),
2434					},
2435				)]),
2436			)
2437			.await;
2438		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
2439		write_group(&mut copy.track, &[ts(0)]);
2440		carried().await;
2441		assert!(matches!(
2442			reader.read().await.unwrap(),
2443			Some(Read::Frame { group: 0, .. })
2444		));
2445		// The hole is the start at 10 ms alone.
2446		copy.track.skip_groups(1..10_000);
2447		copy.track.skip_groups(10_001..20_000);
2448		write_group_after_gap(&mut copy.track, &[ts(20_000)]);
2449		carried().await;
2450		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2451		tokio::time::advance(Duration::from_millis(50)).await;
2452		carried().await;
2453		write_group(&mut copy.track, &[ts(10_000)]);
2454		carried().await;
2455		assert!(matches!(
2456			reader.read().await.unwrap(),
2457			Some(Read::Frame { group: 10_000, .. })
2458		));
2459		assert!(matches!(
2460			reader.read().await.unwrap(),
2461			Some(Read::Frame { group: 20_000, .. })
2462		));
2463		let mut marker = Lazy::new(&copy.track);
2464		marker.write_frame(ts(30_000), Bytes::new()).unwrap();
2465		marker.finish().unwrap();
2466		carried().await;
2467		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2468		tokio::time::advance(Duration::from_millis(99)).await;
2469		carried().await;
2470		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2471		tokio::time::advance(Duration::from_millis(1)).await;
2472		carried().await;
2473		assert!(matches!(
2474			reader.poll_read(&kio::Waiter::noop()),
2475			Poll::Ready(Ok(Some(Read::Gap { .. })))
2476		));
2477		assert!(matches!(
2478			reader.read().await.unwrap(),
2479			Some(Read::End { group: 30_000, .. })
2480		));
2481		let _track = copy.track.finish().unwrap();
2482	}
2483
2484	/// The arrival is when a frame landed, not when it was read, and a break keeps the last one.
2485	#[tokio::test(start_paused = true)]
2486	async fn arrival_is_when_the_frame_landed() {
2487		let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.video));
2488		let subscriber =
2489			track.subscribe(
2490				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2491					moq_net::track::Start::Live {
2492						min: Some(Duration::from_secs(1)),
2493						max: Some(Duration::from_secs(1)),
2494					},
2495				)]),
2496			);
2497		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
2498		assert_eq!(reader.arrival(), None, "nothing read yet");
2499
2500		let first = kio::clock::now();
2501		write_group(&mut track, &[ts(0)]);
2502		tokio::time::advance(Duration::from_millis(30)).await;
2503		let second = kio::clock::now();
2504		write_group(&mut track, &[ts(33_000)]);
2505		tokio::time::advance(Duration::from_millis(30)).await;
2506
2507		assert!(matches!(
2508			reader.read().await.unwrap(),
2509			Some(Read::Frame { group: 0, .. })
2510		));
2511		assert_eq!(reader.arrival(), Some(first));
2512		assert!(matches!(
2513			reader.read().await.unwrap(),
2514			Some(Read::Frame { group: 33_000, .. })
2515		));
2516		assert_eq!(reader.arrival(), Some(second));
2517
2518		let mut marker = Lazy::following(&track);
2519		marker.write_frame(ts(66_000), Bytes::new()).unwrap();
2520		marker.finish().unwrap();
2521		assert!(matches!(
2522			reader.read().await.unwrap(),
2523			Some(Read::End { group: 66_000, .. })
2524		));
2525		assert_eq!(reader.arrival(), Some(second), "an end carries no arrival of its own");
2526	}
2527
2528	/// A group at or below the publisher's largest when the subscription began was produced
2529	/// before it: dropped unread below the cursor, it is the join's backlog, and the reader
2530	/// reports when it landed. One produced since, such as an outage's, is not.
2531	#[tokio::test(start_paused = true)]
2532	async fn a_backlog_group_below_the_cursor_reports_when_it_landed() {
2533		let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.audio));
2534		let subscriber =
2535			track.subscribe(
2536				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2537					moq_net::track::Start::Live {
2538						min: Some(Duration::from_secs(10)),
2539						max: Some(Duration::from_secs(10)),
2540					},
2541				)]),
2542			);
2543		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Audio));
2544		reader.set_delay(
2545			Delay::default()
2546				.with_min(Duration::from_millis(50))
2547				.with_max(Duration::from_secs(10)),
2548		);
2549
2550		// The publisher stood at group 5 as the subscription began.
2551		write_group_after_gap(&mut track, &[ts(100_000)]);
2552		assert!(matches!(
2553			reader.read().await.unwrap(),
2554			Some(Read::Frame { group: 100_000, .. })
2555		));
2556		write_group(&mut track, &[ts(120_000)]);
2557		assert!(matches!(
2558			reader.read().await.unwrap(),
2559			Some(Read::Frame { group: 120_000, .. })
2560		));
2561
2562		tokio::time::advance(Duration::from_millis(30)).await;
2563		write_group(&mut track, &[ts(80_000)]);
2564		write_group(&mut track, &[ts(140_000)]);
2565		assert!(matches!(
2566			reader.read().await.unwrap(),
2567			Some(Read::Frame { group: 140_000, .. })
2568		));
2569		let landed = kio::clock::now();
2570		assert_eq!(reader.backlog(), Some(landed));
2571
2572		// Group 6 itself came after the subscription began, so a copy of it would not be backlog.
2573		tokio::time::advance(Duration::from_millis(30)).await;
2574		write_group(&mut track, &[ts(160_000)]);
2575		write_group_after_gap(&mut track, &[ts(200_000)]);
2576		assert!(matches!(
2577			reader.read().await.unwrap(),
2578			Some(Read::Frame { group: 160_000, .. })
2579		));
2580		assert!(matches!(reader.read().await.unwrap(), Some(Read::Gap { .. })));
2581		assert!(matches!(
2582			reader.read().await.unwrap(),
2583			Some(Read::Frame { group: 200_000, .. })
2584		));
2585		write_group(&mut track, &[ts(180_000)]);
2586		write_group(&mut track, &[ts(220_000)]);
2587		assert!(matches!(
2588			reader.read().await.unwrap(),
2589			Some(Read::Frame { group: 220_000, .. })
2590		));
2591		assert_eq!(
2592			reader.backlog(),
2593			Some(landed),
2594			"group 9 was produced after the subscription"
2595		);
2596	}
2597
2598	/// The start drops the backlog below it unread, which still reports when it landed.
2599	#[tokio::test(start_paused = true)]
2600	async fn a_live_start_reports_the_backlog_it_drops() {
2601		let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.audio));
2602		let landed = kio::clock::now();
2603		write_group_after_gap(&mut track, &[ts(0)]);
2604		tokio::time::advance(Duration::from_millis(30)).await;
2605		write_group(&mut track, &[ts(20_000)]);
2606		let subscriber =
2607			track.subscribe(
2608				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2609					moq_net::track::Start::Live {
2610						min: Some(Duration::from_secs(1)),
2611						max: Some(Duration::from_secs(1)),
2612					},
2613				)]),
2614			);
2615		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Audio)).live();
2616		assert!(matches!(
2617			reader.read().await.unwrap(),
2618			Some(Read::Frame { group: 20_000, .. })
2619		));
2620		assert_eq!(reader.backlog(), Some(landed));
2621	}
2622
2623	/// A join's backlog the ordered reader gives up as stale, never handing it to this reader, still
2624	/// reports when it landed: its gap carries the landing.
2625	#[kio::test]
2626	async fn a_stale_backlog_the_ordered_reader_gives_up_reports_when_it_landed() {
2627		let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.audio));
2628		let landed = kio::clock::now();
2629		write_group(&mut track, &[ts(0)]);
2630		write_group(&mut track, &[ts(20_000)]);
2631		kio::clock::sim::advance(Duration::from_millis(100)).await;
2632		write_group(&mut track, &[ts(40_000)]);
2633		let subscriber =
2634			track.subscribe(
2635				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2636					moq_net::track::Start::Live {
2637						min: Some(Duration::from_millis(50)),
2638						max: Some(Duration::from_millis(50)),
2639					},
2640				)]),
2641			);
2642		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Audio));
2643		assert!(matches!(
2644			reader.read().await.unwrap(),
2645			Some(Read::Frame { group: 20_000, .. })
2646		));
2647		assert_eq!(reader.backlog(), Some(landed), "group 0 went stale unread");
2648	}
2649
2650	/// A gap's landing is when the latest group it gives up landed, so only a gap wholly at or below
2651	/// the join is backlog: one reaching past it may report a group produced after the subscription.
2652	#[tokio::test(start_paused = true)]
2653	async fn a_gap_reaching_past_the_join_folds_no_backlog() {
2654		let budget = Duration::from_secs(2);
2655		for joined in [20_000, 40_000] {
2656			let mut copy = Received::new().await;
2657			let mut reader = copy
2658				.reader(Delay::default().with_min(Duration::from_millis(100)).with_max(budget))
2659				.await;
2660			// Frame 0 sits at its key: a lite-07 hop carries no frame below its group's start.
2661			write_group_after_gap(&mut copy.track, &[ts(150)]);
2662			carried().await;
2663			assert!(matches!(
2664				reader.read().await.unwrap(),
2665				Some(Read::Frame { group: 150, .. })
2666			));
2667			// Where the publisher stood as the subscription began.
2668			reader.joined = Some(joined);
2669			write_group(&mut copy.track, &[ts(20_000)]);
2670			carried().await;
2671			let first = kio::clock::now();
2672			tokio::time::advance(Duration::from_millis(10)).await;
2673			let second = kio::clock::now();
2674			write_group(&mut copy.track, &[ts(40_000)]);
2675			write_group(&mut copy.track, &[ts(60_000)]);
2676			carried().await;
2677			// The groups at 20 and 40 ms wait unread until their successors landed a budget ago, so
2678			// both are given up as stale.
2679			tokio::time::advance(budget + Duration::from_millis(1)).await;
2680			write_group(&mut copy.track, &[ts(80_000)]);
2681			carried().await;
2682			let read = loop {
2683				match reader.read().await.unwrap() {
2684					Some(Read::Gap { .. }) => continue,
2685					other => break other,
2686				}
2687			};
2688			assert!(matches!(read, Some(Read::Frame { group: 60_000, .. })), "{read:?}");
2689			// Only what lies at or below the join folds into the backlog.
2690			let landed = if joined == 40_000 { second } else { first };
2691			assert_eq!(reader.backlog(), Some(landed), "joined at {joined}");
2692		}
2693	}
2694
2695	/// The join's boundary is where the publisher stood as it answered, though the groups it owes
2696	/// are held up while the publisher moves on: the first item the ordered reader hands out comes
2697	/// after the largest has passed it.
2698	#[tokio::test(start_paused = true)]
2699	async fn the_join_is_the_answer_though_the_first_group_is_held() {
2700		use crate::container::test_util::{Link, origin};
2701
2702		let (publisher, subscriber) = (origin(), origin());
2703		// SETUP and the Announce Stream take the first two uni streams, so every group waits.
2704		let link = Link::held(&publisher, &subscriber, 2).await;
2705		let route = publisher
2706			.route("room", moq_net::origin::RouteOptions::hidden())
2707			.unwrap();
2708		let mut track = route
2709			.broadcast()
2710			.create_track("data", hang::container::track_info(hang::catalog::PRIORITY.audio))
2711			.unwrap();
2712		route.announce().unwrap();
2713		let remote = subscriber
2714			.consume()
2715			.follow("room", None)
2716			.unwrap()
2717			.available()
2718			.await
2719			.unwrap()
2720			.unwrap();
2721		write_group(&mut track, &[ts(0)]);
2722		let subscription = remote
2723			.track("data")
2724			.unwrap()
2725			.subscribe(
2726				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2727					moq_net::track::Start::Live {
2728						min: Some(Duration::from_secs(1)),
2729						max: Some(Duration::from_secs(1)),
2730					},
2731				)]),
2732			)
2733			.await
2734			.unwrap();
2735		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Audio));
2736		carried().await;
2737		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2738		write_group(&mut track, &[ts(20_000)]);
2739		write_group(&mut track, &[ts(40_000)]);
2740		link.open();
2741		carried().await;
2742		assert!(matches!(
2743			reader.read().await.unwrap(),
2744			Some(Read::Frame { group: 0, .. })
2745		));
2746		assert_eq!(reader.joined, Some(0));
2747	}
2748
2749	/// The join's boundary is where the publisher stood as it answered, not the newer largest by the
2750	/// time a live start found a frame to start on.
2751	#[tokio::test(start_paused = true)]
2752	async fn the_join_is_the_largest_at_the_answer_not_at_the_start() {
2753		let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.audio));
2754		let landed = kio::clock::now();
2755		let (mut open, rest) = in_flight(&track, ts(0));
2756		let subscriber =
2757			track.subscribe(
2758				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2759					moq_net::track::Start::Live {
2760						min: Some(Duration::from_secs(1)),
2761						max: Some(Duration::from_secs(1)),
2762					},
2763				)]),
2764			);
2765		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Audio)).live();
2766		// The newest group's first frame is still in flight, so the start waits, though the
2767		// publisher answered.
2768		assert!(
2769			kio::clock::timeout(Duration::from_millis(1), reader.read())
2770				.await
2771				.is_err()
2772		);
2773
2774		// The groups at 20 and 40 ms were produced after the subscription began, so they are no
2775		// backlog.
2776		tokio::time::advance(Duration::from_millis(30)).await;
2777		write_group(&mut track, &[ts(20_000)]);
2778		write_group(&mut track, &[ts(40_000)]);
2779		open.write(rest).unwrap();
2780		open.finish().unwrap().finish().unwrap();
2781		assert!(matches!(
2782			reader.read().await.unwrap(),
2783			Some(Read::Frame { group: 40_000, .. })
2784		));
2785		assert_eq!(
2786			reader.backlog(),
2787			Some(landed),
2788			"the group at 20 ms was produced after the answer"
2789		);
2790	}
2791
2792	/// The holes a source left behind when it stopped expire together, a budget after the groups
2793	/// past them arrived, rather than one budget each as the cursor reaches them. The groups that
2794	/// waited behind them that long are a budget late too, superseded that long ago, so only the
2795	/// newest is read.
2796	#[tokio::test(start_paused = true)]
2797	async fn holes_behind_a_stalled_source_share_one_budget() {
2798		let budget = Duration::from_millis(100);
2799		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
2800		let subscriber = copy
2801			.subscribe_with(
2802				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2803					moq_net::track::Start::Live {
2804						min: Some(budget),
2805						max: Some(budget),
2806					},
2807				)]),
2808			)
2809			.await;
2810		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
2811		write_group(&mut copy.track, &[ts(0)]);
2812		carried().await;
2813		assert!(matches!(
2814			reader.read().await.unwrap(),
2815			Some(Read::Frame { group: 0, .. })
2816		));
2817		for sequence in [2, 4, 6] {
2818			write_group_after_gap(&mut copy.track, &[ts(sequence * 10_000)]);
2819			carried().await;
2820		}
2821		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2822		tokio::time::advance(budget).await;
2823		carried().await;
2824		let mut read = Vec::new();
2825		while let Poll::Ready(Ok(Some(item))) = reader.poll_read(&kio::Waiter::noop()) {
2826			read.push(match item {
2827				Read::Frame { group, .. } => format!("frame {group}"),
2828				Read::Gap { .. } => "gap".to_string(),
2829				Read::End { .. } => "end".to_string(),
2830			});
2831		}
2832		assert_eq!(read, ["gap", "frame 60000"]);
2833	}
2834
2835	/// A missing group is waited for the max delay, whatever the min delay: the min only sets
2836	/// where the reader starts.
2837	#[tokio::test(start_paused = true)]
2838	async fn a_hole_is_waited_for_the_max_delay_whatever_the_min() {
2839		let max = Duration::from_secs(1);
2840		for min in [
2841			Some(Duration::ZERO),
2842			Some(Duration::from_millis(100)),
2843			Some(Duration::from_secs(5)),
2844			None,
2845		] {
2846			let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
2847			let subscriber = copy
2848				.subscribe_with(
2849					Delay::default().with_min(min).with_max(max).subscription(
2850						moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]),
2851					),
2852				)
2853				.await;
2854			let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
2855			write_group(&mut copy.track, &[ts(0)]);
2856			carried().await;
2857			assert!(matches!(
2858				reader.read().await.unwrap(),
2859				Some(Read::Frame { group: 0, .. })
2860			));
2861			// Group 1 never arrives, and group 2 starts right after it, so only the wall clock ends it.
2862			write_group_after_gap(&mut copy.track, &[ts(40_000)]);
2863			carried().await;
2864			let since = kio::clock::now();
2865			assert!(matches!(reader.read().await.unwrap(), Some(Read::Gap { .. })));
2866			assert_eq!(since.elapsed(), max, "min {min:?}");
2867		}
2868	}
2869
2870	/// A burst of later groups spanning past the min delay doesn't age out a missing group that
2871	/// lands in the same burst, even once the min delay has passed: a reader starved of CPU takes in
2872	/// every stream at once, and only the max delay gives a hole up.
2873	#[tokio::test(start_paused = true)]
2874	async fn a_burst_past_the_min_delay_does_not_age_out_a_hole() {
2875		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
2876		let subscriber = copy
2877			.subscribe_with(
2878				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2879					moq_net::track::Start::Live {
2880						min: Some(Duration::from_secs(1)),
2881						max: Some(Duration::from_secs(1)),
2882					},
2883				)]),
2884			)
2885			.await;
2886		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
2887		reader.set_delay(
2888			Delay::default()
2889				.with_min(Duration::from_millis(100))
2890				.with_max(Duration::from_secs(1)),
2891		);
2892		write_group(&mut copy.track, &[ts(0)]);
2893		carried().await;
2894		assert!(matches!(
2895			reader.read().await.unwrap(),
2896			Some(Read::Frame { group: 0, .. })
2897		));
2898		// The hole is the start at 20 ms alone.
2899		copy.track.skip_groups(1..20_000);
2900		copy.track.skip_groups(20_001..40_000);
2901		write_group_after_gap(&mut copy.track, &[ts(40_000), ts(200_000)]);
2902		carried().await;
2903		write_group(&mut copy.track, &[ts(300_000)]);
2904		carried().await;
2905		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2906		tokio::time::advance(Duration::from_millis(100)).await;
2907		carried().await;
2908		assert!(
2909			reader.poll_read(&kio::Waiter::noop()).is_pending(),
2910			"the min delay gives nothing up"
2911		);
2912		write_group(&mut copy.track, &[ts(20_000)]);
2913		carried().await;
2914		let mut read = Vec::new();
2915		while let Poll::Ready(Ok(Some(item))) = reader.poll_read(&kio::Waiter::noop()) {
2916			read.push(match item {
2917				Read::Frame { group, .. } => format!("frame {group}"),
2918				Read::Gap { .. } => "gap".to_string(),
2919				Read::End { .. } => "end".to_string(),
2920			});
2921		}
2922		assert_eq!(read, ["frame 20000", "frame 40000", "frame 40000", "frame 300000"]);
2923	}
2924
2925	/// A group that arrives late below an earlier one is late from that earlier arrival, as is the
2926	/// hole past it, so they expire a budget after that earlier arrival. An unsettled hole below
2927	/// the late group waits a budget from the late group's own arrival, its immediate successor.
2928	#[tokio::test(start_paused = true)]
2929	async fn a_hole_is_late_from_the_earliest_arrival_past_it() {
2930		let budget = Duration::from_millis(100);
2931		let drain = |reader: &mut Consumer<Wire>| {
2932			let mut read = Vec::new();
2933			while let Poll::Ready(Ok(Some(item))) = reader.poll_read(&kio::Waiter::noop()) {
2934				read.push(match item {
2935					Read::Frame { group, .. } => format!("frame {group}"),
2936					Read::Gap { .. } => "gap".to_string(),
2937					Read::End { .. } => "end".to_string(),
2938				});
2939			}
2940			read
2941		};
2942
2943		// With an unsettled hole below late group 2, group 2 keeps hole 1 owed for a budget from
2944		// group 2's arrival; once hole 1 expires, already-stale group 2 and hole 3 go with it.
2945		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
2946		let subscriber = copy
2947			.subscribe_with(
2948				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2949					moq_net::track::Start::Live {
2950						min: Some(budget),
2951						max: Some(budget),
2952					},
2953				)]),
2954			)
2955			.await;
2956		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
2957		write_group(&mut copy.track, &[ts(0)]);
2958		carried().await;
2959		assert!(matches!(
2960			reader.read().await.unwrap(),
2961			Some(Read::Frame { group: 0, .. })
2962		));
2963		write_group_after_gap(&mut copy.track, &[ts(40_000)]);
2964		carried().await;
2965		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2966		tokio::time::advance(budget / 2).await;
2967		carried().await;
2968		write_group(&mut copy.track, &[ts(20_000)]);
2969		carried().await;
2970		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
2971		tokio::time::advance(budget / 2).await;
2972		carried().await;
2973		assert!(
2974			reader.poll_read(&kio::Waiter::noop()).is_pending(),
2975			"hole 1 waits on its immediate successor, group 2"
2976		);
2977		tokio::time::advance(budget / 2).await;
2978		carried().await;
2979		assert_eq!(drain(&mut reader), ["gap", "frame 40000"]);
2980
2981		// When nothing is owed below late group 2, group 2 and hole 3 expire a budget after
2982		// group 4's earlier arrival, only half a budget after group 2 itself landed.
2983		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
2984		let subscriber = copy
2985			.subscribe_with(
2986				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2987					moq_net::track::Start::Live {
2988						min: Some(budget),
2989						max: Some(budget),
2990					},
2991				)]),
2992			)
2993			.await;
2994		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
2995		write_group(&mut copy.track, &[ts(0)]);
2996		copy.track.skip_groups(1..20_000);
2997		carried().await;
2998		assert!(matches!(
2999			reader.read().await.unwrap(),
3000			Some(Read::Frame { group: 0, .. })
3001		));
3002		write_group_after_gap(&mut copy.track, &[ts(40_000)]);
3003		carried().await;
3004		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
3005		tokio::time::advance(budget / 2).await;
3006		carried().await;
3007		write_group(&mut copy.track, &[ts(20_000)]);
3008		carried().await;
3009		tokio::time::advance(budget / 2).await;
3010		carried().await;
3011		assert_eq!(drain(&mut reader), ["gap", "frame 40000"]);
3012	}
3013
3014	/// A player waits on a hole for the max delay, as it does on a group that did arrive, whatever
3015	/// its playout delay.
3016	#[tokio::test(start_paused = true)]
3017	async fn a_hole_and_an_arrived_group_both_wait_up_to_the_max_delay() {
3018		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
3019		// From group 0, which the playout delay set below doesn't move: a live join, so a missing
3020		// group can go stale.
3021		let subscriber = copy
3022			.subscribe_with(crate::container::test_util::within(Duration::from_secs(1)))
3023			.await;
3024		let mut reader = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
3025		reader.set_delay(
3026			Delay::default()
3027				.with_min(Duration::from_millis(100))
3028				.with_max(Duration::from_secs(1)),
3029		);
3030		let drain = |reader: &mut Consumer<Wire>| {
3031			let mut read = Vec::new();
3032			while let Poll::Ready(Ok(Some(item))) = reader.poll_read(&kio::Waiter::noop()) {
3033				read.push(match item {
3034					Read::Frame { group, .. } => format!("frame {group}"),
3035					Read::Gap { .. } => "gap".to_string(),
3036					Read::End { .. } => "end".to_string(),
3037				});
3038			}
3039			read
3040		};
3041
3042		// A stalled group 500 ms behind the newest content is still within the max delay.
3043		let mut stalled = Lazy::following(&copy.track);
3044		let frame = Frame {
3045			timestamp: ts(0),
3046			decode: None,
3047			payload: Bytes::from_static(&[0xDE, 0xAD]),
3048			keyframe: false,
3049			duration: None,
3050		};
3051		Wire::legacy(crate::container::Kind::Data)
3052			.write(&mut stalled.writer(), &[frame])
3053			.unwrap();
3054		write_group(&mut copy.track, &[ts(500_000)]);
3055		carried().await;
3056		tokio::time::advance(Duration::from_millis(500)).await;
3057		carried().await;
3058		assert_eq!(drain(&mut reader), ["frame 0"]);
3059		stalled.finish().unwrap();
3060		carried().await;
3061		assert_eq!(drain(&mut reader), ["frame 500000"]);
3062
3063		// A missing group is given up the max delay after the first group past it arrived, not the
3064		// min delay.
3065		write_group_after_gap(&mut copy.track, &[ts(520_000)]);
3066		carried().await;
3067		tokio::time::advance(Duration::from_millis(999)).await;
3068		carried().await;
3069		assert!(drain(&mut reader).is_empty());
3070		tokio::time::advance(Duration::from_millis(1)).await;
3071		carried().await;
3072		assert_eq!(drain(&mut reader), ["gap", "frame 520000"]);
3073
3074		// Content buffered past the hole doesn't skip it early: a burst may still carry the group.
3075		// The hole is the start at 600 ms alone.
3076		copy.track.skip_groups(520_001..600_000);
3077		copy.track.skip_groups(600_001..700_000);
3078		write_group_after_gap(&mut copy.track, &[ts(700_000)]);
3079		carried().await;
3080		write_group(&mut copy.track, &[ts(800_000)]);
3081		carried().await;
3082		tokio::time::advance(Duration::from_millis(100)).await;
3083		carried().await;
3084		assert!(drain(&mut reader).is_empty());
3085		write_group(&mut copy.track, &[ts(600_000)]);
3086		carried().await;
3087		assert_eq!(drain(&mut reader), ["frame 600000", "frame 700000", "frame 800000"]);
3088
3089		// It skips at once when the newest content is already the max delay past the group after it.
3090		write_group_after_gap(&mut copy.track, &[ts(900_000)]);
3091		carried().await;
3092		write_group(&mut copy.track, &[ts(1_900_000)]);
3093		carried().await;
3094		assert_eq!(drain(&mut reader), ["gap", "frame 900000", "frame 1900000"]);
3095	}
3096
3097	/// Everything `reader` hands over now, polled with `waiter`.
3098	fn drain_with(reader: &mut Consumer<Wire>, waiter: &kio::Waiter) -> Vec<String> {
3099		let mut read = Vec::new();
3100		while let Poll::Ready(Ok(Some(item))) = reader.poll_read(waiter) {
3101			read.push(match item {
3102				Read::Frame { group, .. } => format!("frame {group}"),
3103				Read::Gap { .. } => "gap".to_string(),
3104				Read::End { .. } => "end".to_string(),
3105			});
3106		}
3107		read
3108	}
3109
3110	/// The browser's resume: a reader that delivered a tail before a pause, then a replayed backlog
3111	/// arriving newest first behind a hole. Nothing gives a hole up before the max delay, so the
3112	/// reader waits for the backlog's oldest group, which lands last, and plays the replay whole.
3113	#[tokio::test(start_paused = true)]
3114	async fn a_backlog_replayed_newest_first_plays_whole_within_the_max_delay() {
3115		let mut copy = Received::new().await;
3116		let mut reader = copy
3117			.reader(
3118				Delay::default()
3119					.with_min(Duration::from_millis(500))
3120					.with_max(Duration::from_secs(2)),
3121			)
3122			.await;
3123		let waiter = kio::Waiter::noop();
3124		// The tail before the pause, a group per 100 ms of media and of wall time.
3125		for sequence in 0..5 {
3126			write_group(&mut copy.track, &[ts(sequence * 100_000)]);
3127			carried().await;
3128			assert_eq!(
3129				drain_with(&mut reader, &waiter),
3130				[format!("frame {}", sequence * 100_000)]
3131			);
3132			tokio::time::advance(Duration::from_millis(100)).await;
3133		}
3134		// Paused until 1.4 s, when the publisher replays the groups from 1.4 s down to 0.5 s, one
3135		// every 50 ms. Nothing else starts between them.
3136		tokio::time::advance(Duration::from_millis(900)).await;
3137		for sequence in 4..14 {
3138			copy.track.skip_groups(sequence * 100_000 + 1..(sequence + 1) * 100_000);
3139		}
3140		let mut read = Vec::new();
3141		for sequence in (5..15).rev() {
3142			write_group_after_gap(&mut copy.track, &[ts(sequence * 100_000)]);
3143			carried().await;
3144			read.extend(drain_with(&mut reader, &waiter));
3145			tokio::time::advance(Duration::from_millis(50)).await;
3146		}
3147		let expected: Vec<String> = (5..15)
3148			.map(|sequence| format!("frame {}", sequence * 100_000))
3149			.collect();
3150		assert_eq!(read, expected);
3151	}
3152
3153	/// A malformed data marker group found while looking ahead fails the reader, rather than
3154	/// reading as a gap when a latency skip passes over it.
3155	#[tokio::test(start_paused = true)]
3156	async fn a_malformed_marker_passed_by_a_skip_fails_the_reader() {
3157		let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.audio));
3158		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range {
3159			start: moq_net::track::Start::Time(0),
3160			end: None,
3161			..Default::default()
3162		}]);
3163		let mut reader = Consumer::new(
3164			track.subscribe(subscription),
3165			Wire::legacy(crate::container::Kind::Data),
3166		);
3167		reader.max_delay = Duration::ZERO;
3168		// The current group stays open, so only a skip moves past it.
3169		let mut slow = Lazy::following(&track);
3170		write_hang(&mut slow, ts(0), Bytes::from_static(b"a"));
3171		let mut group = Lazy::following(&track);
3172		group.write_frame(ts(10_000), Bytes::new()).unwrap();
3173		write_hang(&mut group, ts(10_000), Bytes::from_static(b"b"));
3174		group.finish().unwrap();
3175		write_group(&mut track, &[ts(1_000_000)]);
3176
3177		let read = loop {
3178			match reader.read().await {
3179				Ok(Some(Read::Frame { frame, .. })) if frame.timestamp == ts(0) => continue,
3180				other => break other,
3181			}
3182		};
3183		assert!(read.is_err(), "{read:?}");
3184	}
3185
3186	/// An object with no bytes marks a break only on a data track: on a media track it is
3187	/// malformed, and fails to decode rather than read as a marker.
3188	#[test]
3189	fn an_empty_object_is_a_marker_only_on_a_data_track() {
3190		for kind in [
3191			crate::container::Kind::Data,
3192			crate::container::Kind::Audio,
3193			crate::container::Kind::Video,
3194		] {
3195			let read = Wire::legacy(kind).decode(moq_net::frame::Frame::new(ts(0), Bytes::new()));
3196			match kind {
3197				crate::container::Kind::Data => assert!(matches!(read, Ok(frames) if frames.is_empty())),
3198				_ => assert!(read.is_err(), "{kind:?}: {read:?}"),
3199			}
3200		}
3201	}
3202
3203	/// A data track's marker is alone in its group: one sharing it with another object, a
3204	/// frame or a second marker, is malformed rather than a break or a frame.
3205	#[tokio::test(start_paused = true)]
3206	async fn a_data_marker_sharing_its_group_is_malformed() {
3207		for second in [Bytes::new(), Bytes::from_static(b"a")] {
3208			for marker_first in [true, false] {
3209				let mut track = track_producer("data", hang::container::track_info(hang::catalog::PRIORITY.audio));
3210				let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range {
3211					start: moq_net::track::Start::Time(0),
3212					end: None,
3213					..Default::default()
3214				}]);
3215				let mut reader = Consumer::new(
3216					track.subscribe(subscription),
3217					Wire::legacy(crate::container::Kind::Data),
3218				);
3219				write_group(&mut track, &[ts(0)]);
3220				let mut group = Lazy::following(&track);
3221				let mut objects = [Bytes::new(), second.clone()];
3222				if !marker_first {
3223					objects.reverse();
3224				}
3225				for object in objects {
3226					match object.is_empty() {
3227						true => group.write_frame(ts(10_000), object).unwrap(),
3228						false => write_hang(&mut group, ts(10_000), object),
3229					}
3230				}
3231				group.finish().unwrap();
3232				let _track = track.finish().unwrap();
3233
3234				let error = loop {
3235					match reader.read().await {
3236						// A frame ahead of the marker goes out before the marker is seen.
3237						Ok(Some(Read::Frame { .. })) => continue,
3238						other => break other,
3239					}
3240				};
3241				assert!(
3242					error.is_err(),
3243					"second {second:?}, marker first {marker_first}: {error:?}"
3244				);
3245			}
3246		}
3247	}
3248
3249	/// A gap runs from the delivered edge to the resume point, in the resume's scale, and
3250	/// never past it.
3251	#[test]
3252	fn a_gap_spans_the_edge_to_the_resume_in_its_scale() {
3253		let scale = moq_net::Timescale::new(90_000).unwrap();
3254		let resume = Timestamp::new(90_000, scale).unwrap();
3255		let Item::Gap { timestamp, duration } = gap(Duration::from_millis(500), resume).unwrap() else {
3256			unreachable!()
3257		};
3258		assert_eq!(timestamp, Timestamp::new(45_000, scale).unwrap());
3259		assert_eq!(duration, Duration::from_millis(500));
3260
3261		// A next group overlapping the edge leaves an empty span at the resume point.
3262		let Item::Gap { timestamp, duration } = gap(Duration::from_secs(2), resume).unwrap() else {
3263			unreachable!()
3264		};
3265		assert_eq!(timestamp, resume);
3266		assert_eq!(duration, Duration::ZERO);
3267	}
3268
3269	#[kio::test]
3270	async fn gaps_mark_holes_while_a_marker_reads_as_an_end() {
3271		let mut track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
3272		let subscription =
3273			track.subscribe(
3274				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3275					moq_net::track::Start::Live {
3276						min: Some(Duration::from_secs(10)),
3277						max: Some(Duration::from_secs(10)),
3278					},
3279				)]),
3280			);
3281		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Audio));
3282		write_group(&mut track, &[ts(0), ts(10_000)]);
3283		write_group_after_gap(&mut track, &[ts(1_000_000), ts(1_010_000)]);
3284		write_marker_group(&mut track, ts(1_020_000));
3285		write_group(&mut track, &[ts(2_000_000), ts(2_010_000)]);
3286		let _track = track.finish().unwrap();
3287		assert_eq!(
3288			items(&mut reader).await,
3289			[
3290				// Nothing was read before the join, so it is no gap. Legacy carries no duration, so
3291				// the hole starts at the last frame read.
3292				"0",
3293				"10000",
3294				"gap 10000+990000",
3295				"1000000",
3296				"1010000",
3297				"end 1020000",
3298				"2000000",
3299				"2010000"
3300			]
3301		);
3302	}
3303
3304	/// Starts are timestamps, so keys lie between any two groups. A run the publisher declared
3305	/// skipped holds nothing, so the reader steps over it without a gap even where the content
3306	/// jumps; one it never declared may have held a group that was lost.
3307	#[tokio::test(start_paused = true)]
3308	async fn only_an_undeclared_run_between_groups_is_a_gap() {
3309		let mut track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
3310		let subscription =
3311			track.subscribe(
3312				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3313					moq_net::track::Start::Live {
3314						min: Some(Duration::from_secs(10)),
3315						max: Some(Duration::from_secs(10)),
3316					},
3317				)]),
3318			);
3319		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Audio));
3320		write_group(&mut track, &[ts(0), ts(10_000)]);
3321		track.skip_groups(1..1_000_000);
3322		write_group_after_gap(&mut track, &[ts(1_000_000), ts(1_010_000)]);
3323		write_group_after_gap(&mut track, &[ts(2_000_000), ts(2_010_000)]);
3324		let _track = track.finish().unwrap();
3325		assert_eq!(
3326			items(&mut reader).await,
3327			[
3328				"0",
3329				"10000",
3330				"1000000",
3331				"1010000",
3332				"gap 1010000+990000",
3333				"2000000",
3334				"2010000"
3335			]
3336		);
3337	}
3338
3339	/// Legacy frames carry no duration, so an audio reader reads each packet's from its codec.
3340	/// One-packet groups then run back to back even where nothing declared the starts between
3341	/// them skipped, as a moq-lite-06 hop can't, while a lost group is still a gap.
3342	#[tokio::test(start_paused = true)]
3343	async fn codec_durations_bridge_undeclared_runs_between_audio_groups() {
3344		let track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
3345		let subscription =
3346			track.subscribe(
3347				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3348					moq_net::track::Start::Live {
3349						min: Some(Duration::from_secs(10)),
3350						max: Some(Duration::from_secs(10)),
3351					},
3352				)]),
3353			);
3354		let config = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
3355		let mut reader = Consumer::new(subscription, Wire::try_from(&config).unwrap());
3356		// One 20 ms CELT packet per group. The group starting at 40 ms never arrives.
3357		for start in [0, 20_000, 60_000] {
3358			let mut group = Lazy::new(&track);
3359			let packet = Frame {
3360				timestamp: ts(start),
3361				decode: None,
3362				payload: Bytes::from_static(&[31 << 3, 0]),
3363				keyframe: false,
3364				duration: None,
3365			};
3366			Wire::try_from(&config)
3367				.unwrap()
3368				.write(&mut group.writer(), &[packet])
3369				.unwrap();
3370			group.finish().unwrap();
3371		}
3372		let _track = track.finish().unwrap();
3373		assert_eq!(items(&mut reader).await, ["0", "20000", "gap 40000+20000", "60000"]);
3374	}
3375
3376	/// MP2 codes 1152 samples per frame, so its groups bridge as Opus's do.
3377	#[tokio::test(start_paused = true)]
3378	async fn mp2_durations_bridge_undeclared_runs_between_audio_groups() {
3379		let track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
3380		let subscription =
3381			track.subscribe(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]));
3382		let config = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Mp2, 48_000, 2);
3383		let mut reader = Consumer::new(subscription, Wire::try_from(&config).unwrap());
3384		// Two 24 ms frames per group. The group starting at 96 ms never arrives.
3385		for start in [0, 48_000, 144_000] {
3386			let mut group = Lazy::new(&track);
3387			for at in [start, start + 24_000] {
3388				let packet = Frame {
3389					timestamp: ts(at),
3390					decode: None,
3391					payload: Bytes::from_static(&[0xFF, 0xFD]),
3392					keyframe: at == start,
3393					duration: None,
3394				};
3395				Wire::try_from(&config)
3396					.unwrap()
3397					.write(&mut group.writer(), &[packet])
3398					.unwrap();
3399			}
3400			group.finish().unwrap();
3401		}
3402		let _track = track.finish().unwrap();
3403		assert_eq!(
3404			items(&mut reader).await,
3405			["0", "24000", "48000", "72000", "gap 96000+48000", "144000", "168000"]
3406		);
3407	}
3408
3409	/// Legacy video groups, each keyed by its first frame's timestamp as a moq-lite-06 hop delivers
3410	/// them with nothing declared between them: the frames of each, in decode order, with no duration.
3411	async fn legacy_video(groups: &[&[u64]]) -> Vec<String> {
3412		let track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.video));
3413		let subscription =
3414			track.subscribe(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]));
3415		let wire = Wire::legacy(crate::container::Kind::Video);
3416		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Video));
3417		for pictures in groups {
3418			let start = pictures[0];
3419			let mut group = Lazy::new(&track);
3420			for &micros in *pictures {
3421				let frame = Frame {
3422					timestamp: ts(micros),
3423					decode: None,
3424					payload: Bytes::from_static(&[0xDE, 0xAD]),
3425					keyframe: micros == start,
3426					duration: None,
3427				};
3428				wire.write(&mut group.writer(), &[frame]).unwrap();
3429			}
3430			group.finish().unwrap();
3431		}
3432		let _track = track.finish().unwrap();
3433		items(&mut reader).await
3434	}
3435
3436	/// The second group is an open GOP: its leading pictures present between the first group's last
3437	/// picture and its keyframe, so the two groups meet and nothing is lost.
3438	#[tokio::test(start_paused = true)]
3439	async fn an_open_gop_that_continues_the_previous_video_group_is_no_gap() {
3440		assert_eq!(
3441			legacy_video(&[&[0, 120_000, 40_000, 80_000], &[280_000, 160_000, 200_000, 240_000]]).await,
3442			["0", "120000", "40000", "80000", "280000", "160000", "200000", "240000"]
3443		);
3444	}
3445
3446	/// A closed GOP with B-frames starts one picture past the previous group's highest timestamp,
3447	/// which is where its last picture starts rather than ends.
3448	#[tokio::test(start_paused = true)]
3449	async fn a_closed_gop_one_picture_past_the_previous_video_group_is_no_gap() {
3450		assert_eq!(
3451			legacy_video(&[&[0, 120_000, 40_000, 80_000], &[160_000, 280_000, 200_000, 240_000]]).await,
3452			["0", "120000", "40000", "80000", "160000", "280000", "200000", "240000"]
3453		);
3454	}
3455
3456	/// Field-coded open GOPs: the keyframe's second field decodes ahead of the leading pictures, so
3457	/// the lowest one comes third, within how far the first group reordered. A 40 ms frame among the
3458	/// second group's 20 ms fields allows its last picture to be one too.
3459	#[tokio::test(start_paused = true)]
3460	async fn field_coded_open_gops_that_continue_each_other_are_no_gap() {
3461		let groups: &[&[u64]] = &[
3462			&[0, 20_000, 120_000, 140_000, 40_000, 60_000, 80_000, 100_000],
3463			&[240_000, 260_000, 160_000, 180_000, 220_000],
3464			&[380_000, 400_000, 300_000, 320_000, 340_000, 360_000],
3465		];
3466		let read = legacy_video(groups).await;
3467		assert!(!read.iter().any(|item| item.starts_with("gap")), "{read:?}");
3468		assert_eq!(read.len(), 19);
3469	}
3470
3471	/// A lost group is still a gap, read ahead of the next group's keyframe, though its leading pictures
3472	/// would have presented nearer: the keyframe waits for them.
3473	#[tokio::test(start_paused = true)]
3474	async fn an_open_gop_past_a_lost_video_group_is_a_gap_before_its_keyframe() {
3475		assert_eq!(
3476			legacy_video(&[
3477				&[0, 120_000, 40_000, 80_000],
3478				&[280_000, 160_000, 200_000, 240_000],
3479				// The group at 560 ms never arrives.
3480				&[840_000, 720_000, 760_000, 800_000],
3481			])
3482			.await,
3483			[
3484				"0",
3485				"120000",
3486				"40000",
3487				"80000",
3488				"280000",
3489				"160000",
3490				"200000",
3491				"240000",
3492				"gap 280000+560000",
3493				"840000",
3494				"720000",
3495				"760000",
3496				"800000"
3497			]
3498		);
3499	}
3500
3501	/// The keyframe of an open GOP is held only until a frame shows the group continues, so it reads
3502	/// while the rest of its group is still to come.
3503	#[tokio::test(start_paused = true)]
3504	async fn an_open_gops_keyframe_reads_once_a_leading_picture_lands() {
3505		let track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.video));
3506		let subscription =
3507			track.subscribe(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]));
3508		let wire = Wire::legacy(crate::container::Kind::Video);
3509		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Video));
3510		let frame = |micros: u64, keyframe| Frame {
3511			timestamp: ts(micros),
3512			decode: None,
3513			payload: Bytes::from_static(&[0xDE, 0xAD]),
3514			keyframe,
3515			duration: None,
3516		};
3517		let mut first = Lazy::following(&track);
3518		for (micros, keyframe) in [(0, true), (120_000, false), (40_000, false), (80_000, false)] {
3519			wire.write(&mut first.writer(), &[frame(micros, keyframe)]).unwrap();
3520		}
3521		first.finish().unwrap();
3522		for _ in 0..4 {
3523			assert!(matches!(reader.read().await.unwrap(), Some(Read::Frame { .. })));
3524		}
3525		let mut open = Lazy::new(&track);
3526		wire.write(&mut open.writer(), &[frame(280_000, true)]).unwrap();
3527		let waiter = kio::Waiter::noop();
3528		assert!(
3529			reader.poll_read(&waiter).is_pending(),
3530			"the keyframe waits for the next frame"
3531		);
3532		wire.write(&mut open.writer(), &[frame(160_000, false)]).unwrap();
3533		let Some(Read::Frame { frame: keyframe, .. }) = reader.read().await.unwrap() else {
3534			panic!("the keyframe reads, with no gap ahead of it");
3535		};
3536		assert_eq!(keyframe.timestamp, ts(280_000));
3537		let Some(Read::Frame { frame: leading, .. }) = reader.read().await.unwrap() else {
3538			panic!("the leading picture reads");
3539		};
3540		assert_eq!(leading.timestamp, ts(160_000));
3541		drop(open);
3542	}
3543
3544	/// A held keyframe is judged by what its group holds once the max buffer fills, and read behind a
3545	/// gap rather than dropped with the group: the pressure skip moves past only a group holding nothing.
3546	#[tokio::test(start_paused = true)]
3547	async fn a_held_keyframe_is_read_once_the_max_buffer_fills() {
3548		let mut track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.video));
3549		let subscription =
3550			track.subscribe(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]));
3551		let wire = Wire::legacy(crate::container::Kind::Video);
3552		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Video));
3553		let frame = |micros: u64, keyframe| Frame {
3554			timestamp: ts(micros),
3555			decode: None,
3556			payload: Bytes::from_static(&[0xDE, 0xAD]),
3557			keyframe,
3558			duration: None,
3559		};
3560		let mut first = Lazy::following(&track);
3561		for (micros, keyframe) in [(0, true), (120_000, false), (40_000, false), (80_000, false)] {
3562			wire.write(&mut first.writer(), &[frame(micros, keyframe)]).unwrap();
3563		}
3564		first.finish().unwrap();
3565		for _ in 0..4 {
3566			assert!(matches!(reader.read().await.unwrap(), Some(Read::Frame { .. })));
3567		}
3568		// The open GOP's keyframe waits for a frame to show whether it continues the first group.
3569		let mut open = Lazy::new(&track);
3570		wire.write(&mut open.writer(), &[frame(280_000, true)]).unwrap();
3571		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
3572		// A later group's first frame, decoded while the keyframe waits, fills the max buffer before
3573		// that frame lands. Its handle alone leaves room.
3574		reader.set_max_buffer(reader.buffered_bytes() + std::mem::size_of::<GroupBuffer<Wire>>() + 1);
3575		write_group_after_gap(&mut track, &[ts(560_000)]);
3576		let Some(Read::Gap { timestamp, duration }) = reader.read().await.unwrap() else {
3577			panic!("the step reads as a gap, judged by the keyframe alone");
3578		};
3579		assert_eq!((timestamp, duration), (ts(120_000), Duration::from_micros(160_000)));
3580		let Some(Read::Frame { frame: keyframe, .. }) = reader.read().await.unwrap() else {
3581			panic!("the held keyframe reads rather than drop with its group");
3582		};
3583		assert_eq!(keyframe.timestamp, ts(280_000));
3584		drop(open);
3585	}
3586
3587	/// A group the cursor stepped onto that holds nothing yet is skipped once the later groups fill the
3588	/// max buffer, as before it held anything to judge.
3589	#[tokio::test(start_paused = true)]
3590	async fn an_empty_unproven_group_is_skipped_once_the_max_buffer_fills() {
3591		let mut track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.video));
3592		let subscription =
3593			track.subscribe(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]));
3594		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Video));
3595		write_group(&mut track, &[ts(0), ts(40_000)]);
3596		for _ in 0..2 {
3597			assert!(matches!(reader.read().await.unwrap(), Some(Read::Frame { .. })));
3598		}
3599		let open = Lazy::new(&track);
3600		assert!(reader.poll_read(&kio::Waiter::noop()).is_pending());
3601		reader.set_max_buffer(reader.buffered_bytes() + std::mem::size_of::<GroupBuffer<Wire>>() + 1);
3602		write_group_after_gap(&mut track, &[ts(560_000)]);
3603		assert!(matches!(reader.read().await.unwrap(), Some(Read::Gap { .. })));
3604		let Some(Read::Frame { frame, .. }) = reader.read().await.unwrap() else {
3605			panic!("the later group reads");
3606		};
3607		assert_eq!(frame.timestamp, ts(560_000));
3608		drop(open);
3609	}
3610
3611	#[kio::test]
3612	async fn a_latency_skip_is_a_gap() {
3613		let mut track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
3614		let subscription =
3615			track.subscribe(
3616				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3617					moq_net::track::Start::Live {
3618						min: Some(Duration::from_secs(10)),
3619						max: Some(Duration::from_secs(10)),
3620					},
3621				)]),
3622			);
3623		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Audio));
3624		reader.max_delay = Duration::ZERO;
3625		// Group 0 stays open, and is read before the newer group lands: the skip comes after the start.
3626		let mut group = Lazy::following(&track);
3627		Wire::legacy(crate::container::Kind::Audio)
3628			.write(
3629				&mut group.writer(),
3630				&[Frame {
3631					timestamp: ts(0),
3632					decode: None,
3633					payload: Bytes::from_static(&[0xDE, 0xAD]),
3634					keyframe: false,
3635					duration: None,
3636				}],
3637			)
3638			.unwrap();
3639		assert!(matches!(reader.read().await.unwrap(), Some(Read::Frame { .. })));
3640		write_group_after_gap(&mut track, &[ts(1_000_000)]);
3641		let _track = track.finish().unwrap();
3642		assert_eq!(items(&mut reader).await, ["gap 0+1000000", "1000000"]);
3643	}
3644
3645	/// A video group's trailing duration marker is that frame's end, not a declared stop.
3646	#[kio::test]
3647	async fn a_trailing_duration_marker_is_not_an_end() {
3648		let track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.video));
3649		let subscription =
3650			track.subscribe(
3651				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3652					moq_net::track::Start::Live {
3653						min: Some(Duration::from_secs(10)),
3654						max: Some(Duration::from_secs(10)),
3655					},
3656				)]),
3657			);
3658		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Video));
3659		let wire = Wire::legacy(crate::container::Kind::Video);
3660		for start in [0, 33_000] {
3661			let mut group = Lazy::new(&track);
3662			let frame = |timestamp: u64, payload| Frame {
3663				timestamp: ts(timestamp),
3664				decode: None,
3665				payload,
3666				keyframe: timestamp == start,
3667				duration: None,
3668			};
3669			wire.write(
3670				&mut group.writer(),
3671				&[
3672					frame(start, Bytes::from_static(&[1])),
3673					frame(start + 33_000, Bytes::new()),
3674				],
3675			)
3676			.unwrap();
3677			group.finish().unwrap();
3678		}
3679		let _track = track.finish().unwrap();
3680		assert_eq!(items(&mut reader).await, ["0", "33000"]);
3681	}
3682
3683	/// An audio terminal opens its group with the endpoint, then the codec's final packets.
3684	#[kio::test]
3685	async fn an_audio_terminal_reads_its_end_before_the_final_packets() {
3686		let mut track = track_producer("gaps", hang::container::track_info(hang::catalog::PRIORITY.audio));
3687		let subscription =
3688			track.subscribe(
3689				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3690					moq_net::track::Start::Live {
3691						min: Some(Duration::from_secs(10)),
3692						max: Some(Duration::from_secs(10)),
3693					},
3694				)]),
3695			);
3696		let mut reader = Consumer::new(subscription, Wire::legacy(crate::container::Kind::Audio));
3697		write_group(&mut track, &[ts(0), ts(20_000)]);
3698		let mut group = Lazy::following(&track);
3699		let frame = |timestamp: u64, payload| Frame {
3700			timestamp: ts(timestamp),
3701			decode: None,
3702			payload,
3703			keyframe: false,
3704			duration: None,
3705		};
3706		Wire::legacy(crate::container::Kind::Audio)
3707			.write(
3708				&mut group.writer(),
3709				&[frame(50_000, Bytes::new()), frame(40_000, Bytes::from_static(&[1]))],
3710			)
3711			.unwrap();
3712		group.finish().unwrap();
3713		let _track = track.finish().unwrap();
3714		assert_eq!(items(&mut reader).await, ["0", "20000", "end 50000", "40000"]);
3715	}
3716
3717	#[kio::test]
3718	async fn a_marker_group_declares_an_end() {
3719		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
3720		let consumer_track =
3721			track.subscribe(
3722				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3723					moq_net::track::Start::Live {
3724						min: Some(Duration::from_secs(2)),
3725						max: Some(Duration::from_secs(2)),
3726					},
3727				)]),
3728			);
3729		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Audio));
3730
3731		write_group(&mut track, &[ts(0)]);
3732		write_marker_group(&mut track, ts(10_000));
3733		write_group(&mut track, &[ts(1_000_000)]);
3734		let _track = track.finish().unwrap();
3735
3736		assert_eq!(items(&mut consumer).await, ["0", "end 10000", "1000000"]);
3737	}
3738
3739	/// Missing media reads as a gap; only the publisher can declare an end.
3740	#[kio::test]
3741	async fn only_a_marker_declares_an_end() {
3742		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
3743		let consumer_track =
3744			track.subscribe(
3745				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3746					moq_net::track::Start::Live {
3747						min: Some(Duration::from_secs(2)),
3748						max: Some(Duration::from_secs(2)),
3749					},
3750				)]),
3751			);
3752		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Audio));
3753
3754		write_group(&mut track, &[ts(0)]);
3755		// Group 1 never arrives.
3756		write_group_after_gap(&mut track, &[ts(1_000_000)]);
3757		write_marker_group(&mut track, ts(1_010_000));
3758		write_group(&mut track, &[ts(2_000_000)]);
3759		let _track = track.finish().unwrap();
3760
3761		assert_eq!(
3762			items(&mut consumer).await,
3763			["0", "gap 0+1000000", "1000000", "end 1010000", "2000000"]
3764		);
3765	}
3766
3767	#[kio::test]
3768	async fn latency_skip_reports_a_gap() {
3769		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
3770		let consumer_track =
3771			track.subscribe(
3772				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3773					moq_net::track::Start::Live {
3774						min: Some(Duration::from_secs(2)),
3775						max: Some(Duration::from_secs(2)),
3776					},
3777				)]),
3778			);
3779		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Audio));
3780		// Keep transport filtering out of this test so it isolates the mux skip logic.
3781		consumer.max_delay = Duration::ZERO;
3782
3783		// Group 0 stays open, and is read before the newer group lands: the skip comes after the start.
3784		let mut group = Lazy::following(&track);
3785		Wire::legacy(crate::container::Kind::Audio)
3786			.write(
3787				&mut group.writer(),
3788				&[Frame {
3789					timestamp: ts(0),
3790					decode: None,
3791					payload: Bytes::from_static(&[0xDE, 0xAD]),
3792					keyframe: false,
3793					duration: None,
3794				}],
3795			)
3796			.unwrap();
3797		assert!(matches!(consumer.read().await.unwrap(), Some(Read::Frame { .. })));
3798		write_group_after_gap(&mut track, &[ts(1_000_000)]);
3799		let _track = track.finish().unwrap();
3800
3801		assert_eq!(items(&mut consumer).await, ["gap 0+1000000", "1000000"]);
3802	}
3803
3804	#[kio::test]
3805	async fn read_multiple_frames_single_group() {
3806		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3807		let consumer_track =
3808			track.subscribe(
3809				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3810					moq_net::track::Start::Live {
3811						min: Some(Duration::from_millis(500)),
3812						max: Some(Duration::from_millis(500)),
3813					},
3814				)]),
3815			);
3816		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
3817
3818		write_group(&mut track, &[ts(0), ts(33_000), ts(66_000)]);
3819		let _track = track.finish().unwrap();
3820
3821		let frames = read_all(&mut consumer).await.unwrap();
3822		assert_eq!(frames.len(), 3);
3823		assert_eq!(frames[0].timestamp, ts(0));
3824		assert_eq!(frames[1].timestamp, ts(33_000));
3825		assert_eq!(frames[2].timestamp, ts(66_000));
3826
3827		assert!(frames[0].keyframe);
3828	}
3829
3830	#[kio::test]
3831	async fn read_multiple_groups_within_latency() {
3832		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3833		let consumer_track =
3834			track.subscribe(
3835				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
3836					moq_net::track::Start::Live {
3837						min: Some(Duration::from_millis(500)),
3838						max: Some(Duration::from_millis(500)),
3839					},
3840				)]),
3841			);
3842		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
3843
3844		// 5 groups, 20ms spacing. Total span = 80ms, well within the 500ms max delay.
3845		for i in 0..5u64 {
3846			write_group(&mut track, &[ts(i * 20_000)]);
3847		}
3848		let _track = track.finish().unwrap();
3849
3850		let frames = read_all(&mut consumer).await.unwrap();
3851		assert_eq!(frames.len(), 5);
3852	}
3853
3854	// ---- Age Skipping ----
3855
3856	#[tokio::test]
3857	async fn latency_skip_delivers_recent_groups() {
3858		tokio::time::pause();
3859		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3860		let consumer_track = track.subscribe(crate::container::test_util::within(Duration::from_millis(100)));
3861		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
3862
3863		// Group 0: 5 frames, NOT finished (blocks consumer)
3864		let mut group0 = Lazy::following(&track);
3865		for f in 0..5u64 {
3866			Wire::legacy(crate::container::Kind::Data)
3867				.write(
3868					&mut group0.writer(),
3869					&[Frame {
3870						timestamp: ts(f * 2_000),
3871						decode: None,
3872						payload: Bytes::from_static(&[0xDE, 0xAD]),
3873						keyframe: false,
3874						duration: None,
3875					}],
3876				)
3877				.unwrap();
3878		}
3879
3880		// Groups 1-19: finished, 15ms spacing, 5 frames each
3881		for g in 1..20u64 {
3882			let timestamps: Vec<_> = (0..5).map(|f| ts(g * 15_000 + f * 2_000)).collect();
3883			write_group(&mut track, &timestamps);
3884		}
3885		let _track = track.finish().unwrap();
3886
3887		// Finish group 0 after consumer has had time to accumulate pending groups
3888		let finisher = tokio::spawn(async move {
3889			kio::clock::sleep(Duration::from_millis(50)).await;
3890			group0.finish().unwrap();
3891		});
3892
3893		let frames = read_all(&mut consumer).await.unwrap();
3894		// Group 0's 5 frames + some later groups (earlier ones skipped by age)
3895		assert!(frames.len() >= 25, "Expected >= 25 frames, got {}", frames.len());
3896		finisher.await.expect("finisher task panicked");
3897	}
3898
3899	#[tokio::test]
3900	async fn zero_latency_skips_aggressively() {
3901		tokio::time::pause();
3902		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3903		let consumer_track = track.subscribe(None);
3904		let mut consumer = container_max_delay_only(consumer_track, Duration::ZERO);
3905
3906		// Group 0 at ts 0 keeps timestamps monotonic with sequence (groups 1-9 follow at
3907		// g*50 ms), so the test exercises age skipping and not rewind detection.
3908		let mut group0 = Lazy::following(&track);
3909		Wire::legacy(crate::container::Kind::Data)
3910			.write(
3911				&mut group0.writer(),
3912				&[Frame {
3913					timestamp: ts(0),
3914					decode: None,
3915					payload: Bytes::from_static(&[0xDE, 0xAD]),
3916					keyframe: false,
3917					duration: None,
3918				}],
3919			)
3920			.unwrap();
3921
3922		// Read group 0's frame before the later groups land, so they skip a stalled group rather
3923		// than move the start.
3924		let first = consumer.read_frame().await.unwrap().unwrap();
3925		assert_eq!(first.timestamp, ts(0));
3926
3927		for g in 1..10u64 {
3928			let timestamps: Vec<_> = (0..3).map(|f| ts(g * 50_000 + f * 5_000)).collect();
3929			write_group(&mut track, &timestamps);
3930		}
3931		let _track = track.finish().unwrap();
3932
3933		let finisher = tokio::spawn(async move {
3934			kio::clock::sleep(Duration::from_millis(50)).await;
3935			group0.finish().unwrap();
3936		});
3937
3938		let frames = read_all(&mut consumer).await.unwrap();
3939		assert_eq!(frames.len(), 27, "Expected groups 1-9 after group 0's frame");
3940		assert!(!frames.is_empty(), "Expected at least some frames");
3941		finisher.await.expect("finisher task panicked");
3942	}
3943
3944	#[tokio::test]
3945	async fn latency_skip_correctness() {
3946		tokio::time::pause();
3947		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3948		let consumer_track = track.subscribe(None);
3949		let mut consumer = container_max_delay_only(consumer_track, Duration::from_millis(100));
3950
3951		let mut group0 = Lazy::following(&track);
3952		Wire::legacy(crate::container::Kind::Data)
3953			.write(
3954				&mut group0.writer(),
3955				&[Frame {
3956					timestamp: ts(0),
3957					decode: None,
3958					payload: Bytes::from_static(&[0xDE, 0xAD]),
3959					keyframe: false,
3960					duration: None,
3961				}],
3962			)
3963			.unwrap();
3964
3965		// Read group 0's frame before the later groups land, so they skip a stalled group rather
3966		// than move the start.
3967		let first = consumer.read_frame().await.unwrap().unwrap();
3968		assert_eq!(first.timestamp, ts(0));
3969
3970		for g in 1..10u64 {
3971			write_group(&mut track, &[ts(g * 30_000)]);
3972		}
3973		let _track = track.finish().unwrap();
3974
3975		let finisher = tokio::spawn(async move {
3976			kio::clock::sleep(Duration::from_millis(50)).await;
3977			group0.finish().unwrap();
3978		});
3979
3980		let frames = read_all(&mut consumer).await.unwrap();
3981		assert_eq!(frames.len(), 9, "Expected groups 1-9 after group 0's frame");
3982		for (i, frame) in (1..10u64).zip(&frames) {
3983			assert_eq!(frame.timestamp, ts(i * 30_000));
3984		}
3985		finisher.await.expect("finisher task panicked");
3986	}
3987
3988	/// A group longer than the budget that blocks for a moment behind a newer group is
3989	/// not cut short while what it could still present (up to where the newer group
3990	/// begins) is within the budget: the newer group races ahead on its own stream while
3991	/// the older one is still arriving.
3992	#[kio::test]
3993	async fn a_long_group_blocked_behind_a_newer_one_is_not_cut_short() {
3994		let waiter = kio::Waiter::noop();
3995		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3996		let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_secs(2));
3997		let write = |group: &mut Lazy, timestamp: Timestamp| {
3998			let frame = Frame {
3999				timestamp,
4000				decode: None,
4001				payload: Bytes::from_static(&[0xDE, 0xAD]),
4002				keyframe: false,
4003				duration: None,
4004			};
4005			Wire::legacy(crate::container::Kind::Data)
4006				.write(&mut group.writer(), &[frame])
4007				.unwrap();
4008		};
4009		let read = |consumer: &mut Consumer<Wire>| loop {
4010			match consumer.poll_read(&waiter) {
4011				Poll::Ready(Ok(Some(Read::Frame { frame, .. }))) => break Some(frame.timestamp),
4012				Poll::Ready(Ok(Some(Read::Gap { .. }))) => continue,
4013				Poll::Pending => break None,
4014				other => panic!("unexpected read: {other:?}"),
4015			}
4016		};
4017
4018		// A 2.5 s group, half arrived, and the next one already 0.5 s in. The reader started
4019		// before the next one landed, so this is a stall, not a join's backlog, which starts
4020		// within the budget instead (see `a_buffered_backlog_starts_within_the_budget`).
4021		let mut group0 = Lazy::following(&track);
4022		write(&mut group0, ts(0));
4023		write(&mut group0, ts(500_000));
4024		assert_eq!(read(&mut consumer), Some(ts(0)));
4025		let mut group1 = Lazy::following(&track);
4026		write(&mut group1, ts(2_500_000));
4027		write(&mut group1, ts(3_000_000));
4028
4029		assert_eq!(read(&mut consumer), Some(ts(500_000)));
4030		// Group 0's reach (2.5 s) is 0.5 s behind the newest frame: wait for it.
4031		assert_eq!(read(&mut consumer), None, "cut group 0 short");
4032		write(&mut group0, ts(1_000_000));
4033		assert_eq!(read(&mut consumer), Some(ts(1_000_000)));
4034		group0.finish().unwrap();
4035		assert_eq!(read(&mut consumer), Some(ts(2_500_000)));
4036
4037		// Once the reach falls a full budget behind, the stalled group is skipped.
4038		let mut group2 = Lazy::following(&track);
4039		write(&mut group2, ts(5_000_000));
4040		write(&mut group2, ts(7_000_000));
4041		assert_eq!(read(&mut consumer), Some(ts(3_000_000)));
4042		assert_eq!(read(&mut consumer), Some(ts(5_000_000)));
4043		group1.finish().unwrap();
4044		group2.finish().unwrap();
4045	}
4046
4047	/// A backlog that lands whole before the first read starts at the first group whose first
4048	/// frame is within the budget of the newest one, though nothing blocks. Five one-second
4049	/// groups of ten frames and a one-frame sixth at 5 s, with a 1.5 s budget, start at the 4 s
4050	/// group, whether the sixth is open or finished. `js/hang`'s `consumer.skips.test.ts` pairs
4051	/// this case.
4052	#[kio::test]
4053	async fn a_buffered_backlog_starts_within_the_budget() {
4054		for open in [true, false] {
4055			let waiter = kio::Waiter::noop();
4056			let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4057			let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_millis(1500));
4058			for g in 0..5u64 {
4059				let timestamps: Vec<_> = (0..10).map(|f| ts(g * 1_000_000 + f * 100_000)).collect();
4060				write_group(&mut track, &timestamps);
4061			}
4062			let mut last = Lazy::new(&track);
4063			Wire::legacy(crate::container::Kind::Data)
4064				.write(
4065					&mut last.writer(),
4066					&[Frame {
4067						timestamp: ts(5_000_000),
4068						decode: None,
4069						payload: Bytes::from_static(&[0xDE, 0xAD]),
4070						keyframe: false,
4071						duration: None,
4072					}],
4073				)
4074				.unwrap();
4075			if !open {
4076				last.finish().unwrap();
4077			}
4078
4079			let mut read = Vec::new();
4080			while let Poll::Ready(Ok(Some(item))) = consumer.poll_read(&waiter) {
4081				match item {
4082					Read::Frame { frame, .. } => read.push(frame.timestamp),
4083					other => panic!("unexpected read: {other:?}"),
4084				}
4085			}
4086			let expected: Vec<_> = (0..10)
4087				.map(|f| ts(4_000_000 + f * 100_000))
4088				.chain([ts(5_000_000)])
4089				.collect();
4090			assert_eq!(read, expected, "sixth group open: {open}");
4091		}
4092	}
4093
4094	/// A backlog join's start skip waits on the next group's first frame, which may land within the
4095	/// budget, rather than skipping on to a later group with data and dropping it. Here the fifth
4096	/// group (4.0 s) arrived with its frames still in flight, so the start keeps the fourth and
4097	/// plays on into the fifth. `js/hang`'s `consumer.skips.test.ts` pairs this case.
4098	#[kio::test]
4099	async fn a_backlog_start_waits_on_a_successor_without_frames() {
4100		let waiter = kio::Waiter::noop();
4101		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4102		let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_millis(1500));
4103		let frames = |g: u64| -> Vec<_> { (0..10).map(|f| ts(g * 1_000_000 + f * 100_000)).collect() };
4104		for g in 0..4u64 {
4105			write_group(&mut track, &frames(g));
4106		}
4107		let (mut head, rest) = in_flight(&track, frames(4)[0]);
4108		write_group(&mut track, &[ts(5_000_000)]);
4109
4110		let mut read = Vec::new();
4111		let mut drain = |consumer: &mut Consumer<Wire>| {
4112			while let Poll::Ready(Ok(Some(item))) = consumer.poll_read(&waiter) {
4113				match item {
4114					Read::Frame { frame, .. } => read.push(frame.timestamp),
4115					other => panic!("unexpected read: {other:?}"),
4116				}
4117			}
4118		};
4119		drain(&mut consumer);
4120		head.write(rest).unwrap();
4121		let mut fifth = Some(head.finish().unwrap());
4122		for frame in frames(4).into_iter().skip(1) {
4123			Wire::legacy(crate::container::Kind::Data)
4124				.write(
4125					&mut crate::container::Writer::new(&track, &mut fifth),
4126					&[Frame {
4127						timestamp: frame,
4128						decode: None,
4129						payload: Bytes::from_static(&[0xDE, 0xAD]),
4130						keyframe: false,
4131						duration: None,
4132					}],
4133				)
4134				.unwrap();
4135		}
4136		fifth.unwrap().finish().unwrap();
4137		drain(&mut consumer);
4138
4139		let expected: Vec<_> = frames(3).into_iter().chain(frames(4)).chain([ts(5_000_000)]).collect();
4140		assert_eq!(read, expected);
4141	}
4142
4143	// ---- Malformed rewind ----
4144
4145	/// The track refuses a group whose first frame rewinds, but not a later frame that does,
4146	/// so the consumer floors every frame against the previous group's start.
4147	#[kio::test]
4148	async fn a_frame_below_the_previous_start_aborts() {
4149		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4150		let mut consumer = Consumer::new(track.subscribe(None), Wire::legacy(crate::container::Kind::Data));
4151		write_group(&mut track, &[ts(100_000)]);
4152		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(100_000));
4153		write_group(&mut track, &[ts(133_000), ts(0)]);
4154		let _track = track.finish().unwrap();
4155		let err = loop {
4156			match consumer.read().await {
4157				Ok(Some(_)) => continue,
4158				Ok(None) => panic!("the rewound frame ended the track cleanly"),
4159				Err(err) => break err,
4160			}
4161		};
4162		assert!(matches!(
4163			err,
4164			crate::Error::TimestampRewind(TimestampRewind { timestamp, floor })
4165				if timestamp == ts(0) && floor == ts(100_000)
4166		));
4167		assert_eq!(
4168			err.to_string(),
4169			"frame timestamp 0 µs is below the previous group's start 100000 µs"
4170		);
4171	}
4172
4173	#[kio::test]
4174	async fn b_frames_within_a_group_are_accepted() {
4175		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4176		let mut consumer = Consumer::new(track.subscribe(None), Wire::legacy(crate::container::Kind::Data));
4177		write_group(&mut track, &[ts(0), ts(66_000), ts(33_000)]);
4178		let _track = track.finish().unwrap();
4179		let frames = continuous_frames(&mut consumer).await;
4180		assert_eq!(
4181			frames.iter().map(|f| f.timestamp).collect::<Vec<_>>(),
4182			vec![ts(0), ts(66_000), ts(33_000)]
4183		);
4184	}
4185
4186	#[kio::test]
4187	async fn open_gop_leading_pictures_above_the_previous_group_are_accepted() {
4188		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4189		let mut consumer = Consumer::new(track.subscribe(None), Wire::legacy(crate::container::Kind::Data));
4190		write_group(&mut track, &[ts(0), ts(33_000)]);
4191		// Read the first group before the second arrives: a superseded group is skipped
4192		// for latency, which is not what this checks.
4193		for expected in [0, 33_000] {
4194			assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(expected));
4195		}
4196		write_group(&mut track, &[ts(66_000), ts(50_000)]);
4197		let _track = track.finish().unwrap();
4198		let frames = continuous_frames(&mut consumer).await;
4199		assert_eq!(
4200			frames
4201				.iter()
4202				.map(|f| f.timestamp.as_micros().unwrap())
4203				.collect::<Vec<_>>(),
4204			vec![66_000, 50_000]
4205		);
4206	}
4207
4208	#[kio::test]
4209	async fn a_marker_group_and_forward_jump_reads_one_end() {
4210		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
4211		let mut consumer = Consumer::new(
4212			track.subscribe(
4213				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4214					moq_net::track::Start::Live {
4215						min: Some(Duration::from_secs(2)),
4216						max: Some(Duration::from_secs(2)),
4217					},
4218				)]),
4219			),
4220			Wire::legacy(crate::container::Kind::Audio),
4221		);
4222		write_group(&mut track, &[ts(0)]);
4223		write_marker_group(&mut track, ts(10_000));
4224		write_group(&mut track, &[ts(1_000_000)]);
4225		let _track = track.finish().unwrap();
4226		assert_eq!(items(&mut consumer).await, ["0", "end 10000", "1000000"]);
4227	}
4228
4229	/// A pause's timestamp jump is not lateness: the group that resumes it can arrive behind the
4230	/// one after it, and is waited for like any hole rather than skipped as too old.
4231	#[tokio::test(start_paused = true)]
4232	async fn the_head_after_a_declared_end_is_waited_for() {
4233		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.audio)).await;
4234		let mut consumer =
4235			Consumer::new(
4236				copy.subscribe_with(moq_net::track::Subscription::default().with_ranges([
4237					moq_net::track::Range::from(moq_net::track::Start::Live {
4238						min: Some(Duration::from_secs(30)),
4239						max: Some(Duration::from_secs(30)),
4240					}),
4241				]))
4242				.await,
4243				Wire::legacy(crate::container::Kind::Audio),
4244			);
4245		consumer.max_delay = Duration::from_millis(300);
4246		write_group(&mut copy.track, &[ts(0)]);
4247		carried().await;
4248		// The end, then the stopped encoder's final packet, as `moq_audio`'s producer writes them.
4249		let mut group = Lazy::following(&copy.track);
4250		let frame = |timestamp, payload| Frame {
4251			timestamp,
4252			decode: None,
4253			payload,
4254			keyframe: true,
4255			duration: None,
4256		};
4257		Wire::legacy(crate::container::Kind::Audio)
4258			.write(
4259				&mut group.writer(),
4260				&[
4261					frame(ts(60_000), Bytes::new()),
4262					frame(ts(40_000), Bytes::from_static(b"x")),
4263				],
4264			)
4265			.unwrap();
4266		group.finish().unwrap();
4267		carried().await;
4268		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(0));
4269		assert!(matches!(
4270			consumer.read().await.unwrap(),
4271			Some(Read::End { group: 60_000, .. })
4272		));
4273		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(40_000));
4274		// Only the resuming group's key is left a hole.
4275		copy.track.skip_groups(60_001..60_000_000);
4276		copy.track.skip_groups(60_000_001..60_060_000);
4277		write_group_after_gap(&mut copy.track, &[ts(60_060_000)]);
4278		carried().await;
4279		tokio::time::advance(Duration::from_millis(299)).await;
4280		carried().await;
4281		assert!(consumer.poll_read(&kio::Waiter::noop()).is_pending());
4282		write_group_after_gap(&mut copy.track, &[ts(60_000_000)]);
4283		carried().await;
4284		let _track = copy.track.finish().unwrap();
4285		assert_eq!(items(&mut consumer).await, ["60000000", "60060000"]);
4286	}
4287
4288	#[kio::test]
4289	async fn a_zero_budget_idle_resume_reports_the_shed_marker_as_a_gap() {
4290		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
4291		let mut consumer = Consumer::new(track.subscribe(None), Wire::legacy(crate::container::Kind::Audio));
4292		consumer.max_delay = Duration::ZERO;
4293		write_group(&mut track, &[ts(0)]);
4294		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(0));
4295		write_marker_group(&mut track, ts(10_000));
4296		write_group(&mut track, &[ts(1_000_000)]);
4297		let _track = track.finish().unwrap();
4298		assert!(matches!(consumer.read().await.unwrap(), Some(Read::Gap { .. })));
4299		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(1_000_000));
4300	}
4301
4302	#[kio::test]
4303	async fn a_zero_budget_skip_reports_a_contiguous_shed_marker_as_a_gap() {
4304		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
4305		let mut consumer = Consumer::new(track.subscribe(None), Wire::legacy(crate::container::Kind::Audio));
4306		consumer.max_delay = Duration::ZERO;
4307
4308		let mut group0 = Lazy::following(&track);
4309		Wire::legacy(crate::container::Kind::Audio)
4310			.write(
4311				&mut group0.writer(),
4312				&[Frame {
4313					timestamp: ts(0),
4314					decode: None,
4315					payload: Bytes::from_static(&[0xDE, 0xAD]),
4316					keyframe: false,
4317					duration: None,
4318				}],
4319			)
4320			.unwrap();
4321		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(0));
4322
4323		write_marker_group(&mut track, ts(9_999));
4324		write_group(&mut track, &[ts(10_000)]);
4325
4326		assert!(matches!(consumer.read().await.unwrap(), Some(Read::Gap { .. })));
4327		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(10_000));
4328		group0.finish().unwrap();
4329	}
4330
4331	#[kio::test]
4332	async fn a_later_frame_below_the_previous_group_start_aborts() {
4333		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4334		let mut consumer = Consumer::new(track.subscribe(None), Wire::legacy(crate::container::Kind::Data));
4335		write_group(&mut track, &[ts(100_000)]);
4336		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(100_000));
4337		write_group(&mut track, &[ts(200_000), ts(50_000)]);
4338		let _track = track.finish().unwrap();
4339		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(200_000));
4340		let err = consumer.read().await.unwrap_err();
4341		assert!(matches!(
4342			err,
4343			crate::Error::TimestampRewind(TimestampRewind { timestamp, floor })
4344				if timestamp == ts(50_000) && floor == ts(100_000)
4345		));
4346		assert_eq!(
4347			err.to_string(),
4348			"frame timestamp 50000 µs is below the previous group's start 100000 µs"
4349		);
4350	}
4351
4352	// ---- Empty payloads ----
4353
4354	/// Write one frame with an empty payload: a marker saying content stops at
4355	/// `timestamp`, carrying no media.
4356	fn write_marker(group: &mut Lazy, timestamp: Timestamp) {
4357		let frame = Frame {
4358			timestamp,
4359			decode: None,
4360			payload: Bytes::new(),
4361			keyframe: false,
4362			duration: None,
4363		};
4364		Wire::legacy(crate::container::Kind::Data)
4365			.write(&mut group.writer(), &[frame])
4366			.unwrap();
4367	}
4368
4369	/// An empty payload carries no media, so it's skipped rather than surfaced as a
4370	/// frame or raised as an error. It times the previous frame and never means the
4371	/// track ended.
4372	#[kio::test]
4373	async fn empty_payload_is_skipped() {
4374		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4375		let consumer_track =
4376			track.subscribe(
4377				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4378					moq_net::track::Start::Live {
4379						min: Some(Duration::from_millis(500)),
4380						max: Some(Duration::from_millis(500)),
4381					},
4382				)]),
4383			);
4384		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Video));
4385
4386		let mut group = Lazy::following(&track);
4387		let media = |timestamp| Frame {
4388			timestamp,
4389			decode: None,
4390			payload: Bytes::from_static(&[0xDE, 0xAD]),
4391			keyframe: false,
4392			duration: None,
4393		};
4394		Wire::legacy(crate::container::Kind::Video)
4395			.write(&mut group.writer(), &[media(ts(0))])
4396			.unwrap();
4397		write_marker(&mut group, ts(16_000)); // closes the first frame
4398		Wire::legacy(crate::container::Kind::Video)
4399			.write(&mut group.writer(), &[media(ts(33_000))])
4400			.unwrap();
4401		write_marker(&mut group, ts(50_000)); // the group's end
4402		group.finish().unwrap();
4403		let _track = track.finish().unwrap();
4404
4405		let frames = read_all(&mut consumer).await.unwrap();
4406		assert_eq!(frames.len(), 2, "markers are not surfaced as media");
4407		assert_eq!(frames[0].timestamp, ts(0));
4408		assert_eq!(frames[1].timestamp, ts(33_000));
4409	}
4410
4411	#[kio::test]
4412	async fn leading_marker_preserves_the_first_media_keyframe() {
4413		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4414		let consumer_track =
4415			track.subscribe(
4416				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4417					moq_net::track::Start::Live {
4418						min: Some(Duration::from_millis(500)),
4419						max: Some(Duration::from_millis(500)),
4420					},
4421				)]),
4422			);
4423		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Video));
4424
4425		let mut group = Lazy::following(&track);
4426		write_marker(&mut group, ts(20_000));
4427		Wire::legacy(crate::container::Kind::Video)
4428			.write(
4429				&mut group.writer(),
4430				&[Frame {
4431					timestamp: ts(20_000),
4432					decode: None,
4433					payload: Bytes::from_static(&[0xDE, 0xAD]),
4434					keyframe: false,
4435					duration: None,
4436				}],
4437			)
4438			.unwrap();
4439		group.finish().unwrap();
4440		let _track = track.finish().unwrap();
4441
4442		let frame = consumer.read_frame().await.unwrap().unwrap();
4443		assert!(frame.keyframe, "the marker does not consume the first-media slot");
4444		assert!(frame.duration.is_none(), "a leading marker has no previous frame");
4445	}
4446
4447	/// Reading a marker consumes its frame, so a run of them makes progress and the
4448	/// consumer reaches the next group instead of spinning. `read_all` times out per
4449	/// read, so a stall or an infinite loop fails this rather than hanging forever.
4450	#[kio::test]
4451	async fn consecutive_markers_do_not_stall() {
4452		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4453		let consumer_track =
4454			track.subscribe(
4455				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4456					moq_net::track::Start::Live {
4457						min: Some(Duration::from_millis(500)),
4458						max: Some(Duration::from_millis(500)),
4459					},
4460				)]),
4461			);
4462		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Video));
4463
4464		let mut group = Lazy::following(&track);
4465		Wire::legacy(crate::container::Kind::Video)
4466			.write(
4467				&mut group.writer(),
4468				&[Frame {
4469					timestamp: ts(0),
4470					decode: None,
4471					payload: Bytes::from_static(&[0xDE, 0xAD]),
4472					keyframe: false,
4473					duration: None,
4474				}],
4475			)
4476			.unwrap();
4477		for i in 1..5u64 {
4478			write_marker(&mut group, ts(i * 1_000));
4479		}
4480		group.finish().unwrap();
4481		write_group(&mut track, &[ts(100_000)]);
4482		let _track = track.finish().unwrap();
4483
4484		let frames = read_all(&mut consumer).await.unwrap();
4485		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
4486		assert_eq!(micros, vec![0, 100_000], "markers skipped, next group reached");
4487	}
4488
4489	/// LOC video consumers skip an empty payload: it is the duration marker, not media.
4490	#[kio::test]
4491	async fn loc_empty_payload_is_skipped() {
4492		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4493		let consumer_track =
4494			track.subscribe(
4495				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4496					moq_net::track::Start::Live {
4497						min: Some(Duration::from_millis(500)),
4498						max: Some(Duration::from_millis(500)),
4499					},
4500				)]),
4501			);
4502		let mut consumer = Consumer::new(consumer_track, Wire::loc(crate::container::Kind::Video));
4503
4504		let mut group = Lazy::following(&track);
4505		let media = Frame {
4506			timestamp: ts(0),
4507			decode: None,
4508			payload: Bytes::from_static(&[0xDE, 0xAD]),
4509			keyframe: true,
4510			duration: None,
4511		};
4512		Wire::loc(crate::container::Kind::Video)
4513			.write(&mut group.writer(), &[media])
4514			.unwrap();
4515		Wire::loc(crate::container::Kind::Video)
4516			.write(
4517				&mut group.writer(),
4518				&[Frame {
4519					timestamp: ts(33_000),
4520					decode: None,
4521					payload: Bytes::new(),
4522					keyframe: false,
4523					duration: None,
4524				}],
4525			)
4526			.unwrap();
4527		group.finish().unwrap();
4528		let _track = track.finish().unwrap();
4529
4530		let frames = read_all(&mut consumer).await.unwrap();
4531		assert_eq!(frames.len(), 1, "the empty LOC payload is not submitted");
4532		assert_eq!(frames[0].timestamp, ts(0));
4533	}
4534
4535	// ---- Group Ordering ----
4536
4537	#[tokio::test]
4538	async fn groups_delivered_in_sequence_order() {
4539		tokio::time::pause();
4540		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4541		let consumer_track =
4542			track.subscribe(
4543				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4544					moq_net::track::Start::Live {
4545						min: Some(Duration::from_millis(500)),
4546						max: Some(Duration::from_millis(500)),
4547					},
4548				)]),
4549			);
4550		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4551
4552		let mut group0 = Lazy::following(&track);
4553		Wire::legacy(crate::container::Kind::Data)
4554			.write(
4555				&mut group0.writer(),
4556				&[Frame {
4557					timestamp: ts(0),
4558					decode: None,
4559					payload: Bytes::from_static(&[0xDE, 0xAD]),
4560					keyframe: false,
4561					duration: None,
4562				}],
4563			)
4564			.unwrap();
4565
4566		write_group_after_gap(&mut track, &[ts(60_000)]);
4567		write_group(&mut track, &[ts(30_000)]);
4568		let _track = track.finish().unwrap();
4569
4570		let finisher = tokio::spawn(async move {
4571			kio::clock::sleep(Duration::from_millis(10)).await;
4572			group0.finish().unwrap();
4573		});
4574
4575		let frames = read_all(&mut consumer).await.unwrap();
4576		assert_eq!(frames.len(), 3);
4577		assert_eq!(frames[0].timestamp, ts(0));
4578		assert_eq!(frames[1].timestamp, ts(30_000));
4579		assert_eq!(frames[2].timestamp, ts(60_000));
4580		finisher.await.expect("finisher task panicked");
4581	}
4582
4583	#[kio::test]
4584	async fn adjacent_group_flushed_immediately() {
4585		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4586		let consumer_track =
4587			track.subscribe(
4588				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4589					moq_net::track::Start::Live {
4590						min: Some(Duration::from_millis(500)),
4591						max: Some(Duration::from_millis(500)),
4592					},
4593				)]),
4594			);
4595		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4596
4597		write_group(&mut track, &[ts(0)]);
4598		write_group(&mut track, &[ts(30_000)]);
4599		let _track = track.finish().unwrap();
4600
4601		let frames = read_all(&mut consumer).await.unwrap();
4602		assert_eq!(frames.len(), 2);
4603		assert_eq!(frames[0].timestamp, ts(0));
4604		assert_eq!(frames[1].timestamp, ts(30_000));
4605	}
4606
4607	// ---- Track Lifecycle ----
4608
4609	#[tokio::test]
4610	async fn empty_track_returns_none() {
4611		tokio::time::pause();
4612		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4613		let consumer_track =
4614			track.subscribe(
4615				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4616					moq_net::track::Start::Live {
4617						min: Some(Duration::from_millis(500)),
4618						max: Some(Duration::from_millis(500)),
4619					},
4620				)]),
4621			);
4622		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4623
4624		let _track = track.finish().unwrap();
4625
4626		let result = kio::clock::timeout(Duration::from_millis(200), consumer.read()).await;
4627		match result {
4628			Ok(Ok(None)) => {} // expected: track ended
4629			Ok(Ok(Some(_))) => panic!("expected None for empty track, got Some"),
4630			Ok(Err(e)) => panic!("expected None for empty track, got error: {e}"),
4631			Err(_) => panic!("should not hang on empty track"),
4632		}
4633	}
4634
4635	#[tokio::test]
4636	async fn track_closed_with_error() {
4637		tokio::time::pause();
4638		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4639		let consumer_track =
4640			track.subscribe(
4641				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4642					moq_net::track::Start::Live {
4643						min: Some(Duration::from_millis(500)),
4644						max: Some(Duration::from_millis(500)),
4645					},
4646				)]),
4647			);
4648		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4649
4650		write_group(&mut track, &[ts(0), ts(10_000)]);
4651		track.abort(moq_net::Error::Cancel).unwrap();
4652
4653		// The groups already here drain before the track's error, as in JS.
4654		let mut frames = Vec::new();
4655		let end = loop {
4656			let read = kio::clock::timeout(Duration::from_millis(500), consumer.read())
4657				.await
4658				.expect("Consumer should not hang after track error");
4659			match read {
4660				Ok(Some(Read::Frame { frame, .. })) => frames.push(frame.timestamp),
4661				Ok(Some(_)) => continue,
4662				other => break other,
4663			}
4664		};
4665		assert_eq!(frames, [ts(0), ts(10_000)]);
4666		assert!(end.is_err(), "{end:?}");
4667		assert!(matches!(consumer.read().await, Ok(None)));
4668	}
4669
4670	// ---- Gap Recovery ----
4671
4672	#[kio::test]
4673	async fn gap_in_group_sequence_recovery() {
4674		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4675		let consumer_track = track.subscribe(crate::container::test_util::within(Duration::from_millis(100)));
4676		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4677
4678		write_group(&mut track, &[ts(0), ts(20_000)]);
4679		write_group(&mut track, &[ts(40_000), ts(60_000)]);
4680		write_group_after_gap(&mut track, &[ts(120_000), ts(140_000)]);
4681		write_group(&mut track, &[ts(160_000), ts(180_000)]);
4682		write_group(&mut track, &[ts(200_000), ts(220_000)]);
4683		write_group(&mut track, &[ts(240_000), ts(260_000)]);
4684		let _track = track.finish().unwrap();
4685
4686		let frames = read_all(&mut consumer).await.unwrap();
4687		assert!(frames.len() >= 4, "Expected >= 4 frames, got {}", frames.len());
4688	}
4689
4690	#[kio::test]
4691	async fn gap_at_start_of_sequence() {
4692		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4693		let consumer_track = track.subscribe(crate::container::test_util::within(Duration::from_millis(80)));
4694		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4695
4696		write_group_after_gap(&mut track, &[ts(0), ts(20_000)]);
4697		write_group_after_gap(&mut track, &[ts(80_000), ts(100_000)]);
4698		write_group(&mut track, &[ts(120_000), ts(140_000)]);
4699		write_group(&mut track, &[ts(160_000), ts(180_000)]);
4700		let _track = track.finish().unwrap();
4701
4702		let frames = read_all(&mut consumer).await.unwrap();
4703		assert!(frames.len() >= 4, "Expected >= 4 frames, got {}", frames.len());
4704	}
4705
4706	#[tokio::test(start_paused = true)]
4707	async fn truncated_resumed_group_skips_to_the_next_clean_group() {
4708		// One publisher identity behind every route, so each may resume the others.
4709		let identity = moq_net::Identity::random();
4710		let origin = crate::source::produce_origin();
4711		let route = |cost: u64| {
4712			moq_net::origin::RouteOptions::hidden()
4713				.with_identity(identity.clone(), 0)
4714				.with_cost(cost)
4715		};
4716		let first = origin.route("live", route(5)).unwrap();
4717		let info = hang::container::track_info(hang::catalog::PRIORITY.video);
4718		let first_track = first.broadcast().create_track("video", info.clone()).unwrap();
4719		first.announce().unwrap();
4720		let broadcast = origin.consume().request("live", None).await.unwrap();
4721		let track = broadcast
4722			.track("video")
4723			.unwrap()
4724			.subscribe(crate::container::test_util::within(Duration::from_secs(2)))
4725			.await
4726			.unwrap();
4727		let format = Wire::legacy(crate::container::Kind::Data);
4728		let mut consumer = Consumer::new(track, Wire::legacy(crate::container::Kind::Data));
4729
4730		let mut open = Lazy::new(&first_track);
4731		format
4732			.write(
4733				&mut open.writer(),
4734				&[Frame {
4735					timestamp: ts(0),
4736					decode: None,
4737					payload: Bytes::from_static(&[0xDE, 0xAD]),
4738					keyframe: true,
4739					duration: None,
4740				}],
4741			)
4742			.unwrap();
4743
4744		// Each cheaper route takes over beyond group 0 without holding its continuation,
4745		// while the first route stays up but silent. They carry the same broadcast, so each
4746		// holds every group from 1 on. The open group is given up once the track runs a
4747		// full budget past it.
4748		let mut sources = Vec::new();
4749		for sequence in 1..=4 {
4750			let source = origin.route("live", route(5 - sequence)).unwrap();
4751			let mut track = source.broadcast().create_track("video", info.clone()).unwrap();
4752			source.announce().unwrap();
4753			let mut demand = track.demand();
4754			while !demand.wanted_changed().await.unwrap() {}
4755			if sequence == 1 {
4756				assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(0));
4757			}
4758			for sequence in 1..=sequence {
4759				write_group(&mut track, &[ts(sequence * 1_000_000)]);
4760			}
4761			sources.push((source, track));
4762		}
4763
4764		let waiter = kio::Waiter::noop();
4765
4766		// The aborted group 0 says it was cut, then skips straight to its successor; a short
4767		// clean group emits GroupEnd.
4768		assert!(
4769			matches!(consumer.poll_event(&waiter), Poll::Ready(Ok(Some(Event::Cut { .. })))),
4770			"the cut is said before the successor"
4771		);
4772		let event = consumer.poll_event(&waiter);
4773		let Poll::Ready(Ok(Some(Event::Frame { frame, .. }))) = event else {
4774			panic!(
4775				"expected a successor frame, current={}; pending={}",
4776				consumer.current,
4777				event.is_pending()
4778			);
4779		};
4780		assert_eq!(frame.timestamp, ts(1_000_000));
4781		assert!(frame.keyframe);
4782		assert_eq!(consumer.current, 1_000_000);
4783		// Once the front settles on the newest route, whose info may still be in flight: a
4784		// short close waits to see whether that route holds more.
4785		assert!(
4786			matches!(
4787				kio::wait(|waiter| consumer.poll_event(waiter)).await,
4788				Ok(Some(Event::GroupEnd))
4789			),
4790			"the complete successor still emits its clean boundary"
4791		);
4792		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(2_000_000));
4793	}
4794
4795	// ---- Eviction recovery (pause/resume) ----
4796
4797	/// A group that aged out of the relay cache (aborted with `Error::Old`) while the
4798	/// consumer was parked on it must not hang the consumer: reading it errors, and
4799	/// the consumer skips the gap to the next live group even though the track is NOT
4800	/// finished. This is the resume-from-pause path (the recorder stops reading, the
4801	/// group + the sequences after it evict, then it resumes).
4802	#[kio::test]
4803	async fn evicted_group_with_gap_skips_to_live() {
4804		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4805		let consumer_track =
4806			track.subscribe(
4807				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4808					moq_net::track::Start::Live {
4809						min: Some(Duration::from_millis(100)),
4810						max: Some(Duration::from_millis(100)),
4811					},
4812				)]),
4813			);
4814		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4815
4816		// Group 0: a frame the consumer reads, positioning it there.
4817		let mut group0 = Lazy::following(&track);
4818		Wire::legacy(crate::container::Kind::Data)
4819			.write(
4820				&mut group0.writer(),
4821				&[Frame {
4822					timestamp: ts(0),
4823					decode: None,
4824					payload: Bytes::from_static(&[0xDE, 0xAD]),
4825					keyframe: false,
4826					duration: None,
4827				}],
4828			)
4829			.unwrap();
4830		let first = consumer.read_frame().await.unwrap().unwrap();
4831		assert_eq!(first.timestamp, ts(0));
4832
4833		// A live group arrives far ahead -- sequences 1..4 never come (evicted). The
4834		// track stays OPEN (not finished), the failure mode that used to hang.
4835		write_group_after_gap(&mut track, &[ts(150_000)]);
4836
4837		// Group 0 ages out of the cache (the relay aborts it on eviction).
4838		group0.abort(moq_net::Error::Old).unwrap();
4839
4840		// Must skip the evicted group + the gap and reach the live group, without
4841		// hanging on a track that never finishes.
4842		let next = kio::clock::timeout(Duration::from_secs(1), consumer.read())
4843			.await
4844			.expect("consumer hung on an evicted group / gap")
4845			.unwrap()
4846			.unwrap();
4847		assert!(
4848			matches!(next, Read::Gap { timestamp, duration } if timestamp == ts(0) && duration == Duration::from_micros(150_000)),
4849			"the evicted media is a gap from the last frame to the live group: {next:?}"
4850		);
4851		let next = consumer.read_frame().await.unwrap().unwrap();
4852		assert_eq!(next.timestamp, ts(150_000), "skipped the evicted gap to the live group");
4853	}
4854
4855	/// A missing (evicted) sequence with a newer group buffered must be skipped once the
4856	/// age budget runs out, even while the track is still LIVE -- not only once it's
4857	/// finished. This is the recorder resume stall: `current` points at a sequence the
4858	/// cache dropped, higher groups are buffered, and the track never finishes. The gap
4859	/// is indistinguishable from a stream that lost the delivery race, so the skip fires
4860	/// only once the newest content is a full budget past what the gap could still hold.
4861	#[tokio::test]
4862	async fn missing_sequence_skips_on_live_track() {
4863		// The delivery budget runs on max(wall, pts): on wall time a stalled runner ages
4864		// group 2 out of delivery before the consumer reaches it.
4865		tokio::time::pause();
4866		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4867		let consumer_track =
4868			track.subscribe(
4869				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4870					moq_net::track::Start::Live {
4871						min: Some(Duration::from_millis(100)),
4872						max: Some(Duration::from_millis(100)),
4873					},
4874				)]),
4875			);
4876		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4877
4878		// Read group 0 first, positioning the cursor there before the newer groups
4879		// arrive; otherwise delivery convicts group 0 and the cursor never meets the gap.
4880		write_group(&mut track, &[ts(0), ts(20_000)]);
4881		for expected in [ts(0), ts(20_000)] {
4882			let frame = consumer.read_frame().await.unwrap().unwrap();
4883			assert_eq!(frame.timestamp, expected);
4884		}
4885
4886		// Group 2 arrives but sequence 1 is missing (evicted) and never does. The track
4887		// is NOT finished (live), the case that used to hang. Group 3 pushes the live
4888		// edge a full budget past group 2's start, expiring the gap at 1.
4889		write_group_after_gap(&mut track, &[ts(200_000)]);
4890		write_group(&mut track, &[ts(320_000)]);
4891
4892		// The age budget alone closes the gap: the deadline sits short of the 100ms
4893		// hole timer, so waiting it out fails the test.
4894		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
4895			.await
4896			.expect("consumer hung on a missing sequence on a live track")
4897			.unwrap()
4898			.unwrap();
4899		assert_eq!(frame.timestamp, ts(200_000), "skipped the missing sequence to group 2");
4900	}
4901
4902	/// The other half of the budget-gated gap: while the newest content is still within
4903	/// the age budget of what the missing sequence could present, the consumer waits for
4904	/// it instead of writing it off, and delivers it when its stream loses the race but
4905	/// still arrives (#3258).
4906	#[tokio::test]
4907	async fn gap_keeps_late_arriving_group_within_max_delay() {
4908		tokio::time::pause();
4909		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
4910		let consumer_track = copy
4911			.subscribe_with(
4912				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4913					moq_net::track::Start::Live {
4914						min: Some(Duration::from_millis(500)),
4915						max: Some(Duration::from_millis(500)),
4916					},
4917				)]),
4918			)
4919			.await;
4920		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4921
4922		// Group 2's stream beats group 1's, which hasn't arrived at all yet.
4923		write_group(&mut copy.track, &[ts(0)]);
4924		carried().await;
4925		write_group_after_gap(&mut copy.track, &[ts(200_000)]);
4926		carried().await;
4927
4928		let first = consumer.read_frame().await.unwrap().expect("group 0 frame");
4929		assert_eq!(first.timestamp, ts(0));
4930
4931		// Group 0 is done; group 1's stream is still racing. Within the budget the
4932		// consumer waits at the gap rather than skipping to group 2.
4933		assert!(
4934			kio::clock::timeout(Duration::from_millis(50), consumer.read())
4935				.await
4936				.is_err(),
4937			"the gap at sequence 1 is within budget and must be waited for"
4938		);
4939
4940		// Group 1's stream opens moments later, well within the 500ms budget.
4941		write_group(&mut copy.track, &[ts(100_000)]);
4942		carried().await;
4943		let _track = copy.track.finish().unwrap();
4944
4945		let frames = read_all(&mut consumer).await.unwrap();
4946		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
4947		assert_eq!(micros, vec![100_000, 200_000], "the late group is delivered in order");
4948	}
4949
4950	/// A group whose frames lost the race to a newer group's stream is still read once
4951	/// they land: the cursor starts at group 0 and waits under the budget (#3258).
4952	#[tokio::test]
4953	async fn startup_keeps_slow_earlier_stream_within_max_delay() {
4954		tokio::time::pause();
4955		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
4956		let consumer_track =
4957			track.subscribe(
4958				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
4959					moq_net::track::Start::Live {
4960						min: Some(Duration::from_millis(500)),
4961						max: Some(Duration::from_millis(500)),
4962					},
4963				)]),
4964			);
4965		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
4966
4967		// Group 0's stream opens first but its first frame is still in flight; group 1's wins.
4968		let (mut head, rest) = in_flight(&track, ts(0));
4969		write_group(&mut track, &[ts(100_000)]);
4970
4971		// Startup latches onto the lowest arrived sequence and waits under the budget.
4972		assert!(
4973			kio::clock::timeout(Duration::from_millis(50), consumer.read())
4974				.await
4975				.is_err(),
4976			"group 0's frames are within budget and must be waited for"
4977		);
4978
4979		head.write(rest).unwrap();
4980		head.finish().unwrap().finish().unwrap();
4981		let _track = track.finish().unwrap();
4982
4983		let frames = read_all(&mut consumer).await.unwrap();
4984		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
4985		assert_eq!(micros, vec![0, 100_000], "the slow stream's frames are delivered");
4986	}
4987
4988	// ---- Start reach ----
4989
4990	/// An unfloored consumer that starts `min` plus `warmup` behind the live edge and skips at `max`.
4991	fn reach_consumer(
4992		track: &mut moq_net::track::Producer,
4993		min: Duration,
4994		max: Duration,
4995		warmup: Duration,
4996	) -> Consumer<Wire> {
4997		let playout = Playout::new(
4998			Delay {
4999				min: Some(min),
5000				max: Some(max),
5001			},
5002			warmup,
5003		);
5004		let consumer_track = track.subscribe(
5005			playout.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL])),
5006		);
5007		playout.consumer(consumer_track, Wire::legacy(crate::container::Kind::Data))
5008	}
5009
5010	/// A reader of `copy` that starts `min` plus `warmup` behind the live edge and skips at `max`.
5011	async fn reach_reader(copy: &Received, min: Duration, max: Duration, warmup: Duration) -> Consumer<Wire> {
5012		let playout = Playout::new(
5013			Delay {
5014				min: Some(min),
5015				max: Some(max),
5016			},
5017			warmup,
5018		);
5019		let subscriber = copy
5020			.subscribe_with(
5021				playout.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL])),
5022			)
5023			.await;
5024		playout.consumer(subscriber, Wire::legacy(crate::container::Kind::Data))
5025	}
5026
5027	/// The publisher sends the live edge first, newest first, yet the reader starts at the earlier
5028	/// group its join owes, which the ordered reader waits for.
5029	#[tokio::test(start_paused = true)]
5030	async fn the_start_waits_for_an_earlier_group_when_the_live_edge_arrives_first() {
5031		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
5032		append_timed(&mut copy.track, &[ts(4_800_000)]);
5033		append_timed(&mut copy.track, &[ts(5_000_000)]);
5034		let mut consumer = reach_reader(
5035			&copy,
5036			Duration::from_millis(500),
5037			Duration::from_millis(500),
5038			Duration::ZERO,
5039		)
5040		.await;
5041		let _track = copy.track.finish().unwrap();
5042
5043		let frames = read_all(&mut consumer).await.unwrap();
5044		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
5045		assert_eq!(
5046			micros,
5047			vec![4_800_000, 5_000_000],
5048			"the earlier group is delivered first"
5049		);
5050	}
5051
5052	/// With no min delay and no warmup, the same race starts at the live edge and drops the earlier
5053	/// group, as before.
5054	#[tokio::test]
5055	async fn a_zero_reach_starts_at_a_live_edge_that_arrives_first() {
5056		tokio::time::pause();
5057		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5058		let mut consumer = reach_consumer(&mut track, Duration::ZERO, Duration::ZERO, Duration::ZERO);
5059
5060		write_group_after_gap(&mut track, &[ts(5_000_000)]);
5061		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5062			.await
5063			.expect("nothing to wait for")
5064			.unwrap()
5065			.unwrap();
5066		assert_eq!(frame.timestamp, ts(5_000_000));
5067
5068		write_group(&mut track, &[ts(4_000_000)]);
5069		let _track = track.finish().unwrap();
5070		assert!(
5071			read_all(&mut consumer).await.unwrap().is_empty(),
5072			"the earlier group is old"
5073		);
5074	}
5075
5076	/// The warmup reaches a live join further back, even one at the live edge, while an unstated
5077	/// min delay stays unstated: it reaches back from the oldest group already.
5078	#[test]
5079	fn the_warmup_widens_only_a_stated_min() {
5080		let warmup = Duration::from_millis(300);
5081		let unstated = Delay::default().with_min(None);
5082		assert_eq!(warmed(unstated, warmup).min, None);
5083		assert_eq!(warmed(unstated, Duration::ZERO).min, None);
5084		assert_eq!(warmed(unstated.with_min(Duration::ZERO), warmup).min, Some(warmup));
5085	}
5086
5087	/// The warmup reaches past the min delay for the start: the subscription widens the max by it,
5088	/// so the publisher serves the group covering the live edge less both.
5089	#[tokio::test(start_paused = true)]
5090	async fn the_warmup_reaches_further_back_for_the_start() {
5091		for (warmup, expected) in [
5092			(Duration::ZERO, vec![4_700_000, 5_000_000]),
5093			(Duration::from_millis(300), vec![4_400_000, 4_700_000, 5_000_000]),
5094		] {
5095			let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
5096			// Group 4 covers the min delay alone, but not the warmup too.
5097			append_timed(&mut copy.track, &[ts(4_400_000)]);
5098			append_timed(&mut copy.track, &[ts(4_700_000)]);
5099			append_timed(&mut copy.track, &[ts(5_000_000)]);
5100			let mut consumer =
5101				reach_reader(&copy, Duration::from_millis(200), Duration::from_millis(200), warmup).await;
5102			let _track = copy.track.finish().unwrap();
5103
5104			let frames = read_all(&mut consumer).await.unwrap();
5105			let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
5106			assert_eq!(micros, expected, "warmup {warmup:?}");
5107		}
5108	}
5109
5110	/// A hole is skipped at the max delay alone: the warmup does not widen it.
5111	#[tokio::test]
5112	async fn the_warmup_does_not_widen_the_skip() {
5113		tokio::time::pause();
5114		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5115		let mut consumer = reach_consumer(
5116			&mut track,
5117			Duration::from_millis(200),
5118			Duration::from_millis(200),
5119			Duration::from_millis(300),
5120		);
5121
5122		write_group(&mut track, &[ts(0)]);
5123		let frame = consumer.read_frame().await.unwrap().unwrap();
5124		assert_eq!(frame.timestamp, ts(0));
5125
5126		// Group 1 is missing, and group 2's content runs 250ms past where it starts: more than the
5127		// max delay, though less than the max delay plus the warmup.
5128		write_group_after_gap(&mut track, &[ts(100_000), ts(350_000)]);
5129		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5130			.await
5131			.expect("the hole is skipped at the max delay")
5132			.unwrap()
5133			.unwrap();
5134		assert_eq!(frame.timestamp, ts(100_000));
5135	}
5136
5137	/// The group covering the reach stays while the rest of its warmup arrives after the first read,
5138	/// though its successor starts past the max delay alone.
5139	#[tokio::test]
5140	async fn the_covering_group_is_kept_while_its_warmup_arrives_after_the_first_read() {
5141		tokio::time::pause();
5142		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
5143		let mut consumer = reach_consumer(&mut track, Duration::ZERO, Duration::ZERO, Duration::from_millis(80));
5144
5145		write_group_after_gap(&mut track, &[ts(5_000_000)]);
5146		// Group 4 covers the 4.92s target, and its first frame is read before the rest of it lands.
5147		let mut covering = Lazy::new(&track);
5148		let write = |group: &mut Lazy, micros| {
5149			let frame = Frame {
5150				timestamp: ts(micros),
5151				decode: None,
5152				payload: Bytes::from_static(&[0xDE, 0xAD]),
5153				keyframe: false,
5154				duration: None,
5155			};
5156			Wire::legacy(crate::container::Kind::Data)
5157				.write(&mut group.writer(), &[frame])
5158				.unwrap();
5159		};
5160		write(&mut covering, 4_900_000);
5161		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5162			.await
5163			.expect("group 4 covers the reach")
5164			.unwrap()
5165			.unwrap();
5166		assert_eq!(frame.timestamp, ts(4_900_000));
5167		assert!(
5168			kio::clock::timeout(Duration::from_millis(50), consumer.read())
5169				.await
5170				.is_err(),
5171			"the covering group's next frame is waited for"
5172		);
5173
5174		write(&mut covering, 4_950_000);
5175		covering.finish().unwrap();
5176		let _track = track.finish().unwrap();
5177		let micros: Vec<u128> = read_all(&mut consumer)
5178			.await
5179			.unwrap()
5180			.iter()
5181			.map(|f| f.timestamp.as_micros().unwrap())
5182			.collect();
5183		assert_eq!(micros, vec![4_950_000, 5_000_000], "the warmup is not skipped as stale");
5184	}
5185
5186	/// The start keeps the group covering the reach though its first frame trails the newest
5187	/// content by more than the max delay plus the warmup. `js/hang`'s
5188	/// `consumer.warmup.test.ts` pairs this case.
5189	#[tokio::test]
5190	async fn the_start_keeps_a_group_that_began_before_the_reach_but_covers_it() {
5191		tokio::time::pause();
5192		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5193		let mut consumer = reach_consumer(
5194			&mut track,
5195			Duration::from_millis(200),
5196			Duration::from_millis(200),
5197			Duration::from_millis(300),
5198		);
5199
5200		write_group_after_gap(&mut track, &[ts(5_000_000)]);
5201		// Group 4 begins 600ms before the newest content, past the 500ms reach, yet covers its 4.5s target.
5202		write_group(&mut track, &[ts(4_400_000), ts(4_600_000), ts(4_900_000)]);
5203		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5204			.await
5205			.expect("group 4 covers the reach")
5206			.unwrap()
5207			.unwrap();
5208		assert_eq!(frame.timestamp, ts(4_400_000));
5209	}
5210
5211	/// The max age clamps the max delay alone, not the subscription's max plus the warmup, so a max
5212	/// delay within the track's max age stays whole.
5213	#[tokio::test]
5214	async fn the_warmup_is_carved_before_the_max_age_clamp() {
5215		let mut info = hang::container::track_info(hang::catalog::PRIORITY.audio);
5216		info.max_age = Some(Duration::from_secs(1));
5217		let mut track = track_producer("test", info);
5218		let consumer = reach_consumer(
5219			&mut track,
5220			Duration::ZERO,
5221			Duration::from_secs(1),
5222			Duration::from_millis(300),
5223		);
5224		assert_eq!(consumer.max_delay, Duration::from_secs(1));
5225	}
5226
5227	/// A quiet copy whose publisher holds nothing earlier starts at once: the ordered reader knows
5228	/// no earlier group is owed, so nothing waits a reach for one.
5229	#[tokio::test(start_paused = true)]
5230	async fn a_quiet_track_starts_at_once_when_nothing_earlier_is_owed() {
5231		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
5232		append_timed(&mut copy.track, &[ts(5_000_000)]);
5233		let mut consumer = reach_reader(
5234			&copy,
5235			Duration::from_millis(200),
5236			Duration::from_millis(200),
5237			Duration::from_millis(300),
5238		)
5239		.await;
5240		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5241			.await
5242			.expect("nothing earlier is owed")
5243			.unwrap()
5244			.unwrap();
5245		assert_eq!(frame.timestamp, ts(5_000_000));
5246	}
5247
5248	/// Media a reach past where the newest group starts ends the wait without the wall clock.
5249	#[tokio::test]
5250	async fn the_start_needs_no_wait_once_a_group_covers_the_reach() {
5251		tokio::time::pause();
5252		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5253		let mut consumer = reach_consumer(
5254			&mut track,
5255			Duration::from_millis(500),
5256			Duration::from_millis(500),
5257			Duration::ZERO,
5258		);
5259
5260		write_group_after_gap(&mut track, &[ts(5_000_000), ts(5_500_000)]);
5261		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5262			.await
5263			.expect("the newest group covers the reach")
5264			.unwrap()
5265			.unwrap();
5266		assert_eq!(frame.timestamp, ts(5_000_000));
5267	}
5268
5269	/// A full max buffer can hold none of what the start waits for, so the wait ends at once.
5270	#[tokio::test]
5271	async fn the_start_wait_ends_once_the_max_buffer_is_full() {
5272		tokio::time::pause();
5273		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5274		let mut consumer = reach_consumer(
5275			&mut track,
5276			Duration::from_millis(500),
5277			Duration::from_millis(500),
5278			Duration::ZERO,
5279		);
5280		consumer.set_max_buffer(1);
5281
5282		write_group_after_gap(&mut track, &[ts(5_000_000), ts(5_100_000)]);
5283		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5284			.await
5285			.expect("the max buffer cannot hold an earlier group")
5286			.unwrap()
5287			.unwrap();
5288		assert_eq!(frame.timestamp, ts(5_000_000));
5289	}
5290
5291	/// A group below the subscriber's range never arrives, so the start does not wait for it.
5292	#[tokio::test]
5293	async fn the_start_stops_at_the_subscriber_range() {
5294		tokio::time::pause();
5295		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5296		let consumer_track = track
5297			.subscribe(
5298				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5299					moq_net::track::Start::Live {
5300						min: Some(Duration::from_millis(500)),
5301						max: Some(Duration::from_millis(500)),
5302					},
5303				)]),
5304			)
5305			.with_range(5..);
5306		let mut consumer = Playout::new(
5307			Delay {
5308				min: Some(Duration::from_millis(500)),
5309				max: Some(Duration::from_millis(500)),
5310			},
5311			Duration::ZERO,
5312		)
5313		.consumer(consumer_track, Wire::legacy(crate::container::Kind::Data));
5314		assert!(
5315			matches!(consumer.startup, Startup::Earliest),
5316			"a local range names no start, so the start still reaches back"
5317		);
5318
5319		write_group_after_gap(&mut track, &[ts(5_000_000)]);
5320		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5321			.await
5322			.expect("nothing below the range can arrive")
5323			.unwrap()
5324			.unwrap();
5325		assert_eq!(frame.timestamp, ts(5_000_000));
5326	}
5327
5328	/// A default min delay starts at a live edge that arrives first however large the max delay is:
5329	/// the max delay bounds lateness, not the start.
5330	#[tokio::test]
5331	async fn a_large_max_delay_alone_starts_at_once() {
5332		tokio::time::pause();
5333		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5334		let mut consumer = reach_consumer(&mut track, Duration::ZERO, Duration::from_secs(10), Duration::ZERO);
5335
5336		write_group_after_gap(&mut track, &[ts(5_000_000)]);
5337		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5338			.await
5339			.expect("nothing to wait for")
5340			.unwrap()
5341			.unwrap();
5342		assert_eq!(frame.timestamp, ts(5_000_000));
5343	}
5344
5345	/// A min delay past the max delay reaches back only the max delay, since the publisher serves
5346	/// nothing older.
5347	#[tokio::test(start_paused = true)]
5348	async fn a_min_delay_past_the_max_delay_reaches_the_max_delay() {
5349		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
5350		append_timed(&mut copy.track, &[ts(4_400_000)]);
5351		append_timed(&mut copy.track, &[ts(4_700_000)]);
5352		append_timed(&mut copy.track, &[ts(5_000_000)]);
5353		let mut consumer = reach_reader(
5354			&copy,
5355			Duration::from_secs(2),
5356			Duration::from_millis(200),
5357			Duration::ZERO,
5358		)
5359		.await;
5360		let _track = copy.track.finish().unwrap();
5361		let frames = read_all(&mut consumer).await.unwrap();
5362		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
5363		assert_eq!(micros, vec![4_700_000, 5_000_000], "group 3 is past the max delay");
5364	}
5365
5366	/// The subscription carries the min and max delay, each plus the warmup, so a live join
5367	/// reaches back far enough to warm the decoder before its first played frame.
5368	#[tokio::test]
5369	async fn the_subscription_carries_the_warmed_min_and_max_delay() {
5370		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5371		let consumer = reach_consumer(
5372			&mut track,
5373			Duration::from_secs(2),
5374			Duration::from_millis(200),
5375			Duration::from_millis(300),
5376		);
5377		let subscription = subscribed(&consumer).subscription();
5378		assert_eq!(
5379			subscription.ranges,
5380			[moq_net::track::Range::from(moq_net::track::Start::Live {
5381				min: Some(Duration::from_millis(2_300)),
5382				max: Some(Duration::from_millis(500)),
5383			})]
5384		);
5385		assert_eq!(consumer.max_delay, Duration::from_millis(200));
5386	}
5387
5388	/// A track subscribed without the warmup has its max widened by the playout, keeping the live
5389	/// join it resolved, and its consumer still starts the warmup further back.
5390	#[tokio::test]
5391	async fn the_playout_widens_a_narrow_subscription() {
5392		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5393		let delay = Delay {
5394			min: Some(Duration::from_millis(100)),
5395			max: Some(Duration::from_millis(200)),
5396		};
5397		let consumer_track = track.subscribe(
5398			delay.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL])),
5399		);
5400		let consumer = Playout::new(delay, Duration::from_millis(300))
5401			.consumer(consumer_track, Wire::legacy(crate::container::Kind::Data));
5402		let subscription = subscribed(&consumer).subscription();
5403		assert_eq!(
5404			subscription.ranges,
5405			[moq_net::track::Range::from(moq_net::track::Start::Live {
5406				min: Some(Duration::from_millis(100)),
5407				max: Some(Duration::from_millis(500)),
5408			})]
5409		);
5410		assert_eq!(consumer.max_delay, Duration::from_millis(200));
5411		assert_eq!(consumer.warmup, Duration::from_millis(300));
5412	}
5413
5414	/// A catalog warmup past the cap reaches back, and widens the subscription, by the cap alone.
5415	#[tokio::test]
5416	async fn the_playout_caps_a_huge_warmup() {
5417		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5418		let delay = Delay::default().with_max(Some(Duration::from_millis(200)));
5419		let playout = Playout::new(delay, Duration::from_secs(3600));
5420		let consumer = playout.consumer(
5421			track.subscribe(
5422				playout.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL])),
5423			),
5424			Wire::legacy(crate::container::Kind::Data),
5425		);
5426		assert_eq!(
5427			subscribed(&consumer).subscription().ranges,
5428			[moq_net::track::Range::from(moq_net::track::Start::Live {
5429				min: Some(Duration::from_millis(200) + DELAY_MAX),
5430				max: Some(Duration::from_millis(200) + DELAY_MAX),
5431			})]
5432		);
5433		assert_eq!(consumer.warmup, DELAY_MAX);
5434	}
5435
5436	/// An unlimited max delay keeps the subscription unlimited and skips nothing: a reader from a
5437	/// time start, which the min delay doesn't place, reads all of the history the copy holds, even
5438	/// past the min delay's reach.
5439	#[tokio::test(start_paused = true)]
5440	async fn an_unlimited_max_delay_reads_all_history() {
5441		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
5442		append_timed(&mut copy.track, &[ts(3_000_000)]);
5443		append_timed(&mut copy.track, &[ts(4_500_000)]);
5444		append_timed(&mut copy.track, &[ts(5_000_000)]);
5445		let playout = Playout::new(
5446			Delay {
5447				min: Some(Duration::from_millis(500)),
5448				max: None,
5449			},
5450			Duration::ZERO,
5451		);
5452		let from_zero = moq_net::track::Subscription::default()
5453			.with_ranges([moq_net::track::Range::from(moq_net::track::Start::Time(0))]);
5454		let subscriber = copy.subscribe_with(playout.subscription(from_zero)).await;
5455		let mut consumer = playout.consumer(subscriber, Wire::legacy(crate::container::Kind::Data));
5456		assert_eq!(
5457			subscribed(&consumer).subscription().ranges,
5458			[moq_net::track::Range::from(moq_net::track::Start::Time(0))],
5459			"a time start stays history, so nothing it reaches goes stale"
5460		);
5461		let _track = copy.track.finish().unwrap();
5462		let frames = read_all(&mut consumer).await.unwrap();
5463		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
5464		assert_eq!(micros, vec![3_000_000, 4_500_000, 5_000_000]);
5465	}
5466
5467	/// A subscription without a max delay reaches back for history, so it starts at once.
5468	#[tokio::test]
5469	async fn an_unbounded_subscription_starts_at_once() {
5470		tokio::time::pause();
5471		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5472		let consumer_track = track.subscribe(moq_net::track::Subscription::default());
5473		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
5474
5475		write_group_after_gap(&mut track, &[ts(5_000_000)]);
5476		let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame())
5477			.await
5478			.expect("an unbounded reach waits for nothing")
5479			.unwrap()
5480			.unwrap();
5481		assert_eq!(frame.timestamp, ts(5_000_000));
5482	}
5483
5484	// ---- Decode errors ----
5485
5486	/// A container that decodes each frame's payload as an 8-byte LE microsecond
5487	/// timestamp, but treats a `FAIL` payload as a malformed frame. Lets a test put a
5488	/// decodable frame first (so the consumer reads the group) and a decode failure after.
5489	struct FailingDecode;
5490
5491	impl ContainerTrait for FailingDecode {
5492		type Error = crate::Error;
5493
5494		fn write(&self, group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
5495			for frame in frames {
5496				group.write_frame(moq_net::Timestamp::ZERO, frame.payload.clone())?;
5497			}
5498			Ok(())
5499		}
5500
5501		fn decode(&self, frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
5502			use bytes::Buf;
5503
5504			let mut data = frame.payload;
5505			if data.as_ref() == b"FAIL" {
5506				return Err(crate::Error::UnknownFormat("malformed payload".into()));
5507			}
5508			Ok(vec![Frame {
5509				timestamp: ts(data.get_u64_le()),
5510				decode: None,
5511				payload: Bytes::new(),
5512				keyframe: false,
5513				duration: None,
5514			}])
5515		}
5516	}
5517
5518	/// A decode error on a cleanly-finished group must propagate to the caller, not be
5519	/// mistaken for a relay eviction and silently skipped. Eviction-skip only fires when
5520	/// the group's stream was actually aborted.
5521	#[tokio::test]
5522	async fn decode_error_propagates() {
5523		tokio::time::pause();
5524		let track = track_producer("test", timed());
5525		let consumer_track = track.subscribe(None);
5526		let mut consumer = Consumer::new(consumer_track, FailingDecode);
5527
5528		// A decodable frame first (so the consumer reads the group), then a malformed one.
5529		let mut group = Lazy::following(&track);
5530		group
5531			.write_frame(moq_net::Timestamp::ZERO, Bytes::from(0u64.to_le_bytes().to_vec()))
5532			.unwrap();
5533		group
5534			.write_frame(moq_net::Timestamp::ZERO, Bytes::from_static(b"FAIL"))
5535			.unwrap();
5536		group.finish().unwrap();
5537		let _track = track.finish().unwrap();
5538
5539		// The first frame decodes; the malformed second frame must surface as an error.
5540		let first = consumer.read_frame().await;
5541		assert!(matches!(first, Ok(Some(_))), "first frame should decode, got {first:?}");
5542
5543		let second = kio::clock::timeout(Duration::from_millis(200), consumer.read())
5544			.await
5545			.expect("consumer hung on a decode error");
5546		assert!(
5547			matches!(second, Err(crate::Error::UnknownFormat(_))),
5548			"decode error must propagate, got {second:?}"
5549		);
5550	}
5551
5552	/// Write one FailingDecode frame: a microsecond timestamp, or `None` for a malformed payload
5553	/// stamped at the group's latest. A malformed frame opening a group uses [`write_malformed`].
5554	fn write_failing(group: &mut Lazy, micros: Option<u64>) {
5555		let payload = match micros {
5556			Some(micros) => Bytes::from(micros.to_le_bytes().to_vec()),
5557			None => Bytes::from_static(b"FAIL"),
5558		};
5559		let stamp = match micros {
5560			Some(micros) => ts(micros),
5561			None => group
5562				.writer()
5563				.latest()
5564				.expect("a malformed frame opening a group says where"),
5565		};
5566		// A group's timestamps never decrease; the payload keeps the frame's own.
5567		let transport = match group.writer().latest() {
5568			Some(latest) if stamp < latest => latest,
5569			_ => stamp,
5570		};
5571		group.write_frame(transport, payload).unwrap();
5572	}
5573
5574	/// Open `group` with a malformed FailingDecode frame stamped at `micros`, which keys it.
5575	fn write_malformed(group: &mut Lazy, micros: u64) {
5576		group.write_frame(ts(micros), Bytes::from_static(b"FAIL")).unwrap();
5577	}
5578
5579	/// Read until something other than a frame, failing if the reader stalls.
5580	async fn read_past_frames(consumer: &mut Consumer<FailingDecode>) -> Result<Option<Read>, crate::Error> {
5581		loop {
5582			let read = kio::clock::timeout(Duration::from_millis(200), consumer.read())
5583				.await
5584				.expect("consumer hung");
5585			match read {
5586				Ok(Some(Read::Frame { .. })) => continue,
5587				other => return other,
5588			}
5589		}
5590	}
5591
5592	/// A malformed object found by the startup lookahead, at the head of the first group, ends the
5593	/// reader rather than being consumed and dropped.
5594	#[tokio::test]
5595	async fn a_decode_error_at_the_head_of_a_group_ends_the_reader() {
5596		tokio::time::pause();
5597		let track = track_producer("test", timed());
5598		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5599			moq_net::track::Start::Live {
5600				min: Some(Duration::from_secs(10)),
5601				max: Some(Duration::from_secs(10)),
5602			},
5603		)]);
5604		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode);
5605
5606		let mut group = Lazy::following(&track);
5607		write_malformed(&mut group, 1);
5608		write_failing(&mut group, Some(0));
5609		group.finish().unwrap();
5610		let _track = track.finish().unwrap();
5611
5612		let read = read_past_frames(&mut consumer).await;
5613		assert!(matches!(read, Err(crate::Error::UnknownFormat(_))), "{read:?}");
5614		// The reader stays ended rather than resuming past the malformed object.
5615		let read = consumer.read().await;
5616		assert!(matches!(read, Ok(None)), "{read:?}");
5617	}
5618
5619	/// The exporter path reads events directly, and it stays ended after an error too.
5620	#[tokio::test]
5621	async fn a_decode_error_ends_the_event_reader() {
5622		tokio::time::pause();
5623		let track = track_producer("test", timed());
5624		let mut consumer = Consumer::new(track.subscribe(None), FailingDecode);
5625
5626		let mut group = Lazy::following(&track);
5627		write_malformed(&mut group, 1);
5628		write_failing(&mut group, Some(0));
5629		group.finish().unwrap();
5630		let _track = track.finish().unwrap();
5631
5632		let event = kio::wait(|waiter| consumer.poll_event(waiter)).await;
5633		assert!(matches!(event, Err(crate::Error::UnknownFormat(_))));
5634		let event = kio::wait(|waiter| consumer.poll_event(waiter)).await;
5635		assert!(matches!(event, Ok(None)), "the event reader resumed after an error");
5636	}
5637
5638	/// An error releases the subscription and the groups it holds, so a reader kept after it pins
5639	/// neither the publisher's demand nor its cache.
5640	#[tokio::test]
5641	async fn an_error_releases_the_subscription_and_its_groups() {
5642		tokio::time::pause();
5643		let track = track_producer("test", timed());
5644		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5645			moq_net::track::Start::Live {
5646				min: Some(Duration::from_secs(10)),
5647				max: Some(Duration::from_secs(10)),
5648			},
5649		)]);
5650		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode);
5651
5652		let mut malformed = Lazy::following(&track);
5653		write_malformed(&mut malformed, 1);
5654		let malformed_demand = malformed.demand();
5655		let _malformed = malformed.finish().unwrap();
5656		let mut later = Lazy::following(&track);
5657		write_failing(&mut later, Some(10_000));
5658
5659		let read = read_past_frames(&mut consumer).await;
5660		assert!(matches!(read, Err(crate::Error::UnknownFormat(_))), "{read:?}");
5661		assert!(!track.demand().wanted(), "the ended reader still subscribes");
5662		assert!(!malformed_demand.wanted(), "the ended reader still holds its group");
5663		assert!(!later.demand().wanted(), "the ended reader still holds a later group");
5664	}
5665
5666	/// A malformed object mid-group, found while looking ahead past a blocked group, ends the
5667	/// reader at its place rather than reading as a shorter group.
5668	#[tokio::test]
5669	async fn a_decode_error_mid_group_found_by_lookahead_ends_the_reader() {
5670		tokio::time::pause();
5671		let track = track_producer("test", timed());
5672		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5673			moq_net::track::Start::Live {
5674				min: Some(Duration::from_secs(10)),
5675				max: Some(Duration::from_secs(10)),
5676			},
5677		)]);
5678		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode);
5679
5680		// The current group stays open, so the reader looks ahead into the next one.
5681		let mut slow = Lazy::following(&track);
5682		write_failing(&mut slow, Some(0));
5683		let mut group = Lazy::following(&track);
5684		write_failing(&mut group, Some(10_000));
5685		write_failing(&mut group, None);
5686		write_failing(&mut group, Some(20_000));
5687		group.finish().unwrap();
5688
5689		let first = consumer.read_frame().await.unwrap().unwrap();
5690		assert_eq!(first.timestamp, ts(0));
5691		// Lookahead finds the error while the reader waits on the open group, which comes first.
5692		assert!(
5693			kio::clock::timeout(Duration::from_millis(50), consumer.read())
5694				.await
5695				.is_err()
5696		);
5697
5698		slow.finish().unwrap();
5699		let frame = consumer.read_frame().await.unwrap().unwrap();
5700		assert_eq!(frame.timestamp, ts(10_000));
5701		let read = kio::clock::timeout(Duration::from_millis(50), consumer.read()).await;
5702		assert!(matches!(read, Ok(Err(crate::Error::UnknownFormat(_)))), "{read:?}");
5703		// The reader stays ended rather than resuming with the group's later frames.
5704		let read = kio::clock::timeout(Duration::from_millis(50), consumer.read()).await;
5705		assert!(matches!(read, Ok(Ok(None))), "{read:?}");
5706	}
5707
5708	/// A malformed head of a later group waits for the current group's frames: errors come in
5709	/// delivery order, however early the lookahead finds them.
5710	#[tokio::test]
5711	async fn a_decode_error_in_a_later_group_waits_for_current_frames() {
5712		tokio::time::pause();
5713		let track = track_producer("test", timed());
5714		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5715			moq_net::track::Start::Live {
5716				min: Some(Duration::from_secs(10)),
5717				max: Some(Duration::from_secs(10)),
5718			},
5719		)]);
5720		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode);
5721
5722		let mut current = Lazy::following(&track);
5723		write_failing(&mut current, Some(0));
5724		write_failing(&mut current, Some(10_000));
5725		write_failing(&mut current, Some(20_000));
5726		let first = consumer.read_frame().await.unwrap().unwrap();
5727		assert_eq!(first.timestamp, ts(0));
5728
5729		let mut later = Lazy::following(&track);
5730		write_malformed(&mut later, 1_000_001);
5731		later.finish().unwrap();
5732		for expected in [10_000, 20_000] {
5733			let frame = consumer.read_frame().await.unwrap().unwrap();
5734			assert_eq!(frame.timestamp, ts(expected));
5735		}
5736
5737		current.finish().unwrap();
5738		let read = read_past_frames(&mut consumer).await;
5739		assert!(matches!(read, Err(crate::Error::UnknownFormat(_))), "{read:?}");
5740	}
5741
5742	/// A later group's rewind does not mask an earlier group's decode error: the first in delivery
5743	/// order is the one returned.
5744	#[tokio::test]
5745	async fn a_decode_error_comes_before_a_later_rewind() {
5746		tokio::time::pause();
5747		let track = track_producer("test", timed());
5748		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5749			moq_net::track::Start::Live {
5750				min: Some(Duration::from_secs(10)),
5751				max: Some(Duration::from_secs(10)),
5752			},
5753		)]);
5754		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode);
5755
5756		let mut current = Lazy::following(&track);
5757		write_failing(&mut current, Some(100_000));
5758		let first = consumer.read_frame().await.unwrap().unwrap();
5759		assert_eq!(first.timestamp, ts(100_000));
5760
5761		let mut malformed = Lazy::following(&track);
5762		write_failing(&mut malformed, Some(110_000));
5763		malformed.write_frame(ts(110_000), Bytes::from_static(b"FAIL")).unwrap();
5764		malformed.finish().unwrap();
5765		// The transport only checks a group's first frame, so the rewind is its second.
5766		let mut rewound = Lazy::following(&track);
5767		write_failing(&mut rewound, Some(150_000));
5768		write_failing(&mut rewound, Some(50_000));
5769		rewound.finish().unwrap();
5770		// The reader looks ahead into both while it waits on the open group.
5771		assert!(
5772			kio::clock::timeout(Duration::from_millis(50), consumer.read())
5773				.await
5774				.is_err()
5775		);
5776
5777		current.finish().unwrap();
5778		let _track = track.finish().unwrap();
5779		let read = read_past_frames(&mut consumer).await;
5780		assert!(matches!(read, Err(crate::Error::UnknownFormat(_))), "{read:?}");
5781	}
5782
5783	/// A live reader discards the groups below the newest, and a malformed one it already read
5784	/// while finding the start still ends the reader.
5785	#[tokio::test]
5786	async fn a_startup_discard_returns_a_malformed_group() {
5787		tokio::time::pause();
5788		let track = track_producer("test", timed());
5789		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5790			moq_net::track::Start::Live {
5791				min: Some(Duration::from_secs(10)),
5792				max: Some(Duration::from_secs(10)),
5793			},
5794		)]);
5795		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode).live();
5796
5797		let mut old = Lazy::following(&track);
5798		write_malformed(&mut old, 1);
5799		old.finish().unwrap();
5800		let mut newest = Lazy::following(&track);
5801		write_failing(&mut newest, Some(10_000));
5802		newest.finish().unwrap();
5803		let _track = track.finish().unwrap();
5804
5805		let read = read_past_frames(&mut consumer).await;
5806		assert!(matches!(read, Err(crate::Error::UnknownFormat(_))), "{read:?}");
5807	}
5808
5809	/// An aborted later group holding a fault is not reaped ahead of its place: its error waits
5810	/// for the current group's frames, as a live group's does.
5811	#[tokio::test]
5812	async fn an_aborted_later_group_keeps_its_fault_in_delivery_order() {
5813		tokio::time::pause();
5814		let track = track_producer("test", timed());
5815		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5816			moq_net::track::Start::Live {
5817				min: Some(Duration::from_secs(10)),
5818				max: Some(Duration::from_secs(10)),
5819			},
5820		)]);
5821		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode);
5822
5823		let mut current = Lazy::following(&track);
5824		write_failing(&mut current, Some(0));
5825		let first = consumer.read_frame().await.unwrap().unwrap();
5826		assert_eq!(first.timestamp, ts(0));
5827
5828		let mut later = Lazy::following(&track);
5829		write_malformed(&mut later, 1_000_001);
5830		// The reader looks ahead into the later group while it waits on the open one.
5831		assert!(
5832			kio::clock::timeout(Duration::from_millis(50), consumer.read())
5833				.await
5834				.is_err()
5835		);
5836		later.abort(moq_net::Error::Cancel).unwrap();
5837
5838		write_failing(&mut current, Some(10_000));
5839		let frame = consumer.read_frame().await.unwrap().unwrap();
5840		assert_eq!(frame.timestamp, ts(10_000));
5841
5842		current.finish().unwrap();
5843		let _track = track.finish().unwrap();
5844		let read = read_past_frames(&mut consumer).await;
5845		assert!(matches!(read, Err(crate::Error::UnknownFormat(_))), "{read:?}");
5846	}
5847
5848	/// A malformed object read from the current group ends the reader even when the group's
5849	/// unread tail was reset afterwards: the reset is loss after it, not a reason to drop it.
5850	#[tokio::test]
5851	async fn a_decode_error_before_a_reset_tail_ends_the_reader() {
5852		tokio::time::pause();
5853		let track = track_producer("test", timed());
5854		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5855			moq_net::track::Start::Live {
5856				min: Some(Duration::from_secs(10)),
5857				max: Some(Duration::from_secs(10)),
5858			},
5859		)]);
5860		let mut consumer = Consumer::new(track.subscribe(subscription), FailingDecode);
5861
5862		let mut group = Lazy::following(&track);
5863		write_failing(&mut group, Some(0));
5864		write_failing(&mut group, None);
5865		let first = consumer.read_frame().await.unwrap().unwrap();
5866		assert_eq!(first.timestamp, ts(0));
5867
5868		group.abort(moq_net::Error::Cancel).unwrap();
5869		let _track = track.finish().unwrap();
5870		let read = kio::clock::timeout(Duration::from_millis(50), consumer.read()).await;
5871		assert!(matches!(read, Ok(Err(crate::Error::UnknownFormat(_)))), "{read:?}");
5872	}
5873
5874	/// The lookahead keeps a malformed object it already holds even when the group is evicted
5875	/// before it gets there: the eviction is loss behind that object, not a reason to drop it.
5876	#[test]
5877	fn the_lookahead_keeps_a_decode_error_before_an_evicted_tail() {
5878		let waiter = kio::Waiter::noop();
5879		let track = track_producer("test", timed());
5880		let mut group = Lazy::following(&track);
5881		write_failing(&mut group, Some(0));
5882		write_failing(&mut group, None);
5883		write_failing(&mut group, Some(10_000));
5884		let group = group.finish().unwrap();
5885
5886		// Finding the start buffers one frame; the read behind it already holds the rest.
5887		let mut buffer = GroupBuffer::<FailingDecode>::new(group.consume(), Memory::new(DEFAULT_MAX_BUFFER));
5888		assert_eq!(
5889			buffer.poll_min_timestamp(&waiter, &FailingDecode, false),
5890			Poll::Ready(Some(ts(0)))
5891		);
5892		group.abort(moq_net::Error::Old).unwrap();
5893
5894		let _ = buffer.look_all(&waiter, &FailingDecode);
5895		assert!(
5896			matches!(buffer.fault, Some(crate::Error::UnknownFormat(_))),
5897			"{:?}",
5898			buffer.fault
5899		);
5900	}
5901
5902	// ---- Frame Decoding ----
5903
5904	#[kio::test]
5905	async fn frame_payload_preserved() {
5906		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5907		let consumer_track =
5908			track.subscribe(
5909				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5910					moq_net::track::Start::Live {
5911						min: Some(Duration::from_millis(500)),
5912						max: Some(Duration::from_millis(500)),
5913					},
5914				)]),
5915			);
5916		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
5917
5918		let payload_bytes = vec![0x01, 0x02, 0x03, 0x04, 0x05];
5919		let mut group = Lazy::following(&track);
5920		Wire::legacy(crate::container::Kind::Data)
5921			.write(
5922				&mut group.writer(),
5923				&[Frame {
5924					timestamp: ts(0),
5925					decode: None,
5926					payload: Bytes::from(payload_bytes.clone()),
5927
5928					keyframe: false,
5929					duration: None,
5930				}],
5931			)
5932			.unwrap();
5933		group.finish().unwrap();
5934		let _track = track.finish().unwrap();
5935
5936		let frames = read_all(&mut consumer).await.unwrap();
5937		assert_eq!(frames.len(), 1);
5938
5939		use bytes::Buf;
5940		let mut received = Vec::new();
5941		let mut payload = frames[0].payload.clone();
5942		while payload.has_remaining() {
5943			received.push(payload.get_u8());
5944		}
5945		assert_eq!(received, payload_bytes);
5946	}
5947
5948	// ---- Regression ----
5949
5950	#[tokio::test]
5951	async fn no_infinite_loop_with_buffered_frames() {
5952		tokio::time::pause();
5953		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
5954		let consumer_track =
5955			track.subscribe(
5956				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5957					moq_net::track::Start::Live {
5958						min: Some(Duration::from_secs(10)),
5959						max: Some(Duration::from_secs(10)),
5960					},
5961				)]),
5962			);
5963		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
5964
5965		let mut group0 = Lazy::following(&track);
5966		Wire::legacy(crate::container::Kind::Data)
5967			.write(
5968				&mut group0.writer(),
5969				&[Frame {
5970					timestamp: ts(0),
5971					decode: None,
5972					payload: Bytes::from_static(&[0xDE, 0xAD]),
5973					keyframe: false,
5974					duration: None,
5975				}],
5976			)
5977			.unwrap();
5978
5979		write_group(&mut track, &[ts(100_000)]);
5980
5981		let finisher = tokio::spawn(async move {
5982			kio::clock::sleep(Duration::from_millis(20)).await;
5983			// Write group 2: recv_group fires, drops current buffer_until for group 1
5984			write_group(&mut track, &[ts(200_000)]);
5985			kio::clock::sleep(Duration::from_millis(20)).await;
5986			group0.finish().unwrap();
5987			let _track = track.finish().unwrap();
5988		});
5989
5990		let frames = kio::clock::timeout(Duration::from_secs(2), async {
5991			let mut frames = Vec::new();
5992			while let Some(frame) = consumer.read_frame().await.unwrap() {
5993				frames.push(frame);
5994			}
5995			frames
5996		})
5997		.await
5998		.expect("consumer hung - possible infinite loop regression");
5999
6000		assert_eq!(frames.len(), 3);
6001		finisher.await.expect("finisher task panicked");
6002	}
6003
6004	// ---- Edge Cases ----
6005
6006	#[kio::test]
6007	async fn large_timestamps() {
6008		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6009		let consumer_track =
6010			track.subscribe(
6011				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6012					moq_net::track::Start::Live {
6013						min: Some(Duration::from_secs(3700)),
6014						max: Some(Duration::from_secs(3700)),
6015					},
6016				)]),
6017			);
6018		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6019
6020		let one_hour = 3_600_000_000u64;
6021		write_group(&mut track, &[ts(one_hour)]);
6022		let _track = track.finish().unwrap();
6023
6024		let frames = read_all(&mut consumer).await.unwrap();
6025		assert_eq!(frames.len(), 1);
6026		assert_eq!(frames[0].timestamp, ts(one_hour));
6027		assert_eq!(frames[0].timestamp.as_micros().unwrap(), one_hour as u128);
6028	}
6029
6030	#[kio::test]
6031	async fn set_delay_changes_behavior() {
6032		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6033		let consumer_track =
6034			track.subscribe(
6035				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6036					moq_net::track::Start::Live {
6037						min: Some(Duration::from_secs(10)),
6038						max: Some(Duration::from_secs(10)),
6039					},
6040				)]),
6041			);
6042		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6043
6044		write_group(&mut track, &[ts(0)]);
6045		let _track = track.finish().unwrap();
6046
6047		let frame = consumer.read_frame().await.unwrap().unwrap();
6048		assert_eq!(frame.timestamp, ts(0));
6049
6050		consumer.set_delay(Delay {
6051			max: Some(Duration::from_millis(100)),
6052			..Delay::default()
6053		});
6054
6055		assert!(consumer.read().await.unwrap().is_none());
6056	}
6057
6058	#[tokio::test]
6059	async fn max_timestamp_tracks_through_bframes() {
6060		tokio::time::pause();
6061		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6062		let consumer_track =
6063			track.subscribe(
6064				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6065					moq_net::track::Start::Live {
6066						min: Some(Duration::from_millis(110)),
6067						max: Some(Duration::from_millis(110)),
6068					},
6069				)]),
6070			);
6071		// max delay must exceed (group1_max - group0_min) = 100ms - 0ms = 100ms
6072		// to avoid the age skip and test B-frame timestamp tracking.
6073		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6074
6075		let mut group0 = Lazy::following(&track);
6076		for &timestamp in &[ts(0), ts(66_000), ts(33_000)] {
6077			Wire::legacy(crate::container::Kind::Data)
6078				.write(
6079					&mut group0.writer(),
6080					&[Frame {
6081						timestamp,
6082						decode: None,
6083						payload: Bytes::from_static(&[0xDE, 0xAD]),
6084						keyframe: false,
6085						duration: None,
6086					}],
6087				)
6088				.unwrap();
6089		}
6090
6091		write_group(&mut track, &[ts(100_000)]);
6092		let _track = track.finish().unwrap();
6093
6094		let finisher = tokio::spawn(async move {
6095			kio::clock::sleep(Duration::from_millis(50)).await;
6096			group0.finish().unwrap();
6097		});
6098
6099		let frames = kio::clock::timeout(Duration::from_secs(2), async {
6100			let mut frames = Vec::new();
6101			while let Some(frame) = consumer.read_frame().await.unwrap() {
6102				frames.push(frame);
6103			}
6104			frames
6105		})
6106		.await
6107		.expect("consumer hung - max_timestamp regression");
6108
6109		assert_eq!(frames.len(), 4, "Expected all 4 frames, got {}", frames.len());
6110		assert_eq!(frames[0].timestamp, ts(0));
6111		assert_eq!(frames[1].timestamp, ts(66_000));
6112		assert_eq!(frames[2].timestamp, ts(33_000));
6113		assert_eq!(frames[3].timestamp, ts(100_000));
6114		finisher.await.expect("finisher task panicked");
6115	}
6116
6117	// ---- Startup Behavior ----
6118
6119	#[tokio::test]
6120	async fn startup_selects_earliest_group() {
6121		tokio::time::pause();
6122		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6123		let consumer_track =
6124			track.subscribe(
6125				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6126					moq_net::track::Start::Live {
6127						min: Some(Duration::from_millis(100)),
6128						max: Some(Duration::from_millis(100)),
6129					},
6130				)]),
6131			);
6132		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6133
6134		write_group_after_gap(&mut track, &[ts(0)]);
6135		write_group_after_gap(&mut track, &[ts(150_000)]);
6136
6137		let mut group7 = Lazy::new(&track);
6138		Wire::legacy(crate::container::Kind::Data)
6139			.write(
6140				&mut group7.writer(),
6141				&[Frame {
6142					timestamp: ts(300_000),
6143					decode: None,
6144					payload: Bytes::from_static(&[0xDE, 0xAD]),
6145					keyframe: false,
6146					duration: None,
6147				}],
6148			)
6149			.unwrap();
6150
6151		let finisher = tokio::spawn(async move {
6152			kio::clock::sleep(Duration::from_millis(50)).await;
6153			Wire::legacy(crate::container::Kind::Data)
6154				.write(
6155					&mut group7.writer(),
6156					&[Frame {
6157						timestamp: ts(400_000),
6158						decode: None,
6159						payload: Bytes::from_static(&[0xBE, 0xEF]),
6160						keyframe: false,
6161						duration: None,
6162					}],
6163				)
6164				.unwrap();
6165			group7.finish().unwrap();
6166			let _track = track.finish().unwrap();
6167		});
6168
6169		let _frames = kio::clock::timeout(Duration::from_secs(2), async {
6170			let mut frames = Vec::new();
6171			while let Some(frame) = consumer.read_frame().await.unwrap() {
6172				frames.push(frame);
6173			}
6174			frames
6175		})
6176		.await
6177		.expect("should not hang");
6178
6179		finisher.await.unwrap();
6180	}
6181
6182	/// An arrived group with no frames yet is settled only by its own FIN, abort, or the
6183	/// age budget, never by the track finishing: the track boundary ends new groups, not
6184	/// the frames still flowing on open ones. Here the budget expires it.
6185	#[tokio::test]
6186	async fn startup_skips_groups_without_data() {
6187		tokio::time::pause();
6188		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6189		let consumer_track =
6190			track.subscribe(
6191				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6192					moq_net::track::Start::Live {
6193						min: Some(Duration::from_millis(500)),
6194						max: Some(Duration::from_millis(500)),
6195					},
6196				)]),
6197			);
6198		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6199
6200		let _group5 = in_flight(&track, ts(150_000));
6201		write_group_after_gap(&mut track, &[ts(210_000)]);
6202
6203		// Group 5 is open and within budget: its first frame may still arrive, so wait.
6204		assert!(
6205			kio::clock::timeout(Duration::from_millis(50), consumer.read())
6206				.await
6207				.is_err(),
6208			"an open group still receiving its first frame must be waited for"
6209		);
6210
6211		// Group 9 pushes the newest content a full budget past what group 5 could still
6212		// present (bounded by group 7's start), expiring it. Exactly a budget, so group 7's
6213		// first frame is not past it and the start stays there.
6214		write_group_after_gap(&mut track, &[ts(710_000)]);
6215		let _track = track.finish().unwrap();
6216
6217		let frames = read_all(&mut consumer).await.unwrap();
6218		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
6219		assert_eq!(micros, vec![210_000, 710_000], "the expired group is skipped");
6220	}
6221
6222	/// Track completion is not group completion: a group already open when the track
6223	/// finishes can still receive frames, so it must not be skipped as if it were a
6224	/// missing sequence. Its late frames are delivered when they land within budget.
6225	#[tokio::test]
6226	async fn finished_track_waits_for_an_open_head_group() {
6227		tokio::time::pause();
6228		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6229		let consumer_track =
6230			track.subscribe(
6231				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6232					moq_net::track::Start::Live {
6233						min: Some(Duration::from_millis(500)),
6234						max: Some(Duration::from_millis(500)),
6235					},
6236				)]),
6237			);
6238		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6239
6240		// Group 0's first frame is in flight and loses the race; the track boundary arrives
6241		// before it.
6242		let (mut head, rest) = in_flight(&track, ts(0));
6243		write_group(&mut track, &[ts(100_000)]);
6244		let _track = track.finish().unwrap();
6245
6246		assert!(
6247			kio::clock::timeout(Duration::from_millis(50), consumer.read())
6248				.await
6249				.is_err(),
6250			"the open head group is within budget and must be waited for"
6251		);
6252
6253		// Its frames land moments later, well within the 500ms budget.
6254		head.write(rest).unwrap();
6255		head.finish().unwrap().finish().unwrap();
6256
6257		let frames = read_all(&mut consumer).await.unwrap();
6258		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
6259		assert_eq!(micros, vec![0, 100_000], "the open group's late frames are delivered");
6260	}
6261
6262	/// A gap between two ranges is never read, so the reader walks over it at once rather
6263	/// than waiting a budget, or forever on an open track, for groups it never gets.
6264	#[tokio::test]
6265	async fn an_excluded_gap_between_ranges_does_not_stall() {
6266		tokio::time::pause();
6267		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6268		let subscription = moq_net::track::Subscription::default().with_ranges([
6269			moq_net::track::Range {
6270				start: moq_net::track::Start::Time(0),
6271				end: Some(0),
6272				..Default::default()
6273			},
6274			moq_net::track::Range {
6275				start: moq_net::track::Start::Time(1_000_000),
6276				end: Some(1_000_000),
6277				..Default::default()
6278			},
6279		]);
6280		let mut consumer = Consumer::new(
6281			track.subscribe(subscription),
6282			Wire::legacy(crate::container::Kind::Data),
6283		);
6284		for sequence in [0, 5, 10] {
6285			write_group(&mut track, &[ts(sequence * 100_000)]);
6286		}
6287
6288		let mut micros = Vec::new();
6289		for _ in 0..2 {
6290			let frame = kio::clock::timeout(Duration::from_millis(200), consumer.read_frame())
6291				.await
6292				.expect("the open track still delivers the later range")
6293				.unwrap()
6294				.expect("a frame");
6295			micros.push(frame.timestamp.as_micros().unwrap());
6296		}
6297		assert_eq!(micros, vec![0, 1_000_000]);
6298	}
6299
6300	/// A live join names its floor once resolved: delivery starts at the group containing the
6301	/// live edge minus its lag, rather than at whichever group arrives first.
6302	#[tokio::test]
6303	async fn startup_at_a_live_join() {
6304		tokio::time::pause();
6305		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6306		for sequence in 5..=9 {
6307			write_group(&mut track, &[ts(sequence * 100_000)]);
6308		}
6309		let subscription = Delay::default()
6310			.with_min(Duration::from_millis(200))
6311			.with_max(Duration::from_secs(10))
6312			.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]));
6313		let consumer_track = track.subscribe(subscription);
6314		assert_eq!(consumer_track.floor(), Some(700_000));
6315		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6316		let _track = track.finish().unwrap();
6317
6318		let frames = read_all(&mut consumer).await.unwrap();
6319		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
6320		assert_eq!(micros, vec![700_000, 800_000, 900_000]);
6321	}
6322
6323	/// The reader starts where the publisher resolved the join, though the newest group lands first.
6324	#[tokio::test(start_paused = true)]
6325	async fn startup_at_the_publishers_start_over_a_newer_first_arrival() {
6326		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
6327		for sequence in [7, 8, 9, 10] {
6328			append_timed(&mut copy.track, &[ts(sequence * 100_000)]);
6329		}
6330		let subscriber = copy
6331			.subscribe_with(
6332				Delay::default()
6333					.with_min(Duration::from_millis(200))
6334					.with_max(Duration::from_secs(10))
6335					.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL])),
6336			)
6337			.await;
6338		let mut consumer = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
6339		let _track = copy.track.finish().unwrap();
6340
6341		assert_eq!(items(&mut consumer).await, ["800000", "900000", "1000000"]);
6342	}
6343
6344	/// A live join takes the start the publisher resolved for it: the publisher starts at a
6345	/// newest group whose first frame is still in flight, which this copy does not hold yet, so
6346	/// the reader waits for no group below it.
6347	#[tokio::test(start_paused = true)]
6348	async fn a_waiting_live_join_takes_the_publishers_resolved_start() {
6349		let mut copy = Received::with_info(hang::container::track_info(hang::catalog::PRIORITY.video)).await;
6350		for sequence in 0..5 {
6351			write_group(&mut copy.track, &[ts(sequence * 100_000)]);
6352		}
6353		skip_to(&copy.track, ts(500_000));
6354		let (mut newest, rest) = in_flight(&copy.track, ts(500_000));
6355		let subscriber = copy
6356			.subscribe_with(
6357				Delay::default()
6358					.with_min(Duration::ZERO)
6359					.with_max(Duration::from_secs(10))
6360					.subscription(moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL])),
6361			)
6362			.await;
6363		let mut consumer = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
6364
6365		newest.write(rest).unwrap();
6366		newest.finish().unwrap().finish().unwrap();
6367		let _track = copy.track.finish().unwrap();
6368		assert_eq!(items(&mut consumer).await, ["500000"]);
6369	}
6370
6371	#[kio::test]
6372	async fn startup_single_group_mid_stream() {
6373		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6374		let consumer_track =
6375			track.subscribe(
6376				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6377					moq_net::track::Start::Live {
6378						min: Some(Duration::from_millis(500)),
6379						max: Some(Duration::from_millis(500)),
6380					},
6381				)]),
6382			);
6383		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6384
6385		write_group_after_gap(&mut track, &[ts(3_000_000)]);
6386		let _track = track.finish().unwrap();
6387
6388		let frames = read_all(&mut consumer).await.unwrap();
6389		assert_eq!(frames.len(), 1);
6390	}
6391
6392	/// An unfloored mid-stream join adopts the publisher's served start instead of
6393	/// waiting for a gap below it to expire: on a quiet track that gap never would,
6394	/// since nothing newer arrives to age it out.
6395	#[tokio::test]
6396	async fn startup_mid_stream_live_track_starts_at_the_served_group() {
6397		tokio::time::pause();
6398		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6399		let consumer_track =
6400			track.subscribe(
6401				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6402					moq_net::track::Start::Live {
6403						min: Some(Duration::from_millis(500)),
6404						max: Some(Duration::from_millis(500)),
6405					},
6406				)]),
6407			);
6408		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6409
6410		// The track is far along and stays live (never finished); only the current
6411		// group is served, and nothing else arrives.
6412		write_group_after_gap(&mut track, &[ts(3_000_000)]);
6413
6414		let frame = kio::clock::timeout(Duration::from_millis(200), consumer.read_frame())
6415			.await
6416			.expect("an unfloored join must not wait out a gap below the served start")
6417			.unwrap()
6418			.expect("track still live");
6419		assert_eq!(frame.timestamp, ts(3_000_000));
6420	}
6421
6422	#[tokio::test]
6423	async fn multiple_sequential_latency_skips() {
6424		tokio::time::pause();
6425		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6426		let consumer_track =
6427			track.subscribe(
6428				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6429					moq_net::track::Start::Live {
6430						min: Some(Duration::from_millis(50)),
6431						max: Some(Duration::from_millis(50)),
6432					},
6433				)]),
6434			);
6435		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6436
6437		let mut group0 = Lazy::following(&track);
6438		Wire::legacy(crate::container::Kind::Data)
6439			.write(
6440				&mut group0.writer(),
6441				&[Frame {
6442					timestamp: ts(0),
6443					decode: None,
6444					payload: Bytes::from_static(&[0xAA]),
6445
6446					keyframe: false,
6447					duration: None,
6448				}],
6449			)
6450			.unwrap();
6451
6452		write_group(&mut track, &[ts(100_000)]);
6453		write_group(&mut track, &[ts(200_000)]);
6454		write_group(&mut track, &[ts(300_000)]);
6455		let _track = track.finish().unwrap();
6456
6457		let finisher = tokio::spawn(async move {
6458			kio::clock::sleep(Duration::from_millis(20)).await;
6459			group0.finish().unwrap();
6460		});
6461
6462		let frames = read_all(&mut consumer).await.unwrap();
6463		assert!(!frames.is_empty());
6464		finisher.await.unwrap();
6465	}
6466
6467	#[tokio::test]
6468	async fn latency_skip_boundary_exact() {
6469		tokio::time::pause();
6470		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6471		let consumer_track =
6472			track.subscribe(
6473				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6474					moq_net::track::Start::Live {
6475						min: Some(Duration::from_millis(100)),
6476						max: Some(Duration::from_millis(100)),
6477					},
6478				)]),
6479			);
6480		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6481
6482		let mut group0 = Lazy::following(&track);
6483		Wire::legacy(crate::container::Kind::Data)
6484			.write(
6485				&mut group0.writer(),
6486				&[Frame {
6487					timestamp: ts(0),
6488					decode: None,
6489					payload: Bytes::from_static(&[0xAA]),
6490
6491					keyframe: false,
6492					duration: None,
6493				}],
6494			)
6495			.unwrap();
6496
6497		write_group(&mut track, &[ts(100_000)]);
6498		let _track = track.finish().unwrap();
6499
6500		let finisher = tokio::spawn(async move {
6501			kio::clock::sleep(Duration::from_millis(20)).await;
6502			group0.finish().unwrap();
6503		});
6504
6505		let frames = read_all(&mut consumer).await.unwrap();
6506		assert!(!frames.is_empty());
6507		finisher.await.unwrap();
6508	}
6509
6510	/// Regression: a single stalled group with one newer group should trigger
6511	/// a delay skip when the timestamp difference exceeds the max delay.
6512	/// Previously, the span was computed across newer groups only (zero for one
6513	/// group), so the skip never fired.
6514	#[tokio::test]
6515	async fn single_newer_group_triggers_skip() {
6516		tokio::time::pause();
6517		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6518		let consumer_track = track.subscribe(None);
6519		let mut consumer = container_max_delay_only(consumer_track, Duration::from_millis(100));
6520
6521		// Group 0: stalled at ts=0, NOT finished
6522		let mut group0 = Lazy::following(&track);
6523		Wire::legacy(crate::container::Kind::Data)
6524			.write(
6525				&mut group0.writer(),
6526				&[Frame {
6527					timestamp: ts(0),
6528					decode: None,
6529					payload: Bytes::from_static(&[0xDE, 0xAD]),
6530					keyframe: false,
6531					duration: None,
6532				}],
6533			)
6534			.unwrap();
6535
6536		// Read before group 1 lands, so the skip comes after the start.
6537		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(0));
6538
6539		// Group 1: finished, 200ms ahead (well beyond the 100ms max delay)
6540		write_group(&mut track, &[ts(200_000)]);
6541		let _track = track.finish().unwrap();
6542
6543		let finisher = tokio::spawn(async move {
6544			kio::clock::sleep(Duration::from_millis(50)).await;
6545			group0.finish().unwrap();
6546		});
6547
6548		let frames = read_all(&mut consumer).await.unwrap();
6549		assert_eq!(frames.len(), 1, "Expected group 1's frame after group 0's");
6550		finisher.await.unwrap();
6551	}
6552
6553	/// Regression: when the current group is fully consumed and the next sequence
6554	/// is missing (gap), the consumer should skip to the next available group
6555	/// once the track is fully received, rather than hanging forever.
6556	#[tokio::test]
6557	async fn single_missing_sequence_near_eof_skips() {
6558		tokio::time::pause();
6559		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6560		let consumer_track = track.subscribe(None);
6561		let mut consumer = container_max_delay_only(consumer_track, Duration::from_millis(100));
6562
6563		// Group 0: finished normally, its first frame read before group 2 lands.
6564		write_group(&mut track, &[ts(0), ts(20_000)]);
6565		assert_eq!(consumer.read_frame().await.unwrap().unwrap().timestamp, ts(0));
6566		// Group 2: finished (group 1 is missing - sequence gap)
6567		write_group_after_gap(&mut track, &[ts(200_000)]);
6568		let _track = track.finish().unwrap();
6569
6570		let frames = read_all(&mut consumer).await.unwrap();
6571		assert_eq!(frames.len(), 2, "Expected group 0's second frame + group 2 (1 frame)");
6572	}
6573
6574	#[kio::test]
6575	async fn group_error_skips_to_next() {
6576		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6577		let consumer_track =
6578			track.subscribe(
6579				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6580					moq_net::track::Start::Live {
6581						min: Some(Duration::from_millis(500)),
6582						max: Some(Duration::from_millis(500)),
6583					},
6584				)]),
6585			);
6586		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6587
6588		// Group 0 aborts before its first frame lands.
6589		let (head, _) = in_flight(&track, ts(0));
6590		head.abort(moq_net::Error::Cancel).unwrap();
6591
6592		write_group(&mut track, &[ts(30_000)]);
6593		let _track = track.finish().unwrap();
6594
6595		let frames = read_all(&mut consumer).await.unwrap();
6596		assert_eq!(frames.len(), 1);
6597	}
6598
6599	/// A finished group aborted afterwards (idle past the cache pool's expiry window)
6600	/// keeps serving the frames it still holds: an abort only matters where a frame is
6601	/// missing, so a reader that stopped short of the end drains the rest and moves on
6602	/// to the next buffered group instead of ending the track.
6603	#[kio::test]
6604	async fn finished_group_aborted_mid_read_drains_then_continues() {
6605		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6606		let consumer_track =
6607			track.subscribe(
6608				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6609					moq_net::track::Start::Live {
6610						min: Some(Duration::from_millis(500)),
6611						max: Some(Duration::from_millis(500)),
6612					},
6613				)]),
6614			);
6615		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6616
6617		let mut group0 = Lazy::following(&track);
6618		for timestamp in [ts(0), ts(10_000)] {
6619			let frame = Frame {
6620				timestamp,
6621				decode: None,
6622				payload: Bytes::from_static(&[0xDE, 0xAD]),
6623				keyframe: false,
6624				duration: None,
6625			};
6626			Wire::legacy(crate::container::Kind::Data)
6627				.write(&mut group0.writer(), &[frame])
6628				.unwrap();
6629		}
6630		let group0 = group0.finish().unwrap();
6631		write_group(&mut track, &[ts(30_000)]);
6632		let _track = track.finish().unwrap();
6633
6634		// Take the first frame only, leaving the second unread.
6635		let first = consumer.read_frame().await.unwrap().unwrap();
6636		assert_eq!(first.timestamp, ts(0));
6637
6638		// Expiry aborts the finished group while the reader is still inside it.
6639		group0.abort(moq_net::Error::Old).unwrap();
6640
6641		let rest = read_all(&mut consumer).await.unwrap();
6642		assert_eq!(rest.len(), 2, "expected the held frame then group 1, got {rest:?}");
6643		assert_eq!(rest[0].timestamp, ts(10_000));
6644		assert_eq!(rest[1].timestamp, ts(30_000));
6645	}
6646
6647	/// A live group its upstream gave up as too large is aborted. A reader whose current
6648	/// group died that way skips forward; the gap is not a decode error.
6649	#[kio::test]
6650	async fn oversized_group_skips_to_next() {
6651		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6652		let consumer_track =
6653			track.subscribe(
6654				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6655					moq_net::track::Start::Live {
6656						min: Some(Duration::from_millis(500)),
6657						max: Some(Duration::from_millis(500)),
6658					},
6659				)]),
6660			);
6661		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6662
6663		let mut group0 = Lazy::following(&track);
6664		let first = Frame {
6665			timestamp: ts(0),
6666			decode: None,
6667			payload: Bytes::from(vec![0xDEu8; 1024]),
6668			keyframe: false,
6669			duration: None,
6670		};
6671		Wire::legacy(crate::container::Kind::Data)
6672			.write(&mut group0.writer(), &[first])
6673			.unwrap();
6674		group0.abort(moq_net::Error::GroupTooLarge).unwrap();
6675
6676		write_group(&mut track, &[ts(30_000)]);
6677		let _track = track.finish().unwrap();
6678
6679		let frames = read_all(&mut consumer).await.unwrap();
6680		assert_eq!(frames.len(), 1, "expected group 1 only, got {} frames", frames.len());
6681		assert_eq!(frames[0].timestamp, ts(30_000));
6682	}
6683
6684	#[tokio::test]
6685	async fn track_finishes_while_reading() {
6686		tokio::time::pause();
6687		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6688		let consumer_track =
6689			track.subscribe(
6690				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6691					moq_net::track::Start::Live {
6692						min: Some(Duration::from_millis(500)),
6693						max: Some(Duration::from_millis(500)),
6694					},
6695				)]),
6696			);
6697		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6698
6699		write_group(&mut track, &[ts(0)]);
6700
6701		let finisher = tokio::spawn(async move {
6702			kio::clock::sleep(Duration::from_millis(20)).await;
6703			write_group(&mut track, &[ts(30_000)]);
6704			kio::clock::sleep(Duration::from_millis(20)).await;
6705			let _track = track.finish().unwrap();
6706		});
6707
6708		let frames = kio::clock::timeout(Duration::from_secs(2), async {
6709			let mut frames = Vec::new();
6710			while let Some(frame) = consumer.read_frame().await.unwrap() {
6711				frames.push(frame);
6712			}
6713			frames
6714		})
6715		.await
6716		.expect("consumer should not hang");
6717
6718		assert_eq!(frames.len(), 2);
6719		finisher.await.unwrap();
6720	}
6721
6722	// ---- VideoConfig Container ----
6723
6724	#[tokio::test]
6725	async fn video_container_legacy() {
6726		tokio::time::pause();
6727
6728		let track = track_producer("video", hang::container::track_info(hang::catalog::PRIORITY.video));
6729		let consumer_track =
6730			track.subscribe(
6731				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6732					moq_net::track::Start::Live {
6733						min: Some(Duration::from_millis(500)),
6734						max: Some(Duration::from_millis(500)),
6735					},
6736				)]),
6737			);
6738		let mut consumer = Consumer::new(consumer_track, Wire::legacy(crate::container::Kind::Data));
6739
6740		// Write frames using Wire::legacy(crate::container::Kind::Data) encoding
6741		let mut group = Lazy::following(&track);
6742		for i in 0..3u64 {
6743			let frame = Frame {
6744				timestamp: ts(i * 33_333),
6745				decode: None,
6746				payload: Bytes::from_static(&[0xDE, 0xAD]),
6747				keyframe: false,
6748				duration: None,
6749			};
6750			Wire::legacy(crate::container::Kind::Data)
6751				.write(&mut group.writer(), &[frame])
6752				.unwrap();
6753		}
6754		group.finish().unwrap();
6755		let _track = track.finish().unwrap();
6756
6757		let mut frames = Vec::new();
6758		while let Some(frame) = consumer.read_frame().await.unwrap() {
6759			frames.push(frame);
6760		}
6761
6762		assert_eq!(frames.len(), 3);
6763		assert_eq!(frames[0].timestamp, ts(0));
6764		assert!(frames[0].keyframe);
6765		assert_eq!(frames[1].timestamp, ts(33_333));
6766		assert!(!frames[1].keyframe);
6767		assert_eq!(frames[2].timestamp, ts(66_666));
6768		assert!(!frames[2].keyframe);
6769	}
6770
6771	// ---- Duration Skipping ----
6772
6773	/// A stalled group whose frame covers up to the next group's start is skipped
6774	/// immediately, even with a max delay budget far larger than the gap. Without
6775	/// duration support the consumer would block on the unfinished group forever.
6776	#[tokio::test]
6777	async fn duration_skip_advances_to_next_group() {
6778		tokio::time::pause();
6779		// DurationWire is a test-only container that doesn't stamp moq_net frame
6780		// timestamps; leave the track untimed so model-layer validation matches.
6781		let track = track_producer("test", timed());
6782		let consumer_track =
6783			track.subscribe(
6784				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6785					moq_net::track::Start::Live {
6786						min: Some(Duration::from_secs(10)),
6787						max: Some(Duration::from_secs(10)),
6788					},
6789				)]),
6790			);
6791		// The max delay dwarfs the gap, so only duration coverage can trigger the skip.
6792		let mut consumer = Consumer::new(consumer_track, DurationWire);
6793
6794		// Group 0: one frame at ts=0 lasting 33ms, never finished.
6795		let mut group0 = Lazy::following(&track);
6796		write_duration_frame(&mut group0, ts(0), ts(33_000));
6797
6798		// Group 1: finished, starts exactly where group 0's frame ends.
6799		let mut group1 = Lazy::following(&track);
6800		write_duration_frame(&mut group1, ts(33_000), ts(33_000));
6801		group1.finish().unwrap();
6802
6803		let _track = track.finish().unwrap();
6804
6805		let frames = kio::clock::timeout(Duration::from_secs(2), async { continuous_frames(&mut consumer).await })
6806			.await
6807			.expect("consumer hung - duration skip regression");
6808
6809		assert_eq!(frames.len(), 2);
6810		assert_eq!(frames[0].timestamp, ts(0));
6811		assert_eq!(frames[1].timestamp, ts(33_000));
6812
6813		// group0 is intentionally never finished.
6814		drop(group0);
6815	}
6816
6817	#[kio::test]
6818	async fn a_nonsequential_contiguous_jump_has_no_gap() {
6819		let track = track_producer("test", timed());
6820		let mut consumer = Consumer::new(
6821			track.subscribe(
6822				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6823					moq_net::track::Start::Live {
6824						min: Some(Duration::from_secs(10)),
6825						max: Some(Duration::from_secs(10)),
6826					},
6827				)]),
6828			),
6829			DurationWire,
6830		);
6831		let mut group0 = Lazy::new(&track);
6832		write_duration_frame(&mut group0, ts(0), ts(33_000));
6833		group0.finish().unwrap();
6834		let mut group1 = Lazy::new(&track);
6835		write_duration_frame(&mut group1, ts(33_000), ts(33_000));
6836		group1.finish().unwrap();
6837		let _track = track.finish().unwrap();
6838		let frames = continuous_frames(&mut consumer).await;
6839		assert_eq!(frames.len(), 2);
6840	}
6841
6842	/// When the current group's frame ends before the next group begins, there is
6843	/// still a gap to cover, so we don't skip early: a late-arriving frame on the
6844	/// slow group is delivered rather than dropped.
6845	#[tokio::test]
6846	async fn duration_below_gap_does_not_skip() {
6847		tokio::time::pause();
6848		// DurationWire is untimed at the moq_net frame layer.
6849		let track = track_producer("test", timed());
6850		let consumer_track =
6851			track.subscribe(
6852				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6853					moq_net::track::Start::Live {
6854						min: Some(Duration::from_secs(10)),
6855						max: Some(Duration::from_secs(10)),
6856					},
6857				)]),
6858			);
6859		let mut consumer = Consumer::new(consumer_track, DurationWire);
6860
6861		// Group 0: frame at ts=0 lasting only 10ms, far short of group 1 at 33ms.
6862		let mut group0 = Lazy::following(&track);
6863		write_duration_frame(&mut group0, ts(0), ts(10_000));
6864
6865		// Group 1: finished at 33ms.
6866		let mut group1 = Lazy::following(&track);
6867		write_duration_frame(&mut group1, ts(33_000), ts(33_000));
6868		group1.finish().unwrap();
6869		let _track = track.finish().unwrap();
6870
6871		// A second frame lands on group 0 and finishes it after the consumer has
6872		// had a chance to (incorrectly) skip.
6873		let finisher = tokio::spawn(async move {
6874			kio::clock::sleep(Duration::from_millis(20)).await;
6875			write_duration_frame(&mut group0, ts(20_000), ts(10_000));
6876			group0.finish().unwrap();
6877		});
6878
6879		let frames = kio::clock::timeout(Duration::from_secs(2), async {
6880			let mut frames = Vec::new();
6881			while let Some(frame) = consumer.read_frame().await.unwrap() {
6882				frames.push(frame);
6883			}
6884			frames
6885		})
6886		.await
6887		.expect("consumer hung");
6888
6889		// The slow group's late frame survives because nothing covered the gap.
6890		assert_eq!(frames.len(), 3);
6891		assert_eq!(frames[0].timestamp, ts(0));
6892		assert_eq!(frames[1].timestamp, ts(20_000));
6893		assert_eq!(frames[2].timestamp, ts(33_000));
6894		finisher.await.unwrap();
6895	}
6896	#[kio::test]
6897	async fn live_duration_marker_follows_an_immediately_delivered_frame() {
6898		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6899		let mut consumer = Consumer::new(track.subscribe(None), Wire::legacy(crate::container::Kind::Video));
6900		let mut group = Lazy::appending(&track);
6901		Wire::legacy(crate::container::Kind::Video)
6902			.write(
6903				&mut group.writer(),
6904				&[Frame {
6905					timestamp: ts(0),
6906					decode: None,
6907					payload: Bytes::from_static(b"video"),
6908					keyframe: true,
6909					duration: None,
6910				}],
6911			)
6912			.unwrap();
6913		let frame = kio::clock::timeout(Duration::from_secs(1), consumer.read_frame())
6914			.await
6915			.unwrap()
6916			.unwrap()
6917			.unwrap();
6918		assert_eq!(frame.timestamp, ts(0));
6919		write_marker(&mut group, ts(15_000));
6920		let event = kio::wait(|waiter| consumer.poll_event(waiter)).await.unwrap();
6921		assert!(matches!(event, Some(Event::FrameEnd { end, opens: false }) if end == ts(15_000)));
6922	}
6923
6924	// ---- Max buffer ----
6925
6926	/// Write one unfinished Legacy data frame into a new group, with nothing between it and the
6927	/// newest group, leaving it open.
6928	fn open_group(track: &mut moq_net::track::Producer, timestamp: Timestamp) -> moq_net::group::Producer {
6929		skip_to(track, timestamp);
6930		let mut group = Lazy::new(track);
6931		Wire::legacy(crate::container::Kind::Data)
6932			.write(
6933				&mut group.writer(),
6934				&[Frame {
6935					timestamp,
6936					decode: None,
6937					payload: Bytes::from_static(&[0xDE, 0xAD]),
6938					keyframe: false,
6939					duration: None,
6940				}],
6941			)
6942			.unwrap();
6943		group.into_inner()
6944	}
6945
6946	/// Read every item, checking after each that the consumer holds about the max buffer at most:
6947	/// past it, one more wire frame and the groups the cursor still needs.
6948	async fn read_bounded(consumer: &mut Consumer<Wire>, max_buffer: usize) -> Vec<Read> {
6949		let slack = 4 * std::mem::size_of::<GroupBuffer<Wire>>() + 1024;
6950		let mut reads = Vec::new();
6951		loop {
6952			let read = kio::clock::timeout(Duration::from_secs(5), consumer.read())
6953				.await
6954				.expect("consumer hung")
6955				.unwrap();
6956			let used = consumer.buffered_bytes();
6957			assert!(
6958				used <= max_buffer + slack,
6959				"holding {used} bytes past a {max_buffer} byte max buffer"
6960			);
6961			match read {
6962				Some(read) => reads.push(read),
6963				None => return reads,
6964			}
6965		}
6966	}
6967
6968	fn timestamps(reads: &[Read]) -> Vec<Timestamp> {
6969		reads
6970			.iter()
6971			.filter_map(|read| match read {
6972				Read::Frame { frame, .. } => Some(frame.timestamp),
6973				_ => None,
6974			})
6975			.collect()
6976	}
6977
6978	/// Frames packed into one timestamp have no span, so the age budget never skips the stalled group
6979	/// they queue behind. Read ahead as the newest group, they fill the max buffer instead, which skips
6980	/// it, and the rest stays unread in the transport's cache until the reader gets to it.
6981	#[tokio::test]
6982	async fn frames_sharing_a_timestamp_stay_within_the_max_buffer() {
6983		tokio::time::pause();
6984		const MAX_BUFFER: usize = 4096;
6985		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
6986		let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_secs(5));
6987		consumer.set_max_buffer(MAX_BUFFER);
6988
6989		let _stalled = open_group(&mut track, ts(0));
6990		write_group(&mut track, &vec![ts(10_000); 2_000]);
6991		let _track = track.finish().unwrap();
6992
6993		let reads = read_bounded(&mut consumer, MAX_BUFFER).await;
6994		let timestamps = timestamps(&reads);
6995		assert_eq!(timestamps.len(), 1 + 2_000);
6996		assert_eq!(timestamps.first(), Some(&ts(0)));
6997		assert_eq!(timestamps.last(), Some(&ts(10_000)));
6998		// The stalled group's tail is lost.
6999		assert!(matches!(reads[1], Read::Gap { .. }), "{:?}", reads[1]);
7000	}
7001
7002	/// A publisher opening many groups fills the max buffer with their overhead and first frames, so
7003	/// the rest wait in the transport's cache: playback still reaches the live edge, and what arrives
7004	/// below the cursor once there is room is dropped as old.
7005	#[tokio::test]
7006	async fn many_groups_stay_within_the_max_buffer() {
7007		tokio::time::pause();
7008		const MAX_BUFFER: usize = 8192;
7009		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7010		let subscriber =
7011			track.subscribe(
7012				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
7013					moq_net::track::Start::Live {
7014						min: Some(Duration::from_millis(100)),
7015						max: Some(Duration::from_millis(100)),
7016					},
7017				)]),
7018			);
7019		let mut consumer = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Data));
7020		consumer.set_max_buffer(MAX_BUFFER);
7021
7022		let _stalled = open_group(&mut track, ts(0));
7023		for g in 1..=500u64 {
7024			write_group(&mut track, &[ts(g * 1_000)]);
7025		}
7026		let _track = track.finish().unwrap();
7027
7028		let reads = read_bounded(&mut consumer, MAX_BUFFER).await;
7029		let timestamps = timestamps(&reads);
7030		assert_eq!(timestamps.last(), Some(&ts(500_000)));
7031		assert!(timestamps.len() < 501, "nothing was skipped: {}", timestamps.len());
7032	}
7033
7034	/// A successor holding only endpoint markers stops buffering at the max buffer like any other
7035	/// lookahead, rather than reading past it in search of a media frame.
7036	#[kio::test]
7037	async fn an_endpoint_only_successor_stays_within_the_max_buffer() {
7038		const MAX_BUFFER: usize = 1024;
7039		let waiter = kio::Waiter::noop();
7040		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7041		let subscriber =
7042			track.subscribe(
7043				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
7044					moq_net::track::Start::Live {
7045						min: Some(Duration::from_secs(30)),
7046						max: Some(Duration::from_secs(30)),
7047					},
7048				)]),
7049			);
7050		let mut consumer = Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Video));
7051		consumer.set_max_buffer(MAX_BUFFER);
7052
7053		let _stalled = open_group(&mut track, ts(0));
7054		let mut markers = Lazy::following(&track);
7055		for _ in 0..2_000 {
7056			write_marker(&mut markers, ts(10_000));
7057		}
7058		Wire::legacy(crate::container::Kind::Data)
7059			.write(
7060				&mut markers.writer(),
7061				&[Frame {
7062					timestamp: ts(20_000),
7063					decode: None,
7064					payload: Bytes::from_static(b"video"),
7065					keyframe: false,
7066					duration: None,
7067				}],
7068			)
7069			.unwrap();
7070		markers.finish().unwrap();
7071
7072		// The markers fill the max buffer behind the stalled group, which moves the cursor on to them,
7073		// and the media past them still plays.
7074		let slack = 2 * std::mem::size_of::<GroupBuffer<Wire>>() + MARKER_COST;
7075		let mut frames = Vec::new();
7076		loop {
7077			let read = consumer.poll_read(&waiter);
7078			let used = consumer.buffered_bytes();
7079			assert!(
7080				used <= MAX_BUFFER + slack,
7081				"holding {used} bytes past a {MAX_BUFFER} byte max buffer"
7082			);
7083			match read {
7084				Poll::Ready(Ok(Some(Read::Frame { frame, .. }))) => frames.push(frame.timestamp),
7085				Poll::Ready(Ok(Some(_))) => continue,
7086				Poll::Pending => break,
7087				other => panic!("unexpected read: {other:?}"),
7088			}
7089		}
7090		assert_eq!(frames, vec![ts(0), ts(20_000)]);
7091	}
7092
7093	/// A decoded payload is a view of its wire frame, which stays allocated while the view is held, so a
7094	/// view that leaves out most of its wire frame is copied out: what holds the frame after the reader,
7095	/// such as an export's jitter buffer, retains only its payload. Here each is a 1 byte payload behind
7096	/// a large LOC property block.
7097	#[kio::test]
7098	async fn a_small_view_of_a_large_wire_frame_is_copied_out() {
7099		const PADDING: usize = 60_000;
7100
7101		// A QUIC varint, which is all LOC's framing needs.
7102		fn varint(buf: &mut Vec<u8>, value: usize) {
7103			match value {
7104				0..64 => buf.push(value as u8),
7105				64..16_384 => buf.extend_from_slice(&(value as u16 | 0x4000).to_be_bytes()),
7106				_ => buf.extend_from_slice(&(value as u32 | 0x8000_0000).to_be_bytes()),
7107			}
7108		}
7109
7110		let waiter = kio::Waiter::noop();
7111		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7112		let subscriber =
7113			track.subscribe(
7114				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
7115					moq_net::track::Start::Live {
7116						min: Some(Duration::from_secs(30)),
7117						max: Some(Duration::from_secs(30)),
7118					},
7119				)]),
7120			);
7121		let mut consumer = Consumer::new(subscriber, Wire::loc(crate::container::Kind::Data));
7122
7123		let mut padded = Lazy::following(&track);
7124		for i in 0..8 {
7125			let timestamp = i * 1_000;
7126			// An unknown video-config property (0x0d) padding the frame, then the timestamp (0x10).
7127			let mut props = Vec::new();
7128			varint(&mut props, 0x0d);
7129			varint(&mut props, PADDING);
7130			props.resize(props.len() + PADDING, 0);
7131			varint(&mut props, 0x10 - 0x0d);
7132			varint(&mut props, timestamp);
7133			let mut wire = Vec::new();
7134			varint(&mut wire, props.len());
7135			wire.extend_from_slice(&props);
7136			wire.push(0xAD);
7137			padded.write_frame(ts(timestamp as u64), wire).unwrap();
7138		}
7139		padded.finish().unwrap();
7140
7141		let mut reads = Vec::new();
7142		while let Poll::Ready(read) = consumer.poll_read(&waiter) {
7143			match read.unwrap() {
7144				Some(Read::Frame { frame, .. }) => {
7145					assert_eq!(frame.payload[..], [0xAD]);
7146					// The group still holds its wire frames, so a view of one would share it.
7147					assert!(frame.payload.is_unique(), "the payload still shares its wire frame");
7148					reads.push(frame.timestamp);
7149				}
7150				Some(Read::End { .. }) | None => break,
7151				other => panic!("unexpected read: {other:?}"),
7152			}
7153		}
7154		assert_eq!(reads, (0..8).map(|i| ts(i * 1_000)).collect::<Vec<_>>());
7155	}
7156
7157	/// A stalled successor does not hide a readable group behind it once group overhead alone fills the
7158	/// max buffer: the cursor moves on group by group until one has something to read.
7159	#[kio::test]
7160	async fn a_stalled_successor_does_not_hide_a_readable_group() {
7161		let waiter = kio::Waiter::noop();
7162		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7163		let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_secs(5));
7164		consumer.set_max_buffer(2 * std::mem::size_of::<GroupBuffer<Wire>>());
7165
7166		let _stalled = open_group(&mut track, ts(0));
7167		let _empty = Lazy::following(&track);
7168		write_group(&mut track, &[ts(20_000)]);
7169
7170		let mut reads = Vec::new();
7171		while let Poll::Ready(read) = consumer.poll_read(&waiter) {
7172			match read.unwrap() {
7173				Some(Read::Frame { frame, .. }) => reads.push(Some(frame.timestamp)),
7174				Some(Read::Gap { .. }) => reads.push(None),
7175				other => panic!("unexpected read: {other:?}"),
7176			}
7177		}
7178		assert_eq!(reads, vec![Some(ts(0)), None, Some(ts(20_000))]);
7179	}
7180
7181	/// Groups 0 and 1 open behind a cursor that read group 0's frame, and group 2's large frame that
7182	/// fills the max buffer once read ahead. Returns groups 0 and 1.
7183	fn fill_behind_a_stalled_group(
7184		track: &mut moq_net::track::Producer,
7185		consumer: &mut Consumer<Wire>,
7186		waiter: &kio::Waiter,
7187	) -> (moq_net::group::Producer, Lazy) {
7188		let stalled = open_group(track, ts(0));
7189		assert!(matches!(
7190			consumer.poll_read(waiter),
7191			Poll::Ready(Ok(Some(Read::Frame { group: 0, .. })))
7192		));
7193		// Group 1's start stays open for it, and nothing else comes between them.
7194		track.skip_groups(1..10_000);
7195		track.skip_groups(10_001..20_000);
7196		let between = Lazy::new(track);
7197		let mut later = Lazy::new(track);
7198		Wire::legacy(crate::container::Kind::Data)
7199			.write(
7200				&mut later.writer(),
7201				&[Frame {
7202					timestamp: ts(20_000),
7203					decode: None,
7204					payload: Bytes::from(vec![0; 4096]),
7205					keyframe: false,
7206					duration: None,
7207				}],
7208			)
7209			.unwrap();
7210		later.finish().unwrap();
7211		(stalled, between)
7212	}
7213
7214	// A max buffer that holds three groups' overhead with room to spare, short of group 2's large frame.
7215	fn pressured_data_consumer(track: &mut moq_net::track::Producer) -> Consumer<Wire> {
7216		let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_secs(5));
7217		consumer.set_max_buffer(1024 + 3 * std::mem::size_of::<GroupBuffer<Wire>>());
7218		consumer
7219	}
7220
7221	/// A malformed frame landing in the group the cursor moves on to under pressure fails the reader
7222	/// rather than leaving it waiting on the group.
7223	#[kio::test]
7224	async fn a_malformed_frame_in_a_group_moved_to_under_pressure_fails_the_reader() {
7225		let waiter = kio::Waiter::noop();
7226		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7227		let mut consumer = pressured_data_consumer(&mut track);
7228		let (_stalled, mut between) = fill_behind_a_stalled_group(&mut track, &mut consumer, &waiter);
7229
7230		between.write_frame(ts(10_000), Bytes::from_static(&[0x80])).unwrap();
7231		let read = loop {
7232			match consumer.poll_read(&waiter) {
7233				Poll::Ready(Ok(Some(Read::Gap { .. }))) => continue,
7234				other => break other,
7235			}
7236		};
7237		assert!(matches!(read, Poll::Ready(Err(_))), "{read:?}");
7238	}
7239
7240	/// A data marker group that finished before the cursor moved on to it under pressure still reads
7241	/// its end before the group after it.
7242	#[kio::test]
7243	async fn a_finished_marker_group_moved_to_under_pressure_reads_its_end() {
7244		let waiter = kio::Waiter::noop();
7245		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7246		let mut consumer = pressured_data_consumer(&mut track);
7247		let (_stalled, mut between) = fill_behind_a_stalled_group(&mut track, &mut consumer, &waiter);
7248
7249		between.write_frame(ts(10_000), Bytes::new()).unwrap();
7250		between.finish().unwrap();
7251		let mut reads = Vec::new();
7252		while let Poll::Ready(read) = consumer.poll_read(&waiter) {
7253			reads.push(match read.unwrap() {
7254				Some(Read::Frame { group, frame }) => format!("frame {group} {}", frame.timestamp.as_micros().unwrap()),
7255				Some(Read::Gap { .. }) => "gap".to_string(),
7256				Some(Read::End { group, .. }) => format!("end {group}"),
7257				None => break,
7258			});
7259		}
7260		assert_eq!(reads, ["gap", "end 10000", "frame 20000 20000"]);
7261	}
7262
7263	/// A hole's budget runs from when the group past it landed, not from when the reader pulled it:
7264	/// a full max buffer holds pulls back, so a hole that already expired is passed at once.
7265	#[tokio::test(start_paused = true)]
7266	async fn a_hole_behind_a_full_max_buffer_expires_from_its_successors_arrival() {
7267		let max_delay = Duration::from_millis(500);
7268		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7269		let mut consumer = container_max_delay_only(track.subscribe(None), max_delay);
7270		consumer.set_max_buffer(4096);
7271		for sequence in 0..2u64 {
7272			let mut group = Lazy::following(&track);
7273			Wire::legacy(crate::container::Kind::Data)
7274				.write(
7275					&mut group.writer(),
7276					&[Frame {
7277						timestamp: ts(sequence * 10_000),
7278						decode: None,
7279						payload: Bytes::from(vec![0; 4096]),
7280						keyframe: false,
7281						duration: None,
7282					}],
7283				)
7284				.unwrap();
7285			group.finish().unwrap();
7286		}
7287		let mut marker = Lazy::new(&track);
7288		marker.write_frame(ts(20_000), Bytes::new()).unwrap();
7289		marker.finish().unwrap();
7290
7291		// The reader gets to the track only after the hole before the marker has expired.
7292		tokio::time::advance(2 * max_delay).await;
7293		let waiter = kio::Waiter::noop();
7294		let mut reads = Vec::new();
7295		while let Poll::Ready(read) = consumer.poll_read(&waiter) {
7296			reads.push(match read.unwrap() {
7297				Some(Read::Frame { group, frame }) => format!("frame {group} {}", frame.timestamp.as_micros().unwrap()),
7298				Some(Read::Gap { .. }) => "gap".to_string(),
7299				Some(Read::End { group, .. }) => format!("end {group}"),
7300				None => break,
7301			});
7302		}
7303		assert_eq!(reads, ["frame 0 0", "frame 10000 10000", "gap", "end 20000"]);
7304	}
7305
7306	/// A joining reader drains the backlog in sequence order, not arrival order, so a group can land
7307	/// before the one below it is pulled: the hole before that lower group is late from the earlier one.
7308	#[tokio::test(start_paused = true)]
7309	async fn a_hole_in_a_drained_backlog_is_late_from_the_earliest_arrival_past_it() {
7310		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7311		let marker = |track: &mut moq_net::track::Producer, sequence: u64| {
7312			let mut group = Lazy::new(track);
7313			group.write_frame(ts(sequence * 10_000), Bytes::new()).unwrap();
7314			group.finish().unwrap();
7315		};
7316		write_group(&mut track, &[ts(0)]);
7317		marker(&mut track, 5);
7318		tokio::time::advance(Duration::from_millis(900)).await;
7319		marker(&mut track, 3);
7320		tokio::time::advance(Duration::from_millis(100)).await;
7321
7322		let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_millis(500));
7323		let waiter = kio::Waiter::noop();
7324		let mut reads = Vec::new();
7325		while let Poll::Ready(read) = consumer.poll_read(&waiter) {
7326			reads.push(match read.unwrap() {
7327				Some(Read::Frame { group, .. }) => format!("frame {group}"),
7328				Some(Read::Gap { .. }) => "gap".to_string(),
7329				Some(Read::End { group, .. }) => format!("end {group}"),
7330				None => break,
7331			});
7332		}
7333		// The group at 50 ms landed a second ago, so the holes before it and the one at 30 ms both
7334		// expired.
7335		assert_eq!(reads, ["frame 0", "gap", "end 30000", "gap", "end 50000"]);
7336	}
7337
7338	/// No cap is too small to read through: the cursor's group and one successor are always pulled, so
7339	/// a stalled group can be moved past even when one group's overhead fills the max buffer.
7340	#[kio::test]
7341	async fn a_zero_max_buffer_still_moves_past_a_stalled_group() {
7342		let waiter = kio::Waiter::noop();
7343		let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
7344		let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_secs(5));
7345		consumer.set_max_buffer(0);
7346
7347		let _stalled = open_group(&mut track, ts(0));
7348		write_group(&mut track, &[ts(10_000)]);
7349
7350		let mut reads = Vec::new();
7351		while let Poll::Ready(read) = consumer.poll_read(&waiter) {
7352			match read.unwrap() {
7353				Some(Read::Frame { frame, .. }) => reads.push(Some(frame.timestamp)),
7354				Some(Read::Gap { .. }) => reads.push(None),
7355				other => panic!("unexpected read: {other:?}"),
7356			}
7357		}
7358		assert_eq!(reads, vec![Some(ts(0)), None, Some(ts(10_000))]);
7359	}
7360
7361	/// A paused payload reader must not retain metadata for cache entries that were evicted.
7362	#[kio::test]
7363	async fn receiving_under_backpressure_releases_aborted_group_handles() {
7364		let track = track_producer("backpressured", timed());
7365		let mut consumer = Consumer::new(
7366			track.subscribe(moq_net::track::Subscription::default()),
7367			Wire::legacy(crate::container::Kind::Data),
7368		);
7369		for sequence in 0..256 {
7370			let mut group = Lazy::new(&track);
7371			Wire::legacy(crate::container::Kind::Data)
7372				.write(
7373					&mut group.writer(),
7374					&[Frame {
7375						timestamp: ts(sequence * 20_000),
7376						decode: None,
7377						payload: Bytes::from_static(b"payload"),
7378						keyframe: true,
7379						duration: None,
7380					}],
7381				)
7382				.unwrap();
7383			assert!(consumer.poll_received(&kio::Waiter::noop()).is_pending());
7384			group.abort(moq_net::Error::Evicted).unwrap();
7385		}
7386		let _ = consumer.poll_received(&kio::Waiter::noop());
7387		assert!(
7388			consumer.pending.len() <= 2,
7389			"doubling compaction bounds metadata by twice the cursor's one retained gap, retained {} aborted group handles",
7390			consumer.pending.len()
7391		);
7392	}
7393
7394	/// A finished track may still have bytes in flight on a group already received.
7395	#[kio::test]
7396	async fn received_input_waits_for_group_fin_without_consuming_payload() {
7397		let mut track = track_producer("finite", timed());
7398		let mut consumer = Consumer::new(
7399			track.subscribe(
7400				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
7401					moq_net::track::Start::Live {
7402						min: Some(Duration::from_millis(500)),
7403						max: Some(Duration::from_millis(500)),
7404					},
7405				)]),
7406			),
7407			Wire::legacy(crate::container::Kind::Data),
7408		);
7409		write_group(&mut track, &[ts(0)]);
7410		let mut group = Lazy::following(&track);
7411		Wire::legacy(crate::container::Kind::Data)
7412			.write(
7413				&mut group.writer(),
7414				&[Frame {
7415					timestamp: ts(20_000),
7416					decode: None,
7417					payload: Bytes::from_static(b"tail"),
7418					keyframe: true,
7419					duration: None,
7420				}],
7421			)
7422			.unwrap();
7423		let _track = track.finish().unwrap();
7424		assert!(consumer.poll_received(&kio::Waiter::noop()).is_pending());
7425		assert!(
7426			consumer.pending.iter().all(|group| group.is_empty()),
7427			"receipt must not decode payload"
7428		);
7429		group.finish().unwrap();
7430		assert!(consumer.poll_received(&kio::Waiter::noop()).is_ready());
7431		let mut frames = Vec::new();
7432		while let Some(frame) = consumer.read_frame().await.unwrap() {
7433			frames.push(frame.timestamp);
7434		}
7435		assert_eq!(frames, [ts(0), ts(20_000)]);
7436	}
7437}