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