diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index 673c08a48b..033db3420c 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -220,7 +220,7 @@ This is what lets a subscriber move a Track to a different publisher partway thr A Group can therefore be assembled from more than one publisher: each contributes a disjoint run of frames, and the subscriber concatenates them in index order. A partial Group is only ever delivered to a subscriber that asked for one, with FETCH or a Position Start. -A publisher that holds only the later frames of a Group a subscription covers names it in a [SUBSCRIBE_DROP](#subscribe-drop) rather than deliver the part it holds. +A relay that holds only the later frames of a Group a subscription covers fetches the earlier frames from upstream and delivers the Group whole; a publisher that can't obtain them names the Group in a [SUBSCRIBE_DROP](#subscribe-drop) rather than deliver the part it holds. One that holds its earlier frames, such as a relay whose upstream closed the Group, delivers them and closes the Group Stream without a GROUP_END. A Group is the unit of decodability: its earlier Frames may carry a keyframe or compression state the later Frames need. diff --git a/js/net/src/lite/copy_fill.test.ts b/js/net/src/lite/copy_fill.test.ts index eae8e3ea64..30c4a0e5c5 100644 --- a/js/net/src/lite/copy_fill.test.ts +++ b/js/net/src/lite/copy_fill.test.ts @@ -550,3 +550,67 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( } }, ); + +// A publisher whose cache holds group 2 from frame 3 only fetches the head from its track's +// handler and serves the group whole to a subscriber reading whole groups, as the Rust +// `position_group` does: a cache only makes things faster. A refused head drops the group. +test.each([Lite.ALPN_06, Lite.ALPN_07_WIP])("%s: a publisher fetches a headless group's head", async (alpn) => { + for (const refuse of [false, true]) { + const pair = createMockTransportPair(alpn); + const origin = new OriginProducer(); + const [client, server] = await Promise.all([ + connectSession({ url, transport: pair.client }), + acceptSession({ transport: pair.server, url, publish: origin.consume() }), + ]); + const broadcast = origin.route(Path.from("room")).broadcast; + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); + const tail = hooks.receiveGroup(track, { start: 2n, offset: 3 }); + for (const frame of [3, 4]) + tail.writeFrame({ payload: enc.encode(`c${frame}`), timestamp: Timestamp.fromMillis(2000) }); + tail.finish(); + write(track.createGroup(3n), 3n, "live"); + const requests = track.requests(); + void (async () => { + for (let fill = await requests.requestedFill(); fill; fill = await requests.requestedFill()) { + for (let key = fill.wanted(); key !== undefined; key = fill.wanted()) { + if (key !== 2n || refuse) { + fill.refuseGroups(key, key + 1n, new StreamError(StreamCode.NotFound)); + continue; + } + const group = defined(fill.accept(key)); + for (let frame = 0; frame < 5; frame++) + group.writeFrame({ payload: enc.encode(`c${frame}`), timestamp: Timestamp.fromMillis(2000) }); + group.finish(); + } + fill.close(); + } + })(); + const remote = wireOf(client).consume(Path.from("room")); + try { + const reader = remote.track("video").subscribe({ + ranges: [{ start: { time: 2n } }], + delay: { max: null }, + order: "ascending", + }); + const ordered = reader.ordered(); + const got: [bigint, string[]][] = []; + for (let group = await ordered.nextGroup(); group; group = await ordered.nextGroup()) { + const frames: string[] = []; + for (let frame = await group.readFrame(); frame; frame = await group.readFrame()) + frames.push(dec.decode(frame.payload)); + got.push([group.start, frames]); + if (group.start === 3n) break; + } + const head: [bigint, string[]][] = refuse ? [] : [[2n, ["c0", "c1", "c2", "c3", "c4"]]]; + expect(got).toEqual([...head, [3n, ["live 3"]]]); + reader.close(); + } finally { + remote.close(); + requests.close(); + broadcast.close(); + client.abort(); + server.abort(); + origin.close(); + } + } +}); diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index da9f002725..be0dff4f51 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -240,6 +240,8 @@ interface RunGroup { group: group.Consumer; /** Why to stop writing {@link group}, watched while it is served. */ givenUp: GivenUp; + /** The reader the subscription handed out, when {@link group} is a copy fetched in its place. */ + judged?: group.Consumer; /** How every frame is stamped, or undefined to send no timestamps. */ stamp: Stamp | undefined; @@ -1325,6 +1327,7 @@ export class Publisher { }, }); const finished = await this.#runTrack(track, stream.writer, controls, { + source: consumer, sub: msg.id, broadcast: msg.broadcast, stamp, @@ -1507,6 +1510,8 @@ export class Publisher { stream: Writer, controls: SubscriptionControls, serving: { + /** The track `track` reads, which fetches the frames a group's copy lacks. */ + source: track.Consumer; sub: bigint; broadcast: Path.Valid; stamp: Stamp | undefined; @@ -1523,7 +1528,7 @@ export class Publisher { initial: bigint; }, ): Promise { - const { sub, broadcast, stamp, publisher, compress, named, bounds, initial } = serving; + const { source, sub, broadcast, stamp, publisher, compress, named, bounds, initial } = serving; // What the wire was told of each key: served, or given up, and how. Kept in the // reader's own record, which its drops consult too. Undefined before lite-05. const record = named ? hooks.wire(track) : undefined; @@ -2052,12 +2057,15 @@ export class Publisher { // The FIN waits for every stream to finish or reset, including one that has not opened yet. // A stream reset to make room fails the group like any other reset, so it is dropped. const task = (async () => { - const writer = await this.#openGroup(options); - let failed: Error | undefined; + let failed = await this.#fetchHead(source, track, options); try { - failed = writer instanceof Error ? writer : await this.#serveGroup(writer, options); + if (!failed) { + const writer = await this.#openGroup(options); + failed = writer instanceof Error ? writer : await this.#serveGroup(writer, options); + } } finally { options.givenUp.close(); + options.judged?.close(); } if (failed && emitRange) { pendingDrops.push({ @@ -2562,6 +2570,49 @@ export class Publisher { } } + /** + * Swap a group whose copy lacks frames the subscription asked for for a copy fetched from + * that frame on, as the Rust `position_group` does: a cache only makes things faster, so + * a partial hit asks upstream for the rest. + * + * @returns The fetch's error, for SUBSCRIBE_DROP to name, when nothing upstream supplies them + * + * @internal + */ + async #fetchHead(source: track.Consumer, reader: track.Subscriber, options: RunGroup): Promise { + const held = options.group; + if (hooks.groupIndex(held) <= options.start) return undefined; + const asking = reader.subscription.peek(); + const left = new AbortController(); + const fetch: track.FetchGroupOptions & broadcast.FetchFrom = { + priority: asking?.priority, + maxDelay: asking?.delay?.max ?? undefined, + signal: left.signal, + frameStart: options.start, + }; + const fetched = source.fetchGroup(held.start, fetch).then( + (group) => group, + (err: unknown) => error(err), + ); + // The serving subscription's budget, or its end, gives up on the head too. + const result = await race([fetched, options.givenUp, options.unsubscribed]); + options.givenUp.close(); + if (result === undefined || result instanceof Error) { + left.abort(result ?? new Error("unsubscribed while fetching a group's head")); + void fetched.then((late) => { + if (!(late instanceof Error)) late.close(); + }); + held.close(); + return result ?? new Error("unsubscribed while fetching a group's head"); + } + // The copy serves under the subscription's live budget, which the reader it replaces still + // carries, not the fetch's: held open until the group is served. + options.group = result; + options.judged = held; + options.givenUp = new GivenUp(result, held); + return undefined; + } + /** * Serves one group on the stream {@link #openGroup} opened for it. * diff --git a/js/net/src/util/given_up.test.ts b/js/net/src/util/given_up.test.ts index 4191c2a7ab..88edb006c2 100644 --- a/js/net/src/util/given_up.test.ts +++ b/js/net/src/util/given_up.test.ts @@ -102,3 +102,17 @@ test("a closed watch hears no later verdict", async () => { expect(givenUp.peek()).toBeUndefined(); producer.finish(); }); + +test("a copy fetched in a reader's place is given up on that reader's budget, not its own", async () => { + const { producer, group: judged, expired } = served(); + const fetched = served(); + const givenUp = new GivenUp(fetched.group, judged); + const parked = givenUp.write(() => new Promise(() => {})); + await yieldNow(); + expired.set(true); + expect(((await parked) as StreamError).code).toBe(StreamCode.Old); + expect(fetched.watching()).toBe(0); + givenUp.close(); + producer.finish(); + fetched.producer.finish(); +}); diff --git a/js/net/src/util/given_up.ts b/js/net/src/util/given_up.ts index 1904d37fb7..2913fbb69d 100644 --- a/js/net/src/util/given_up.ts +++ b/js/net/src/util/given_up.ts @@ -1,11 +1,12 @@ import { type Dispose, type GetPromise, race } from "@moq/signals"; import type { Consumer as GroupConsumer } from "../group.ts"; -// Why to stop writing `group`: the subscription's budget gave it up, or it failed for good -// before it was read whole (evicted, or its copy aborted with no route to continue it). -function reason(group: GroupConsumer): Error | undefined { +// Why to stop writing `group`: the subscription's budget, judged on `judged`, gave it up, or it +// failed for good before it was read whole (evicted, or its copy aborted with no route to +// continue it). +function reason(group: GroupConsumer, judged: GroupConsumer): Error | undefined { const closed = group.closed.peek(); - return group.expired.peek() ?? (closed instanceof Error ? closed : undefined); + return judged.expired.peek() ?? (closed instanceof Error ? closed : undefined); } /** @@ -22,13 +23,19 @@ function reason(group: GroupConsumer): Error | undefined { */ export class GivenUp implements GetPromise { #group: GroupConsumer; + #judged: GroupConsumer; #stop?: Error; #listeners = new Set<(value: Error | undefined) => void>(); #unwatch: Dispose[]; - constructor(group: GroupConsumer) { + /** + * Watch `group`, judging its budget on `judged`: the reader the subscription handed out, when + * `group` is a copy fetched in its place, whose own budget is the fetch's. + */ + constructor(group: GroupConsumer, judged: GroupConsumer = group) { this.#group = group; - this.#unwatch = [group.expired.subscribe(() => this.#check()), group.closed.subscribe(() => this.#check())]; + this.#judged = judged; + this.#unwatch = [judged.expired.subscribe(() => this.#check()), group.closed.subscribe(() => this.#check())]; } /** @@ -88,7 +95,7 @@ export class GivenUp implements GetPromise { #check(): void { if (this.#stop) return; - const stop = reason(this.#group); + const stop = reason(this.#group, this.#judged); if (!stop) return; this.#stop = stop; this.close(); diff --git a/quest/m1/missing-head-asks-upstream.md b/quest/m1/missing-head-asks-upstream.md deleted file mode 100644 index 89d2090622..0000000000 --- a/quest/m1/missing-head-asks-upstream.md +++ /dev/null @@ -1,39 +0,0 @@ -# [M] A relay fetches a group's missing head instead of dropping it - -## Goal - -When a relay's copy holds only the later frames of a group a subscription -covers, as when its upstream subscription started at a Position, the relay -fetches the earlier frames from upstream and delivers the group whole. It -names the group in SUBSCRIBE_DROP only when upstream can't supply them. A -subscriber gets the same group through the relay, warm or cold, as it would -from the publisher. Rust and `@moq/net` match, and the moq-lite draft says so. - -## Plan - -Found by the 2026-11-20 audit of the subscription rules before the lite-07 -cut. A cache only makes things faster (root `AGENTS.md`), so a partial hit -asks upstream for the miss. The draft's Positions section says the opposite: -"A publisher that holds only the later frames of a Group a subscription -covers names it in a SUBSCRIBE_DROP rather than deliver the part it holds". -The Rust publisher does that. `position_group` (`rs/moq-net/src/lite/publisher.rs`) -finds no head, and its caller logs "skipping group with a missing head" and -drops the group with `NotFound` (test `a_missing_head_is_dropped_early`). -Check what `@moq/net`'s publisher does. - -- Recommended: the copy FETCHes the missing frames (`Frame Start` 0 through - the first frame it holds) through the group-fill path a miss already uses, - and the publisher serves the group once the head lands, within the - subscriber's budget. A failed or refused fetch falls back to the DROP. -- The draft's sentence becomes: a relay fetches the missing earlier frames - from upstream, and a publisher that can't obtain them names the group in a - SUBSCRIBE_DROP. A subscriber already handles both. -- A copy holding the earlier frames of a group its upstream closed short keeps - delivering them and closing without GROUP_END. Upstream has no more, so - that matches a direct read. - -Reproduce first: a relay whose first reader resumes at a Position partway -through a group, then a second reader whose range covers that group whole. - -Public API: none expected. Wire: none; the draft's Positions rule changes for -relays. diff --git a/quest/m2/time-addressing/range-table.md b/quest/m2/time-addressing/range-table.md index 6e8256f124..40e8bd1bb4 100644 --- a/quest/m2/time-addressing/range-table.md +++ b/quest/m2/time-addressing/range-table.md @@ -35,13 +35,11 @@ Recommended: - The relayed run uses the real copy path in each language, so a JS copy under a Rust origin is covered the way `just test relay-fill` already covers fills. - Drive time with the manual clocks both test suites already use. +- A copy holding only a group's later frames is a case too: the relay fetches the head and + delivers the group whole, or names it in SUBSCRIBE_DROP when upstream can't supply it. Public API: none. Wire: none; a divergence this finds is fixed under lite-07-wip before the cut. ## Required - [No relative anchors](/quest/m2/time-addressing/no-relative-anchors.md) - the range shapes this table pins - -## Related - -- [A relay fetches a group's missing head](/quest/m1/missing-head-asks-upstream.md) - a partial group a copy holds is another case for the table diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 068eaa8a12..c1c4c9a247 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -4839,20 +4839,19 @@ async fn recv_next(track: &mut track::Subscriber, emit_boundary: bool) -> Result /// at all. /// /// Frame bounds qualify the start and end group only; everything in between is served -/// whole. `None` means the group's head is missing and the subscriber never asked for a -/// partial group, so it must be skipped: a group is the unit of decodability, and only -/// the subscriber knows whether a partial one is any use to it. +/// whole. A copy missing frames asked for reads them from upstream, as a cache only makes +/// things faster. `None` means nothing upstream can supply them and the subscriber never +/// asked for a partial group, so it must be skipped: a group is the unit of decodability, +/// and only the subscriber knows whether a partial one is any use to it. fn position_group(group: group::Consumer, frames: &Frames) -> Option { if group.start < frames.floor { return None; } let expected = frames.start(group.start); - let end = frames.end(group.start).map_or(Bound::Unbounded, Bound::Included); - - // The start clamps up to the first frame the group still holds, so landing higher - // than asked means the frames below it are gone. - let group = group.with_range((Bound::Included(expected), end)); - (group.index() == expected).then_some(group) + let end = frames.end(group.start).and_then(|last| last.checked_add(1)); + group + .fetches_from(expected) + .then(|| group.with_end(end).fetching_from(expected)) } /// The frame bounds of a subscription, which the model leaves to the publisher: it reads @@ -5926,9 +5925,10 @@ impl TrackRun { return Poll::Ready(Ok(ControlFlow::Continue(()))); } let Some(group) = position_group(group, &self.frames) else { - // Its head is gone, and this subscriber didn't ask for a - // partial group. Skip it rather than open a stream that can - // only be reset; the next servable group resolves the start. + // Its head is gone with nothing upstream to fetch it from, and this + // subscriber didn't ask for a partial group. Skip it rather than open + // a stream that can only be reset; the next servable group resolves + // the start. tracing::debug!(subscribe = self.ctx.id, track = %self.ctx.track_name, key, "skipping group with a missing head"); let hole = Hole::drop(StreamError::NotFound); match &mut self.start { @@ -10179,6 +10179,170 @@ mod serve_group_test { assert_eq!(drops(&mut writer, &log, version).await, [(1, 1)]); } + /// A group missing its head on a track whose handler serves history is fetched from + /// that handler and served whole, as the source would: a cache only makes things + /// faster. Refused, it is named in SUBSCRIBE_DROP. + #[kio::test] + async fn a_missing_head_is_fetched() { + for refuse in [false, true] { + let version = Version::Lite07; + let mut track = track::Producer::new( + Arc::new(broadcast::Info::default()), + "test", + crate::track::Info::timed(), + ); + let dynamic = track.requests(); + let subscriber = track.subscribe( + track::Subscription::default().with_delay(track::Delay::default().with_max(Duration::from_secs(60))), + ); + let session = SinkSession::new(Log::default()); + let streams = session.log.clone(); + let (mut run, mut writer, log) = lite_run(version, session, subscriber); + write_group(&mut track, 0, 0); + while run.poll_step(&mut writer, &kio::Waiter::noop()).is_ready() {} + + let mut headless = track.create_group(group::Info { start: 1 }).unwrap(); + headless.start_at(1).unwrap(); + headless + .write_frame(Timestamp::from_millis(1).unwrap(), b"tail".as_slice()) + .unwrap(); + headless.finish().unwrap(); + while run.poll_step(&mut writer, &kio::Waiter::noop()).is_ready() {} + + let fill = dynamic.requested_fill_group().now_or_never().expect("a fill").unwrap(); + assert_eq!((fill.key(), fill.frame_start()), (1, 0), "asks for the head"); + match refuse { + false => { + let mut whole = fill.accept(crate::track::Info::timed()).unwrap().unwrap(); + for payload in [b"head", b"tail"] { + whole + .write_frame(Timestamp::from_millis(1).unwrap(), payload.as_slice()) + .unwrap(); + } + whole.finish().unwrap(); + } + true => drop(fill), + } + drop(dynamic); + for _ in 0..8 { + while run.poll_step(&mut writer, &kio::Waiter::noop()).is_ready() {} + kio::clock::sim::advance(Duration::from_millis(1)).await; + } + + let stream = group_stream(&streams, version, 1); + match refuse { + false => { + let (frame_start, frames) = stream.expect("group 1 is served"); + assert_eq!(frame_start, 0, "served from its first frame"); + let head = frames.windows(4).position(|w| w == b"head").expect("the head"); + let tail = frames.windows(4).position(|w| w == b"tail").expect("the tail"); + assert!(head < tail); + assert_eq!(drops(&mut writer, &log, version).await, []); + } + true => assert_eq!(drops(&mut writer, &log, version).await, [(1, 1)]), + } + } + } + + /// A relay whose route copy holds only the later frames of a group fetches the rest from + /// that route and serves the group whole, as the publisher would. + #[kio::test] + async fn a_relay_fetches_a_missing_head_from_its_route() { + use crate::model::ProduceTest; + let version = Version::Lite07; + let relay = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); + let route = relay.forward("room", crate::origin::RouteInfo::new()).unwrap(); + let pending = relay.consume().request("room", None); + let upstream = broadcast::Info::new().produce(); + let mut dynamic = upstream.requests(); + let request = loop { + if let Poll::Ready(Some(request)) = route.poll_requested(&kio::Waiter::noop()) { + break request; + } + kio::clock::sim::advance(Duration::from_millis(1)).await; + }; + request.serve(&upstream); + let resolved = pending.await.unwrap(); + + let track = resolved.track("test").unwrap(); + let subscribing = kio::clock::sim::spawn(async move { + track + .subscribe( + track::Subscription::default() + .with_delay(track::Delay::default().with_max(Duration::from_secs(60))), + ) + .await + }); + let copy = dynamic + .requested_track() + .await + .unwrap() + .accept(crate::track::Info::timed()); + let fetches = copy.requests(); + let mut headless = copy.create_group(group::Info { start: 0 }).unwrap(); + headless.start_at(1).unwrap(); + headless + .write_frame(Timestamp::from_millis(0).unwrap(), b"tail".as_slice()) + .unwrap(); + headless.finish().unwrap(); + let subscriber = subscribing.await.unwrap().unwrap(); + + let session = SinkSession::new(Log::default()); + let streams = session.log.clone(); + let (mut run, mut writer, log) = lite_run(version, session, subscriber); + let serving = kio::clock::sim::spawn(async move { + let fill = fetches.requested_fill_group().await.unwrap(); + assert_eq!((fill.key(), fill.frame_start()), (0, 0), "asks for the head"); + let mut whole = fill.accept(crate::track::Info::timed()).unwrap().unwrap(); + for payload in [b"head", b"tail"] { + whole + .write_frame(Timestamp::from_millis(0).unwrap(), payload.as_slice()) + .unwrap(); + } + whole.finish().unwrap(); + fetches + }); + for _ in 0..16 { + while run.poll_step(&mut writer, &kio::Waiter::noop()).is_ready() {} + kio::clock::sim::advance(Duration::from_millis(1)).await; + } + let _fetches = kio::clock::timeout(Duration::from_secs(1), serving) + .await + .expect("the relay asks its route for the head") + .unwrap(); + for _ in 0..16 { + while run.poll_step(&mut writer, &kio::Waiter::noop()).is_ready() {} + kio::clock::sim::advance(Duration::from_millis(1)).await; + } + + let (frame_start, frames) = group_stream(&streams, version, 0).expect("group 0 is served"); + assert_eq!(frame_start, 0, "served from its first frame"); + let head = frames.windows(4).position(|w| w == b"head").expect("the head"); + let tail = frames.windows(4).position(|w| w == b"tail").expect("the tail"); + assert!(head < tail); + assert_eq!(drops(&mut writer, &log, version).await, []); + } + + /// Group `key`'s Group Stream on `log`'s session, as its Frame Start and the bytes after + /// its GROUP. + fn group_stream(log: &Log, version: Version, key: u64) -> Option<(u64, Vec)> { + let mut streams = std::collections::BTreeMap::<_, Vec>::new(); + for (id, sent) in log.trail() { + if let Sent::Write(bytes) = sent { + streams.entry(id).or_default().extend(bytes); + } + } + streams.into_values().find_map(|bytes| { + let mut buf = bytes.as_slice(); + let group = crate::coding::decode_buf(&mut buf, version, |r, v| { + lite::DataType::decode(r, v)?; + lite::Group::decode(r, v) + }) + .unwrap(); + (group.key == key).then(|| (group.frame_start, buf.to_vec())) + }) + } + /// A long-budget reader warms the relay without changing a live reader's resolved start. #[kio::test] async fn cold_and_warm_relays_resolve_the_same_start() { diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 40c06bf6cc..de4ddac0fc 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -4617,19 +4617,46 @@ impl Consumer { } } - /// Whether the copy read shed the frame read next, rather than failing or never holding - /// it. Ordinals stand for frames only on a dense group, so only one boards a flight. A - /// plain read of a compressed copy also loses a frame its inflated copy shed, which the - /// decoder, already past it, cannot inflate again. + /// Whether the copy read lacks the frame read next, having shed it or started past it, + /// rather than failing. Ordinals stand for frames only on a dense group, so only one + /// boards a flight. A plain read of a compressed copy also loses a frame its inflated copy + /// shed, which the decoder, already past it, cannot inflate again. A group handed out + /// from a front recovers a frame its copy started past from a route instead. fn shed_next(&self) -> bool { let state = self.cursor.state.read(); let index = self.cursor.index; - if state.outcome.error().is_some() || state.sparse() || index < state.offset { + if state.outcome.error().is_some() || state.sparse() { return false; } + if index < state.offset { + return self.recover().is_none(); + } index < state.held() || state.plain(self.cursor.raw).is_some_and(|plain| plain.shed_past(index)) } + /// Whether reading from frame `index` can fetch the frames below where this copy starts: + /// a front recovers them from a route, and a track's [`track::Requests`] handlers serve + /// them as a flight. A failed or refused fetch fails the read. + pub(crate) fn fetches_from(&self, index: u64) -> bool { + let state = self.cursor.state.read(); + if index >= state.offset as u64 { + return true; + } + if state.outcome.error().is_some() || state.sparse() { + return false; + } + drop(state); + self.recover().is_some() || self.cursor.cache.track().is_some_and(|track| track::flies(&track)) + } + + /// Start reads at frame `index`, even below the first frame this copy holds, which a read + /// then fetches (see [`Self::fetches_from`]). A start below the cursor is ignored. + #[cfg(feature = "async")] + pub(crate) fn fetching_from(mut self, index: u64) -> Self { + self.skip_to(index); + self + } + /// Read the same frames from `copy` from here on, keeping this reader's place and cap. fn adopt_copy(&mut self, copy: Consumer) { let (index, end, raw) = (self.cursor.index, self.cursor.end, self.cursor.raw); @@ -4857,7 +4884,13 @@ impl Consumer { let (raw, end) = (self.cursor.raw, self.cursor.end); // Frames already prefetched are this cursor's whatever the group sheds since, so // only the first one past them can be evicted. - let unread = index + self.cursor.prefetch.buffered().0 as usize; + let mut unread = index + self.cursor.prefetch.buffered().0 as usize; + // The frames below where this copy starts come from a flight, and the group ends + // where this copy does. + let offset = self.cursor.state.read().offset; + if unread < offset && self.recover().is_none() && self.fetches_from(unread as u64) { + unread = offset; + } let res = self .cursor .poll(waiter, |state| state.poll_end(index, unread, raw, end)) diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 8ac17d86bd..e9db38f5ba 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -4230,6 +4230,11 @@ pub(super) fn board(track: &kio::Producer, reader: &group::Consumer) })) } +/// Whether `track`'s [`Requests`] handlers can serve a flight, which [`board`] asks of them. +pub(super) fn flies(track: &kio::Producer) -> bool { + track.read().fills.read().has_handlers() +} + /// The copy `reader`, riding a flight, hands over to: one further along that admits it, /// and whether that is a flight. See [`TrackState::ride`]. pub(super) fn hand_over(