Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
9c5b16c
quest: a session's live-edge budget never sheds a frame a paced reade…
kixelated Nov 22, 2026
ed8afad
wip(net): a session past its live-edge budget sheds by priority, take…
kixelated Nov 23, 2026
a09e34f
fix(net): a session past its live-edge budget sheds by priority, take…
kixelated Nov 23, 2026
e1c8e23
chore(net): format and drop an unused mut
kixelated Nov 23, 2026
709dc27
fix(net): a live-edge move and its queue entry update under one lock;…
kixelated Nov 23, 2026
663125d
fix(net): leave a compressed edge's inflated copies to the whole-edge…
kixelated Nov 23, 2026
0cf4be4
fix(net): rank live edges without the async-only priority module
kixelated Nov 23, 2026
437f610
Merge remote-tracking branch 'origin/main' into quest-plan/live-edge-…
kixelated Nov 25, 2026
60611f3
fix(net): the taken-frame shed keeps a copy no reader has opened yet
kixelated Nov 25, 2026
2241a8f
fix(net): reclaim visits only edges with taken frames, and inflates n…
kixelated Nov 25, 2026
1df6486
fix(net): serialize reclaims, list only live-edge reads, relist after…
kixelated Nov 25, 2026
ece92e9
fix(net): defer reclaim wakes, list only slot copies' reads, list und…
kixelated Nov 25, 2026
d2a2c19
style: rustfmt
kixelated Nov 25, 2026
731e006
fix(net): gate the reclaim-lock probe to the async tests using it
kixelated Nov 25, 2026
91ee9c5
quest: defer the displaced-decoder relist, reproduce m4 over whole tr…
kixelated Nov 25, 2026
79e4f31
fix(net): bound a reclaim's whole-edge pass to the edges queued when …
kixelated Nov 25, 2026
be24ece
fix(net): a reclaim's whole-edge pass skips edges that moved after it…
kixelated Nov 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions doc/bin/relay/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion doc/lib/rs/moq-net.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
18 changes: 18 additions & 0 deletions quest/m1/live-edge-inflated-taken.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 9 additions & 3 deletions quest/m4/unsealed-frame-credit.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion rs/justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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::/)'
Expand Down
2 changes: 1 addition & 1 deletion rs/kio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down
36 changes: 33 additions & 3 deletions rs/kio/src/waiter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,17 +375,35 @@ impl WaiterList {
struct Held {
depth: usize,
wakers: Vec<Weak<Waker>>,
// Wakes made by [`wake`], which owns its waker rather than a list's registration.
owned: Vec<Waker>,
}

thread_local! {
static HELD: std::cell::RefCell<Held> = const {
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
Expand All @@ -408,20 +426,23 @@ 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();
// Outside the borrow: a waker may poll inline and open a hold of its own.
for waker in wakers.into_iter().filter_map(|w| w.upgrade()) {
waker.wake_by_ref();
}
for waker in owned {
waker.wake();
}
}
}

Expand Down Expand Up @@ -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]
Expand Down
7 changes: 6 additions & 1 deletion rs/moq-net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -248,5 +248,10 @@ name = "canonical"
harness = false
required-features = ["fuzz"]

[[bench]]
name = "edges"
harness = false
required-features = ["fuzz"]

[lints]
workspace = true
38 changes: 38 additions & 0 deletions rs/moq-net/benches/edges.rs
Original file line number Diff line number Diff line change
@@ -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);
15 changes: 15 additions & 0 deletions rs/moq-net/src/fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>.rs` shim.
pub const TARGETS: &[(&str, Target)] = &[
("lite", lite_wire),
Expand Down
Loading