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		// A raised `start_at` drops parked groups it overtook, and eviction/expiry
2220		// (which aborts a cached group) drops its parked entry. The latter is what
2221		// bounds parking: a subscription capped indefinitely holds only what the
2222		// track's cache policy still retains, not every group it ever observed.
2223		self.parked
2224			.retain(|sequence, group| *sequence >= self.min_sequence && !group.is_aborted());
2225
2226		// Re-offer the lowest parked group back inside the cap once it rises.
2227		if let Some(&sequence) = self.parked.keys().next()
2228			&& self.end_sequence.is_none_or(|end| sequence <= end)
2229		{
2230			return Poll::Ready(Ok(self.parked.remove(&sequence)));
2231		}
2232
2233		loop {
2234			let Some((consumer, found_index)) =
2235				ready!(self.poll(waiter, |state| state.poll_recv_group(self.index, self.min_sequence))?)
2236			else {
2237				// Parked groups survive a finished track: they become deliverable
2238				// again if the cap rises, so the stream isn't over while any are held.
2239				if self.parked.is_empty() {
2240					return Poll::Ready(Ok(None));
2241				}
2242				return Poll::Pending;
2243			};
2244			self.index = found_index + 1;
2245
2246			// Park a group beyond the cap instead of dropping it, and keep scanning
2247			// so an in-range group that arrived behind it still flows.
2248			if self.end_sequence.is_some_and(|end| consumer.sequence > end) {
2249				self.parked.insert(consumer.sequence, consumer);
2250				continue;
2251			}
2252			return Poll::Ready(Ok(Some(consumer)));
2253		}
2254	}
2255
2256	fn poll_recv_datagram(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
2257		let Some((datagram, found_index)) =
2258			ready!(self.poll(waiter, |state| state.poll_recv_datagram(self.datagram_index))?)
2259		else {
2260			return Poll::Ready(Ok(None));
2261		};
2262
2263		self.datagram_index = found_index + 1;
2264		self.next_sequence = self.next_sequence.max(datagram.sequence.saturating_add(1));
2265		Poll::Ready(Ok(Some(datagram)))
2266	}
2267
2268	fn poll_next_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2269		let floor = self.next_sequence.max(self.min_sequence);
2270		let Some(group) = ready!(self.poll(waiter, |state| state.poll_next_in_range(floor, self.end_sequence))?) else {
2271			return Poll::Ready(Ok(None));
2272		};
2273		self.next_sequence = group.sequence.saturating_add(1);
2274		Poll::Ready(Ok(Some(group)))
2275	}
2276
2277	fn poll_read_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Frame>>> {
2278		let lower = self.min_sequence.max(self.next_sequence);
2279		let Some((frame, found_index, sequence)) =
2280			ready!(self.poll(waiter, |state| { state.poll_read_frame(self.index, lower, waiter) })?)
2281		else {
2282			return Poll::Ready(Ok(None));
2283		};
2284
2285		self.index = found_index + 1;
2286		self.next_sequence = sequence.saturating_add(1);
2287		Poll::Ready(Ok(Some(frame)))
2288	}
2289}
2290
2291/// A cloneable handle to a subscriber's delivery preferences.
2292///
2293/// This updates the same subscription as the owning [`Subscriber`] without
2294/// borrowing its read cursor, so callers can change delivery priority, group
2295/// ordering priority, or group bounds while another task is waiting for groups.
2296#[derive(Clone)]
2297pub struct SubscriberControl {
2298	subscription: kio::Producer<Subscription>,
2299}
2300
2301impl SubscriberControl {
2302	/// This subscriber's current preferences.
2303	pub fn subscription(&self) -> Subscription {
2304		self.subscription.read().clone()
2305	}
2306
2307	/// Replace this subscriber's preferences, updating the producer's aggregate.
2308	///
2309	/// Returns [`Error::Closed`] if the track already ended; the update is
2310	/// meaningless at that point and can usually be ignored.
2311	pub fn update(&self, subscription: Subscription) -> Result<()> {
2312		let mut state = self.subscription.write().map_err(|_| Error::Closed)?;
2313		*state = subscription;
2314		Ok(())
2315	}
2316}
2317
2318impl Subscriber {
2319	/// The track's [`Info`], resolved when the subscription was established.
2320	///
2321	/// Free, unlike [`Consumer::info`]: subscribing already waited for the info
2322	/// (SUBSCRIBE_OK on the wire), so a subscriber always has it.
2323	pub fn info(&self) -> &Info {
2324		&self.info
2325	}
2326
2327	/// The track's name, unique within its broadcast.
2328	pub fn name(&self) -> &str {
2329		&self.name
2330	}
2331
2332	/// Create a handle for updating this subscriber's delivery preferences.
2333	pub fn control(&self) -> SubscriberControl {
2334		SubscriberControl {
2335			subscription: match &self.inner {
2336				SubscriberKind::Plain(plain) => plain.subscription.clone(),
2337				SubscriberKind::Spliced(spliced) => spliced.prefs(),
2338			},
2339		}
2340	}
2341
2342	/// Poll for the next group in arrival order, without blocking.
2343	///
2344	/// Returns every group exactly once in the order it landed on the wire, which may be
2345	/// out of sequence due to network reordering or loss. Use [`Self::poll_next_group`] if
2346	/// you only want groups whose sequence number is higher than any previously returned.
2347	///
2348	/// Honors the floor set by [`Self::start_at`] and the cap set by [`Self::end_at`]:
2349	/// a group beyond the cap is parked (not dropped) and re-offered once the cap rises
2350	/// (lowest sequence first), without blocking in-range groups that arrive behind it.
2351	/// A parked group that the producer evicts or expires in the meantime is dropped,
2352	/// so parking never outlives the track's cache policy.
2353	///
2354	/// Returns `Poll::Ready(Ok(Some(group)))` when a group is available,
2355	/// `Poll::Ready(Ok(None))` when the track is finished,
2356	/// `Poll::Ready(Err(e))` when the track has been aborted, or
2357	/// `Poll::Pending` when no group is available yet.
2358	pub fn poll_recv_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2359		let meter = self.stats.meter();
2360		let res = match &mut self.inner {
2361			SubscriberKind::Plain(plain) => plain.poll_recv_group(waiter),
2362			SubscriberKind::Spliced(spliced) => spliced.poll_recv_group(waiter),
2363		};
2364		res.map(|res| res.map(|group| group.map(|group| group.with_meter(meter))))
2365	}
2366
2367	/// Receive the next group in arrival order.
2368	///
2369	/// Every group is returned exactly once, in the order it landed on the wire, which may
2370	/// be out of sequence due to network reordering or loss. Use [`Self::next_group`] if you
2371	/// only want groups whose sequence number is higher than any previously returned.
2372	/// See [`Self::poll_recv_group`] for how [`Self::start_at`] and [`Self::end_at`] apply.
2373	pub async fn recv_group(&mut self) -> Result<Option<group::Consumer>> {
2374		kio::wait(|waiter| self.poll_recv_group(waiter)).await
2375	}
2376
2377	/// Poll for the next datagram in arrival order, without blocking.
2378	///
2379	/// Datagrams are a separate best-effort channel from groups (see
2380	/// [`Producer::append_datagram`]); they share only the sequence namespace. A consumer
2381	/// that falls too far behind silently loses the oldest datagrams.
2382	/// Returning a datagram advances [`Self::poll_next_group`] past that sequence.
2383	///
2384	/// Returns `Poll::Ready(Ok(Some(datagram)))` when one is available,
2385	/// `Poll::Ready(Ok(None))` when the track is finished, `Poll::Ready(Err(e))` when the track
2386	/// is aborted, or `Poll::Pending` when none is buffered yet.
2387	pub fn poll_recv_datagram(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
2388		let meter = self.stats.meter();
2389		let res = match &mut self.inner {
2390			SubscriberKind::Plain(plain) => plain.poll_recv_datagram(waiter),
2391			SubscriberKind::Spliced(spliced) => spliced.poll_recv_datagram(waiter),
2392		};
2393		// Unlike a group (metered lazily as its frames are read), a datagram is
2394		// delivered whole here, so count it as the single-frame group it stands in for.
2395		if let Poll::Ready(Ok(Some(datagram))) = &res {
2396			meter.datagram(datagram.payload.len() as u64);
2397		}
2398		res
2399	}
2400
2401	/// Receive the next datagram in arrival order.
2402	///
2403	/// A best-effort channel parallel to [`Self::recv_group`]; the two share only the sequence
2404	/// namespace. To receive both concurrently from one subscriber, poll [`Self::poll_next_group`]
2405	/// (or [`Self::poll_recv_group`]) and [`Self::poll_recv_datagram`] together in a single `poll`
2406	/// closure (sequential `&mut` borrows), rather than awaiting the two `recv` futures at once.
2407	pub async fn recv_datagram(&mut self) -> Result<Option<Datagram>> {
2408		kio::wait(|waiter| self.poll_recv_datagram(waiter)).await
2409	}
2410
2411	/// Poll for the next group with a higher sequence number than any previously returned.
2412	///
2413	/// Late arrivals (sequence at or below the last returned) are silently skipped, so this
2414	/// produces a monotonically increasing sequence at the cost of dropping out-of-order
2415	/// groups. Use [`Self::poll_recv_group`] to see every group in arrival order instead.
2416	///
2417	/// Honors the cap set by [`Self::end_at`]: groups with sequence past the cap are left
2418	/// in the producer's cache and become eligible again if the cap is raised or removed.
2419	pub fn poll_next_group(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<group::Consumer>>> {
2420		let meter = self.stats.meter();
2421		let res = match &mut self.inner {
2422			SubscriberKind::Plain(plain) => plain.poll_next_group(waiter),
2423			SubscriberKind::Spliced(spliced) => spliced.poll_next_group(waiter),
2424		};
2425		res.map(|res| res.map(|group| group.map(|group| group.with_meter(meter))))
2426	}
2427
2428	/// Return the next group with a higher sequence number than any previously returned.
2429	///
2430	/// Late arrivals (sequence at or below the last returned) are silently skipped, so this
2431	/// produces a monotonically increasing sequence at the cost of dropping out-of-order
2432	/// groups. Use [`Self::recv_group`] to see every group in arrival order instead.
2433	pub async fn next_group(&mut self) -> Result<Option<group::Consumer>> {
2434		kio::wait(|waiter| self.poll_next_group(waiter)).await
2435	}
2436
2437	/// A helper that calls [`Self::poll_next_group`] and returns its first frame
2438	/// (timestamp and payload), skipping the rest of the group. Intended for
2439	/// single-frame groups (see [`Producer::write_frame`]).
2440	pub fn poll_read_frame(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<frame::Frame>>> {
2441		let meter = self.stats.meter();
2442		let res = match &mut self.inner {
2443			SubscriberKind::Plain(plain) => plain.poll_read_frame(waiter),
2444			SubscriberKind::Spliced(spliced) => spliced.poll_read_frame(waiter),
2445		};
2446		// This helper collapses a group to its first frame: count the group, the one
2447		// frame, and the bytes actually read.
2448		if let Poll::Ready(Ok(Some(frame))) = &res {
2449			meter.group();
2450			meter.frames(1);
2451			meter.bytes(frame.payload.len() as u64);
2452		}
2453		res
2454	}
2455
2456	/// Read a single full frame (timestamp and payload) from the next group in
2457	/// sequence order.
2458	///
2459	/// See [`Self::poll_read_frame`] for semantics.
2460	pub async fn read_frame(&mut self) -> Result<Option<frame::Frame>> {
2461		kio::wait(|waiter| self.poll_read_frame(waiter)).await
2462	}
2463
2464	/// Whether `other` was cloned from this subscriber (shares the same underlying state).
2465	pub fn is_clone(&self, other: &Self) -> bool {
2466		match (&self.inner, &other.inner) {
2467			(SubscriberKind::Plain(a), SubscriberKind::Plain(b)) => a.state.same_channel(&b.state),
2468			(SubscriberKind::Spliced(a), SubscriberKind::Spliced(b)) => a.is_clone(b),
2469			_ => false,
2470		}
2471	}
2472
2473	/// Poll for the track's declared final sequence, without blocking.
2474	pub fn poll_finished(&mut self, waiter: &kio::Waiter) -> Poll<Result<u64>> {
2475		match &mut self.inner {
2476			SubscriberKind::Plain(plain) => plain.poll(waiter, |state| state.poll_finished()),
2477			SubscriberKind::Spliced(spliced) => spliced.poll_finished(waiter),
2478		}
2479	}
2480
2481	/// Block until the track declares its end, returning the exclusive final sequence
2482	/// (also the total group count), or the cause on an abort.
2483	///
2484	/// Resolves as soon as the boundary is known, which may be ahead of the live edge
2485	/// when the producer finished via [`Producer::finish_at`]. This reports the declared
2486	/// end, not that every group has arrived: drive [`Self::recv_group`] /
2487	/// [`Self::next_group`] until they yield `None` to observe the track fully drained.
2488	pub async fn finished(&mut self) -> Result<u64> {
2489		kio::wait(|waiter| self.poll_finished(waiter)).await
2490	}
2491
2492	/// Start this subscriber's read cursor at the given sequence.
2493	///
2494	/// A local filter, not a request: it doesn't tell the publisher anything, so the
2495	/// skipped groups are still delivered and simply not returned. To ask the publisher
2496	/// to start there instead, set [`Subscription::group_start`] via [`Self::update`].
2497	/// See [Local cursor vs wire preference](Self#local-cursor-vs-wire-preference).
2498	pub fn start_at(&mut self, sequence: u64) {
2499		match &mut self.inner {
2500			SubscriberKind::Plain(plain) => plain.min_sequence = sequence,
2501			SubscriberKind::Spliced(spliced) => spliced.start_at(sequence),
2502		}
2503	}
2504
2505	/// Cap this subscriber's read cursor at the given sequence (inclusive), or remove the
2506	/// cap entirely.
2507	///
2508	/// Accepts a bare `u64` (cap), `Some(u64)`, or `None` (uncap).
2509	///
2510	/// A local filter, not a request; [`Subscription::group_end`] is the wire-level
2511	/// counterpart. See [Local cursor vs wire preference](Self#local-cursor-vs-wire-preference).
2512	///
2513	/// Affects [`Self::next_group`] and [`Self::recv_group`]: groups beyond the cap are
2514	/// held rather than skipped past, so a later call to [`Self::end_at`] with a higher
2515	/// value (or `None`) makes them available again. Lowering the cap below the
2516	/// consumer's current cursor parks the consumer until the cap is raised.
2517	pub fn end_at(&mut self, sequence: impl Into<Option<u64>>) {
2518		match &mut self.inner {
2519			SubscriberKind::Plain(plain) => plain.end_sequence = sequence.into(),
2520			SubscriberKind::Spliced(spliced) => spliced.end_at(sequence),
2521		}
2522	}
2523
2524	/// This subscriber's current preferences.
2525	pub fn subscription(&self) -> Subscription {
2526		self.control().subscription()
2527	}
2528
2529	/// Replace this subscriber's delivery preferences.
2530	///
2531	/// Stored verbatim; the publisher's latency window is applied to the aggregate, not
2532	/// here (see [`Producer::subscription`]). Returns [`Error::Closed`] if the track
2533	/// already ended; the update is meaningless at that point and can usually be ignored.
2534	pub fn update(&mut self, subscription: Subscription) -> Result<()> {
2535		match &mut self.inner {
2536			SubscriberKind::Plain(plain) => {
2537				let mut state = plain.subscription.write().map_err(|_| Error::Closed)?;
2538				*state = subscription;
2539			}
2540			SubscriberKind::Spliced(spliced) => spliced.update(subscription),
2541		}
2542		Ok(())
2543	}
2544
2545	/// Return the latest sequence number in the track.
2546	pub fn latest(&self) -> Option<u64> {
2547		match &self.inner {
2548			SubscriberKind::Plain(plain) => plain.state.read().max_sequence,
2549			SubscriberKind::Spliced(spliced) => spliced.latest(),
2550		}
2551	}
2552}
2553
2554/// A subscriber asked for a track this broadcast doesn't have yet.
2555///
2556/// Yielded by [`broadcast::Dynamic::requested_track`](crate::broadcast::Dynamic::requested_track),
2557/// or created up front with [`broadcast::Producer::reserve_track`](crate::broadcast::Producer::reserve_track).
2558/// Subscribers block until the request is
2559/// resolved: call [`accept`](Self::accept) to serve it with a [`Producer`], or
2560/// [`reject`](Self::reject) to fail them. Dropping it without either rejects with
2561/// [`Error::Dropped`].
2562///
2563/// Concurrent requests for one name are coalesced, so exactly one of these exists per
2564/// name at a time.
2565pub struct Request {
2566	name: Arc<str>,
2567	// The parent broadcast's info, threaded into the [`Producer`] on accept.
2568	broadcast: Arc<broadcast::Info>,
2569	state: kio::Producer<TrackState>,
2570
2571	// The previous subscription that was combined, used to detect changes.
2572	prev_subscription: Option<Subscription>,
2573
2574	// Shared with the accepted [`Producer`] and every [`Dynamic`]: its `Drop` is the
2575	// teardown, and it stays inert until a producer is minted.
2576	alive: Arc<Alive>,
2577
2578	// A requested track is served on demand, so it counts as fetch-capable from
2579	// birth: a consumer's cache-miss `fetch_group` waits to be served instead of
2580	// racing the producer (e.g. a relay) into creating its own handler. Released
2581	// when the request is accepted or dropped; by then the relay holds its own.
2582	_dynamic: Dynamic,
2583
2584	// Ingress stats scope, threaded into the accepted [`Producer`]. Empty (no-op)
2585	// unless this request was reserved on a tagged broadcast.
2586	stats: stats::Scope,
2587}
2588
2589impl Request {
2590	pub(crate) fn new(broadcast: Arc<broadcast::Info>, name: impl Into<Arc<str>>) -> Self {
2591		let name = name.into();
2592		let state = TrackState::spawn(broadcast.clone());
2593		let alive = Alive::new(name.clone(), state.clone());
2594		let dynamic = Dynamic::new(name.clone(), state.clone(), alive.clone());
2595		Self {
2596			name,
2597			broadcast,
2598			state,
2599			prev_subscription: None,
2600			alive,
2601			_dynamic: dynamic,
2602			stats: stats::Scope::default(),
2603		}
2604	}
2605
2606	/// Attach an ingress stats scope, applied to the [`Producer`] on accept. Set by
2607	/// a tagged [`broadcast::Producer::reserve_track`].
2608	pub(crate) fn with_stats(mut self, scope: stats::Scope) -> Self {
2609		self.stats = scope;
2610		self
2611	}
2612
2613	/// The requested track name.
2614	pub fn name(&self) -> &str {
2615		&self.name
2616	}
2617
2618	/// A [`Consumer`] for the eventual track, usable before the request is accepted.
2619	pub fn consume(&self) -> Consumer {
2620		Consumer::plain(self.name.clone(), self.state.consume())
2621	}
2622
2623	/// Create a [`Dynamic`] handle that serves on-demand fetches of uncached
2624	/// groups, before [`Self::accept`] is even called. A relay creates one to fetch
2625	/// past groups from upstream while (or instead of) serving a live subscription.
2626	pub fn dynamic(&self) -> Dynamic {
2627		Dynamic::new(self.name.clone(), self.state.clone(), self.alive.clone())
2628	}
2629
2630	/// Poll for the request becoming unused (every consumer dropped), so a relay can
2631	/// stop serving and drop the request.
2632	pub fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
2633		self.state.poll_unused(waiter).map(|_| ())
2634	}
2635
2636	/// Serve the request with the given track, resolving every waiting subscriber.
2637	///
2638	/// The name is taken from [`Self::name`]; `info` supplies the remaining knobs
2639	/// (`None` for the defaults). If the track was already aborted, the returned
2640	/// [`Producer`] is inert: writes fail with the abort error, as if it had been
2641	/// aborted immediately after accepting.
2642	pub fn accept(self, info: impl Into<Option<Info>>) -> Producer {
2643		// A closed state means the track was aborted under us. Mirror `reject` and
2644		// tolerate it: the Producer we hand back simply can't write.
2645		if let Ok(mut state) = self.state.write() {
2646			state.install(info.into().unwrap_or_default());
2647		}
2648		// Accepting the request creates the track producer: count it as one ingress
2649		// subscription (closed when the last handle drops). No-op when untagged.
2650		self.alive.publish(Some(&self.stats));
2651		Producer {
2652			name: self.name,
2653			broadcast: self.broadcast,
2654			state: self.state,
2655			prev_subscription: None,
2656			alive: self.alive,
2657			stats: self.stats,
2658		}
2659	}
2660
2661	/// Reject the request, waking all waiting subscribers with `err`.
2662	pub fn reject(self, err: Error) {
2663		if let Ok(mut state) = self.state.write() {
2664			state.abort = Some(err);
2665		}
2666	}
2667
2668	/// The delivery preferences aggregated across everyone waiting on this request,
2669	/// or `None` if nobody is waiting. Useful for sizing the track before accepting.
2670	pub fn subscription(&self) -> Option<Subscription> {
2671		let state = self.state.read();
2672		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
2673		drop(state);
2674		snapshot_subscription(&subs, bound)
2675	}
2676
2677	/// Block until the aggregate [`subscription`](Self::subscription) changes,
2678	/// yielding `None` once nobody is waiting.
2679	pub async fn subscription_changed(&mut self) -> Option<Subscription> {
2680		kio::wait(|waiter| self.poll_subscription_changed(waiter)).await
2681	}
2682
2683	/// Poll counterpart to [`subscription_changed`](Self::subscription_changed).
2684	pub fn poll_subscription_changed(&mut self, waiter: &kio::Waiter) -> Poll<Option<Subscription>> {
2685		let state = self.state.read();
2686		let (subs, bound) = (state.subscriptions.clone(), state.latency_bound());
2687		drop(state);
2688
2689		let prev = &self.prev_subscription;
2690		let mut combined = None;
2691		let mut guard = ready!(subs.poll(waiter, |subs| {
2692			let next = combined_subscription(subs, bound, waiter);
2693			if &next == prev {
2694				Poll::Pending
2695			} else {
2696				combined = next;
2697				Poll::Ready(())
2698			}
2699		}));
2700		// The aggregate changed: prune any closed subscribers now that we hold the lock.
2701		guard.retain(|sub| !sub.is_closed());
2702		drop(guard);
2703		self.prev_subscription = combined.clone();
2704		Poll::Ready(combined)
2705	}
2706
2707	pub(super) fn weak(&self) -> TrackWeak {
2708		TrackWeak {
2709			name: self.name.clone(),
2710			state: self.state.weak(),
2711		}
2712	}
2713}
2714
2715#[cfg(test)]
2716use futures::FutureExt;
2717
2718#[cfg(test)]
2719#[allow(missing_docs)] // test-only assertion helpers
2720impl Subscriber {
2721	pub fn assert_group(&mut self) -> group::Consumer {
2722		self.recv_group()
2723			.now_or_never()
2724			.expect("group would have blocked")
2725			.expect("would have errored")
2726			.expect("track was closed")
2727	}
2728
2729	pub fn assert_no_group(&mut self) {
2730		assert!(
2731			self.recv_group().now_or_never().is_none(),
2732			"recv_group would not have blocked"
2733		);
2734	}
2735
2736	pub fn assert_not_closed(&mut self) {
2737		assert!(self.finished().now_or_never().is_none(), "should not be closed");
2738	}
2739
2740	pub fn assert_closed(&mut self) {
2741		assert!(self.finished().now_or_never().is_some(), "should be closed");
2742	}
2743
2744	// TODO assert specific errors after implementing PartialEq
2745	pub fn assert_error(&mut self) {
2746		assert!(
2747			self.finished().now_or_never().expect("should not block").is_err(),
2748			"should be error"
2749		);
2750	}
2751
2752	pub fn assert_is_clone(&self, other: &Self) {
2753		assert!(self.is_clone(other), "should be clone");
2754	}
2755
2756	pub fn assert_not_clone(&self, other: &Self) {
2757		assert!(!self.is_clone(other), "should not be clone");
2758	}
2759}
2760
2761#[cfg(test)]
2762mod test {
2763	use super::*;
2764	use crate::model::test_tracing::count_drop_warnings;
2765
2766	/// Mint a track for tests with a default parent broadcast, since tracks are
2767	/// normally born from a [`broadcast::Producer`].
2768	fn track_producer(name: impl Into<Arc<str>>, info: impl Into<Option<Info>>) -> Producer {
2769		Producer::new(Arc::new(broadcast::Info::default()), name, info)
2770	}
2771
2772	/// Helper: count live cached groups in state.
2773	fn live_groups(state: &TrackState) -> usize {
2774		state.lookup.len()
2775	}
2776
2777	/// Helper: get the sequence number of the first live group in arrival order.
2778	fn first_live_sequence(state: &TrackState) -> u64 {
2779		state
2780			.arrival
2781			.iter()
2782			.find(|(sequence, stamp)| state.lookup.get(sequence).is_some_and(|slot| slot.stamp == *stamp))
2783			.map(|(sequence, _)| *sequence)
2784			.unwrap()
2785	}
2786
2787	/// Helper: non-blocking datagram receive that must be ready with a datagram.
2788	fn recv_datagram(dg: &mut Subscriber) -> Datagram {
2789		dg.recv_datagram()
2790			.now_or_never()
2791			.expect("datagram would have blocked")
2792			.expect("would have errored")
2793			.expect("track was closed")
2794	}
2795
2796	#[tokio::test]
2797	async fn append_datagram_shares_group_sequence() {
2798		let mut producer = track_producer("test", None);
2799		let ts = Timestamp::from_millis(10).unwrap();
2800
2801		// Interleave groups and datagrams: they draw from one monotonic counter.
2802		assert_eq!(producer.append_group().unwrap().sequence, 0);
2803		assert_eq!(producer.append_datagram(ts, &b"a"[..]).unwrap(), 1);
2804		assert_eq!(producer.append_group().unwrap().sequence, 2);
2805		assert_eq!(producer.append_datagram(ts, &b"b"[..]).unwrap(), 3);
2806		assert_eq!(producer.latest(), Some(3));
2807	}
2808
2809	#[tokio::test]
2810	async fn append_datagram_roundtrip() {
2811		let mut producer = track_producer("test", None);
2812		let mut dg = producer.subscribe(None);
2813
2814		let ts = Timestamp::from_millis(42).unwrap();
2815		let seq = producer.append_datagram(ts, &b"hello"[..]).unwrap();
2816
2817		let got = recv_datagram(&mut dg);
2818		assert_eq!(got.sequence, seq);
2819		assert_eq!(got.timestamp, ts);
2820		assert_eq!(&got.payload[..], b"hello");
2821	}
2822
2823	#[tokio::test]
2824	async fn write_datagram_preserves_sequence() {
2825		let mut producer = track_producer("test", None);
2826		let mut dg = producer.subscribe(None);
2827
2828		let ts = Timestamp::from_millis(5).unwrap();
2829		// A relay forwarding an upstream datagram keeps its sequence number.
2830		producer
2831			.write_datagram(Datagram {
2832				sequence: 100,
2833				timestamp: ts,
2834				payload: bytes::Bytes::from_static(b"x"),
2835			})
2836			.unwrap();
2837
2838		assert_eq!(recv_datagram(&mut dg).sequence, 100);
2839		// max_sequence advanced, so the next appended group/datagram continues past it.
2840		assert_eq!(producer.append_group().unwrap().sequence, 101);
2841	}
2842
2843	#[tokio::test]
2844	async fn recv_datagram_advances_ordered_group_cursor() {
2845		let mut producer = track_producer("test", None);
2846		let mut subscriber = producer.subscribe(None);
2847		let ts = Timestamp::from_millis(5).unwrap();
2848
2849		producer
2850			.write_datagram(Datagram {
2851				sequence: 5,
2852				timestamp: ts,
2853				payload: bytes::Bytes::from_static(b"x"),
2854			})
2855			.unwrap();
2856		assert_eq!(recv_datagram(&mut subscriber).sequence, 5);
2857
2858		producer.create_group(group::Info { sequence: 3 }).unwrap();
2859		producer.create_group(group::Info { sequence: 6 }).unwrap();
2860
2861		let group = subscriber
2862			.next_group()
2863			.now_or_never()
2864			.expect("group would have blocked")
2865			.expect("would have errored")
2866			.expect("track was closed");
2867		assert_eq!(group.sequence, 6);
2868	}
2869
2870	#[tokio::test]
2871	async fn datagram_normalized_to_track_timescale() {
2872		let info = Info::default().with_timescale(Timescale::MICRO);
2873		let mut producer = track_producer("test", info);
2874		let mut dg = producer.subscribe(None);
2875
2876		// Supplied at millis; stored/emitted at the track's micro timescale.
2877		producer
2878			.append_datagram(Timestamp::from_millis(2).unwrap(), &b"z"[..])
2879			.unwrap();
2880		let got = recv_datagram(&mut dg);
2881		assert_eq!(got.timestamp.scale(), Timescale::MICRO);
2882		assert_eq!(got.timestamp.value(), 2_000);
2883	}
2884
2885	#[tokio::test]
2886	async fn datagram_rejects_oversized() {
2887		let mut producer = track_producer("test", None);
2888		let big = bytes::Bytes::from(vec![0u8; crate::model::datagram::MAX_DATAGRAM_PAYLOAD + 1]);
2889		let ts = Timestamp::from_millis(0).unwrap();
2890		assert!(matches!(
2891			producer.append_datagram(ts, big.clone()),
2892			Err(Error::FrameTooLarge)
2893		));
2894		assert!(matches!(
2895			producer.write_datagram(Datagram {
2896				sequence: 0,
2897				timestamp: ts,
2898				payload: big,
2899			}),
2900			Err(Error::FrameTooLarge)
2901		));
2902	}
2903
2904	#[tokio::test]
2905	async fn datagram_fanout_to_subscribers() {
2906		let mut producer = track_producer("test", None);
2907		// Two independent subscribers, each with its own datagram cursor.
2908		let mut a = producer.subscribe(None);
2909		let mut b = producer.subscribe(None);
2910		let ts = Timestamp::from_millis(1).unwrap();
2911
2912		producer.append_datagram(ts, &b"first"[..]).unwrap();
2913		producer.append_datagram(ts, &b"second"[..]).unwrap();
2914
2915		// Both receive every datagram in order, independently.
2916		assert_eq!(&recv_datagram(&mut a).payload[..], b"first");
2917		assert_eq!(&recv_datagram(&mut a).payload[..], b"second");
2918		assert_eq!(&recv_datagram(&mut b).payload[..], b"first");
2919		assert_eq!(&recv_datagram(&mut b).payload[..], b"second");
2920	}
2921
2922	#[tokio::test]
2923	async fn datagram_evicts_stale() {
2924		tokio::time::pause();
2925
2926		let mut producer = track_producer("test", None);
2927		let mut dg = producer.subscribe(None);
2928		let ts = Timestamp::from_millis(0).unwrap();
2929
2930		producer.append_datagram(ts, &b"old"[..]).unwrap(); // sequence 0
2931
2932		// Age past the send-buffer window, then push a fresh datagram: the stale one is evicted.
2933		tokio::time::advance(MAX_DATAGRAM_AGE + Duration::from_millis(10)).await;
2934		producer.append_datagram(ts, &b"new"[..]).unwrap(); // sequence 1
2935
2936		// A lagging consumer resumes at the oldest still-buffered datagram (the fresh one).
2937		let got = recv_datagram(&mut dg);
2938		assert_eq!(got.sequence, 1);
2939		assert_eq!(&got.payload[..], b"new");
2940	}
2941
2942	#[tokio::test]
2943	async fn datagram_recv_pends_until_written() {
2944		let mut producer = track_producer("test", None);
2945		let mut dg = producer.subscribe(None);
2946
2947		assert!(
2948			dg.recv_datagram().now_or_never().is_none(),
2949			"should block with no datagrams"
2950		);
2951
2952		producer
2953			.append_datagram(Timestamp::from_millis(0).unwrap(), &b"go"[..])
2954			.unwrap();
2955		assert_eq!(&recv_datagram(&mut dg).payload[..], b"go");
2956	}
2957
2958	/// Exercises the full producer -> publisher-encode -> subscriber-decode -> producer seam
2959	/// (everything but the QUIC datagram send/recv), catching any field-order mismatch between
2960	/// the wire codec and the model.
2961	#[tokio::test]
2962	async fn datagram_wire_roundtrip_between_tracks() {
2963		use crate::coding::{Decode, Encode};
2964		use crate::lite;
2965
2966		let version = lite::Version::Lite05;
2967
2968		// Origin publishes a datagram; the publisher reads it and encodes the wire body.
2969		let mut origin = track_producer("test", None);
2970		let mut origin_dg = origin.subscribe(None);
2971		let ts = Timestamp::from_millis(7).unwrap();
2972		let seq = origin.append_datagram(ts, &b"payload"[..]).unwrap();
2973
2974		let d = recv_datagram(&mut origin_dg);
2975		let body = lite::Datagram {
2976			subscribe: 5,
2977			sequence: d.sequence,
2978			timestamp: d.timestamp.value(),
2979			payload: d.payload.clone(),
2980		}
2981		.encode_bytes(version)
2982		.unwrap();
2983
2984		// Subscriber decodes the body and writes it downstream, preserving the sequence.
2985		let mut slice = &body[..];
2986		let wire = lite::Datagram::decode(&mut slice, version).unwrap();
2987		let mut downstream = track_producer("test", None);
2988		let mut downstream_dg = downstream.subscribe(None);
2989		downstream
2990			.write_datagram(Datagram {
2991				sequence: wire.sequence,
2992				timestamp: Timestamp::new(wire.timestamp, Timescale::MILLI).unwrap(),
2993				payload: wire.payload,
2994			})
2995			.unwrap();
2996
2997		let got = recv_datagram(&mut downstream_dg);
2998		assert_eq!(got.sequence, seq);
2999		assert_eq!(got.timestamp, ts);
3000		assert_eq!(&got.payload[..], b"payload");
3001	}
3002
3003	#[tokio::test]
3004	async fn evict_expired_groups() {
3005		tokio::time::pause();
3006
3007		let mut producer = track_producer("test", None);
3008
3009		// Create 3 groups at time 0.
3010		producer.append_group().unwrap(); // seq 0
3011		producer.append_group().unwrap(); // seq 1
3012		producer.append_group().unwrap(); // seq 2
3013
3014		{
3015			let state = producer.state.read();
3016			assert_eq!(live_groups(&state), 3);
3017			assert_eq!(state.offset, 0);
3018		}
3019
3020		// Advance time past the eviction threshold.
3021		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3022
3023		// Append a new group to trigger eviction.
3024		producer.append_group().unwrap(); // seq 3
3025
3026		// Groups 0, 1, 2 are expired but seq 3 (the live edge) is kept. Their arrival
3027		// entries no longer resolve, so the leading ones are trimmed and the offset
3028		// advances past them.
3029		{
3030			let state = producer.state.read();
3031			assert_eq!(live_groups(&state), 1);
3032			assert_eq!(first_live_sequence(&state), 3);
3033			assert_eq!(state.offset, 3);
3034			assert!(!state.lookup.contains_key(&0));
3035			assert!(!state.lookup.contains_key(&1));
3036			assert!(!state.lookup.contains_key(&2));
3037			assert!(state.lookup.contains_key(&3));
3038		}
3039	}
3040
3041	/// A group whose frames outlive `latency_max` is aged out when the next group starts, but
3042	/// a subscriber that already drained it must still see the clean end of group. Otherwise a
3043	/// track with long groups (a per-minute rollup, say) fails its readers at every boundary.
3044	#[tokio::test]
3045	async fn aging_out_a_finished_group_keeps_the_clean_end() {
3046		tokio::time::pause();
3047
3048		let mut producer = track_producer("test", None);
3049		let mut group = producer.create_group(group::Info { sequence: 0 }).unwrap();
3050		let mut consumer = group.consume();
3051
3052		group
3053			.write_frame(Timestamp::from_millis(0).unwrap(), b"hello".as_slice())
3054			.unwrap();
3055		assert_eq!(consumer.next_frame().await.unwrap().unwrap().size, 5);
3056
3057		// The group stays open well past latency_max, then the next period starts.
3058		tokio::time::advance(DEFAULT_LATENCY_MAX * 12).await;
3059		group.finish().unwrap();
3060		let _next = producer.create_group(group::Info { sequence: 1 }).unwrap();
3061
3062		assert!(consumer.next_frame().await.unwrap().is_none());
3063	}
3064
3065	#[tokio::test]
3066	async fn evict_keeps_max_sequence() {
3067		tokio::time::pause();
3068
3069		let mut producer = track_producer("test", None);
3070		producer.append_group().unwrap(); // seq 0
3071
3072		// Advance time past threshold.
3073		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3074
3075		// Append another group; seq 0 is expired and evicted.
3076		producer.append_group().unwrap(); // seq 1
3077
3078		{
3079			let state = producer.state.read();
3080			assert_eq!(live_groups(&state), 1);
3081			assert_eq!(first_live_sequence(&state), 1);
3082			assert_eq!(state.offset, 1);
3083		}
3084	}
3085
3086	#[tokio::test]
3087	async fn no_eviction_when_fresh() {
3088		tokio::time::pause();
3089
3090		let mut producer = track_producer("test", None);
3091		producer.append_group().unwrap(); // seq 0
3092		producer.append_group().unwrap(); // seq 1
3093		producer.append_group().unwrap(); // seq 2
3094
3095		{
3096			let state = producer.state.read();
3097			assert_eq!(live_groups(&state), 3);
3098			assert_eq!(state.offset, 0);
3099		}
3100	}
3101
3102	#[tokio::test]
3103	async fn consumer_skips_evicted_groups() {
3104		tokio::time::pause();
3105
3106		let mut producer = track_producer("test", None);
3107		producer.append_group().unwrap(); // seq 0
3108
3109		let mut consumer = producer.subscribe(None);
3110
3111		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3112		producer.append_group().unwrap(); // seq 1
3113
3114		// Group 0 was evicted. Consumer should get group 1.
3115		let group = consumer.assert_group();
3116		assert_eq!(group.sequence, 1);
3117	}
3118
3119	#[tokio::test]
3120	async fn cache_age_controls_eviction() {
3121		tokio::time::pause();
3122
3123		// A shorter cache evicts sooner than the default.
3124		let mut producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(1)));
3125		producer.append_group().unwrap(); // seq 0
3126
3127		// Past the custom budget but well within DEFAULT_LATENCY_MAX.
3128		tokio::time::advance(Duration::from_secs(2)).await;
3129		producer.append_group().unwrap(); // seq 1
3130
3131		// Seq 0 is gone because the publisher only keeps groups for 1s.
3132		let state = producer.state.read();
3133		assert_eq!(live_groups(&state), 1);
3134		assert_eq!(first_live_sequence(&state), 1);
3135	}
3136
3137	#[test]
3138	fn latency_max_clamped_to_cache() {
3139		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3140
3141		// A latency budget beyond the cache is capped in the aggregate; a group can't be
3142		// waited for longer than the publisher keeps it. The subscriber's own preference
3143		// is stored verbatim, so what it asked for stays readable.
3144		let mut subscriber = producer.subscribe(Subscription::default().with_latency_max(Duration::from_secs(10)));
3145		assert_eq!(subscriber.subscription().latency_max, Duration::from_secs(10));
3146		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3147
3148		// A budget within the cache is left alone, and ZERO (skip immediately) stays ZERO.
3149		subscriber
3150			.update(Subscription::default().with_latency_max(Duration::from_millis(500)))
3151			.unwrap();
3152		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_millis(500));
3153
3154		subscriber
3155			.update(Subscription::default().with_latency_max(Duration::ZERO))
3156			.unwrap();
3157		assert_eq!(producer.subscription().unwrap().latency_max, Duration::ZERO);
3158	}
3159
3160	/// Mint a track under an origin whose retention ceiling is `cap`, so the
3161	/// track's own window is clamped down to it on bind.
3162	fn track_producer_capped(name: impl Into<Arc<str>>, info: Info, cap: Duration) -> Producer {
3163		let origin = crate::origin::Info::default().with_cache_duration(cap);
3164		Producer::new(Arc::new(broadcast::Info { origin }), name, info)
3165	}
3166
3167	#[test]
3168	fn origin_cache_duration_clamps_latency_max() {
3169		// A publisher asking to keep groups for a minute is capped to the origin's 1s
3170		// ceiling; a publisher already below the ceiling is left alone (it's a min).
3171		let capped = track_producer_capped(
3172			"test",
3173			Info::default().with_latency_max(Duration::from_secs(60)),
3174			Duration::from_secs(1),
3175		);
3176		assert_eq!(capped.state.read().latency_bound(), Some(Duration::from_secs(1)));
3177
3178		let under = track_producer_capped(
3179			"test",
3180			Info::default().with_latency_max(Duration::from_millis(500)),
3181			Duration::from_secs(1),
3182		);
3183		assert_eq!(under.state.read().latency_bound(), Some(Duration::from_millis(500)));
3184	}
3185
3186	#[tokio::test]
3187	async fn origin_cache_duration_caps_eviction() {
3188		tokio::time::pause();
3189
3190		// The publisher wants a 60s window, but the origin caps retention at 1s.
3191		let mut producer = track_producer_capped(
3192			"test",
3193			Info::default().with_latency_max(Duration::from_secs(60)),
3194			Duration::from_secs(1),
3195		);
3196		producer.append_group().unwrap(); // seq 0
3197
3198		// Past the origin ceiling but far within the publisher's own 60s window.
3199		tokio::time::advance(Duration::from_secs(2)).await;
3200		producer.append_group().unwrap(); // seq 1
3201
3202		// Seq 0 is evicted anyway: the origin ceiling wins over the larger publisher window.
3203		let state = producer.state.read();
3204		assert_eq!(live_groups(&state), 1);
3205		assert_eq!(first_live_sequence(&state), 1);
3206	}
3207
3208	#[test]
3209	fn latency_max_clamped_via_every_update_path() {
3210		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3211		let over = Subscription::default().with_latency_max(Duration::from_secs(10));
3212
3213		// The clamp lives in the aggregation, so it applies no matter which entry point
3214		// wrote the raw preference. Previously only `Subscriber::update` clamped.
3215		let mut subscriber = producer.subscribe(over.clone());
3216		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3217
3218		subscriber.control().update(over.clone()).unwrap();
3219		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3220
3221		subscriber.update(over).unwrap();
3222		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3223	}
3224
3225	#[test]
3226	fn latency_max_aggregate_clamps_the_max_across_subscribers() {
3227		let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2)));
3228
3229		// The aggregate takes the max, then clamps once. Equivalent to clamping each
3230		// subscriber first, since `min` distributes over `max`.
3231		let _a = producer.subscribe(Subscription::default().with_latency_max(Duration::from_millis(500)));
3232		let _b = producer.subscribe(Subscription::default().with_latency_max(Duration::from_secs(10)));
3233
3234		assert_eq!(producer.subscription().unwrap().latency_max, Duration::from_secs(2));
3235	}
3236
3237	#[test]
3238	fn subscriber_control_updates_while_read_future_is_pending() {
3239		let producer = track_producer("test", None);
3240		let mut subscriber = producer.subscribe(None);
3241		let control = subscriber.control();
3242
3243		let mut recv = Box::pin(subscriber.recv_group());
3244		assert!(recv.as_mut().now_or_never().is_none());
3245
3246		control
3247			.update(Subscription::default().with_priority(7).with_ordered(false))
3248			.unwrap();
3249
3250		let aggregate = producer.subscription().expect("expected an active subscription");
3251		assert_eq!(aggregate.priority, 7);
3252		assert!(!aggregate.ordered);
3253	}
3254
3255	#[test]
3256	fn dropped_subscriber_leaves_no_ghost_in_aggregate() {
3257		// Regression (#2351): a departed subscriber must not keep contributing its
3258		// last subscription to the aggregate. When it did, a relay's linger loop
3259		// never observed the track going idle, and an identical viewer reconnecting
3260		// within the linger window was reset when the stale timer fired.
3261		let mut producer = track_producer("test", None);
3262		let a = producer.subscribe(Subscription::default().with_priority(5));
3263
3264		// Prime the change cursor: the aggregate currently has one subscriber.
3265		let waiter = kio::Waiter::noop();
3266		assert!(
3267			matches!(producer.poll_subscription_changed(&waiter), Poll::Ready(Ok(Some(_)))),
3268			"one live subscriber should aggregate to Some",
3269		);
3270
3271		// The only subscriber leaves.
3272		drop(a);
3273
3274		// The aggregate must report the drop to None, not the ghost's last value.
3275		assert!(
3276			matches!(producer.poll_subscription_changed(&waiter), Poll::Ready(Ok(None))),
3277			"a dropped subscriber must not linger in the aggregate",
3278		);
3279
3280		// And the snapshot used by the linger loop must agree.
3281		assert!(
3282			producer.subscription().is_none(),
3283			"snapshot must exclude a dropped subscriber",
3284		);
3285	}
3286
3287	#[test]
3288	fn dropped_subscriber_wakes_the_aggregate() {
3289		// The value being right isn't enough: nothing re-polls the aggregate on its
3290		// own, so the drop has to wake the waiter. A subscriber contributing demand
3291		// takes `kio::Consumer::poll`'s Ready path, which registers no waiter, so
3292		// the departure needs the closed waiter armed explicitly. Without it a relay
3293		// never learns the last viewer left and holds the upstream subscription (and
3294		// the upstream's viewer count) open forever.
3295		use std::sync::atomic::{AtomicBool, Ordering};
3296
3297		let mut producer = track_producer("test", None);
3298		let a = producer.subscribe(Subscription::default().with_priority(5));
3299
3300		let woken = Arc::new(AtomicBool::new(false));
3301		let waiter = kio::Waiter::new(futures::task::waker(Arc::new(FlagWake(woken.clone()))));
3302
3303		// Prime the cursor, then confirm the next poll parks.
3304		assert!(matches!(
3305			producer.poll_subscription_changed(&waiter),
3306			Poll::Ready(Ok(Some(_)))
3307		));
3308		assert!(
3309			producer.poll_subscription_changed(&waiter).is_pending(),
3310			"the aggregate is unchanged, so this poll must park",
3311		);
3312		assert!(!woken.load(Ordering::SeqCst), "nothing happened yet");
3313
3314		drop(a);
3315		assert!(
3316			woken.load(Ordering::SeqCst),
3317			"the last subscriber leaving must wake the aggregate watcher",
3318		);
3319	}
3320
3321	/// An [`ArcWake`] that just records that it was woken.
3322	struct FlagWake(Arc<std::sync::atomic::AtomicBool>);
3323
3324	impl futures::task::ArcWake for FlagWake {
3325		fn wake_by_ref(arc_self: &Arc<Self>) {
3326			arc_self.0.store(true, std::sync::atomic::Ordering::SeqCst);
3327		}
3328	}
3329
3330	#[tokio::test]
3331	async fn out_of_order_max_sequence_at_front() {
3332		tokio::time::pause();
3333
3334		let mut producer = track_producer("test", None);
3335
3336		// Arrive out of order: seq 5 first, then 3, then 4.
3337		producer.create_group(group::Info { sequence: 5 }).unwrap();
3338		producer.create_group(group::Info { sequence: 3 }).unwrap();
3339		producer.create_group(group::Info { sequence: 4 }).unwrap();
3340
3341		// max_sequence = 5, which is at the front of the VecDeque.
3342		{
3343			let state = producer.state.read();
3344			assert_eq!(state.max_sequence, Some(5));
3345		}
3346
3347		// Expire all three groups.
3348		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3349
3350		// Append seq 6 (becomes new max_sequence).
3351		producer.append_group().unwrap(); // seq 6
3352
3353		// Seq 3, 4, 5 are all expired. Seq 5 was the old max_sequence but now 6 is.
3354		// All old groups are evicted.
3355		{
3356			let state = producer.state.read();
3357			assert_eq!(live_groups(&state), 1);
3358			assert_eq!(first_live_sequence(&state), 6);
3359			assert!(!state.lookup.contains_key(&3));
3360			assert!(!state.lookup.contains_key(&4));
3361			assert!(!state.lookup.contains_key(&5));
3362			assert!(state.lookup.contains_key(&6));
3363		}
3364	}
3365
3366	#[tokio::test]
3367	async fn max_sequence_at_front_blocks_trim() {
3368		tokio::time::pause();
3369
3370		let mut producer = track_producer("test", None);
3371
3372		// Arrive: seq 5, then seq 3.
3373		producer.create_group(group::Info { sequence: 5 }).unwrap();
3374
3375		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3376
3377		// Seq 3 arrives late; max_sequence is still 5 (at front).
3378		producer.create_group(group::Info { sequence: 3 }).unwrap();
3379
3380		// Seq 5 is max_sequence (protected). Seq 3 is not expired (just created).
3381		// Nothing should be evicted.
3382		{
3383			let state = producer.state.read();
3384			assert_eq!(live_groups(&state), 2);
3385			assert_eq!(state.offset, 0);
3386		}
3387
3388		// Expire seq 3 as well.
3389		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
3390
3391		// Seq 2 arrives late, triggering eviction.
3392		producer.create_group(group::Info { sequence: 2 }).unwrap();
3393
3394		// Seq 5 is the live edge (protected) and still resolves at the front of
3395		// `arrival`, so nothing is trimmed and the offset stays. Seq 3 expired out of
3396		// `lookup`, leaving a hole its arrival entry no longer resolves; seq 2 is
3397		// fresh and kept.
3398		{
3399			let state = producer.state.read();
3400			assert_eq!(live_groups(&state), 2);
3401			assert_eq!(state.offset, 0);
3402			assert!(state.lookup.contains_key(&5));
3403			assert!(!state.lookup.contains_key(&3));
3404			assert!(state.lookup.contains_key(&2));
3405		}
3406
3407		// Consumer should still be able to read through the hole.
3408		let mut consumer = producer.subscribe(None);
3409		let group = consumer.assert_group();
3410		// consume() starts at index 0; the first arrival entry that still resolves is seq 5.
3411		assert_eq!(group.sequence, 5);
3412	}
3413
3414	#[tokio::test]
3415	async fn abort_clears_cached_groups() {
3416		let mut producer = track_producer("test", None);
3417		producer.append_group().unwrap();
3418		producer.append_group().unwrap();
3419
3420		// A stale consumer that never drains must not pin the cached groups.
3421		let mut consumer = producer.subscribe(None);
3422		assert_eq!(live_groups(&producer.state.read()), 2);
3423
3424		producer.clone().abort(Error::Cancel).unwrap();
3425
3426		{
3427			let state = producer.state.read();
3428			assert!(state.lookup.is_empty(), "cached groups should be dropped on abort");
3429			assert!(state.arrival.is_empty());
3430			assert!(state.evict.is_empty());
3431		}
3432
3433		// The consumer now surfaces the abort error rather than the leftover cache.
3434		let result = consumer.recv_group().now_or_never().expect("should not block");
3435		assert!(matches!(result, Err(Error::Cancel)));
3436	}
3437
3438	#[tokio::test]
3439	async fn drop_unfinished_clears_cached_groups() {
3440		let producer = track_producer("test", None);
3441		let mut writer = producer.clone();
3442		writer.append_group().unwrap();
3443
3444		// A stale consumer keeps the channel (and thus the cache) alive.
3445		let mut consumer = producer.subscribe(None);
3446		assert_eq!(live_groups(&producer.state.read()), 1);
3447
3448		// Drop every producer without finishing: the cache is released.
3449		drop(writer);
3450		drop(producer);
3451
3452		let result = consumer.recv_group().now_or_never().expect("should not block");
3453		assert!(matches!(result, Err(Error::Dropped)));
3454	}
3455
3456	#[tokio::test]
3457	async fn drop_after_abort_does_not_warn() {
3458		// abort() closes the channel after recording `abort`. Drop must treat the
3459		// read-only guard returned by write() as clean or it emits a false WARN.
3460		let warns = count_drop_warnings("track::Producer dropped without finish", || {
3461			let producer = track_producer("test", None);
3462			let keep = producer.clone();
3463			let mut writer = producer.clone();
3464			let mut group = writer.append_group().unwrap();
3465			group.finish().unwrap();
3466			let _consumer = producer.subscribe(None);
3467			writer.abort(Error::Cancel).unwrap();
3468			drop(keep);
3469		});
3470		assert_eq!(warns, 0, "abort-then-drop must not emit unfinished-producer WARN");
3471	}
3472
3473	#[tokio::test]
3474	async fn drop_unfinished_warns() {
3475		let warns = count_drop_warnings("track::Producer dropped without finish", || {
3476			let producer = track_producer("test", None);
3477			let mut writer = producer.clone();
3478			writer.append_group().unwrap();
3479			let _consumer = producer.subscribe(None);
3480			drop(writer);
3481			drop(producer);
3482		});
3483		assert!(warns >= 1, "unfinished drop must emit unfinished-producer WARN");
3484	}
3485
3486	#[tokio::test]
3487	async fn drop_finished_keeps_cached_groups() {
3488		let mut producer = track_producer("test", None);
3489		producer.append_group().unwrap();
3490		producer.finish().unwrap();
3491
3492		let mut consumer = producer.subscribe(None);
3493		drop(producer);
3494
3495		// A cleanly finished track keeps its cache so the consumer can still drain.
3496		assert_eq!(consumer.assert_group().sequence, 0);
3497		let done = consumer.recv_group().now_or_never().expect("should not block").unwrap();
3498		assert!(done.is_none(), "consumer should drain then see clean finish");
3499	}
3500
3501	#[test]
3502	fn append_finish_cannot_be_rewritten() {
3503		let mut producer = track_producer("test", None);
3504
3505		// Finishing an empty track is valid (fin = 0, total groups = 0).
3506		assert!(producer.finish().is_ok());
3507		assert!(producer.finish().is_err());
3508		assert!(producer.append_group().is_err());
3509	}
3510
3511	#[test]
3512	fn finish_after_groups() {
3513		let mut producer = track_producer("test", None);
3514
3515		producer.append_group().unwrap();
3516		assert!(producer.finish().is_ok());
3517		assert!(producer.finish().is_err());
3518		assert!(producer.append_group().is_err());
3519	}
3520
3521	#[test]
3522	fn finish_at_rejects_a_boundary_at_or_below_the_live_edge() {
3523		let mut producer = track_producer("test", None);
3524		producer.create_group(group::Info { sequence: 5 }).unwrap();
3525
3526		// The boundary is exclusive, so it must be strictly above the highest produced
3527		// group. 5 or below would orphan groups that already exist.
3528		assert!(producer.finish_at(4).is_err());
3529		assert!(producer.finish_at(5).is_err());
3530		assert!(producer.finish_at(6).is_ok());
3531
3532		{
3533			let state = producer.state.read();
3534			assert_eq!(state.final_sequence, Some(6));
3535		}
3536
3537		// Re-finishing is rejected, and no group at or above the boundary can be created.
3538		assert!(producer.finish_at(6).is_err());
3539		assert!(producer.create_group(group::Info { sequence: 4 }).is_ok());
3540		assert!(producer.create_group(group::Info { sequence: 6 }).is_err());
3541	}
3542
3543	#[test]
3544	fn final_sequence_reports_the_declared_boundary() {
3545		let mut producer = track_producer("test", None);
3546		assert_eq!(producer.final_sequence(), None);
3547
3548		producer.create_group(group::Info { sequence: 5 }).unwrap();
3549		assert_eq!(producer.final_sequence(), None, "a group does not declare a boundary");
3550
3551		producer.finish_at(9).unwrap();
3552		assert_eq!(producer.final_sequence(), Some(9));
3553
3554		// finish() would try to declare a second boundary, so callers check first.
3555		assert!(producer.finish().is_err());
3556	}
3557
3558	#[test]
3559	fn final_sequence_reports_the_live_edge_after_finish() {
3560		let mut producer = track_producer("test", None);
3561		producer.create_group(group::Info { sequence: 5 }).unwrap();
3562		producer.finish().unwrap();
3563		assert_eq!(producer.final_sequence(), Some(6));
3564	}
3565
3566	#[tokio::test]
3567	async fn finish_at_declares_a_future_boundary() {
3568		let mut producer = track_producer("test", None);
3569		producer.create_group(group::Info { sequence: 5 }).unwrap();
3570
3571		// Learn the track ends at group 6 (exclusive 7) while the live edge is still 5.
3572		producer.finish_at(7).unwrap();
3573
3574		let mut consumer = producer.subscribe(None);
3575		assert_eq!(consumer.assert_group().sequence, 5);
3576
3577		// The boundary is known immediately, but the track isn't done: group 6 is still
3578		// outstanding, so the consumer parks rather than seeing end-of-stream.
3579		let boundary = consumer
3580			.finished()
3581			.now_or_never()
3582			.expect("boundary is known immediately")
3583			.expect("would have errored");
3584		assert_eq!(boundary, 7);
3585		assert!(
3586			consumer.recv_group().now_or_never().is_none(),
3587			"should wait for the outstanding group"
3588		);
3589
3590		// The trailing group arrives (below the boundary), then the track completes.
3591		producer.create_group(group::Info { sequence: 6 }).unwrap();
3592		assert_eq!(consumer.assert_group().sequence, 6);
3593		let done = consumer
3594			.recv_group()
3595			.now_or_never()
3596			.expect("should not block")
3597			.expect("would have errored");
3598		assert!(done.is_none(), "track completes once the boundary is reached");
3599	}
3600
3601	#[tokio::test]
3602	async fn recv_group_finishes_without_waiting_for_gaps() {
3603		let mut producer = track_producer("test", None);
3604		producer.create_group(group::Info { sequence: 1 }).unwrap();
3605		producer.finish().unwrap();
3606
3607		let mut consumer = producer.subscribe(None);
3608		assert_eq!(consumer.assert_group().sequence, 1);
3609
3610		let done = consumer
3611			.recv_group()
3612			.now_or_never()
3613			.expect("should not block")
3614			.expect("would have errored");
3615		assert!(done.is_none(), "track should finish without waiting for gaps");
3616	}
3617
3618	#[tokio::test]
3619	async fn next_group_skips_late_arrivals() {
3620		let mut producer = track_producer("test", None);
3621		let mut consumer = producer.subscribe(None);
3622
3623		// Seq 5 arrives first.
3624		producer.create_group(group::Info { sequence: 5 }).unwrap();
3625		let group = consumer
3626			.next_group()
3627			.now_or_never()
3628			.expect("should not block")
3629			.expect("would have errored")
3630			.expect("track should not be closed");
3631		assert_eq!(group.sequence, 5);
3632
3633		// Seq 3 arrives late, skipped because 3 <= 5.
3634		producer.create_group(group::Info { sequence: 3 }).unwrap();
3635		// Seq 4 arrives late and is also skipped.
3636		producer.create_group(group::Info { sequence: 4 }).unwrap();
3637		// Seq 7 arrives and is returned.
3638		producer.create_group(group::Info { sequence: 7 }).unwrap();
3639
3640		let group = consumer
3641			.next_group()
3642			.now_or_never()
3643			.expect("should not block")
3644			.expect("would have errored")
3645			.expect("track should not be closed");
3646		assert_eq!(group.sequence, 7);
3647
3648		// No more groups. This would block.
3649		assert!(
3650			consumer.next_group().now_or_never().is_none(),
3651			"should block waiting for a higher sequence"
3652		);
3653	}
3654
3655	#[tokio::test]
3656	async fn next_group_returns_arrivals_in_order() {
3657		let mut producer = track_producer("test", None);
3658		let mut consumer = producer.subscribe(None);
3659
3660		// Seq 3 arrives first, then seq 5. Both should be returned in arrival order.
3661		producer.create_group(group::Info { sequence: 3 }).unwrap();
3662		producer.create_group(group::Info { sequence: 5 }).unwrap();
3663
3664		let group = consumer
3665			.next_group()
3666			.now_or_never()
3667			.expect("should not block")
3668			.expect("would have errored")
3669			.expect("track should not be closed");
3670		assert_eq!(group.sequence, 3);
3671
3672		let group = consumer
3673			.next_group()
3674			.now_or_never()
3675			.expect("should not block")
3676			.expect("would have errored")
3677			.expect("track should not be closed");
3678		assert_eq!(group.sequence, 5);
3679	}
3680
3681	#[tokio::test]
3682	async fn next_group_and_recv_group_use_independent_cursors() {
3683		let mut producer = track_producer("test", None);
3684		let mut consumer = producer.subscribe(None);
3685
3686		// Out-of-order arrivals: seq 5 first, then seq 3.
3687		producer.create_group(group::Info { sequence: 5 }).unwrap();
3688		producer.create_group(group::Info { sequence: 3 }).unwrap();
3689
3690		// next_group is sequence-ordered: it returns the smallest sequence first,
3691		// regardless of arrival order.
3692		let group = consumer
3693			.next_group()
3694			.now_or_never()
3695			.expect("should not block")
3696			.expect("would have errored")
3697			.expect("track should not be closed");
3698		assert_eq!(group.sequence, 3);
3699
3700		// recv_group is arrival-ordered and uses an independent cursor, so it
3701		// still starts at the first arrival.
3702		assert_eq!(consumer.assert_group().sequence, 5);
3703	}
3704
3705	#[tokio::test]
3706	async fn end_at_caps_next_group() {
3707		let mut producer = track_producer("test", None);
3708		let mut consumer = producer.subscribe(None);
3709
3710		for s in 0..6 {
3711			producer.create_group(group::Info { sequence: s }).unwrap();
3712		}
3713
3714		consumer.end_at(2);
3715
3716		// Groups 0, 1, 2 are within the cap.
3717		assert_eq!(
3718			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3719			0
3720		);
3721		assert_eq!(
3722			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3723			1
3724		);
3725		assert_eq!(
3726			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3727			2
3728		);
3729
3730		// Group 3 is beyond the cap: next_group parks even though cached groups exist.
3731		assert!(
3732			consumer.next_group().now_or_never().is_none(),
3733			"capped consumer must block instead of returning out-of-range groups"
3734		);
3735	}
3736
3737	#[tokio::test]
3738	async fn end_at_release_drains_cached_groups() {
3739		let mut producer = track_producer("test", None);
3740		let mut consumer = producer.subscribe(None);
3741
3742		for s in 0..6 {
3743			producer.create_group(group::Info { sequence: s }).unwrap();
3744		}
3745
3746		consumer.end_at(1);
3747		assert_eq!(
3748			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3749			0
3750		);
3751		assert_eq!(
3752			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3753			1
3754		);
3755		assert!(consumer.next_group().now_or_never().is_none(), "capped at 1");
3756
3757		// Raise the cap; previously-blocked cached groups become available again.
3758		consumer.end_at(4);
3759		assert_eq!(
3760			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3761			2
3762		);
3763		assert_eq!(
3764			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3765			3
3766		);
3767		assert_eq!(
3768			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3769			4
3770		);
3771		assert!(consumer.next_group().now_or_never().is_none(), "capped at 4");
3772
3773		// Remove the cap; everything remaining flows.
3774		consumer.end_at(None);
3775		assert_eq!(
3776			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3777			5
3778		);
3779		assert!(consumer.next_group().now_or_never().is_none(), "no more groups");
3780	}
3781
3782	#[tokio::test]
3783	async fn end_at_lower_than_cursor_parks_consumer() {
3784		let mut producer = track_producer("test", None);
3785		let mut consumer = producer.subscribe(None);
3786
3787		for s in 0..3 {
3788			producer.create_group(group::Info { sequence: s }).unwrap();
3789		}
3790
3791		// Drain everything with no cap.
3792		assert_eq!(
3793			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3794			0
3795		);
3796		assert_eq!(
3797			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3798			1
3799		);
3800		assert_eq!(
3801			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3802			2
3803		);
3804
3805		// Lower the cap below the cursor. New groups beyond the cap are blocked.
3806		consumer.end_at(1);
3807		producer.create_group(group::Info { sequence: 3 }).unwrap();
3808		producer.create_group(group::Info { sequence: 4 }).unwrap();
3809		assert!(
3810			consumer.next_group().now_or_never().is_none(),
3811			"cap is below cursor; nothing returnable until cap rises"
3812		);
3813
3814		// Restoring the cap to no-limit (or any value >= cursor) releases them.
3815		consumer.end_at(None);
3816		assert_eq!(
3817			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3818			3
3819		);
3820		assert_eq!(
3821			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3822			4
3823		);
3824	}
3825
3826	#[tokio::test]
3827	async fn end_at_toggling_around_late_arrivals() {
3828		let mut producer = track_producer("test", None);
3829		let mut consumer = producer.subscribe(None);
3830
3831		consumer.end_at(5);
3832
3833		// Out-of-order arrivals all within the cap.
3834		producer.create_group(group::Info { sequence: 2 }).unwrap();
3835		producer.create_group(group::Info { sequence: 5 }).unwrap();
3836		producer.create_group(group::Info { sequence: 3 }).unwrap();
3837		// One beyond the cap; should be held even though it arrived in the middle.
3838		producer.create_group(group::Info { sequence: 8 }).unwrap();
3839		producer.create_group(group::Info { sequence: 4 }).unwrap();
3840
3841		// next_group walks in sequence order through everything <= cap.
3842		assert_eq!(
3843			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3844			2
3845		);
3846		assert_eq!(
3847			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3848			3
3849		);
3850		assert_eq!(
3851			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3852			4
3853		);
3854		assert_eq!(
3855			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3856			5
3857		);
3858		// Now blocked: 8 is still beyond the cap.
3859		assert!(consumer.next_group().now_or_never().is_none());
3860
3861		// Raise the cap; cached seq 8 is finally served.
3862		consumer.end_at(10);
3863		assert_eq!(
3864			consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3865			8
3866		);
3867	}
3868
3869	/// `recv_group` (arrival order) honors the `end_at` cap by parking, like
3870	/// `next_group`: beyond-cap groups are held, not dropped, and a raised cap
3871	/// re-offers them, even after the track finishes.
3872	#[tokio::test]
3873	async fn end_at_parks_recv_group() {
3874		let mut producer = track_producer("test", None);
3875		let mut consumer = producer.subscribe(None);
3876
3877		for s in 0..3 {
3878			producer.create_group(group::Info { sequence: s }).unwrap();
3879		}
3880
3881		consumer.end_at(1);
3882		assert_eq!(
3883			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3884			0
3885		);
3886		assert_eq!(
3887			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3888			1
3889		);
3890		assert!(consumer.recv_group().now_or_never().is_none(), "capped at 1");
3891
3892		// A finished track keeps the parked group claimable: the cap may rise.
3893		producer.finish().unwrap();
3894		assert!(
3895			consumer.recv_group().now_or_never().is_none(),
3896			"still parked after finish"
3897		);
3898
3899		consumer.end_at(None);
3900		assert_eq!(
3901			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3902			2
3903		);
3904		assert!(
3905			matches!(consumer.recv_group().now_or_never(), Some(Ok(None))),
3906			"finished once the parked group drains"
3907		);
3908	}
3909
3910	/// A group beyond the cap must not block in-range groups that arrive behind
3911	/// it: a relay can ingest a burst micro-reordered (newest first).
3912	#[tokio::test]
3913	async fn recv_group_serves_arrivals_behind_the_cap() {
3914		let mut producer = track_producer("test", None);
3915		let mut consumer = producer.subscribe(None);
3916
3917		consumer.end_at(1);
3918
3919		// Reordered burst: the beyond-cap group arrives first.
3920		producer.create_group(group::Info { sequence: 2 }).unwrap();
3921		producer.create_group(group::Info { sequence: 0 }).unwrap();
3922		producer.create_group(group::Info { sequence: 1 }).unwrap();
3923
3924		assert_eq!(
3925			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3926			0
3927		);
3928		assert_eq!(
3929			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3930			1
3931		);
3932		assert!(consumer.recv_group().now_or_never().is_none(), "capped at 1");
3933
3934		consumer.end_at(2);
3935		assert_eq!(
3936			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3937			2
3938		);
3939	}
3940
3941	/// A raised `start_at` drops parked groups it overtook instead of re-offering
3942	/// them once the cap rises.
3943	#[tokio::test]
3944	async fn start_at_drops_parked_recv_groups() {
3945		let mut producer = track_producer("test", None);
3946		let mut consumer = producer.subscribe(None);
3947
3948		consumer.end_at(0);
3949		producer.create_group(group::Info { sequence: 1 }).unwrap();
3950		assert!(
3951			consumer.recv_group().now_or_never().is_none(),
3952			"group 1 parked at the cap"
3953		);
3954
3955		consumer.start_at(2);
3956		consumer.end_at(None);
3957		producer.create_group(group::Info { sequence: 2 }).unwrap();
3958		assert_eq!(
3959			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3960			2,
3961			"the overtaken parked group is dropped, not re-offered"
3962		);
3963	}
3964
3965	/// A parked group the producer aborts (eviction/expiry) is dropped: it is
3966	/// neither delivered once the cap rises nor allowed to hold the stream open
3967	/// after the track finishes. This is what bounds parking by the cache policy.
3968	#[tokio::test]
3969	async fn evicted_parked_recv_groups_are_dropped() {
3970		let mut producer = track_producer("test", None);
3971		let mut consumer = producer.subscribe(None);
3972
3973		producer.create_group(group::Info { sequence: 0 }).unwrap();
3974		assert_eq!(
3975			consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().sequence,
3976			0
3977		);
3978
3979		consumer.end_at(0);
3980		let straggler = producer.create_group(group::Info { sequence: 1 }).unwrap();
3981		assert!(
3982			consumer.recv_group().now_or_never().is_none(),
3983			"group 1 parked at the cap"
3984		);
3985
3986		// The cache evicts the parked group (abort-as-tombstone), then the track ends.
3987		straggler.abort(Error::Old).unwrap();
3988		producer.finish().unwrap();
3989
3990		consumer.end_at(None);
3991		assert!(
3992			matches!(consumer.recv_group().now_or_never(), Some(Ok(None))),
3993			"a dead parked group must not be delivered or hold the stream open"
3994		);
3995	}
3996
3997	#[tokio::test]
3998	async fn read_frame_returns_single_frame_per_group() {
3999		let mut producer = track_producer("test", None);
4000		let mut consumer = producer.subscribe(None);
4001
4002		producer.write_frame(Timestamp::ZERO, b"hello".as_slice()).unwrap();
4003		producer.write_frame(Timestamp::ZERO, b"world".as_slice()).unwrap();
4004
4005		let frame = consumer
4006			.read_frame()
4007			.now_or_never()
4008			.expect("should not block")
4009			.expect("would have errored")
4010			.expect("track should not be closed");
4011		assert_eq!(&frame.payload[..], b"hello");
4012
4013		let frame = consumer
4014			.read_frame()
4015			.now_or_never()
4016			.expect("should not block")
4017			.expect("would have errored")
4018			.expect("track should not be closed");
4019		assert_eq!(&frame.payload[..], b"world");
4020	}
4021
4022	#[tokio::test]
4023	async fn read_frame_preserves_timestamp() {
4024		let mut producer = track_producer("test", None);
4025		let mut consumer = producer.subscribe(None);
4026
4027		producer
4028			.write_frame(Timestamp::from_micros(20_000).unwrap(), b"hello".as_slice())
4029			.unwrap();
4030
4031		let frame = consumer
4032			.read_frame()
4033			.now_or_never()
4034			.expect("should not block")
4035			.expect("would have errored")
4036			.expect("track should not be closed");
4037		assert_eq!(frame.timestamp.as_micros(), 20_000);
4038		assert_eq!(&frame.payload[..], b"hello");
4039	}
4040
4041	#[tokio::test]
4042	async fn read_frame_skips_stalled_group_for_newer_ready_frame() {
4043		let mut producer = track_producer("test", None);
4044		let mut consumer = producer.subscribe(None);
4045
4046		// Seq 3: group open, no frame yet (stalled).
4047		let _stalled = producer.create_group(group::Info { sequence: 3 }).unwrap();
4048		// Seq 5: fully-written group with a frame.
4049		let mut g5 = producer.create_group(group::Info { sequence: 5 }).unwrap();
4050		g5.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"later"))
4051			.unwrap();
4052		g5.finish().unwrap();
4053
4054		// read_frame should not block on the stalled seq 3. It returns seq 5's frame.
4055		let frame = consumer
4056			.read_frame()
4057			.now_or_never()
4058			.expect("should not block on stalled earlier group")
4059			.expect("would have errored")
4060			.expect("track should not be closed");
4061		assert_eq!(&frame.payload[..], b"later");
4062	}
4063
4064	#[tokio::test]
4065	async fn read_frame_discards_rest_of_multi_frame_group() {
4066		let mut producer = track_producer("test", None);
4067		let mut consumer = producer.subscribe(None);
4068
4069		// Group 0 has two frames; only the first is returned.
4070		let mut g0 = producer.create_group(group::Info { sequence: 0 }).unwrap();
4071		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"one"))
4072			.unwrap();
4073		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"two"))
4074			.unwrap();
4075		g0.finish().unwrap();
4076
4077		// Group 1 is a normal single-frame group.
4078		producer.write_frame(Timestamp::ZERO, b"next".as_slice()).unwrap();
4079
4080		let frame = consumer
4081			.read_frame()
4082			.now_or_never()
4083			.expect("should not block")
4084			.expect("would have errored")
4085			.expect("track should not be closed");
4086		assert_eq!(&frame.payload[..], b"one");
4087
4088		// The second frame of group 0 is discarded; the next read jumps to group 1.
4089		let frame = consumer
4090			.read_frame()
4091			.now_or_never()
4092			.expect("should not block")
4093			.expect("would have errored")
4094			.expect("track should not be closed");
4095		assert_eq!(&frame.payload[..], b"next");
4096	}
4097
4098	#[tokio::test]
4099	async fn read_frame_waits_for_pending_group_after_finish() {
4100		// finish() sets final_sequence, but groups already created with lower sequences
4101		// can still produce frames. read_frame must not return None prematurely.
4102		let mut producer = track_producer("test", None);
4103		let mut consumer = producer.subscribe(None);
4104
4105		let mut g0 = producer.create_group(group::Info { sequence: 0 }).unwrap();
4106		producer.finish().unwrap();
4107
4108		// Track is finished but group 0 has no frame yet. It must block, not return None.
4109		assert!(
4110			consumer.read_frame().now_or_never().is_none(),
4111			"read_frame must block on a pending group even after finish()"
4112		);
4113
4114		// A late frame on the pending group is still delivered.
4115		g0.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"late"))
4116			.unwrap();
4117		let frame = consumer
4118			.read_frame()
4119			.now_or_never()
4120			.expect("should not block once a frame is written")
4121			.expect("would have errored")
4122			.expect("track should not be closed");
4123		assert_eq!(&frame.payload[..], b"late");
4124	}
4125
4126	#[tokio::test]
4127	async fn read_frame_respects_start_at() {
4128		// start_at sets min_sequence; read_frame must skip groups below it even though
4129		// next_sequence is still 0.
4130		let mut producer = track_producer("test", None);
4131		let mut consumer = producer.subscribe(None);
4132		consumer.start_at(5);
4133
4134		// Seq 3 has a frame but is below min_sequence, so it must be skipped.
4135		let mut g3 = producer.create_group(group::Info { sequence: 3 }).unwrap();
4136		g3.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"skip-me"))
4137			.unwrap();
4138		g3.finish().unwrap();
4139
4140		let mut g5 = producer.create_group(group::Info { sequence: 5 }).unwrap();
4141		g5.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"keep"))
4142			.unwrap();
4143		g5.finish().unwrap();
4144
4145		let frame = consumer
4146			.read_frame()
4147			.now_or_never()
4148			.expect("should not block")
4149			.expect("would have errored")
4150			.expect("track should not be closed");
4151		assert_eq!(&frame.payload[..], b"keep");
4152	}
4153
4154	#[tokio::test]
4155	async fn read_frame_returns_none_when_finished() {
4156		let mut producer = track_producer("test", None);
4157		let mut consumer = producer.subscribe(None);
4158
4159		producer.write_frame(Timestamp::ZERO, b"only".as_slice()).unwrap();
4160		producer.finish().unwrap();
4161
4162		let frame = consumer
4163			.read_frame()
4164			.now_or_never()
4165			.expect("should not block")
4166			.expect("would have errored")
4167			.expect("track should not be closed");
4168		assert_eq!(&frame.payload[..], b"only");
4169
4170		let done = consumer
4171			.read_frame()
4172			.now_or_never()
4173			.expect("should not block")
4174			.expect("would have errored");
4175		assert!(done.is_none());
4176	}
4177
4178	#[test]
4179	fn append_group_returns_bounds_exceeded_on_sequence_overflow() {
4180		let mut producer = track_producer("test", None);
4181		{
4182			let mut state = producer.state.write().ok().unwrap();
4183			state.max_sequence = Some(u64::MAX);
4184		}
4185
4186		assert!(matches!(producer.append_group(), Err(Error::BoundsExceeded(_))));
4187	}
4188
4189	#[tokio::test]
4190	async fn fetch_cache_hit() {
4191		let mut producer = track_producer("test", None);
4192
4193		// Produce a cached group.
4194		let mut group = producer.append_group().unwrap(); // seq 0
4195		group
4196			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hello"))
4197			.unwrap();
4198		group.finish().unwrap();
4199
4200		// A cached group resolves immediately and never queues a request. `peek_group`
4201		// also returns it synchronously.
4202		let dynamic = producer.dynamic();
4203		let consumer = producer.consume();
4204		assert!(consumer.peek_group(0).is_some());
4205		let mut g = consumer.fetch_group(0, None).await.unwrap();
4206		assert_eq!(g.sequence, 0);
4207		assert_eq!(&g.read_frame().await.unwrap().unwrap().payload[..], b"hello");
4208
4209		// Nothing was queued for the dynamic handler to serve.
4210		assert!(dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending());
4211	}
4212
4213	#[tokio::test]
4214	async fn fetch_miss_signals_dynamic() {
4215		let producer = track_producer("test", None);
4216		let dynamic = producer.dynamic();
4217		let consumer = producer.consume();
4218
4219		// A cache miss isn't in `peek_group`, but a dynamic handler exists, so
4220		// `fetch_group` stays pending and queues a request. `*pending` derefs the
4221		// wrapper to the inner `Fetching` (a `kio::Pollable`).
4222		assert!(consumer.peek_group(5).is_none());
4223		let pending = consumer.fetch_group(5, group::Fetch::default().with_priority(7));
4224		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
4225
4226		let req = dynamic
4227			.requested_group()
4228			.now_or_never()
4229			.expect("should not block")
4230			.unwrap();
4231		assert_eq!(req.sequence(), 5);
4232		assert_eq!(req.priority(), 7);
4233
4234		// Serve it by accepting the request; the fetch then resolves.
4235		let mut group = req.accept(None).unwrap();
4236		group
4237			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hi"))
4238			.unwrap();
4239		group.finish().unwrap();
4240
4241		let mut g = pending.await.unwrap();
4242		assert_eq!(g.sequence, 5);
4243		assert_eq!(&g.read_frame().await.unwrap().unwrap().payload[..], b"hi");
4244	}
4245
4246	#[tokio::test]
4247	async fn fetch_miss_rejects() {
4248		let producer = track_producer("test", None);
4249		let dynamic = producer.dynamic();
4250		let consumer = producer.consume();
4251
4252		let pending = consumer.fetch_group(5, None);
4253		let req = dynamic
4254			.requested_group()
4255			.now_or_never()
4256			.expect("should not block")
4257			.unwrap();
4258
4259		req.reject(Error::Cancel);
4260		assert!(matches!(pending.await, Err(Error::Cancel)));
4261		let fetch = producer.state.read().fetch.clone();
4262		assert!(fetch.read().is_empty());
4263	}
4264
4265	#[tokio::test]
4266	async fn fetch_miss_drop_rejects() {
4267		let producer = track_producer("test", None);
4268		let dynamic = producer.dynamic();
4269		let consumer = producer.consume();
4270
4271		let pending = consumer.fetch_group(5, None);
4272		let req = dynamic
4273			.requested_group()
4274			.now_or_never()
4275			.expect("should not block")
4276			.unwrap();
4277
4278		drop(req);
4279		assert!(matches!(pending.await, Err(Error::Dropped)));
4280	}
4281
4282	#[tokio::test]
4283	async fn fetch_reject_does_not_poison_retry() {
4284		let producer = track_producer("test", None);
4285		let dynamic = producer.dynamic();
4286		let consumer = producer.consume();
4287
4288		let pending = consumer.fetch_group(5, None);
4289		let req = dynamic
4290			.requested_group()
4291			.now_or_never()
4292			.expect("should not block")
4293			.unwrap();
4294		req.reject(Error::Cancel);
4295		assert!(matches!(pending.await, Err(Error::Cancel)));
4296
4297		let retry = consumer.fetch_group(5, None);
4298		let req = dynamic
4299			.requested_group()
4300			.now_or_never()
4301			.expect("should not block")
4302			.unwrap();
4303		let mut group = req.accept(None).unwrap();
4304		group
4305			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"retry"))
4306			.unwrap();
4307		group.finish().unwrap();
4308
4309		let mut group = retry.await.unwrap();
4310		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"retry");
4311	}
4312
4313	#[tokio::test]
4314	async fn fetch_coalesces_concurrent() {
4315		let producer = track_producer("test", None);
4316		let dynamic = producer.dynamic();
4317		let consumer = producer.consume();
4318
4319		// Two fetches for the same uncached group produce ONE handler request,
4320		// carrying the higher of the two priorities.
4321		let first = consumer.fetch_group(5, group::Fetch::default().with_priority(1));
4322		let second = consumer.fetch_group(5, group::Fetch::default().with_priority(7));
4323		assert!(kio::Pollable::poll(&*first, &kio::Waiter::noop()).is_pending());
4324
4325		let req = dynamic
4326			.requested_group()
4327			.now_or_never()
4328			.expect("should not block")
4329			.unwrap();
4330		assert_eq!(req.sequence(), 5);
4331		assert_eq!(req.priority(), 7);
4332		assert!(
4333			dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending(),
4334			"the second fetch queued a duplicate request"
4335		);
4336
4337		// A fetch arriving while the request is already in flight joins it too.
4338		let third = consumer.fetch_group(5, None);
4339
4340		// One accept resolves all of them.
4341		let mut group = req.accept(None).unwrap();
4342		group
4343			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"hi"))
4344			.unwrap();
4345		group.finish().unwrap();
4346
4347		assert_eq!(first.await.unwrap().sequence, 5);
4348		assert_eq!(second.await.unwrap().sequence, 5);
4349		assert_eq!(third.await.unwrap().sequence, 5);
4350	}
4351
4352	#[tokio::test]
4353	async fn fetch_coalesced_reject_fails_all() {
4354		let producer = track_producer("test", None);
4355		let dynamic = producer.dynamic();
4356		let consumer = producer.consume();
4357
4358		let first = consumer.fetch_group(5, None);
4359		let second = consumer.fetch_group(5, None);
4360		let req = dynamic
4361			.requested_group()
4362			.now_or_never()
4363			.expect("should not block")
4364			.unwrap();
4365		req.reject(Error::Cancel);
4366
4367		assert!(matches!(first.await, Err(Error::Cancel)));
4368		assert!(matches!(second.await, Err(Error::Cancel)));
4369
4370		// The rejected attempt is gone: a retry starts a fresh one.
4371		let retry = consumer.fetch_group(5, None);
4372		assert!(kio::Pollable::poll(&*retry, &kio::Waiter::noop()).is_pending());
4373		let req = dynamic
4374			.requested_group()
4375			.now_or_never()
4376			.expect("should not block")
4377			.unwrap();
4378		assert_eq!(req.sequence(), 5);
4379	}
4380
4381	#[tokio::test]
4382	async fn fetch_queued_fails_when_handlers_leave() {
4383		let producer = track_producer("test", None);
4384		let dynamic = producer.dynamic();
4385		let consumer = producer.consume();
4386
4387		// Queued but never popped: the last handler leaving fails it fast.
4388		let pending = consumer.fetch_group(5, None);
4389		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
4390		drop(dynamic);
4391		assert!(matches!(pending.await, Err(Error::NotFound)));
4392
4393		// And the attempt didn't leak.
4394		let fetch = producer.state.read().fetch.clone();
4395		assert!(fetch.read().is_empty());
4396	}
4397
4398	#[tokio::test]
4399	async fn fetch_miss_no_dynamic_not_found() {
4400		// A track with no `Dynamic` can't serve old content, so a cache miss
4401		// resolves to NotFound instead of blocking forever.
4402		let mut producer = track_producer("test", None);
4403		producer.append_group().unwrap(); // seq 0, but we miss on seq 5
4404		let consumer = producer.consume();
4405		assert!(matches!(consumer.fetch_group(5, None).await, Err(Error::NotFound)));
4406	}
4407
4408	#[tokio::test]
4409	async fn fetch_past_final_not_found() {
4410		let mut producer = track_producer("test", None);
4411		producer.append_group().unwrap(); // seq 0
4412		producer.finish().unwrap(); // final_sequence = 1
4413
4414		// A group at or past the final sequence can never exist, even with a handler,
4415		// so it resolves to NotFound.
4416		let dynamic = producer.dynamic();
4417		let consumer = producer.consume();
4418		assert!(matches!(consumer.fetch_group(5, None).await, Err(Error::NotFound)));
4419
4420		// And it doesn't signal the dynamic handler.
4421		assert!(dynamic.poll_requested_group(&kio::Waiter::noop()).is_pending());
4422	}
4423
4424	/// Mint a track whose groups charge into a bounded [`cache::Pool`].
4425	fn pooled_producer(capacity: u64) -> (Producer, cache::Pool) {
4426		let pool = cache::Pool::new(capacity);
4427		let broadcast = broadcast::Info {
4428			origin: crate::origin::Info::default().with_pool(pool.clone()),
4429			..Default::default()
4430		};
4431		let producer = Producer::new(Arc::new(broadcast), "test", None);
4432		(producer, pool)
4433	}
4434
4435	fn finished_group(producer: &mut Producer, size: usize) -> u64 {
4436		let mut group = producer.append_group().unwrap();
4437		group
4438			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; size]))
4439			.unwrap();
4440		group.finish().unwrap();
4441		group.sequence
4442	}
4443
4444	/// While the pool is over capacity, every append accrues debt and pays it by
4445	/// evicting this track's own oldest groups, so the newest content survives.
4446	#[tokio::test]
4447	async fn debt_evicts_oldest_group() {
4448		tokio::time::pause();
4449
4450		// Fits one 10k group; each additional group pushes the pool over budget.
4451		let (mut producer, pool) = pooled_producer(10_000);
4452
4453		finished_group(&mut producer, 10_000); // seq 0
4454		finished_group(&mut producer, 10_000); // seq 1: over budget, debt starts accruing
4455		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4456
4457		let consumer = producer.consume();
4458		assert!(consumer.peek_group(0).is_none(), "oldest group is evicted");
4459		assert!(consumer.peek_group(2).is_some(), "latest group survives");
4460		// Steady state carries the protected live edge plus the just-demoted group
4461		// (debt is charged before the demotion, so eviction lags one append).
4462		assert!(pool.used() <= 21_000, "usage hovers near capacity: {}", pool.used());
4463
4464		// A fresh subscriber skips the evicted groups entirely.
4465		let mut subscriber = producer.subscribe(None);
4466		assert!(subscriber.assert_group().sequence > 0, "evicted group is not delivered");
4467	}
4468
4469	/// The latest group is never in the eviction order, so it survives any budget.
4470	#[tokio::test]
4471	async fn latest_group_never_evicted() {
4472		tokio::time::pause();
4473
4474		// Far too small for even one group: the latest survives anyway.
4475		let (mut producer, pool) = pooled_producer(100);
4476		finished_group(&mut producer, 1000); // seq 0
4477		assert!(pool.used() > 100, "the latest may exceed the budget");
4478
4479		// Later writes evict the demoted seq 0; each new latest is untouchable in turn.
4480		finished_group(&mut producer, 1000); // seq 1: demotes seq 0
4481		finished_group(&mut producer, 1000); // seq 2: pays by evicting seq 0
4482
4483		let consumer = producer.consume();
4484		assert!(consumer.peek_group(0).is_none());
4485		let mut group = consumer.peek_group(2).expect("latest survives");
4486		assert_eq!(group.read_frame().await.unwrap().unwrap().payload.len(), 1000);
4487	}
4488
4489	/// A FETCH cache hit refreshes the group's access time: anything accessed more
4490	/// recently than the pool-wide average is protected, so the eviction walk skips
4491	/// it and evicts a never-read group instead, even one that arrived later.
4492	#[tokio::test]
4493	async fn fetch_refresh_survives_eviction() {
4494		tokio::time::pause();
4495
4496		let (mut producer, _pool) = pooled_producer(10_000);
4497		let consumer = producer.consume();
4498
4499		finished_group(&mut producer, 3_000); // seq 0
4500		tokio::time::advance(Duration::from_secs(1)).await;
4501		finished_group(&mut producer, 3_000); // seq 1
4502		tokio::time::advance(Duration::from_secs(1)).await;
4503		finished_group(&mut producer, 3_000); // seq 2
4504		tokio::time::advance(Duration::from_millis(500)).await;
4505
4506		// FETCH seq 0: the cache hit lifts its access time above the average.
4507		let mut fetched = consumer.fetch_group(0, None).await.unwrap();
4508		assert_eq!(fetched.read_frame().await.unwrap().unwrap().payload.len(), 3_000);
4509		tokio::time::advance(Duration::from_millis(500)).await;
4510
4511		// Pressure: seq 0 is first in eviction order but freshly accessed, so it
4512		// rotates to the back and the never-read seq 1 dies instead.
4513		finished_group(&mut producer, 3_000); // seq 3
4514		tokio::time::advance(Duration::from_secs(1)).await;
4515		finished_group(&mut producer, 3_000); // seq 4
4516
4517		assert!(consumer.peek_group(0).is_some(), "refreshed group survives");
4518		assert!(consumer.peek_group(1).is_none(), "unread group is evicted instead");
4519	}
4520
4521	/// A consumer holding an evicted group surfaces the eviction, not a hang or a
4522	/// truncated clean end.
4523	#[tokio::test]
4524	async fn eviction_aborts_readers() {
4525		tokio::time::pause();
4526
4527		let (mut producer, _pool) = pooled_producer(10_000);
4528		let mut subscriber = producer.subscribe(None);
4529
4530		finished_group(&mut producer, 10_000); // seq 0
4531		let mut group0 = subscriber.assert_group();
4532
4533		finished_group(&mut producer, 10_000); // seq 1: demotes seq 0
4534		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
4535
4536		let read = group0.read_frame().await;
4537		assert!(matches!(read, Err(Error::Evicted)), "expected Evicted, got {read:?}");
4538	}
4539
4540	/// A write smaller than the next victim carries debt instead of evicting: a
4541	/// large group dies only once enough debt accumulates, never to pay off a
4542	/// far smaller write.
4543	#[tokio::test]
4544	async fn small_writes_carry_debt() {
4545		tokio::time::pause();
4546
4547		let (mut producer, pool) = pooled_producer(22_000);
4548		let consumer = producer.consume();
4549
4550		finished_group(&mut producer, 20_000); // seq 0, the large victim-to-be
4551
4552		// The first few small writes owe far less than seq 0's size: the debt
4553		// carries over instead of evicting it.
4554		for _ in 0..3 {
4555			finished_group(&mut producer, 1_000);
4556		}
4557		assert!(consumer.peek_group(0).is_some(), "debt smaller than the victim carries");
4558
4559		// Enough small writes accumulate the debt to finally evict it.
4560		for _ in 0..20 {
4561			finished_group(&mut producer, 1_000);
4562		}
4563		assert!(
4564			consumer.peek_group(0).is_none(),
4565			"accumulated debt evicts the large group"
4566		);
4567		// Steady state hovers within about one group of capacity: a victim smaller
4568		// than the outstanding debt is never evicted, so the excess stays bounded.
4569		assert!(pool.used() <= 24_000, "usage hovers near capacity: {}", pool.used());
4570	}
4571
4572	/// One write pays at most twice what it produced, so a capacity shrink (or one
4573	/// track's burst) drains gradually instead of one writer dumping its whole
4574	/// backlog in a single call.
4575	#[tokio::test]
4576	async fn payment_capped_per_write() {
4577		tokio::time::pause();
4578
4579		let (mut producer, pool) = pooled_producer(1 << 40);
4580		for _ in 0..10 {
4581			finished_group(&mut producer, 1_000);
4582		}
4583
4584		// The governor slashes the target; nothing is reclaimed synchronously.
4585		pool.resize(100);
4586		let before = pool.used();
4587
4588		// One 1k write may evict at most ~2k of backlog, not all ten groups.
4589		finished_group(&mut producer, 1_000);
4590
4591		let consumer = producer.consume();
4592		assert!(consumer.peek_group(0).is_none(), "the oldest groups are evicted");
4593		assert!(consumer.peek_group(1).is_none());
4594		assert!(consumer.peek_group(2).is_some(), "the backlog drains gradually");
4595		assert!(pool.used() > before - 4_000, "one write must not dump the backlog");
4596	}
4597
4598	/// Accepting a track after pre-accept backfill must keep the same write
4599	/// counter: the counter is owned by the track state, so replacing the info
4600	/// can't strand the bytes already-created groups keep charging.
4601	#[tokio::test]
4602	async fn accept_preserves_write_accounting() {
4603		tokio::time::pause();
4604
4605		let pool = cache::Pool::new(12_000);
4606		let broadcast = broadcast::Info {
4607			origin: crate::origin::Info::default().with_pool(pool.clone()),
4608			..Default::default()
4609		};
4610		let request = Request::new(Arc::new(broadcast), "test");
4611		let dynamic = request.dynamic();
4612		let consumer = request.consume();
4613
4614		// Serve a backfill before the track is accepted, then grow it.
4615		let pending = consumer.fetch_group(0, None);
4616		let req = dynamic
4617			.requested_group()
4618			.now_or_never()
4619			.expect("should not block")
4620			.unwrap();
4621		let mut backfill = req.accept(None).unwrap();
4622		pending.await.unwrap();
4623		backfill
4624			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 30_000]))
4625			.unwrap();
4626
4627		// Accept with a fresh Info: the pre-accept group's writes must still be
4628		// drained by this track's future charges.
4629		let mut producer = request.accept(None);
4630		producer.append_group().unwrap().finish().unwrap();
4631		producer.append_group().unwrap().finish().unwrap();
4632
4633		assert!(
4634			producer.consume().peek_group(0).is_none(),
4635			"pre-accept backfill growth is reclaimed after accept"
4636		);
4637		assert!(pool.used() <= 13_000, "usage converges: {}", pool.used());
4638	}
4639
4640	/// Re-serving a sequence many times must not accumulate eviction hints: stale
4641	/// hints die on stamp mismatch and compaction reclaims them.
4642	#[tokio::test]
4643	async fn recreated_sequence_bounds_eviction_hints() {
4644		let (mut producer, _pool) = pooled_producer(1 << 40);
4645		producer.create_group(5u64.into()).unwrap().finish().unwrap();
4646
4647		for _ in 0..200 {
4648			let group = producer.create_group(1u64.into()).unwrap();
4649			group.abort(Error::Cancel).unwrap();
4650		}
4651
4652		let state = producer.state.read();
4653		assert!(
4654			state.evict.len() <= 2 * state.lookup.len() + EVICT_SLACK,
4655			"stale hints are compacted: {} entries for {} slots",
4656			state.evict.len(),
4657			state.lookup.len()
4658		);
4659	}
4660
4661	/// A frame write within the same coarse tick still outranks merely-inserted
4662	/// content, so the freshly-written group survives and the empty one pays.
4663	#[tokio::test]
4664	async fn same_tick_write_outranks_inserted() {
4665		tokio::time::pause();
4666
4667		// No time advances: every stamp lands in the same tick.
4668		let (mut producer, _pool) = pooled_producer(10_000);
4669
4670		producer.append_group().unwrap().finish().unwrap(); // seq 0: empty
4671		finished_group(&mut producer, 3_000); // seq 1: written
4672		finished_group(&mut producer, 3_000); // seq 2
4673		finished_group(&mut producer, 3_000); // seq 3
4674		finished_group(&mut producer, 3_000); // seq 4: over budget, pays
4675
4676		let consumer = producer.consume();
4677		assert!(consumer.peek_group(0).is_none(), "insert-only content pays first");
4678		assert!(consumer.peek_group(1).is_some(), "same-tick written content survives");
4679	}
4680
4681	/// A track that only appends frames to an open group, never inserting another
4682	/// group, still settles its eviction debt once enough bytes accumulate.
4683	#[tokio::test]
4684	async fn frame_only_writer_pays() {
4685		tokio::time::pause();
4686
4687		let (mut producer, pool) = pooled_producer(2_000);
4688		let mut demoted = producer.append_group().unwrap(); // seq 0
4689		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4690
4691		// One large frame crosses the charge threshold: the write itself pays,
4692		// with no further group insert on this track.
4693		demoted
4694			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 300_000]))
4695			.unwrap();
4696
4697		assert!(
4698			pool.used() <= 5_000,
4699			"the frame write settled the debt: {}",
4700			pool.used()
4701		);
4702		assert!(matches!(demoted.finish(), Err(Error::Evicted)));
4703	}
4704
4705	/// One `Info` describing several tracks must not join their eviction accounting:
4706	/// each track opens its own account against the pool.
4707	#[tokio::test]
4708	async fn each_track_owns_its_account() {
4709		let broadcast = Arc::new(broadcast::Info::default());
4710		let info = Info::default();
4711		let a = Producer::new(broadcast.clone(), "a", info.clone());
4712		let b = Producer::new(broadcast, "b", info);
4713
4714		let a = a.state.read().cache.clone();
4715		let b = b.state.read().cache.clone();
4716		assert!(!Arc::ptr_eq(&a, &b), "each track owns its account");
4717	}
4718
4719	/// A `Dynamic` still serving fetches keeps the track alive, so the publisher
4720	/// letting go isn't an abrupt teardown: the handler can still serve the cache.
4721	#[tokio::test]
4722	async fn a_dynamic_defers_teardown() {
4723		let (mut producer, pool) = pooled_producer(1 << 40);
4724		let dynamic = producer.dynamic();
4725		finished_group(&mut producer, 100);
4726
4727		drop(producer);
4728		assert!(pool.used() > 0, "the handler still serves the cache");
4729
4730		drop(dynamic);
4731		assert_eq!(pool.used(), 0, "the last handle tears it down");
4732	}
4733
4734	/// A finished track releases everything once every handle is gone.
4735	///
4736	/// Its groups hold the cache account, and the account links back here, so that link
4737	/// has to be weak: anything stronger makes the state (and every cached frame in it)
4738	/// immortal, even with no producer or consumer left.
4739	#[tokio::test]
4740	async fn finished_track_frees_its_cache() {
4741		let (mut producer, pool) = pooled_producer(1 << 40);
4742		finished_group(&mut producer, 100);
4743		producer.finish().unwrap();
4744
4745		let state = producer.state.downgrade();
4746		drop(producer);
4747
4748		assert!(state.upgrade().is_none(), "the track state is freed");
4749		assert_eq!(pool.used(), 0, "so are its cached bytes");
4750	}
4751
4752	/// A group settling its eviction debt upgrades the account's weak handle, which
4753	/// counts as a producer on the track state. Teardown must not mistake that for a
4754	/// surviving publisher, or an abrupt drop silently behaves like a clean finish.
4755	#[tokio::test]
4756	async fn teardown_ignores_a_settling_group() {
4757		let (mut producer, pool) = pooled_producer(1 << 40);
4758		finished_group(&mut producer, 100);
4759
4760		// Stand in for a concurrent `cache::Track::settle`, mid-upgrade.
4761		let settling = producer.state.downgrade().upgrade().expect("open");
4762		drop(producer);
4763
4764		assert_eq!(pool.used(), 0, "the abrupt teardown still released the cache");
4765		drop(settling);
4766	}
4767
4768	/// A subscriber holding one cached group must not pin the whole track: a group
4769	/// carries the track's properties by value, not a handle back to its state.
4770	#[tokio::test]
4771	async fn cached_group_outlives_its_track() {
4772		let (mut producer, pool) = pooled_producer(1 << 40);
4773		let sequence = finished_group(&mut producer, 100);
4774		let group = producer.consume().peek_group(sequence).expect("cached");
4775		producer.finish().unwrap();
4776
4777		let state = producer.state.downgrade();
4778		drop(producer);
4779		assert!(state.upgrade().is_none(), "the track state is freed");
4780		assert!(pool.used() > 0, "the retained group keeps its own bytes");
4781
4782		drop(group);
4783		assert_eq!(pool.used(), 0, "which it releases when dropped");
4784	}
4785
4786	/// A backfill served before the track was accepted settles its own debt: the
4787	/// account exists from the moment the state does, so acceptance replacing the
4788	/// `Info` can't leave already-created groups writing for free.
4789	#[tokio::test]
4790	async fn pre_accept_backfill_settles_late_writes() {
4791		tokio::time::pause();
4792
4793		let pool = cache::Pool::new(2_000);
4794		let broadcast = broadcast::Info {
4795			origin: crate::origin::Info::default().with_pool(pool.clone()),
4796			..Default::default()
4797		};
4798		let request = Request::new(Arc::new(broadcast), "test");
4799		let dynamic = request.dynamic();
4800		let consumer = request.consume();
4801
4802		// Serve backfill seq 0 before the track is accepted.
4803		let pending = consumer.fetch_group(0, None);
4804		let req = dynamic
4805			.requested_group()
4806			.now_or_never()
4807			.expect("should not block")
4808			.unwrap();
4809		let mut backfill = req.accept(None).unwrap();
4810		pending.await.unwrap();
4811
4812		// Accept, then demote the backfill with a live group.
4813		let mut producer = request.accept(None);
4814		producer.append_group().unwrap().finish().unwrap();
4815
4816		// No further insert: the late write into the demoted backfill is the only
4817		// thing that can pay the debt it just took on.
4818		backfill
4819			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 300_000]))
4820			.unwrap();
4821
4822		assert!(
4823			pool.used() <= 5_000,
4824			"the frame write settled the debt: {}",
4825			pool.used()
4826		);
4827	}
4828
4829	/// A late frame write restarts the retention clock (retention is documented as
4830	/// time since last written or fetched), so an actively-growing group is not
4831	/// expired as old mid-write.
4832	#[tokio::test]
4833	async fn write_restarts_retention_clock() {
4834		tokio::time::pause();
4835
4836		let (mut producer, _pool) = pooled_producer(1 << 40);
4837		let mut straggler = producer.append_group().unwrap(); // seq 0
4838		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4839
4840		// Idle past the window, then the straggler receives a late frame.
4841		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4842		straggler
4843			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4844			.unwrap();
4845		producer.append_group().unwrap().finish().unwrap(); // seq 2 runs expiry
4846
4847		let consumer = producer.consume();
4848		assert!(consumer.peek_group(0).is_some(), "the write restarted the clock");
4849
4850		// Once the writes stop, the group ages out normally.
4851		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4852		producer.append_group().unwrap().finish().unwrap(); // seq 3 runs expiry
4853		assert!(consumer.peek_group(0).is_none(), "idle content still expires");
4854	}
4855
4856	/// Continuously refreshed entries at the front of the eviction order must not
4857	/// starve expiry of entries behind them: the scan cursor rotates.
4858	#[tokio::test]
4859	async fn refreshed_front_does_not_starve_expiry() {
4860		tokio::time::pause();
4861
4862		let (mut producer, _pool) = pooled_producer(1 << 40);
4863		let dynamic = producer.dynamic();
4864		let consumer = producer.consume();
4865
4866		producer.create_group(10u64.into()).unwrap().finish().unwrap();
4867		for sequence in 1..=5u64 {
4868			let pending = consumer.fetch_group(sequence, None);
4869			let req = dynamic
4870				.requested_group()
4871				.now_or_never()
4872				.expect("should not block")
4873				.unwrap();
4874			let mut group = req.accept(None).unwrap();
4875			group
4876				.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
4877				.unwrap();
4878			group.finish().unwrap();
4879			pending.await.unwrap();
4880		}
4881
4882		// Age everything out, then refresh the first four backfills so they sit
4883		// fresh at the front of the eviction order, hiding the expired fifth.
4884		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
4885		for sequence in 1..=4u64 {
4886			consumer.fetch_group(sequence, None).await.unwrap();
4887		}
4888
4889		// The rotating cursor reaches the fifth entry within a few writes.
4890		for _ in 0..3 {
4891			producer.append_group().unwrap().finish().unwrap();
4892		}
4893		assert!(consumer.peek_group(5).is_none(), "expired backfill is reclaimed");
4894		assert!(consumer.peek_group(1).is_some(), "refreshed backfill survives");
4895	}
4896
4897	/// A publisher re-creating an aborted sequence is delivered exactly once, at
4898	/// its actual arrival position: the historical arrival entry is dead.
4899	#[tokio::test]
4900	async fn recreated_sequence_delivered_once() {
4901		let (mut producer, _pool) = pooled_producer(1 << 40);
4902
4903		producer.create_group(0u64.into()).unwrap().finish().unwrap();
4904		let aborted = producer.create_group(1u64.into()).unwrap();
4905		aborted.abort(Error::Cancel).unwrap();
4906		producer.create_group(2u64.into()).unwrap().finish().unwrap();
4907		producer.create_group(1u64.into()).unwrap().finish().unwrap();
4908
4909		let mut subscriber = producer.subscribe(None);
4910		assert_eq!(subscriber.assert_group().sequence, 0);
4911		assert_eq!(subscriber.assert_group().sequence, 2);
4912		assert_eq!(
4913			subscriber.assert_group().sequence,
4914			1,
4915			"replacement arrives at its own position"
4916		);
4917		subscriber.assert_no_group();
4918	}
4919
4920	/// Datagrams share `max_sequence` but must not break group demotion: the live
4921	/// edge is tracked per group, so interleaving datagrams can't strand groups
4922	/// outside the eviction order and bypass the budget.
4923	#[tokio::test]
4924	async fn datagrams_do_not_block_eviction() {
4925		tokio::time::pause();
4926
4927		let (mut producer, pool) = pooled_producer(1_000);
4928		for _ in 0..10 {
4929			finished_group(&mut producer, 1_000);
4930			producer.append_datagram(Timestamp::ZERO, &b"beat"[..]).unwrap();
4931		}
4932
4933		let consumer = producer.consume();
4934		assert!(consumer.peek_group(0).is_none(), "old groups still evict");
4935		assert!(
4936			pool.used() < 4 * 1_256,
4937			"interleaved datagrams must not bypass the budget: {}",
4938			pool.used()
4939		);
4940	}
4941
4942	/// An aborted group releases its access sample along with its bytes, from any
4943	/// handle: ghost samples must not linger in the pool mean where they'd hold it
4944	/// in the past and over-protect every live group.
4945	#[tokio::test]
4946	async fn aborted_group_leaves_no_ghost_sample() {
4947		tokio::time::pause();
4948
4949		let (mut producer, pool) = pooled_producer(1 << 40);
4950		let group0 = producer.append_group().unwrap();
4951		producer.append_group().unwrap(); // demotes seq 0 into the mean
4952
4953		assert!(pool.average().is_some(), "demoted group is sampled");
4954		group0.abort(Error::Cancel).unwrap();
4955		assert_eq!(pool.average(), None, "the abort must remove the sample");
4956	}
4957
4958	/// Empty groups still carry fixed overhead; they must repay the budget when
4959	/// evicted rather than being unevictable freeloaders.
4960	#[tokio::test]
4961	async fn empty_groups_repay_overhead() {
4962		tokio::time::pause();
4963
4964		let (mut producer, pool) = pooled_producer(1_000);
4965		for _ in 0..100 {
4966			let mut group = producer.append_group().unwrap();
4967			group.finish().unwrap();
4968		}
4969
4970		assert!(
4971			pool.used() <= 3_000,
4972			"empty-group overhead must stay near the budget: {}",
4973			pool.used()
4974		);
4975	}
4976
4977	/// Late growth on an already-demoted group is billed: the gross-write counter
4978	/// feeds debt on the next append, so a straggler can't grow unbounded.
4979	#[tokio::test]
4980	async fn growth_on_demoted_group_is_billed() {
4981		tokio::time::pause();
4982
4983		let (mut producer, pool) = pooled_producer(2_000);
4984		let mut straggler = producer.append_group().unwrap(); // seq 0
4985		producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0
4986
4987		// The demoted group balloons: no eviction yet (nothing ran), but billed.
4988		straggler
4989			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 10_000]))
4990			.unwrap();
4991
4992		// The next append observes the growth and evicts the straggler.
4993		producer.append_group().unwrap().finish().unwrap(); // seq 2
4994
4995		let consumer = producer.consume();
4996		assert!(consumer.peek_group(0).is_none(), "the ballooned group is evicted");
4997		assert!(pool.used() <= 3_000, "growth is reclaimed: {}", pool.used());
4998	}
4999
5000	/// A stale arrival entry whose sequence was later re-served by fetched backfill
5001	/// must not leak the replacement into arrival-order subscriptions.
5002	#[tokio::test]
5003	async fn refilled_sequence_stays_out_of_subscriptions() {
5004		let (mut producer, _pool) = pooled_producer(1 << 40);
5005		let dynamic = producer.dynamic();
5006		let consumer = producer.consume();
5007
5008		producer.create_group(0u64.into()).unwrap().finish().unwrap();
5009		let aborted = producer.create_group(1u64.into()).unwrap();
5010		aborted.abort(Error::Cancel).unwrap();
5011		producer.create_group(2u64.into()).unwrap().finish().unwrap();
5012
5013		// Re-serve seq 1 as backfill; its slot replaces the aborted one, and the
5014		// old arrival entry for seq 1 now resolves to it.
5015		let pending = consumer.fetch_group(1, None);
5016		let req = dynamic
5017			.requested_group()
5018			.now_or_never()
5019			.expect("should not block")
5020			.unwrap();
5021		let mut group = req.accept(None).unwrap();
5022		group
5023			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"backfill"))
5024			.unwrap();
5025		group.finish().unwrap();
5026		pending.await.unwrap();
5027
5028		// The backfill serves by sequence, but never in arrival order.
5029		assert!(consumer.peek_group(1).is_some());
5030		let mut subscriber = producer.subscribe(None);
5031		assert_eq!(subscriber.assert_group().sequence, 0);
5032		assert_eq!(subscriber.assert_group().sequence, 2);
5033		subscriber.assert_no_group();
5034	}
5035
5036	/// An expired backfill can't hide behind a refreshed one: the eviction-order
5037	/// expiry scans a bounded prefix instead of stopping at the first fresh entry.
5038	#[tokio::test]
5039	async fn expired_backfill_behind_refreshed_reclaimed() {
5040		tokio::time::pause();
5041
5042		let (mut producer, _pool) = pooled_producer(1 << 40);
5043		let dynamic = producer.dynamic();
5044		let consumer = producer.consume();
5045
5046		producer.create_group(5u64.into()).unwrap().finish().unwrap();
5047		for sequence in [2u64, 3u64] {
5048			let pending = consumer.fetch_group(sequence, None);
5049			let req = dynamic
5050				.requested_group()
5051				.now_or_never()
5052				.expect("should not block")
5053				.unwrap();
5054			let mut group = req.accept(None).unwrap();
5055			group
5056				.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100]))
5057				.unwrap();
5058			group.finish().unwrap();
5059			pending.await.unwrap();
5060		}
5061
5062		// Keep seq 2 fresh while seq 3 (behind it in eviction order) expires.
5063		tokio::time::advance(Duration::from_secs(4)).await;
5064		consumer.fetch_group(2, None).await.unwrap();
5065		tokio::time::advance(DEFAULT_LATENCY_MAX - Duration::from_secs(2)).await;
5066		producer.create_group(6u64.into()).unwrap().finish().unwrap();
5067
5068		let consumer = producer.consume();
5069		assert!(consumer.peek_group(2).is_some(), "refreshed backfill survives");
5070		assert!(consumer.peek_group(3).is_none(), "expired backfill is reclaimed");
5071	}
5072
5073	/// A FETCH hit within the same coarse clock tick still protects the group: the
5074	/// refresh stamps one tick ahead, so it reads strictly newer than the mean.
5075	#[tokio::test]
5076	async fn same_tick_fetch_protects() {
5077		tokio::time::pause();
5078
5079		// No time advances at all: every timestamp lands in the same tick.
5080		let (mut producer, _pool) = pooled_producer(10_000);
5081		let consumer = producer.consume();
5082
5083		finished_group(&mut producer, 3_000); // seq 0
5084		finished_group(&mut producer, 3_000); // seq 1
5085		finished_group(&mut producer, 3_000); // seq 2
5086
5087		consumer.fetch_group(0, None).await.unwrap();
5088
5089		finished_group(&mut producer, 3_000); // seq 3
5090		finished_group(&mut producer, 3_000); // seq 4
5091
5092		assert!(consumer.peek_group(0).is_some(), "same-tick refresh protects");
5093		assert!(consumer.peek_group(1).is_none(), "the unread group dies instead");
5094	}
5095
5096	/// A refetched group that reclaims max_sequence is the live edge again: it must
5097	/// not re-enter the eviction order, or memory pressure could evict the newest
5098	/// content.
5099	#[tokio::test]
5100	async fn refetched_latest_stays_protected() {
5101		tokio::time::pause();
5102
5103		let (mut producer, _pool) = pooled_producer(10_000);
5104		let dynamic = producer.dynamic();
5105		let consumer = producer.consume();
5106
5107		let straggler = producer.append_group().unwrap(); // seq 0
5108
5109		// The publisher aborts its own latest group; the sequence stays at the live edge.
5110		let latest = producer.append_group().unwrap(); // seq 1
5111		latest.abort(Error::Cancel).unwrap();
5112
5113		// Re-fetch it: the replacement takes over max_sequence.
5114		let pending = consumer.fetch_group(1, None);
5115		let req = dynamic
5116			.requested_group()
5117			.now_or_never()
5118			.expect("should not block")
5119			.unwrap();
5120		let mut group = req.accept(None).unwrap();
5121		group
5122			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 1000]))
5123			.unwrap();
5124		group.finish().unwrap();
5125		pending.await.unwrap();
5126
5127		// The refetched latest is protected by omission: it has no entry in the
5128		// eviction order, so no amount of debt can select it.
5129		{
5130			let state = producer.state.read();
5131			assert!(state.lookup.contains_key(&1), "refetched group is cached");
5132			assert!(
5133				state.evict.iter().all(|(sequence, _)| *sequence != 1),
5134				"the live edge must not be an eviction candidate"
5135			);
5136		}
5137		drop(straggler);
5138	}
5139
5140	/// An evicted group is a cache miss, so a fetch re-fetches it and the accepted
5141	/// replacement serves the sequence again (not `Error::Duplicate`).
5142	#[tokio::test]
5143	async fn eviction_allows_refetch() {
5144		tokio::time::pause();
5145
5146		let (mut producer, _pool) = pooled_producer(10_000);
5147		let dynamic = producer.dynamic();
5148
5149		finished_group(&mut producer, 10_000); // seq 0
5150		finished_group(&mut producer, 10_000); // seq 1: demotes seq 0
5151		finished_group(&mut producer, 10_000); // seq 2: pays by evicting seq 0
5152
5153		let consumer = producer.consume();
5154		assert!(consumer.peek_group(0).is_none());
5155		let pending = consumer.fetch_group(0, None);
5156
5157		let req = dynamic
5158			.requested_group()
5159			.now_or_never()
5160			.expect("should not block")
5161			.unwrap();
5162		assert_eq!(req.sequence(), 0);
5163
5164		let mut group = req.accept(None).unwrap();
5165		group
5166			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"refetched"))
5167			.unwrap();
5168		group.finish().unwrap();
5169
5170		let mut group = pending.await.unwrap();
5171		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"refetched");
5172	}
5173
5174	/// A fetched (backfill) group is served by sequence but never replayed to
5175	/// arrival-order subscribers.
5176	#[tokio::test]
5177	async fn fetched_backfill_not_subscribed() {
5178		let (mut producer, _pool) = pooled_producer(1 << 40);
5179		let dynamic = producer.dynamic();
5180		let consumer = producer.consume();
5181
5182		// The publisher starts at seq 5; earlier groups exist only upstream.
5183		producer.create_group(5u64.into()).unwrap().finish().unwrap();
5184		producer.create_group(6u64.into()).unwrap().finish().unwrap();
5185
5186		// Fetch the gap: it lands in the cache and resolves the fetch...
5187		let pending = consumer.fetch_group(2, None);
5188		let req = dynamic
5189			.requested_group()
5190			.now_or_never()
5191			.expect("should not block")
5192			.unwrap();
5193		let mut group = req.accept(None).unwrap();
5194		group
5195			.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"backfill"))
5196			.unwrap();
5197		group.finish().unwrap();
5198		let mut fetched = pending.await.unwrap();
5199		assert_eq!(&fetched.read_frame().await.unwrap().unwrap().payload[..], b"backfill");
5200		assert!(consumer.peek_group(2).is_some(), "backfill is cached for later fetches");
5201
5202		// ...but an arrival-order subscriber only sees the live groups.
5203		let mut subscriber = producer.subscribe(None);
5204		assert_eq!(subscriber.assert_group().sequence, 5);
5205		assert_eq!(subscriber.assert_group().sequence, 6);
5206		subscriber.assert_no_group();
5207	}
5208
5209	/// Fetched backfill isn't in arrival order, so it ages out through the eviction
5210	/// order instead of lingering until the track closes.
5211	#[tokio::test]
5212	async fn expired_backfill_reclaimed() {
5213		tokio::time::pause();
5214
5215		let (mut producer, pool) = pooled_producer(1 << 40);
5216		let dynamic = producer.dynamic();
5217		let consumer = producer.consume();
5218
5219		producer.create_group(5u64.into()).unwrap().finish().unwrap();
5220
5221		// Serve a backfill fetch for an old sequence.
5222		let pending = consumer.fetch_group(2, None);
5223		let req = dynamic
5224			.requested_group()
5225			.now_or_never()
5226			.expect("should not block")
5227			.unwrap();
5228		let mut group = req.accept(None).unwrap();
5229		group
5230			.write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 1000]))
5231			.unwrap();
5232		group.finish().unwrap();
5233		pending.await.unwrap();
5234		let used = pool.used();
5235
5236		// Age past the track window; the next write reclaims the backfill.
5237		tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await;
5238		producer.create_group(6u64.into()).unwrap().finish().unwrap();
5239
5240		assert!(consumer.peek_group(2).is_none(), "expired backfill is reclaimed");
5241		assert!(pool.used() < used, "its bytes are released");
5242	}
5243
5244	#[tokio::test]
5245	async fn fetch_aborts_with_track() {
5246		let producer = track_producer("test", None);
5247		let dynamic = producer.dynamic();
5248		let consumer = producer.consume();
5249
5250		let pending = consumer.fetch_group(3, None);
5251		assert!(kio::Pollable::poll(&*pending, &kio::Waiter::noop()).is_pending());
5252
5253		producer.abort(Error::Cancel).unwrap();
5254		assert!(pending.await.is_err());
5255		drop(dynamic);
5256	}
5257}