Skip to main content

moq_net/model/
track.rs

1//! A track is a collection of semi-reliable and semi-ordered streams, split into a [Producer] and [Subscriber] handle.
2//!
3//! A [Producer] creates streams with a sequence number and priority.
4//! The sequence number is used to determine the order of streams, while the priority is used to determine which stream to transmit first.
5//! This may seem counter-intuitive, but is designed for live streaming where the newest streams may be higher priority.
6//! A cloned [Producer] can be used to create streams in parallel, but will error if a duplicate sequence number is used.
7//!
8//! A [Subscriber] may not receive all streams in order or at all.
9//! These streams are meant to be transmitted over congested networks and the key to MoQ Transport is to not block on them.
10//! Streams will be cached for a potentially limited duration added to the unreliable nature.
11//! A [Consumer] is a cheap, cloneable handle; subscribing it multiple times fans the same
12//! cached streams out to each independent [Subscriber].
13//!
14//! The track is closed with [Error] when all writers or readers are dropped.
15
16use crate::{Error, Result, Timescale, Timestamp, coding};
17use crate::{broadcast, cache, frame, group, stats};
18
19use super::{Datagram, Requests};
20
21pub use super::subscription::Subscription;
22
23use std::{
24	collections::{HashMap, VecDeque},
25	sync::Arc,
26	sync::OnceLock,
27	sync::atomic::{AtomicBool, Ordering},
28	task::{Poll, ready},
29	time::Duration,
30};
31
32/// Default [`Info::latency_max`] age when the publisher doesn't set one.
33pub const DEFAULT_LATENCY_MAX: Duration = Duration::from_secs(5);
34
35/// How long a datagram stays in the per-track buffer before it is dropped.
36///
37/// Datagrams are a best-effort send buffer, not a replay cache (unlike groups): only the last
38/// few tens of milliseconds are kept, so a consumer that stalls loses stale datagrams instead of
39/// replaying them. Sized like a typical send buffer for real-time audio/video.
40const MAX_DATAGRAM_AGE: Duration = Duration::from_millis(50);
41
42/// Slack before the eviction order is rebuilt, so a track holding just a few groups
43/// doesn't rebuild on every write.
44const EVICT_SLACK: usize = 64;
45
46/// How many live eviction candidates one debt payment examines (Redis-style
47/// bounded sampling): enough to step over a few protected (recently accessed)
48/// groups, small enough that a write never scans a long queue.
49const EVICT_SCAN: usize = 4;
50
51/// Publisher-side properties of a track.
52///
53/// These are fixed by the publisher when the track is created and don't change
54/// while the track is alive. A subscriber learns them via
55/// [`broadcast::Consumer::track`](broadcast::Consumer::track),
56/// which returns the publisher's [`Info`] once the subscription is accepted.
57//
58// Deliberately not `Copy`, even though it's now a plain value: adding `Copy` turns
59// every existing `info.clone()` in a consumer's code into a `clippy::clone_on_copy`
60// error under `-D warnings`.
61#[derive(Clone, Debug)]
62#[non_exhaustive]
63pub struct Info {
64	/// Units per second for per-frame timestamps on this track.
65	///
66	/// Every track is timed; this defaults to [`Timescale::MILLI`]. On Lite05+ it is
67	/// reported in TRACK_INFO and the publisher zigzag-delta encodes per-frame
68	/// timestamps at this scale on the wire. Protocols whose wire can't carry it
69	/// (pre-Lite05 moq-lite, IETF moq-transport) fall back to local monotonic milliseconds.
70	pub timescale: Timescale,
71	/// The maximum age of a non-latest group before the publisher evicts it (the
72	/// newest group is always retained). A subscriber's
73	/// [`Subscription::latency_max`] window is clamped to this, since a group can't be
74	/// waited for longer than it's kept around. Reported in TRACK_INFO so
75	/// relays re-serve with the same window. Defaults to [`DEFAULT_LATENCY_MAX`].
76	///
77	/// This is the `Publisher Max Latency` on the wire, the publisher-side half of
78	/// the same budget [`Subscription::latency_max`] sets for a subscriber.
79	pub latency_max: Duration,
80	/// The publisher's priority for this track, used only to break ties between
81	/// subscriptions of equal subscriber priority. Reported in TRACK_INFO (Lite05+).
82	pub priority: u8,
83	/// Whether groups are prioritized in sequence order. Groups may always arrive
84	/// out-of-order (or not at all) over the network. Used only to break ties,
85	/// reported in TRACK_INFO (Lite05+), and defaults to `false` (newest-first).
86	pub ordered: bool,
87}
88
89impl Default for Info {
90	fn default() -> Self {
91		Self {
92			timescale: Timescale::default(),
93			latency_max: DEFAULT_LATENCY_MAX,
94			priority: 0,
95			ordered: false,
96		}
97	}
98}
99
100impl Info {
101	/// Set the per-frame timestamp scale, returning `self` for chaining.
102	///
103	/// Defaults to [`Timescale::MILLI`]. On Lite05+ this scale is reported in TRACK_INFO
104	/// and used to encode per-frame timestamps on the wire.
105	pub fn with_timescale(mut self, timescale: Timescale) -> Self {
106		self.timescale = timescale;
107		self
108	}
109
110	/// Set the maximum age of a non-latest group before eviction, returning `self` for chaining.
111	pub fn with_latency_max(mut self, latency_max: Duration) -> Self {
112		self.latency_max = latency_max;
113		self
114	}
115
116	/// Set the publisher's tie-break priority, returning `self` for chaining.
117	pub fn with_priority(mut self, priority: u8) -> Self {
118		self.priority = priority;
119		self
120	}
121
122	/// Set whether groups are prioritized in sequence order, returning `self` for
123	/// chaining. Groups may always arrive out-of-order (or not at all) over the
124	/// network. Defaults to `false`.
125	pub fn with_ordered(mut self, ordered: bool) -> Self {
126		self.ordered = ordered;
127		self
128	}
129}
130
131#[derive(Default)]
132pub(crate) struct TrackState {
133	// The publisher's properties, once known; always Some for Subscriber/Producer.
134	// Copied by value into each group it creates.
135	info: Option<Info>,
136
137	// The broadcast this track belongs to. Supplies the cache pool its groups charge
138	// into and the `cache_duration` ceiling clamping `Info::latency_max`.
139	broadcast: Arc<broadcast::Info>,
140
141	// This track's account against the shared cache pool, shared with every group it
142	// creates (see `cache::Track`). Holds the gross-write counter `charge_debt` drains,
143	// and the weak link a frame write follows back here to settle its own debt.
144	cache: Arc<cache::Track>,
145
146	// Cached groups by sequence: the single source of truth for what is cached. The
147	// two orderings below hold bare sequences and validate against this map, so a
148	// removed or replaced group turns their entries into discarded-on-pop hints.
149	lookup: HashMap<u64, Slot>,
150
151	// Publisher-produced groups in arrival order as (sequence, stamp), walked by
152	// subscriptions; an entry only resolves while its stamp matches the slot's.
153	// Fetched backfill (`insert_group_request`) is deliberately absent: it is
154	// served by sequence, never replayed to arrival-order subscribers.
155	arrival: VecDeque<(u64, u32)>,
156
157	// Eviction order under memory pressure as (sequence, stamp): every cached
158	// group except the protected latest. `pay_debt` scans victims from the front;
159	// groups accessed more recently than the pool-wide average rotate to the back
160	// instead of dying, decoupling eviction order from arrival order. Entries are
161	// hints that only resolve while their stamp matches the slot's, so a re-served
162	// sequence can't accumulate duplicate hints that alias its replacement.
163	// Eviction is deliberately approximate: a bounded scan per write.
164	evict: VecDeque<(u64, u32)>,
165
166	// Outstanding eviction debt in bytes, accrued by writes while the shared pool
167	// is over capacity (see `cache::Pool::accrue`) and paid by aborting this
168	// track's own oldest groups. Per track, so eviction lands proportionally to
169	// what each track writes and never touches another track's cache.
170	debt: u64,
171
172	// Datagrams in arrival order paired with their arrival time, a best-effort send buffer
173	// evicted by age (see `MAX_DATAGRAM_AGE`). Shares the group `max_sequence` namespace but
174	// is otherwise independent.
175	datagrams: VecDeque<(Datagram, web_async::time::Instant)>,
176
177	// Number of datagrams dropped off the front (aged out), mapping a subscriber's absolute
178	// cursor to an index into `datagrams` (mirrors `offset` for groups).
179	datagram_offset: usize,
180
181	// We've popped the front of `arrival` this many times, mapping a subscriber's
182	// absolute cursor to an index.
183	offset: usize,
184
185	// The highest sequence number successfully appended to the track. Shared with
186	// datagrams, so it can run ahead of any cached group.
187	max_sequence: Option<u64>,
188
189	// The sequence of the newest cached group: the live edge, protected from
190	// eviction by never entering the eviction order. Tracked separately from
191	// `max_sequence` because datagrams advance that shared counter, and the live
192	// edge must still demote correctly when the next group lands past one.
193	latest_group: Option<u64>,
194
195	// Incarnation counter for `Slot::stamp`.
196	next_stamp: u32,
197
198	// Rotating position of the expiry scan over `evict`, so entries beyond one
199	// scan window can't be starved by fresh entries in front of them.
200	expire_cursor: usize,
201
202	// The sequence number at which the track was finalized.
203	final_sequence: Option<u64>,
204
205	// The error that caused the track to be aborted, if any.
206	abort: Option<Error>,
207
208	// Active subscriptions, in their own [`kio::Shared`] so a read-only `Consumer`
209	// registers under that lock instead of writing back into the track state.
210	// Kept here (rather than threaded through every handle) so any holder reaches it.
211	subscriptions: kio::Shared<Subscriptions>,
212
213	// The reverse fetch queue (see [`FetchState`]), same reasoning: cache-miss
214	// `fetch_group` calls enqueue here and a `Dynamic` drains.
215	fetch: kio::Shared<FetchState>,
216}
217
218/// A cached group plus its bookkeeping in the track's `lookup` map.
219///
220/// Access times and the evictable-population sample live in the group's own
221/// `cache::Charge`, so they share the group's lifecycle exactly: an abort from any
222/// handle releases the bytes and the sample together.
223struct Slot {
224	group: group::Producer,
225
226	// Incarnation stamp, echoed by this slot's arrival entry (if any). A re-served
227	// sequence (an aborted group re-created by the publisher or re-fetched as
228	// backfill) gets a fresh stamp, so a historical arrival entry can't resolve to
229	// the replacement and deliver it twice or at the wrong position.
230	stamp: u32,
231}
232
233/// The registered subscriptions, aggregated by the producer.
234type Subscriptions = Vec<kio::Consumer<Subscription>>;
235
236/// Reverse state for [`Consumer::fetch_group`], beside the track state in its own
237/// [`kio::Shared`]: consumers enqueue (coalescing per sequence, so a relay opens one
238/// upstream FETCH per group) and [`Dynamic`] handlers drain under one lock, without
239/// write access to the track itself.
240type FetchState = Requests<u64, PendingFetch>;
241
242/// One fetch attempt for a sequence, shared by every [`Fetching`] that joined it.
243struct PendingFetch {
244	// The most demanding delivery priority across the joined fetches.
245	priority: u8,
246
247	// Result channel back to the joined fetches. Written only on rejection; a
248	// successful accept resolves them through the track cache instead. Dropping
249	// every producer without writing (a vanished handler) closes the channel,
250	// which a [`Fetching`] reads as [`Error::NotFound`].
251	result: kio::Producer<FetchOutcome>,
252}
253
254/// The result of a fetch attempt. Stays empty on success (the group lands in the
255/// track cache); a handler writes `rejected` to fail every joined fetch.
256#[derive(Default)]
257struct FetchOutcome {
258	rejected: Option<Error>,
259}
260
261impl TrackState {
262	fn poll_info(&self) -> Poll<Result<Info>> {
263		if let Some(info) = &self.info {
264			Poll::Ready(Ok(info.clone()))
265		} else {
266			Poll::Pending
267		}
268	}
269
270	/// Find the next live group at or after `index` in arrival order.
271	///
272	/// Returns the group and its absolute index so the consumer can advance past it.
273	fn poll_recv_group(&self, index: usize, min_sequence: u64) -> Poll<Result<Option<(group::Consumer, usize)>>> {
274		let start = index.saturating_sub(self.offset);
275		for (i, (sequence, stamp)) in self.arrival.iter().enumerate().skip(start) {
276			if *sequence >= min_sequence
277				&& let Some(slot) = self.lookup.get(sequence)
278				&& slot.stamp == *stamp
279				&& !slot.group.is_aborted()
280			{
281				return Poll::Ready(Ok(Some((slot.group.consume(), self.offset + i))));
282			}
283		}
284
285		// TODO once we have drop notifications, check if index == final_sequence.
286		if self.is_complete() {
287			Poll::Ready(Ok(None))
288		} else if let Some(err) = &self.abort {
289			Poll::Ready(Err(err.clone()))
290		} else {
291			Poll::Pending
292		}
293	}
294
295	/// Find the next datagram at or after the subscriber's absolute `index`.
296	///
297	/// Returns the datagram and its absolute index so the consumer can advance past it. A
298	/// consumer whose `index` has fallen behind `datagram_offset` (older datagrams dropped)
299	/// resumes at the oldest still-buffered datagram, skipping the lost ones.
300	fn poll_recv_datagram(&self, index: usize) -> Poll<Result<Option<(Datagram, usize)>>> {
301		let start = index.saturating_sub(self.datagram_offset);
302		if let Some((datagram, _)) = self.datagrams.get(start) {
303			return Poll::Ready(Ok(Some((datagram.clone(), self.datagram_offset + start))));
304		}
305
306		// Nothing buffered at the cursor: the track ending terminates the datagram stream too.
307		if self.is_complete() {
308			Poll::Ready(Ok(None))
309		} else if let Some(err) = &self.abort {
310			Poll::Ready(Err(err.clone()))
311		} else {
312			Poll::Pending
313		}
314	}
315
316	/// Push a datagram onto the buffer, dropping any that have aged past [`MAX_DATAGRAM_AGE`].
317	fn push_datagram(&mut self, datagram: Datagram) {
318		let now = web_async::time::Instant::now();
319		self.datagrams.push_back((datagram, now));
320		while let Some((_, at)) = self.datagrams.front() {
321			if now.duration_since(*at) <= MAX_DATAGRAM_AGE {
322				break;
323			}
324			self.datagrams.pop_front();
325			self.datagram_offset += 1;
326		}
327	}
328
329	/// Scan groups at or after `index` in arrival order, looking for the first with sequence
330	/// `>= next_sequence` that has a fully-buffered next frame. Returns the frame plus the
331	/// winning slot's absolute index and sequence so the consumer can advance past it.
332	fn poll_read_frame(
333		&self,
334		index: usize,
335		next_sequence: u64,
336		waiter: &kio::Waiter,
337	) -> Poll<Result<Option<(frame::Frame, usize, u64)>>> {
338		let start = index.saturating_sub(self.offset);
339		let mut pending_seen = false;
340		for (i, (sequence, stamp)) in self.arrival.iter().enumerate().skip(start) {
341			if *sequence < next_sequence {
342				continue;
343			}
344			let Some(slot) = self.lookup.get(sequence) else {
345				continue;
346			};
347			if slot.stamp != *stamp {
348				// A historical entry; the sequence was re-served by a newer
349				// incarnation, delivered (if at all) at its own arrival position.
350				continue;
351			}
352
353			let mut consumer = slot.group.consume();
354			match consumer.poll_read_frame(waiter) {
355				Poll::Ready(Ok(Some(frame))) => {
356					return Poll::Ready(Ok(Some((frame, self.offset + i, *sequence))));
357				}
358				Poll::Ready(Ok(None)) => continue,
359				// A single group failing (aborted upstream, or evicted from the
360				// cache) doesn't poison the track; skip it like a gap.
361				Poll::Ready(Err(_)) => continue,
362				Poll::Pending => {
363					pending_seen = true;
364					continue;
365				}
366			}
367		}
368
369		// A pending group can still produce a frame even after finish(). Finish only
370		// blocks new groups at/above final_sequence, not frames on existing groups.
371		if pending_seen {
372			Poll::Pending
373		} else if self.is_complete() {
374			Poll::Ready(Ok(None))
375		} else if let Some(err) = &self.abort {
376			Poll::Ready(Err(err.clone()))
377		} else {
378			Poll::Pending
379		}
380	}
381
382	/// Find the smallest-sequence cached group satisfying
383	/// `next_sequence <= seq <= end_sequence (if set)`. Used by
384	/// [`Subscriber::next_group`] so the range can be widened (or unset)
385	/// after the fact and previously-skipped cached groups become available
386	/// without scanning past them in arrival order.
387	///
388	/// Returns `Poll::Pending` when no in-range group is currently cached but
389	/// future groups could still arrive in range; returns `Ok(None)` only when
390	/// the track is finalized and no further in-range group is possible.
391	fn poll_next_in_range(
392		&self,
393		next_sequence: u64,
394		end_sequence: Option<u64>,
395	) -> Poll<Result<Option<group::Consumer>>> {
396		// If the end cap is already below where we'd resume, no group can
397		// ever satisfy this call until the cap rises. Pending (not None) so
398		// the consumer is parked rather than told the stream is over.
399		if let Some(end) = end_sequence
400			&& end < next_sequence
401		{
402			if let Some(err) = &self.abort {
403				return Poll::Ready(Err(err.clone()));
404			}
405			return Poll::Pending;
406		}
407
408		let mut best: Option<&group::Producer> = None;
409		for slot in self.lookup.values() {
410			let group = &slot.group;
411			if group.sequence < next_sequence {
412				continue;
413			}
414			if let Some(end) = end_sequence
415				&& group.sequence > end
416			{
417				continue;
418			}
419			if group.is_aborted() {
420				continue;
421			}
422			if best.is_none_or(|b| group.sequence < b.sequence) {
423				best = Some(group);
424			}
425		}
426
427		if let Some(group) = best {
428			return Poll::Ready(Ok(Some(group.consume())));
429		}
430
431		// No in-range group is cached. Decide whether more could ever arrive.
432		if let Some(err) = &self.abort {
433			return Poll::Ready(Err(err.clone()));
434		}
435		// `final_sequence` is one past the last possible sequence. If our
436		// floor is already at/past it, nothing else can land in range.
437		if let Some(fin) = self.final_sequence
438			&& next_sequence >= fin
439		{
440			return Poll::Ready(Ok(None));
441		}
442		Poll::Pending
443	}
444
445	/// Find a cached group by sequence; an aborted (evicted) group is a miss, so a
446	/// fetch re-fetches it. Synchronous, never blocks. Test hook for `peek_group`;
447	/// the real fetch path is [`Self::poll_fetch_cached`], which also refreshes the
448	/// group.
449	#[cfg(test)]
450	fn cached_group(&self, sequence: u64) -> Option<group::Consumer> {
451		let slot = self.lookup.get(&sequence)?;
452		if slot.group.is_aborted() {
453			return None;
454		}
455		Some(slot.group.consume())
456	}
457
458	/// The publisher's latency window, or `None` while the info is unknown (an
459	/// unaccepted [`Request`]). Bounds the aggregate subscription; see [`clamp_combined`].
460	fn latency_bound(&self) -> Option<Duration> {
461		self.info.as_ref().map(|info| info.latency_max)
462	}
463
464	/// Resolve a one-shot fetch from the track side: the cached group, or an [`Error`]
465	/// once it can never be served. A missing group is a failure ([`Error::NotFound`]), not an
466	/// end-of-stream. The handler side (a rejection, or no [`Dynamic`] at all) lives
467	/// in [`FetchState`]; [`Fetching`] polls both.
468	fn poll_fetch_cached(&self, sequence: u64) -> Poll<Result<group::Consumer>> {
469		if let Some(slot) = self.lookup.get(&sequence)
470			&& !slot.group.is_aborted()
471		{
472			// A cache hit refreshes the group: it resets both its age (expiry keys
473			// off the last access) and its standing against the pool-wide average,
474			// so the eviction walk keeps it over never-read groups.
475			slot.group.cache_refresh();
476			return Poll::Ready(Ok(slot.group.consume()));
477		}
478
479		if let Some(err) = &self.abort {
480			return Poll::Ready(Err(err.clone()));
481		}
482
483		// Past the final sequence: the group can never exist.
484		if self.final_sequence.is_some_and(|fin| sequence >= fin) {
485			return Poll::Ready(Err(Error::NotFound));
486		}
487
488		Poll::Pending
489	}
490
491	/// Expire groups whose last access is older than `max_age`, never the latest.
492	///
493	/// One bounded, rotating scan over the eviction order, which holds every cached
494	/// group except the protected latest. The cursor persists across calls, so
495	/// entries beyond one scan window can't be starved by fresh (recently fetched
496	/// or written) entries in front of them: every position is revisited within a
497	/// few writes. Expiry throughput is therefore EVICT_SCAN groups per write; the
498	/// byte budget reclaims the remainder under memory pressure.
499	fn evict_expired(&mut self, max_age: Duration) {
500		let now = self.cache.pool().now();
501		let max_ticks = cache::Pool::ticks(max_age);
502
503		let len = self.evict.len();
504		if len > 0 {
505			let start = self.expire_cursor % len;
506			for step in 0..len.min(EVICT_SCAN) {
507				let (sequence, stamp) = self.evict[(start + step) % len];
508				let Some(slot) = self.lookup.get(&sequence) else {
509					continue;
510				};
511				if slot.stamp != stamp {
512					// A historical hint; the live entry is elsewhere in the queue.
513					continue;
514				}
515				// Already aborted: the frames are gone, reclaim the slot so a
516				// later fetch can serve the sequence again.
517				if slot.group.is_aborted() {
518					self.lookup.remove(&sequence);
519					continue;
520				}
521				if Some(sequence) == self.latest_group || now.saturating_sub(slot.group.cache_accessed()) <= max_ticks {
522					continue;
523				}
524				// Take the group out of the cache and abort it, so any consumer
525				// still reading surfaces `Error::Old` instead of blocking forever
526				// on a frame that will never arrive.
527				let slot = self.lookup.remove(&sequence).unwrap();
528				let _ = slot.group.abort(Error::Old);
529			}
530			self.expire_cursor = (start + EVICT_SCAN) % len;
531		}
532
533		// Trim dead leading arrival entries to advance the subscriber offset. An
534		// entry is dead once its slot is gone or re-stamped by a newer incarnation.
535		while let Some((sequence, stamp)) = self.arrival.front() {
536			if self.lookup.get(sequence).is_some_and(|slot| slot.stamp == *stamp) {
537				break;
538			}
539			self.arrival.pop_front();
540			self.offset += 1;
541		}
542
543		// Drop dead leading eviction entries so scans stay over live candidates.
544		while let Some((sequence, stamp)) = self.evict.front() {
545			if self.lookup.get(sequence).is_some_and(|slot| slot.stamp == *stamp) {
546				break;
547			}
548			self.evict.pop_front();
549		}
550
551		// Dead entries behind a live front can linger; rebuild once they clearly
552		// outnumber the live slots.
553		if self.evict.len() > 2 * self.lookup.len() + EVICT_SLACK {
554			let lookup = &self.lookup;
555			self.evict
556				.retain(|(sequence, stamp)| lookup.get(sequence).is_some_and(|slot| slot.stamp == *stamp));
557		}
558	}
559
560	/// Drop every cached group and reset the eviction bookkeeping. Each group's
561	/// access sample lives in its own charge, released when the group itself dies.
562	fn clear_cache(&mut self) {
563		self.lookup.clear();
564		self.arrival.clear();
565		self.evict.clear();
566		self.latest_group = None;
567		self.debt = 0;
568	}
569
570	/// Attach `info` to this track, clamping the publisher's window down to the
571	/// origin's [`cache_duration`](crate::origin::Info::cache_duration) ceiling so a
572	/// group is never retained longer than the origin allows. Every path that binds an
573	/// info to a track funnels through here, covering local publishers and relayed
574	/// (lite / IETF) tracks alike.
575	fn install(&mut self, mut info: Info) {
576		info.latency_max = info.latency_max.min(self.broadcast.origin.cache_duration);
577		self.info = Some(info);
578	}
579
580	/// Create the shared state for a track under `broadcast`, along with the cache
581	/// account it and its groups charge into.
582	///
583	/// The account holds a [`kio::Weak`] back to this state: a group must be able to
584	/// settle the track's eviction debt as it writes, but the track owns its cached
585	/// groups, so anything stronger would make the pair immortal.
586	fn spawn(broadcast: Arc<broadcast::Info>) -> kio::Producer<Self> {
587		let state = kio::Producer::new(Self {
588			broadcast: broadcast.clone(),
589			..Default::default()
590		});
591		let cache = cache::Track::new(broadcast.origin.pool.clone(), state.downgrade());
592		state.write().ok().expect("a new track is open").cache = cache;
593		state
594	}
595
596	/// Reject a sequence that is still cached; a dead (aborted or evicted)
597	/// incarnation is removed so a fresh group can serve the sequence again.
598	///
599	/// Best effort: nothing remembers a sequence whose slot is already gone, so a
600	/// publisher re-sending a long-evicted sequence is accepted as new.
601	fn claim_sequence(&mut self, sequence: u64) -> Result<()> {
602		if let Some(slot) = self.lookup.get(&sequence) {
603			if !slot.group.is_aborted() {
604				return Err(Error::Duplicate);
605			}
606			self.lookup.remove(&sequence);
607		}
608		Ok(())
609	}
610
611	/// Insert a freshly-created group into the cache.
612	///
613	/// Updates the live edge, demoting the previous latest into the eviction order;
614	/// the current latest is never enqueued, which is what protects it from
615	/// eviction. `visible` controls arrival-order delivery: publisher-produced
616	/// groups reach subscribers, fetched backfill is served by sequence only.
617	fn insert_group(&mut self, group: &group::Producer, visible: bool) {
618		let sequence = group.sequence;
619		self.next_stamp = self.next_stamp.wrapping_add(1);
620		let stamp = self.next_stamp;
621
622		// The live edge is tracked separately from `max_sequence`, which datagrams
623		// share and can push past any cached group: demotion must still fire when
624		// the next group lands beyond a datagram-advanced counter.
625		if self.latest_group.is_none_or(|latest| sequence >= latest) {
626			// Demote the previous latest: it joins the eviction order (and the
627			// pool's access average) like any other cached group.
628			if let Some(latest) = self.latest_group
629				&& sequence > latest
630				&& let Some(prev) = self.lookup.get(&latest)
631			{
632				prev.group.cache_demote();
633				self.evict.push_back((latest, prev.stamp));
634			}
635			self.latest_group = Some(sequence);
636		} else {
637			group.cache_demote();
638			self.evict.push_back((sequence, stamp));
639		}
640
641		self.max_sequence = Some(self.max_sequence.map_or(sequence, |max| max.max(sequence)));
642		self.lookup.insert(
643			sequence,
644			Slot {
645				group: group.clone(),
646				stamp,
647			},
648		);
649		if visible {
650			self.arrival.push_back((sequence, stamp));
651		}
652	}
653
654	/// Admit a freshly-created group: settle eviction debt first (so the newcomer
655	/// can never be a victim of the very write that created it), insert it, then
656	/// expire by age.
657	fn commit_group(&mut self, group: &group::Producer, visible: bool, latency_max: Duration) {
658		self.charge_debt();
659		self.insert_group(group, visible);
660		self.evict_expired(latency_max);
661	}
662
663	/// Accrue and pay eviction debt for everything written since the last charge:
664	/// this track's account, which the groups' charges feed on every frame (so
665	/// growth on already-demoted groups and backfill is billed too).
666	///
667	/// Runs BEFORE the new group is inserted, so a brand-new entry is never a
668	/// victim of the very write that created it. A track whose oldest content is
669	/// staler than the pool-wide average access time accrues at double rate, so
670	/// stale-heavy tracks drain first.
671	///
672	/// Also runs from the frame-write path via [`cache::Track::settle`], which is
673	/// why it's reachable from the account, so a track that only appends frames to
674	/// open groups still pays.
675	pub(super) fn charge_debt(&mut self) {
676		let written = self.cache.take_written();
677		let pool = self.cache.pool().clone();
678		match pool.accrue(written) {
679			Some(mut accrued) => {
680				if self.oldest_is_stale(&pool) {
681					accrued = accrued.saturating_mul(2);
682				}
683				// `used` bounds what eviction could ever free, keeping a track that
684				// can't pay (everything protected) from hoarding a stale schedule.
685				self.debt = self.debt.saturating_add(accrued).min(pool.used());
686				// Cap each payment at twice what was written so one write never dumps
687				// a deep backlog at once; the remainder carries to the next write.
688				self.pay_debt(&pool, written.saturating_mul(2));
689			}
690			// Under capacity there is nothing to work off, and stale debt would
691			// cause a spurious eviction burst at the next pressure spike.
692			None => self.debt = 0,
693		}
694	}
695
696	/// Whether this track's oldest evictable group was accessed at or before the
697	/// pool-wide average, doubling the debt it accrues. A dead entry at the front
698	/// just reads as not-stale until the next payment or expiry cleans it up.
699	fn oldest_is_stale(&self, pool: &cache::Pool) -> bool {
700		let Some(average) = pool.average() else {
701			return false;
702		};
703		let Some((sequence, stamp)) = self.evict.front() else {
704			return false;
705		};
706		let Some(slot) = self.lookup.get(sequence) else {
707			return false;
708		};
709		slot.stamp == *stamp && !slot.group.is_aborted() && slot.group.cache_accessed() <= average
710	}
711
712	/// Abort this track's stalest groups until the outstanding debt is paid, or
713	/// `cap` bytes have been freed by this call.
714	///
715	/// Deliberately approximate, Redis-style: at most a handful of live candidates
716	/// are examined per call, from the front of the eviction order. A group
717	/// accessed more recently than the pool-wide average is protected and rotates
718	/// to the back, so fresh content in this track never dies while staler content
719	/// survives elsewhere; the unfreed bytes keep the pool over budget, shifting
720	/// the debt onto the tracks holding that staler content. When the next victim
721	/// is larger than the remaining debt it is left in place and the debt carries
722	/// over, so a small write never evicts a huge group (once the debt does cover
723	/// it, that one victim may overshoot `cap`).
724	fn pay_debt(&mut self, pool: &cache::Pool, cap: u64) {
725		let average = pool.average().unwrap_or(0);
726		let mut paid = 0u64;
727		let mut scanned = 0usize;
728		for _ in 0..self.evict.len() {
729			if self.debt == 0 || paid >= cap || scanned >= EVICT_SCAN {
730				return;
731			}
732			let Some((sequence, stamp)) = self.evict.pop_front() else {
733				return;
734			};
735			let Some(slot) = self.lookup.get(&sequence) else {
736				// Evicted or expired; discard the dead entry.
737				continue;
738			};
739			if slot.stamp != stamp {
740				// A historical hint; the live entry is elsewhere in the queue.
741				continue;
742			}
743			if slot.group.is_aborted() {
744				// Aborted upstream: the frames are already gone, reclaim the slot.
745				self.lookup.remove(&sequence);
746				continue;
747			}
748			if Some(sequence) == self.latest_group {
749				// The live edge is never enqueued, but tolerate finding it anyway.
750				self.evict.push_back((sequence, stamp));
751				continue;
752			}
753
754			scanned += 1;
755			// Protected: accessed more recently than the average (a fresh insert or
756			// a FETCH hit, which also covers a backfill still being filled). Rotate
757			// to the back.
758			if slot.group.cache_accessed() > average {
759				self.evict.push_back((sequence, stamp));
760				continue;
761			}
762			// The full footprint including overhead, so even empty groups repay
763			// their share of the budget when evicted.
764			let size = slot.group.cache_size();
765			if size > self.debt {
766				self.evict.push_front((sequence, stamp));
767				return;
768			}
769
770			self.debt -= size;
771			paid = paid.saturating_add(size);
772			let slot = self.lookup.remove(&sequence).unwrap();
773			let _ = slot.group.abort(Error::Evicted);
774		}
775	}
776
777	/// Record the exclusive final sequence, rejecting a re-finish or a boundary that
778	/// would orphan already-produced groups.
779	fn set_final(&mut self, final_sequence: u64) -> Result<()> {
780		if self.final_sequence.is_some() {
781			return Err(Error::Closed);
782		}
783		if let Some(max) = self.max_sequence
784			&& final_sequence <= max
785		{
786			return Err(Error::ProtocolViolation);
787		}
788		self.final_sequence = Some(final_sequence);
789		Ok(())
790	}
791
792	/// Whether the track has reached its end: the final boundary is set and the live
793	/// edge has caught up to it, so no further group can arrive. A future boundary
794	/// (declared via [`Producer::finish_at`] ahead of the live edge) stays incomplete
795	/// until the remaining groups are produced. Drives the end-of-stream signal from
796	/// the read methods (`recv_group` / `next_group` / `read_frame` return `None`).
797	fn is_complete(&self) -> bool {
798		self.final_sequence
799			.is_some_and(|fin| self.max_sequence.map_or(0, |max| max.saturating_add(1)) >= fin)
800	}
801
802	fn poll_finished(&self) -> Poll<Result<u64>> {
803		if let Some(fin) = self.final_sequence {
804			Poll::Ready(Ok(fin))
805		} else if let Some(err) = &self.abort {
806			Poll::Ready(Err(err.clone()))
807		} else {
808			Poll::Pending
809		}
810	}
811
812	fn modify(producer: &kio::Producer<Self>) -> Result<kio::Mut<'_, Self>> {
813		producer.write().map_err(|r| r.abort.clone().unwrap_or(Error::Dropped))
814	}
815
816	/// Insert a group fetched for a [`GroupRequest`], setting the track's [`Info`]
817	/// if it isn't accepted yet. The group's timescale comes from that info, so a
818	/// fetch can serve an as-yet-unaccepted track (e.g. a relay with no live
819	/// subscription). The group lands in the cache so a waiting
820	/// [`Fetching`] resolves via [`Self::poll_fetch`].
821	fn insert_group_request(&mut self, sequence: u64, info: Option<Info>) -> Result<group::Producer> {
822		if let Some(err) = &self.abort {
823			return Err(err.clone());
824		}
825		if let Some(fin) = self.final_sequence
826			&& sequence >= fin
827		{
828			return Err(Error::Closed);
829		}
830
831		// Adopt the supplied info only if the track hasn't been accepted yet. Groups
832		// created here charge the same account as any other, so backfill written
833		// before the track is accepted settles its debt like the rest.
834		if self.info.is_none() {
835			self.install(info.unwrap_or_default());
836		}
837		let info = self.info.clone().unwrap();
838
839		// An evicted sequence can be re-fetched; a live one is a duplicate.
840		self.claim_sequence(sequence)?;
841
842		let latency_max = info.latency_max;
843		let group = group::Producer::new(group::Info { sequence }, info, self.cache.clone());
844		// A backfill exists because someone is fetching it right now: stamp that
845		// access so the eviction walk can't kill it before the fetch resolves.
846		// It is also invisible to arrival-order subscribers: fetched on demand,
847		// not produced live by the publisher.
848		group.cache_refresh();
849		self.commit_group(&group, false, latency_max);
850		Ok(group)
851	}
852}
853
854/// A producer for a track, used to create new groups.
855#[derive(Clone)]
856pub struct Producer {
857	name: Arc<str>,
858	// The parent broadcast's info, inherited from [`broadcast::Producer::create_track`].
859	// Top link of the ownership chain; carried for identity and future inheritance.
860	broadcast: Arc<broadcast::Info>,
861	state: kio::Producer<TrackState>,
862	prev_subscription: Option<Subscription>,
863	// Shared with every clone and every `Dynamic`: its `Drop` is the teardown.
864	alive: Arc<Alive>,
865	// Ingress stats scope, inherited from a tagged [`broadcast::Producer`]. Bumped as
866	// one subscription on tag and closed when the last producer clone drops. Empty
867	// (no-op) for an untagged broadcast.
868	stats: stats::Scope,
869}
870
871impl Producer {
872	/// Build a producer for the given track metadata.
873	///
874	/// Crate-private: tracks are born from their broadcast via
875	/// [`broadcast::Producer::create_track`] (or served on demand through a
876	/// [`Request`]), which threads the broadcast's `Arc<broadcast::Info>` down. The
877	/// track opens its cache account against that broadcast's origin pool, and every
878	/// group it creates charges into it.
879	pub(crate) fn new(
880		broadcast: Arc<broadcast::Info>,
881		name: impl Into<Arc<str>>,
882		info: impl Into<Option<Info>>,
883	) -> Self {
884		let name = name.into();
885		let state = TrackState::spawn(broadcast.clone());
886		state
887			.write()
888			.ok()
889			.expect("a new track is open")
890			.install(info.into().unwrap_or_default());
891		let alive = Alive::new(name.clone(), state.clone());
892		alive.publish(None);
893		Self {
894			name,
895			state,
896			broadcast,
897			prev_subscription: None,
898			alive,
899			stats: stats::Scope::default(),
900		}
901	}
902
903	/// Attach the parent broadcast's ingress stats scope, counting this track as one
904	/// ingress subscription (closed when the last producer clone drops). Called by a
905	/// tagged [`broadcast::Producer`] when it creates the track.
906	pub(crate) fn with_stats(mut self, scope: stats::Scope) -> Self {
907		self.alive.publish(Some(&scope));
908		self.stats = scope;
909		self
910	}
911
912	/// The track's name, unique within its broadcast.
913	pub fn name(&self) -> &str {
914		&self.name
915	}
916
917	/// The parent broadcast this track belongs to.
918	pub fn broadcast(&self) -> &broadcast::Info {
919		&self.broadcast
920	}
921
922	/// Create a new group with the given sequence number.
923	pub fn create_group(&mut self, group: group::Info) -> Result<group::Producer> {
924		let mut state = self.modify()?;
925		if let Some(fin) = state.final_sequence
926			&& group.sequence >= fin
927		{
928			return Err(Error::Closed);
929		}
930		let track = state.info.clone().unwrap();
931		let latency_max = track.latency_max;
932
933		// An evicted sequence can be re-created; a live one is a duplicate.
934		state.claim_sequence(group.sequence)?;
935
936		let group = group::Producer::new(group, track, state.cache.clone()).with_meter(self.stats.meter());
937		state.commit_group(&group, true, latency_max);
938
939		Ok(group)
940	}
941
942	/// Create a new group with the next sequence number.
943	pub fn append_group(&mut self) -> Result<group::Producer> {
944		let mut state = self.modify()?;
945		let sequence = match state.max_sequence {
946			Some(s) => s.checked_add(1).ok_or(coding::BoundsExceeded)?,
947			None => 0,
948		};
949		if let Some(fin) = state.final_sequence
950			&& sequence >= fin
951		{
952			return Err(Error::Closed);
953		}
954
955		let track = state.info.clone().unwrap();
956		let latency_max = track.latency_max;
957
958		let group =
959			group::Producer::new(group::Info { sequence }, track, state.cache.clone()).with_meter(self.stats.meter());
960		state.commit_group(&group, true, latency_max);
961
962		Ok(group)
963	}
964
965	/// Append a datagram with the next sequence number, returning the assigned sequence.
966	///
967	/// A datagram is delivered best-effort over a single QUIC datagram, parallel to the
968	/// track's groups but drawing from the same sequence namespace (so interleaving with
969	/// [`Self::append_group`] never reuses a number). There is no group fallback: each
970	/// session drops (with a debug log) any datagram whose encoded body exceeds the
971	/// transport's datagram size, and sessions that can't carry datagrams at all (IETF
972	/// moq-transport, moq-lite before 05, or stream-only transports like WebSocket) never
973	/// deliver them. Keep payloads well under the 1200-byte minimum path MTU. An origin
974	/// publisher uses this; a relay preserving upstream numbering uses
975	/// [`Self::write_datagram`].
976	pub fn append_datagram<B: crate::IntoBytes>(&mut self, timestamp: Timestamp, payload: B) -> Result<u64> {
977		let payload = payload.into_bytes();
978		if payload.len() > super::datagram::MAX_DATAGRAM_PAYLOAD {
979			return Err(Error::FrameTooLarge);
980		}
981		// Resolved before the state guard borrows `self`.
982		let meter = self.stats.meter();
983		let mut state = self.modify()?;
984		// Normalize into the track's timescale, like frames (see `group::Producer::create_frame`).
985		let timescale = state.info.as_ref().unwrap().timescale;
986		let timestamp = timestamp.convert(timescale).map_err(|_| Error::TimestampMismatch)?;
987		let sequence = match state.max_sequence {
988			Some(s) => s.checked_add(1).ok_or(coding::BoundsExceeded)?,
989			None => 0,
990		};
991		if let Some(fin) = state.final_sequence
992			&& sequence >= fin
993		{
994			return Err(Error::Closed);
995		}
996		state.max_sequence = Some(sequence);
997		meter.datagram(payload.len() as u64);
998		state.push_datagram(Datagram {
999			sequence,
1000			timestamp,
1001			payload,
1002		});
1003		Ok(sequence)
1004	}
1005
1006	/// Write a datagram with an explicit sequence number.
1007	///
1008	/// Preserves the supplied sequence (bumping the shared `max_sequence` if needed), so a
1009	/// relay can forward a datagram without renumbering it. Most origin publishers want
1010	/// [`Self::append_datagram`] instead.
1011	pub fn write_datagram(&mut self, mut datagram: Datagram) -> Result<()> {
1012		if datagram.payload.len() > super::datagram::MAX_DATAGRAM_PAYLOAD {
1013			return Err(Error::FrameTooLarge);
1014		}
1015		// Resolved before the state guard borrows `self`.
1016		let meter = self.stats.meter();
1017		let mut state = self.modify()?;
1018		// Normalize into the track's timescale, like frames (see `group::Producer::create_frame`).
1019		let timescale = state.info.as_ref().unwrap().timescale;
1020		datagram.timestamp = datagram
1021			.timestamp
1022			.convert(timescale)
1023			.map_err(|_| Error::TimestampMismatch)?;
1024		if let Some(fin) = state.final_sequence
1025			&& datagram.sequence >= fin
1026		{
1027			return Err(Error::Closed);
1028		}
1029		state.max_sequence = Some(state.max_sequence.unwrap_or(0).max(datagram.sequence));
1030		meter.datagram(datagram.payload.len() as u64);
1031		state.push_datagram(datagram);
1032		Ok(())
1033	}
1034
1035	/// Create a group with a single frame, at the given presentation timestamp.
1036	///
1037	/// The timestamp is converted into the track's timescale. For data without
1038	/// a presentation time, pass [`Timestamp::now`] explicitly.
1039	pub fn write_frame<B: crate::IntoBytes>(&mut self, timestamp: Timestamp, frame: B) -> Result<()> {
1040		let mut group = self.append_group()?;
1041		group.write_frame(timestamp, frame)?;
1042		group.finish()?;
1043		Ok(())
1044	}
1045
1046	/// Mark the track as finished after the last appended group.
1047	///
1048	/// Sets the final sequence to one past the current max_sequence.
1049	/// No new groups at or above this sequence can be appended.
1050	/// NOTE: Old groups with lower sequence numbers can still arrive.
1051	pub fn finish(&mut self) -> Result<()> {
1052		let mut state = self.modify()?;
1053		let final_sequence = match state.max_sequence {
1054			Some(max) => max.checked_add(1).ok_or(coding::BoundsExceeded)?,
1055			None => 0,
1056		};
1057		state.set_final(final_sequence)
1058	}
1059
1060	/// Declare the track's exclusive final sequence, possibly ahead of the live edge.
1061	///
1062	/// `final_sequence` is the first sequence that will never be produced, so a track
1063	/// whose last group is 89 finishes at `90`. Passing a boundary beyond the current
1064	/// max_sequence records a known ending before the remaining groups arrive (e.g.
1065	/// learning a track ends at group 89 while only 87 has been received). The boundary
1066	/// must be strictly greater than the highest produced group, otherwise it would
1067	/// orphan groups that already exist ([`Error::ProtocolViolation`]).
1068	///
1069	/// Groups below `final_sequence` may still be created afterwards; groups at or above
1070	/// it are rejected. Consumers only see end-of-stream once the live edge reaches the
1071	/// boundary. Use [`Self::finish`] to finish exactly at the live edge.
1072	pub fn finish_at(&mut self, final_sequence: u64) -> Result<()> {
1073		self.modify()?.set_final(final_sequence)
1074	}
1075
1076	/// The exclusive final sequence, once [`Self::finish`] or [`Self::finish_at`] declared one.
1077	///
1078	/// `None` while the track is still open ended. Both methods reject a second boundary, so
1079	/// callers that may have already declared one check here first.
1080	pub fn final_sequence(&self) -> Option<u64> {
1081		self.state.read().final_sequence
1082	}
1083
1084	/// Abort the track with the given error.
1085	///
1086	/// Consumes the handle, since nothing can be written to an aborted track. Drops the
1087	/// cached groups so a stale [`Consumer`] can't pin them (and their frame buffers) in
1088	/// memory forever. Consumers that haven't drained yet surface the abort error instead
1089	/// of the leftover cache. Child groups are independent: a consumer that already pulled
1090	/// a [`group::Consumer`] keeps its own handle and can finish reading it.
1091	///
1092	/// [`finish`](Self::finish) is deliberately not terminal: it declares the final
1093	/// sequence, and lower-numbered groups may still be written afterwards.
1094	pub fn abort(self, err: Error) -> Result<()> {
1095		let mut guard = self.modify()?;
1096		guard.abort = Some(err);
1097		guard.clear_cache();
1098		guard.datagrams.clear();
1099		guard.close();
1100		Ok(())
1101	}
1102
1103	/// Block until there are no active consumers.
1104	pub async fn unused(&self) -> Result<()> {
1105		self.state.unused().await.map_err(|_| self.abort_reason())
1106	}
1107
1108	/// Block until there is at least one active consumer.
1109	pub async fn used(&self) -> Result<()> {
1110		self.state.used().await.map_err(|_| self.abort_reason())
1111	}
1112
1113	/// Block until the track is closed or aborted, returning the cause.
1114	pub async fn closed(&self) -> Error {
1115		kio::wait(|waiter| self.poll_closed(waiter)).await
1116	}
1117
1118	/// Poll until the track is closed or aborted; ready with the cause.
1119	pub fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Error> {
1120		self.state.poll_closed(waiter).map(|()| self.abort_reason())
1121	}
1122
1123	/// The recorded abort reason, or [`Error::Dropped`] if the track closed without one.
1124	fn abort_reason(&self) -> Error {
1125		self.state.read().abort.clone().unwrap_or(Error::Dropped)
1126	}
1127
1128	/// Return true if the track has been closed.
1129	pub fn is_closed(&self) -> bool {
1130		self.state.read().is_closed()
1131	}
1132
1133	/// Return the latest sequence number successfully appended to the track.
1134	pub fn latest(&self) -> Option<u64> {
1135		self.state.read().max_sequence
1136	}
1137
1138	/// Return true if this is the same track.
1139	pub fn is_clone(&self, other: &Self) -> bool {
1140		self.state.same_channel(&other.state)
1141	}
1142
1143	/// Create a weak reference that doesn't prevent auto-close.
1144	pub(crate) fn weak(&self) -> TrackWeak {
1145		TrackWeak {
1146			name: self.name.clone(),
1147			state: self.state.weak(),
1148		}
1149	}
1150
1151	/// Create a [`Demand`]: a cloneable, watch-only handle to this track's
1152	/// subscriber demand.
1153	///
1154	/// Lets a publisher gate work (e.g. on-demand capture) on whether anyone is
1155	/// subscribed, without the ability to publish frames or close the track. The
1156	/// handle is weak, so holding one neither keeps the track alive nor pins its
1157	/// cached groups.
1158	pub fn demand(&self) -> Demand {
1159		Demand {
1160			name: self.name.clone(),
1161			state: self.state.weak(),
1162		}
1163	}
1164
1165	/// Get a consumer handle for this in-process track.
1166	///
1167	/// Unlike a wire subscription, the info is already known, so a subscription
1168	/// opened from this handle resolves immediately.
1169	pub fn consume(&self) -> Consumer {
1170		Consumer::plain(self.name.clone(), self.state.consume())
1171	}
1172
1173	/// Subscribing to this in-process track, resolving synchronously.
1174	///
1175	/// The info is fixed at creation, so there's nothing to wait for (no
1176	/// SUBSCRIBE_OK round trip). Pass `None` for [`Subscription::default`].
1177	pub fn subscribe(&self, subscription: impl Into<Option<Subscription>>) -> Subscriber {
1178		let preferences = subscription.into().unwrap_or_default();
1179
1180		// Info is fixed at creation and survives a close/abort, so read it without
1181		// requiring a live producer state. If the track already ended, the returned
1182		// subscriber surfaces the close/abort on its first read; the preferences are
1183		// simply never registered (nothing aggregates them anymore).
1184		let info = self.state.read().info.clone().expect("producer always has info");
1185		let subscription = kio::Producer::new(preferences);
1186		register_subscription(self.state.read(), &subscription);
1187
1188		Subscriber {
1189			name: self.name.clone(),
1190			info,
1191			inner: SubscriberKind::Plain(PlainSubscriber {
1192				state: self.state.consume(),
1193				subscription,
1194				index: 0,
1195				datagram_index: 0,
1196				min_sequence: 0,
1197				next_sequence: 0,
1198				end_sequence: None,
1199			}),
1200			// A producer-side (in-process) subscribe is not egress: stay untagged.
1201			stats: stats::Scope::default(),
1202			_stats_sub: stats::Subscription::default(),
1203		}
1204	}
1205
1206	/// Block until the aggregate subscription changes, then return the new value.
1207	///
1208	/// Yields the most demanding request across all live subscribers, or `None`
1209	/// once the last one drops. Used by relays to forward downstream demand
1210	/// upstream (e.g. SUBSCRIBE_UPDATE).
1211	pub async fn subscription_changed(&mut self) -> Result<Option<Subscription>> {
1212		kio::wait(|waiter| self.poll_subscription_changed(waiter)).await
1213	}
1214
1215	/// A non-blocking snapshot of the current aggregate subscription, or `None`
1216	/// when there are no live subscribers. Unlike [`Self::subscription`], this
1217	/// doesn't wait for a change or advance the change cursor.
1218	///
1219	/// The aggregate's [`Subscription::latency_max`] is clamped to this track's
1220	/// [`Info::latency_max`]: no subscriber can wait for a late group longer than the
1221	/// publisher keeps it.
1222	pub fn subscription(&self) -> Option<Subscription> {
1223		let state = self.state.read();
1224		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
1225		drop(state);
1226		snapshot_subscription(&subs, bound)
1227	}
1228
1229	/// Poll counterpart to [`subscription_changed`](Self::subscription_changed): the
1230	/// aggregate subscription whenever it changes, or `None` once nobody is subscribed.
1231	/// Errors once the track is aborted.
1232	pub fn poll_subscription_changed(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Subscription>>> {
1233		// Surface an abort as the stream ending. `poll_closed` parks on the closed
1234		// waiters, so per-group churn on the track state never wakes this poll.
1235		if self.state.poll_closed(waiter).is_ready() {
1236			let abort = self.state.read().abort.clone();
1237			return Poll::Ready(Err(abort.unwrap_or(Error::Dropped)));
1238		}
1239
1240		// Read the bound before locking `subs`, so the aggregation never nests the two locks.
1241		let state = self.state.read();
1242		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
1243		drop(state);
1244
1245		let prev = &self.prev_subscription;
1246		let mut combined = None;
1247		let mut guard = match subs.poll(waiter, |subs| {
1248			let next = combined_subscription(subs, bound, waiter);
1249			if &next == prev {
1250				Poll::Pending
1251			} else {
1252				combined = next;
1253				Poll::Ready(())
1254			}
1255		}) {
1256			Poll::Ready(guard) => guard,
1257			Poll::Pending => return Poll::Pending,
1258		};
1259		// The aggregate changed: prune any closed subscribers now that we hold the lock.
1260		guard.retain(|sub| !sub.is_closed());
1261		drop(guard);
1262		self.prev_subscription = combined.clone();
1263		Poll::Ready(Ok(combined))
1264	}
1265
1266	/// Poll for the producer becoming unused (every consumer dropped).
1267	pub fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
1268		self.state.poll_unused(waiter).map(|_| ())
1269	}
1270
1271	/// Create a [`Dynamic`] handle that serves on-demand fetches of uncached
1272	/// (old) groups. Most producers never need this; a relay creates one to fetch
1273	/// past groups from upstream.
1274	pub fn dynamic(&self) -> Dynamic {
1275		Dynamic::new(self.name.clone(), self.state.clone(), self.alive.clone())
1276	}
1277
1278	fn modify(&self) -> Result<kio::Mut<'_, TrackState>> {
1279		TrackState::modify(&self.state)
1280	}
1281}
1282
1283/// Pop the next queued group fetch off the fetch queue and wrap it in a
1284/// [`GroupRequest`] bound to a fresh producer handle. Shared by every
1285/// [`Dynamic`] handle on the track.
1286fn poll_requested_group(
1287	state: &kio::Producer<TrackState>,
1288	fetch: &kio::Shared<FetchState>,
1289	waiter: &kio::Waiter,
1290) -> Poll<Result<GroupRequest>> {
1291	// Prefer serving a queued fetch, even if the track has since aborted.
1292	if let Poll::Ready(mut guard) = fetch.poll(waiter, |fetch| {
1293		if fetch.has_queued() {
1294			Poll::Ready(())
1295		} else {
1296			Poll::Pending
1297		}
1298	}) {
1299		let sequence = guard.pop().expect("predicate guaranteed a request");
1300		// The popped attempt stays pending, so a fetch in the window between hand-off
1301		// and accept joins it instead of queueing a duplicate.
1302		// `GroupRequest::{accept, reject, drop}` removes the entry.
1303		let pending = guard.get(&sequence).expect("popped key must be pending");
1304		let priority = pending.priority;
1305		let result = pending.result.clone();
1306		drop(guard);
1307		return Poll::Ready(Ok(GroupRequest {
1308			state: state.clone(),
1309			fetch: fetch.clone(),
1310			sequence,
1311			priority,
1312			result,
1313			done: false,
1314		}));
1315	}
1316
1317	// No fetch queued: surface a track abort so the handler loop can exit.
1318	match state.poll_ref(waiter, |state| match &state.abort {
1319		Some(err) => Poll::Ready(err.clone()),
1320		None => Poll::Pending,
1321	}) {
1322		Poll::Ready(Ok(err)) => Poll::Ready(Err(err)),
1323		Poll::Ready(Err(closed)) => Poll::Ready(Err(closed.abort.clone().unwrap_or(Error::Dropped))),
1324		Poll::Pending => Poll::Pending,
1325	}
1326}
1327
1328/// Serves on-demand fetches of uncached (old) groups for a track, the group-level
1329/// analogue of [`broadcast::Dynamic`].
1330///
1331/// Most tracks never serve old content, so this capability lives on a dedicated
1332/// handle rather than [`Producer`]: a relay creates one (via
1333/// [`Producer::dynamic`] or [`Request::dynamic`]) to pull past groups
1334/// from upstream. While at least one is alive the track will block a cache-miss
1335/// [`Consumer::fetch_group`] waiting to be served; with none, an accepted track's
1336/// miss fails fast with [`Error::NotFound`].
1337pub struct Dynamic {
1338	name: Arc<str>,
1339	// Kept to insert served groups into the cache and observe track abort.
1340	state: kio::Producer<TrackState>,
1341	// The fetch queue this handle drains; its `dynamic` count gates `fetch_group`.
1342	fetch: kio::Shared<FetchState>,
1343	// Shared with the track's producers: a handler still serving fetches keeps the
1344	// track alive, like a producer clone does.
1345	alive: Arc<Alive>,
1346}
1347
1348impl Dynamic {
1349	fn new(name: Arc<str>, state: kio::Producer<TrackState>, alive: Arc<Alive>) -> Self {
1350		let fetch = state.read().fetch.clone();
1351		fetch.lock().add_handler();
1352		Self {
1353			name,
1354			state,
1355			fetch,
1356			alive,
1357		}
1358	}
1359
1360	/// The track's name, unique within its broadcast.
1361	pub fn name(&self) -> &str {
1362		&self.name
1363	}
1364
1365	/// Block until a consumer fetches a group that isn't cached, returning a
1366	/// [`GroupRequest`] to serve via [`GroupRequest::accept`].
1367	///
1368	/// A relay issues a wire FETCH first; an origin already has the group cached, so
1369	/// the fetch resolves without ever reaching here. Errors once the track is aborted.
1370	pub async fn requested_group(&self) -> Result<GroupRequest> {
1371		kio::wait(|waiter| self.poll_requested_group(waiter)).await
1372	}
1373
1374	/// Poll counterpart to [`requested_group`](Self::requested_group).
1375	pub fn poll_requested_group(&self, waiter: &kio::Waiter) -> Poll<Result<GroupRequest>> {
1376		poll_requested_group(&self.state, &self.fetch, waiter)
1377	}
1378
1379	/// Poll for the track becoming unused (every consumer dropped).
1380	pub fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
1381		self.state.poll_unused(waiter).map(|_| ())
1382	}
1383}
1384
1385impl Clone for Dynamic {
1386	fn clone(&self) -> Self {
1387		// Count each live handle (mirrors `broadcast::Dynamic`).
1388		self.fetch.lock().add_handler();
1389		Self {
1390			name: self.name.clone(),
1391			state: self.state.clone(),
1392			fetch: self.fetch.clone(),
1393			alive: self.alive.clone(),
1394		}
1395	}
1396}
1397
1398impl Drop for Dynamic {
1399	fn drop(&mut self) {
1400		// Unlike `broadcast::Dynamic`, dropping the last handle doesn't abort the track:
1401		// a live `Producer` may still be serving the subscription. It just stops fetch
1402		// serving. Queued attempts no handler will ever pop are dropped, closing their
1403		// result channels so every joined `Fetching` resolves NotFound; an attempt
1404		// already handed to a handler stays, resolved by its `GroupRequest` instead.
1405		let mut fetch = self.fetch.lock();
1406		if fetch.remove_handler() {
1407			fetch.drain_queued();
1408		}
1409	}
1410}
1411
1412/// Ends the track when the last [`Producer`] or [`Dynamic`] drops.
1413///
1414/// A refcount rather than a "am I the last one?" check inside `Drop`: that answer is a
1415/// snapshot, and acting on it is exactly what invalidates it. The track state's own
1416/// producer count can't answer it either, since a group settling its eviction debt
1417/// upgrades the account's weak handle and counts there for the duration (see
1418/// [`cache::Track::settle`]). Holding a producer of its own also keeps the state
1419/// writable until the teardown has run, whatever order the last owner's fields drop in.
1420struct Alive {
1421	name: Arc<str>,
1422	state: kio::Producer<TrackState>,
1423
1424	// Set when a `Producer` is first minted, so a `Request` nobody accepted (its
1425	// `Dynamic` holds this guard too) isn't reported as an abandoned publisher.
1426	published: AtomicBool,
1427
1428	// Ingress subscription for this track, opened by the tagged producer that claimed
1429	// it and closed when this guard drops.
1430	stats: OnceLock<stats::Subscription>,
1431}
1432
1433impl Alive {
1434	fn new(name: Arc<str>, state: kio::Producer<TrackState>) -> Arc<Self> {
1435		Arc::new(Self {
1436			name,
1437			state,
1438			published: Default::default(),
1439			stats: Default::default(),
1440		})
1441	}
1442
1443	/// Note that a [`Producer`] was minted from this track, optionally under a tagged
1444	/// broadcast's ingress scope (counted as one subscription for as long as the track
1445	/// has a publisher).
1446	fn publish(&self, stats: Option<&stats::Scope>) {
1447		self.published.store(true, Ordering::Relaxed);
1448		if let Some(scope) = stats {
1449			// At most one scope ever arrives: a track is minted either through
1450			// `Producer::new` (+ `with_stats`) or through `Request::accept`, never both.
1451			let _ = self.stats.set(scope.subscribe());
1452		}
1453	}
1454}
1455
1456impl Drop for Alive {
1457	fn drop(&mut self) {
1458		// A request nobody accepted was never publishing; there's nothing to tear down.
1459		if !self.published.load(Ordering::Relaxed) {
1460			return;
1461		}
1462		// The last producer going away without finishing is an abrupt teardown:
1463		// release the cached groups so a stale consumer can't pin them (and their
1464		// frame buffers) forever, the same as an explicit abort. A cleanly
1465		// finished track keeps its cache so consumers can still drain it.
1466		if let Ok(mut state) = self.state.write()
1467			&& state.final_sequence.is_none()
1468		{
1469			// Dropped without finish() or abort(), so consumers will see
1470			// Error::Dropped instead of a clean end. Deliberate ends go through
1471			// finish()/abort().
1472			tracing::warn!(
1473				track = %self.name,
1474				"track::Producer dropped without finish() or abort()"
1475			);
1476			state.clear_cache();
1477			state.datagrams.clear();
1478		}
1479	}
1480}
1481
1482/// Aggregate every live subscriber's preferences into the most demanding request.
1483///
1484/// Read-only: iterates the subscriptions immutably and registers `waiter` on each, so a
1485/// preference update (or a subscriber dropping) wakes the caller's poll. Callers decide
1486/// readiness from the returned value, then prune closed subscribers through the `Mut`.
1487fn combined_subscription(subs: &Subscriptions, bound: Option<Duration>, waiter: &kio::Waiter) -> Option<Subscription> {
1488	let mut combined = None;
1489	for sub in subs.iter() {
1490		// A closed consumer means the subscriber dropped: it holds no live demand.
1491		// `Consumer::poll` evaluates the closure before the closed flag, so it would
1492		// still replay the final value into the aggregate; skip it explicitly so a
1493		// departed subscriber can't keep the aggregate pinned to its last request.
1494		if sub.is_closed() {
1495			continue;
1496		}
1497		// Arm the closed waiter explicitly. `poll` below registers on the value
1498		// channel only when it returns Pending, so a subscriber that contributes
1499		// demand (always the case for the first one) would leave nothing watching
1500		// for its departure, and the last one leaving would never wake this poll.
1501		let _ = sub.poll_closed(waiter);
1502		if let Poll::Ready(Ok(sub)) = sub.poll(waiter, |sub| sub.poll_combined(&combined)) {
1503			combined = Some(sub);
1504		}
1505	}
1506	clamp_combined(combined, bound)
1507}
1508
1509/// A non-blocking aggregate of the current subscriptions, without arming any waiter.
1510fn snapshot_subscription(subs: &kio::Shared<Subscriptions>, bound: Option<Duration>) -> Option<Subscription> {
1511	let mut combined: Option<Subscription> = None;
1512	for sub in subs.read().iter() {
1513		// Skip dropped subscribers, matching `combined_subscription`.
1514		if sub.is_closed() {
1515			continue;
1516		}
1517		if let Poll::Ready(merged) = sub.read().poll_combined(&combined) {
1518			combined = Some(merged);
1519		}
1520	}
1521	clamp_combined(combined, bound)
1522}
1523
1524/// Clamp the aggregate's latency budget to the publisher's window: nobody can wait for a
1525/// late group longer than the publisher keeps it around.
1526///
1527/// The single clamp point. Subscribers hold their preferences verbatim, so what they asked
1528/// for stays readable, and clamping the aggregate is equivalent to clamping each subscriber
1529/// first (`min` distributes over the `max` that combines them). `bound` is `None` on a track
1530/// whose info isn't known yet (an unaccepted [`Request`]), which imposes no window.
1531fn clamp_combined(combined: Option<Subscription>, bound: Option<Duration>) -> Option<Subscription> {
1532	let mut combined = combined?;
1533	if let Some(bound) = bound {
1534		combined.latency_max = combined.latency_max.min(bound);
1535	}
1536	Some(combined)
1537}
1538
1539/// Register a subscription if the track is live: clone the shared list out of the
1540/// state, release the track lock, then push under the list's own lock. A closed
1541/// track skips the push; nothing aggregates the preferences anymore.
1542fn register_subscription(state: kio::Ref<'_, TrackState>, subscription: &kio::Producer<Subscription>) {
1543	if state.is_closed() {
1544		return;
1545	}
1546	let subs = state.subscriptions.clone();
1547	drop(state);
1548	subs.lock().push(subscription.consume());
1549}
1550
1551/// A weak reference to a track that doesn't prevent auto-close.
1552#[derive(Clone)]
1553pub(crate) struct TrackWeak {
1554	name: Arc<str>,
1555	state: kio::ProducerWeak<TrackState>,
1556}
1557
1558impl TrackWeak {
1559	pub fn consume(&self) -> Consumer {
1560		Consumer::plain(self.name.clone(), self.state.consume())
1561	}
1562
1563	/// The shared name handle, for use as a broadcast lookup key (clone is a
1564	/// refcount bump, and the same `Arc` is shared with the track's handles).
1565	pub(crate) fn name(&self) -> &Arc<str> {
1566		&self.name
1567	}
1568
1569	/// Whether anyone is consuming the track right now. A closed track doesn't
1570	/// count even if consumers linger to drain its cache: no new work is owed.
1571	pub(crate) fn is_used(&self) -> bool {
1572		!self.state.is_closed() && self.state.is_used()
1573	}
1574
1575	/// Park `waiter` for the next consumer appearing; a no-op once one exists.
1576	/// Feeds [`crate::broadcast::Demand`], which recomputes on wake.
1577	pub(crate) fn poll_used(&self, waiter: &kio::Waiter) {
1578		let _ = self.state.poll_used(waiter);
1579	}
1580
1581	/// Park `waiter` for the last consumer (or the track) going away; a no-op
1582	/// once none remain. Feeds [`crate::broadcast::Demand`].
1583	pub(crate) fn poll_unused(&self, waiter: &kio::Waiter) {
1584		let _ = self.state.poll_unused(waiter);
1585	}
1586}
1587
1588impl super::WeakEntry for TrackWeak {
1589	fn is_closed(&self) -> bool {
1590		self.state.is_closed()
1591	}
1592
1593	fn same_channel(&self, other: &Self) -> bool {
1594		self.state.same_channel(&other.state)
1595	}
1596}
1597
1598/// A cloneable, watch-only handle to a track's subscriber demand.
1599///
1600/// Obtained from [`Producer::demand`]. A publisher uses it to react to
1601/// whether anyone is subscribed (on-demand capture / encoding) without being able
1602/// to publish frames or close the track. It's a weak handle, so it neither keeps
1603/// the track alive nor pins its cached groups; once the owning [`Producer`]
1604/// goes away, [`used`](Self::used) / [`unused`](Self::unused) report the track's
1605/// closure.
1606#[derive(Clone)]
1607pub struct Demand {
1608	name: Arc<str>,
1609	state: kio::ProducerWeak<TrackState>,
1610}
1611
1612impl Demand {
1613	/// The track name this handle is bound to.
1614	pub fn name(&self) -> &str {
1615		&self.name
1616	}
1617
1618	/// Block until there is at least one active consumer.
1619	pub async fn used(&self) -> Result<()> {
1620		self.state.used().await.map_err(|_| self.abort_reason())
1621	}
1622
1623	/// Block until there are no active consumers.
1624	pub async fn unused(&self) -> Result<()> {
1625		self.state.unused().await.map_err(|_| self.abort_reason())
1626	}
1627
1628	/// Block until the track is closed or aborted, returning the cause.
1629	pub async fn closed(&self) -> Error {
1630		self.state.closed().await;
1631		self.abort_reason()
1632	}
1633
1634	/// The recorded abort reason, or [`Error::Dropped`] if the track closed without one.
1635	fn abort_reason(&self) -> Error {
1636		self.state.read().abort.clone().unwrap_or(Error::Dropped)
1637	}
1638}
1639
1640/// A handle to a single track within a broadcast.
1641///
1642/// Obtained from [`broadcast::Consumer::track`]. Holding it sends nothing
1643/// to the publisher; it just names a track you can [`subscribe`](Self::subscribe)
1644/// to (a live, ongoing stream of groups) later. The same handle can be subscribed
1645/// to multiple times, and clones are cheap.
1646///
1647/// A track reached through a route-fed broadcast is *spliced*: it is backed by one
1648/// or more per-session tracks joined at group boundaries, and this handle reads
1649/// across them transparently.
1650#[derive(Clone)]
1651pub struct Consumer {
1652	name: Arc<str>,
1653	inner: ConsumerKind,
1654	// Egress stats scope, set by a tagged [`broadcast::Consumer`] via
1655	// [`Self::with_stats`]. Empty (no-op) for an untagged track.
1656	stats: stats::Scope,
1657}
1658
1659#[derive(Clone)]
1660enum ConsumerKind {
1661	Plain(kio::Consumer<TrackState>),
1662	Spliced(super::resume::Consumer),
1663}
1664
1665impl Consumer {
1666	fn plain(name: Arc<str>, state: kio::Consumer<TrackState>) -> Self {
1667		Self {
1668			name,
1669			inner: ConsumerKind::Plain(state),
1670			stats: stats::Scope::default(),
1671		}
1672	}
1673
1674	/// A consumer over a spliced logical track (a route-fed broadcast's track).
1675	pub(crate) fn spliced(name: Arc<str>, resume: super::resume::Consumer) -> Self {
1676		Self {
1677			name,
1678			inner: ConsumerKind::Spliced(resume),
1679			stats: stats::Scope::default(),
1680		}
1681	}
1682
1683	/// Attach an egress stats scope, inherited by the subscriptions, fetches, and
1684	/// groups derived from this handle. Called by a tagged [`broadcast::Consumer`].
1685	pub(crate) fn with_stats(mut self, scope: stats::Scope) -> Self {
1686		self.stats = scope;
1687		self
1688	}
1689
1690	/// The track name this handle is bound to.
1691	pub fn name(&self) -> &str {
1692		&self.name
1693	}
1694
1695	/// Open a live subscription.
1696	///
1697	/// Registers the subscription on the track and returns a [`kio::Pending`] that resolves to the
1698	/// [`Subscriber`] once the track info is available, or the track's abort error (or
1699	/// [`Error::Dropped`]) if it is already closed.
1700	pub fn subscribe(&self, subscription: impl Into<Option<Subscription>>) -> kio::Pending<Subscribing> {
1701		let subscription = kio::Producer::new(subscription.into().unwrap_or_default());
1702
1703		let inner = match &self.inner {
1704			ConsumerKind::Plain(state) => {
1705				// Register the subscription if the track is live. If it is already closed, the
1706				// returned future resolves to the abort error via `Subscribing::poll_ok`.
1707				register_subscription(state.read(), &subscription);
1708				SubscribingKind::Plain(state.clone())
1709			}
1710			// A spliced subscription registers per segment once the subscriber polls.
1711			ConsumerKind::Spliced(resume) => SubscribingKind::Spliced(resume.clone()),
1712		};
1713
1714		kio::Pending::new(Subscribing {
1715			name: self.name.clone(),
1716			inner,
1717			subscription,
1718			stats: self.stats.clone(),
1719		})
1720	}
1721
1722	// Peek at a cached group by sequence without blocking, or `None` if it isn't in the
1723	// cache. A test hook for asserting cache state; the library reads
1724	// `TrackState::cached_group` directly, and callers want `fetch_group`.
1725	#[cfg(test)]
1726	pub(crate) fn peek_group(&self, sequence: u64) -> Option<group::Consumer> {
1727		match &self.inner {
1728			ConsumerKind::Plain(state) => state.read().cached_group(sequence),
1729			// Spliced tracks have no cache of their own; peek the newest segment
1730			// via `fetch_group` instead.
1731			ConsumerKind::Spliced(_) => None,
1732		}
1733	}
1734
1735	/// Fetching a single past group, without holding a live subscription.
1736	///
1737	/// Returns a [`kio::Pending`] that resolves to the [`group::Consumer`]:
1738	/// immediately if the group is cached, otherwise once a [`Dynamic`] serves
1739	/// the request (a wire FETCH for a relay). `options` accepts `None`, a [`group::Fetch`],
1740	/// or `group::Fetch::default()`.
1741	///
1742	/// The returned future resolves to [`Error::NotFound`] when the group can never be served
1743	/// (past the final sequence, or no [`Dynamic`] on the track), or the track's abort error
1744	/// if it's already closed. Concurrent fetches for the same sequence coalesce onto one
1745	/// handler request.
1746	pub fn fetch_group(&self, sequence: u64, options: impl Into<Option<group::Fetch>>) -> kio::Pending<Fetching> {
1747		let options = options.into().unwrap_or_default();
1748
1749		// One fetch per calling context, counted here (coalesced upstream work is
1750		// still one request served). Independent of `subscriptions` and the viewer
1751		// refcount.
1752		self.stats.fetch();
1753
1754		let state = match &self.inner {
1755			ConsumerKind::Plain(state) => state,
1756			// Spliced: routed to the newest segment's (plain) track, waiting for a
1757			// segment to exist if no route has served the track yet.
1758			ConsumerKind::Spliced(resume) => {
1759				return kio::Pending::new(Fetching {
1760					inner: FetchingKind::Spliced(resume.fetch_group(sequence, options)),
1761					stats: self.stats.clone(),
1762				});
1763			}
1764		};
1765
1766		let mut result = None;
1767
1768		// Queue a request only when the group isn't already resolvable from the track
1769		// (cached, aborted, or past-final all resolve through `Fetching::poll` without
1770		// a queue entry).
1771		let (fetch, unresolved) = {
1772			let state = state.read();
1773			(state.fetch.clone(), state.poll_fetch_cached(sequence).is_pending())
1774		};
1775
1776		if unresolved {
1777			let mut fetch = fetch.lock();
1778			if let Some(pending) = fetch.join(&sequence) {
1779				// Join the in-flight attempt for this sequence (queued or already being
1780				// served): share its result channel, raising its priority if ours is higher.
1781				pending.priority = pending.priority.max(options.priority);
1782				result = Some(pending.result.consume());
1783			} else {
1784				// Queue a new attempt. The handler gate is atomic with a handler
1785				// dropping (no fetch stranded on a queue nobody drains); with no
1786				// handler, `Fetching::poll` fails fast instead.
1787				let producer = kio::Producer::<FetchOutcome>::default();
1788				let consumer = producer.consume();
1789				let attempt = PendingFetch {
1790					priority: options.priority,
1791					result: producer,
1792				};
1793				if fetch.insert(sequence, attempt).is_ok() {
1794					result = Some(consumer);
1795				}
1796			}
1797		}
1798
1799		kio::Pending::new(Fetching {
1800			inner: FetchingKind::Plain {
1801				state: state.clone(),
1802				fetch,
1803				sequence,
1804				result,
1805			},
1806			stats: self.stats.clone(),
1807		})
1808	}
1809
1810	/// Resolve the track's [`Info`] without subscribing.
1811	///
1812	/// A [`Consumer`] is a lazy handle, so the info may not be known yet: this waits
1813	/// for the producer to [`Request::accept`] the track (a wire TRACK_INFO round-trip
1814	/// for a relay), and errors with the track's abort error if it closes first.
1815	/// [`Subscriber::info`] is the already-resolved counterpart.
1816	pub fn info(&self) -> kio::Pending<Querying> {
1817		kio::Pending::new(Querying {
1818			inner: match &self.inner {
1819				ConsumerKind::Plain(state) => QueryingKind::Plain(state.clone()),
1820				ConsumerKind::Spliced(resume) => QueryingKind::Spliced(resume.clone()),
1821			},
1822		})
1823	}
1824
1825	/// Return the latest group sequence in the track, or `None` before any group.
1826	pub fn latest(&self) -> Option<u64> {
1827		match &self.inner {
1828			ConsumerKind::Plain(state) => state.read().max_sequence,
1829			ConsumerKind::Spliced(resume) => resume.latest(),
1830		}
1831	}
1832
1833	/// Poll for the track reaching a terminal state: `Ok(())` once it is complete
1834	/// (the final group was produced), `Err` once it closed or aborted before
1835	/// completing. The origin's dispatcher uses this to tell a track that truly
1836	/// ended from one whose serving route died mid-stream.
1837	pub(crate) fn poll_complete(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
1838		let ConsumerKind::Plain(state) = &self.inner else {
1839			// Spliced tracks are compositions; the dispatcher never monitors one.
1840			return Poll::Pending;
1841		};
1842		match ready!(state.poll(waiter, |state| {
1843			if state.is_complete() {
1844				Poll::Ready(())
1845			} else {
1846				Poll::Pending
1847			}
1848		})) {
1849			Ok(_) => Poll::Ready(Ok(())),
1850			// Closed before completing. Read through the returned guard: it holds
1851			// the lock, so re-locking the channel here would deadlock.
1852			Err(closed) => Poll::Ready(Err(closed.abort.clone().unwrap_or(Error::Dropped))),
1853		}
1854	}
1855}
1856
1857/// The pollable state of a [`Consumer::subscribe`]; awaited via the
1858/// [`kio::Pending`] wrapper, whose `DerefMut` exposes [`Self::update`].
1859pub struct Subscribing {
1860	name: Arc<str>,
1861	inner: SubscribingKind,
1862	subscription: kio::Producer<Subscription>,
1863	stats: stats::Scope,
1864}
1865
1866enum SubscribingKind {
1867	Plain(kio::Consumer<TrackState>),
1868	Spliced(super::resume::Consumer),
1869}
1870
1871impl Subscribing {
1872	/// Poll until the peer confirms the subscription, yielding the [`Subscriber`].
1873	/// Errors if the track is aborted or not found.
1874	pub fn poll_ok(&self, waiter: &kio::Waiter) -> Poll<Result<Subscriber>> {
1875		match &self.inner {
1876			SubscribingKind::Plain(state) => {
1877				// Wait until the track info is available
1878				let info = ready!(state.poll(waiter, |state| state.poll_info()))
1879					.map_err(|e| e.abort.clone().unwrap_or(Error::Dropped))??;
1880
1881				Poll::Ready(Ok(Subscriber {
1882					name: self.name.clone(),
1883					info,
1884					inner: SubscriberKind::Plain(PlainSubscriber {
1885						state: state.clone(),
1886						subscription: self.subscription.clone(),
1887						index: 0,
1888						datagram_index: 0,
1889						min_sequence: 0,
1890						next_sequence: 0,
1891						end_sequence: None,
1892					}),
1893					stats: self.stats.clone(),
1894					_stats_sub: self.stats.subscribe(),
1895				}))
1896			}
1897			SubscribingKind::Spliced(resume) => {
1898				// Resolved from the first segment's track. The publisher's latency
1899				// window is applied to each per-session aggregate, not here.
1900				let info = ready!(resume.poll_info(waiter))?;
1901
1902				Poll::Ready(Ok(Subscriber {
1903					name: self.name.clone(),
1904					info,
1905					inner: SubscriberKind::Spliced(Box::new(resume.subscribe_shared(self.subscription.clone()))),
1906					stats: self.stats.clone(),
1907					_stats_sub: self.stats.subscribe(),
1908				}))
1909			}
1910		}
1911	}
1912
1913	/// Change the subscription preferences before (or after) it resolves.
1914	///
1915	/// Returns [`Error::Closed`] if the track already ended; the update is
1916	/// meaningless at that point and can usually be ignored.
1917	pub fn update(&mut self, subscription: Subscription) -> Result<()> {
1918		let mut state = self.subscription.write().map_err(|_| Error::Closed)?;
1919		*state = subscription;
1920		Ok(())
1921	}
1922}
1923
1924impl kio::Pollable for Subscribing {
1925	type Output = Result<Subscriber>;
1926
1927	fn poll(&self, waiter: &kio::Waiter) -> Poll<Self::Output> {
1928		self.poll_ok(waiter)
1929	}
1930}
1931
1932/// The pollable state of a [`Consumer::info`]; awaited via the
1933/// [`kio::Pending`] wrapper.
1934pub struct Querying {
1935	inner: QueryingKind,
1936}
1937
1938enum QueryingKind {
1939	Plain(kio::Consumer<TrackState>),
1940	Spliced(super::resume::Consumer),
1941}
1942
1943impl Querying {
1944	/// Poll until the track's [`Info`] is known, without subscribing to its groups.
1945	pub fn poll_ok(&self, waiter: &kio::Waiter) -> Poll<Result<Info>> {
1946		match &self.inner {
1947			QueryingKind::Plain(state) => {
1948				// Wait until the track info is available
1949				let info = ready!(state.poll(waiter, |state| state.poll_info()))
1950					.map_err(|e| e.abort.clone().unwrap_or(Error::Dropped))??;
1951				Poll::Ready(Ok(info))
1952			}
1953			QueryingKind::Spliced(resume) => resume.poll_info(waiter),
1954		}
1955	}
1956}
1957
1958impl kio::Pollable for Querying {
1959	type Output = Result<Info>;
1960
1961	fn poll(&self, waiter: &kio::Waiter) -> Poll<Self::Output> {
1962		self.poll_ok(waiter)
1963	}
1964}
1965
1966/// A consumer's request for a single past group, handed to a handler via
1967/// [`Dynamic::requested_group`].
1968///
1969/// The handler fulfills it by calling [`Self::accept`], which inserts the group
1970/// into the track cache (resolving every [`Consumer::fetch_group`] that joined the
1971/// attempt) and returns a [`group::Producer`] to fill. A relay typically opens a wire
1972/// FETCH, reads FETCH_OK, then accepts. The request carries its own producer handle,
1973/// so it works the same whether or not the track has been accepted yet.
1974pub struct GroupRequest {
1975	state: kio::Producer<TrackState>,
1976	// To remove this attempt from the fetch state once it resolves.
1977	fetch: kio::Shared<FetchState>,
1978	sequence: u64,
1979	priority: u8,
1980	// Rejections route back to every joined `Fetching`.
1981	result: kio::Producer<FetchOutcome>,
1982	done: bool,
1983}
1984
1985impl GroupRequest {
1986	/// The group sequence the consumer wants.
1987	pub fn sequence(&self) -> u64 {
1988		self.sequence
1989	}
1990
1991	/// The delivery priority the consumer requested for this group.
1992	pub fn priority(&self) -> u8 {
1993		self.priority
1994	}
1995
1996	/// Insert the fetched group into the track cache, resolving the waiting
1997	/// [`Consumer::fetch_group`], and return a [`group::Producer`] to fill.
1998	///
1999	/// The group's timescale comes from the track's [`Info`]. `info` sets that
2000	/// info if the track hasn't been accepted yet (a fetch with no live subscription),
2001	/// and is ignored once accepted. Returns [`Error::Duplicate`] if the group is
2002	/// already present, or the track's abort error if it closed while pending.
2003	pub fn accept(mut self, info: impl Into<Option<Info>>) -> Result<group::Producer> {
2004		self.done = true;
2005		// Cache the group before removing the attempt: the joined fetches resolve
2006		// through the cache, and removal closes their result channel (which alone
2007		// would read as NotFound).
2008		let res = TrackState::modify(&self.state)
2009			.and_then(|mut state| state.insert_group_request(self.sequence, info.into()));
2010		self.remove();
2011		res
2012	}
2013
2014	/// Reject the fetch, resolving every joined [`Consumer::fetch_group`] with `err`.
2015	pub fn reject(mut self, err: Error) {
2016		self.done = true;
2017		// Remove before writing, so a fetch arriving now starts a fresh attempt
2018		// instead of joining a rejected one.
2019		self.remove();
2020		if let Ok(mut outcome) = self.result.write() {
2021			outcome.rejected = Some(err);
2022		}
2023	}
2024
2025	/// Remove this attempt from the fetch state, unless a newer attempt for the same
2026	/// sequence has already replaced it.
2027	fn remove(&self) {
2028		self.fetch
2029			.lock()
2030			.remove_if(&self.sequence, |pending| pending.result.same_channel(&self.result));
2031	}
2032}
2033
2034impl Drop for GroupRequest {
2035	fn drop(&mut self) {
2036		if self.done {
2037			return;
2038		}
2039		self.remove();
2040		if let Ok(mut outcome) = self.result.write() {
2041			outcome.rejected = Some(Error::Dropped);
2042		}
2043	}
2044}
2045
2046/// The pollable state of a [`Consumer::fetch_group`].
2047///
2048/// Awaited via the [`kio::Pending`] wrapper; resolves to the
2049/// [`group::Consumer`] once the group lands in the track's cache (already present,
2050/// or produced after a wire FETCH), or [`Error::NotFound`] if it can never exist.
2051pub struct Fetching {
2052	inner: FetchingKind,
2053	// Egress stats scope, so the resolved group carries a payload meter (and counts
2054	// as one delivered group). Empty (no-op) for an untagged track.
2055	stats: stats::Scope,
2056}
2057
2058enum FetchingKind {
2059	Plain {
2060		state: kio::Consumer<TrackState>,
2061		fetch: kio::Shared<FetchState>,
2062		sequence: u64,
2063		// The joined attempt's result channel; `None` when no handler existed to queue on.
2064		result: Option<kio::Consumer<FetchOutcome>>,
2065	},
2066	/// A spliced track's fetch: waits for a segment, then fetches from it.
2067	Spliced(kio::Pending<super::resume::Fetching>),
2068}
2069
2070impl kio::Pollable for Fetching {
2071	type Output = Result<group::Consumer>;
2072
2073	fn poll(&self, waiter: &kio::Waiter) -> Poll<Self::Output> {
2074		let (state, fetch, sequence, result) = match &self.inner {
2075			FetchingKind::Plain {
2076				state,
2077				fetch,
2078				sequence,
2079				result,
2080			} => (state, fetch, *sequence, result.as_ref()),
2081			FetchingKind::Spliced(spliced) => {
2082				// A fetched group is metered here (once), at the tagged handle: the
2083				// spliced source track it comes from is the origin's own, untagged.
2084				return kio::Pollable::poll(&**spliced, waiter)
2085					.map(|res| res.map(|group| group.with_meter(self.stats.meter())));
2086			}
2087		};
2088
2089		// Track side: the cached group, the abort error, or past-final. The outer
2090		// error is the channel closing without any of those.
2091		match state.poll(waiter, |state| state.poll_fetch_cached(sequence)) {
2092			Poll::Ready(Ok(res)) => return Poll::Ready(res.map(|group| group.with_meter(self.stats.meter()))),
2093			Poll::Ready(Err(closed)) => {
2094				return Poll::Ready(Err(closed.abort.clone().unwrap_or(Error::Dropped)));
2095			}
2096			Poll::Pending => {}
2097		}
2098
2099		// Handler side.
2100		let Some(result) = result else {
2101			// Never queued: no handler existed when the fetch was made. Fail fast while
2102			// that's still true; a handler that appeared since may yet fill the cache.
2103			return match fetch.poll(waiter, |fetch| match fetch.has_handlers() {
2104				false => Poll::Ready(()),
2105				true => Poll::Pending,
2106			}) {
2107				Poll::Ready(_guard) => Poll::Ready(Err(Error::NotFound)),
2108				Poll::Pending => Poll::Pending,
2109			};
2110		};
2111
2112		// A written rejection fails every joined fetch. The channel closing without
2113		// one means the attempt was dropped unserved (its handlers went away).
2114		match result.poll(waiter, |outcome| match &outcome.rejected {
2115			Some(err) => Poll::Ready(err.clone()),
2116			None => Poll::Pending,
2117		}) {
2118			Poll::Ready(Ok(err)) => Poll::Ready(Err(err)),
2119			Poll::Ready(Err(_closed)) => Poll::Ready(Err(Error::NotFound)),
2120			Poll::Pending => Poll::Pending,
2121		}
2122	}
2123}
2124
2125/// A live subscription to a track, used to read its groups.
2126///
2127/// Created via [`Consumer::subscribe`](Consumer::subscribe), or
2128/// directly from a [`Producer`] for an in-process track. Carries this
2129/// subscriber's [`Subscription`] preferences, which feed the producer's aggregate.
2130///
2131/// # Local cursor vs wire preference
2132///
2133/// Group bounds exist at two levels, and setting one does not imply the other:
2134///
2135/// - [`Self::start_at`] / [`Self::end_at`] move **this subscriber's read cursor**. They
2136///   filter exactly what this handle returns and are invisible to the publisher.
2137/// - [`Subscription::group_start`] / [`Subscription::group_end`], set via [`Self::update`],
2138///   are a **request to the publisher**. They're aggregated across every live subscriber
2139///   (earliest start, widest end), so they say what the publisher should send, not what
2140///   this subscriber sees.
2141///
2142/// They stay separate because their scopes differ: a subscriber can't filter by the
2143/// aggregate, since another subscriber can widen it, and the publisher can't honor a
2144/// cursor it's never told about. So setting only the cursor still transfers the skipped
2145/// groups, and setting only the preference still returns groups another subscriber asked
2146/// for. Set both to skip them *and* avoid the transfer.
2147pub struct Subscriber {
2148	name: Arc<str>,
2149	info: Info,
2150	inner: SubscriberKind,
2151	// Egress stats scope, used to meter the groups this subscriber reads. Empty
2152	// (no-op) for an untagged track.
2153	stats: stats::Scope,
2154	// The subscription guard: bumps `subscriptions` (and the egress viewer refcount)
2155	// while held, closing them on drop. Empty (no-op) for an untagged track.
2156	_stats_sub: stats::Subscription,
2157}
2158
2159enum SubscriberKind {
2160	Plain(PlainSubscriber),
2161	// Boxed: the spliced cursor set dwarfs the plain cursor.
2162	Spliced(Box<super::resume::Subscriber>),
2163}
2164
2165/// The cursor state for a subscription over a single (per-session) track.
2166struct PlainSubscriber {
2167	state: kio::Consumer<TrackState>,
2168
2169	subscription: kio::Producer<Subscription>,
2170	/// Arrival-order cursor used by `recv_group`.
2171	index: usize,
2172	/// Arrival-order cursor used by `recv_datagram`, independent of groups.
2173	datagram_index: usize,
2174	/// Minimum sequence to return from any `recv` method. Set by `start_at`.
2175	min_sequence: u64,
2176	/// One past the highest sequence returned by `next_group`.
2177	/// Used only by that method to skip late arrivals; does not affect `recv_group`.
2178	next_sequence: u64,
2179	/// Inclusive upper sequence bound for `next_group`. `None` means no cap. Set by
2180	/// `end_at`; can be raised, lowered, or unset at any time. Groups beyond the
2181	/// cap stay in the producer's cache and become eligible again when the cap
2182	/// rises (or is removed).
2183	end_sequence: Option<u64>,
2184}
2185
2186impl PlainSubscriber {
2187	// A helper to automatically apply Dropped if the state is closed without an error.
2188	fn poll<F, R>(&self, waiter: &kio::Waiter, f: F) -> Poll<Result<R>>
2189	where
2190		F: Fn(&kio::Ref<'_, TrackState>) -> Poll<Result<R>>,
2191	{
2192		Poll::Ready(match ready!(self.state.poll(waiter, f)) {
2193			Ok(res) => res,
2194			// We try to clone abort just in case the function forgot to check for terminal state.
2195			Err(state) => Err(state.abort.clone().unwrap_or(Error::Dropped)),
2196		})
2197	}
2198
2199	fn poll_recv_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2200		let Some((consumer, found_index)) =
2201			ready!(self.poll(waiter, |state| state.poll_recv_group(self.index, self.min_sequence))?)
2202		else {
2203			return Poll::Ready(Ok(None));
2204		};
2205
2206		self.index = found_index + 1;
2207		Poll::Ready(Ok(Some(consumer)))
2208	}
2209
2210	fn poll_recv_datagram(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
2211		let Some((datagram, found_index)) =
2212			ready!(self.poll(waiter, |state| state.poll_recv_datagram(self.datagram_index))?)
2213		else {
2214			return Poll::Ready(Ok(None));
2215		};
2216
2217		self.datagram_index = found_index + 1;
2218		self.next_sequence = self.next_sequence.max(datagram.sequence.saturating_add(1));
2219		Poll::Ready(Ok(Some(datagram)))
2220	}
2221
2222	fn poll_next_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2223		let floor = self.next_sequence.max(self.min_sequence);
2224		let Some(group) = ready!(self.poll(waiter, |state| state.poll_next_in_range(floor, self.end_sequence))?) else {
2225			return Poll::Ready(Ok(None));
2226		};
2227		self.next_sequence = group.sequence.saturating_add(1);
2228		Poll::Ready(Ok(Some(group)))
2229	}
2230
2231	fn poll_read_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Frame>>> {
2232		let lower = self.min_sequence.max(self.next_sequence);
2233		let Some((frame, found_index, sequence)) =
2234			ready!(self.poll(waiter, |state| { state.poll_read_frame(self.index, lower, waiter) })?)
2235		else {
2236			return Poll::Ready(Ok(None));
2237		};
2238
2239		self.index = found_index + 1;
2240		self.next_sequence = sequence.saturating_add(1);
2241		Poll::Ready(Ok(Some(frame)))
2242	}
2243}
2244
2245/// A cloneable handle to a subscriber's delivery preferences.
2246///
2247/// This updates the same subscription as the owning [`Subscriber`] without
2248/// borrowing its read cursor, so callers can change delivery priority, group
2249/// ordering priority, or group bounds while another task is waiting for groups.
2250#[derive(Clone)]
2251pub struct SubscriberControl {
2252	subscription: kio::Producer<Subscription>,
2253}
2254
2255impl SubscriberControl {
2256	/// This subscriber's current preferences.
2257	pub fn subscription(&self) -> Subscription {
2258		self.subscription.read().clone()
2259	}
2260
2261	/// Replace this subscriber's preferences, updating the producer's aggregate.
2262	///
2263	/// Returns [`Error::Closed`] if the track already ended; the update is
2264	/// meaningless at that point and can usually be ignored.
2265	pub fn update(&self, subscription: Subscription) -> Result<()> {
2266		let mut state = self.subscription.write().map_err(|_| Error::Closed)?;
2267		*state = subscription;
2268		Ok(())
2269	}
2270}
2271
2272impl Subscriber {
2273	/// The track's [`Info`], resolved when the subscription was established.
2274	///
2275	/// Free, unlike [`Consumer::info`]: subscribing already waited for the info
2276	/// (SUBSCRIBE_OK on the wire), so a subscriber always has it.
2277	pub fn info(&self) -> &Info {
2278		&self.info
2279	}
2280
2281	/// The track's name, unique within its broadcast.
2282	pub fn name(&self) -> &str {
2283		&self.name
2284	}
2285
2286	/// Create a handle for updating this subscriber's delivery preferences.
2287	pub fn control(&self) -> SubscriberControl {
2288		SubscriberControl {
2289			subscription: match &self.inner {
2290				SubscriberKind::Plain(plain) => plain.subscription.clone(),
2291				SubscriberKind::Spliced(spliced) => spliced.prefs(),
2292			},
2293		}
2294	}
2295
2296	/// Poll for the next group in arrival order, without blocking.
2297	///
2298	/// Returns every group exactly once in the order it landed on the wire, which may be
2299	/// out of sequence due to network reordering or loss. Use [`Self::poll_next_group`] if
2300	/// you only want groups whose sequence number is higher than any previously returned.
2301	///
2302	/// Returns `Poll::Ready(Ok(Some(group)))` when a group is available,
2303	/// `Poll::Ready(Ok(None))` when the track is finished,
2304	/// `Poll::Ready(Err(e))` when the track has been aborted, or
2305	/// `Poll::Pending` when no group is available yet.
2306	pub fn poll_recv_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2307		let meter = self.stats.meter();
2308		let res = match &mut self.inner {
2309			SubscriberKind::Plain(plain) => plain.poll_recv_group(waiter),
2310			SubscriberKind::Spliced(spliced) => spliced.poll_recv_group(waiter),
2311		};
2312		res.map(|res| res.map(|group| group.map(|group| group.with_meter(meter))))
2313	}
2314
2315	/// Receive the next group in arrival order.
2316	///
2317	/// Every group is returned exactly once, in the order it landed on the wire, which may
2318	/// be out of sequence due to network reordering or loss. Use [`Self::next_group`] if you
2319	/// only want groups whose sequence number is higher than any previously returned.
2320	pub async fn recv_group(&mut self) -> Result<Option<group::Consumer>> {
2321		kio::wait(|waiter| self.poll_recv_group(waiter)).await
2322	}
2323
2324	/// Poll for the next datagram in arrival order, without blocking.
2325	///
2326	/// Datagrams are a separate best-effort channel from groups (see
2327	/// [`Producer::append_datagram`]); they share only the sequence namespace. A consumer
2328	/// that falls too far behind silently loses the oldest datagrams.
2329	/// Returning a datagram advances [`Self::poll_next_group`] past that sequence.
2330	///
2331	/// Returns `Poll::Ready(Ok(Some(datagram)))` when one is available,
2332	/// `Poll::Ready(Ok(None))` when the track is finished, `Poll::Ready(Err(e))` when the track
2333	/// is aborted, or `Poll::Pending` when none is buffered yet.
2334	pub fn poll_recv_datagram(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
2335		let meter = self.stats.meter();
2336		let res = match &mut self.inner {
2337			SubscriberKind::Plain(plain) => plain.poll_recv_datagram(waiter),
2338			SubscriberKind::Spliced(spliced) => spliced.poll_recv_datagram(waiter),
2339		};
2340		// Unlike a group (metered lazily as its frames are read), a datagram is
2341		// delivered whole here, so count it as the single-frame group it stands in for.
2342		if let Poll::Ready(Ok(Some(datagram))) = &res {
2343			meter.datagram(datagram.payload.len() as u64);
2344		}
2345		res
2346	}
2347
2348	/// Receive the next datagram in arrival order.
2349	///
2350	/// A best-effort channel parallel to [`Self::recv_group`]; the two share only the sequence
2351	/// namespace. To receive both concurrently from one subscriber, poll [`Self::poll_next_group`]
2352	/// (or [`Self::poll_recv_group`]) and [`Self::poll_recv_datagram`] together in a single `poll`
2353	/// closure (sequential `&mut` borrows), rather than awaiting the two `recv` futures at once.
2354	pub async fn recv_datagram(&mut self) -> Result<Option<Datagram>> {
2355		kio::wait(|waiter| self.poll_recv_datagram(waiter)).await
2356	}
2357
2358	/// Poll for the next group with a higher sequence number than any previously returned.
2359	///
2360	/// Late arrivals (sequence at or below the last returned) are silently skipped, so this
2361	/// produces a monotonically increasing sequence at the cost of dropping out-of-order
2362	/// groups. Use [`Self::poll_recv_group`] to see every group in arrival order instead.
2363	///
2364	/// Honors the cap set by [`Self::end_at`]: groups with sequence past the cap are left
2365	/// in the producer's cache and become eligible again if the cap is raised or removed.
2366	pub fn poll_next_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2367		let meter = self.stats.meter();
2368		let res = match &mut self.inner {
2369			SubscriberKind::Plain(plain) => plain.poll_next_group(waiter),
2370			SubscriberKind::Spliced(spliced) => spliced.poll_next_group(waiter),
2371		};
2372		res.map(|res| res.map(|group| group.map(|group| group.with_meter(meter))))
2373	}
2374
2375	/// Return the next group with a higher sequence number than any previously returned.
2376	///
2377	/// Late arrivals (sequence at or below the last returned) are silently skipped, so this
2378	/// produces a monotonically increasing sequence at the cost of dropping out-of-order
2379	/// groups. Use [`Self::recv_group`] to see every group in arrival order instead.
2380	pub async fn next_group(&mut self) -> Result<Option<group::Consumer>> {
2381		kio::wait(|waiter| self.poll_next_group(waiter)).await
2382	}
2383
2384	/// A helper that calls [`Self::poll_next_group`] and returns its first frame
2385	/// (timestamp and payload), skipping the rest of the group. Intended for
2386	/// single-frame groups (see [`Producer::write_frame`]).
2387	pub fn poll_read_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Frame>>> {
2388		let meter = self.stats.meter();
2389		let res = match &mut self.inner {
2390			SubscriberKind::Plain(plain) => plain.poll_read_frame(waiter),
2391			SubscriberKind::Spliced(spliced) => spliced.poll_read_frame(waiter),
2392		};
2393		// This helper collapses a group to its first frame: count the group, the one
2394		// frame, and the bytes actually read.
2395		if let Poll::Ready(Ok(Some(frame))) = &res {
2396			meter.group();
2397			meter.frames(1);
2398			meter.bytes(frame.payload.len() as u64);
2399		}
2400		res
2401	}
2402
2403	/// Read a single full frame (timestamp and payload) from the next group in
2404	/// sequence order.
2405	///
2406	/// See [`Self::poll_read_frame`] for semantics.
2407	pub async fn read_frame(&mut self) -> Result<Option<frame::Frame>> {
2408		kio::wait(|waiter| self.poll_read_frame(waiter)).await
2409	}
2410
2411	/// Whether `other` was cloned from this subscriber (shares the same underlying state).
2412	pub fn is_clone(&self, other: &Self) -> bool {
2413		match (&self.inner, &other.inner) {
2414			(SubscriberKind::Plain(a), SubscriberKind::Plain(b)) => a.state.same_channel(&b.state),
2415			(SubscriberKind::Spliced(a), SubscriberKind::Spliced(b)) => a.is_clone(b),
2416			_ => false,
2417		}
2418	}
2419
2420	/// Poll for the track's declared final sequence, without blocking.
2421	pub fn poll_finished(&mut self, waiter: &kio::Waiter) -> Poll<Result<u64>> {
2422		match &mut self.inner {
2423			SubscriberKind::Plain(plain) => plain.poll(waiter, |state| state.poll_finished()),
2424			SubscriberKind::Spliced(spliced) => spliced.poll_finished(waiter),
2425		}
2426	}
2427
2428	/// Block until the track declares its end, returning the exclusive final sequence
2429	/// (also the total group count), or the cause on an abort.
2430	///
2431	/// Resolves as soon as the boundary is known, which may be ahead of the live edge
2432	/// when the producer finished via [`Producer::finish_at`]. This reports the declared
2433	/// end, not that every group has arrived: drive [`Self::recv_group`] /
2434	/// [`Self::next_group`] until they yield `None` to observe the track fully drained.
2435	pub async fn finished(&mut self) -> Result<u64> {
2436		kio::wait(|waiter| self.poll_finished(waiter)).await
2437	}
2438
2439	/// Start this subscriber's read cursor at the given sequence.
2440	///
2441	/// A local filter, not a request: it doesn't tell the publisher anything, so the
2442	/// skipped groups are still delivered and simply not returned. To ask the publisher
2443	/// to start there instead, set [`Subscription::group_start`] via [`Self::update`].
2444	/// See [Local cursor vs wire preference](Self#local-cursor-vs-wire-preference).
2445	pub fn start_at(&mut self, sequence: u64) {
2446		match &mut self.inner {
2447			SubscriberKind::Plain(plain) => plain.min_sequence = sequence,
2448			SubscriberKind::Spliced(spliced) => spliced.start_at(sequence),
2449		}
2450	}
2451
2452	/// Cap this subscriber's read cursor at the given sequence (inclusive), or remove the
2453	/// cap entirely.
2454	///
2455	/// Accepts a bare `u64` (cap), `Some(u64)`, or `None` (uncap).
2456	///
2457	/// A local filter, not a request; [`Subscription::group_end`] is the wire-level
2458	/// counterpart. See [Local cursor vs wire preference](Self#local-cursor-vs-wire-preference).
2459	///
2460	/// Affects [`Self::next_group`] only: groups beyond the cap stay in the producer's
2461	/// cache rather than being skipped past, so a later call to [`Self::end_at`] with a
2462	/// higher value (or `None`) makes them available again. Lowering the cap below the
2463	/// consumer's current cursor parks the consumer until the cap is raised.
2464	pub fn end_at(&mut self, sequence: impl Into<Option<u64>>) {
2465		match &mut self.inner {
2466			SubscriberKind::Plain(plain) => plain.end_sequence = sequence.into(),
2467			SubscriberKind::Spliced(spliced) => spliced.end_at(sequence),
2468		}
2469	}
2470
2471	/// This subscriber's current preferences.
2472	pub fn subscription(&self) -> Subscription {
2473		self.control().subscription()
2474	}
2475
2476	/// Replace this subscriber's delivery preferences.
2477	///
2478	/// Stored verbatim; the publisher's latency window is applied to the aggregate, not
2479	/// here (see [`Producer::subscription`]). Returns [`Error::Closed`] if the track
2480	/// already ended; the update is meaningless at that point and can usually be ignored.
2481	pub fn update(&mut self, subscription: Subscription) -> Result<()> {
2482		match &mut self.inner {
2483			SubscriberKind::Plain(plain) => {
2484				let mut state = plain.subscription.write().map_err(|_| Error::Closed)?;
2485				*state = subscription;
2486			}
2487			SubscriberKind::Spliced(spliced) => spliced.update(subscription),
2488		}
2489		Ok(())
2490	}
2491
2492	/// Return the latest sequence number in the track.
2493	pub fn latest(&self) -> Option<u64> {
2494		match &self.inner {
2495			SubscriberKind::Plain(plain) => plain.state.read().max_sequence,
2496			SubscriberKind::Spliced(spliced) => spliced.latest(),
2497		}
2498	}
2499}
2500
2501/// A subscriber asked for a track this broadcast doesn't have yet.
2502///
2503/// Yielded by [`broadcast::Dynamic::requested_track`](crate::broadcast::Dynamic::requested_track),
2504/// or created up front with [`broadcast::Producer::reserve_track`](crate::broadcast::Producer::reserve_track).
2505/// Subscribers block until the request is
2506/// resolved: call [`accept`](Self::accept) to serve it with a [`Producer`], or
2507/// [`reject`](Self::reject) to fail them. Dropping it without either rejects with
2508/// [`Error::Dropped`].
2509///
2510/// Concurrent requests for one name are coalesced, so exactly one of these exists per
2511/// name at a time.
2512pub struct Request {
2513	name: Arc<str>,
2514	// The parent broadcast's info, threaded into the [`Producer`] on accept.
2515	broadcast: Arc<broadcast::Info>,
2516	state: kio::Producer<TrackState>,
2517
2518	// The previous subscription that was combined, used to detect changes.
2519	prev_subscription: Option<Subscription>,
2520
2521	// Shared with the accepted [`Producer`] and every [`Dynamic`]: its `Drop` is the
2522	// teardown, and it stays inert until a producer is minted.
2523	alive: Arc<Alive>,
2524
2525	// A requested track is served on demand, so it counts as fetch-capable from
2526	// birth: a consumer's cache-miss `fetch_group` waits to be served instead of
2527	// racing the producer (e.g. a relay) into creating its own handler. Released
2528	// when the request is accepted or dropped; by then the relay holds its own.
2529	_dynamic: Dynamic,
2530
2531	// Ingress stats scope, threaded into the accepted [`Producer`]. Empty (no-op)
2532	// unless this request was reserved on a tagged broadcast.
2533	stats: stats::Scope,
2534}
2535
2536impl Request {
2537	pub(crate) fn new(broadcast: Arc<broadcast::Info>, name: impl Into<Arc<str>>) -> Self {
2538		let name = name.into();
2539		let state = TrackState::spawn(broadcast.clone());
2540		let alive = Alive::new(name.clone(), state.clone());
2541		let dynamic = Dynamic::new(name.clone(), state.clone(), alive.clone());
2542		Self {
2543			name,
2544			broadcast,
2545			state,
2546			prev_subscription: None,
2547			alive,
2548			_dynamic: dynamic,
2549			stats: stats::Scope::default(),
2550		}
2551	}
2552
2553	/// Attach an ingress stats scope, applied to the [`Producer`] on accept. Set by
2554	/// a tagged [`broadcast::Producer::reserve_track`].
2555	pub(crate) fn with_stats(mut self, scope: stats::Scope) -> Self {
2556		self.stats = scope;
2557		self
2558	}
2559
2560	/// The requested track name.
2561	pub fn name(&self) -> &str {
2562		&self.name
2563	}
2564
2565	/// A [`Consumer`] for the eventual track, usable before the request is accepted.
2566	pub fn consume(&self) -> Consumer {
2567		Consumer::plain(self.name.clone(), self.state.consume())
2568	}
2569
2570	/// Create a [`Dynamic`] handle that serves on-demand fetches of uncached
2571	/// groups, before [`Self::accept`] is even called. A relay creates one to fetch
2572	/// past groups from upstream while (or instead of) serving a live subscription.
2573	pub fn dynamic(&self) -> Dynamic {
2574		Dynamic::new(self.name.clone(), self.state.clone(), self.alive.clone())
2575	}
2576
2577	/// Poll for the request becoming unused (every consumer dropped), so a relay can
2578	/// stop serving and drop the request.
2579	pub fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
2580		self.state.poll_unused(waiter).map(|_| ())
2581	}
2582
2583	/// Serve the request with the given track, resolving every waiting subscriber.
2584	///
2585	/// The name is taken from [`Self::name`]; `info` supplies the remaining knobs
2586	/// (`None` for the defaults). If the track was already aborted, the returned
2587	/// [`Producer`] is inert: writes fail with the abort error, as if it had been
2588	/// aborted immediately after accepting.
2589	pub fn accept(self, info: impl Into<Option<Info>>) -> Producer {
2590		// A closed state means the track was aborted under us. Mirror `reject` and
2591		// tolerate it: the Producer we hand back simply can't write.
2592		if let Ok(mut state) = self.state.write() {
2593			state.install(info.into().unwrap_or_default());
2594		}
2595		// Accepting the request creates the track producer: count it as one ingress
2596		// subscription (closed when the last handle drops). No-op when untagged.
2597		self.alive.publish(Some(&self.stats));
2598		Producer {
2599			name: self.name,
2600			broadcast: self.broadcast,
2601			state: self.state,
2602			prev_subscription: None,
2603			alive: self.alive,
2604			stats: self.stats,
2605		}
2606	}
2607
2608	/// Reject the request, waking all waiting subscribers with `err`.
2609	pub fn reject(self, err: Error) {
2610		if let Ok(mut state) = self.state.write() {
2611			state.abort = Some(err);
2612		}
2613	}
2614
2615	/// The delivery preferences aggregated across everyone waiting on this request,
2616	/// or `None` if nobody is waiting. Useful for sizing the track before accepting.
2617	pub fn subscription(&self) -> Option<Subscription> {
2618		let state = self.state.read();
2619		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
2620		drop(state);
2621		snapshot_subscription(&subs, bound)
2622	}
2623
2624	/// Block until the aggregate [`subscription`](Self::subscription) changes,
2625	/// yielding `None` once nobody is waiting.
2626	pub async fn subscription_changed(&mut self) -> Option<Subscription> {
2627		kio::wait(|waiter| self.poll_subscription_changed(waiter)).await
2628	}
2629
2630	/// Poll counterpart to [`subscription_changed`](Self::subscription_changed).
2631	pub fn poll_subscription_changed(&mut self, waiter: &kio::Waiter) -> Poll<Option<Subscription>> {
2632		let state = self.state.read();
2633		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
2634		drop(state);
2635
2636		let prev = &self.prev_subscription;
2637		let mut combined = None;
2638		let mut guard = ready!(subs.poll(waiter, |subs| {
2639			let next = combined_subscription(subs, bound, waiter);
2640			if &next == prev {
2641				Poll::Pending
2642			} else {
2643				combined = next;
2644				Poll::Ready(())
2645			}
2646		}));
2647		// The aggregate changed: prune any closed subscribers now that we hold the lock.
2648		guard.retain(|sub| !sub.is_closed());
2649		drop(guard);
2650		self.prev_subscription = combined.clone();
2651		Poll::Ready(combined)
2652	}
2653
2654	pub(super) fn weak(&self) -> TrackWeak {
2655		TrackWeak {
2656			name: self.name.clone(),
2657			state: self.state.weak(),
2658		}
2659	}
2660}
2661
2662#[cfg(test)]
2663use futures::FutureExt;
2664
2665#[cfg(test)]
2666#[allow(missing_docs)] // test-only assertion helpers
2667impl Subscriber {
2668	pub fn assert_group(&mut self) -> group::Consumer {
2669		self.recv_group()
2670			.now_or_never()
2671			.expect("group would have blocked")
2672			.expect("would have errored")
2673			.expect("track was closed")
2674	}
2675
2676	pub fn assert_no_group(&mut self) {
2677		assert!(
2678			self.recv_group().now_or_never().is_none(),
2679			"recv_group would not have blocked"
2680		);
2681	}
2682
2683	pub fn assert_not_closed(&mut self) {
2684		assert!(self.finished().now_or_never().is_none(), "should not be closed");
2685	}
2686
2687	pub fn assert_closed(&mut self) {
2688		assert!(self.finished().now_or_never().is_some(), "should be closed");
2689	}
2690
2691	// TODO assert specific errors after implementing PartialEq
2692	pub fn assert_error(&mut self) {
2693		assert!(
2694			self.finished().now_or_never().expect("should not block").is_err(),
2695			"should be error"
2696		);
2697	}
2698
2699	pub fn assert_is_clone(&self, other: &Self) {
2700		assert!(self.is_clone(other), "should be clone");
2701	}
2702
2703	pub fn assert_not_clone(&self, other: &Self) {
2704		assert!(!self.is_clone(other), "should not be clone");
2705	}
2706}
2707
2708#[cfg(test)]
2709mod test {
2710	use super::*;
2711
2712	/// Mint a track for tests with a default parent broadcast, since tracks are
2713	/// normally born from a [`broadcast::Producer`].
2714	fn track_producer(name: impl Into<Arc<str>>, info: impl Into<Option<Info>>) -> Producer {
2715		Producer::new(Arc::new(broadcast::Info::default()), name, info)
2716	}
2717
2718	/// Helper: count live cached groups in state.
2719	fn live_groups(state: &TrackState) -> usize {
2720		state.lookup.len()
2721	}
2722
2723	/// Helper: get the sequence number of the first live group in arrival order.
2724	fn first_live_sequence(state: &TrackState) -> u64 {
2725		state
2726			.arrival
2727			.iter()
2728			.find(|(sequence, stamp)| state.lookup.get(sequence).is_some_and(|slot| slot.stamp == *stamp))
2729			.map(|(sequence, _)| *sequence)
2730			.unwrap()
2731	}
2732
2733	/// Helper: non-blocking datagram receive that must be ready with a datagram.
2734	fn recv_datagram(dg: &mut Subscriber) -> Datagram {
2735		dg.recv_datagram()
2736			.now_or_never()
2737			.expect("datagram would have blocked")
2738			.expect("would have errored")
2739			.expect("track was closed")
2740	}
2741
2742	#[tokio::test]
2743	async fn append_datagram_shares_group_sequence() {
2744		let mut producer = track_producer("test", None);
2745		let ts = Timestamp::from_millis(10).unwrap();
2746
2747		// Interleave groups and datagrams: they draw from one monotonic counter.
2748		assert_eq!(producer.append_group().unwrap().sequence, 0);
2749		assert_eq!(producer.append_datagram(ts, &b"a"[..]).unwrap(), 1);
2750		assert_eq!(producer.append_group().unwrap().sequence, 2);
2751		assert_eq!(producer.append_datagram(ts, &b"b"[..]).unwrap(), 3);
2752		assert_eq!(producer.latest(), Some(3));
2753	}
2754
2755	#[tokio::test]
2756	async fn append_datagram_roundtrip() {
2757		let mut producer = track_producer("test", None);
2758		let mut dg = producer.subscribe(None);
2759
2760		let ts = Timestamp::from_millis(42).unwrap();
2761		let seq = producer.append_datagram(ts, &b"hello"[..]).unwrap();
2762
2763		let got = recv_datagram(&mut dg);
2764		assert_eq!(got.sequence, seq);
2765		assert_eq!(got.timestamp, ts);
2766		assert_eq!(&got.payload[..], b"hello");
2767	}
2768
2769	#[tokio::test]
2770	async fn write_datagram_preserves_sequence() {
2771		let mut producer = track_producer("test", None);
2772		let mut dg = producer.subscribe(None);
2773
2774		let ts = Timestamp::from_millis(5).unwrap();
2775		// A relay forwarding an upstream datagram keeps its sequence number.
2776		producer
2777			.write_datagram(Datagram {
2778				sequence: 100,
2779				timestamp: ts,
2780				payload: bytes::Bytes::from_static(b"x"),
2781			})
2782			.unwrap();
2783
2784		assert_eq!(recv_datagram(&mut dg).sequence, 100);
2785		// max_sequence advanced, so the next appended group/datagram continues past it.
2786		assert_eq!(producer.append_group().unwrap().sequence, 101);
2787	}
2788
2789	#[tokio::test]
2790	async fn recv_datagram_advances_ordered_group_cursor() {
2791		let mut producer = track_producer("test", None);
2792		let mut subscriber = producer.subscribe(None);
2793		let ts = Timestamp::from_millis(5).unwrap();
2794
2795		producer
2796			.write_datagram(Datagram {
2797				sequence: 5,
2798				timestamp: ts,
2799				payload: bytes::Bytes::from_static(b"x"),
2800			})
2801			.unwrap();
2802		assert_eq!(recv_datagram(&mut subscriber).sequence, 5);
2803
2804		producer.create_group(group::Info { sequence: 3 }).unwrap();
2805		producer.create_group(group::Info { sequence: 6 }).unwrap();
2806
2807		let group = subscriber
2808			.next_group()
2809			.now_or_never()
2810			.expect("group would have blocked")
2811			.expect("would have errored")
2812			.expect("track was closed");
2813		assert_eq!(group.sequence, 6);
2814	}
2815
2816	#[tokio::test]
2817	async fn datagram_normalized_to_track_timescale() {
2818		let info = Info::default().with_timescale(Timescale::MICRO);
2819		let mut producer = track_producer("test", info);
2820		let mut dg = producer.subscribe(None);
2821
2822		// Supplied at millis; stored/emitted at the track's micro timescale.
2823		producer
2824			.append_datagram(Timestamp::from_millis(2).unwrap(), &b"z"[..])
2825			.unwrap();
2826		let got = recv_datagram(&mut dg);
2827		assert_eq!(got.timestamp.scale(), Timescale::MICRO);
2828		assert_eq!(got.timestamp.value(), 2_000);
2829	}
2830
2831	#[tokio::test]
2832	async fn datagram_rejects_oversized() {
2833		let mut producer = track_producer("test", None);
2834		let big = bytes::Bytes::from(vec![0u8; crate::model::datagram::MAX_DATAGRAM_PAYLOAD + 1]);
2835		let ts = Timestamp::from_millis(0).unwrap();
2836		assert!(matches!(
2837			producer.append_datagram(ts, big.clone()),
2838			Err(Error::FrameTooLarge)
2839		));
2840		assert!(matches!(
2841			producer.write_datagram(Datagram {
2842				sequence: 0,
2843				timestamp: ts,
2844				payload: big,
2845			}),
2846			Err(Error::FrameTooLarge)
2847		));
2848	}
2849
2850	#[tokio::test]
2851	async fn datagram_fanout_to_subscribers() {
2852		let mut producer = track_producer("test", None);
2853		// Two independent subscribers, each with its own datagram cursor.
2854		let mut a = producer.subscribe(None);
2855		let mut b = producer.subscribe(None);
2856		let ts = Timestamp::from_millis(1).unwrap();
2857
2858		producer.append_datagram(ts, &b"first"[..]).unwrap();
2859		producer.append_datagram(ts, &b"second"[..]).unwrap();
2860
2861		// Both receive every datagram in order, independently.
2862		assert_eq!(&recv_datagram(&mut a).payload[..], b"first");
2863		assert_eq!(&recv_datagram(&mut a).payload[..], b"second");
2864		assert_eq!(&recv_datagram(&mut b).payload[..], b"first");
2865		assert_eq!(&recv_datagram(&mut b).payload[..], b"second");
2866	}
2867
2868	#[tokio::test]
2869	async fn datagram_evicts_stale() {
2870		tokio::time::pause();
2871
2872		let mut producer = track_producer("test", None);
2873		let mut dg = producer.subscribe(None);
2874		let ts = Timestamp::from_millis(0).unwrap();
2875
2876		producer.append_datagram(ts, &b"old"[..]).unwrap(); // sequence 0
2877
2878		// Age past the send-buffer window, then push a fresh datagram: the stale one is evicted.
2879		tokio::time::advance(MAX_DATAGRAM_AGE + Duration::from_millis(10)).await;
2880		producer.append_datagram(ts, &b"new"[..]).unwrap(); // sequence 1
2881
2882		// A lagging consumer resumes at the oldest still-buffered datagram (the fresh one).
2883		let got = recv_datagram(&mut dg);
2884		assert_eq!(got.sequence, 1);
2885		assert_eq!(&got.payload[..], b"new");
2886	}
2887
2888	#[tokio::test]
2889	async fn datagram_recv_pends_until_written() {
2890		let mut producer = track_producer("test", None);
2891		let mut dg = producer.subscribe(None);
2892
2893		assert!(
2894			dg.recv_datagram().now_or_never().is_none(),
2895			"should block with no datagrams"
2896		);
2897
2898		producer
2899			.append_datagram(Timestamp::from_millis(0).unwrap(), &b"go"[..])
2900			.unwrap();
2901		assert_eq!(&recv_datagram(&mut dg).payload[..], b"go");
2902	}
2903
2904	/// Exercises the full producer -> publisher-encode -> subscriber-decode -> producer seam
2905	/// (everything but the QUIC datagram send/recv), catching any field-order mismatch between
2906	/// the wire codec and the model.
2907	#[tokio::test]
2908	async fn datagram_wire_roundtrip_between_tracks() {
2909		use crate::coding::{Decode, Encode};
2910		use crate::lite;
2911
2912		let version = lite::Version::Lite05;
2913
2914		// Origin publishes a datagram; the publisher reads it and encodes the wire body.
2915		let mut origin = track_producer("test", None);
2916		let mut origin_dg = origin.subscribe(None);
2917		let ts = Timestamp::from_millis(7).unwrap();
2918		let seq = origin.append_datagram(ts, &b"payload"[..]).unwrap();
2919
2920		let d = recv_datagram(&mut origin_dg);
2921		let body = lite::Datagram {
2922			subscribe: 5,
2923			sequence: d.sequence,
2924			timestamp: d.timestamp.value(),
2925			payload: d.payload.clone(),
2926		}
2927		.encode_bytes(version)
2928		.unwrap();
2929
2930		// Subscriber decodes the body and writes it downstream, preserving the sequence.
2931		let mut slice = &body[..];
2932		let wire = lite::Datagram::decode(&mut slice, version).unwrap();
2933		let mut downstream = track_producer("test", None);
2934		let mut downstream_dg = downstream.subscribe(None);
2935		downstream
2936			.write_datagram(Datagram {
2937				sequence: wire.sequence,
2938				timestamp: Timestamp::new(wire.timestamp, Timescale::MILLI).unwrap(),
2939				payload: wire.payload,
2940			})
2941			.unwrap();
2942
2943		let got = recv_datagram(&mut downstream_dg);
2944		assert_eq!(got.sequence, seq);
2945		assert_eq!(got.timestamp, ts);
2946		assert_eq!(&got.payload[..], b"payload");
2947	}
2948
2949	#[tokio::test]
2950	async fn evict_expired_groups() {
2951		tokio::time::pause();
2952
2953		let mut producer = track_producer("test", None);
2954
2955		// Create 3 groups at time 0.
2956		producer.append_group().unwrap(); // seq 0
2957		producer.append_group().unwrap(); // seq 1
2958		producer.append_group().unwrap(); // seq 2
2959
2960		{
2961			let state = producer.state.read();
2962			assert_eq!(live_groups(&state), 3);
2963			assert_eq!(state.offset, 0);
2964		}
2965
2966		// Advance time past the eviction threshold.
2967		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
2968
2969		// Append a new group to trigger eviction.
2970		producer.append_group().unwrap(); // seq 3
2971
2972		// Groups 0, 1, 2 are expired but seq 3 (the live edge) is kept. Their arrival
2973		// entries no longer resolve, so the leading ones are trimmed and the offset
2974		// advances past them.
2975		{
2976			let state = producer.state.read();
2977			assert_eq!(live_groups(&state), 1);
2978			assert_eq!(first_live_sequence(&state), 3);
2979			assert_eq!(state.offset, 3);
2980			assert!(!state.lookup.contains_key(&0));
2981			assert!(!state.lookup.contains_key(&1));
2982			assert!(!state.lookup.contains_key(&2));
2983			assert!(state.lookup.contains_key(&3));
2984		}
2985	}
2986
2987	/// A group whose frames outlive `latency_max` is aged out when the next group starts, but
2988	/// a subscriber that already drained it must still see the clean end of group. Otherwise a
2989	/// track with long groups (a per-minute rollup, say) fails its readers at every boundary.
2990	#[tokio::test]
2991	async fn aging_out_a_finished_group_keeps_the_clean_end() {
2992		tokio::time::pause();
2993
2994		let mut producer = track_producer("test", None);
2995		let mut group = producer.create_group(group::Info { sequence: 0 }).unwrap();
2996		let mut consumer = group.consume();
2997
2998		group
2999			.write_frame(Timestamp::from_millis(0).unwrap(), b"hello".as_slice())
3000			.unwrap();
3001		assert_eq!(consumer.next_frame().await.unwrap().unwrap().size, 5);
3002
3003		// The group stays open well past latency_max, then the next period starts.
3004		tokio::time::advance(DEFAULT_LATENCY_MAX * 12).await;
3005		group.finish().unwrap();
3006		let _next = producer.create_group(group::Info { sequence: 1 }).unwrap();
3007
3008		assert!(consumer.next_frame().await.unwrap().is_none());
3009	}
3010
3011	#[tokio::test]
3012	async fn evict_keeps_max_sequence() {
3013		tokio::time::pause();
3014
3015		let mut producer = track_producer("test", None);
3016		producer.append_group().unwrap(); // seq 0
3017
3018		// Advance time past threshold.
3019		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3020
3021		// Append another group; seq 0 is expired and evicted.
3022		producer.append_group().unwrap(); // seq 1
3023
3024		{
3025			let state = producer.state.read();
3026			assert_eq!(live_groups(&state), 1);
3027			assert_eq!(first_live_sequence(&state), 1);
3028			assert_eq!(state.offset, 1);
3029		}
3030	}
3031
3032	#[tokio::test]
3033	async fn no_eviction_when_fresh() {
3034		tokio::time::pause();
3035
3036		let mut producer = track_producer("test", None);
3037		producer.append_group().unwrap(); // seq 0
3038		producer.append_group().unwrap(); // seq 1
3039		producer.append_group().unwrap(); // seq 2
3040
3041		{
3042			let state = producer.state.read();
3043			assert_eq!(live_groups(&state), 3);
3044			assert_eq!(state.offset, 0);
3045		}
3046	}
3047
3048	#[tokio::test]
3049	async fn consumer_skips_evicted_groups() {
3050		tokio::time::pause();
3051
3052		let mut producer = track_producer("test", None);
3053		producer.append_group().unwrap(); // seq 0
3054
3055		let mut consumer = producer.subscribe(None);
3056
3057		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3058		producer.append_group().unwrap(); // seq 1
3059
3060		// Group 0 was evicted. Consumer should get group 1.
3061		let group = consumer.assert_group();
3062		assert_eq!(group.sequence, 1);
3063	}
3064
3065	#[tokio::test]
3066	async fn cache_age_controls_eviction() {
3067		tokio::time::pause();
3068
3069		// A shorter cache evicts sooner than the default.
3070		let mut producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(1)));
3071		producer.append_group().unwrap(); // seq 0
3072
3073		// Past the custom budget but well within DEFAULT_LATENCY_MAX.
3074		tokio::time::advance(Duration::from_secs(2)).await;
3075		producer.append_group().unwrap(); // seq 1
3076
3077		// Seq 0 is gone because the publisher only keeps groups for 1s.
3078		let state = producer.state.read();
3079		assert_eq!(live_groups(&state), 1);
3080		assert_eq!(first_live_sequence(&state), 1);
3081	}
3082
3083	#[test]
3084	fn latency_max_clamped_to_cache() {
3085		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3086
3087		// A latency budget beyond the cache is capped in the aggregate; a group can't be
3088		// waited for longer than the publisher keeps it. The subscriber's own preference
3089		// is stored verbatim, so what it asked for stays readable.
3090		let mut subscriber = producer.subscribe(Subscription::default().with_latency_max(Duration::from_secs(10)));
3091		assert_eq!(subscriber.subscription().latency_max, Duration::from_secs(10));
3092		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3093
3094		// A budget within the cache is left alone, and ZERO (skip immediately) stays ZERO.
3095		subscriber
3096			.update(Subscription::default().with_latency_max(Duration::from_millis(500)))
3097			.unwrap();
3098		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_millis(500));
3099
3100		subscriber
3101			.update(Subscription::default().with_latency_max(Duration::ZERO))
3102			.unwrap();
3103		assert_eq!(producer.subscription().unwrap().latency_max, Duration::ZERO);
3104	}
3105
3106	/// Mint a track under an origin whose retention ceiling is `cap`, so the
3107	/// track's own window is clamped down to it on bind.
3108	fn track_producer_capped(name: impl Into<Arc<str>>, info: Info, cap: Duration) -> Producer {
3109		let origin = crate::origin::Info::default().with_cache_duration(cap);
3110		Producer::new(Arc::new(broadcast::Info { origin }), name, info)
3111	}
3112
3113	#[test]
3114	fn origin_cache_duration_clamps_latency_max() {
3115		// A publisher asking to keep groups for a minute is capped to the origin's 1s
3116		// ceiling; a publisher already below the ceiling is left alone (it's a min).
3117		let capped = track_producer_capped(
3118			"test",
3119			Info::default().with_latency_max(Duration::from_secs(60)),
3120			Duration::from_secs(1),
3121		);
3122		assert_eq!(capped.state.read().latency_bound(), Some(Duration::from_secs(1)));
3123
3124		let under = track_producer_capped(
3125			"test",
3126			Info::default().with_latency_max(Duration::from_millis(500)),
3127			Duration::from_secs(1),
3128		);
3129		assert_eq!(under.state.read().latency_bound(), Some(Duration::from_millis(500)));
3130	}
3131
3132	#[tokio::test]
3133	async fn origin_cache_duration_caps_eviction() {
3134		tokio::time::pause();
3135
3136		// The publisher wants a 60s window, but the origin caps retention at 1s.
3137		let mut producer = track_producer_capped(
3138			"test",
3139			Info::default().with_latency_max(Duration::from_secs(60)),
3140			Duration::from_secs(1),
3141		);
3142		producer.append_group().unwrap(); // seq 0
3143
3144		// Past the origin ceiling but far within the publisher's own 60s window.
3145		tokio::time::advance(Duration::from_secs(2)).await;
3146		producer.append_group().unwrap(); // seq 1
3147
3148		// Seq 0 is evicted anyway: the origin ceiling wins over the larger publisher window.
3149		let state = producer.state.read();
3150		assert_eq!(live_groups(&state), 1);
3151		assert_eq!(first_live_sequence(&state), 1);
3152	}
3153
3154	#[test]
3155	fn latency_max_clamped_via_every_update_path() {
3156		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3157		let over = Subscription::default().with_latency_max(Duration::from_secs(10));
3158
3159		// The clamp lives in the aggregation, so it applies no matter which entry point
3160		// wrote the raw preference. Previously only `Subscriber::update` clamped.
3161		let mut subscriber = producer.subscribe(over.clone());
3162		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3163
3164		subscriber.control().update(over.clone()).unwrap();
3165		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3166
3167		subscriber.update(over).unwrap();
3168		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3169	}
3170
3171	#[test]
3172	fn latency_max_aggregate_clamps_the_max_across_subscribers() {
3173		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3174
3175		// The aggregate takes the max, then clamps once. Equivalent to clamping each
3176		// subscriber first, since `min` distributes over `max`.
3177		let _a = producer.subscribe(Subscription::default().with_latency_max(Duration::from_millis(500)));
3178		let _b = producer.subscribe(Subscription::default().with_latency_max(Duration::from_secs(10)));
3179
3180		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3181	}
3182
3183	#[test]
3184	fn subscriber_control_updates_while_read_future_is_pending() {
3185		let producer = track_producer("test", None);
3186		let mut subscriber = producer.subscribe(None);
3187		let control = subscriber.control();
3188
3189		let mut recv = Box::pin(subscriber.recv_group());
3190		assert!(recv.as_mut().now_or_never().is_none());
3191
3192		control
3193			.update(Subscription::default().with_priority(7).with_ordered(false))
3194			.unwrap();
3195
3196		let aggregate = producer.subscription().expect("expected an active subscription");
3197		assert_eq!(aggregate.priority, 7);
3198		assert!(!aggregate.ordered);
3199	}
3200
3201	#[test]
3202	fn dropped_subscriber_leaves_no_ghost_in_aggregate() {
3203		// Regression (#2351): a departed subscriber must not keep contributing its
3204		// last subscription to the aggregate. When it did, a relay's linger loop
3205		// never observed the track going idle, and an identical viewer reconnecting
3206		// within the linger window was reset when the stale timer fired.
3207		let mut producer = track_producer("test", None);
3208		let a = producer.subscribe(Subscription::default().with_priority(5));
3209
3210		// Prime the change cursor: the aggregate currently has one subscriber.
3211		let waiter = kio::Waiter::noop();
3212		assert!(
3213			matches!(producer.poll_subscription_changed(&waiter), Poll::Ready(Ok(Some(_)))),
3214			"one live subscriber should aggregate to Some",
3215		);
3216
3217		// The only subscriber leaves.
3218		drop(a);
3219
3220		// The aggregate must report the drop to None, not the ghost's last value.
3221		assert!(
3222			matches!(producer.poll_subscription_changed(&waiter), Poll::Ready(Ok(None))),
3223			"a dropped subscriber must not linger in the aggregate",
3224		);
3225
3226		// And the snapshot used by the linger loop must agree.
3227		assert!(
3228			producer.subscription().is_none(),
3229			"snapshot must exclude a dropped subscriber",
3230		);
3231	}
3232
3233	#[test]
3234	fn dropped_subscriber_wakes_the_aggregate() {
3235		// The value being right isn't enough: nothing re-polls the aggregate on its
3236		// own, so the drop has to wake the waiter. A subscriber contributing demand
3237		// takes `kio::Consumer::poll`'s Ready path, which registers no waiter, so
3238		// the departure needs the closed waiter armed explicitly. Without it a relay
3239		// never learns the last viewer left and holds the upstream subscription (and
3240		// the upstream's viewer count) open forever.
3241		use std::sync::atomic::{AtomicBool, Ordering};
3242
3243		let mut producer = track_producer("test", None);
3244		let a = producer.subscribe(Subscription::default().with_priority(5));
3245
3246		let woken = Arc::new(AtomicBool::new(false));
3247		let waiter = kio::Waiter::new(futures::task::waker(Arc::new(FlagWake(woken.clone()))));
3248
3249		// Prime the cursor, then confirm the next poll parks.
3250		assert!(matches!(
3251			producer.poll_subscription_changed(&waiter),
3252			Poll::Ready(Ok(Some(_)))
3253		));
3254		assert!(
3255			producer.poll_subscription_changed(&waiter).is_pending(),
3256			"the aggregate is unchanged, so this poll must park",
3257		);
3258		assert!(!woken.load(Ordering::SeqCst), "nothing happened yet");
3259
3260		drop(a);
3261		assert!(
3262			woken.load(Ordering::SeqCst),
3263			"the last subscriber leaving must wake the aggregate watcher",
3264		);
3265	}
3266
3267	/// An [`ArcWake`] that just records that it was woken.
3268	struct FlagWake(Arc<std::sync::atomic::AtomicBool>);
3269
3270	impl futures::task::ArcWake for FlagWake {
3271		fn wake_by_ref(arc_self: &Arc<Self>) {
3272			arc_self.0.store(true, std::sync::atomic::Ordering::SeqCst);
3273		}
3274	}
3275
3276	#[tokio::test]
3277	async fn out_of_order_max_sequence_at_front() {
3278		tokio::time::pause();
3279
3280		let mut producer = track_producer("test", None);
3281
3282		// Arrive out of order: seq 5 first, then 3, then 4.
3283		producer.create_group(group::Info { sequence: 5 }).unwrap();
3284		producer.create_group(group::Info { sequence: 3 }).unwrap();
3285		producer.create_group(group::Info { sequence: 4 }).unwrap();
3286
3287		// max_sequence = 5, which is at the front of the VecDeque.
3288		{
3289			let state = producer.state.read();
3290			assert_eq!(state.max_sequence, Some(5));
3291		}
3292
3293		// Expire all three groups.
3294		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3295
3296		// Append seq 6 (becomes new max_sequence).
3297		producer.append_group().unwrap(); // seq 6
3298
3299		// Seq 3, 4, 5 are all expired. Seq 5 was the old max_sequence but now 6 is.
3300		// All old groups are evicted.
3301		{
3302			let state = producer.state.read();
3303			assert_eq!(live_groups(&state), 1);
3304			assert_eq!(first_live_sequence(&state), 6);
3305			assert!(!state.lookup.contains_key(&3));
3306			assert!(!state.lookup.contains_key(&4));
3307			assert!(!state.lookup.contains_key(&5));
3308			assert!(state.lookup.contains_key(&6));
3309		}
3310	}
3311
3312	#[tokio::test]
3313	async fn max_sequence_at_front_blocks_trim() {
3314		tokio::time::pause();
3315
3316		let mut producer = track_producer("test", None);
3317
3318		// Arrive: seq 5, then seq 3.
3319		producer.create_group(group::Info { sequence: 5 }).unwrap();
3320
3321		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3322
3323		// Seq 3 arrives late; max_sequence is still 5 (at front).
3324		producer.create_group(group::Info { sequence: 3 }).unwrap();
3325
3326		// Seq 5 is max_sequence (protected). Seq 3 is not expired (just created).
3327		// Nothing should be evicted.
3328		{
3329			let state = producer.state.read();
3330			assert_eq!(live_groups(&state), 2);
3331			assert_eq!(state.offset, 0);
3332		}
3333
3334		// Expire seq 3 as well.
3335		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3336
3337		// Seq 2 arrives late, triggering eviction.
3338		producer.create_group(group::Info { sequence: 2 }).unwrap();
3339
3340		// Seq 5 is the live edge (protected) and still resolves at the front of
3341		// `arrival`, so nothing is trimmed and the offset stays. Seq 3 expired out of
3342		// `lookup`, leaving a hole its arrival entry no longer resolves; seq 2 is
3343		// fresh and kept.
3344		{
3345			let state = producer.state.read();
3346			assert_eq!(live_groups(&state), 2);
3347			assert_eq!(state.offset, 0);
3348			assert!(state.lookup.contains_key(&5));
3349			assert!(!state.lookup.contains_key(&3));
3350			assert!(state.lookup.contains_key(&2));
3351		}
3352
3353		// Consumer should still be able to read through the hole.
3354		let mut consumer = producer.subscribe(None);
3355		let group = consumer.assert_group();
3356		// consume() starts at index 0; the first arrival entry that still resolves is seq 5.
3357		assert_eq!(group.sequence, 5);
3358	}
3359
3360	#[tokio::test]
3361	async fn abort_clears_cached_groups() {
3362		let mut producer = track_producer("test", None);
3363		producer.append_group().unwrap();
3364		producer.append_group().unwrap();
3365
3366		// A stale consumer that never drains must not pin the cached groups.
3367		let mut consumer = producer.subscribe(None);
3368		assert_eq!(live_groups(&producer.state.read()), 2);
3369
3370		producer.clone().abort(Error::Cancel).unwrap();
3371
3372		{
3373			let state = producer.state.read();
3374			assert!(state.lookup.is_empty(), "cached groups should be dropped on abort");
3375			assert!(state.arrival.is_empty());
3376			assert!(state.evict.is_empty());
3377		}
3378
3379		// The consumer now surfaces the abort error rather than the leftover cache.
3380		let result = consumer.recv_group().now_or_never().expect("should not block");
3381		assert!(matches!(result, Err(Error::Cancel)));
3382	}
3383
3384	#[tokio::test]
3385	async fn drop_unfinished_clears_cached_groups() {
3386		let producer = track_producer("test", None);
3387		let mut writer = producer.clone();
3388		writer.append_group().unwrap();
3389
3390		// A stale consumer keeps the channel (and thus the cache) alive.
3391		let mut consumer = producer.subscribe(None);
3392		assert_eq!(live_groups(&producer.state.read()), 1);
3393
3394		// Drop every producer without finishing: the cache is released.
3395		drop(writer);
3396		drop(producer);
3397
3398		let result = consumer.recv_group().now_or_never().expect("should not block");
3399		assert!(matches!(result, Err(Error::Dropped)));
3400	}
3401
3402	#[tokio::test]
3403	async fn drop_finished_keeps_cached_groups() {
3404		let mut producer = track_producer("test", None);
3405		producer.append_group().unwrap();
3406		producer.finish().unwrap();
3407
3408		let mut consumer = producer.subscribe(None);
3409		drop(producer);
3410
3411		// A cleanly finished track keeps its cache so the consumer can still drain.
3412		assert_eq!(consumer.assert_group().sequence, 0);
3413		let done = consumer.recv_group().now_or_never().expect("should not block").unwrap();
3414		assert!(done.is_none(), "consumer should drain then see clean finish");
3415	}
3416
3417	#[test]
3418	fn append_finish_cannot_be_rewritten() {
3419		let mut producer = track_producer("test", None);
3420
3421		// Finishing an empty track is valid (fin = 0, total groups = 0).
3422		assert!(producer.finish().is_ok());
3423		assert!(producer.finish().is_err());
3424		assert!(producer.append_group().is_err());
3425	}
3426
3427	#[test]
3428	fn finish_after_groups() {
3429		let mut producer = track_producer("test", None);
3430
3431		producer.append_group().unwrap();
3432		assert!(producer.finish().is_ok());
3433		assert!(producer.finish().is_err());
3434		assert!(producer.append_group().is_err());
3435	}
3436
3437	#[test]
3438	fn finish_at_rejects_a_boundary_at_or_below_the_live_edge() {
3439		let mut producer = track_producer("test", None);
3440		producer.create_group(group::Info { sequence: 5 }).unwrap();
3441
3442		// The boundary is exclusive, so it must be strictly above the highest produced
3443		// group. 5 or below would orphan groups that already exist.
3444		assert!(producer.finish_at(4).is_err());
3445		assert!(producer.finish_at(5).is_err());
3446		assert!(producer.finish_at(6).is_ok());
3447
3448		{
3449			let state = producer.state.read();
3450			assert_eq!(state.final_sequence, Some(6));
3451		}
3452
3453		// Re-finishing is rejected, and no group at or above the boundary can be created.
3454		assert!(producer.finish_at(6).is_err());
3455		assert!(producer.create_group(group::Info { sequence: 4 }).is_ok());
3456		assert!(producer.create_group(group::Info { sequence: 6 }).is_err());
3457	}
3458
3459	#[test]
3460	fn final_sequence_reports_the_declared_boundary() {
3461		let mut producer = track_producer("test", None);
3462		assert_eq!(producer.final_sequence(), None);
3463
3464		producer.create_group(group::Info { sequence: 5 }).unwrap();
3465		assert_eq!(producer.final_sequence(), None, "a group does not declare a boundary");
3466
3467		producer.finish_at(9).unwrap();
3468		assert_eq!(producer.final_sequence(), Some(9));
3469
3470		// finish() would try to declare a second boundary, so callers check first.
3471		assert!(producer.finish().is_err());
3472	}
3473
3474	#[test]
3475	fn final_sequence_reports_the_live_edge_after_finish() {
3476		let mut producer = track_producer("test", None);
3477		producer.create_group(group::Info { sequence: 5 }).unwrap();
3478		producer.finish().unwrap();
3479		assert_eq!(producer.final_sequence(), Some(6));
3480	}
3481
3482	#[tokio::test]
3483	async fn finish_at_declares_a_future_boundary() {
3484		let mut producer = track_producer("test", None);
3485		producer.create_group(group::Info { sequence: 5 }).unwrap();
3486
3487		// Learn the track ends at group 6 (exclusive 7) while the live edge is still 5.
3488		producer.finish_at(7).unwrap();
3489
3490		let mut consumer = producer.subscribe(None);
3491		assert_eq!(consumer.assert_group().sequence, 5);
3492
3493		// The boundary is known immediately, but the track isn't done: group 6 is still
3494		// outstanding, so the consumer parks rather than seeing end-of-stream.
3495		let boundary = consumer
3496			.finished()
3497			.now_or_never()
3498			.expect("boundary is known immediately")
3499			.expect("would have errored");
3500		assert_eq!(boundary, 7);
3501		assert!(
3502			consumer.recv_group().now_or_never().is_none(),
3503			"should wait for the outstanding group"
3504		);
3505
3506		// The trailing group arrives (below the boundary), then the track completes.
3507		producer.create_group(group::Info { sequence: 6 }).unwrap();
3508		assert_eq!(consumer.assert_group().sequence, 6);
3509		let done = consumer
3510			.recv_group()
3511			.now_or_never()
3512			.expect("should not block")
3513			.expect("would have errored");
3514		assert!(done.is_none(), "track completes once the boundary is reached");
3515	}
3516
3517	#[tokio::test]
3518	async fn recv_group_finishes_without_waiting_for_gaps() {
3519		let mut producer = track_producer("test", None);
3520		producer.create_group(group::Info { sequence: 1 }).unwrap();
3521		producer.finish().unwrap();
3522
3523		let mut consumer = producer.subscribe(None);
3524		assert_eq!(consumer.assert_group().sequence, 1);
3525
3526		let done = consumer
3527			.recv_group()
3528			.now_or_never()
3529			.expect("should not block")
3530			.expect("would have errored");
3531		assert!(done.is_none(), "track should finish without waiting for gaps");
3532	}
3533
3534	#[tokio::test]
3535	async fn next_group_skips_late_arrivals() {
3536		let mut producer = track_producer("test", None);
3537		let mut consumer = producer.subscribe(None);
3538
3539		// Seq 5 arrives first.
3540		producer.create_group(group::Info { sequence: 5 }).unwrap();
3541		let group = consumer
3542			.next_group()
3543			.now_or_never()
3544			.expect("should not block")
3545			.expect("would have errored")
3546			.expect("track should not be closed");
3547		assert_eq!(group.sequence, 5);
3548
3549		// Seq 3 arrives late, skipped because 3 <= 5.
3550		producer.create_group(group::Info { sequence: 3 }).unwrap();
3551		// Seq 4 arrives late and is also skipped.
3552		producer.create_group(group::Info { sequence: 4 }).unwrap();
3553		// Seq 7 arrives and is returned.
3554		producer.create_group(group::Info { sequence: 7 }).unwrap();
3555
3556		let group = consumer
3557			.next_group()
3558			.now_or_never()
3559			.expect("should not block")
3560			.expect("would have errored")
3561			.expect("track should not be closed");
3562		assert_eq!(group.sequence, 7);
3563
3564		// No more groups. This would block.
3565		assert!(
3566			consumer.next_group().now_or_never().is_none(),
3567			"should block waiting for a higher sequence"
3568		);
3569	}
3570
3571	#[tokio::test]
3572	async fn next_group_returns_arrivals_in_order() {
3573		let mut producer = track_producer("test", None);
3574		let mut consumer = producer.subscribe(None);
3575
3576		// Seq 3 arrives first, then seq 5. Both should be returned in arrival order.
3577		producer.create_group(group::Info { sequence: 3 }).unwrap();
3578		producer.create_group(group::Info { sequence: 5 }).unwrap();
3579
3580		let group = consumer
3581			.next_group()
3582			.now_or_never()
3583			.expect("should not block")
3584			.expect("would have errored")
3585			.expect("track should not be closed");
3586		assert_eq!(group.sequence, 3);
3587
3588		let group = consumer
3589			.next_group()
3590			.now_or_never()
3591			.expect("should not block")
3592			.expect("would have errored")
3593			.expect("track should not be closed");
3594		assert_eq!(group.sequence, 5);
3595	}
3596
3597	#[tokio::test]
3598	async fn next_group_and_recv_group_use_independent_cursors() {
3599		let mut producer = track_producer("test", None);
3600		let mut consumer = producer.subscribe(None);
3601
3602		// Out-of-order arrivals: seq 5 first, then seq 3.
3603		producer.create_group(group::Info { sequence: 5 }).unwrap();
3604		producer.create_group(group::Info { sequence: 3 }).unwrap();
3605
3606		// next_group is sequence-ordered: it returns the smallest sequence first,
3607		// regardless of arrival order.
3608		let group = consumer
3609			.next_group()
3610			.now_or_never()
3611			.expect("should not block")
3612			.expect("would have errored")
3613			.expect("track should not be closed");
3614		assert_eq!(group.sequence, 3);
3615
3616		// recv_group is arrival-ordered and uses an independent cursor, so it
3617		// still starts at the first arrival.
3618		assert_eq!(consumer.assert_group().sequence, 5);
3619	}
3620
3621	#[tokio::test]
3622	async fn end_at_caps_next_group() {
3623		let mut producer = track_producer("test", None);
3624		let mut consumer = producer.subscribe(None);
3625
3626		for s in 0..6 {
3627			producer.create_group(group::Info { sequence: s }).unwrap();
3628		}
3629
3630		consumer.end_at(2);
3631
3632		// Groups 0, 1, 2 are within the cap.
3633		assert_eq!(
3634			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3635			0
3636		);
3637		assert_eq!(
3638			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3639			1
3640		);
3641		assert_eq!(
3642			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3643			2
3644		);
3645
3646		// Group 3 is beyond the cap: next_group parks even though cached groups exist.
3647		assert!(
3648			consumer.next_group().now_or_never().is_none(),
3649			"capped consumer must block instead of returning out-of-range groups"
3650		);
3651	}
3652
3653	#[tokio::test]
3654	async fn end_at_release_drains_cached_groups() {
3655		let mut producer = track_producer("test", None);
3656		let mut consumer = producer.subscribe(None);
3657
3658		for s in 0..6 {
3659			producer.create_group(group::Info { sequence: s }).unwrap();
3660		}
3661
3662		consumer.end_at(1);
3663		assert_eq!(
3664			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3665			0
3666		);
3667		assert_eq!(
3668			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3669			1
3670		);
3671		assert!(consumer.next_group().now_or_never().is_none(), "capped at 1");
3672
3673		// Raise the cap; previously-blocked cached groups become available again.
3674		consumer.end_at(4);
3675		assert_eq!(
3676			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3677			2
3678		);
3679		assert_eq!(
3680			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3681			3
3682		);
3683		assert_eq!(
3684			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3685			4
3686		);
3687		assert!(consumer.next_group().now_or_never().is_none(), "capped at 4");
3688
3689		// Remove the cap; everything remaining flows.
3690		consumer.end_at(None);
3691		assert_eq!(
3692			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3693			5
3694		);
3695		assert!(consumer.next_group().now_or_never().is_none(), "no more groups");
3696	}
3697
3698	#[tokio::test]
3699	async fn end_at_lower_than_cursor_parks_consumer() {
3700		let mut producer = track_producer("test", None);
3701		let mut consumer = producer.subscribe(None);
3702
3703		for s in 0..3 {
3704			producer.create_group(group::Info { sequence: s }).unwrap();
3705		}
3706
3707		// Drain everything with no cap.
3708		assert_eq!(
3709			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3710			0
3711		);
3712		assert_eq!(
3713			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3714			1
3715		);
3716		assert_eq!(
3717			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3718			2
3719		);
3720
3721		// Lower the cap below the cursor. New groups beyond the cap are blocked.
3722		consumer.end_at(1);
3723		producer.create_group(group::Info { sequence: 3 }).unwrap();
3724		producer.create_group(group::Info { sequence: 4 }).unwrap();
3725		assert!(
3726			consumer.next_group().now_or_never().is_none(),
3727			"cap is below cursor; nothing returnable until cap rises"
3728		);
3729
3730		// Restoring the cap to no-limit (or any value >= cursor) releases them.
3731		consumer.end_at(None);
3732		assert_eq!(
3733			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3734			3
3735		);
3736		assert_eq!(
3737			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3738			4
3739		);
3740	}
3741
3742	#[tokio::test]
3743	async fn end_at_toggling_around_late_arrivals() {
3744		let mut producer = track_producer("test", None);
3745		let mut consumer = producer.subscribe(None);
3746
3747		consumer.end_at(5);
3748
3749		// Out-of-order arrivals all within the cap.
3750		producer.create_group(group::Info { sequence: 2 }).unwrap();
3751		producer.create_group(group::Info { sequence: 5 }).unwrap();
3752		producer.create_group(group::Info { sequence: 3 }).unwrap();
3753		// One beyond the cap; should be held even though it arrived in the middle.
3754		producer.create_group(group::Info { sequence: 8 }).unwrap();
3755		producer.create_group(group::Info { sequence: 4 }).unwrap();
3756
3757		// next_group walks in sequence order through everything <= cap.
3758		assert_eq!(
3759			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3760			2
3761		);
3762		assert_eq!(
3763			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3764			3
3765		);
3766		assert_eq!(
3767			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3768			4
3769		);
3770		assert_eq!(
3771			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3772			5
3773		);
3774		// Now blocked: 8 is still beyond the cap.
3775		assert!(consumer.next_group().now_or_never().is_none());
3776
3777		// Raise the cap; cached seq 8 is finally served.
3778		consumer.end_at(10);
3779		assert_eq!(
3780			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3781			8
3782		);
3783	}
3784
3785	#[tokio::test]
3786	async fn read_frame_returns_single_frame_per_group() {
3787		let mut producer = track_producer("test", None);
3788		let mut consumer = producer.subscribe(None);
3789
3790		producer.write_frame(Timestamp::ZERO, b"hello".as_slice()).unwrap();
3791		producer.write_frame(Timestamp::ZERO, b"world".as_slice()).unwrap();
3792
3793		let frame = consumer
3794			.read_frame()
3795			.now_or_never()
3796			.expect("should not block")
3797			.expect("would have errored")
3798			.expect("track should not be closed");
3799		assert_eq!(&frame.payload[..], b"hello");
3800
3801		let frame = consumer
3802			.read_frame()
3803			.now_or_never()
3804			.expect("should not block")
3805			.expect("would have errored")
3806			.expect("track should not be closed");
3807		assert_eq!(&frame.payload[..], b"world");
3808	}
3809
3810	#[tokio::test]
3811	async fn read_frame_preserves_timestamp() {
3812		let mut producer = track_producer("test", None);
3813		let mut consumer = producer.subscribe(None);
3814
3815		producer
3816			.write_frame(Timestamp::from_micros(20_000).unwrap(), b"hello".as_slice())
3817			.unwrap();
3818
3819		let frame = consumer
3820			.read_frame()
3821			.now_or_never()
3822			.expect("should not block")
3823			.expect("would have errored")
3824			.expect("track should not be closed");
3825		assert_eq!(frame.timestamp.as_micros(), 20_000);
3826		assert_eq!(&frame.payload[..], b"hello");
3827	}
3828
3829	#[tokio::test]
3830	async fn read_frame_skips_stalled_group_for_newer_ready_frame() {
3831		let mut producer = track_producer("test", None);
3832		let mut consumer = producer.subscribe(None);
3833
3834		// Seq 3: group open, no frame yet (stalled).
3835		let _stalled = producer.create_group(group::Info { sequence: 3 }).unwrap();
3836		// Seq 5: fully-written group with a frame.
3837		let mut g5 = producer.create_group(group::Info { sequence: 5 }).unwrap();
3838		g5.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"later"))
3839			.unwrap();
3840		g5.finish().unwrap();
3841
3842		// read_frame should not block on the stalled seq 3. It returns seq 5's frame.
3843		let frame = consumer
3844			.read_frame()
3845			.now_or_never()
3846			.expect("should not block on stalled earlier group")
3847			.expect("would have errored")
3848			.expect("track should not be closed");
3849		assert_eq!(&frame.payload[..], b"later");
3850	}
3851
3852	#[tokio::test]
3853	async fn read_frame_discards_rest_of_multi_frame_group() {
3854		let mut producer = track_producer("test", None);
3855		let mut consumer = producer.subscribe(None);
3856
3857		// Group 0 has two frames; only the first is returned.
3858		let mut g0 = producer.create_group(group::Info { sequence: 0 }).unwrap();
3859		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"one"))
3860			.unwrap();
3861		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"two"))
3862			.unwrap();
3863		g0.finish().unwrap();
3864
3865		// Group 1 is a normal single-frame group.
3866		producer.write_frame(Timestamp::ZERO, b"next".as_slice()).unwrap();
3867
3868		let frame = consumer
3869			.read_frame()
3870			.now_or_never()
3871			.expect("should not block")
3872			.expect("would have errored")
3873			.expect("track should not be closed");
3874		assert_eq!(&frame.payload[..], b"one");
3875
3876		// The second frame of group 0 is discarded; the next read jumps to group 1.
3877		let frame = consumer
3878			.read_frame()
3879			.now_or_never()
3880			.expect("should not block")
3881			.expect("would have errored")
3882			.expect("track should not be closed");
3883		assert_eq!(&frame.payload[..], b"next");
3884	}
3885
3886	#[tokio::test]
3887	async fn read_frame_waits_for_pending_group_after_finish() {
3888		// finish() sets final_sequence, but groups already created with lower sequences
3889		// can still produce frames. read_frame must not return None prematurely.
3890		let mut producer = track_producer("test", None);
3891		let mut consumer = producer.subscribe(None);
3892
3893		let mut g0 = producer.create_group(group::Info { sequence: 0 }).unwrap();
3894		producer.finish().unwrap();
3895
3896		// Track is finished but group 0 has no frame yet. It must block, not return None.
3897		assert!(
3898			consumer.read_frame().now_or_never().is_none(),
3899			"read_frame must block on a pending group even after finish()"
3900		);
3901
3902		// A late frame on the pending group is still delivered.
3903		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"late"))
3904			.unwrap();
3905		let frame = consumer
3906			.read_frame()
3907			.now_or_never()
3908			.expect("should not block once a frame is written")
3909			.expect("would have errored")
3910			.expect("track should not be closed");
3911		assert_eq!(&frame.payload[..], b"late");
3912	}
3913
3914	#[tokio::test]
3915	async fn read_frame_respects_start_at() {
3916		// start_at sets min_sequence; read_frame must skip groups below it even though
3917		// next_sequence is still 0.
3918		let mut producer = track_producer("test", None);
3919		let mut consumer = producer.subscribe(None);
3920		consumer.start_at(5);
3921
3922		// Seq 3 has a frame but is below min_sequence, so it must be skipped.
3923		let mut g3 = producer.create_group(group::Info { sequence: 3 }).unwrap();
3924		g3.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"skip-me"))
3925			.unwrap();
3926		g3.finish().unwrap();
3927
3928		let mut g5 = producer.create_group(group::Info { sequence: 5 }).unwrap();
3929		g5.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"keep"))
3930			.unwrap();
3931		g5.finish().unwrap();
3932
3933		let frame = consumer
3934			.read_frame()
3935			.now_or_never()
3936			.expect("should not block")
3937			.expect("would have errored")
3938			.expect("track should not be closed");
3939		assert_eq!(&frame.payload[..], b"keep");
3940	}
3941
3942	#[tokio::test]
3943	async fn read_frame_returns_none_when_finished() {
3944		let mut producer = track_producer("test", None);
3945		let mut consumer = producer.subscribe(None);
3946
3947		producer.write_frame(Timestamp::ZERO, b"only".as_slice()).unwrap();
3948		producer.finish().unwrap();
3949
3950		let frame = consumer
3951			.read_frame()
3952			.now_or_never()
3953			.expect("should not block")
3954			.expect("would have errored")
3955			.expect("track should not be closed");
3956		assert_eq!(&frame.payload[..], b"only");
3957
3958		let done = consumer
3959			.read_frame()
3960			.now_or_never()
3961			.expect("should not block")
3962			.expect("would have errored");
3963		assert!(done.is_none());
3964	}
3965
3966	#[test]
3967	fn append_group_returns_bounds_exceeded_on_sequence_overflow() {
3968		let mut producer = track_producer("test", None);
3969		{
3970			let mut state = producer.state.write().ok().unwrap();
3971			state.max_sequence = Some(u64::MAX);
3972		}
3973
3974		assert!(matches!(producer.append_group(), Err(Error::BoundsExceeded(_))));
3975	}
3976
3977	#[tokio::test]
3978	async fn fetch_cache_hit() {
3979		let mut producer = track_producer("test", None);
3980
3981		// Produce a cached group.
3982		let mut group = producer.append_group().unwrap(); // seq 0
3983		group
3984			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hello"))
3985			.unwrap();
3986		group.finish().unwrap();
3987
3988		// A cached group resolves immediately and never queues a request. `peek_group`
3989		// also returns it synchronously.
3990		let dynamic = producer.dynamic();
3991		let consumer = producer.consume();
3992		assert!(consumer.peek_group(0).is_some());
3993		let mut g = consumer.fetch_group(0, None).await.unwrap();
3994		assert_eq!(g.sequence, 0);
3995		assert_eq!(&g.read_frame().await.unwrap().unwrap().payload[..], b"hello");
3996
3997		// Nothing was queued for the dynamic handler to serve.
3998		assert!(dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending());
3999	}
4000
4001	#[tokio::test]
4002	async fn fetch_miss_signals_dynamic() {
4003		let producer = track_producer("test", None);
4004		let dynamic = producer.dynamic();
4005		let consumer = producer.consume();
4006
4007		// A cache miss isn't in `peek_group`, but a dynamic handler exists, so
4008		// `fetch_group` stays pending and queues a request. `*pending` derefs the
4009		// wrapper to the inner `Fetching` (a `kio::Pollable`).
4010		assert!(consumer.peek_group(5).is_none());
4011		let pending = consumer.fetch_group(5, group::Fetch::default().with_priority(7));
4012		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
4013
4014		let req = dynamic
4015			.requested_group()
4016			.now_or_never()
4017			.expect("should not block")
4018			.unwrap();
4019		assert_eq!(req.sequence(), 5);
4020		assert_eq!(req.priority(), 7);
4021
4022		// Serve it by accepting the request; the fetch then resolves.
4023		let mut group = req.accept(None).unwrap();
4024		group
4025			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hi"))
4026			.unwrap();
4027		group.finish().unwrap();
4028
4029		let mut g = pending.await.unwrap();
4030		assert_eq!(g.sequence, 5);
4031		assert_eq!(&g.read_frame().await.unwrap().unwrap().payload[..], b"hi");
4032	}
4033
4034	#[tokio::test]
4035	async fn fetch_miss_rejects() {
4036		let producer = track_producer("test", None);
4037		let dynamic = producer.dynamic();
4038		let consumer = producer.consume();
4039
4040		let pending = consumer.fetch_group(5, None);
4041		let req = dynamic
4042			.requested_group()
4043			.now_or_never()
4044			.expect("should not block")
4045			.unwrap();
4046
4047		req.reject(Error::Cancel);
4048		assert!(matches!(pending.await, Err(Error::Cancel)));
4049		let fetch = producer.state.read().fetch.clone();
4050		assert!(fetch.read().is_empty());
4051	}
4052
4053	#[tokio::test]
4054	async fn fetch_miss_drop_rejects() {
4055		let producer = track_producer("test", None);
4056		let dynamic = producer.dynamic();
4057		let consumer = producer.consume();
4058
4059		let pending = consumer.fetch_group(5, None);
4060		let req = dynamic
4061			.requested_group()
4062			.now_or_never()
4063			.expect("should not block")
4064			.unwrap();
4065
4066		drop(req);
4067		assert!(matches!(pending.await, Err(Error::Dropped)));
4068	}
4069
4070	#[tokio::test]
4071	async fn fetch_reject_does_not_poison_retry() {
4072		let producer = track_producer("test", None);
4073		let dynamic = producer.dynamic();
4074		let consumer = producer.consume();
4075
4076		let pending = consumer.fetch_group(5, None);
4077		let req = dynamic
4078			.requested_group()
4079			.now_or_never()
4080			.expect("should not block")
4081			.unwrap();
4082		req.reject(Error::Cancel);
4083		assert!(matches!(pending.await, Err(Error::Cancel)));
4084
4085		let retry = consumer.fetch_group(5, None);
4086		let req = dynamic
4087			.requested_group()
4088			.now_or_never()
4089			.expect("should not block")
4090			.unwrap();
4091		let mut group = req.accept(None).unwrap();
4092		group
4093			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"retry"))
4094			.unwrap();
4095		group.finish().unwrap();
4096
4097		let mut group = retry.await.unwrap();
4098		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"retry");
4099	}
4100
4101	#[tokio::test]
4102	async fn fetch_coalesces_concurrent() {
4103		let producer = track_producer("test", None);
4104		let dynamic = producer.dynamic();
4105		let consumer = producer.consume();
4106
4107		// Two fetches for the same uncached group produce ONE handler request,
4108		// carrying the higher of the two priorities.
4109		let first = consumer.fetch_group(5, group::Fetch::default().with_priority(1));
4110		let second = consumer.fetch_group(5, group::Fetch::default().with_priority(7));
4111		assert!(kio::Pollable::poll(&*first, &kio::Waiter::noop()).is_pending());
4112
4113		let req = dynamic
4114			.requested_group()
4115			.now_or_never()
4116			.expect("should not block")
4117			.unwrap();
4118		assert_eq!(req.sequence(), 5);
4119		assert_eq!(req.priority(), 7);
4120		assert!(
4121			dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending(),
4122			"the second fetch queued a duplicate request"
4123		);
4124
4125		// A fetch arriving while the request is already in flight joins it too.
4126		let third = consumer.fetch_group(5, None);
4127
4128		// One accept resolves all of them.
4129		let mut group = req.accept(None).unwrap();
4130		group
4131			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hi"))
4132			.unwrap();
4133		group.finish().unwrap();
4134
4135		assert_eq!(first.await.unwrap().sequence, 5);
4136		assert_eq!(second.await.unwrap().sequence, 5);
4137		assert_eq!(third.await.unwrap().sequence, 5);
4138	}
4139
4140	#[tokio::test]
4141	async fn fetch_coalesced_reject_fails_all() {
4142		let producer = track_producer("test", None);
4143		let dynamic = producer.dynamic();
4144		let consumer = producer.consume();
4145
4146		let first = consumer.fetch_group(5, None);
4147		let second = consumer.fetch_group(5, None);
4148		let req = dynamic
4149			.requested_group()
4150			.now_or_never()
4151			.expect("should not block")
4152			.unwrap();
4153		req.reject(Error::Cancel);
4154
4155		assert!(matches!(first.await, Err(Error::Cancel)));
4156		assert!(matches!(second.await, Err(Error::Cancel)));
4157
4158		// The rejected attempt is gone: a retry starts a fresh one.
4159		let retry = consumer.fetch_group(5, None);
4160		assert!(kio::Pollable::poll(&*retry, &kio::Waiter::noop()).is_pending());
4161		let req = dynamic
4162			.requested_group()
4163			.now_or_never()
4164			.expect("should not block")
4165			.unwrap();
4166		assert_eq!(req.sequence(), 5);
4167	}
4168
4169	#[tokio::test]
4170	async fn fetch_queued_fails_when_handlers_leave() {
4171		let producer = track_producer("test", None);
4172		let dynamic = producer.dynamic();
4173		let consumer = producer.consume();
4174
4175		// Queued but never popped: the last handler leaving fails it fast.
4176		let pending = consumer.fetch_group(5, None);
4177		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
4178		drop(dynamic);
4179		assert!(matches!(pending.await, Err(Error::NotFound)));
4180
4181		// And the attempt didn't leak.
4182		let fetch = producer.state.read().fetch.clone();
4183		assert!(fetch.read().is_empty());
4184	}
4185
4186	#[tokio::test]
4187	async fn fetch_miss_no_dynamic_not_found() {
4188		// A track with no `Dynamic` can't serve old content, so a cache miss
4189		// resolves to NotFound instead of blocking forever.
4190		let mut producer = track_producer("test", None);
4191		producer.append_group().unwrap(); // seq 0, but we miss on seq 5
4192		let consumer = producer.consume();
4193		assert!(matches!(consumer.fetch_group(5, None).await, Err(Error::NotFound)));
4194	}
4195
4196	#[tokio::test]
4197	async fn fetch_past_final_not_found() {
4198		let mut producer = track_producer("test", None);
4199		producer.append_group().unwrap(); // seq 0
4200		producer.finish().unwrap(); // final_sequence = 1
4201
4202		// A group at or past the final sequence can never exist, even with a handler,
4203		// so it resolves to NotFound.
4204		let dynamic = producer.dynamic();
4205		let consumer = producer.consume();
4206		assert!(matches!(consumer.fetch_group(5, None).await, Err(Error::NotFound)));
4207
4208		// And it doesn't signal the dynamic handler.
4209		assert!(dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending());
4210	}
4211
4212	/// Mint a track whose groups charge into a bounded [`cache::Pool`].
4213	fn pooled_producer(capacity: u64) -> (Producer, cache::Pool) {
4214		let pool = cache::Pool::new(capacity);
4215		let broadcast = broadcast::Info {
4216			origin: crate::origin::Info::default().with_pool(pool.clone()),
4217			..Default::default()
4218		};
4219		let producer = Producer::new(Arc::new(broadcast), "test", None);
4220		(producer, pool)
4221	}
4222
4223	fn finished_group(producer: &mut Producer, size: usize) -> u64 {
4224		let mut group = producer.append_group().unwrap();
4225		group
4226			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; size]))
4227			.unwrap();
4228		group.finish().unwrap();
4229		group.sequence
4230	}
4231
4232	/// While the pool is over capacity, every append accrues debt and pays it by
4233	/// evicting this track's own oldest groups, so the newest content survives.
4234	#[tokio::test]
4235	async fn debt_evicts_oldest_group() {
4236		tokio::time::pause();
4237
4238		// Fits one 10k group; each additional group pushes the pool over budget.
4239		let (mut producer, pool) = pooled_producer(10_000);
4240
4241		finished_group(&mut producer, 10_000); // seq 0
4242		finished_group(&mut producer, 10_000); // seq 1: over budget, debt starts accruing
4243		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4244
4245		let consumer = producer.consume();
4246		assert!(consumer.peek_group(0).is_none(), "oldest group is evicted");
4247		assert!(consumer.peek_group(2).is_some(), "latest group survives");
4248		// Steady state carries the protected live edge plus the just-demoted group
4249		// (debt is charged before the demotion, so eviction lags one append).
4250		assert!(pool.used() <= 21_000, "usage hovers near capacity: {}", pool.used());
4251
4252		// A fresh subscriber skips the evicted groups entirely.
4253		let mut subscriber = producer.subscribe(None);
4254		assert!(subscriber.assert_group().sequence > 0, "evicted group is not delivered");
4255	}
4256
4257	/// The latest group is never in the eviction order, so it survives any budget.
4258	#[tokio::test]
4259	async fn latest_group_never_evicted() {
4260		tokio::time::pause();
4261
4262		// Far too small for even one group: the latest survives anyway.
4263		let (mut producer, pool) = pooled_producer(100);
4264		finished_group(&mut producer, 1000); // seq 0
4265		assert!(pool.used() > 100, "the latest may exceed the budget");
4266
4267		// Later writes evict the demoted seq 0; each new latest is untouchable in turn.
4268		finished_group(&mut producer, 1000); // seq 1: demotes seq 0
4269		finished_group(&mut producer, 1000); // seq 2: pays by evicting seq 0
4270
4271		let consumer = producer.consume();
4272		assert!(consumer.peek_group(0).is_none());
4273		let mut group = consumer.peek_group(2).expect("latest survives");
4274		assert_eq!(group.read_frame().await.unwrap().unwrap().payload.len(), 1000);
4275	}
4276
4277	/// A FETCH cache hit refreshes the group's access time: anything accessed more
4278	/// recently than the pool-wide average is protected, so the eviction walk skips
4279	/// it and evicts a never-read group instead, even one that arrived later.
4280	#[tokio::test]
4281	async fn fetch_refresh_survives_eviction() {
4282		tokio::time::pause();
4283
4284		let (mut producer, _pool) = pooled_producer(10_000);
4285		let consumer = producer.consume();
4286
4287		finished_group(&mut producer, 3_000); // seq 0
4288		tokio::time::advance(Duration::from_secs(1)).await;
4289		finished_group(&mut producer, 3_000); // seq 1
4290		tokio::time::advance(Duration::from_secs(1)).await;
4291		finished_group(&mut producer, 3_000); // seq 2
4292		tokio::time::advance(Duration::from_millis(500)).await;
4293
4294		// FETCH seq 0: the cache hit lifts its access time above the average.
4295		let mut fetched = consumer.fetch_group(0, None).await.unwrap();
4296		assert_eq!(fetched.read_frame().await.unwrap().unwrap().payload.len(), 3_000);
4297		tokio::time::advance(Duration::from_millis(500)).await;
4298
4299		// Pressure: seq 0 is first in eviction order but freshly accessed, so it
4300		// rotates to the back and the never-read seq 1 dies instead.
4301		finished_group(&mut producer, 3_000); // seq 3
4302		tokio::time::advance(Duration::from_secs(1)).await;
4303		finished_group(&mut producer, 3_000); // seq 4
4304
4305		assert!(consumer.peek_group(0).is_some(), "refreshed group survives");
4306		assert!(consumer.peek_group(1).is_none(), "unread group is evicted instead");
4307	}
4308
4309	/// A consumer holding an evicted group surfaces the eviction, not a hang or a
4310	/// truncated clean end.
4311	#[tokio::test]
4312	async fn eviction_aborts_readers() {
4313		tokio::time::pause();
4314
4315		let (mut producer, _pool) = pooled_producer(10_000);
4316		let mut subscriber = producer.subscribe(None);
4317
4318		finished_group(&mut producer, 10_000); // seq 0
4319		let mut group0 = subscriber.assert_group();
4320
4321		finished_group(&mut producer, 10_000); // seq 1: demotes seq 0
4322		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4323
4324		let read = group0.read_frame().await;
4325		assert!(matches!(read, Err(Error::Evicted)), "expected Evicted, got {read:?}");
4326	}
4327
4328	/// A write smaller than the next victim carries debt instead of evicting: a
4329	/// large group dies only once enough debt accumulates, never to pay off a
4330	/// far smaller write.
4331	#[tokio::test]
4332	async fn small_writes_carry_debt() {
4333		tokio::time::pause();
4334
4335		let (mut producer, pool) = pooled_producer(22_000);
4336		let consumer = producer.consume();
4337
4338		finished_group(&mut producer, 20_000); // seq 0, the large victim-to-be
4339
4340		// The first few small writes owe far less than seq 0's size: the debt
4341		// carries over instead of evicting it.
4342		for _ in 0..3 {
4343			finished_group(&mut producer, 1_000);
4344		}
4345		assert!(consumer.peek_group(0).is_some(), "debt smaller than the victim carries");
4346
4347		// Enough small writes accumulate the debt to finally evict it.
4348		for _ in 0..20 {
4349			finished_group(&mut producer, 1_000);
4350		}
4351		assert!(
4352			consumer.peek_group(0).is_none(),
4353			"accumulated debt evicts the large group"
4354		);
4355		// Steady state hovers within about one group of capacity: a victim smaller
4356		// than the outstanding debt is never evicted, so the excess stays bounded.
4357		assert!(pool.used() <= 24_000, "usage hovers near capacity: {}", pool.used());
4358	}
4359
4360	/// One write pays at most twice what it produced, so a capacity shrink (or one
4361	/// track's burst) drains gradually instead of one writer dumping its whole
4362	/// backlog in a single call.
4363	#[tokio::test]
4364	async fn payment_capped_per_write() {
4365		tokio::time::pause();
4366
4367		let (mut producer, pool) = pooled_producer(1 << 40);
4368		for _ in 0..10 {
4369			finished_group(&mut producer, 1_000);
4370		}
4371
4372		// The governor slashes the target; nothing is reclaimed synchronously.
4373		pool.resize(100);
4374		let before = pool.used();
4375
4376		// One 1k write may evict at most ~2k of backlog, not all ten groups.
4377		finished_group(&mut producer, 1_000);
4378
4379		let consumer = producer.consume();
4380		assert!(consumer.peek_group(0).is_none(), "the oldest groups are evicted");
4381		assert!(consumer.peek_group(1).is_none());
4382		assert!(consumer.peek_group(2).is_some(), "the backlog drains gradually");
4383		assert!(pool.used() > before - 4_000, "one write must not dump the backlog");
4384	}
4385
4386	/// Accepting a track after pre-accept backfill must keep the same write
4387	/// counter: the counter is owned by the track state, so replacing the info
4388	/// can't strand the bytes already-created groups keep charging.
4389	#[tokio::test]
4390	async fn accept_preserves_write_accounting() {
4391		tokio::time::pause();
4392
4393		let pool = cache::Pool::new(12_000);
4394		let broadcast = broadcast::Info {
4395			origin: crate::origin::Info::default().with_pool(pool.clone()),
4396			..Default::default()
4397		};
4398		let request = Request::new(Arc::new(broadcast), "test");
4399		let dynamic = request.dynamic();
4400		let consumer = request.consume();
4401
4402		// Serve a backfill before the track is accepted, then grow it.
4403		let pending = consumer.fetch_group(0, None);
4404		let req = dynamic
4405			.requested_group()
4406			.now_or_never()
4407			.expect("should not block")
4408			.unwrap();
4409		let mut backfill = req.accept(None).unwrap();
4410		pending.await.unwrap();
4411		backfill
4412			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 30_000]))
4413			.unwrap();
4414
4415		// Accept with a fresh Info: the pre-accept group's writes must still be
4416		// drained by this track's future charges.
4417		let mut producer = request.accept(None);
4418		producer.append_group().unwrap().finish().unwrap();
4419		producer.append_group().unwrap().finish().unwrap();
4420
4421		assert!(
4422			producer.consume().peek_group(0).is_none(),
4423			"pre-accept backfill growth is reclaimed after accept"
4424		);
4425		assert!(pool.used() <= 13_000, "usage converges: {}", pool.used());
4426	}
4427
4428	/// Re-serving a sequence many times must not accumulate eviction hints: stale
4429	/// hints die on stamp mismatch and compaction reclaims them.
4430	#[tokio::test]
4431	async fn recreated_sequence_bounds_eviction_hints() {
4432		let (mut producer, _pool) = pooled_producer(1 << 40);
4433		producer.create_group(5u64.into()).unwrap().finish().unwrap();
4434
4435		for _ in 0..200 {
4436			let group = producer.create_group(1u64.into()).unwrap();
4437			group.abort(Error::Cancel).unwrap();
4438		}
4439
4440		let state = producer.state.read();
4441		assert!(
4442			state.evict.len() <= 2 * state.lookup.len() + EVICT_SLACK,
4443			"stale hints are compacted: {} entries for {} slots",
4444			state.evict.len(),
4445			state.lookup.len()
4446		);
4447	}
4448
4449	/// A frame write within the same coarse tick still outranks merely-inserted
4450	/// content, so the freshly-written group survives and the empty one pays.
4451	#[tokio::test]
4452	async fn same_tick_write_outranks_inserted() {
4453		tokio::time::pause();
4454
4455		// No time advances: every stamp lands in the same tick.
4456		let (mut producer, _pool) = pooled_producer(10_000);
4457
4458		producer.append_group().unwrap().finish().unwrap(); // seq 0: empty
4459		finished_group(&mut producer, 3_000); // seq 1: written
4460		finished_group(&mut producer, 3_000); // seq 2
4461		finished_group(&mut producer, 3_000); // seq 3
4462		finished_group(&mut producer, 3_000); // seq 4: over budget, pays
4463
4464		let consumer = producer.consume();
4465		assert!(consumer.peek_group(0).is_none(), "insert-only content pays first");
4466		assert!(consumer.peek_group(1).is_some(), "same-tick written content survives");
4467	}
4468
4469	/// A track that only appends frames to an open group, never inserting another
4470	/// group, still settles its eviction debt once enough bytes accumulate.
4471	#[tokio::test]
4472	async fn frame_only_writer_pays() {
4473		tokio::time::pause();
4474
4475		let (mut producer, pool) = pooled_producer(2_000);
4476		let mut demoted = producer.append_group().unwrap(); // seq 0
4477		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4478
4479		// One large frame crosses the charge threshold: the write itself pays,
4480		// with no further group insert on this track.
4481		demoted
4482			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 300_000]))
4483			.unwrap();
4484
4485		assert!(
4486			pool.used() <= 5_000,
4487			"the frame write settled the debt: {}",
4488			pool.used()
4489		);
4490		assert!(matches!(demoted.finish(), Err(Error::Evicted)));
4491	}
4492
4493	/// One `Info` describing several tracks must not join their eviction accounting:
4494	/// each track opens its own account against the pool.
4495	#[tokio::test]
4496	async fn each_track_owns_its_account() {
4497		let broadcast = Arc::new(broadcast::Info::default());
4498		let info = Info::default();
4499		let a = Producer::new(broadcast.clone(), "a", info.clone());
4500		let b = Producer::new(broadcast, "b", info);
4501
4502		let a = a.state.read().cache.clone();
4503		let b = b.state.read().cache.clone();
4504		assert!(!Arc::ptr_eq(&a, &b), "each track owns its account");
4505	}
4506
4507	/// A `Dynamic` still serving fetches keeps the track alive, so the publisher
4508	/// letting go isn't an abrupt teardown: the handler can still serve the cache.
4509	#[tokio::test]
4510	async fn a_dynamic_defers_teardown() {
4511		let (mut producer, pool) = pooled_producer(1 << 40);
4512		let dynamic = producer.dynamic();
4513		finished_group(&mut producer, 100);
4514
4515		drop(producer);
4516		assert!(pool.used() > 0, "the handler still serves the cache");
4517
4518		drop(dynamic);
4519		assert_eq!(pool.used(), 0, "the last handle tears it down");
4520	}
4521
4522	/// A finished track releases everything once every handle is gone.
4523	///
4524	/// Its groups hold the cache account, and the account links back here, so that link
4525	/// has to be weak: anything stronger makes the state (and every cached frame in it)
4526	/// immortal, even with no producer or consumer left.
4527	#[tokio::test]
4528	async fn finished_track_frees_its_cache() {
4529		let (mut producer, pool) = pooled_producer(1 << 40);
4530		finished_group(&mut producer, 100);
4531		producer.finish().unwrap();
4532
4533		let state = producer.state.downgrade();
4534		drop(producer);
4535
4536		assert!(state.upgrade().is_none(), "the track state is freed");
4537		assert_eq!(pool.used(), 0, "so are its cached bytes");
4538	}
4539
4540	/// A group settling its eviction debt upgrades the account's weak handle, which
4541	/// counts as a producer on the track state. Teardown must not mistake that for a
4542	/// surviving publisher, or an abrupt drop silently behaves like a clean finish.
4543	#[tokio::test]
4544	async fn teardown_ignores_a_settling_group() {
4545		let (mut producer, pool) = pooled_producer(1 << 40);
4546		finished_group(&mut producer, 100);
4547
4548		// Stand in for a concurrent `cache::Track::settle`, mid-upgrade.
4549		let settling = producer.state.downgrade().upgrade().expect("open");
4550		drop(producer);
4551
4552		assert_eq!(pool.used(), 0, "the abrupt teardown still released the cache");
4553		drop(settling);
4554	}
4555
4556	/// A subscriber holding one cached group must not pin the whole track: a group
4557	/// carries the track's properties by value, not a handle back to its state.
4558	#[tokio::test]
4559	async fn cached_group_outlives_its_track() {
4560		let (mut producer, pool) = pooled_producer(1 << 40);
4561		let sequence = finished_group(&mut producer, 100);
4562		let group = producer.consume().peek_group(sequence).expect("cached");
4563		producer.finish().unwrap();
4564
4565		let state = producer.state.downgrade();
4566		drop(producer);
4567		assert!(state.upgrade().is_none(), "the track state is freed");
4568		assert!(pool.used() > 0, "the retained group keeps its own bytes");
4569
4570		drop(group);
4571		assert_eq!(pool.used(), 0, "which it releases when dropped");
4572	}
4573
4574	/// A backfill served before the track was accepted settles its own debt: the
4575	/// account exists from the moment the state does, so acceptance replacing the
4576	/// `Info` can't leave already-created groups writing for free.
4577	#[tokio::test]
4578	async fn pre_accept_backfill_settles_late_writes() {
4579		tokio::time::pause();
4580
4581		let pool = cache::Pool::new(2_000);
4582		let broadcast = broadcast::Info {
4583			origin: crate::origin::Info::default().with_pool(pool.clone()),
4584			..Default::default()
4585		};
4586		let request = Request::new(Arc::new(broadcast), "test");
4587		let dynamic = request.dynamic();
4588		let consumer = request.consume();
4589
4590		// Serve backfill seq 0 before the track is accepted.
4591		let pending = consumer.fetch_group(0, None);
4592		let req = dynamic
4593			.requested_group()
4594			.now_or_never()
4595			.expect("should not block")
4596			.unwrap();
4597		let mut backfill = req.accept(None).unwrap();
4598		pending.await.unwrap();
4599
4600		// Accept, then demote the backfill with a live group.
4601		let mut producer = request.accept(None);
4602		producer.append_group().unwrap().finish().unwrap();
4603
4604		// No further insert: the late write into the demoted backfill is the only
4605		// thing that can pay the debt it just took on.
4606		backfill
4607			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 300_000]))
4608			.unwrap();
4609
4610		assert!(
4611			pool.used() <= 5_000,
4612			"the frame write settled the debt: {}",
4613			pool.used()
4614		);
4615	}
4616
4617	/// A late frame write restarts the retention clock (retention is documented as
4618	/// time since last written or fetched), so an actively-growing group is not
4619	/// expired as old mid-write.
4620	#[tokio::test]
4621	async fn write_restarts_retention_clock() {
4622		tokio::time::pause();
4623
4624		let (mut producer, _pool) = pooled_producer(1 << 40);
4625		let mut straggler = producer.append_group().unwrap(); // seq 0
4626		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4627
4628		// Idle past the window, then the straggler receives a late frame.
4629		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4630		straggler
4631			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4632			.unwrap();
4633		producer.append_group().unwrap().finish().unwrap(); // seq 2 runs expiry
4634
4635		let consumer = producer.consume();
4636		assert!(consumer.peek_group(0).is_some(), "the write restarted the clock");
4637
4638		// Once the writes stop, the group ages out normally.
4639		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4640		producer.append_group().unwrap().finish().unwrap(); // seq 3 runs expiry
4641		assert!(consumer.peek_group(0).is_none(), "idle content still expires");
4642	}
4643
4644	/// Continuously refreshed entries at the front of the eviction order must not
4645	/// starve expiry of entries behind them: the scan cursor rotates.
4646	#[tokio::test]
4647	async fn refreshed_front_does_not_starve_expiry() {
4648		tokio::time::pause();
4649
4650		let (mut producer, _pool) = pooled_producer(1 << 40);
4651		let dynamic = producer.dynamic();
4652		let consumer = producer.consume();
4653
4654		producer.create_group(10u64.into()).unwrap().finish().unwrap();
4655		for sequence in 1..=5u64 {
4656			let pending = consumer.fetch_group(sequence, None);
4657			let req = dynamic
4658				.requested_group()
4659				.now_or_never()
4660				.expect("should not block")
4661				.unwrap();
4662			let mut group = req.accept(None).unwrap();
4663			group
4664				.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4665				.unwrap();
4666			group.finish().unwrap();
4667			pending.await.unwrap();
4668		}
4669
4670		// Age everything out, then refresh the first four backfills so they sit
4671		// fresh at the front of the eviction order, hiding the expired fifth.
4672		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4673		for sequence in 1..=4u64 {
4674			consumer.fetch_group(sequence, None).await.unwrap();
4675		}
4676
4677		// The rotating cursor reaches the fifth entry within a few writes.
4678		for _ in 0..3 {
4679			producer.append_group().unwrap().finish().unwrap();
4680		}
4681		assert!(consumer.peek_group(5).is_none(), "expired backfill is reclaimed");
4682		assert!(consumer.peek_group(1).is_some(), "refreshed backfill survives");
4683	}
4684
4685	/// A publisher re-creating an aborted sequence is delivered exactly once, at
4686	/// its actual arrival position: the historical arrival entry is dead.
4687	#[tokio::test]
4688	async fn recreated_sequence_delivered_once() {
4689		let (mut producer, _pool) = pooled_producer(1 << 40);
4690
4691		producer.create_group(0u64.into()).unwrap().finish().unwrap();
4692		let aborted = producer.create_group(1u64.into()).unwrap();
4693		aborted.abort(Error::Cancel).unwrap();
4694		producer.create_group(2u64.into()).unwrap().finish().unwrap();
4695		producer.create_group(1u64.into()).unwrap().finish().unwrap();
4696
4697		let mut subscriber = producer.subscribe(None);
4698		assert_eq!(subscriber.assert_group().sequence, 0);
4699		assert_eq!(subscriber.assert_group().sequence, 2);
4700		assert_eq!(
4701			subscriber.assert_group().sequence,
4702			1,
4703			"replacement arrives at its own position"
4704		);
4705		subscriber.assert_no_group();
4706	}
4707
4708	/// Datagrams share `max_sequence` but must not break group demotion: the live
4709	/// edge is tracked per group, so interleaving datagrams can't strand groups
4710	/// outside the eviction order and bypass the budget.
4711	#[tokio::test]
4712	async fn datagrams_do_not_block_eviction() {
4713		tokio::time::pause();
4714
4715		let (mut producer, pool) = pooled_producer(1_000);
4716		for _ in 0..10 {
4717			finished_group(&mut producer, 1_000);
4718			producer.append_datagram(Timestamp::ZERO, &b"beat"[..]).unwrap();
4719		}
4720
4721		let consumer = producer.consume();
4722		assert!(consumer.peek_group(0).is_none(), "old groups still evict");
4723		assert!(
4724			pool.used() < 4 * 1_256,
4725			"interleaved datagrams must not bypass the budget: {}",
4726			pool.used()
4727		);
4728	}
4729
4730	/// An aborted group releases its access sample along with its bytes, from any
4731	/// handle: ghost samples must not linger in the pool mean where they'd hold it
4732	/// in the past and over-protect every live group.
4733	#[tokio::test]
4734	async fn aborted_group_leaves_no_ghost_sample() {
4735		tokio::time::pause();
4736
4737		let (mut producer, pool) = pooled_producer(1 << 40);
4738		let group0 = producer.append_group().unwrap();
4739		producer.append_group().unwrap(); // demotes seq 0 into the mean
4740
4741		assert!(pool.average().is_some(), "demoted group is sampled");
4742		group0.abort(Error::Cancel).unwrap();
4743		assert_eq!(pool.average(), None, "the abort must remove the sample");
4744	}
4745
4746	/// Empty groups still carry fixed overhead; they must repay the budget when
4747	/// evicted rather than being unevictable freeloaders.
4748	#[tokio::test]
4749	async fn empty_groups_repay_overhead() {
4750		tokio::time::pause();
4751
4752		let (mut producer, pool) = pooled_producer(1_000);
4753		for _ in 0..100 {
4754			let mut group = producer.append_group().unwrap();
4755			group.finish().unwrap();
4756		}
4757
4758		assert!(
4759			pool.used() <= 3_000,
4760			"empty-group overhead must stay near the budget: {}",
4761			pool.used()
4762		);
4763	}
4764
4765	/// Late growth on an already-demoted group is billed: the gross-write counter
4766	/// feeds debt on the next append, so a straggler can't grow unbounded.
4767	#[tokio::test]
4768	async fn growth_on_demoted_group_is_billed() {
4769		tokio::time::pause();
4770
4771		let (mut producer, pool) = pooled_producer(2_000);
4772		let mut straggler = producer.append_group().unwrap(); // seq 0
4773		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4774
4775		// The demoted group balloons: no eviction yet (nothing ran), but billed.
4776		straggler
4777			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 10_000]))
4778			.unwrap();
4779
4780		// The next append observes the growth and evicts the straggler.
4781		producer.append_group().unwrap().finish().unwrap(); // seq 2
4782
4783		let consumer = producer.consume();
4784		assert!(consumer.peek_group(0).is_none(), "the ballooned group is evicted");
4785		assert!(pool.used() <= 3_000, "growth is reclaimed: {}", pool.used());
4786	}
4787
4788	/// A stale arrival entry whose sequence was later re-served by fetched backfill
4789	/// must not leak the replacement into arrival-order subscriptions.
4790	#[tokio::test]
4791	async fn refilled_sequence_stays_out_of_subscriptions() {
4792		let (mut producer, _pool) = pooled_producer(1 << 40);
4793		let dynamic = producer.dynamic();
4794		let consumer = producer.consume();
4795
4796		producer.create_group(0u64.into()).unwrap().finish().unwrap();
4797		let aborted = producer.create_group(1u64.into()).unwrap();
4798		aborted.abort(Error::Cancel).unwrap();
4799		producer.create_group(2u64.into()).unwrap().finish().unwrap();
4800
4801		// Re-serve seq 1 as backfill; its slot replaces the aborted one, and the
4802		// old arrival entry for seq 1 now resolves to it.
4803		let pending = consumer.fetch_group(1, None);
4804		let req = dynamic
4805			.requested_group()
4806			.now_or_never()
4807			.expect("should not block")
4808			.unwrap();
4809		let mut group = req.accept(None).unwrap();
4810		group
4811			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"backfill"))
4812			.unwrap();
4813		group.finish().unwrap();
4814		pending.await.unwrap();
4815
4816		// The backfill serves by sequence, but never in arrival order.
4817		assert!(consumer.peek_group(1).is_some());
4818		let mut subscriber = producer.subscribe(None);
4819		assert_eq!(subscriber.assert_group().sequence, 0);
4820		assert_eq!(subscriber.assert_group().sequence, 2);
4821		subscriber.assert_no_group();
4822	}
4823
4824	/// An expired backfill can't hide behind a refreshed one: the eviction-order
4825	/// expiry scans a bounded prefix instead of stopping at the first fresh entry.
4826	#[tokio::test]
4827	async fn expired_backfill_behind_refreshed_reclaimed() {
4828		tokio::time::pause();
4829
4830		let (mut producer, _pool) = pooled_producer(1 << 40);
4831		let dynamic = producer.dynamic();
4832		let consumer = producer.consume();
4833
4834		producer.create_group(5u64.into()).unwrap().finish().unwrap();
4835		for sequence in [2u64, 3u64] {
4836			let pending = consumer.fetch_group(sequence, None);
4837			let req = dynamic
4838				.requested_group()
4839				.now_or_never()
4840				.expect("should not block")
4841				.unwrap();
4842			let mut group = req.accept(None).unwrap();
4843			group
4844				.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4845				.unwrap();
4846			group.finish().unwrap();
4847			pending.await.unwrap();
4848		}
4849
4850		// Keep seq 2 fresh while seq 3 (behind it in eviction order) expires.
4851		tokio::time::advance(Duration::from_secs(4)).await;
4852		consumer.fetch_group(2, None).await.unwrap();
4853		tokio::time::advance(DEFAULT_LATENCY_MAX - Duration::from_secs(2)).await;
4854		producer.create_group(6u64.into()).unwrap().finish().unwrap();
4855
4856		let consumer = producer.consume();
4857		assert!(consumer.peek_group(2).is_some(), "refreshed backfill survives");
4858		assert!(consumer.peek_group(3).is_none(), "expired backfill is reclaimed");
4859	}
4860
4861	/// A FETCH hit within the same coarse clock tick still protects the group: the
4862	/// refresh stamps one tick ahead, so it reads strictly newer than the mean.
4863	#[tokio::test]
4864	async fn same_tick_fetch_protects() {
4865		tokio::time::pause();
4866
4867		// No time advances at all: every timestamp lands in the same tick.
4868		let (mut producer, _pool) = pooled_producer(10_000);
4869		let consumer = producer.consume();
4870
4871		finished_group(&mut producer, 3_000); // seq 0
4872		finished_group(&mut producer, 3_000); // seq 1
4873		finished_group(&mut producer, 3_000); // seq 2
4874
4875		consumer.fetch_group(0, None).await.unwrap();
4876
4877		finished_group(&mut producer, 3_000); // seq 3
4878		finished_group(&mut producer, 3_000); // seq 4
4879
4880		assert!(consumer.peek_group(0).is_some(), "same-tick refresh protects");
4881		assert!(consumer.peek_group(1).is_none(), "the unread group dies instead");
4882	}
4883
4884	/// A refetched group that reclaims max_sequence is the live edge again: it must
4885	/// not re-enter the eviction order, or memory pressure could evict the newest
4886	/// content.
4887	#[tokio::test]
4888	async fn refetched_latest_stays_protected() {
4889		tokio::time::pause();
4890
4891		let (mut producer, _pool) = pooled_producer(10_000);
4892		let dynamic = producer.dynamic();
4893		let consumer = producer.consume();
4894
4895		let straggler = producer.append_group().unwrap(); // seq 0
4896
4897		// The publisher aborts its own latest group; the sequence stays at the live edge.
4898		let latest = producer.append_group().unwrap(); // seq 1
4899		latest.abort(Error::Cancel).unwrap();
4900
4901		// Re-fetch it: the replacement takes over max_sequence.
4902		let pending = consumer.fetch_group(1, None);
4903		let req = dynamic
4904			.requested_group()
4905			.now_or_never()
4906			.expect("should not block")
4907			.unwrap();
4908		let mut group = req.accept(None).unwrap();
4909		group
4910			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 1000]))
4911			.unwrap();
4912		group.finish().unwrap();
4913		pending.await.unwrap();
4914
4915		// The refetched latest is protected by omission: it has no entry in the
4916		// eviction order, so no amount of debt can select it.
4917		{
4918			let state = producer.state.read();
4919			assert!(state.lookup.contains_key(&1), "refetched group is cached");
4920			assert!(
4921				state.evict.iter().all(|(sequence, _)| *sequence != 1),
4922				"the live edge must not be an eviction candidate"
4923			);
4924		}
4925		drop(straggler);
4926	}
4927
4928	/// An evicted group is a cache miss, so a fetch re-fetches it and the accepted
4929	/// replacement serves the sequence again (not `Error::Duplicate`).
4930	#[tokio::test]
4931	async fn eviction_allows_refetch() {
4932		tokio::time::pause();
4933
4934		let (mut producer, _pool) = pooled_producer(10_000);
4935		let dynamic = producer.dynamic();
4936
4937		finished_group(&mut producer, 10_000); // seq 0
4938		finished_group(&mut producer, 10_000); // seq 1: demotes seq 0
4939		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4940
4941		let consumer = producer.consume();
4942		assert!(consumer.peek_group(0).is_none());
4943		let pending = consumer.fetch_group(0, None);
4944
4945		let req = dynamic
4946			.requested_group()
4947			.now_or_never()
4948			.expect("should not block")
4949			.unwrap();
4950		assert_eq!(req.sequence(), 0);
4951
4952		let mut group = req.accept(None).unwrap();
4953		group
4954			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"refetched"))
4955			.unwrap();
4956		group.finish().unwrap();
4957
4958		let mut group = pending.await.unwrap();
4959		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"refetched");
4960	}
4961
4962	/// A fetched (backfill) group is served by sequence but never replayed to
4963	/// arrival-order subscribers.
4964	#[tokio::test]
4965	async fn fetched_backfill_not_subscribed() {
4966		let (mut producer, _pool) = pooled_producer(1 << 40);
4967		let dynamic = producer.dynamic();
4968		let consumer = producer.consume();
4969
4970		// The publisher starts at seq 5; earlier groups exist only upstream.
4971		producer.create_group(5u64.into()).unwrap().finish().unwrap();
4972		producer.create_group(6u64.into()).unwrap().finish().unwrap();
4973
4974		// Fetch the gap: it lands in the cache and resolves the fetch...
4975		let pending = consumer.fetch_group(2, None);
4976		let req = dynamic
4977			.requested_group()
4978			.now_or_never()
4979			.expect("should not block")
4980			.unwrap();
4981		let mut group = req.accept(None).unwrap();
4982		group
4983			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"backfill"))
4984			.unwrap();
4985		group.finish().unwrap();
4986		let mut fetched = pending.await.unwrap();
4987		assert_eq!(&fetched.read_frame().await.unwrap().unwrap().payload[..], b"backfill");
4988		assert!(consumer.peek_group(2).is_some(), "backfill is cached for later fetches");
4989
4990		// ...but an arrival-order subscriber only sees the live groups.
4991		let mut subscriber = producer.subscribe(None);
4992		assert_eq!(subscriber.assert_group().sequence, 5);
4993		assert_eq!(subscriber.assert_group().sequence, 6);
4994		subscriber.assert_no_group();
4995	}
4996
4997	/// Fetched backfill isn't in arrival order, so it ages out through the eviction
4998	/// order instead of lingering until the track closes.
4999	#[tokio::test]
5000	async fn expired_backfill_reclaimed() {
5001		tokio::time::pause();
5002
5003		let (mut producer, pool) = pooled_producer(1 << 40);
5004		let dynamic = producer.dynamic();
5005		let consumer = producer.consume();
5006
5007		producer.create_group(5u64.into()).unwrap().finish().unwrap();
5008
5009		// Serve a backfill fetch for an old sequence.
5010		let pending = consumer.fetch_group(2, None);
5011		let req = dynamic
5012			.requested_group()
5013			.now_or_never()
5014			.expect("should not block")
5015			.unwrap();
5016		let mut group = req.accept(None).unwrap();
5017		group
5018			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 1000]))
5019			.unwrap();
5020		group.finish().unwrap();
5021		pending.await.unwrap();
5022		let used = pool.used();
5023
5024		// Age past the track window; the next write reclaims the backfill.
5025		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
5026		producer.create_group(6u64.into()).unwrap().finish().unwrap();
5027
5028		assert!(consumer.peek_group(2).is_none(), "expired backfill is reclaimed");
5029		assert!(pool.used() < used, "its bytes are released");
5030	}
5031
5032	#[tokio::test]
5033	async fn fetch_aborts_with_track() {
5034		let producer = track_producer("test", None);
5035		let dynamic = producer.dynamic();
5036		let consumer = producer.consume();
5037
5038		let pending = consumer.fetch_group(3, None);
5039		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
5040
5041		producer.abort(Error::Cancel).unwrap();
5042		assert!(pending.await.is_err());
5043		drop(dynamic);
5044	}
5045}