Skip to main content

moq_net/model/
origin.rs

1use crate::{broadcast, cache, stats, track};
2use kio::Pollable;
3use std::{
4	cmp::Reverse,
5	collections::{BTreeMap, HashMap, HashSet},
6	fmt,
7	sync::Arc,
8	sync::atomic::{AtomicU64, Ordering},
9	task::{Poll, ready},
10	time::Duration,
11};
12
13use rand::RngExt;
14use web_async::Lock;
15
16use super::{Requests, WeakCache};
17use crate::{
18	AsPath, Error, Path, PathOwned, PathPrefixes,
19	coding::{BoundsExceeded, Decode, DecodeError, Encode, EncodeError},
20};
21
22/// A relay origin, identified by a 62-bit varint on the wire.
23///
24/// Local origins are built with [`Origin::new`] or [`Origin::random`], both of
25/// which guarantee a non-zero id so loop detection can work. Remote peers may
26/// still send `0`; it is legal on the wire but cannot be used for loop detection.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub struct Origin {
29	/// 62-bit identifier. Encoded as a QUIC varint on the wire.
30	id: u64,
31}
32
33/// Returned when a local origin id is zero or outside the 62-bit wire range.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct InvalidOrigin;
37
38impl fmt::Display for InvalidOrigin {
39	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40		write!(f, "local origin id must be non-zero and below 2^62")
41	}
42}
43
44impl std::error::Error for InvalidOrigin {}
45
46impl Origin {
47	/// Placeholder for hop entries whose actual id is not on the wire (Lite03).
48	/// Also used for remote peers that choose the legal but loop-blind id 0.
49	pub(crate) const UNKNOWN: Self = Self { id: 0 };
50
51	/// Build an origin from a stable id.
52	///
53	/// The id must be non-zero and fit in the 62-bit QUIC varint range. Wire
54	/// decode accepts remote id 0, but local origins should not use it because
55	/// downstream peers cannot exclude it for loop detection.
56	pub fn new(id: u64) -> Result<Self, InvalidOrigin> {
57		if id == 0 || id >= 1u64 << 62 {
58			return Err(InvalidOrigin);
59		}
60		Ok(Self { id })
61	}
62
63	/// Generate a fresh origin with a random non-zero id. Use this for any
64	/// origin that does not need a stable identity across restarts.
65	///
66	/// TEMPORARY: the wire format allows 62 bits, but older `@moq/lite` JS
67	/// clients decode `AnnounceInterest.exclude_hop` as a u53 (number) and
68	/// throw on anything > 2^53-1. To keep those clients alive against
69	/// fresh relays, we cap the random id at 53 bits. Restore to 62 bits
70	/// once the JS u62 fix has propagated to deployed bundles.
71	pub fn random() -> Self {
72		let mut rng = rand::rng();
73		let id = rng.random_range(1..(1u64 << 53));
74		Self { id }
75	}
76
77	/// Return the origin's wire id.
78	pub fn id(self) -> u64 {
79		self.id
80	}
81
82	/// Consume this [Origin] to create a producer that carries its id, with an
83	/// unbounded cache pool. Use [`Info::produce`] to configure the pool.
84	pub fn produce(self) -> Producer {
85		Info::new(self).produce()
86	}
87}
88
89/// An origin's identity plus the cache pool its broadcasts inherit.
90///
91/// Doubles as the construction config for an [origin `Producer`](Producer) and as the
92/// parent handle every broadcast carries ([`broadcast::Info::origin`]): the origin owns
93/// the [`cache::Pool`] every group in the tree charges into, so a relay configures one
94/// bounded pool here and every broadcast, track, and group beneath it reaches that single
95/// budget by walking up the ownership chain. Defaults to an unbounded pool
96/// ([`Origin::produce`] is the shorthand for that). Cheap to clone (a `Copy` id plus an
97/// `Arc`-handle bump), so it's stored by value rather than behind another `Arc`.
98#[derive(Clone, Debug)]
99#[non_exhaustive]
100pub struct Info {
101	/// The origin's wire identity, appended to broadcast hop chains for loop
102	/// detection and shortest-path routing.
103	pub id: Origin,
104
105	/// The cache pool broadcasts under this origin charge their groups into. It flows
106	/// down the ownership chain (origin -> broadcast -> track -> group): a track opens
107	/// an account against it, and its groups charge through that. Unbounded by
108	/// default; a relay sets a bounded one (via [`Self::with_pool`]) so cached groups
109	/// across the whole process share one memory budget.
110	pub pool: cache::Pool,
111
112	/// Ceiling on how long any non-latest group under this origin is retained. Each
113	/// track's own [`latency_max`](track::Info::latency_max) window is clamped down to
114	/// this when the track binds, so a group is never held longer than this regardless
115	/// of what a publisher advertises. The age budget alongside [`Self::pool`]'s byte
116	/// budget: a relay bounds memory by both. [`Duration::MAX`] (the default) imposes no
117	/// ceiling, leaving each track's own window in force.
118	pub cache_duration: Duration,
119
120	/// The retention window given to a track whose publisher advertises none.
121	///
122	/// moq-lite 05+ carries [`latency_max`](track::Info::latency_max) in TRACK_INFO, so a
123	/// track relayed over it keeps the window its publisher chose. Every moq-transport
124	/// draft and moq-lite 01-04 have no such wire property, so a track arriving over one
125	/// of them lands here instead. Raise it on a relay fronting a segmented egress
126	/// (HLS/DASH), which needs a playlist window's worth of history rather than the live
127	/// edge. Defaults to [`track::DEFAULT_LATENCY_MAX`], and [`Self::cache_duration`]
128	/// still caps it.
129	pub latency_default: Duration,
130
131	/// How long a broadcast under this origin outlives the *ungraceful* loss of its
132	/// last source before closing. Within the window the path stays announced and a
133	/// source re-attaching at it (a session reconnecting, a publisher re-announcing)
134	/// splices in seamlessly, so consumers never observe the gap. A source that ends
135	/// deliberately ([`broadcast::Producer::finish`], a clean unannounce from a peer)
136	/// closes the broadcast immediately regardless. Zero (the default) closes
137	/// immediately either way; a duration too large to represent as a deadline
138	/// (e.g. [`Duration::MAX`]) lingers indefinitely.
139	pub linger: Duration,
140}
141
142impl Default for Info {
143	/// An unknown origin (id `0`, no loop detection) with an unbounded pool. This is
144	/// what a standalone broadcast (no relay origin) inherits.
145	fn default() -> Self {
146		Self {
147			id: Origin::UNKNOWN,
148			pool: cache::Pool::default(),
149			cache_duration: Duration::MAX,
150			latency_default: track::DEFAULT_LATENCY_MAX,
151			linger: Duration::ZERO,
152		}
153	}
154}
155
156impl Info {
157	/// Config for the given origin id with an unbounded cache pool.
158	pub fn new(id: Origin) -> Self {
159		Self { id, ..Self::default() }
160	}
161
162	/// Set the cache pool this origin's broadcasts inherit, returning `self` for chaining.
163	pub fn with_pool(mut self, pool: cache::Pool) -> Self {
164		self.pool = pool;
165		self
166	}
167
168	/// Set the retention ceiling (see [`Self::cache_duration`]) applied to every track
169	/// under this origin, returning `self` for chaining.
170	pub fn with_cache_duration(mut self, cache_duration: Duration) -> Self {
171		self.cache_duration = cache_duration;
172		self
173	}
174
175	/// Set the retention window (see [`Self::latency_default`]) used for tracks whose
176	/// publisher advertises none, returning `self` for chaining.
177	pub fn with_latency_default(mut self, latency_default: Duration) -> Self {
178		self.latency_default = latency_default;
179		self
180	}
181
182	/// Set how long a broadcast survives ungracefully losing its last source (see
183	/// [`Self::linger`]), returning `self` for chaining.
184	pub fn with_linger(mut self, linger: Duration) -> Self {
185		self.linger = linger;
186		self
187	}
188
189	/// Consume this config to create an origin [`Producer`].
190	pub fn produce(self) -> Producer {
191		Producer::new(self)
192	}
193}
194
195impl TryFrom<u64> for Origin {
196	type Error = InvalidOrigin;
197
198	fn try_from(id: u64) -> Result<Self, Self::Error> {
199		Self::new(id)
200	}
201}
202
203impl fmt::Display for Origin {
204	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205		self.id.fmt(f)
206	}
207}
208
209impl<V: Copy> Encode<V> for Origin
210where
211	u64: Encode<V>,
212{
213	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) -> Result<(), EncodeError> {
214		self.id.encode(w, version)
215	}
216}
217
218impl<V: Copy> Decode<V> for Origin
219where
220	u64: Decode<V>,
221{
222	fn decode<R: bytes::Buf>(r: &mut R, version: V) -> Result<Self, DecodeError> {
223		let id = u64::decode(r, version)?;
224		if id >= 1u64 << 62 {
225			return Err(DecodeError::InvalidValue);
226		}
227		Ok(Self { id })
228	}
229}
230
231/// Maximum number of origins (hops) an [`OriginList`] can hold.
232///
233/// Caps pathological or loop-induced announcements at a reasonable cluster
234/// diameter; appending past this limit returns [`TooManyOrigins`] rather than
235/// silently truncating.
236pub(crate) const MAX_HOPS: usize = 32;
237
238/// Bounded list of [`Origin`] entries, typically the hop chain of a broadcast.
239///
240/// Guarantees `len() <= MAX_HOPS`. Construct via [`OriginList::new`] +
241/// [`OriginList::push`], or fall back to the fallible [`TryFrom<Vec<Origin>>`].
242#[derive(Debug, Clone, Default, PartialEq, Eq)]
243pub struct OriginList(Vec<Origin>);
244
245/// Returned when an operation would grow an [`OriginList`] past its hop-count cap.
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247#[non_exhaustive]
248pub struct TooManyOrigins;
249
250impl fmt::Display for TooManyOrigins {
251	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252		write!(f, "too many origins (max {MAX_HOPS})")
253	}
254}
255
256impl std::error::Error for TooManyOrigins {}
257
258impl From<TooManyOrigins> for DecodeError {
259	fn from(_: TooManyOrigins) -> Self {
260		DecodeError::BoundsExceeded
261	}
262}
263
264impl OriginList {
265	/// Create an empty list.
266	pub fn new() -> Self {
267		Self(Vec::new())
268	}
269
270	/// Append an [`Origin`]. Returns [`TooManyOrigins`] if the list is full.
271	pub fn push(&mut self, origin: Origin) -> Result<(), TooManyOrigins> {
272		if self.0.len() >= MAX_HOPS {
273			return Err(TooManyOrigins);
274		}
275		self.0.push(origin);
276		Ok(())
277	}
278
279	/// Replace the first entry equal to `target` with `replacement`, returning
280	/// true if a match was found. The length is unchanged.
281	pub fn replace_first(&mut self, target: Origin, replacement: Origin) -> bool {
282		for entry in &mut self.0 {
283			if *entry == target {
284				*entry = replacement;
285				return true;
286			}
287		}
288		false
289	}
290
291	/// Returns true if any entry matches `origin`.
292	pub fn contains(&self, origin: &Origin) -> bool {
293		self.0.contains(origin)
294	}
295
296	/// Number of entries currently in the list (always `<= MAX_HOPS`).
297	pub fn len(&self) -> usize {
298		self.0.len()
299	}
300
301	/// Whether the list contains no entries.
302	pub fn is_empty(&self) -> bool {
303		self.0.is_empty()
304	}
305
306	/// Iterate over the entries in hop order (oldest first).
307	pub fn iter(&self) -> std::slice::Iter<'_, Origin> {
308		self.0.iter()
309	}
310
311	/// Borrow the entries as a slice.
312	pub fn as_slice(&self) -> &[Origin] {
313		&self.0
314	}
315}
316
317impl TryFrom<Vec<Origin>> for OriginList {
318	type Error = TooManyOrigins;
319
320	fn try_from(v: Vec<Origin>) -> Result<Self, Self::Error> {
321		if v.len() > MAX_HOPS {
322			return Err(TooManyOrigins);
323		}
324		Ok(Self(v))
325	}
326}
327
328impl<'a> IntoIterator for &'a OriginList {
329	type Item = &'a Origin;
330	type IntoIter = std::slice::Iter<'a, Origin>;
331
332	fn into_iter(self) -> Self::IntoIter {
333		self.iter()
334	}
335}
336
337impl<V: Copy> Encode<V> for OriginList
338where
339	u64: Encode<V>,
340	Origin: Encode<V>,
341{
342	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) -> Result<(), EncodeError> {
343		(self.0.len() as u64).encode(w, version)?;
344		for origin in &self.0 {
345			origin.encode(w, version)?;
346		}
347		Ok(())
348	}
349}
350
351impl<V: Copy> Decode<V> for OriginList
352where
353	u64: Decode<V>,
354	Origin: Decode<V>,
355{
356	fn decode<R: bytes::Buf>(r: &mut R, version: V) -> Result<Self, DecodeError> {
357		let count = u64::decode(r, version)? as usize;
358		if count > MAX_HOPS {
359			return Err(DecodeError::BoundsExceeded);
360		}
361		let mut list = Vec::with_capacity(count);
362		for _ in 0..count {
363			list.push(Origin::decode(r, version)?);
364		}
365		Ok(Self(list))
366	}
367}
368
369static NEXT_CONSUMER_ID: AtomicU64 = AtomicU64::new(0);
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
372struct ConsumerId(u64);
373
374impl ConsumerId {
375	fn new() -> Self {
376		Self(NEXT_CONSUMER_ID.fetch_add(1, Ordering::Relaxed))
377	}
378}
379
380// The origin-owned broadcast at a leaf: the spliced broadcast consumers see,
381// the table of sources feeding it, and whether the path is currently announced.
382// `announced` is gated on the best source's `live` flag; a non-announced entry
383// is still returned by lookups, so an offline broadcast stays reachable for
384// subscribes and fetches.
385struct OriginBroadcast {
386	path: PathOwned,
387	/// The shared, spliced broadcast; its `consume()` is what consumers get.
388	broadcast: broadcast::Producer,
389	/// The source table, shared with every source watcher and the front task.
390	/// Also the broadcast's identity for stale-teardown checks.
391	state: kio::Producer<FrontState>,
392	announced: bool,
393}
394
395/// Ordering key used to pick the active route among broadcasts at the same path.
396///
397/// Lower wins. Shorter hop chains sort first (routing prefers the shortest path);
398/// remaining ties break on a deterministic hash of the broadcast name and hop
399/// chain. Every node in the cluster, given the same candidate routes, converges
400/// on the same winner: the hops are forwarded unchanged, and the hash is
401/// build-stable. Mixing the name in spreads equal routes across different
402/// upstreams rather than funneling onto one.
403fn route_key(name: &Path, hops: &OriginList) -> (usize, u64) {
404	(hops.len(), fnv_key(name, hops.iter().copied()))
405}
406
407/// FNV-1a over the broadcast name and a sequence of origin ids.
408///
409/// FNV-1a, not the std hasher: its output is fixed across Rust versions and
410/// builds, which matters when nodes run mismatched binaries during a rolling
411/// deploy and still need to agree on the same route. SEED is a custom basis
412/// (any nonzero u64 works, the textbook one is just as arbitrary); FNV_PRIME is
413/// the standard FNV-64 prime and should stay put.
414///
415/// Two callers, two different id sequences: [`route_key`] hashes a route's hop
416/// chain to pick among *routes*, and [`FrontState::handover_allowed`] hashes a
417/// single relay's origin to pick among *relays*. Mixing the name in spreads
418/// equal candidates across different winners rather than funneling onto one.
419fn fnv_key(name: &Path, origins: impl IntoIterator<Item = Origin>) -> u64 {
420	const SEED: u64 = 0x420C0DECB00B; // 420 C0DEC B00B
421	const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
422
423	let mut hash = SEED;
424	for &byte in name.as_str().as_bytes() {
425		hash = (hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME);
426	}
427	for origin in origins {
428		for &byte in &origin.id().to_le_bytes() {
429			hash = (hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME);
430		}
431	}
432
433	hash
434}
435
436/// Full ordering key for an attached route: announced routes first (an actively
437/// published source beats an offline one), then the marginal cost of pulling via
438/// the route, then the [`route_key`] hop ordering, and finally the newest source
439/// to attach. Lower wins.
440///
441/// Hop length stays the tie-break below cost, so peers that never carry a cost
442/// (pre-lite-06, or a plain local publish) rank exactly as they did before route
443/// cost existed, and equal-cost warm copies resolve to the closest one, which
444/// bounds same-datacenter chains to a single hop.
445///
446/// Recency is the last word, so it only separates routes that are identical in
447/// every advertised respect: same hop chain, same cost. That is a publisher
448/// reconnecting over a fresh session while its old one is still being kept alive
449/// by the transport, and the new session is the one actually carrying frames, so
450/// it wins the moment it attaches instead of after the QUIC idle timeout finally
451/// retires the corpse. Local attach order never leaks into cluster convergence:
452/// routes it can reorder are indistinguishable downstream, since what is
453/// forwarded is the chain and cost, which are equal by construction here.
454fn route_order(name: &Path, route: &FrontRoute) -> (bool, u64, usize, u64, Reverse<u64>) {
455	let (len, hash) = route_key(name, &route.route.hops);
456	(!route.route.announce, route.route.cost, len, hash, Reverse(route.id))
457}
458
459/// One coalesced update queued for an `AnnounceConsumer`.
460///
461/// At most one entry exists per path, so a slow consumer's pending set is bounded
462/// by the number of distinct paths. `UnannounceAnnounce` preserves the signal
463/// that a broadcast genuinely went away and a different one took its place (the
464/// consumer must see the `None` before the `Some`), while a stale `Announce`
465/// cancels with a subsequent `unannounce` because the consumer has not yet
466/// observed it.
467enum PendingUpdate {
468	Announce(broadcast::Consumer),
469	Unannounce,
470	UnannounceAnnounce(broadcast::Consumer),
471}
472
473/// Pending updates keyed by path. `BTreeMap` keeps memory strictly bounded by
474/// the number of distinct paths with outstanding work (collapsed pairs are
475/// fully erased) and gives a deterministic lexicographic delivery order so
476/// tests can predict it.
477#[derive(Default)]
478struct OriginConsumerState {
479	pending: BTreeMap<PathOwned, PendingUpdate>,
480}
481
482impl OriginConsumerState {
483	fn apply_announce(&mut self, path: PathOwned, broadcast: broadcast::Consumer) {
484		let new = match self.pending.remove(&path) {
485			// First announce, or a stale announce being replaced.
486			None | Some(PendingUpdate::Announce(_)) => PendingUpdate::Announce(broadcast),
487			// Consumer needs to observe the unannounce before this announce.
488			Some(PendingUpdate::Unannounce | PendingUpdate::UnannounceAnnounce(_)) => {
489				PendingUpdate::UnannounceAnnounce(broadcast)
490			}
491		};
492		self.pending.insert(path, new);
493	}
494
495	fn apply_unannounce(&mut self, path: PathOwned) {
496		match self.pending.remove(&path) {
497			// Consumer has not seen the pending announce; drop both entirely.
498			Some(PendingUpdate::Announce(_)) => {}
499			None | Some(PendingUpdate::Unannounce) => {
500				self.pending.insert(path, PendingUpdate::Unannounce);
501			}
502			// The embedded announce cancels with this unannounce; the consumer still
503			// needs the leading unannounce.
504			Some(PendingUpdate::UnannounceAnnounce(_)) => {
505				self.pending.insert(path, PendingUpdate::Unannounce);
506			}
507		}
508	}
509
510	/// Take one update to deliver to the consumer, if any.
511	fn take(&mut self) -> Option<OriginAnnounce> {
512		let path = self.pending.keys().next()?.clone();
513		let broadcast = match self.pending.remove(&path).unwrap() {
514			PendingUpdate::Announce(broadcast) => Some(broadcast),
515			PendingUpdate::Unannounce => None,
516			PendingUpdate::UnannounceAnnounce(broadcast) => {
517				// Deliver the unannounce now; leave the trailing announce pending so
518				// the next take returns it for the same path.
519				self.pending.insert(path.clone(), PendingUpdate::Announce(broadcast));
520				None
521			}
522		};
523		Some(OriginAnnounce { path, broadcast })
524	}
525}
526
527#[derive(Clone)]
528struct AnnounceConsumerNotify {
529	root: PathOwned,
530	state: kio::Producer<OriginConsumerState>,
531	/// The peer this stream advertises to, when it is scoped to one (see
532	/// [`Consumer::excluding`]). Every broadcast handed out registers an
533	/// [`ExclusionGuard`] for it, which is what tells the front it is exposed to that
534	/// peer even before they subscribe.
535	exclude: Option<Origin>,
536}
537
538impl AnnounceConsumerNotify {
539	fn announce(&self, path: impl AsPath, broadcast: broadcast::Consumer, front: &kio::Producer<FrontState>) {
540		let path = path.as_path().strip_prefix(&self.root).unwrap().to_owned();
541
542		// Advertising a path to a peer exposes the front to them, so register the
543		// exclusion now rather than waiting for them to subscribe. A reflection can
544		// come back before any subscription does, and the front has to already know
545		// the route it arrives on leads to a peer we are feeding.
546		let broadcast = match self.exclude.and_then(|peer| ExclusionGuard::new(front, peer)) {
547			Some(guard) => broadcast.with_exclusion(guard),
548			None => broadcast,
549		};
550
551		self.state
552			.write()
553			.ok()
554			.expect("consumer closed")
555			.apply_announce(path, broadcast);
556	}
557
558	fn unannounce(&self, path: impl AsPath) {
559		let path = path.as_path().strip_prefix(&self.root).unwrap().to_owned();
560		self.state.write().ok().expect("consumer closed").apply_unannounce(path);
561	}
562}
563
564struct NotifyNode {
565	parent: Option<Lock<NotifyNode>>,
566
567	// Consumers that are subscribed to this node.
568	// We store a consumer ID so we can remove it easily when it closes.
569	consumers: HashMap<ConsumerId, AnnounceConsumerNotify>,
570}
571
572impl NotifyNode {
573	fn new(parent: Option<Lock<NotifyNode>>) -> Self {
574		Self {
575			parent,
576			consumers: HashMap::new(),
577		}
578	}
579
580	/// `state` is the announced front's source table, so a consumer scoped to a peer
581	/// can register its [`ExclusionGuard`] against it (see
582	/// [`AnnounceConsumerNotify::announce`]).
583	fn announce(&mut self, path: impl AsPath, broadcast: &broadcast::Consumer, state: &kio::Producer<FrontState>) {
584		for consumer in self.consumers.values() {
585			consumer.announce(path.as_path(), broadcast.clone(), state);
586		}
587
588		if let Some(parent) = &self.parent {
589			parent.lock().announce(path, broadcast, state);
590		}
591	}
592
593	fn unannounce(&mut self, path: impl AsPath) {
594		for consumer in self.consumers.values() {
595			consumer.unannounce(path.as_path());
596		}
597
598		if let Some(parent) = &self.parent {
599			parent.lock().unannounce(path);
600		}
601	}
602}
603
604/// Keeps a peer registered in [`FrontState::excluded`] for as long as it holds the
605/// shared front, so the front stays off routes that flow back through it.
606///
607/// Carried by the [`broadcast::Consumer`] handed to that peer and shared by its
608/// clones, so the registration ends when the last of them drops. A guard whose
609/// front has already closed is inert.
610pub(crate) struct ExclusionGuard {
611	state: kio::Producer<FrontState>,
612	peer: Origin,
613}
614
615impl ExclusionGuard {
616	/// Register `peer` and return the guard that releases it, or `None` if the
617	/// front is closing (nothing left to keep off a route).
618	fn new(state: &kio::Producer<FrontState>, peer: Origin) -> Option<Arc<Self>> {
619		let mut s = state.write().ok()?;
620		if s.closed {
621			return None;
622		}
623		*s.excluded.entry(peer).or_default() += 1;
624		drop(s);
625		Some(Arc::new(Self {
626			state: state.clone(),
627			peer,
628		}))
629	}
630}
631
632impl Drop for ExclusionGuard {
633	fn drop(&mut self) {
634		let Ok(mut state) = self.state.write() else { return };
635		if let std::collections::hash_map::Entry::Occupied(mut entry) = state.excluded.entry(self.peer) {
636			match entry.get() {
637				1 => drop(entry.remove()),
638				n => *entry.get_mut() = n - 1,
639			}
640		}
641	}
642}
643
644/// How a path resolves against the announce tree for one consumer.
645///
646/// `Excluded` is deliberately not folded into `Missing`: they mean opposite
647/// things to a caller holding a dynamic handler. Missing is "nobody here, go
648/// ask"; excluded is "here, but not for you", and asking a handler to route it
649/// anyway is how a split-horizon violation gets in through the back door.
650enum Resolved {
651	/// A broadcast this consumer may read: the shared front, or a single source
652	/// pinned because the front holds a route back through the requester.
653	Found(broadcast::Consumer),
654	/// The path is live, but every route to it flows through the requester.
655	Excluded,
656	/// Nothing is published at the path, or it is outside the consumer's scope.
657	Missing,
658}
659
660struct OriginNode {
661	// The origin-owned broadcast published at this node, if any (see
662	// [`Producer::create_broadcast`]).
663	broadcast: Option<OriginBroadcast>,
664
665	// Nested nodes, one level down the tree.
666	nested: HashMap<String, Lock<OriginNode>>,
667
668	// Unfortunately, to notify consumers we need to traverse back up the tree.
669	notify: Lock<NotifyNode>,
670}
671
672impl OriginNode {
673	fn new(parent: Option<Lock<NotifyNode>>) -> Self {
674		Self {
675			broadcast: None,
676			nested: HashMap::new(),
677			notify: Lock::new(NotifyNode::new(parent)),
678		}
679	}
680
681	fn leaf(&mut self, path: &Path) -> Lock<OriginNode> {
682		let (dir, rest) = path.next_part().expect("leaf called with empty path");
683
684		let next = self.entry(dir);
685		if rest.is_empty() { next } else { next.lock().leaf(&rest) }
686	}
687
688	fn entry(&mut self, dir: &str) -> Lock<OriginNode> {
689		match self.nested.get(dir) {
690			Some(next) => next.clone(),
691			None => {
692				let next = Lock::new(OriginNode::new(Some(self.notify.clone())));
693				self.nested.insert(dir.to_string(), next.clone());
694				next
695			}
696		}
697	}
698
699	/// Toggle the announce state of this leaf's broadcast, notifying consumers on
700	/// a change. The identity check keeps a stale front from toggling its
701	/// successor.
702	fn set_announced(&mut self, expect: &kio::Producer<FrontState>, announce: bool) {
703		let Some(existing) = &mut self.broadcast else { return };
704		if !existing.state.same_channel(expect) || existing.announced == announce {
705			return;
706		}
707		existing.announced = announce;
708		let path = existing.path.clone();
709		let consumer = existing.broadcast.consume();
710		let state = existing.state.clone();
711		let mut notify = self.notify.lock();
712		if announce {
713			notify.announce(&path, &consumer, &state);
714		} else {
715			notify.unannounce(&path);
716		}
717	}
718
719	fn consume(&mut self, id: ConsumerId, mut notify: AnnounceConsumerNotify) {
720		self.consume_initial(&mut notify);
721		self.notify.lock().consumers.insert(id, notify);
722	}
723
724	fn consume_initial(&mut self, notify: &mut AnnounceConsumerNotify) {
725		// Only announced (live) broadcasts replay; offline ones are reachable by
726		// exact path but never advertised.
727		if let Some(broadcast) = &self.broadcast
728			&& broadcast.announced
729		{
730			notify.announce(&broadcast.path, broadcast.broadcast.consume(), &broadcast.state);
731		}
732
733		// Recursively subscribe to all nested nodes.
734		for nested in self.nested.values() {
735			nested.lock().consume_initial(notify);
736		}
737	}
738
739	fn resolve_broadcast(&self, rest: impl AsPath, exclude: Option<Origin>) -> Resolved {
740		let rest = rest.as_path();
741
742		if let Some((dir, rest)) = rest.next_part() {
743			let Some(node) = self.nested.get(dir) else {
744				return Resolved::Missing;
745			};
746			let node = node.lock();
747			return node.resolve_broadcast(&rest, exclude);
748		}
749
750		let Some(broadcast) = self.broadcast.as_ref() else {
751			return Resolved::Missing;
752		};
753		let Some(origin) = exclude else {
754			return Resolved::Found(broadcast.broadcast.consume());
755		};
756
757		// Data-plane split horizon: never serve a requester from a source whose
758		// chain flows through them (they'd receive their own bytes back, or worse,
759		// a subscription cycle).
760		//
761		// The shared spliced front is safe only while *no* attached route is
762		// tainted for the requester: the front picks per track and re-picks on
763		// failover, so a tainted route anywhere in the table is one the front may
764		// serve them from. Checking the whole table rather than just the active
765		// route is what keeps that honest at this instant; the guard registered
766		// below keeps it honest afterwards, holding the front off a route through
767		// this peer for as long as they are reading it. Otherwise pin them to the
768		// best clean source. A pinned broadcast skips the front's re-splicing,
769		// which is fine: the requester is itself a relay (only a forwarder's origin
770		// can appear in a chain) and re-splices via its own front when the pinned
771		// source dies.
772		let state = broadcast.state.read();
773		if !state.routes.iter().any(|r| r.route.hops.contains(&origin)) {
774			drop(state);
775			let shared = broadcast.broadcast.consume();
776			return match ExclusionGuard::new(&broadcast.state, origin) {
777				Some(guard) => Resolved::Found(shared.with_exclusion(guard)),
778				// The front closed between the lookup and the registration; it
779				// serves nothing now, so there is nothing to keep off a route.
780				None => Resolved::Found(shared),
781			};
782		}
783		match state
784			.dispatch(Some(origin))
785			.and_then(|clean| state.routes.iter().find(|r| r.id == clean))
786		{
787			Some(route) => Resolved::Found(route.source.clone()),
788			None => Resolved::Excluded,
789		}
790	}
791
792	fn unconsume(&mut self, id: ConsumerId) {
793		self.notify.lock().consumers.remove(&id).expect("consumer not found");
794		if self.is_empty() {
795			//tracing::warn!("TODO: empty node; memory leak");
796			// This happens when consuming a path that is not being broadcasted.
797		}
798	}
799
800	/// Remove the broadcast at `relative` if it is `expect`, unannouncing it if
801	/// needed and pruning empty nodes on the way back up. The identity check
802	/// keeps a stale teardown from clobbering a replacement.
803	fn remove(&mut self, expect: &kio::Producer<FrontState>, relative: impl AsPath) {
804		let relative = relative.as_path();
805
806		if let Some((dir, relative)) = relative.next_part() {
807			let Some(nested) = self.nested.get(dir) else { return };
808			let nested = nested.clone();
809			let mut locked = nested.lock();
810			locked.remove(expect, &relative);
811
812			if locked.is_empty() {
813				drop(locked);
814				self.nested.remove(dir);
815			}
816		} else if let Some(existing) = &self.broadcast
817			&& existing.state.same_channel(expect)
818		{
819			let existing = self.broadcast.take().expect("checked above");
820			if existing.announced {
821				self.notify.lock().unannounce(&existing.path);
822			}
823		}
824	}
825
826	fn is_empty(&self) -> bool {
827		self.broadcast.is_none() && self.nested.is_empty() && self.notify.lock().consumers.is_empty()
828	}
829}
830
831#[derive(Clone)]
832struct OriginNodes {
833	nodes: Vec<(PathOwned, Lock<OriginNode>)>,
834}
835
836impl OriginNodes {
837	// Returns nested roots that match the prefixes.
838	// PathPrefixes guarantees no duplicates or overlapping prefixes.
839	pub fn select(&self, prefixes: &PathPrefixes) -> Option<Self> {
840		let mut roots = Vec::new();
841
842		for (root, state) in &self.nodes {
843			for prefix in prefixes {
844				if root.has_prefix(prefix) {
845					// Keep the existing node if we're allowed to access it.
846					roots.push((root.to_owned(), state.clone()));
847					continue;
848				}
849
850				if let Some(suffix) = prefix.strip_prefix(root) {
851					// If the requested prefix is larger than the allowed prefix, then we further scope it.
852					let nested = state.lock().leaf(&suffix);
853					roots.push((prefix.to_owned(), nested));
854				}
855			}
856		}
857
858		if roots.is_empty() {
859			None
860		} else {
861			Some(Self { nodes: roots })
862		}
863	}
864
865	pub fn root(&self, new_root: impl AsPath) -> Option<Self> {
866		let new_root = new_root.as_path();
867		let mut roots = Vec::new();
868
869		if new_root.is_empty() {
870			return Some(self.clone());
871		}
872
873		for (root, state) in &self.nodes {
874			if let Some(suffix) = root.strip_prefix(&new_root) {
875				// If the old root is longer than the new root, shorten the keys.
876				roots.push((suffix.to_owned(), state.clone()));
877			} else if let Some(suffix) = new_root.strip_prefix(root) {
878				// If the new root is longer than the old root, add a new root.
879				// NOTE: suffix can't be empty
880				let nested = state.lock().leaf(&suffix);
881				roots.push(("".into(), nested));
882			}
883		}
884
885		if roots.is_empty() {
886			None
887		} else {
888			Some(Self { nodes: roots })
889		}
890	}
891
892	// Returns the root that has this prefix.
893	pub fn get(&self, path: impl AsPath) -> Option<(Lock<OriginNode>, PathOwned)> {
894		let path = path.as_path();
895
896		for (root, state) in &self.nodes {
897			if let Some(suffix) = path.strip_prefix(root) {
898				return Some((state.clone(), suffix.to_owned()));
899			}
900		}
901
902		None
903	}
904}
905
906impl Default for OriginNodes {
907	fn default() -> Self {
908		Self {
909			nodes: vec![("".into(), Lock::new(OriginNode::new(None)))],
910		}
911	}
912}
913
914/// A path and the broadcast now available there, delivered by [`AnnounceConsumer`].
915#[derive(Clone)]
916pub struct OriginAnnounce {
917	/// The path of the broadcast, relative to the consuming cursor's root.
918	pub path: PathOwned,
919	/// The broadcast now available at that path, or `None` if it is no longer available.
920	///
921	/// A replacement (a relay failover, or a shorter hop path arriving) is delivered as a
922	/// `None` followed by a `Some`, never as a swap in place. A route change alone is invisible here (the handles stay
923	/// valid); observe it via [`broadcast::Consumer::route_changed`].
924	pub broadcast: Option<broadcast::Consumer>,
925}
926
927/// Announces broadcasts to consumers over the network.
928#[derive(Clone)]
929pub struct Producer {
930	// Identity for this origin. Appended to broadcast hops when
931	// re-announcing so downstream relays can detect loops and prefer the
932	// shortest path.
933	info: Origin,
934
935	// The roots of the tree that we are allowed to publish.
936	// A path of "" means we can publish anything.
937	nodes: OriginNodes,
938
939	// The prefix that is automatically stripped from all paths.
940	root: PathOwned,
941
942	// Fallback request queue, shared with every derived consumer. Separate from
943	// `nodes` because dynamic broadcasts are never announced: they only resolve a
944	// consumer's `request_broadcast` when no live announcement exists.
945	dynamic: kio::Shared<OriginDynamicState>,
946
947	// The cache pool inherited by broadcasts created under this origin (sessions
948	// mint their remote broadcasts with it). Unbounded by default.
949	pool: cache::Pool,
950
951	// Retention ceiling inherited by broadcasts created under this origin (see
952	// [`Info::cache_duration`]). `Duration::MAX` (no ceiling) by default.
953	cache_duration: Duration,
954
955	// Retention window for a track whose publisher advertises none (see
956	// [`Info::latency_default`]).
957	latency_default: Duration,
958
959	// How long a broadcast outlives ungracefully losing its last source (see
960	// [`Info::linger`]). Zero by default.
961	linger: Duration,
962
963	// Ingress stats context. Broadcasts created through this producer are attributed
964	// to it (writes counted on the subscriber/ingress side). Empty (no-op) unless a
965	// session tagged this handle via [`Self::with_stats`].
966	stats: stats::Session,
967}
968
969impl std::ops::Deref for Producer {
970	type Target = Origin;
971
972	fn deref(&self) -> &Self::Target {
973		&self.info
974	}
975}
976
977impl Producer {
978	/// Build a producer from an [`Info`] (identity + cache pool) with no scoped
979	/// prefix and no pre-existing broadcasts. Prefer [`Info::produce`] /
980	/// [`Origin::produce`].
981	pub fn new(info: Info) -> Self {
982		Self {
983			info: info.id,
984			nodes: OriginNodes::default(),
985			root: PathOwned::default(),
986			dynamic: kio::Shared::default(),
987			pool: info.pool,
988			cache_duration: info.cache_duration,
989			latency_default: info.latency_default,
990			linger: info.linger,
991			stats: stats::Session::default(),
992		}
993	}
994
995	/// Attach an ingress stats context: broadcasts created through this handle (and
996	/// any handle derived from it) are attributed to `session` on the subscriber
997	/// (ingress) side. Pass [`stats::Session::default`] to opt out.
998	pub fn with_stats(mut self, session: stats::Session) -> Self {
999		self.stats = session;
1000		self
1001	}
1002
1003	/// Set the linger (see [`Info::linger`]) for broadcasts created through this
1004	/// handle and any handle derived from it.
1005	///
1006	/// A broadcast adopts the window of the handle whose source *created* it (the
1007	/// first source at the path), so set this before handing the producer to
1008	/// whatever attaches sources through it (e.g. a session). Lets one supplier
1009	/// declare its own recovery promise, like a reconnecting client lingering for
1010	/// as long as its retry loop keeps trying, without reconfiguring the origin.
1011	pub fn with_linger(mut self, linger: Duration) -> Self {
1012		self.linger = linger;
1013		self
1014	}
1015
1016	/// This origin's [`Info`] (identity + cache pool), the parent handle a broadcast
1017	/// created under this origin carries (see [`broadcast::Info::origin`]).
1018	pub fn info(&self) -> Info {
1019		Info {
1020			id: self.info,
1021			pool: self.pool.clone(),
1022			cache_duration: self.cache_duration,
1023			latency_default: self.latency_default,
1024			linger: self.linger,
1025		}
1026	}
1027
1028	// The retention window for a track whose publisher advertises none (see
1029	// [`Info::latency_default`]). Cheaper than `info()`, which clones the pool.
1030	pub(crate) fn latency_default(&self) -> Duration {
1031		self.latency_default
1032	}
1033
1034	/// A producer with *no* allowed prefixes: it can't publish anything and
1035	/// advertises no subscribe interest (its `allowed()` is empty, so the
1036	/// subscriber issues no ANNOUNCE_PLEASE). Used to fill an unset session half
1037	/// so both the publisher and subscriber loops still run.
1038	pub(crate) fn empty(info: Origin) -> Self {
1039		Self {
1040			info,
1041			nodes: OriginNodes { nodes: Vec::new() },
1042			root: PathOwned::default(),
1043			dynamic: kio::Shared::default(),
1044			pool: cache::Pool::default(),
1045			cache_duration: Duration::MAX,
1046			latency_default: track::DEFAULT_LATENCY_MAX,
1047			linger: Duration::ZERO,
1048			stats: stats::Session::default(),
1049		}
1050	}
1051
1052	/// Create a broadcast at `path`, fed through the returned producer.
1053	///
1054	/// This is the sole way content enters an origin. The returned
1055	/// [`broadcast::Producer`] is a route source: the origin owns the broadcast
1056	/// consumers actually see, and splices its tracks across every source created
1057	/// at the same path (other local publishers, or sessions attaching announces
1058	/// from the network), always serving from the best [`broadcast::Route`] (live
1059	/// first, then lowest cost, then shortest hops with a deterministic
1060	/// tie-break, and the newest source among otherwise equal routes). When the
1061	/// best source changes, tracks resume from the replacement at the first
1062	/// missing group; consumers never observe the swap.
1063	///
1064	/// Splicing requires the same content identity: every source at a path must
1065	/// share the first hop of its route, which is a promise that they produce
1066	/// interchangeable tracks. An *announced* source arriving with a different
1067	/// first hop is a replacement instead: it takes the path immediately and
1068	/// consumers see an unannounce followed by an announce, rather than unrelated
1069	/// content spliced into a live subscription. So a publisher reconnecting
1070	/// under a fresh identity displaces the session it replaced right away,
1071	/// without waiting for the transport to notice the old one is gone. An
1072	/// offline source never displaces anything: it ranks below every announced
1073	/// route, so it waits invisibly for the incumbent to end.
1074	///
1075	/// `route` is the source's initial metadata; update it with
1076	/// [`broadcast::Producer::set_route`]. The [`broadcast::Route::announce`] flag
1077	/// controls whether the path is announced: a non-live broadcast is invisible
1078	/// to [`Consumer::announced`] but stays reachable by exact path for
1079	/// subscribes and fetches (e.g. serving cached or on-demand content), so
1080	/// toggling `live` announces or unannounces without touching the broadcast.
1081	///
1082	/// The broadcast becomes visible to consumers asynchronously, shortly after
1083	/// this returns. Create tracks and register a
1084	/// [`broadcast::Producer::dynamic`] handler before awaiting, so the first
1085	/// consumer finds them.
1086	///
1087	/// End the broadcast with [`broadcast::Producer::finish`]; dropping it
1088	/// without finishing also works, but logs a warning. A finish closes and
1089	/// unannounces the path immediately once it was the last source. An unfinished
1090	/// drop is treated as an outage: the path survives for the origin's
1091	/// [`Info::linger`] (zero by default), so a replacement source attaching within
1092	/// that window splices in without consumers noticing.
1093	///
1094	/// Fails with [`Error::Unauthorized`] if `path` is outside the prefixes this
1095	/// producer may publish under (after [`scope`](Self::scope) /
1096	/// [`with_root`](Self::with_root)), or [`Error::BoundsExceeded`] if the full
1097	/// rooted path exceeds [`Path::MAX_PARTS`]. Must be called with a runtime
1098	/// available (it spawns the broadcast's lifecycle task). Callers must not use
1099	/// a route whose hop chain contains this origin's id (it would form a routing
1100	/// loop); relays filter such reflections before they reach here, checked by a
1101	/// `debug_assert`.
1102	pub fn create_broadcast(&self, path: impl AsPath, route: broadcast::Route) -> Result<broadcast::Producer, Error> {
1103		let path = path.as_path();
1104
1105		debug_assert!(
1106			!route.hops.contains(&self.info),
1107			"create_broadcast called with a looping hop chain",
1108		);
1109
1110		let (node, rest) = self.nodes.get(&path).ok_or(Error::Unauthorized)?;
1111		let full = self.root.join(&path).to_owned();
1112
1113		// A decoded announce prefix and suffix are each within the wire limit, but their
1114		// join might not be. Enforcing here bounds the tree depth and guarantees the path
1115		// can be re-encoded when forwarded.
1116		if full.parts().count() > Path::MAX_PARTS {
1117			return Err(BoundsExceeded.into());
1118		}
1119
1120		// Resolve the ingress counters once, keyed by the absolute broadcast path.
1121		// The source producer tags its tracks; run_source drives the announce guard
1122		// off route transitions.
1123		let ingress = self.stats.ingress(&full);
1124
1125		let mut source = broadcast::Info { origin: self.info() }
1126			.produce()
1127			.with_stats(ingress.clone());
1128		source.set_route(route).expect("fresh producer");
1129
1130		web_async::spawn(run_source(self.info(), node, full, rest, source.consume(), ingress));
1131
1132		Ok(source)
1133	}
1134
1135	/// Returns a new Producer restricted to publishing under one of `prefixes`.
1136	///
1137	/// Returns None if there are no legal prefixes (the requested prefixes are
1138	/// disjoint from this producer's current scope).
1139	// TODO accept PathPrefixes instead of &[Path]
1140	pub fn scope(&self, prefixes: &[Path]) -> Option<Producer> {
1141		let prefixes = PathPrefixes::new(prefixes);
1142		Some(Producer {
1143			info: self.info,
1144			nodes: self.nodes.select(&prefixes)?,
1145			root: self.root.clone(),
1146			dynamic: self.dynamic.clone(),
1147			pool: self.pool.clone(),
1148			cache_duration: self.cache_duration,
1149			latency_default: self.latency_default,
1150			linger: self.linger,
1151			stats: self.stats.clone(),
1152		})
1153	}
1154
1155	/// Create a dynamic handler that picks up [`Consumer::request_broadcast`]
1156	/// calls for paths that are not announced.
1157	///
1158	/// This is the origin-level analogue of [`broadcast::Producer::dynamic`]: it serves
1159	/// broadcasts on demand rather than tracks. Crucially the served broadcasts are
1160	/// *not* announced, so [`Consumer::announced`] never sees them; they exist
1161	/// only as a fallback for a consumer that asks for an exact path with no live
1162	/// announcement. Drop the handler (and every clone) to reject pending requests.
1163	pub fn dynamic(&self) -> Dynamic {
1164		Dynamic::new(self.info, self.root.clone(), self.dynamic.clone())
1165	}
1166
1167	/// Cheap read handle over this origin's broadcast tree.
1168	///
1169	/// Use [`Consumer::announced`] to register interest and start receiving
1170	/// announcement events; the consumer itself does not allocate any channels.
1171	pub fn consume(&self) -> Consumer {
1172		// Untagged: a session tags the egress consumer separately via
1173		// `origin::Consumer::with_stats` (ingress and egress are distinct sides).
1174		Consumer::new(
1175			self.info,
1176			self.root.clone(),
1177			self.nodes.clone(),
1178			self.dynamic.clone(),
1179			stats::Session::default(),
1180		)
1181	}
1182
1183	/// Handle to the announcement stream for this producer's subtree.
1184	///
1185	/// Symmetric counterpart to [`Self::consume`]; call
1186	/// [`AnnounceProducer::consume`] to get an [`AnnounceConsumer`] that
1187	/// receives announce / unannounce events.
1188	pub fn announces(&self) -> AnnounceProducer {
1189		AnnounceProducer::new(self.root.clone(), self.nodes.clone())
1190	}
1191
1192	/// Returns a new Producer that automatically strips out the provided prefix.
1193	///
1194	/// Returns None if the provided root is not authorized; when [`Self::scope`]
1195	/// was already used without a wildcard.
1196	pub fn with_root(&self, prefix: impl AsPath) -> Option<Self> {
1197		let prefix = prefix.as_path();
1198
1199		Some(Self {
1200			info: self.info,
1201			root: self.root.join(&prefix).to_owned(),
1202			nodes: self.nodes.root(&prefix)?,
1203			dynamic: self.dynamic.clone(),
1204			pool: self.pool.clone(),
1205			cache_duration: self.cache_duration,
1206			latency_default: self.latency_default,
1207			linger: self.linger,
1208			stats: self.stats.clone(),
1209		})
1210	}
1211
1212	/// Returns the root that is automatically stripped from all paths.
1213	pub fn root(&self) -> &Path<'_> {
1214		&self.root
1215	}
1216
1217	/// Iterate over the path prefixes this handle is permitted to publish or subscribe under.
1218	// TODO return PathPrefixes
1219	pub fn allowed(&self) -> impl Iterator<Item = &Path<'_>> {
1220		self.nodes.nodes.iter().map(|(root, _)| root)
1221	}
1222
1223	/// Converts a relative path to an absolute path.
1224	pub fn absolute(&self, path: impl AsPath) -> Path<'_> {
1225		self.root.join(path)
1226	}
1227}
1228
1229/// How long a spliced track stays warm after its last reader leaves.
1230///
1231/// Within the window a returning viewer, or the next of a run of back-to-back
1232/// fetches, reuses the source's copy: no new track request, and no second round
1233/// trip for its `TRACK_INFO`. After it, the copy is released so an idle track
1234/// costs nothing upstream.
1235///
1236/// Sized above the fetch cadence of a segmented consumer: HLS polls every
1237/// `TARGETDURATION` seconds, commonly 6 or 10, so a shorter window would drop the
1238/// copy between every segment and re-request the track each time. A warm copy
1239/// holds no upstream subscription (that is canceled as soon as demand ends), so
1240/// waiting longer costs cached state, not a viewer.
1241const TRACK_IDLE_LINGER: Duration = Duration::from_secs(30);
1242
1243/// One attached source in a [`FrontState`] table.
1244struct FrontRoute {
1245	id: u64,
1246	/// The source's latest [`broadcast::Route`], mirrored from its
1247	/// `route_changed` stream; picks the active source and gates the announce.
1248	route: broadcast::Route,
1249	/// The source broadcast tracks are served from.
1250	source: broadcast::Consumer,
1251}
1252
1253/// Shared state behind a [`Front`]: the attached sources and which one is active.
1254struct FrontState {
1255	/// Absolute path of the broadcast, mixed into the route tie-break hash.
1256	path: PathOwned,
1257	/// The local origin's identity, the other half of the handover key gate.
1258	self_origin: Origin,
1259	/// Content identity: the original publisher (first hop) shared by every
1260	/// attached source, or `None` for a broadcast produced locally (no hops).
1261	/// Fixed for the front's lifetime; a source with a different first hop is new
1262	/// content, not an alternate route, so it replaces this front (or waits for
1263	/// it, when offline) rather than joining it (see [`attach_source`]). This is
1264	/// the same rule the session layer applies to a restart whose first hop
1265	/// changed.
1266	publisher: Option<Origin>,
1267	/// Attach counter, handed to each [`FrontRoute`] so [`route_order`] can break
1268	/// an exact tie toward the newest source.
1269	next_route: u64,
1270	routes: Vec<FrontRoute>,
1271	/// Peers this front is exposed to, refcounted by live [`ExclusionGuard`]s: those
1272	/// reading it through the shared broadcast, and those we merely advertise it to.
1273	/// The resolve-time check only proves the table is clean for a requester at that
1274	/// instant; the front picks per track and re-picks on failover, so without this a
1275	/// route tainted for an attached peer could be adopted underneath them and hand
1276	/// them back their own bytes. Routes through these origins are avoided while any
1277	/// clean alternative exists.
1278	///
1279	/// Advertising registers a peer too, because a peer that cannot echo our identity
1280	/// back (moq-transport carries no hop ids) may re-advertise the path to us before
1281	/// it ever subscribes. That reflection is otherwise indistinguishable from a rival
1282	/// publisher, and this is what tells [`attach_source`] apart.
1283	excluded: HashMap<Origin, usize>,
1284	/// The source tracks are dispatched to. Backups park until promoted.
1285	active: Option<u64>,
1286	/// How long the front outlives ungracefully losing its last source (see
1287	/// [`Info::linger`]). [`run_front`] arms the countdown when the table empties.
1288	linger: Duration,
1289	/// Terminal: no more sources may attach and every poller stops. Set
1290	/// synchronously by the detach that empties the table or by an
1291	/// [`attach_source`] takeover, and by [`run_front`] when the linger window
1292	/// expires without a replacement.
1293	closed: bool,
1294}
1295
1296impl FrontState {
1297	/// The one selection primitive every picker goes through: the best route by
1298	/// [`route_order`] among those surviving `keep`. With `untainted`, the pick
1299	/// also steers away from routes that flow through a peer currently reading
1300	/// the shared front, unless that leaves nothing (see
1301	/// [`Self::prefer_untainted`]); it is off for [`Self::dispatch`], which pins
1302	/// one requester to one source rather than serving the shared front.
1303	fn pick(&self, keep: impl Fn(&FrontRoute) -> bool, untainted: bool) -> Option<u64> {
1304		let candidates: Vec<&FrontRoute> = self.routes.iter().filter(|r| keep(r)).collect();
1305		let candidates = match untainted {
1306			true => self.prefer_untainted(&candidates),
1307			false => candidates,
1308		};
1309		candidates
1310			.into_iter()
1311			.min_by_key(|r| route_order(&self.path.as_path(), r))
1312			.map(|r| r.id)
1313	}
1314
1315	/// The source new track requests should dispatch to: live first, then lowest
1316	/// cost, then shortest hop chain with a deterministic hash tie-break and the
1317	/// newest source last, skipping routes that flow through a peer currently
1318	/// reading the front while any other route remains.
1319	fn best_route(&self) -> Option<u64> {
1320		self.pick(|_| true, true)
1321	}
1322
1323	/// The source a subscription from `exclude` should dispatch to: the best
1324	/// route whose hop chain does not contain the requester. This is the same
1325	/// selection a session uses to pick what it announces to that peer, and the
1326	/// two being one computation is the loop-freedom invariant: chains stay
1327	/// truthful, so any would-be cycle surfaces the requester's own origin in
1328	/// the candidate chain and is filtered here, at any cycle length.
1329	fn dispatch(&self, exclude: Option<Origin>) -> Option<u64> {
1330		self.pick(|r| exclude.is_none_or(|origin| !r.route.hops.contains(&origin)), false)
1331	}
1332
1333	/// Whether `route` flows back through a peer this front is exposed to, so serving
1334	/// (or attaching) it would hand that peer its own bytes back.
1335	///
1336	/// Doubles as the reflection test in [`attach_source`]: a route arriving through a
1337	/// peer we are already advertising this path to is our own broadcast coming home,
1338	/// whatever its chain claims.
1339	fn taints_a_reader(&self, route: &broadcast::Route) -> bool {
1340		route.hops.iter().any(|hop| self.excluded.contains_key(hop))
1341	}
1342
1343	/// Narrow `candidates` to the routes clean for every peer currently reading the
1344	/// shared front, unless that would leave nothing.
1345	///
1346	/// Keeping the front off a tainted route is what makes the resolve-time
1347	/// split-horizon check hold for the life of a subscription rather than just at
1348	/// request time. Falling back when every route is tainted is deliberate: the
1349	/// alternative is starving readers the route is perfectly good for, and a peer
1350	/// whose only path runs back through itself has nothing to be served from
1351	/// anyway. It re-resolves to [`Error::Unroutable`] on its next request.
1352	fn prefer_untainted<'a>(&self, candidates: &[&'a FrontRoute]) -> Vec<&'a FrontRoute> {
1353		if self.excluded.is_empty() {
1354			return candidates.to_vec();
1355		}
1356		let clean: Vec<&FrontRoute> = candidates
1357			.iter()
1358			.copied()
1359			.filter(|r| !self.taints_a_reader(&r.route))
1360			.collect();
1361		match clean.is_empty() {
1362			true => candidates.to_vec(),
1363			false => clean,
1364		}
1365	}
1366
1367	/// The source one track should be served from: the front's active source
1368	/// unless `skip` rules it out, then the next-best route that survives.
1369	///
1370	/// Whether a source carries a given track is a per-track property (a standby
1371	/// that has not created it yet, a publisher whose encoder is still starting),
1372	/// so a source refusing one track is ruled out of that track only, never out
1373	/// of the front. Preferring `active` keeps a servable track on exactly the
1374	/// route [`Self::reselect`] chose, handover gate included.
1375	fn serve_route(&self, skip: impl Fn(u64) -> bool) -> Option<u64> {
1376		if let Some(active) = self.active
1377			&& !skip(active)
1378			&& let Some(route) = self.routes.iter().find(|r| r.id == active)
1379			&& !self.taints_a_reader(&route.route)
1380		{
1381			return Some(active);
1382		}
1383		self.pick(|r| !skip(r.id), true)
1384	}
1385
1386	/// Re-pick the active source after the table changed. Serve tasks watch
1387	/// `active` and re-splice on their own, so a cheaper route takes over
1388	/// seamlessly at a group boundary.
1389	///
1390	/// The one exception is the simultaneous-activation race: two nodes that
1391	/// each pulled the broadcast before seeing the other both advertise zero
1392	/// cost, so each sees the other as cheaper than its own source, and
1393	/// re-parenting onto each other at once leaves the broadcast with no
1394	/// upstream at all. That hazard only exists when both sides are actively
1395	/// carrying, so the gate is scoped to exactly that: while `carrying` (the
1396	/// front has live demand), a cheaper route whose announcing relay is itself
1397	/// carrying (it advertised zero from a chain of two or more hops; a chain of
1398	/// one is the original publisher, which can never adopt a route to its own
1399	/// broadcast) displaces an announced incumbent only when
1400	/// [`Self::handover_allowed`] says so. Every other cheaper route, e.g. a
1401	/// forwarder path or an upstream that repriced itself down, is taken
1402	/// immediately.
1403	fn reselect(&mut self, carrying: bool) {
1404		let best = self.best_route();
1405		if carrying
1406			&& let (Some(best_id), Some(cur_id)) = (best, self.active)
1407			&& best_id != cur_id
1408			&& let Some(candidate) = self.routes.iter().find(|r| r.id == best_id)
1409			&& let Some(incumbent) = self.routes.iter().find(|r| r.id == cur_id)
1410			&& incumbent.route.announce
1411			&& candidate.route.cost < incumbent.route.cost
1412			&& candidate.route.advertised == 0
1413			&& candidate.route.hops.len() >= 2
1414			&& !self.handover_allowed(&candidate.route)
1415		{
1416			// We won the key comparison: keep our source and let the peer come to us.
1417			return;
1418		}
1419		self.active = best;
1420	}
1421
1422	/// Whether re-parenting onto `route` is allowed while actively carrying: the
1423	/// announcing peer (the chain's last hop) must hash strictly below our own
1424	/// origin for this broadcast name.
1425	///
1426	/// Both sides compute the same two keys (the hash is build-stable and the
1427	/// inputs are shared), so the comparison resolves the same way everywhere:
1428	/// the lower-keyed node keeps its source, the higher-keyed one re-parents.
1429	/// A strict total order has no cycles, so mutual pulls cannot happen. Mixing
1430	/// the broadcast name in spreads ownership across a region's relays instead
1431	/// of funneling every broadcast onto the lowest-keyed one. A route with no
1432	/// hops is a local publish and always allowed.
1433	fn handover_allowed(&self, route: &broadcast::Route) -> bool {
1434		let name = self.path.as_path();
1435		match route.hops.iter().last() {
1436			Some(peer) => fnv_key(&name, [*peer]) < fnv_key(&name, [self.self_origin]),
1437			None => true,
1438		}
1439	}
1440
1441	/// Every attached route in preference order with the active one first,
1442	/// mirrored onto the front's broadcast so sessions can advertise (and be
1443	/// served) a different route per peer. The active route leads even when the
1444	/// handover gate kept it over a lower-ordered candidate, so `routes[0]` is
1445	/// always what this node is actually serving from.
1446	fn routes_snapshot(&self) -> Vec<broadcast::Route> {
1447		let mut routes: Vec<&FrontRoute> = self.routes.iter().collect();
1448		routes.sort_by_key(|r| route_order(&self.path.as_path(), r));
1449		routes.sort_by_key(|r| Some(r.id) != self.active);
1450		routes.into_iter().map(|r| r.route.clone()).collect()
1451	}
1452}
1453
1454/// Refresh the front's public face after a table change: advertise the best
1455/// source's route on the spliced broadcast and gate the path's announcement on
1456/// its `live` flag.
1457///
1458/// Re-reads the table at apply time (rather than applying a value computed under
1459/// an earlier lock) so concurrent attach/detach/update calls converge on the
1460/// latest winner regardless of the order their applies land in. An empty table
1461/// leaves the advert and announce state alone; the front task is closing and
1462/// unannounces on its way out.
1463fn sync_front(state: &kio::Producer<FrontState>, broadcast: &broadcast::Producer, leaf: &Lock<OriginNode>) {
1464	// Snapshot and apply under the leaf lock: two concurrent syncs would
1465	// otherwise race their applies, letting a stale snapshot land last and
1466	// leave the announce flag (or advert) contradicting the current table.
1467	// Lock order (leaf, then table, then broadcast) matches attach_source.
1468	let mut leaf_guard = leaf.lock();
1469	let routes = state.read().routes_snapshot();
1470	if let Some(advert) = routes.first() {
1471		let announce = advert.announce;
1472		broadcast.clone().set_routes(routes);
1473		leaf_guard.set_announced(state, announce);
1474	}
1475}
1476
1477/// Detach source `id`, promoting the next-best source; the tracks it was serving
1478/// re-splice on their own. Idempotent.
1479///
1480/// `graceful` says how the source ended: a deliberate finish (a publisher done
1481/// publishing, a peer's clean unannounce) or an abrupt loss (a session dying).
1482/// Detaching the last source *gracefully* closes the broadcast synchronously,
1483/// which guarantees a following create at the path is a *new* broadcast rather
1484/// than splicing new content into this one. An abrupt last detach instead leaves
1485/// the front open for the configured linger ([`Info::linger`]), so a source
1486/// re-attaching within the window (a reconnect) splices in seamlessly;
1487/// [`run_front`] closes it if the window expires empty. A zero linger closes
1488/// abrupt detaches synchronously too.
1489fn detach_source(
1490	state: &kio::Producer<FrontState>,
1491	broadcast: &broadcast::Producer,
1492	leaf: &Lock<OriginNode>,
1493	id: u64,
1494	graceful: bool,
1495) {
1496	let close = {
1497		// Snapshotted before the state lock (lock order: broadcast, then front).
1498		// A demand flip in between only stales this reselect's handover gate,
1499		// which self-corrects on the next table change.
1500		let carrying = broadcast.demand().is_used();
1501		let Ok(mut s) = state.write() else { return };
1502		let Some(pos) = s.routes.iter().position(|r| r.id == id) else {
1503			return;
1504		};
1505		s.routes.remove(pos);
1506		s.reselect(carrying);
1507		if s.routes.is_empty() && !s.closed && (graceful || s.linger.is_zero()) {
1508			// Last one out: close now. The front task observes `closed` and
1509			// finishes the teardown (unpublish).
1510			s.closed = true;
1511			true
1512		} else {
1513			false
1514		}
1515	};
1516	if close {
1517		broadcast.abort_spliced(Error::Dropped);
1518	}
1519	sync_front(state, broadcast, leaf);
1520}
1521
1522/// Match the ingress announce guard to a route's announce flag: opening bumps
1523/// the announced counters, dropping bumps the closed ones. See [`run_source`].
1524fn sync_announce(guard: &mut Option<stats::Announce>, announced: bool, ingress: &stats::Scope) {
1525	match (announced, guard.is_some()) {
1526		(true, false) => *guard = Some(ingress.announce()),
1527		(false, true) => *guard = None,
1528		_ => {}
1529	}
1530}
1531
1532/// Owns one source's lifecycle: attaches it to the front at its path on the first
1533/// route observation, forwards route updates, and detaches it when the source
1534/// closes. Spawned by [`Producer::create_broadcast`].
1535///
1536/// An announced source whose original publisher (first hop) differs from the
1537/// live front's takes the path over as a fresh broadcast rather than joining; an
1538/// offline one parks until the front closes. A route update that changes the
1539/// source's own first hop likewise detaches it and re-runs the attach, so a
1540/// publisher swap is always a replacement, never a silent splice.
1541async fn run_source(
1542	origin: Info,
1543	node: Lock<OriginNode>,
1544	full: PathOwned,
1545	rest: PathOwned,
1546	mut source: broadcast::Consumer,
1547	ingress: stats::Scope,
1548) {
1549	let ctx = AttachContext {
1550		origin: &origin,
1551		node: &node,
1552		full: &full,
1553		rest: &rest,
1554	};
1555
1556	// The first `route_changed` yields the current route immediately; nothing is
1557	// visible to consumers until this attach, giving the creator a window to set
1558	// up tracks and dynamic handlers.
1559	let Ok(mut route) = source.route_changed().await else {
1560		// Closed before ever attaching; nothing became visible.
1561		return;
1562	};
1563
1564	// Ingress announce guard: held while this source's route is announced. Opening
1565	// bumps `announced` + `announced_bytes`; dropping (route offline, or the source
1566	// closing below) bumps `announced_closed` + `announced_bytes`. Empty scope =
1567	// no-op.
1568	let mut announce = route.announce.then(|| ingress.announce());
1569
1570	'attach: loop {
1571		// Re-resolved every attempt: between attaches the previous front's
1572		// teardown may have pruned the (then-empty) leaf from the tree, and
1573		// attaching to the stale lock would publish into an orphan that lookups
1574		// can no longer reach.
1575		let leaf = if rest.is_empty() {
1576			node.clone()
1577		} else {
1578			node.lock().leaf(&rest)
1579		};
1580
1581		let (state, broadcast, id) = match attach_source(&ctx, &leaf, &source, route.clone()) {
1582			Attach::Ready(state, broadcast, id) => (state, broadcast, id),
1583			Attach::Parked(incumbent) => {
1584				tracing::debug!(
1585					broadcast = %full,
1586					"path already live with a different publisher; parking this source until it ends",
1587				);
1588				// Wait for the incumbent front to close, or for our own route to
1589				// change: announcing ourselves is what earns the takeover, and our
1590				// source closing means giving up.
1591				let update = kio::wait(|waiter| {
1592					if let Poll::Ready(update) = source.poll_route_changed(waiter) {
1593						return Poll::Ready(Some(update));
1594					}
1595					// Ready on either the closed flag or the channel itself dying;
1596					// both mean the incumbent is gone.
1597					match incumbent.poll(waiter, |s| if s.closed { Poll::Ready(()) } else { Poll::Pending }) {
1598						Poll::Ready(_) => Poll::Ready(None),
1599						Poll::Pending => Poll::Pending,
1600					}
1601				})
1602				.await;
1603				match update {
1604					// Our route moved; recompute the guard and retry with it.
1605					Some(Ok(update)) => {
1606						sync_announce(&mut announce, update.announce, &ingress);
1607						route = update;
1608					}
1609					// The source closed while parked; it was never visible.
1610					Some(Err(_)) => return,
1611					// The incumbent is gone; retry, creating a fresh front.
1612					None => {}
1613				}
1614				continue 'attach;
1615			}
1616		};
1617		let publisher = route.hops.iter().next().copied();
1618
1619		loop {
1620			match source.route_changed().await {
1621				Ok(update) => {
1622					let announced = update.announce;
1623					// A different first hop is new content: this source can no
1624					// longer feed the front it attached to. Detach deliberately
1625					// (a linger would only stall the replacement) and re-attach.
1626					//
1627					// Plain equality, not `same_publisher`: within one source
1628					// handle the session layer already guarantees continuity (it
1629					// replaces the handle when identity breaks, UNKNOWN restarts
1630					// included), so this only catches a caller moving a live
1631					// handle to a new publisher. An UNKNOWN-to-UNKNOWN metadata
1632					// update (a legacy peer repricing) must not detach.
1633					if update.hops.iter().next().copied() != publisher {
1634						detach_source(&state, &broadcast, &leaf, id, true);
1635						sync_announce(&mut announce, announced, &ingress);
1636						route = update;
1637						continue 'attach;
1638					}
1639					{
1640						let carrying = broadcast.demand().is_used();
1641						let Ok(mut s) = state.write() else { return };
1642						let Some(entry) = s.routes.iter_mut().find(|r| r.id == id) else {
1643							return;
1644						};
1645						if entry.route == update {
1646							continue;
1647						}
1648						entry.route = update;
1649						s.reselect(carrying);
1650					}
1651					// Toggle the ingress announce guard on a live/offline transition.
1652					sync_announce(&mut announce, announced, &ingress);
1653					sync_front(&state, &broadcast, &leaf);
1654				}
1655				Err(_) => {
1656					// A deliberate finish closes the front immediately; an abrupt loss
1657					// (dropped producer, dead session) may linger for a replacement.
1658					detach_source(&state, &broadcast, &leaf, id, source.is_finished());
1659					return;
1660				}
1661			}
1662		}
1663	}
1664}
1665
1666/// The outcome of [`attach_source`].
1667enum Attach {
1668	/// The source joined (or created) the front at its path, yielding the shared
1669	/// source table, the spliced broadcast, and the source's table id.
1670	Ready(kio::Producer<FrontState>, broadcast::Producer, u64),
1671	/// The path's live front belongs to a different original publisher and this
1672	/// source may not take it: either the source is offline (so it would rank below
1673	/// every route the front holds) or its chain leads back through a peer the front
1674	/// is already exposed to, making it a reflection rather than rival content. The
1675	/// caller parks on the returned table until the front closes.
1676	Parked(kio::Producer<FrontState>),
1677}
1678
1679/// Everything about a source's attach that does not change between attempts.
1680struct AttachContext<'a> {
1681	origin: &'a Info,
1682	node: &'a Lock<OriginNode>,
1683	/// Absolute path, for the front's identity and log lines.
1684	full: &'a PathOwned,
1685	/// Path relative to `node`, for locating (and later pruning) the leaf.
1686	rest: &'a PathOwned,
1687}
1688
1689/// Whether two sources carry the same content and may therefore splice.
1690///
1691/// [`Origin::UNKNOWN`] identifies nothing: it is what a peer that declared no
1692/// identity, or that does not speak the hops extension at all, contributes as a
1693/// first hop. Two such sources are not interchangeable even though their first
1694/// hops compare equal, so splicing them would cut one publisher's subscribers
1695/// over to an unrelated publisher's content. Every other id compares normally,
1696/// including `None` for a locally produced broadcast with no hops.
1697fn same_publisher(a: Option<Origin>, b: Option<Origin>) -> bool {
1698	if a == Some(Origin::UNKNOWN) || b == Some(Origin::UNKNOWN) {
1699		return false;
1700	}
1701	a == b
1702}
1703
1704/// Attach a source to the broadcast at `leaf`, creating (and publishing) the
1705/// broadcast if none is live. One lock acquisition covers the whole
1706/// join-or-create decision, so concurrent attaches cannot race each other.
1707///
1708/// Joining requires the same content identity (first hop). A source whose
1709/// original publisher differs takes the path over instead: the incumbent front
1710/// closes and a fresh one is created below, so consumers observe an unannounce
1711/// followed by an announce. That mirrors the session layer's rule that a restart
1712/// with a different first hop is a replacement, never a standby, and it is what
1713/// keeps a reconnect from waiting on the transport to retire the session it
1714/// replaced.
1715///
1716/// Taking over requires announcing, which keeps the rule consistent with
1717/// [`route_order`]: an offline source ranks below every announced route, so it
1718/// waits ([`Attach::Parked`]) rather than unannouncing a live broadcast and
1719/// cutting its subscribers for content nobody has advertised. It also requires a
1720/// chain that does not lead back through a peer this front is already exposed to
1721/// (see [`FrontState::taints_a_reader`]): such a source is our own broadcast
1722/// reflected by a peer that cannot detect the loop itself, and letting it evict the
1723/// front is how a publish direction ends up withdrawing its own announce.
1724fn attach_source(
1725	ctx: &AttachContext,
1726	leaf: &Lock<OriginNode>,
1727	source: &broadcast::Consumer,
1728	route: broadcast::Route,
1729) -> Attach {
1730	let publisher = route.hops.iter().next().copied();
1731	let mut leaf_guard = leaf.lock();
1732
1733	// Join the live broadcast if the leaf already has one. A closed one (torn
1734	// down, awaiting teardown, or evicted just below) is replaced instead.
1735	if let Some(existing) = &leaf_guard.broadcast {
1736		let mut joined = None;
1737		let carrying = existing.broadcast.demand().is_used();
1738		if let Ok(mut s) = existing.state.write()
1739			&& !s.closed
1740		{
1741			if same_publisher(s.publisher, publisher) {
1742				let id = s.next_route;
1743				s.next_route += 1;
1744				s.routes.push(FrontRoute {
1745					id,
1746					route: route.clone(),
1747					source: source.clone(),
1748				});
1749				s.reselect(carrying);
1750				joined = Some(id);
1751			} else if !route.announce || s.taints_a_reader(&route) {
1752				return Attach::Parked(existing.state.clone());
1753			} else {
1754				// New content at a live path: the newest publisher wins it. Closing
1755				// the incumbent here (rather than letting the newcomer wait it out)
1756				// is what makes a reconnect immediate, and routing the takeover
1757				// through the replacement path below keeps the guarantee that
1758				// unrelated content is never spliced into live subscribers. The
1759				// incumbent's own task observes the flag and finishes its teardown,
1760				// finding the leaf slot already taken.
1761				s.closed = true;
1762				tracing::warn!(broadcast = %ctx.full, "replacing a live broadcast from a different publisher");
1763			}
1764		}
1765		if let Some(id) = joined {
1766			let state = existing.state.clone();
1767			let broadcast = existing.broadcast.clone();
1768			drop(leaf_guard);
1769			sync_front(&state, &broadcast, leaf);
1770			return Attach::Ready(state, broadcast, id);
1771		}
1772	}
1773
1774	// First source: create the broadcast and publish it into the tree.
1775	let announce = route.announce;
1776	let broadcast = broadcast::Producer::new_spliced(broadcast::Info {
1777		origin: ctx.origin.clone(),
1778	});
1779	let _ = broadcast.clone().set_route(route.clone());
1780	let state = kio::Producer::new(FrontState {
1781		path: ctx.full.clone(),
1782		self_origin: ctx.origin.id,
1783		publisher,
1784		next_route: 1,
1785		excluded: HashMap::new(),
1786		routes: vec![FrontRoute {
1787			id: 0,
1788			route,
1789			source: source.clone(),
1790		}],
1791		active: Some(0),
1792		linger: ctx.origin.linger,
1793		closed: false,
1794	});
1795
1796	// Replacing a stale (closed) entry counts as an unannounce, so consumers
1797	// observe the replacement rather than a silent swap; its own teardown task
1798	// then finds the slot already taken and leaves it alone.
1799	if let Some(stale) = leaf_guard.broadcast.take()
1800		&& stale.announced
1801	{
1802		leaf_guard.notify.lock().unannounce(&stale.path);
1803	}
1804	let entry = OriginBroadcast {
1805		path: ctx.full.clone(),
1806		broadcast: broadcast.clone(),
1807		state: state.clone(),
1808		announced: announce,
1809	};
1810	if entry.announced {
1811		leaf_guard
1812			.notify
1813			.lock()
1814			.announce(ctx.full, &broadcast.consume(), &state);
1815	}
1816	leaf_guard.broadcast = Some(entry);
1817	drop(leaf_guard);
1818
1819	web_async::spawn(run_front(
1820		state.clone(),
1821		broadcast.clone(),
1822		ctx.node.clone(),
1823		ctx.rest.clone(),
1824	));
1825
1826	Attach::Ready(state, broadcast, 0)
1827}
1828
1829/// Owns a front's lifecycle: dispatches each requested track to a serve task
1830/// until the last source detaches, then unpublishes the broadcast.
1831async fn run_front(
1832	state: kio::Producer<FrontState>,
1833	mut broadcast: broadcast::Producer,
1834	node: Lock<OriginNode>,
1835	rest: PathOwned,
1836) {
1837	enum Step {
1838		Serve(Arc<str>, super::resume::Producer),
1839		/// The source table emptied or refilled: re-arm the linger countdown.
1840		Changed,
1841		/// The linger window expired: close if the table is still empty.
1842		Expired,
1843		Closed,
1844	}
1845
1846	let linger = state.read().linger;
1847	// Armed while the table is ungracefully empty: the instant the front gives up
1848	// waiting for a replacement source. A graceful close never gets here (the
1849	// detach sets `closed` synchronously), so a running countdown always means a
1850	// reconnect is welcome.
1851	let mut deadline = kio::time::Deadline::new();
1852
1853	loop {
1854		let empty = {
1855			let s = state.read();
1856			!s.closed && s.routes.is_empty()
1857		};
1858		deadline.set(match (empty, deadline.deadline()) {
1859			// An unrepresentable deadline (e.g. `Duration::MAX`) lingers forever:
1860			// no timer, only a re-attach or teardown moves the front on.
1861			(true, None) => web_async::time::Instant::now().checked_add(linger),
1862			(true, at) => at,
1863			(false, _) => None,
1864		});
1865
1866		let step = {
1867			kio::wait(|waiter| {
1868				if let Poll::Ready((name, resume)) = broadcast.poll_spliced_assigned(waiter) {
1869					return Poll::Ready(Step::Serve(name, resume));
1870				}
1871				// Watch for the close, and for the table changing shape so the
1872				// countdown re-arms (a detach emptying it, a reconnect refilling it).
1873				match state.poll(waiter, |s| {
1874					if s.closed || s.routes.is_empty() != empty {
1875						Poll::Ready(())
1876					} else {
1877						Poll::Pending
1878					}
1879				}) {
1880					Poll::Ready(Ok(guard)) => {
1881						return Poll::Ready(if guard.closed { Step::Closed } else { Step::Changed });
1882					}
1883					Poll::Ready(Err(_)) => return Poll::Ready(Step::Closed),
1884					Poll::Pending => {}
1885				}
1886				deadline.poll(waiter).map(|_| Step::Expired)
1887			})
1888			.await
1889		};
1890
1891		match step {
1892			Step::Serve(name, resume) => {
1893				// Serve tasks self-terminate when the track completes or the
1894				// front closes.
1895				web_async::spawn(serve_track(state.clone(), name, resume));
1896			}
1897			Step::Changed => {}
1898			Step::Expired => {
1899				// Close only if the table is still empty: a source that re-attached
1900				// as the window expired wins the write-lock race and keeps the
1901				// broadcast alive.
1902				let close = {
1903					let Ok(mut s) = state.write() else { break };
1904					if !s.closed && s.routes.is_empty() {
1905						s.closed = true;
1906						true
1907					} else {
1908						false
1909					}
1910				};
1911				if close {
1912					break;
1913				}
1914			}
1915			Step::Closed => break,
1916		}
1917	}
1918
1919	// Abort the logical tracks (releasing their subscribers) and unpublish.
1920	broadcast.abort_spliced(Error::Dropped);
1921
1922	// Deliberate end; suppresses the dropped-without-finish warning.
1923	broadcast.finish();
1924
1925	// Remove the broadcast from the tree (identity-checked, so a replacement is
1926	// untouched) and prune empty nodes.
1927	node.lock().remove(&state, &rest);
1928}
1929
1930/// Serves one spliced logical track: splices in the best source's copy of the
1931/// track, re-splicing on handover or failure, until the track completes or the
1932/// front closes. A refusal (a source rejecting the track, or its copy dying
1933/// before delivering anything) is authoritative and never retried: the refuser
1934/// is skipped for this track so a joining standby cannot kill a subscription
1935/// the incumbent is serving, and once every attached source has refused, the
1936/// track aborts with the last refusal's error. The verdict belongs to this
1937/// request; a later consumer request asks afresh (see `track_inner`). Failures
1938/// after delivered progress (a serving session dying mid-stream) are normal
1939/// failover and re-splice from the next source at the first missing group; a
1940/// source that fails while *closing* is a corpse to fail over past (its watcher
1941/// is about to detach it), not a verdict on the track.
1942async fn serve_track(state: kio::Producer<FrontState>, name: Arc<str>, mut resume: super::resume::Producer) {
1943	enum Step {
1944		Closed,
1945		Splice(u64, broadcast::Consumer),
1946		Complete,
1947		Failed(Error),
1948		/// The route we were serving from left the table with nothing servable to
1949		/// replace it: drop our handle; the verdict block at the top of the loop
1950		/// decides between aborting (all refused) and parking (corpses detaching,
1951		/// or an empty table awaiting a reconnect).
1952		NoRoute,
1953		/// The linger expired with the track still unread: release the segment.
1954		Idle,
1955		/// A reader arrived or the last one left: recompute the demand gate.
1956		Demand,
1957	}
1958
1959	// The source whose copy is currently spliced in, and that copy.
1960	let mut serving: Option<(u64, track::Consumer)> = None;
1961	// The delivered edge when that copy spliced in. A copy that dies without
1962	// advancing it never delivered anything, which is what [`Step::Failed`]
1963	// uses to tell a refusal from a mid-stream failover. Snapshotted per splice,
1964	// not per wake: an unrelated wake between the copy's last group and its
1965	// death must not launder its delivered progress away.
1966	let mut spliced_edge: Option<u64> = None;
1967	// Sources that refused this track, and the most recent refusal's error. A
1968	// standby joining a live front wins dispatch the moment it attaches, which is
1969	// before a real publisher has created every track, so its refusal must cost
1970	// the incumbent nothing: we keep serving from a route that has the track.
1971	let mut refused: HashSet<u64> = HashSet::new();
1972	let mut refusal: Option<Error> = None;
1973	// Sources whose splice failed because they had already closed. Their watchers
1974	// are about to detach them, so wait for the table to move on rather than
1975	// treating a corpse's error as a refusal (ids are never reused, so this
1976	// cannot wedge).
1977	let mut dead: HashSet<u64> = HashSet::new();
1978	// When the spliced segment stopped being read, starting the release countdown.
1979	let mut idle_since: Option<web_async::time::Instant> = None;
1980	let mut deadline = kio::time::Deadline::new();
1981
1982	loop {
1983		let serving_id = serving.as_ref().map(|(id, _)| *id);
1984
1985		// The table's verdict: once every attached source has refused, nothing
1986		// will ever serve the track (refusals are never retried) and it aborts
1987		// with the last refusal's error. A detached refuser leaves the set, so a
1988		// source that reattaches (under a fresh id) is asked anew; a table blocked
1989		// only by corpses awaiting detach parks instead, since their replacement
1990		// (a reconnect) deserves the seamless splice.
1991		{
1992			let s = state.read();
1993			refused.retain(|id| s.routes.iter().any(|r| r.id == *id));
1994			dead.retain(|id| s.routes.iter().any(|r| r.id == *id));
1995			let exhausted = !s.routes.is_empty()
1996				&& s.serve_route(|id| refused.contains(&id) || dead.contains(&id))
1997					.is_none();
1998			if exhausted && dead.is_empty() {
1999				drop(s);
2000				let err = refusal.take().unwrap_or(Error::NotFound);
2001				tracing::debug!(name = %name, %err, "every source refused track; aborting");
2002				let _ = resume.abort(err);
2003				return;
2004			}
2005		}
2006
2007		// Demand gates both directions: an unread track never splices a source in,
2008		// and a spliced one is released once the linger expires. Both sides use the
2009		// same signal, so a release can't immediately re-splice and spin.
2010		//
2011		// The countdown keys off the segment, not our handle on the route that
2012		// produced it: a route that leaves (or a copy that dies) drops the handle
2013		// while the segment stays spliced, and that segment is exactly what the
2014		// release exists to reclaim. Keying off the handle strands it until the front
2015		// closes, which pins the departed source's cached groups for a linger that
2016		// may never expire and leaves a dead segment's edge behind for the next
2017		// takeover to splice above.
2018		let used = resume.is_used();
2019		idle_since = match (resume.is_spliced(), used) {
2020			(true, false) => idle_since.or_else(|| Some(web_async::time::Instant::now())),
2021			_ => None,
2022		};
2023		deadline.set(idle_since.and_then(|at| at.checked_add(TRACK_IDLE_LINGER)));
2024
2025		let step = {
2026			let skip = |id: u64| refused.contains(&id) || dead.contains(&id);
2027			kio::wait(|waiter| {
2028				// Watch the source table: the front closing, a better servable
2029				// source than the one spliced in (skipping any we already know
2030				// can't serve this track), or the served route leaving the table,
2031				// which retires the refusals collected against it. Splicing waits
2032				// for a reader.
2033				match state.poll(waiter, |s| {
2034					let gone = serving_id.is_some_and(|id| !s.routes.iter().any(|r| r.id == id));
2035					if s.closed
2036						|| (used && (gone || matches!(s.serve_route(skip), Some(next) if Some(next) != serving_id)))
2037					{
2038						Poll::Ready(())
2039					} else {
2040						Poll::Pending
2041					}
2042				}) {
2043					Poll::Ready(Ok(guard)) => {
2044						if guard.closed {
2045							return Poll::Ready(Step::Closed);
2046						}
2047						let Some(next) = guard.serve_route(skip) else {
2048							return Poll::Ready(Step::NoRoute);
2049						};
2050						let source = guard
2051							.routes
2052							.iter()
2053							.find(|r| r.id == next)
2054							.expect("servable source in table")
2055							.source
2056							.clone();
2057						return Poll::Ready(Step::Splice(next, source));
2058					}
2059					Poll::Ready(Err(_)) => return Poll::Ready(Step::Closed),
2060					Poll::Pending => {}
2061				}
2062
2063				// Watch the demand edge in whichever direction is unmet. This has to end
2064				// the wait, not just wake it: `used` and the countdown are computed by
2065				// the outer loop, so a wake that stayed inside would re-poll with the
2066				// stale value and never arm (or cancel) the linger.
2067				let edge = match used {
2068					true => resume.poll_unused(waiter),
2069					false => resume.poll_used(waiter),
2070				};
2071				if edge.is_ready() {
2072					return Poll::Ready(Step::Demand);
2073				}
2074
2075				// Watch the spliced copy for its end: complete means the logical
2076				// track is over; anything else means the serving copy died.
2077				if let Some((_, track)) = &serving
2078					&& let Poll::Ready(result) = track.poll_complete(waiter)
2079				{
2080					return Poll::Ready(match result {
2081						Ok(()) => Step::Complete,
2082						Err(err) => Step::Failed(err),
2083					});
2084				}
2085
2086				deadline.poll(waiter).map(|_| Step::Idle)
2087			})
2088			.await
2089		};
2090
2091		match step {
2092			// The front's teardown aborts the logical track.
2093			Step::Closed => return,
2094			Step::Complete => {
2095				let _ = resume.finish();
2096				return;
2097			}
2098			Step::Failed(err) => {
2099				// The spliced copy died mid-serve. With delivered progress since
2100				// its splice it's a normal failover: re-splice from the (possibly
2101				// same) active source. A copy that died before producing anything
2102				// is a refusal (a source whose track keeps dying right after
2103				// acceptance must not re-splice forever), unless the source
2104				// itself is closing: that corpse parks for its detach so a
2105				// reconnect gets the seamless splice.
2106				if resume.latest() == spliced_edge
2107					&& let Some(id) = serving_id
2108				{
2109					let closing = state
2110						.read()
2111						.routes
2112						.iter()
2113						.find(|r| r.id == id)
2114						.is_some_and(|r| r.source.is_closing());
2115					if closing {
2116						dead.insert(id);
2117					} else {
2118						refused.insert(id);
2119						refusal = Some(err);
2120					}
2121				}
2122				serving = None;
2123			}
2124			// The outer loop recomputes `used` and the countdown on the next pass.
2125			Step::Demand => {}
2126			// Forget which route we were serving from, or the `gone` edge that woke
2127			// us keeps firing: the id stays absent from the table, the wait returns
2128			// Ready at once, and the loop spins on a full core without ever parking.
2129			// The segment itself stays spliced into `resume` (readers keep whatever
2130			// it delivered) until a replacement is proven servable.
2131			Step::NoRoute => serving = None,
2132			Step::Idle => {
2133				// Nobody has read the track for the linger: drop the source's copy so
2134				// its session can release the track (and the cached `track::Info` that
2135				// came with it). The logical track stays alive and re-splices on the
2136				// next reader, so a returning viewer or a follow-up fetch resumes.
2137				if resume.release().is_err() {
2138					// Finished or aborted meanwhile; the track is over either way.
2139					return;
2140				}
2141				serving = None;
2142			}
2143			Step::Splice(id, source) => {
2144				// Ask the source for its copy and wait for the info to resolve,
2145				// proving it servable, before splicing it in. Bail out early if
2146				// the table moves on while waiting.
2147				let attempt = match source.track(&name) {
2148					Ok(track) => {
2149						// `into_inner` sheds the `Pending` future wrapper so only
2150						// the pollable (which is `Sync`) is held across the await.
2151						let query = track.info().into_inner();
2152						let skip = |id: u64| refused.contains(&id) || dead.contains(&id);
2153						let info = kio::wait(|waiter| {
2154							if let Poll::Ready(result) = query.poll(waiter) {
2155								return Poll::Ready(Some(result));
2156							}
2157							match state.poll(waiter, |s| {
2158								if s.closed || s.serve_route(skip) != Some(id) {
2159									Poll::Ready(())
2160								} else {
2161									Poll::Pending
2162								}
2163							}) {
2164								Poll::Ready(_) => Poll::Ready(None),
2165								Poll::Pending => Poll::Pending,
2166							}
2167						})
2168						.await;
2169						match info {
2170							// The table changed under us; re-pick from the top.
2171							None => continue,
2172							// A copy that is already aborted can't be spliced;
2173							// its error is the source's answer for the track.
2174							Some(Ok(_)) => match track.poll_complete(&kio::Waiter::noop()) {
2175								Poll::Ready(Err(err)) => Err(err),
2176								_ => Ok(track),
2177							},
2178							Some(Err(err)) => Err(err),
2179						}
2180					}
2181					Err(err) => Err(err),
2182				};
2183
2184				match attempt {
2185					Ok(track) => {
2186						if let Err(err) = resume.takeover(&track) {
2187							// Closed means the logical track already ended
2188							// (finished or aborted). Anything else is a boundary
2189							// bug; abort rather than strand subscribers on a
2190							// track no task serves (a no-op after a clean end).
2191							let _ = resume.abort(err);
2192							return;
2193						}
2194						// `dead` must survive the takeover. A dead source can never
2195						// serve again (ids are never reused; `is_closing` is
2196						// terminal), and the retain above reclaims its entry once
2197						// its watcher detaches it. Re-admitting a still-attached
2198						// closing route here would let `serve_route`'s active
2199						// preference re-dispatch it, and because both its instant
2200						// failure and a cached standby splice resolve without
2201						// awaiting, the loop would spin inside a single poll,
2202						// starving the watcher whose detach ends the cycle.
2203						// The new segment has produced nothing yet, so this is
2204						// the edge the copy is asked to advance.
2205						spliced_edge = resume.latest();
2206						serving = Some((id, track));
2207					}
2208					// The source itself closed or deliberately ended: not a
2209					// verdict on the track. Park until its watcher detaches
2210					// it and the table promotes a replacement.
2211					Err(_) if source.is_closing() => {
2212						dead.insert(id);
2213						serving = None;
2214					}
2215					// The dispatched source does not carry the track: a publisher
2216					// announces a broadcast only once its tracks exist, so the
2217					// answer is authoritative and never re-asked. Skip the source
2218					// for this track; the verdict block aborts once every source
2219					// has refused.
2220					Err(err) => {
2221						tracing::debug!(name = %name, source = id, %err, "source refused track");
2222						refused.insert(id);
2223						refusal = Some(err);
2224						serving = None;
2225					}
2226				}
2227			}
2228		}
2229	}
2230}
2231
2232/// Shared fallback request queue for an origin.
2233///
2234/// Lives off to the side of the announce tree because dynamically served broadcasts
2235/// are never announced. Carried in a [`kio::Shared`], so consumers enqueue and handlers
2236/// drain under one lock. Mirrors the fetch state of the track model.
2237#[derive(Default)]
2238struct OriginDynamicState {
2239	// Result channels for pending requests, keyed by absolute path so concurrent
2240	// `request_broadcast` calls for the same path coalesce onto one channel.
2241	requests: Requests<PathOwned, kio::Producer<PendingBroadcast>>,
2242
2243	// Broadcasts a handler has already served, kept weakly so a repeat request for the
2244	// same path resolves to a shared clone instead of re-invoking the handler (which would
2245	// open a duplicate upstream subscription). Weak so a served broadcast still closes once
2246	// its real consumers drop. The cache reclaims closed entries incrementally on insert, so a
2247	// long-lived origin serving many distinct one-shot paths stays bounded by the live count.
2248	served: WeakCache<PathOwned, broadcast::WeakConsumer>,
2249}
2250
2251/// One-shot result of a dynamic broadcast request.
2252///
2253/// Stays `None` until a handler [`accept`](Request::accept)s (yielding the served
2254/// broadcast) or [`reject`](Request::reject)s (yielding an error). The producer is
2255/// dropped right after writing, closing the channel; kio checks the value before the closed
2256/// flag, so an awaiting requester still observes the final result.
2257#[derive(Default)]
2258struct PendingBroadcast {
2259	resolved: Option<Result<broadcast::Consumer, Error>>,
2260}
2261
2262/// Picks up [`Consumer::request_broadcast`] calls for paths that are not announced.
2263///
2264/// The origin-level analogue of [`broadcast::Dynamic`]: where that serves tracks on
2265/// demand within a broadcast, this serves whole broadcasts on demand within an origin. A
2266/// relay uses it as a fallback router, fetching a broadcast from upstream only when a
2267/// downstream consumer asks for an exact path that nobody announced.
2268///
2269/// Served broadcasts are deliberately *not* announced, so they never appear in
2270/// [`Consumer::announced`]. Drop this handle (and every clone) to reject the
2271/// requests still waiting to be served.
2272pub struct Dynamic {
2273	info: Origin,
2274	root: PathOwned,
2275	state: kio::Shared<OriginDynamicState>,
2276}
2277
2278impl Clone for Dynamic {
2279	fn clone(&self) -> Self {
2280		// Mirror `new`: count each live handle. Without this, dropping a clone would
2281		// decrement past `new`'s increment and prematurely flip the handler count to
2282		// zero, making future `request_broadcast` calls return `Unroutable`.
2283		self.state.lock().requests.add_handler();
2284
2285		Self {
2286			info: self.info,
2287			root: self.root.clone(),
2288			state: self.state.clone(),
2289		}
2290	}
2291}
2292
2293impl Dynamic {
2294	fn new(info: Origin, root: PathOwned, state: kio::Shared<OriginDynamicState>) -> Self {
2295		state.lock().requests.add_handler();
2296
2297		Self { info, root, state }
2298	}
2299
2300	/// The origin this handler belongs to.
2301	pub fn info(&self) -> &Origin {
2302		&self.info
2303	}
2304
2305	/// Poll for the next requested broadcast, without blocking.
2306	pub fn poll_requested_broadcast(&mut self, waiter: &kio::Waiter) -> Poll<Result<Request, Error>> {
2307		let mut state = ready!(self.state.poll(waiter, |state| {
2308			if state.requests.has_queued() {
2309				Poll::Ready(())
2310			} else {
2311				Poll::Pending
2312			}
2313		}));
2314
2315		let path = state.requests.pop().expect("predicate guaranteed a request");
2316		// The popped request stays pending, so a repeat request in the window between
2317		// hand-off and accept coalesces onto it instead of re-invoking the handler. The
2318		// producer is a shared clone; `Request::{accept, reject, drop}` removes the
2319		// entry. This mirrors how `poll_requested_track` keeps a served track
2320		// discoverable via the weak cache across the same window.
2321		let producer = state.requests.get(&path).expect("popped key must be pending").clone();
2322		Poll::Ready(Ok(Request {
2323			path,
2324			producer,
2325			state: self.state.clone(),
2326		}))
2327	}
2328
2329	/// Block until a consumer requests an unannounced broadcast, returning a
2330	/// [`Request`] to serve.
2331	pub async fn requested_broadcast(&mut self) -> Result<Request, Error> {
2332		kio::wait(|waiter| self.poll_requested_broadcast(waiter)).await
2333	}
2334
2335	/// Returns the prefix that is automatically stripped from requested paths.
2336	pub fn root(&self) -> &Path<'_> {
2337		&self.root
2338	}
2339}
2340
2341impl Drop for Dynamic {
2342	fn drop(&mut self) {
2343		// Decrement and reject under one lock, so a `request_broadcast` that saw a
2344		// live handler through the same lock can't slip a request past the rejection.
2345		let mut state = self.state.lock();
2346		if state.requests.remove_handler() {
2347			// No handlers left to pop queued requests; drop them, closing their result
2348			// channels so awaiting requesters resolve to `Unroutable`. A request already
2349			// handed to a handler stays, resolved by its `Request` instead.
2350			state.requests.drain_queued();
2351		}
2352	}
2353}
2354
2355/// A pending request for a broadcast that was not announced.
2356///
2357/// Yielded by [`Dynamic::requested_broadcast`]. The requester is awaiting inside
2358/// [`Consumer::request_broadcast`]; [`accept`](Self::accept) resolves it with a live
2359/// broadcast (which the handler keeps producing into) and [`reject`](Self::reject) resolves
2360/// it with an error. Dropping the request without either rejects it.
2361pub struct Request {
2362	// Absolute path that was requested.
2363	path: PathOwned,
2364
2365	// Result channel back to the awaiting requester(s). Writing `resolved` and dropping
2366	// this wakes them with the outcome.
2367	producer: kio::Producer<PendingBroadcast>,
2368
2369	// Shared dynamic state, so `accept` can cache the served broadcast for repeat requests.
2370	state: kio::Shared<OriginDynamicState>,
2371}
2372
2373impl Request {
2374	/// The absolute path that was requested.
2375	pub fn path(&self) -> &Path<'_> {
2376		&self.path
2377	}
2378
2379	/// Accept the request, resolving every awaiting requester with `broadcast`.
2380	///
2381	/// The caller keeps producing into `broadcast` (e.g. a relay proxying tracks from
2382	/// upstream); the requesters receive a consumer for it. The broadcast is *not*
2383	/// announced.
2384	pub fn accept(self, broadcast: impl Consume<broadcast::Consumer>) {
2385		let broadcast = broadcast.consume();
2386
2387		// Move the entry out of the in-flight queue and into the weak `served` cache, so repeat
2388		// requests for this path share the same broadcast instead of asking the handler to serve
2389		// (and subscribe upstream) again. Re-check under the lock: if a live broadcast was already
2390		// served for this path while we were fetching upstream, dedup onto it and drop ours rather
2391		// than replace a good entry with a duplicate subscription.
2392		let resolved = {
2393			let mut state = self.state.lock();
2394			let existing = state.served.insert(self.path.clone(), broadcast.weak());
2395			state
2396				.requests
2397				.remove_if(&self.path, |producer| producer.same_channel(&self.producer));
2398			existing.map(|weak| weak.consume()).unwrap_or(broadcast)
2399		};
2400
2401		if let Ok(mut pending) = self.producer.write() {
2402			pending.resolved = Some(Ok(resolved));
2403		}
2404		// `self.producer` drops here, closing the channel; the value is still observable.
2405	}
2406
2407	/// Reject the request, resolving every awaiting requester with `err`.
2408	pub fn reject(self, err: Error) {
2409		self.state
2410			.lock()
2411			.requests
2412			.remove_if(&self.path, |producer| producer.same_channel(&self.producer));
2413		if let Ok(mut state) = self.producer.write() {
2414			state.resolved = Some(Err(err));
2415		}
2416	}
2417}
2418
2419impl Drop for Request {
2420	fn drop(&mut self) {
2421		// Handed off but neither accepted nor rejected: drop the still-pending entry so its
2422		// producer clone (plus this one) closes the channel, resolving coalesced requesters to
2423		// `Unroutable` rather than hanging.
2424		//
2425		// The identity guard matters: `accept`/`reject` already removed our entry and released
2426		// the lock before we run, so a concurrent request for the same path may have registered
2427		// a *new* one here. Removing unconditionally would clobber it, stranding its requesters.
2428		self.state
2429			.lock()
2430			.requests
2431			.remove_if(&self.path, |producer| producer.same_channel(&self.producer));
2432	}
2433}
2434
2435/// The pollable result of [`Consumer::request_broadcast`].
2436///
2437/// Awaited via the [`kio::Pending`] wrapper; resolves to the [`broadcast::Consumer`]
2438/// immediately when the broadcast was already announced, or once an [`Dynamic`]
2439/// handler serves the request. Resolves to an error if the request is rejected or every
2440/// handler drops before serving it.
2441pub struct Requesting {
2442	inner: RequestState,
2443	// Egress scope applied to the resolved broadcast, so its reads are attributed.
2444	// Empty (no-op) for an untagged consumer.
2445	stats: stats::Scope,
2446}
2447
2448enum RequestState {
2449	// Already announced: resolves immediately with a clone of this broadcast.
2450	Ready(broadcast::Consumer),
2451	// Unroutable at request time: resolves immediately with this error. Baked in so
2452	// `request_broadcast` itself stays infallible.
2453	Failed(Error),
2454	// Awaiting a handler: resolves when the request's result channel is written.
2455	Pending(kio::Consumer<PendingBroadcast>),
2456}
2457
2458impl Requesting {
2459	fn ready(broadcast: broadcast::Consumer) -> Self {
2460		Self {
2461			inner: RequestState::Ready(broadcast),
2462			stats: stats::Scope::default(),
2463		}
2464	}
2465
2466	fn failed(error: Error) -> Self {
2467		Self {
2468			inner: RequestState::Failed(error),
2469			stats: stats::Scope::default(),
2470		}
2471	}
2472
2473	fn pending(consumer: kio::Consumer<PendingBroadcast>) -> Self {
2474		Self {
2475			inner: RequestState::Pending(consumer),
2476			stats: stats::Scope::default(),
2477		}
2478	}
2479
2480	fn with_stats(mut self, scope: stats::Scope) -> Self {
2481		self.stats = scope;
2482		self
2483	}
2484
2485	/// Poll for the requested broadcast without blocking.
2486	pub fn poll_ok(&self, waiter: &kio::Waiter) -> Poll<Result<broadcast::Consumer, Error>> {
2487		match &self.inner {
2488			RequestState::Ready(broadcast) => Poll::Ready(Ok(broadcast.clone().with_stats(self.stats.clone()))),
2489			RequestState::Failed(error) => Poll::Ready(Err(error.clone())),
2490			RequestState::Pending(consumer) => Poll::Ready(
2491				match ready!(consumer.poll(waiter, |state| match &state.resolved {
2492					Some(result) => Poll::Ready(result.clone()),
2493					None => Poll::Pending,
2494				})) {
2495					Ok(result) => result.map(|broadcast| broadcast.with_stats(self.stats.clone())),
2496					// Every handler dropped without resolving: nobody could route it.
2497					Err(_closed) => Err(Error::Unroutable),
2498				},
2499			),
2500		}
2501	}
2502}
2503
2504impl kio::Pollable for Requesting {
2505	type Output = Result<broadcast::Consumer, Error>;
2506
2507	fn poll(&self, waiter: &kio::Waiter) -> Poll<Self::Output> {
2508		self.poll_ok(waiter)
2509	}
2510}
2511
2512/// Derive a read view from a handle.
2513///
2514/// Lets APIs accept either a producer or a consumer (e.g.
2515/// [`Client::with_publisher`](crate::Client::with_publisher),
2516/// [`Request::accept`]). The blanket `&T` impl means you can
2517/// pass by value (`foo(x)`) to hand off ownership, or by reference (`foo(&x)`)
2518/// to keep it, without spelling out `.consume()`.
2519pub trait Consume<T> {
2520	/// Derive a read view (a consumer) from this handle.
2521	fn consume(&self) -> T;
2522}
2523
2524impl<T, U: Consume<T>> Consume<T> for &U {
2525	fn consume(&self) -> T {
2526		(**self).consume()
2527	}
2528}
2529
2530impl Consume<Consumer> for Producer {
2531	fn consume(&self) -> Consumer {
2532		// Mirrors the inherent `Producer::consume`; inlined to avoid the
2533		// inherent-vs-trait `consume` ambiguity. Untagged: egress is tagged
2534		// separately from ingress.
2535		Consumer::new(
2536			self.info,
2537			self.root.clone(),
2538			self.nodes.clone(),
2539			self.dynamic.clone(),
2540			stats::Session::default(),
2541		)
2542	}
2543}
2544
2545impl Consume<Consumer> for Consumer {
2546	fn consume(&self) -> Consumer {
2547		self.clone()
2548	}
2549}
2550
2551impl Consume<broadcast::Consumer> for broadcast::Producer {
2552	fn consume(&self) -> broadcast::Consumer {
2553		// The inherent `consume` shadows this trait method, so this delegates.
2554		self.consume()
2555	}
2556}
2557
2558impl Consume<broadcast::Consumer> for broadcast::Consumer {
2559	fn consume(&self) -> broadcast::Consumer {
2560		self.clone()
2561	}
2562}
2563
2564impl Consume<track::Consumer> for track::Producer {
2565	fn consume(&self) -> track::Consumer {
2566		self.consume()
2567	}
2568}
2569
2570impl Consume<track::Consumer> for track::Consumer {
2571	fn consume(&self) -> track::Consumer {
2572		self.clone()
2573	}
2574}
2575
2576/// Cheap read handle over an origin's broadcast tree.
2577///
2578/// Clones share the underlying tree state without allocating any per-cursor
2579/// resources. To actually receive announce / unannounce events, call
2580/// [`Self::announced`] to obtain an [`AnnounceConsumer`].
2581#[derive(Clone)]
2582pub struct Consumer {
2583	// Identity of the origin this consumer was derived from.
2584	info: Origin,
2585	nodes: OriginNodes,
2586
2587	// A prefix that is automatically stripped from all paths.
2588	root: PathOwned,
2589
2590	// Shared fallback request queue, fed to any `Dynamic` handler on the
2591	// producer side. Used only by `request_broadcast`; announced lookups ignore it.
2592	dynamic: kio::Shared<OriginDynamicState>,
2593
2594	// Egress stats context. Broadcasts handed out through this consumer (and any
2595	// handle derived from them) are attributed to it (reads counted on the
2596	// publisher/egress side). Empty (no-op) unless a session tagged this handle.
2597	stats: stats::Session,
2598
2599	// Data-plane split horizon: broadcasts resolved through this handle are
2600	// served from a source whose hop chain excludes this origin (the requesting
2601	// peer). `None` (the default) serves from the active source as usual.
2602	exclude: Option<Origin>,
2603}
2604
2605impl std::ops::Deref for Consumer {
2606	type Target = Origin;
2607
2608	fn deref(&self) -> &Self::Target {
2609		&self.info
2610	}
2611}
2612
2613impl Consumer {
2614	fn new(
2615		info: Origin,
2616		root: PathOwned,
2617		nodes: OriginNodes,
2618		dynamic: kio::Shared<OriginDynamicState>,
2619		stats: stats::Session,
2620	) -> Self {
2621		Self {
2622			info,
2623			nodes,
2624			root,
2625			dynamic,
2626			stats,
2627			exclude: None,
2628		}
2629	}
2630
2631	/// A clone that never serves the given peer its own data: broadcasts resolve
2632	/// to a source whose hop chain excludes `peer`, matching what the announce
2633	/// loop advertises to them. Sessions apply this once they learn the peer's
2634	/// origin id.
2635	pub(crate) fn excluding(mut self, peer: Origin) -> Self {
2636		self.exclude = Some(peer);
2637		self
2638	}
2639
2640	/// Attach an egress stats context: broadcasts handed out through this handle (and
2641	/// any handle derived from it) are attributed to `session` on the publisher
2642	/// (egress) side. Pass [`stats::Session::default`] to opt out.
2643	pub fn with_stats(mut self, session: stats::Session) -> Self {
2644		self.stats = session;
2645		self
2646	}
2647
2648	/// A clone of this consumer with its stats context cleared, so an internal
2649	/// lookup stream (e.g. [`Self::announced_broadcast`]) doesn't drive the egress
2650	/// announce guards; the caller re-attributes the result itself.
2651	fn untagged(&self) -> Self {
2652		Self {
2653			stats: stats::Session::default(),
2654			..self.clone()
2655		}
2656	}
2657
2658	/// A view with this consumer's identity and root but no broadcasts:
2659	/// [`announced`](Self::announced) yields nothing. Used to answer a peer's
2660	/// announce-interest for a prefix outside our scope by announcing nothing,
2661	/// rather than tearing the stream down.
2662	pub(crate) fn empty(&self) -> Self {
2663		Self {
2664			info: self.info,
2665			nodes: OriginNodes { nodes: Vec::new() },
2666			root: self.root.clone(),
2667			dynamic: self.dynamic.clone(),
2668			stats: self.stats.clone(),
2669			exclude: self.exclude,
2670		}
2671	}
2672
2673	/// Subscribe to announce / unannounce events for this consumer's subtree.
2674	///
2675	/// Allocates a per-cursor coalescing buffer, registers it with each root
2676	/// in this consumer's scope, and replays the currently active broadcast
2677	/// set as initial announcements. Drop the returned [`AnnounceConsumer`]
2678	/// to unregister.
2679	pub fn announced(&self) -> AnnounceConsumer {
2680		AnnounceConsumer::new(self.root.clone(), self.nodes.clone(), self.stats.clone(), self.exclude)
2681	}
2682
2683	/// Returns a cheap duplicate of this read handle.
2684	pub fn consume(&self) -> Self {
2685		self.clone()
2686	}
2687
2688	/// Internal synchronous lookup: how the broadcast at `path` resolves for this
2689	/// consumer, telling "announced but every route loops back through you" apart
2690	/// from "nothing here".
2691	///
2692	/// Races announcement gossip (a freshly-connected consumer sees `Missing` even when
2693	/// the broadcast is about to arrive), so it is not public. [`Self::request_broadcast`]
2694	/// is the public lookup: it builds on this for the announced case, then falls back to
2695	/// a dynamic handler. [`Self::announced_broadcast`] waits for a future announcement.
2696	fn resolve(&self, path: impl AsPath) -> Resolved {
2697		let path = path.as_path();
2698		let Some((root, rest)) = self.nodes.get(&path) else {
2699			return Resolved::Missing;
2700		};
2701		let state = root.lock();
2702		state.resolve_broadcast(&rest, self.exclude)
2703	}
2704
2705	/// [`Self::resolve`] reduced to "can I read it": the peek the tests assert on.
2706	#[cfg(test)]
2707	pub(crate) fn get_broadcast(&self, path: impl AsPath) -> Option<broadcast::Consumer> {
2708		match self.resolve(path) {
2709			Resolved::Found(broadcast) => Some(broadcast),
2710			Resolved::Excluded | Resolved::Missing => None,
2711		}
2712	}
2713
2714	/// Block until a broadcast with the given path is announced and return it.
2715	///
2716	/// Returns `None` if the path is outside this consumer's allowed prefixes or if the consumer
2717	/// is closed before the broadcast is announced. The returned broadcast may itself be closed
2718	/// later. Subscribers should watch [`broadcast::Consumer::closed`] to react to that.
2719	///
2720	/// Prefer this over [`Self::request_broadcast`] when you know the exact path you want but
2721	/// cannot guarantee the announcement has already been received. With moq-lite-05 (and
2722	/// the older Lite01/02) `connect()` already blocks until the initial announce set lands,
2723	/// so [`Self::request_broadcast`] is race-free for broadcasts that were live at connect time;
2724	/// this method is still needed to wait for a broadcast that comes online *after* connect.
2725	pub async fn announced_broadcast(&self, path: impl AsPath) -> Option<broadcast::Consumer> {
2726		let path = path.as_path();
2727
2728		// Scope a fresh consumer down to this path so we only wake up for relevant announcements.
2729		let consumer = self.scope(std::slice::from_ref(&path))?;
2730
2731		// `scope` keeps narrower permissions intact: if we ask for `foo` on a consumer limited
2732		// to `foo/specific`, `scope` returns a consumer scoped to `foo/specific`. No
2733		// announcement at the exact path `foo` can ever arrive. Bail rather than loop forever.
2734		if !consumer.allowed().any(|allowed| path.has_prefix(allowed)) {
2735			return None;
2736		}
2737
2738		// Use an untagged stream: this is a lookup, not egress announce forwarding, so
2739		// it must not drive the announce guards. The matched result is attributed
2740		// with the egress scope instead.
2741		let mut announced = consumer.untagged().announced();
2742		let scope = self.stats.egress(self.root.join(&path).to_owned());
2743		loop {
2744			let OriginAnnounce {
2745				path: announced_path,
2746				broadcast,
2747			} = announced.next().await?;
2748			// `scope` narrows by prefix, but we only want an exact-path match.
2749			if announced_path.as_path() == path
2750				&& let Some(broadcast) = broadcast
2751			{
2752				return Some(broadcast.with_stats(scope));
2753			}
2754		}
2755	}
2756
2757	/// Returns a new Consumer restricted to broadcasts under one of `prefixes`.
2758	///
2759	/// Returns None if there are no legal prefixes (the requested prefixes are
2760	/// disjoint from this consumer's current scope, so it would always return None).
2761	// TODO accept PathPrefixes instead of &[Path]
2762	pub fn scope(&self, prefixes: &[Path]) -> Option<Consumer> {
2763		let prefixes = PathPrefixes::new(prefixes);
2764		Some(Consumer {
2765			info: self.info,
2766			root: self.root.clone(),
2767			nodes: self.nodes.select(&prefixes)?,
2768			dynamic: self.dynamic.clone(),
2769			stats: self.stats.clone(),
2770			exclude: self.exclude,
2771		})
2772	}
2773
2774	/// Get a broadcast by path, falling back to a dynamic request when it is not announced.
2775	///
2776	/// Returns a [`kio::Pending`] future (resolved synchronously for an announced broadcast,
2777	/// otherwise once a handler serves it), mirroring [`track::Consumer::fetch_group`](track::Consumer::fetch_group).
2778	/// The lookup order is: an already-announced broadcast resolves
2779	/// immediately; otherwise, if an [`Dynamic`] handler is live (see
2780	/// [`Producer::dynamic`]), a fallback request is registered and the future resolves
2781	/// when the handler [`accept`](Request::accept)s it (or errors if it
2782	/// [`reject`](Request::reject)s or every handler drops). Concurrent requests for
2783	/// the same unannounced path coalesce onto one handler request, and once served the
2784	/// broadcast is cached weakly so *later* requests for that path also share it (rather
2785	/// than re-invoking the handler and opening a duplicate upstream subscription) for as
2786	/// long as it stays live; a closed one is re-served on the next request.
2787	///
2788	/// The returned future resolves to [`Error::Unroutable`] when the path is not announced and no
2789	/// dynamic handler exists. A request that is registered while a handler is live but then loses
2790	/// every handler before being served also resolves to [`Error::Unroutable`]. Unlike an announced
2791	/// broadcast, a dynamically served one is never visible to [`Self::announced`].
2792	pub fn request_broadcast(&self, path: impl AsPath) -> kio::Pending<Requesting> {
2793		let path = path.as_path();
2794
2795		// Key requests by absolute path so a scoped/rooted consumer and the handler
2796		// (which may have a different root) agree on the same entry, and so the egress
2797		// counters resolve against the same broadcast the ingress side wrote.
2798		let absolute = self.root.join(&path).to_owned();
2799		let scope = self.stats.egress(&absolute);
2800
2801		// Prefer a live announcement when one is present; the dynamic queue is only a
2802		// fallback for a path we hold nothing for. A broadcast we do hold but cannot
2803		// serve this requester is unroutable, not missing: a handler resolves paths
2804		// with no route chain to check, so falling through would let it route around
2805		// the split horizon and rebuild the loop.
2806		match self.resolve(&path) {
2807			Resolved::Found(broadcast) => return kio::Pending::new(Requesting::ready(broadcast).with_stats(scope)),
2808			Resolved::Excluded => return kio::Pending::new(Requesting::failed(Error::Unroutable)),
2809			Resolved::Missing => {}
2810		}
2811
2812		let mut state = self.dynamic.lock();
2813
2814		// Reuse a still-live broadcast a handler already served for this path, so repeat
2815		// requests share one upstream subscription. A closed entry is stale; `get` drops it
2816		// and returns `None`, so we fall through and re-serve below.
2817		if let Some(weak) = state.served.get(&absolute) {
2818			return kio::Pending::new(Requesting::ready(weak.consume()).with_stats(scope));
2819		}
2820
2821		// Coalesce onto a pending request for the same path; otherwise register a new
2822		// one, unless there is no handler alive to serve it.
2823		let consumer = if let Some(producer) = state.requests.join(&absolute) {
2824			producer.consume()
2825		} else {
2826			let producer = kio::Producer::<PendingBroadcast>::default();
2827			let consumer = producer.consume();
2828			if state.requests.insert(absolute, producer).is_err() {
2829				return kio::Pending::new(Requesting::failed(Error::Unroutable));
2830			}
2831			consumer
2832		};
2833
2834		kio::Pending::new(Requesting::pending(consumer).with_stats(scope))
2835	}
2836
2837	/// Returns a new Consumer that automatically strips out the provided prefix.
2838	///
2839	/// Returns None if the provided root is not authorized; when [`Self::scope`] was
2840	/// already used without a wildcard.
2841	pub fn with_root(&self, prefix: impl AsPath) -> Option<Self> {
2842		let prefix = prefix.as_path();
2843
2844		Some(Self {
2845			info: self.info,
2846			root: self.root.join(&prefix).to_owned(),
2847			nodes: self.nodes.root(&prefix)?,
2848			dynamic: self.dynamic.clone(),
2849			stats: self.stats.clone(),
2850			exclude: self.exclude,
2851		})
2852	}
2853
2854	/// Returns the prefix that is automatically stripped from all paths.
2855	pub fn root(&self) -> &Path<'_> {
2856		&self.root
2857	}
2858
2859	/// Iterate over the path prefixes this handle is permitted to publish or subscribe under.
2860	// TODO return PathPrefixes
2861	pub fn allowed(&self) -> impl Iterator<Item = &Path<'_>> {
2862		self.nodes.nodes.iter().map(|(root, _)| root)
2863	}
2864
2865	/// Converts a relative path to an absolute path.
2866	pub fn absolute(&self, path: impl AsPath) -> Path<'_> {
2867		self.root.join(path)
2868	}
2869}
2870
2871/// Handle to the announcement stream for a subtree.
2872///
2873/// Symmetric counterpart of [`AnnounceConsumer`]. Cheap to clone; call
2874/// [`Self::consume`] to obtain an [`AnnounceConsumer`] that receives events.
2875#[derive(Clone)]
2876pub struct AnnounceProducer {
2877	nodes: OriginNodes,
2878	root: PathOwned,
2879}
2880
2881impl AnnounceProducer {
2882	fn new(root: PathOwned, nodes: OriginNodes) -> Self {
2883		Self { nodes, root }
2884	}
2885
2886	/// Subscribe to announce / unannounce events for this subtree.
2887	///
2888	/// Allocates a per-cursor coalescing buffer and replays the currently active broadcast set
2889	/// as initial announcements. Drop the returned [`AnnounceConsumer`] to
2890	/// unregister.
2891	pub fn consume(&self) -> AnnounceConsumer {
2892		// Untagged: `AnnounceProducer` is used for internal announce plumbing, not
2893		// egress attribution (which flows through `origin::Consumer::announced`).
2894		AnnounceConsumer::new(self.root.clone(), self.nodes.clone(), stats::Session::default(), None)
2895	}
2896
2897	/// Returns the prefix that is automatically stripped from announced paths.
2898	pub fn root(&self) -> &Path<'_> {
2899		&self.root
2900	}
2901}
2902
2903/// Receives announce / unannounce events for a subtree.
2904///
2905/// Created by [`Consumer::announced`] or [`AnnounceProducer::consume`].
2906/// Drop to unregister.
2907pub struct AnnounceConsumer {
2908	id: ConsumerId,
2909	nodes: OriginNodes,
2910	root: PathOwned,
2911
2912	// Pending updates queued for this cursor. Coalesced so a slow consumer
2913	// can't accumulate redundant announce/unannounce pairs.
2914	state: kio::Producer<OriginConsumerState>,
2915
2916	// Egress stats context (empty for an untagged stream). Announce events drive the
2917	// per-broadcast announce guards below and tag the broadcasts handed out.
2918	stats: stats::Session,
2919
2920	// Live egress announce guards, keyed by absolute broadcast path. An announce
2921	// opens one (bumping `announced` + `announced_bytes`); the matching unannounce
2922	// drops it (bumping `announced_closed` + `announced_bytes`).
2923	guards: HashMap<PathOwned, stats::Announce>,
2924}
2925
2926impl AnnounceConsumer {
2927	fn new(root: PathOwned, nodes: OriginNodes, stats: stats::Session, exclude: Option<Origin>) -> Self {
2928		let state = kio::Producer::<OriginConsumerState>::default();
2929		let id = ConsumerId::new();
2930
2931		for (_, node) in &nodes.nodes {
2932			let notify = AnnounceConsumerNotify {
2933				root: root.clone(),
2934				state: state.clone(),
2935				exclude,
2936			};
2937			node.lock().consume(id, notify);
2938		}
2939
2940		Self {
2941			id,
2942			nodes,
2943			root,
2944			state,
2945			stats,
2946			guards: HashMap::new(),
2947		}
2948	}
2949
2950	/// Drive the egress announce guards and tag the broadcast for one update.
2951	///
2952	/// An announce opens a guard (keyed by absolute path) and tags the yielded
2953	/// broadcast with the egress scope; an unannounce drops the guard. A no-op for
2954	/// an untagged stream.
2955	fn attribute(&mut self, update: OriginAnnounce) -> OriginAnnounce {
2956		let OriginAnnounce { path, broadcast } = update;
2957		let absolute = self.root.join(&path).to_owned();
2958		match broadcast {
2959			Some(broadcast) => {
2960				let scope = self.stats.egress(&absolute);
2961				self.guards.entry(absolute).or_insert_with(|| scope.announce());
2962				OriginAnnounce {
2963					path,
2964					broadcast: Some(broadcast.with_stats(scope)),
2965				}
2966			}
2967			None => {
2968				self.guards.remove(&absolute);
2969				OriginAnnounce { path, broadcast: None }
2970			}
2971		}
2972	}
2973
2974	/// Returns the next (un)announced broadcast and its path relative to this
2975	/// cursor's root.
2976	///
2977	/// The broadcast will only be announced if it was previously unannounced.
2978	/// The same path won't be announced/unannounced twice in a row; instead it
2979	/// toggles. Returns None if the cursor is closed.
2980	pub async fn next(&mut self) -> Option<OriginAnnounce> {
2981		kio::wait(|waiter| self.poll_next(waiter)).await
2982	}
2983
2984	/// Poll for the next (un)announced broadcast, without blocking.
2985	///
2986	/// Returns `Poll::Ready(Some(_))` for an update, `Poll::Ready(None)` if the
2987	/// cursor is closed, or `Poll::Pending` after registering `waiter` to be
2988	/// notified when the next update arrives.
2989	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Option<OriginAnnounce>> {
2990		let update = {
2991			let mut state = match ready!(self.state.poll(waiter, |state| {
2992				if state.pending.is_empty() {
2993					Poll::Pending
2994				} else {
2995					Poll::Ready(())
2996				}
2997			})) {
2998				Ok(state) => state,
2999				// Closed: discard the Ref so its MutexGuard doesn't escape this call.
3000				Err(_) => return Poll::Ready(None),
3001			};
3002			state.take().expect("predicate guaranteed an update")
3003		};
3004		Poll::Ready(Some(self.attribute(update)))
3005	}
3006
3007	/// Returns the next (un)announced broadcast without blocking.
3008	///
3009	/// Returns None if there is no update available; NOT because the cursor is closed.
3010	/// Use [`Self::is_closed`] to check if the cursor is closed.
3011	pub fn try_next(&mut self) -> Option<OriginAnnounce> {
3012		let update = self.state.write().ok()?.take()?;
3013		Some(self.attribute(update))
3014	}
3015
3016	/// Returns true if the cursor is closed (no more updates will arrive).
3017	pub fn is_closed(&self) -> bool {
3018		self.state.write().is_err()
3019	}
3020
3021	/// Returns the prefix that is automatically stripped from emitted paths.
3022	pub fn root(&self) -> &Path<'_> {
3023		&self.root
3024	}
3025
3026	/// Converts a relative path to an absolute path.
3027	pub fn absolute(&self, path: impl AsPath) -> Path<'_> {
3028		self.root.join(path)
3029	}
3030}
3031
3032impl Drop for AnnounceConsumer {
3033	fn drop(&mut self) {
3034		for (_, root) in &self.nodes.nodes {
3035			root.lock().unconsume(self.id);
3036		}
3037	}
3038}
3039
3040#[cfg(test)]
3041use futures::FutureExt;
3042
3043#[cfg(test)]
3044#[allow(missing_docs)] // test-only assertion helpers
3045impl AnnounceConsumer {
3046	pub fn assert_next(&mut self, expected: impl AsPath, broadcast: &broadcast::Consumer) {
3047		let expected = expected.as_path();
3048		let announce = self.next().now_or_never().expect("next blocked").expect("no next");
3049		assert_eq!(announce.path, expected, "wrong path");
3050		let announced = announce.broadcast.expect("should be an active announce");
3051		assert!(announced.is_clone(broadcast), "should be the same broadcast");
3052	}
3053
3054	/// An announce for `expected`, without asserting which broadcast backs it
3055	/// (the origin owns the announced broadcast, not the publisher). Returns the
3056	/// announced consumer.
3057	pub fn assert_next_some(&mut self, expected: impl AsPath) -> broadcast::Consumer {
3058		let expected = expected.as_path();
3059		let announce = self.next().now_or_never().expect("next blocked").expect("no next");
3060		assert_eq!(announce.path, expected, "wrong path");
3061		announce.broadcast.expect("should be an active announce")
3062	}
3063
3064	pub fn assert_try_next(&mut self, expected: impl AsPath, broadcast: &broadcast::Consumer) {
3065		let expected = expected.as_path();
3066		let announce = self.try_next().expect("no next");
3067		assert_eq!(announce.path, expected, "wrong path");
3068		let announced = announce.broadcast.expect("should be an active announce");
3069		assert!(announced.is_clone(broadcast), "should be the same broadcast");
3070	}
3071
3072	/// The `try_next` counterpart of [`Self::assert_next_some`].
3073	pub fn assert_try_next_some(&mut self, expected: impl AsPath) -> broadcast::Consumer {
3074		let expected = expected.as_path();
3075		let announce = self.try_next().expect("no next");
3076		assert_eq!(announce.path, expected, "wrong path");
3077		announce.broadcast.expect("should be an active announce")
3078	}
3079
3080	pub fn assert_next_none(&mut self, expected: impl AsPath) {
3081		let expected = expected.as_path();
3082		let announce = self.next().now_or_never().expect("next blocked").expect("no next");
3083		assert_eq!(announce.path, expected, "wrong path");
3084		assert!(announce.broadcast.is_none(), "should be unannounced");
3085	}
3086
3087	pub fn assert_next_wait(&mut self) {
3088		if let Some(res) = self.next().now_or_never() {
3089			panic!("next should block: got {:?}", res.map(|a| a.path));
3090		}
3091	}
3092
3093	/*
3094	pub fn assert_next_closed(&mut self) {
3095		assert!(
3096			self.next().now_or_never().expect("next blocked").is_none(),
3097			"next should be closed"
3098		);
3099	}
3100	*/
3101}
3102
3103#[cfg(test)]
3104mod tests {
3105	use crate::coding::Decode;
3106	use crate::group;
3107
3108	use super::*;
3109
3110	/// An announced direct route.
3111	fn announce() -> broadcast::Route {
3112		broadcast::Route::new().with_announce(true)
3113	}
3114
3115	/// The first origin whose handover key for `name` sits above (`true`) or below
3116	/// (`false`) the peer's, so tests exercising the carrying gate are
3117	/// deterministic instead of hinging on a random id winning a hash comparison.
3118	/// Starts searching above the small ids the tests use in hop chains, so the
3119	/// result never collides with a hop (a looping chain trips a debug_assert).
3120	fn origin_keyed(name: &str, peer: Origin, above: bool) -> Origin {
3121		let name = Path::new(name);
3122		let peer_key = fnv_key(&name, [peer]);
3123		(100u64..)
3124			.map(|id| Origin::new(id).unwrap())
3125			.find(|origin| (fnv_key(&name, [*origin]) > peer_key) == above)
3126			.unwrap()
3127	}
3128
3129	/// A front table for reselect tests: routes get ids in order, the first is
3130	/// the incumbent.
3131	fn front_state(self_origin: Origin, routes: Vec<broadcast::Route>) -> FrontState {
3132		let source = broadcast::Info::new().produce().consume();
3133		FrontState {
3134			path: Path::new("test").to_owned(),
3135			self_origin,
3136			publisher: routes.first().and_then(|r| r.hops.iter().next().copied()),
3137			next_route: routes.len() as u64,
3138			excluded: HashMap::new(),
3139			routes: routes
3140				.into_iter()
3141				.enumerate()
3142				.map(|(id, route)| FrontRoute {
3143					id: id as u64,
3144					route,
3145					source: source.clone(),
3146				})
3147				.collect(),
3148			active: Some(0),
3149			linger: Duration::ZERO,
3150			closed: false,
3151		}
3152	}
3153
3154	/// A route as a warm sibling would announce it: zero cost, chain ending at
3155	/// the announcing peer.
3156	fn sibling_route(peer: Origin) -> broadcast::Route {
3157		let hops = OriginList::try_from(vec![Origin::new(90).unwrap(), peer]).unwrap();
3158		announce().with_hops(hops)
3159	}
3160
3161	/// A route as the upstream announces it: priced, one hop.
3162	fn upstream_route(cost: u64) -> broadcast::Route {
3163		let hops = OriginList::try_from(vec![Origin::new(90).unwrap()]).unwrap();
3164		announce().with_hops(hops).with_cost(cost)
3165	}
3166
3167	/// While carrying, a strictly cheaper route from a peer that hashes above us
3168	/// must not displace the incumbent; the same table re-parents freely once
3169	/// idle, or when the peer hashes below us.
3170	#[test]
3171	fn test_carrying_gate_keys() {
3172		let peer = Origin::new(3).unwrap();
3173
3174		// We lose the key comparison: stay put while carrying, migrate when idle.
3175		let mut lost = front_state(
3176			origin_keyed("test", peer, false),
3177			vec![upstream_route(10), sibling_route(peer)],
3178		);
3179		lost.reselect(true);
3180		assert_eq!(
3181			lost.active,
3182			Some(0),
3183			"carrying front re-parented onto a higher-keyed peer"
3184		);
3185		lost.reselect(false);
3186		assert_eq!(lost.active, Some(1), "idle front must take the cheaper route");
3187
3188		// We win the key comparison: re-parent even while carrying.
3189		let mut won = front_state(
3190			origin_keyed("test", peer, true),
3191			vec![upstream_route(10), sibling_route(peer)],
3192		);
3193		won.reselect(true);
3194		assert_eq!(won.active, Some(1), "carrying front must follow a lower-keyed peer");
3195	}
3196
3197	/// The simultaneous-activation race: two relays that each pulled the same
3198	/// broadcast independently see each other's zero-cost route. Exactly one of
3199	/// them re-parents; the other keeps its upstream, so the broadcast is never
3200	/// left without a source.
3201	#[test]
3202	fn test_carrying_gate_symmetric_race() {
3203		let a = Origin::new(1).unwrap();
3204		let b = Origin::new(2).unwrap();
3205
3206		let mut a_view = front_state(a, vec![upstream_route(10), sibling_route(b)]);
3207		let mut b_view = front_state(b, vec![upstream_route(10), sibling_route(a)]);
3208		a_view.reselect(true);
3209		b_view.reselect(true);
3210
3211		let a_moved = a_view.active == Some(1);
3212		let b_moved = b_view.active == Some(1);
3213		assert!(
3214			a_moved != b_moved,
3215			"exactly one side must re-parent (a: {a_moved}, b: {b_moved})"
3216		);
3217	}
3218
3219	/// The gate is scoped to warm siblings: a cheaper route via a relay that is
3220	/// not itself carrying (advertised nonzero), or directly from the original
3221	/// publisher (single-hop chain), is taken immediately even while carrying
3222	/// and even when we would lose the key comparison.
3223	#[test]
3224	fn test_carrying_switches_to_benign_routes() {
3225		let peer = Origin::new(3).unwrap();
3226		let lost = origin_keyed("test", peer, false);
3227
3228		// A cheaper forwarder path: the relay advertised its accumulated cost.
3229		let mut forwarder = sibling_route(peer).with_cost(4);
3230		forwarder.advertised = 4;
3231		let mut state = front_state(lost, vec![upstream_route(10), forwarder]);
3232		state.reselect(true);
3233		assert_eq!(
3234			state.active,
3235			Some(1),
3236			"a cheaper forwarder path must win while carrying"
3237		);
3238
3239		// Directly from the original publisher: single-hop chain, advertised zero.
3240		let direct = announce().with_hops(OriginList::try_from(vec![peer]).unwrap());
3241		let mut state = front_state(lost, vec![upstream_route(10), direct]);
3242		state.reselect(true);
3243		assert_eq!(
3244			state.active,
3245			Some(1),
3246			"a direct publisher route must win while carrying"
3247		);
3248
3249		// The peer's session reconnecting: same chain, same cost, so the gate's
3250		// strictly-cheaper test does not apply and recency decides. Loosening that
3251		// test to `<=` would hold a carrying front on the dead session until the
3252		// transport timed it out, which is the whole point of the recency order.
3253		let mut state = front_state(lost, vec![sibling_route(peer), sibling_route(peer)]);
3254		state.reselect(true);
3255		assert_eq!(
3256			state.active,
3257			Some(1),
3258			"a reconnect on an identical chain must win while carrying"
3259		);
3260	}
3261
3262	/// The gate only protects an announced incumbent: one that lost its announce
3263	/// (the upstream retracted) is displaced regardless of the key comparison.
3264	#[test]
3265	fn test_carrying_gate_ignores_unannounced_incumbent() {
3266		let peer = Origin::new(3).unwrap();
3267		let unannounced = upstream_route(10).with_announce(false);
3268		let mut state = front_state(
3269			origin_keyed("test", peer, false),
3270			vec![unannounced, sibling_route(peer)],
3271		);
3272		state.reselect(true);
3273		assert_eq!(
3274			state.active,
3275			Some(1),
3276			"an unannounced incumbent must always be displaced"
3277		);
3278	}
3279
3280	/// A route arriving through a peer the front is already exposed to is our own
3281	/// broadcast reflected back, whatever its chain claims, so it must not evict the
3282	/// front. This is the shape a relay with no hop ids produces when both directions
3283	/// of a sync target point at it.
3284	#[test]
3285	fn test_reflection_through_an_exposed_peer_cannot_take_over() {
3286		let peer = Origin::new(42).unwrap();
3287		let upstream = OriginList::try_from(vec![Origin::new(7).unwrap()]).unwrap();
3288		let reflected = announce().with_hops(OriginList::try_from(vec![peer]).unwrap());
3289
3290		let mut state = front_state(Origin::new(1).unwrap(), vec![announce().with_hops(upstream)]);
3291
3292		// Nobody is exposed yet: a different publisher is free to take the path.
3293		assert!(!state.taints_a_reader(&reflected));
3294
3295		// Advertising the path to `peer` registers them, and the same route is now
3296		// recognizable as a reflection.
3297		*state.excluded.entry(peer).or_default() += 1;
3298		assert!(state.taints_a_reader(&reflected));
3299	}
3300
3301	/// The exposure is what discriminates, not the shape of the chain: an unrelated
3302	/// publisher reaching us through some *other* peer still takes the path over.
3303	#[test]
3304	fn test_rival_publisher_through_another_peer_still_takes_over() {
3305		let peer = Origin::new(42).unwrap();
3306		let elsewhere = Origin::new(43).unwrap();
3307		let upstream = OriginList::try_from(vec![Origin::new(7).unwrap()]).unwrap();
3308		let rival = announce().with_hops(OriginList::try_from(vec![Origin::UNKNOWN, elsewhere]).unwrap());
3309
3310		let mut state = front_state(Origin::new(1).unwrap(), vec![announce().with_hops(upstream)]);
3311		*state.excluded.entry(peer).or_default() += 1;
3312
3313		assert!(!state.taints_a_reader(&rival), "only the peer we feed is a reflection");
3314	}
3315
3316	/// A peer that carries no hop ids hides its depth: everything behind it collapses
3317	/// into one entry, so its route understates its true length and wins the cost
3318	/// comparison against a longer-looking but genuinely shorter path. Pricing the
3319	/// opaque link (`Client::with_cost`) is what restores the intended order.
3320	#[test]
3321	fn test_opaque_peer_understates_its_depth() {
3322		let us = Origin::new(1).unwrap();
3323
3324		// Our own upstream, honestly described: two hops, charged per link.
3325		let direct = || {
3326			announce()
3327				.with_hops(OriginList::try_from(vec![Origin::new(7).unwrap(), Origin::new(8).unwrap()]).unwrap())
3328				.with_cost(2)
3329		};
3330		// The same content reached through an opaque relay, which is actually further
3331		// away but advertises no chain at all, so it lands as one unpriced hop.
3332		let opaque = |cost| {
3333			announce()
3334				.with_hops(OriginList::try_from(vec![Origin::new(42).unwrap()]).unwrap())
3335				.with_cost(cost)
3336		};
3337
3338		// Unpriced, the opaque route wins on cost even though it is the longer path.
3339		let mut state = front_state(us, vec![direct(), opaque(1)]);
3340		state.reselect(false);
3341		assert_eq!(
3342			state.active,
3343			Some(1),
3344			"an unpriced opaque link out-ranks a shorter real path"
3345		);
3346
3347		// Priced to reflect what it hides, the real path wins again.
3348		let mut state = front_state(us, vec![direct(), opaque(16)]);
3349		state.reselect(false);
3350		assert_eq!(
3351			state.active,
3352			Some(0),
3353			"pricing the opaque link restores the intended order"
3354		);
3355	}
3356
3357	/// Let the spawned origin tasks (source watchers, front dispatch) run. The
3358	/// tests pause tokio time, so this advances the clock instantly.
3359	async fn settle() {
3360		tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;
3361	}
3362
3363	/// Serve one requested track from a source like a session would: wait for the
3364	/// origin to dispatch it, then accept with default info.
3365	async fn accept_track(dynamic: &mut broadcast::Dynamic, name: &str) -> track::Producer {
3366		let request = tokio::time::timeout(std::time::Duration::from_secs(1), dynamic.requested_track())
3367			.await
3368			.expect("timed out waiting for a track request")
3369			.expect("source closed");
3370		assert_eq!(request.name(), name, "unexpected track dispatched");
3371		request.accept(None)
3372	}
3373
3374	/// Tagging both origin handles with one context attributes the full model path:
3375	/// ingress writes on the subscriber side, egress reads on the publisher side,
3376	/// each counter landing exactly once (the model-layer silent-zero guard).
3377	#[tokio::test]
3378	async fn test_stats_tagged_end_to_end() {
3379		use crate::Timestamp;
3380		use crate::stats::{Config, Registry, Tier};
3381		use bytes::Bytes;
3382
3383		tokio::time::pause();
3384
3385		let registry = Registry::new(Config::new());
3386		let ctx = registry.tier(Tier::default()).session("acme");
3387
3388		let origin = Origin::random().produce();
3389		let ingress = origin.clone().with_stats(ctx.clone());
3390		let egress = origin.consume().with_stats(ctx.clone());
3391
3392		// Egress announce stream: this is the tagged stream that drives the egress
3393		// announce guard.
3394		let mut announced = egress.announced();
3395
3396		// Ingress publishes an announced broadcast.
3397		let source = ingress.create_broadcast("demo", announce()).unwrap();
3398		let mut dynamic = source.dynamic();
3399		settle().await;
3400		settle().await;
3401
3402		// Egress observes the announce and gets the tagged broadcast.
3403		let update = announced.next().await.unwrap();
3404		assert_eq!(update.path.as_str(), "demo");
3405		let broadcast = update.broadcast.unwrap();
3406
3407		// Egress subscribes; the ingress side serves the track on demand.
3408		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3409		let mut producer = accept_track(&mut dynamic, "video").await;
3410		settle().await;
3411		let mut sub = subscribing.await.unwrap();
3412
3413		// Ingress writes one group with two 5-byte frames.
3414		let mut group = producer.append_group().unwrap();
3415		group
3416			.write_frame(Timestamp::ZERO, Bytes::from_static(b"hello"))
3417			.unwrap();
3418		group
3419			.write_frame(Timestamp::ZERO, Bytes::from_static(b"world"))
3420			.unwrap();
3421		group.finish().unwrap();
3422
3423		// Egress reads the group and both frames.
3424		let mut group_c = sub.recv_group().await.unwrap().unwrap();
3425		let mut frames = 0;
3426		while let Some(frame) = group_c.read_frame().await.unwrap() {
3427			assert_eq!(frame.payload.len(), 5);
3428			frames += 1;
3429		}
3430		assert_eq!(frames, 2);
3431		settle().await;
3432
3433		let report = registry.report();
3434		let entry = report
3435			.traffic
3436			.iter()
3437			.find(|e| e.path.as_str() == "demo")
3438			.expect("demo tracked");
3439		let path_len = "demo".len() as u64;
3440
3441		// Egress (publisher side): reads out of the model.
3442		let egress = &entry.publisher;
3443		assert_eq!(egress.announced, 1, "one egress announce");
3444		assert_eq!(egress.announced_bytes, path_len);
3445		assert_eq!(egress.subscriptions, 1, "one egress subscription");
3446		assert_eq!(egress.broadcasts, 1, "one viewer");
3447		assert_eq!(egress.groups, 1);
3448		assert_eq!(egress.frames, 2);
3449		assert_eq!(egress.bytes, 10);
3450		assert_eq!(egress.fetches, 0);
3451
3452		// Ingress (subscriber side): writes into the model.
3453		let ingress = &entry.subscriber;
3454		assert_eq!(ingress.announced, 1, "one ingress announce");
3455		assert_eq!(ingress.announced_bytes, path_len);
3456		assert_eq!(ingress.subscriptions, 1, "one ingress track");
3457		assert_eq!(ingress.broadcasts, 0, "ingress has no viewer refcount");
3458		assert_eq!(ingress.groups, 1);
3459		assert_eq!(ingress.frames, 2);
3460		assert_eq!(ingress.bytes, 10);
3461
3462		// A fetch bumps only `fetches` on the egress side, plus the delivered group.
3463		let fetched = broadcast.track("video").unwrap().fetch_group(0, None).await.unwrap();
3464		let _ = fetched;
3465		settle().await;
3466		let report = registry.report();
3467		let entry = report.traffic.iter().find(|e| e.path.as_str() == "demo").unwrap();
3468		assert_eq!(entry.publisher.fetches, 1, "one fetch");
3469		assert_eq!(entry.publisher.subscriptions, 1, "fetch does not bump subscriptions");
3470		assert_eq!(entry.publisher.broadcasts, 1, "fetch does not bump the viewer refcount");
3471		// `fetches` is egress-only for the same structural reason as `broadcasts`:
3472		// only a `track::Consumer` can fetch, and the ingress scope never reaches one
3473		// (`broadcast::Producer::consume` hands out an untagged consumer).
3474		assert_eq!(entry.subscriber.fetches, 0, "ingress cannot fetch");
3475	}
3476
3477	/// `Subscriber::read_frame` collapses a group to its first frame. The paths it
3478	/// delegates to (plain and spliced) build their own *unmetered* group consumers,
3479	/// so the wrapper is the only place that can attribute the read: exactly one
3480	/// group, one frame, and the payload bytes, counted once each.
3481	#[tokio::test]
3482	async fn test_stats_read_frame_counts_once() {
3483		use crate::Timestamp;
3484		use crate::stats::{Config, Registry, Tier};
3485		use bytes::Bytes;
3486
3487		tokio::time::pause();
3488
3489		let registry = Registry::new(Config::new());
3490		let ctx = registry.tier(Tier::default()).session("acme");
3491
3492		let origin = Origin::random().produce();
3493		let ingress = origin.clone().with_stats(ctx.clone());
3494		let egress = origin.consume().with_stats(ctx.clone());
3495
3496		let mut announced = egress.announced();
3497		let source = ingress.create_broadcast("demo", announce()).unwrap();
3498		let mut dynamic = source.dynamic();
3499		settle().await;
3500		settle().await;
3501
3502		let broadcast = announced.next().await.unwrap().broadcast.unwrap();
3503		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3504		let mut producer = accept_track(&mut dynamic, "video").await;
3505		settle().await;
3506		let mut sub = subscribing.await.unwrap();
3507
3508		// A single-frame group, read back through the collapsing helper.
3509		producer
3510			.write_frame(Timestamp::ZERO, Bytes::from_static(b"hello"))
3511			.unwrap();
3512
3513		let frame = sub.read_frame().await.unwrap().expect("frame");
3514		assert_eq!(frame.payload.len(), 5);
3515		settle().await;
3516
3517		let report = registry.report();
3518		let entry = report
3519			.traffic
3520			.iter()
3521			.find(|e| e.path.as_str() == "demo")
3522			.expect("demo tracked");
3523		assert_eq!(entry.publisher.groups, 1, "one group, counted once");
3524		assert_eq!(entry.publisher.frames, 1, "one frame, counted once");
3525		assert_eq!(
3526			entry.publisher.bytes, 5,
3527			"payload counted once, not zero and not doubled"
3528		);
3529	}
3530
3531	/// Datagrams bypass the group/frame handles entirely, so they're metered at the
3532	/// producer (ingress write) and the subscriber (egress read). Each one counts as
3533	/// the single-frame group it stands in for, plus the `datagrams` breakout.
3534	#[tokio::test]
3535	async fn test_stats_datagrams_counted_both_sides() {
3536		use crate::Timestamp;
3537		use crate::stats::{Config, Registry, Tier};
3538
3539		tokio::time::pause();
3540
3541		let registry = Registry::new(Config::new());
3542		let ctx = registry.tier(Tier::default()).session("acme");
3543
3544		let origin = Origin::random().produce();
3545		let ingress = origin.clone().with_stats(ctx.clone());
3546		let egress = origin.consume().with_stats(ctx.clone());
3547
3548		let mut announced = egress.announced();
3549		let source = ingress.create_broadcast("demo", announce()).unwrap();
3550		let mut dynamic = source.dynamic();
3551		settle().await;
3552		settle().await;
3553
3554		let broadcast = announced.next().await.unwrap().broadcast.unwrap();
3555		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3556		let mut producer = accept_track(&mut dynamic, "video").await;
3557		settle().await;
3558		let mut sub = subscribing.await.unwrap();
3559
3560		producer.append_datagram(Timestamp::ZERO, &b"hello"[..]).unwrap();
3561		let datagram = sub.recv_datagram().await.unwrap().expect("datagram");
3562		assert_eq!(&datagram.payload[..], b"hello");
3563		settle().await;
3564
3565		let report = registry.report();
3566		let entry = report
3567			.traffic
3568			.iter()
3569			.find(|e| e.path.as_str() == "demo")
3570			.expect("demo tracked");
3571
3572		for (side, traffic) in [("egress", &entry.publisher), ("ingress", &entry.subscriber)] {
3573			assert_eq!(traffic.datagrams, 1, "{side}: one datagram");
3574			assert_eq!(traffic.groups, 1, "{side}: counted as its single-frame group");
3575			assert_eq!(traffic.frames, 1, "{side}: one frame");
3576			assert_eq!(traffic.bytes, 5, "{side}: payload counted once");
3577		}
3578	}
3579
3580	#[test]
3581	fn origin_rejects_reserved_ids() {
3582		assert!(Origin::new(0).is_err());
3583		assert!(Origin::new(1u64 << 62).is_err());
3584		assert_eq!(Origin::new(1).unwrap().id(), 1);
3585
3586		let mut zero = [0u8].as_slice();
3587		assert_eq!(
3588			Origin::decode(&mut zero, crate::lite::Version::Lite05).unwrap(),
3589			Origin::UNKNOWN
3590		);
3591	}
3592
3593	#[test]
3594	fn origin_list_push_fails_at_limit() {
3595		let mut list = OriginList::new();
3596		for _ in 0..MAX_HOPS {
3597			list.push(Origin::random()).unwrap();
3598		}
3599		assert_eq!(list.len(), MAX_HOPS);
3600		assert_eq!(list.push(Origin::random()), Err(TooManyOrigins));
3601	}
3602
3603	#[test]
3604	fn origin_list_replace_first() {
3605		let mut list = OriginList::new();
3606		for _ in 0..3 {
3607			list.push(Origin::UNKNOWN).unwrap();
3608		}
3609
3610		// Rewrites only the first placeholder, keeping the length the same.
3611		assert!(list.replace_first(Origin::UNKNOWN, Origin::new(7).unwrap()));
3612		assert_eq!(
3613			list.as_slice(),
3614			&[Origin::new(7).unwrap(), Origin::UNKNOWN, Origin::UNKNOWN]
3615		);
3616
3617		// No match leaves the list untouched.
3618		assert!(!list.replace_first(Origin::new(99).unwrap(), Origin::new(8).unwrap()));
3619		assert_eq!(list.len(), 3);
3620	}
3621
3622	#[test]
3623	fn origin_list_try_from_vec_enforces_limit() {
3624		let under: Vec<Origin> = (0..MAX_HOPS).map(|_| Origin::random()).collect();
3625		assert!(OriginList::try_from(under).is_ok());
3626
3627		let over: Vec<Origin> = (0..MAX_HOPS + 1).map(|_| Origin::random()).collect();
3628		assert_eq!(OriginList::try_from(over), Err(TooManyOrigins));
3629	}
3630
3631	#[tokio::test]
3632	async fn test_announce() {
3633		tokio::time::pause();
3634
3635		let origin = Origin::random().produce();
3636
3637		let mut consumer1 = origin.consume().announced();
3638		consumer1.assert_next_wait();
3639
3640		// Publish the first broadcast; it becomes visible asynchronously.
3641		let mut broadcast1 = origin.create_broadcast("test1", announce()).unwrap();
3642		settle().await;
3643
3644		consumer1.assert_next_some("test1");
3645		consumer1.assert_next_wait();
3646
3647		// Make a new consumer that should get the existing broadcast.
3648		// But we don't consume it yet.
3649		let mut consumer2 = origin.consume().announced();
3650
3651		// Publish the second broadcast.
3652		let mut broadcast2 = origin.create_broadcast("test2", announce()).unwrap();
3653		settle().await;
3654
3655		consumer1.assert_next_some("test2");
3656		consumer1.assert_next_wait();
3657
3658		consumer2.assert_next_some("test1");
3659		consumer2.assert_next_some("test2");
3660		consumer2.assert_next_wait();
3661
3662		// Finish the first broadcast: a graceful end unannounces immediately.
3663		broadcast1.finish();
3664		settle().await;
3665
3666		// All consumers should get a None now.
3667		consumer1.assert_next_none("test1");
3668		consumer2.assert_next_none("test1");
3669		consumer1.assert_next_wait();
3670		consumer2.assert_next_wait();
3671
3672		// And a new consumer only gets the last broadcast.
3673		let mut consumer3 = origin.consume().announced();
3674		consumer3.assert_next_some("test2");
3675		consumer3.assert_next_wait();
3676
3677		broadcast2.finish();
3678		settle().await;
3679
3680		consumer1.assert_next_none("test2");
3681		consumer2.assert_next_none("test2");
3682		consumer3.assert_next_none("test2");
3683	}
3684
3685	/// Multiple sources created at one path feed a single origin-owned broadcast:
3686	/// one announce, no churn as sources come and go, and an unannounce only when
3687	/// the last source leaves.
3688	#[tokio::test]
3689	async fn test_duplicate() {
3690		tokio::time::pause();
3691
3692		let origin = Origin::random().produce();
3693		let consumer = origin.consume();
3694		let mut announced = consumer.announced();
3695
3696		let mut broadcast1 = origin.create_broadcast("test", announce()).unwrap();
3697		let mut broadcast2 = origin.create_broadcast("test", announce()).unwrap();
3698		let mut broadcast3 = origin.create_broadcast("test", announce()).unwrap();
3699		settle().await;
3700		assert!(consumer.get_broadcast("test").is_some());
3701
3702		announced.assert_next_some("test");
3703		announced.assert_next_wait();
3704
3705		// A standby source finishing changes nothing.
3706		broadcast2.finish();
3707		settle().await;
3708		assert!(consumer.get_broadcast("test").is_some());
3709		announced.assert_next_wait();
3710
3711		// The active source finishing hands over to a survivor, invisibly.
3712		broadcast1.finish();
3713		settle().await;
3714		assert!(consumer.get_broadcast("test").is_some());
3715		announced.assert_next_wait();
3716
3717		// The last source finishing unannounces and removes the broadcast.
3718		broadcast3.finish();
3719		settle().await;
3720		assert!(consumer.get_broadcast("test").is_none());
3721
3722		announced.assert_next_none("test");
3723		announced.assert_next_wait();
3724	}
3725
3726	/// A source dying mid-serve fails over: the track re-splices from the standby
3727	/// source and resumes exactly at the first missing group.
3728	#[tokio::test]
3729	async fn test_route_failover() {
3730		tokio::time::pause();
3731
3732		let origin = Origin::random().produce();
3733		let consumer = origin.consume();
3734		let mut announced = consumer.announced();
3735
3736		// Both routes share the first hop (the original publisher): only
3737		// interchangeable content may join as a standby.
3738		let hops_a = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
3739		let hops_b = OriginList::try_from(vec![Origin::new(1).unwrap(), Origin::new(3).unwrap()]).unwrap();
3740
3741		// The first source announces the broadcast.
3742		let source_a = origin.create_broadcast("test", announce().with_hops(hops_a)).unwrap();
3743		let mut dynamic_a = source_a.dynamic();
3744		settle().await;
3745		settle().await;
3746		let broadcast = consumer.request_broadcast("test").await.unwrap();
3747		announced.assert_next_some("test");
3748
3749		// A second (longer) source joins silently as a standby.
3750		let source_b = origin.create_broadcast("test", announce().with_hops(hops_b)).unwrap();
3751		let mut dynamic_b = source_b.dynamic();
3752		settle().await;
3753		settle().await;
3754		announced.assert_next_wait();
3755
3756		// Subscribing dispatches the track to the best source (A).
3757		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3758		let mut producer = accept_track(&mut dynamic_a, "video").await;
3759		settle().await;
3760		dynamic_b.assert_no_request();
3761
3762		let mut sub = subscribing.await.unwrap();
3763		// Demand registers as the subscriber polls; a fresh segment carries no
3764		// boundary, so the demand is the subscriber's own.
3765		sub.assert_no_group();
3766		assert_eq!(producer.subscription().unwrap().group_start, None);
3767
3768		producer.append_group().unwrap();
3769		producer.append_group().unwrap();
3770		assert_eq!(sub.assert_group().sequence, 0);
3771		assert_eq!(sub.assert_group().sequence, 1);
3772
3773		// Source A dies (session loss): the track re-splices from B and nothing
3774		// is announced.
3775		// abort() consumes the producer, so this both aborts and drops it.
3776		producer.abort(Error::Dropped).unwrap();
3777		source_a.abort(Error::Dropped).unwrap();
3778		drop(dynamic_a);
3779		settle().await;
3780		announced.assert_next_wait();
3781
3782		// The new copy resumes one past the spliced groups: its demand starts at
3783		// the boundary, and groups the old source already delivered are filtered.
3784		let mut producer = accept_track(&mut dynamic_b, "video").await;
3785		settle().await;
3786		sub.assert_no_group();
3787		assert_eq!(producer.subscription().unwrap().group_start, Some(2));
3788		producer.create_group(group::Info { sequence: 1 }).unwrap();
3789		producer.create_group(group::Info { sequence: 2 }).unwrap();
3790		assert_eq!(sub.assert_group().sequence, 2, "groups below the boundary are filtered");
3791		sub.assert_not_closed();
3792	}
3793
3794	/// `route_changed` yields the current route first, then each change; equal
3795	/// updates coalesce, and the watch errors once every producer is gone.
3796	#[tokio::test]
3797	async fn test_broadcast_route_watch() {
3798		let mut producer = broadcast::Info::new().produce();
3799		let mut consumer = producer.consume();
3800
3801		// Initial value: the default route.
3802		assert_eq!(consumer.route_changed().await.unwrap(), broadcast::Route::default());
3803
3804		// An equal update is a no-op.
3805		producer.set_route(broadcast::Route::default()).unwrap();
3806		assert!(consumer.route_changed().now_or_never().is_none());
3807
3808		let mut hops = OriginList::new();
3809		hops.push(Origin::new(7).unwrap()).unwrap();
3810		let route = broadcast::Route::new().with_hops(hops).with_cost(3);
3811		producer.set_route(route.clone()).unwrap();
3812		assert_eq!(consumer.route_changed().await.unwrap(), route);
3813
3814		// A fresh consumer sees the current value immediately.
3815		let mut fresh = producer.consume();
3816		assert_eq!(fresh.route_changed().await.unwrap(), route);
3817
3818		drop(producer);
3819		assert!(matches!(consumer.route_changed().await.unwrap_err(), Error::Dropped));
3820	}
3821
3822	/// A cost update that flips the winning source hands live tracks over at a
3823	/// group boundary and re-advertises the broadcast's route, without announce
3824	/// churn.
3825	#[tokio::test]
3826	async fn test_route_cost_update() {
3827		tokio::time::pause();
3828
3829		// The takeover happens while a subscriber is live (carrying), so the local
3830		// origin must win the handover key comparison against B's announcing hop
3831		// (origin 3); a random id would flake on the hash.
3832		let origin = Info::new(origin_keyed("test", Origin::new(3).unwrap(), true)).produce();
3833		let consumer = origin.consume();
3834		let mut announced = consumer.announced();
3835
3836		// Both routes share the first hop (the original publisher): only
3837		// interchangeable content may join as a standby.
3838		let hops_a = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
3839		let hops_b = OriginList::try_from(vec![Origin::new(1).unwrap(), Origin::new(3).unwrap()]).unwrap();
3840
3841		// A (shorter chain) wins at equal cost.
3842		let mut source_a = origin
3843			.create_broadcast("test", announce().with_hops(hops_a.clone()))
3844			.unwrap();
3845		let mut dynamic_a = source_a.dynamic();
3846		settle().await;
3847		let broadcast = consumer.request_broadcast("test").await.unwrap();
3848		announced.assert_next_some("test");
3849
3850		let mut watch = broadcast.clone();
3851		assert_eq!(watch.route_changed().await.unwrap().hops, hops_a);
3852
3853		let mut source_b = origin
3854			.create_broadcast("test", announce().with_hops(hops_b.clone()))
3855			.unwrap();
3856		let mut dynamic_b = source_b.dynamic();
3857		settle().await;
3858		assert!(
3859			watch.route_changed().now_or_never().is_none(),
3860			"a losing standby must not change the advertised route"
3861		);
3862
3863		// Dispatch the track to A and deliver a group.
3864		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3865		let mut producer = accept_track(&mut dynamic_a, "video").await;
3866		settle().await;
3867		let mut sub = subscribing.await.unwrap();
3868		producer.append_group().unwrap();
3869		assert_eq!(sub.assert_group().sequence, 0);
3870
3871		// A's cost rises above B's: B takes over at the boundary and the
3872		// broadcast re-advertises B's route. No announce events.
3873		source_a
3874			.set_route(announce().with_hops(hops_a.clone()).with_cost(10))
3875			.unwrap();
3876		settle().await;
3877		assert_eq!(watch.route_changed().await.unwrap().hops, hops_b);
3878		announced.assert_next_wait();
3879
3880		let mut producer_b = accept_track(&mut dynamic_b, "video").await;
3881		settle().await;
3882		// Demand registers as the subscriber polls; the new segment starts at the
3883		// splice boundary.
3884		sub.assert_no_group();
3885		assert_eq!(producer_b.subscription().unwrap().group_start, Some(1));
3886		producer_b.create_group(group::Info { sequence: 1 }).unwrap();
3887		assert_eq!(sub.assert_group().sequence, 1);
3888		sub.assert_not_closed();
3889
3890		// The active source updating its own metadata re-advertises in place.
3891		source_b
3892			.set_route(announce().with_hops(hops_b.clone()).with_cost(5))
3893			.unwrap();
3894		settle().await;
3895		let advertised = watch.route_changed().await.unwrap();
3896		assert_eq!(advertised.hops, hops_b);
3897		assert_eq!(advertised.cost, 5);
3898		announced.assert_next_wait();
3899	}
3900
3901	/// A track completed for good must survive later source churn: it is never
3902	/// re-dispatched, and late subscribers still see a clean end.
3903	#[tokio::test]
3904	async fn test_completed_track_survives_route_churn() {
3905		tokio::time::pause();
3906
3907		let origin = Origin::random().produce();
3908		let consumer = origin.consume();
3909
3910		// Shared first hop, so B is a standby rather than a parked replacement.
3911		let hops_a = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
3912		let hops_b = OriginList::try_from(vec![Origin::new(1).unwrap(), Origin::new(3).unwrap()]).unwrap();
3913
3914		let source_a = origin.create_broadcast("test", announce().with_hops(hops_a)).unwrap();
3915		let mut dynamic_a = source_a.dynamic();
3916		settle().await;
3917		let source_b = origin.create_broadcast("test", announce().with_hops(hops_b)).unwrap();
3918		let mut dynamic_b = source_b.dynamic();
3919		settle().await;
3920		settle().await;
3921		let broadcast = consumer.request_broadcast("test").await.unwrap();
3922
3923		// Serve the track via A and end it for good.
3924		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3925		let mut producer = accept_track(&mut dynamic_a, "video").await;
3926		settle().await;
3927		let mut sub = subscribing.await.unwrap();
3928		producer.append_group().unwrap();
3929		assert_eq!(sub.assert_group().sequence, 0);
3930		producer.finish().unwrap();
3931		drop(producer);
3932		settle().await;
3933		sub.assert_closed();
3934
3935		// A detaching must not re-dispatch the finished track to B.
3936		source_a.abort(Error::Dropped).unwrap();
3937		drop(dynamic_a);
3938		settle().await;
3939		dynamic_b.assert_no_request();
3940
3941		// A late subscriber sees the same clean end, not an abort.
3942		let mut late = broadcast.track("video").unwrap().subscribe(None).await.unwrap();
3943		late.assert_closed();
3944	}
3945
3946	/// A source rejecting a track ends the logical track immediately, with the
3947	/// source's own error: which tracks a broadcast carries is the publisher's
3948	/// contract, so there is no sweep of other routes and no retry budget.
3949	#[tokio::test]
3950	async fn test_refused_track_aborts_instantly() {
3951		tokio::time::pause();
3952
3953		let origin = Origin::random().produce();
3954		let consumer = origin.consume();
3955
3956		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
3957		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
3958		let mut dynamic = source.dynamic();
3959		settle().await;
3960		settle().await;
3961		let broadcast = consumer.request_broadcast("test").await.unwrap();
3962
3963		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3964		let request = dynamic.requested_track().await.unwrap();
3965		request.reject(Error::NotFound);
3966		settle().await;
3967
3968		// One refusal is the verdict; the source is never re-asked.
3969		assert!(matches!(subscribing.await, Err(Error::NotFound)));
3970		dynamic.assert_no_request();
3971	}
3972
3973	/// A rejection only rules its source out of the track, so a better route
3974	/// taking over while the original source's info request is pending (and the
3975	/// stale source rejecting at the same moment) rides the handover instead of
3976	/// aborting the subscription.
3977	#[tokio::test]
3978	async fn test_stale_rejection_does_not_abort_a_handover() {
3979		tokio::time::pause();
3980
3981		let origin = Origin::random().produce();
3982		let consumer = origin.consume();
3983
3984		let publisher = Origin::new(1).unwrap();
3985		let peer = Origin::new(5).unwrap();
3986		let via_peer = OriginList::try_from(vec![publisher, peer]).unwrap();
3987		let local = OriginList::try_from(vec![publisher]).unwrap();
3988
3989		// The only route: dispatch parks on its pending info request.
3990		let source_remote = origin
3991			.create_broadcast("test", announce().with_hops(via_peer).with_cost(2))
3992			.unwrap();
3993		let mut dynamic_remote = source_remote.dynamic();
3994		settle().await;
3995		settle().await;
3996		let broadcast = consumer.request_broadcast("test").await.unwrap();
3997		let subscribing = broadcast.track("video").unwrap().subscribe(None);
3998		let request_remote = dynamic_remote.requested_track().await.unwrap();
3999
4000		// A better route attaches (taking dispatch) while the old source's
4001		// request is still pending; the old source rejects in the same window.
4002		let source_local = origin.create_broadcast("test", announce().with_hops(local)).unwrap();
4003		let mut dynamic_local = source_local.dynamic();
4004		request_remote.reject(Error::NotFound);
4005		settle().await;
4006
4007		// The subscription rides the handover onto the new route.
4008		let mut producer_local = accept_track(&mut dynamic_local, "video").await;
4009		settle().await;
4010		let mut sub = subscribing
4011			.await
4012			.expect("the handover must win over the stale rejection");
4013		producer_local.append_group().unwrap();
4014		assert_eq!(sub.assert_group().sequence, 0);
4015		sub.assert_not_closed();
4016	}
4017
4018	/// A better source attaching mid-subscription takes the track over at an
4019	/// explicit group boundary: the old copy's demand is capped, the new copy
4020	/// starts at the boundary, and the subscriber reads a seamless sequence.
4021	#[tokio::test]
4022	async fn test_route_handover() {
4023		tokio::time::pause();
4024
4025		let origin = Origin::random().produce();
4026		let consumer = origin.consume();
4027		let mut announced = consumer.announced();
4028
4029		// Shared first hop, so the short route joins as an interchangeable source.
4030		let hops_long = OriginList::try_from(vec![Origin::new(1).unwrap(), Origin::new(3).unwrap()]).unwrap();
4031		let hops_short = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4032
4033		let source_a = origin
4034			.create_broadcast("test", announce().with_hops(hops_long))
4035			.unwrap();
4036		let mut dynamic_a = source_a.dynamic();
4037		settle().await;
4038		settle().await;
4039		let broadcast = consumer.request_broadcast("test").await.unwrap();
4040		announced.assert_next_some("test");
4041
4042		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4043		let mut producer_a = accept_track(&mut dynamic_a, "video").await;
4044		settle().await;
4045		let mut sub = subscribing.await.unwrap();
4046		producer_a.append_group().unwrap();
4047		producer_a.append_group().unwrap();
4048		assert_eq!(sub.assert_group().sequence, 0);
4049		assert_eq!(sub.assert_group().sequence, 1);
4050
4051		// A strictly shorter source attaches: the live track is handed over with
4052		// no announce churn.
4053		let source_b = origin
4054			.create_broadcast("test", announce().with_hops(hops_short))
4055			.unwrap();
4056		let mut dynamic_b = source_b.dynamic();
4057		settle().await;
4058		settle().await;
4059		announced.assert_next_wait();
4060
4061		let mut producer_b = accept_track(&mut dynamic_b, "video").await;
4062		settle().await;
4063
4064		// The old copy's demand is capped at the boundary; the new copy's starts
4065		// there. Both propagate as the subscriber polls.
4066		sub.assert_no_group();
4067		assert_eq!(producer_a.subscription().unwrap().group_end, Some(1));
4068		assert_eq!(producer_b.subscription().unwrap().group_start, Some(2));
4069
4070		// The old copy racing past its cap is filtered; the new copy serves on.
4071		producer_a.create_group(group::Info { sequence: 2 }).unwrap();
4072		producer_b.create_group(group::Info { sequence: 2 }).unwrap();
4073		producer_b.create_group(group::Info { sequence: 3 }).unwrap();
4074		assert_eq!(sub.assert_group().sequence, 2);
4075		assert_eq!(sub.assert_group().sequence, 3);
4076		sub.assert_no_group();
4077		sub.assert_not_closed();
4078	}
4079
4080	/// A graceful detach (deliberate unannounce) closes immediately: no linger, so
4081	/// the unannounce propagates promptly and a re-create is a fresh broadcast.
4082	#[tokio::test(start_paused = true)]
4083	async fn test_route_unannounce_immediate() {
4084		let origin = Origin::random().produce();
4085		let consumer = origin.consume();
4086		let mut announced = consumer.announced();
4087
4088		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4089		let mut source = origin
4090			.create_broadcast("test", announce().with_hops(hops.clone()))
4091			.unwrap();
4092		settle().await;
4093		let broadcast = consumer.request_broadcast("test").await.unwrap();
4094		announced.assert_next_some("test");
4095
4096		// The peer deliberately unannounced: no reconnect window, the broadcast is
4097		// gone as soon as the teardown task observes the close.
4098		source.finish();
4099		settle().await;
4100		announced.assert_next_none("test");
4101
4102		// A re-create at the same path is a brand-new broadcast.
4103		let _source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4104		settle().await;
4105		let fresh = consumer.request_broadcast("test").await.unwrap();
4106		announced.assert_next_some("test");
4107		assert!(
4108			!fresh.is_clone(&broadcast),
4109			"re-create must not splice the old broadcast"
4110		);
4111	}
4112
4113	/// With the default zero linger, a dying source (a session drop, not a
4114	/// deliberate unannounce) closes the broadcast just as promptly as a graceful
4115	/// one: no reconnect window, the tracks abort, and a re-create is a fresh
4116	/// broadcast rather than a splice.
4117	#[tokio::test(start_paused = true)]
4118	async fn test_route_detach_immediate() {
4119		let origin = Origin::random().produce();
4120		let consumer = origin.consume();
4121		let mut announced = consumer.announced();
4122
4123		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4124		let source = origin
4125			.create_broadcast("test", announce().with_hops(hops.clone()))
4126			.unwrap();
4127		let mut dynamic = source.dynamic();
4128		settle().await;
4129		settle().await;
4130		let broadcast = consumer.request_broadcast("test").await.unwrap();
4131		announced.assert_next_some("test");
4132
4133		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4134		let producer = accept_track(&mut dynamic, "video").await;
4135		settle().await;
4136		let mut sub = subscribing.await.unwrap();
4137
4138		// The session dies without unannouncing.
4139		drop(producer);
4140		source.abort(Error::Dropped).unwrap();
4141		drop(dynamic);
4142
4143		settle().await;
4144		announced.assert_next_none("test");
4145		sub.assert_error();
4146
4147		// A reconnecting session gets a brand-new broadcast, not a splice into
4148		// the old one.
4149		let _source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4150		settle().await;
4151		settle().await;
4152		let fresh = consumer.request_broadcast("test").await.unwrap();
4153		announced.assert_next_some("test");
4154		assert!(
4155			!fresh.is_clone(&broadcast),
4156			"re-create must not splice the old broadcast"
4157		);
4158	}
4159
4160	/// A track nobody reads keeps the source's copy for [`TRACK_IDLE_LINGER`], then
4161	/// releases it. Crucially, the release must not immediately re-splice: the same
4162	/// demand signal gates both directions, so an idle track settles instead of
4163	/// re-requesting the track (and its info) every linger.
4164	#[tokio::test(start_paused = true)]
4165	async fn test_idle_track_releases_without_respinning() {
4166		let origin = Info::new(Origin::random()).produce();
4167		let consumer = origin.consume();
4168
4169		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4170		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4171		let mut dynamic = source.dynamic();
4172		settle().await;
4173		let broadcast = consumer.request_broadcast("test").await.unwrap();
4174
4175		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4176		let producer = accept_track(&mut dynamic, "video").await;
4177		settle().await;
4178		let sub = subscribing.await.unwrap();
4179
4180		// The reader leaves, but the copy stays warm inside the window so a viewer
4181		// coming back (or a follow-up fetch) reuses it.
4182		drop(sub);
4183		tokio::time::sleep(TRACK_IDLE_LINGER / 2).await;
4184		settle().await;
4185		assert!(
4186			producer.poll_unused(&kio::Waiter::noop()).is_pending(),
4187			"the copy must stay spliced inside the linger",
4188		);
4189
4190		// Past the window the segment is released, so the serving session sees its
4191		// copy go unused and can drop it (along with the track info).
4192		tokio::time::sleep(TRACK_IDLE_LINGER).await;
4193		settle().await;
4194		assert!(
4195			producer.poll_unused(&kio::Waiter::noop()).is_ready(),
4196			"an idle copy must be released after the linger",
4197		);
4198
4199		// The anti-spin property: the release must not re-arm the splice. Ungated,
4200		// the loop re-attaches the copy immediately and drops it again every linger,
4201		// re-requesting the track (and its info) from the session each time it dies.
4202		for _ in 0..3 {
4203			tokio::time::sleep(TRACK_IDLE_LINGER).await;
4204			settle().await;
4205			assert!(
4206				producer.poll_unused(&kio::Waiter::noop()).is_ready(),
4207				"an unread copy must stay released, not be re-spliced",
4208			);
4209		}
4210		assert!(
4211			dynamic.requested_track().now_or_never().is_none(),
4212			"an unread track must not be re-requested",
4213		);
4214		drop(producer);
4215
4216		// A returning reader re-splices: the origin asks the source for a fresh copy.
4217		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4218		let mut producer = accept_track(&mut dynamic, "video").await;
4219		settle().await;
4220		let mut sub = subscribing.await.unwrap();
4221		producer.append_group().unwrap();
4222		assert_eq!(sub.assert_group().sequence, 0);
4223	}
4224
4225	/// Back-to-back fetches reuse the source's copy: only the first asks the source
4226	/// for the track, so a fetch-driven consumer (HLS pulling segment after segment)
4227	/// doesn't re-request the track, and its `TRACK_INFO`, for every group.
4228	#[tokio::test(start_paused = true)]
4229	async fn test_back_to_back_fetches_reuse_the_track() {
4230		let origin = Info::new(Origin::random()).produce();
4231		let consumer = origin.consume();
4232
4233		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4234		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4235		let mut dynamic = source.dynamic();
4236		settle().await;
4237		let broadcast = consumer.request_broadcast("test").await.unwrap();
4238
4239		// The first fetch has to ask the source for the track.
4240		let fetching = broadcast.track("video").unwrap().fetch_group(0, None);
4241		let mut producer = accept_track(&mut dynamic, "video").await;
4242		producer.append_group().unwrap().finish().unwrap();
4243		settle().await;
4244		let first = fetching.await.expect("first fetch");
4245		drop(first);
4246
4247		// A second fetch inside the linger reuses the copy already spliced in.
4248		settle().await;
4249		let fetching = broadcast.track("video").unwrap().fetch_group(0, None);
4250		settle().await;
4251		assert!(
4252			dynamic.requested_track().now_or_never().is_none(),
4253			"a fetch inside the linger must reuse the track, not re-request it",
4254		);
4255		drop(fetching.await.expect("second fetch"));
4256
4257		// Once the fetches stop, the copy is released like any other idle track.
4258		tokio::time::sleep(TRACK_IDLE_LINGER * 2).await;
4259		settle().await;
4260		assert!(
4261			producer.poll_unused(&kio::Waiter::noop()).is_ready(),
4262			"the copy must be released once the fetches stop",
4263		);
4264		drop(producer);
4265
4266		// And a later fetch re-requests it: `accept_track` times out if it doesn't.
4267		settle().await;
4268		let fetching = broadcast.track("video").unwrap().fetch_group(0, None);
4269		let mut producer = accept_track(&mut dynamic, "video").await;
4270		producer.append_group().unwrap().finish().unwrap();
4271		settle().await;
4272		fetching.await.expect("fetch after the linger");
4273	}
4274
4275	/// With a linger configured, an ungraceful source loss keeps the broadcast
4276	/// alive and announced; a source re-attaching within the window splices in and
4277	/// consumers resume at the group boundary, never observing the outage.
4278	#[tokio::test(start_paused = true)]
4279	async fn test_linger_reconnect_splices() {
4280		let origin = Info::new(Origin::random())
4281			.with_linger(Duration::from_secs(5))
4282			.produce();
4283		let consumer = origin.consume();
4284		let mut announced = consumer.announced();
4285
4286		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4287		let source = origin
4288			.create_broadcast("test", announce().with_hops(hops.clone()))
4289			.unwrap();
4290		let mut dynamic = source.dynamic();
4291		settle().await;
4292		settle().await;
4293		let broadcast = consumer.request_broadcast("test").await.unwrap();
4294		announced.assert_next_some("test");
4295
4296		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4297		let mut producer = accept_track(&mut dynamic, "video").await;
4298		settle().await;
4299		let mut sub = subscribing.await.unwrap();
4300
4301		producer.append_group().unwrap();
4302		producer.append_group().unwrap();
4303		assert_eq!(sub.assert_group().sequence, 0);
4304		assert_eq!(sub.assert_group().sequence, 1);
4305
4306		// The session dies without unannouncing: the broadcast enters the linger
4307		// window instead of closing.
4308		drop(producer);
4309		source.abort(Error::Dropped).unwrap();
4310		drop(dynamic);
4311		settle().await;
4312
4313		// No unannounce, no track error: the outage is invisible so far.
4314		announced.assert_next_wait();
4315		sub.assert_no_group();
4316		sub.assert_not_closed();
4317
4318		// A consumer arriving mid-outage still resolves the lingering broadcast.
4319		let during = consumer.request_broadcast("test").await.unwrap();
4320		assert!(during.is_clone(&broadcast), "the lingering broadcast still resolves");
4321
4322		// The session reconnects within the window: the new source splices into
4323		// the same broadcast.
4324		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4325		let mut dynamic = source.dynamic();
4326		settle().await;
4327		settle().await;
4328		announced.assert_next_wait();
4329		let again = consumer.request_broadcast("test").await.unwrap();
4330		assert!(again.is_clone(&broadcast), "the reconnect must splice, not replace");
4331
4332		// The pending track re-splices from the new source and resumes one past
4333		// the groups the old source already delivered. Demand registers as the
4334		// subscriber polls.
4335		let mut producer = accept_track(&mut dynamic, "video").await;
4336		settle().await;
4337		sub.assert_no_group();
4338		assert_eq!(producer.subscription().unwrap().group_start, Some(2));
4339		producer.create_group(group::Info { sequence: 2 }).unwrap();
4340		assert_eq!(sub.assert_group().sequence, 2);
4341		sub.assert_not_closed();
4342	}
4343
4344	/// The linger window expiring without a replacement closes the broadcast: the
4345	/// path unannounces, tracks abort, and a later re-create is a fresh broadcast.
4346	#[tokio::test(start_paused = true)]
4347	async fn test_linger_expiry_closes() {
4348		let origin = Info::new(Origin::random())
4349			.with_linger(Duration::from_secs(5))
4350			.produce();
4351		let consumer = origin.consume();
4352		let mut announced = consumer.announced();
4353
4354		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4355		let source = origin
4356			.create_broadcast("test", announce().with_hops(hops.clone()))
4357			.unwrap();
4358		let mut dynamic = source.dynamic();
4359		settle().await;
4360		settle().await;
4361		let broadcast = consumer.request_broadcast("test").await.unwrap();
4362		announced.assert_next_some("test");
4363
4364		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4365		let producer = accept_track(&mut dynamic, "video").await;
4366		settle().await;
4367		let mut sub = subscribing.await.unwrap();
4368
4369		drop(producer);
4370		source.abort(Error::Dropped).unwrap();
4371		drop(dynamic);
4372		settle().await;
4373		announced.assert_next_wait();
4374
4375		// Nobody comes back: the window expires and the broadcast closes.
4376		tokio::time::sleep(std::time::Duration::from_secs(6)).await;
4377		settle().await;
4378		announced.assert_next_none("test");
4379		sub.assert_error();
4380
4381		// A session reconnecting after the window gets a brand-new broadcast.
4382		let _source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4383		settle().await;
4384		settle().await;
4385		let fresh = consumer.request_broadcast("test").await.unwrap();
4386		announced.assert_next_some("test");
4387		assert!(
4388			!fresh.is_clone(&broadcast),
4389			"a late re-create must not splice the expired broadcast"
4390		);
4391	}
4392
4393	/// A linger too large to represent as a deadline never expires: the broadcast
4394	/// outlives an arbitrarily long outage (a reconnect loop with no give-up
4395	/// timeout promises to retry forever).
4396	#[tokio::test(start_paused = true)]
4397	async fn test_linger_forever() {
4398		let origin = Info::new(Origin::random()).with_linger(Duration::MAX).produce();
4399		let consumer = origin.consume();
4400		let mut announced = consumer.announced();
4401
4402		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4403		let source = origin
4404			.create_broadcast("test", announce().with_hops(hops.clone()))
4405			.unwrap();
4406		settle().await;
4407		let broadcast = consumer.request_broadcast("test").await.unwrap();
4408		announced.assert_next_some("test");
4409
4410		source.abort(Error::Dropped).unwrap();
4411		settle().await;
4412
4413		// Days later the broadcast is still announced and still splices a reconnect.
4414		tokio::time::sleep(std::time::Duration::from_secs(60 * 60 * 24 * 3)).await;
4415		announced.assert_next_wait();
4416		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4417		settle().await;
4418		settle().await;
4419		let again = consumer.request_broadcast("test").await.unwrap();
4420		assert!(again.is_clone(&broadcast), "the reconnect must splice, not replace");
4421		drop(source);
4422	}
4423
4424	/// A lingering broadcast with a live subscription parks, then resumes on the
4425	/// reconnect.
4426	///
4427	/// An ungraceful loss empties the route table while the front waits out its
4428	/// linger, so the route a track is spliced from is gone with no replacement to
4429	/// serve it. The task has to park for the whole window on the strength of
4430	/// dropping the departed route, because nothing else bounds it: a "route gone"
4431	/// edge that keeps firing yields a wait that is Ready on every poll, a full
4432	/// core per subscribed track, and the runtime that has to deliver the
4433	/// reconnect starved along with it.
4434	///
4435	/// Under a paused clock that spin never yields, so a regression hangs here
4436	/// rather than failing.
4437	#[tokio::test(start_paused = true)]
4438	async fn test_linger_parks_a_live_subscription() {
4439		let origin = Info::new(Origin::random())
4440			.with_linger(Duration::from_secs(5))
4441			.produce();
4442		let consumer = origin.consume();
4443
4444		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4445		let source = origin
4446			.create_broadcast("test", announce().with_hops(hops.clone()))
4447			.unwrap();
4448		let mut dynamic = source.dynamic();
4449		settle().await;
4450		settle().await;
4451		let broadcast = consumer.request_broadcast("test").await.unwrap();
4452
4453		// A viewer reading a track that is written once and then stays quiet, like a
4454		// catalog.
4455		let subscribing = broadcast.track("catalog.json").unwrap().subscribe(None);
4456		let mut producer = accept_track(&mut dynamic, "catalog.json").await;
4457		settle().await;
4458		let mut sub = subscribing.await.unwrap();
4459		producer.append_group().unwrap();
4460		assert_eq!(sub.assert_group().sequence, 0);
4461
4462		// The publisher's session dies abruptly: the table empties and the front
4463		// lingers, holding the subscription open for a reconnect. The track copy
4464		// outlives the broadcast (closes don't cascade), so nothing reports the
4465		// spliced segment as ended: the departed route is the only edge left.
4466		source.abort(Error::Dropped).unwrap();
4467		settle().await;
4468		settle().await;
4469		sub.assert_not_closed();
4470
4471		// Most of the window with no source at all: the subscription stays parked
4472		// rather than being cut, which is what the linger promises a reconnect.
4473		tokio::time::sleep(Duration::from_secs(4)).await;
4474		settle().await;
4475		sub.assert_not_closed();
4476
4477		// The reconnect inside the window resumes the same subscription.
4478		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4479		let mut dynamic = source.dynamic();
4480		settle().await;
4481		let mut producer = accept_track(&mut dynamic, "catalog.json").await;
4482		settle().await;
4483		producer.create_group(group::Info { sequence: 1 }).unwrap();
4484		assert_eq!(sub.assert_group().sequence, 1);
4485		sub.assert_not_closed();
4486	}
4487
4488	/// An idle segment is released even once the route that produced it is gone.
4489	///
4490	/// A departed route drops the loop's handle on it, so the idle countdown has to
4491	/// key off the segment itself. Otherwise the segment is stranded for the life of
4492	/// the front, pinning the dead source's cached groups.
4493	///
4494	/// Asserted through the boundary a stranded segment would leave behind, since
4495	/// `resume` is private and delivery is what a viewer actually feels: a released
4496	/// segment set splices the next source unbounded, so its first group arrives,
4497	/// while a retained one caps it below that edge.
4498	#[tokio::test(start_paused = true)]
4499	async fn test_idle_release_survives_the_route_leaving() {
4500		let origin = Info::new(Origin::random())
4501			.with_linger(Duration::from_secs(600))
4502			.produce();
4503		let consumer = origin.consume();
4504
4505		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4506		let source = origin
4507			.create_broadcast("test", announce().with_hops(hops.clone()))
4508			.unwrap();
4509		let mut dynamic = source.dynamic();
4510		settle().await;
4511		settle().await;
4512		let broadcast = consumer.request_broadcast("test").await.unwrap();
4513
4514		let subscribing = broadcast.track("catalog.json").unwrap().subscribe(None);
4515		let mut producer = accept_track(&mut dynamic, "catalog.json").await;
4516		settle().await;
4517		let mut sub = subscribing.await.unwrap();
4518		producer.append_group().unwrap();
4519		assert_eq!(sub.assert_group().sequence, 0);
4520
4521		// The publisher's session dies, then the viewer gives up: nothing holds the
4522		// segment, and nothing is left to serve the track.
4523		source.abort(Error::Dropped).unwrap();
4524		settle().await;
4525		settle().await;
4526		drop(sub);
4527		drop(producer);
4528		drop(dynamic);
4529		settle().await;
4530		tokio::time::sleep(TRACK_IDLE_LINGER + Duration::from_secs(1)).await;
4531		settle().await;
4532
4533		// The publisher reconnects under the same identity, so it joins the front as
4534		// a route rather than replacing it, and restarts its group numbering.
4535		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4536		let mut dynamic = source.dynamic();
4537		settle().await;
4538		settle().await;
4539		let broadcast = consumer.request_broadcast("test").await.unwrap();
4540		let subscribing = broadcast.track("catalog.json").unwrap().subscribe(None);
4541		let mut producer = accept_track(&mut dynamic, "catalog.json").await;
4542		settle().await;
4543		let mut sub = subscribing.await.unwrap();
4544		producer.append_group().unwrap();
4545		assert_eq!(
4546			sub.assert_group().sequence,
4547			0,
4548			"the reconnect's first group must not be filtered by a stale boundary"
4549		);
4550	}
4551
4552	/// A deliberate finish never lingers, even with a linger configured: a clean
4553	/// unannounce from a peer must propagate immediately.
4554	#[tokio::test(start_paused = true)]
4555	async fn test_linger_skipped_on_finish() {
4556		let origin = Info::new(Origin::random())
4557			.with_linger(Duration::from_secs(5))
4558			.produce();
4559		let consumer = origin.consume();
4560		let mut announced = consumer.announced();
4561
4562		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4563		let mut source = origin
4564			.create_broadcast("test", announce().with_hops(hops.clone()))
4565			.unwrap();
4566		settle().await;
4567		let broadcast = consumer.request_broadcast("test").await.unwrap();
4568		announced.assert_next_some("test");
4569
4570		// A clean unannounce: the broadcast is gone as soon as the teardown task
4571		// observes the close, with no reconnect window.
4572		source.finish();
4573		settle().await;
4574		announced.assert_next_none("test");
4575
4576		// A re-create at the same path is a brand-new broadcast.
4577		let _source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
4578		settle().await;
4579		let fresh = consumer.request_broadcast("test").await.unwrap();
4580		announced.assert_next_some("test");
4581		assert!(
4582			!fresh.is_clone(&broadcast),
4583			"a finish must not leave a lingering broadcast to splice into"
4584		);
4585	}
4586
4587	/// A non-live broadcast is reachable by exact path but never announced;
4588	/// toggling `live` announces and unannounces without touching the broadcast.
4589	#[tokio::test]
4590	async fn test_announce_toggle() {
4591		tokio::time::pause();
4592
4593		let origin = Origin::random().produce();
4594		let consumer = origin.consume();
4595		let mut announced = consumer.announced();
4596
4597		let mut source = origin.create_broadcast("test", broadcast::Route::new()).unwrap();
4598		settle().await;
4599
4600		// Routable but not announced.
4601		announced.assert_next_wait();
4602		let broadcast = consumer
4603			.get_broadcast("test")
4604			.expect("offline broadcast is still routable");
4605		assert!(!broadcast.route().announce);
4606
4607		// request_broadcast resolves the offline broadcast too.
4608		let requested = consumer.request_broadcast("test").await.unwrap();
4609		assert!(requested.is_clone(&broadcast));
4610
4611		// Going live announces.
4612		source.set_route(announce()).unwrap();
4613		settle().await;
4614		let face = announced.assert_next_some("test");
4615		assert!(face.is_clone(&broadcast));
4616
4617		// A fresh consumer replays only announced broadcasts.
4618		let mut fresh = origin.consume().announced();
4619		fresh.assert_next_some("test");
4620		fresh.assert_next_wait();
4621
4622		// Going offline unannounces but stays routable.
4623		source.set_route(broadcast::Route::new()).unwrap();
4624		settle().await;
4625		announced.assert_next_none("test");
4626		assert!(consumer.get_broadcast("test").is_some());
4627		let mut fresh = origin.consume().announced();
4628		fresh.assert_next_wait();
4629
4630		source.finish();
4631		settle().await;
4632		assert!(consumer.get_broadcast("test").is_none());
4633	}
4634
4635	/// An announced source outranks a cheaper offline one, so the broadcast
4636	/// stays announced and serves from it.
4637	#[tokio::test]
4638	async fn test_announce_beats_offline() {
4639		tokio::time::pause();
4640
4641		let origin = Origin::random().produce();
4642		let consumer = origin.consume();
4643		let mut announced = consumer.announced();
4644
4645		// An unannounced source with the best cost.
4646		let _offline = origin.create_broadcast("test", broadcast::Route::new()).unwrap();
4647		settle().await;
4648		announced.assert_next_wait();
4649
4650		// An announced source with a worse cost still wins: the path announces
4651		// and advertises its route.
4652		let mut announced_source = origin.create_broadcast("test", announce().with_cost(10)).unwrap();
4653		settle().await;
4654		announced.assert_next_some("test");
4655		let face = consumer.get_broadcast("test").unwrap();
4656		assert!(face.route().announce);
4657		assert_eq!(face.route().cost, 10);
4658
4659		// The announced source leaving falls back to the offline one: the path
4660		// unannounces but stays routable.
4661		announced_source.finish();
4662		settle().await;
4663		announced.assert_next_none("test");
4664		assert!(consumer.get_broadcast("test").is_some());
4665	}
4666
4667	/// A better source attaching does not churn announces: the broadcast identity
4668	/// is origin-owned, so the swap is invisible to consumers.
4669	#[tokio::test]
4670	async fn test_better_source_no_churn() {
4671		tokio::time::pause();
4672
4673		let origin = Origin::random().produce();
4674		let mut announced = origin.consume().announced();
4675
4676		// `a` carries two hops; `b` reaches the same publisher in one, so `b`
4677		// wins dispatch when it joins.
4678		let hops_a = OriginList::try_from(vec![Origin::new(1).unwrap(), Origin::new(3).unwrap()]).unwrap();
4679		let hops_b = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4680		let _a = origin.create_broadcast("test", announce().with_hops(hops_a)).unwrap();
4681		settle().await;
4682		let face = announced.assert_next_some("test");
4683
4684		let _b = origin
4685			.create_broadcast("test", announce().with_hops(hops_b.clone()))
4686			.unwrap();
4687		settle().await;
4688		announced.assert_next_wait();
4689		let current = origin.consume().get_broadcast("test").unwrap();
4690		assert!(current.is_clone(&face), "the broadcast identity must not change");
4691		// The face now advertises the winning (shorter) route.
4692		assert_eq!(current.route().hops, hops_b);
4693	}
4694
4695	/// A second source with a different original publisher (first hop) is new
4696	/// content, not a standby: it must not splice into the incumbent's
4697	/// subscribers. It takes the path over immediately, as a real unannounce +
4698	/// announce, rather than waiting out an incumbent whose session may only be
4699	/// alive because the transport has not timed it out yet.
4700	#[tokio::test]
4701	async fn test_publisher_mismatch_replaces() {
4702		tokio::time::pause();
4703
4704		let origin = Origin::random().produce();
4705		let consumer = origin.consume();
4706		let mut announced = consumer.announced();
4707
4708		let hops_a = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4709		let hops_b = OriginList::try_from(vec![Origin::new(2).unwrap()]).unwrap();
4710
4711		let mut source_a = origin
4712			.create_broadcast("test", announce().with_hops(hops_a.clone()))
4713			.unwrap();
4714		settle().await;
4715		let face_a = announced.assert_next_some("test");
4716
4717		// A different publisher at the same path: the newcomer wins it now, while
4718		// the incumbent is still attached and still believes it is publishing.
4719		let _source_b = origin
4720			.create_broadcast("test", announce().with_hops(hops_b.clone()))
4721			.unwrap();
4722		settle().await;
4723		settle().await;
4724		announced.assert_next_none("test");
4725		let face_b = announced.assert_next_some("test");
4726		assert!(!face_b.is_clone(&face_a), "a replacement, never a splice");
4727		assert_eq!(consumer.get_broadcast("test").unwrap().route().hops, hops_b);
4728		// The displaced front is torn down, not merely unpublished: leaving it
4729		// running would strand its subscribers and its source watchers on a face
4730		// nothing can reach.
4731		assert!(face_a.is_closed(), "the displaced front must close");
4732
4733		// The displaced incumbent ending is invisible: it no longer owns the path.
4734		source_a.finish();
4735		settle().await;
4736		settle().await;
4737		announced.assert_next_wait();
4738		assert_eq!(consumer.get_broadcast("test").unwrap().route().hops, hops_b);
4739	}
4740
4741	/// A publisher reconnecting under the same identity attaches as a second
4742	/// route with an identical hop chain and cost. The new session is the one
4743	/// actually carrying frames, so it must win selection immediately rather than
4744	/// waiting for the transport to retire the old one.
4745	#[tokio::test]
4746	async fn test_reconnect_wins_over_stale_route() {
4747		tokio::time::pause();
4748
4749		let origin = Origin::random().produce();
4750		let consumer = origin.consume();
4751
4752		let publisher = Origin::new(1).unwrap();
4753		let hops = OriginList::try_from(vec![publisher]).unwrap();
4754
4755		// The original session, still attached: its QUIC connection has not been
4756		// declared dead yet.
4757		let stale = origin
4758			.create_broadcast("test", announce().with_hops(hops.clone()))
4759			.unwrap();
4760		let mut stale_dynamic = stale.dynamic();
4761		settle().await;
4762
4763		// The same publisher reconnecting over a fresh session.
4764		let fresh = origin
4765			.create_broadcast("test", announce().with_hops(hops.clone()))
4766			.unwrap();
4767		let mut fresh_dynamic = fresh.dynamic();
4768		settle().await;
4769		settle().await;
4770
4771		// Track requests dispatch to the reconnect, not the corpse.
4772		let broadcast = consumer.request_broadcast("test").await.unwrap();
4773		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4774		settle().await;
4775		let _producer = accept_track(&mut fresh_dynamic, "video").await;
4776		settle().await;
4777		subscribing.await.unwrap();
4778		stale_dynamic.assert_no_request();
4779	}
4780
4781	/// The same reconnect, but arriving while a subscription is already spliced
4782	/// onto the stale route: the live track must re-splice onto the new session
4783	/// rather than ride the dead one until the transport gives up. The gate
4784	/// [`FrontState::reselect`] applies while carrying is pinned separately, in
4785	/// [`test_carrying_switches_to_benign_routes`].
4786	#[tokio::test]
4787	async fn test_carrying_reconnect_switches_immediately() {
4788		tokio::time::pause();
4789
4790		let origin = Origin::random().produce();
4791		let consumer = origin.consume();
4792
4793		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4794
4795		let stale = origin
4796			.create_broadcast("test", announce().with_hops(hops.clone()))
4797			.unwrap();
4798		let mut stale_dynamic = stale.dynamic();
4799		settle().await;
4800
4801		// A live subscription riding the original session.
4802		let broadcast = consumer.request_broadcast("test").await.unwrap();
4803		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4804		settle().await;
4805		let _stale_producer = accept_track(&mut stale_dynamic, "video").await;
4806		settle().await;
4807		// Held: the splice only follows the active route while the track is read.
4808		let _subscription = subscribing.await.unwrap();
4809
4810		// The reconnect arrives with the front already carrying.
4811		let fresh = origin
4812			.create_broadcast("test", announce().with_hops(hops.clone()))
4813			.unwrap();
4814		let mut fresh_dynamic = fresh.dynamic();
4815		settle().await;
4816		settle().await;
4817
4818		// The carrying front re-splices onto the reconnect rather than waiting for
4819		// the stale session to die.
4820		let _fresh_producer = accept_track(&mut fresh_dynamic, "video").await;
4821	}
4822
4823	/// Taking the path over is scoped to a newcomer that would actually outrank
4824	/// the incumbent. An offline source (a cache, or an on-demand handler) is
4825	/// ranked below every announced route, so arriving under a different
4826	/// publisher must not unannounce a live broadcast and cut its subscribers.
4827	///
4828	/// The tail of this test covers the park's *exit*: the parked source has to
4829	/// wake and attach once the incumbent ends. Nothing else drives that wait, so
4830	/// without this a lost wakeup would strand the source invisibly forever
4831	/// rather than failing anything.
4832	#[tokio::test]
4833	async fn test_offline_mismatch_never_evicts_a_live_front() {
4834		tokio::time::pause();
4835
4836		let origin = Origin::random().produce();
4837		let consumer = origin.consume();
4838		let mut announced = consumer.announced();
4839
4840		let hops_live = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
4841		let hops_cache = OriginList::try_from(vec![Origin::new(2).unwrap()]).unwrap();
4842
4843		let mut live = origin
4844			.create_broadcast("test", announce().with_hops(hops_live.clone()))
4845			.unwrap();
4846		let mut live_dynamic = live.dynamic();
4847		settle().await;
4848		let face = announced.assert_next_some("test");
4849
4850		// A subscriber riding the live broadcast, which the eviction would cut.
4851		let broadcast = consumer.request_broadcast("test").await.unwrap();
4852		let subscribing = broadcast.track("video").unwrap().subscribe(None);
4853		settle().await;
4854		let _producer = accept_track(&mut live_dynamic, "video").await;
4855		settle().await;
4856		subscribing.await.unwrap();
4857
4858		// An offline source for different content at the same path: it stays
4859		// invisible rather than displacing the live one.
4860		let cache = origin
4861			.create_broadcast("test", broadcast::Route::new().with_hops(hops_cache.clone()))
4862			.unwrap();
4863		settle().await;
4864		settle().await;
4865		announced.assert_next_wait();
4866		assert!(!face.is_closed(), "the live front must survive");
4867		assert_eq!(consumer.get_broadcast("test").unwrap().route().hops, hops_live);
4868
4869		// The incumbent ending hands the path to the parked source, which is the
4870		// only thing that ever wakes that wait.
4871		live.finish();
4872		settle().await;
4873		settle().await;
4874		announced.assert_next_none("test");
4875		let taken = consumer
4876			.get_broadcast("test")
4877			.expect("the parked source must take over");
4878		assert_eq!(taken.route().hops, hops_cache);
4879		// Offline, so it holds the path without being advertised.
4880		announced.assert_next_wait();
4881		drop(cache);
4882	}
4883
4884	/// A subscription from a peer the active chain flows through is served from
4885	/// the best clean source directly (data-plane split horizon), while every
4886	/// other consumer keeps the shared spliced broadcast fed by the active
4887	/// source. The two selections match what the announce loop advertises, so
4888	/// the data plane keeps the control plane's promise.
4889	#[tokio::test]
4890	async fn test_dispatch_excludes_requester() {
4891		tokio::time::pause();
4892
4893		let origin = Origin::random().produce();
4894		let consumer = origin.consume();
4895
4896		let peer = Origin::new(5).unwrap();
4897		let publisher = Origin::new(1).unwrap();
4898		// The route through the peer is cheaper, so it is the active source.
4899		let tainted = OriginList::try_from(vec![publisher, peer]).unwrap();
4900		let clean = OriginList::try_from(vec![publisher]).unwrap();
4901
4902		let source_a = origin.create_broadcast("test", announce().with_hops(tainted)).unwrap();
4903		let mut dynamic_a = source_a.dynamic();
4904		settle().await;
4905		let source_b = origin
4906			.create_broadcast("test", announce().with_hops(clean).with_cost(5))
4907			.unwrap();
4908		let mut dynamic_b = source_b.dynamic();
4909		settle().await;
4910		settle().await;
4911
4912		// An ordinary consumer rides the shared front, dispatched to the active
4913		// (peer-tainted) source.
4914		let shared = consumer.request_broadcast("test").await.unwrap();
4915		let subscribing = shared.track("video").unwrap().subscribe(None);
4916		let _producer_a = accept_track(&mut dynamic_a, "video").await;
4917		settle().await;
4918		subscribing.await.unwrap();
4919
4920		// The peer is pinned to the clean source. Crucially, nothing reaches the
4921		// via-peer source: a track request on it is what a session would forward
4922		// upstream as a SUBSCRIBE, and forwarding this one would send the peer's
4923		// own subscription back to them.
4924		let scoped = consumer.clone().excluding(peer);
4925		let pinned = scoped.request_broadcast("test").await.unwrap();
4926		let subscribing = pinned.track("video").unwrap().subscribe(None);
4927		let _producer_b = accept_track(&mut dynamic_b, "video").await;
4928		settle().await;
4929		subscribing.await.unwrap();
4930		dynamic_a.assert_no_request();
4931	}
4932
4933	/// Two publishers that never declared an identity both arrive with a first
4934	/// hop of UNKNOWN. They are unrelated content, so the second MUST replace the
4935	/// first rather than joining it as an interchangeable standby: splicing them
4936	/// would cut one publisher's subscribers over to the other's stream.
4937	#[tokio::test]
4938	async fn test_unknown_publishers_do_not_splice() {
4939		tokio::time::pause();
4940
4941		let origin = Origin::random().produce();
4942		let consumer = origin.consume();
4943		let mut announced = consumer.announced();
4944
4945		let unknown_a = OriginList::try_from(vec![Origin::UNKNOWN]).unwrap();
4946		let unknown_b = OriginList::try_from(vec![Origin::UNKNOWN]).unwrap();
4947
4948		let source_a = origin
4949			.create_broadcast("test", announce().with_hops(unknown_a))
4950			.unwrap();
4951		settle().await;
4952		settle().await;
4953		announced.assert_next_some("test");
4954
4955		// Same first hop by value, but it identifies nothing, so this is a
4956		// replacement: the path is unannounced and re-announced rather than
4957		// silently gaining a standby.
4958		let source_b = origin
4959			.create_broadcast("test", announce().with_hops(unknown_b))
4960			.unwrap();
4961		settle().await;
4962		settle().await;
4963		announced.assert_next_none("test");
4964		announced.assert_next_some("test");
4965
4966		drop(source_a);
4967		drop(source_b);
4968	}
4969
4970	/// The same two sources under a real shared publisher id do splice, which is
4971	/// what keeps the rule above about UNKNOWN rather than about hop chains.
4972	#[tokio::test]
4973	async fn test_known_publishers_still_splice() {
4974		tokio::time::pause();
4975
4976		let origin = Origin::random().produce();
4977		let consumer = origin.consume();
4978		let mut announced = consumer.announced();
4979
4980		let publisher = Origin::new(1).unwrap();
4981		let hops_a = OriginList::try_from(vec![publisher]).unwrap();
4982		let hops_b = OriginList::try_from(vec![publisher, Origin::new(3).unwrap()]).unwrap();
4983
4984		let source_a = origin.create_broadcast("test", announce().with_hops(hops_a)).unwrap();
4985		settle().await;
4986		settle().await;
4987		announced.assert_next_some("test");
4988
4989		// Shares the publisher, so it joins silently as a standby: no churn.
4990		let source_b = origin.create_broadcast("test", announce().with_hops(hops_b)).unwrap();
4991		settle().await;
4992		settle().await;
4993		announced.assert_next_wait();
4994
4995		drop(source_a);
4996		drop(source_b);
4997	}
4998
4999	/// A local standby with the same original publisher joining a front that is
5000	/// carrying the broadcast from a peer must splice the live subscription onto
5001	/// the new source, never tear it down (#2473, e2e finding 2). Redundant
5002	/// publishers sharing an origin id MUST produce the same tracks, so the
5003	/// splice resumes seamlessly at the group boundary.
5004	#[tokio::test]
5005	async fn test_standby_join_splices_live_subscriber() {
5006		tokio::time::pause();
5007
5008		let origin = Origin::random().produce();
5009		let consumer = origin.consume();
5010
5011		let publisher = Origin::new(1).unwrap();
5012		let peer = Origin::new(5).unwrap();
5013		let via_peer = OriginList::try_from(vec![publisher, peer]).unwrap();
5014		let local = OriginList::try_from(vec![publisher]).unwrap();
5015
5016		// Carrying via the peer, with a live subscriber mid-stream.
5017		let source_remote = origin
5018			.create_broadcast("test", announce().with_hops(via_peer).with_cost(2))
5019			.unwrap();
5020		let mut dynamic_remote = source_remote.dynamic();
5021		settle().await;
5022		settle().await;
5023		let broadcast = consumer.request_broadcast("test").await.unwrap();
5024		let subscribing = broadcast.track("video").unwrap().subscribe(None);
5025		let mut producer_remote = accept_track(&mut dynamic_remote, "video").await;
5026		settle().await;
5027		let mut sub = subscribing.await.unwrap();
5028		producer_remote.append_group().unwrap();
5029		assert_eq!(sub.assert_group().sequence, 0);
5030
5031		// The local standby joins with the same first hop and a cheaper route:
5032		// it wins dispatch and the live track re-splices at the boundary.
5033		let source_local = origin.create_broadcast("test", announce().with_hops(local)).unwrap();
5034		let mut dynamic_local = source_local.dynamic();
5035		settle().await;
5036		let mut producer_local = accept_track(&mut dynamic_local, "video").await;
5037		settle().await;
5038		sub.assert_no_group();
5039		assert_eq!(producer_local.subscription().unwrap().group_start, Some(1));
5040		producer_local.create_group(group::Info { sequence: 1 }).unwrap();
5041		assert_eq!(sub.assert_group().sequence, 1);
5042		sub.assert_not_closed();
5043	}
5044
5045	/// A standby that wins dispatch before creating a track must not kill a
5046	/// subscription the incumbent is serving: its refusal only rules it out of
5047	/// this track, and the incumbent keeps delivering. The refusal is still
5048	/// never retried: once the incumbent goes away every remaining source has
5049	/// refused, so the subscription aborts and the consumer's next request asks
5050	/// afresh.
5051	#[tokio::test]
5052	async fn test_standby_missing_track_keeps_incumbent() {
5053		tokio::time::pause();
5054
5055		let origin = Origin::random().produce();
5056		let consumer = origin.consume();
5057
5058		let publisher = Origin::new(1).unwrap();
5059		let peer = Origin::new(5).unwrap();
5060		let via_peer = OriginList::try_from(vec![publisher, peer]).unwrap();
5061		let local = OriginList::try_from(vec![publisher]).unwrap();
5062
5063		// Carrying via the peer, with a live subscriber mid-stream.
5064		let source_remote = origin
5065			.create_broadcast("test", announce().with_hops(via_peer).with_cost(2))
5066			.unwrap();
5067		let mut dynamic_remote = source_remote.dynamic();
5068		settle().await;
5069		settle().await;
5070		let broadcast = consumer.request_broadcast("test").await.unwrap();
5071		let subscribing = broadcast.track("audio").unwrap().subscribe(None);
5072		let mut producer_remote = accept_track(&mut dynamic_remote, "audio").await;
5073		settle().await;
5074		let mut sub = subscribing.await.unwrap();
5075		producer_remote.append_group().unwrap();
5076		assert_eq!(sub.assert_group().sequence, 0);
5077
5078		// The standby joins and wins dispatch, but has not created "audio" yet.
5079		// Its refusal must cost the incumbent nothing.
5080		let source_local = origin.create_broadcast("test", announce().with_hops(local)).unwrap();
5081		let mut dynamic_local = source_local.dynamic();
5082		settle().await;
5083		let request = dynamic_local.requested_track().await.unwrap();
5084		assert_eq!(request.name(), "audio");
5085		request.reject(Error::NotFound);
5086		settle().await;
5087
5088		// Still spliced to the incumbent, still delivering.
5089		producer_remote.append_group().unwrap();
5090		assert_eq!(sub.assert_group().sequence, 1);
5091		sub.assert_not_closed();
5092
5093		// The incumbent leaving exhausts the table (the standby's refusal is
5094		// never retried): the subscription aborts.
5095		source_remote.abort(Error::Dropped).unwrap();
5096		settle().await;
5097		settle().await;
5098		sub.assert_closed();
5099		dynamic_local.assert_no_request();
5100
5101		// A fresh consumer request asks the standby anew, which has the track now.
5102		let retry = broadcast.track("audio").unwrap().subscribe(None);
5103		let mut producer_local = accept_track(&mut dynamic_local, "audio").await;
5104		settle().await;
5105		let mut sub = retry.await.expect("a fresh request must reach the standby");
5106		producer_local.create_group(group::Info { sequence: 2 }).unwrap();
5107		assert_eq!(sub.assert_group().sequence, 2);
5108	}
5109
5110	/// A refused track aborts, but the verdict is not cached: it belongs to the
5111	/// request that received it, so a later request re-asks the source. Otherwise
5112	/// one early request for a track the publisher had not created yet leaves the
5113	/// name dead for the life of the front.
5114	#[tokio::test]
5115	async fn test_unservable_track_retried_by_a_later_request() {
5116		tokio::time::pause();
5117
5118		let origin = Origin::random().produce();
5119		let consumer = origin.consume();
5120
5121		let source = origin.create_broadcast("test", announce()).unwrap();
5122		let mut dynamic = source.dynamic();
5123		settle().await;
5124		settle().await;
5125		let broadcast = consumer.request_broadcast("test").await.unwrap();
5126
5127		// Nothing serves it: the refusal aborts the track with the source's error.
5128		let subscribing = broadcast.track("audio").unwrap().subscribe(None);
5129		let request = dynamic.requested_track().await.unwrap();
5130		request.reject(Error::NotFound);
5131		settle().await;
5132		assert!(matches!(subscribing.await, Err(Error::NotFound)));
5133
5134		// The publisher has the track now; a fresh request must reach it.
5135		let retry = broadcast.track("audio").unwrap().subscribe(None);
5136		let mut producer = accept_track(&mut dynamic, "audio").await;
5137		settle().await;
5138		let mut sub = retry.await.expect("a fresh request must reach the source");
5139		producer.append_group().unwrap();
5140		assert_eq!(sub.assert_group().sequence, 0);
5141	}
5142
5143	/// A copy that dies before delivering anything is a refusal, not a failover:
5144	/// a source whose track keeps dying right after acceptance must not
5145	/// re-splice forever. With every attached source refused, the track aborts
5146	/// with the copy's error, and the verdict belongs to that request: a fresh
5147	/// consumer request asks again.
5148	#[tokio::test]
5149	async fn test_track_dying_without_progress_aborts() {
5150		tokio::time::pause();
5151
5152		let origin = Origin::random().produce();
5153		let consumer = origin.consume();
5154
5155		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
5156		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
5157		let mut dynamic = source.dynamic();
5158		settle().await;
5159		settle().await;
5160		let broadcast = consumer.request_broadcast("test").await.unwrap();
5161
5162		let subscribing = broadcast.track("video").unwrap().subscribe(None);
5163		let producer = accept_track(&mut dynamic, "video").await;
5164		settle().await;
5165		let mut sub = subscribing.await.unwrap();
5166
5167		// The copy dies without delivering a single group, from a source that is
5168		// alive and well: that's its answer for the track, not a failover.
5169		drop(producer);
5170		settle().await;
5171		sub.assert_closed();
5172		dynamic.assert_no_request();
5173
5174		// A fresh request asks the (still attached) source anew.
5175		let retry = broadcast.track("video").unwrap().subscribe(None);
5176		let mut producer = accept_track(&mut dynamic, "video").await;
5177		settle().await;
5178		let mut sub = retry.await.expect("a fresh request must reach the source");
5179		producer.append_group().unwrap();
5180		assert_eq!(sub.assert_group().sequence, 0);
5181	}
5182
5183	/// A copy that delivered and later died is a failover even when unrelated
5184	/// wakes happened between its last group and its death: progress is tracked
5185	/// per splice, so a demand edge must not launder it into a zero-progress
5186	/// refusal that aborts the only route.
5187	#[tokio::test]
5188	async fn test_delivered_copy_death_survives_unrelated_wakes() {
5189		tokio::time::pause();
5190
5191		let origin = Origin::random().produce();
5192		let consumer = origin.consume();
5193
5194		let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
5195		let source = origin.create_broadcast("test", announce().with_hops(hops)).unwrap();
5196		let mut dynamic = source.dynamic();
5197		settle().await;
5198		settle().await;
5199		let broadcast = consumer.request_broadcast("test").await.unwrap();
5200
5201		let subscribing = broadcast.track("video").unwrap().subscribe(None);
5202		let mut producer = accept_track(&mut dynamic, "video").await;
5203		settle().await;
5204		let mut sub = subscribing.await.unwrap();
5205		producer.append_group().unwrap();
5206		assert_eq!(sub.assert_group().sequence, 0);
5207
5208		// Unrelated demand-edge wakes after the copy's last group: the reader
5209		// leaves and a new one arrives.
5210		drop(sub);
5211		settle().await;
5212		let resubscribing = broadcast.track("video").unwrap().subscribe(None);
5213		settle().await;
5214		let mut sub = resubscribing.await.unwrap();
5215		assert_eq!(sub.assert_group().sequence, 0, "cached group re-served");
5216
5217		// The copy then dies having delivered: failover, so the source is
5218		// re-asked and the subscription resumes.
5219		drop(producer);
5220		let mut producer = accept_track(&mut dynamic, "video").await;
5221		settle().await;
5222		producer.create_group(group::Info { sequence: 1 }).unwrap();
5223		assert_eq!(sub.assert_group().sequence, 1);
5224		sub.assert_not_closed();
5225	}
5226
5227	/// The front picks a source per track and re-picks on failover, so a route
5228	/// tainted for a peer is one the front may serve them from even when the
5229	/// active route is clean. Sharing the front therefore has to check the whole
5230	/// table, not just the active route: here the clean route is active but cannot
5231	/// carry the track, and the fallback is the peer's own route.
5232	#[tokio::test]
5233	async fn test_per_track_fallback_respects_exclusion() {
5234		tokio::time::pause();
5235
5236		let origin = Origin::random().produce();
5237		let consumer = origin.consume();
5238
5239		let publisher = Origin::new(1).unwrap();
5240		let peer = Origin::new(5).unwrap();
5241		let via_peer = OriginList::try_from(vec![publisher, peer]).unwrap();
5242		let local = OriginList::try_from(vec![publisher]).unwrap();
5243
5244		// The route through the peer has the track.
5245		let source_tainted = origin
5246			.create_broadcast("test", announce().with_hops(via_peer).with_cost(2))
5247			.unwrap();
5248		let mut dynamic_tainted = source_tainted.dynamic();
5249		settle().await;
5250		settle().await;
5251
5252		// The clean route is cheaper, so it is active, but its publisher has not
5253		// created the track yet.
5254		let source_clean = origin.create_broadcast("test", announce().with_hops(local)).unwrap();
5255		let mut dynamic_clean = source_clean.dynamic();
5256		settle().await;
5257
5258		let scoped = consumer.clone().excluding(peer);
5259		let broadcast = scoped.request_broadcast("test").await.unwrap();
5260		let _subscribing = broadcast.track("video").unwrap().subscribe(None);
5261		settle().await;
5262
5263		// The peer is pinned to the clean source, so the fallback the front would
5264		// take for everyone else is not reachable from their subscription: the
5265		// refusal aborts the track rather than asking the tainted route.
5266		let request = dynamic_clean.requested_track().await.unwrap();
5267		request.reject(Error::NotFound);
5268		settle().await;
5269		dynamic_tainted.assert_no_request();
5270	}
5271
5272	/// The same guarantee under failover: the peer resolves while a clean route is
5273	/// active, then that route dies. Its subscription must not migrate onto the
5274	/// route that flows back through it.
5275	#[tokio::test]
5276	async fn test_exclusion_survives_failover_onto_a_tainted_route() {
5277		tokio::time::pause();
5278
5279		let origin = Origin::random().produce();
5280		let consumer = origin.consume();
5281
5282		let publisher = Origin::new(1).unwrap();
5283		let peer = Origin::new(5).unwrap();
5284		let via_peer = OriginList::try_from(vec![publisher, peer]).unwrap();
5285		let local = OriginList::try_from(vec![publisher]).unwrap();
5286
5287		let source_tainted = origin
5288			.create_broadcast("test", announce().with_hops(via_peer).with_cost(2))
5289			.unwrap();
5290		let mut dynamic_tainted = source_tainted.dynamic();
5291		settle().await;
5292		settle().await;
5293		let source_clean = origin.create_broadcast("test", announce().with_hops(local)).unwrap();
5294		let mut dynamic_clean = source_clean.dynamic();
5295		settle().await;
5296
5297		let scoped = consumer.clone().excluding(peer);
5298		let broadcast = scoped.request_broadcast("test").await.unwrap();
5299		let _subscribing = broadcast.track("video").unwrap().subscribe(None);
5300		let _clean = accept_track(&mut dynamic_clean, "video").await;
5301		settle().await;
5302
5303		// The clean route dies, so the front's only remaining route is the peer's.
5304		source_clean.abort(Error::Dropped).unwrap();
5305		settle().await;
5306		settle().await;
5307		dynamic_tainted.assert_no_request();
5308
5309		// A fresh request now has nowhere clean to go, and says so rather than
5310		// silently serving the peer their own route.
5311		assert!(matches!(scoped.request_broadcast("test").await, Err(Error::Unroutable)));
5312	}
5313
5314	/// The resolve-time check only proves the table is clean for a peer at that
5315	/// instant. A route through them attaching *afterwards* must not be adopted
5316	/// underneath their live subscription: they hold the shared front, so the front
5317	/// stays off that route while a clean one remains.
5318	#[tokio::test]
5319	async fn test_exclusion_holds_when_a_tainted_route_attaches_later() {
5320		tokio::time::pause();
5321
5322		let origin = Origin::random().produce();
5323		let consumer = origin.consume();
5324
5325		let publisher = Origin::new(1).unwrap();
5326		let peer = Origin::new(5).unwrap();
5327		let local = OriginList::try_from(vec![publisher]).unwrap();
5328		let via_peer = OriginList::try_from(vec![publisher, peer]).unwrap();
5329
5330		// Only a clean route exists, so the peer legitimately gets the shared front.
5331		// Priced above the route that arrives later, so the front genuinely prefers
5332		// that one and staying put is the guard's doing, not the tie-break's.
5333		let source_clean = origin
5334			.create_broadcast("test", announce().with_hops(local).with_cost(5))
5335			.unwrap();
5336		let mut dynamic_clean = source_clean.dynamic();
5337		settle().await;
5338		settle().await;
5339		let scoped = consumer.clone().excluding(peer);
5340		let broadcast = scoped.request_broadcast("test").await.unwrap();
5341		let subscribing = broadcast.track("video").unwrap().subscribe(None);
5342		let mut producer_clean = accept_track(&mut dynamic_clean, "video").await;
5343		settle().await;
5344		let mut sub = subscribing.await.unwrap();
5345		producer_clean.append_group().unwrap();
5346		assert_eq!(sub.assert_group().sequence, 0);
5347
5348		// A cheaper route back through the peer attaches. Without the registration
5349		// the front would re-splice onto it and hand the peer its own bytes.
5350		// `advertised` non-zero says the announcing relay is not itself carrying, which
5351		// keeps the simultaneous-activation handover gate (whose key comparison is
5352		// hash-random) out of this test: the front takes the cheaper route outright
5353		// unless the exclusion stops it.
5354		let mut tainted = announce().with_hops(via_peer.clone()).with_cost(0);
5355		tainted.advertised = 1;
5356		let mut source_tainted = origin.create_broadcast("test", tainted).unwrap();
5357		let mut dynamic_tainted = source_tainted.dynamic();
5358		settle().await;
5359		settle().await;
5360		dynamic_tainted.assert_no_request();
5361		producer_clean.append_group().unwrap();
5362		assert_eq!(sub.assert_group().sequence, 1);
5363		sub.assert_not_closed();
5364
5365		// The registration ends with the last handle. The next table change is free
5366		// to take the cheaper route, which is what proves it was released.
5367		drop(sub);
5368		drop(broadcast);
5369		drop(scoped);
5370		settle().await;
5371		let mut bumped = announce().with_hops(via_peer).with_cost(1);
5372		bumped.advertised = 1;
5373		source_tainted.set_route(bumped).unwrap();
5374		settle().await;
5375		let plain = consumer.request_broadcast("test").await.unwrap();
5376		let _plain_track = plain.track("video").unwrap().subscribe(None);
5377		settle().await;
5378		settle().await;
5379		assert!(
5380			dynamic_tainted.requested_track().now_or_never().is_some(),
5381			"the front must be free to use the route again once the peer is gone"
5382		);
5383	}
5384
5385	/// An announced path every route of which loops through the requester is
5386	/// unroutable, not missing: the dynamic handler resolves paths with no route
5387	/// chain to check, so consulting it would route around the split horizon.
5388	#[tokio::test]
5389	async fn test_excluded_path_never_reaches_the_dynamic_handler() {
5390		tokio::time::pause();
5391
5392		let origin = Origin::random().produce();
5393		let consumer = origin.consume();
5394		let mut dynamic = origin.dynamic();
5395
5396		let peer = Origin::new(5).unwrap();
5397		let tainted = OriginList::try_from(vec![Origin::new(1).unwrap(), peer]).unwrap();
5398		let _source = origin.create_broadcast("test", announce().with_hops(tainted)).unwrap();
5399		settle().await;
5400		settle().await;
5401
5402		let scoped = consumer.clone().excluding(peer);
5403		assert!(matches!(scoped.request_broadcast("test").await, Err(Error::Unroutable)));
5404		assert!(
5405			dynamic.requested_broadcast().now_or_never().is_none(),
5406			"the dynamic handler was asked to route around the exclusion"
5407		);
5408
5409		// An unannounced path still reaches the handler, exclusion or not.
5410		let _pending = scoped.request_broadcast("other");
5411		settle().await;
5412		assert!(
5413			dynamic.requested_broadcast().now_or_never().is_some(),
5414			"a genuinely missing path must still fall back"
5415		);
5416	}
5417
5418	/// When every route flows through the requester, the path is unroutable for
5419	/// them: serving it would hand them their own bytes back.
5420	#[tokio::test]
5421	async fn test_dispatch_all_tainted_unroutable() {
5422		tokio::time::pause();
5423
5424		let origin = Origin::random().produce();
5425		let consumer = origin.consume();
5426
5427		let peer = Origin::new(5).unwrap();
5428		let tainted = OriginList::try_from(vec![Origin::new(1).unwrap(), peer]).unwrap();
5429		let _source = origin.create_broadcast("test", announce().with_hops(tainted)).unwrap();
5430		settle().await;
5431		settle().await;
5432
5433		let scoped = consumer.clone().excluding(peer);
5434		match scoped.request_broadcast("test").await {
5435			Err(Error::Unroutable) => {}
5436			Err(err) => panic!("expected Unroutable, got {err:?}"),
5437			Ok(_) => panic!("expected Unroutable, got a broadcast"),
5438		}
5439
5440		// Everyone else still resolves the shared front.
5441		consumer.request_broadcast("test").await.unwrap();
5442	}
5443
5444	#[tokio::test]
5445	async fn test_duplicate_reverse() {
5446		tokio::time::pause();
5447
5448		let origin = Origin::random().produce();
5449
5450		let mut broadcast1 = origin.create_broadcast("test", announce()).unwrap();
5451		let mut broadcast2 = origin.create_broadcast("test", announce()).unwrap();
5452		settle().await;
5453		assert!(origin.consume().get_broadcast("test").is_some());
5454
5455		// This is harder, finishing the newer source first.
5456		broadcast2.finish();
5457		settle().await;
5458		assert!(origin.consume().get_broadcast("test").is_some());
5459
5460		broadcast1.finish();
5461		settle().await;
5462		assert!(origin.consume().get_broadcast("test").is_none());
5463	}
5464
5465	#[tokio::test]
5466	async fn test_deterministic_tiebreak() {
5467		tokio::time::pause();
5468
5469		fn hops(ids: &[u64]) -> OriginList {
5470			OriginList::try_from(
5471				ids.iter()
5472					.copied()
5473					.map(|id| Origin::new(id).unwrap())
5474					.collect::<Vec<_>>(),
5475			)
5476			.unwrap()
5477		}
5478
5479		// Resolve the advertised route for "test" after creating both sources in
5480		// the given order.
5481		async fn winner(first: &[u64], second: &[u64]) -> OriginList {
5482			let origin = Origin::random().produce();
5483			let _a = origin
5484				.create_broadcast("test", announce().with_hops(hops(first)))
5485				.unwrap();
5486			let _b = origin
5487				.create_broadcast("test", announce().with_hops(hops(second)))
5488				.unwrap();
5489			settle().await;
5490			origin.consume().get_broadcast("test").unwrap().route().hops
5491		}
5492
5493		// Two routes with equal hop counts but distinct chains (sharing the first
5494		// hop, so both may attach). The winner is decided by the deterministic
5495		// key, not arrival order, so both publish orders converge.
5496		let forward = winner(&[5, 20], &[5, 40]).await;
5497		let reverse = winner(&[5, 40], &[5, 20]).await;
5498		assert_eq!(forward, reverse, "tie-break must not depend on publish order");
5499
5500		// A strictly shorter chain always wins regardless of the hash.
5501		assert_eq!(winner(&[5, 20], &[5]).await.len(), 1);
5502		assert_eq!(winner(&[5], &[5, 20]).await.len(), 1);
5503	}
5504
5505	// A previous mpsc-based implementation could only deliver the first 127 broadcasts
5506	// instantly via `assert_next` (which uses `now_or_never`). The kio-backed
5507	// implementation polls synchronously and can deliver all of them without yielding.
5508	// Names are zero-padded so lexicographic delivery order matches the loop index.
5509	#[tokio::test]
5510	async fn test_many_announces() {
5511		let origin = Origin::random().produce();
5512
5513		let mut consumer = origin.consume().announced();
5514		// Held for the duration: a dropped source unannounces immediately.
5515		let mut broadcasts = Vec::new();
5516		for i in 0..256 {
5517			broadcasts.push(origin.create_broadcast(format!("test{i:03}"), announce()).unwrap());
5518			settle().await;
5519		}
5520
5521		for i in 0..256 {
5522			consumer.assert_next_some(format!("test{i:03}"));
5523		}
5524		consumer.assert_next_wait();
5525	}
5526
5527	#[tokio::test]
5528	async fn test_many_announces_try() {
5529		let origin = Origin::random().produce();
5530
5531		let mut consumer = origin.consume().announced();
5532		// Held for the duration: a dropped source unannounces immediately.
5533		let mut broadcasts = Vec::new();
5534		for i in 0..256 {
5535			broadcasts.push(origin.create_broadcast(format!("test{i:03}"), announce()).unwrap());
5536			settle().await;
5537		}
5538
5539		for i in 0..256 {
5540			consumer.assert_try_next_some(format!("test{i:03}"));
5541		}
5542	}
5543
5544	#[tokio::test]
5545	async fn test_with_root_basic() {
5546		let origin = Origin::random().produce();
5547
5548		// Create a producer with root "/foo"
5549		let foo_producer = origin.with_root("foo").expect("should create root");
5550		assert_eq!(foo_producer.root().as_str(), "foo");
5551
5552		let mut consumer = origin.consume().announced();
5553
5554		// When publishing to "bar/baz", it should actually publish to "foo/bar/baz"
5555		let _broadcast = foo_producer
5556			.create_broadcast("bar/baz", announce())
5557			.expect("publish allowed");
5558		settle().await;
5559		// The original consumer should see the full path
5560		consumer.assert_next_some("foo/bar/baz");
5561
5562		// A consumer created from the rooted producer should see the stripped path
5563		let mut foo_consumer = foo_producer.consume().announced();
5564		foo_consumer.assert_next_some("bar/baz");
5565	}
5566
5567	#[tokio::test]
5568	async fn test_with_root_nested() {
5569		let origin = Origin::random().produce();
5570
5571		// Create nested roots
5572		let foo_producer = origin.with_root("foo").expect("should create foo root");
5573		let foo_bar_producer = foo_producer.with_root("bar").expect("should create bar root");
5574		assert_eq!(foo_bar_producer.root().as_str(), "foo/bar");
5575
5576		let mut consumer = origin.consume().announced();
5577
5578		// Publishing to "baz" should actually publish to "foo/bar/baz"
5579		let _broadcast = foo_bar_producer
5580			.create_broadcast("baz", announce())
5581			.expect("publish allowed");
5582		settle().await;
5583		// The original consumer sees the full path
5584		consumer.assert_next_some("foo/bar/baz");
5585
5586		// Consumer from foo_bar_producer sees just "baz"
5587		let mut foo_bar_consumer = foo_bar_producer.consume().announced();
5588		foo_bar_consumer.assert_next_some("baz");
5589	}
5590
5591	#[tokio::test]
5592	async fn test_publish_scope_allows() {
5593		let origin = Origin::random().produce();
5594
5595		// Create a producer that can only publish to "allowed" paths
5596		let limited_producer = origin
5597			.scope(&["allowed/path1".into(), "allowed/path2".into()])
5598			.expect("should create limited producer");
5599
5600		// Should be able to publish to allowed paths
5601		let _broadcast = limited_producer
5602			.create_broadcast("allowed/path1", announce())
5603			.expect("publish allowed");
5604		let _keep2 = limited_producer
5605			.create_broadcast("allowed/path1/nested", announce())
5606			.expect("publish allowed");
5607		let _keep3 = limited_producer
5608			.create_broadcast("allowed/path2", announce())
5609			.expect("publish allowed");
5610		settle().await;
5611
5612		// Should not be able to publish to disallowed paths
5613		assert!(limited_producer.create_broadcast("notallowed", announce()).is_err());
5614		assert!(limited_producer.create_broadcast("allowed", announce()).is_err()); // Parent of allowed path
5615		assert!(limited_producer.create_broadcast("other/path", announce()).is_err());
5616	}
5617
5618	#[tokio::test]
5619	async fn test_publish_max_parts() {
5620		let origin = Origin::random().produce();
5621
5622		let at_limit = (0..Path::MAX_PARTS)
5623			.map(|i| i.to_string())
5624			.collect::<Vec<_>>()
5625			.join("/");
5626		let _broadcast = origin
5627			.create_broadcast(at_limit.as_str(), announce())
5628			.expect("publish allowed");
5629		settle().await;
5630
5631		let too_deep = format!("{at_limit}/extra");
5632		assert!(origin.create_broadcast(too_deep.as_str(), announce()).is_err());
5633
5634		// The root counts toward the limit; a joined path past 32 parts is rejected.
5635		let rooted = origin.with_root("root").expect("wildcard allows any root");
5636		assert!(rooted.create_broadcast(at_limit.as_str(), announce()).is_err());
5637	}
5638
5639	#[tokio::test]
5640	async fn test_publish_scope_empty() {
5641		let origin = Origin::random().produce();
5642
5643		// Creating a producer with no allowed paths should return None
5644		assert!(origin.scope(&[]).is_none());
5645	}
5646
5647	#[tokio::test]
5648	async fn test_consume_scope_filters() {
5649		let origin = Origin::random().produce();
5650
5651		let mut consumer = origin.consume().announced();
5652
5653		// Publish to different paths
5654		let _broadcast1 = origin.create_broadcast("allowed", announce()).unwrap();
5655		let _broadcast2 = origin.create_broadcast("allowed/nested", announce()).unwrap();
5656		let _broadcast3 = origin.create_broadcast("notallowed", announce()).unwrap();
5657		settle().await;
5658
5659		// Create a consumer that only sees "allowed" paths
5660		let mut limited_consumer = origin
5661			.consume()
5662			.scope(&["allowed".into()])
5663			.expect("should create limited consumer")
5664			.announced();
5665
5666		// Should only receive broadcasts under "allowed"
5667		limited_consumer.assert_next_some("allowed");
5668		limited_consumer.assert_next_some("allowed/nested");
5669		limited_consumer.assert_next_wait(); // Should not see "notallowed"
5670
5671		// Unscoped consumer should see all
5672		consumer.assert_next_some("allowed");
5673		consumer.assert_next_some("allowed/nested");
5674		consumer.assert_next_some("notallowed");
5675	}
5676
5677	#[tokio::test]
5678	async fn test_consume_scope_multiple_prefixes() {
5679		let origin = Origin::random().produce();
5680
5681		let _broadcast1 = origin.create_broadcast("foo/test", announce()).unwrap();
5682		let _broadcast2 = origin.create_broadcast("bar/test", announce()).unwrap();
5683		let _broadcast3 = origin.create_broadcast("baz/test", announce()).unwrap();
5684		settle().await;
5685
5686		// Consumer that only sees "foo" and "bar" paths
5687		let mut limited_consumer = origin
5688			.consume()
5689			.scope(&["foo".into(), "bar".into()])
5690			.expect("should create limited consumer")
5691			.announced();
5692
5693		// Order depends on PathPrefixes canonical sort (lexicographic for same length)
5694		limited_consumer.assert_next_some("bar/test");
5695		limited_consumer.assert_next_some("foo/test");
5696		limited_consumer.assert_next_wait(); // Should not see "baz/test"
5697	}
5698
5699	#[tokio::test]
5700	async fn test_with_root_and_publish_scope() {
5701		let origin = Origin::random().produce();
5702
5703		// User connects to /foo root
5704		let foo_producer = origin.with_root("foo").expect("should create foo root");
5705
5706		// Limit them to publish only to "bar" and "goop/pee" within /foo
5707		let limited_producer = foo_producer
5708			.scope(&["bar".into(), "goop/pee".into()])
5709			.expect("should create limited producer");
5710
5711		let mut consumer = origin.consume().announced();
5712
5713		// Should be able to publish to foo/bar and foo/goop/pee (but user sees as bar and goop/pee)
5714		let _broadcast = limited_producer
5715			.create_broadcast("bar", announce())
5716			.expect("publish allowed");
5717		let _keep2 = limited_producer
5718			.create_broadcast("bar/nested", announce())
5719			.expect("publish allowed");
5720		let _keep3 = limited_producer
5721			.create_broadcast("goop/pee", announce())
5722			.expect("publish allowed");
5723		let _keep4 = limited_producer
5724			.create_broadcast("goop/pee/nested", announce())
5725			.expect("publish allowed");
5726		settle().await;
5727
5728		// Should not be able to publish outside allowed paths
5729		assert!(limited_producer.create_broadcast("baz", announce()).is_err());
5730		assert!(limited_producer.create_broadcast("goop", announce()).is_err()); // Parent of allowed
5731		assert!(limited_producer.create_broadcast("goop/other", announce()).is_err());
5732
5733		// Original consumer sees full paths
5734		consumer.assert_next_some("foo/bar");
5735		consumer.assert_next_some("foo/bar/nested");
5736		consumer.assert_next_some("foo/goop/pee");
5737		consumer.assert_next_some("foo/goop/pee/nested");
5738	}
5739
5740	#[tokio::test]
5741	async fn test_with_root_and_consume_scope() {
5742		let origin = Origin::random().produce();
5743
5744		// Publish broadcasts
5745		let _broadcast1 = origin.create_broadcast("foo/bar/test", announce()).unwrap();
5746		let _broadcast2 = origin.create_broadcast("foo/goop/pee/test", announce()).unwrap();
5747		let _broadcast3 = origin.create_broadcast("foo/other/test", announce()).unwrap();
5748		settle().await;
5749
5750		// User connects to /foo root
5751		let foo_producer = origin.with_root("foo").expect("should create foo root");
5752
5753		// Create consumer limited to "bar" and "goop/pee" within /foo
5754		let mut limited_consumer = foo_producer
5755			.consume()
5756			.scope(&["bar".into(), "goop/pee".into()])
5757			.expect("should create limited consumer")
5758			.announced();
5759
5760		// Should only see allowed paths (without foo prefix)
5761		limited_consumer.assert_next_some("bar/test");
5762		limited_consumer.assert_next_some("goop/pee/test");
5763		limited_consumer.assert_next_wait(); // Should not see "other/test"
5764	}
5765
5766	#[tokio::test]
5767	async fn test_with_root_unauthorized() {
5768		let origin = Origin::random().produce();
5769
5770		// First limit the producer to specific paths
5771		let limited_producer = origin
5772			.scope(&["allowed".into()])
5773			.expect("should create limited producer");
5774
5775		// Trying to create a root outside allowed paths should fail
5776		assert!(limited_producer.with_root("notallowed").is_none());
5777
5778		// But creating a root within allowed paths should work
5779		let allowed_root = limited_producer
5780			.with_root("allowed")
5781			.expect("should create allowed root");
5782		assert_eq!(allowed_root.root().as_str(), "allowed");
5783	}
5784
5785	#[tokio::test]
5786	async fn test_wildcard_permission() {
5787		let origin = Origin::random().produce();
5788
5789		// Producer with root access (empty string means wildcard)
5790		let root_producer = origin.clone();
5791
5792		// Should be able to publish anywhere
5793		let _broadcast = root_producer
5794			.create_broadcast("any/path", announce())
5795			.expect("publish allowed");
5796		let _keep2 = root_producer
5797			.create_broadcast("other/path", announce())
5798			.expect("publish allowed");
5799		settle().await;
5800
5801		// Can create any root
5802		let foo_producer = root_producer.with_root("foo").expect("should create any root");
5803		assert_eq!(foo_producer.root().as_str(), "foo");
5804	}
5805
5806	#[tokio::test]
5807	async fn test_consume_broadcast_with_permissions() {
5808		let origin = Origin::random().produce();
5809
5810		let _broadcast1 = origin.create_broadcast("allowed/test", announce()).unwrap();
5811		let _broadcast2 = origin.create_broadcast("notallowed/test", announce()).unwrap();
5812		settle().await;
5813
5814		// Create limited consumer
5815		let limited_consumer = origin
5816			.consume()
5817			.scope(&["allowed".into()])
5818			.expect("should create limited consumer");
5819
5820		// Should be able to get allowed broadcast
5821		let result = limited_consumer.get_broadcast("allowed/test");
5822		assert!(result.is_some());
5823		assert!(
5824			result
5825				.unwrap()
5826				.is_clone(&origin.consume().get_broadcast("allowed/test").unwrap())
5827		);
5828
5829		// Should not be able to get disallowed broadcast
5830		assert!(limited_consumer.get_broadcast("notallowed/test").is_none());
5831
5832		// Original consumer can get both
5833		let consumer = origin.consume();
5834		assert!(consumer.get_broadcast("allowed/test").is_some());
5835		assert!(consumer.get_broadcast("notallowed/test").is_some());
5836	}
5837
5838	#[tokio::test]
5839	async fn test_nested_paths_with_permissions() {
5840		let origin = Origin::random().produce();
5841
5842		// Create producer limited to "a/b/c"
5843		let limited_producer = origin.scope(&["a/b/c".into()]).expect("should create limited producer");
5844
5845		// Should be able to publish to exact path and nested paths
5846		let _broadcast = limited_producer
5847			.create_broadcast("a/b/c", announce())
5848			.expect("publish allowed");
5849		let _keep2 = limited_producer
5850			.create_broadcast("a/b/c/d", announce())
5851			.expect("publish allowed");
5852		let _keep3 = limited_producer
5853			.create_broadcast("a/b/c/d/e", announce())
5854			.expect("publish allowed");
5855		settle().await;
5856
5857		// Should not be able to publish to parent or sibling paths
5858		assert!(limited_producer.create_broadcast("a", announce()).is_err());
5859		assert!(limited_producer.create_broadcast("a/b", announce()).is_err());
5860		assert!(limited_producer.create_broadcast("a/b/other", announce()).is_err());
5861	}
5862
5863	#[tokio::test]
5864	async fn test_multiple_consumers_with_different_permissions() {
5865		let origin = Origin::random().produce();
5866
5867		// Publish to different paths
5868		let _broadcast1 = origin.create_broadcast("foo/test", announce()).unwrap();
5869		let _broadcast2 = origin.create_broadcast("bar/test", announce()).unwrap();
5870		let _broadcast3 = origin.create_broadcast("baz/test", announce()).unwrap();
5871		settle().await;
5872
5873		// Create consumers with different permissions
5874		let mut foo_consumer = origin
5875			.consume()
5876			.scope(&["foo".into()])
5877			.expect("should create foo consumer")
5878			.announced();
5879
5880		let mut bar_consumer = origin
5881			.consume()
5882			.scope(&["bar".into()])
5883			.expect("should create bar consumer")
5884			.announced();
5885
5886		let mut foobar_consumer = origin
5887			.consume()
5888			.scope(&["foo".into(), "bar".into()])
5889			.expect("should create foobar consumer")
5890			.announced();
5891
5892		// Each consumer should only see their allowed paths
5893		foo_consumer.assert_next_some("foo/test");
5894		foo_consumer.assert_next_wait();
5895
5896		bar_consumer.assert_next_some("bar/test");
5897		bar_consumer.assert_next_wait();
5898
5899		foobar_consumer.assert_next_some("bar/test");
5900		foobar_consumer.assert_next_some("foo/test");
5901		foobar_consumer.assert_next_wait();
5902	}
5903
5904	#[tokio::test]
5905	async fn test_select_with_empty_prefix() {
5906		let origin = Origin::random().produce();
5907
5908		// User with root "demo" allowed to subscribe to "worm-node" and "foobar"
5909		let demo_producer = origin.with_root("demo").expect("should create demo root");
5910		let limited_producer = demo_producer
5911			.scope(&["worm-node".into(), "foobar".into()])
5912			.expect("should create limited producer");
5913
5914		// Publish some broadcasts
5915		let _broadcast1 = limited_producer
5916			.create_broadcast("worm-node/test", announce())
5917			.expect("publish allowed");
5918		let _broadcast2 = limited_producer
5919			.create_broadcast("foobar/test", announce())
5920			.expect("publish allowed");
5921		settle().await;
5922
5923		// scope with empty prefix should keep the exact same "worm-node" and "foobar" nodes
5924		let mut consumer = limited_producer
5925			.consume()
5926			.scope(&["".into()])
5927			.expect("should create consumer with empty prefix")
5928			.announced();
5929
5930		// Should see both broadcasts (order depends on PathPrefixes sort)
5931		let a1 = consumer.try_next().expect("expected first announcement");
5932		let a2 = consumer.try_next().expect("expected second announcement");
5933		consumer.assert_next_wait();
5934
5935		let mut paths: Vec<_> = [&a1, &a2].iter().map(|a| a.path.to_string()).collect();
5936		paths.sort();
5937		assert_eq!(paths, ["foobar/test", "worm-node/test"]);
5938	}
5939
5940	#[tokio::test]
5941	async fn test_select_narrowing_scope() {
5942		let origin = Origin::random().produce();
5943
5944		// User with root "demo" allowed to subscribe to "worm-node" and "foobar"
5945		let demo_producer = origin.with_root("demo").expect("should create demo root");
5946		let limited_producer = demo_producer
5947			.scope(&["worm-node".into(), "foobar".into()])
5948			.expect("should create limited producer");
5949
5950		// Publish broadcasts at different levels
5951		let _broadcast1 = limited_producer
5952			.create_broadcast("worm-node", announce())
5953			.expect("publish allowed");
5954		let _broadcast2 = limited_producer
5955			.create_broadcast("worm-node/foo", announce())
5956			.expect("publish allowed");
5957		let _broadcast3 = limited_producer
5958			.create_broadcast("foobar/bar", announce())
5959			.expect("publish allowed");
5960		settle().await;
5961
5962		// Test 1: scope("worm-node") should result in a single "" node with contents of "worm-node" ONLY
5963		let mut worm_consumer = limited_producer
5964			.consume()
5965			.scope(&["worm-node".into()])
5966			.expect("should create worm-node consumer")
5967			.announced();
5968
5969		// Should see worm-node content with paths stripped to ""
5970		worm_consumer.assert_next_some("worm-node");
5971		worm_consumer.assert_next_some("worm-node/foo");
5972		worm_consumer.assert_next_wait(); // Should NOT see foobar content
5973
5974		// Test 2: scope("worm-node/foo") should result in a "" node with contents of "worm-node/foo"
5975		let mut foo_consumer = limited_producer
5976			.consume()
5977			.scope(&["worm-node/foo".into()])
5978			.expect("should create worm-node/foo consumer")
5979			.announced();
5980
5981		foo_consumer.assert_next_some("worm-node/foo");
5982		foo_consumer.assert_next_wait(); // Should NOT see other content
5983	}
5984
5985	#[tokio::test]
5986	async fn test_select_multiple_roots_with_empty_prefix() {
5987		let origin = Origin::random().produce();
5988
5989		// Producer with multiple allowed roots
5990		let limited_producer = origin
5991			.scope(&["app1".into(), "app2".into(), "shared".into()])
5992			.expect("should create limited producer");
5993
5994		// Publish to each root
5995		let _broadcast1 = limited_producer
5996			.create_broadcast("app1/data", announce())
5997			.expect("publish allowed");
5998		let _broadcast2 = limited_producer
5999			.create_broadcast("app2/config", announce())
6000			.expect("publish allowed");
6001		let _broadcast3 = limited_producer
6002			.create_broadcast("shared/resource", announce())
6003			.expect("publish allowed");
6004		settle().await;
6005
6006		// scope with empty prefix should maintain all roots
6007		let mut consumer = limited_producer
6008			.consume()
6009			.scope(&["".into()])
6010			.expect("should create consumer with empty prefix")
6011			.announced();
6012
6013		// Should see all broadcasts from all roots
6014		consumer.assert_next_some("app1/data");
6015		consumer.assert_next_some("app2/config");
6016		consumer.assert_next_some("shared/resource");
6017		consumer.assert_next_wait();
6018	}
6019
6020	#[tokio::test]
6021	async fn test_publish_scope_with_empty_prefix() {
6022		let origin = Origin::random().produce();
6023
6024		// Producer with specific allowed paths
6025		let limited_producer = origin
6026			.scope(&["services/api".into(), "services/web".into()])
6027			.expect("should create limited producer");
6028
6029		// scope with empty prefix should keep the same restrictions
6030		let same_producer = limited_producer
6031			.scope(&["".into()])
6032			.expect("should create producer with empty prefix");
6033
6034		// Should still have the same publishing restrictions
6035		let _broadcast = same_producer
6036			.create_broadcast("services/api", announce())
6037			.expect("publish allowed");
6038		let _keep2 = same_producer
6039			.create_broadcast("services/web", announce())
6040			.expect("publish allowed");
6041		assert!(same_producer.create_broadcast("services/db", announce()).is_err());
6042		assert!(same_producer.create_broadcast("other", announce()).is_err());
6043	}
6044
6045	#[tokio::test]
6046	async fn test_select_narrowing_to_deeper_path() {
6047		let origin = Origin::random().produce();
6048
6049		// Producer with broad permission
6050		let limited_producer = origin.scope(&["org".into()]).expect("should create limited producer");
6051
6052		// Publish at various depths
6053		let _broadcast1 = limited_producer
6054			.create_broadcast("org/team1/project1", announce())
6055			.expect("publish allowed");
6056		let _broadcast2 = limited_producer
6057			.create_broadcast("org/team1/project2", announce())
6058			.expect("publish allowed");
6059		let _broadcast3 = limited_producer
6060			.create_broadcast("org/team2/project1", announce())
6061			.expect("publish allowed");
6062		settle().await;
6063
6064		// Narrow down to team2 only
6065		let mut team2_consumer = limited_producer
6066			.consume()
6067			.scope(&["org/team2".into()])
6068			.expect("should create team2 consumer")
6069			.announced();
6070
6071		team2_consumer.assert_next_some("org/team2/project1");
6072		team2_consumer.assert_next_wait(); // Should NOT see team1 content
6073
6074		// Further narrow down to team1/project1
6075		let mut project1_consumer = limited_producer
6076			.consume()
6077			.scope(&["org/team1/project1".into()])
6078			.expect("should create project1 consumer")
6079			.announced();
6080
6081		// Should only see project1 content at root
6082		project1_consumer.assert_next_some("org/team1/project1");
6083		project1_consumer.assert_next_wait();
6084	}
6085
6086	#[tokio::test]
6087	async fn test_select_with_non_matching_prefix() {
6088		let origin = Origin::random().produce();
6089
6090		// Producer with specific allowed paths
6091		let limited_producer = origin
6092			.scope(&["allowed/path".into()])
6093			.expect("should create limited producer");
6094
6095		// Trying to scope with a completely different prefix should return None
6096		assert!(limited_producer.consume().scope(&["different/path".into()]).is_none());
6097
6098		// Similarly for scope
6099		assert!(limited_producer.scope(&["other/path".into()]).is_none());
6100	}
6101
6102	// Regression test for https://github.com/moq-dev/moq/issues/910
6103	// with_root panics when String has trailing slash (AsPath for String skips normalization)
6104	#[tokio::test]
6105	async fn test_with_root_trailing_slash_consumer() {
6106		let origin = Origin::random().produce();
6107
6108		// Use an owned String so the trailing slash is NOT normalized away.
6109		let prefix = "some_prefix/".to_string();
6110		let mut consumer = origin.consume().with_root(prefix).unwrap().announced();
6111
6112		let _b = origin.create_broadcast("some_prefix/test", announce()).unwrap();
6113		settle().await;
6114		consumer.assert_next_some("test");
6115	}
6116
6117	// Same issue but for the producer side of with_root
6118	#[tokio::test]
6119	async fn test_with_root_trailing_slash_producer() {
6120		let origin = Origin::random().produce();
6121
6122		// Use an owned String so the trailing slash is NOT normalized away.
6123		let prefix = "some_prefix/".to_string();
6124		let rooted = origin.with_root(prefix).unwrap();
6125
6126		let _b = rooted.create_broadcast("test", announce()).unwrap();
6127		settle().await;
6128
6129		let mut consumer = rooted.consume().announced();
6130		consumer.assert_next_some("test");
6131	}
6132
6133	// Verify unannounce also doesn't panic with trailing slash
6134	#[tokio::test]
6135	async fn test_with_root_trailing_slash_unannounce() {
6136		tokio::time::pause();
6137
6138		let origin = Origin::random().produce();
6139
6140		let prefix = "some_prefix/".to_string();
6141		let mut consumer = origin.consume().with_root(prefix).unwrap().announced();
6142
6143		let mut b = origin.create_broadcast("some_prefix/test", announce()).unwrap();
6144		settle().await;
6145		consumer.assert_next_some("test");
6146
6147		// Finish the broadcast to trigger an immediate unannounce.
6148		b.finish();
6149		settle().await;
6150
6151		// unannounce also calls strip_prefix(&self.root).unwrap()
6152		consumer.assert_next_none("test");
6153	}
6154
6155	#[tokio::test]
6156	async fn test_select_maintains_access_with_wider_prefix() {
6157		let origin = Origin::random().produce();
6158
6159		// Setup: user with root "demo" allowed to subscribe to specific paths
6160		let demo_producer = origin.with_root("demo").expect("should create demo root");
6161		let user_producer = demo_producer
6162			.scope(&["worm-node".into(), "foobar".into()])
6163			.expect("should create user producer");
6164
6165		// Publish some data
6166		let _broadcast1 = user_producer
6167			.create_broadcast("worm-node/data", announce())
6168			.expect("publish allowed");
6169		let _broadcast2 = user_producer
6170			.create_broadcast("foobar", announce())
6171			.expect("publish allowed");
6172		settle().await;
6173
6174		// Key test: scope with "" should maintain access to allowed roots
6175		let mut consumer = user_producer
6176			.consume()
6177			.scope(&["".into()])
6178			.expect("scope with empty prefix should not fail when user has specific permissions")
6179			.announced();
6180
6181		// Should still receive broadcasts from allowed paths (order not guaranteed)
6182		let a1 = consumer.try_next().expect("expected first announcement");
6183		let a2 = consumer.try_next().expect("expected second announcement");
6184		consumer.assert_next_wait();
6185
6186		let mut paths: Vec<_> = [&a1, &a2].iter().map(|a| a.path.to_string()).collect();
6187		paths.sort();
6188		assert_eq!(paths, ["foobar", "worm-node/data"]);
6189
6190		// Also test that we can still narrow the scope
6191		let mut narrow_consumer = user_producer
6192			.consume()
6193			.scope(&["worm-node".into()])
6194			.expect("should be able to narrow scope to worm-node")
6195			.announced();
6196
6197		narrow_consumer.assert_next_some("worm-node/data");
6198		narrow_consumer.assert_next_wait(); // Should not see foobar
6199	}
6200
6201	#[tokio::test]
6202	async fn test_duplicate_prefixes_deduped() {
6203		let origin = Origin::random().produce();
6204
6205		// scope with duplicate prefixes should work (deduped internally)
6206		let producer = origin
6207			.scope(&["demo".into(), "demo".into()])
6208			.expect("should create producer");
6209
6210		let _broadcast = producer
6211			.create_broadcast("demo/stream", announce())
6212			.expect("publish allowed");
6213		settle().await;
6214
6215		let mut consumer = producer.consume().announced();
6216		consumer.assert_next_some("demo/stream");
6217		consumer.assert_next_wait();
6218	}
6219
6220	#[tokio::test]
6221	async fn test_overlapping_prefixes_deduped() {
6222		let origin = Origin::random().produce();
6223
6224		// "demo" and "demo/foo". "demo/foo" is redundant, only "demo" should remain
6225		let producer = origin
6226			.scope(&["demo".into(), "demo/foo".into()])
6227			.expect("should create producer");
6228
6229		// Can still publish under "demo/bar" since "demo" covers everything
6230		let _broadcast = producer
6231			.create_broadcast("demo/bar/stream", announce())
6232			.expect("publish allowed");
6233		settle().await;
6234
6235		let mut consumer = producer.consume().announced();
6236		consumer.assert_next_some("demo/bar/stream");
6237		consumer.assert_next_wait();
6238	}
6239
6240	#[tokio::test]
6241	async fn test_overlapping_prefixes_no_duplicate_announcements() {
6242		let origin = Origin::random().produce();
6243
6244		// Both "demo" and "demo/foo" are requested. Should only have one node
6245		let producer = origin
6246			.scope(&["demo".into(), "demo/foo".into()])
6247			.expect("should create producer");
6248
6249		let _broadcast = producer
6250			.create_broadcast("demo/foo/stream", announce())
6251			.expect("publish allowed");
6252		settle().await;
6253
6254		let mut consumer = producer.consume().announced();
6255		// Should only get ONE announcement (not two from overlapping nodes)
6256		consumer.assert_next_some("demo/foo/stream");
6257		consumer.assert_next_wait();
6258	}
6259
6260	#[tokio::test]
6261	async fn test_allowed_returns_deduped_prefixes() {
6262		let origin = Origin::random().produce();
6263
6264		let producer = origin
6265			.scope(&["demo".into(), "demo/foo".into(), "anon".into()])
6266			.expect("should create producer");
6267
6268		let allowed: Vec<_> = producer.allowed().collect();
6269		assert_eq!(allowed.len(), 2, "demo/foo should be subsumed by demo");
6270	}
6271
6272	#[tokio::test]
6273	async fn test_announced_broadcast_already_announced() {
6274		let origin = Origin::random().produce();
6275
6276		let _broadcast = origin.create_broadcast("test", announce()).unwrap();
6277		settle().await;
6278
6279		let consumer = origin.consume();
6280		let result = consumer.announced_broadcast("test").await.expect("should find it");
6281		assert!(result.is_clone(&consumer.get_broadcast("test").unwrap()));
6282	}
6283
6284	#[tokio::test]
6285	async fn test_announced_broadcast_delayed() {
6286		tokio::time::pause();
6287
6288		let origin = Origin::random().produce();
6289
6290		let consumer = origin.consume();
6291
6292		// Start waiting before it's announced.
6293		let wait = tokio::spawn({
6294			let consumer = consumer.clone();
6295			async move { consumer.announced_broadcast("test").await }
6296		});
6297
6298		// Give the spawned task a chance to subscribe.
6299		tokio::task::yield_now().await;
6300
6301		let _broadcast = origin.create_broadcast("test", announce()).unwrap();
6302		settle().await;
6303
6304		let result = wait.await.unwrap().expect("should find it");
6305		assert!(result.is_clone(&consumer.get_broadcast("test").unwrap()));
6306	}
6307
6308	#[tokio::test]
6309	async fn test_announced_broadcast_ignores_unrelated_paths() {
6310		tokio::time::pause();
6311
6312		let origin = Origin::random().produce();
6313
6314		let consumer = origin.consume();
6315
6316		let wait = tokio::spawn({
6317			let consumer = consumer.clone();
6318			async move { consumer.announced_broadcast("target").await }
6319		});
6320
6321		tokio::task::yield_now().await;
6322
6323		// Publish an unrelated broadcast first. announced_broadcast should skip it.
6324		let _other = origin.create_broadcast("other", announce()).unwrap();
6325		settle().await;
6326		tokio::task::yield_now().await;
6327		assert!(!wait.is_finished(), "must not resolve on unrelated path");
6328
6329		let _target = origin.create_broadcast("target", announce()).unwrap();
6330		settle().await;
6331		let result = wait.await.unwrap().expect("should find target");
6332		assert!(result.is_clone(&consumer.get_broadcast("target").unwrap()));
6333	}
6334
6335	#[tokio::test]
6336	async fn test_announced_broadcast_skips_nested_paths() {
6337		tokio::time::pause();
6338
6339		let origin = Origin::random().produce();
6340
6341		let consumer = origin.consume();
6342
6343		let wait = tokio::spawn({
6344			let consumer = consumer.clone();
6345			async move { consumer.announced_broadcast("foo").await }
6346		});
6347
6348		tokio::task::yield_now().await;
6349
6350		// "foo/bar" is under the prefix scope, but it's not the exact path. Skip it.
6351		let _nested = origin.create_broadcast("foo/bar", announce()).unwrap();
6352		settle().await;
6353		tokio::task::yield_now().await;
6354		assert!(!wait.is_finished(), "must not resolve on a nested path");
6355
6356		let _exact = origin.create_broadcast("foo", announce()).unwrap();
6357		settle().await;
6358		let result = wait.await.unwrap().expect("should find foo exactly");
6359		assert!(result.is_clone(&consumer.get_broadcast("foo").unwrap()));
6360	}
6361
6362	#[tokio::test]
6363	async fn test_announced_broadcast_disallowed() {
6364		let origin = Origin::random().produce();
6365		let limited = origin
6366			.consume()
6367			.scope(&["allowed".into()])
6368			.expect("should create limited");
6369
6370		// Path is outside allowed prefixes. Should return None immediately.
6371		assert!(limited.announced_broadcast("notallowed").await.is_none());
6372	}
6373
6374	#[tokio::test]
6375	async fn test_announced_broadcast_scope_too_narrow() {
6376		// Consumer's scope is narrower than the requested path: asking for `foo` on a consumer
6377		// limited to `foo/specific` can never resolve. Must return None, not loop forever.
6378		let origin = Origin::random().produce();
6379		let limited = origin
6380			.consume()
6381			.scope(&["foo/specific".into()])
6382			.expect("should create limited");
6383
6384		// now_or_never so we fail fast instead of hanging if the guard regresses.
6385		let result = limited
6386			.announced_broadcast("foo")
6387			.now_or_never()
6388			.expect("must not block");
6389		assert!(result.is_none());
6390	}
6391
6392	// Coalescing tests: a slow cursor that doesn't drain between updates
6393	// should observe a bounded number of deliveries.
6394
6395	#[tokio::test]
6396	async fn test_coalesce_announce_then_unannounce() {
6397		// announce + unannounce that the cursor hasn't observed yet collapses to nothing.
6398		tokio::time::pause();
6399
6400		let origin = Origin::random().produce();
6401		let mut announced = origin.consume().announced();
6402
6403		let mut broadcast = origin.create_broadcast("test", announce()).unwrap();
6404		settle().await;
6405		broadcast.finish();
6406
6407		settle().await;
6408
6409		announced.assert_next_wait();
6410	}
6411
6412	#[tokio::test]
6413	async fn test_coalesce_announce_unannounce_announce() {
6414		// announce, unannounce, announce that the cursor hasn't drained collapses
6415		// to a single Announce of the latest broadcast.
6416		tokio::time::pause();
6417
6418		let origin = Origin::random().produce();
6419		let mut announced = origin.consume().announced();
6420
6421		let mut broadcast1 = origin.create_broadcast("test", announce()).unwrap();
6422		settle().await;
6423		broadcast1.finish();
6424		settle().await;
6425		let _broadcast2 = origin.create_broadcast("test", announce()).unwrap();
6426		settle().await;
6427
6428		announced.assert_next_some("test");
6429		announced.assert_next_wait();
6430	}
6431
6432	#[tokio::test]
6433	async fn test_coalesce_unannounce_announce_preserved() {
6434		// unannounce followed by announce of a different broadcast must be preserved
6435		// as two deliveries so the cursor learns the origin changed.
6436		tokio::time::pause();
6437
6438		let origin = Origin::random().produce();
6439		let mut broadcast1 = origin.create_broadcast("test", announce()).unwrap();
6440		settle().await;
6441
6442		let mut announced = origin.consume().announced();
6443		announced.assert_next_some("test");
6444
6445		// Finish, then publish a fresh broadcast at the same path.
6446		broadcast1.finish();
6447		settle().await;
6448
6449		let _broadcast2 = origin.create_broadcast("test", announce()).unwrap();
6450		settle().await;
6451
6452		// The cursor must see the unannounce before the new announce.
6453		announced.assert_next_none("test");
6454		announced.assert_next_some("test");
6455		announced.assert_next_wait();
6456	}
6457
6458	#[tokio::test]
6459	async fn test_coalesce_unannounce_announce_unannounce() {
6460		// unannounce + announce + unannounce collapses to a single unannounce: the
6461		// embedded announce was never observed.
6462		tokio::time::pause();
6463
6464		let origin = Origin::random().produce();
6465		let mut broadcast1 = origin.create_broadcast("test", announce()).unwrap();
6466		settle().await;
6467
6468		let mut announced = origin.consume().announced();
6469		announced.assert_next_some("test");
6470
6471		broadcast1.finish();
6472		settle().await;
6473
6474		let mut broadcast2 = origin.create_broadcast("test", announce()).unwrap();
6475		settle().await;
6476		broadcast2.finish();
6477		settle().await;
6478
6479		announced.assert_next_none("test");
6480		announced.assert_next_wait();
6481	}
6482
6483	#[tokio::test]
6484	async fn test_coalesce_churn_bounded() {
6485		// A churn loop on a single path should keep the pending set bounded.
6486		// Backup promotion during cleanup can leave the cursor with zero or one
6487		// pending update for "test" depending on the order tasks run; we only
6488		// require that churn doesn't accumulate across iterations.
6489		tokio::time::pause();
6490
6491		let origin = Origin::random().produce();
6492		let mut announced = origin.consume().announced();
6493
6494		for _ in 0..1000 {
6495			let mut broadcast = origin.create_broadcast("test", announce()).unwrap();
6496			settle().await;
6497			broadcast.finish();
6498		}
6499		settle().await;
6500
6501		let mut collected = Vec::new();
6502		while let Some(update) = announced.try_next() {
6503			collected.push(update);
6504		}
6505		assert!(
6506			collected.len() <= 1,
6507			"expected at most one pending update, got {}",
6508			collected.len()
6509		);
6510		assert!(
6511			collected.iter().all(|a| a.path == Path::new("test")),
6512			"unexpected path in pending updates",
6513		);
6514	}
6515
6516	// Consumer should be cheap to clone: cloning must NOT drain any
6517	// other cursor's announce channel. A freshly-built AnnounceConsumer
6518	// still receives the active backlog.
6519	#[tokio::test]
6520	async fn test_consumer_clone_is_side_effect_free() {
6521		let origin = Origin::random().produce();
6522
6523		let _broadcast1 = origin.create_broadcast("test1", announce()).unwrap();
6524		let _broadcast2 = origin.create_broadcast("test2", announce()).unwrap();
6525		settle().await;
6526
6527		let consumer = origin.consume();
6528		let mut announced = consumer.announced();
6529
6530		// Cloning the Consumer many times and looking up broadcasts
6531		// must not consume any events from the existing cursor.
6532		for _ in 0..16 {
6533			let cloned = consumer.clone();
6534			assert!(cloned.get_broadcast("test1").is_some());
6535			assert!(cloned.get_broadcast("test2").is_some());
6536		}
6537
6538		// The original cursor still sees both announcements in their
6539		// natural order, undisturbed by the clones above.
6540		let a1 = announced.try_next().expect("first announcement");
6541		let a2 = announced.try_next().expect("second announcement");
6542		announced.assert_next_wait();
6543
6544		let mut paths: Vec<_> = [&a1, &a2].iter().map(|a| a.path.to_string()).collect();
6545		paths.sort();
6546		assert_eq!(paths, ["test1", "test2"]);
6547
6548		// A freshly-built AnnounceConsumer still receives the active backlog.
6549		let mut fresh = consumer.announced();
6550		let b1 = fresh.try_next().expect("backlog: first");
6551		let b2 = fresh.try_next().expect("backlog: second");
6552		fresh.assert_next_wait();
6553
6554		let mut paths: Vec<_> = [&b1, &b2].iter().map(|a| a.path.to_string()).collect();
6555		paths.sort();
6556		assert_eq!(paths, ["test1", "test2"]);
6557	}
6558
6559	// With no Dynamic handler, an unannounced path resolves to Unroutable.
6560	#[tokio::test]
6561	async fn dynamic_request_unroutable_without_handler() {
6562		let origin = Origin::random().produce();
6563		let consumer = origin.consume();
6564		assert!(matches!(
6565			consumer.request_broadcast("missing").await,
6566			Err(Error::Unroutable)
6567		));
6568	}
6569
6570	// A dynamically served broadcast resolves the requester and serves tracks, but is
6571	// never announced.
6572	#[tokio::test(start_paused = true)]
6573	async fn dynamic_request_served_not_announced() {
6574		let origin = Origin::random().produce();
6575		let mut dynamic = origin.dynamic();
6576		let consumer = origin.consume();
6577
6578		// A separate announce cursor must never observe the dynamic broadcast.
6579		let mut announced = origin.consume().announced();
6580		announced.assert_next_wait();
6581
6582		let served = broadcast::Info::new().produce();
6583		// Request a path that nobody announced; the future stays pending until served.
6584		// Registration happens up front, so the handler sees the request immediately.
6585		let request_fut = consumer.request_broadcast("fallback");
6586
6587		// The handler serves it with a live broadcast it keeps producing into.
6588		let mut served_dynamic = served.dynamic();
6589
6590		let request = dynamic.requested_broadcast().await.unwrap();
6591		assert_eq!(request.path(), &Path::new("fallback"));
6592		request.accept(&served);
6593
6594		let broadcast = request_fut.await.unwrap();
6595		assert!(broadcast.is_clone(&served.consume()));
6596
6597		// The served broadcast is live: a track subscription resolves via its handler.
6598		let track_fut = broadcast.track("video").unwrap().subscribe(None);
6599		let mut producer = served_dynamic.requested_track().await.unwrap().accept(None);
6600		let mut track = track_fut.await.unwrap();
6601		producer.append_group().unwrap();
6602		track.assert_group();
6603
6604		// Still nothing announced.
6605		announced.assert_next_wait();
6606	}
6607
6608	// Concurrent requests for the same queued path coalesce onto one handler request.
6609	#[tokio::test(start_paused = true)]
6610	async fn dynamic_request_coalesces() {
6611		let origin = Origin::random().produce();
6612		let mut dynamic = origin.dynamic();
6613		let consumer = origin.consume();
6614
6615		// Both register before the handler drains either.
6616		let f1 = consumer.request_broadcast("dup");
6617		let f2 = consumer.request_broadcast("dup");
6618
6619		// Exactly one request reaches the handler.
6620		let request = dynamic.requested_broadcast().await.unwrap();
6621		assert_eq!(request.path(), &Path::new("dup"));
6622		assert!(
6623			dynamic.requested_broadcast().now_or_never().is_none(),
6624			"a coalesced request must not be served twice"
6625		);
6626
6627		// Accepting resolves both awaiting requesters with the same broadcast.
6628		let served = broadcast::Info::new().produce();
6629		request.accept(&served);
6630		assert!(f1.await.unwrap().is_clone(&served.consume()));
6631		assert!(f2.await.unwrap().is_clone(&served.consume()));
6632	}
6633
6634	// A repeat request for an already-served, still-live path shares the same broadcast
6635	// instead of asking the handler again (no duplicate upstream subscription).
6636	#[tokio::test(start_paused = true)]
6637	async fn dynamic_request_dedups_served() {
6638		let origin = Origin::random().produce();
6639		let mut dynamic = origin.dynamic();
6640		let consumer = origin.consume();
6641
6642		let request_fut = consumer.request_broadcast("fallback");
6643		let request = dynamic.requested_broadcast().await.unwrap();
6644		let served = broadcast::Info::new().produce();
6645		request.accept(&served);
6646		let first = request_fut.await.unwrap();
6647		assert!(first.is_clone(&served.consume()));
6648
6649		// The repeat resolves immediately to the same broadcast...
6650		let second = consumer.request_broadcast("fallback").await.unwrap();
6651		assert!(second.is_clone(&served.consume()));
6652
6653		// ...and the handler never sees a second request.
6654		assert!(
6655			dynamic.requested_broadcast().now_or_never().is_none(),
6656			"a still-live served broadcast must not be re-requested from the handler"
6657		);
6658	}
6659
6660	// Once a served broadcast closes, its cache entry is stale, so the next request re-serves.
6661	#[tokio::test(start_paused = true)]
6662	async fn dynamic_request_reserves_after_close() {
6663		let origin = Origin::random().produce();
6664		let mut dynamic = origin.dynamic();
6665		let consumer = origin.consume();
6666
6667		let request_fut = consumer.request_broadcast("fallback");
6668		let request = dynamic.requested_broadcast().await.unwrap();
6669		let served = broadcast::Info::new().produce();
6670		request.accept(&served);
6671		request_fut.await.unwrap();
6672
6673		// Close the first served broadcast; the weak cache entry goes stale.
6674		drop(served);
6675
6676		// A fresh request must reach the handler again and resolve to the new broadcast.
6677		let request_fut = consumer.request_broadcast("fallback");
6678		let request = dynamic.requested_broadcast().await.unwrap();
6679		assert_eq!(request.path(), &Path::new("fallback"));
6680		let served = broadcast::Info::new().produce();
6681		request.accept(&served);
6682		assert!(request_fut.await.unwrap().is_clone(&served.consume()));
6683	}
6684
6685	// Serving many distinct one-shot paths that each close must not grow the `served` cache
6686	// unboundedly: the amortized GC on `accept` reclaims the stale entries left by closed ones.
6687	#[tokio::test(start_paused = true)]
6688	async fn dynamic_request_served_cache_bounded() {
6689		let origin = Origin::random().produce();
6690		let mut dynamic = origin.dynamic();
6691		let consumer = origin.consume();
6692
6693		for i in 0..100 {
6694			let path = format!("one-shot/{i}");
6695			let request_fut = consumer.request_broadcast(&path);
6696			let request = dynamic.requested_broadcast().await.unwrap();
6697			let served = broadcast::Info::new().produce();
6698			request.accept(&served);
6699			request_fut.await.unwrap();
6700			// Close the served broadcast; its cache entry is now stale.
6701			drop(served);
6702		}
6703
6704		// The GC keeps the map bounded by the live count (zero here) plus a small probe window,
6705		// rather than one entry per distinct path.
6706		assert!(
6707			origin.dynamic.read().served.len() <= 4,
6708			"stale served entries must be reclaimed, not accumulate per distinct path: {}",
6709			origin.dynamic.read().served.len()
6710		);
6711	}
6712
6713	// A repeat request in the window after the handler picks one up but before it accepts
6714	// coalesces onto the in-flight request instead of queuing a duplicate.
6715	#[tokio::test(start_paused = true)]
6716	async fn dynamic_request_coalesces_after_handoff() {
6717		let origin = Origin::random().produce();
6718		let mut dynamic = origin.dynamic();
6719		let consumer = origin.consume();
6720
6721		let f1 = consumer.request_broadcast("fallback");
6722		// Handler drains the request but has not accepted yet.
6723		let request = dynamic.requested_broadcast().await.unwrap();
6724
6725		// A second request in this window must not queue another handler request.
6726		let f2 = consumer.request_broadcast("fallback");
6727		assert!(
6728			dynamic.requested_broadcast().now_or_never().is_none(),
6729			"a repeat request during hand-off must coalesce, not re-queue"
6730		);
6731
6732		// Accepting resolves both awaiting requesters with the same broadcast.
6733		let served = broadcast::Info::new().produce();
6734		request.accept(&served);
6735		assert!(f1.await.unwrap().is_clone(&served.consume()));
6736		assert!(f2.await.unwrap().is_clone(&served.consume()));
6737	}
6738
6739	// Dropping a handed-off request without accept/reject rejects every coalesced requester.
6740	#[tokio::test(start_paused = true)]
6741	async fn dynamic_request_dropped_after_handoff() {
6742		let origin = Origin::random().produce();
6743		let mut dynamic = origin.dynamic();
6744		let consumer = origin.consume();
6745
6746		let f1 = consumer.request_broadcast("fallback");
6747		let request = dynamic.requested_broadcast().await.unwrap();
6748		let f2 = consumer.request_broadcast("fallback");
6749
6750		// Abandon it; both requesters resolve to Unroutable instead of hanging.
6751		drop(request);
6752		assert!(matches!(f1.await, Err(Error::Unroutable)));
6753		assert!(matches!(f2.await, Err(Error::Unroutable)));
6754	}
6755
6756	// Rejecting a request resolves the requester with the error.
6757	#[tokio::test(start_paused = true)]
6758	async fn dynamic_request_rejected() {
6759		let origin = Origin::random().produce();
6760		let mut dynamic = origin.dynamic();
6761		let consumer = origin.consume();
6762
6763		let request_fut = consumer.request_broadcast("fallback");
6764
6765		let request = dynamic.requested_broadcast().await.unwrap();
6766		request.reject(Error::Cancel);
6767
6768		assert!(matches!(request_fut.await, Err(Error::Cancel)));
6769	}
6770
6771	// After a rejected hand-off, a fresh request for the same path reaches the handler again:
6772	// the rejected `Request`'s removal + `Drop` leave the request queue consistent
6773	// (a stale/clobbered entry would strand this request or panic the handler).
6774	#[tokio::test(start_paused = true)]
6775	async fn dynamic_request_rerequest_after_reject() {
6776		let origin = Origin::random().produce();
6777		let mut dynamic = origin.dynamic();
6778		let consumer = origin.consume();
6779
6780		let f1 = consumer.request_broadcast("fallback");
6781		dynamic.requested_broadcast().await.unwrap().reject(Error::Unroutable);
6782		assert!(matches!(f1.await, Err(Error::Unroutable)));
6783
6784		let served = broadcast::Info::new().produce();
6785		// A fresh request re-reaches the handler and can be served.
6786		let f2 = consumer.request_broadcast("fallback");
6787		let request = dynamic.requested_broadcast().await.unwrap();
6788		assert_eq!(request.path(), &Path::new("fallback"));
6789		request.accept(&served);
6790		assert!(f2.await.unwrap().is_clone(&served.consume()));
6791	}
6792
6793	// Dropping the last handler resolves queued requests with an error and reverts to
6794	// resolving Unroutable.
6795	#[tokio::test(start_paused = true)]
6796	async fn dynamic_request_handler_dropped() {
6797		let origin = Origin::random().produce();
6798		let dynamic = origin.dynamic();
6799		let consumer = origin.consume();
6800
6801		let request_fut = consumer.request_broadcast("fallback");
6802		drop(dynamic);
6803		assert!(matches!(request_fut.await, Err(Error::Unroutable)));
6804
6805		// With no handler left, a fresh request resolves Unroutable.
6806		assert!(matches!(
6807			consumer.request_broadcast("again").await,
6808			Err(Error::Unroutable)
6809		));
6810	}
6811
6812	// `accept` is decoupled from the dynamic count: once a handler has picked a request up,
6813	// it can still serve it even if every handler (including itself) drops first, flipping the
6814	// count to zero. The in-flight request must not be rejected as `Unroutable`.
6815	#[tokio::test(start_paused = true)]
6816	async fn dynamic_request_accept_after_handler_dropped() {
6817		let origin = Origin::random().produce();
6818		let mut dynamic = origin.dynamic();
6819		let consumer = origin.consume();
6820
6821		let request_fut = consumer.request_broadcast("fallback");
6822
6823		// The handler picks the request up, then every handler drops (count -> 0).
6824		let request = dynamic.requested_broadcast().await.unwrap();
6825		drop(dynamic);
6826
6827		let served = broadcast::Info::new().produce();
6828		// Accept still resolves the awaiting requester with the served broadcast.
6829		request.accept(&served);
6830		assert!(request_fut.await.unwrap().is_clone(&served.consume()));
6831	}
6832
6833	// A published broadcast wins over the dynamic fallback; no request is queued.
6834	#[tokio::test(start_paused = true)]
6835	async fn dynamic_request_prefers_announced() {
6836		let origin = Origin::random().produce();
6837		let mut dynamic = origin.dynamic();
6838		let consumer = origin.consume();
6839
6840		let _broadcast = origin.create_broadcast("live", announce()).unwrap();
6841		settle().await;
6842
6843		let got = consumer.request_broadcast("live").await.unwrap();
6844		assert!(
6845			got.is_clone(&consumer.get_broadcast("live").unwrap()),
6846			"should return the published broadcast"
6847		);
6848		assert!(
6849			dynamic.requested_broadcast().now_or_never().is_none(),
6850			"a published path must not queue a fallback request"
6851		);
6852	}
6853
6854	// Cloning a handler and dropping the clone must not flip the count to zero.
6855	#[tokio::test(start_paused = true)]
6856	async fn dynamic_clone_keeps_alive() {
6857		let origin = Origin::random().produce();
6858		let dynamic = origin.dynamic();
6859		let consumer = origin.consume();
6860
6861		drop(dynamic.clone());
6862
6863		// The original handle is still live, so the request registers (stays pending)
6864		// instead of resolving Unroutable.
6865		let request_fut = consumer.request_broadcast("fallback");
6866		assert!(
6867			request_fut.now_or_never().is_none(),
6868			"request should stay pending until served"
6869		);
6870	}
6871
6872	/// Run `scenario` on its own thread with a current_thread runtime and fail
6873	/// if it does not complete within `secs`. A `serve_track` task that spins
6874	/// inside a single poll (the livelock class this guards against) never
6875	/// yields, so the runtime wedges and the scenario cannot finish; a timeout
6876	/// here IS the detection, not flakiness.
6877	fn wedge_watchdog<F>(name: &str, secs: u64, scenario: F)
6878	where
6879		F: std::future::Future<Output = ()> + Send + 'static,
6880	{
6881		let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
6882		let handle = std::thread::spawn(move || {
6883			let rt = ::tokio::runtime::Builder::new_current_thread()
6884				.enable_time()
6885				.build()
6886				.unwrap();
6887			rt.block_on(scenario);
6888			let _ = done_tx.send(());
6889		});
6890		match done_rx.recv_timeout(std::time::Duration::from_secs(secs)) {
6891			Ok(()) => {
6892				let _ = handle.join();
6893			}
6894			Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
6895				// The scenario thread panicked before sending: surface it.
6896				let err = handle.join().unwrap_err();
6897				std::panic::resume_unwind(err);
6898			}
6899			Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
6900				panic!("{name}: scenario wedged; a task is spinning inside a single poll")
6901			}
6902		}
6903	}
6904
6905	/// A closing route that is still `active` (its watcher has not detached it
6906	/// yet) must not be re-dispatched after a successful takeover from a
6907	/// healthy standby. If the takeover re-admits the corpse, serve_track
6908	/// cycles splice(corpse) -> splice(healthy) -> takeover -> splice(corpse)
6909	/// with no await: a livelock inside one task poll that also starves the
6910	/// watcher whose detach would end it.
6911	///
6912	/// The setup makes every step of the cycle synchronous: the healthy source
6913	/// holds a live producer (so a re-splice needs no handler roundtrip), and
6914	/// the corpse is aborted while its track request is still pending (so
6915	/// serve_track, a value waiter, wakes before the corpse's closed-watcher
6916	/// and observes the corpse still attached).
6917	#[test]
6918	fn test_active_corpse_does_not_livelock_takeover() {
6919		wedge_watchdog("active-corpse", 20, async {
6920			let origin = Origin::random().produce();
6921			let consumer = origin.consume();
6922			let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
6923
6924			// The healthy source: accepts the track and keeps the producer
6925			// alive, so a later re-splice resolves synchronously from cache.
6926			let source_a = origin
6927				.create_broadcast("test", announce().with_hops(hops.clone()))
6928				.unwrap();
6929			let mut dynamic_a = source_a.dynamic();
6930			settle().await;
6931			settle().await;
6932
6933			let broadcast = consumer.request_broadcast("test").await.unwrap();
6934			let subscribing = broadcast.track("video").unwrap().subscribe(None);
6935			let mut producer_a = accept_track(&mut dynamic_a, "video").await;
6936			settle().await;
6937			let mut sub = subscribing.await.unwrap();
6938			producer_a.append_group().unwrap();
6939			sub.assert_group();
6940
6941			// A newer same-cost source attaches: recency wins the tie, so it
6942			// becomes `active` and the serve task asks it for the track. Leave
6943			// the request unanswered.
6944			let source_b = origin
6945				.create_broadcast("test", announce().with_hops(hops.clone()))
6946				.unwrap();
6947			let dynamic_b = source_b.dynamic();
6948			settle().await;
6949
6950			// Kill it with the request still pending: a corpse that is still
6951			// attached and still `active`. Dropping the handler first queues the
6952			// serve task's request-failure wake ahead of the corpse watcher's
6953			// closed-wake, so the serve task observes the corpse before the
6954			// watcher can detach it - the fleet-wedge ordering. It must fail
6955			// over to the healthy cached copy and park there instead of
6956			// re-dispatching the corpse.
6957			drop(dynamic_b);
6958			source_b.abort(Error::Dropped).unwrap();
6959			settle().await;
6960
6961			// Progress through the healthy source proves the serve task parked
6962			// instead of spinning.
6963			producer_a.append_group().unwrap();
6964			sub.assert_group();
6965			sub.assert_not_closed();
6966		});
6967	}
6968
6969	/// Randomized source/subscriber churn over one path: sources attach with
6970	/// per-track behaviors (refuse, serve-then-abort, serve-and-hold, finish),
6971	/// detach by abort or plain drop, and subscribers come and go. A wedge net
6972	/// for the livelock class the test above pins down. The LCG makes each
6973	/// seed's action sequence repeatable, but task interleaving still varies
6974	/// per run, so treat a wedge here as real and shrink it with the seed as a
6975	/// starting point rather than expecting an identical replay.
6976	#[test]
6977	fn test_route_churn_never_wedges() {
6978		for seed in 1..=8u64 {
6979			wedge_watchdog(&format!("churn seed {seed}"), 30, churn_scenario(seed));
6980		}
6981	}
6982
6983	async fn churn_scenario(seed: u64) {
6984		// LCG: deterministic sequence per seed.
6985		let mut rng = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
6986		let mut next = move || {
6987			rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
6988			rng >> 33
6989		};
6990
6991		let origin = Origin::random().produce();
6992		let consumer = origin.consume();
6993		let names: Vec<Arc<str>> = (0..8).map(|i| Arc::from(format!("t{i}"))).collect();
6994
6995		let mut subs: Vec<track::Subscriber> = Vec::new();
6996		let mut pending_subs: Vec<kio::Pending<track::Subscribing>> = Vec::new();
6997
6998		struct Source {
6999			producer: Option<broadcast::Producer>,
7000			server: ::tokio::task::JoinHandle<()>,
7001		}
7002		let mut sources: Vec<Source> = Vec::new();
7003
7004		for step in 0..400u64 {
7005			match next() % 10 {
7006				// Attach a source whose handler randomly refuses / serves-then-
7007				// aborts / serves-and-holds / finishes each track request.
7008				0 | 1 => {
7009					if sources.len() >= 3 {
7010						continue;
7011					}
7012					let hops = OriginList::try_from(vec![Origin::new(1).unwrap()]).unwrap();
7013					let route = announce().with_hops(hops).with_cost(next() % 4);
7014					let Ok(source) = origin.create_broadcast("test", route) else {
7015						continue;
7016					};
7017					let mut dynamic = source.dynamic();
7018					let behavior = next();
7019					let server = ::tokio::spawn(async move {
7020						let mut round = 0u64;
7021						let mut kept: Vec<track::Producer> = Vec::new();
7022						while let Ok(request) = dynamic.requested_track().await {
7023							round += 1;
7024							match (behavior >> (round % 16)) % 4 {
7025								0 => drop(request), // refuse
7026								1 => {
7027									let mut producer = request.accept(None);
7028									let _ = producer.create_group(group::Info { sequence: round });
7029									let _ = producer.abort(Error::Dropped);
7030								}
7031								2 => {
7032									let mut producer = request.accept(None);
7033									let _ = producer.create_group(group::Info { sequence: round });
7034									kept.push(producer);
7035								}
7036								_ => {
7037									let mut producer = request.accept(None);
7038									let _ = producer.finish();
7039								}
7040							}
7041						}
7042					});
7043					sources.push(Source {
7044						producer: Some(source),
7045						server,
7046					});
7047				}
7048				// Detach a source, by abort or plain drop.
7049				2 | 3 => {
7050					if sources.is_empty() {
7051						continue;
7052					}
7053					let i = (next() as usize) % sources.len();
7054					let mut source = sources.swap_remove(i);
7055					if next() % 2 == 0
7056						&& let Some(producer) = source.producer.take()
7057					{
7058						let _ = producer.abort(Error::Dropped);
7059					}
7060					source.server.abort();
7061				}
7062				// Subscribe to a random track.
7063				4..=6 => {
7064					if subs.len() + pending_subs.len() >= 24 {
7065						continue;
7066					}
7067					let Some(broadcast) = consumer.get_broadcast("test") else {
7068						continue;
7069					};
7070					let name = &names[(next() as usize) % names.len()];
7071					if let Ok(track) = broadcast.track(name.as_ref()) {
7072						pending_subs.push(track.subscribe(None));
7073					}
7074				}
7075				// Drop a random subscriber.
7076				7 => {
7077					if subs.is_empty() {
7078						continue;
7079					}
7080					let i = (next() as usize) % subs.len();
7081					subs.swap_remove(i);
7082				}
7083				// Drain: resolve pending subscriptions and read groups.
7084				_ => {
7085					for sub in pending_subs.drain(..) {
7086						match ::tokio::time::timeout(std::time::Duration::from_millis(5), sub).await {
7087							Ok(Ok(sub)) => subs.push(sub),
7088							Ok(Err(_)) => {}
7089							// Still pending: dropping unsubscribes.
7090							Err(_) => {}
7091						}
7092					}
7093					for sub in subs.iter_mut() {
7094						while let Some(Ok(Some(_))) = sub.recv_group().now_or_never() {}
7095					}
7096				}
7097			}
7098			if step % 16 == 0 {
7099				settle().await;
7100			}
7101			// Vary task interleaving per seed.
7102			for _ in 0..(next() % 3) {
7103				::tokio::task::yield_now().await;
7104			}
7105		}
7106
7107		for source in sources {
7108			source.server.abort();
7109		}
7110		settle().await;
7111	}
7112}