From 9c5b16c7d3045f93400e77ba0324d8aaf179e18d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 22 Nov 2026 11:41:55 -0800 Subject: [PATCH 01/16] quest: a session's live-edge budget never sheds a frame a paced reader is owed Co-Authored-By: Claude Opus 5.5 --- quest/m0/nightly/live-edge-budget-paced.md | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 quest/m0/nightly/live-edge-budget-paced.md diff --git a/quest/m0/nightly/live-edge-budget-paced.md b/quest/m0/nightly/live-edge-budget-paced.md new file mode 100644 index 00000000000..b3a17d6e0a2 --- /dev/null +++ b/quest/m0/nightly/live-edge-budget-paced.md @@ -0,0 +1,79 @@ +# [L] A session's live-edge budget never sheds a frame a paced reader is owed + +## Goal + +`quic_sim::many_groups_carry_bulk_transfers_losslessly` (Nightly's `Tests (rs +quic-sim)`, `just rs quic-sim`) passes on any seed: a client session past its +`live_edges` budget sheds only frames no reader is owed, and stays bounded by +pausing ingest rather than by losing frames its paced readers have yet to take. + +## Plan + +Nightly run [45035580806](https://github.com/moq-dev/moq/actions/runs/45035580806) +failed `data4 frame 1: evicted`. It replays on `main` at `a2e356dfd0`: + +```sh +cd rs && MOQ_SIM_SEED=13746849096869201041 \ + CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS=true CARGO_PROFILE_RELEASE_OVERFLOW_CHECKS=true \ + cargo nextest run --profile ci --locked --release -p moq-relay --features test-support \ + --test integration --run-ignored only -E 'test(/^quic_sim::many_/)' +``` + +With `limits.client.live_edges = 0` in the test's cluster options, the same +seed passes in 11 s. No QUIC stream is evicted. The cause: + +- The relay ingests the publisher's 100 groups on one client session, whose + `live_edges` budget is 256 MiB by default + ([moq-dev/moq#9308](https://github.com/moq-dev/moq/pull/9308)). +- Ingest runs each group up to `pace::window`, the stream's receive window + (4 MiB by default), ahead of the group's fastest reader. Nothing bounds that + across a session's groups, so 100 paced groups may hold 400 MiB that no + reader took. Instrumented, they held about 2.6 MiB each at the failure. +- Past the budget, `cache::Edges::reclaim` calls `TrackState::shed_edge_all` + on the oldest edge. That sheds frames the relay's reader has not taken yet, + and aborts a copy still receiving a frame (`group::Handle::shed_all`). + Either way the downstream reader reads `Evicted`, which the wire carries as + 0x35 to the subscriber. + +Shedding only the frames readers took first is necessary but not enough. +Branch `fix/live-edge-shed-before-abort` (head `ab96065ebf`) does it: it sheds +the frames each edge's fastest reader took, or everything of an edge no reader +holds, before any frame a reader is owed. The seed still fails, since frames +ahead of active readers alone fill the budget. Reuse that branch for the +shedding order. + +The budget needs a way to stay bounded without shedding owed frames. Options, +pending the maintainer's pick under Waiting: + +- **Pace ingest to the budget (recommended).** While its session is past + `live_edges`, a group's ingest with a reader behind stops reading ahead, + as `poll_paced` does past its window, and resumes once a reader takes frames + and the shed brings the session back under. Stream credit then pushes back + to the publisher, as for any slow reader, so a hostile publisher still can't + make the relay hold more. Shedding keeps its current order only for groups + no reader holds and for a copy left receiving a frame while ingest is paused. + Check the credit side with `/verify-credit`: many streams paused at once must + still fit the half-window allowance from + [moq-dev/moq#9210](https://github.com/moq-dev/moq/pull/9210). +- **Split one session-wide ahead allowance among paced groups**, by slot as + `Pacing::allowance` splits credit. This bounds owed bytes by design, but + shrinks every group's read-ahead as the track count grows, even when the + budget has room. +- **Leave the design and set `live_edges = 0` in the test.** This is cheapest, + but a relay at its defaults still loses frames for a publisher with many + concurrent bulk groups, which the test exists to catch. + +Public API: none expected. Wire: none. + +## Waiting + +- Maintainer: pick how a session past `live_edges` stays bounded without + shedding frames a paced reader is owed: pace ingest to the budget + (recommended), split a session-wide ahead allowance by slot, or set + `live_edges = 0` in the test. Check: the pick is recorded in this Plan. + +## Related + +- [Pool pinned debt](/quest/m1/pool-pinned-debt.md) - the pool-side bound + on live edges ([moq-dev/moq#9422](https://github.com/moq-dev/moq/pull/9422)), + which leaves the session budget's shedding as is From ed8afad5e9bcfca7dfcc25d1fa52e6aab121c13f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 22 Nov 2026 16:12:05 -0800 Subject: [PATCH 02/16] wip(net): a session past its live-edge budget sheds by priority, taken frames first Co-Authored-By: Claude Opus 5.5 --- quest/m4/unsealed-frame-credit.md | 2 +- rs/moq-net/src/model/cache.rs | 214 +++++++++++++++------ rs/moq-net/src/model/group.rs | 44 ++++- rs/moq-net/src/model/track.rs | 112 +++++++++-- rs/moq-net/src/model/track/demand.rs | 9 + rs/moq-relay/tests/integration/quic_sim.rs | 43 +++-- 6 files changed, 330 insertions(+), 94 deletions(-) diff --git a/quest/m4/unsealed-frame-credit.md b/quest/m4/unsealed-frame-credit.md index 2b3cd6817ad..e69f28b3f9d 100644 --- a/quest/m4/unsealed-frame-credit.md +++ b/quest/m4/unsealed-frame-credit.md @@ -26,7 +26,7 @@ credit for bytes the model already counts. It is a design change of its own, as [unbounded groups](/quest/m3/unbounded-groups/README.md) made the release per segment. -Reproduce with `quic_sim::many_groups_carry_bulk_transfers_losslessly` at 200 +Reproduce with `quic_sim::many_groups_carry_their_highest_priorities_losslessly` at 200 groups instead of `MANY`. The fix raises `MANY` until a frame's worth of credit per stream no longer bounds it, or says what bounds it instead. diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 5f0f36f4170..54cb077cc8b 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -44,9 +44,9 @@ //! every origin so the whole process caches into a single policy. use crate::util::SendCell; -use std::collections::{BTreeMap, VecDeque}; +use std::collections::BTreeMap; use std::sync::Mutex; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI8, AtomicI64, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, OnceLock, PoisonError, Weak}; use std::task::{Poll, ready}; use std::time::Duration; @@ -672,21 +672,29 @@ const EDGE_SLACK: usize = 64; /// Each track a session ingests bills its live edge here: the newest group, which a live /// track keeps whatever the pool's budget, so a publisher holding many quiet tracks would /// otherwise hold one group each past any capacity. A frame write that leaves the session -/// past its limit sheds the frames of the session's live edges in the order they last -/// moved, oldest first, and then the writer's own older frames, so the cost stays with the session -/// causing it. The default is unbounded and costs nothing. +/// past its limit sheds its live edges in the order delivery would give up on them: the +/// lowest priority first, as [`crate::priority::Priority`] ranks a track, and among equals +/// the edge that moved longest ago, so the cost stays with the session causing it. Each edge +/// first sheds the frames its readers took, then everything; the one being written keeps +/// its newest frame. The default is unbounded and costs nothing. #[derive(Clone, Default)] pub(crate) struct Edges(Option>); +/// Where a live edge pays in its session's order: its track's rank, lowest first, then the +/// session's count of edge moves when it last moved, oldest first. +type EdgeKey = (i64, u64); + struct EdgesInner { limit: u64, // Bytes billed by the live edges of this session's tracks. Signed: a footprint that flips // while one of its bytes is mid-update bills the session an instant early or late, which // may dip it below zero, never a reason to reclaim. used: AtomicI64, - // The tracks in the order their live edges moved, oldest first, each with the move it - // was queued at, so an entry for an edge that moved on since is skipped. - order: Mutex, u64)>>, + // The tracks in the order their live edges pay, each with the move it was queued at. An + // entry whose track moved on or changed rank since is stale, and skipped. + order: Mutex, u64)>>, + // The moves of every live edge in this session, ordering edges of equal rank. + moves: AtomicU64, // The tracks billing here, so the order knows how many of its entries can be current. tracks: AtomicUsize, } @@ -699,6 +707,7 @@ impl Edges { limit, used: AtomicI64::new(0), order: Mutex::default(), + moves: AtomicU64::new(0), tracks: AtomicUsize::new(0), }) })) @@ -731,69 +740,95 @@ impl Edges { used.checked_sub(inner.limit).filter(|excess| *excess > 0) } - /// Pay the session's excess with its oldest live edges other than `writer`'s, then with - /// `writer`'s own older frames. Takes track locks: call with none held. + /// Pay the session's excess with its live edges in order, lowest rank and oldest first, + /// in two passes. The first sheds the frames each edge's readers took, which no reader is + /// owed. Only once none is left does the second shed every frame of an edge (aborting a + /// copy still receiving one), which then leaves the order until it grows again. `writer`'s + /// edge, being written, instead sheds its older frames in its turn and stays queued. + /// Takes track locks: call with none held. fn reclaim(&self, writer: &Track) { let Some(inner) = &self.0 else { return; }; - // Each entry is offered once per call, so an order holding only edges this write - // can't take never spins. - let mut offers = inner.order.lock().unwrap_or_else(PoisonError::into_inner).len(); - let mut kept = None; - while offers > 0 && self.excess().is_some() { - offers -= 1; - let Some((weak, moves)) = inner.order.lock().unwrap_or_else(PoisonError::into_inner).pop_front() else { - break; - }; - let Some(track) = weak.upgrade() else { - continue; - }; - if !track.edge_is(moves) { - continue; - } - // The writer's edge is the one being written: it pays last, and only in part. - if std::ptr::eq(Arc::as_ptr(&track), writer) { - kept = Some((weak, moves)); - continue; - } - let Some(state) = track.state.upgrade() else { - continue; - }; - // Unqueued before the shed, so whatever the edge bills after it queues it again. - track.queued.store(false, Ordering::Relaxed); - if let Ok(mut state) = state.write() { + for whole in [false, true] { + // The writer pays in its turn, or after every queued edge when it has no entry. + let mut paid = false; + // Each step resumes after the last key, so an entry is visited once per pass. + let mut after = None; + while self.excess().is_some() + && let Some((key, track, moves)) = self.next(after) + { + after = Some(key); + if std::ptr::eq(Arc::as_ptr(&track), writer) { + paid = true; + writer.shed_own(self, whole); + continue; + } + let Some(state) = track.state.upgrade() else { + continue; + }; + let Ok(mut state) = state.write() else { + continue; + }; + if !whole { + state.shed_edge_taken(moves); + continue; + } + // Unqueued before the shed, so whatever the edge bills after it queues it again. + inner.order.lock().unwrap_or_else(PoisonError::into_inner).remove(&key); + track.queued.store(false, Ordering::Relaxed); state.shed_edge_all(moves); } + if !paid { + writer.shed_own(self, whole); + } } - if let Some(entry) = kept { - inner - .order - .lock() - .unwrap_or_else(PoisonError::into_inner) - .push_front(entry); - } - if let Some(excess) = self.excess() - && let Some(state) = writer.state.upgrade() - && let Ok(mut state) = state.write() - { - state.shed_edge(excess); + } + + /// The first current entry in the order past `after`, dropping the stale ones before it. + fn next(&self, mut after: Option) -> Option<(EdgeKey, Arc, u64)> { + let inner = self.0.as_ref()?; + let mut order = inner.order.lock().unwrap_or_else(PoisonError::into_inner); + loop { + let (key, (weak, moves)) = match after { + None => order.range(..), + Some(key) => order.range((std::ops::Bound::Excluded(key), std::ops::Bound::Unbounded)), + } + .next()?; + let (key, moves) = (*key, *moves); + match weak.upgrade().filter(|track| track.queued_at(key, moves)) { + Some(track) => return Some((key, track, moves)), + None => { + order.remove(&key); + after = Some(key); + } + } } } - /// Queue `track`'s live edge as the session's newest, after its `moves`th move. - fn moved(&self, track: &Arc, moves: u64) { + /// Queue `track`'s live edge at its rank and last move, replacing nothing: an entry it + /// left at another rank or move turns stale. + fn queue(&self, track: &Arc) { let Some(inner) = &self.0 else { return; }; + let moves = track.moves.load(Ordering::Relaxed); + let key = (track.rank(), track.seq.load(Ordering::Relaxed)); let mut order = inner.order.lock().unwrap_or_else(PoisonError::into_inner); - order.push_back((Arc::downgrade(track), moves)); - // Each move leaves its track's earlier entry behind: drop those once they clearly - // outnumber the current ones, which costs a constant per move. + order.insert(key, (Arc::downgrade(track), moves)); + // Each move or rank change leaves its track's earlier entry behind: drop those once + // they clearly outnumber the current ones, which costs a constant per change. if order.len() > 2 * inner.tracks.load(Ordering::Relaxed) + EDGE_SLACK { - order.retain(|(track, moves)| track.upgrade().is_some_and(|track| track.edge_is(*moves))); + order.retain(|key, (track, moves)| track.upgrade().is_some_and(|track| track.queued_at(*key, *moves))); } } + + /// Number the session's next live-edge move, newer than every earlier one. + fn next_move(&self) -> u64 { + self.0 + .as_ref() + .map_or(0, |inner| inner.moves.fetch_add(1, Ordering::Relaxed)) + } } impl std::fmt::Debug for Edges { @@ -876,6 +911,12 @@ pub(super) struct Track { edges: Edges, // How many times the live edge moved to a newer group, naming its entry in `edges`. moves: AtomicU64, + // The session's count of edge moves when this live edge last moved, its age in `edges`. + seq: AtomicU64, + // The most urgent priority a subscriber asks with, `i8::MIN` while none does, and the + // publisher's: the track's rank in `edges`, as delivery ranks it. + subscriber: AtomicI8, + publisher: AtomicI8, // Whether the live edge has an entry in its session's order, so one that a reclaim shed // queues again once it grows. queued: AtomicBool, @@ -1024,6 +1065,9 @@ impl Track { frames, edges, moves: AtomicU64::new(0), + seq: AtomicU64::new(0), + subscriber: AtomicI8::new(i8::MIN), + publisher: AtomicI8::new(0), queued: AtomicBool::new(false), written: AtomicU64::new(0), next_expiry: AtomicU64::new(0), @@ -1061,15 +1105,69 @@ impl Track { /// The live edge moved to a newer group: queue it as its session's newest. Called under /// the track lock, which orders the moves. pub(super) fn edge_moved(self: &Arc) { - let moves = self.moves.fetch_add(1, Ordering::Relaxed) + 1; + self.seq.store(self.edges.next_move(), Ordering::Relaxed); + self.moves.fetch_add(1, Ordering::Relaxed); self.queued.store(true, Ordering::Relaxed); - self.edges.moved(self, moves); + self.edges.queue(self); } - /// The live edge billed more: queue it again if a reclaim took its entry. + /// The live edge billed more: queue it again, at the age it had, if a reclaim took its + /// entry. fn edge_grew(self: &Arc) { if !self.queued.swap(true, Ordering::Relaxed) { - self.edges.moved(self, self.moves.load(Ordering::Relaxed)); + self.edges.queue(self); + } + } + + /// The most urgent priority the track's subscribers ask with now, `None` with none. + pub(super) fn set_subscriber(self: &Arc, priority: Option) { + self.rerank(&self.subscriber, priority.unwrap_or(i8::MIN)); + } + + /// The publisher's priority for the track. + pub(super) fn set_publisher(self: &Arc, priority: i8) { + self.rerank(&self.publisher, priority); + } + + /// Store one half of the rank, moving the live edge to its new place in the session's + /// order if it has one. Queued even if a reclaim took its entry: an edge with nothing + /// left to shed costs that reclaim one look. + fn rerank(self: &Arc, half: &AtomicI8, priority: i8) { + if half.swap(priority, Ordering::Relaxed) != priority && self.moves.load(Ordering::Relaxed) > 0 { + self.edges.queue(self); + } + } + + /// The track's rank among its session's live edges, as [`crate::priority::group`] ranks + /// its subscription for delivery: higher pays later. + fn rank(&self) -> i64 { + crate::priority::group( + self.subscriber.load(Ordering::Relaxed), + self.publisher.load(Ordering::Relaxed), + ) + } + + /// Whether the live edge still sits at `key` after its `moves`th move. + fn queued_at(&self, key: EdgeKey, moves: u64) -> bool { + self.edge_is(moves) && self.rank() == key.0 + } + + /// Pay the session's excess with this track's own live edge, being written: the frames + /// its readers took, or with `whole`, its older frames, keeping the newest of an open + /// group. + fn shed_own(&self, edges: &Edges, whole: bool) { + let Some(excess) = edges.excess() else { + return; + }; + let Some(state) = self.state.upgrade() else { + return; + }; + let Ok(mut state) = state.write() else { + return; + }; + match whole { + false => state.shed_edge_taken(self.moves.load(Ordering::Relaxed)), + true => state.shed_edge(excess), } } diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index f9d4d64eb72..2e8d723a469 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -1120,6 +1120,31 @@ impl GroupState { } } + /// Shed the front frames the fastest reader took, those ending at or below `read` on the + /// pace scale: a reader on the group loses nothing it has yet to take, though a slower one + /// falls off as after any shed. Frames adopted from a head are off that scale, so the shed + /// stops at them. + fn shed_taken(&mut self, read: u64) { + if self.outcome.error().is_some() { + return; + } + let mut end = self.held(); + while let Some(entry) = self.entry(end) + && entry.end != 0 + && entry.end <= read + { + end += 1; + } + self.shed_to(end); + } + + /// Whether a frame still arriving bills the session: its payload or its header's fields. + fn arriving(&self) -> bool { + self.partial + .as_ref() + .is_some_and(|partial| !partial.scratch && (partial.charged > 0 || partial.fields.is_some())) + } + /// Whether this copy holds no committed frame. fn is_empty(&self) -> bool { self.front.is_empty() && self.log.base() == self.log.end() @@ -2801,16 +2826,23 @@ impl Handle { return; }; state.shed_all(); - // Its payload and its header's fields both bill the session. - if state - .partial - .as_ref() - .is_some_and(|partial| !partial.scratch && (partial.charged > 0 || partial.fields.is_some())) - { + if state.arriving() { self.commit_abort(state, Error::Evicted); } } + /// Shed the frames this copy's fastest reader took, see [`GroupState::shed_taken`], or + /// every committed frame while no reader holds the copy, which no reader is owed. + pub(super) fn shed_taken(&self) { + let Ok(mut state) = self.state.write() else { + return; + }; + match self.state.wanted() { + true => state.shed_taken(self.alive.pace.read()), + false => state.shed_all(), + } + } + pub(super) fn delivery_size(&self) -> u64 { let state = self.state.read(); state.charge.size() diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index f717dca4fc3..e10d674967a 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -3070,6 +3070,7 @@ impl TrackState { /// Attach the publisher's immutable metadata without replacing it with local cache policy. fn install(&mut self, info: Info) { + self.cache.set_publisher(info.priority); // A replaced max age moves every parked read's budget. if self.info.replace(info).is_some() { self.cache.wakes().wake_all(); @@ -3096,6 +3097,7 @@ impl TrackState { let mut new = state.write().ok().expect("a new track is open"); new.drops_bill = cache.extra(); new.arrivals_bill = cache.extra(); + new.subscriptions.lock().account = Some(cache.clone()); new.cache = cache; drop(new); state @@ -3457,29 +3459,38 @@ impl TrackState { paid } - /// Shed every frame of the live edge its session queued at its `moves`th move, if it is - /// still the edge: the session holds more live edges than its budget, and this one moved - /// longest ago. + /// Shed the frames each copy's fastest reader took of the live edge its session queued at + /// its `moves`th move, if it is still the edge: the session holds more live edges than its + /// budget, and this one moved longest ago. /// /// The group stays cached, its timeline intact, so it still marks where the live edge is: /// a live join is placed and staleness is judged as before, and a reader reaching a shed /// frame reads [`Error::Evicted`], as after any shed. - pub(super) fn shed_edge_all(&mut self, moves: u64) { - if !self.cache.edge_is(moves) { - return; + pub(super) fn shed_edge_taken(&mut self, moves: u64) { + for group in self.edge_copies(moves) { + group.shed_taken(); } - let Some(slot) = self - .latest_group - .filter(|latest| self.protects(*latest)) - .and_then(|latest| self.lookup.get(&latest)) - else { - return; - }; - for group in slot.copies() { + } + + /// Shed every frame of the live edge queued at its `moves`th move, read or not, and abort + /// each copy still receiving a frame, which cannot be shed: the session is past its budget + /// with no frame its readers took left to shed. + pub(super) fn shed_edge_all(&mut self, moves: u64) { + for group in self.edge_copies(moves) { group.shed_all(); } } + /// The copies of the live edge its session queued at its `moves`th move, if it is still + /// the edge. + fn edge_copies(&self, moves: u64) -> impl Iterator { + self.latest_group + .filter(|latest| self.cache.edge_is(moves) && self.protects(*latest)) + .and_then(|latest| self.lookup.get(&latest)) + .into_iter() + .flat_map(Slot::copies) + } + /// Shed up to `excess` bytes of the live edge's older frames, keeping the newest of an /// open group: the session is past its budget with no other live edge left to shed. pub(super) fn shed_edge(&mut self, excess: u64) { @@ -25919,6 +25930,74 @@ mod test { drop(open); } + /// A session past its live-edge budget sheds in delivery's order: the lowest-priority + /// edge first even when it is newer, a subscriber's priority over the publisher's, and + /// the older of two equal edges. + #[test] + #[cfg(feature = "async")] + fn a_session_sheds_its_lowest_priority_edge_first() { + const FRAME: usize = 10_000; + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(25_000)); + let track = |name: &str, priority| Producer::new(broadcast.clone(), name, Info::timed().with_priority(priority)); + let (mut old, mut low, mut mid, mut new) = (track("old", 0), track("low", -5), track("mid", 0), track("new", 0)); + let kept = |producer: &Producer| { + let mut group = producer.consume().peek_group(0).expect("the edge stays cached"); + matches!(group.read_frame().now_or_never(), Some(Ok(Some(_)))) + }; + + finished_group(&mut old, FRAME); + finished_group(&mut low, FRAME); + // Past the budget: `low` moved after `old`, but the publisher ranks it lower. + finished_group(&mut mid, FRAME); + assert!(broadcast.edges.used() <= 25_000, "{:?}", broadcast.edges); + assert!(!kept(&low), "the lowest-priority edge kept its frame"); + assert!(kept(&old), "the older equal edge paid"); + assert!(kept(&mid), "the writer paid"); + + // A subscriber's priority outranks any publisher's: `old` now pays after `mid`, the + // older of the two equals left. + let _urgent = old.subscribe(Subscription::default().with_priority(1)); + finished_group(&mut new, FRAME); + assert!(broadcast.edges.used() <= 25_000, "{:?}", broadcast.edges); + assert!(!kept(&mid), "the older of two equal edges kept its frame"); + assert!(kept(&old) && kept(&new), "a subscribed or newer edge paid"); + } + + /// Frames a reader took pay before any frame a reader is owed, whatever their priority: + /// a higher-priority edge whose reader caught up sheds what it read, and a lower one + /// whose reader lags keeps its frame. + #[test] + #[cfg(feature = "async")] + fn taken_frames_pay_before_owed_ones() { + const FRAME: usize = 10_000; + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(25_000)); + let track = |name: &str, priority| Producer::new(broadcast.clone(), name, Info::timed().with_priority(priority)); + let (mut low, mut high, mut new) = (track("low", -5), track("high", 5), track("new", 0)); + let write = |producer: &mut Producer| { + let mut group = producer.append_next().unwrap(); + let reader = producer.consume().peek_group(group.start).expect("cached"); + group.write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; FRAME])).unwrap(); + (group, reader) + }; + + let (_low_group, mut lagging) = write(&mut low); + let (_high_group, mut caught_up) = write(&mut high); + assert!(matches!(caught_up.read_frame().now_or_never(), Some(Ok(Some(_))))); + let _new = write(&mut new); + assert!(broadcast.edges.used() <= 25_000, "{:?}", broadcast.edges); + assert!( + matches!(lagging.read_frame().now_or_never(), Some(Ok(Some(_)))), + "an owed frame paid while a taken one was left" + ); + let mut late = high.consume().peek_group(0).expect("the edge stays cached"); + assert!( + matches!(late.read_frame().now_or_never(), Some(Err(Error::Evicted))), + "the taken frame was kept" + ); + } + /// Shedding a received compressed edge whose plain copy a reader started inflates nothing /// just to drop it: the plain copy goes with the slices, decoder included, a plain read of /// them is evicted, and the edge bills only its fixed bookkeeping after. @@ -26064,7 +26143,10 @@ mod test { }) .unwrap(); partial.write(bytes::Bytes::from(vec![0u8; 10_000])).unwrap(); - finished_group(&mut b, 10_000); + // b's reader is owed its frame, so no frame a reader took can pay instead. + let mut written = b.append_next().unwrap(); + let _reader = b.consume().peek_group(written.start).expect("cached"); + written.write_frame(written.key_time(), bytes::Bytes::from(vec![0u8; 10_000])).unwrap(); assert!(broadcast.edges.used() <= 15_000, "{:?}", broadcast.edges); // The rest of the frame lands in an aborted copy, which finishing reports. let _ = partial.write(bytes::Bytes::from(vec![0u8; 10_000])); diff --git a/rs/moq-net/src/model/track/demand.rs b/rs/moq-net/src/model/track/demand.rs index d95cd7bdded..bd10191e08e 100644 --- a/rs/moq-net/src/model/track/demand.rs +++ b/rs/moq-net/src/model/track/demand.rs @@ -68,6 +68,9 @@ pub(super) struct Subscriptions { waiters: kio::WaiterList, /// [`super::Refreshing`] callers, woken when their request is sent or ends. callers: kio::WaiterList, + /// The track's cache account, told the most urgent priority so its session sheds live + /// edges in delivery's order. Absent on a track with no account. + pub(super) account: Option>, } /// The readers waiting on one live join, counted under the budget each waits with and the @@ -425,6 +428,12 @@ impl Subscriptions { } self.count -= 1; } + let priority = self.priority.last_key_value().map(|(priority, _)| *priority); + if let Some(account) = &self.account + && prev.map(|prev| prev.0) != priority + { + account.set_subscriber(priority); + } if reshaped || self.scalars() != prev { self.waiters.take() } else { diff --git a/rs/moq-relay/tests/integration/quic_sim.rs b/rs/moq-relay/tests/integration/quic_sim.rs index 72c8ab75cb7..d37fabc5b44 100644 --- a/rs/moq-relay/tests/integration/quic_sim.rs +++ b/rs/moq-relay/tests/integration/quic_sim.rs @@ -303,9 +303,12 @@ fn concurrent_groups_carry_bulk_transfers_losslessly() { /// fixed credit per paused stream fits in half the connection window. Every one still /// pauses, since a paused stream holds a share of that half set by its slot, not by how many /// pause. +/// +/// Their read-ahead together passes the relay session's live-edge budget, which sheds the +/// lowest priorities first: only the [`LOSSLESS`] highest must arrive whole. #[test] #[ignore = "a hundred bulk transfers, about a minute in debug: run in release by `just rs quic-sim`"] -fn many_groups_carry_bulk_transfers_losslessly() { +fn many_groups_carry_their_highest_priorities_losslessly() { memory::run(|| bulk(MANY, 64 * 1024, 1024 * 1024)); } @@ -314,14 +317,20 @@ fn many_groups_carry_bulk_transfers_losslessly() { /// each paused stream holds its whole stream window. const SESSIONS: usize = 12; -/// How many share one in [`many_groups_carry_bulk_transfers_losslessly`]. Past a couple of -/// hundred, the frames in flight at once each hold credit until they seal, and that fills -/// the connection window whatever the paused streams hold. +/// How many share one in [`many_groups_carry_their_highest_priorities_losslessly`]. Past a +/// couple of hundred, the frames in flight at once each hold credit until they seal, and that +/// fills the connection window whatever the paused streams hold. const MANY: usize = 100; +/// How many of the highest-priority tracks [`bulk`] reads whole: each holds at most a stream +/// window (4 MiB) ahead of its reader plus what the reader took, so this many stay well +/// inside a session's default 256 MiB live-edge budget, which sheds lower priorities first. +const LOSSLESS: usize = 40; + /// Write `tracks` tracks of one group each, [`BULK`] bytes in `chunk`-byte frames, through -/// one relay, and read the first `read` bytes of each slower than they are written, -/// asserting every one arrives. +/// one relay, and read the first `read` bytes of each slower than they are written. Track `i` +/// has publisher priority `i`: the [`LOSSLESS`] highest must arrive whole, and a lower one may +/// end early with an error but never delivers a wrong frame. async fn bulk(tracks: usize, chunk: usize, read: usize) { let network = Network::new(0); let auth = memory::public(&[""], &[], &[]); @@ -336,7 +345,10 @@ async fn bulk(tracks: usize, chunk: usize, read: usize) { .map(|index| { broadcast .broadcast() - .create_track(format!("data{index}"), moq_net::track::Info::default()) + .create_track( + format!("data{index}"), + moq_net::track::Info::default().with_priority(i8::try_from(index).expect("a priority per track")), + ) .expect("track") }) .collect(); @@ -369,8 +381,10 @@ async fn bulk(tracks: usize, chunk: usize, read: usize) { // Held until the reads end: dropping a track unfinished aborts it. futures::future::pending::<()>().await; }; - let read = |name: String| { + let read = |index: usize| { let viewer = viewer.clone(); + let name = format!("data{index}"); + let lossless = index + LOSSLESS >= tracks; async move { let remote = loop { match viewer.consume().request("bulk", None).await { @@ -391,11 +405,12 @@ async fn bulk(tracks: usize, chunk: usize, read: usize) { let mut ordered = consumer.ordered(); let mut group = ordered.next_group().await.unwrap().expect("a group"); for index in 0..read / chunk { - let frame = group - .read_frame() - .await - .unwrap_or_else(|err| panic!("{name} frame {index}: {err}")) - .unwrap_or_else(|| panic!("{name} ended at frame {index}")); + let frame = match group.read_frame().await { + Ok(frame) => frame.unwrap_or_else(|| panic!("{name} ended at frame {index}")), + // Shed by the budget, which a lower priority may be. + Err(_) if !lossless => return, + Err(err) => panic!("{name} frame {index}: {err}"), + }; assert_eq!(frame.payload.len(), chunk, "{name} frame {index} is cut short"); assert!( frame.payload.iter().all(|&byte| byte == index as u8), @@ -415,7 +430,7 @@ async fn bulk(tracks: usize, chunk: usize, read: usize) { } }; let writes = futures::future::join_all(sources.into_iter().map(write)); - let reads = futures::future::join_all((0..tracks).map(|index| read(format!("data{index}")))); + let reads = futures::future::join_all((0..tracks).map(read)); kio::clock::timeout(Duration::from_secs(600), async { futures::pin_mut!(writes, reads); futures::future::select(writes, reads).await; From a09e34fa13d64251301da6d0b2262b23ff204128 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 22 Nov 2026 16:46:59 -0800 Subject: [PATCH 03/16] fix(net): a session past its live-edge budget sheds by priority, taken frames first Co-Authored-By: Claude Opus 5.5 --- doc/bin/relay/config.md | 6 +- doc/lib/rs/moq-net.md | 2 +- quest/m0/nightly/live-edge-budget-paced.md | 79 ---------------------- rs/moq-net/src/session.rs | 6 +- rs/moq-relay/tests/integration/quic_sim.rs | 9 +-- 5 files changed, 14 insertions(+), 88 deletions(-) delete mode 100644 quest/m0/nightly/live-edge-budget-paced.md diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md index afb0ca534e1..6c844d31913 100644 --- a/doc/bin/relay/config.md +++ b/doc/bin/relay/config.md @@ -211,8 +211,10 @@ Zero admits no entries of that kind, not unlimited entries. `live_edges` bounds the newest group of every track a session publishes to the relay. The cache keeps that group whatever its `capacity` or `headroom`, so a publisher holding many quiet tracks would otherwise hold one group each past -any budget. Past the bound, the frames of the session's own live edges are -shed, the one that moved longest ago first. A viewer reaching a shed frame +any budget. Past the bound, the session's own live edges are shed in delivery's +priority order: the lowest-priority track first, and among equals the edge that +moved longest ago. Frames viewers already read go before any frame a viewer is +still owed. A viewer reaching a shed frame meets it as it would any frame the cache dropped; the group's place on the timeline stays, so live joins land where they did. Another session's edges are never touched. Here zero means no bound. diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index db08c6181d5..77081ce2ceb 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -30,7 +30,7 @@ What you use it for, beyond what the concept page already describes: - **Use the model without a runtime.** By default `moq-net` is its `poll_*` APIs and origin driver with caller-supplied time. The `async` feature adds their async wrappers, `time::run`, and both wire sessions. - **You drive the session, or `moq-tokio` does.** `connect` and `accept` return a session plus a driver that never reads the clock itself. `moq_net::time::run` polls it on tokio. `moq-tokio` hides that. A custom transport implements `moq_net::transport::poll`, and `moq_net::transport::memory::pair` links two sessions in one process with no sockets, for tests or in-process links. `Server` bounds each accept with one deadline from the connection's arrival (30 s by default, `with_timeout`), across your transport handshake (`Server::deadline`), SETUP, your admission decision (`Handshake::expired`), and moq-lite 01/02's SETUP reply, and opens a receive window the transport held back once you admit (`with_receive_window`). - **Reconnect policy comes with it.** With the `async` feature, `moq_net::Reconnect` decides which of a peer's addresses to dial, how long each dial and handshake may take, when to back off and give up, and how to follow a GOAWAY, without doing I/O: you dial each `Attempt` it asks for and report back. `moq-tokio`'s `Connection` runs it, so a client on another runtime gets the same policy rather than a copy. The first walk of the peer's addresses fails fast: if it yields no session, the policy ends with that walk's error instead of retrying, so a setup mistake such as an untrusted certificate or no version in common surfaces at once, and a client started before its relay is reachable exits for its supervisor to restart. Once a session has been established, later failures back off and retry, so relay restarts still recover. -- **A session bounds what its peer can hold.** Each request holds a stream, so the transport's stream credit bounds subscriptions and FETCHes. Once that credit runs out, a waiting open resets the lowest-priority group stream below it, which the subscriber sees dropped, so the credit it frees goes to the higher-priority group. `session::Limits` (via `Client::with_limits` and `Server::with_limits`) bounds the announcements per session. The default suits a relay mesh, so lower it for untrusted peers. Past it, the session closes with `TOO_MANY_REQUESTS`. Its `live_edges` bounds the bytes held by the newest group of every track the peer publishes, which the cache otherwise keeps past any capacity: past it, the session sheds the frames of its own live edges, the one that moved longest ago first. It is unbounded by default. Peer-declared lengths are capped before they are buffered. +- **A session bounds what its peer can hold.** Each request holds a stream, so the transport's stream credit bounds subscriptions and FETCHes. Once that credit runs out, a waiting open resets the lowest-priority group stream below it, which the subscriber sees dropped, so the credit it frees goes to the higher-priority group. `session::Limits` (via `Client::with_limits` and `Server::with_limits`) bounds the announcements per session. The default suits a relay mesh, so lower it for untrusted peers. Past it, the session closes with `TOO_MANY_REQUESTS`. Its `live_edges` bounds the bytes held by the newest group of every track the peer publishes, which the cache otherwise keeps past any capacity: past it, the session sheds its own live edges in delivery's priority order, the lowest-priority track and then the oldest edge first, shedding the frames readers took before any a reader is owed. It is unbounded by default. Peer-declared lengths are capped before they are buffered. - **Authorization is in band.** On moq-lite 07 (`moq-lite-07-wip`, opt-in), `session.auth()` presents tokens without reconnecting and watches the grant the peer sent back. `add(token)` presents another and returns its `Credential` at once, and `credential.answered().await` waits for the peer to take it: on its AUTH stream, or at once on moq-transport without AUTH, where only a request that names it carries it. Dropping its last clone, including any a route holds, withdraws it, answered or not. A handle passed to `Client::with_auth` outlives each session, so its tokens, and the routes naming them, carry across your own reconnects. A server verifies tokens itself by taking `handshake.requests()` before `ok()`. `authorize(&grant)` narrows or widens a live session on any version: what falls outside resets with `Unauthorized` and the session stays up. A client that publishes outside its grant closes the session, naming the path. - **A graceful close waits.** `session.close().await` withdraws announcements and drains for up to one second. `moq-lite-05` and newer wait for the subscriber to receive finished tails; older Lite versions and IETF wait only for transport ACKs. `abort` ends immediately. diff --git a/quest/m0/nightly/live-edge-budget-paced.md b/quest/m0/nightly/live-edge-budget-paced.md deleted file mode 100644 index b3a17d6e0a2..00000000000 --- a/quest/m0/nightly/live-edge-budget-paced.md +++ /dev/null @@ -1,79 +0,0 @@ -# [L] A session's live-edge budget never sheds a frame a paced reader is owed - -## Goal - -`quic_sim::many_groups_carry_bulk_transfers_losslessly` (Nightly's `Tests (rs -quic-sim)`, `just rs quic-sim`) passes on any seed: a client session past its -`live_edges` budget sheds only frames no reader is owed, and stays bounded by -pausing ingest rather than by losing frames its paced readers have yet to take. - -## Plan - -Nightly run [45035580806](https://github.com/moq-dev/moq/actions/runs/45035580806) -failed `data4 frame 1: evicted`. It replays on `main` at `a2e356dfd0`: - -```sh -cd rs && MOQ_SIM_SEED=13746849096869201041 \ - CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS=true CARGO_PROFILE_RELEASE_OVERFLOW_CHECKS=true \ - cargo nextest run --profile ci --locked --release -p moq-relay --features test-support \ - --test integration --run-ignored only -E 'test(/^quic_sim::many_/)' -``` - -With `limits.client.live_edges = 0` in the test's cluster options, the same -seed passes in 11 s. No QUIC stream is evicted. The cause: - -- The relay ingests the publisher's 100 groups on one client session, whose - `live_edges` budget is 256 MiB by default - ([moq-dev/moq#9308](https://github.com/moq-dev/moq/pull/9308)). -- Ingest runs each group up to `pace::window`, the stream's receive window - (4 MiB by default), ahead of the group's fastest reader. Nothing bounds that - across a session's groups, so 100 paced groups may hold 400 MiB that no - reader took. Instrumented, they held about 2.6 MiB each at the failure. -- Past the budget, `cache::Edges::reclaim` calls `TrackState::shed_edge_all` - on the oldest edge. That sheds frames the relay's reader has not taken yet, - and aborts a copy still receiving a frame (`group::Handle::shed_all`). - Either way the downstream reader reads `Evicted`, which the wire carries as - 0x35 to the subscriber. - -Shedding only the frames readers took first is necessary but not enough. -Branch `fix/live-edge-shed-before-abort` (head `ab96065ebf`) does it: it sheds -the frames each edge's fastest reader took, or everything of an edge no reader -holds, before any frame a reader is owed. The seed still fails, since frames -ahead of active readers alone fill the budget. Reuse that branch for the -shedding order. - -The budget needs a way to stay bounded without shedding owed frames. Options, -pending the maintainer's pick under Waiting: - -- **Pace ingest to the budget (recommended).** While its session is past - `live_edges`, a group's ingest with a reader behind stops reading ahead, - as `poll_paced` does past its window, and resumes once a reader takes frames - and the shed brings the session back under. Stream credit then pushes back - to the publisher, as for any slow reader, so a hostile publisher still can't - make the relay hold more. Shedding keeps its current order only for groups - no reader holds and for a copy left receiving a frame while ingest is paused. - Check the credit side with `/verify-credit`: many streams paused at once must - still fit the half-window allowance from - [moq-dev/moq#9210](https://github.com/moq-dev/moq/pull/9210). -- **Split one session-wide ahead allowance among paced groups**, by slot as - `Pacing::allowance` splits credit. This bounds owed bytes by design, but - shrinks every group's read-ahead as the track count grows, even when the - budget has room. -- **Leave the design and set `live_edges = 0` in the test.** This is cheapest, - but a relay at its defaults still loses frames for a publisher with many - concurrent bulk groups, which the test exists to catch. - -Public API: none expected. Wire: none. - -## Waiting - -- Maintainer: pick how a session past `live_edges` stays bounded without - shedding frames a paced reader is owed: pace ingest to the budget - (recommended), split a session-wide ahead allowance by slot, or set - `live_edges = 0` in the test. Check: the pick is recorded in this Plan. - -## Related - -- [Pool pinned debt](/quest/m1/pool-pinned-debt.md) - the pool-side bound - on live edges ([moq-dev/moq#9422](https://github.com/moq-dev/moq/pull/9422)), - which leaves the session budget's shedding as is diff --git a/rs/moq-net/src/session.rs b/rs/moq-net/src/session.rs index de9353a3df4..16835b17896 100644 --- a/rs/moq-net/src/session.rs +++ b/rs/moq-net/src/session.rs @@ -1190,8 +1190,10 @@ pub struct Limits { /// /// The cache never evicts a live track's newest group, so a peer holding many quiet /// tracks would otherwise hold one group each past any cache capacity. Past this, the - /// session sheds the frames of its own live edges, the one that moved longest ago first, - /// and then the older frames of the one being written. `None` leaves them unbounded. + /// session sheds its own live edges in delivery's priority order, the lowest-priority + /// track and then the edge that moved longest ago first: the frames readers took, then + /// whole edges, of which the one being written keeps its newest frame. `None` leaves + /// them unbounded. pub live_edges: Option, } diff --git a/rs/moq-relay/tests/integration/quic_sim.rs b/rs/moq-relay/tests/integration/quic_sim.rs index d37fabc5b44..fad720ff42c 100644 --- a/rs/moq-relay/tests/integration/quic_sim.rs +++ b/rs/moq-relay/tests/integration/quic_sim.rs @@ -322,10 +322,11 @@ const SESSIONS: usize = 12; /// fills the connection window whatever the paused streams hold. const MANY: usize = 100; -/// How many of the highest-priority tracks [`bulk`] reads whole: each holds at most a stream -/// window (4 MiB) ahead of its reader plus what the reader took, so this many stay well -/// inside a session's default 256 MiB live-edge budget, which sheds lower priorities first. -const LOSSLESS: usize = 40; +/// How many of the highest-priority tracks [`bulk`] reads whole. A session past its 256 MiB +/// live-edge budget sheds every frame readers took first, and each group's ingest runs at most +/// half the 32 MiB live tail ahead of its reader, so this many fit with room to spare however +/// the rest are shed. Measured, a group holds about 8 MiB ahead, so about 30 survive. +const LOSSLESS: usize = 12; /// Write `tracks` tracks of one group each, [`BULK`] bytes in `chunk`-byte frames, through /// one relay, and read the first `read` bytes of each slower than they are written. Track `i` From e1c8e234d64942c4b6c9ddde95111968449d64f3 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 22 Nov 2026 17:07:14 -0800 Subject: [PATCH 04/16] chore(net): format and drop an unused mut Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/track.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index e10d674967a..f7215420b49 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -25939,8 +25939,10 @@ mod test { const FRAME: usize = 10_000; let pool = cache::Pool::unbounded(); let broadcast = session_broadcast(&pool, Some(25_000)); - let track = |name: &str, priority| Producer::new(broadcast.clone(), name, Info::timed().with_priority(priority)); - let (mut old, mut low, mut mid, mut new) = (track("old", 0), track("low", -5), track("mid", 0), track("new", 0)); + let track = + |name: &str, priority| Producer::new(broadcast.clone(), name, Info::timed().with_priority(priority)); + let (mut old, mut low, mut mid, mut new) = + (track("old", 0), track("low", -5), track("mid", 0), track("new", 0)); let kept = |producer: &Producer| { let mut group = producer.consume().peek_group(0).expect("the edge stays cached"); matches!(group.read_frame().now_or_never(), Some(Ok(Some(_)))) @@ -25973,12 +25975,15 @@ mod test { const FRAME: usize = 10_000; let pool = cache::Pool::unbounded(); let broadcast = session_broadcast(&pool, Some(25_000)); - let track = |name: &str, priority| Producer::new(broadcast.clone(), name, Info::timed().with_priority(priority)); + let track = + |name: &str, priority| Producer::new(broadcast.clone(), name, Info::timed().with_priority(priority)); let (mut low, mut high, mut new) = (track("low", -5), track("high", 5), track("new", 0)); let write = |producer: &mut Producer| { let mut group = producer.append_next().unwrap(); let reader = producer.consume().peek_group(group.start).expect("cached"); - group.write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; FRAME])).unwrap(); + group + .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; FRAME])) + .unwrap(); (group, reader) }; @@ -26133,7 +26138,7 @@ mod test { let pool = cache::Pool::unbounded(); let broadcast = session_broadcast(&pool, Some(15_000)); let a = Producer::new(broadcast.clone(), "a", Info::timed()); - let mut b = Producer::new(broadcast.clone(), "b", Info::timed()); + let b = Producer::new(broadcast.clone(), "b", Info::timed()); let group = a.append_next().unwrap(); let mut partial = group @@ -26146,7 +26151,9 @@ mod test { // b's reader is owed its frame, so no frame a reader took can pay instead. let mut written = b.append_next().unwrap(); let _reader = b.consume().peek_group(written.start).expect("cached"); - written.write_frame(written.key_time(), bytes::Bytes::from(vec![0u8; 10_000])).unwrap(); + written + .write_frame(written.key_time(), bytes::Bytes::from(vec![0u8; 10_000])) + .unwrap(); assert!(broadcast.edges.used() <= 15_000, "{:?}", broadcast.edges); // The rest of the frame lands in an aborted copy, which finishing reports. let _ = partial.write(bytes::Bytes::from(vec![0u8; 10_000])); From 709dc27bde302d2efd280ebec3bdf8704895e8a1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 22 Nov 2026 17:23:08 -0800 Subject: [PATCH 05/16] fix(net): a live-edge move and its queue entry update under one lock; taken inflated frames shed too Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/cache.rs | 27 ++++++++++++++-------- rs/moq-net/src/model/group.rs | 15 ++++++++++++ rs/moq-net/src/model/track.rs | 26 +++++++++++++++++++++ rs/moq-relay/tests/integration/quic_sim.rs | 5 ++-- 4 files changed, 62 insertions(+), 11 deletions(-) diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 54cb077cc8b..06cfbca5c04 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -812,9 +812,10 @@ impl Edges { let Some(inner) = &self.0 else { return; }; + let mut order = inner.order.lock().unwrap_or_else(PoisonError::into_inner); + // Read under the lock a move updates them under, so the two always match. let moves = track.moves.load(Ordering::Relaxed); let key = (track.rank(), track.seq.load(Ordering::Relaxed)); - let mut order = inner.order.lock().unwrap_or_else(PoisonError::into_inner); order.insert(key, (Arc::downgrade(track), moves)); // Each move or rank change leaves its track's earlier entry behind: drop those once // they clearly outnumber the current ones, which costs a constant per change. @@ -823,11 +824,21 @@ impl Edges { } } - /// Number the session's next live-edge move, newer than every earlier one. - fn next_move(&self) -> u64 { - self.0 - .as_ref() - .map_or(0, |inner| inner.moves.fetch_add(1, Ordering::Relaxed)) + /// Move `track`'s live edge to a newer group, queued as the session's newest. + fn moved(&self, track: &Arc) { + let Some(inner) = &self.0 else { + track.moves.fetch_add(1, Ordering::Relaxed); + return; + }; + // Under the order's lock, so a concurrent queue never pairs this move with the last one's + // age, or overwrites this entry with the last move's. + let order = inner.order.lock().unwrap_or_else(PoisonError::into_inner); + track + .seq + .store(inner.moves.fetch_add(1, Ordering::Relaxed), Ordering::Relaxed); + track.moves.fetch_add(1, Ordering::Relaxed); + drop(order); + self.queue(track); } } @@ -1105,10 +1116,8 @@ impl Track { /// The live edge moved to a newer group: queue it as its session's newest. Called under /// the track lock, which orders the moves. pub(super) fn edge_moved(self: &Arc) { - self.seq.store(self.edges.next_move(), Ordering::Relaxed); - self.moves.fetch_add(1, Ordering::Relaxed); self.queued.store(true, Ordering::Relaxed); - self.edges.queue(self); + self.edges.moved(self); } /// The live edge billed more: queue it again, at the age it had, if a reclaim took its diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 2e8d723a469..f92063ad449 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -687,6 +687,17 @@ impl Plain { freed } + /// Shed the inflated frames before group frame `end`, which a reader took. + fn shed_before(&self, end: usize) { + let mut state = self.lock(); + while state.base < end && !state.frames.is_empty() { + self.pop(&mut state); + } + if state.frames.is_empty() { + state.frames = VecDeque::new(); + } + } + /// Whether inflating failed on the group's content, rather than its release. fn malformed(&self) -> bool { let state = self.lock(); @@ -1136,6 +1147,10 @@ impl GroupState { end += 1; } self.shed_to(end); + // A plain read takes the same frames on the same scale, so their inflated copies go too. + if let Some(flate) = &self.flate { + flate.plain.shed_before(end); + } } /// Whether a frame still arriving bills the session: its payload or its header's fields. diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index f7215420b49..ecd41e9c4fe 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -26038,6 +26038,32 @@ mod test { drop(group); } + /// The frames a plain reader took of a received compressed edge go with their slices: a + /// shed of what readers took leaves no inflated copy billing the session. + #[kio::test] + #[cfg(feature = "async")] + async fn a_shed_of_taken_frames_drops_their_inflated_copies() { + let info = Info::timed().with_compression(Compression::Deflate); + let stored = stored_slices(&info); + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(1 << 30)); + let producer = Producer::new(broadcast.clone(), "test", info); + let mut group = producer.create_group(group::Info { start: 0 }).unwrap(); + for object in &stored { + group = ingest_slice(group, object); + } + let mut reader = producer.consume().peek_group(0).expect("cached"); + for _ in 0..stored.len() { + assert!(reader.read_frame().await.unwrap().is_some()); + } + assert!(broadcast.edges.used() > 1024); + + let moves = producer.state.read().cache.moves(); + producer.state.write().ok().expect("open").shed_edge_taken(moves); + assert!(broadcast.edges.used() < 1024, "{:?}", broadcast.edges); + drop((reader, group)); + } + /// The stored slices a publisher of a compressed group would send. #[cfg(feature = "async")] fn stored_slices(info: &Info) -> arrayvec::ArrayVec { diff --git a/rs/moq-relay/tests/integration/quic_sim.rs b/rs/moq-relay/tests/integration/quic_sim.rs index fad720ff42c..29ed573f3cf 100644 --- a/rs/moq-relay/tests/integration/quic_sim.rs +++ b/rs/moq-relay/tests/integration/quic_sim.rs @@ -330,7 +330,7 @@ const LOSSLESS: usize = 12; /// Write `tracks` tracks of one group each, [`BULK`] bytes in `chunk`-byte frames, through /// one relay, and read the first `read` bytes of each slower than they are written. Track `i` -/// has publisher priority `i`: the [`LOSSLESS`] highest must arrive whole, and a lower one may +/// has publisher priority `i - 128`, ordered for up to 256 tracks: the [`LOSSLESS`] highest must arrive whole, and a lower one may /// end early with an error but never delivers a wrong frame. async fn bulk(tracks: usize, chunk: usize, read: usize) { let network = Network::new(0); @@ -348,7 +348,8 @@ async fn bulk(tracks: usize, chunk: usize, read: usize) { .broadcast() .create_track( format!("data{index}"), - moq_net::track::Info::default().with_priority(i8::try_from(index).expect("a priority per track")), + moq_net::track::Info::default() + .with_priority(i8::try_from(index as i64 - 128).expect("at most 256 tracks")), ) .expect("track") }) From 663125dbca2bde74af7541d00f21b421fe88f6c0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 22 Nov 2026 17:40:20 -0800 Subject: [PATCH 06/16] fix(net): leave a compressed edge's inflated copies to the whole-edge pass Shedding them by slice index could drop an in-flight read's result or frames past the reader; the follow-up quest plans the bounded version. Co-Authored-By: Claude Opus 5.5 --- quest/m1/live-edge-inflated-taken.md | 20 ++++++++++++++++++++ rs/moq-net/src/model/group.rs | 15 --------------- rs/moq-net/src/model/track.rs | 26 -------------------------- 3 files changed, 20 insertions(+), 41 deletions(-) create mode 100644 quest/m1/live-edge-inflated-taken.md diff --git a/quest/m1/live-edge-inflated-taken.md b/quest/m1/live-edge-inflated-taken.md new file mode 100644 index 00000000000..41466c92f7b --- /dev/null +++ b/quest/m1/live-edge-inflated-taken.md @@ -0,0 +1,20 @@ +# [S] A session's taken-frame shed also drops inflated copies readers took + +## Goal + +When a session is past its `live_edges` budget, the first reclaim pass (`cache::Edges::reclaim`, `GroupState::shed_taken`) sheds the inflated frames a plain reader of a received compressed edge already took, along with their stored slices. That keeps a higher-priority compressed edge's read content from making the whole-edge pass evict a lower-priority reader's owed frames. It must never drop an inflated frame a reader is still owed, and never one an in-flight read has yet to take. + +## Plan + +Today `shed_taken` sheds only stored slices. The plain copy's inflated frames keep billing the session until the whole-edge pass or `MAX_CACHE_BYTES` trims them. + +A first attempt, in [moq-dev/moq#9439](https://github.com/moq-dev/moq/pull/9439)'s review, popped plain frames below the shed slice index. Codex found two flaws in it: + +- `Prefetch::fill` advances pace before `Prefetch::inflate` takes the job's result, and `Inflate::run` settles the bill in between. So a reclaim can drop the active read's inflated frames as taken, and that reader gets `Evicted`. +- A long compressed group trims its slices while keeping their inflated frames for a plain reader (`a_long_compressed_group_sheds_its_front`). Bounding by the slice front sheds frames past `read`. + +Recommended: bound by each inflated entry's own `end`, which `Inflate` copies from its slice (`entry.end <= read`). Also pin the frames of inflate jobs in flight in `PlainState`, for example the lowest index a running job keeps, as `Inflate::keep` does for the `MAX_CACHE_BYTES` trim. Test it with mock time: a plain reader mid-prefetch, a session past its budget, and a second compressed edge. + +## Related + +- [Pool pinned debt](/quest/m1/pool-pinned-debt.md) - the pool-side bound on live edges diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index f92063ad449..2e8d723a469 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -687,17 +687,6 @@ impl Plain { freed } - /// Shed the inflated frames before group frame `end`, which a reader took. - fn shed_before(&self, end: usize) { - let mut state = self.lock(); - while state.base < end && !state.frames.is_empty() { - self.pop(&mut state); - } - if state.frames.is_empty() { - state.frames = VecDeque::new(); - } - } - /// Whether inflating failed on the group's content, rather than its release. fn malformed(&self) -> bool { let state = self.lock(); @@ -1147,10 +1136,6 @@ impl GroupState { end += 1; } self.shed_to(end); - // A plain read takes the same frames on the same scale, so their inflated copies go too. - if let Some(flate) = &self.flate { - flate.plain.shed_before(end); - } } /// Whether a frame still arriving bills the session: its payload or its header's fields. diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index ecd41e9c4fe..f7215420b49 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -26038,32 +26038,6 @@ mod test { drop(group); } - /// The frames a plain reader took of a received compressed edge go with their slices: a - /// shed of what readers took leaves no inflated copy billing the session. - #[kio::test] - #[cfg(feature = "async")] - async fn a_shed_of_taken_frames_drops_their_inflated_copies() { - let info = Info::timed().with_compression(Compression::Deflate); - let stored = stored_slices(&info); - let pool = cache::Pool::unbounded(); - let broadcast = session_broadcast(&pool, Some(1 << 30)); - let producer = Producer::new(broadcast.clone(), "test", info); - let mut group = producer.create_group(group::Info { start: 0 }).unwrap(); - for object in &stored { - group = ingest_slice(group, object); - } - let mut reader = producer.consume().peek_group(0).expect("cached"); - for _ in 0..stored.len() { - assert!(reader.read_frame().await.unwrap().is_some()); - } - assert!(broadcast.edges.used() > 1024); - - let moves = producer.state.read().cache.moves(); - producer.state.write().ok().expect("open").shed_edge_taken(moves); - assert!(broadcast.edges.used() < 1024, "{:?}", broadcast.edges); - drop((reader, group)); - } - /// The stored slices a publisher of a compressed group would send. #[cfg(feature = "async")] fn stored_slices(info: &Info) -> arrayvec::ArrayVec { From 0cf4be488183e6df2db6a82ca7c45add991f808f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 22 Nov 2026 17:57:56 -0800 Subject: [PATCH 07/16] fix(net): rank live edges without the async-only priority module Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/cache.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 06cfbca5c04..87d21efd5e1 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -673,10 +673,11 @@ const EDGE_SLACK: usize = 64; /// track keeps whatever the pool's budget, so a publisher holding many quiet tracks would /// otherwise hold one group each past any capacity. A frame write that leaves the session /// past its limit sheds its live edges in the order delivery would give up on them: the -/// lowest priority first, as [`crate::priority::Priority`] ranks a track, and among equals -/// the edge that moved longest ago, so the cost stays with the session causing it. Each edge -/// first sheds the frames its readers took, then everything; the one being written keeps -/// its newest frame. The default is unbounded and costs nothing. +/// lowest priority first, as delivery ranks a track (its subscriber's priority, then its +/// publisher's), and among equals the edge that moved longest ago, so the cost stays with +/// the session causing it. Each edge first sheds the frames its readers took, then +/// everything; the one being written keeps its newest frame. The default is unbounded and +/// costs nothing. #[derive(Clone, Default)] pub(crate) struct Edges(Option>); @@ -1147,13 +1148,11 @@ impl Track { } } - /// The track's rank among its session's live edges, as [`crate::priority::group`] ranks - /// its subscription for delivery: higher pays later. + /// The track's rank among its session's live edges, packed as delivery ranks its + /// subscription (the subscriber's priority always dominates the publisher's): higher + /// pays later. fn rank(&self) -> i64 { - crate::priority::group( - self.subscriber.load(Ordering::Relaxed), - self.publisher.load(Ordering::Relaxed), - ) + i64::from(self.subscriber.load(Ordering::Relaxed)) * 256 + i64::from(self.publisher.load(Ordering::Relaxed)) } /// Whether the live edge still sits at `key` after its `moves`th move. From 60611f35193e2497d3743222b9fd404141d089e9 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 00:54:10 -0800 Subject: [PATCH 08/16] fix(net): the taken-frame shed keeps a copy no reader has opened yet A copy no group::Consumer holds is not a copy whose frames were all read: a new group often has none until the downstream publisher picks it up. Pass 1 now sheds only frames at or below the fastest reader's pace, so such a copy waits for the whole-edge pass and the writer keeps its newest frame. The lone-edge test asserts that after every write. Also reflows the quic_sim bulk doc and drops a link to the finished pool-pinned-debt quest. Co-Authored-By: Claude Opus 5.5 --- quest/m1/live-edge-inflated-taken.md | 4 ---- rs/moq-net/src/model/group.rs | 9 +++------ rs/moq-net/src/model/track.rs | 7 ++++--- rs/moq-relay/tests/integration/quic_sim.rs | 5 +++-- 4 files changed, 10 insertions(+), 15 deletions(-) diff --git a/quest/m1/live-edge-inflated-taken.md b/quest/m1/live-edge-inflated-taken.md index 41466c92f7b..01477eec351 100644 --- a/quest/m1/live-edge-inflated-taken.md +++ b/quest/m1/live-edge-inflated-taken.md @@ -14,7 +14,3 @@ A first attempt, in [moq-dev/moq#9439](https://github.com/moq-dev/moq/pull/9439) - A long compressed group trims its slices while keeping their inflated frames for a plain reader (`a_long_compressed_group_sheds_its_front`). Bounding by the slice front sheds frames past `read`. Recommended: bound by each inflated entry's own `end`, which `Inflate` copies from its slice (`entry.end <= read`). Also pin the frames of inflate jobs in flight in `PlainState`, for example the lowest index a running job keeps, as `Inflate::keep` does for the `MAX_CACHE_BYTES` trim. Test it with mock time: a plain reader mid-prefetch, a session past its budget, and a second compressed edge. - -## Related - -- [Pool pinned debt](/quest/m1/pool-pinned-debt.md) - the pool-side bound on live edges diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 1637ea3a2a8..d3e6fac4e32 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -2905,16 +2905,13 @@ impl Handle { } } - /// Shed the frames this copy's fastest reader took, see [`GroupState::shed_taken`], or - /// every committed frame while no reader holds the copy, which no reader is owed. + /// Shed the frames this copy's fastest reader took, see [`GroupState::shed_taken`]. A copy + /// no reader holds keeps the rest: one not yet handed out is still owed downstream. pub(super) fn shed_taken(&self) { let Ok(mut state) = self.state.write() else { return; }; - match self.state.wanted() { - true => state.shed_taken(self.alive.pace.read()), - false => state.shed_all(), - } + state.shed_taken(self.alive.pace.read()); } pub(super) fn delivery_size(&self) -> u64 { diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index ed2cf60bb13..83cdbe09774 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -27997,14 +27997,15 @@ mod test { let broadcast = session_broadcast(&pool, Some(25_000)); let producer = Producer::new(broadcast.clone(), "test", Info::timed()); let mut group = producer.append_next().unwrap(); + // No reader holds the group yet, so none took a frame: each shed still keeps the newest. for _ in 0..5 { group .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; 10_000])) .unwrap(); + let held = broadcast.edges.used(); + assert!(held <= 25_000, "the open edge holds {held}"); + assert!(held >= 10_000, "the newest frame went too: {held}"); } - let held = broadcast.edges.used(); - assert!(held <= 25_000, "the open edge holds {held}"); - assert!(held >= 10_000, "the newest frame went too: {held}"); // Demoting the edge stops billing the session. let mut next = producer.append_next().unwrap(); diff --git a/rs/moq-relay/tests/integration/quic_sim.rs b/rs/moq-relay/tests/integration/quic_sim.rs index 8068c6ac417..3809c5b2458 100644 --- a/rs/moq-relay/tests/integration/quic_sim.rs +++ b/rs/moq-relay/tests/integration/quic_sim.rs @@ -335,8 +335,9 @@ const LOSSLESS: usize = 12; /// Write `tracks` tracks of one group each, [`BULK`] bytes in `chunk`-byte frames, through /// one relay, and read the first `read` bytes of each slower than they are written. Track `i` -/// has publisher priority `i - 128`, ordered for up to 256 tracks: the [`LOSSLESS`] highest must arrive whole, and a lower one may -/// end early with an error but never delivers a wrong frame. +/// has publisher priority `i - 128`, ordered for up to 256 tracks: the [`LOSSLESS`] highest +/// must arrive whole, and a lower one may end early with an error but never delivers a wrong +/// frame. async fn bulk(tracks: usize, chunk: usize, read: usize) { let network = Network::new(0); let auth = memory::public(&[""], &[], &[]); From 2241a8f3bc47cb9ce2c481e4048d984096c497ce Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 02:16:07 -0800 Subject: [PATCH 09/16] fix(net): reclaim visits only edges with taken frames, and inflates nothing A session at its live-edge budget reclaimed on every write by walking its edges from the lowest rank, so quiet edges with nothing taken cost a track lock each per write. A reader that takes a frame its copy still holds now lists the track with its session (once, until a reclaim visits it), keyed by its edge's rank and age, and the taken-frame pass pops only those. The new `edges` bench, at 1024 quiet edges: 16.1 us -> 0.28 us per 1 KiB write, 46.2 us -> 0.39 us per 64 KiB write; flat from 1 to 1024. The taken-frame shed of a compressed edge whose plain copy started now stops at that copy's inflated prefix and inflates nothing, where it used to inflate the slices it shed and bill the session more than it freed. Docs: the relay flag help and cache overview describe the priority order, the guides note the inflated-copy exception, and the nightly recipe says only the highest-priority transfers must be lossless. Co-Authored-By: Claude Opus 5.5 --- doc/bin/relay/config.md | 3 +- doc/lib/rs/moq-net.md | 2 +- rs/justfile | 2 +- rs/moq-net/Cargo.toml | 7 +- rs/moq-net/benches/edges.rs | 38 ++++++++ rs/moq-net/src/fuzz.rs | 15 ++++ rs/moq-net/src/model/cache.rs | 165 +++++++++++++++++++++++++--------- rs/moq-net/src/model/group.rs | 18 +++- rs/moq-net/src/model/pace.rs | 17 +++- rs/moq-net/src/model/track.rs | 132 ++++++++++++++++++++++++++- rs/moq-net/src/session.rs | 6 +- rs/moq-relay/src/limits.rs | 5 +- 12 files changed, 356 insertions(+), 54 deletions(-) create mode 100644 rs/moq-net/benches/edges.rs diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md index 7f7897ec2c3..00e8cbccdaf 100644 --- a/doc/bin/relay/config.md +++ b/doc/bin/relay/config.md @@ -214,7 +214,8 @@ publisher holding many quiet tracks would otherwise hold one group each past any budget. Past the bound, the session's own live edges are shed in delivery's priority order: the lowest-priority track first, and among equals the edge that moved longest ago. Frames viewers already read go before any frame a viewer is -still owed. A viewer reaching a shed frame +still owed, except a compressed track's decoded copies, which go with their +whole edge. A viewer reaching a shed frame meets it as it would any frame the cache dropped; the group's place on the timeline stays, so live joins land where they did. Another session's edges are never touched. Here zero means no bound. diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index 9b51fd5fe16..e1876b40d3c 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -30,7 +30,7 @@ What you use it for, beyond what the concept page already describes: - **Use the model without a runtime.** By default `moq-net` is its `poll_*` APIs and origin driver with caller-supplied time. The `async` feature adds their async wrappers, `time::run`, and both wire sessions. - **You drive the session, or `moq-tokio` does.** `connect` and `accept` return a session plus a driver that never reads the clock itself. `moq_net::time::run` polls it on tokio. `moq-tokio` hides that. A custom transport implements `moq_net::transport::poll`, and `moq_net::transport::memory::pair` links two sessions in one process with no sockets, for tests or in-process links. `Server` bounds each accept with one deadline from the connection's arrival (30 s by default, `with_timeout`), across your transport handshake (`Server::deadline`), SETUP, your admission decision (`Handshake::expired`), and moq-lite 01/02's SETUP reply, and opens a receive window the transport held back once you admit (`with_receive_window`). - **Reconnect policy comes with it.** With the `async` feature, `moq_net::Reconnect` decides which of a peer's addresses to dial, how long each dial and handshake may take, when to back off and give up, and how to follow a GOAWAY, without doing I/O: you dial each `Attempt` it asks for and report back. `moq-tokio`'s `Connection` runs it, so a client on another runtime gets the same policy rather than a copy. The first walk of the peer's addresses fails fast: if it yields no session, the policy ends with that walk's error instead of retrying, so a setup mistake such as an untrusted certificate or no version in common surfaces at once, and a client started before its relay is reachable exits for its supervisor to restart. Once a session has been established, later failures back off and retry, so relay restarts still recover. A policy given `reconnect::Dials` (`Client::with_dials` in moq-tokio) asks you for each dial's tokens as it starts, for a credential that must be fresh when presented, and retries from the first failure: each `Dial` carries why the last one ended, and failing it ends the policy. -- **A session bounds what its peer can hold.** Each request holds a stream, so the transport's stream credit bounds subscriptions and FETCHes. Once that credit runs out, a waiting open resets the lowest-priority group stream below it, which the subscriber sees dropped, so the credit it frees goes to the higher-priority group. `session::Limits` (via `Client::with_limits` and `Server::with_limits`) bounds the announcements per session. The default suits a relay mesh, so lower it for untrusted peers. Past it, the session closes with `TOO_MANY_REQUESTS`. Its `live_edges` bounds the bytes held by the newest group of every track the peer publishes, which the cache otherwise keeps past any capacity: past it, the session sheds its own live edges in delivery's priority order, the lowest-priority track and then the oldest edge first, shedding the frames readers took before any a reader is owed. It is unbounded by default. Peer-declared lengths are capped before they are buffered. +- **A session bounds what its peer can hold.** Each request holds a stream, so the transport's stream credit bounds subscriptions and FETCHes. Once that credit runs out, a waiting open resets the lowest-priority group stream below it, which the subscriber sees dropped, so the credit it frees goes to the higher-priority group. `session::Limits` (via `Client::with_limits` and `Server::with_limits`) bounds the announcements per session. The default suits a relay mesh, so lower it for untrusted peers. Past it, the session closes with `TOO_MANY_REQUESTS`. Its `live_edges` bounds the bytes held by the newest group of every track the peer publishes, which the cache otherwise keeps past any capacity: past it, the session sheds its own live edges in delivery's priority order, the lowest-priority track and then the oldest edge first, shedding the frames readers took before any a reader is owed, except a compressed track's inflated copies. It is unbounded by default. Peer-declared lengths are capped before they are buffered. - **Authorization is in band.** On moq-lite 07 (`moq-lite-07-wip`, opt-in), `session.auth()` presents tokens without reconnecting and watches the grant the peer sent back. `add(token)` presents another and returns its `Credential` at once, and `credential.answered().await` waits for the peer to take it: on its AUTH stream, or at once on moq-transport without AUTH, where only a request that names it carries it. Dropping its last clone, including any a route holds, withdraws it, answered or not. A handle passed to `Client::with_auth` outlives each session, so its tokens, and the routes naming them, carry across your own reconnects. A server verifies tokens itself by taking `handshake.requests()` before `ok()`. `authorize(&grant)` narrows or widens a live session on any version: what falls outside resets with `Unauthorized` and the session stays up. A client that publishes outside its grant closes the session, naming the path. - **A graceful close waits.** `session.close().await` withdraws announcements and drains for up to one second. `moq-lite-05` and newer wait for the subscriber to receive finished tails; older Lite versions and IETF wait only for transport ACKs. `abort` ends immediately. diff --git a/rs/justfile b/rs/justfile index a822ee0cf04..23ea2096123 100644 --- a/rs/justfile +++ b/rs/justfile @@ -409,7 +409,7 @@ quic-sim: # Forward delay against RTT as a queue-growth signal: deterministic in the simulation, then over real sockets through each cellular moq-shaper preset, one at a time so they do not add to each other's noise. bash sh/rs/nextest.sh cargo nextest run --locked --release -p moq-quic --lib --run-ignored only --no-capture -E 'test(/^tests::receive_ts::/)' bash sh/rs/nextest.sh cargo nextest run --locked --release -p moq-tokio --test integration --run-ignored only --no-capture --test-threads 1 -E 'test(/^receive_ts::/)' - # A hundred bulk transfers on one relay connection all pause losslessly, where the merge gate runs twelve. + # A hundred bulk transfers on one relay connection, past its live-edge budget: the highest-priority ones arrive losslessly. The merge gate runs twelve. bash sh/rs/nextest.sh cargo nextest run --locked --release -p moq-relay --features test-support --test integration --run-ignored only -E 'test(/^quic_sim::many_/)' # Each realtime congestion controller against BBR3 over sim replicas of the cellular presets: queueing delay, throughput, reaction to the drop, and share beside CUBIC. bash sh/rs/nextest.sh cargo nextest run --locked --release -p moq-quic --lib --run-ignored only --no-capture -E 'test(/^tests::realtime::/)' diff --git a/rs/moq-net/Cargo.toml b/rs/moq-net/Cargo.toml index 9c851a7d0d5..37173917318 100644 --- a/rs/moq-net/Cargo.toml +++ b/rs/moq-net/Cargo.toml @@ -22,7 +22,7 @@ default = [] # methods and explicit-time model drivers stay available without it. async = ["dep:futures", "kio/async", "kio/runtime"] -# Exposes the wire codecs to the `fuzz/` harness and the announce, codec, path, varint, frame, and canonical storage benches, +# Exposes the wire codecs to the `fuzz/` harness and the announce, codec, path, varint, frame, canonical storage, and live-edge benches, # session views of an origin to the viewers bench, the lite publisher's run loop to the # publisher bench, and a lite-07 publisher's frame bounds to the ranges bench, through the # `fuzz` module. Its session targets run on kio's simulated clock. Off by default. @@ -248,5 +248,10 @@ name = "canonical" harness = false required-features = ["fuzz"] +[[bench]] +name = "edges" +harness = false +required-features = ["fuzz"] + [lints] workspace = true diff --git a/rs/moq-net/benches/edges.rs b/rs/moq-net/benches/edges.rs new file mode 100644 index 00000000000..7e0cc3c190c --- /dev/null +++ b/rs/moq-net/benches/edges.rs @@ -0,0 +1,38 @@ +//! A frame write on a session at its live-edge budget, which reclaims on every write. +//! +//! `reclaim` holds `quiet` edges that moved first, each with a frame nobody read, and writes +//! frames to one more edge whose reader takes each as it lands, so the frames to shed are +//! that edge's alone. A reclaim that looks at every edge shows a slope over the quiet edges; +//! the frame size sets how many bytes each write pushes past the budget. +//! +//! Run with `cargo bench -p moq-net --features fuzz --bench edges`. + +use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use moq_net::fuzz::LiveEdges; +use std::time::Duration; + +/// Edges holding a frame nobody read, ranked to pay before the written one. +const QUIET: [usize; 3] = [1, 32, 1024]; + +/// Bytes per frame written. +const FRAME: [usize; 2] = [1024, 64 * 1024]; + +fn reclaim(c: &mut Criterion) { + let mut group = c.benchmark_group("reclaim"); + group.sample_size(20); + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_secs(2)); + group.throughput(Throughput::Elements(1)); + for quiet in QUIET { + for frame in FRAME { + let mut edges = LiveEdges::new(quiet, frame); + group.bench_function(BenchmarkId::new(format!("{frame}B"), quiet), |b| { + b.iter(|| edges.write()) + }); + } + } + group.finish(); +} + +criterion_group!(benches, reclaim); +criterion_main!(benches); diff --git a/rs/moq-net/src/fuzz.rs b/rs/moq-net/src/fuzz.rs index 1f76f213d57..26b90fc36d2 100644 --- a/rs/moq-net/src/fuzz.rs +++ b/rs/moq-net/src/fuzz.rs @@ -230,6 +230,21 @@ impl CanonicalStorage { } } +/// A session at its live-edge budget whose every write reclaims, for the edges bench. +pub struct LiveEdges(crate::model::track::EdgesBench); + +impl LiveEdges { + /// `quiet` edges holding a `frame`-byte frame nobody read, and one written edge. + pub fn new(quiet: usize, frame: usize) -> Self { + Self(crate::model::track::EdgesBench::new(quiet, frame)) + } + + /// Write a `frame`-byte frame to the written edge and read it. + pub fn write(&mut self) { + self.0.write() + } +} + /// Every target, keyed by the name of its `fuzz_targets/.rs` shim. pub const TARGETS: &[(&str, Target)] = &[ ("lite", lite_wire), diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 53a5f10b9a6..fd9066e8538 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -36,7 +36,7 @@ //! The pool never evicts a live track's latest group, so a session's live-edge budget //! (`session::Limits::live_edges`) bounds what those hold in bytes: every track a session //! ingests bills its live edge there, and a session past its budget pays with its own -//! oldest live edges, never another session's. +//! live edges in delivery's priority order, never another session's. //! //! A bare pool is inert by default ([`Pool::unbounded`]): publishers and subscribers //! that never set a capacity or expiry pay only a couple of atomic counters, and @@ -781,8 +781,17 @@ struct EdgesInner { moves: AtomicU64, // The tracks billing here, so the order knows how many of its entries can be current. tracks: AtomicUsize, + // The tracks whose readers took a frame their groups still hold, in the order their edges + // pay, each listed once until a reclaim visits it: what a reclaim's first pass sheds, + // without looking at an edge that has nothing taken. A track's entry moves with its + // rank and age, under this lock. + taken: Mutex>>, } +/// A track's place among its session's edges with taken frames: its [`EdgeKey`], then its +/// account's address, which keeps two tracks at one key apart. +type TakenKey = (EdgeKey, usize); + impl Edges { /// A budget of `limit` bytes, or unbounded for `None`. pub(crate) fn new(limit: Option) -> Self { @@ -793,12 +802,13 @@ impl Edges { order: Mutex::default(), moves: AtomicU64::new(0), tracks: AtomicUsize::new(0), + taken: Mutex::default(), }) })) } /// Bytes the session's live edges bill now. - #[cfg(test)] + #[cfg(any(test, feature = "fuzz"))] pub(super) fn used(&self) -> u64 { self.0 .as_ref() @@ -825,47 +835,82 @@ impl Edges { } /// Pay the session's excess with its live edges in order, lowest rank and oldest first, - /// in two passes. The first sheds the frames each edge's readers took, which no reader is - /// owed. Only once none is left does the second shed every frame of an edge (aborting a - /// copy still receiving one), which then leaves the order until it grows again. `writer`'s - /// edge, being written, instead sheds its older frames in its turn and stays queued. + /// in two passes. The first sheds the frames readers took, which no reader is owed, + /// visiting only the edges a reader took one of since a reclaim last visited them. Only + /// once none is left does the second shed every frame of an edge (aborting a copy still + /// receiving one), which then leaves the order until it grows again. `writer`'s edge, + /// being written, instead sheds its older frames in its turn and stays queued. /// Takes track locks: call with none held. fn reclaim(&self, writer: &Track) { let Some(inner) = &self.0 else { return; }; - for whole in [false, true] { - // The writer pays in its turn, or after every queued edge when it has no entry. - let mut paid = false; - // Each step resumes after the last key, so an entry is visited once per pass. - let mut after = None; - while self.excess().is_some() - && let Some((key, track, moves)) = self.next(after) - { - after = Some(key); - if std::ptr::eq(Arc::as_ptr(&track), writer) { - paid = true; - writer.shed_own(self, whole); - continue; - } - let Some(state) = track.state.upgrade() else { - continue; + while self.excess().is_some() { + let track = { + let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner); + let Some((_, track)) = taken.pop_first() else { + break; }; - let Ok(mut state) = state.write() else { + let Some(track) = track.upgrade() else { continue; }; - if !whole { - state.shed_edge_taken(moves); - continue; - } - // Unqueued before the shed, so whatever the edge bills after it queues it again. - inner.order.lock().unwrap_or_else(PoisonError::into_inner).remove(&key); - track.queued.store(false, Ordering::Relaxed); - state.shed_edge_all(moves); + *track.listed.lock().unwrap_or_else(PoisonError::into_inner) = None; + track + }; + track.shed_taken(); + } + // The writer pays in its turn, or after every queued edge when it has no entry. + let mut paid = false; + // Each step resumes after the last key, so an entry is visited once. + let mut after = None; + while self.excess().is_some() + && let Some((key, track, moves)) = self.next(after) + { + after = Some(key); + if std::ptr::eq(Arc::as_ptr(&track), writer) { + paid = true; + writer.shed_own(self); + continue; } - if !paid { - writer.shed_own(self, whole); + let Some(state) = track.state.upgrade() else { + continue; + }; + let Ok(mut state) = state.write() else { + continue; + }; + // Unqueued before the shed, so whatever the edge bills after it queues it again. + inner.order.lock().unwrap_or_else(PoisonError::into_inner).remove(&key); + track.queued.store(false, Ordering::Relaxed); + state.shed_edge_all(moves); + } + if !paid { + writer.shed_own(self); + } + } + + /// List `track` as having taken frames to shed, or with `again`, move its entry to its + /// current rank and age if it has one. Drops the entries of tracks gone since once they + /// clearly outnumber the live ones, as [`Self::queue`] does. + fn list(&self, track: &Arc, again: bool) { + let Some(inner) = &self.0 else { + return; + }; + let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner); + let mut listed = track.listed.lock().unwrap_or_else(PoisonError::into_inner); + let at = Arc::as_ptr(track) as usize; + match (*listed, again) { + (Some(key), true) => { + taken.remove(&(key, at)); } + (None, false) => {} + _ => return, + } + let key = (track.rank(), track.seq.load(Ordering::Relaxed)); + taken.insert((key, at), Arc::downgrade(track)); + *listed = Some(key); + drop(listed); + if taken.len() > 2 * inner.tracks.load(Ordering::Relaxed) + EDGE_SLACK { + taken.retain(|_, track| track.strong_count() > 0); } } @@ -906,6 +951,11 @@ impl Edges { if order.len() > 2 * inner.tracks.load(Ordering::Relaxed) + EDGE_SLACK { order.retain(|key, (track, moves)| track.upgrade().is_some_and(|track| track.queued_at(*key, *moves))); } + drop(order); + // A listed edge with taken frames moves with it, so they pay in its new turn. + if track.taken.load(Ordering::SeqCst) { + self.list(track, true); + } } /// Move `track`'s live edge to a newer group, queued as the session's newest. @@ -1015,6 +1065,12 @@ pub(super) struct Track { // Whether the live edge has an entry in its session's order, so one that a reclaim shed // queues again once it grows. queued: AtomicBool, + // Whether a reader took a frame this track's groups still hold since a reclaim last + // visited it, so a reader lists the track once. + taken: AtomicBool, + // Where the session lists this track among its edges with taken frames, if it does. + // Changed only under that list's lock. + listed: Mutex>, // One finished local group's encoder, kept until another group needs it or the // account drops. Raw codec only: an Extra here would keep this account alive. @@ -1159,6 +1215,8 @@ impl Track { subscriber: AtomicI8::new(i8::MIN), publisher: AtomicI8::new(0), queued: AtomicBool::new(false), + taken: AtomicBool::new(false), + listed: Mutex::default(), written: AtomicU64::new(0), next_expiry: AtomicU64::new(0), expiry_cursor: AtomicUsize::new(0), @@ -1238,10 +1296,9 @@ impl Track { self.edge_is(moves) && self.rank() == key.0 } - /// Pay the session's excess with this track's own live edge, being written: the frames - /// its readers took, or with `whole`, its older frames, keeping the newest of an open - /// group. - fn shed_own(&self, edges: &Edges, whole: bool) { + /// Pay the session's excess with this track's own live edge, being written: its older + /// frames, keeping the newest of an open group. + fn shed_own(&self, edges: &Edges) { let Some(excess) = edges.excess() else { return; }; @@ -1251,12 +1308,40 @@ impl Track { let Ok(mut state) = state.write() else { return; }; - match whole { - false => state.shed_edge_taken(self.moves.load(Ordering::Relaxed)), - true => state.shed_edge(excess), + state.shed_edge(excess); + } + + /// A reader took a frame one of this track's groups still holds: list the track with its + /// session, once until a reclaim visits it. Called by [`super::pace::Pace`] only while + /// the session has a live-edge budget. + pub(super) fn took(self: &Arc) { + // SeqCst pairs with the fence in `shed_taken`: either this sees the track unlisted, + // or that shed sees the reader's progress. + if !self.taken.load(Ordering::SeqCst) && !self.taken.swap(true, Ordering::SeqCst) { + self.edges.list(self, false); } } + /// Shed the frames readers took of this track's live edge, unlisting it first, so a frame + /// a reader takes during the shed lists it again. + fn shed_taken(&self) { + self.taken.store(false, Ordering::SeqCst); + std::sync::atomic::fence(Ordering::SeqCst); + let Some(state) = self.state.upgrade() else { + return; + }; + let Ok(mut state) = state.write() else { + return; + }; + state.shed_edge_taken(self.moves.load(Ordering::Relaxed)); + } + + /// Whether this track's session bounds its live edges, so its readers' progress matters + /// to a reclaim. + pub(super) fn bounded(&self) -> bool { + self.edges.0.is_some() + } + /// How many times the live edge moved. #[cfg(all(test, feature = "async"))] pub(super) fn moves(&self) -> u64 { diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index d3e6fac4e32..4c094968104 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -1160,19 +1160,28 @@ impl GroupState { /// Shed the front frames the fastest reader took, those ending at or below `read` on the /// pace scale: a reader on the group loses nothing it has yet to take, though a slower one /// falls off as after any shed. Frames adopted from a head are off that scale, so the shed - /// stops at them. + /// stops at them. So does a started plain copy's inflated prefix: inflating slices to shed + /// them would bill the session more than it frees. fn shed_taken(&mut self, read: u64) { if self.outcome.error().is_some() { return; } + let inflated = match &self.flate { + Some(flate) => match flate.plain.len.load(Ordering::Acquire) { + 0 => usize::MAX, + len => len, + }, + None => usize::MAX, + }; let mut end = self.held(); - while let Some(entry) = self.entry(end) + while end < inflated + && let Some(entry) = self.entry(end) && entry.end != 0 && entry.end <= read { end += 1; } - self.shed_to(end); + self.shed_frames(end, false); } /// Whether a frame still arriving bills the session: its payload or its header's fields. @@ -1844,6 +1853,9 @@ impl Producer { ))); } state.charge = charge; + if cache.bounded() { + state.pace.report(cache.clone()); + } (state.log.reader(), state.pace.clone()) }; let alive = Arc::new(Alive { diff --git a/rs/moq-net/src/model/pace.rs b/rs/moq-net/src/model/pace.rs index 0fe9e244b31..8531361a0f4 100644 --- a/rs/moq-net/src/model/pace.rs +++ b/rs/moq-net/src/model/pace.rs @@ -18,11 +18,12 @@ //! waiting on the writer. use std::sync::{ - Mutex, PoisonError, + Arc, Mutex, OnceLock, PoisonError, atomic::{AtomicBool, AtomicU64, Ordering}, }; use std::task::Waker; +use super::cache; use super::group::MAX_CACHE_BYTES; #[cfg(any(test, feature = "async"))] use crate::transport::ReceiveWindow; @@ -58,6 +59,9 @@ pub(super) struct Pace { parked: AtomicBool, // The writer's waker: a group has one writer, so one slot, far smaller than a list. writer: Mutex>, + // The track told when the fastest reader takes a frame the copy still holds, set only + // while its session has a live-edge budget to shed those frames toward. + edge: OnceLock>, } impl Pace { @@ -70,6 +74,17 @@ impl Pace { // SeqCst pairs with `park`: either this sees the writer parked, or it sees the read. self.read.fetch_max(end, Ordering::SeqCst); self.wake(); + if let Some(track) = self.edge.get() + && end > self.front.load(Ordering::SeqCst) + { + track.took(); + } + } + + /// Tell `track` whenever the fastest reader takes a frame this copy still holds, so its + /// session, past its live-edge budget, visits only the edges with taken frames to shed. + pub fn report(&self, track: Arc) { + let _ = self.edge.set(track); } /// Wake the writer, if parked, since what it waits on changed. diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 83cdbe09774..913f3c3a382 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -382,7 +382,7 @@ impl Info { } } -#[cfg(test)] +#[cfg(any(test, feature = "fuzz"))] impl Info { /// A millisecond track with no publisher max age, for tests that write timestamps: a test /// of staleness sets its max age explicitly. @@ -6816,6 +6816,90 @@ impl Routed { } } +/// A session at its live-edge budget, for benches: `quiet` edges that moved first, each +/// holding one frame nobody read, and one edge written a frame at a time, which a reader +/// takes as it lands. Each write past the budget reclaims. +#[cfg(feature = "fuzz")] +pub(crate) struct EdgesBench { + _quiet: Vec<(Producer, group::Producer)>, + written: Producer, + group: group::Producer, + reader: group::Consumer, + frame: bytes::Bytes, + frames: usize, +} + +#[cfg(feature = "fuzz")] +impl EdgesBench { + /// Frames the written edge takes before it moves to a new group. + const GROUP: usize = 1024; + + /// `quiet` quiet edges of a `frame`-byte frame each, and a written edge of `frame`-byte + /// frames, with room past the quiet edges for a new group's first frame, two more, and + /// the two log segments of slots a shed may leave billed, so only the written edge sheds. + pub(crate) fn new(quiet: usize, frame: usize) -> Self { + let frame = bytes::Bytes::from(vec![0u8; frame]); + // What an edge of one frame bills, measured on a session that never sheds. + let probe = Self::session(Some(u64::MAX)); + let (_edge, edge) = (Self::quiet(&probe, "probe", &frame), probe.edges.used()); + let slots = 2 * kio::log::Writer::::SEGMENT_HEAP as u64; + let room = edge + 2 * frame.len() as u64 + slots; + let broadcast = Self::session(Some(edge * quiet as u64 + room)); + let quiet = (0..quiet) + .map(|i| Self::quiet(&broadcast, &format!("quiet{i}"), &frame)) + .collect(); + let written = Producer::new(broadcast, "written", Info::timed()); + let (group, reader) = Self::open(&written); + Self { + _quiet: quiet, + written, + group, + reader, + frame, + frames: 0, + } + } + + fn session(limit: Option) -> Arc { + Arc::new(broadcast::Info { + edges: cache::Edges::new(limit), + ..Default::default() + }) + } + + fn quiet(broadcast: &Arc, name: &str, frame: &bytes::Bytes) -> (Producer, group::Producer) { + let producer = Producer::new(broadcast.clone(), name, Info::timed()); + let mut group = producer.append_next().expect("open"); + group.write_frame(Self::time(&group), frame.clone()).expect("open"); + (producer, group) + } + + /// Where `group` starts on a millisecond track, so groups start in key order. + fn time(group: &group::Producer) -> Timestamp { + Timestamp::from_millis(group.start).expect("a bench key fits a timestamp") + } + + fn open(written: &Producer) -> (group::Producer, group::Consumer) { + let group = written.append_next().expect("open"); + let reader = written.consume().peek_group(group.start).expect("cached"); + (group, reader) + } + + /// Write one frame to the written edge and read it, moving to a new group every + /// [`Self::GROUP`] frames. + pub(crate) fn write(&mut self) { + if self.frames == Self::GROUP { + (self.group, self.reader) = Self::open(&self.written); + self.frames = 0; + } + self.frames += 1; + let time = Self::time(&self.group); + self.group.write_frame(time, self.frame.clone()).expect("open"); + let read = self.reader.poll_read_frame(&kio::Waiter::noop()); + assert!(matches!(read, Poll::Ready(Ok(Some(_)))), "{read:?}"); + } +} + /// Aborts a track without keeping it open, from [`Producer::abort_handle`]. /// /// Holding one neither keeps the track alive nor counts as its producer, so a track whose @@ -27753,6 +27837,52 @@ mod test { drop(group); } + /// The taken-frame shed of a received compressed edge inflates nothing: a raw reader past + /// a plain reader's decoded prefix sheds only the slices that prefix already used, so the + /// session's bill never grows and the plain reader keeps decoding. + #[kio::test] + #[cfg(feature = "async")] + async fn a_taken_shed_leaves_slices_the_plain_copy_needs() { + let info = Info::timed().with_compression(Compression::Deflate); + let stored = stored_slices(&info); + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(1 << 30)); + let producer = Producer::new(broadcast.clone(), "test", info); + let mut group = producer.create_group(group::Info { start: 0 }).unwrap(); + // A plain reader decodes the first slices, then a raw one takes every slice. + for object in &stored[..2] { + group = ingest_slice(group, object); + } + let mut plain = producer.consume().peek_group(0).expect("cached"); + assert!(plain.read_frame().await.unwrap().is_some()); + for object in &stored[2..] { + group = ingest_slice(group, object); + } + let mut raw = arrayvec::ArrayVec::::new(); + assert!(matches!( + producer + .consume() + .peek_group(0) + .expect("cached") + .compressed() + .poll_read_objects(&kio::Waiter::noop(), &mut raw), + Poll::Ready(Ok(4)) + )); + + let before = broadcast.edges.used(); + let moves = producer.state.read().cache.moves(); + producer.state.write().ok().expect("open").shed_edge_taken(moves); + let after = broadcast.edges.used(); + assert!(after <= before, "the shed billed more: {before} -> {after}"); + for _ in 1..4 { + assert!( + plain.read_frame().await.unwrap().is_some(), + "a slice the plain copy needed went" + ); + } + drop(group); + } + /// The stored slices a publisher of a compressed group would send. #[cfg(feature = "async")] fn stored_slices(info: &Info) -> arrayvec::ArrayVec { diff --git a/rs/moq-net/src/session.rs b/rs/moq-net/src/session.rs index eec912c7bb0..9604c213f70 100644 --- a/rs/moq-net/src/session.rs +++ b/rs/moq-net/src/session.rs @@ -1193,9 +1193,9 @@ pub struct Limits { /// The cache never evicts a live track's newest group, so a peer holding many quiet /// tracks would otherwise hold one group each past any cache capacity. Past this, the /// session sheds its own live edges in delivery's priority order, the lowest-priority - /// track and then the edge that moved longest ago first: the frames readers took, then - /// whole edges, of which the one being written keeps its newest frame. `None` leaves - /// them unbounded. + /// track and then the edge that moved longest ago first: the frames readers took (a + /// compressed track's inflated copies aside), then whole edges, of which the one being + /// written keeps its newest frame. `None` leaves them unbounded. pub live_edges: Option, } diff --git a/rs/moq-relay/src/limits.rs b/rs/moq-relay/src/limits.rs index 92ca51543f3..de11491ae21 100644 --- a/rs/moq-relay/src/limits.rs +++ b/rs/moq-relay/src/limits.rs @@ -33,8 +33,9 @@ pub struct Client { /// bound. /// /// The cache keeps each live track's newest group past its capacity, so this is what - /// bounds a client holding many quiet tracks. Past it, the frames of the client's own - /// live edges are shed, the one that moved longest ago first, never another session's. + /// bounds a client holding many quiet tracks. Past it, the client's own live edges are + /// shed in delivery's priority order, the frames viewers read before any a viewer is + /// owed, never another session's. #[usage( long = "limits-client-live-edges", env = "MOQ_LIMITS_CLIENT_LIVE_EDGES", From 1df64861449819bad231e2d1a8cb6c697c9b1961 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 03:22:39 -0800 Subject: [PATCH 10/16] fix(net): serialize reclaims, list only live-edge reads, relist after decoding A reclaim now holds its session's lock, so one that finds no taken frame listed never sheds a whole edge while another is still shedding the candidate it popped. Only a copy on the live edge reports its reads (a `cache::Report` checks its footprint's edge bit), and an edge move drops the track's listing. An inflate job relists its track when its decoding leaves taken slices a capped shed kept, so they pay before owed frames. Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/cache.rs | 69 ++++++++++++++++++++++++++++++----- rs/moq-net/src/model/group.rs | 11 ++++-- rs/moq-net/src/model/pace.rs | 33 ++++++++++++----- rs/moq-net/src/model/track.rs | 34 ++++++++++++++++- 4 files changed, 123 insertions(+), 24 deletions(-) diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index fd9066e8538..69c3852817d 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -786,6 +786,9 @@ struct EdgesInner { // without looking at an edge that has nothing taken. A track's entry moves with its // rank and age, under this lock. taken: Mutex>>, + // Held through a reclaim, so one that finds no taken frame listed never sheds a whole + // edge while another is still shedding the taken frames it popped. + reclaiming: Mutex<()>, } /// A track's place among its session's edges with taken frames: its [`EdgeKey`], then its @@ -803,6 +806,7 @@ impl Edges { moves: AtomicU64::new(0), tracks: AtomicUsize::new(0), taken: Mutex::default(), + reclaiming: Mutex::default(), }) })) } @@ -845,6 +849,7 @@ impl Edges { let Some(inner) = &self.0 else { return; }; + let _reclaiming = inner.reclaiming.lock().unwrap_or_else(PoisonError::into_inner); while self.excess().is_some() { let track = { let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner); @@ -972,8 +977,24 @@ impl Edges { .store(inner.moves.fetch_add(1, Ordering::Relaxed), Ordering::Relaxed); track.moves.fetch_add(1, Ordering::Relaxed); drop(order); + self.unlist(track); self.queue(track); } + + /// Drop `track`'s listing, if it has one: the edge whose readers took frames left it. + fn unlist(&self, track: &Arc) { + let Some(inner) = &self.0 else { + return; + }; + if !track.taken.load(Ordering::SeqCst) { + return; + } + let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(key) = track.listed.lock().unwrap_or_else(PoisonError::into_inner).take() { + taken.remove(&(key, Arc::as_ptr(track) as usize)); + } + track.taken.store(false, Ordering::SeqCst); + } } impl std::fmt::Debug for Edges { @@ -989,6 +1010,22 @@ impl std::fmt::Debug for Edges { } } +/// Tells a group's session when its readers take frames it still holds, while it is the live +/// edge, so a reclaim past the session's budget visits only edges with taken frames. +pub(super) struct Report { + track: Arc, + footprint: Arc, +} + +impl Report { + /// A reader took a frame the group still holds. + pub(super) fn took(&self) { + if self.footprint.edge() { + self.track.took(); + } + } +} + /// Gross bytes a track writes before a frame write settles its eviction debt itself, /// so a track appending frames to open groups (never inserting another group) still /// pays. Coarse: the cost is one track-state lock per threshold crossing. @@ -1311,10 +1348,9 @@ impl Track { state.shed_edge(excess); } - /// A reader took a frame one of this track's groups still holds: list the track with its - /// session, once until a reclaim visits it. Called by [`super::pace::Pace`] only while - /// the session has a live-edge budget. - pub(super) fn took(self: &Arc) { + /// A reader took a frame the live edge still holds: list the track with its session, once + /// until a reclaim visits it or the edge moves. + fn took(self: &Arc) { // SeqCst pairs with the fence in `shed_taken`: either this sees the track unlisted, // or that shed sees the reader's progress. if !self.taken.load(Ordering::SeqCst) && !self.taken.swap(true, Ordering::SeqCst) { @@ -1324,7 +1360,7 @@ impl Track { /// Shed the frames readers took of this track's live edge, unlisting it first, so a frame /// a reader takes during the shed lists it again. - fn shed_taken(&self) { + pub(super) fn shed_taken(&self) { self.taken.store(false, Ordering::SeqCst); std::sync::atomic::fence(Ordering::SeqCst); let Some(state) = self.state.upgrade() else { @@ -1336,10 +1372,10 @@ impl Track { state.shed_edge_taken(self.moves.load(Ordering::Relaxed)); } - /// Whether this track's session bounds its live edges, so its readers' progress matters - /// to a reclaim. - pub(super) fn bounded(&self) -> bool { - self.edges.0.is_some() + /// Whether the session lists this track as having taken frames to shed. + #[cfg(all(test, feature = "async"))] + pub(super) fn listed(&self) -> bool { + self.taken.load(Ordering::SeqCst) } /// How many times the live edge moved. @@ -1392,6 +1428,16 @@ impl Track { } /// Charge a new group's fixed overhead, returning its [`Charge`]. + /// How a group's reader progress reaches this track's session, `None` while it has no + /// live-edge budget to shed taken frames toward. + pub(super) fn report(self: &Arc, charge: &Charge) -> Option { + self.edges.0.as_ref()?; + Some(Report { + track: self.clone(), + footprint: charge.footprint.clone(), + }) + } + pub(super) fn charge(self: &Arc) -> Charge { self.pool.add(ENTRY_OVERHEAD); self.written.fetch_add(ENTRY_OVERHEAD, Ordering::Relaxed); @@ -1690,6 +1736,11 @@ pub(super) struct Footprint { } impl Footprint { + /// Whether the group bills its session as its track's live edge. + fn edge(&self) -> bool { + self.content.load(Ordering::Relaxed) & EDGE != 0 + } + /// Count `n` more content bytes, returning whether they bill the session. fn add(&self, track: &Track, n: u64) -> bool { let prior = self.content.fetch_add(n, Ordering::Relaxed); diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 4c094968104..1067e9a0b32 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -746,6 +746,8 @@ impl Plain { struct Inflate { release: Arc, plain: Arc, + // The group copy's reader progress, told when inflating lets a reclaim shed more slices. + pace: Arc, // Local index of the first slice: the copy's inflated length when the read took them. from: usize, // The first frame the read needs, which shedding the inflated copy stops short of. @@ -762,6 +764,8 @@ impl Inflate { /// lock held, since settling the debt takes the track's. fn run(&self, meter: &stats::Meter) { self.inflate(meter); + // Slices a raw reader took that a taken-frame shed kept for this copy may go now. + self.pace.retake(); // The inflated bytes are written like a producer's, so they pay the pool's debt the // same way: a finished track has no writer left to settle it. self.plain.bill.settle(); @@ -1294,6 +1298,7 @@ impl GroupState { .clone() .ok_or_else(|| self.outcome.error().cloned().unwrap_or(Error::Dropped))?, plain: flate.plain.clone(), + pace: self.pace.clone(), from, keep: first, slices: self.entries(from, last + 1).cloned().collect(), @@ -1852,10 +1857,10 @@ impl Producer { charge.extra(), ))); } - state.charge = charge; - if cache.bounded() { - state.pace.report(cache.clone()); + if let Some(report) = cache.report(&charge) { + state.pace.report(report); } + state.charge = charge; (state.log.reader(), state.pace.clone()) }; let alive = Arc::new(Alive { diff --git a/rs/moq-net/src/model/pace.rs b/rs/moq-net/src/model/pace.rs index 8531361a0f4..b12229d4858 100644 --- a/rs/moq-net/src/model/pace.rs +++ b/rs/moq-net/src/model/pace.rs @@ -18,7 +18,7 @@ //! waiting on the writer. use std::sync::{ - Arc, Mutex, OnceLock, PoisonError, + Mutex, OnceLock, PoisonError, atomic::{AtomicBool, AtomicU64, Ordering}, }; use std::task::Waker; @@ -59,9 +59,9 @@ pub(super) struct Pace { parked: AtomicBool, // The writer's waker: a group has one writer, so one slot, far smaller than a list. writer: Mutex>, - // The track told when the fastest reader takes a frame the copy still holds, set only - // while its session has a live-edge budget to shed those frames toward. - edge: OnceLock>, + // Told when the fastest reader takes a frame the copy still holds, set only while its + // session has a live-edge budget to shed those frames toward. + report: OnceLock, } impl Pace { @@ -74,17 +74,30 @@ impl Pace { // SeqCst pairs with `park`: either this sees the writer parked, or it sees the read. self.read.fetch_max(end, Ordering::SeqCst); self.wake(); - if let Some(track) = self.edge.get() + if let Some(report) = self.report.get() && end > self.front.load(Ordering::SeqCst) { - track.took(); + report.took(); } } - /// Tell `track` whenever the fastest reader takes a frame this copy still holds, so its - /// session, past its live-edge budget, visits only the edges with taken frames to shed. - pub fn report(&self, track: Arc) { - let _ = self.edge.set(track); + /// Report reader progress through `report`, so the copy's session, past its live-edge + /// budget, visits only the edges with taken frames to shed. + pub fn report(&self, report: cache::Report) { + let _ = self.report.set(report); + } + + /// Report the taken frames the copy still holds again, as a frame read does: a shed that + /// had to leave some now may take them. + pub fn retake(&self) { + // SeqCst pairs with the fence a reclaim's shed takes: either that shed sees what made + // the frames sheddable, or this sees the track unlisted. + std::sync::atomic::fence(Ordering::SeqCst); + if let Some(report) = self.report.get() + && self.read() > self.front.load(Ordering::SeqCst) + { + report.took(); + } } /// Wake the writer, if parked, since what it waits on changed. diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 913f3c3a382..b7be867c5ea 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -27870,19 +27870,49 @@ mod test { )); let before = broadcast.edges.used(); - let moves = producer.state.read().cache.moves(); - producer.state.write().ok().expect("open").shed_edge_taken(moves); + let cache = producer.state.read().cache.clone(); + cache.shed_taken(); let after = broadcast.edges.used(); assert!(after <= before, "the shed billed more: {before} -> {after}"); + assert!(!producer.state.read().cache.listed(), "the reclaim visit unlisted it"); for _ in 1..4 { assert!( plain.read_frame().await.unwrap().is_some(), "a slice the plain copy needed went" ); } + // Decoding the rest made the slices it kept sheddable, so the edge is listed again. + assert!(producer.state.read().cache.listed(), "the kept slices went unreported"); drop(group); } + /// Only reads of the live edge list its track for a reclaim, and the listing goes when the + /// edge moves: a reclaim never visits a track for frames taken from an older group. + #[test] + #[cfg(feature = "async")] + fn only_live_edge_reads_list_a_track() { + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(1 << 30)); + let producer = Producer::new(broadcast, "test", Info::timed()); + let listed = || producer.state.read().cache.listed(); + let mut group = producer.append_next().unwrap(); + let mut reader = producer.consume().peek_group(group.start).expect("cached"); + for _ in 0..2 { + group + .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; 100])) + .unwrap(); + } + assert!(!listed(), "listed before any read"); + assert!(matches!(reader.read_frame().now_or_never(), Some(Ok(Some(_))))); + assert!(listed(), "a live-edge read went unreported"); + + let next = producer.append_next().unwrap(); + assert!(!listed(), "the listing outlived the edge"); + assert!(matches!(reader.read_frame().now_or_never(), Some(Ok(Some(_))))); + assert!(!listed(), "a read behind the edge listed the track"); + drop((group, next)); + } + /// The stored slices a publisher of a compressed group would send. #[cfg(feature = "async")] fn stored_slices(info: &Info) -> arrayvec::ArrayVec { From ece92e95cf8a2d2adc3be7b48dd69af15d681bc8 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 04:24:44 -0800 Subject: [PATCH 11/16] fix(net): defer reclaim wakes, list only slot copies' reads, list under one lock - Edges::reclaim opens a kio::hold before its lock, and Pace wakes its writer through the new kio::wake, so no task polled inline re-enters the lock. - A copy's footprint records whether it is itself the live edge; only its readers' progress lists the track, not a displaced sibling's. - The taken flag changes only under the list lock, with its entry. - Tests drive a real reclaim and read after the edge moves; the m4 quest's reproduction fits every group in the budget. Co-Authored-By: Claude Opus 5.5 --- quest/m4/unsealed-frame-credit.md | 11 ++- rs/kio/src/lib.rs | 2 +- rs/kio/src/waiter.rs | 36 ++++++++- rs/moq-net/src/model/cache.rs | 59 ++++++++------ rs/moq-net/src/model/pace.rs | 3 +- rs/moq-net/src/model/track.rs | 124 ++++++++++++++++++++++++++---- 6 files changed, 189 insertions(+), 46 deletions(-) diff --git a/quest/m4/unsealed-frame-credit.md b/quest/m4/unsealed-frame-credit.md index e69f28b3f9d..62b1484c62e 100644 --- a/quest/m4/unsealed-frame-credit.md +++ b/quest/m4/unsealed-frame-credit.md @@ -26,9 +26,14 @@ credit for bytes the model already counts. It is a design change of its own, as [unbounded groups](/quest/m3/unbounded-groups/README.md) made the release per segment. -Reproduce with `quic_sim::many_groups_carry_their_highest_priorities_losslessly` at 200 -groups instead of `MANY`. The fix raises `MANY` until a frame's worth of -credit per stream no longer bounds it, or says what bounds it instead. +Reproduce with `quic_sim::many_groups_carry_their_highest_priorities_losslessly` +(`rs/moq-relay/tests/integration/quic_sim.rs`) at `MANY = 200` and +`LOSSLESS = 200`, with the relay's client `live_edges` budget raised to fit +every group (each holds at most `pace::AHEAD`, 16 MiB, ahead of its reader, so +200 need 3.2 GiB; `0` leaves it unbounded). Every track must then arrive whole: +the budget sheds nothing, so an eviction is the credit limit, not priority +shedding. The fix raises `MANY` until a frame's worth of credit per stream no +longer bounds it, or says what bounds it instead. Whatever lands updates the credit model (the [`verify-credit` skill](/.claude/skills/verify-credit/SKILL.md)): early return changes when credit comes back, and its safety property (credit held diff --git a/rs/kio/src/lib.rs b/rs/kio/src/lib.rs index 34f054d2d60..e197b5ede9a 100644 --- a/rs/kio/src/lib.rs +++ b/rs/kio/src/lib.rs @@ -71,7 +71,7 @@ pub use producer::{Producer, Unwanted}; pub use queue::{PushError, Queue}; pub use shared::Shared; pub use task::{Task, TaskKey, Tasks}; -pub use waiter::{Hold, Park, Waiter, WaiterList, hold, wait}; +pub use waiter::{Hold, Park, Waiter, WaiterList, hold, wait, wake}; pub use watch::Watch; pub use weak::{ConsumerWeak, ProducerWeak, Weak}; diff --git a/rs/kio/src/waiter.rs b/rs/kio/src/waiter.rs index 8f88330799e..3a9aa9e84ca 100644 --- a/rs/kio/src/waiter.rs +++ b/rs/kio/src/waiter.rs @@ -375,6 +375,8 @@ impl WaiterList { struct Held { depth: usize, wakers: Vec>, + // Wakes made by [`wake`], which owns its waker rather than a list's registration. + owned: Vec, } thread_local! { @@ -382,10 +384,26 @@ thread_local! { std::cell::RefCell::new(Held { depth: 0, wakers: Vec::new(), + owned: Vec::new(), }) }; } +/// Wake `waker` now, or under a [`Hold`] once the outermost one drops, as a +/// [`WaiterList`] does: for a single waker kept outside a list. +pub fn wake(waker: Waker) { + let mut waker = Some(waker); + let _ = HELD.try_with(|held| { + let mut held = held.borrow_mut(); + if held.depth > 0 { + held.owned.extend(waker.take()); + } + }); + if let Some(waker) = waker { + waker.wake(); + } +} + /// Holds back every wake this thread makes through a [`WaiterList`] until it drops. /// /// A waker may poll its task inline, and that task may take a lock its waker is still @@ -408,13 +426,13 @@ pub fn hold() -> Hold { impl Drop for Hold { fn drop(&mut self) { - let wakers = HELD + let (wakers, owned) = HELD .try_with(|held| { let mut held = held.borrow_mut(); held.depth = held.depth.saturating_sub(1); match held.depth { - 0 => std::mem::take(&mut held.wakers), - _ => Vec::new(), + 0 => (std::mem::take(&mut held.wakers), std::mem::take(&mut held.owned)), + _ => Default::default(), } }) .unwrap_or_default(); @@ -422,6 +440,9 @@ impl Drop for Hold { for waker in wakers.into_iter().filter_map(|w| w.upgrade()) { waker.wake_by_ref(); } + for waker in owned { + waker.wake(); + } } } @@ -613,6 +634,15 @@ mod tests { waiter.register(&mut list); list.wake(); assert_eq!(woken(), 2, "a wake with no hold open waited"); + + // A lone waker's wake waits the same way. + let outer = hold(); + wake(Waker::from(count.clone())); + assert_eq!(woken(), 2, "a held lone wake went out"); + drop(outer); + assert_eq!(woken(), 3, "the hold lost the lone wake"); + wake(Waker::from(count.clone())); + assert_eq!(woken(), 4, "a lone wake with no hold open waited"); } #[test] diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 69c3852817d..e37cd2a8185 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -811,6 +811,12 @@ impl Edges { })) } + /// Whether a reclaim holds the session's reclaim lock now. + #[cfg(test)] + pub(super) fn reclaiming(&self) -> bool { + self.0.as_ref().is_some_and(|inner| inner.reclaiming.try_lock().is_err()) + } + /// Bytes the session's live edges bill now. #[cfg(any(test, feature = "fuzz"))] pub(super) fn used(&self) -> u64 { @@ -849,6 +855,9 @@ impl Edges { let Some(inner) = &self.0 else { return; }; + // Opened first, so it drops last: a shed's wakes go out once the lock is released, + // since a woken task polled inline may settle a write here and reclaim again. + let _hold = kio::hold(); let _reclaiming = inner.reclaiming.lock().unwrap_or_else(PoisonError::into_inner); while self.excess().is_some() { let track = { @@ -859,7 +868,10 @@ impl Edges { let Some(track) = track.upgrade() else { continue; }; + // Unlisted before the shed, so a frame a reader takes during it lists the + // track again. *track.listed.lock().unwrap_or_else(PoisonError::into_inner) = None; + track.taken.store(false, Ordering::SeqCst); track }; track.shed_taken(); @@ -894,8 +906,9 @@ impl Edges { } /// List `track` as having taken frames to shed, or with `again`, move its entry to its - /// current rank and age if it has one. Drops the entries of tracks gone since once they - /// clearly outnumber the live ones, as [`Self::queue`] does. + /// current rank and age if it has one. Its `taken` flag changes only here, with the entry, + /// so the two always agree. Drops the entries of tracks gone since once they clearly + /// outnumber the live ones, as [`Self::queue`] does. fn list(&self, track: &Arc, again: bool) { let Some(inner) = &self.0 else { return; @@ -913,6 +926,7 @@ impl Edges { let key = (track.rank(), track.seq.load(Ordering::Relaxed)); taken.insert((key, at), Arc::downgrade(track)); *listed = Some(key); + track.taken.store(true, Ordering::SeqCst); drop(listed); if taken.len() > 2 * inner.tracks.load(Ordering::Relaxed) + EDGE_SLACK { taken.retain(|_, track| track.strong_count() > 0); @@ -1010,8 +1024,9 @@ impl std::fmt::Debug for Edges { } } -/// Tells a group's session when its readers take frames it still holds, while it is the live -/// edge, so a reclaim past the session's budget visits only edges with taken frames. +/// Tells a group's session when its readers take frames it still holds, while the copy is +/// itself the live edge, so a reclaim past the session's budget visits only edges with taken +/// frames: a sibling that bills the edge from outside its slot is never visited. pub(super) struct Report { track: Arc, footprint: Arc, @@ -1020,7 +1035,7 @@ pub(super) struct Report { impl Report { /// A reader took a frame the group still holds. pub(super) fn took(&self) { - if self.footprint.edge() { + if self.footprint.slot() { self.track.took(); } } @@ -1102,8 +1117,8 @@ pub(super) struct Track { // Whether the live edge has an entry in its session's order, so one that a reclaim shed // queues again once it grows. queued: AtomicBool, - // Whether a reader took a frame this track's groups still hold since a reclaim last - // visited it, so a reader lists the track once. + // Whether the session lists this track among its edges with taken frames, so a reader + // lists it once. Changed only under that list's lock, with `listed`. taken: AtomicBool, // Where the session lists this track among its edges with taken frames, if it does. // Changed only under that list's lock. @@ -1353,15 +1368,13 @@ impl Track { fn took(self: &Arc) { // SeqCst pairs with the fence in `shed_taken`: either this sees the track unlisted, // or that shed sees the reader's progress. - if !self.taken.load(Ordering::SeqCst) && !self.taken.swap(true, Ordering::SeqCst) { + if !self.taken.load(Ordering::SeqCst) { self.edges.list(self, false); } } - /// Shed the frames readers took of this track's live edge, unlisting it first, so a frame - /// a reader takes during the shed lists it again. - pub(super) fn shed_taken(&self) { - self.taken.store(false, Ordering::SeqCst); + /// Shed the frames readers took of this track's live edge, which a reclaim unlisted first. + fn shed_taken(&self) { std::sync::atomic::fence(Ordering::SeqCst); let Some(state) = self.state.upgrade() else { return; @@ -1450,9 +1463,9 @@ impl Track { footprint: Arc::new(Footprint { content: AtomicU64::new(0), fixed: AtomicU64::new(ENTRY_OVERHEAD), + slot: AtomicBool::new(false), }), content: 0, - edge: false, whole: false, held: AtomicBool::new(false), } @@ -1733,12 +1746,15 @@ fn fixed_class(flags: u64) -> Class { pub(super) struct Footprint { content: AtomicU64, fixed: AtomicU64, + // Whether this copy is itself its track's cached live edge, not billed for a sibling that + // is. Atomic so a reader's progress can check it outside the group's lock. + slot: AtomicBool, } impl Footprint { - /// Whether the group bills its session as its track's live edge. - fn edge(&self) -> bool { - self.content.load(Ordering::Relaxed) & EDGE != 0 + /// Whether this copy is itself its track's cached live edge. + fn slot(&self) -> bool { + self.slot.load(Ordering::Relaxed) } /// Count `n` more content bytes, returning whether they bill the session. @@ -1882,14 +1898,14 @@ impl Siblings { .find(|sibling| Arc::ptr_eq(&sibling.footprint, &charge.footprint)) { Some(sibling) => { - sibling.edge = charge.edge; + sibling.edge = charge.footprint.slot(); sibling.whole = charge.whole; sibling.held = charge.is_held(); } None => siblings.push(Sibling { track: track.clone(), footprint: charge.footprint.clone(), - edge: charge.edge, + edge: charge.footprint.slot(), whole: charge.whole, held: charge.is_held(), }), @@ -1955,9 +1971,6 @@ pub(super) struct Charge { footprint: Arc, // The part of `bytes` in `footprint`: content, its fixed overhead left out. content: u64, - // Whether this group is itself its track's cached live edge, as opposed to billing the - // session only for a sibling that is: see [`Siblings`]. - edge: bool, // Whether this copy finished the whole group, which makes its siblings whole too. whole: bool, // Whether a fill holds this copy for a reader, which holds its siblings too. Atomic, since a @@ -2125,7 +2138,7 @@ impl Charge { if let Some(track) = &self.track { self.footprint.demote(track); } - self.edge = false; + self.footprint.slot.store(false, Ordering::Relaxed); } /// Bill the group, its extras included, to its session's [`Edges`] as its track's cached @@ -2136,7 +2149,7 @@ impl Charge { && !self.counted { self.footprint.promote(track); - self.edge = true; + self.footprint.slot.store(true, Ordering::Relaxed); } } diff --git a/rs/moq-net/src/model/pace.rs b/rs/moq-net/src/model/pace.rs index b12229d4858..9ee78a46b0d 100644 --- a/rs/moq-net/src/model/pace.rs +++ b/rs/moq-net/src/model/pace.rs @@ -106,8 +106,9 @@ impl Pace { // SeqCst, to stay in the order `park` pairs with. if self.parked.load(Ordering::SeqCst) && self.parked.swap(false, Ordering::SeqCst) { let writer = self.writer.lock().unwrap_or_else(PoisonError::into_inner).take(); + // Through kio, so a wake made under a hold (a reclaim's) waits for it. if let Some(writer) = writer { - writer.wake(); + kio::wake(writer); } } } diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index b7be867c5ea..e45f4a1be3b 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -6819,7 +6819,7 @@ impl Routed { /// A session at its live-edge budget, for benches: `quiet` edges that moved first, each /// holding one frame nobody read, and one edge written a frame at a time, which a reader /// takes as it lands. Each write past the budget reclaims. -#[cfg(feature = "fuzz")] +#[cfg(all(feature = "async", any(test, feature = "fuzz")))] pub(crate) struct EdgesBench { _quiet: Vec<(Producer, group::Producer)>, written: Producer, @@ -6829,7 +6829,7 @@ pub(crate) struct EdgesBench { frames: usize, } -#[cfg(feature = "fuzz")] +#[cfg(all(feature = "async", any(test, feature = "fuzz")))] impl EdgesBench { /// Frames the written edge takes before it moves to a new group. const GROUP: usize = 1024; @@ -27838,16 +27838,19 @@ mod test { } /// The taken-frame shed of a received compressed edge inflates nothing: a raw reader past - /// a plain reader's decoded prefix sheds only the slices that prefix already used, so the - /// session's bill never grows and the plain reader keeps decoding. + /// a plain reader's decoded prefix sheds only the slices that prefix already used, so a + /// reclaim's first pass brings the session back under budget without shedding a whole + /// edge, and the plain reader keeps decoding. #[kio::test] #[cfg(feature = "async")] async fn a_taken_shed_leaves_slices_the_plain_copy_needs() { - let info = Info::timed().with_compression(Compression::Deflate); + const LIMIT: u64 = 1 << 20; + let info = Info::timed().with_compression(Compression::Deflate).with_priority(5); let stored = stored_slices(&info); let pool = cache::Pool::unbounded(); - let broadcast = session_broadcast(&pool, Some(1 << 30)); + let broadcast = session_broadcast(&pool, Some(LIMIT)); let producer = Producer::new(broadcast.clone(), "test", info); + let mut writer = Producer::new(broadcast.clone(), "writer", Info::timed()); let mut group = producer.create_group(group::Info { start: 0 }).unwrap(); // A plain reader decodes the first slices, then a raw one takes every slice. for object in &stored[..2] { @@ -27869,12 +27872,16 @@ mod test { Poll::Ready(Ok(4)) )); + assert!(producer.state.read().cache.listed(), "the raw read went unreported"); + + // A lower-priority write passes the budget by a byte, so a reclaim visits the edge. let before = broadcast.edges.used(); - let cache = producer.state.read().cache.clone(); - cache.shed_taken(); + finished_group(&mut writer, usize::try_from(LIMIT - before + 1).unwrap()); let after = broadcast.edges.used(); - assert!(after <= before, "the shed billed more: {before} -> {after}"); - assert!(!producer.state.read().cache.listed(), "the reclaim visit unlisted it"); + assert!(after <= LIMIT, "the shed left the session over: {before} -> {after}"); + assert!(!producer.state.read().cache.listed(), "the reclaim visit left it listed"); + // Its bill leaves with it, so decoding the rest never passes the budget again. + drop(writer); for _ in 1..4 { assert!( plain.read_frame().await.unwrap().is_some(), @@ -27897,15 +27904,15 @@ mod test { let listed = || producer.state.read().cache.listed(); let mut group = producer.append_next().unwrap(); let mut reader = producer.consume().peek_group(group.start).expect("cached"); - for _ in 0..2 { - group - .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; 100])) - .unwrap(); - } + let frame = || bytes::Bytes::from(vec![0u8; 100]); + group.write_frame(group.key_time(), frame()).unwrap(); assert!(!listed(), "listed before any read"); assert!(matches!(reader.read_frame().now_or_never(), Some(Ok(Some(_))))); assert!(listed(), "a live-edge read went unreported"); + // Written after the first read, so the read after the move takes it from the group, + // moving the reader's progress past a group that is no longer the edge. + group.write_frame(group.key_time(), frame()).unwrap(); let next = producer.append_next().unwrap(); assert!(!listed(), "the listing outlived the edge"); assert!(matches!(reader.read_frame().now_or_never(), Some(Ok(Some(_))))); @@ -27913,6 +27920,93 @@ mod test { drop((group, next)); } + /// A fetched copy of the live edge that another copy displaced from its slot lists nothing + /// when read: a reclaim visits only the slot's copies, so it would find nothing to shed. + #[test] + #[cfg(feature = "async")] + fn a_displaced_copys_reads_list_nothing() { + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(1 << 30)); + let producer = Producer::new(broadcast, "test", Info::timed()); + producer.received(); + elapse(&producer, Duration::ZERO); + let listed = || producer.state.read().cache.listed(); + let at = |millis| Timestamp::from_millis(millis).unwrap(); + let payload = || bytes::Bytes::from(vec![0u8; 100]); + let fetched = |end| { + producer + .state + .write() + .ok() + .unwrap() + .insert_group_request(3, group::Bounds { start: 0, end }, None) + .unwrap() + .expect("a fresh group") + }; + + // The live copy, received from frame 1, beside a fetch of the head cut short at frame 1. + let Ok(Received::Group(mut live)) = producer.create_group_at(group::Info { start: 3 }, 1, 0..0) else { + panic!("the live copy opens"); + }; + live.write_frame(at(301), payload()).unwrap(); + let mut cut = fetched(Some(1)); + let mut reader = cut.consume(); + // A whole fetch of the group displaces the cut one from the slot. + let whole = fetched(None); + cut.write_frame(at(300), payload()).unwrap(); + assert!(matches!(reader.read_frame().now_or_never(), Some(Ok(Some(_))))); + assert!(!listed(), "a displaced copy's read listed the track"); + drop((live, whole)); + } + + /// A reclaim wakes nothing while it holds its session's reclaim lock: a waker may poll its + /// task inline, and a task that settles a write on the same session would reclaim again + /// and wait on that lock forever. Here a reclaim's taken-frame shed wakes a parked writer. + #[test] + #[cfg(feature = "async")] + fn a_reclaim_wakes_nothing_under_its_lock() { + struct Probe { + edges: cache::Edges, + woken: AtomicBool, + locked: AtomicBool, + } + impl std::task::Wake for Probe { + fn wake(self: Arc) { + self.locked.fetch_or(self.edges.reclaiming(), Ordering::SeqCst); + self.woken.store(true, Ordering::SeqCst); + } + } + const FRAME: usize = 10_000; + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(25_000)); + let a = Producer::new(broadcast.clone(), "a", Info::timed()); + let mut b = Producer::new(broadcast.clone(), "b", Info::timed()); + let frame = || bytes::Bytes::from(vec![0u8; FRAME]); + + // a's reader takes its first frame, and its writer parks a frame ahead of that reader. + let mut group = a.append_next().unwrap(); + let mut reader = a.consume().peek_group(group.start).expect("cached"); + group.write_frame(group.key_time(), frame()).unwrap(); + assert!(matches!(reader.read_frame().now_or_never(), Some(Ok(Some(_))))); + group.write_frame(group.key_time(), frame()).unwrap(); + let probe = Arc::new(Probe { + edges: broadcast.edges.clone(), + woken: AtomicBool::new(false), + locked: AtomicBool::new(false), + }); + let waiter = kio::Waiter::new(std::task::Waker::from(probe.clone())); + assert!(group.poll_paced(&waiter, 0, 1).is_pending()); + + // b's write passes the budget, and the reclaim sheds a's taken frame. + finished_group(&mut b, FRAME); + assert!(probe.woken.load(Ordering::SeqCst), "the shed left the writer parked"); + assert!( + !probe.locked.load(Ordering::SeqCst), + "a waker ran under the reclaim lock" + ); + drop(group); + } + /// The stored slices a publisher of a compressed group would send. #[cfg(feature = "async")] fn stored_slices(info: &Info) -> arrayvec::ArrayVec { From d2a2c19731e61a4b0286763a2fff0e7ec4ac254c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 04:54:45 -0800 Subject: [PATCH 12/16] style: rustfmt Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/cache.rs | 4 +++- rs/moq-net/src/model/track.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index e37cd2a8185..ca42d91f8ef 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -814,7 +814,9 @@ impl Edges { /// Whether a reclaim holds the session's reclaim lock now. #[cfg(test)] pub(super) fn reclaiming(&self) -> bool { - self.0.as_ref().is_some_and(|inner| inner.reclaiming.try_lock().is_err()) + self.0 + .as_ref() + .is_some_and(|inner| inner.reclaiming.try_lock().is_err()) } /// Bytes the session's live edges bill now. diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index e45f4a1be3b..f1f89ebe95b 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -27879,7 +27879,10 @@ mod test { finished_group(&mut writer, usize::try_from(LIMIT - before + 1).unwrap()); let after = broadcast.edges.used(); assert!(after <= LIMIT, "the shed left the session over: {before} -> {after}"); - assert!(!producer.state.read().cache.listed(), "the reclaim visit left it listed"); + assert!( + !producer.state.read().cache.listed(), + "the reclaim visit left it listed" + ); // Its bill leaves with it, so decoding the rest never passes the budget again. drop(writer); for _ in 1..4 { From 731e006ddd9ffab941a0caeb6681ceb2950dd0c8 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 05:20:59 -0800 Subject: [PATCH 13/16] fix(net): gate the reclaim-lock probe to the async tests using it Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/cache.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index ca42d91f8ef..6b764ee2016 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -812,7 +812,7 @@ impl Edges { } /// Whether a reclaim holds the session's reclaim lock now. - #[cfg(test)] + #[cfg(all(test, feature = "async"))] pub(super) fn reclaiming(&self) -> bool { self.0 .as_ref() From 91ee9c5981f114a4567ef8df2c61a9d5dcb94fb1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 06:19:50 -0800 Subject: [PATCH 14/16] quest: defer the displaced-decoder relist, reproduce m4 over whole transfers Co-Authored-By: Claude Opus 5.5 --- quest/m1/live-edge-inflated-taken.md | 2 ++ quest/m4/unsealed-frame-credit.md | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/quest/m1/live-edge-inflated-taken.md b/quest/m1/live-edge-inflated-taken.md index 01477eec351..66638164938 100644 --- a/quest/m1/live-edge-inflated-taken.md +++ b/quest/m1/live-edge-inflated-taken.md @@ -14,3 +14,5 @@ A first attempt, in [moq-dev/moq#9439](https://github.com/moq-dev/moq/pull/9439) - A long compressed group trims its slices while keeping their inflated frames for a plain reader (`a_long_compressed_group_sheds_its_front`). Bounding by the slice front sheds frames past `read`. Recommended: bound by each inflated entry's own `end`, which `Inflate` copies from its slice (`entry.end <= read`). Also pin the frames of inflate jobs in flight in `PlainState`, for example the lowest index a running job keeps, as `Inflate::keep` does for the `MAX_CACHE_BYTES` trim. Test it with mock time: a plain reader mid-prefetch, a session past its budget, and a second compressed edge. + +Also relist the live edge when a displaced copy decodes further ([moq-dev/moq#9439](https://github.com/moq-dev/moq/pull/9439) review round 4). A bounded fetch that a wider fetch displaced while it was still decoding shares the plain copy's decoded prefix with the live edge. But `Pace::retake` reports through the displaced copy, whose `Footprint::slot` is clear, so `Report::took` lists nothing. Until the next raw read on the live edge relists the track, pass 1 skips the slices that decoding made sheddable, and pass 2 sheds the way it always did. Recommended: keep read reports scoped to the slot copy, and notify the current live edge separately when the shared decoded prefix advances. Test it with a raw reader on the live edge and a displaced bounded fetch that decodes past the shed front. diff --git a/quest/m4/unsealed-frame-credit.md b/quest/m4/unsealed-frame-credit.md index 62b1484c62e..4897da35b0b 100644 --- a/quest/m4/unsealed-frame-credit.md +++ b/quest/m4/unsealed-frame-credit.md @@ -28,7 +28,8 @@ per segment. Reproduce with `quic_sim::many_groups_carry_their_highest_priorities_losslessly` (`rs/moq-relay/tests/integration/quic_sim.rs`) at `MANY = 200` and -`LOSSLESS = 200`, with the relay's client `live_edges` budget raised to fit +`LOSSLESS = 200`, reading `BULK` bytes per group instead of 1 MiB so it checks whole +transfers, with the relay's client `live_edges` budget raised to fit every group (each holds at most `pace::AHEAD`, 16 MiB, ahead of its reader, so 200 need 3.2 GiB; `0` leaves it unbounded). Every track must then arrive whole: the budget sheds nothing, so an eviction is the credit limit, not priority From 79e4f311d647e5f3f7cfe8065aa6c6133498bd4a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 07:04:54 -0800 Subject: [PATCH 15/16] fix(net): bound a reclaim's whole-edge pass to the edges queued when it starts Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/cache.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 6b764ee2016..3cd102b37e9 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -880,11 +880,16 @@ impl Edges { } // The writer pays in its turn, or after every queued edge when it has no entry. let mut paid = false; - // Each step resumes after the last key, so an entry is visited once. + // Each step resumes after the last key, so an entry is visited once. Visits are bounded + // by the entries present now, since a publisher inserting groups requeues its edge after + // `after` and could otherwise keep this pass, and the lock, going. + let mut offers = inner.order.lock().unwrap_or_else(PoisonError::into_inner).len(); let mut after = None; - while self.excess().is_some() + while offers > 0 + && self.excess().is_some() && let Some((key, track, moves)) = self.next(after) { + offers -= 1; after = Some(key); if std::ptr::eq(Arc::as_ptr(&track), writer) { paid = true; From be24ece846f3157ad69023a9b2815bb8f304cdb1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 25 Nov 2026 08:50:04 -0800 Subject: [PATCH 16/16] fix(net): a reclaim's whole-edge pass skips edges that moved after it started A publisher opening empty groups on its lowest-ranked tracks mid-pass queued entries after the last visited one; each used a visit without freeing bytes, so the pass could run out before reaching a lower-ranked edge that covered the excess and shed the writer's unread frames instead. An edge that moved since the pass started now waits for the next reclaim, uncounted, and the pass jumps past the rest of its rank. The visit cap stays for reranks. Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/cache.rs | 54 +++++++++++++++++++++++++---------- rs/moq-net/src/model/track.rs | 45 +++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 15 deletions(-) diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 3cd102b37e9..25a22c361b6 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -46,6 +46,7 @@ use crate::util::SendCell; use std::collections::BTreeMap; +use std::ops::Bound; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicI8, AtomicI64, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, OnceLock, PoisonError, Weak}; @@ -789,6 +790,9 @@ struct EdgesInner { // Held through a reclaim, so one that finds no taken frame listed never sheds a whole // edge while another is still shedding the taken frames it popped. reclaiming: Mutex<()>, + // Run once when a reclaim's whole-edge pass starts, so a test can move edges mid-pass. + #[cfg(test)] + started: Mutex>>, } /// A track's place among its session's edges with taken frames: its [`EdgeKey`], then its @@ -807,6 +811,8 @@ impl Edges { tracks: AtomicUsize::new(0), taken: Mutex::default(), reclaiming: Mutex::default(), + #[cfg(test)] + started: Mutex::default(), }) })) } @@ -819,6 +825,14 @@ impl Edges { .is_some_and(|inner| inner.reclaiming.try_lock().is_err()) } + /// Run `hook` once the next reclaim's whole-edge pass starts. + #[cfg(all(test, feature = "async"))] + pub(super) fn on_pass(&self, hook: impl FnOnce() + Send + 'static) { + if let Some(inner) = &self.0 { + *inner.started.lock().unwrap() = Some(Box::new(hook)); + } + } + /// Bytes the session's live edges bill now. #[cfg(any(test, feature = "fuzz"))] pub(super) fn used(&self) -> u64 { @@ -880,17 +894,31 @@ impl Edges { } // The writer pays in its turn, or after every queued edge when it has no entry. let mut paid = false; - // Each step resumes after the last key, so an entry is visited once. Visits are bounded - // by the entries present now, since a publisher inserting groups requeues its edge after - // `after` and could otherwise keep this pass, and the lock, going. - let mut offers = inner.order.lock().unwrap_or_else(PoisonError::into_inner).len(); - let mut after = None; + // Each step resumes after the last key, so an entry is visited once. The pass covers + // only the edges that last moved before it started: one a publisher moves meanwhile + // sorts after its own, so publishing faster than this pass could otherwise keep it, and + // the lock, going, or use up its visits on empty new groups. Visits are also bounded by + // the entries present now, since a rerank requeues an edge at its old age. + let (mut offers, start) = { + let order = inner.order.lock().unwrap_or_else(PoisonError::into_inner); + (order.len(), inner.moves.load(Ordering::Relaxed)) + }; + #[cfg(test)] + if let Some(hook) = inner.started.lock().unwrap().take() { + hook(); + } + let mut from = Bound::Unbounded; while offers > 0 && self.excess().is_some() - && let Some((key, track, moves)) = self.next(after) + && let Some((key, track, moves)) = self.next(from) { + // Moved since the pass started, as has every later edge at its rank. + if key.1 >= start { + from = Bound::Included((key.0 + 1, 0)); + continue; + } offers -= 1; - after = Some(key); + from = Bound::Excluded(key); if std::ptr::eq(Arc::as_ptr(&track), writer) { paid = true; writer.shed_own(self); @@ -940,22 +968,18 @@ impl Edges { } } - /// The first current entry in the order past `after`, dropping the stale ones before it. - fn next(&self, mut after: Option) -> Option<(EdgeKey, Arc, u64)> { + /// The first current entry in the order from `from` on, dropping the stale ones before it. + fn next(&self, mut from: Bound) -> Option<(EdgeKey, Arc, u64)> { let inner = self.0.as_ref()?; let mut order = inner.order.lock().unwrap_or_else(PoisonError::into_inner); loop { - let (key, (weak, moves)) = match after { - None => order.range(..), - Some(key) => order.range((std::ops::Bound::Excluded(key), std::ops::Bound::Unbounded)), - } - .next()?; + let (key, (weak, moves)) = order.range((from, Bound::Unbounded)).next()?; let (key, moves) = (*key, *moves); match weak.upgrade().filter(|track| track.queued_at(key, moves)) { Some(track) => return Some((key, track, moves)), None => { order.remove(&key); - after = Some(key); + from = Bound::Excluded(key); } } } diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index f1f89ebe95b..5b1daabe04b 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -27765,6 +27765,51 @@ mod test { assert!(kept(&old) && kept(&new), "a subscribed or newer edge paid"); } + /// Edges that move while a reclaim runs wait for the next one: a publisher opening empty + /// groups on its lowest-ranked tracks mid-pass never uses up the pass before it reaches + /// a lower-ranked edge than the writer's that covers the excess. + #[test] + #[cfg(feature = "async")] + fn edges_moved_during_a_reclaim_wait_for_the_next() { + const FRAME: usize = 8_000; + let pool = cache::Pool::unbounded(); + let broadcast = session_broadcast(&pool, Some(25_000)); + let track = + |name: &str, priority| Producer::new(broadcast.clone(), name, Info::timed().with_priority(priority)); + let (mut low, mut mid, writer) = (track("low", -10), track("mid", -5), track("writer", 0)); + let empty = [track("e1", -10), track("e2", -10)]; + let opened = Arc::new(std::sync::Mutex::new(Vec::new())); + + // The lowest edge frees too little to cover the excess. + finished_group(&mut low, 1_000); + finished_group(&mut mid, 2 * FRAME); + // Once the pass starts, empty edges open at the lowest rank, after `low`'s. + broadcast.edges.on_pass({ + let opened = opened.clone(); + let empty = empty.clone(); + move || { + let groups = empty.iter().map(|track| track.append_next().unwrap()); + opened.lock().unwrap().extend(groups); + } + }); + // The writer's two frames pass the budget. + let mut open = writer.append_next().unwrap(); + for _ in 0..2 { + open.write_frame(open.key_time(), bytes::Bytes::from(vec![0u8; FRAME])) + .unwrap(); + } + assert_eq!(opened.lock().unwrap().len(), 2, "no pass started"); + assert!(broadcast.edges.used() <= 25_000, "{:?}", broadcast.edges); + let mut first = writer.consume().peek_group(0).expect("the edge stays cached"); + assert!( + matches!(first.read_frame().now_or_never(), Some(Ok(Some(_)))), + "the writer paid while a lower edge still held its frame" + ); + let mut shed = mid.consume().peek_group(0).expect("the edge stays cached"); + assert!(matches!(shed.read_frame().now_or_never(), Some(Err(Error::Evicted)))); + drop(open); + } + /// Frames a reader took pay before any frame a reader is owed, whatever their priority: /// a higher-priority edge whose reader caught up sheds what it read, and a lower one /// whose reader lags keeps its frame.