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		//
1467		// `abort()` closes the channel, so `write()` returns `Err(Ref)`. `finish()`
1468		// leaves it open with `final_sequence` set, so inspect both outcomes.
1469		match self.state.write() {
1470			Ok(mut state) => {
1471				if state.final_sequence.is_some() || state.abort.is_some() {
1472					return;
1473				}
1474				tracing::warn!(
1475					track = %self.name,
1476					"track::Producer dropped without finish() or abort()"
1477				);
1478				state.clear_cache();
1479				state.datagrams.clear();
1480			}
1481			Err(state) => {
1482				if state.final_sequence.is_some() || state.abort.is_some() {
1483					return;
1484				}
1485				tracing::warn!(
1486					track = %self.name,
1487					"track::Producer dropped without finish() or abort()"
1488				);
1489			}
1490		}
1491	}
1492}
1493
1494/// Aggregate every live subscriber's preferences into the most demanding request.
1495///
1496/// Read-only: iterates the subscriptions immutably and registers `waiter` on each, so a
1497/// preference update (or a subscriber dropping) wakes the caller's poll. Callers decide
1498/// readiness from the returned value, then prune closed subscribers through the `Mut`.
1499fn combined_subscription(subs: &Subscriptions, bound: Option<Duration>, waiter: &kio::Waiter) -> Option<Subscription> {
1500	let mut combined = None;
1501	for sub in subs.iter() {
1502		// A closed consumer means the subscriber dropped: it holds no live demand.
1503		// `Consumer::poll` evaluates the closure before the closed flag, so it would
1504		// still replay the final value into the aggregate; skip it explicitly so a
1505		// departed subscriber can't keep the aggregate pinned to its last request.
1506		if sub.is_closed() {
1507			continue;
1508		}
1509		// Arm the closed waiter explicitly. `poll` below registers on the value
1510		// channel only when it returns Pending, so a subscriber that contributes
1511		// demand (always the case for the first one) would leave nothing watching
1512		// for its departure, and the last one leaving would never wake this poll.
1513		let _ = sub.poll_closed(waiter);
1514		if let Poll::Ready(Ok(sub)) = sub.poll(waiter, |sub| sub.poll_combined(&combined)) {
1515			combined = Some(sub);
1516		}
1517	}
1518	clamp_combined(combined, bound)
1519}
1520
1521/// A non-blocking aggregate of the current subscriptions, without arming any waiter.
1522fn snapshot_subscription(subs: &kio::Shared<Subscriptions>, bound: Option<Duration>) -> Option<Subscription> {
1523	let mut combined: Option<Subscription> = None;
1524	for sub in subs.read().iter() {
1525		// Skip dropped subscribers, matching `combined_subscription`.
1526		if sub.is_closed() {
1527			continue;
1528		}
1529		if let Poll::Ready(merged) = sub.read().poll_combined(&combined) {
1530			combined = Some(merged);
1531		}
1532	}
1533	clamp_combined(combined, bound)
1534}
1535
1536/// Clamp the aggregate's latency budget to the publisher's window: nobody can wait for a
1537/// late group longer than the publisher keeps it around.
1538///
1539/// The single clamp point. Subscribers hold their preferences verbatim, so what they asked
1540/// for stays readable, and clamping the aggregate is equivalent to clamping each subscriber
1541/// first (`min` distributes over the `max` that combines them). `bound` is `None` on a track
1542/// whose info isn't known yet (an unaccepted [`Request`]), which imposes no window.
1543fn clamp_combined(combined: Option<Subscription>, bound: Option<Duration>) -> Option<Subscription> {
1544	let mut combined = combined?;
1545	if let Some(bound) = bound {
1546		combined.latency_max = combined.latency_max.min(bound);
1547	}
1548	Some(combined)
1549}
1550
1551/// Register a subscription if the track is live: clone the shared list out of the
1552/// state, release the track lock, then push under the list's own lock. A closed
1553/// track skips the push; nothing aggregates the preferences anymore.
1554fn register_subscription(state: kio::Ref<'_, TrackState>, subscription: &kio::Producer<Subscription>) {
1555	if state.is_closed() {
1556		return;
1557	}
1558	let subs = state.subscriptions.clone();
1559	drop(state);
1560	subs.lock().push(subscription.consume());
1561}
1562
1563/// A weak reference to a track that doesn't prevent auto-close.
1564#[derive(Clone)]
1565pub(crate) struct TrackWeak {
1566	name: Arc<str>,
1567	state: kio::ProducerWeak<TrackState>,
1568}
1569
1570impl TrackWeak {
1571	pub fn consume(&self) -> Consumer {
1572		Consumer::plain(self.name.clone(), self.state.consume())
1573	}
1574
1575	/// The shared name handle, for use as a broadcast lookup key (clone is a
1576	/// refcount bump, and the same `Arc` is shared with the track's handles).
1577	pub(crate) fn name(&self) -> &Arc<str> {
1578		&self.name
1579	}
1580
1581	/// Whether anyone is consuming the track right now. A closed track doesn't
1582	/// count even if consumers linger to drain its cache: no new work is owed.
1583	pub(crate) fn is_used(&self) -> bool {
1584		!self.state.is_closed() && self.state.is_used()
1585	}
1586
1587	/// Park `waiter` for the next consumer appearing; a no-op once one exists.
1588	/// Feeds [`crate::broadcast::Demand`], which recomputes on wake.
1589	pub(crate) fn poll_used(&self, waiter: &kio::Waiter) {
1590		let _ = self.state.poll_used(waiter);
1591	}
1592
1593	/// Park `waiter` for the last consumer (or the track) going away; a no-op
1594	/// once none remain. Feeds [`crate::broadcast::Demand`].
1595	pub(crate) fn poll_unused(&self, waiter: &kio::Waiter) {
1596		let _ = self.state.poll_unused(waiter);
1597	}
1598}
1599
1600impl super::WeakEntry for TrackWeak {
1601	fn is_closed(&self) -> bool {
1602		self.state.is_closed()
1603	}
1604
1605	fn same_channel(&self, other: &Self) -> bool {
1606		self.state.same_channel(&other.state)
1607	}
1608}
1609
1610/// A cloneable, watch-only handle to a track's subscriber demand.
1611///
1612/// Obtained from [`Producer::demand`]. A publisher uses it to react to
1613/// whether anyone is subscribed (on-demand capture / encoding) without being able
1614/// to publish frames or close the track. It's a weak handle, so it neither keeps
1615/// the track alive nor pins its cached groups; once the owning [`Producer`]
1616/// goes away, [`used`](Self::used) / [`unused`](Self::unused) report the track's
1617/// closure.
1618#[derive(Clone)]
1619pub struct Demand {
1620	name: Arc<str>,
1621	state: kio::ProducerWeak<TrackState>,
1622}
1623
1624impl Demand {
1625	/// The track name this handle is bound to.
1626	pub fn name(&self) -> &str {
1627		&self.name
1628	}
1629
1630	/// Block until there is at least one active consumer.
1631	pub async fn used(&self) -> Result<()> {
1632		self.state.used().await.map_err(|_| self.abort_reason())
1633	}
1634
1635	/// Block until there are no active consumers.
1636	pub async fn unused(&self) -> Result<()> {
1637		self.state.unused().await.map_err(|_| self.abort_reason())
1638	}
1639
1640	/// Block until the track is closed or aborted, returning the cause.
1641	pub async fn closed(&self) -> Error {
1642		self.state.closed().await;
1643		self.abort_reason()
1644	}
1645
1646	/// The recorded abort reason, or [`Error::Dropped`] if the track closed without one.
1647	fn abort_reason(&self) -> Error {
1648		self.state.read().abort.clone().unwrap_or(Error::Dropped)
1649	}
1650}
1651
1652/// A handle to a single track within a broadcast.
1653///
1654/// Obtained from [`broadcast::Consumer::track`]. Holding it sends nothing
1655/// to the publisher; it just names a track you can [`subscribe`](Self::subscribe)
1656/// to (a live, ongoing stream of groups) later. The same handle can be subscribed
1657/// to multiple times, and clones are cheap.
1658///
1659/// A track reached through a route-fed broadcast is *spliced*: it is backed by one
1660/// or more per-session tracks joined at group boundaries, and this handle reads
1661/// across them transparently.
1662#[derive(Clone)]
1663pub struct Consumer {
1664	name: Arc<str>,
1665	inner: ConsumerKind,
1666	// Egress stats scope, set by a tagged [`broadcast::Consumer`] via
1667	// [`Self::with_stats`]. Empty (no-op) for an untagged track.
1668	stats: stats::Scope,
1669}
1670
1671#[derive(Clone)]
1672enum ConsumerKind {
1673	Plain(kio::Consumer<TrackState>),
1674	Spliced(super::resume::Consumer),
1675}
1676
1677impl Consumer {
1678	fn plain(name: Arc<str>, state: kio::Consumer<TrackState>) -> Self {
1679		Self {
1680			name,
1681			inner: ConsumerKind::Plain(state),
1682			stats: stats::Scope::default(),
1683		}
1684	}
1685
1686	/// A consumer over a spliced logical track (a route-fed broadcast's track).
1687	pub(crate) fn spliced(name: Arc<str>, resume: super::resume::Consumer) -> Self {
1688		Self {
1689			name,
1690			inner: ConsumerKind::Spliced(resume),
1691			stats: stats::Scope::default(),
1692		}
1693	}
1694
1695	/// Attach an egress stats scope, inherited by the subscriptions, fetches, and
1696	/// groups derived from this handle. Called by a tagged [`broadcast::Consumer`].
1697	pub(crate) fn with_stats(mut self, scope: stats::Scope) -> Self {
1698		self.stats = scope;
1699		self
1700	}
1701
1702	/// The track name this handle is bound to.
1703	pub fn name(&self) -> &str {
1704		&self.name
1705	}
1706
1707	/// Open a live subscription.
1708	///
1709	/// Registers the subscription on the track and returns a [`kio::Pending`] that resolves to the
1710	/// [`Subscriber`] once the track info is available, or the track's abort error (or
1711	/// [`Error::Dropped`]) if it is already closed.
1712	pub fn subscribe(&self, subscription: impl Into<Option<Subscription>>) -> kio::Pending<Subscribing> {
1713		let subscription = kio::Producer::new(subscription.into().unwrap_or_default());
1714
1715		let inner = match &self.inner {
1716			ConsumerKind::Plain(state) => {
1717				// Register the subscription if the track is live. If it is already closed, the
1718				// returned future resolves to the abort error via `Subscribing::poll_ok`.
1719				register_subscription(state.read(), &subscription);
1720				SubscribingKind::Plain(state.clone())
1721			}
1722			// A spliced subscription registers per segment once the subscriber polls.
1723			ConsumerKind::Spliced(resume) => SubscribingKind::Spliced(resume.clone()),
1724		};
1725
1726		kio::Pending::new(Subscribing {
1727			name: self.name.clone(),
1728			inner,
1729			subscription,
1730			stats: self.stats.clone(),
1731		})
1732	}
1733
1734	// Peek at a cached group by sequence without blocking, or `None` if it isn't in the
1735	// cache. A test hook for asserting cache state; the library reads
1736	// `TrackState::cached_group` directly, and callers want `fetch_group`.
1737	#[cfg(test)]
1738	pub(crate) fn peek_group(&self, sequence: u64) -> Option<group::Consumer> {
1739		match &self.inner {
1740			ConsumerKind::Plain(state) => state.read().cached_group(sequence),
1741			// Spliced tracks have no cache of their own; peek the newest segment
1742			// via `fetch_group` instead.
1743			ConsumerKind::Spliced(_) => None,
1744		}
1745	}
1746
1747	/// Fetching a single past group, without holding a live subscription.
1748	///
1749	/// Returns a [`kio::Pending`] that resolves to the [`group::Consumer`]:
1750	/// immediately if the group is cached, otherwise once a [`Dynamic`] serves
1751	/// the request (a wire FETCH for a relay). `options` accepts `None`, a [`group::Fetch`],
1752	/// or `group::Fetch::default()`.
1753	///
1754	/// The returned future resolves to [`Error::NotFound`] when the group can never be served
1755	/// (past the final sequence, or no [`Dynamic`] on the track), or the track's abort error
1756	/// if it's already closed. Concurrent fetches for the same sequence coalesce onto one
1757	/// handler request.
1758	pub fn fetch_group(&self, sequence: u64, options: impl Into<Option<group::Fetch>>) -> kio::Pending<Fetching> {
1759		let options = options.into().unwrap_or_default();
1760
1761		// One fetch per calling context, counted here (coalesced upstream work is
1762		// still one request served). Independent of `subscriptions` and the viewer
1763		// refcount.
1764		self.stats.fetch();
1765
1766		let state = match &self.inner {
1767			ConsumerKind::Plain(state) => state,
1768			// Spliced: routed to the newest segment's (plain) track, waiting for a
1769			// segment to exist if no route has served the track yet.
1770			ConsumerKind::Spliced(resume) => {
1771				return kio::Pending::new(Fetching {
1772					inner: FetchingKind::Spliced(resume.fetch_group(sequence, options)),
1773					stats: self.stats.clone(),
1774				});
1775			}
1776		};
1777
1778		let mut result = None;
1779
1780		// Queue a request only when the group isn't already resolvable from the track
1781		// (cached, aborted, or past-final all resolve through `Fetching::poll` without
1782		// a queue entry).
1783		let (fetch, unresolved) = {
1784			let state = state.read();
1785			(state.fetch.clone(), state.poll_fetch_cached(sequence).is_pending())
1786		};
1787
1788		if unresolved {
1789			let mut fetch = fetch.lock();
1790			if let Some(pending) = fetch.join(&sequence) {
1791				// Join the in-flight attempt for this sequence (queued or already being
1792				// served): share its result channel, raising its priority if ours is higher.
1793				pending.priority = pending.priority.max(options.priority);
1794				result = Some(pending.result.consume());
1795			} else {
1796				// Queue a new attempt. The handler gate is atomic with a handler
1797				// dropping (no fetch stranded on a queue nobody drains); with no
1798				// handler, `Fetching::poll` fails fast instead.
1799				let producer = kio::Producer::<FetchOutcome>::default();
1800				let consumer = producer.consume();
1801				let attempt = PendingFetch {
1802					priority: options.priority,
1803					result: producer,
1804				};
1805				if fetch.insert(sequence, attempt).is_ok() {
1806					result = Some(consumer);
1807				}
1808			}
1809		}
1810
1811		kio::Pending::new(Fetching {
1812			inner: FetchingKind::Plain {
1813				state: state.clone(),
1814				fetch,
1815				sequence,
1816				result,
1817			},
1818			stats: self.stats.clone(),
1819		})
1820	}
1821
1822	/// Resolve the track's [`Info`] without subscribing.
1823	///
1824	/// A [`Consumer`] is a lazy handle, so the info may not be known yet: this waits
1825	/// for the producer to [`Request::accept`] the track (a wire TRACK_INFO round-trip
1826	/// for a relay), and errors with the track's abort error if it closes first.
1827	/// [`Subscriber::info`] is the already-resolved counterpart.
1828	pub fn info(&self) -> kio::Pending<Querying> {
1829		kio::Pending::new(Querying {
1830			inner: match &self.inner {
1831				ConsumerKind::Plain(state) => QueryingKind::Plain(state.clone()),
1832				ConsumerKind::Spliced(resume) => QueryingKind::Spliced(resume.clone()),
1833			},
1834		})
1835	}
1836
1837	/// Return the latest group sequence in the track, or `None` before any group.
1838	pub fn latest(&self) -> Option<u64> {
1839		match &self.inner {
1840			ConsumerKind::Plain(state) => state.read().max_sequence,
1841			ConsumerKind::Spliced(resume) => resume.latest(),
1842		}
1843	}
1844
1845	/// Poll for the track reaching a terminal state: `Ok(())` once it is complete
1846	/// (the final group was produced), `Err` once it closed or aborted before
1847	/// completing. The origin's dispatcher uses this to tell a track that truly
1848	/// ended from one whose serving route died mid-stream.
1849	pub(crate) fn poll_complete(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
1850		let ConsumerKind::Plain(state) = &self.inner else {
1851			// Spliced tracks are compositions; the dispatcher never monitors one.
1852			return Poll::Pending;
1853		};
1854		match ready!(state.poll(waiter, |state| {
1855			if state.is_complete() {
1856				Poll::Ready(())
1857			} else {
1858				Poll::Pending
1859			}
1860		})) {
1861			Ok(_) => Poll::Ready(Ok(())),
1862			// Closed before completing. Read through the returned guard: it holds
1863			// the lock, so re-locking the channel here would deadlock.
1864			Err(closed) => Poll::Ready(Err(closed.abort.clone().unwrap_or(Error::Dropped))),
1865		}
1866	}
1867}
1868
1869/// The pollable state of a [`Consumer::subscribe`]; awaited via the
1870/// [`kio::Pending`] wrapper, whose `DerefMut` exposes [`Self::update`].
1871pub struct Subscribing {
1872	name: Arc<str>,
1873	inner: SubscribingKind,
1874	subscription: kio::Producer<Subscription>,
1875	stats: stats::Scope,
1876}
1877
1878enum SubscribingKind {
1879	Plain(kio::Consumer<TrackState>),
1880	Spliced(super::resume::Consumer),
1881}
1882
1883impl Subscribing {
1884	/// Poll until the peer confirms the subscription, yielding the [`Subscriber`].
1885	/// Errors if the track is aborted or not found.
1886	pub fn poll_ok(&self, waiter: &kio::Waiter) -> Poll<Result<Subscriber>> {
1887		match &self.inner {
1888			SubscribingKind::Plain(state) => {
1889				// Wait until the track info is available
1890				let info = ready!(state.poll(waiter, |state| state.poll_info()))
1891					.map_err(|e| e.abort.clone().unwrap_or(Error::Dropped))??;
1892
1893				Poll::Ready(Ok(Subscriber {
1894					name: self.name.clone(),
1895					info,
1896					inner: SubscriberKind::Plain(PlainSubscriber {
1897						state: state.clone(),
1898						subscription: self.subscription.clone(),
1899						index: 0,
1900						datagram_index: 0,
1901						min_sequence: 0,
1902						next_sequence: 0,
1903						end_sequence: None,
1904					}),
1905					stats: self.stats.clone(),
1906					_stats_sub: self.stats.subscribe(),
1907				}))
1908			}
1909			SubscribingKind::Spliced(resume) => {
1910				// Resolved from the first segment's track. The publisher's latency
1911				// window is applied to each per-session aggregate, not here.
1912				let info = ready!(resume.poll_info(waiter))?;
1913
1914				Poll::Ready(Ok(Subscriber {
1915					name: self.name.clone(),
1916					info,
1917					inner: SubscriberKind::Spliced(Box::new(resume.subscribe_shared(self.subscription.clone()))),
1918					stats: self.stats.clone(),
1919					_stats_sub: self.stats.subscribe(),
1920				}))
1921			}
1922		}
1923	}
1924
1925	/// Change the subscription preferences before (or after) it resolves.
1926	///
1927	/// Returns [`Error::Closed`] if the track already ended; the update is
1928	/// meaningless at that point and can usually be ignored.
1929	pub fn update(&mut self, subscription: Subscription) -> Result<()> {
1930		let mut state = self.subscription.write().map_err(|_| Error::Closed)?;
1931		*state = subscription;
1932		Ok(())
1933	}
1934}
1935
1936impl kio::Pollable for Subscribing {
1937	type Output = Result<Subscriber>;
1938
1939	fn poll(&self, waiter: &kio::Waiter) -> Poll<Self::Output> {
1940		self.poll_ok(waiter)
1941	}
1942}
1943
1944/// The pollable state of a [`Consumer::info`]; awaited via the
1945/// [`kio::Pending`] wrapper.
1946pub struct Querying {
1947	inner: QueryingKind,
1948}
1949
1950enum QueryingKind {
1951	Plain(kio::Consumer<TrackState>),
1952	Spliced(super::resume::Consumer),
1953}
1954
1955impl Querying {
1956	/// Poll until the track's [`Info`] is known, without subscribing to its groups.
1957	pub fn poll_ok(&self, waiter: &kio::Waiter) -> Poll<Result<Info>> {
1958		match &self.inner {
1959			QueryingKind::Plain(state) => {
1960				// Wait until the track info is available
1961				let info = ready!(state.poll(waiter, |state| state.poll_info()))
1962					.map_err(|e| e.abort.clone().unwrap_or(Error::Dropped))??;
1963				Poll::Ready(Ok(info))
1964			}
1965			QueryingKind::Spliced(resume) => resume.poll_info(waiter),
1966		}
1967	}
1968}
1969
1970impl kio::Pollable for Querying {
1971	type Output = Result<Info>;
1972
1973	fn poll(&self, waiter: &kio::Waiter) -> Poll<Self::Output> {
1974		self.poll_ok(waiter)
1975	}
1976}
1977
1978/// A consumer's request for a single past group, handed to a handler via
1979/// [`Dynamic::requested_group`].
1980///
1981/// The handler fulfills it by calling [`Self::accept`], which inserts the group
1982/// into the track cache (resolving every [`Consumer::fetch_group`] that joined the
1983/// attempt) and returns a [`group::Producer`] to fill. A relay typically opens a wire
1984/// FETCH, reads FETCH_OK, then accepts. The request carries its own producer handle,
1985/// so it works the same whether or not the track has been accepted yet.
1986pub struct GroupRequest {
1987	state: kio::Producer<TrackState>,
1988	// To remove this attempt from the fetch state once it resolves.
1989	fetch: kio::Shared<FetchState>,
1990	sequence: u64,
1991	priority: u8,
1992	// Rejections route back to every joined `Fetching`.
1993	result: kio::Producer<FetchOutcome>,
1994	done: bool,
1995}
1996
1997impl GroupRequest {
1998	/// The group sequence the consumer wants.
1999	pub fn sequence(&self) -> u64 {
2000		self.sequence
2001	}
2002
2003	/// The delivery priority the consumer requested for this group.
2004	pub fn priority(&self) -> u8 {
2005		self.priority
2006	}
2007
2008	/// Insert the fetched group into the track cache, resolving the waiting
2009	/// [`Consumer::fetch_group`], and return a [`group::Producer`] to fill.
2010	///
2011	/// The group's timescale comes from the track's [`Info`]. `info` sets that
2012	/// info if the track hasn't been accepted yet (a fetch with no live subscription),
2013	/// and is ignored once accepted. Returns [`Error::Duplicate`] if the group is
2014	/// already present, or the track's abort error if it closed while pending.
2015	pub fn accept(mut self, info: impl Into<Option<Info>>) -> Result<group::Producer> {
2016		self.done = true;
2017		// Cache the group before removing the attempt: the joined fetches resolve
2018		// through the cache, and removal closes their result channel (which alone
2019		// would read as NotFound).
2020		let res = TrackState::modify(&self.state)
2021			.and_then(|mut state| state.insert_group_request(self.sequence, info.into()));
2022		self.remove();
2023		res
2024	}
2025
2026	/// Reject the fetch, resolving every joined [`Consumer::fetch_group`] with `err`.
2027	pub fn reject(mut self, err: Error) {
2028		self.done = true;
2029		// Remove before writing, so a fetch arriving now starts a fresh attempt
2030		// instead of joining a rejected one.
2031		self.remove();
2032		if let Ok(mut outcome) = self.result.write() {
2033			outcome.rejected = Some(err);
2034		}
2035	}
2036
2037	/// Remove this attempt from the fetch state, unless a newer attempt for the same
2038	/// sequence has already replaced it.
2039	fn remove(&self) {
2040		self.fetch
2041			.lock()
2042			.remove_if(&self.sequence, |pending| pending.result.same_channel(&self.result));
2043	}
2044}
2045
2046impl Drop for GroupRequest {
2047	fn drop(&mut self) {
2048		if self.done {
2049			return;
2050		}
2051		self.remove();
2052		if let Ok(mut outcome) = self.result.write() {
2053			outcome.rejected = Some(Error::Dropped);
2054		}
2055	}
2056}
2057
2058/// The pollable state of a [`Consumer::fetch_group`].
2059///
2060/// Awaited via the [`kio::Pending`] wrapper; resolves to the
2061/// [`group::Consumer`] once the group lands in the track's cache (already present,
2062/// or produced after a wire FETCH), or [`Error::NotFound`] if it can never exist.
2063pub struct Fetching {
2064	inner: FetchingKind,
2065	// Egress stats scope, so the resolved group carries a payload meter (and counts
2066	// as one delivered group). Empty (no-op) for an untagged track.
2067	stats: stats::Scope,
2068}
2069
2070enum FetchingKind {
2071	Plain {
2072		state: kio::Consumer<TrackState>,
2073		fetch: kio::Shared<FetchState>,
2074		sequence: u64,
2075		// The joined attempt's result channel; `None` when no handler existed to queue on.
2076		result: Option<kio::Consumer<FetchOutcome>>,
2077	},
2078	/// A spliced track's fetch: waits for a segment, then fetches from it.
2079	Spliced(kio::Pending<super::resume::Fetching>),
2080}
2081
2082impl kio::Pollable for Fetching {
2083	type Output = Result<group::Consumer>;
2084
2085	fn poll(&self, waiter: &kio::Waiter) -> Poll<Self::Output> {
2086		let (state, fetch, sequence, result) = match &self.inner {
2087			FetchingKind::Plain {
2088				state,
2089				fetch,
2090				sequence,
2091				result,
2092			} => (state, fetch, *sequence, result.as_ref()),
2093			FetchingKind::Spliced(spliced) => {
2094				// A fetched group is metered here (once), at the tagged handle: the
2095				// spliced source track it comes from is the origin's own, untagged.
2096				return kio::Pollable::poll(&**spliced, waiter)
2097					.map(|res| res.map(|group| group.with_meter(self.stats.meter())));
2098			}
2099		};
2100
2101		// Track side: the cached group, the abort error, or past-final. The outer
2102		// error is the channel closing without any of those.
2103		match state.poll(waiter, |state| state.poll_fetch_cached(sequence)) {
2104			Poll::Ready(Ok(res)) => return Poll::Ready(res.map(|group| group.with_meter(self.stats.meter()))),
2105			Poll::Ready(Err(closed)) => {
2106				return Poll::Ready(Err(closed.abort.clone().unwrap_or(Error::Dropped)));
2107			}
2108			Poll::Pending => {}
2109		}
2110
2111		// Handler side.
2112		let Some(result) = result else {
2113			// Never queued: no handler existed when the fetch was made. Fail fast while
2114			// that's still true; a handler that appeared since may yet fill the cache.
2115			return match fetch.poll(waiter, |fetch| match fetch.has_handlers() {
2116				false => Poll::Ready(()),
2117				true => Poll::Pending,
2118			}) {
2119				Poll::Ready(_guard) => Poll::Ready(Err(Error::NotFound)),
2120				Poll::Pending => Poll::Pending,
2121			};
2122		};
2123
2124		// A written rejection fails every joined fetch. The channel closing without
2125		// one means the attempt was dropped unserved (its handlers went away).
2126		match result.poll(waiter, |outcome| match &outcome.rejected {
2127			Some(err) => Poll::Ready(err.clone()),
2128			None => Poll::Pending,
2129		}) {
2130			Poll::Ready(Ok(err)) => Poll::Ready(Err(err)),
2131			Poll::Ready(Err(_closed)) => Poll::Ready(Err(Error::NotFound)),
2132			Poll::Pending => Poll::Pending,
2133		}
2134	}
2135}
2136
2137/// A live subscription to a track, used to read its groups.
2138///
2139/// Created via [`Consumer::subscribe`](Consumer::subscribe), or
2140/// directly from a [`Producer`] for an in-process track. Carries this
2141/// subscriber's [`Subscription`] preferences, which feed the producer's aggregate.
2142///
2143/// # Local cursor vs wire preference
2144///
2145/// Group bounds exist at two levels, and setting one does not imply the other:
2146///
2147/// - [`Self::start_at`] / [`Self::end_at`] move **this subscriber's read cursor**. They
2148///   filter exactly what this handle returns and are invisible to the publisher.
2149/// - [`Subscription::group_start`] / [`Subscription::group_end`], set via [`Self::update`],
2150///   are a **request to the publisher**. They're aggregated across every live subscriber
2151///   (earliest start, widest end), so they say what the publisher should send, not what
2152///   this subscriber sees.
2153///
2154/// They stay separate because their scopes differ: a subscriber can't filter by the
2155/// aggregate, since another subscriber can widen it, and the publisher can't honor a
2156/// cursor it's never told about. So setting only the cursor still transfers the skipped
2157/// groups, and setting only the preference still returns groups another subscriber asked
2158/// for. Set both to skip them *and* avoid the transfer.
2159pub struct Subscriber {
2160	name: Arc<str>,
2161	info: Info,
2162	inner: SubscriberKind,
2163	// Egress stats scope, used to meter the groups this subscriber reads. Empty
2164	// (no-op) for an untagged track.
2165	stats: stats::Scope,
2166	// The subscription guard: bumps `subscriptions` (and the egress viewer refcount)
2167	// while held, closing them on drop. Empty (no-op) for an untagged track.
2168	_stats_sub: stats::Subscription,
2169}
2170
2171enum SubscriberKind {
2172	Plain(PlainSubscriber),
2173	// Boxed: the spliced cursor set dwarfs the plain cursor.
2174	Spliced(Box<super::resume::Subscriber>),
2175}
2176
2177/// The cursor state for a subscription over a single (per-session) track.
2178struct PlainSubscriber {
2179	state: kio::Consumer<TrackState>,
2180
2181	subscription: kio::Producer<Subscription>,
2182	/// Arrival-order cursor used by `recv_group`.
2183	index: usize,
2184	/// Arrival-order cursor used by `recv_datagram`, independent of groups.
2185	datagram_index: usize,
2186	/// Minimum sequence to return from any `recv` method. Set by `start_at`.
2187	min_sequence: u64,
2188	/// One past the highest sequence returned by `next_group`.
2189	/// Used only by that method to skip late arrivals; does not affect `recv_group`.
2190	next_sequence: u64,
2191	/// Inclusive upper sequence bound for `next_group`. `None` means no cap. Set by
2192	/// `end_at`; can be raised, lowered, or unset at any time. Groups beyond the
2193	/// cap stay in the producer's cache and become eligible again when the cap
2194	/// rises (or is removed).
2195	end_sequence: Option<u64>,
2196}
2197
2198impl PlainSubscriber {
2199	// A helper to automatically apply Dropped if the state is closed without an error.
2200	fn poll<F, R>(&self, waiter: &kio::Waiter, f: F) -> Poll<Result<R>>
2201	where
2202		F: Fn(&kio::Ref<'_, TrackState>) -> Poll<Result<R>>,
2203	{
2204		Poll::Ready(match ready!(self.state.poll(waiter, f)) {
2205			Ok(res) => res,
2206			// We try to clone abort just in case the function forgot to check for terminal state.
2207			Err(state) => Err(state.abort.clone().unwrap_or(Error::Dropped)),
2208		})
2209	}
2210
2211	fn poll_recv_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2212		let Some((consumer, found_index)) =
2213			ready!(self.poll(waiter, |state| state.poll_recv_group(self.index, self.min_sequence))?)
2214		else {
2215			return Poll::Ready(Ok(None));
2216		};
2217
2218		self.index = found_index + 1;
2219		Poll::Ready(Ok(Some(consumer)))
2220	}
2221
2222	fn poll_recv_datagram(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
2223		let Some((datagram, found_index)) =
2224			ready!(self.poll(waiter, |state| state.poll_recv_datagram(self.datagram_index))?)
2225		else {
2226			return Poll::Ready(Ok(None));
2227		};
2228
2229		self.datagram_index = found_index + 1;
2230		self.next_sequence = self.next_sequence.max(datagram.sequence.saturating_add(1));
2231		Poll::Ready(Ok(Some(datagram)))
2232	}
2233
2234	fn poll_next_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2235		let floor = self.next_sequence.max(self.min_sequence);
2236		let Some(group) = ready!(self.poll(waiter, |state| state.poll_next_in_range(floor, self.end_sequence))?) else {
2237			return Poll::Ready(Ok(None));
2238		};
2239		self.next_sequence = group.sequence.saturating_add(1);
2240		Poll::Ready(Ok(Some(group)))
2241	}
2242
2243	fn poll_read_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Frame>>> {
2244		let lower = self.min_sequence.max(self.next_sequence);
2245		let Some((frame, found_index, sequence)) =
2246			ready!(self.poll(waiter, |state| { state.poll_read_frame(self.index, lower, waiter) })?)
2247		else {
2248			return Poll::Ready(Ok(None));
2249		};
2250
2251		self.index = found_index + 1;
2252		self.next_sequence = sequence.saturating_add(1);
2253		Poll::Ready(Ok(Some(frame)))
2254	}
2255}
2256
2257/// A cloneable handle to a subscriber's delivery preferences.
2258///
2259/// This updates the same subscription as the owning [`Subscriber`] without
2260/// borrowing its read cursor, so callers can change delivery priority, group
2261/// ordering priority, or group bounds while another task is waiting for groups.
2262#[derive(Clone)]
2263pub struct SubscriberControl {
2264	subscription: kio::Producer<Subscription>,
2265}
2266
2267impl SubscriberControl {
2268	/// This subscriber's current preferences.
2269	pub fn subscription(&self) -> Subscription {
2270		self.subscription.read().clone()
2271	}
2272
2273	/// Replace this subscriber's preferences, updating the producer's aggregate.
2274	///
2275	/// Returns [`Error::Closed`] if the track already ended; the update is
2276	/// meaningless at that point and can usually be ignored.
2277	pub fn update(&self, subscription: Subscription) -> Result<()> {
2278		let mut state = self.subscription.write().map_err(|_| Error::Closed)?;
2279		*state = subscription;
2280		Ok(())
2281	}
2282}
2283
2284impl Subscriber {
2285	/// The track's [`Info`], resolved when the subscription was established.
2286	///
2287	/// Free, unlike [`Consumer::info`]: subscribing already waited for the info
2288	/// (SUBSCRIBE_OK on the wire), so a subscriber always has it.
2289	pub fn info(&self) -> &Info {
2290		&self.info
2291	}
2292
2293	/// The track's name, unique within its broadcast.
2294	pub fn name(&self) -> &str {
2295		&self.name
2296	}
2297
2298	/// Create a handle for updating this subscriber's delivery preferences.
2299	pub fn control(&self) -> SubscriberControl {
2300		SubscriberControl {
2301			subscription: match &self.inner {
2302				SubscriberKind::Plain(plain) => plain.subscription.clone(),
2303				SubscriberKind::Spliced(spliced) => spliced.prefs(),
2304			},
2305		}
2306	}
2307
2308	/// Poll for the next group in arrival order, without blocking.
2309	///
2310	/// Returns every group exactly once in the order it landed on the wire, which may be
2311	/// out of sequence due to network reordering or loss. Use [`Self::poll_next_group`] if
2312	/// you only want groups whose sequence number is higher than any previously returned.
2313	///
2314	/// Returns `Poll::Ready(Ok(Some(group)))` when a group is available,
2315	/// `Poll::Ready(Ok(None))` when the track is finished,
2316	/// `Poll::Ready(Err(e))` when the track has been aborted, or
2317	/// `Poll::Pending` when no group is available yet.
2318	pub fn poll_recv_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2319		let meter = self.stats.meter();
2320		let res = match &mut self.inner {
2321			SubscriberKind::Plain(plain) => plain.poll_recv_group(waiter),
2322			SubscriberKind::Spliced(spliced) => spliced.poll_recv_group(waiter),
2323		};
2324		res.map(|res| res.map(|group| group.map(|group| group.with_meter(meter))))
2325	}
2326
2327	/// Receive the next group in arrival order.
2328	///
2329	/// Every group is returned exactly once, in the order it landed on the wire, which may
2330	/// be out of sequence due to network reordering or loss. Use [`Self::next_group`] if you
2331	/// only want groups whose sequence number is higher than any previously returned.
2332	pub async fn recv_group(&mut self) -> Result<Option<group::Consumer>> {
2333		kio::wait(|waiter| self.poll_recv_group(waiter)).await
2334	}
2335
2336	/// Poll for the next datagram in arrival order, without blocking.
2337	///
2338	/// Datagrams are a separate best-effort channel from groups (see
2339	/// [`Producer::append_datagram`]); they share only the sequence namespace. A consumer
2340	/// that falls too far behind silently loses the oldest datagrams.
2341	/// Returning a datagram advances [`Self::poll_next_group`] past that sequence.
2342	///
2343	/// Returns `Poll::Ready(Ok(Some(datagram)))` when one is available,
2344	/// `Poll::Ready(Ok(None))` when the track is finished, `Poll::Ready(Err(e))` when the track
2345	/// is aborted, or `Poll::Pending` when none is buffered yet.
2346	pub fn poll_recv_datagram(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
2347		let meter = self.stats.meter();
2348		let res = match &mut self.inner {
2349			SubscriberKind::Plain(plain) => plain.poll_recv_datagram(waiter),
2350			SubscriberKind::Spliced(spliced) => spliced.poll_recv_datagram(waiter),
2351		};
2352		// Unlike a group (metered lazily as its frames are read), a datagram is
2353		// delivered whole here, so count it as the single-frame group it stands in for.
2354		if let Poll::Ready(Ok(Some(datagram))) = &res {
2355			meter.datagram(datagram.payload.len() as u64);
2356		}
2357		res
2358	}
2359
2360	/// Receive the next datagram in arrival order.
2361	///
2362	/// A best-effort channel parallel to [`Self::recv_group`]; the two share only the sequence
2363	/// namespace. To receive both concurrently from one subscriber, poll [`Self::poll_next_group`]
2364	/// (or [`Self::poll_recv_group`]) and [`Self::poll_recv_datagram`] together in a single `poll`
2365	/// closure (sequential `&mut` borrows), rather than awaiting the two `recv` futures at once.
2366	pub async fn recv_datagram(&mut self) -> Result<Option<Datagram>> {
2367		kio::wait(|waiter| self.poll_recv_datagram(waiter)).await
2368	}
2369
2370	/// Poll for the next group with a higher sequence number than any previously returned.
2371	///
2372	/// Late arrivals (sequence at or below the last returned) are silently skipped, so this
2373	/// produces a monotonically increasing sequence at the cost of dropping out-of-order
2374	/// groups. Use [`Self::poll_recv_group`] to see every group in arrival order instead.
2375	///
2376	/// Honors the cap set by [`Self::end_at`]: groups with sequence past the cap are left
2377	/// in the producer's cache and become eligible again if the cap is raised or removed.
2378	pub fn poll_next_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2379		let meter = self.stats.meter();
2380		let res = match &mut self.inner {
2381			SubscriberKind::Plain(plain) => plain.poll_next_group(waiter),
2382			SubscriberKind::Spliced(spliced) => spliced.poll_next_group(waiter),
2383		};
2384		res.map(|res| res.map(|group| group.map(|group| group.with_meter(meter))))
2385	}
2386
2387	/// Return the next group with a higher sequence number than any previously returned.
2388	///
2389	/// Late arrivals (sequence at or below the last returned) are silently skipped, so this
2390	/// produces a monotonically increasing sequence at the cost of dropping out-of-order
2391	/// groups. Use [`Self::recv_group`] to see every group in arrival order instead.
2392	pub async fn next_group(&mut self) -> Result<Option<group::Consumer>> {
2393		kio::wait(|waiter| self.poll_next_group(waiter)).await
2394	}
2395
2396	/// A helper that calls [`Self::poll_next_group`] and returns its first frame
2397	/// (timestamp and payload), skipping the rest of the group. Intended for
2398	/// single-frame groups (see [`Producer::write_frame`]).
2399	pub fn poll_read_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Frame>>> {
2400		let meter = self.stats.meter();
2401		let res = match &mut self.inner {
2402			SubscriberKind::Plain(plain) => plain.poll_read_frame(waiter),
2403			SubscriberKind::Spliced(spliced) => spliced.poll_read_frame(waiter),
2404		};
2405		// This helper collapses a group to its first frame: count the group, the one
2406		// frame, and the bytes actually read.
2407		if let Poll::Ready(Ok(Some(frame))) = &res {
2408			meter.group();
2409			meter.frames(1);
2410			meter.bytes(frame.payload.len() as u64);
2411		}
2412		res
2413	}
2414
2415	/// Read a single full frame (timestamp and payload) from the next group in
2416	/// sequence order.
2417	///
2418	/// See [`Self::poll_read_frame`] for semantics.
2419	pub async fn read_frame(&mut self) -> Result<Option<frame::Frame>> {
2420		kio::wait(|waiter| self.poll_read_frame(waiter)).await
2421	}
2422
2423	/// Whether `other` was cloned from this subscriber (shares the same underlying state).
2424	pub fn is_clone(&self, other: &Self) -> bool {
2425		match (&self.inner, &other.inner) {
2426			(SubscriberKind::Plain(a), SubscriberKind::Plain(b)) => a.state.same_channel(&b.state),
2427			(SubscriberKind::Spliced(a), SubscriberKind::Spliced(b)) => a.is_clone(b),
2428			_ => false,
2429		}
2430	}
2431
2432	/// Poll for the track's declared final sequence, without blocking.
2433	pub fn poll_finished(&mut self, waiter: &kio::Waiter) -> Poll<Result<u64>> {
2434		match &mut self.inner {
2435			SubscriberKind::Plain(plain) => plain.poll(waiter, |state| state.poll_finished()),
2436			SubscriberKind::Spliced(spliced) => spliced.poll_finished(waiter),
2437		}
2438	}
2439
2440	/// Block until the track declares its end, returning the exclusive final sequence
2441	/// (also the total group count), or the cause on an abort.
2442	///
2443	/// Resolves as soon as the boundary is known, which may be ahead of the live edge
2444	/// when the producer finished via [`Producer::finish_at`]. This reports the declared
2445	/// end, not that every group has arrived: drive [`Self::recv_group`] /
2446	/// [`Self::next_group`] until they yield `None` to observe the track fully drained.
2447	pub async fn finished(&mut self) -> Result<u64> {
2448		kio::wait(|waiter| self.poll_finished(waiter)).await
2449	}
2450
2451	/// Start this subscriber's read cursor at the given sequence.
2452	///
2453	/// A local filter, not a request: it doesn't tell the publisher anything, so the
2454	/// skipped groups are still delivered and simply not returned. To ask the publisher
2455	/// to start there instead, set [`Subscription::group_start`] via [`Self::update`].
2456	/// See [Local cursor vs wire preference](Self#local-cursor-vs-wire-preference).
2457	pub fn start_at(&mut self, sequence: u64) {
2458		match &mut self.inner {
2459			SubscriberKind::Plain(plain) => plain.min_sequence = sequence,
2460			SubscriberKind::Spliced(spliced) => spliced.start_at(sequence),
2461		}
2462	}
2463
2464	/// Cap this subscriber's read cursor at the given sequence (inclusive), or remove the
2465	/// cap entirely.
2466	///
2467	/// Accepts a bare `u64` (cap), `Some(u64)`, or `None` (uncap).
2468	///
2469	/// A local filter, not a request; [`Subscription::group_end`] is the wire-level
2470	/// counterpart. See [Local cursor vs wire preference](Self#local-cursor-vs-wire-preference).
2471	///
2472	/// Affects [`Self::next_group`] only: groups beyond the cap stay in the producer's
2473	/// cache rather than being skipped past, so a later call to [`Self::end_at`] with a
2474	/// higher value (or `None`) makes them available again. Lowering the cap below the
2475	/// consumer's current cursor parks the consumer until the cap is raised.
2476	pub fn end_at(&mut self, sequence: impl Into<Option<u64>>) {
2477		match &mut self.inner {
2478			SubscriberKind::Plain(plain) => plain.end_sequence = sequence.into(),
2479			SubscriberKind::Spliced(spliced) => spliced.end_at(sequence),
2480		}
2481	}
2482
2483	/// This subscriber's current preferences.
2484	pub fn subscription(&self) -> Subscription {
2485		self.control().subscription()
2486	}
2487
2488	/// Replace this subscriber's delivery preferences.
2489	///
2490	/// Stored verbatim; the publisher's latency window is applied to the aggregate, not
2491	/// here (see [`Producer::subscription`]). Returns [`Error::Closed`] if the track
2492	/// already ended; the update is meaningless at that point and can usually be ignored.
2493	pub fn update(&mut self, subscription: Subscription) -> Result<()> {
2494		match &mut self.inner {
2495			SubscriberKind::Plain(plain) => {
2496				let mut state = plain.subscription.write().map_err(|_| Error::Closed)?;
2497				*state = subscription;
2498			}
2499			SubscriberKind::Spliced(spliced) => spliced.update(subscription),
2500		}
2501		Ok(())
2502	}
2503
2504	/// Return the latest sequence number in the track.
2505	pub fn latest(&self) -> Option<u64> {
2506		match &self.inner {
2507			SubscriberKind::Plain(plain) => plain.state.read().max_sequence,
2508			SubscriberKind::Spliced(spliced) => spliced.latest(),
2509		}
2510	}
2511}
2512
2513/// A subscriber asked for a track this broadcast doesn't have yet.
2514///
2515/// Yielded by [`broadcast::Dynamic::requested_track`](crate::broadcast::Dynamic::requested_track),
2516/// or created up front with [`broadcast::Producer::reserve_track`](crate::broadcast::Producer::reserve_track).
2517/// Subscribers block until the request is
2518/// resolved: call [`accept`](Self::accept) to serve it with a [`Producer`], or
2519/// [`reject`](Self::reject) to fail them. Dropping it without either rejects with
2520/// [`Error::Dropped`].
2521///
2522/// Concurrent requests for one name are coalesced, so exactly one of these exists per
2523/// name at a time.
2524pub struct Request {
2525	name: Arc<str>,
2526	// The parent broadcast's info, threaded into the [`Producer`] on accept.
2527	broadcast: Arc<broadcast::Info>,
2528	state: kio::Producer<TrackState>,
2529
2530	// The previous subscription that was combined, used to detect changes.
2531	prev_subscription: Option<Subscription>,
2532
2533	// Shared with the accepted [`Producer`] and every [`Dynamic`]: its `Drop` is the
2534	// teardown, and it stays inert until a producer is minted.
2535	alive: Arc<Alive>,
2536
2537	// A requested track is served on demand, so it counts as fetch-capable from
2538	// birth: a consumer's cache-miss `fetch_group` waits to be served instead of
2539	// racing the producer (e.g. a relay) into creating its own handler. Released
2540	// when the request is accepted or dropped; by then the relay holds its own.
2541	_dynamic: Dynamic,
2542
2543	// Ingress stats scope, threaded into the accepted [`Producer`]. Empty (no-op)
2544	// unless this request was reserved on a tagged broadcast.
2545	stats: stats::Scope,
2546}
2547
2548impl Request {
2549	pub(crate) fn new(broadcast: Arc<broadcast::Info>, name: impl Into<Arc<str>>) -> Self {
2550		let name = name.into();
2551		let state = TrackState::spawn(broadcast.clone());
2552		let alive = Alive::new(name.clone(), state.clone());
2553		let dynamic = Dynamic::new(name.clone(), state.clone(), alive.clone());
2554		Self {
2555			name,
2556			broadcast,
2557			state,
2558			prev_subscription: None,
2559			alive,
2560			_dynamic: dynamic,
2561			stats: stats::Scope::default(),
2562		}
2563	}
2564
2565	/// Attach an ingress stats scope, applied to the [`Producer`] on accept. Set by
2566	/// a tagged [`broadcast::Producer::reserve_track`].
2567	pub(crate) fn with_stats(mut self, scope: stats::Scope) -> Self {
2568		self.stats = scope;
2569		self
2570	}
2571
2572	/// The requested track name.
2573	pub fn name(&self) -> &str {
2574		&self.name
2575	}
2576
2577	/// A [`Consumer`] for the eventual track, usable before the request is accepted.
2578	pub fn consume(&self) -> Consumer {
2579		Consumer::plain(self.name.clone(), self.state.consume())
2580	}
2581
2582	/// Create a [`Dynamic`] handle that serves on-demand fetches of uncached
2583	/// groups, before [`Self::accept`] is even called. A relay creates one to fetch
2584	/// past groups from upstream while (or instead of) serving a live subscription.
2585	pub fn dynamic(&self) -> Dynamic {
2586		Dynamic::new(self.name.clone(), self.state.clone(), self.alive.clone())
2587	}
2588
2589	/// Poll for the request becoming unused (every consumer dropped), so a relay can
2590	/// stop serving and drop the request.
2591	pub fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
2592		self.state.poll_unused(waiter).map(|_| ())
2593	}
2594
2595	/// Serve the request with the given track, resolving every waiting subscriber.
2596	///
2597	/// The name is taken from [`Self::name`]; `info` supplies the remaining knobs
2598	/// (`None` for the defaults). If the track was already aborted, the returned
2599	/// [`Producer`] is inert: writes fail with the abort error, as if it had been
2600	/// aborted immediately after accepting.
2601	pub fn accept(self, info: impl Into<Option<Info>>) -> Producer {
2602		// A closed state means the track was aborted under us. Mirror `reject` and
2603		// tolerate it: the Producer we hand back simply can't write.
2604		if let Ok(mut state) = self.state.write() {
2605			state.install(info.into().unwrap_or_default());
2606		}
2607		// Accepting the request creates the track producer: count it as one ingress
2608		// subscription (closed when the last handle drops). No-op when untagged.
2609		self.alive.publish(Some(&self.stats));
2610		Producer {
2611			name: self.name,
2612			broadcast: self.broadcast,
2613			state: self.state,
2614			prev_subscription: None,
2615			alive: self.alive,
2616			stats: self.stats,
2617		}
2618	}
2619
2620	/// Reject the request, waking all waiting subscribers with `err`.
2621	pub fn reject(self, err: Error) {
2622		if let Ok(mut state) = self.state.write() {
2623			state.abort = Some(err);
2624		}
2625	}
2626
2627	/// The delivery preferences aggregated across everyone waiting on this request,
2628	/// or `None` if nobody is waiting. Useful for sizing the track before accepting.
2629	pub fn subscription(&self) -> Option<Subscription> {
2630		let state = self.state.read();
2631		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
2632		drop(state);
2633		snapshot_subscription(&subs, bound)
2634	}
2635
2636	/// Block until the aggregate [`subscription`](Self::subscription) changes,
2637	/// yielding `None` once nobody is waiting.
2638	pub async fn subscription_changed(&mut self) -> Option<Subscription> {
2639		kio::wait(|waiter| self.poll_subscription_changed(waiter)).await
2640	}
2641
2642	/// Poll counterpart to [`subscription_changed`](Self::subscription_changed).
2643	pub fn poll_subscription_changed(&mut self, waiter: &kio::Waiter) -> Poll<Option<Subscription>> {
2644		let state = self.state.read();
2645		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
2646		drop(state);
2647
2648		let prev = &self.prev_subscription;
2649		let mut combined = None;
2650		let mut guard = ready!(subs.poll(waiter, |subs| {
2651			let next = combined_subscription(subs, bound, waiter);
2652			if &next == prev {
2653				Poll::Pending
2654			} else {
2655				combined = next;
2656				Poll::Ready(())
2657			}
2658		}));
2659		// The aggregate changed: prune any closed subscribers now that we hold the lock.
2660		guard.retain(|sub| !sub.is_closed());
2661		drop(guard);
2662		self.prev_subscription = combined.clone();
2663		Poll::Ready(combined)
2664	}
2665
2666	pub(super) fn weak(&self) -> TrackWeak {
2667		TrackWeak {
2668			name: self.name.clone(),
2669			state: self.state.weak(),
2670		}
2671	}
2672}
2673
2674#[cfg(test)]
2675use futures::FutureExt;
2676
2677#[cfg(test)]
2678#[allow(missing_docs)] // test-only assertion helpers
2679impl Subscriber {
2680	pub fn assert_group(&mut self) -> group::Consumer {
2681		self.recv_group()
2682			.now_or_never()
2683			.expect("group would have blocked")
2684			.expect("would have errored")
2685			.expect("track was closed")
2686	}
2687
2688	pub fn assert_no_group(&mut self) {
2689		assert!(
2690			self.recv_group().now_or_never().is_none(),
2691			"recv_group would not have blocked"
2692		);
2693	}
2694
2695	pub fn assert_not_closed(&mut self) {
2696		assert!(self.finished().now_or_never().is_none(), "should not be closed");
2697	}
2698
2699	pub fn assert_closed(&mut self) {
2700		assert!(self.finished().now_or_never().is_some(), "should be closed");
2701	}
2702
2703	// TODO assert specific errors after implementing PartialEq
2704	pub fn assert_error(&mut self) {
2705		assert!(
2706			self.finished().now_or_never().expect("should not block").is_err(),
2707			"should be error"
2708		);
2709	}
2710
2711	pub fn assert_is_clone(&self, other: &Self) {
2712		assert!(self.is_clone(other), "should be clone");
2713	}
2714
2715	pub fn assert_not_clone(&self, other: &Self) {
2716		assert!(!self.is_clone(other), "should not be clone");
2717	}
2718}
2719
2720#[cfg(test)]
2721mod test {
2722	use super::*;
2723	use crate::model::test_tracing::count_drop_warnings;
2724
2725	/// Mint a track for tests with a default parent broadcast, since tracks are
2726	/// normally born from a [`broadcast::Producer`].
2727	fn track_producer(name: impl Into<Arc<str>>, info: impl Into<Option<Info>>) -> Producer {
2728		Producer::new(Arc::new(broadcast::Info::default()), name, info)
2729	}
2730
2731	/// Helper: count live cached groups in state.
2732	fn live_groups(state: &TrackState) -> usize {
2733		state.lookup.len()
2734	}
2735
2736	/// Helper: get the sequence number of the first live group in arrival order.
2737	fn first_live_sequence(state: &TrackState) -> u64 {
2738		state
2739			.arrival
2740			.iter()
2741			.find(|(sequence, stamp)| state.lookup.get(sequence).is_some_and(|slot| slot.stamp == *stamp))
2742			.map(|(sequence, _)| *sequence)
2743			.unwrap()
2744	}
2745
2746	/// Helper: non-blocking datagram receive that must be ready with a datagram.
2747	fn recv_datagram(dg: &mut Subscriber) -> Datagram {
2748		dg.recv_datagram()
2749			.now_or_never()
2750			.expect("datagram would have blocked")
2751			.expect("would have errored")
2752			.expect("track was closed")
2753	}
2754
2755	#[tokio::test]
2756	async fn append_datagram_shares_group_sequence() {
2757		let mut producer = track_producer("test", None);
2758		let ts = Timestamp::from_millis(10).unwrap();
2759
2760		// Interleave groups and datagrams: they draw from one monotonic counter.
2761		assert_eq!(producer.append_group().unwrap().sequence, 0);
2762		assert_eq!(producer.append_datagram(ts, &b"a"[..]).unwrap(), 1);
2763		assert_eq!(producer.append_group().unwrap().sequence, 2);
2764		assert_eq!(producer.append_datagram(ts, &b"b"[..]).unwrap(), 3);
2765		assert_eq!(producer.latest(), Some(3));
2766	}
2767
2768	#[tokio::test]
2769	async fn append_datagram_roundtrip() {
2770		let mut producer = track_producer("test", None);
2771		let mut dg = producer.subscribe(None);
2772
2773		let ts = Timestamp::from_millis(42).unwrap();
2774		let seq = producer.append_datagram(ts, &b"hello"[..]).unwrap();
2775
2776		let got = recv_datagram(&mut dg);
2777		assert_eq!(got.sequence, seq);
2778		assert_eq!(got.timestamp, ts);
2779		assert_eq!(&got.payload[..], b"hello");
2780	}
2781
2782	#[tokio::test]
2783	async fn write_datagram_preserves_sequence() {
2784		let mut producer = track_producer("test", None);
2785		let mut dg = producer.subscribe(None);
2786
2787		let ts = Timestamp::from_millis(5).unwrap();
2788		// A relay forwarding an upstream datagram keeps its sequence number.
2789		producer
2790			.write_datagram(Datagram {
2791				sequence: 100,
2792				timestamp: ts,
2793				payload: bytes::Bytes::from_static(b"x"),
2794			})
2795			.unwrap();
2796
2797		assert_eq!(recv_datagram(&mut dg).sequence, 100);
2798		// max_sequence advanced, so the next appended group/datagram continues past it.
2799		assert_eq!(producer.append_group().unwrap().sequence, 101);
2800	}
2801
2802	#[tokio::test]
2803	async fn recv_datagram_advances_ordered_group_cursor() {
2804		let mut producer = track_producer("test", None);
2805		let mut subscriber = producer.subscribe(None);
2806		let ts = Timestamp::from_millis(5).unwrap();
2807
2808		producer
2809			.write_datagram(Datagram {
2810				sequence: 5,
2811				timestamp: ts,
2812				payload: bytes::Bytes::from_static(b"x"),
2813			})
2814			.unwrap();
2815		assert_eq!(recv_datagram(&mut subscriber).sequence, 5);
2816
2817		producer.create_group(group::Info { sequence: 3 }).unwrap();
2818		producer.create_group(group::Info { sequence: 6 }).unwrap();
2819
2820		let group = subscriber
2821			.next_group()
2822			.now_or_never()
2823			.expect("group would have blocked")
2824			.expect("would have errored")
2825			.expect("track was closed");
2826		assert_eq!(group.sequence, 6);
2827	}
2828
2829	#[tokio::test]
2830	async fn datagram_normalized_to_track_timescale() {
2831		let info = Info::default().with_timescale(Timescale::MICRO);
2832		let mut producer = track_producer("test", info);
2833		let mut dg = producer.subscribe(None);
2834
2835		// Supplied at millis; stored/emitted at the track's micro timescale.
2836		producer
2837			.append_datagram(Timestamp::from_millis(2).unwrap(), &b"z"[..])
2838			.unwrap();
2839		let got = recv_datagram(&mut dg);
2840		assert_eq!(got.timestamp.scale(), Timescale::MICRO);
2841		assert_eq!(got.timestamp.value(), 2_000);
2842	}
2843
2844	#[tokio::test]
2845	async fn datagram_rejects_oversized() {
2846		let mut producer = track_producer("test", None);
2847		let big = bytes::Bytes::from(vec![0u8; crate::model::datagram::MAX_DATAGRAM_PAYLOAD + 1]);
2848		let ts = Timestamp::from_millis(0).unwrap();
2849		assert!(matches!(
2850			producer.append_datagram(ts, big.clone()),
2851			Err(Error::FrameTooLarge)
2852		));
2853		assert!(matches!(
2854			producer.write_datagram(Datagram {
2855				sequence: 0,
2856				timestamp: ts,
2857				payload: big,
2858			}),
2859			Err(Error::FrameTooLarge)
2860		));
2861	}
2862
2863	#[tokio::test]
2864	async fn datagram_fanout_to_subscribers() {
2865		let mut producer = track_producer("test", None);
2866		// Two independent subscribers, each with its own datagram cursor.
2867		let mut a = producer.subscribe(None);
2868		let mut b = producer.subscribe(None);
2869		let ts = Timestamp::from_millis(1).unwrap();
2870
2871		producer.append_datagram(ts, &b"first"[..]).unwrap();
2872		producer.append_datagram(ts, &b"second"[..]).unwrap();
2873
2874		// Both receive every datagram in order, independently.
2875		assert_eq!(&recv_datagram(&mut a).payload[..], b"first");
2876		assert_eq!(&recv_datagram(&mut a).payload[..], b"second");
2877		assert_eq!(&recv_datagram(&mut b).payload[..], b"first");
2878		assert_eq!(&recv_datagram(&mut b).payload[..], b"second");
2879	}
2880
2881	#[tokio::test]
2882	async fn datagram_evicts_stale() {
2883		tokio::time::pause();
2884
2885		let mut producer = track_producer("test", None);
2886		let mut dg = producer.subscribe(None);
2887		let ts = Timestamp::from_millis(0).unwrap();
2888
2889		producer.append_datagram(ts, &b"old"[..]).unwrap(); // sequence 0
2890
2891		// Age past the send-buffer window, then push a fresh datagram: the stale one is evicted.
2892		tokio::time::advance(MAX_DATAGRAM_AGE + Duration::from_millis(10)).await;
2893		producer.append_datagram(ts, &b"new"[..]).unwrap(); // sequence 1
2894
2895		// A lagging consumer resumes at the oldest still-buffered datagram (the fresh one).
2896		let got = recv_datagram(&mut dg);
2897		assert_eq!(got.sequence, 1);
2898		assert_eq!(&got.payload[..], b"new");
2899	}
2900
2901	#[tokio::test]
2902	async fn datagram_recv_pends_until_written() {
2903		let mut producer = track_producer("test", None);
2904		let mut dg = producer.subscribe(None);
2905
2906		assert!(
2907			dg.recv_datagram().now_or_never().is_none(),
2908			"should block with no datagrams"
2909		);
2910
2911		producer
2912			.append_datagram(Timestamp::from_millis(0).unwrap(), &b"go"[..])
2913			.unwrap();
2914		assert_eq!(&recv_datagram(&mut dg).payload[..], b"go");
2915	}
2916
2917	/// Exercises the full producer -> publisher-encode -> subscriber-decode -> producer seam
2918	/// (everything but the QUIC datagram send/recv), catching any field-order mismatch between
2919	/// the wire codec and the model.
2920	#[tokio::test]
2921	async fn datagram_wire_roundtrip_between_tracks() {
2922		use crate::coding::{Decode, Encode};
2923		use crate::lite;
2924
2925		let version = lite::Version::Lite05;
2926
2927		// Origin publishes a datagram; the publisher reads it and encodes the wire body.
2928		let mut origin = track_producer("test", None);
2929		let mut origin_dg = origin.subscribe(None);
2930		let ts = Timestamp::from_millis(7).unwrap();
2931		let seq = origin.append_datagram(ts, &b"payload"[..]).unwrap();
2932
2933		let d = recv_datagram(&mut origin_dg);
2934		let body = lite::Datagram {
2935			subscribe: 5,
2936			sequence: d.sequence,
2937			timestamp: d.timestamp.value(),
2938			payload: d.payload.clone(),
2939		}
2940		.encode_bytes(version)
2941		.unwrap();
2942
2943		// Subscriber decodes the body and writes it downstream, preserving the sequence.
2944		let mut slice = &body[..];
2945		let wire = lite::Datagram::decode(&mut slice, version).unwrap();
2946		let mut downstream = track_producer("test", None);
2947		let mut downstream_dg = downstream.subscribe(None);
2948		downstream
2949			.write_datagram(Datagram {
2950				sequence: wire.sequence,
2951				timestamp: Timestamp::new(wire.timestamp, Timescale::MILLI).unwrap(),
2952				payload: wire.payload,
2953			})
2954			.unwrap();
2955
2956		let got = recv_datagram(&mut downstream_dg);
2957		assert_eq!(got.sequence, seq);
2958		assert_eq!(got.timestamp, ts);
2959		assert_eq!(&got.payload[..], b"payload");
2960	}
2961
2962	#[tokio::test]
2963	async fn evict_expired_groups() {
2964		tokio::time::pause();
2965
2966		let mut producer = track_producer("test", None);
2967
2968		// Create 3 groups at time 0.
2969		producer.append_group().unwrap(); // seq 0
2970		producer.append_group().unwrap(); // seq 1
2971		producer.append_group().unwrap(); // seq 2
2972
2973		{
2974			let state = producer.state.read();
2975			assert_eq!(live_groups(&state), 3);
2976			assert_eq!(state.offset, 0);
2977		}
2978
2979		// Advance time past the eviction threshold.
2980		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
2981
2982		// Append a new group to trigger eviction.
2983		producer.append_group().unwrap(); // seq 3
2984
2985		// Groups 0, 1, 2 are expired but seq 3 (the live edge) is kept. Their arrival
2986		// entries no longer resolve, so the leading ones are trimmed and the offset
2987		// advances past them.
2988		{
2989			let state = producer.state.read();
2990			assert_eq!(live_groups(&state), 1);
2991			assert_eq!(first_live_sequence(&state), 3);
2992			assert_eq!(state.offset, 3);
2993			assert!(!state.lookup.contains_key(&0));
2994			assert!(!state.lookup.contains_key(&1));
2995			assert!(!state.lookup.contains_key(&2));
2996			assert!(state.lookup.contains_key(&3));
2997		}
2998	}
2999
3000	/// A group whose frames outlive `latency_max` is aged out when the next group starts, but
3001	/// a subscriber that already drained it must still see the clean end of group. Otherwise a
3002	/// track with long groups (a per-minute rollup, say) fails its readers at every boundary.
3003	#[tokio::test]
3004	async fn aging_out_a_finished_group_keeps_the_clean_end() {
3005		tokio::time::pause();
3006
3007		let mut producer = track_producer("test", None);
3008		let mut group = producer.create_group(group::Info { sequence: 0 }).unwrap();
3009		let mut consumer = group.consume();
3010
3011		group
3012			.write_frame(Timestamp::from_millis(0).unwrap(), b"hello".as_slice())
3013			.unwrap();
3014		assert_eq!(consumer.next_frame().await.unwrap().unwrap().size, 5);
3015
3016		// The group stays open well past latency_max, then the next period starts.
3017		tokio::time::advance(DEFAULT_LATENCY_MAX * 12).await;
3018		group.finish().unwrap();
3019		let _next = producer.create_group(group::Info { sequence: 1 }).unwrap();
3020
3021		assert!(consumer.next_frame().await.unwrap().is_none());
3022	}
3023
3024	#[tokio::test]
3025	async fn evict_keeps_max_sequence() {
3026		tokio::time::pause();
3027
3028		let mut producer = track_producer("test", None);
3029		producer.append_group().unwrap(); // seq 0
3030
3031		// Advance time past threshold.
3032		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3033
3034		// Append another group; seq 0 is expired and evicted.
3035		producer.append_group().unwrap(); // seq 1
3036
3037		{
3038			let state = producer.state.read();
3039			assert_eq!(live_groups(&state), 1);
3040			assert_eq!(first_live_sequence(&state), 1);
3041			assert_eq!(state.offset, 1);
3042		}
3043	}
3044
3045	#[tokio::test]
3046	async fn no_eviction_when_fresh() {
3047		tokio::time::pause();
3048
3049		let mut producer = track_producer("test", None);
3050		producer.append_group().unwrap(); // seq 0
3051		producer.append_group().unwrap(); // seq 1
3052		producer.append_group().unwrap(); // seq 2
3053
3054		{
3055			let state = producer.state.read();
3056			assert_eq!(live_groups(&state), 3);
3057			assert_eq!(state.offset, 0);
3058		}
3059	}
3060
3061	#[tokio::test]
3062	async fn consumer_skips_evicted_groups() {
3063		tokio::time::pause();
3064
3065		let mut producer = track_producer("test", None);
3066		producer.append_group().unwrap(); // seq 0
3067
3068		let mut consumer = producer.subscribe(None);
3069
3070		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3071		producer.append_group().unwrap(); // seq 1
3072
3073		// Group 0 was evicted. Consumer should get group 1.
3074		let group = consumer.assert_group();
3075		assert_eq!(group.sequence, 1);
3076	}
3077
3078	#[tokio::test]
3079	async fn cache_age_controls_eviction() {
3080		tokio::time::pause();
3081
3082		// A shorter cache evicts sooner than the default.
3083		let mut producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(1)));
3084		producer.append_group().unwrap(); // seq 0
3085
3086		// Past the custom budget but well within DEFAULT_LATENCY_MAX.
3087		tokio::time::advance(Duration::from_secs(2)).await;
3088		producer.append_group().unwrap(); // seq 1
3089
3090		// Seq 0 is gone because the publisher only keeps groups for 1s.
3091		let state = producer.state.read();
3092		assert_eq!(live_groups(&state), 1);
3093		assert_eq!(first_live_sequence(&state), 1);
3094	}
3095
3096	#[test]
3097	fn latency_max_clamped_to_cache() {
3098		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3099
3100		// A latency budget beyond the cache is capped in the aggregate; a group can't be
3101		// waited for longer than the publisher keeps it. The subscriber's own preference
3102		// is stored verbatim, so what it asked for stays readable.
3103		let mut subscriber = producer.subscribe(Subscription::default().with_latency_max(Duration::from_secs(10)));
3104		assert_eq!(subscriber.subscription().latency_max, Duration::from_secs(10));
3105		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3106
3107		// A budget within the cache is left alone, and ZERO (skip immediately) stays ZERO.
3108		subscriber
3109			.update(Subscription::default().with_latency_max(Duration::from_millis(500)))
3110			.unwrap();
3111		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_millis(500));
3112
3113		subscriber
3114			.update(Subscription::default().with_latency_max(Duration::ZERO))
3115			.unwrap();
3116		assert_eq!(producer.subscription().unwrap().latency_max, Duration::ZERO);
3117	}
3118
3119	/// Mint a track under an origin whose retention ceiling is `cap`, so the
3120	/// track's own window is clamped down to it on bind.
3121	fn track_producer_capped(name: impl Into<Arc<str>>, info: Info, cap: Duration) -> Producer {
3122		let origin = crate::origin::Info::default().with_cache_duration(cap);
3123		Producer::new(Arc::new(broadcast::Info { origin }), name, info)
3124	}
3125
3126	#[test]
3127	fn origin_cache_duration_clamps_latency_max() {
3128		// A publisher asking to keep groups for a minute is capped to the origin's 1s
3129		// ceiling; a publisher already below the ceiling is left alone (it's a min).
3130		let capped = track_producer_capped(
3131			"test",
3132			Info::default().with_latency_max(Duration::from_secs(60)),
3133			Duration::from_secs(1),
3134		);
3135		assert_eq!(capped.state.read().latency_bound(), Some(Duration::from_secs(1)));
3136
3137		let under = track_producer_capped(
3138			"test",
3139			Info::default().with_latency_max(Duration::from_millis(500)),
3140			Duration::from_secs(1),
3141		);
3142		assert_eq!(under.state.read().latency_bound(), Some(Duration::from_millis(500)));
3143	}
3144
3145	#[tokio::test]
3146	async fn origin_cache_duration_caps_eviction() {
3147		tokio::time::pause();
3148
3149		// The publisher wants a 60s window, but the origin caps retention at 1s.
3150		let mut producer = track_producer_capped(
3151			"test",
3152			Info::default().with_latency_max(Duration::from_secs(60)),
3153			Duration::from_secs(1),
3154		);
3155		producer.append_group().unwrap(); // seq 0
3156
3157		// Past the origin ceiling but far within the publisher's own 60s window.
3158		tokio::time::advance(Duration::from_secs(2)).await;
3159		producer.append_group().unwrap(); // seq 1
3160
3161		// Seq 0 is evicted anyway: the origin ceiling wins over the larger publisher window.
3162		let state = producer.state.read();
3163		assert_eq!(live_groups(&state), 1);
3164		assert_eq!(first_live_sequence(&state), 1);
3165	}
3166
3167	#[test]
3168	fn latency_max_clamped_via_every_update_path() {
3169		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3170		let over = Subscription::default().with_latency_max(Duration::from_secs(10));
3171
3172		// The clamp lives in the aggregation, so it applies no matter which entry point
3173		// wrote the raw preference. Previously only `Subscriber::update` clamped.
3174		let mut subscriber = producer.subscribe(over.clone());
3175		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3176
3177		subscriber.control().update(over.clone()).unwrap();
3178		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3179
3180		subscriber.update(over).unwrap();
3181		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3182	}
3183
3184	#[test]
3185	fn latency_max_aggregate_clamps_the_max_across_subscribers() {
3186		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3187
3188		// The aggregate takes the max, then clamps once. Equivalent to clamping each
3189		// subscriber first, since `min` distributes over `max`.
3190		let _a = producer.subscribe(Subscription::default().with_latency_max(Duration::from_millis(500)));
3191		let _b = producer.subscribe(Subscription::default().with_latency_max(Duration::from_secs(10)));
3192
3193		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3194	}
3195
3196	#[test]
3197	fn subscriber_control_updates_while_read_future_is_pending() {
3198		let producer = track_producer("test", None);
3199		let mut subscriber = producer.subscribe(None);
3200		let control = subscriber.control();
3201
3202		let mut recv = Box::pin(subscriber.recv_group());
3203		assert!(recv.as_mut().now_or_never().is_none());
3204
3205		control
3206			.update(Subscription::default().with_priority(7).with_ordered(false))
3207			.unwrap();
3208
3209		let aggregate = producer.subscription().expect("expected an active subscription");
3210		assert_eq!(aggregate.priority, 7);
3211		assert!(!aggregate.ordered);
3212	}
3213
3214	#[test]
3215	fn dropped_subscriber_leaves_no_ghost_in_aggregate() {
3216		// Regression (#2351): a departed subscriber must not keep contributing its
3217		// last subscription to the aggregate. When it did, a relay's linger loop
3218		// never observed the track going idle, and an identical viewer reconnecting
3219		// within the linger window was reset when the stale timer fired.
3220		let mut producer = track_producer("test", None);
3221		let a = producer.subscribe(Subscription::default().with_priority(5));
3222
3223		// Prime the change cursor: the aggregate currently has one subscriber.
3224		let waiter = kio::Waiter::noop();
3225		assert!(
3226			matches!(producer.poll_subscription_changed(&waiter), Poll::Ready(Ok(Some(_)))),
3227			"one live subscriber should aggregate to Some",
3228		);
3229
3230		// The only subscriber leaves.
3231		drop(a);
3232
3233		// The aggregate must report the drop to None, not the ghost's last value.
3234		assert!(
3235			matches!(producer.poll_subscription_changed(&waiter), Poll::Ready(Ok(None))),
3236			"a dropped subscriber must not linger in the aggregate",
3237		);
3238
3239		// And the snapshot used by the linger loop must agree.
3240		assert!(
3241			producer.subscription().is_none(),
3242			"snapshot must exclude a dropped subscriber",
3243		);
3244	}
3245
3246	#[test]
3247	fn dropped_subscriber_wakes_the_aggregate() {
3248		// The value being right isn't enough: nothing re-polls the aggregate on its
3249		// own, so the drop has to wake the waiter. A subscriber contributing demand
3250		// takes `kio::Consumer::poll`'s Ready path, which registers no waiter, so
3251		// the departure needs the closed waiter armed explicitly. Without it a relay
3252		// never learns the last viewer left and holds the upstream subscription (and
3253		// the upstream's viewer count) open forever.
3254		use std::sync::atomic::{AtomicBool, Ordering};
3255
3256		let mut producer = track_producer("test", None);
3257		let a = producer.subscribe(Subscription::default().with_priority(5));
3258
3259		let woken = Arc::new(AtomicBool::new(false));
3260		let waiter = kio::Waiter::new(futures::task::waker(Arc::new(FlagWake(woken.clone()))));
3261
3262		// Prime the cursor, then confirm the next poll parks.
3263		assert!(matches!(
3264			producer.poll_subscription_changed(&waiter),
3265			Poll::Ready(Ok(Some(_)))
3266		));
3267		assert!(
3268			producer.poll_subscription_changed(&waiter).is_pending(),
3269			"the aggregate is unchanged, so this poll must park",
3270		);
3271		assert!(!woken.load(Ordering::SeqCst), "nothing happened yet");
3272
3273		drop(a);
3274		assert!(
3275			woken.load(Ordering::SeqCst),
3276			"the last subscriber leaving must wake the aggregate watcher",
3277		);
3278	}
3279
3280	/// An [`ArcWake`] that just records that it was woken.
3281	struct FlagWake(Arc<std::sync::atomic::AtomicBool>);
3282
3283	impl futures::task::ArcWake for FlagWake {
3284		fn wake_by_ref(arc_self: &Arc<Self>) {
3285			arc_self.0.store(true, std::sync::atomic::Ordering::SeqCst);
3286		}
3287	}
3288
3289	#[tokio::test]
3290	async fn out_of_order_max_sequence_at_front() {
3291		tokio::time::pause();
3292
3293		let mut producer = track_producer("test", None);
3294
3295		// Arrive out of order: seq 5 first, then 3, then 4.
3296		producer.create_group(group::Info { sequence: 5 }).unwrap();
3297		producer.create_group(group::Info { sequence: 3 }).unwrap();
3298		producer.create_group(group::Info { sequence: 4 }).unwrap();
3299
3300		// max_sequence = 5, which is at the front of the VecDeque.
3301		{
3302			let state = producer.state.read();
3303			assert_eq!(state.max_sequence, Some(5));
3304		}
3305
3306		// Expire all three groups.
3307		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3308
3309		// Append seq 6 (becomes new max_sequence).
3310		producer.append_group().unwrap(); // seq 6
3311
3312		// Seq 3, 4, 5 are all expired. Seq 5 was the old max_sequence but now 6 is.
3313		// All old groups are evicted.
3314		{
3315			let state = producer.state.read();
3316			assert_eq!(live_groups(&state), 1);
3317			assert_eq!(first_live_sequence(&state), 6);
3318			assert!(!state.lookup.contains_key(&3));
3319			assert!(!state.lookup.contains_key(&4));
3320			assert!(!state.lookup.contains_key(&5));
3321			assert!(state.lookup.contains_key(&6));
3322		}
3323	}
3324
3325	#[tokio::test]
3326	async fn max_sequence_at_front_blocks_trim() {
3327		tokio::time::pause();
3328
3329		let mut producer = track_producer("test", None);
3330
3331		// Arrive: seq 5, then seq 3.
3332		producer.create_group(group::Info { sequence: 5 }).unwrap();
3333
3334		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3335
3336		// Seq 3 arrives late; max_sequence is still 5 (at front).
3337		producer.create_group(group::Info { sequence: 3 }).unwrap();
3338
3339		// Seq 5 is max_sequence (protected). Seq 3 is not expired (just created).
3340		// Nothing should be evicted.
3341		{
3342			let state = producer.state.read();
3343			assert_eq!(live_groups(&state), 2);
3344			assert_eq!(state.offset, 0);
3345		}
3346
3347		// Expire seq 3 as well.
3348		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3349
3350		// Seq 2 arrives late, triggering eviction.
3351		producer.create_group(group::Info { sequence: 2 }).unwrap();
3352
3353		// Seq 5 is the live edge (protected) and still resolves at the front of
3354		// `arrival`, so nothing is trimmed and the offset stays. Seq 3 expired out of
3355		// `lookup`, leaving a hole its arrival entry no longer resolves; seq 2 is
3356		// fresh and kept.
3357		{
3358			let state = producer.state.read();
3359			assert_eq!(live_groups(&state), 2);
3360			assert_eq!(state.offset, 0);
3361			assert!(state.lookup.contains_key(&5));
3362			assert!(!state.lookup.contains_key(&3));
3363			assert!(state.lookup.contains_key(&2));
3364		}
3365
3366		// Consumer should still be able to read through the hole.
3367		let mut consumer = producer.subscribe(None);
3368		let group = consumer.assert_group();
3369		// consume() starts at index 0; the first arrival entry that still resolves is seq 5.
3370		assert_eq!(group.sequence, 5);
3371	}
3372
3373	#[tokio::test]
3374	async fn abort_clears_cached_groups() {
3375		let mut producer = track_producer("test", None);
3376		producer.append_group().unwrap();
3377		producer.append_group().unwrap();
3378
3379		// A stale consumer that never drains must not pin the cached groups.
3380		let mut consumer = producer.subscribe(None);
3381		assert_eq!(live_groups(&producer.state.read()), 2);
3382
3383		producer.clone().abort(Error::Cancel).unwrap();
3384
3385		{
3386			let state = producer.state.read();
3387			assert!(state.lookup.is_empty(), "cached groups should be dropped on abort");
3388			assert!(state.arrival.is_empty());
3389			assert!(state.evict.is_empty());
3390		}
3391
3392		// The consumer now surfaces the abort error rather than the leftover cache.
3393		let result = consumer.recv_group().now_or_never().expect("should not block");
3394		assert!(matches!(result, Err(Error::Cancel)));
3395	}
3396
3397	#[tokio::test]
3398	async fn drop_unfinished_clears_cached_groups() {
3399		let producer = track_producer("test", None);
3400		let mut writer = producer.clone();
3401		writer.append_group().unwrap();
3402
3403		// A stale consumer keeps the channel (and thus the cache) alive.
3404		let mut consumer = producer.subscribe(None);
3405		assert_eq!(live_groups(&producer.state.read()), 1);
3406
3407		// Drop every producer without finishing: the cache is released.
3408		drop(writer);
3409		drop(producer);
3410
3411		let result = consumer.recv_group().now_or_never().expect("should not block");
3412		assert!(matches!(result, Err(Error::Dropped)));
3413	}
3414
3415	#[tokio::test]
3416	async fn drop_after_abort_does_not_warn() {
3417		// abort() closes the channel after recording `abort`. Drop must treat the
3418		// read-only guard returned by write() as clean or it emits a false WARN.
3419		let warns = count_drop_warnings("track::Producer dropped without finish", || {
3420			let producer = track_producer("test", None);
3421			let keep = producer.clone();
3422			let mut writer = producer.clone();
3423			let mut group = writer.append_group().unwrap();
3424			group.finish().unwrap();
3425			let _consumer = producer.subscribe(None);
3426			writer.abort(Error::Cancel).unwrap();
3427			drop(keep);
3428		});
3429		assert_eq!(warns, 0, "abort-then-drop must not emit unfinished-producer WARN");
3430	}
3431
3432	#[tokio::test]
3433	async fn drop_unfinished_warns() {
3434		let warns = count_drop_warnings("track::Producer dropped without finish", || {
3435			let producer = track_producer("test", None);
3436			let mut writer = producer.clone();
3437			writer.append_group().unwrap();
3438			let _consumer = producer.subscribe(None);
3439			drop(writer);
3440			drop(producer);
3441		});
3442		assert!(warns >= 1, "unfinished drop must emit unfinished-producer WARN");
3443	}
3444
3445	#[tokio::test]
3446	async fn drop_finished_keeps_cached_groups() {
3447		let mut producer = track_producer("test", None);
3448		producer.append_group().unwrap();
3449		producer.finish().unwrap();
3450
3451		let mut consumer = producer.subscribe(None);
3452		drop(producer);
3453
3454		// A cleanly finished track keeps its cache so the consumer can still drain.
3455		assert_eq!(consumer.assert_group().sequence, 0);
3456		let done = consumer.recv_group().now_or_never().expect("should not block").unwrap();
3457		assert!(done.is_none(), "consumer should drain then see clean finish");
3458	}
3459
3460	#[test]
3461	fn append_finish_cannot_be_rewritten() {
3462		let mut producer = track_producer("test", None);
3463
3464		// Finishing an empty track is valid (fin = 0, total groups = 0).
3465		assert!(producer.finish().is_ok());
3466		assert!(producer.finish().is_err());
3467		assert!(producer.append_group().is_err());
3468	}
3469
3470	#[test]
3471	fn finish_after_groups() {
3472		let mut producer = track_producer("test", None);
3473
3474		producer.append_group().unwrap();
3475		assert!(producer.finish().is_ok());
3476		assert!(producer.finish().is_err());
3477		assert!(producer.append_group().is_err());
3478	}
3479
3480	#[test]
3481	fn finish_at_rejects_a_boundary_at_or_below_the_live_edge() {
3482		let mut producer = track_producer("test", None);
3483		producer.create_group(group::Info { sequence: 5 }).unwrap();
3484
3485		// The boundary is exclusive, so it must be strictly above the highest produced
3486		// group. 5 or below would orphan groups that already exist.
3487		assert!(producer.finish_at(4).is_err());
3488		assert!(producer.finish_at(5).is_err());
3489		assert!(producer.finish_at(6).is_ok());
3490
3491		{
3492			let state = producer.state.read();
3493			assert_eq!(state.final_sequence, Some(6));
3494		}
3495
3496		// Re-finishing is rejected, and no group at or above the boundary can be created.
3497		assert!(producer.finish_at(6).is_err());
3498		assert!(producer.create_group(group::Info { sequence: 4 }).is_ok());
3499		assert!(producer.create_group(group::Info { sequence: 6 }).is_err());
3500	}
3501
3502	#[test]
3503	fn final_sequence_reports_the_declared_boundary() {
3504		let mut producer = track_producer("test", None);
3505		assert_eq!(producer.final_sequence(), None);
3506
3507		producer.create_group(group::Info { sequence: 5 }).unwrap();
3508		assert_eq!(producer.final_sequence(), None, "a group does not declare a boundary");
3509
3510		producer.finish_at(9).unwrap();
3511		assert_eq!(producer.final_sequence(), Some(9));
3512
3513		// finish() would try to declare a second boundary, so callers check first.
3514		assert!(producer.finish().is_err());
3515	}
3516
3517	#[test]
3518	fn final_sequence_reports_the_live_edge_after_finish() {
3519		let mut producer = track_producer("test", None);
3520		producer.create_group(group::Info { sequence: 5 }).unwrap();
3521		producer.finish().unwrap();
3522		assert_eq!(producer.final_sequence(), Some(6));
3523	}
3524
3525	#[tokio::test]
3526	async fn finish_at_declares_a_future_boundary() {
3527		let mut producer = track_producer("test", None);
3528		producer.create_group(group::Info { sequence: 5 }).unwrap();
3529
3530		// Learn the track ends at group 6 (exclusive 7) while the live edge is still 5.
3531		producer.finish_at(7).unwrap();
3532
3533		let mut consumer = producer.subscribe(None);
3534		assert_eq!(consumer.assert_group().sequence, 5);
3535
3536		// The boundary is known immediately, but the track isn't done: group 6 is still
3537		// outstanding, so the consumer parks rather than seeing end-of-stream.
3538		let boundary = consumer
3539			.finished()
3540			.now_or_never()
3541			.expect("boundary is known immediately")
3542			.expect("would have errored");
3543		assert_eq!(boundary, 7);
3544		assert!(
3545			consumer.recv_group().now_or_never().is_none(),
3546			"should wait for the outstanding group"
3547		);
3548
3549		// The trailing group arrives (below the boundary), then the track completes.
3550		producer.create_group(group::Info { sequence: 6 }).unwrap();
3551		assert_eq!(consumer.assert_group().sequence, 6);
3552		let done = consumer
3553			.recv_group()
3554			.now_or_never()
3555			.expect("should not block")
3556			.expect("would have errored");
3557		assert!(done.is_none(), "track completes once the boundary is reached");
3558	}
3559
3560	#[tokio::test]
3561	async fn recv_group_finishes_without_waiting_for_gaps() {
3562		let mut producer = track_producer("test", None);
3563		producer.create_group(group::Info { sequence: 1 }).unwrap();
3564		producer.finish().unwrap();
3565
3566		let mut consumer = producer.subscribe(None);
3567		assert_eq!(consumer.assert_group().sequence, 1);
3568
3569		let done = consumer
3570			.recv_group()
3571			.now_or_never()
3572			.expect("should not block")
3573			.expect("would have errored");
3574		assert!(done.is_none(), "track should finish without waiting for gaps");
3575	}
3576
3577	#[tokio::test]
3578	async fn next_group_skips_late_arrivals() {
3579		let mut producer = track_producer("test", None);
3580		let mut consumer = producer.subscribe(None);
3581
3582		// Seq 5 arrives first.
3583		producer.create_group(group::Info { sequence: 5 }).unwrap();
3584		let group = consumer
3585			.next_group()
3586			.now_or_never()
3587			.expect("should not block")
3588			.expect("would have errored")
3589			.expect("track should not be closed");
3590		assert_eq!(group.sequence, 5);
3591
3592		// Seq 3 arrives late, skipped because 3 <= 5.
3593		producer.create_group(group::Info { sequence: 3 }).unwrap();
3594		// Seq 4 arrives late and is also skipped.
3595		producer.create_group(group::Info { sequence: 4 }).unwrap();
3596		// Seq 7 arrives and is returned.
3597		producer.create_group(group::Info { sequence: 7 }).unwrap();
3598
3599		let group = consumer
3600			.next_group()
3601			.now_or_never()
3602			.expect("should not block")
3603			.expect("would have errored")
3604			.expect("track should not be closed");
3605		assert_eq!(group.sequence, 7);
3606
3607		// No more groups. This would block.
3608		assert!(
3609			consumer.next_group().now_or_never().is_none(),
3610			"should block waiting for a higher sequence"
3611		);
3612	}
3613
3614	#[tokio::test]
3615	async fn next_group_returns_arrivals_in_order() {
3616		let mut producer = track_producer("test", None);
3617		let mut consumer = producer.subscribe(None);
3618
3619		// Seq 3 arrives first, then seq 5. Both should be returned in arrival order.
3620		producer.create_group(group::Info { sequence: 3 }).unwrap();
3621		producer.create_group(group::Info { sequence: 5 }).unwrap();
3622
3623		let group = consumer
3624			.next_group()
3625			.now_or_never()
3626			.expect("should not block")
3627			.expect("would have errored")
3628			.expect("track should not be closed");
3629		assert_eq!(group.sequence, 3);
3630
3631		let group = consumer
3632			.next_group()
3633			.now_or_never()
3634			.expect("should not block")
3635			.expect("would have errored")
3636			.expect("track should not be closed");
3637		assert_eq!(group.sequence, 5);
3638	}
3639
3640	#[tokio::test]
3641	async fn next_group_and_recv_group_use_independent_cursors() {
3642		let mut producer = track_producer("test", None);
3643		let mut consumer = producer.subscribe(None);
3644
3645		// Out-of-order arrivals: seq 5 first, then seq 3.
3646		producer.create_group(group::Info { sequence: 5 }).unwrap();
3647		producer.create_group(group::Info { sequence: 3 }).unwrap();
3648
3649		// next_group is sequence-ordered: it returns the smallest sequence first,
3650		// regardless of arrival order.
3651		let group = consumer
3652			.next_group()
3653			.now_or_never()
3654			.expect("should not block")
3655			.expect("would have errored")
3656			.expect("track should not be closed");
3657		assert_eq!(group.sequence, 3);
3658
3659		// recv_group is arrival-ordered and uses an independent cursor, so it
3660		// still starts at the first arrival.
3661		assert_eq!(consumer.assert_group().sequence, 5);
3662	}
3663
3664	#[tokio::test]
3665	async fn end_at_caps_next_group() {
3666		let mut producer = track_producer("test", None);
3667		let mut consumer = producer.subscribe(None);
3668
3669		for s in 0..6 {
3670			producer.create_group(group::Info { sequence: s }).unwrap();
3671		}
3672
3673		consumer.end_at(2);
3674
3675		// Groups 0, 1, 2 are within the cap.
3676		assert_eq!(
3677			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3678			0
3679		);
3680		assert_eq!(
3681			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3682			1
3683		);
3684		assert_eq!(
3685			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3686			2
3687		);
3688
3689		// Group 3 is beyond the cap: next_group parks even though cached groups exist.
3690		assert!(
3691			consumer.next_group().now_or_never().is_none(),
3692			"capped consumer must block instead of returning out-of-range groups"
3693		);
3694	}
3695
3696	#[tokio::test]
3697	async fn end_at_release_drains_cached_groups() {
3698		let mut producer = track_producer("test", None);
3699		let mut consumer = producer.subscribe(None);
3700
3701		for s in 0..6 {
3702			producer.create_group(group::Info { sequence: s }).unwrap();
3703		}
3704
3705		consumer.end_at(1);
3706		assert_eq!(
3707			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3708			0
3709		);
3710		assert_eq!(
3711			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3712			1
3713		);
3714		assert!(consumer.next_group().now_or_never().is_none(), "capped at 1");
3715
3716		// Raise the cap; previously-blocked cached groups become available again.
3717		consumer.end_at(4);
3718		assert_eq!(
3719			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3720			2
3721		);
3722		assert_eq!(
3723			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3724			3
3725		);
3726		assert_eq!(
3727			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3728			4
3729		);
3730		assert!(consumer.next_group().now_or_never().is_none(), "capped at 4");
3731
3732		// Remove the cap; everything remaining flows.
3733		consumer.end_at(None);
3734		assert_eq!(
3735			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3736			5
3737		);
3738		assert!(consumer.next_group().now_or_never().is_none(), "no more groups");
3739	}
3740
3741	#[tokio::test]
3742	async fn end_at_lower_than_cursor_parks_consumer() {
3743		let mut producer = track_producer("test", None);
3744		let mut consumer = producer.subscribe(None);
3745
3746		for s in 0..3 {
3747			producer.create_group(group::Info { sequence: s }).unwrap();
3748		}
3749
3750		// Drain everything with no cap.
3751		assert_eq!(
3752			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3753			0
3754		);
3755		assert_eq!(
3756			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3757			1
3758		);
3759		assert_eq!(
3760			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3761			2
3762		);
3763
3764		// Lower the cap below the cursor. New groups beyond the cap are blocked.
3765		consumer.end_at(1);
3766		producer.create_group(group::Info { sequence: 3 }).unwrap();
3767		producer.create_group(group::Info { sequence: 4 }).unwrap();
3768		assert!(
3769			consumer.next_group().now_or_never().is_none(),
3770			"cap is below cursor; nothing returnable until cap rises"
3771		);
3772
3773		// Restoring the cap to no-limit (or any value >= cursor) releases them.
3774		consumer.end_at(None);
3775		assert_eq!(
3776			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3777			3
3778		);
3779		assert_eq!(
3780			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3781			4
3782		);
3783	}
3784
3785	#[tokio::test]
3786	async fn end_at_toggling_around_late_arrivals() {
3787		let mut producer = track_producer("test", None);
3788		let mut consumer = producer.subscribe(None);
3789
3790		consumer.end_at(5);
3791
3792		// Out-of-order arrivals all within the cap.
3793		producer.create_group(group::Info { sequence: 2 }).unwrap();
3794		producer.create_group(group::Info { sequence: 5 }).unwrap();
3795		producer.create_group(group::Info { sequence: 3 }).unwrap();
3796		// One beyond the cap; should be held even though it arrived in the middle.
3797		producer.create_group(group::Info { sequence: 8 }).unwrap();
3798		producer.create_group(group::Info { sequence: 4 }).unwrap();
3799
3800		// next_group walks in sequence order through everything <= cap.
3801		assert_eq!(
3802			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3803			2
3804		);
3805		assert_eq!(
3806			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3807			3
3808		);
3809		assert_eq!(
3810			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3811			4
3812		);
3813		assert_eq!(
3814			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3815			5
3816		);
3817		// Now blocked: 8 is still beyond the cap.
3818		assert!(consumer.next_group().now_or_never().is_none());
3819
3820		// Raise the cap; cached seq 8 is finally served.
3821		consumer.end_at(10);
3822		assert_eq!(
3823			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3824			8
3825		);
3826	}
3827
3828	#[tokio::test]
3829	async fn read_frame_returns_single_frame_per_group() {
3830		let mut producer = track_producer("test", None);
3831		let mut consumer = producer.subscribe(None);
3832
3833		producer.write_frame(Timestamp::ZERO, b"hello".as_slice()).unwrap();
3834		producer.write_frame(Timestamp::ZERO, b"world".as_slice()).unwrap();
3835
3836		let frame = consumer
3837			.read_frame()
3838			.now_or_never()
3839			.expect("should not block")
3840			.expect("would have errored")
3841			.expect("track should not be closed");
3842		assert_eq!(&frame.payload[..], b"hello");
3843
3844		let frame = consumer
3845			.read_frame()
3846			.now_or_never()
3847			.expect("should not block")
3848			.expect("would have errored")
3849			.expect("track should not be closed");
3850		assert_eq!(&frame.payload[..], b"world");
3851	}
3852
3853	#[tokio::test]
3854	async fn read_frame_preserves_timestamp() {
3855		let mut producer = track_producer("test", None);
3856		let mut consumer = producer.subscribe(None);
3857
3858		producer
3859			.write_frame(Timestamp::from_micros(20_000).unwrap(), b"hello".as_slice())
3860			.unwrap();
3861
3862		let frame = consumer
3863			.read_frame()
3864			.now_or_never()
3865			.expect("should not block")
3866			.expect("would have errored")
3867			.expect("track should not be closed");
3868		assert_eq!(frame.timestamp.as_micros(), 20_000);
3869		assert_eq!(&frame.payload[..], b"hello");
3870	}
3871
3872	#[tokio::test]
3873	async fn read_frame_skips_stalled_group_for_newer_ready_frame() {
3874		let mut producer = track_producer("test", None);
3875		let mut consumer = producer.subscribe(None);
3876
3877		// Seq 3: group open, no frame yet (stalled).
3878		let _stalled = producer.create_group(group::Info { sequence: 3 }).unwrap();
3879		// Seq 5: fully-written group with a frame.
3880		let mut g5 = producer.create_group(group::Info { sequence: 5 }).unwrap();
3881		g5.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"later"))
3882			.unwrap();
3883		g5.finish().unwrap();
3884
3885		// read_frame should not block on the stalled seq 3. It returns seq 5's frame.
3886		let frame = consumer
3887			.read_frame()
3888			.now_or_never()
3889			.expect("should not block on stalled earlier group")
3890			.expect("would have errored")
3891			.expect("track should not be closed");
3892		assert_eq!(&frame.payload[..], b"later");
3893	}
3894
3895	#[tokio::test]
3896	async fn read_frame_discards_rest_of_multi_frame_group() {
3897		let mut producer = track_producer("test", None);
3898		let mut consumer = producer.subscribe(None);
3899
3900		// Group 0 has two frames; only the first is returned.
3901		let mut g0 = producer.create_group(group::Info { sequence: 0 }).unwrap();
3902		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"one"))
3903			.unwrap();
3904		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"two"))
3905			.unwrap();
3906		g0.finish().unwrap();
3907
3908		// Group 1 is a normal single-frame group.
3909		producer.write_frame(Timestamp::ZERO, b"next".as_slice()).unwrap();
3910
3911		let frame = consumer
3912			.read_frame()
3913			.now_or_never()
3914			.expect("should not block")
3915			.expect("would have errored")
3916			.expect("track should not be closed");
3917		assert_eq!(&frame.payload[..], b"one");
3918
3919		// The second frame of group 0 is discarded; the next read jumps to group 1.
3920		let frame = consumer
3921			.read_frame()
3922			.now_or_never()
3923			.expect("should not block")
3924			.expect("would have errored")
3925			.expect("track should not be closed");
3926		assert_eq!(&frame.payload[..], b"next");
3927	}
3928
3929	#[tokio::test]
3930	async fn read_frame_waits_for_pending_group_after_finish() {
3931		// finish() sets final_sequence, but groups already created with lower sequences
3932		// can still produce frames. read_frame must not return None prematurely.
3933		let mut producer = track_producer("test", None);
3934		let mut consumer = producer.subscribe(None);
3935
3936		let mut g0 = producer.create_group(group::Info { sequence: 0 }).unwrap();
3937		producer.finish().unwrap();
3938
3939		// Track is finished but group 0 has no frame yet. It must block, not return None.
3940		assert!(
3941			consumer.read_frame().now_or_never().is_none(),
3942			"read_frame must block on a pending group even after finish()"
3943		);
3944
3945		// A late frame on the pending group is still delivered.
3946		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"late"))
3947			.unwrap();
3948		let frame = consumer
3949			.read_frame()
3950			.now_or_never()
3951			.expect("should not block once a frame is written")
3952			.expect("would have errored")
3953			.expect("track should not be closed");
3954		assert_eq!(&frame.payload[..], b"late");
3955	}
3956
3957	#[tokio::test]
3958	async fn read_frame_respects_start_at() {
3959		// start_at sets min_sequence; read_frame must skip groups below it even though
3960		// next_sequence is still 0.
3961		let mut producer = track_producer("test", None);
3962		let mut consumer = producer.subscribe(None);
3963		consumer.start_at(5);
3964
3965		// Seq 3 has a frame but is below min_sequence, so it must be skipped.
3966		let mut g3 = producer.create_group(group::Info { sequence: 3 }).unwrap();
3967		g3.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"skip-me"))
3968			.unwrap();
3969		g3.finish().unwrap();
3970
3971		let mut g5 = producer.create_group(group::Info { sequence: 5 }).unwrap();
3972		g5.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"keep"))
3973			.unwrap();
3974		g5.finish().unwrap();
3975
3976		let frame = consumer
3977			.read_frame()
3978			.now_or_never()
3979			.expect("should not block")
3980			.expect("would have errored")
3981			.expect("track should not be closed");
3982		assert_eq!(&frame.payload[..], b"keep");
3983	}
3984
3985	#[tokio::test]
3986	async fn read_frame_returns_none_when_finished() {
3987		let mut producer = track_producer("test", None);
3988		let mut consumer = producer.subscribe(None);
3989
3990		producer.write_frame(Timestamp::ZERO, b"only".as_slice()).unwrap();
3991		producer.finish().unwrap();
3992
3993		let frame = consumer
3994			.read_frame()
3995			.now_or_never()
3996			.expect("should not block")
3997			.expect("would have errored")
3998			.expect("track should not be closed");
3999		assert_eq!(&frame.payload[..], b"only");
4000
4001		let done = consumer
4002			.read_frame()
4003			.now_or_never()
4004			.expect("should not block")
4005			.expect("would have errored");
4006		assert!(done.is_none());
4007	}
4008
4009	#[test]
4010	fn append_group_returns_bounds_exceeded_on_sequence_overflow() {
4011		let mut producer = track_producer("test", None);
4012		{
4013			let mut state = producer.state.write().ok().unwrap();
4014			state.max_sequence = Some(u64::MAX);
4015		}
4016
4017		assert!(matches!(producer.append_group(), Err(Error::BoundsExceeded(_))));
4018	}
4019
4020	#[tokio::test]
4021	async fn fetch_cache_hit() {
4022		let mut producer = track_producer("test", None);
4023
4024		// Produce a cached group.
4025		let mut group = producer.append_group().unwrap(); // seq 0
4026		group
4027			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hello"))
4028			.unwrap();
4029		group.finish().unwrap();
4030
4031		// A cached group resolves immediately and never queues a request. `peek_group`
4032		// also returns it synchronously.
4033		let dynamic = producer.dynamic();
4034		let consumer = producer.consume();
4035		assert!(consumer.peek_group(0).is_some());
4036		let mut g = consumer.fetch_group(0, None).await.unwrap();
4037		assert_eq!(g.sequence, 0);
4038		assert_eq!(&g.read_frame().await.unwrap().unwrap().payload[..], b"hello");
4039
4040		// Nothing was queued for the dynamic handler to serve.
4041		assert!(dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending());
4042	}
4043
4044	#[tokio::test]
4045	async fn fetch_miss_signals_dynamic() {
4046		let producer = track_producer("test", None);
4047		let dynamic = producer.dynamic();
4048		let consumer = producer.consume();
4049
4050		// A cache miss isn't in `peek_group`, but a dynamic handler exists, so
4051		// `fetch_group` stays pending and queues a request. `*pending` derefs the
4052		// wrapper to the inner `Fetching` (a `kio::Pollable`).
4053		assert!(consumer.peek_group(5).is_none());
4054		let pending = consumer.fetch_group(5, group::Fetch::default().with_priority(7));
4055		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
4056
4057		let req = dynamic
4058			.requested_group()
4059			.now_or_never()
4060			.expect("should not block")
4061			.unwrap();
4062		assert_eq!(req.sequence(), 5);
4063		assert_eq!(req.priority(), 7);
4064
4065		// Serve it by accepting the request; the fetch then resolves.
4066		let mut group = req.accept(None).unwrap();
4067		group
4068			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hi"))
4069			.unwrap();
4070		group.finish().unwrap();
4071
4072		let mut g = pending.await.unwrap();
4073		assert_eq!(g.sequence, 5);
4074		assert_eq!(&g.read_frame().await.unwrap().unwrap().payload[..], b"hi");
4075	}
4076
4077	#[tokio::test]
4078	async fn fetch_miss_rejects() {
4079		let producer = track_producer("test", None);
4080		let dynamic = producer.dynamic();
4081		let consumer = producer.consume();
4082
4083		let pending = consumer.fetch_group(5, None);
4084		let req = dynamic
4085			.requested_group()
4086			.now_or_never()
4087			.expect("should not block")
4088			.unwrap();
4089
4090		req.reject(Error::Cancel);
4091		assert!(matches!(pending.await, Err(Error::Cancel)));
4092		let fetch = producer.state.read().fetch.clone();
4093		assert!(fetch.read().is_empty());
4094	}
4095
4096	#[tokio::test]
4097	async fn fetch_miss_drop_rejects() {
4098		let producer = track_producer("test", None);
4099		let dynamic = producer.dynamic();
4100		let consumer = producer.consume();
4101
4102		let pending = consumer.fetch_group(5, None);
4103		let req = dynamic
4104			.requested_group()
4105			.now_or_never()
4106			.expect("should not block")
4107			.unwrap();
4108
4109		drop(req);
4110		assert!(matches!(pending.await, Err(Error::Dropped)));
4111	}
4112
4113	#[tokio::test]
4114	async fn fetch_reject_does_not_poison_retry() {
4115		let producer = track_producer("test", None);
4116		let dynamic = producer.dynamic();
4117		let consumer = producer.consume();
4118
4119		let pending = consumer.fetch_group(5, None);
4120		let req = dynamic
4121			.requested_group()
4122			.now_or_never()
4123			.expect("should not block")
4124			.unwrap();
4125		req.reject(Error::Cancel);
4126		assert!(matches!(pending.await, Err(Error::Cancel)));
4127
4128		let retry = consumer.fetch_group(5, None);
4129		let req = dynamic
4130			.requested_group()
4131			.now_or_never()
4132			.expect("should not block")
4133			.unwrap();
4134		let mut group = req.accept(None).unwrap();
4135		group
4136			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"retry"))
4137			.unwrap();
4138		group.finish().unwrap();
4139
4140		let mut group = retry.await.unwrap();
4141		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"retry");
4142	}
4143
4144	#[tokio::test]
4145	async fn fetch_coalesces_concurrent() {
4146		let producer = track_producer("test", None);
4147		let dynamic = producer.dynamic();
4148		let consumer = producer.consume();
4149
4150		// Two fetches for the same uncached group produce ONE handler request,
4151		// carrying the higher of the two priorities.
4152		let first = consumer.fetch_group(5, group::Fetch::default().with_priority(1));
4153		let second = consumer.fetch_group(5, group::Fetch::default().with_priority(7));
4154		assert!(kio::Pollable::poll(&*first, &kio::Waiter::noop()).is_pending());
4155
4156		let req = dynamic
4157			.requested_group()
4158			.now_or_never()
4159			.expect("should not block")
4160			.unwrap();
4161		assert_eq!(req.sequence(), 5);
4162		assert_eq!(req.priority(), 7);
4163		assert!(
4164			dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending(),
4165			"the second fetch queued a duplicate request"
4166		);
4167
4168		// A fetch arriving while the request is already in flight joins it too.
4169		let third = consumer.fetch_group(5, None);
4170
4171		// One accept resolves all of them.
4172		let mut group = req.accept(None).unwrap();
4173		group
4174			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hi"))
4175			.unwrap();
4176		group.finish().unwrap();
4177
4178		assert_eq!(first.await.unwrap().sequence, 5);
4179		assert_eq!(second.await.unwrap().sequence, 5);
4180		assert_eq!(third.await.unwrap().sequence, 5);
4181	}
4182
4183	#[tokio::test]
4184	async fn fetch_coalesced_reject_fails_all() {
4185		let producer = track_producer("test", None);
4186		let dynamic = producer.dynamic();
4187		let consumer = producer.consume();
4188
4189		let first = consumer.fetch_group(5, None);
4190		let second = consumer.fetch_group(5, None);
4191		let req = dynamic
4192			.requested_group()
4193			.now_or_never()
4194			.expect("should not block")
4195			.unwrap();
4196		req.reject(Error::Cancel);
4197
4198		assert!(matches!(first.await, Err(Error::Cancel)));
4199		assert!(matches!(second.await, Err(Error::Cancel)));
4200
4201		// The rejected attempt is gone: a retry starts a fresh one.
4202		let retry = consumer.fetch_group(5, None);
4203		assert!(kio::Pollable::poll(&*retry, &kio::Waiter::noop()).is_pending());
4204		let req = dynamic
4205			.requested_group()
4206			.now_or_never()
4207			.expect("should not block")
4208			.unwrap();
4209		assert_eq!(req.sequence(), 5);
4210	}
4211
4212	#[tokio::test]
4213	async fn fetch_queued_fails_when_handlers_leave() {
4214		let producer = track_producer("test", None);
4215		let dynamic = producer.dynamic();
4216		let consumer = producer.consume();
4217
4218		// Queued but never popped: the last handler leaving fails it fast.
4219		let pending = consumer.fetch_group(5, None);
4220		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
4221		drop(dynamic);
4222		assert!(matches!(pending.await, Err(Error::NotFound)));
4223
4224		// And the attempt didn't leak.
4225		let fetch = producer.state.read().fetch.clone();
4226		assert!(fetch.read().is_empty());
4227	}
4228
4229	#[tokio::test]
4230	async fn fetch_miss_no_dynamic_not_found() {
4231		// A track with no `Dynamic` can't serve old content, so a cache miss
4232		// resolves to NotFound instead of blocking forever.
4233		let mut producer = track_producer("test", None);
4234		producer.append_group().unwrap(); // seq 0, but we miss on seq 5
4235		let consumer = producer.consume();
4236		assert!(matches!(consumer.fetch_group(5, None).await, Err(Error::NotFound)));
4237	}
4238
4239	#[tokio::test]
4240	async fn fetch_past_final_not_found() {
4241		let mut producer = track_producer("test", None);
4242		producer.append_group().unwrap(); // seq 0
4243		producer.finish().unwrap(); // final_sequence = 1
4244
4245		// A group at or past the final sequence can never exist, even with a handler,
4246		// so it resolves to NotFound.
4247		let dynamic = producer.dynamic();
4248		let consumer = producer.consume();
4249		assert!(matches!(consumer.fetch_group(5, None).await, Err(Error::NotFound)));
4250
4251		// And it doesn't signal the dynamic handler.
4252		assert!(dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending());
4253	}
4254
4255	/// Mint a track whose groups charge into a bounded [`cache::Pool`].
4256	fn pooled_producer(capacity: u64) -> (Producer, cache::Pool) {
4257		let pool = cache::Pool::new(capacity);
4258		let broadcast = broadcast::Info {
4259			origin: crate::origin::Info::default().with_pool(pool.clone()),
4260			..Default::default()
4261		};
4262		let producer = Producer::new(Arc::new(broadcast), "test", None);
4263		(producer, pool)
4264	}
4265
4266	fn finished_group(producer: &mut Producer, size: usize) -> u64 {
4267		let mut group = producer.append_group().unwrap();
4268		group
4269			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; size]))
4270			.unwrap();
4271		group.finish().unwrap();
4272		group.sequence
4273	}
4274
4275	/// While the pool is over capacity, every append accrues debt and pays it by
4276	/// evicting this track's own oldest groups, so the newest content survives.
4277	#[tokio::test]
4278	async fn debt_evicts_oldest_group() {
4279		tokio::time::pause();
4280
4281		// Fits one 10k group; each additional group pushes the pool over budget.
4282		let (mut producer, pool) = pooled_producer(10_000);
4283
4284		finished_group(&mut producer, 10_000); // seq 0
4285		finished_group(&mut producer, 10_000); // seq 1: over budget, debt starts accruing
4286		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4287
4288		let consumer = producer.consume();
4289		assert!(consumer.peek_group(0).is_none(), "oldest group is evicted");
4290		assert!(consumer.peek_group(2).is_some(), "latest group survives");
4291		// Steady state carries the protected live edge plus the just-demoted group
4292		// (debt is charged before the demotion, so eviction lags one append).
4293		assert!(pool.used() <= 21_000, "usage hovers near capacity: {}", pool.used());
4294
4295		// A fresh subscriber skips the evicted groups entirely.
4296		let mut subscriber = producer.subscribe(None);
4297		assert!(subscriber.assert_group().sequence > 0, "evicted group is not delivered");
4298	}
4299
4300	/// The latest group is never in the eviction order, so it survives any budget.
4301	#[tokio::test]
4302	async fn latest_group_never_evicted() {
4303		tokio::time::pause();
4304
4305		// Far too small for even one group: the latest survives anyway.
4306		let (mut producer, pool) = pooled_producer(100);
4307		finished_group(&mut producer, 1000); // seq 0
4308		assert!(pool.used() > 100, "the latest may exceed the budget");
4309
4310		// Later writes evict the demoted seq 0; each new latest is untouchable in turn.
4311		finished_group(&mut producer, 1000); // seq 1: demotes seq 0
4312		finished_group(&mut producer, 1000); // seq 2: pays by evicting seq 0
4313
4314		let consumer = producer.consume();
4315		assert!(consumer.peek_group(0).is_none());
4316		let mut group = consumer.peek_group(2).expect("latest survives");
4317		assert_eq!(group.read_frame().await.unwrap().unwrap().payload.len(), 1000);
4318	}
4319
4320	/// A FETCH cache hit refreshes the group's access time: anything accessed more
4321	/// recently than the pool-wide average is protected, so the eviction walk skips
4322	/// it and evicts a never-read group instead, even one that arrived later.
4323	#[tokio::test]
4324	async fn fetch_refresh_survives_eviction() {
4325		tokio::time::pause();
4326
4327		let (mut producer, _pool) = pooled_producer(10_000);
4328		let consumer = producer.consume();
4329
4330		finished_group(&mut producer, 3_000); // seq 0
4331		tokio::time::advance(Duration::from_secs(1)).await;
4332		finished_group(&mut producer, 3_000); // seq 1
4333		tokio::time::advance(Duration::from_secs(1)).await;
4334		finished_group(&mut producer, 3_000); // seq 2
4335		tokio::time::advance(Duration::from_millis(500)).await;
4336
4337		// FETCH seq 0: the cache hit lifts its access time above the average.
4338		let mut fetched = consumer.fetch_group(0, None).await.unwrap();
4339		assert_eq!(fetched.read_frame().await.unwrap().unwrap().payload.len(), 3_000);
4340		tokio::time::advance(Duration::from_millis(500)).await;
4341
4342		// Pressure: seq 0 is first in eviction order but freshly accessed, so it
4343		// rotates to the back and the never-read seq 1 dies instead.
4344		finished_group(&mut producer, 3_000); // seq 3
4345		tokio::time::advance(Duration::from_secs(1)).await;
4346		finished_group(&mut producer, 3_000); // seq 4
4347
4348		assert!(consumer.peek_group(0).is_some(), "refreshed group survives");
4349		assert!(consumer.peek_group(1).is_none(), "unread group is evicted instead");
4350	}
4351
4352	/// A consumer holding an evicted group surfaces the eviction, not a hang or a
4353	/// truncated clean end.
4354	#[tokio::test]
4355	async fn eviction_aborts_readers() {
4356		tokio::time::pause();
4357
4358		let (mut producer, _pool) = pooled_producer(10_000);
4359		let mut subscriber = producer.subscribe(None);
4360
4361		finished_group(&mut producer, 10_000); // seq 0
4362		let mut group0 = subscriber.assert_group();
4363
4364		finished_group(&mut producer, 10_000); // seq 1: demotes seq 0
4365		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4366
4367		let read = group0.read_frame().await;
4368		assert!(matches!(read, Err(Error::Evicted)), "expected Evicted, got {read:?}");
4369	}
4370
4371	/// A write smaller than the next victim carries debt instead of evicting: a
4372	/// large group dies only once enough debt accumulates, never to pay off a
4373	/// far smaller write.
4374	#[tokio::test]
4375	async fn small_writes_carry_debt() {
4376		tokio::time::pause();
4377
4378		let (mut producer, pool) = pooled_producer(22_000);
4379		let consumer = producer.consume();
4380
4381		finished_group(&mut producer, 20_000); // seq 0, the large victim-to-be
4382
4383		// The first few small writes owe far less than seq 0's size: the debt
4384		// carries over instead of evicting it.
4385		for _ in 0..3 {
4386			finished_group(&mut producer, 1_000);
4387		}
4388		assert!(consumer.peek_group(0).is_some(), "debt smaller than the victim carries");
4389
4390		// Enough small writes accumulate the debt to finally evict it.
4391		for _ in 0..20 {
4392			finished_group(&mut producer, 1_000);
4393		}
4394		assert!(
4395			consumer.peek_group(0).is_none(),
4396			"accumulated debt evicts the large group"
4397		);
4398		// Steady state hovers within about one group of capacity: a victim smaller
4399		// than the outstanding debt is never evicted, so the excess stays bounded.
4400		assert!(pool.used() <= 24_000, "usage hovers near capacity: {}", pool.used());
4401	}
4402
4403	/// One write pays at most twice what it produced, so a capacity shrink (or one
4404	/// track's burst) drains gradually instead of one writer dumping its whole
4405	/// backlog in a single call.
4406	#[tokio::test]
4407	async fn payment_capped_per_write() {
4408		tokio::time::pause();
4409
4410		let (mut producer, pool) = pooled_producer(1 << 40);
4411		for _ in 0..10 {
4412			finished_group(&mut producer, 1_000);
4413		}
4414
4415		// The governor slashes the target; nothing is reclaimed synchronously.
4416		pool.resize(100);
4417		let before = pool.used();
4418
4419		// One 1k write may evict at most ~2k of backlog, not all ten groups.
4420		finished_group(&mut producer, 1_000);
4421
4422		let consumer = producer.consume();
4423		assert!(consumer.peek_group(0).is_none(), "the oldest groups are evicted");
4424		assert!(consumer.peek_group(1).is_none());
4425		assert!(consumer.peek_group(2).is_some(), "the backlog drains gradually");
4426		assert!(pool.used() > before - 4_000, "one write must not dump the backlog");
4427	}
4428
4429	/// Accepting a track after pre-accept backfill must keep the same write
4430	/// counter: the counter is owned by the track state, so replacing the info
4431	/// can't strand the bytes already-created groups keep charging.
4432	#[tokio::test]
4433	async fn accept_preserves_write_accounting() {
4434		tokio::time::pause();
4435
4436		let pool = cache::Pool::new(12_000);
4437		let broadcast = broadcast::Info {
4438			origin: crate::origin::Info::default().with_pool(pool.clone()),
4439			..Default::default()
4440		};
4441		let request = Request::new(Arc::new(broadcast), "test");
4442		let dynamic = request.dynamic();
4443		let consumer = request.consume();
4444
4445		// Serve a backfill before the track is accepted, then grow it.
4446		let pending = consumer.fetch_group(0, None);
4447		let req = dynamic
4448			.requested_group()
4449			.now_or_never()
4450			.expect("should not block")
4451			.unwrap();
4452		let mut backfill = req.accept(None).unwrap();
4453		pending.await.unwrap();
4454		backfill
4455			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 30_000]))
4456			.unwrap();
4457
4458		// Accept with a fresh Info: the pre-accept group's writes must still be
4459		// drained by this track's future charges.
4460		let mut producer = request.accept(None);
4461		producer.append_group().unwrap().finish().unwrap();
4462		producer.append_group().unwrap().finish().unwrap();
4463
4464		assert!(
4465			producer.consume().peek_group(0).is_none(),
4466			"pre-accept backfill growth is reclaimed after accept"
4467		);
4468		assert!(pool.used() <= 13_000, "usage converges: {}", pool.used());
4469	}
4470
4471	/// Re-serving a sequence many times must not accumulate eviction hints: stale
4472	/// hints die on stamp mismatch and compaction reclaims them.
4473	#[tokio::test]
4474	async fn recreated_sequence_bounds_eviction_hints() {
4475		let (mut producer, _pool) = pooled_producer(1 << 40);
4476		producer.create_group(5u64.into()).unwrap().finish().unwrap();
4477
4478		for _ in 0..200 {
4479			let group = producer.create_group(1u64.into()).unwrap();
4480			group.abort(Error::Cancel).unwrap();
4481		}
4482
4483		let state = producer.state.read();
4484		assert!(
4485			state.evict.len() <= 2 * state.lookup.len() + EVICT_SLACK,
4486			"stale hints are compacted: {} entries for {} slots",
4487			state.evict.len(),
4488			state.lookup.len()
4489		);
4490	}
4491
4492	/// A frame write within the same coarse tick still outranks merely-inserted
4493	/// content, so the freshly-written group survives and the empty one pays.
4494	#[tokio::test]
4495	async fn same_tick_write_outranks_inserted() {
4496		tokio::time::pause();
4497
4498		// No time advances: every stamp lands in the same tick.
4499		let (mut producer, _pool) = pooled_producer(10_000);
4500
4501		producer.append_group().unwrap().finish().unwrap(); // seq 0: empty
4502		finished_group(&mut producer, 3_000); // seq 1: written
4503		finished_group(&mut producer, 3_000); // seq 2
4504		finished_group(&mut producer, 3_000); // seq 3
4505		finished_group(&mut producer, 3_000); // seq 4: over budget, pays
4506
4507		let consumer = producer.consume();
4508		assert!(consumer.peek_group(0).is_none(), "insert-only content pays first");
4509		assert!(consumer.peek_group(1).is_some(), "same-tick written content survives");
4510	}
4511
4512	/// A track that only appends frames to an open group, never inserting another
4513	/// group, still settles its eviction debt once enough bytes accumulate.
4514	#[tokio::test]
4515	async fn frame_only_writer_pays() {
4516		tokio::time::pause();
4517
4518		let (mut producer, pool) = pooled_producer(2_000);
4519		let mut demoted = producer.append_group().unwrap(); // seq 0
4520		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4521
4522		// One large frame crosses the charge threshold: the write itself pays,
4523		// with no further group insert on this track.
4524		demoted
4525			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 300_000]))
4526			.unwrap();
4527
4528		assert!(
4529			pool.used() <= 5_000,
4530			"the frame write settled the debt: {}",
4531			pool.used()
4532		);
4533		assert!(matches!(demoted.finish(), Err(Error::Evicted)));
4534	}
4535
4536	/// One `Info` describing several tracks must not join their eviction accounting:
4537	/// each track opens its own account against the pool.
4538	#[tokio::test]
4539	async fn each_track_owns_its_account() {
4540		let broadcast = Arc::new(broadcast::Info::default());
4541		let info = Info::default();
4542		let a = Producer::new(broadcast.clone(), "a", info.clone());
4543		let b = Producer::new(broadcast, "b", info);
4544
4545		let a = a.state.read().cache.clone();
4546		let b = b.state.read().cache.clone();
4547		assert!(!Arc::ptr_eq(&a, &b), "each track owns its account");
4548	}
4549
4550	/// A `Dynamic` still serving fetches keeps the track alive, so the publisher
4551	/// letting go isn't an abrupt teardown: the handler can still serve the cache.
4552	#[tokio::test]
4553	async fn a_dynamic_defers_teardown() {
4554		let (mut producer, pool) = pooled_producer(1 << 40);
4555		let dynamic = producer.dynamic();
4556		finished_group(&mut producer, 100);
4557
4558		drop(producer);
4559		assert!(pool.used() > 0, "the handler still serves the cache");
4560
4561		drop(dynamic);
4562		assert_eq!(pool.used(), 0, "the last handle tears it down");
4563	}
4564
4565	/// A finished track releases everything once every handle is gone.
4566	///
4567	/// Its groups hold the cache account, and the account links back here, so that link
4568	/// has to be weak: anything stronger makes the state (and every cached frame in it)
4569	/// immortal, even with no producer or consumer left.
4570	#[tokio::test]
4571	async fn finished_track_frees_its_cache() {
4572		let (mut producer, pool) = pooled_producer(1 << 40);
4573		finished_group(&mut producer, 100);
4574		producer.finish().unwrap();
4575
4576		let state = producer.state.downgrade();
4577		drop(producer);
4578
4579		assert!(state.upgrade().is_none(), "the track state is freed");
4580		assert_eq!(pool.used(), 0, "so are its cached bytes");
4581	}
4582
4583	/// A group settling its eviction debt upgrades the account's weak handle, which
4584	/// counts as a producer on the track state. Teardown must not mistake that for a
4585	/// surviving publisher, or an abrupt drop silently behaves like a clean finish.
4586	#[tokio::test]
4587	async fn teardown_ignores_a_settling_group() {
4588		let (mut producer, pool) = pooled_producer(1 << 40);
4589		finished_group(&mut producer, 100);
4590
4591		// Stand in for a concurrent `cache::Track::settle`, mid-upgrade.
4592		let settling = producer.state.downgrade().upgrade().expect("open");
4593		drop(producer);
4594
4595		assert_eq!(pool.used(), 0, "the abrupt teardown still released the cache");
4596		drop(settling);
4597	}
4598
4599	/// A subscriber holding one cached group must not pin the whole track: a group
4600	/// carries the track's properties by value, not a handle back to its state.
4601	#[tokio::test]
4602	async fn cached_group_outlives_its_track() {
4603		let (mut producer, pool) = pooled_producer(1 << 40);
4604		let sequence = finished_group(&mut producer, 100);
4605		let group = producer.consume().peek_group(sequence).expect("cached");
4606		producer.finish().unwrap();
4607
4608		let state = producer.state.downgrade();
4609		drop(producer);
4610		assert!(state.upgrade().is_none(), "the track state is freed");
4611		assert!(pool.used() > 0, "the retained group keeps its own bytes");
4612
4613		drop(group);
4614		assert_eq!(pool.used(), 0, "which it releases when dropped");
4615	}
4616
4617	/// A backfill served before the track was accepted settles its own debt: the
4618	/// account exists from the moment the state does, so acceptance replacing the
4619	/// `Info` can't leave already-created groups writing for free.
4620	#[tokio::test]
4621	async fn pre_accept_backfill_settles_late_writes() {
4622		tokio::time::pause();
4623
4624		let pool = cache::Pool::new(2_000);
4625		let broadcast = broadcast::Info {
4626			origin: crate::origin::Info::default().with_pool(pool.clone()),
4627			..Default::default()
4628		};
4629		let request = Request::new(Arc::new(broadcast), "test");
4630		let dynamic = request.dynamic();
4631		let consumer = request.consume();
4632
4633		// Serve backfill seq 0 before the track is accepted.
4634		let pending = consumer.fetch_group(0, None);
4635		let req = dynamic
4636			.requested_group()
4637			.now_or_never()
4638			.expect("should not block")
4639			.unwrap();
4640		let mut backfill = req.accept(None).unwrap();
4641		pending.await.unwrap();
4642
4643		// Accept, then demote the backfill with a live group.
4644		let mut producer = request.accept(None);
4645		producer.append_group().unwrap().finish().unwrap();
4646
4647		// No further insert: the late write into the demoted backfill is the only
4648		// thing that can pay the debt it just took on.
4649		backfill
4650			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 300_000]))
4651			.unwrap();
4652
4653		assert!(
4654			pool.used() <= 5_000,
4655			"the frame write settled the debt: {}",
4656			pool.used()
4657		);
4658	}
4659
4660	/// A late frame write restarts the retention clock (retention is documented as
4661	/// time since last written or fetched), so an actively-growing group is not
4662	/// expired as old mid-write.
4663	#[tokio::test]
4664	async fn write_restarts_retention_clock() {
4665		tokio::time::pause();
4666
4667		let (mut producer, _pool) = pooled_producer(1 << 40);
4668		let mut straggler = producer.append_group().unwrap(); // seq 0
4669		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4670
4671		// Idle past the window, then the straggler receives a late frame.
4672		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4673		straggler
4674			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4675			.unwrap();
4676		producer.append_group().unwrap().finish().unwrap(); // seq 2 runs expiry
4677
4678		let consumer = producer.consume();
4679		assert!(consumer.peek_group(0).is_some(), "the write restarted the clock");
4680
4681		// Once the writes stop, the group ages out normally.
4682		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4683		producer.append_group().unwrap().finish().unwrap(); // seq 3 runs expiry
4684		assert!(consumer.peek_group(0).is_none(), "idle content still expires");
4685	}
4686
4687	/// Continuously refreshed entries at the front of the eviction order must not
4688	/// starve expiry of entries behind them: the scan cursor rotates.
4689	#[tokio::test]
4690	async fn refreshed_front_does_not_starve_expiry() {
4691		tokio::time::pause();
4692
4693		let (mut producer, _pool) = pooled_producer(1 << 40);
4694		let dynamic = producer.dynamic();
4695		let consumer = producer.consume();
4696
4697		producer.create_group(10u64.into()).unwrap().finish().unwrap();
4698		for sequence in 1..=5u64 {
4699			let pending = consumer.fetch_group(sequence, None);
4700			let req = dynamic
4701				.requested_group()
4702				.now_or_never()
4703				.expect("should not block")
4704				.unwrap();
4705			let mut group = req.accept(None).unwrap();
4706			group
4707				.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4708				.unwrap();
4709			group.finish().unwrap();
4710			pending.await.unwrap();
4711		}
4712
4713		// Age everything out, then refresh the first four backfills so they sit
4714		// fresh at the front of the eviction order, hiding the expired fifth.
4715		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4716		for sequence in 1..=4u64 {
4717			consumer.fetch_group(sequence, None).await.unwrap();
4718		}
4719
4720		// The rotating cursor reaches the fifth entry within a few writes.
4721		for _ in 0..3 {
4722			producer.append_group().unwrap().finish().unwrap();
4723		}
4724		assert!(consumer.peek_group(5).is_none(), "expired backfill is reclaimed");
4725		assert!(consumer.peek_group(1).is_some(), "refreshed backfill survives");
4726	}
4727
4728	/// A publisher re-creating an aborted sequence is delivered exactly once, at
4729	/// its actual arrival position: the historical arrival entry is dead.
4730	#[tokio::test]
4731	async fn recreated_sequence_delivered_once() {
4732		let (mut producer, _pool) = pooled_producer(1 << 40);
4733
4734		producer.create_group(0u64.into()).unwrap().finish().unwrap();
4735		let aborted = producer.create_group(1u64.into()).unwrap();
4736		aborted.abort(Error::Cancel).unwrap();
4737		producer.create_group(2u64.into()).unwrap().finish().unwrap();
4738		producer.create_group(1u64.into()).unwrap().finish().unwrap();
4739
4740		let mut subscriber = producer.subscribe(None);
4741		assert_eq!(subscriber.assert_group().sequence, 0);
4742		assert_eq!(subscriber.assert_group().sequence, 2);
4743		assert_eq!(
4744			subscriber.assert_group().sequence,
4745			1,
4746			"replacement arrives at its own position"
4747		);
4748		subscriber.assert_no_group();
4749	}
4750
4751	/// Datagrams share `max_sequence` but must not break group demotion: the live
4752	/// edge is tracked per group, so interleaving datagrams can't strand groups
4753	/// outside the eviction order and bypass the budget.
4754	#[tokio::test]
4755	async fn datagrams_do_not_block_eviction() {
4756		tokio::time::pause();
4757
4758		let (mut producer, pool) = pooled_producer(1_000);
4759		for _ in 0..10 {
4760			finished_group(&mut producer, 1_000);
4761			producer.append_datagram(Timestamp::ZERO, &b"beat"[..]).unwrap();
4762		}
4763
4764		let consumer = producer.consume();
4765		assert!(consumer.peek_group(0).is_none(), "old groups still evict");
4766		assert!(
4767			pool.used() < 4 * 1_256,
4768			"interleaved datagrams must not bypass the budget: {}",
4769			pool.used()
4770		);
4771	}
4772
4773	/// An aborted group releases its access sample along with its bytes, from any
4774	/// handle: ghost samples must not linger in the pool mean where they'd hold it
4775	/// in the past and over-protect every live group.
4776	#[tokio::test]
4777	async fn aborted_group_leaves_no_ghost_sample() {
4778		tokio::time::pause();
4779
4780		let (mut producer, pool) = pooled_producer(1 << 40);
4781		let group0 = producer.append_group().unwrap();
4782		producer.append_group().unwrap(); // demotes seq 0 into the mean
4783
4784		assert!(pool.average().is_some(), "demoted group is sampled");
4785		group0.abort(Error::Cancel).unwrap();
4786		assert_eq!(pool.average(), None, "the abort must remove the sample");
4787	}
4788
4789	/// Empty groups still carry fixed overhead; they must repay the budget when
4790	/// evicted rather than being unevictable freeloaders.
4791	#[tokio::test]
4792	async fn empty_groups_repay_overhead() {
4793		tokio::time::pause();
4794
4795		let (mut producer, pool) = pooled_producer(1_000);
4796		for _ in 0..100 {
4797			let mut group = producer.append_group().unwrap();
4798			group.finish().unwrap();
4799		}
4800
4801		assert!(
4802			pool.used() <= 3_000,
4803			"empty-group overhead must stay near the budget: {}",
4804			pool.used()
4805		);
4806	}
4807
4808	/// Late growth on an already-demoted group is billed: the gross-write counter
4809	/// feeds debt on the next append, so a straggler can't grow unbounded.
4810	#[tokio::test]
4811	async fn growth_on_demoted_group_is_billed() {
4812		tokio::time::pause();
4813
4814		let (mut producer, pool) = pooled_producer(2_000);
4815		let mut straggler = producer.append_group().unwrap(); // seq 0
4816		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4817
4818		// The demoted group balloons: no eviction yet (nothing ran), but billed.
4819		straggler
4820			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 10_000]))
4821			.unwrap();
4822
4823		// The next append observes the growth and evicts the straggler.
4824		producer.append_group().unwrap().finish().unwrap(); // seq 2
4825
4826		let consumer = producer.consume();
4827		assert!(consumer.peek_group(0).is_none(), "the ballooned group is evicted");
4828		assert!(pool.used() <= 3_000, "growth is reclaimed: {}", pool.used());
4829	}
4830
4831	/// A stale arrival entry whose sequence was later re-served by fetched backfill
4832	/// must not leak the replacement into arrival-order subscriptions.
4833	#[tokio::test]
4834	async fn refilled_sequence_stays_out_of_subscriptions() {
4835		let (mut producer, _pool) = pooled_producer(1 << 40);
4836		let dynamic = producer.dynamic();
4837		let consumer = producer.consume();
4838
4839		producer.create_group(0u64.into()).unwrap().finish().unwrap();
4840		let aborted = producer.create_group(1u64.into()).unwrap();
4841		aborted.abort(Error::Cancel).unwrap();
4842		producer.create_group(2u64.into()).unwrap().finish().unwrap();
4843
4844		// Re-serve seq 1 as backfill; its slot replaces the aborted one, and the
4845		// old arrival entry for seq 1 now resolves to it.
4846		let pending = consumer.fetch_group(1, None);
4847		let req = dynamic
4848			.requested_group()
4849			.now_or_never()
4850			.expect("should not block")
4851			.unwrap();
4852		let mut group = req.accept(None).unwrap();
4853		group
4854			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"backfill"))
4855			.unwrap();
4856		group.finish().unwrap();
4857		pending.await.unwrap();
4858
4859		// The backfill serves by sequence, but never in arrival order.
4860		assert!(consumer.peek_group(1).is_some());
4861		let mut subscriber = producer.subscribe(None);
4862		assert_eq!(subscriber.assert_group().sequence, 0);
4863		assert_eq!(subscriber.assert_group().sequence, 2);
4864		subscriber.assert_no_group();
4865	}
4866
4867	/// An expired backfill can't hide behind a refreshed one: the eviction-order
4868	/// expiry scans a bounded prefix instead of stopping at the first fresh entry.
4869	#[tokio::test]
4870	async fn expired_backfill_behind_refreshed_reclaimed() {
4871		tokio::time::pause();
4872
4873		let (mut producer, _pool) = pooled_producer(1 << 40);
4874		let dynamic = producer.dynamic();
4875		let consumer = producer.consume();
4876
4877		producer.create_group(5u64.into()).unwrap().finish().unwrap();
4878		for sequence in [2u64, 3u64] {
4879			let pending = consumer.fetch_group(sequence, None);
4880			let req = dynamic
4881				.requested_group()
4882				.now_or_never()
4883				.expect("should not block")
4884				.unwrap();
4885			let mut group = req.accept(None).unwrap();
4886			group
4887				.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4888				.unwrap();
4889			group.finish().unwrap();
4890			pending.await.unwrap();
4891		}
4892
4893		// Keep seq 2 fresh while seq 3 (behind it in eviction order) expires.
4894		tokio::time::advance(Duration::from_secs(4)).await;
4895		consumer.fetch_group(2, None).await.unwrap();
4896		tokio::time::advance(DEFAULT_LATENCY_MAX - Duration::from_secs(2)).await;
4897		producer.create_group(6u64.into()).unwrap().finish().unwrap();
4898
4899		let consumer = producer.consume();
4900		assert!(consumer.peek_group(2).is_some(), "refreshed backfill survives");
4901		assert!(consumer.peek_group(3).is_none(), "expired backfill is reclaimed");
4902	}
4903
4904	/// A FETCH hit within the same coarse clock tick still protects the group: the
4905	/// refresh stamps one tick ahead, so it reads strictly newer than the mean.
4906	#[tokio::test]
4907	async fn same_tick_fetch_protects() {
4908		tokio::time::pause();
4909
4910		// No time advances at all: every timestamp lands in the same tick.
4911		let (mut producer, _pool) = pooled_producer(10_000);
4912		let consumer = producer.consume();
4913
4914		finished_group(&mut producer, 3_000); // seq 0
4915		finished_group(&mut producer, 3_000); // seq 1
4916		finished_group(&mut producer, 3_000); // seq 2
4917
4918		consumer.fetch_group(0, None).await.unwrap();
4919
4920		finished_group(&mut producer, 3_000); // seq 3
4921		finished_group(&mut producer, 3_000); // seq 4
4922
4923		assert!(consumer.peek_group(0).is_some(), "same-tick refresh protects");
4924		assert!(consumer.peek_group(1).is_none(), "the unread group dies instead");
4925	}
4926
4927	/// A refetched group that reclaims max_sequence is the live edge again: it must
4928	/// not re-enter the eviction order, or memory pressure could evict the newest
4929	/// content.
4930	#[tokio::test]
4931	async fn refetched_latest_stays_protected() {
4932		tokio::time::pause();
4933
4934		let (mut producer, _pool) = pooled_producer(10_000);
4935		let dynamic = producer.dynamic();
4936		let consumer = producer.consume();
4937
4938		let straggler = producer.append_group().unwrap(); // seq 0
4939
4940		// The publisher aborts its own latest group; the sequence stays at the live edge.
4941		let latest = producer.append_group().unwrap(); // seq 1
4942		latest.abort(Error::Cancel).unwrap();
4943
4944		// Re-fetch it: the replacement takes over max_sequence.
4945		let pending = consumer.fetch_group(1, None);
4946		let req = dynamic
4947			.requested_group()
4948			.now_or_never()
4949			.expect("should not block")
4950			.unwrap();
4951		let mut group = req.accept(None).unwrap();
4952		group
4953			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 1000]))
4954			.unwrap();
4955		group.finish().unwrap();
4956		pending.await.unwrap();
4957
4958		// The refetched latest is protected by omission: it has no entry in the
4959		// eviction order, so no amount of debt can select it.
4960		{
4961			let state = producer.state.read();
4962			assert!(state.lookup.contains_key(&1), "refetched group is cached");
4963			assert!(
4964				state.evict.iter().all(|(sequence, _)| *sequence != 1),
4965				"the live edge must not be an eviction candidate"
4966			);
4967		}
4968		drop(straggler);
4969	}
4970
4971	/// An evicted group is a cache miss, so a fetch re-fetches it and the accepted
4972	/// replacement serves the sequence again (not `Error::Duplicate`).
4973	#[tokio::test]
4974	async fn eviction_allows_refetch() {
4975		tokio::time::pause();
4976
4977		let (mut producer, _pool) = pooled_producer(10_000);
4978		let dynamic = producer.dynamic();
4979
4980		finished_group(&mut producer, 10_000); // seq 0
4981		finished_group(&mut producer, 10_000); // seq 1: demotes seq 0
4982		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4983
4984		let consumer = producer.consume();
4985		assert!(consumer.peek_group(0).is_none());
4986		let pending = consumer.fetch_group(0, None);
4987
4988		let req = dynamic
4989			.requested_group()
4990			.now_or_never()
4991			.expect("should not block")
4992			.unwrap();
4993		assert_eq!(req.sequence(), 0);
4994
4995		let mut group = req.accept(None).unwrap();
4996		group
4997			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"refetched"))
4998			.unwrap();
4999		group.finish().unwrap();
5000
5001		let mut group = pending.await.unwrap();
5002		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"refetched");
5003	}
5004
5005	/// A fetched (backfill) group is served by sequence but never replayed to
5006	/// arrival-order subscribers.
5007	#[tokio::test]
5008	async fn fetched_backfill_not_subscribed() {
5009		let (mut producer, _pool) = pooled_producer(1 << 40);
5010		let dynamic = producer.dynamic();
5011		let consumer = producer.consume();
5012
5013		// The publisher starts at seq 5; earlier groups exist only upstream.
5014		producer.create_group(5u64.into()).unwrap().finish().unwrap();
5015		producer.create_group(6u64.into()).unwrap().finish().unwrap();
5016
5017		// Fetch the gap: it lands in the cache and resolves the fetch...
5018		let pending = consumer.fetch_group(2, None);
5019		let req = dynamic
5020			.requested_group()
5021			.now_or_never()
5022			.expect("should not block")
5023			.unwrap();
5024		let mut group = req.accept(None).unwrap();
5025		group
5026			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"backfill"))
5027			.unwrap();
5028		group.finish().unwrap();
5029		let mut fetched = pending.await.unwrap();
5030		assert_eq!(&fetched.read_frame().await.unwrap().unwrap().payload[..], b"backfill");
5031		assert!(consumer.peek_group(2).is_some(), "backfill is cached for later fetches");
5032
5033		// ...but an arrival-order subscriber only sees the live groups.
5034		let mut subscriber = producer.subscribe(None);
5035		assert_eq!(subscriber.assert_group().sequence, 5);
5036		assert_eq!(subscriber.assert_group().sequence, 6);
5037		subscriber.assert_no_group();
5038	}
5039
5040	/// Fetched backfill isn't in arrival order, so it ages out through the eviction
5041	/// order instead of lingering until the track closes.
5042	#[tokio::test]
5043	async fn expired_backfill_reclaimed() {
5044		tokio::time::pause();
5045
5046		let (mut producer, pool) = pooled_producer(1 << 40);
5047		let dynamic = producer.dynamic();
5048		let consumer = producer.consume();
5049
5050		producer.create_group(5u64.into()).unwrap().finish().unwrap();
5051
5052		// Serve a backfill fetch for an old sequence.
5053		let pending = consumer.fetch_group(2, None);
5054		let req = dynamic
5055			.requested_group()
5056			.now_or_never()
5057			.expect("should not block")
5058			.unwrap();
5059		let mut group = req.accept(None).unwrap();
5060		group
5061			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 1000]))
5062			.unwrap();
5063		group.finish().unwrap();
5064		pending.await.unwrap();
5065		let used = pool.used();
5066
5067		// Age past the track window; the next write reclaims the backfill.
5068		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
5069		producer.create_group(6u64.into()).unwrap().finish().unwrap();
5070
5071		assert!(consumer.peek_group(2).is_none(), "expired backfill is reclaimed");
5072		assert!(pool.used() < used, "its bytes are released");
5073	}
5074
5075	#[tokio::test]
5076	async fn fetch_aborts_with_track() {
5077		let producer = track_producer("test", None);
5078		let dynamic = producer.dynamic();
5079		let consumer = producer.consume();
5080
5081		let pending = consumer.fetch_group(3, None);
5082		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
5083
5084		producer.abort(Error::Cancel).unwrap();
5085		assert!(pending.await.is_err());
5086		drop(dynamic);
5087	}
5088}