diff --git a/bench/README.md b/bench/README.md index eda3b0b5eaa..81ac8fb193d 100644 --- a/bench/README.md +++ b/bench/README.md @@ -376,6 +376,12 @@ and group setup stay outside drift timing; each parked read checks its live payload. `ledger` uses one fixture against every checkout's internal ledger, sweeping ascending, descending, shuffled, and rolling-expiration arrivals over the retained gap count. It includes each arrival's expiration and coverage checks. +The drift sweep includes untimed controls and timed groups with decode-order +B-frames, independently varying publisher and reader counts and retained history. +Its `time_mode` column is 0 for untimed, 1 for millisecond timestamps, and 2 +for mixed millisecond/microsecond timestamps, which exercise exact cross-scale +comparison. + The browser smoke lane preserves one measured round of all three fixtures, and drift and ledger also run in the nightly JS benchmark leg. Timing is observational, with the A/A spread showing the host's noise floor. diff --git a/bench/browser/micro.ts b/bench/browser/micro.ts index d268a324e88..1bf4d138034 100644 --- a/bench/browser/micro.ts +++ b/bench/browser/micro.ts @@ -109,7 +109,8 @@ try { rows.set(variant, []); await pages.get(variant)?.evaluate("globalThis.measure()"); const measured = rows.get(variant); - if (measured?.length !== (benchmark === "frames" ? 26 : 12)) throw new Error(`incomplete rows: ${variant}`); + if (measured?.length !== (benchmark === "frames" ? 26 : benchmark === "drift" ? 36 : 12)) + throw new Error(`incomplete rows: ${variant}`); samples.push({ round, variant, rows: measured }); await Bun.write( values.out, diff --git a/js/net/bench/drift.ts b/js/net/bench/drift.ts index a37dfdcce29..47c95ba7a82 100644 --- a/js/net/bench/drift.ts +++ b/js/net/bench/drift.ts @@ -1,63 +1,106 @@ /** Sweep publishers, readers, and retained history for a parked frame read's drift check. */ import { Manual, Milli } from "@moq/clock"; -import { type Group, Track } from "@moq/net"; +import { type Group, Time, Track } from "@moq/net"; /** Read live frames after a retained window, checking every delivered payload. */ export async function run(): Promise { const clock = new Manual(); const installed = clock.install(); const payload = new Uint8Array([7]); + const iterations = 2000; + const warmup = 20; + const offsets = [0, 80, 40]; try { - console.log("retained,publishers,readers,ns_per_frame"); + // The same reordered-PTS verdict runs here in Chromium before timing any work. + const check = new Track.Producer("reordered").accept({ timescale: Time.Timescale.MILLI }); + const reader = check.subscribe({ maxDelay: Milli(80) }); + try { + for (const timestamps of [[0], [100], [150, 200, 160]]) { + const group = check.appendGroup(); + for (const ms of timestamps) group.writeFrame({ payload, timestamp: Time.Timestamp.fromMillis(ms) }); + group.finish(); + } + if ((await reader.recvGroup())?.sequence !== 1) throw new Error("B-frame tail rewound the drift edge"); + } finally { + reader.close(); + check.finish(); + check.close(); + } + console.log("time_mode,retained,publishers,readers,ns_per_frame"); for (const retained of [1, 64, 1024]) for (const publishers of [1, 4]) - for (const readers of [1, 8]) { - const tracks = Array.from({ length: publishers }, (_, i) => new Track.Producer(`p${i}`).accept({})); - const sources: Group.Producer[] = []; - const consumers: Group.Consumer[] = []; - try { - for (const track of tracks) { - for (let sequence = 0; sequence < retained; sequence++) { - const group = track.appendGroup(); - group.writeFrame({ payload }); - group.finish(); - } - const subscribers = Array.from({ length: readers }, () => - track.subscribe({ maxDelay: Milli(60_000) }), - ); - // Drain replay through the normal ordered cursor while retaining its timeline. - const ordered = subscribers.map((sub) => sub.ordered()); - for (let sequence = 0; sequence < retained; sequence++) + for (const readers of [1, 8]) + for (const mode of [0, 1, 2]) { + const stamp = (ms: number, index: number) => + mode === 0 + ? undefined + : mode === 2 && index % 2 !== 0 + ? Time.Timestamp.fromMicros(ms * 1000) + : Time.Timestamp.fromMillis(ms); + const tracks = Array.from({ length: publishers }, (_, i) => + new Track.Producer(`p${i}`).accept(mode !== 0 ? { timescale: Time.Timescale.MILLI } : {}), + ); + const sources: Group.Producer[] = []; + const consumers: Group.Consumer[] = []; + try { + for (const track of tracks) { + for (let sequence = 0; sequence < retained; sequence++) { + const group = track.appendGroup(); + group.writeFrame({ + payload, + timestamp: stamp(sequence * 100, sequence), + }); + group.finish(); + } + const subscribers = Array.from({ length: readers }, () => + track.subscribe({ + maxDelay: Milli( + (retained + Math.ceil((iterations + warmup) / offsets.length) + 1) * 100, + ), + }), + ); + // Drain replay through the normal ordered cursor while retaining its timeline. + const ordered = subscribers.map((sub) => sub.ordered()); + for (let sequence = 0; sequence < retained; sequence++) + for (const reader of ordered) { + const group = await reader.nextGroup(); + if (group?.sequence !== sequence) throw new Error("history missing"); + await group.readFrame(); + } + sources.push(track.appendGroup()); for (const reader of ordered) { const group = await reader.nextGroup(); - if (group?.sequence !== sequence) throw new Error("history missing"); - await group.readFrame(); + if (!group) throw new Error("live group missing"); + consumers.push(group); } - sources.push(track.appendGroup()); - for (const reader of ordered) { - const group = await reader.nextGroup(); - if (!group) throw new Error("live group missing"); - consumers.push(group); } + let start = 0; + for (let iteration = 0; iteration < iterations + warmup; iteration++) { + if (iteration === warmup) start = performance.now(); + const pending = consumers.map((consumer) => consumer.readFrame()); + const timestamp = stamp( + retained * 100 + + Math.floor(iteration / offsets.length) * 100 + + offsets[iteration % offsets.length], + iteration, + ); + for (const source of sources) source.writeFrame({ payload, timestamp }); + for (const frame of await Promise.all(pending)) + if ( + frame?.payload[0] !== 7 || + frame.timestamp?.asMillis() !== timestamp?.asMillis() + ) + throw new Error("frame missing or reordered"); + } + const elapsed = performance.now() - start; + console.log( + `${mode},${retained},${publishers},${readers},${((elapsed * 1e6) / (iterations * publishers * readers)).toFixed(0)}`, + ); + } finally { + for (const track of tracks) track.finish(); + for (const track of tracks) track.close(); } - const iterations = 2000; - let start = 0; - for (let iteration = 0; iteration < iterations + 20; iteration++) { - if (iteration === 20) start = performance.now(); - const pending = consumers.map((consumer) => consumer.readFrame()); - for (const source of sources) source.writeFrame({ payload }); - for (const frame of await Promise.all(pending)) - if (frame?.payload[0] !== 7) throw new Error("frame missing"); - } - const elapsed = performance.now() - start; - console.log( - `${retained},${publishers},${readers},${((elapsed * 1e6) / (iterations * publishers * readers)).toFixed(0)}`, - ); - } finally { - for (const track of tracks) track.finish(); - for (const track of tracks) track.close(); } - } } finally { installed.close(); } diff --git a/js/net/src/group.test.ts b/js/net/src/group.test.ts index f67d874767a..62faf87a33b 100644 --- a/js/net/src/group.test.ts +++ b/js/net/src/group.test.ts @@ -1,4 +1,5 @@ import { expect, test } from "bun:test"; +import { Manual } from "@moq/clock"; import { Signal } from "@moq/signals"; import { FrameTooLarge, GroupTooLarge, StreamCode, StreamError } from "./error.ts"; import { MAX_GROUP_CACHE_BYTES, MAX_GROUP_FRAMES, Producer } from "./group.ts"; @@ -8,6 +9,47 @@ import { Timestamp } from "./time.ts"; const dec = new TextDecoder(); +test("reordered frames keep the highest group PTS in live and later mirrors", () => { + const installed = new Manual().install(); + try { + const producer = new Producer(0); + const shared = producer.consume(); + const live = producer.mirror(); + for (const timestamp of [Timestamp.fromMillis(0), Timestamp.fromMicros(80_000), Timestamp.fromMillis(40)]) + producer.writeFrame({ payload: new Uint8Array([1]), timestamp }); + expect(hooks.groupTimestamp(shared)?.asMillis()).toBe(0); + expect(hooks.groupLatest(shared)?.asMillis()).toBe(80); + expect(hooks.groupLatest(live)?.asMillis()).toBe(80); + // A later mirror only replays the remaining B-frame, but keeps the known high PTS. + shared.tryReadFrame(); + shared.tryReadFrame(); + const later = producer.mirror(); + expect(hooks.groupLatest(later)?.asMillis()).toBe(80); + expect(later.tryReadFrame()?.timestamp?.asMillis()).toBe(40); + for (const reader of [shared, live, later]) reader.close(); + producer.finish(); + } finally { + installed.close(); + } +}); + +test("zero group PTS keeps its scale and untimed groups stay unstamped", () => { + const installed = new Manual().install(); + try { + for (const timestamp of [undefined, Timestamp.fromMicros(0)]) { + const producer = new Producer(0); + const consumer = producer.consume(); + expect(hooks.groupLatest(consumer)).toBeUndefined(); + producer.writeFrame({ payload: new Uint8Array(), timestamp }); + expect(hooks.groupLatest(consumer)).toBe(timestamp); + consumer.close(); + producer.finish(); + } + } finally { + installed.close(); + } +}); + test("used reflects mirror demand and unused resolves when the last reader leaves", async () => { const producer = new Producer(0); diff --git a/js/net/src/group.ts b/js/net/src/group.ts index 4e04be14278..88efe70291b 100644 --- a/js/net/src/group.ts +++ b/js/net/src/group.ts @@ -78,7 +78,7 @@ class GroupState { // The first frame's timestamp, retained after reads. Media time only: an untimed group // never has one, so it says nothing about whether a frame was written. timestamp?: Timestamp; - // The newest frame's timestamp: where a reader that has taken every frame sits. + // The highest frame PTS, including when the decode-order tail presents earlier. latest?: Timestamp; // Accepted below the track's eviction watermark, where nothing proves where it starts, // so this mirror drives no media-time expiry. @@ -104,7 +104,8 @@ function appendFrame(state: GroupState, frame: Frame) { if (state.closed.peek() !== undefined) throw new Error("group is closed"); state.timestamp ??= frame.timestamp; - state.latest = frame.timestamp; + if (frame.timestamp === undefined) state.latest = undefined; + else if (state.latest === undefined || state.latest.isBefore(frame.timestamp)) state.latest = frame.timestamp; state.cacheBytes += stored(frame)?.payload.length ?? frame.payload.byteLength; state.frames.mutate((frames) => { frames.push(frame); diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index a00b70088e4..9632346f9fc 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -582,6 +582,31 @@ test("nextGroup returns buffered groups in sequence", async () => { expect((await track.nextGroup())?.sequence).toBe(5); }); +test.each([false, true])("a reordered tail keeps the group PTS drift verdict (B-frame: %s)", async (reordered) => { + const clock = manualTime(0); + try { + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI }); + const subscriber = producer.subscribe({ maxDelay: Milli(80) }); + for (const ms of [0, 100]) { + const group = producer.appendGroup(); + group.writeFrame({ payload: new Uint8Array(), timestamp: Timestamp.fromMillis(ms) }); + group.finish(); + } + const edge = producer.appendGroup(); + for (const ms of [150, 200]) + edge.writeFrame({ payload: new Uint8Array(), timestamp: Timestamp.fromMillis(ms) }); + if (reordered) edge.writeFrame({ payload: new Uint8Array(), timestamp: Timestamp.fromMillis(160) }); + edge.finish(); + // Group 0 reaches 100ms and is 100ms behind the highest PTS; group 1 reaches 150ms. + expect((await subscriber.recvGroup())?.sequence).toBe(1); + subscriber.close(); + producer.finish(); + producer.close(); + } finally { + clock.installed.close(); + } +}); + // A group's age is where its content *ends*, not where it began. A long group whose tail // is level with the live edge still owes the reader every frame in it, so judging it by // its first timestamp would discard exactly the group being filled. diff --git a/quest/m1/README.md b/quest/m1/README.md index fe80cc5833f..c546bfcd928 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -114,7 +114,6 @@ surface and zero-copy texture import, land before the cut. - [Resume checked against a model](/quest/m1/resume-model-test.md) - a randomized test checks every resumed reader against a one-track reference model in Rust and JS, and passes before the cut - [Address groups by timestamp](/quest/m1/time-addressing/README.md) - group start timestamps replace sequence numbers in the moq-net API and lite-07 wire, while old subscribers, old publishers, and published JS clients keep working -- [A group ends at its highest PTS](/quest/m1/group-end-pts.md) - a B-frame tail no longer understates a group's end, in Rust and JS - [Release audit findings](/quest/m1/release-audit/README.md) - resolve newly identified resource, parser, playback, and interoperability risks before the cut - [Pre-cut audit findings](/quest/m1/cut-audit/README.md) - fix the crashes, hostile-input costs, and correctness bugs the 2026-10-24 audit of main found - [Cancelled moq-transport requests stop](/quest/m1/ietf-request-cancel.md) - a cancelled request releases its state even when the peer withholds credit diff --git a/quest/m1/group-end-pts.md b/quest/m1/group-end-pts.md deleted file mode 100644 index 46055b2520e..00000000000 --- a/quest/m1/group-end-pts.md +++ /dev/null @@ -1,21 +0,0 @@ -# [XS] A group ends at its highest PTS - -## Goal - -A group's end in presentation time is the highest PTS among its frames, not -its newest frame's, in Rust and `@moq/net`, so a group whose decode-order tail -holds B-frames is not judged stale early. - -## Plan - -Rust overwrites the group's `latest` with each new frame's timestamp -(`rs/moq-net/src/model/group.rs`, `Timeline::Timed` in `stamp` and on -adoption), and so does JS (`js/net/src/group.ts`, `state.latest`). Keep the -maximum instead, and test a group written in decode order with a B-frame -last against a drift budget. - -Public API: none. Wire: none. - -## Related - -- [Rust groups by start](/quest/m1/time-addressing/model.md) - group ends become explicit, but a group without GROUP_END still ends at its highest PTS diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 419a7f5d103..c9816d61d3f 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -69,8 +69,7 @@ impl Info { /// Create a producer for this group on a millisecond track. /// /// Test-only: real groups are created via [`track::Producer`], which - /// supplies the parent track's [`track::Info`]. This helper exists for in-crate - /// tests that don't exercise timestamps. + /// supplies the parent track's [`track::Info`]. #[cfg(test)] pub(crate) fn produce(self) -> Producer { Producer::new( @@ -538,7 +537,7 @@ enum Timeline { Empty, /// The track is untimed, so the group has no place in media time. Untimed, - /// `start` is the first frame's timestamp, never revised. `latest` is the newest + /// `start` is the first frame's timestamp, never revised. `latest` is the highest /// frame's: the group's presentation end so far, which a reader that has taken /// every frame sits at and a drift budget measures it against. Timed { start: Timestamp, latest: Timestamp }, @@ -793,11 +792,14 @@ impl GroupState { } /// Record a frame's place in presentation time: the first frame starts the group, - /// and each later one extends a timed group's end. Every frame matches its track + /// and later frames can extend a timed group's end. Every frame matches its track /// ([`on_track`]), so a group never mixes the two. fn stamp(&mut self, timestamp: Option) { self.timeline = match (self.timeline, timestamp) { - (Timeline::Timed { start, .. }, Some(latest)) => Timeline::Timed { start, latest }, + (Timeline::Timed { start, latest }, Some(timestamp)) => Timeline::Timed { + start, + latest: latest.max(timestamp), + }, (_, Some(start)) => Timeline::Timed { start, latest: start }, (_, None) => Timeline::Untimed, }; @@ -1381,7 +1383,7 @@ impl Producer { let size = frame.payload.len() as u64; state.cache += size; state.stamp(frame.timestamp); - latest = frame.timestamp; + latest = latest.max(frame.timestamp); let slots = state.push(Entry::plain(frame.into(), inflated)); now = state.charge.add(size + slots); } @@ -1797,15 +1799,15 @@ impl Handle { state.offset = head.start; state.cache += payload; let start = entries.iter().find_map(|entry| entry.frame.timestamp); + let head_latest = entries.iter().filter_map(|entry| entry.frame.timestamp).max(); state.timeline = match (state.timeline, start) { - (Timeline::Timed { latest, .. }, Some(start)) => Timeline::Timed { start, latest }, + (Timeline::Timed { latest, .. }, Some(start)) => Timeline::Timed { + start, + latest: latest.max(head_latest.unwrap_or(start)), + }, (Timeline::Empty, Some(start)) => Timeline::Timed { start, - latest: entries - .iter() - .rev() - .find_map(|entry| entry.frame.timestamp) - .unwrap_or(start), + latest: head_latest.unwrap_or(start), }, (Timeline::Empty, None) => Timeline::Untimed, (timeline, _) => timeline, @@ -1820,6 +1822,9 @@ impl Handle { drop(state); self.start(None); self.cache.settle(now); + if let Some(latest) = head_latest { + self.cache.wakes().presented(latest); + } } /// One past the index of the last frame written (completed or in-flight), which is @@ -2036,14 +2041,10 @@ impl Handle { } } - /// Where the group ends in presentation time: its newest timed frame's timestamp, or - /// `None` while no frame has been opened or when the group is untimed. + /// Highest PTS among this group's timed frames, or `None` while it is empty or untimed. /// - /// This is what a drift budget measures an untouched group against. A group is not - /// late because it *started* long ago: a two-second group whose tail is level with - /// the live edge still has content nobody has read. Only once its newest frame has - /// fallen behind is there nothing left worth delivering. Grows as the group does, so - /// a group still receiving frames stays fresh and a stalled one ages in place. + /// The newest servable group's highest PTS drives presentation-time drift. + /// Decode-order B-frames cannot move that edge backwards. pub(super) fn latest(&self) -> Option { let state = self.state.read(); match state.timeline { @@ -3396,6 +3397,90 @@ mod test { #[cfg(feature = "async")] use futures::FutureExt; + #[test] + fn reordered_frames_keep_the_highest_group_pts() { + for mode in 0..3 { + let mut group = Info { sequence: 0 }.produce(); + let timestamps = [0, 80, 40].map(|ms| Timestamp::from_millis(ms).unwrap()); + if mode == 1 { + let mut frames = frame::Buffer::<3>::new(); + for timestamp in timestamps { + frames.push(Frame::new(timestamp, Bytes::new())).unwrap(); + } + group.write_frames(&mut frames).unwrap(); + } else { + for timestamp in timestamps { + if mode == 0 { + group.write_frame(timestamp, Bytes::new()).unwrap(); + } else { + let frame = group + .create_frame(frame::Info { + size: 0, + timestamp: Some(timestamp), + }) + .unwrap(); + group = frame.finish().unwrap(); + } + } + } + assert_eq!(group.handle.timestamp(), Some(timestamps[0]), "mode {mode}"); + assert_eq!(group.handle.latest(), Some(timestamps[1]), "mode {mode}"); + group.finish().unwrap(); + } + } + + #[test] + fn adopted_heads_keep_the_highest_pts_beside_the_tail() { + let head = Head { + start: 0, + first_object: true, + entries: [0, 80, 40] + .into_iter() + .map(|ms| Entry::plain(Frame::new(Timestamp::from_millis(ms).unwrap(), Bytes::new()).into(), 0)) + .collect(), + compressed: false, + }; + for tail in [None, Some(20), Some(120)] { + let mut group = Info { sequence: 0 }.produce(); + group.start_at(3).unwrap(); + if let Some(ms) = tail { + group + .write_frame(Timestamp::from_millis(ms).unwrap(), Bytes::new()) + .unwrap(); + } + group.handle.adopt_head(&head); + let Timeline::Timed { start, latest } = group.handle.state.read().timeline else { + panic!("adopted timestamps are timed") + }; + assert_eq!(start, Timestamp::from_millis(0).unwrap()); + assert_eq!( + latest, + Timestamp::from_millis(tail.unwrap_or(0).max(80)).unwrap(), + "tail {tail:?}" + ); + group.finish().unwrap(); + } + } + + #[test] + fn a_zero_group_pts_keeps_its_track_scale_and_untimed_stays_unstamped() { + let mut timed = Producer::new( + Info { sequence: 0 }, + track::Info::default().with_timescale(Timescale::MICRO), + Default::default(), + ); + timed + .write_frame(Timestamp::from_micros(0).unwrap(), Bytes::new()) + .unwrap(); + assert_eq!(timed.handle.latest(), Some(Timestamp::from_micros(0).unwrap())); + timed.finish().unwrap(); + let mut untimed = Info { sequence: 0 }.produce_untimed(); + assert_eq!(untimed.handle.latest(), None); + untimed.write_frame(None, Bytes::new()).unwrap(); + assert_eq!(untimed.handle.latest(), None); + untimed.finish().unwrap(); + } + /// Fields sit beside the frames only from the first fielded one, so every read path /// must line them up by index across plain frames and prefetch batches. #[test] diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 2dd189c59d7..e2571e368e9 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -10974,6 +10974,84 @@ mod test { ); } + /// A batch must notify expiry at its highest PTS even when its decode-order tail is lower. + #[test] + #[cfg(feature = "async")] + fn a_reordered_batch_wakes_the_group_pts_drift_deadline() { + let mut producer = track_producer("test", Info::timed()); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(10))); + let mut head = producer.append_group().unwrap(); + head.write_frame(Timestamp::from_millis(0).unwrap(), bytes::Bytes::new()) + .unwrap(); + append_at(&mut producer, 1000); + let mut edge = producer.append_group().unwrap(); + edge.write_frame(Timestamp::from_millis(2000).unwrap(), bytes::Bytes::new()) + .unwrap(); + let mut held = subscriber.recv_group().now_or_never().unwrap().unwrap().unwrap(); + assert!(held.read_frame().now_or_never().unwrap().unwrap().is_some()); + let woken = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let waker = futures::task::waker(Arc::new(FlagWake(woken.clone()))); + let mut cx = std::task::Context::from_waker(&waker); + let mut next = std::pin::pin!(held.read_frame()); + assert!(next.as_mut().poll(&mut cx).is_pending()); + let mut frames = crate::frame::Buffer::<2>::new(); + for ms in [11_000, 10_000] { + frames + .push(crate::frame::Frame::new( + Timestamp::from_millis(ms).unwrap(), + bytes::Bytes::new(), + )) + .unwrap(); + } + edge.write_frames(&mut frames).unwrap(); + assert!( + woken.load(Ordering::SeqCst), + "the batch's highest PTS reaches the deadline" + ); + assert!(matches!(next.as_mut().poll(&mut cx), Poll::Ready(Err(Error::Old)))); + head.finish().unwrap(); + edge.finish().unwrap(); + } + + #[test] + #[cfg(feature = "async")] + fn an_adopted_high_pts_wakes_the_group_drift_deadline() { + let mut producer = track_producer("test", Info::timed()); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(10))); + let mut old = producer.append_group().unwrap(); + old.write_frame(Timestamp::from_millis(0).unwrap(), bytes::Bytes::new()) + .unwrap(); + append_at(&mut producer, 1000); + let mut edge = producer.append_group().unwrap(); + edge.start_at(2).unwrap(); + edge.write_frame(Timestamp::from_millis(2000).unwrap(), bytes::Bytes::new()) + .unwrap(); + let mut held = subscriber.recv_group().now_or_never().unwrap().unwrap().unwrap(); + assert!(held.read_frame().now_or_never().unwrap().unwrap().is_some()); + let woken = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let waker = futures::task::waker(Arc::new(FlagWake(woken.clone()))); + let mut cx = std::task::Context::from_waker(&waker); + let mut next = std::pin::pin!(held.read_frame()); + assert!(next.as_mut().poll(&mut cx).is_pending()); + let mut prefix = group::Info { sequence: 2 }.produce(); + for ms in [1500, 11_000] { + prefix + .write_frame(Timestamp::from_millis(ms).unwrap(), bytes::Bytes::new()) + .unwrap(); + } + let head = prefix.consume().handoff().head().unwrap(); + edge.handle().adopt_head(&head); + assert_eq!(edge.handle().latest(), Some(Timestamp::from_millis(11_000).unwrap())); + assert!( + woken.load(Ordering::SeqCst), + "the adopted prefix reaches the drift deadline" + ); + assert!(matches!(next.as_mut().poll(&mut cx), Poll::Ready(Err(Error::Old)))); + old.finish().unwrap(); + edge.finish().unwrap(); + prefix.finish().unwrap(); + } + /// An aborted edge hands the edge to a group between it and the successor, and neither /// the abort nor that group's frames touch the track, so the read must still wake. #[test] @@ -11337,6 +11415,40 @@ mod test { assert_eq!(read, vec![(0, 2), (1, 2), (2, 2), (3, 2)], "every frame of every group"); } + /// Decode-order B-frames cannot rewind the presentation edge and re-admit an old group. + #[moq_clock::test] + #[cfg(feature = "async")] + async fn a_reordered_tail_keeps_the_group_pts_drift_verdict() { + for reordered in [false, true] { + let producer = track_producer("test", Info::timed()); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(80))); + for ms in [0, 100] { + let mut group = producer.append_group().unwrap(); + group + .write_frame(Timestamp::from_millis(ms).unwrap(), bytes::Bytes::new()) + .unwrap(); + group.finish().unwrap(); + } + let mut edge = producer.append_group().unwrap(); + for ms in [150, 200] { + edge.write_frame(Timestamp::from_millis(ms).unwrap(), bytes::Bytes::new()) + .unwrap(); + } + if reordered { + edge.write_frame(Timestamp::from_millis(160).unwrap(), bytes::Bytes::new()) + .unwrap(); + } + edge.finish().unwrap(); + // Group 0 can reach 100ms: 100ms behind the 200ms edge, past its 80ms budget. + // Group 1 can reach 150ms and stays within the same budget. + assert_eq!( + subscriber.recv_group().await.unwrap().unwrap().sequence, + 1, + "reordered {reordered}" + ); + } + } + /// A budget is spent from where the reader stands, not from where its group opened. /// /// A 2s GOP with a 1s budget: the reader has drained to 1900ms when the next group