diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md index 21f37af1ae7..00e8cbccdaf 100644 --- a/doc/bin/relay/config.md +++ b/doc/bin/relay/config.md @@ -211,8 +211,11 @@ 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, 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 819d9793567..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 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, 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/quest/m1/live-edge-inflated-taken.md b/quest/m1/live-edge-inflated-taken.md new file mode 100644 index 00000000000..66638164938 --- /dev/null +++ b/quest/m1/live-edge-inflated-taken.md @@ -0,0 +1,18 @@ +# [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. + +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 2b3cd6817ad..4897da35b0b 100644 --- a/quest/m4/unsealed-frame-credit.md +++ b/quest/m4/unsealed-frame-credit.md @@ -26,9 +26,15 @@ 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 -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`, 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 +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/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/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/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 cd9668b2b66..25a22c361b6 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 @@ -45,9 +45,10 @@ //! 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::ops::Bound; 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; @@ -755,25 +756,49 @@ 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 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>); +/// 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, + // 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>>, + // 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 +/// 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 { @@ -782,13 +807,34 @@ impl Edges { limit, used: AtomicI64::new(0), order: Mutex::default(), + moves: AtomicU64::new(0), tracks: AtomicUsize::new(0), + taken: Mutex::default(), + reclaiming: Mutex::default(), + #[cfg(test)] + started: Mutex::default(), }) })) } + /// Whether a reclaim holds the session's reclaim lock now. + #[cfg(all(test, feature = "async"))] + pub(super) fn reclaiming(&self) -> bool { + self.0 + .as_ref() + .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(test)] + #[cfg(any(test, feature = "fuzz"))] pub(super) fn used(&self) -> u64 { self.0 .as_ref() @@ -814,68 +860,185 @@ 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 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; }; - // 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; + // 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 = { + let mut taken = inner.taken.lock().unwrap_or_else(PoisonError::into_inner); + let Some((_, track)) = taken.pop_first() else { + break; + }; + 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 }; - let Some(track) = weak.upgrade() else { - continue; - }; - if !track.edge_is(moves) { + 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. 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(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; } - // The writer's edge is the one being written: it pays last, and only in part. + offers -= 1; + from = Bound::Excluded(key); if std::ptr::eq(Arc::as_ptr(&track), writer) { - kept = Some((weak, moves)); + paid = true; + writer.shed_own(self); continue; } 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); - if let Ok(mut state) = state.write() { - state.shed_edge_all(moves); + 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. 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; + }; + 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, } - if let Some(entry) = kept { - inner - .order - .lock() - .unwrap_or_else(PoisonError::into_inner) - .push_front(entry); + 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); } - 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 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)) = 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); + from = Bound::Excluded(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 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. + // 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)); + 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))); + } + 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. + 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.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); } } @@ -892,6 +1055,23 @@ impl std::fmt::Debug for Edges { } } +/// 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, +} + +impl Report { + /// A reader took a frame the group still holds. + pub(super) fn took(&self) { + if self.footprint.slot() { + 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. @@ -959,9 +1139,21 @@ 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, + // 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. + 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. @@ -1102,7 +1294,12 @@ 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), + taken: AtomicBool::new(false), + listed: Mutex::default(), written: AtomicU64::new(0), next_expiry: AtomicU64::new(0), expiry_cursor: AtomicUsize::new(0), @@ -1139,18 +1336,92 @@ 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.queued.store(true, Ordering::Relaxed); - self.edges.moved(self, moves); + self.edges.moved(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, packed as delivery ranks its + /// subscription (the subscriber's priority always dominates the publisher's): higher + /// pays later. + fn rank(&self) -> i64 { + 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. + 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: its older + /// frames, keeping the newest of an open group. + fn shed_own(&self, edges: &Edges) { + let Some(excess) = edges.excess() else { + return; + }; + let Some(state) = self.state.upgrade() else { + return; + }; + let Ok(mut state) = state.write() else { + return; + }; + state.shed_edge(excess); + } + + /// 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.edges.list(self, false); + } + } + + /// 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; + }; + let Ok(mut state) = state.write() else { + return; + }; + state.shed_edge_taken(self.moves.load(Ordering::Relaxed)); + } + + /// 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. #[cfg(all(test, feature = "async"))] pub(super) fn moves(&self) -> u64 { @@ -1201,6 +1472,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); @@ -1213,9 +1494,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), } @@ -1496,9 +1777,17 @@ 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 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. fn add(&self, track: &Track, n: u64) -> bool { let prior = self.content.fetch_add(n, Ordering::Relaxed); @@ -1640,14 +1929,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(), }), @@ -1713,9 +2002,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 @@ -1883,7 +2169,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 @@ -1894,7 +2180,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/group.rs b/rs/moq-net/src/model/group.rs index e8685070b6a..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(); @@ -1157,6 +1161,40 @@ 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. 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 end < inflated + && let Some(entry) = self.entry(end) + && entry.end != 0 + && entry.end <= read + { + end += 1; + } + self.shed_frames(end, false); + } + + /// 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() @@ -1260,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(), @@ -1818,6 +1857,9 @@ impl Producer { charge.extra(), ))); } + if let Some(report) = cache.report(&charge) { + state.pace.report(report); + } state.charge = charge; (state.log.reader(), state.pace.clone()) }; @@ -2875,16 +2917,20 @@ 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, Abort::Evicted); } } + /// 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; + }; + state.shed_taken(self.alive.pace.read()); + } + pub(super) fn delivery_size(&self) -> u64 { let state = self.state.read(); state.charge.size() diff --git a/rs/moq-net/src/model/pace.rs b/rs/moq-net/src/model/pace.rs index 0fe9e244b31..9ee78a46b0d 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, + 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>, + // 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 { @@ -70,6 +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(report) = self.report.get() + && end > self.front.load(Ordering::SeqCst) + { + report.took(); + } + } + + /// 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. @@ -78,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 75acc2477ee..5b1daabe04b 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. @@ -3393,6 +3393,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(); @@ -3419,6 +3420,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.lost_bill = cache.extra(); new.cache = cache; drop(new); @@ -3821,29 +3823,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) { @@ -6805,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(all(feature = "async", any(test, 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(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; + + /// `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 @@ -27634,6 +27729,124 @@ 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"); + } + + /// 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. + #[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. @@ -27669,6 +27882,179 @@ 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 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() { + 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(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] { + 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)) + )); + + 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(); + 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" + ); + // 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(), + "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"); + 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(_))))); + assert!(!listed(), "a read behind the edge listed the track"); + 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 { @@ -27769,7 +28155,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 @@ -27779,7 +28165,12 @@ 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])); @@ -27908,14 +28299,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-net/src/model/track/demand.rs b/rs/moq-net/src/model/track/demand.rs index 08df6144503..44ce8e66c4a 100644 --- a/rs/moq-net/src/model/track/demand.rs +++ b/rs/moq-net/src/model/track/demand.rs @@ -139,6 +139,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 `max` each waits with and the @@ -560,6 +563,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-net/src/session.rs b/rs/moq-net/src/session.rs index 44c93da59e4..9604c213f70 100644 --- a/rs/moq-net/src/session.rs +++ b/rs/moq-net/src/session.rs @@ -1192,8 +1192,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 (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", diff --git a/rs/moq-relay/tests/integration/quic_sim.rs b/rs/moq-relay/tests/integration/quic_sim.rs index 91be8c5dc13..3809c5b2458 100644 --- a/rs/moq-relay/tests/integration/quic_sim.rs +++ b/rs/moq-relay/tests/integration/quic_sim.rs @@ -308,9 +308,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)); } @@ -319,14 +322,22 @@ 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. 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, -/// 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 - 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(&[""], &[], &[]); @@ -341,7 +352,11 @@ 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 as i64 - 128).expect("at most 256 tracks")), + ) .expect("track") }) .collect(); @@ -374,8 +389,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 { @@ -400,11 +417,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), @@ -424,7 +442,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;