diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 79f79134017..e895a0bcaff 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -47,7 +47,7 @@ exclude_re = [ # Polling a covered copy hands out nothing, so polling it anyway only costs work. An # expired copy's groups are past the reader's own budget too: the copy expires a budget # after the newer group that makes them stale, and `let_go` arms the same timer. - ':\d+:13: replace \|\| with && in Reader::poll_lowest$', + ':\d+:13: replace \|\| with && in Reader::poll_first$', # A run starting at the window's end or the resume point clips to an empty range, which # has no gaps. 'replace < with <= in Reader::(exhausted|lacking)$', @@ -76,9 +76,9 @@ exclude_re = [ 'replace == with != in Consumer::subscribe$', # A backfill fails only with its route's track, so asking that route again for what it # refused fails at once too and is let go: skipping the ask only saves the subscribe. - # `poll_lowest` records that refusal for the skip. + # `poll_first` records that refusal for the skip. ':\d+:19: replace <= with > in Reader::backfill$', - ':\d+:30: replace == with != in Reader::poll_lowest$', + ':\d+:30: replace == with != in Reader::poll_first$', # With no resume point `raised` names no start, and a settled window has no unsettled # range: each guard only skips the walk. 'replace \|\| with && in Reader::raised$', diff --git a/.claude/skills/verify-resume/SKILL.md b/.claude/skills/verify-resume/SKILL.md index dfba1a09403..49ef6fed20a 100644 --- a/.claude/skills/verify-resume/SKILL.md +++ b/.claude/skills/verify-resume/SKILL.md @@ -5,7 +5,7 @@ description: Model-check logical track resume across route switches (`rs/moq-net # Verify track resume -`rs/moq-net/verify/resume/ResumeReader.tla` models one `Reader` of a logical track that `resume::Producer` serves across route changes. Each route is a received track whose groups land in any order, even below an end its session already settled. The front serves one route at a time, switches to another live route at will, and ends the track cleanly once the serving route completes, or unroutable once no route is left. One reader poll (`poll_lowest`, through `sync` and `backfill_gaps`) is one atomic step, as the reader's lock makes it; so is a switch, which the reader follows at once as `serve_from` does. TLC checks every ordering of arrivals, route failures, switches, polls, and finished reads under the bounds in each config. +`rs/moq-net/verify/resume/ResumeReader.tla` models one `Reader` of a logical track that `resume::Producer` serves across route changes. Each route is a received track whose groups land in any order, even below an end its session already settled. The front serves one route at a time, switches to another live route at will, and ends the track cleanly once the serving route completes, or unroutable once no route is left. Each copy's cursor holds what landed in its window and picks the newest first, as an arrival read in the default Group Order does, and a poll takes the newest any copy offers, a tie going to the newer copy. One reader poll (`poll_first`, through `sync` and `backfill_gaps`) is one atomic step, as the reader's lock makes it; so is a switch, which the reader follows at once as `serve_from` does. TLC checks every ordering of arrivals, route failures, switches, polls, and finished reads under the bounds in each config. ## Rules @@ -30,7 +30,7 @@ quest gate just rs tla moq-net/verify/resume/ResumeReader.tla quest gate just rs tla moq-net/verify/resume/ResumeReader.tla -config rs/moq-net/verify/resume/ThreeRoutes.cfg ``` -The first checks every rule over two routes, three groups, two switches, and a reader holding each group until it finishes it: about 21.3M distinct states, in about six minutes. The second trades a group for a third route, so a route can come up after another failed: about 5.4M states, in about a minute. Both pass at the sync commit. Nightly runs every config here and fails if a config with an `\* Open finding:` line passes. +The first checks every rule over two routes, three groups, two switches, and a reader holding each group until it finishes it: about 18.7M distinct states, in about seven minutes. The second trades a group for a third route, so a route can come up after another failed: about 4.9M states, in about a minute and a half. Both pass at the sync commit. Nightly runs every config here and fails if a config with an `\* Open finding:` line passes. ## Open findings @@ -42,13 +42,14 @@ Follow Reading a failure in `rs/moq-net/verify/README.md`. Replay the path as a ## Coverage -Sync commit: `8c939bc9d05e5e882fb4e042a9efbf2db227b721`, plus [moq-dev/moq#9103](https://github.com/moq-dev/moq/pull/9103), which reads a group landing late on a drained copy, and [moq-dev/moq#9276](https://github.com/moq-dev/moq/pull/9276), which splits a switch at one boundary. Run `git log 8c939bc9d0.. -- rs/moq-net/src/model/resume.rs rs/moq-net/src/model/track.rs` to see what changed since. Follow Coverage in `rs/moq-net/verify/README.md` after a change to a covered function. +Sync commit: `8c939bc9d05e5e882fb4e042a9efbf2db227b721`, plus [moq-dev/moq#9103](https://github.com/moq-dev/moq/pull/9103), which reads a group landing late on a drained copy, [moq-dev/moq#9276](https://github.com/moq-dev/moq/pull/9276), which splits a switch at one boundary, and [moq-dev/moq#9529](https://github.com/moq-dev/moq/pull/9529), which picks in Group Order. Run `git log 8c939bc9d0.. -- rs/moq-net/src/model/resume.rs rs/moq-net/src/model/track.rs` to see what changed since. Follow Coverage in `rs/moq-net/verify/README.md` after a change to a covered function. | Code | Model | | --- | --- | | `rs/moq-net/src/model/resume.rs` `Reader::sync`, `boundary`, `Copy::cap` (reuse of a route's copy, new copy at the boundary, replaced copies capped there) | `Sync`, `Boundary`, `Cap`, `Serve` | | `rs/moq-net/src/model/resume.rs` `Reader::backfill`, `backfill_gaps` | `Backfill`, `BackfillGaps` | -| `rs/moq-net/src/model/resume.rs` `Reader::poll_lowest`, `deliverable`, `take`, `Copy::done` | `Poll`, `Pass`, `Scan`, `Peek`, `Deliverable`, `Take` | +| `rs/moq-net/src/model/resume.rs` `Reader::poll_first`, `deliverable`, `take`, `Copy::done` | `Poll`, `Pass`, `Scan`, `Peek`, `Deliverable`, `Take` | +| `rs/moq-net/src/model/track.rs` `Cursor::poll_recv_with` (the pick in Group Order) | `Peek` | | `rs/moq-net/src/model/resume.rs` `Reader::let_go`, `Copy::retains` | `LetGo`, `Retains` | | `rs/moq-net/src/model/resume.rs` `Reader::poll_end` | `PollEnd` | | `rs/moq-net/src/model/resume.rs` `Producer::splice`, `serve_from`, `Producer::end`, `Phase::Finished` | `Serve`, `FrontFinish`, `FrontFail` | @@ -56,4 +57,4 @@ Sync commit: `8c939bc9d05e5e882fb4e042a9efbf2db227b721`, plus [moq-dev/moq#9103] ## Not covered -Whole groups only, so no frames and no `Recover`: a group whose copy stalls or fails mid-read continuing on another copy is left out, as are compressed groups and fetches. The subscription is unbounded from the oldest group with an hour's budget, so nothing goes stale or expires (nor is the budget clock a replaced copy runs on, `since` and `drained`, modeled), and local ranges (`set_range`, a lowered floor's backfill), ordered reads, caps, refusals, drops and their reports, and re-offers are left out. Copies answer at once (no `Sub::Pending`), the reader joins before any group lands, a route declares its end only once it holds the last group, and a route that declared its end never fails. A pass covers two routes with three groups or three routes with two, two switches between live routes, and one reader. `resume_model.rs`'s proptest and the tests in `resume.rs` own the rest. +Whole groups only, so no frames and no `Recover`: a group whose copy stalls or fails mid-read continuing on another copy is left out, as are compressed groups and fetches. The subscription is unbounded from the oldest group with an hour's budget, so nothing goes stale or expires (nor is the budget clock a replaced copy runs on, `since` and `drained`, modeled), and local ranges (`set_range`, a lowered floor's backfill), ordered reads, ascending order, caps, refusals, drops and their reports, and re-offers are left out. Copies answer at once (no `Sub::Pending`), the reader joins before any group lands, a route declares its end only once it holds the last group, and a route that declared its end never fails. A pass covers two routes with three groups or three routes with two, two switches between live routes, and one reader. `resume_model.rs`'s proptest and the tests in `resume.rs` own the rest. diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index 9111e8d193d..b9526640019 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -202,7 +202,8 @@ Subscription defaultSubscription() => Subscription._(moqSubscriptionDefaults()); /// following the live edge. typedef Range = MoqRange; -/// Which pending group the publisher sends first. +/// Which group comes first, as the publisher sends them and `recvGroup` returns those held. +/// Before moq-lite-07 the publisher sends newest first whatever this asks. typedef Order = MoqOrder; /// A location within a track: a group start and a frame index in it. diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 4f5a4b6c7d8..7fadf13b9df 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -40,7 +40,8 @@ so a raw byte stream needs no other importer. `ContainerFormat.fmp4()` splits each fragment into one frame per sample. `media.CatalogConsumer.subscribe`, `media.TrackConsumer.subscribe`, and `media.GroupConsumer.fetch` construct the read side from a broadcast; the last two take a catalog `media.Rendition` and -follow its broadcast and track themselves. For arrival-order reads, decode each group from +follow its broadcast and track themselves. For arrival reads, which take the groups already held in +the subscription's group order, newest first unless it asks ascending, decode each group from `TrackConsumer.recvGroup()` with `media.GroupConsumer(group: ..., container: ...)`; frames carry container media time as they land. `package:moq/video.dart` and `package:moq/audio.dart` encode raw pixels and PCM inside the diff --git a/go/wrapper/subscribe.go b/go/wrapper/subscribe.go index 66bf71183d2..29d34e691be 100644 --- a/go/wrapper/subscribe.go +++ b/go/wrapper/subscribe.go @@ -107,8 +107,9 @@ type TrackConsumer struct { } // RecvGroup returns the next group in arrival order (possibly out of start order), -// or (nil, nil) when the track ends. Prefer this for live, latency-sensitive -// consumption. +// or (nil, nil) when the track ends. Groups already held come in the +// subscription's group order, newest first unless it asks ascending. Prefer this +// for live, latency-sensitive consumption. func (t *TrackConsumer) RecvGroup(ctx context.Context) (*GroupConsumer, error) { return t.group(ctx, t.inner.RecvGroup) } @@ -175,7 +176,8 @@ func (t *TrackConsumer) Groups(ctx context.Context) iter.Seq2[*GroupConsumer, er } // GroupsAsArrived ranges over groups in arrival order, including -// out-of-order deliveries. +// out-of-order deliveries. Groups already held come in the subscription's +// order, newest first unless it asks ascending, as RecvGroup returns them. func (t *TrackConsumer) GroupsAsArrived(ctx context.Context) iter.Seq2[*GroupConsumer, error] { return bridge.Seq(ctx, t.inner.Cancel, t.RecvGroup) } diff --git a/go/wrapper/types.go b/go/wrapper/types.go index e162fa39935..b98a6187d3e 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -56,7 +56,9 @@ type ( // live join that far behind the live edge (zero is the latest group), and an unstated one // reaches back as far as Max allows. A nil End keeps following the live edge. Range = ffi.MoqRange - // Order is which of a subscription's pending groups the publisher sends first. + // Order is which of a subscription's groups comes first, as the publisher sends them and + // RecvGroup returns those held. Before moq-lite-07 the publisher sends newest first whatever + // this asks. Order = ffi.MoqOrder // Compression is how a track's frames are compressed on the wire. Build one with // DeflateCompression, and compare a received one by Name; a new compression joins as a @@ -143,7 +145,8 @@ func NamedEncoder(name string) VideoEncoderKind { return VideoEncoderKindNamed{Name: name} } -// Order values: which pending group the publisher sends first. +// Order values: which group comes first, as the publisher sends them and RecvGroup returns +// those held. const ( // OrderAscending sends the oldest first, draining a backlog in start order. OrderAscending = ffi.MoqOrderAscending diff --git a/js/e2ee/src/e2ee.test.ts b/js/e2ee/src/e2ee.test.ts index 4eafd9c7520..830f6fbbc5d 100644 --- a/js/e2ee/src/e2ee.test.ts +++ b/js/e2ee/src/e2ee.test.ts @@ -49,8 +49,9 @@ function netTrack(name: string, timed = true): NetTrack.Producer { return defined(new Broadcast.Producer().createTrack(name, { timescale, maxAge: null })); } +// Every group, oldest first, as the tests read their backlogs in order. function subscribe(net: NetTrack.Producer): NetTrack.Subscriber { - return net.subscribe({ ranges: [{}] }); + return net.subscribe({ order: "ascending", ranges: [{}] }); } interface Pair { diff --git a/js/e2ee/src/track.ts b/js/e2ee/src/track.ts index 2a69ccd402e..e2eae5033b6 100644 --- a/js/e2ee/src/track.ts +++ b/js/e2ee/src/track.ts @@ -151,7 +151,8 @@ export class Consumer { } /** - * Receive the next protected group in arrival order, or `undefined` once the track ends. + * Receive the next protected group in arrival order, or `undefined` once the track ends. Groups + * already held come in the subscription's Group Order, newest first unless it asks ascending. * * Rejects with {@link Failure} `authentication` once a grouped frame has failed to open, or a net error. */ diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index 2763b11bac7..3bb34992121 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -106,7 +106,7 @@ async function poll(read: Promise): Promise { // These tests write every group up front and only then read, so they ask for history // rather than the live edge. function replay(track: Track.Producer): Track.Subscriber { - return track.subscribe({ ranges: [{}] }); + return track.subscribe({ order: "ascending", ranges: [{}] }); } // A subscription from group `from` on whose missing groups an unserved fill owes, as a session's // feed would, so its ordered read waits `max` for each hole before giving it up. @@ -205,7 +205,7 @@ test("Legacy Producer accepts open-GOP leading pictures above the previous group test("Legacy Producer continues a group at a keyframe overlapping it, and drops a leading picture before it with those after it", async () => { const track = micro("test"); - const subscriber = track.subscribe({ ranges: [{}] }); + const subscriber = track.subscribe({ order: "ascending", ranges: [{}] }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [timestamp, keyframe] of [ [100_000, true], @@ -248,7 +248,7 @@ test("Legacy Producer drops a keyframe overlapping a closed group", () => { test("Legacy Producer writes a duration marker at the next keyframe", async () => { const track = micro("test"); - const subscriber = track.subscribe({ ranges: [{}] }); + const subscriber = track.subscribe({ order: "ascending", ranges: [{}] }); const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([0xde, 0xad]), Duration.micros(0), true); producer.encode(new Uint8Array([0xbe, 0xef]), Duration.micros(10_000), false); @@ -273,7 +273,7 @@ test("Legacy Producer writes a duration marker at the next keyframe", async () = test("Legacy Producer omits a reordered group's presentation endpoint marker", async () => { const track = micro("test"); - const subscriber = track.subscribe({ ranges: [{}] }); + const subscriber = track.subscribe({ order: "ascending", ranges: [{}] }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 120_000, 40_000, 80_000].entries()) { producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); @@ -299,7 +299,7 @@ test("Legacy Producer omits a reordered group's presentation endpoint marker", a test("Legacy Producer estimates the tail from the current cadence", async () => { const track = micro("test"); - const subscriber = track.subscribe({ ranges: [{}] }); + const subscriber = track.subscribe({ order: "ascending", ranges: [{}] }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 16_000, 32_000, 65_000, 98_000].entries()) { producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); @@ -319,7 +319,7 @@ test("Legacy Producer estimates the tail from the current cadence", async () => test("Legacy Producer rejects a backwards discontinuity without closing the group", async () => { const track = micro("test"); - const subscriber = track.subscribe({ ranges: [{}] }); + const subscriber = track.subscribe({ order: "ascending", ranges: [{}] }); const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); expect(() => producer.discontinuity(Duration.micros(10_000))).toThrow(); @@ -338,7 +338,7 @@ test("Legacy Producer rejects a backwards discontinuity without closing the grou test("Legacy Producer keeps the cadence after rejecting a backwards discontinuity", async () => { const track = micro("test"); - const subscriber = track.subscribe({ ranges: [{}] }); + const subscriber = track.subscribe({ order: "ascending", ranges: [{}] }); const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); @@ -516,7 +516,7 @@ test("Legacy Producer discontinuity keeps pre-pause media from reading as live", producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.finish(); - const subscriber = track.subscribe(within(Duration.millis(1_000))); + const subscriber = track.subscribe({ ...within(Duration.millis(1_000)), order: "ascending" }); expect((await readGroups(subscriber, 5_000_000n)).map(([start]) => start)).toEqual([33_000n, 5_000_000n]); }); diff --git a/js/hang/src/container/legacy.test.ts b/js/hang/src/container/legacy.test.ts index 0a1348230fd..a325604c32a 100644 --- a/js/hang/src/container/legacy.test.ts +++ b/js/hang/src/container/legacy.test.ts @@ -34,7 +34,7 @@ async function groups(subscriber: Track.Subscriber) { test("Legacy Producer keys groups in a millisecond track's timescale", async () => { const media = track(Time.Timescale.MILLI); - const subscriber = media.subscribe({ ranges: [{}] }); + const subscriber = media.subscribe({ order: "ascending", ranges: [{}] }); const producer = new Producer(media, new Format("video")); producer.encode(new Uint8Array([1]), Duration.micros(1_400), true); // The same millisecond as the open group's start, so it continues that group. @@ -55,7 +55,7 @@ test("Legacy Producer keys groups in a millisecond track's timescale", async () test("Legacy Producer keys groups in a nanosecond track's timescale", async () => { const media = track(Time.Timescale.NANO); - const subscriber = media.subscribe({ ranges: [{}] }); + const subscriber = media.subscribe({ order: "ascending", ranges: [{}] }); const producer = new Producer(media, new Format("video")); producer.encode(new Uint8Array([1]), Duration.micros(1_000), true); producer.encode(new Uint8Array([1]), Duration.micros(2_000), true); @@ -73,7 +73,7 @@ test("Legacy Producer keys groups in a nanosecond track's timescale", async () = test("Legacy Producer ends an audio group whole at its discontinuity marker", async () => { const media = track(Time.Timescale.MICRO); - const subscriber = media.subscribe({ ranges: [{}] }); + const subscriber = media.subscribe({ order: "ascending", ranges: [{}] }); const producer = new Producer(media, new Format("audio")); producer.encode(new Uint8Array([1]), Duration.micros(0), true); producer.encode(new Uint8Array([1]), Duration.micros(20_000), false); @@ -96,7 +96,7 @@ test("Legacy Producer ends an audio group whole at its discontinuity marker", as // has the group's End treats any start inside the span as skipped, so nothing later starts there. test("Legacy Producer starts nothing inside the span of a group a cut ended", async () => { const media = track(Time.Timescale.MICRO); - const subscriber = media.subscribe({ ranges: [{}] }); + const subscriber = media.subscribe({ order: "ascending", ranges: [{}] }); const producer = new Producer(media, new Format("audio")); producer.encode(new Uint8Array([1]), Duration.micros(0), true); producer.encode(new Uint8Array([1]), Duration.micros(20_000), false); @@ -131,7 +131,7 @@ test("Legacy Producer starts video resuming at a discontinuity's end past its ma [Time.Timescale.MILLI, 34_000], ] as const) { const media = track(scale); - const subscriber = media.subscribe({ ranges: [{}] }); + const subscriber = media.subscribe({ order: "ascending", ranges: [{}] }); const producer = new Producer(media, new Format("video")); producer.encode(new Uint8Array([1]), Duration.micros(0), true); producer.discontinuity(Duration.micros(33_000)); @@ -151,7 +151,7 @@ test("Legacy Producer starts video resuming at a discontinuity's end past its ma test("Legacy Producer moves a picture with the parameter sets a marker moved", async () => { const media = track(Time.Timescale.MICRO); - const subscriber = media.subscribe({ ranges: [{}] }); + const subscriber = media.subscribe({ order: "ascending", ranges: [{}] }); const producer = new Producer(media, new Format("video")); producer.encode(new Uint8Array([1]), Duration.micros(0), true); producer.discontinuity(Duration.micros(33_000)); @@ -171,7 +171,7 @@ test("Legacy Producer moves a picture with the parameter sets a marker moved", a test("Legacy Producer reorders a group whose frame is written below its moved keyframe", async () => { const media = track(Time.Timescale.MILLI); - const subscriber = media.subscribe({ ranges: [{}] }); + const subscriber = media.subscribe({ order: "ascending", ranges: [{}] }); const producer = new Producer(media, new Format("video")); producer.encode(new Uint8Array([1]), Duration.micros(0), true); producer.discontinuity(Duration.micros(33_000)); diff --git a/js/json/src/stream/consumer.ts b/js/json/src/stream/consumer.ts index 05f8b8ff10c..f9c6ce185ee 100644 --- a/js/json/src/stream/consumer.ts +++ b/js/json/src/stream/consumer.ts @@ -53,6 +53,11 @@ export class Consumer { constructor(config: Consumer.Config) { this.#track = config.track; + // The log is read oldest first whatever order the subscription asked, so a second group a + // broken publisher opens is caught as Rolled rather than read ahead of the first. Mirrors + // the Rust `Consumer::new`. + const subscription = this.#track.subscription.peek(); + if (subscription?.order !== "ascending") this.#track.update({ ...subscription, order: "ascending" }); this.#decoder = new Decoder({ schema: config.schema }); } diff --git a/js/net/bench/drift.ts b/js/net/bench/drift.ts index ab9f128fa62..a03cd212b0c 100644 --- a/js/net/bench/drift.ts +++ b/js/net/bench/drift.ts @@ -17,7 +17,9 @@ export async function run(): Promise { // No publisher limit, so the reader's own 80 ms max alone judges the reordered tail: a live join // reaching back past every group, so it takes each still within that max. const check = new Track.Producer("reordered").accept({ timescale: Time.Timescale.MILLI, maxAge: null }); + // Ascending, so the first group read is the oldest the max keeps. const reader = check.subscribe({ + order: "ascending", ranges: [{ start: { live: { min: null, max: Duration.millis(80) } } }], }); try { diff --git a/js/net/bench/replay.ts b/js/net/bench/replay.ts index 96ae6e978c5..7cc2780e979 100644 --- a/js/net/bench/replay.ts +++ b/js/net/bench/replay.ts @@ -10,8 +10,9 @@ const PAYLOAD = 8; // Arrivals timed per append row, so a sample spans enough work to read. const APPENDS = 64; const REPS = 5; -// Every retained group, however old: replay is the work being measured. -const SUBSCRIPTION = { ranges: [{ start: 0n }] }; +// Every retained group, however old: replay is the work being measured. Ascending, so a reader +// drains its backlog oldest first whatever order it arrived in. +const SUBSCRIPTION: Track.Subscription = { order: "ascending", ranges: [{ start: 0n }] }; // The arrival order of sequences 0..count-1: ascending, descending, or a seeded shuffle. function arrivals(count: number, order: Order): number[] { diff --git a/js/net/src/cache.test.ts b/js/net/src/cache.test.ts index c07f078636e..aa0c47675f3 100644 --- a/js/net/src/cache.test.ts +++ b/js/net/src/cache.test.ts @@ -50,7 +50,7 @@ test("delivery restarts a group's idle window", async () => { await withClock(async (clock) => { const pool = new cache.Pool({ expiry: Duration.millis(10_000) }); const producer = pooled(pool); - const subscriber = producer.subscribe(withMax({ delay: { max: null } })); + const subscriber = producer.subscribe(withMax({ order: "ascending", delay: { max: null } })); finished(producer, 1); // seq 0 finished(producer, 1); // seq 1 takes the live edge, so seq 0 can expire @@ -171,7 +171,9 @@ test("a forgotten run is asked only by a reader that never judged it", async () hooks.receiveTrack(producer); const requests = producer.requests(); const patient = () => - producer.subscribe(withMax({ ranges: [{ start: 0n }], delay: { max: Duration.secs(3600) } })); + producer.subscribe( + withMax({ order: "ascending", ranges: [{ start: 0n }], delay: { max: Duration.secs(3600) } }), + ); const asked = async () => { const runs: bigint[][] = []; for (;;) { diff --git a/js/net/src/cover.test.ts b/js/net/src/cover.test.ts new file mode 100644 index 00000000000..3e371710348 --- /dev/null +++ b/js/net/src/cover.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from "bun:test"; +import { Cover } from "./cover.ts"; + +// `prev` finds the highest covered key below a bound in one descent; checked against the runs it +// would otherwise walk, over random overlapping and cancelling edits. +test("prev agrees with the runs below it", () => { + let seed = 1; + const random = (below: number) => { + seed = (seed * 1103515245 + 12345) % 2 ** 31; + return seed % below; + }; + for (let round = 0; round < 200; round++) { + const cover = new Cover(); + const added: [bigint, bigint][] = []; + for (let edit = 0; edit < 12; edit++) { + if (added.length > 0 && random(3) === 0) { + const [start, end] = added.splice(random(added.length), 1)[0]; + cover.add(start, end, -1); + continue; + } + const start = BigInt(random(60)); + const end = start + BigInt(1 + random(10)); + cover.add(start, end, 1); + added.push([start, end]); + } + for (let before = 0n; before <= 72n; before++) { + const expected = cover.runs(0n, before).at(-1); + expect(cover.prev(before)).toBe(expected === undefined ? undefined : expected.end - 1n); + } + } +}); diff --git a/js/net/src/cover.ts b/js/net/src/cover.ts index 098cba39e1b..051ddf2f9a0 100644 --- a/js/net/src/cover.ts +++ b/js/net/src/cover.ts @@ -208,6 +208,17 @@ function firstFrom(node: Link, offset: number, from: bigint, want: Want) return firstIn(node.right, at, want); } +// {@link lastIn} over the keys at or before `to`. +function lastThrough(node: Link, offset: number, to: bigint, want: Want): bigint | undefined { + if (!node) return undefined; + const at = offset + sum(node.left) + node.delta; + if (node.key > to) return lastThrough(node.left, offset, to, want); + const right = lastThrough(node.right, at, to, want); + if (right !== undefined) return right; + if (want(at)) return node.key; + return lastIn(node.left, offset, want); +} + /** A multiset of runs of keys, read as the set of keys any run covers. */ export class Cover { #root: Link; @@ -234,6 +245,20 @@ export class Cover { return this.contains(from) ? from : firstFrom(this.#root, 0, from, COVERED); } + /** The highest key covered below `before`. */ + prev(before: bigint): bigint | undefined { + if (before <= 0n) return undefined; + const key = before - 1n; + if (this.contains(key)) return key; + // The last run starting at or below `key` ends at the first gap past its start, which `key`, + // uncovered, is at or past. + const start = lastThrough(this.#root, 0, key, COVERED); + if (start === undefined) return undefined; + const end = firstFrom(this.#root, 0, start + 1n, GAP); + if (end === undefined) throw new Error("an uncovered key lies past a gap"); + return end - 1n; + } + /** The lowest key covered: where the first run starts. */ lowest(): bigint | undefined { return first(this.#root); diff --git a/js/net/src/fill.test.ts b/js/net/src/fill.test.ts index d3ab15484ac..9efe9031638 100644 --- a/js/net/src/fill.test.ts +++ b/js/net/src/fill.test.ts @@ -814,10 +814,7 @@ test("fill: a bounded reader keeps waiting on a fresh fill once an older one goe write(5n); const requests = track.requests(); const reader = track.subscribe( - withMax({ - ranges: [{ start: 0n, end: 5n }], - delay: { max: Duration.millis(1000) }, - }), + withMax({ order: "ascending", ranges: [{ start: 0n, end: 5n }], delay: { max: Duration.millis(1000) } }), ); expect((await reader.recvGroup())?.start).toBe(2n); expect((await reader.recvGroup())?.start).toBe(5n); @@ -1453,6 +1450,31 @@ test.each(["arrival", "sequence"])( }, ); +// A resumed reader picks across copies by what each peeks, so a peek offers the group the take hands +// out: newest first, a bounded reader passes a group whose head a fill still owes. +test("fill: a bounded newest-first reader peeks the group its take hands out, past a headless one", async () => { + const broadcast = new BroadcastProducer(); + const track = defined(broadcast.createTrack("video", { maxAge: null })); + const whole = track.createGroup(2n); + whole.writeFrame({ payload: enc.encode("c0"), timestamp: Timestamp.unscaled(2n) }); + whole.finish(); + const tail = hooks.receiveGroup(track, { start: 3n, offset: 1 }); + tail.writeFrame({ payload: enc.encode("d1"), timestamp: Timestamp.unscaled(3n) }); + tail.finish(); + // Asked, never answered: the head of group 3 stays owed. + const requests = track.requests(); + const reader = track.subscribe(withMax({ ranges: [{ start: 2n, end: 3n }], delay: { max: null } })); + await yieldNow(); + + expect(hooks.peekGroup(reader, false)).toBe(2n); + const recv = hooks.tryRecvGroup(reader, false); + expect(recv.kind === "group" ? recv.group.start : recv.kind).toBe(2n); + + reader.close(); + requests.close(); + broadcast.close(); +}); + test("fill: a refused head gives its group up, and the bounded reader moves past it", async () => { const { broadcast, track } = headless(); const requests = track.requests(); diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 9ad9b83534e..ad907f0809e 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -2576,6 +2576,7 @@ test("draft-22: an absolute filter trims the range it serves", async () => { trackNamespace: Path.from("test"), trackName: "video", subscriberPriority: 0, + groupOrder: "ascending", filter: { kind: "absolute", startGroup: 1n, startObject: 1n, endGroup: 2n, endObject: 0n }, }), ); @@ -2634,6 +2635,7 @@ test("draft-22: a filter starting past a group's end claims no END_OF_GROUP", as trackNamespace: Path.from("test"), trackName: "video", subscriberPriority: 0, + groupOrder: "ascending", filter: { kind: "absolute", startGroup: 0n, startObject: 5n, endGroup: 1n, endObject: 0n }, }), ); diff --git a/js/net/src/ietf/subscriber.test.ts b/js/net/src/ietf/subscriber.test.ts index c2ca519d8cf..65b44249bd9 100644 --- a/js/net/src/ietf/subscriber.test.ts +++ b/js/net/src/ietf/subscriber.test.ts @@ -1577,7 +1577,7 @@ test("a clear FIRST_OBJECT past object 0 is dropped", async () => { */ test.each([ [VERSION, false, [4]], - [VERSION, true, [3, 4]], + [VERSION, true, [4, 3]], ])("draft %s with FIRST_OBJECT=%s: a header-only stream delivers %p", async (version, firstObject, expected) => { // A budget, so the empty group outlives its successor's arrival. const { subscriber, track } = await subscribeTrack({ diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index d03dcb2c47e..e89a4ad58e7 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -284,8 +284,9 @@ test("a reader holds for groups from SUBSCRIBE_OK's Largest that land after a hi low.write(object(`${key}.0`)); low.finish(); } - expect(await readAll(await held)).toEqual(["3.0"]); - expect(await readAll(await reader.recvGroup())).toEqual(["4.0"]); + // Both land before the held read takes one, so it takes the newer first. + expect(await readAll(await held)).toEqual(["4.0"]); + expect(await readAll(await reader.recvGroup())).toEqual(["3.0"]); expect(await reader.recvGroup()).toBeUndefined(); await done(TRACK_ENDED, 4n); expect(await reader.closed).toBeNull(); diff --git a/js/net/src/internal.ts b/js/net/src/internal.ts index b2ee7da33a9..91dd27c7cb6 100644 --- a/js/net/src/internal.ts +++ b/js/net/src/internal.ts @@ -680,13 +680,16 @@ export interface ResumeSource { accounts(delivered: Delivered, gaps: readonly Run[], ordered: boolean): boolean; /** Wake once a read may go differently; fires at most once. */ changed(fn: () => void): Dispose; - /** Forget the gaps in `delivered` below each group past the budget, judged on the newest copy. */ + /** Forget the gaps in `delivered` below each group past the budget, as {@link forgetPast} does. */ forgetPastBudget(delivered: Delivered): void; /** * Forget the gaps in `delivered` below each group past `budget`, an outer reader's whose - * `delivered` this is, judged on the newest copy. Mirrors the Rust `Subscriber::forget_past`. + * `delivered` this is, judged on the newest copy, but never past a group a replaced copy still + * feeding the reader holds unread, nor past `keep`. Mirrors the Rust `Subscriber::forget_past`. */ - forgetPast(delivered: Delivered, budget: Budget): void; + forgetPast(delivered: Delivered, budget: Budget, keep?: bigint): void; + /** The lowest group any copy holds unread that `delivered` lacks; see `hooks.lowestBuffered`. */ + lowestBuffered(delivered: Delivered): bigint | undefined; /** * Forget every copy's report of `[start, end)`, so the copy serving when the reader's ranges ask * for it again reports it again. Mirrors the Rust `Reader::untell`. @@ -741,6 +744,12 @@ export interface ResumeSource { finished(): Promise; /** The serving copy's newest buffered frame, which a wire answer names as its edge. */ bufferedLargest(): Position | undefined; + /** The group the next take hands out, without taking it; see `hooks.peekGroup`. */ + peek(ordered: boolean, delivered: Delivered): bigint | undefined; + /** The lowest group any copy holds unread below `below`; see `hooks.lowestUnread`. */ + lowestUnread(below: bigint): bigint | undefined; + /** Whether any copy holds group `key` unread; see `hooks.heldAt`. */ + heldAt(key: bigint): "servable" | "unservable" | undefined; /** The serving copy's newest actual object, including metadata retained past cache eviction. */ objectLargest(): Position | undefined; /** The serving copy's largest location now, and whether it can still advance. */ @@ -1058,6 +1067,17 @@ export const hooks: { knowsEdge: (subscriber: Subscriber) => boolean; /** The newest frame still buffered for a subscriber; assigned by `track.ts`. */ bufferedLargest: (subscriber: Subscriber) => Position | undefined; + /** + * The lowest group the subscriber holds unread below `below`, in its window and whole from the + * frame asked: where a newest-first read's delivery starts. Mirrors the Rust + * `track::Subscriber::lowest_unread`; assigned by `track.ts`. + */ + lowestUnread: (subscriber: Subscriber, below: bigint) => bigint | undefined; + /** + * Whether the subscriber holds group `key` unread in its window, and whether it is whole from the + * frame asked: a publisher's start passes a held group it cannot serve. Assigned by `track.ts`. + */ + heldAt: (subscriber: Subscriber, key: bigint) => "servable" | "unservable" | undefined; /** The newest actual object received or reported upstream, independent of cache retention. */ objectLargest: (subscriber: Subscriber) => Position | undefined; /** Call `fn` with a group's frame count now and on every change; assigned by `group.ts`. */ @@ -1149,7 +1169,10 @@ export const hooks: { * Rust `Subscriber::resolve_ranges`. Assigned by `track.ts`. */ resolveRanges: (subscriber: Subscriber, subscription: Subscription) => (Resolved | undefined)[]; - /** The lowest buffered candidate, which an ordered take may wait below; `floor` passes keys taken on other copies. */ + /** + * The buffered candidate the next take hands out: the lowest for an ordered take, which may wait + * below it, else the first in the subscription's Group Order. `floor` passes keys taken on other copies. + */ peekGroup: (subscriber: Subscriber, ordered: boolean, floor?: bigint) => bigint | undefined; /** Take the next group in sequence order without waiting, as {@link tryRecvGroup} does in arrival order. */ tryNextGroup: (subscriber: Subscriber, floor?: bigint) => Recv; @@ -1203,9 +1226,16 @@ export const hooks: { /** * Forget the gaps in another reader's `delivered` below each group past `budget`, the budget of * the reader whose `delivered` this is, which a front's copy, its ranges raised to a resume point, - * cannot judge by its own. Mirrors the Rust `Subscriber::forget_past_budget`. + * cannot judge by its own, forgetting no gap at or above `keep`. Mirrors the Rust + * `Subscriber::forget_past_budget`. + */ + forgetPastBudget: (subscriber: Subscriber, delivered: Delivered, budget: Budget, keep?: bigint) => void; + /** + * The lowest group the subscriber holds unread that another reader's `delivered` lacks, in its + * range and window, on any copy it reads. Mirrors the Rust `track::Subscriber::lowest_unread` + * as a front's compaction reads it. */ - forgetPastBudget: (subscriber: Subscriber, delivered: Delivered, budget: Budget) => void; + lowestBuffered: (subscriber: Subscriber, delivered: Delivered) => bigint | undefined; /** Fold a route copy's record below `at`, where the reader it feeds is, which reports nothing there. */ fold: (subscriber: Subscriber, at: bigint) => void; /** Forget what a route copy reported of `[start, end)`, which its reader's wire was never told. */ @@ -1632,6 +1662,12 @@ export const hooks: { bufferedLargest: () => { throw new Error("track.ts not loaded"); }, + lowestUnread: () => { + throw new Error("track.ts not loaded"); + }, + heldAt: () => { + throw new Error("track.ts not loaded"); + }, objectLargest: () => { throw new Error("track.ts not loaded"); }, @@ -1656,6 +1692,9 @@ export const hooks: { forgetPastBudget: () => { throw new Error("track.ts not loaded"); }, + lowestBuffered: () => { + throw new Error("track.ts not loaded"); + }, fold: () => { throw new Error("track.ts not loaded"); }, diff --git a/js/net/src/lite/copy_fill.test.ts b/js/net/src/lite/copy_fill.test.ts index d97215e6023..d7d5a349cbd 100644 --- a/js/net/src/lite/copy_fill.test.ts +++ b/js/net/src/lite/copy_fill.test.ts @@ -144,7 +144,7 @@ test("copy fill: lite-07 fills below a start resolved from the budget, as far as try { populate(peer.track); const narrow = peer.remote.track("video").subscribe(NARROW); - expect((await narrow.recvGroup())?.start).toBe(3n); + expect(sorted(await take(narrow, 2)).map(([key]) => key)).toEqual([3n, 4n]); const before = peer.fetches(); // The copy cannot tell which budget picked its start, so it fills what this one reaches, @@ -261,7 +261,7 @@ test("copy fill: lite-06 asks nothing below a start resolved from the budget, an try { populate(peer.track); const narrow = peer.remote.track("video").subscribe(NARROW); - expect((await narrow.recvGroup())?.start).toBe(3n); + expect(sorted(await take(narrow, 2)).map(([key]) => key)).toEqual([3n, 4n]); const before = peer.fetches(); // The widened budget has the publisher re-offer them: lite-06 FETCH carries no budget. @@ -725,15 +725,16 @@ test("copy fill: a group reset to make room ends", async () => { live?.close(); // Two groups, so the fill rides the subscription's ranges. const history = remote.track("video").subscribe({ ...WIDE, ranges: [{ start: 0n, end: 1n }] }); - const group = await history.recvGroup(); - expect(group?.start).toBe(0n); + // The copy's upstream subscription keeps the live reader's Group Order, so either may land first. + const got = [await history.recvGroup(), await history.recvGroup()]; + const group = got.find((held) => held?.start === 0n); + const one = got.find((held) => held?.start === 1n); expect(dec.decode((await group?.readFrame())?.payload)).toBe("old 0"); await archived; // The session resets the group's stream to make room, so the publisher drops it on the // subscription the fill rides. - const one = await history.recvGroup(); - expect(one?.start).toBe(1n); + expect(one).toBeDefined(); while (await one?.readFrame()); // The live stream has finished, so the archived group's is the only one still open. await clock.advance(Duration.ZERO); diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 1801b268a0b..f174f8cab3c 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -2465,9 +2465,10 @@ test.each([Version.DRAFT_01, Version.DRAFT_02])( const sub = await servedSubscription({ version, pending: true }); try { await sub.accept([0n, 3n, 7n]); - expect(await sub.servedHeader()).toBe(0n); - expect(await sub.servedHeader()).toBe(3n); + // Newest first, the default Group Order these versions cannot change. expect(await sub.servedHeader()).toBe(7n); + expect(await sub.servedHeader()).toBe(3n); + expect(await sub.servedHeader()).toBe(0n); } finally { await sub.close(); } @@ -2490,6 +2491,26 @@ test("lite draft-05: an update dropping the floor on an empty track serves the n // Lite-06 encodes a floor of group 0 as 0, including a subscribe that omitted Group Start. // That is a floor, so a later group 0 is still served. +// A held group missing its head, which no fill can bring, cannot be where the feed starts either. +// Mirrors the Rust `TrackRun::start`. +test("lite draft-06: START advances past a held group it cannot serve", async () => { + const sub = await servedSubscription({ version: Version.DRAFT_06, startGroup: 5n }); + try { + hooks.receiveTrack(sub.track); + hooks.startTrack(sub.track, { start: 5n, requested: 5n }); + const tail = hooks.receiveGroup(sub.track, { start: 5n, offset: 1 }); + tail.writeFrame(textFrame("tail", Timestamp.fromMillis(5))); + tail.finish(); + sub.serve(6n); + const response = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); + if (!("start" in response)) throw new Error("expected SUBSCRIBE_START"); + expect(response.start.start).toBe(6n); + expect(await sub.servedSequence()).toBe(6n); + } finally { + await sub.close(); + } +}); + test("lite draft-06: an omitted group start still serves a group below the first one", async () => { const sub = await servedSubscription({ version: Version.DRAFT_06 }); try { diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index 662bc7b9bc6..5e78ede7fae 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -2254,13 +2254,21 @@ export class Publisher { } source = floor; } - // Newest-first delivery can put a group ahead of where the source's feed - // starts. Preserve that start so a resumed subscriber still waits for the backlog. - startKey = min(group.start, source ?? group.start); - // A group given up cannot be where the feed starts. Adjacent runs given up with - // different errors stay separate, so walk them in order. - for (const range of skipped.all) { - if (range.start <= startKey && range.end > startKey) startKey = min(range.end, group.start); + // Newest first, this reader still holds groups below the first to go out: delivery + // starts at the lowest it can serve. A newer group's stream can also beat where the + // source's feed starts: preserve that start so a resumed subscriber still waits for + // the backlog. + const lowest = hooks.lowestUnread(track, group.start) ?? group.start; + startKey = min(lowest, source ?? lowest); + // A group given up, or held and not servable, cannot be where the feed starts. This + // stops at the first group out at the latest. Adjacent runs given up with different + // errors stay separate, so walk them all. Mirrors the Rust `TrackRun::start`. + while (startKey < group.start) { + const key = startKey; + const end = + skipped.at(key)?.end ?? (hooks.heldAt(track, key) === "unservable" ? key + 1n : undefined); + if (end === undefined) break; + startKey = min(end, group.start); } // A later group above an explicit floor is still delivered, so the cursor stays put. // A pre-06 subscribe that named no group is the exception: an absent diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 70cfbf67f2f..9747921b523 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -3001,9 +3001,9 @@ test.each([Version.DRAFT_05, Version.DRAFT_06])("version %p passes received time got.push([group?.start, frame?.payload.length, frame?.timestamp?.value]); } expect(got).toEqual([ - [3n, 1, 2000], - [4n, 1, 1000], [5n, 1, 500], + [4n, 1, 1000], + [3n, 1, 2000], ]); expect((await track.info()).timescale).toBe(Timescale.MILLI); expect(track.closed.peek()).toBeUndefined(); diff --git a/js/net/src/lite/tail.test.ts b/js/net/src/lite/tail.test.ts index eda4554b8cd..12d3d6b1eb5 100644 --- a/js/net/src/lite/tail.test.ts +++ b/js/net/src/lite/tail.test.ts @@ -158,8 +158,8 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver late.write("1.0"); late.finish(); - expect(await readAll(await reader.recvGroup())).toEqual(["0.0"]); expect(await readAll(await reader.recvGroup())).toEqual(["1.0"]); + expect(await readAll(await reader.recvGroup())).toEqual(["0.0"]); expect(await reader.recvGroup()).toBeUndefined(); expect(await reader.closed).toBeNull(); expect(hooks.subscriberEnd(reader)).toEqual({ group: 2n, frame: 0 }); @@ -481,8 +481,8 @@ test("lite-07 settles a skipped group with SUBSCRIBE_DROP", async () => { await respond({ drop: new SubscribeDrop({ start: 1n, end: 2n, error: 0 }) }); await fin(); - expect((await reader.recvGroup())?.start).toBe(0n); expect((await reader.recvGroup())?.start).toBe(2n); + expect((await reader.recvGroup())?.start).toBe(0n); expect(await settlesWithin(reader.recvGroup(), clock, Duration.millis(1000))).toBe(true); expect(await reader.closed).toBeNull(); }); diff --git a/js/net/src/resume.test.ts b/js/net/src/resume.test.ts index 9cff76df81a..91093b9a6a1 100644 --- a/js/net/src/resume.test.ts +++ b/js/net/src/resume.test.ts @@ -306,7 +306,7 @@ test("a returning route backfills below the reader's newest", async () => { await clock.advance(Duration.ZERO); tb.write(10n); tb.write(20n); - expect(drain(sub)).toEqual([10n, 20n]); + expect(drain(sub)).toEqual([20n, 10n]); ta.write(15n); front.serve(handles[0]); await clock.advance(Duration.ZERO); @@ -353,7 +353,7 @@ test("a returning route keeps the reader's bounded end across its cap", async () await clock.advance(Duration.ZERO); tb.write(10n); tb.write(20n); - expect(drain(sub)).toEqual([10n, 20n]); + expect(drain(sub)).toEqual([20n, 10n]); front.serve(handles[0]); await clock.advance(Duration.ZERO); ta.write(30n); @@ -408,7 +408,71 @@ test("a resumed reader's replaced ranges reach its serving copy", async () => { tb.write(70n); await clock.advance(Duration.ZERO); // 30 holds time 50, so the new range starts there; 70 is past its end. - expect(drain(sub)).toEqual([30n, 55n]); + expect(drain(sub)).toEqual([55n, 30n]); + } finally { + sub.close(); + front.consumer.close(); + for (const handle of handles) handle.close(); + for (const source of sources) source.close(); + installed.close(); + } +}); + +test("a serving copy behind an inner front offers its group in Group Order before a replaced copy's", async () => { + const clock = new Manual(); + const installed = install(clock); + const front = new Front(); + const inner = new Front(); + const sources = [new BroadcastProducer(), new BroadcastProducer()]; + const [ta, tb] = sources.map(copy); + ta.write(0n); + ta.write(2n); + front.serve(sources[0].consume()); + const sub = front.consumer.track("seq").subscribe({ ranges: [{ start: 0n, end: 10n }] }); + try { + await clock.advance(Duration.ZERO); + const first = sub.tryRecvGroup(); + expect(first?.start).toBe(2n); + first?.close(); + // The replaced copy still holds 0 unread; the serving one, behind an inner front, holds 3. + inner.serve(sources[1].consume()); + front.serve(inner.consumer); + tb.write(3n); + await clock.advance(Duration.ZERO); + expect(drain(sub)).toEqual([3n, 0n]); + } finally { + sub.close(); + front.consumer.close(); + inner.consumer.close(); + for (const source of sources) source.close(); + installed.close(); + } +}); + +test("a closed copy still holding groups hands them out in the reader's new Group Order", async () => { + const clock = new Manual(); + const installed = install(clock); + const front = new Front(); + const sources = [new BroadcastProducer(), new BroadcastProducer()]; + const handles = sources.map((source) => source.consume()); + const [ta, tb] = sources.map(copy); + ta.write(0n); + ta.write(1n); + front.serve(handles[0]); + const preferences = { delay: { max: Duration.millis(3_600_000) }, ranges: [{ start: 0n }] }; + const sub = front.consumer.track("seq").subscribe(withMax(preferences)); + try { + await clock.advance(Duration.ZERO); + front.serve(handles[1]); + await clock.advance(Duration.ZERO); + // The replaced copy's subscription closes with groups 0 and 1 still unread. + ta.producer.close(); + await clock.advance(Duration.ZERO); + sub.update(withMax({ ...preferences, order: "ascending" })); + await clock.advance(Duration.ZERO); + tb.write(2n); + await clock.advance(Duration.ZERO); + expect(drain(sub)).toEqual([0n, 1n, 2n]); } finally { sub.close(); front.consumer.close(); @@ -429,6 +493,7 @@ test("a group the window dropped above the serving copy's resume point is backfi ta.write(50n); front.serve(handles[0]); const sub = front.consumer.track("seq").subscribe({ + order: "ascending", ranges: [ { start: 10n, end: 10n }, { start: 50n, end: 50n }, @@ -647,7 +712,7 @@ test("a backfill through an inner front waits on a copy it replaced", async () = const sub = front.consumer.track("seq").subscribe(withMax({ delay })); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([6n, 8n]); + expect(drain(sub)).toEqual([8n, 6n]); tb.write(6n); tb.write(8n); inner.serve(handles[1]); @@ -990,7 +1055,7 @@ test("a group below the replacement's resume point is backfilled", async () => { tb.write(2n); tb.write(6n); await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([2n, 6n]); + expect(drain(sub)).toEqual([6n, 2n]); tb.write(4n); await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([4n]); @@ -1041,6 +1106,42 @@ test("a late group on a drained serving copy is read", async () => { } }); +test("a late group on a drained serving copy is peeked as the take hands it out", async () => { + const clock = new Manual(); + const installed = install(clock); + const front = new Front(); + const sources = [new BroadcastProducer(), new BroadcastProducer()]; + const handles = sources.map((source) => source.consume()); + const [ta, tb] = sources.map(copy); + hooks.receiveTrack(ta.producer); + hooks.receiveTrack(tb.producer); + front.serve(handles[0]); + const sub = front.consumer.track("seq").subscribe({ ranges: [{}] }); + try { + await clock.advance(Duration.ZERO); + ta.write(0n); + ta.write(2n); + front.serve(handles[1]); + await clock.advance(Duration.ZERO); + tb.write(3n); + tb.write(5n); + tb.producer.finish(); + await clock.advance(Duration.ZERO); + expect(drain(sub)).toEqual([5n, 3n, 2n, 0n]); + // The serving copy ran out; a group landing on it late is what the next take hands out. + tb.write(4n); + await clock.advance(Duration.ZERO); + expect(hooks.peekGroup(sub, false)).toBe(4n); + expect(drain(sub)).toEqual([4n]); + } finally { + sub.close(); + front.consumer.close(); + for (const handle of handles) handle.close(); + for (const source of sources) source.close(); + installed.close(); + } +}); + // A replacement that ends cleanly before delivering any group doesn't end the read while the // replaced copy may still deliver a group the reader lacks under its cap. test("a replacement ending before any group waits for the replaced copy's late group", async () => { @@ -1289,7 +1390,7 @@ test("a front's reader places a live join from an answer its copy recorded befor front.serve(a.consume()); await settle(); await settle(); - expect(drain(sub)).toEqual([3n, 4n]); + expect(drain(sub)).toEqual([4n, 3n]); expect(hooks.requested(ta.producer).joins()).toEqual([]); } finally { sub.close(); @@ -1310,10 +1411,10 @@ test("a bounded read through routes ends once its window is read, across a route front.serve(a.consume()); const sub = front.consumer .track("seq") - .subscribe(withMax({ delay: { max: null }, ranges: [{ start: 1n, end: 4n }] })); + .subscribe(withMax({ order: "ascending", delay: { max: null }, ranges: [{ start: 1n, end: 4n }] })); const floored = front.consumer .track("seq") - .subscribe(withMax({ delay: { max: null }, ranges: [{ start: 1n, end: 4n }] })) + .subscribe(withMax({ order: "ascending", delay: { max: null }, ranges: [{ start: 1n, end: 4n }] })) .withRange({ start: { included: 3n } }); try { expect((await sub.recvGroup())?.start).toBe(1n); @@ -1365,7 +1466,7 @@ test("a skip under the resume point the local floor keeps out ends the read", as .subscribe(withMax({ delay: { max: Duration.millis(3_600_000) }, ranges: [{ start: 0n, end: 3n }] })); try { await settle(); - expect(drain(sub)).toEqual([0n, 2n]); + expect(drain(sub)).toEqual([2n, 0n]); tb.write(3n); front.serve(b.consume()); sub.withRange({ start: { included: 2n }, end: { excluded: 4n } }); @@ -1403,7 +1504,7 @@ test("a kept-out key is asked through an inner front", async () => { .subscribe(withMax({ delay: { max: Duration.millis(3_600_000) }, ranges: [{ start: 0n, end: 3n }] })); try { await settle(); - expect(drain(sub)).toEqual([0n, 2n]); + expect(drain(sub)).toEqual([2n, 0n]); tb.write(3n); inner.serve(b.consume()); front.serve(inner.consumer); @@ -1450,7 +1551,7 @@ test("a skip starting a gap the local floor keeps out ends the read", async () = .subscribe(withMax({ delay: { max: Duration.millis(3_600_000) }, ranges: [{ end: 4n }] })); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([0n, 3n]); + expect(drain(sub)).toEqual([3n, 0n]); tb.write(4n); front.serve(b.consume()); sub.withRange({ start: { included: 2n }, end: { excluded: 5n } }); @@ -1499,7 +1600,7 @@ test("a skip split between a replaced and the serving copy ends the read", async .subscribe(withMax({ delay: { max: Duration.millis(3_600_000) }, ranges: [{ end: 5n }] })); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([0n, 4n]); + expect(drain(sub)).toEqual([4n, 0n]); tb.producer.skipGroups(1n, 2n); tb.write(5n); front.serve(b.consume()); @@ -1544,7 +1645,7 @@ test("a kept-out skip a let-go copy knew is asked upstream", async () => { .subscribe(withMax({ delay: { max: Duration.millis(3_600_000) }, ranges: [{ start: 0n, end: 6n }] })); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([0n, 5n]); + expect(drain(sub)).toEqual([5n, 0n]); tb.write(6n); front.serve(b.consume()); sub.withRange({ start: { included: 3n }, end: { excluded: 7n } }); @@ -1594,7 +1695,7 @@ test("a kept-out skip the asked copy forgot is asked again", async () => { const sub = front.consumer.track("seq").subscribe({ ranges: [{ start: 0n, end: 6n }] }); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([0n, 5n]); + expect(drain(sub)).toEqual([5n, 0n]); tb.write(6n); front.serve(b.consume()); sub.withRange({ start: { included: 5n }, end: { excluded: 7n } }); @@ -1668,7 +1769,7 @@ for (const nested of [false, true]) { const sub = front.consumer.track("seq").subscribe({ ranges: [{ start: 0n, end: 6n }] }); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([0n, 5n]); + expect(drain(sub)).toEqual([5n, 0n]); tb.write(6n); tb.write(5n); serve(b); @@ -1729,7 +1830,7 @@ test("a kept-out group is asked once and stays owed", async () => { const subscribed = spyOn(tb.producer, "subscribe"); try { await settle(); - expect(drain(sub)).toEqual([0n, 2n]); + expect(drain(sub)).toEqual([2n, 0n]); tb.write(3n); front.serve(b.consume()); sub.withRange({ start: { included: 2n }, end: { excluded: 4n } }); @@ -1791,7 +1892,7 @@ test("a window moved down under the cursor keeps one ask", async () => { }); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([10n, 11n]); + expect(drain(sub)).toEqual([11n, 10n]); front.serve(b.consume()); sub.withRange({ start: { included: 10n }, end: { excluded: 13n } }); await clock.advance(Duration.ZERO); @@ -1846,7 +1947,7 @@ test("a skip behind an inner switch ends the read", async () => { .subscribe(withMax({ delay: { max: Duration.millis(3_600_000) }, ranges: [{ start: 0n, end: 4n }] })); try { await clock.advance(Duration.ZERO); - expect(drain(sub)).toEqual([0n, 2n]); + expect(drain(sub)).toEqual([2n, 0n]); tb.write(3n); inner.serve(b.consume()); await clock.advance(Duration.ZERO); @@ -1891,7 +1992,7 @@ test("a skip under the local floor ends a single route read", async () => { .withRange({ start: { included: 1n }, end: { excluded: 3n } }); try { await settle(); - expect(drain(sub)).toEqual([1n, 2n]); + expect(drain(sub)).toEqual([2n, 1n]); expect(await isPending(sub.recvGroup())).toBe(false); expect(await sub.recvGroup()).toBeUndefined(); } finally { @@ -2023,7 +2124,7 @@ test.each(["conclude", "park"] as const)("a fork made after the front's %s repla front[end](); const fork = parent.fork(withMax({ delay: { max: Duration.millis(10_000) } })); try { - expect(drain(fork)).toEqual([0n, 1n]); + expect(drain(fork)).toEqual([1n, 0n]); } finally { parent.close(); fork.close(); @@ -2048,7 +2149,7 @@ test("a resumed fork has its own preferences and replay cursor", async () => { expect(drain(parent)).toEqual([1n]); const fork = parent.fork(withMax({ priority: 7, delay: { max: Duration.millis(10_000) } })); try { - expect(drain(fork)).toEqual([0n, 1n]); + expect(drain(fork)).toEqual([1n, 0n]); fork.update({ priority: 9 }); expect(parent.subscription.peek()?.priority).toBe(2); expect(fork.subscription.peek()?.priority).toBe(9); @@ -2195,17 +2296,20 @@ test("a lagging same-instance replica resumes from one publisher's bytes exactly last.writeFrame({ payload: enc.encode(`2.${frame}`), timestamp: Timestamp.unscaled(last.start) }); last.finish(); - // The standby holds the complete original while the incumbent cannot pass 1.1. - for (let key = 0n; key < 3n; key++) { + // The standby holds the complete original while the incumbent cannot pass 1.1, in whatever + // order its groups landed. + const warmed: bigint[] = []; + for (let read = 0; read < 3; read++) { const group = await warm.recvGroup(); if (!group) throw new Error("expected a warmed group"); - expect(group.start).toBe(key); + warmed.push(group.start); for (let frame = 0; frame < 4; frame++) { - expect(dec.decode((await group.readFrame())?.payload)).toBe(`${key}.${frame}`); + expect(dec.decode((await group.readFrame())?.payload)).toBe(`${group.start}.${frame}`); } expect(await group.readFrame()).toBeUndefined(); group.close(); } + expect(warmed.sort((x, y) => Number(x - y))).toEqual([0n, 1n, 2n]); disposeB = serve(origin, b.broadcast, 9n); await clock.advance(Duration.nanos(0)); expect(request.active.peek()).toBe(active); @@ -2259,7 +2363,7 @@ test("a subscription reads on across a same-instance route swap, each group once await swap(); expect(request.active.peek()).toBe(active); tb.write(2n); - expect(drain(sub)).toEqual([1n, 2n]); + expect(drain(sub)).toEqual([2n, 1n]); // The replaced route's later groups are the new route's to deliver. ta.write(3n); @@ -4475,8 +4579,8 @@ test("a resumed reader reports a drop once and still serves a late group", async // Re-created under a run already reported dropped. ta.write(3n); ta.write(4n); - expect(recvDisposition(sub)).toBe(3n); expect(recvDisposition(sub)).toBe(4n); + expect(recvDisposition(sub)).toBe(3n); expect(recvDisposition(sub)).toBe("idle"); sub.close(); @@ -4736,8 +4840,8 @@ test("a front serving another front reports the inner serving route's drop", asy // Re-created under a run already reported dropped. ta.write(2n); ta.write(3n); - expect(recvDisposition(sub)).toBe(2n); expect(recvDisposition(sub)).toBe(3n); + expect(recvDisposition(sub)).toBe(2n); expect(recvDisposition(sub)).toBe("idle"); sub.close(); @@ -5524,6 +5628,52 @@ test("a fetch waits for the copy being read to say what the track is", async () b.close(); }); +// Late groups a replaced copy holds unread, fresh by their own successors there, outlive the +// serving copy's old arrival above them making the gap below it stale, as they do on one track: a +// cursor never forgets what it still holds to hand out. Mirrors the Rust +// `a_replaced_copys_unread_late_groups_outlive_the_serving_copys_stale_verdict`. +test("a replaced copy's unread late groups outlive the serving copy's stale verdict", async () => { + for (const routed of [false, true]) { + const clock = new Manual(); + const installed = install(clock); + try { + const front = new Front(); + const a = new BroadcastProducer(); + const b = new BroadcastProducer(); + const ta = copy(a); + const tb = copy(b); + front.serve(a.consume()); + const budget = withMax({ delay: { max: Duration.millis(1_000) } }); + const sub = routed ? front.consumer.track("seq").subscribe(budget) : ta.producer.subscribe(budget); + ta.write(0n); + ta.write(5n); + // Held, so the replaced copy stays subscribed. + const held = defined(sub.tryRecvGroup()); + expect(held.start).toBe(5n); + expect(drain(sub)).toEqual([0n]); + if (routed) { + front.serve(b.consume()); + await settle(); + } + expect(drain(sub)).toEqual([]); + // 6 arrives long before the late groups, and the reader looks only once they land: 4 is + // stale by 5, while 2 and 1 are fresh by 4 and 2. + (routed ? tb : ta).write(6n); + await clock.advance(Duration.millis(2_000)); + for (const key of [4n, 2n, 1n]) ta.write(key); + expect(drain(sub), `routed ${routed}`).toEqual([6n, 2n, 1n]); + + held.close(); + sub.close(); + front.consumer.close(); + a.close(); + b.close(); + } finally { + installed.close(); + } + } +}); + test("an arrival read takes a replaced copy's buffered group before the new copy's later one", async () => { const front = new Front(); const a = new BroadcastProducer(); @@ -5539,7 +5689,7 @@ test("an arrival read takes a replaced copy's buffered group before the new copy tb.write(2n); front.serve(b.consume()); await settle(); - expect(drain(sub)).toEqual([1n, 2n]); + expect(drain(sub)).toEqual([2n, 1n]); sub.close(); front.consumer.close(); @@ -5671,7 +5821,7 @@ test.each(["lands", "dropped", "expired"])( front.serve(b.consume()); await settle(); tb.write(3n); - expect(drain(sub)).toEqual([2n, 3n]); + expect(drain(sub)).toEqual([3n, 2n]); expect(drain(sub)).toEqual([]); expect(ta.producer.demand().wanted.peek()).toBe(true); @@ -5878,7 +6028,7 @@ test("a clean end waits for a group the replaced copy still carries", async () = try { ta.write(0n); ta.write(2n); - expect(drain(sub)).toEqual([0n, 2n]); + expect(drain(sub)).toEqual([2n, 0n]); // The new route has only the group already handed out, and ends there. tb.write(2n); @@ -6104,7 +6254,7 @@ test.each(["lands", "expired"])( try { ta.write(0n); ta.write(2n); - expect(drain(sub)).toEqual([0n, 2n]); + expect(drain(sub)).toEqual([2n, 0n]); // The new route has only the group already handed out, and ends there. Nothing reads. tb.write(2n); @@ -6167,7 +6317,7 @@ test.each([ sub.withRange({ start: { included: 4n } }); await clock.advance(Duration.ZERO); for (let key = 0n; key < 6n; key++) ta.write(key); - expect(read()).toEqual([4n, 5n]); + expect(read()).toEqual(ordered ? [4n, 5n] : [5n, 4n]); if (cached) for (let key = 0n; key < 6n; key++) tb.write(key); front.serve(b.consume()); @@ -6185,7 +6335,7 @@ test.each([ expect(read()).toEqual([]); for (let key = 1n; key < 4n; key++) tb.write(key); } - expect(read()).toEqual(ordered ? [] : [1n, 2n, 3n]); + expect(read()).toEqual(ordered ? [] : [3n, 2n, 1n]); tb.write(7n); expect(read()).toEqual([7n]); } finally { @@ -6329,7 +6479,9 @@ test("an ended track's reader hands out nothing from the copy served after the e const tb = copy(b); const failure = new StreamError(StreamCode.SessionClosed); front.serve(counted(a, () => Promise.reject(failure)).route); - const sub = front.consumer.track("seq").subscribe(withMax({ delay: { max: Duration.millis(3_600_000) } })); + const sub = front.consumer + .track("seq") + .subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(3_600_000) } })); try { const open = ta.write(1n, 1, false); ta.write(3n); @@ -6376,7 +6528,7 @@ test("a retained copy declaring another end after a clean end fails nothing", as try { ta.write(0n); ta.write(2n); - expect(drain(sub)).toEqual([0n, 2n]); + expect(drain(sub)).toEqual([2n, 0n]); // The new route ends at 3, while the old one still owes group 1. tb.write(2n); @@ -6993,7 +7145,7 @@ test("a failed copy holding a group back is still subscribed afresh", async () = group.close(); } } - expect(read).toEqual([66n, 67n]); + expect(read).toEqual([67n, 66n]); expect(sub.closed.peek()).toBeUndefined(); sub.close(); @@ -7033,7 +7185,7 @@ test("failed copies holding groups back are each subscribed afresh", async () => again.write(66n); again.write(67n); await poll(); - expect(read).toEqual([66n, 67n]); + expect(read).toEqual([67n, 66n]); expect(sub.closed.peek()).toBeUndefined(); sub.close(); diff --git a/js/net/src/resume.ts b/js/net/src/resume.ts index 47b82d8bed1..da68d8c6943 100644 --- a/js/net/src/resume.ts +++ b/js/net/src/resume.ts @@ -1035,6 +1035,11 @@ class Reader implements ResumeSource { if (this.#shell.retuned()) copy.sub.update(wire); else hooks.restateSubscriber(copy.sub, wire); this.#stamp(copy); + } else { + // Its ranges stay as resolved when it closed, but the groups it still holds are picked in + // the reader's Group Order. Mirrors the Rust `Copy::send`, which edits every copy. + const { priority = 0, order = "descending" } = wire; + hooks.editSubscriber(copy.sub, { retire: [], add: [], priority, order }); } } @@ -1378,7 +1383,7 @@ class Reader implements ResumeSource { // Whether a copy's next group, `key`, waits for the reader's window to be placed, which decides // whether it goes out: a failed copy's, until a copy continuing the track places it, and a // backfill's that no range placed so far holds, since only a placed range bounds the groups under - // the resume point. Mirrors the Rust `Reader::poll_lowest`. + // the resume point. Mirrors the Rust `Reader::poll_first`. #waits(copy: Copy, key: bigint): boolean { if (!this.#mayWait(copy)) return false; const failed = !this.route.concluded && copyFailed(copy); @@ -1403,14 +1408,15 @@ class Reader implements ResumeSource { const dropped = this.#tryDrop(delivered); if (dropped) return dropped; } - // The lowest group any copy holds next, in either order: a replaced copy's buffered group - // comes before a later one the serving copy already has. Arrival order still delivers a - // lower group that truly arrives later. + // The first group any copy holds next: the lowest for an ordered read, else the first in + // the subscription's Group Order. A replaced copy's buffered group comes before a later one + // the serving copy already has. An arrival read still delivers a lower group that truly + // arrives later. let owing: Copy[]; for (;;) { - const lowest = this.#lowest(ordered, delivered); - owing = lowest.owing; - const next = lowest.next; + const first = this.#first(ordered, delivered); + owing = first.owing; + const next = first.next; if (!next) break; const recv = this.#take(next, ordered, dispositions); if (recv.kind === "drop") { @@ -1508,7 +1514,7 @@ class Reader implements ResumeSource { // group already. A replaced copy that failed this pass owes the serving route a backfill // once the window is placed: ask now, since its close already fired and no later group is // sure to wake the read. A backfill that failed is not asked again (`#refused`), so this - // ends. Mirrors the Rust `Reader::poll_lowest`. + // ends. Mirrors the Rust `Reader::poll_first`. const backfill = owed && this.#resumed && this.#window().floor() !== undefined; if (end.kind === "idle" && (this.route.generation !== generation || backfill)) { return this.tryGroup(ordered, delivered, dispositions); @@ -1733,7 +1739,7 @@ class Reader implements ResumeSource { // A copy that ran out cleanly still takes a group in flight below its end while the read stays // open, as a cursor still reading it would. One landing on the serving copy may lie under its // resume point, which is not that copy's to read, and a backfill that already ran out was let - // go: ask its route again. Mirrors the Rust `Reader::poll_lowest`. + // go: ask its route again. Mirrors the Rust `Reader::poll_first`. #reopen(): void { const serving = this.#serving(); for (const copy of this.#copies) { @@ -1755,13 +1761,15 @@ class Reader implements ResumeSource { copy.dropped = max(copy.dropped ?? 0n, key + 1n); } - // The copy whose next group is the lowest deliverable one in the reader's window, dropping any + // The copy whose next group is the first deliverable one in the reader's window, dropping any // it holds next that are not, and the copies whose ordered cursor is left on such a group - // because the window still owes a lower one that may yet land there. - #lowest(ordered: boolean, delivered: Delivered): { next?: Copy; owing: Copy[] } { - let lowest: { copy: Copy; key: bigint } | undefined; + // because the window still owes a lower one that may yet land there. First is the lowest for an + // ordered read, else the first in the subscription's Group Order. Mirrors the Rust `poll_first`. + #first(ordered: boolean, delivered: Delivered): { next?: Copy; owing: Copy[] } { + let first: { copy: Copy; key: bigint } | undefined; const owing: Copy[] = []; const floor = ordered ? (delivered.runEnd(0n) ?? 0n) : 0n; + const ascending = ordered || this.#shell.subscription.peek()?.order === "ascending"; for (const copy of this.#copies) { if (!this.#feeds(copy)) continue; for (;;) { @@ -1775,7 +1783,7 @@ class Reader implements ResumeSource { if (deliverable && this.#inWindow(key)) { // A tie goes to the newer copy, so the serving one hands out its first group and // bounds the copies it replaced. - if (!lowest || key <= lowest.key) lowest = { copy, key: key }; + if (!first || (ascending ? key <= first.key : key >= first.key)) first = { copy, key }; break; } // Skipping an ordered cursor past a group the window still owes below would lose it. @@ -1789,7 +1797,7 @@ class Reader implements ResumeSource { recv.group.close(); } } - return { next: lowest?.copy, owing }; + return { next: first?.copy, owing }; } /** @@ -2193,9 +2201,28 @@ class Reader implements ResumeSource { for (const copy of this.#copies) hooks.untell(copy.sub, start, end); } - forgetPast(delivered: Delivered, budget: Budget): void { + // Judged on the newest copy, but never past a group a replaced copy still feeding the reader + // holds unread: as one cursor keeps what it owes, since a late group there may be fresh by its + // own successor on that copy. Nor past `keep`, an outer reader's own such group. + forgetPast(delivered: Delivered, budget: Budget, keep?: bigint): void { const newest = this.#copies.at(-1); - if (newest) hooks.forgetPastBudget(newest.sub, delivered, budget); + if (!newest) return; + let kept = keep; + for (const copy of this.#copies) { + if (copy === newest || !copy.replaced || !this.#feeds(copy)) continue; + const key = hooks.lowestBuffered(copy.sub, delivered); + if (key !== undefined) kept = min(kept ?? key, key); + } + hooks.forgetPastBudget(newest.sub, delivered, budget, kept); + } + + lowestBuffered(delivered: Delivered): bigint | undefined { + let lowest: bigint | undefined; + for (const copy of this.#copies) { + const key = hooks.lowestBuffered(copy.sub, delivered); + if (key !== undefined) lowest = min(lowest ?? key, key); + } + return lowest; } latest(): bigint | undefined { @@ -2440,6 +2467,42 @@ class Reader implements ResumeSource { return serving && hooks.bufferedLargest(serving.sub); } + /** + * The group a {@link tryGroup} with nothing to drop would hand out next, without taking it: the + * first any copy offers. A front reading this one as its copy picks across copies by it. + */ + peek(ordered: boolean, delivered: Delivered): bigint | undefined { + this.#delivered = delivered; + this.sync(); + if (this.#closed) return undefined; + // As the take does, so a late group on a copy that ran out is offered here too. A serving + // copy it reopens owes a backfill, which the next take asks. + this.#reopen(); + const { next } = this.#first(ordered, delivered); + if (!next) return undefined; + return hooks.peekGroup(next.sub, ordered, this.#newest === undefined ? undefined : this.#newest + 1n); + } + + lowestUnread(below: bigint): bigint | undefined { + let lowest: bigint | undefined; + for (const copy of this.#copies) { + const key = hooks.lowestUnread(copy.sub, lowest ?? below); + if (key !== undefined) lowest = key; + } + return lowest; + } + + // Servable if any copy can serve it. + heldAt(key: bigint): "servable" | "unservable" | undefined { + let held: "unservable" | undefined; + for (const copy of this.#copies) { + const state = hooks.heldAt(copy.sub, key); + if (state === "servable") return state; + held ??= state; + } + return held; + } + objectLargest(): track.Position | undefined { this.sync(); const serving = this.#serving(); diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 86c6163996e..ac6f7eff01e 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -208,7 +208,7 @@ test("a stale group forgets no gap a wider budget owes", () => { putGroup(producer, 0n); putGroup(producer, 3n); putGroup(producer, 4n); - expect(drain(reader)).toEqual([0n, 3n, 4n]); + expect(drain(reader)).toEqual([4n, 3n, 0n]); clock.set(50); putGroup(producer, 5n); expect(drain(reader)).toEqual([5n]); @@ -1152,12 +1152,12 @@ test("each reader reads only its own ranges, whatever the union asks for", () => for (let group = subscriber.tryRecvGroup(); group; group = subscriber.tryRecvGroup()) got.push(group.start); return got; }; - expect(read(sparse)).toEqual([1n, 2n, 5n]); - expect(read(tail)).toEqual([4n, 5n, 6n]); + expect(read(sparse)).toEqual([5n, 2n, 1n]); + expect(read(tail)).toEqual([6n, 5n, 4n]); // Replacing the ranges offers the held groups the new ones take in, never one read already. sparse.update(withMax({ delay: { max: null }, ranges: [{ start: 0n, end: 4n }] })); - expect(read(sparse)).toEqual([0n, 3n, 4n]); + expect(read(sparse)).toEqual([4n, 3n, 0n]); producer.finish(); expect(hooks.tryRecvGroup(sparse, false)).toEqual({ kind: "done" }); }); @@ -1179,7 +1179,7 @@ test("a bounded read ends once its window is read, unless a cap or a wire publis const parked = hooks.parked(producer.subscribe(withMax({ delay: { max: null }, ranges }))); const open = producer.subscribe(withMax({ delay: { max: null }, ranges: [{ start: 1n }] })); for (const key of [0n, 1n, 2n]) producer.createGroup(key).finish(); - expect(read(reader)).toEqual([1n, 2n]); + expect(read(reader)).toEqual([2n, 1n]); // Groups 3 and 4 may still arrive. expect(hooks.tryRecvGroup(reader, false)).toEqual({ kind: "idle" }); @@ -1190,12 +1190,12 @@ test("a bounded read ends once its window is read, unless a cap or a wire publis expect(drainOrdered(ordered)).toEqual([1n, 2n, 4n]); expect(hooks.tryNextGroup(sequenced)).toEqual({ kind: "done" }); // A wire publisher's peer would read the end of the stream as the track's. - expect(read(parked)).toEqual([1n, 2n, 4n]); + expect(read(parked)).toEqual([4n, 2n, 1n]); expect(hooks.tryRecvGroup(parked, false)).toEqual({ kind: "idle" }); - expect(read(open)).toEqual([1n, 2n, 4n]); + expect(read(open)).toEqual([4n, 2n, 1n]); expect(hooks.tryRecvGroup(open, false)).toEqual({ kind: "idle" }); // The cap keeps group 4 out, and may rise. - expect(read(capped)).toEqual([1n, 2n]); + expect(read(capped)).toEqual([2n, 1n]); expect(hooks.tryRecvGroup(capped, false).kind).not.toBe("done"); capped.withRange({}); expect(read(capped)).toEqual([4n]); @@ -1216,6 +1216,7 @@ test("a bounded read on a subscribed copy ends once its feed stops owing a hole" try { const producer = receivedTrack(); const reader = producer.subscribe({ + order: "ascending", ranges: [{ start: { live: { min: Duration.ZERO, max: Duration.millis(1000) } }, end: 2n }], }); putGroup(producer, 0n); @@ -1267,7 +1268,7 @@ test("a live join waits for the first group", () => { empty.createGroup(6n).finish(); empty.createGroup(8n).finish(); // Resolved at the first group to arrive: group 6 sits below where it started. - expect([live.tryRecvGroup()?.start, live.tryRecvGroup()?.start, live.tryRecvGroup()]).toEqual([7n, 8n, undefined]); + expect([live.tryRecvGroup()?.start, live.tryRecvGroup()?.start, live.tryRecvGroup()]).toEqual([8n, 7n, undefined]); }); test("a time range reads the groups containing its times, by their starts", () => { @@ -1291,7 +1292,7 @@ test("a time range reads the groups containing its times, by their starts", () = return got; }; // Group 1000 contains 1500, and a group may still start inside the end. - expect(read()).toEqual([1000n, 2000n]); + expect(read()).toEqual([2000n, 1000n]); // A group's key is its start, so the end places it before any frame arrives. producer.createGroup(3000n); expect(read()).toEqual([3000n]); @@ -1336,7 +1337,7 @@ test("a live join reaches back by its min age", () => { }), ); // The newest frame presents at 5 s, so the join starts at the group containing 3 s. - expect(readable(reader)).toEqual(halfSeconds(6, 10)); + expect(readable(reader)).toEqual(halfSeconds(6, 10).reverse()); appendHalfSecond(producer, 11n); expect(readable(reader)).toEqual([5500n]); }); @@ -1358,7 +1359,7 @@ test("a lag update reaches a live join not yet started", () => { }), ); for (let n = 0n; n <= 10n; n++) appendHalfSecond(producer, n); - expect(readable(reader)).toEqual(halfSeconds(6, 10)); + expect(readable(reader)).toEqual(halfSeconds(6, 10).reverse()); }); test("a zero lag joins at the latest group, a range with no start reaches back to the oldest", () => { @@ -1368,11 +1369,11 @@ test("a zero lag joins at the latest group, a range with no start reaches back t expect(readable(producer.subscribe(join(Duration.ZERO)))).toEqual([5000n]); // The default is a zero lag too. expect(readable(producer.subscribe())).toEqual([5000n]); - expect(readable(producer.subscribe({ ranges: [{}] }))).toEqual(all); + expect(readable(producer.subscribe({ ranges: [{}] }))).toEqual(all.toReversed()); // Past everything held, it starts at the oldest group. - expect(readable(producer.subscribe(join(Duration.secs(60))))).toEqual(all); + expect(readable(producer.subscribe(join(Duration.secs(60))))).toEqual(all.toReversed()); const named = producer.subscribe({ ranges: [{ start: 4500n }] }); - expect(readable(named)).toEqual([4500n, 5000n]); + expect(readable(named)).toEqual([5000n, 4500n]); }); test("a live join reads nothing until the groups held measure the live edge", () => { @@ -1395,7 +1396,7 @@ test("a live join reads nothing until the groups held measure the live edge", () group.writeFrame(textFrame(`${key}`, Timestamp.fromMillis(key * 500))); group.finish(); } - expect(readable(reader)).toEqual([6n, 7n, 8n, 9n, 10n]); + expect(readable(reader)).toEqual([10n, 9n, 8n, 7n, 6n]); }); test("a live join reaches back by ticks rounded up, at any timestamp the track accepts", () => { @@ -1416,7 +1417,7 @@ test("a live join reaches back by ticks rounded up, at any timestamp the track a ranges: [{ start: { live: { min: Duration.micros(1500), max: Duration.ZERO } } }], }), ); - expect(readable(reader)).toEqual(starts); + expect(readable(reader)).toEqual(starts.toReversed()); }); test("a live join measures timestamps between ticks, floored", () => { @@ -1434,7 +1435,7 @@ test("a live join measures timestamps between ticks, floored", () => { ranges: [{ start: { live: { min: Duration.millis(1), max: Duration.ZERO } } }], }), ); - expect(readable(reader)).toEqual([1n, 2n]); + expect(readable(reader)).toEqual([2n, 1n]); }); test("a scale-less join reaches back by arrival", () => { @@ -1455,7 +1456,7 @@ test("a scale-less join reaches back by arrival", () => { ranges: [{ start: { live: { min: Duration.millis(2500), max: Duration.ZERO } } }], }), ); - expect(readable(reader)).toEqual([2n, 3n, 4n]); + expect(readable(reader)).toEqual([4n, 3n, 2n]); producer.close(); } finally { clock.installed.close(); @@ -1478,7 +1479,7 @@ test("a scale-less track ages by arrival alone", () => { } const subscribe = () => producer.subscribe(withMax({ delay: { max: Duration.millis(5) } })); // All three arrived at once, so however far apart their starts, none is stale yet. - expect(readable(subscribe())).toEqual([base, base + 10_000n, base + 20_000n]); + expect(readable(subscribe())).toEqual([base + 20_000n, base + 10_000n, base]); // Their successors arrived a full budget ago, and the newest has none to age it. clock.set(i * 1000 + 10); expect(readable(subscribe())).toEqual([base + 20_000n]); @@ -1489,6 +1490,86 @@ test("a scale-less track ages by arrival alone", () => { } }); +// Retiring a group written off at the bound keeps a lower group still buffered: it arrived after +// a newer one, so its own successor may be fresh. Mirrors the Rust +// `a_group_written_off_at_the_bound_keeps_a_fresh_lower_one_owed`. +test("a group written off at the bound keeps a fresh lower one buffered", () => { + const clock = manualTime(0); + try { + const producer = new TrackProducer("test").accept({ maxAge: Duration.millis(100) }); + const reader = producer.subscribe(withMax({ delay: { max: Duration.millis(100) } })); + const write = (key: bigint) => { + const group = producer.createGroup(key); + group.writeFrame(textFrame("x", Timestamp.unscaled(key))); + group.finishAt(key + 1n); + }; + write(3n); + clock.set(140); + write(2n); + write(1n); + // 2 went stale when 3 arrived a full budget ago, but 1's successor 2 arrived 10 ms ago. + clock.set(150); + expect(readable(reader)).toEqual([3n, 1n]); + producer.close(); + } finally { + clock.installed.close(); + } +}); + +// A peek offers a group a widened budget re-offers, as the take hands it out, so a front picking +// across copies by peek sees it. +test("a peek offers a group a widened budget re-offers", () => { + const clock = manualTime(0); + try { + const producer = new TrackProducer("test").accept({ maxAge: Duration.millis(1000) }); + const reader = producer.subscribe(withMax({ delay: { max: Duration.millis(5) } })); + const write = (key: bigint) => { + const group = producer.createGroup(key); + group.writeFrame(textFrame("x", Timestamp.unscaled(key))); + group.finishAt(key + 1n); + }; + write(7n); + write(8n); + expect(reader.tryRecvGroup()?.start).toBe(8n); + clock.set(10); + write(9n); + // 7's successor arrived 10 ms ago, past the 5 ms budget: skipped, not given up. + expect(readable(reader)).toEqual([9n]); + reader.update(withMax({ delay: { max: Duration.millis(1000) } })); + expect(hooks.peekGroup(reader, false)).toBe(7n); + expect(readable(reader)).toEqual([7n]); + producer.close(); + } finally { + clock.installed.close(); + } +}); + +// A read of disjoint ranges seeks past the cached groups between them in either Group Order, and +// keeps them for a widening. +test("an arrival read of disjoint ranges seeks past the groups between them", () => { + for (const [order, expected] of [ + ["descending", [8n, 7n, 2n, 1n, 0n]], + ["ascending", [0n, 1n, 2n, 7n, 8n]], + ] as const) { + const producer = new TrackProducer("test").accept({ maxAge: null }); + for (let key = 0n; key < 10n; key++) { + const group = producer.createGroup(key); + group.writeFrame(textFrame("x", Timestamp.unscaled(key))); + group.finishAt(key + 1n); + } + const ranges = [ + { start: 0n, end: 2n }, + { start: 7n, end: 8n }, + ]; + const reader = producer.subscribe(withMax({ delay: { max: null }, order, ranges })); + expect(hooks.peekGroup(reader, false)).toBe(expected[0]); + expect(readable(reader)).toEqual([...expected]); + reader.update(withMax({ delay: { max: null }, order, ranges: [{ start: 0n, end: 9n }] })); + expect(readable(reader).sort()).toEqual([3n, 4n, 5n, 6n, 9n]); + producer.close(); + } +}); + // A time start resolves on keys alone: groups opened before their first frames, below a // reached end, are read from the one containing it. Mirrors the Rust `a_time_start_needs_no_frame`. test("a time start resolves on keys alone, before any group's first frame", () => { @@ -1543,7 +1624,7 @@ test("time anchors resolve against group spans", () => { expect(drainGroups(inside)).toEqual([2000n]); expect(drainGroups(paused)).toEqual([2000n]); expect(drainGroups(atEnd)).toEqual([2000n]); - expect(drainGroups(from(0n, 1700n))).toEqual([0n, 1000n]); + expect(drainGroups(from(0n, 1700n))).toEqual([1000n, 0n]); // 2000 has no End, so it spans up to the next start. expect(holdings.containing(2500n, NO_MAX_DELAY)).toEqual({ at: 2000n }); producer.close(); @@ -1616,7 +1697,7 @@ test("an untimed track reads time anchors as keys", () => { untimed.accept({ maxAge: null }); for (const key of [0n, 5n, 10n, 15n]) untimed.appendGroup(Timestamp.unscaled(key)).finish(); const reader = untimed.subscribe(withMax({ delay: { max: null }, ranges: [{ start: 7n, end: 10n }] })); - expect(readable(reader)).toEqual([5n, 10n]); + expect(readable(reader)).toEqual([10n, 5n]); }); // A moq-transport frame's time is its Group ID, so its starts never rewind and index like any. @@ -1630,7 +1711,7 @@ test("a moq-transport copy resolves a time anchor", () => { ranges: [{ start: 1500n }], }), ); - expect(readable(reader)).toEqual([1000n, 2000n]); + expect(readable(reader)).toEqual([2000n, 1000n]); }); test("live joins of one lag aggregate under the widest max, an omitted one being zero", () => { @@ -1710,7 +1791,7 @@ test.each([false, true])("a reordered tail keeps the group PTS drift verdict (B- const clock = manualTime(0); try { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe(withMax({ delay: { max: Duration.millis(80) } })); + const subscriber = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(80) } })); for (const ms of [0, 100]) { const group = hooks.appendNext(producer); group.writeFrame({ payload: new Uint8Array(), timestamp: Timestamp.fromMillis(ms) }); @@ -1736,7 +1817,7 @@ test.each([false, true])("a reordered tail keeps the group PTS drift verdict (B- // its first timestamp would discard exactly the group being filled. test("a long group is not stale while its tail reaches the edge", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); - const sub = producer.subscribe(withMax({ delay: { max: Duration.millis(500) } })); + const sub = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(500) } })); // Group 0 spans 0..2000ms; group 2000 starts there, where group 0 ends. const long = hooks.appendNext(producer); @@ -1752,7 +1833,7 @@ test("a long group is not stale while its tail reaches the edge", async () => { test("a long group is stale once its successor falls behind", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); - const sub = producer.subscribe(withMax({ delay: { max: Duration.millis(500) } })); + const sub = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(500) } })); const long = hooks.appendNext(producer); for (const ms of [0, 500, 1000]) { @@ -1806,14 +1887,14 @@ test("a frameless successor leaves the next started group as the bound", async ( producer.writeFrame({ payload: enc.encode("3"), timestamp: Timestamp.fromMillis(11_000) }); // Groups 0 and 1 both reach at most group 10000's start, a second behind the edge: stale. - expect(drain(track)).toEqual([10_000n, 11_000n]); + expect(drain(track)).toEqual([11_000n, 10_000n]); }); // Groups can arrive out of sequence order; the immediate successor bounds reach even when it // arrived last. test("a late-arriving successor bounds a group's reach", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); - const track = producer.subscribe(withMax({ delay: { max: Duration.millis(500) } })); + const track = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(500) } })); for (const [key, ms] of [ [0n, 0], @@ -1941,7 +2022,7 @@ test("the default joins live under a zero max, and history sets no limit", async // History leaves the publisher's max age as the only bound. const unlimited = producer.subscribe({ ranges: [{}] }); - for (const key of [0n, 1000n, 2000n]) expect((await unlimited.recvGroup())?.start).toBe(key); + for (const key of [2000n, 1000n, 0n]) expect((await unlimited.recvGroup())?.start).toBe(key); expect(hooks.tailGrace(producer)).toEqual(Duration.millis(5000)); producer.finish(); producer.close(); @@ -1949,7 +2030,7 @@ test("the default joins live under a zero max, and history sets no limit", async test("latency budget admits groups within its presentation-time window", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); - const track = producer.subscribe(withMax({ delay: { max: Duration.millis(1500) } })); + const track = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(1500) } })); for (const timestamp of [0, 1000, 2000]) { producer.writeFrame({ payload: enc.encode(`${timestamp}`), timestamp: Timestamp.fromMillis(timestamp) }); @@ -1973,7 +2054,7 @@ test("a late lower group within the budget is delivered", async () => { group.finish(); } - const track = producer.subscribe(withMax({ delay: { max: Duration.millis(5000) } })); + const track = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(5000) } })); expect((await track.recvGroup())?.start).toBe(5n); expect((await track.recvGroup())?.start).toBe(6n); expect((await track.recvGroup())?.start).toBe(7n); @@ -2018,7 +2099,7 @@ test("the ordered cursor sheds a stale backlog", async () => { test("the budget is clamped to the publisher's maxAge", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(1500) }); - const track = producer.subscribe(withMax({ delay: { max: Duration.millis(60_000) } })); + const track = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(60_000) } })); // Spaced so group 0's reach (2s) sits 2s behind the edge (4s): outside the // publisher's 1.5s window, inside the subscriber's requested minute. @@ -2287,7 +2368,7 @@ test("a stalled track serves only its newest group", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(1000) }); try { for (const millis of [0, 10, 20]) appendAt(producer, millis); - expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1000) } })))).toEqual([0n, 1n, 2n]); + expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1000) } })))).toEqual([2n, 1n, 0n]); // Nothing is written again: media time stands still. clock.set(12_000); @@ -2313,9 +2394,9 @@ test("frozen timestamps still age out by wall clock", () => { frame(); // Group 0's successor arrived 800ms ago, group 1's just now. - expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1000) } })))).toEqual([0n, 1n, 2n]); + expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1000) } })))).toEqual([2n, 1n, 0n]); clock.set(11_500); - expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1000) } })))).toEqual([1n, 2n]); + expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1000) } })))).toEqual([2n, 1n]); clock.set(12_500); expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1000) } })))).toEqual([2n]); } finally { @@ -2334,7 +2415,7 @@ test("a startup burst ages out by media time", () => { for (let second = 0; second < 5; second++) appendAt(producer, second * 1000); // Group N reaches N + 1 seconds against the 4s edge: groups 0 and 1 are 3s and 2s // behind, past 1.5s. Their successors arrived just now. - expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1500) } })))).toEqual([2n, 3n, 4n]); + expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1500) } })))).toEqual([4n, 3n, 2n]); } finally { producer.finish(); producer.close(); @@ -2575,7 +2656,7 @@ test("retention reclaims a group the publisher abandoned open", async () => { const clock = manualTime(10_000); try { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); - const track = producer.subscribe(withMax({ delay: { max: Duration.millis(100) } })); + const track = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(100) } })); const stalled = hooks.appendNext(producer); stalled.writeFrame(textFrame("first", Timestamp.fromMillis(Number(stalled.start)))); // A successor, so the stalled group is not the live edge the publisher is @@ -2587,7 +2668,7 @@ test("retention reclaims a group the publisher abandoned open", async () => { expect(await group.readString()).toBe("first"); clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe(withMax({ delay: { max: Duration.millis(100) } })); + producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(100) } })); // A gap, not a clean finish: the publisher never ended this group. await expect(group.readFrame()).rejects.toBeInstanceOf(TooFarBehind); @@ -2631,7 +2712,9 @@ test("an abandoned open group ages out with no further write", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); try { // A budget past the cache window, so the eviction rather than the budget ends it. - const track = producer.subscribe(withMax({ delay: { max: Duration.millis(2 * CACHE_WINDOW_MS) } })); + const track = producer.subscribe( + withMax({ order: "ascending", delay: { max: Duration.millis(2 * CACHE_WINDOW_MS) } }), + ); const stalled = hooks.appendNext(producer); stalled.writeFrame(textFrame("first", Timestamp.fromMillis(Number(stalled.start)))); hooks.appendNext(producer); @@ -2702,7 +2785,7 @@ test("system clock changes do not affect the latency budget", async () => { clock.stepWall(10_000); try { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); - const track = producer.subscribe(withMax({ delay: { max: Duration.millis(100) } })); + const track = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(100) } })); appendFrozen(producer, "old"); clock.stepWall(20_000); @@ -2760,39 +2843,50 @@ test("an aborted live-edge anchor does not make older content stale", async () = // A join reaching back past every group under a zero max: the aborted group is no live edge, so // the older one is the newest it judges by. - const track = producer.subscribe({ ranges: [{ start: { live: { min: null, max: Duration.ZERO } } }] }); + const track = producer.subscribe({ + order: "ascending", + ranges: [{ start: { live: { min: null, max: Duration.ZERO } } }], + }); expect((await track.recvGroup())?.start).toBe(1n); track.close(); }); -test.each(["arrival", "ordered"] as const)("subscription bounds stay reader-local for %s reads", async (order) => { +test.each([ + ["arrival", "descending"], + ["arrival", "ascending"], + ["ordered", "descending"], +] as const)("subscription bounds stay reader-local for %s reads, %s", async (mode, order) => { const producer = new TrackProducer("test"); const everything = producer.subscribe({ ranges: [{}] }); - const subscriber = producer.subscribe({ ranges: [{ start: 1n, end: 2n }] }); - const ordered = order === "ordered" ? subscriber.ordered() : undefined; + const subscription = (range: { start?: bigint; end?: bigint }) => ({ ranges: [range], order }); + const subscriber = producer.subscribe(subscription({ start: 1n, end: 2n })); + const ordered = mode === "ordered" ? subscriber.ordered() : undefined; const read = () => (ordered ? ordered.nextGroup() : subscriber.recvGroup()); try { for (let key = 0n; key < 5n; key++) producer.createGroup(key); - expect((await everything.recvGroup())?.start).toBe(0n); - expect((await read())?.start).toBe(1n); - expect((await read())?.start).toBe(2n); - // A bounded read ends once its window is read, as in Rust, though the track goes on. - expect(await read()).toBeUndefined(); - // Replacing the ranges reads on from the same reader. - subscriber.update({ ranges: [{ start: 3n, end: 3n }] }); - expect((await read())?.start).toBe(3n); - expect(await read()).toBeUndefined(); - subscriber.update({ ranges: [{ end: 4n }] }); - // Arrival readers can now offer the unread group below the old floors; ordered ones cannot - // rewind. Which goes first is the Group Order, not what this pins. Mirrors the Rust - // `a_widened_history_read_offers_a_group_it_passed_over`. - const widened: (bigint | undefined)[] = []; - for (let count = ordered ? 1 : 2; count > 0; count--) widened.push((await read())?.start); - widened.sort((a, b) => Number((a ?? 0n) - (b ?? 0n))); - expect(widened).toEqual(ordered ? [4n] : [0n, 4n]); - expect(await read()).toBeUndefined(); + expect((await everything.recvGroup())?.start).toBe(4n); + const got: (bigint | undefined)[] = []; + // Replacing the ranges reads on from the same reader. Arrival readers can then offer the + // unread group below the old floors, in Group Order with what they hold; ordered ones cannot + // rewind. Mirrors the Rust `a_widened_history_read_offers_a_group_it_passed_over`. + for (const [range, count] of [ + [undefined, 2], + [{ start: 3n, end: 3n }, 1], + [{ end: 4n }, ordered ? 1 : 2], + ] as const) { + if (range) subscriber.update(subscription(range)); + for (let left = count; left > 0; left--) got.push((await read())?.start); + // A bounded read ends once its window is read, as in Rust, though the track goes on. + expect(await read()).toBeUndefined(); + } + const want = { + ordered: [1n, 2n, 3n, 4n], + descending: [2n, 1n, 3n, 4n, 0n], + ascending: [1n, 2n, 3n, 0n, 4n], + }; + expect(got).toEqual(want[ordered ? "ordered" : order]); // An open range parks at the live edge instead. - subscriber.update({ ranges: [{ start: 5n }] }); + subscriber.update(subscription({ start: 5n })); const pending = read(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); producer.finish(); @@ -2853,13 +2947,13 @@ test("withRange with an excluded end of 0 is the empty range and does not ride a for (let key = 0n; key < 3n; key++) producer.createGroup(key); - expect((await everything.recvGroup())?.start).toBe(0n); + expect((await everything.recvGroup())?.start).toBe(2n); const pending = empty.recvGroup(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); empty.withRange({ end: { excluded: 2n } }); - expect((await pending)?.start).toBe(0n); - expect((await empty.recvGroup())?.start).toBe(1n); + expect((await pending)?.start).toBe(1n); + expect((await empty.recvGroup())?.start).toBe(0n); empty.withRange({}); expect((await empty.recvGroup())?.start).toBe(2n); @@ -2875,18 +2969,20 @@ for (const ordered of [false, true]) { .withRange({ end: { excluded: end } }); if (ordered) subscriber.ordered(); const read = () => (ordered ? hooks.tryNextGroup(subscriber) : hooks.tryRecvGroup(subscriber, false)); + // Key order, or the default Group Order, newest first. + const inOrder = (keys: bigint[]) => (ordered ? keys : keys.toReversed()); for (const key of [0n, 2n, 4n]) producer.createGroup(key).finish(); producer.finish(); producer.close(); - for (const key of [0n, 2n].filter((key) => key < end)) { + for (const key of inOrder([0n, 2n].filter((key) => key < end))) { expect(read()).toMatchObject({ kind: "group", group: { start: key } }); } expect(read()).toEqual({ kind: "done" }); // Ending a read preserves the cache for a later widened range. subscriber.withRange({}); - for (const key of [0n, 2n, 4n].filter((key) => key >= end)) { + for (const key of inOrder([0n, 2n, 4n].filter((key) => key >= end))) { expect(read()).toMatchObject({ kind: "group", group: { start: key } }); } expect(read()).toEqual({ kind: "done" }); @@ -2974,8 +3070,8 @@ test("withRange parks recvGroup beyond the cap and a raised cap re-offers", asyn for (let key = 0n; key < 3n; key++) producer.createGroup(key).finish(); track.withRange({ end: { excluded: 2n } }); - expect((await track.recvGroup())?.start).toBe(0n); expect((await track.recvGroup())?.start).toBe(1n); + expect((await track.recvGroup())?.start).toBe(0n); const pending = track.recvGroup(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); @@ -3003,8 +3099,8 @@ test("recvGroup serves in-range groups that arrive behind a capped one", async ( producer.createGroup(0n); producer.createGroup(1n); - expect((await track.recvGroup())?.start).toBe(0n); expect((await track.recvGroup())?.start).toBe(1n); + expect((await track.recvGroup())?.start).toBe(0n); const pending = track.recvGroup(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); @@ -3118,19 +3214,26 @@ test("closing the subscriber releases a recvGroup parked while the producer is l expect(await pending).toBeUndefined(); }); -test("the ordered and arrival cursors are independent", async () => { - const producer = new TrackProducer("test"); - const ordered = producer.subscribe({ ranges: [{}] }).ordered(); - const arrival = producer.subscribe({ ranges: [{}] }); - - producer.createGroup(5n); - expect((await ordered.nextGroup())?.start).toBe(5n); - - // A late seq 3 is skipped by the ordered cursor, which has already passed it, but the - // arrival cursor has both buffered and still delivers each exactly once. - producer.createGroup(3n); - expect((await arrival.recvGroup())?.start).toBe(3n); - expect((await arrival.recvGroup())?.start).toBe(5n); +// The ordered cursor reads in key order and the arrival cursor in the subscription's Group Order, +// each from what it holds, whichever group arrived first. Mirrors the Rust +// `ordered_and_arrival_cursors_are_independent`. +test.each([ + ["descending", 5n], + ["ascending", 3n], +] as const)("the ordered and arrival cursors are independent (%s)", async (order, first) => { + for (const arrivals of [ + [5n, 3n], + [3n, 5n], + ]) { + const producer = new TrackProducer("test"); + const ordered = producer.subscribe({ ranges: [{}], order }).ordered(); + const arrival = producer.subscribe({ ranges: [{}], order }); + for (const key of arrivals) producer.createGroup(key); + expect((await ordered.nextGroup())?.start).toBe(3n); + expect((await arrival.recvGroup())?.start).toBe(first); + producer.finish(); + producer.close(); + } }); // Both cursors draw from one buffer, so interleaving them produces a stream in neither @@ -3454,7 +3557,7 @@ test("a live-edge reader starts on an empty largest group", async () => { first.finish(); const empty = hooks.appendNext(producer); - const reader = producer.subscribe(withMax({ delay: { max: Duration.millis(30_000) } })); + const reader = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(30_000) } })); const edge = await reader.largest(); expect(edge).toEqual({ group: 1n, frame: 0 }); reader.withRange({ start: { included: edge?.group ?? 0n } }); @@ -3594,8 +3697,8 @@ test("finishAt declares an end ahead of the live edge without ending the track", late.finish(); const straggler = producer.createGroup(6n); straggler.finish(); - expect((await track.recvGroup())?.start).toBe(6n); expect((await track.recvGroup())?.start).toBe(7n); + expect((await track.recvGroup())?.start).toBe(6n); // A clean close keeps the declared end rather than the live edge. producer.finish(); @@ -3678,20 +3781,20 @@ test("no publisher limit still ages idle groups out", async () => { source.finish(); clock.set(10_000 + CACHE_WINDOW_MS - 1_000); hooks.appendNext(producer); - const within = producer.subscribe(withMax({ delay: { max: Duration.millis(100_000) } })); + const within = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(100_000) } })); expect(await (await within.recvGroup())?.readString()).toBe("old"); within.close(); // The read was an access, as in Rust: past the write's window, the group stays. Taking it // again is another access. clock.set(10_000 + CACHE_WINDOW_MS + 1_000); - const read = producer.subscribe(withMax({ delay: { max: Duration.millis(100_000) } })); + const read = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(100_000) } })); expect(read.tryRecvGroup()?.start).toBe(0n); read.close(); // Past that delivery's window, a subscribe's own scan reclaims it. clock.set(10_000 + 2 * CACHE_WINDOW_MS + 2_000); - const after = producer.subscribe(withMax({ delay: { max: Duration.millis(100_000) } })); + const after = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(100_000) } })); expect(after.tryRecvGroup()?.start).toBe(1n); expect(after.tryRecvGroup()).toBeUndefined(); after.close(); @@ -3792,8 +3895,10 @@ test("a late subscriber to a closed unlimited track is released once the cache a test("an abort keeps finished groups for a slow reader, then reports it", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(10_000) }); - const arrival = producer.subscribe(withMax({ delay: { max: Duration.millis(10_000) } })); - const ordered = producer.subscribe(withMax({ delay: { max: Duration.millis(10_000) } })).ordered(); + const arrival = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(10_000) } })); + const ordered = producer + .subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(10_000) } })) + .ordered(); for (let i = 0; i < 2; i++) { const group = hooks.appendNext(producer); group.writeFrame(textFrame(`g${i}`, Timestamp.fromMillis(Number(group.start)))); @@ -3816,8 +3921,10 @@ test("an abort keeps finished groups for a slow reader, then reports it", async test("an abort after the declared end settles ends clean", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(10_000) }); - const arrival = producer.subscribe(withMax({ delay: { max: Duration.millis(10_000) } })); - const ordered = producer.subscribe(withMax({ delay: { max: Duration.millis(10_000) } })).ordered(); + const arrival = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(10_000) } })); + const ordered = producer + .subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(10_000) } })) + .ordered(); for (let i = 0; i < 2; i++) { const group = hooks.appendNext(producer); group.writeFrame(textFrame(`g${i}`, Timestamp.fromMillis(Number(group.start)))); @@ -4006,9 +4113,9 @@ test("unknown track metadata keeps presentation-time expiry until accepted", () for (let second = 0; second < 4; second++) appendAt(producer, second * 1000); // No wall time passes. Until metadata is accepted, buffered timestamps still // prove that the two oldest groups are outside this reader's media budget. - expect(drain(before)).toEqual([2n, 3n]); + expect(drain(before)).toEqual([3n, 2n]); producer.accept({ timescale: Timescale.MILLI, maxAge: null }); - expect(drain(after)).toEqual([2n, 3n]); + expect(drain(after)).toEqual([3n, 2n]); } finally { producer.finish(); producer.close(); @@ -4031,16 +4138,16 @@ test("an untimed subscriber starts at the oldest fresh group", () => { // Four seconds after group 4 arrived, groups 0 to 2 were superseded 4, 3, and 2 // seconds ago: past a 1.5s budget. Group 3 was superseded 1s ago. - expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1500) } })))).toEqual([3n, 4n]); + expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(1500) } })))).toEqual([4n, 3n]); // No budget takes the newest group alone, which is never stale. const live = producer.subscribe(); expect(drain(live)).toEqual([4n]); expect(drain(producer.subscribe(withMax({ delay: { max: Duration.millis(60_000) } })))).toEqual([ - 0n, - 1n, - 2n, - 3n, 4n, + 3n, + 2n, + 1n, + 0n, ]); producer.writeFrame({ payload: enc.encode("5"), timestamp: Timestamp.unscaled(5n) }); @@ -4062,7 +4169,7 @@ test("an untimed subscriber without a start begins at the latest group under its test("a single-frame write that throws aborts its group", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe(withMax({ delay: { max: Duration.millis(60_000) } })); + const subscriber = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(60_000) } })); // A mismatched timestamp is refused before any group exists. expect(() => producer.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.unscaled(0n) })).toThrow( TimestampMismatch, @@ -4094,7 +4201,7 @@ test("a scale-less single-frame write lands at its key", () => { TimestampMismatch, ); producer.writeFrame({ payload: enc.encode("c"), timestamp: Timestamp.unscaled(5n) }); - expect(drain(subscriber)).toEqual([3n, 5n]); + expect(drain(subscriber)).toEqual([5n, 3n]); // The keys below each write are skipped, so creating one is refused. expect(() => producer.createGroup(4n)).toThrow(Skipped); }); @@ -4143,7 +4250,7 @@ test("a group ended by a cancel or cache policy is a hole, not a drop", async () test("an upstream drop ends a group still arriving with its error", async () => { const producer = new TrackProducer("video").accept({ maxAge: null }); - const reader = producer.subscribe(withMax({ delay: { max: Duration.millis(60_000) } })); + const reader = producer.subscribe(withMax({ order: "ascending", delay: { max: Duration.millis(60_000) } })); const arriving = producer.createGroup(3n); arriving.writeFrame({ payload: enc.encode("3"), timestamp: Timestamp.unscaled(arriving.start) }); const finished = producer.createGroup(4n); @@ -4805,7 +4912,7 @@ test("an unanswered copy places a join past every group at once", () => { const subscriber = producer.subscribe(withMax({ delay: { max: Duration.secs(1) } })); putGroup(producer, 0n); putGroup(producer, 1n); - expect(drainGroups(subscriber)).toEqual([0n, 1n]); + expect(drainGroups(subscriber)).toEqual([1n, 0n]); }); test("a re-created group is handed out once", () => { @@ -4813,7 +4920,7 @@ test("a re-created group is handed out once", () => { const subscriber = producer.subscribe(withMax({ delay: { max: Duration.millis(30_000) } })); stampGroup(producer, 0n, 0); const aborted = producer.createGroup(1n); - expect(drainGroups(subscriber)).toEqual([0n, 1n]); + expect(drainGroups(subscriber)).toEqual([1n, 0n]); aborted.abort(new Error("aborted")); stampGroup(producer, 1n, 1); @@ -4835,7 +4942,7 @@ test("a gap is forgotten once a group above it is past the budget", () => { const subscriber = producer.subscribe(withMax({ delay: { max: maxDelay } })); // Group 3 never arrives. for (const key of [0n, 1n, 2n, 4n, 5n, 6n]) stampGroup(producer, key, Number(key)); - expect(drainGroups(subscriber)).toEqual([0n, 1n, 2n, 4n, 5n, 6n]); + expect(drainGroups(subscriber)).toEqual([6n, 5n, 4n, 2n, 1n, 0n]); // Group 4 reaches until group 5 presents at 5ms, so it is past a 10ms budget once the // edge presents at 15ms. for (let key = 7n; key <= 14n; key++) { @@ -5027,42 +5134,46 @@ test("an untimed track takes groups in any order", () => { } }); -test("replay and backlogs deliver sparse out-of-order arrivals ascending without sorting", () => { - const producer = new TrackProducer("test").accept({ maxAge: null }); - const all = withMax({ ranges: [{ start: 0n }], delay: { max: null } }); - const write = (key: bigint) => { - const group = producer.createGroup(key); - group.writeFrame({ payload: enc.encode(`${key}`), timestamp: Timestamp.unscaled(group.start) }); - group.finish(); - }; - const drain = (reader: ReturnType) => { - const seen: bigint[] = []; - for (let group = reader.tryRecvGroup(); group; group = reader.tryRecvGroup()) { - const frame = group.tryReadFrame(); - expect(frame && dec.decode(frame.payload)).toBe(`${group.start}`); - seen.push(group.start); +test.each(["descending", "ascending"] as const)( + "replay and backlogs deliver sparse out-of-order arrivals in %s order without sorting", + (order) => { + const producer = new TrackProducer("test").accept({ maxAge: null }); + const all = withMax({ ranges: [{ start: 0n }], delay: { max: null }, order }); + const write = (key: bigint) => { + const group = producer.createGroup(key); + group.writeFrame({ payload: enc.encode(`${key}`), timestamp: Timestamp.unscaled(group.start) }); + group.finish(); + }; + const drain = (reader: ReturnType) => { + const seen: bigint[] = []; + for (let group = reader.tryRecvGroup(); group; group = reader.tryRecvGroup()) { + const frame = group.tryReadFrame(); + expect(frame && dec.decode(frame.payload)).toBe(`${group.start}`); + seen.push(group.start); + } + return seen; + }; + const sort = spyOn(Array.prototype, "sort"); + try { + const live = producer.subscribe(all); + // Subscribing merges the subscribers' ranges, which sorts them; only arrivals are judged. + sort.mockClear(); + for (const key of [40n, 10n, 30n, 0n, 20n]) write(key); + expect(sort).not.toHaveBeenCalled(); + const joined = producer.subscribe(all); + sort.mockClear(); + // Arrivals below, between and above the joiner's replayed cache. + for (const key of [25n, 50n, 5n, 35n]) write(key); + expect(sort).not.toHaveBeenCalled(); + const ascending = [0n, 5n, 10n, 20n, 25n, 30n, 35n, 40n, 50n]; + const expected = order === "ascending" ? ascending : ascending.toReversed(); + expect(drain(live)).toEqual(expected); + expect(drain(joined)).toEqual(expected); + } finally { + sort.mockRestore(); } - return seen; - }; - const sort = spyOn(Array.prototype, "sort"); - try { - const live = producer.subscribe(all); - // Subscribing merges the subscribers' ranges, which sorts them; only arrivals are judged. - sort.mockClear(); - for (const key of [40n, 10n, 30n, 0n, 20n]) write(key); - expect(sort).not.toHaveBeenCalled(); - const joined = producer.subscribe(all); - sort.mockClear(); - // Arrivals below, between and above the joiner's replayed cache. - for (const key of [25n, 50n, 5n, 35n]) write(key); - expect(sort).not.toHaveBeenCalled(); - const expected = [0n, 5n, 10n, 20n, 25n, 30n, 35n, 40n, 50n]; - expect(drain(live)).toEqual(expected); - expect(drain(joined)).toEqual(expected); - } finally { - sort.mockRestore(); - } -}); + }, +); // A received track as a wire subscription leaves it: the feed starts at group 0 and its end is // pending, so lower groups may still arrive behind a higher one. Read from the oldest group unless @@ -5287,8 +5398,8 @@ test("an end after the highest group holds the reader at the hole", async () => const low = producer.createGroup(key); low.finish(); } - expect((await next)?.start).toBe(0n); - expect((await reader.recvGroup())?.start).toBe(1n); + expect((await next)?.start).toBe(1n); + expect((await reader.recvGroup())?.start).toBe(0n); expect(await reader.recvGroup()).toBeUndefined(); producer.finish(); producer.close(); @@ -5312,8 +5423,8 @@ test("an abort after a full tail ends cleanly", async () => { write(1n); write(0n); producer.abort(new Error("dropped")); - expect((await reader.recvGroup())?.start).toBe(0n); expect((await reader.recvGroup())?.start).toBe(1n); + expect((await reader.recvGroup())?.start).toBe(0n); expect(await reader.recvGroup()).toBeUndefined(); expect(await reader.closed).toBeNull(); }); @@ -5405,10 +5516,10 @@ test("a widened maxDelay re-offers what it skipped as stale", () => { stampGroup(producer, key, ms); } // Groups 1 and 2 reach 2s and 3s, at least 1.5s behind the 6s edge. - expect(drainGroups(subscriber)).toEqual([3n, 4n]); + expect(drainGroups(subscriber)).toEqual([4n, 3n]); subscriber.update(withMax({ delay: { max: Duration.millis(10_000) } })); - expect(drainGroups(subscriber)).toEqual([1n, 2n]); + expect(drainGroups(subscriber)).toEqual([2n, 1n]); expect(drainGroups(subscriber)).toEqual([]); producer.close(); }); @@ -5428,14 +5539,14 @@ test("a stale skip may be taken only once the budget widens", () => { ] as const) { stampGroup(producer, key, ms); } - expect(drainGroups(subscriber)).toEqual([3n, 4n]); + expect(drainGroups(subscriber)).toEqual([4n, 3n]); expect(hooks.taking(subscriber)(0n)).toBe(false); expect(hooks.taking(subscriber)(1n)).toBe(false); expect(hooks.taking(subscriber)(5n)).toBe(true); subscriber.update(withMax({ delay: { max: Duration.millis(10_000) } })); expect(hooks.taking(subscriber)(1n)).toBe(true); - expect(drainGroups(subscriber)).toEqual([1n, 2n]); + expect(drainGroups(subscriber)).toEqual([2n, 1n]); expect(hooks.taking(subscriber)(1n)).toBe(false); producer.close(); }); @@ -5457,12 +5568,14 @@ test("a stale skip may not be taken once its successors leave", async () => { stampGroup(producer, key, ms); } // Groups 1 and 2 reach 2 and 3 windows, at least 4 behind the edge. - expect(drainGroups(subscriber)).toEqual([3n, 4n]); + expect(drainGroups(subscriber)).toEqual([4n, 3n]); // Another reader keeps group 1 cached while 2 and 3 idle out, leaving the edge to bound // its reach. await clock.advance(10_000 + window - 1); - const keeper = producer.subscribe(withMax({ delay: { max: null }, ranges: [{ start: 1n, end: 2n }] })); + const keeper = producer.subscribe( + withMax({ order: "ascending", delay: { max: null }, ranges: [{ start: 1n, end: 2n }] }), + ); expect(keeper.tryRecvGroup()?.start).toBe(1n); await clock.advance(10_000 + window + SWEEP_LAG_MS + 1); await settle(); @@ -5500,7 +5613,7 @@ test("a stale skip at the max age bound may not be taken", async () => { ] as const) { stampGroup(producer, key, ms); } - expect(drainGroups(subscriber)).toEqual([3n, 4n]); + expect(drainGroups(subscriber)).toEqual([4n, 3n]); subscriber.update(withMax({ delay: { max: Duration.millis(100 * window) } })); expect(drainGroups(subscriber)).toEqual([]); @@ -5509,7 +5622,9 @@ test("a stale skip at the max age bound may not be taken", async () => { // Another reader keeps group 1 cached while 2 and 3 idle out. await clock.advance(10_000 + window - 1); - const keeper = producer.subscribe(withMax({ delay: { max: null }, ranges: [{ start: 1n, end: 2n }] })); + const keeper = producer.subscribe( + withMax({ order: "ascending", delay: { max: null }, ranges: [{ start: 1n, end: 2n }] }), + ); expect(keeper.tryRecvGroup()?.start).toBe(1n); await clock.advance(10_000 + window + SWEEP_LAG_MS + 1); await settle(); @@ -5552,7 +5667,7 @@ test("a widened maxDelay wakes a parked read", async () => { stampGroup(producer, key, ms); } // Group 1 reaches 2s, 4s behind the 6s edge. - expect(drainGroups(subscriber)).toEqual([2n, 3n]); + expect(drainGroups(subscriber)).toEqual([3n, 2n]); const parked = subscriber.recvGroup(); subscriber.update(withMax({ delay: { max: Duration.millis(10_000) } })); @@ -5576,7 +5691,7 @@ test("an evicted stale skip lets the delivered gaps fold", () => { stampGroup(producer, 1n, 1); stampGroup(producer, 2n, 5); stampGroup(producer, 3n, 30); - expect(drainGroups(subscriber)).toEqual([2n, 3n]); + expect(drainGroups(subscriber)).toEqual([3n, 2n]); // Past the cache window, so the next write evicts group 1. time.set(1_000 + 2 * CACHE_WINDOW_MS); @@ -5608,7 +5723,7 @@ test("a widened maxDelay re-offers nothing below a raised floor", () => { ] as const) { stampGroup(producer, key, ms); } - expect(drainGroups(subscriber)).toEqual([3n, 4n]); + expect(drainGroups(subscriber)).toEqual([4n, 3n]); subscriber.update(withMax({ delay: { max: Duration.millis(10_000) }, ranges: [{ start: 2n }] })); expect(drainGroups(subscriber)).toEqual([2n]); @@ -5632,7 +5747,7 @@ for (const reported of [false, true]) { stampGroup(producer, key, ms); } // Group 1 reaches 2s, 4s behind the 6s edge. - expect(drainGroups(subscriber)).toEqual([2n, 3n]); + expect(drainGroups(subscriber)).toEqual([3n, 2n]); if (reported) { expect(hooks.tryDrop(subscriber)).toMatchObject({ start: 1n, end: 2n }); @@ -5656,7 +5771,7 @@ test("an unreported stale skip below an idle start is left to a widening", () => stampGroup(producer, 1n, 1000); stampGroup(producer, 2n, 6000); // Groups 0 and 1 reach 1s and 6s; only group 0 is 1.5s behind the 6s edge. - expect(drainGroups(subscriber)).toEqual([1n, 2n]); + expect(drainGroups(subscriber)).toEqual([2n, 1n]); expect(hooks.tryDrop(subscriber)).toMatchObject({ start: 0n, end: 1n }); // SUBSCRIBE_START resolved at group 1 with the skip still held for it. @@ -5683,7 +5798,7 @@ test("a partial maxDelay widening keeps the older skip owed", () => { ] as const) { stampGroup(producer, key, ms); } - expect(drainGroups(subscriber)).toEqual([2n, 3n]); + expect(drainGroups(subscriber)).toEqual([3n, 2n]); for (const [key, ms] of [ [4n, 5000], [5n, 6000], @@ -5691,7 +5806,7 @@ test("a partial maxDelay widening keeps the older skip owed", () => { ] as const) { stampGroup(producer, key, ms); } - expect(drainGroups(subscriber)).toEqual([5n, 6n]); + expect(drainGroups(subscriber)).toEqual([6n, 5n]); // Group 4 reaches 6s, 3s behind the 9s edge; group 1 reaches 2s, 7s behind. subscriber.update(withMax({ delay: { max: Duration.millis(4000) } })); @@ -5759,8 +5874,8 @@ test("a failed track keeps its history", async () => { const replay = withMax({ ranges: [{ start: 0n }], delay: { max: Duration.millis(30_000) } }); const arrival = producer.subscribe(replay); - expect((await arrival.recvGroup())?.start).toBe(0n); expect((await arrival.recvGroup())?.start).toBe(1n); + expect((await arrival.recvGroup())?.start).toBe(0n); await expect(arrival.recvGroup()).rejects.toBe(failed); const ordered = producer.subscribe(replay).ordered(); @@ -5770,8 +5885,8 @@ test("a failed track keeps its history", async () => { // The nonblocking reads end the same way. const polled = producer.subscribe(replay); - expect(polled.tryRecvGroup()?.start).toBe(0n); expect(polled.tryRecvGroup()?.start).toBe(1n); + expect(polled.tryRecvGroup()?.start).toBe(0n); expect(() => polled.tryRecvGroup()).toThrow(failed); const polledOrdered = producer.subscribe(replay).ordered(); expect(polledOrdered.tryNextGroup()?.start).toBe(0n); @@ -5793,8 +5908,8 @@ test("fail ends at the live edge and leaves an end already given", async () => { late.writeFrame(textFrame("b", Timestamp.fromMillis(1))); late.finish(); const sub = producer.subscribe(withMax({ ranges: [{ start: 1n }], delay: { max: Duration.millis(30_000) } })); - expect((await sub.recvGroup())?.start).toBe(1n); expect((await sub.recvGroup())?.start).toBe(2n); + expect((await sub.recvGroup())?.start).toBe(1n); await expect(sub.recvGroup()).rejects.toBe(failed); producer.close(); @@ -5850,7 +5965,7 @@ test("an append skips the holes created groups left below it", () => { producer.createGroup(0n).finish(); hooks.dropTrackGroups(producer, 2n, 3n, { error: DROPPED }); producer.createGroup(4n).finish(); - expect(drain()).toEqual([[2n, 3n, false], 0n, 4n]); + expect(drain()).toEqual([[2n, 3n, false], 4n, 0n]); hooks.appendNext(producer).finish(); expect(drain()).toEqual([[1n, 4n, true], 5n]); @@ -5858,7 +5973,7 @@ test("an append skips the holes created groups left below it", () => { // The next append only names what was left since this one. producer.createGroup(7n).finish(); hooks.appendNext(producer).finish(); - expect(drain()).toEqual([[6n, 7n, true], 7n, 8n]); + expect(drain()).toEqual([[6n, 7n, true], 8n, 7n]); const copy = new TrackProducer("test"); hooks.receiveTrack(copy); @@ -5993,7 +6108,7 @@ test("a skip is reported over a reported drop", () => { hooks.dropTrackGroups(producer, 1n, 3n, { error: DROPPED }); hooks.dropTrackGroups(producer, 4n, 5n, { error: DROPPED }); producer.createGroup(5n).finish(); - expect(drain()).toEqual([[1n, 3n, false], [4n, 5n, false], 0n, 5n]); + expect(drain()).toEqual([[1n, 3n, false], [4n, 5n, false], 5n, 0n]); // Group 0 arrived, so the skip leaves it; both drops and the gap between become one skip. expect(hooks.skipTrackGroups(producer, 0n, 5n)).toEqual([{ start: 0n, end: 1n }]); @@ -6031,7 +6146,7 @@ test("a huge skip costs one run", () => { if (next.kind === "group") got.push(next.group.start); else if (next.kind === "drop") got.push([next.start, next.end, next.skip === true]); } - const groups = append ? [0n, FAR, FAR + 1n] : [0n, FAR]; + const groups = append ? [FAR + 1n, FAR, 0n] : [FAR, 0n]; expect(got.filter((entry) => typeof entry === "bigint")).toEqual(groups); expect(got.filter((entry) => typeof entry !== "bigint")).toEqual([[1n, FAR, true]]); } @@ -6109,6 +6224,7 @@ test("track: a received copy places a live join only from a fresh answer", () => const producer = receivedTrack({ timescale: Timescale.MILLI }); hooks.answersJoins(producer); const join = withMax({ + order: "ascending", delay: { max: null }, ranges: [{ start: { live: { min: Duration.millis(200), max: Duration.ZERO } }, end: 9000n }], }); @@ -6323,8 +6439,8 @@ test("track: a received copy keeps a join answer past its declared end", () => { producer.finishAt({ group: 7001n, frame: 0 }); putGroup(producer, 4000n, 4000); putGroup(producer, 6000n, 6000); - expect(reader.tryRecvGroup()?.start).toBe(4000n); expect(reader.tryRecvGroup()?.start).toBe(6000n); + expect(reader.tryRecvGroup()?.start).toBe(4000n); const later = producer.subscribe(join); expect(later.tryRecvGroup()?.start).not.toBe(4000n); } finally { @@ -6580,8 +6696,8 @@ test("a kept-out fill is withdrawn when the range moves", async () => { group.finish(); } const sub = producer.subscribe({ ranges: [{ start: 0n, end: 6n }] }); - expect(sub.tryRecvGroup()?.start).toBe(0n); expect(sub.tryRecvGroup()?.start).toBe(6n); + expect(sub.tryRecvGroup()?.start).toBe(0n); sub.withRange({ start: { included: 6n }, end: { excluded: 7n } }); const ended = sub.recvGroup(); producer.skipGroups(3n, 6n); @@ -6627,8 +6743,8 @@ test("a kept-out fill is withdrawn when the feed ends", async () => { group.finish(); } const sub = producer.subscribe({ ranges: [{ start: 0n, end: 6n }] }); - expect(sub.tryRecvGroup()?.start).toBe(0n); expect(sub.tryRecvGroup()?.start).toBe(6n); + expect(sub.tryRecvGroup()?.start).toBe(0n); sub.withRange({ start: { included: 6n }, end: { excluded: 7n } }); const ended = sub.recvGroup(); producer.skipGroups(3n, 6n); @@ -6670,8 +6786,8 @@ test("a kept-out key a fill refused stays given up once the read ends", async () group.finish(); } const sub = producer.subscribe({ ranges: [{ start: 0n, end: 6n }] }); - expect(sub.tryRecvGroup()?.start).toBe(0n); expect(sub.tryRecvGroup()?.start).toBe(6n); + expect(sub.tryRecvGroup()?.start).toBe(0n); sub.withRange({ start: { included: 6n }, end: { excluded: 7n } }); const ended = sub.recvGroup(); producer.skipGroups(3n, 6n); @@ -6722,8 +6838,8 @@ test("a forgotten kept-out run is judged by each range's budget", async () => { { start: { live: { min: null, max: Duration.millis(1_000) } }, end: 7n }, ], }); - expect(sub.tryRecvGroup()?.start).toBe(0n); expect(sub.tryRecvGroup()?.start).toBe(6n); + expect(sub.tryRecvGroup()?.start).toBe(0n); sub.withRange({ start: { included: 6n }, end: { excluded: 8n } }); const next = sub.recvGroup(); producer.skipGroups(1n, 6n); @@ -6782,8 +6898,8 @@ test("a bounded read asks again for a kept-out skip its track forgot", async () group.finish(); } const sub = producer.subscribe({ ranges: [{ start: 0n, end: 6n }] }); - expect(sub.tryRecvGroup()?.start).toBe(0n); expect(sub.tryRecvGroup()?.start).toBe(6n); + expect(sub.tryRecvGroup()?.start).toBe(0n); sub.withRange({ start: { included: 6n }, end: { excluded: 7n } }); const ended = sub.recvGroup(); producer.skipGroups(3n, 6n); diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 5163981421c..c0443218a36 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -410,7 +410,8 @@ export interface Subscription { */ ranges?: Range[]; /** - * Which pending group the publisher sends first. Defaults to `"descending"`. + * Which group comes first, as the publisher sends them and {@link Subscriber.recvGroup} returns + * those held. Defaults to `"descending"`. * * Carried by moq-lite 07 and moq-transport (fixed at subscribe time there); older * moq-lite versions are served newest first whatever this says. @@ -432,11 +433,12 @@ export interface Subscription { } /** - * Which of a subscription's pending groups the publisher sends first: `"descending"` (newest - * first, so congestion sheds the backlog rather than the live edge) or `"ascending"` (oldest - * first, draining a backlog in sequence order). + * Which of a subscription's groups comes first, as the publisher sends its pending groups and + * {@link Subscriber.recvGroup} hands out the groups it holds: `"descending"` (newest first, so + * congestion sheds the backlog rather than the live edge) or `"ascending"` (oldest first, draining + * a backlog in sequence order). * - * A transmission order only: it never decides whether a group is delivered. A history range + * An order only: it never decides whether a group is delivered. A history range * delivers every group it covers, and a live join skips what its {@link Live.max} judges stale, so * an ascending subscriber that wants a backlog drains it from a history range or a `max` that * covers it. @@ -3447,6 +3449,8 @@ export class Subscriber { #skipped = new Map(); // At most the narrowest budget in #skipped, so a read whose widest budget did not pass it skips the scan. #narrowest = Number.POSITIVE_INFINITY; + // The budget #reoffer last judged #skipped under, so a read under an equal one skips the scan. + #reofferedUnder: Budget | undefined; // This reader closed itself, so lowering its floor offers nothing: a producer's clean close // alone leaves the cache readable, but the reader leaving must stay terminal. Leaving also // settles the shared `#state.closed`, so a guard for either close reads that alone. @@ -3933,8 +3937,11 @@ export class Subscriber { // Forget the gaps in `delivered` below each group past this subscriber's budget now, whether // this track holds it or not: one landing there would be written off. A group skipped as - // stale is not forgotten, since a wider budget offers it again. - #forgetPastBudget(delivered: Delivered, budget = this.#window.budget()): void { + // stale is not forgotten, since a wider budget offers it again, and neither is one still + // buffered unread: it may have arrived after a newer one, so its own successor may be fresh. + // Mirrors the Rust `Cursor::forget_past_budget` keeping what the arrivals still owe. No gap at + // or above `keep` is forgotten either. + #forgetPastBudget(delivered: Delivered, budget = this.#window.budget(), keep?: bigint): void { if (delivered.aboveGap() === undefined) return; // One edge for every group judged, so forgetting N gaps never resolves it N times. const own = this.#drift(); @@ -3959,6 +3966,9 @@ export class Subscriber { if (producer && !cachedHolds(producer, key)) this.#skipped.delete(key); else skipped = min(skipped ?? key, key); } + const owed = this.#lowestBuffered(delivered); + if (owed !== undefined) skipped = min(skipped ?? owed, owed); + if (keep !== undefined) skipped = min(skipped ?? keep, keep); } if (skipped !== undefined && skipped < oldest) { delivered.forgetBelow(skipped); @@ -3972,6 +3982,18 @@ export class Subscriber { if (forgot !== undefined && delivered === this.#delivered) this.#judge(0n, forgot); } + // The lowest group buffered unread within this reader's range and window, not in `delivered`. + #lowestBuffered(delivered: Delivered): bigint | undefined { + const groups = this.#state.groups.peek(); + const { start, end } = this.#cursor.peek(); + for (let index = timelineIndex(groups, start); index < groups.length; index++) { + const key = groups[index].start; + if (end !== undefined && key >= end) return undefined; + if (this.#window.contains(key) && !delivered.has(key)) return key; + } + return undefined; + } + // Record `key` as skipped stale under `budget`, so a wider one offers it again. #skip(key: bigint, budget: number): void { this.#skipped.set(key, budget); @@ -3990,6 +4012,9 @@ export class Subscriber { // handed out or skipped again, so a newer one handed out first never folds it into #delivered. // Costs the skipped groups, never the cache. Mirrors the Rust `Skipped::widened`. #reoffer(budget: Budget): void { + // A skip is judged under the budget current then, so an equal one offers nothing again. + if (this.#reofferedUnder?.equals(budget)) return; + this.#reofferedUnder = budget; if (this.#skipped.size === 0 || budget.widest() <= this.#narrowest) return; const keys: bigint[] = []; let narrowest = Number.POSITIVE_INFINITY; @@ -4013,7 +4038,7 @@ export class Subscriber { } this.#narrowest = narrowest; const producer = this.#state.producer; - if (producer && !this.#left) reofferKeys(producer, this.#state, keys); + if (producer && !this.#left && keys.length > 0) reofferKeys(producer, this.#state, keys); } // The publisher's view of this reader's record. @@ -5180,10 +5205,12 @@ export class Subscriber { if (ordered) subscriber.#raiseNext(floor); return subscriber.#peekGroup(ordered); }; - hooks.forgetPastBudget = (subscriber, delivered, budget) => { - if (subscriber.#resume) subscriber.#resume.forgetPast(delivered, budget); - else subscriber.#forgetPastBudget(delivered, budget); + hooks.forgetPastBudget = (subscriber, delivered, budget, keep) => { + if (subscriber.#resume) subscriber.#resume.forgetPast(delivered, budget, keep); + else subscriber.#forgetPastBudget(delivered, budget, keep); }; + hooks.lowestBuffered = (subscriber, delivered) => + subscriber.#resume ? subscriber.#resume.lowestBuffered(delivered) : subscriber.#lowestBuffered(delivered); hooks.fold = (subscriber, at) => subscriber.#fold(at); hooks.untell = (subscriber, start, end) => { if (start >= end) return; @@ -5332,6 +5359,8 @@ export class Subscriber { hooks.latestKey = (subscriber) => (subscriber.#resume ? subscriber.#resume.latest() : subscriber.#state.latest); hooks.arrived = (subscriber) => (subscriber.#resume ? 0 : subscriber.#state.arrived); hooks.bufferedLargest = (subscriber) => subscriber.#bufferedLargest(); + hooks.lowestUnread = (subscriber, below) => subscriber.#lowestUnread(below); + hooks.heldAt = (subscriber, key) => subscriber.#heldAt(key); hooks.objectLargest = (subscriber) => { if (subscriber.#resume) return subscriber.#resume.objectLargest(); const producer = subscriber.#state.producer; @@ -5535,6 +5564,43 @@ export class Subscriber { } } + // The lowest group held unread below `below`, in the window and servable from the frame asked. + // Mirrors the Rust `Cursor::lowest_unread` and the publisher's `servable`. + #lowestUnread(below: bigint): bigint | undefined { + if (this.#resume) return this.#resume.lowestUnread(below); + const { start } = this.#cursor.peek(); + const groups = this.#state.groups.peek(); + for (let index = timelineIndex(groups, start); index < groups.length; index++) { + const group = groups[index]; + if (group.start >= below) return undefined; + if (!this.#window.contains(group.start) || this.#delivered.has(group.start)) continue; + if (!this.#lacksHead(group) || this.#fetchesHead(group.start)) return group.start; + } + return undefined; + } + + // Whether group `key` is held unread in the window, and whether it is servable from the frame + // asked, as #lowestUnread judges. Mirrors the Rust publisher's `servable` on `lowest_unread`. + #heldAt(key: bigint): "servable" | "unservable" | undefined { + if (this.#resume) return this.#resume.heldAt(key); + if (key < this.#cursor.peek().start) return undefined; + const groups = this.#state.groups.peek(); + const group = groups[timelineIndex(groups, key)]; + if (group?.start !== key || !this.#window.contains(key) || this.#delivered.has(key)) return undefined; + return !this.#lacksHead(group) || this.#fetchesHead(key) ? "servable" : "unservable"; + } + + // Whether the head of held group `key` can still come from a fill, which {@link #askHead} + // would ask. Mirrors the Rust `group::Consumer::fetches_from`. + #fetchesHead(key: bigint): boolean { + const end = key + 1n; + if (dropAt(this.#state.refused.peek(), key) || runGaps(this.#givenUp, key, end).length === 0) return false; + const producer = this.#state.producer; + if (!producer) return false; + const fills = fillsOf(producer); + return fills.serving || !fills.covered(key, end, this.#askerOf()).next().done; + } + // The newest frame buffered for this subscriber, which a wire answer names as its edge: // a newest group with no frames yet falls back to the newest older group that does, and it // reads as undefined once the newest group was evicted or received, since what is left can @@ -5649,12 +5715,13 @@ export class Subscriber { * * Groups may arrive out of order or with gaps due to network conditions; unlike * {@link Ordered.nextGroup}, one that arrives after a newer group was already returned - * is still delivered. When several groups are buffered, the lowest key is - * returned first. + * is still delivered. When several groups are buffered, a backlog or a replayed cache, + * they come in the subscription's {@link Order}: newest first unless `"ascending"`, which + * reads them oldest first. * * Honors the range set by {@link withRange}: a group - * beyond the cap stays buffered (not dropped) and is offered once the cap rises, even - * after a clean close, without blocking in-range groups that arrive behind it. + * beyond the cap stays buffered (not dropped) and is offered once the cap rises, in the same + * order, even after a clean close, without blocking in-range groups that arrive behind it. * Once the track closes cleanly, a reader with nothing left in range finishes. So does a * read whose {@link Subscription.ranges} all end, once every group in them was handed out, * dropped, skipped as stale, or will never arrive, while the track goes on, as in Rust; @@ -5728,22 +5795,34 @@ export class Subscriber { } const drift = this.#drift(); this.#reoffer(drift.budget); + // Newest first, the stale groups at the oldest end are written off before one is picked, + // as the Rust `write_off_oldest` does, so their verdicts settle first. + const ascending = this.#state.update.scalars()?.order === "ascending"; + if (!ascending) { + const dropped = this.#writeOffOldest(groups, start, end, drift, dispositions); + if (dropped) return dropped; + } // Keep unread groups below the floor until cache eviction: replacing the // subscription can lower it, just as raising the cap re-offers held groups. Found // after the re-offer, which may insert below the floor. - let index = timelineIndex(groups, start); + const floor = timelineIndex(groups, start); + // The buffer is key-sorted, so it is walked in the subscription's Group Order: up from the + // floor, or down from below the cap. A beyond-cap group stays held without blocking an + // in-range one, which sorts in front of it. + let index = ascending ? floor : timelineIndex(groups, end ?? UNBOUNDED) - 1; for (;;) { - // The buffer is key-sorted, so an in-range group that arrives behind a - // beyond-cap one sorts in front of it and is never blocked by it. + if (index < floor) break; const group = groups[index]; if (!group || (end !== undefined && group.start >= end)) break; // Kept, like a group below the floor: replacing the ranges can take it in. if (!this.#window.contains(group.start)) { - index++; + index = this.#pastExcluded(groups, group.start, ascending); continue; } groups.splice(index, 1); + // What lies below moved down into this slot, so a descending walk steps past it. + if (!ascending) index--; const failed = hooks.groupFailed(group); if (dispositions === true && failed) { // A group expired under this subscription's budget is a stale verdict. @@ -5760,27 +5839,16 @@ export class Subscriber { continue; } if (this.#staleAt(group.start, drift)) { - group.close(); - const budget = drift.budget.at(group.start); - let dropped: (Recv & { kind: "drop" }) | undefined; - if (dispositions) { - dropped = this.#report(group.start, group.start + 1n, staleHole(budget)); - } else if (this.#dropsSeen) { - // A cursor #tryDrop reads reports it there. - this.#pending = insertDrop(this.#pending, group.start, group.start + 1n, staleHole(budget)); - } - // Stale at the bound is final: settled as handed out, compacted the same way, as the - // Rust `retire_written_off` does, so nothing counts on this reader to hand it out once - // what convicted it leaves. - if (drift.bound !== undefined && budget >= drift.bound) this.#handOut(group.start, false); - else this.#skip(group.start, budget); + const dropped = this.#writeOff(group, drift, dispositions); if (dropped) return dropped; continue; } // A group missing its head comes from the fill asked for it, in its turn. if (this.#lacksHead(group)) { if (this.#askHead(group.start)) { - groups.splice(index++, 0, group); + // Back in its slot, and the walk moves past it. + if (ascending) groups.splice(index++, 0, group); + else groups.splice(index + 1, 0, group); continue; } group.close(); @@ -5806,6 +5874,66 @@ export class Subscriber { return this.#parked(groups) ? { kind: "boundary" } : this.#done(); } + // Where a walk of the key-sorted `groups` resumes past `key`, which the window leaves out: the + // next group the window admits in the walk's direction, or past either end. One seek over the + // excluded groups, which stay buffered for a widening, rather than a step per group. + #pastExcluded(groups: readonly GroupConsumer[], key: bigint, ascending: boolean): number { + if (ascending) { + const next = this.#window.next(key); + return next === undefined ? groups.length : timelineIndex(groups, next); + } + const below = this.#window.prev(key); + return below === undefined ? -1 : timelineIndex(groups, below + 1n) - 1; + } + + // Write off the stale groups at the oldest end of `groups` within `[start, end)`, up to the first + // one still fresh. Mirrors the Rust `Cursor::write_off_oldest`. + #writeOffOldest( + groups: GroupConsumer[], + start: bigint, + end: bigint | undefined, + drift: Drift, + dispositions: Dispositions, + ): (Recv & { kind: "drop" }) | undefined { + let index = timelineIndex(groups, start); + for (;;) { + const group = groups[index]; + if (!group || (end !== undefined && group.start >= end)) return undefined; + if (!this.#window.contains(group.start)) { + index = this.#pastExcluded(groups, group.start, true); + continue; + } + if (this.#delivered.has(group.start)) { + groups.splice(index, 1); + group.close(); + continue; + } + if (hooks.groupFailed(group) || !this.#staleAt(group.start, drift)) return undefined; + groups.splice(index, 1); + const dropped = this.#writeOff(group, drift, dispositions); + if (dropped) return dropped; + } + } + + // Skip `group`, stale under `drift`, and report it as this read reports what it gives up. + #writeOff(group: GroupConsumer, drift: Drift, dispositions: Dispositions): (Recv & { kind: "drop" }) | undefined { + group.close(); + const budget = drift.budget.at(group.start); + let dropped: (Recv & { kind: "drop" }) | undefined; + if (dispositions) { + dropped = this.#report(group.start, group.start + 1n, staleHole(budget)); + } else if (this.#dropsSeen) { + // A cursor #tryDrop reads reports it there. + this.#pending = insertDrop(this.#pending, group.start, group.start + 1n, staleHole(budget)); + } + // Stale at the bound is final: settled as handed out, compacted the same way, as the + // Rust `retire_written_off` does, so nothing counts on this reader to hand it out once + // what convicted it leaves. + if (drift.bound !== undefined && budget >= drift.bound) this.#handOut(group.start, false); + else this.#skip(group.start, budget); + return dropped; + } + // The first part of `[from, to)` this cursor has not reported yet within its window, now // reported, with why. #report(from: bigint, to: bigint, hole: Hole & { own?: boolean }): (Recv & { kind: "drop" }) | undefined { @@ -6448,20 +6576,50 @@ export class Subscriber { return true; } - // The lowest buffered candidate in range that the budget spares. An ordered take may - // still wait on an owed hole below it, so a resumed reader must keep its place. + // The first buffered candidate in range that the budget spares: the lowest for an ordered + // take, else the first in the subscription's Group Order, as #tryRecvGroup picks it. An ordered + // take may still wait on an owed hole below it, so a resumed reader must keep its place. An + // arrival take passes a group missing its head, so its peek does too: a resumed reader picks + // across copies by what each offers. #peekGroup(ordered: boolean): bigint | undefined { + if (this.#resume) return this.#resume.peek(ordered, this.#delivered); this.#settle(); const cursor = this.#cursor.peek(); const start = ordered ? max(cursor.start, this.#nextKey) : cursor.start; const drift = this.#drift(); - for (const group of this.#state.groups.peek()) { - if (group.start < start || !this.#window.contains(group.start)) continue; + // What a widened budget offers again, as the arrival take does first. + if (!ordered) this.#reoffer(drift.budget); + const groups = this.#state.groups.peek(); + const offers = (group: GroupConsumer) => + !this.#delivered.has(group.start) && + !this.#staleAt(group.start, drift) && + (ordered || !this.#lacksHead(group)); + if (!ordered && this.#state.update.scalars()?.order !== "ascending") { + let index = timelineIndex(groups, cursor.end ?? UNBOUNDED) - 1; + while (index >= 0 && groups[index].start >= start) { + const group = groups[index]; + if (!this.#window.contains(group.start)) { + index = this.#pastExcluded(groups, group.start, false); + continue; + } + if (offers(group)) return group.start; + index--; + } + return undefined; + } + let index = timelineIndex(groups, start); + while (index < groups.length) { + const group = groups[index]; if (cursor.end !== undefined && group.start >= cursor.end) return undefined; - if (!this.#delivered.has(group.start) && !this.#staleAt(group.start, drift)) { + if (!this.#window.contains(group.start)) { + index = this.#pastExcluded(groups, group.start, true); + continue; + } + if (offers(group)) { if (ordered && this.#waitTimeStart(start, group.start, drift)) return undefined; return group.start; } + index++; } return undefined; } diff --git a/js/net/src/window.ts b/js/net/src/window.ts index f6d81eda4f6..e123cad9de9 100644 --- a/js/net/src/window.ts +++ b/js/net/src/window.ts @@ -982,6 +982,12 @@ export class Window { return this.pending ? from : this.#groups.next(from); } + /** The highest group in range below `before`, undefined when none is. The one just below while a live join waits on a first group. */ + prev(before: bigint): bigint | undefined { + if (this.pending) return before > 0n ? before - 1n : undefined; + return this.#groups.prev(before); + } + /** The lowest group in range, undefined while a start waits. Nothing in range floors at group 0. */ floor(): bigint | undefined { if (this.pending || this.#unplaced()) return undefined; diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index 8a4d60129a7..ba7d7e6f915 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -230,7 +230,11 @@ fun uniffi.moq.MoqSubscription.Companion.default(): Subscription = */ typealias Range = uniffi.moq.MoqRange -/** Which pending group the publisher sends first: `ASCENDING` or `DESCENDING`. */ +/** + * Which group comes first, as the publisher sends them and `recvGroup` returns those held: + * `ASCENDING` or `DESCENDING`. Before moq-lite-07 the publisher sends newest first whatever this + * asks. + */ typealias Order = uniffi.moq.MoqOrder /** A location within a track: a group start and a frame index in it. */ diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt index 31799212952..19a61c27867 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt @@ -26,7 +26,10 @@ fun dev.moq.media.TrackConsumer.reads(): Flow = pull({ cance /** Stream of groups in start order, skipping forward if the reader falls behind. */ fun TrackConsumer.groups(): Flow = pull({ cancel() }) { nextGroup() } -/** Stream of groups in arrival order, including out-of-order deliveries. */ +/** + * Stream of groups in arrival order, including out-of-order deliveries. Groups already held come in + * the subscription's order, newest first unless it asks ascending, as `recvGroup` returns them. + */ fun TrackConsumer.groupsAsArrived(): Flow = pull({ cancel() }) { recvGroup() } /** diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index f09ed5f9a9e..7280d654acd 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -241,7 +241,7 @@ same either way. Opaque bytes go on a plain `TrackProducer`. - `await .subscribe_track(name, subscription=None) → TrackConsumer` - **`TrackConsumer`**. Async iterator of raw groups, in start order. - `await .next_group() → GroupConsumer | None`. Start order; what the default iteration yields. - - `await .recv_group() → GroupConsumer | None`. Arrival order, which may be out of start order. Prefer it when latency matters more than order. + - `await .recv_group() → GroupConsumer | None`. Arrival order, which may be out of start order; groups already held come in the subscription's group order, newest first unless it asks ascending. Prefer it when latency matters more than order. - `.groups_as_arrived()`. Async iterator over `recv_group()`. - `.read_frame() -> Frame | None` returns the first frame of the next group. Empty groups are skipped; `None` is track EOF. - `.info() → TrackInfo` diff --git a/py/moq-rs/moq/_records.py b/py/moq-rs/moq/_records.py index dcaf94b5fc1..6ad52cd1c86 100644 --- a/py/moq-rs/moq/_records.py +++ b/py/moq-rs/moq/_records.py @@ -207,8 +207,9 @@ class Subscription: ``priority`` is in ``-128..=127``, higher first, and defaults to 0, the midpoint. ``delay`` is where a range with no start begins and how far a non-latest group may fall behind before it is skipped. ``ranges`` are the spans of the track to deliver, ``None`` for - one :class:`Range` with no start. ``order`` is which pending group the publisher - sends first, ``None`` for newest first. + one :class:`Range` with no start. ``order`` is which group comes first, as the + publisher sends them and :meth:`recv_group` returns those held, ``None`` for newest first. + Before moq-lite-07 the publisher sends newest first whatever ``order`` asks. A bare ``Subscription()`` has moq-net's defaults, as :meth:`default` does. """ diff --git a/py/moq-rs/moq/subscribe.py b/py/moq-rs/moq/subscribe.py index b8e77324626..b94cbe35269 100644 --- a/py/moq-rs/moq/subscribe.py +++ b/py/moq-rs/moq/subscribe.py @@ -73,6 +73,9 @@ async def _next(self) -> GroupConsumer | None: async def groups_as_arrived(self) -> AsyncIterator[GroupConsumer]: """Iterate groups in arrival order, including out-of-order deliveries. + Groups already held come in the subscription's order, newest first unless it asks + ascending, as :meth:`recv_group` returns them. + The default iteration uses start order instead. Use this for live consumption where latency matters more than order. """ @@ -86,7 +89,9 @@ async def recv_group(self) -> GroupConsumer | None: """Return the next group in arrival order. Returns `None` when the track ends. Groups are returned as they arrive on the wire, which may be out of start - order. Use this for live consumption where latency matters more than order. + order; those already held come in the subscription's group order, newest + first unless it asks ascending. Use this for live consumption where latency + matters more than order. """ group = await self._inner.recv_group() if group is None: diff --git a/quest/m0/nightly/resume-route-mutants.md b/quest/m0/nightly/resume-route-mutants.md index 2333be66c82..ee71be07b68 100644 --- a/quest/m0/nightly/resume-route-mutants.md +++ b/quest/m0/nightly/resume-route-mutants.md @@ -26,7 +26,7 @@ so none is excluded. Kill each with a unit test or a model regression, or exclud is covered another way (a replaced non-fill copy removes its fed range, the serving copy starts above, a fill waits through its unread group). Needs a second fill, from another route, holding a key the first covers while the local cap holds it back. -- `Reader::poll_lowest` `!copy.replaced && Some(copy.generation) == self.generation`, `&&` +- `Reader::poll_first` `!copy.replaced && Some(copy.generation) == self.generation`, `&&` to `||`: also counts a late backfill of the serving route, which only reruns `backfill_gaps` (a no-op, or a reset of that backfill's budget), and a last copy of an old generation left while the route has no copy. That one reading late with a floor may ask diff --git a/quest/m0/nightly/track-bench-fixtures.md b/quest/m0/nightly/track-bench-fixtures.md new file mode 100644 index 00000000000..8fec04dac7f --- /dev/null +++ b/quest/m0/nightly/track-bench-fixtures.md @@ -0,0 +1,25 @@ +# [M] The moq-net track benches' empty-run and fill fixtures pass + +## Goal + +`cargo bench -p moq-net --all-features --bench track -- --test` runs every group to the end. +Three fixtures in `rs/moq-net/benches/track.rs` panic on `main` before measuring, and each stops +the groups after it in that target. + +## Plan + +Kept by the maintainer on 2026-11-24 ([pick round](https://github.com/moq-dev/moq/pull/9529#issuecomment-7140096782)). + +Found while smoke-running the benches for [moq-dev/moq#9529](https://github.com/moq-dev/moq/pull/9529). +Each failure below reproduces identically on 85ab682bf4, the commit before that PR: + +- `track_empty_run/stale/1/64`: `EmptyRun::drain` expects `run + 2` groups handed out, and gets + 2. The run's groups sit about four hours behind the newest under a one-hour live budget, so the + read writes them off. Decide whether the fixture or its expectation is wrong; the doc comment says + only the run's last group is written off. +- `track_fill/1r/64`: `the update reached the fill` sees a fill at priority 0 after every reader + raised its priority to 1, and once that is skipped, `readers share each run's fill` counts 1 of 64. +- `track_range_filling/span_1/16`: not every reader drains `ranges * width` filled groups. + +For each, decide whether the fixture or the code is wrong, and fix it at the cause. Check whether +Nightly's measured run already reports them. diff --git a/quest/m1/arrival-group-order.md b/quest/m1/arrival-group-order.md deleted file mode 100644 index d1564ad819c..00000000000 --- a/quest/m1/arrival-group-order.md +++ /dev/null @@ -1,42 +0,0 @@ -# [L] An arrival read serves its buffered and re-offered groups in Group Order, in Rust and JS - -## Goal - -An arrival reader (`recv_group` in Rust, `recvGroup` in JS, and each lite publisher that serves a subscription from one) picks the next group from everything it holds unread in the subscription's `Group Order`: newest first, unless `order` is ascending. That covers two sets the languages order differently today: - -- Buffered groups, those that arrived and are still unread with no widening involved, including a replayed cache. Rust walks them in arrival order (`poll_recv_group` in `rs/moq-net/src/model/track.rs`), and JS returns the lowest key first from its key-sorted buffer (`#tryRecvGroup` and `bufferInsert` in `js/net/src/track.ts`). -- Re-offered groups, those a widening newly covers: replacing the ranges with `update`, raising a `withRange` cap over groups held beyond it, or widening a live `max` over groups skipped as stale. Rust already re-offers them in Group Order ahead of its arrival walk (`next_owed`). JS puts them back into its key-sorted buffer (`#reoffer`), so the lowest key goes first. - -A reader that keeps up sees no change: with one group held, the order has nothing to pick. A reader holding a backlog or a replay reads it newest first by default, as the draft's publisher transmits it. Delivery stays exactly-once, and an arrival read still never skips a lower group that arrives late, which is why Rust walks arrivals rather than keys. The ordered reader (`ordered()`) keeps key order. The wire and the public API do not change; the arrival read's documented order does. - -The lite-07 draft needs no change: its `Group Order` section already says a publisher SHOULD transmit pending Groups in the subscriber's `Group Order`, newest first when descending, and this makes both implementations do so for what they hold. - -## Plan - -Decided 2026-11-23 by the maintainer, via /quest-run: plan it, as found in [moq-dev/moq#9509](https://github.com/moq-dev/moq/pull/9509) ([thread](https://github.com/moq-dev/moq/pull/9509#discussion_r4675205934)), where the Rust and JS twins of the widened-read test pinned opposite orders. That PR made both sort their widened phase, so they pin only the set of groups. - -Decided 2026-11-24 by the maintainer, via /quest-run ([decision](https://github.com/moq-dev/moq/pull/9522#issuecomment-7121668986)): the order for buffered groups (arrived, unread, no widening). ✅ (c) serve them in Group Order in both languages, newest first unless the subscription is ascending (rejected: (a) keep each language's order and document the difference; (b) move JS to Rust's arrival order). It changes Rust's tested arrival order too, so it is folded into this quest, now L and no longer JS-only. - -Tests: - -- Rust `a_widened_history_read_offers_a_group_it_passed_over` (`rs/moq-net/src/model/track.rs`): drop `read[3..].sort_unstable()` and assert `[2, 1, 3, 4, 0]`, since groups 1 and 2 are buffered when it first reads. Its JS twin `subscription bounds stay reader-local for %s reads` (`js/net/src/track.test.ts`): drop the `widened.sort` and assert the same for the arrival read; the ordered read stays `1, 2, 3, 4`. Add an ascending variant to both, which reads `[1, 2, 3, 0, 4]`. -- Rust `ordered_and_arrival_cursors_are_independent` and JS `the ordered and arrival cursors are independent`: the plain cursor no longer walks arrivals. Make both twins hold `3` and `5` at once and assert `5` first, then `3` first under ascending, whichever arrived first. -- JS `replay and backlogs deliver sparse out-of-order arrivals ascending without sorting`: the default order reads `50` down to `0`, and an ascending variant reads the current expectation. Keep its guard that an arrival never sorts the buffer. -- The tests that pin lowest-first re-offers or arrival-order backlogs move with it. Look in `js/net/src/track.test.ts` (cap raises over held groups, widened ranges), `js/net/src/lite/widened_max_age.test.ts`, and the `recv_group` tests in `rs/moq-net/src/lite/publisher.rs` and `rs/moq-net/src/model/track.rs`, and keep each Rust and JS twin asserting the same order. - -Guidance: - -- Rust: the arrival walk becomes a pick over what is held unread. Keep the arrival cursor's guarantee that a late lower group is never passed over, and keep the cost of a pick from growing with the backlog: no rescan of the held set per hand-out. One shape: track the arrived-unread keys as a set the walk adds to and `take` removes from, and pick its last (or first, for ascending), as `next_owed` does over `filter.owed`; re-offers and buffered groups may then share one owed set. -- JS: walk the key-sorted buffer from the top below `end` for descending, from `start` for ascending. Keep beyond-cap and out-of-window groups held, as now, and keep `#reoffer`'s groups in the same buffer, since the buffer's order is now the Group Order. The order is `this.#state.update.scalars()?.order`, which defaults to `"descending"`. -- Resume across route copies: both readers pick the lowest group any copy holds next (`Reader::poll_lowest` in `rs/moq-net/src/model/resume.rs`, `#lowest` in `js/net/src/resume.ts`). An arrival read picks across copies in Group Order instead, with a tie still favoring the newer copy; an ordered read stays lowest-first. Re-run `/verify-resume` and update `rs/moq-net/verify/resume/` to the new pick. -- Update the docs that state the arrival order: Rust's `poll_recv_group` and `recv_group`, `poll_recv_next` in `rs/moq-net/src/lite/publisher.rs`, JS's `recvGroup`, the bindings' `recv_group` docs in `moq-ffi`, and `doc/lib/dart/index.md`'s "arrival-order reads". `doc/concept/identity.md`'s "Arrivals are unordered" already says Group Order chooses what goes first. -- Audit callers of an arrival read that drain a replay or backlog and expect oldest first, such as a history range read from `Start::Oldest`, in Rust, JS, `moq-ffi`, and the hang and watch packages. Each moves to `ordered()` or asks `order: ascending`. [Buffered playback subscribes in ascending order](/quest/m3/buffered-ascending.md) already plans that for buffered `` media. -- Since this changes what a published release's readers return, the PR's Impact section says so as a behavior change, with the migration: ask ascending, or read `ordered()`, to keep oldest first. - -No single PR caused this. JS has kept a key-sorted buffer since [moq-dev/moq#2772](https://github.com/moq-dev/moq/pull/2772), and [moq-dev/moq#6717](https://github.com/moq-dev/moq/pull/6717) added the newest-first re-offer in Rust while knowingly leaving JS lowest-first, "since its buffer is ascending". So the PR lists no `## Caused by` culprit. - -Public API: none, though the arrival read's documented order changes. Wire: none. - -## Related - -- [Buffered playback subscribes in ascending order](/quest/m3/buffered-ascending.md) - the JS player whose ascending subscriptions this order serves diff --git a/quest/m1/cursor-start-group.md b/quest/m1/cursor-start-group.md new file mode 100644 index 00000000000..257c9642cca --- /dev/null +++ b/quest/m1/cursor-start-group.md @@ -0,0 +1,25 @@ +# [M] A subscriber reports where its delivery starts + +## Goal + +The Rust and JS lite publishers name SUBSCRIBE_START from one answer the track subscriber gives: the lowest group its read will hand out, given the first group out and the frame asked. Today three places rebuild that answer from parts, and each fix has to land in all three. Behavior, wire, and public API stay as they are. + +## Plan + +Recommended by the second reviewer (Claude Opus 5.5) on [moq-dev/moq#9529](https://github.com/moq-dev/moq/pull/9529), which made an arrival read serve held groups newest first. Once the first group out is no longer the lowest, the publisher has to work out where delivery starts. It does that in three places: + +- Rust `TrackRun::start` in `rs/moq-net/src/lite/publisher.rs` walks `track::Subscriber::lowest_unread` and checks `servable` against the frames asked. A second loop then steps past runs given up and held groups it can't serve. +- JS `lite/publisher.ts` does the same with `hooks.lowestUnread`, `hooks.heldAt`, and its `skipped` runs. +- The front (`resume::Subscriber::lowest_unread` in Rust, `Reader.lowestUnread`/`heldAt` in JS) merges the copies' answers, picking the most servable copy on a tie. + +Recommendations (no open decisions): + +- Add one crate-internal method on `track::Subscriber`, for example `delivery_start(first: u64, frame: u64) -> u64`. It returns the lowest group at or below `first` that the read will still hand out from `frame`, past the runs it gave up. A front answers it across its copies. Mirror it as one hook in JS. +- Delete `lowest_unread`, `servable`, and `heldAt`, and the publisher's two loops. `poll_start`, the source's feed start, stays separate. The publisher still takes the lower of the two, because that start comes from the source, not from what the reader holds. +- Keep every existing `lowest_unread`, `servable`, and START test as the regression suite, with Rust/JS twins asserting the same starts. Add a differential test that checks the new answer against the old reconstruction over random held, given-up, and headless groups before deleting the old code. + +Public API: none. Wire: none. + +## Related + +- [A front's ordered reader reports a drop that lands with the group above it](/quest/m1/front-drop-with-next-group.md) - touches the same front reader diff --git a/quest/m1/front-drop-with-next-group.md b/quest/m1/front-drop-with-next-group.md new file mode 100644 index 00000000000..871bb589565 --- /dev/null +++ b/quest/m1/front-drop-with-next-group.md @@ -0,0 +1,33 @@ +# [M] A front's ordered reader reports a drop that lands with the group above it + +## Goal + +An ordered reader (`ordered()`) of a logical track a front serves reports a dropped run as a gap +before the group above it, even when the drop and that group land in the same poll, as a reader +of a plain track does. Today it hands out the group and never reports the gap. + +## Plan + +Kept by the maintainer on 2026-11-24 ([pick round](https://github.com/moq-dev/moq/pull/9529#issuecomment-7140096782)). + +Found while building [moq-dev/moq#9529](https://github.com/moq-dev/moq/pull/9529): on lite-06, +`drop_record::an_ordered_reader_is_told_of_every_group_the_origin_evicted` hit it once the origin +served its queued groups newest first. That PR lets group 0 go out before the rest queue, which +keeps the test on what it checks. The bug is as old as the front's ordered reader, and the repro +below fails on the commit before that PR too. + +Repro, as a test in `rs/moq-net/src/model/resume.rs`'s `mod test`: serve one copy, subscribe +`ordered()` with `Range::groups(from..)` and an hour's budget, then `a.drop_groups(from..4, +StreamError::Old)` and `write(&a, 4)` before the next poll. The read yields `group 4` with no +`gap from..4`, for each of `(start, from)` in `[(None, 0), (None, 1), (Some(1), 1)]`. + +Why: `Ordered::poll_item` in `rs/moq-net/src/model/track.rs` calls `find_gap` only after a read +comes back empty, so a group ready in the same poll goes out first and the gap below it is +passed. Calling `find_gap(false)` before every read fixes the repro, but it also makes +`waiting_time_start::a_range_before_every_group_reads_past_it` fail: see +[A relayed reader reports a refused fill as a gap](/quest/m1/relayed-refused-fill-gap.md), which +lands first or with it. + +## Required + +- [A relayed reader reports a refused fill as a gap](/quest/m1/relayed-refused-fill-gap.md) - the discrepancy the fix unmasks diff --git a/quest/m1/relayed-refused-fill-gap.md b/quest/m1/relayed-refused-fill-gap.md new file mode 100644 index 00000000000..64f2e6e9204 --- /dev/null +++ b/quest/m1/relayed-refused-fill-gap.md @@ -0,0 +1,24 @@ +# [S] A relayed reader reports a refused fill as a gap a direct reader never sees + +## Goal + +An ordered reader of a relay copy reports the same items as the same reader at the publisher. +Asking from a time before every group, a direct reader reads the first group with no gap, while +the relayed one reports `Err(10..21)` with `NotFound` first, once its ordered reader checks for +gaps before every read. + +## Plan + +Kept by the maintainer on 2026-11-24 ([pick round](https://github.com/moq-dev/moq/pull/9529#issuecomment-7140096782)). + +Found while building [moq-dev/moq#9529](https://github.com/moq-dev/moq/pull/9529), with the fix +[A front's ordered reader reports a drop that lands with the group above it](/quest/m1/front-drop-with-next-group.md) +plans applied: `waiting_time_start::a_range_before_every_group_reads_past_it` in +`rs/moq-net/tests/integration/` fails there, the relayed reader reporting a NotFound gap over +`10..21` where the direct one reports none. + +The copy asks upstream to fill the range before the only group; upstream refuses it, since no +group exists there, and the copy records the refusal as a gap. A range that resolves empty at the +publisher is no loss: the copy must answer it the same way, per the cache rule in `AGENTS.md`. +Start by checking how the refusal reaches `find_gap` on the copy, and whether lite-07's +SUBSCRIBE_DROP or the fill's refusal carries it. Check JS's twin of the test too. diff --git a/rs/libmoq/src/api.rs b/rs/libmoq/src/api.rs index f86d7357308..ae7e66418ce 100644 --- a/rs/libmoq/src/api.rs +++ b/rs/libmoq/src/api.rs @@ -899,7 +899,8 @@ pub struct moq_subscription { /// The number of entries in `ranges`. pub ranges_len: usize, - /// `moq_order` discriminant: which pending group the publisher sends first. + /// `moq_order` discriminant: which group comes first, as the publisher sends them and a read + /// in arrival order returns those held. pub order: u32, } @@ -932,7 +933,9 @@ pub struct moq_range { pub end_present: bool, } -/// Which of a subscription's pending groups the publisher sends first. Zero is the default. +/// Which of a subscription's groups comes first, as the publisher sends them and a read in +/// arrival order returns those held. Zero is the default. Before moq-lite-07 the publisher +/// sends newest first whatever this asks. #[repr(C)] #[expect(non_camel_case_types, reason = "C ABI type names match moq.h")] #[derive(Clone, Copy, Debug)] diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index 8f6d3badb2d..4e6b51dabfb 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -1891,12 +1891,12 @@ pub(crate) mod tests { .track(&passthrough.track) .unwrap() .subscribe( - moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(RECORDING_MAX_AGE), max: Some(RECORDING_MAX_AGE), - }, - )]), + })]) + .with_order(moq_net::track::Order::Ascending), ) .await .unwrap(); diff --git a/rs/moq-e2ee/src/tests.rs b/rs/moq-e2ee/src/tests.rs index 4126b1a6d6e..459341d7b03 100644 --- a/rs/moq-e2ee/src/tests.rs +++ b/rs/moq-e2ee/src/tests.rs @@ -341,9 +341,12 @@ fn consume(generation: &Producer) -> Consumer { generation.credential().consume(generation.epoch().clone()) } -/// Every group the track holds, as history, so none goes stale and none waits on a live edge. +/// Every group the track holds, as history, so none goes stale and none waits on a live edge, +/// oldest first. fn subscribe_all() -> moq_net::track::Subscription { - moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]) + moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::ALL]) + .with_order(moq_net::track::Order::Ascending) } /// A track whose superseded groups stay fresh, so [`subscribe_all`] reads every group. diff --git a/rs/moq-e2ee/src/track.rs b/rs/moq-e2ee/src/track.rs index 5f61c378049..0353274239a 100644 --- a/rs/moq-e2ee/src/track.rs +++ b/rs/moq-e2ee/src/track.rs @@ -235,7 +235,9 @@ impl Consumer { &self.name } - /// The next protected group in arrival order, or `None` once the track finished. + /// The next protected group in arrival order, or `None` once the track finished. Groups + /// already held come in the subscription's Group Order, newest first unless it asks + /// ascending. /// /// # Errors /// diff --git a/rs/moq-ffi/src/consumer.rs b/rs/moq-ffi/src/consumer.rs index 921aed0da30..b4d4dc4d8e3 100644 --- a/rs/moq-ffi/src/consumer.rs +++ b/rs/moq-ffi/src/consumer.rs @@ -84,7 +84,9 @@ pub struct MoqSubscription { /// subscription's read filter: it reads only the groups its own ranges cover. #[uniffi(default = None)] pub ranges: Option>, - /// Which pending group the publisher sends first, or null for newest first. + /// Which group comes first, as the publisher sends them and `recv_group` returns those held, + /// or null for newest first. Before moq-lite-07 the publisher sends newest first whatever this + /// asks, and `recv_group` still returns those held in this order. #[uniffi(default = None)] pub order: Option, } @@ -128,8 +130,9 @@ pub struct MoqRange { pub end: Option, } -/// Which of a subscription's pending groups the publisher sends first, mirroring -/// [`moq_net::track::Order`]. +/// Which of a subscription's groups comes first, as the publisher sends them and `recv_group` +/// returns those held, mirroring [`moq_net::track::Order`]. Before moq-lite-07 the publisher +/// sends newest first whatever this asks. #[derive(Clone, Copy, uniffi::Enum)] pub enum MoqOrder { /// Oldest first, draining a backlog in start order. @@ -586,7 +589,8 @@ impl MoqTrackConsumer { /// /// Groups are returned as they arrive on the wire, which may be out of start /// order (e.g. if a later group lands before an earlier one on a separate stream). - /// One that drifts further behind the live edge than the subscription's `delay.max` + /// Of the groups already held, it returns them in the subscription's group order: + /// newest first unless the subscription asks ascending. One that drifts further behind the live edge than the subscription's `delay.max` /// is skipped, or ends its pending read if already returned; raise it to keep stalled groups. /// /// The first call commits this track to arrival order: start-order reads diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index a16ed789381..29161498e0e 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -1671,12 +1671,12 @@ mod tests { .track("audio") .unwrap() .subscribe( - moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(Duration::from_secs(1)), max: Some(Duration::from_secs(1)), - }, - )]), + })]) + .with_order(moq_net::track::Order::Ascending), ) .await .unwrap(); diff --git a/rs/moq-json/src/snapshot/producer.rs b/rs/moq-json/src/snapshot/producer.rs index a71e6aa0e6b..01617849631 100644 --- a/rs/moq-json/src/snapshot/producer.rs +++ b/rs/moq-json/src/snapshot/producer.rs @@ -614,7 +614,9 @@ mod tests { .produce() .create_track("test", moq_net::track::Info::default()) .unwrap(); - let mut groups = track.subscribe(None); + // Oldest first, as published. + let mut groups = + track.subscribe(moq_net::track::Subscription::default().with_order(moq_net::track::Order::Ascending)); let mut producer = Producer::::new(track, Config::default().with_deltas(true)); producer .update(&json!({ "n": 1 }), moq_net::Timestamp::unscaled(1)) diff --git a/rs/moq-json/src/stream/consumer.rs b/rs/moq-json/src/stream/consumer.rs index 05c9a2376ad..0a779ef1ce3 100644 --- a/rs/moq-json/src/stream/consumer.rs +++ b/rs/moq-json/src/stream/consumer.rs @@ -48,7 +48,12 @@ impl Consumer { /// track: every record matters here, so the caller picks the subscription's delay budget and /// priority, while a snapshot only wants the newest value and subscribes itself at a zero delay. /// A [compressed](moq_net::track::Info::compression) track reads the same: moq-net inflates it. - pub fn new(track: moq_net::track::Subscriber, config: Config) -> Self { + /// The log is read oldest first whatever order the subscription asked, so a second group a + /// broken publisher opens is caught as `Rolled` rather than read ahead of the first. + pub fn new(mut track: moq_net::track::Subscriber, config: Config) -> Self { + let subscription = track.subscription().with_order(moq_net::track::Order::Ascending); + // A track that already ended holds no group to read out of order. + let _ = track.update(subscription); Self { track, log: Log::Waiting, diff --git a/rs/moq-json/src/window/mod.rs b/rs/moq-json/src/window/mod.rs index 4217a0bcf67..994faff5d29 100644 --- a/rs/moq-json/src/window/mod.rs +++ b/rs/moq-json/src/window/mod.rs @@ -1090,7 +1090,9 @@ mod test { .produce() .create_track("test", moq_net::track::Info::default().with_max_age(None)) .unwrap(); - let replay = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]); + let replay = moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::ALL]) + .with_order(moq_net::track::Order::Ascending); let mut groups = track.subscribe(replay); let mut producer = Producer::::new(track, Config::default()); diff --git a/rs/moq-json/src/window/producer.rs b/rs/moq-json/src/window/producer.rs index 90fd88f0316..1d961dbbfb2 100644 --- a/rs/moq-json/src/window/producer.rs +++ b/rs/moq-json/src/window/producer.rs @@ -455,7 +455,9 @@ mod tests { .produce() .create_track("test", moq_net::track::Info::default()) .unwrap(); - let mut groups = track.subscribe(None); + // Oldest first, as published. + let mut groups = + track.subscribe(moq_net::track::Subscription::default().with_order(moq_net::track::Order::Ascending)); let mut producer = Producer::::new(track, Config::default()); producer .push(&json!({ "n": 1 }), moq_net::Timestamp::unscaled(1)) diff --git a/rs/moq-mux/src/container/fmp4/import.rs b/rs/moq-mux/src/container/fmp4/import.rs index 027d8257292..e1d0feda416 100644 --- a/rs/moq-mux/src/container/fmp4/import.rs +++ b/rs/moq-mux/src/container/fmp4/import.rs @@ -2582,12 +2582,12 @@ mod tests { } fn replay(output: &Output<()>) -> moq_net::track::Subscriber { - let replay = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + let replay = moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(std::time::Duration::from_secs(30)), max: Some(std::time::Duration::from_secs(30)), - }, - )]); + })]) + .with_order(moq_net::track::Order::Ascending); match output { Output::Audio(output) => output.subscribe(replay), Output::Passthrough(output) => output.track.subscribe(replay), diff --git a/rs/moq-mux/src/container/mkv/import_test.rs b/rs/moq-mux/src/container/mkv/import_test.rs index 69475bb84cf..78cba37838e 100644 --- a/rs/moq-mux/src/container/mkv/import_test.rs +++ b/rs/moq-mux/src/container/mkv/import_test.rs @@ -1878,12 +1878,12 @@ async fn a_seek_mid_block_waits_for_the_block() { let snapshot = catalog.snapshot(); let name = snapshot.audio.renditions.keys().next().unwrap(); - let replay = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + let replay = moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(std::time::Duration::from_secs(3600)), max: Some(std::time::Duration::from_secs(3600)), - }, - )]); + })]) + .with_order(moq_net::track::Order::Ascending); let mut track = consumer.track(name).unwrap().subscribe(replay).await.unwrap(); let mut groups = Vec::new(); while let Some(mut group) = track.recv_group().await.unwrap() { diff --git a/rs/moq-mux/src/container/producer.rs b/rs/moq-mux/src/container/producer.rs index a20766fd3d8..49d08324f56 100644 --- a/rs/moq-mux/src/container/producer.rs +++ b/rs/moq-mux/src/container/producer.rs @@ -1486,13 +1486,14 @@ mod tests { /// These tests write every group up front and only then read, which the default /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) budget collapses to the live /// edge: history has to be asked for. + /// Oldest first, as they are read back. fn replay() -> moq_net::track::Subscription { - moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(RECORDING_MAX_DELAY), max: Some(RECORDING_MAX_DELAY), - }, - )]) + })]) + .with_order(moq_net::track::Order::Ascending) } /// The media track's full max age, so readers started after publishing @@ -1869,9 +1870,11 @@ mod tests { } /// Drain all groups from a finished track, returning their frame counts. - async fn collect_groups(mut consumer: moq_net::track::Subscriber) -> Vec { + async fn collect_groups(consumer: moq_net::track::Subscriber) -> Vec { + // Key order, oldest first, whatever the subscription's Group Order. + let mut consumer = consumer.ordered(); let mut groups = Vec::new(); - while let Some(mut group) = consumer.recv_group().await.unwrap() { + while let Some(mut group) = consumer.next_group().await.unwrap() { let mut count = 0; while group.next_frame().await.unwrap().is_some() { count += 1; @@ -2011,9 +2014,11 @@ mod tests { } /// Drain all groups, returning each group's (timestamp_micros, payload_len) pairs. - async fn collect_payloads(mut consumer: moq_net::track::Subscriber) -> Vec> { + async fn collect_payloads(consumer: moq_net::track::Subscriber) -> Vec> { + // Key order, oldest first, whatever the subscription's Group Order. + let mut consumer = consumer.ordered(); let mut groups = Vec::new(); - while let Some(mut group) = consumer.recv_group().await.unwrap() { + while let Some(mut group) = consumer.next_group().await.unwrap() { let mut frames = Vec::new(); while let Some(frame) = group.read_frame().await.unwrap() { let decoded = hang::container::Frame::decode(frame.payload).unwrap(); @@ -2060,9 +2065,11 @@ mod tests { } /// Drain all LOC groups, returning each group's (timestamp_micros, payload_len) pairs. - async fn collect_loc_payloads(mut consumer: moq_net::track::Subscriber) -> Vec> { + async fn collect_loc_payloads(consumer: moq_net::track::Subscriber) -> Vec> { + // Key order, oldest first, whatever the subscription's Group Order. + let mut consumer = consumer.ordered(); let mut groups = Vec::new(); - while let Some(mut group) = consumer.recv_group().await.unwrap() { + while let Some(mut group) = consumer.next_group().await.unwrap() { let mut frames = Vec::new(); while let Some(frame) = group.read_frame().await.unwrap() { let decoded = moq_loc::decode(frame.payload).unwrap(); @@ -2164,9 +2171,11 @@ mod tests { } /// Drain all groups from a finished track, returning their starts. - async fn collect_starts(mut consumer: moq_net::track::Subscriber) -> Vec { + async fn collect_starts(consumer: moq_net::track::Subscriber) -> Vec { + // Key order, oldest first, whatever the subscription's Group Order. + let mut consumer = consumer.ordered(); let mut starts = Vec::new(); - while let Some(group) = consumer.recv_group().await.unwrap() { + while let Some(group) = consumer.next_group().await.unwrap() { starts.push(group.start); } starts @@ -2767,9 +2776,11 @@ mod tests { type Published = (u64, Vec, Option); /// Every group `consumer` reads, with its frames and End. - async fn collect_published(mut consumer: moq_net::track::Subscriber) -> Vec { + async fn collect_published(consumer: moq_net::track::Subscriber) -> Vec { + // Key order, oldest first, whatever the subscription's Group Order. + let mut consumer = consumer.ordered(); let mut groups = Vec::new(); - while let Some(mut group) = consumer.recv_group().await.unwrap() { + while let Some(mut group) = consumer.next_group().await.unwrap() { let mut frames = Vec::new(); while let Some(frame) = group.read_frame().await.unwrap() { frames.push(frame); diff --git a/rs/moq-mux/src/container/test_util.rs b/rs/moq-mux/src/container/test_util.rs index 0cec86a7626..f0963c00138 100644 --- a/rs/moq-mux/src/container/test_util.rs +++ b/rs/moq-mux/src/container/test_util.rs @@ -630,10 +630,13 @@ impl std::task::Wake for Woken { /// A live join with no lag limit, so it takes each group still within `max` of the live edge: /// what a subscription-wide max age asked before moq-lite-07. Test groups often start at their -/// sequence, not their time, so a join placed by time alone would land on the newest. +/// sequence, not their time, so a join placed by time alone would land on the newest. Oldest +/// first, as the tests read them back. pub(crate) fn within(max: std::time::Duration) -> moq_net::track::Subscription { - moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { - min: None, - max: Some(max), - })]) + moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { + min: None, + max: Some(max), + })]) + .with_order(moq_net::track::Order::Ascending) } diff --git a/rs/moq-mux/src/container/ts/import.rs b/rs/moq-mux/src/container/ts/import.rs index a3786ea9487..175fd966d43 100644 --- a/rs/moq-mux/src/container/ts/import.rs +++ b/rs/moq-mux/src/container/ts/import.rs @@ -10233,12 +10233,12 @@ pub(super) mod test { // Each group as published, its empty end marker included. let name = catalog.snapshot().video.renditions.keys().next().unwrap().clone(); - let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + let subscription = moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(Duration::from_secs(3600)), max: Some(Duration::from_secs(3600)), - }, - )]); + })]) + .with_order(moq_net::track::Order::Ascending); let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap(); let mut groups = Vec::new(); while let Some(mut group) = track.recv_group().await.unwrap() { @@ -10479,12 +10479,12 @@ pub(super) mod test { let (consumer, catalog, _import) = import_all(&mux.out).unwrap(); let name = catalog.snapshot().audio.renditions.keys().next().unwrap().clone(); - let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + let subscription = moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(Duration::from_secs(3600)), max: Some(Duration::from_secs(3600)), - }, - )]); + })]) + .with_order(moq_net::track::Order::Ascending); let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap(); let mut groups = Vec::new(); while let Ok(Ok(Some(mut group))) = kio::clock::timeout(Duration::from_millis(50), track.recv_group()).await { @@ -10527,12 +10527,12 @@ pub(super) mod test { let (consumer, catalog, _import) = import_all(&mux.out).unwrap(); let name = catalog.snapshot().audio.renditions.keys().next().unwrap().clone(); - let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + let subscription = moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(Duration::from_secs(3600)), max: Some(Duration::from_secs(3600)), - }, - )]); + })]) + .with_order(moq_net::track::Order::Ascending); let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap(); let mut groups = Vec::new(); while let Ok(Ok(Some(mut group))) = kio::clock::timeout(Duration::from_millis(50), track.recv_group()).await { diff --git a/rs/moq-mux/src/import/track.rs b/rs/moq-mux/src/import/track.rs index caef69c2190..7620053651f 100644 --- a/rs/moq-mux/src/import/track.rs +++ b/rs/moq-mux/src/import/track.rs @@ -1218,10 +1218,11 @@ mod tests { let _finished = import.finish().unwrap(); } - /// Count the frames in each group of a finished track. - async fn collect_groups(mut subscriber: moq_net::track::Subscriber) -> Vec { + /// Count the frames in each group of a finished track, in key order. + async fn collect_groups(subscriber: moq_net::track::Subscriber) -> Vec { + let mut subscriber = subscriber.ordered(); let mut groups = Vec::new(); - while let Some(mut group) = subscriber.recv_group().await.unwrap() { + while let Some(mut group) = subscriber.next_group().await.unwrap() { let mut count = 0; while group.next_frame().await.unwrap().is_some() { count += 1; diff --git a/rs/moq-net/benches/track.rs b/rs/moq-net/benches/track.rs index 3d527636b10..914dd1f6481 100644 --- a/rs/moq-net/benches/track.rs +++ b/rs/moq-net/benches/track.rs @@ -585,12 +585,15 @@ impl Aged { let track = broadcast .create_track(format!("bench{i}"), moq_net::track::Info::default().with_max_age(None)) .unwrap(); - let mut sub = track.subscribe(track::Subscription::default().with_ranges([track::Range::from( - track::Start::Live { - min: Some(AGED_BUDGET), - max: Some(AGED_BUDGET), - }, - )])); + // Ascending, so the first read is the held group under the finished ones. + let mut sub = track.subscribe( + track::Subscription::default() + .with_ranges([track::Range::from(track::Start::Live { + min: Some(AGED_BUDGET), + max: Some(AGED_BUDGET), + })]) + .with_order(track::Order::Ascending), + ); let mut held = track.append_group(Timestamp::unscaled(0)).unwrap(); held.write_frame(moq_net::Timestamp::unscaled(held.start), Bytes::from_static(b"x")) .unwrap(); diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 053468f0f52..0de082ac986 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -9022,7 +9022,7 @@ mod group_priority_test { [(0, 0), (1, 0)], "each stream joins the subscription's group" ); - assert_eq!(log.orders(), [(0, 1), (1, 3)], "newer groups first"); + assert_eq!(log.orders(), [(0, 3), (1, 1)], "newer groups first"); assert!(log.priorities().is_empty(), "the session queue ranks no stream"); serve.set_priority(9).unwrap(); @@ -19315,7 +19315,7 @@ mod tests { "no Max Age leaves the publisher's max age alone" ); let mut subscriber = producer.subscribe(subscription); - for key in [0, 1] { + for key in [1, 0] { let group = subscriber .recv_group() .now_or_never() diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 9fd02d1d3c4..4bfd798f1d4 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -3370,7 +3370,7 @@ mod test { let mut unpinned = served(); assert_eq!( drain(&mut unpinned), - vec![0, 1, 2], + vec![2, 1, 0], "the unbounded budget alone resolves to the whole cache" ); @@ -3387,7 +3387,7 @@ mod test { // On lite-06 the declared budget is what resolves the start, so it stands. let declared = producer.subscribe(track::Subscription::default().with_max(std::time::Duration::from_secs(5))); let mut declared = declared.with_range(cursor_floor(Version::Lite06, None, producer.latest_key())..); - assert_eq!(drain(&mut declared), vec![0, 1, 2]); + assert_eq!(drain(&mut declared), vec![2, 1, 0]); } /// An unfloored join adopts the first served group: the cursor rises to it, so a @@ -4736,12 +4736,14 @@ fn final_key(end: track::Position) -> u64 { /// Every group key, for [`poll_recv_next`] to hand out any. const ALL: (Bound, Bound) = (Bound::Unbounded, Bound::Unbounded); -/// Poll a single [`track::Subscriber`] for the next group (cap-aware, in arrival order). +/// Poll a single [`track::Subscriber`] for the next group (cap-aware, as an arrival read). /// -/// Groups are served in arrival order (`poll_recv_group`), not key order: on a relay, a -/// burst can be ingested micro-reordered by the upstream leg, and a key cursor would then -/// permanently skip the older group even though it is cached and in demand. Staleness is -/// governed by max age and the subscriber's max delay, not arrival raciness. +/// Groups are served as an arrival read (`poll_recv_group`) serves them, not by a key cursor: +/// of the groups held unread, the first in the subscription's Group Order, and never past a +/// lower one that lands late. On a relay, a burst can be ingested micro-reordered by the +/// upstream leg, and a key cursor would then permanently skip the older group even though it +/// is cached and in demand. Staleness is governed by max age and the subscriber's max delay, +/// not arrival raciness. /// /// The cursor hands out the next group only if its key lies in `groups`, leaving it in /// the cache otherwise, and without `groups` none at all. Either way it then never reports @@ -4818,14 +4820,17 @@ async fn recv_next(track: &mut track::Subscriber, emit_boundary: bool) -> Result /// 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, capped: bool) -> Option { - if group.start < frames.floor { + if !servable(&group, frames) { return None; } let expected = frames.start(group.start); let end = frames.end(group.start).filter(|_| capped); - group - .fetches_from(expected) - .then(|| group.with_end(end).fetching_from(expected)) + Some(group.with_end(end).fetching_from(expected)) +} + +/// Whether [`position_group`] can serve `group` at all. +fn servable(group: &group::Consumer, frames: &Frames) -> bool { + group.start >= frames.floor && group.fetches_from(frames.start(group.start)) } /// The frame bounds of a subscription, which the model leaves to the publisher: it reads @@ -6095,7 +6100,7 @@ impl TrackRun { return Poll::Ready(Ok(ControlFlow::Continue(()))); } - // One cursor drives the whole subscription: poll the cap-aware arrival-order group. + // One cursor drives the whole subscription: poll the cap-aware arrival read. let order = self.ctx.steer_current().order; let stuck = self.stuck(); let emit_boundary = self.start.emits_range() && !self.end_sent; @@ -6497,15 +6502,33 @@ impl TrackRun { source: Option, writer: &mut Writer, ) -> Result<(), Error> { - let mut start = source.map_or(group.start, |source| source.min(group.start)); - // A group given up cannot be where the feed starts. This stops at the held group - // at the latest, since it was not skipped. + // Newest first, the cursor still holds groups below the first to go out: delivery + // starts at the lowest it can serve. + let mut lowest = group.start; + let mut from = 0; + while let Some(held) = self.track.lowest_unread(from).filter(|held| held.start < group.start) { + from = held.start + 1; + if servable(&held, &self.frames) { + lowest = held.start; + break; + } + } + let mut start = source.map_or(lowest, |source| source.min(lowest)); + // A group given up, or held and not servable, cannot be where the feed starts. This + // stops at the held group at the latest, since it was not skipped. // Adjacent runs given up with different errors stay separate, so walk them all. - if let Start::Unresolved { skipped, .. } = &self.start { - while start < group.start - && let Some((given_up, _)) = skipped.get_key_value(&start) - { - start = given_up.end.min(group.start); + while start < group.start { + let given_up = match &self.start { + Start::Unresolved { skipped, .. } => skipped.get_key_value(&start).map(|(run, _)| run.end), + _ => None, + }; + let unservable = || { + let held = self.track.lowest_unread(start)?; + (held.start == start && !servable(&held, &self.frames)).then_some(start + 1) + }; + match given_up.or_else(unservable) { + Some(end) => start = end.min(group.start), + None => break, } } self.resolve(start, writer)?; @@ -9241,7 +9264,7 @@ mod serve_group_test { [(0, 0), (1, 0)], "each stream joins the subscription's group" ); - assert_eq!(log.orders(), [(0, 1), (1, 3)], "newer groups first"); + assert_eq!(log.orders(), [(0, 3), (1, 1)], "newer groups first"); assert!(log.priorities().is_empty(), "the session queue ranks no stream"); run.replace(lite::SubscribeUpdate { @@ -9262,7 +9285,8 @@ mod serve_group_test { ); let mut flipped = log.orders()[2..].to_vec(); flipped.sort(); - assert_eq!(flipped, [(0, 1), (1, -1)], "older groups first"); + // Stream 0 carries group 1, which went first. + assert_eq!(flipped, [(0, -1), (1, 1)], "older groups first"); } /// A group with more frames ready than one poll's budget drains over several polls, diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 51e7a75b49a..5c2539fd656 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -7816,7 +7816,9 @@ mod tests { for _ in 0..3 { read.push(consumer.recv_group().await.unwrap().unwrap().start); } - assert_eq!(read, [1, 2, 3]); + assert_eq!(track.arrival_order(), [1, 2, 3], "opened in arrival order"); + // Read newest first, the default Group Order. + assert_eq!(read, [3, 2, 1]); } /// A parked stream that fails before taking its group withdraws it: the accept opens none diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 657f4eb17cb..f11c4fb0c0d 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -17342,11 +17342,12 @@ mod tests { let mut group = track.append_next().unwrap(); group.write_frame(group.key_time(), b"live".as_ref()).unwrap(); group.finish().unwrap(); + // Both held at once, the newest goes first. let mut group = subscription.recv_group().await.unwrap().unwrap(); - assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"cached"); + assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"live"); drop(group); let mut group = subscription.recv_group().await.unwrap().unwrap(); - assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"live"); + assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"cached"); drop(group); drop(subscription); diff --git a/rs/moq-net/src/model/resume.rs b/rs/moq-net/src/model/resume.rs index 683e1346dbb..234151b7bea 100644 --- a/rs/moq-net/src/model/resume.rs +++ b/rs/moq-net/src/model/resume.rs @@ -1260,8 +1260,8 @@ impl Mirror { } impl Subscriber { - /// Reserve the lowest next group not in `delivered` across copies, without handing it - /// out: in arrival order, or in key order for `ordered`. + /// Reserve the next group not in `delivered` across copies, without handing it out: the + /// first any copy holds in the subscription's Group Order, or the lowest for `ordered`. /// Unless it `parks`, a bounded reader ends once its window has nothing left on any copy; /// see [`Reader::exhausted`]. /// @@ -1294,7 +1294,7 @@ impl Subscriber { // even on a path that parks without looking at the route. reader.route.register(waiter); let polled = loop { - if let Some(result) = reader.poll_lowest(ordered, parks, delivered, waiter) { + if let Some(result) = reader.poll_first(ordered, parks, delivered, waiter) { break result; } }; @@ -1378,24 +1378,46 @@ impl Subscriber { .collect() } - /// Forget the gaps in `delivered` below each group past the reader's budget, judged on - /// the newest copy that answered; see [`track::Subscriber::forget_past_budget`]. + /// Forget the gaps in `delivered` below each group past the reader's budget, as + /// [`Self::forget_past`] does; see [`track::Subscriber::forget_past_budget`]. pub(super) fn forget_past_budget(&self, delivered: &mut Delivered) { let budget = self.reader().budget(); - self.forget_past(delivered, budget); + self.forget_past(delivered, budget, None); } /// Forget the gaps in `delivered` below each group past `budget`, an outer reader's whose - /// `delivered` this is, judged on the newest copy that answered. - pub(super) fn forget_past(&self, delivered: &mut Delivered, budget: Budget) { + /// `delivered` this is, judged on the newest copy that answered, but never past a group a + /// replaced copy the reader still reads holds unread: as one cursor keeps what it owes, + /// since a late group there may be fresh by its own successor on that copy. Nor past `keep`, + /// an outer reader's own such group. + pub(super) fn forget_past(&self, delivered: &mut Delivered, budget: Budget, keep: Option) { let reader = self.reader(); let mut ready = reader.copies.iter().rev().filter_map(|copy| match ©.sub { - Sub::Ready(sub) => Some(sub), + Sub::Ready(sub) => Some((copy, sub)), Sub::Pending(_) => None, }); - if let Some(sub) = ready.next() { - sub.forget_past_budget(delivered, budget); - } + let Some((_, newest)) = ready.next() else { + return; + }; + let unread = |sub: &track::Subscriber| { + let mut from = delivered.floor(); + while let Some(group) = sub.lowest_unread(from) { + if !delivered.contains(group.start) { + return Some(group.start); + } + from = group.start.checked_add(1)?; + } + None + }; + // Judged as the pick judges a copy now, not by the verdict letting it go last made: a + // widened budget reads an expired copy again. + let widest = reader.mirrored.widest(); + let kept = ready + .filter(|(copy, _)| copy.replaced && reader.reads(copy, widest, delivered, &kio::Waiter::noop()).is_some()) + .filter_map(|(_, sub)| unread(sub)) + .chain(keep) + .min(); + newest.forget_past_budget(delivered, budget, kept); } /// Poll for the track's declared exclusive end. @@ -1403,6 +1425,22 @@ impl Subscriber { self.reader().poll_finished(waiter) } + /// The lowest group at or above `from` any copy's arrival read holds unread; see + /// [`track::Subscriber::lowest_unread`]. Of the copies holding it, the one serving the + /// most of it, so which copy holds a group never decides whether it can be served: one + /// that can fetch its head serves any frame, and below its first frame a copy that can't + /// fetches nothing, so the lowest first frame serves the rest. + #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] + pub(super) fn lowest_unread(&self, from: u64) -> Option { + let reader = self.reader(); + (reader.copies.iter()) + .filter_map(|copy| match ©.sub { + Sub::Ready(sub) => sub.lowest_unread(from), + Sub::Pending(_) => None, + }) + .min_by_key(|group| (group.start, !group.fetches_from(0), group.first_frame())) + } + /// Poll for where the serving copy's live feed starts; see /// [`track::Subscriber::poll_start`]. #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] @@ -2692,7 +2730,7 @@ impl Reader { owed.remove(run.clone()); } for copy in &self.copies { - // Only a copy `poll_lowest` still reads delivers: not ran out, failed, or past + // Only a copy `poll_first` still reads delivers: not ran out, failed, or past // the budget. if copy.done.is_some() || copy.expired(budget, waiter) { continue; @@ -2886,9 +2924,32 @@ impl Reader { Ok(self.hand_out(index, group)) } - /// Choose without consuming a candidate, so a newer copy cannot overtake a lower - /// group still buffered on an older one. A tie favors the newer copy. - fn poll_lowest( + /// Whether [`Self::poll_first`] reads `copy` now, given the reader's [`Mirrored::widest`] + /// budget: `Some(true)` when it ran out cleanly but a late group reopened it. + fn reads(&self, copy: &Copy, widest: Duration, delivered: &Delivered, waiter: &kio::Waiter) -> Option { + // A fully handed-out bounded copy still backs groups being read, but cannot + // supply another one. Keep its recovery lease without polling its empty range. + let spent = copy.end().is_some_and(|end| delivered.covers(self.groups.0..end)); + // A copy that ran out cleanly still takes a group in flight below its end while the + // read stays open, as a cursor still reading it would. + let ran_out = match ©.done { + None => false, + Some(Ok(drained)) if !spent && copy.track.poll_arrived(*drained, waiter).is_ready() => true, + Some(_) => return None, + }; + // What a replaced copy holds is past the reader's budget once a newer group superseded + // it a full budget ago. A copy is let go as a whole, so it waits out the widest budget + // any group gets. + if spent || copy.expired(widest, waiter) { + return None; + } + Some(ran_out) + } + + /// Choose without consuming a candidate, so a newer copy cannot overtake a group still + /// buffered on an older one that goes first: the lowest for an `ordered` read, else the + /// first in the subscription's Group Order. A tie favors the newer copy. + fn poll_first( &mut self, ordered: bool, parks: bool, @@ -2899,28 +2960,16 @@ impl Reader { self.groups_read = true; self.backfill_gaps(delivered, waiter); let groups = self.groups; - // A copy is let go as a whole, so it waits out the widest budget any group gets. - let budget = self.mirrored.widest(); + let widest = self.mirrored.widest(); let floor = if ordered { delivered.floor() } else { 0 }; - let mut lowest: Option = None; + let ascending = ordered || self.mirrored.order == track::Order::Ascending; + let mut first: Option = None; let mut held = false; for index in 0..self.copies.len() { - let copy = &mut self.copies[index]; - // What a replaced copy holds is past the reader's budget once a newer group - // superseded it a full budget ago. - // A fully handed-out bounded copy still backs groups being read, but cannot - // supply another one. Keep its recovery lease without polling its empty range. - let spent = copy.end().is_some_and(|end| delivered.covers(groups.0..end)); - // A copy that ran out cleanly still takes a group in flight below its end while the - // read stays open, as a cursor still reading it would. - let ran_out = match ©.done { - None => false, - Some(Ok(drained)) if !spent && copy.track.poll_arrived(*drained, waiter).is_ready() => true, - Some(_) => continue, - }; - if spent || copy.expired(budget, waiter) { + let Some(ran_out) = self.reads(&self.copies[index], widest, delivered, waiter) else { continue; - } + }; + let copy = &mut self.copies[index]; if ran_out { copy.done = None; } @@ -2998,8 +3047,12 @@ impl Reader { } continue; } - if lowest.as_ref().is_none_or(|lowest| key <= lowest.key()) { - lowest = Some(Candidate { + let goes_first = |first: &Candidate| match ascending { + true => key <= first.key(), + false => key >= first.key(), + }; + if first.as_ref().is_none_or(goes_first) { + first = Some(Candidate { lease: self.copies[index].lease.clone(), reserved, }); @@ -3051,13 +3104,13 @@ impl Reader { .get_or_insert_with(|| Resumed::Route(None, BTreeMap::new())); } } - // A later copy placed the window this pass: a group held back above may now be the lowest. + // A later copy placed the window this pass: a group held back above may now go first. if held && !self.window().is_pending() { - drop(lowest); - return self.poll_lowest(ordered, parks, delivered, waiter); + drop(first); + return self.poll_first(ordered, parks, delivered, waiter); } - if let Some(lowest) = lowest { - return Some(Poll::Ready(Ok(Some(lowest)))); + if let Some(first) = first { + return Some(Poll::Ready(Ok(Some(first)))); } // A copy answering this pass may have placed the ranges the switch's backfill waits // for: ask for it now, since no later group is sure to wake the read. @@ -4927,13 +4980,13 @@ mod test { let mut last = source.create_group(group::Info { start: 2 }).unwrap(); last.write_frame(ts(2), b"c".as_ref()).unwrap(); source.finish_at(Position { group: 2, frame: 1 }).unwrap(); + let mut capped = recv(&mut sub); + assert_eq!(read(&mut capped), Some(b"c".to_vec())); + assert_eq!(read(&mut capped), None); let mut first = recv(&mut sub); assert_eq!(read(&mut first), Some(b"a".to_vec())); assert_eq!(read(&mut first), Some(b"b".to_vec())); assert_eq!(read(&mut first), None); - let mut capped = recv(&mut sub); - assert_eq!(read(&mut capped), Some(b"c".to_vec())); - assert_eq!(read(&mut capped), None); } #[kio::test] @@ -5589,7 +5642,7 @@ mod test { routes.serve(b.consume()); write(&b, 10); write(&b, 20); - assert_eq!(drain(&mut sub, false), [10, 20]); + assert_eq!(drain(&mut sub, false), [20, 10]); routes.serve(a.consume()); write(&a, 30); @@ -5618,7 +5671,7 @@ mod test { routes.serve(b.consume()); write(&b, 10); write(&b, 20); - assert_eq!(drain(&mut sub, false), [10, 20]); + assert_eq!(drain(&mut sub, false), [20, 10]); write(&a, 15); assert_eq!(copies(&routes), 2, "the held group keeps the first route"); routes.serve(a.consume()); @@ -5794,7 +5847,7 @@ mod test { for sequence in 0..4 { write(&a, sequence); } - assert_eq!(drain(&mut sub, false), [0, 1, 2, 3], "routed={routed}"); + assert_eq!(drain(&mut sub, false), [3, 2, 1, 0], "routed={routed}"); // It reaches back to the oldest group rather than naming one. assert_eq!(sub.floor(), None, "routed={routed}"); assert_eq!( @@ -7531,7 +7584,7 @@ mod test { assert_eq!(dropped(&mut sub), []); write(&a, 3); write(&a, 4); - assert_eq!(drain(&mut sub, false), [3, 4]); + assert_eq!(drain(&mut sub, false), [4, 3]); assert_eq!(dropped(&mut sub), []); } @@ -8003,7 +8056,7 @@ mod test { write(&c, key); } routes.serve(c.consume()); - assert_eq!(drain(&mut sub, false), (1..9).collect::>()); + assert_eq!(drain(&mut sub, false), (1..9).rev().collect::>()); open.abort(Error::Stream(StreamError::Session(SessionError::Cancel))) .unwrap(); @@ -8030,8 +8083,8 @@ mod test { } } - assert_eq!(recv(&mut sub).start, 0); assert_eq!(recv(&mut sub).start, 1); + assert_eq!(recv(&mut sub).start, 0); routes.serve(b.consume()); assert_eq!(recv(&mut sub).start, 2); assert!(sub.recv_group().now_or_never().is_none()); @@ -8597,7 +8650,7 @@ mod test { for key in 0..6 { write(&a, key); } - assert_eq!(drain(&mut sub, false), vec![4, 5]); + assert_eq!(drain(&mut sub, false), vec![5, 4]); let mut sub = sub.with_range(1..); assert_eq!(drain(&mut sub, false), vec![3, 2, 1], "passed below the floor"); @@ -8668,7 +8721,8 @@ mod test { for key in 0..6 { write(&a, key); } - assert_eq!(drain(&mut sub, ordered), [4, 5]); + let held: &[u64] = if ordered { &[4, 5] } else { &[5, 4] }; + assert_eq!(drain(&mut sub, ordered), held, "{case}"); let b = copy(); if cached { @@ -8692,7 +8746,7 @@ mod test { write(&b, key); } } - let lowered: &[u64] = if ordered { &[] } else { &[1, 2, 3] }; + let lowered: &[u64] = if ordered { &[] } else { &[3, 2, 1] }; assert_eq!(drain(&mut sub, ordered), lowered, "{case}"); write(&b, 7); assert_eq!(drain(&mut sub, ordered), [7], "{case}"); @@ -8711,7 +8765,7 @@ mod test { for key in 0..6 { write(&a, key); } - assert_eq!(drain(&mut sub, false), [0, 1, 2, 3, 4, 5]); + assert_eq!(drain(&mut sub, false), [5, 4, 3, 2, 1, 0]); let b = copy(); for key in 0..6 { write(&b, key); @@ -8749,7 +8803,7 @@ mod test { for key in 0..6 { write(&a, key); } - assert_eq!(drain(&mut sub, false), [4, 5]); + assert_eq!(drain(&mut sub, false), [5, 4]); let b = copy(); for key in 0..6 { write(&b, key); @@ -8797,7 +8851,7 @@ mod test { for key in [0, 2, 4, 6] { write(&a, key); } - assert_eq!(drain(&mut sub, false), [4, 6]); + assert_eq!(drain(&mut sub, false), [6, 4]); let b = copy(); for key in [0, 2, 4, 6] { write(&b, key); @@ -8843,7 +8897,7 @@ mod test { for key in [0, 2, 4, 6] { write(&a, key); } - assert_eq!(drain(&mut sub, false), [4, 6]); + assert_eq!(drain(&mut sub, false), [6, 4]); let b = copy(); for key in [0, 2, 4, 6] { write(&b, key); @@ -8888,7 +8942,7 @@ mod test { for key in 0..6 { write(&a, key); } - assert_eq!(drain(&mut sub, false), [4, 5]); + assert_eq!(drain(&mut sub, false), [5, 4]); a.clone().abort(Error::Cancel).unwrap(); let b = track::Request::new(Arc::new(broadcast::Info::default()), "video"); @@ -9002,7 +9056,8 @@ mod test { }; write(&a, 0); write(&a, 1); - assert_eq!(drain(&mut sub, ordered), [0, 1], "ordered={ordered}"); + let held: &[u64] = if ordered { &[0, 1] } else { &[1, 0] }; + assert_eq!(drain(&mut sub, ordered), held, "ordered={ordered}"); assert!( poll(&mut sub).is_pending(), "ordered={ordered}: group 2 is still to come" @@ -9039,7 +9094,7 @@ mod test { .unwrap(); write(&a, 3); write(&a, 7); - assert_eq!(drain(&mut sub, false), [3, 7], "5 is missing"); + assert_eq!(drain(&mut sub, false), [7, 3], "5 is missing"); // b resumes at 7, placing the range's start there, and lacks 5 too. let b = received_copy(); @@ -9251,8 +9306,8 @@ mod test { .unwrap(); write(&a, 0); write(&a, 1); - assert_eq!(recv(&mut sub).start, 0); assert_eq!(recv(&mut sub).start, 1); + assert_eq!(recv(&mut sub).start, 0); routes.park(); assert!(sub.poll_recv_group(&kio::Waiter::noop()).is_pending()); routes.serve(a.consume()); @@ -9321,7 +9376,7 @@ mod test { for sequence in [0, 1, 3] { write(&a, sequence); } - assert_eq!(drain(&mut sub, false), [0, 1, 3], "{case}"); + assert_eq!(drain(&mut sub, false), [3, 1, 0], "{case}"); let b = copy(); routes.serve(b.consume()); write(&b, 4); @@ -9340,7 +9395,7 @@ mod test { } /// A replaced copy is bounded only once the new copy delivers its first group: a group - /// buffered on it must be read before a later group on the serving copy. + /// buffered on it is still read, before a later group on the serving copy in key order. #[test] fn key_reads_take_a_replaced_copys_lower_buffered_group() { replaced_copy_reads_lowest(true); @@ -9363,7 +9418,10 @@ mod test { let b = copy(); routes.serve(b.consume()); write(&b, 2); - assert_eq!(drain(&mut sub, ordered), [1, 2]); + // An arrival read takes the newer group first, in Group Order, but still reads the + // replaced copy's. + let read: &[u64] = if ordered { &[1, 2] } else { &[2, 1] }; + assert_eq!(drain(&mut sub, ordered), read); } /// An ordered read after arrival reads passes a group the new copy replays that an arrival @@ -9377,7 +9435,7 @@ mod test { let mut sub = subscribe(&logical, HOUR); write(&a, 0); write(&a, 2); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); let b = copy(); write(&b, 2); write(&b, 3); @@ -9396,7 +9454,17 @@ mod test { outer_routes.serve(inner.consume()); let a = copy(); routes.serve(a.consume()); - let mut sub = subscribe(if nested { &outer } else { &inner }, HOUR); + // Oldest first, so the arrival read reserves group 1 too. + let subscription = Subscription::default() + .with_max(HOUR) + .with_order(track::Order::Ascending); + let logical = if nested { &outer } else { &inner }; + let mut sub = logical + .consume() + .subscribe(subscription) + .now_or_never() + .unwrap() + .unwrap(); let mut one = a.create_group(group::Info { start: 1 }).unwrap(); one.write_frame(ts(1), b"x".as_ref()).unwrap(); let one = one.finish().unwrap(); @@ -9562,7 +9630,7 @@ mod test { let b = copy(); routes.serve(b.consume()); write(&b, 3); - assert_eq!(drain(&mut sub, false), [2, 3]); + assert_eq!(drain(&mut sub, false), [3, 2]); let held = |routes: &Producer| { let readers = routes.readers.lock().unwrap(); let reader = readers.iter().find_map(Weak::upgrade).unwrap(); @@ -9646,7 +9714,7 @@ mod test { write(&a, 1); // Still read, so the replaced copy stays. let _reading = recv(&mut sub); - assert_eq!(drain(&mut sub, false), [1]); + assert_eq!(drain(&mut sub, false), [0]); let b = copy(); routes.serve(b.consume()); write(&b, 2); @@ -9683,7 +9751,7 @@ mod test { let b = copy(); routes.serve(b.consume()); // Group 2 is the replaced copy's to drain, group 1 the serving route's to fill. - assert_eq!(drain(&mut sub, false), [2, 3]); + assert_eq!(drain(&mut sub, false), [3, 2]); { let readers = routes.readers.lock().unwrap(); let reader = readers.iter().find_map(Weak::upgrade).unwrap(); @@ -9844,7 +9912,7 @@ mod test { let mut sub = subscribe(&logical, Duration::from_secs(1)); write(&a, 0); write(&a, 2); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); // The new route has only the group already handed out, and ends there. let b = copy(); @@ -9877,7 +9945,7 @@ mod test { let mut sub = subscribe(&logical, budget); write(&a, 0); write(&a, 2); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); pool.poll(opened.saturating_add(budget / 2), &noop); let b = copy(); @@ -9929,7 +9997,7 @@ mod test { let mut sub = subscribe(&logical, Duration::from_secs(1)); write(&a, 0); write(&a, 2); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); let b = copy(); write(&b, 2); @@ -10453,7 +10521,7 @@ mod test { for key in 2..=2000 { write(&b, key); } - assert_eq!(drain(&mut sub, false), (2..=2000).collect::>()); + assert_eq!(drain(&mut sub, false), (2..=2000).rev().collect::>()); assert_eq!(sub.delivered_runs(), 2, "the gap at 1 is within the budget"); // The replacement's copies of groups 1 and 0 land last: 1 is new, 0 is not. @@ -10495,7 +10563,7 @@ mod test { let mut sub = subscribe(&logical, HOUR); write(&a, 0); let open = a.create_group(group::Info { start: 1 }).unwrap(); - assert_eq!(drain(&mut sub, false), [0, 1]); + assert_eq!(drain(&mut sub, false), [1, 0]); open.abort(Error::Cancel).unwrap(); write(&a, 1); @@ -10647,7 +10715,7 @@ mod test { } sub.set_range(..); - assert_eq!(drain(&mut sub, false), [2, 6]); + assert_eq!(drain(&mut sub, false), [6, 2]); } /// A serving copy that ran out at its session's settled end still hands out a group in @@ -10732,7 +10800,8 @@ mod test { ]; let subscription = Subscription::default() .with_ranges(ranges) - .with_max(Duration::from_secs(30)); + .with_max(Duration::from_secs(30)) + .with_order(track::Order::Ascending); let mut sub = logical .consume() .subscribe(subscription) @@ -11183,7 +11252,7 @@ mod test { while let Some(Ok(Some(group))) = sub.recv_group().now_or_never() { rest.push(group.start); } - assert_eq!(rest, vec![0, 1000, 2000, 3000, 4000, 6000]); + assert_eq!(rest, vec![6000, 4000, 3000, 2000, 1000, 0]); } /// A reader that moves its start to exactly the replacement's resume point, while that @@ -11227,7 +11296,9 @@ mod test { got.extend(drain(&mut sub, ordered)); write(&b, 9); got.extend(drain(&mut sub, ordered)); - assert_eq!(got, [5, 6, 8, 9], "fail={fail} ordered={ordered}"); + // An arrival read takes the groups it holds newest first. + let expected = if ordered { [5, 6, 8, 9] } else { [8, 6, 5, 9] }; + assert_eq!(got, expected, "fail={fail} ordered={ordered}"); } } } @@ -11619,7 +11690,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); let b = received_copy(); b.anchored(); routes.serve(b.consume()); @@ -11740,7 +11811,7 @@ mod test { write(&a, 8); routes.serve(a.consume()); let mut sub = subscribe(&front, HOUR); - assert_eq!(drain(&mut sub, false), [6, 8]); + assert_eq!(drain(&mut sub, false), [8, 6]); let inner_routes = Producer::new(); let inner = logical(&inner_routes); let b = received_copy(); @@ -12070,7 +12141,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(recv(&mut sub).start, 8); + assert_eq!(recv(&mut sub).start, 10); let (b, _requests) = pending_copy(); routes.serve(b.consume()); @@ -12459,7 +12530,9 @@ mod test { }; let placed = |ranges: Vec| Subscription { placed: [(0, 3)].into(), - ..Subscription::default().with_ranges(ranges) + ..Subscription::default() + .with_ranges(ranges) + .with_order(track::Order::Ascending) }; let preferences = track::Preferences::from(placed(vec![join])); let mut sub = routes.consume().subscribe(preferences.clone()); @@ -12515,7 +12588,7 @@ mod test { else { panic!("a group to reserve") }; - assert_eq!(sub.take(candidate).unwrap().start, 5); + assert_eq!(sub.take(candidate).unwrap().start, 10); for sequence in 11..=20 { write(&a, sequence); } @@ -12551,10 +12624,12 @@ mod test { max: None, }; let ranges = |back| { - Subscription::default().with_ranges([track::Range { - start: join(back), - end: Some(1_000_000 + back), - }]) + Subscription::default() + .with_ranges([track::Range { + start: join(back), + end: Some(1_000_000 + back), + }]) + .with_order(track::Order::Ascending) }; let preferences = track::Preferences::from(ranges(5)); let mut sub = routes.consume().subscribe(preferences.clone()); @@ -12599,7 +12674,11 @@ mod test { false => vec![first], true => vec![first, past], }; - let preferences = track::Preferences::from(Subscription::default().with_ranges(ranges)); + let preferences = track::Preferences::from( + Subscription::default() + .with_ranges(ranges) + .with_order(track::Order::Ascending), + ); let mut sub = routes.consume().subscribe(preferences.clone()); let mut delivered = Delivered::default(); let Poll::Ready(Ok(Some(candidate))) = @@ -12621,7 +12700,11 @@ mod test { match switched { // Not yet mirrored into the copies: group 8 holds time 100. false => preferences - .update(Subscription::default().with_ranges([first, past])) + .update( + Subscription::default() + .with_ranges([first, past]) + .with_order(track::Order::Ascending), + ) .unwrap(), // The new copy answered, holding nothing yet. true => { @@ -12664,7 +12747,11 @@ mod test { }, end: Some(1_000_000), }; - let preferences = track::Preferences::from(Subscription::default().with_ranges([join])); + let preferences = track::Preferences::from( + Subscription::default() + .with_ranges([join]) + .with_order(track::Order::Ascending), + ); let mut sub = routes.consume().subscribe(preferences.clone()); let mut delivered = Delivered::default(); let mut next = |sub: &mut Subscriber| { @@ -12683,11 +12770,13 @@ mod test { for _ in 0..40 { let add = track::Edit { add: vec![(1, track::Range::ALL)], + order: track::Order::Ascending, ..Default::default() }; preferences.edit(add).unwrap(); let retire = track::Edit { retire: vec![1], + order: track::Order::Ascending, ..Default::default() }; preferences.edit(retire).unwrap(); @@ -12695,6 +12784,7 @@ mod test { if let Some(range) = left { let add = track::Edit { add: vec![(2, range)], + order: track::Order::Ascending, ..Default::default() }; preferences.edit(add).unwrap(); @@ -12715,7 +12805,7 @@ mod test { for key in (0..=50).step_by(10) { write(&a, key); } - assert_eq!(drain(&mut sub, false), [0, 10, 20, 30, 40, 50]); + assert_eq!(drain(&mut sub, false), [50, 40, 30, 20, 10, 0]); assert_eq!(sub.delivered_runs(), 6, "every gap is still owed"); sub.update(Subscription::default().with_range(50..=50)).unwrap(); assert_eq!(sub.delivered_runs(), 2, "0 through 40, then 50"); @@ -12883,9 +12973,8 @@ mod test { let mut group = a.create_group(group::Info { start: key }).unwrap(); group.write_frame(ts(ms), b"x".as_ref()).unwrap(); group.finish().unwrap(); + assert_eq!(recv(&mut sub).start, key); } - assert_eq!(recv(&mut sub).start, 0); - assert_eq!(recv(&mut sub).start, 1); let mut open = a.create_group(group::Info { start: 2 }).unwrap(); open.write_frame(ts(2000), b"held".as_ref()).unwrap(); let mut group = recv(&mut sub); @@ -13227,7 +13316,7 @@ mod test { for key in 0..=4 { write(&a, key); } - assert_eq!(drain(&mut sub, false), [0, 1, 2, 3, 4]); + assert_eq!(drain(&mut sub, false), [4, 3, 2, 1, 0]); let mut open = a.create_group(group::Info { start: 5 }).unwrap(); open.write_frame(ts(5), b"x".as_ref()).unwrap(); let reading = recv(&mut sub); @@ -13273,7 +13362,7 @@ mod test { for key in 0..=4 { write(&a, key); } - assert_eq!(drain(&mut sub, false), [0, 1, 2, 3, 4]); + assert_eq!(drain(&mut sub, false), [4, 3, 2, 1, 0]); let mut open = a.create_group(group::Info { start: 5 }).unwrap(); open.write_frame(ts(5), b"x".as_ref()).unwrap(); let reading = recv(&mut sub); @@ -13339,7 +13428,7 @@ mod test { for key in 0..=4 { write(&a, key); } - assert_eq!(drain(&mut sub, false), [0, 1, 2, 3, 4]); + assert_eq!(drain(&mut sub, false), [4, 3, 2, 1, 0]); let mut open = a.create_group(group::Info { start: 5 }).unwrap(); open.write_frame(ts(5), b"x".as_ref()).unwrap(); let reading = recv(&mut sub); @@ -13376,8 +13465,8 @@ mod test { for key in 0..=4 { write(&a, key); } - assert_eq!(drain(&mut first, false), [0, 1, 2, 3, 4]); - assert_eq!(drain(&mut second, false), [0, 1, 2, 3, 4]); + assert_eq!(drain(&mut first, false), [4, 3, 2, 1, 0]); + assert_eq!(drain(&mut second, false), [4, 3, 2, 1, 0]); let mut open = a.create_group(group::Info { start: 5 }).unwrap(); open.write_frame(ts(5), b"x".as_ref()).unwrap(); let (keeper, other) = match keeper_first { @@ -14537,7 +14626,7 @@ mod test { .unwrap() .unwrap(); let mut sub = sub; - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); let b = copy(); write(&b, 3); routes.serve(b.consume()); @@ -14566,7 +14655,7 @@ mod test { end: Some(3), }]); let mut sub = front.consume().subscribe(subscription).now_or_never().unwrap().unwrap(); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); let inner_routes = Producer::new(); let inner = logical(&inner_routes); let b = copy(); @@ -14606,7 +14695,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(drain(&mut sub, false), [0, 3]); + assert_eq!(drain(&mut sub, false), [3, 0]); let b = copy(); write(&b, 4); routes.serve(b.consume()); @@ -14648,7 +14737,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(drain(&mut sub, false), [0, 4]); + assert_eq!(drain(&mut sub, false), [4, 0]); let b = copy(); b.skip_groups(1..2); write(&b, 5); @@ -14686,7 +14775,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(drain(&mut sub, false), [0, 5]); + assert_eq!(drain(&mut sub, false), [5, 0]); let b = copy(); write(&b, 6); routes.serve(b.consume()); @@ -14717,7 +14806,11 @@ mod test { write(&a, 1); routes.serve(a.consume()); let budget = Duration::from_secs(1); - let mut sub = subscribe(&logical, budget); + // Oldest first, so group 1 is left unread. + let ascending = Subscription::default() + .with_max(budget) + .with_order(track::Order::Ascending); + let mut sub = logical.consume().subscribe(ascending).now_or_never().unwrap().unwrap(); assert_eq!(recv(&mut sub).start, 0); sub.set_range(..1); let b = copy(); @@ -14728,6 +14821,77 @@ mod test { assert!(matches!(sub.poll_recv_group(&fresh()), Poll::Ready(Ok(None)))); } + /// Late groups a replaced copy holds unread, fresh by their own successors there, outlive + /// the serving copy's old arrival above them making the gap below it stale, as they do on + /// one track: a cursor never forgets what it still holds to hand out. + #[kio::test] + async fn a_replaced_copys_unread_late_groups_outlive_the_serving_copys_stale_verdict() { + for routed in [false, true] { + let routes = Producer::new(); + let logical = logical(&routes); + let a = copy(); + routes.serve(a.consume()); + let budget = Duration::from_secs(1); + let mut sub = subscribe(if routed { &logical } else { &a }, budget); + write(&a, 0); + write(&a, 5); + // Held, so the replaced copy stays subscribed. + let _held = recv(&mut sub); + assert_eq!(drain(&mut sub, false), [0]); + let b = copy(); + if routed { + routes.serve(b.consume()); + } + let serving = if routed { &b } else { &a }; + assert_eq!(drain(&mut sub, false), Vec::::new()); + // 6 arrives long before the late groups, and the reader looks only once they land: + // 4 is stale by 5, while 2 and 1 are fresh by 4 and 2. + write(serving, 6); + kio::clock::sleep(2 * budget).await; + for key in [4, 2, 1] { + write(&a, key); + } + assert_eq!(drain(&mut sub, false), [6, 2, 1], "routed {routed}"); + } + } + + /// A replaced copy past the reader's budget is read again once the budget widens, so its + /// late groups outlive the serving copy's stale verdict as they do on one track: compaction + /// judges a copy as the pick does now, not by the verdict letting copies go last made. + #[kio::test] + async fn a_widened_budget_keeps_an_expired_copys_late_groups() { + let ms = Duration::from_millis; + for routed in [false, true] { + let routes = Producer::new(); + let logical = logical(&routes); + let a = copy(); + routes.serve(a.consume()); + let mut sub = subscribe(if routed { &logical } else { &a }, ms(1000)); + write(&a, 0); + write(&a, 5); + // Held, so the replaced copy stays subscribed once it expires. + let _held = recv(&mut sub); + assert_eq!(drain(&mut sub, false), [0]); + let b = copy(); + if routed { + routes.serve(b.consume()); + } + write(if routed { &b } else { &a }, 6); + // Read within the budget, so no gap below 6 is stale yet. + kio::clock::sleep(ms(900)).await; + assert_eq!(drain(&mut sub, false), [6]); + // A budget past 6 superseding it, the replaced copy expires and goes unread. + kio::clock::sleep(ms(1500)).await; + assert!(sub.poll_recv_group(&fresh()).is_pending()); + for key in [4, 2, 1] { + write(&a, key); + } + // Wide enough to read the copy again, not to keep 4: 5 arrived past it. + sub.update(Subscription::default().with_max(ms(2000))).unwrap(); + assert_eq!(drain(&mut sub, false), [2, 1], "routed {routed}"); + } + } + /// A backfill of the serving route goes once it delivered what it was asked for, when the /// only key the local floor keeps out under the resume point is skipped: nothing is left to /// ask that route, so no copy is kept for the ask. @@ -14741,7 +14905,7 @@ mod test { write(&a, 3); routes.serve(a.consume()); let mut sub = subscribe_until(&logical, 5); - assert_eq!(drain(&mut sub, false), [0, 3]); + assert_eq!(drain(&mut sub, false), [3, 0]); let mut sub = sub.with_range(2..6); let b = copy(); write(&b, 4); @@ -14766,7 +14930,7 @@ mod test { write(&a, 3); routes.serve(a.consume()); let mut sub = subscribe(&logical, HOUR); - assert_eq!(drain(&mut sub, false), [0, 3]); + assert_eq!(drain(&mut sub, false), [3, 0]); let b = copy(); write(&b, 4); routes.serve(b.consume()); @@ -14791,7 +14955,7 @@ mod test { } routes.serve(a.consume()); let mut sub = subscribe_until(&logical, 9); - assert_eq!(drain(&mut sub, false), [0, 1, 2]); + assert_eq!(drain(&mut sub, false), [2, 1, 0]); // Asked from 2, it never gets 3. let b = received_copy(); let b_fills = b.requests(); @@ -14834,7 +14998,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(drain(&mut sub, false), [0, 5]); + assert_eq!(drain(&mut sub, false), [5, 0]); let pool = crate::cache::Pool::new(crate::cache::Config::default().with_expiry(Duration::from_secs(10))); let b = track::Producer::new( Arc::new(broadcast::Info { @@ -14916,7 +15080,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(drain(&mut sub, false), [0, 5]); + assert_eq!(drain(&mut sub, false), [5, 0]); let pool = crate::cache::Pool::new(crate::cache::Config::default().with_expiry(Duration::from_secs(10))); let b = track::Producer::new( Arc::new(broadcast::Info { @@ -14990,7 +15154,7 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); let b = copy(); write(&b, 3); routes.serve(b.consume()); @@ -15032,7 +15196,7 @@ mod test { routes.serve(a.consume()); let window = |start| Subscription::default().with_range(start..14); let mut sub = logical.consume().subscribe(window(10)).now_or_never().unwrap().unwrap(); - assert_eq!(drain(&mut sub, false), [10, 11]); + assert_eq!(drain(&mut sub, false), [11, 10]); let b = copy(); write(&b, 12); routes.serve(b.consume()); @@ -15082,9 +15246,9 @@ mod test { .now_or_never() .unwrap() .unwrap(); - assert_eq!(recv(&mut sub).start, 0); let reading = recv(&mut sub); assert_eq!(reading.start, 5); + assert_eq!(recv(&mut sub).start, 0); let b = copy(); // The route answers fills, so its copy never gives 2 up as unfillable. let _requests = b.requests(); @@ -15129,7 +15293,7 @@ mod test { }]) .with_max(HOUR); let mut sub = front.consume().subscribe(subscription).now_or_never().unwrap().unwrap(); - assert_eq!(drain(&mut sub, false), [0, 2]); + assert_eq!(drain(&mut sub, false), [2, 0]); let b = copy(); write(&b, 3); inner_routes.serve(b.consume()); @@ -15169,7 +15333,7 @@ mod test { .unwrap() .unwrap() .with_range(1..3); - assert_eq!(drain(&mut sub, false), [1, 2]); + assert_eq!(drain(&mut sub, false), [2, 1]); assert!(matches!( sub.poll_recv_group(&kio::Waiter::noop()), Poll::Ready(Ok(None)) diff --git a/rs/moq-net/src/model/subscription.rs b/rs/moq-net/src/model/subscription.rs index f813ee1bcf3..d2280baff4a 100644 --- a/rs/moq-net/src/model/subscription.rs +++ b/rs/moq-net/src/model/subscription.rs @@ -113,9 +113,11 @@ pub(crate) fn max_of(budget: Duration) -> Option { Some(budget).filter(|budget| *budget != Duration::MAX) } -/// Which of a subscription's pending groups the publisher sends first. +/// Which of a subscription's groups comes first: the publisher sends its pending groups in +/// this order, and `recv_group` hands out the groups it holds in it. Before moq-lite-07 the +/// publisher sends newest first whatever this asks. /// -/// A transmission order only: it never decides *whether* a group is delivered. A history +/// An order only: it never decides *whether* a group is delivered. A history /// range ([`Start::Time`] or [`Start::Oldest`]) delivers every group it covers, and a /// [`Start::Live`] range skips what its `max` judges stale, so an ascending subscriber that /// wants a backlog drains it from a history range or a `max` that covers it. diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 5b1daabe04b..70e4604af7e 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -2327,38 +2327,39 @@ impl TrackState { }; } - /// Find the next live group at or after `index` in arrival order, for a reader reading - /// `window`. + /// Take in the live groups that arrived at or after `index`, for a reader reading `window` + /// from `min_key` to pick from in its Group Order: their keys, in arrival order. /// - /// Returns the group and its absolute index so the consumer can advance past it. - /// The cached producer rather than a consumer: `consume` reads the clock and can - /// take the group's own lock, which the caller does once the track guard is gone. + /// Moves `index` past every entry it looks at, the dead ones and those below `min_key` + /// included, which a lower floor re-offers from the cache instead. It stays only on a + /// trailing entry not handed out yet, which a fetched head may revive, so a wake walks + /// only that trailing run and what arrived since, however many stale entries did. The run + /// holds only groups that arrived cut short after the last readable one. /// - /// Moves `index` past the leading entries this reader is never handed: dead, or below - /// `min_key`, which a lower floor re-offers from the cache instead. So a wake walks - /// only what the reader may still be handed, however many stale entries arrived. - fn poll_recv_group( - &self, - index: &Cell, - min_key: u64, - window: &Window, - ) -> Poll>> { + /// Ready with nothing once the track completed, or with its abort. + fn poll_arrivals(&self, index: &Cell, min_key: u64, window: &Window) -> Poll>>> { + let mut arrived = Vec::new(); if self.serves_bounded(window) { - let mut passed = true; + let mut stop = None; + let mut past = index.get(); for entry in self.arrivals_from(index.get()) { + past = entry.at + 1; let slot = self.lookup.get(&entry.key).filter(|slot| slot.stamp == entry.stamp); let Some(slot) = slot.filter(|_| entry.key >= min_key) else { - if passed { - index.set(entry.at + 1); - } continue; }; // A cut group is handed out too, so its reader sees why it ended. if slot.is_read() { - return Poll::Ready(Ok(Some((slot.serving().clone(), entry.at)))); + arrived.push(entry.key); + stop = None; + } else { + stop.get_or_insert(entry.at); } - passed = false; } + index.set(stop.unwrap_or(past)); + } + if !arrived.is_empty() { + return Poll::Ready(Ok(Some(arrived))); } // TODO once we have drop notifications, check if index == final_key. @@ -6138,6 +6139,16 @@ impl Producer { self.state.read().start.key() } + /// The cached groups' keys in the order they arrived, which no reader's Group Order changes. + #[cfg(all(test, feature = "async"))] + pub(crate) fn arrival_order(&self) -> Vec { + let state = self.state.read(); + (state.arrivals_from(0)) + .filter(|entry| state.is_current(entry.key, entry.stamp)) + .map(|entry| entry.key) + .collect() + } + /// Evict group `key` from the cache, as expiry does. #[cfg(all(test, feature = "async"))] pub(crate) fn evict(&self, key: u64) { @@ -9595,7 +9606,7 @@ struct Cursor { cache: Arc, subscription: Preferences, - /// Arrival-order cursor used by `recv_group`. + /// How far `recv_group` took in the track's arrivals, which it owes until handed out. index: usize, /// Minimum key to return from any `recv` method. Set by `set_range`. min_key: u64, @@ -9860,9 +9871,7 @@ pub(super) struct Peeked { /// Where a recv-order candidate came from, which taking it advances past. #[derive(Clone, Copy)] enum Taken { - /// The arrival walk, which moves to this index. - Walk(usize), - /// What a widening owes. + /// What this cursor owes: an arrival, or what a widening newly covers. Owed, /// What a fill answered. Filled, @@ -10163,9 +10172,10 @@ struct Filter { admitted: Admitted, /// The floor, [`Self::revision`], and cap [`Self::admitted`] was taken at. admitted_at: Option<(u64, u64, Option)>, - /// The spans a widening newly covers, from the ranges, the floor, the cap, or the - /// budget, scanned in the cache in the subscription's order and handed out ahead of the - /// walk: each cached group in them is visited once. + /// What the arrival read holds unread: the arrivals it took in and not handed out yet, + /// and the spans a widening newly covers, from the ranges, the floor, the cap, or the + /// budget. Scanned in the cache in the subscription's order, so each cached group in + /// them is visited once. owed: RangeInclusiveSet, /// The time starts [`Self::window`] looks up from the track's history, each asked once. lookups: Vec, @@ -10806,15 +10816,19 @@ impl Cursor { } } - /// The next cached group still owed in the subscription's order, newest first unless - /// ascending, consuming the spans scanned on the way: only one the walk could have read, - /// never fetched backfill or a withheld group. The group itself stays owed until + /// The next cached group still owed in `order`; see [`Self::first_owed`]. + fn next_owed(&mut self, order: Order) -> Option { + self.first_owed(order == Order::Ascending) + } + + /// The lowest cached group still owed, or with `ascending` false the highest, consuming + /// the spans scanned on the way: only one the arrivals could have delivered, never + /// fetched backfill or a withheld group. The group itself stays owed until /// [`Self::advance_arrival`] takes it, so a peek keeps it. - fn next_owed(&mut self) -> Option { + fn first_owed(&mut self, ascending: bool) -> Option { if self.filter.owed.is_empty() { return None; } - let ascending = self.subscription.read().order == Order::Ascending; let state = self.state.read(); // Nothing is read from the cache now, so leave what is owed until it is. if !state.serves_bounded(&self.filter.window) { @@ -10847,6 +10861,37 @@ impl Cursor { } } + /// The lowest group at or above `from` this arrival read holds unread: owed and cached, + /// answered by a fill, or a head answered. Costs the owed runs up to it. + fn lowest_unread(&self, from: u64) -> Option { + let state = self.state.read(); + let owed = (self.filter.owed.overlapping(&(from..=u64::MAX))).find_map(|run| { + let mut slots = state.lookup.range((*run.start()).max(from)..=*run.end()); + slots.find(|(_, slot)| slot.is_read()).map(|(_, slot)| slot.serving()) + }); + // An answered group evicted or aborted since is passed over, as `next_filled` prunes it. + let filled = (self.misses.as_ref()).and_then(|misses| { + misses.filled_from(from).find_map(|key| { + state + .lookup + .get(&key) + .filter(|slot| slot.serves_end()) + .map(Slot::serving) + }) + }); + let lowest = [owed, filled] + .into_iter() + .flatten() + .min_by_key(|group| group.start) + .map(|group| group.consume()); + drop(state); + let head = self + .heads + .as_ref() + .and_then(|heads| heads.filled.range(from..).next().map(|(_, group)| group.clone())); + [lowest, head].into_iter().flatten().min_by_key(|group| group.start) + } + /// Record `key` as skipped stale under `budget`, so a wider one owes it again. fn skip(&mut self, key: u64, budget: Duration) { self.record.skipped.insert(key, budget); @@ -10860,8 +10905,10 @@ impl Cursor { return; } let state = self.state.read(); + // A fill's answer counts too: a widening hands it back to the fills (see `reowe`). + let refills = self.misses.is_some(); self.record.skipped.prune(state.lookup.len(), |run| { - !state.lookup.range(run.clone()).any(|(_, slot)| slot.is_read()) + !(state.lookup.range(run.clone())).any(|(_, slot)| slot.is_read() || (refills && slot.serves_end())) }); } @@ -10891,7 +10938,17 @@ impl Cursor { self.record.pending.remove(range); } } + let state = self.state.read(); for owed in self.filter.admitted.overlapping(run) { + // A fill's answer is no live-feed slot, which is all the owed set reads: it goes + // back to the fills answered. + if let Some(misses) = &mut self.misses { + for (key, slot) in state.lookup.range(owed.clone()) { + if !slot.visible && slot.serves_end() { + misses.refill(*key); + } + } + } self.filter.owed.insert(owed); } } @@ -11122,7 +11179,7 @@ impl Cursor { self.prune_skipped(); self.record.delivered.insert(key); let mut delivered = std::mem::take(&mut self.record.delivered); - self.forget_past_budget(&mut delivered, self.filter.window.budget()); + self.forget_past_budget(&mut delivered, self.filter.window.budget(), None); self.record.delivered = delivered; self.retire_written_off(); } @@ -11130,15 +11187,15 @@ impl Cursor { /// Forget the gaps in `delivered` below each group past `budget` now, whether this track /// holds it or not: one landing there would be written off. A group skipped as stale is /// not forgotten, since a wider budget owes it again, and neither is one a widening still - /// owes, which a newest-first re-offer has yet to judge. + /// owes, which a newest-first re-offer has yet to judge, nor any gap at or above `keep`. /// /// One edge for every group judged, so forgetting N gaps never resolves it N times. - fn forget_past_budget(&self, delivered: &mut Delivered, budget: Budget) { + fn forget_past_budget(&self, delivered: &mut Delivered, budget: Budget, keep: Option) { if delivered.above_gap().is_none() { return; } let owed = self.filter.owed.first().map(|run| *run.start()); - let skipped = self.record.skipped.lowest().into_iter().chain(owed).min(); + let kept = self.record.skipped.lowest().into_iter().chain(owed).chain(keep).min(); let state = self.state.read(); let budgets = budget.clamped(state.max_age_bound()); let edge = state.drift_edge(&self.servable); @@ -11171,10 +11228,10 @@ impl Cursor { let last = delivered .last_before(shared) .expect("the oldest run is below its successor"); - if let Some(skipped) = skipped - && skipped < last + if let Some(kept) = kept + && kept < last { - delivered.forget_below(skipped); + delivered.forget_below(kept); break; } delivered.forget_below(last); @@ -11447,11 +11504,10 @@ impl Cursor { } } - /// The next group a fill answered for this cursor in its order, cached and not handed - /// out yet, asking again for any evicted before it got to them. - fn next_filled(&mut self) -> Option { + /// The next group a fill answered for this cursor in `order`, cached and not handed out + /// yet, asking again for any evicted before it got to them. + fn next_filled(&mut self, order: Order) -> Option { let misses = self.misses.as_mut().filter(|misses| misses.has_filled())?; - let order = self.subscription.read().order; let (mut lost, mut given_up) = (RangeSet::new(), Vec::new()); let group = misses.next_filled(&self.state.read(), order, &mut lost, &mut given_up); if !lost.is_empty() { @@ -11526,26 +11582,55 @@ impl Cursor { self.poll_heads(waiter); self.expire_heads(&drift, waiter); loop { - // Re-offer what a widening newly covers ahead of the arrival walk, in the - // subscription's order: it is the oldest thing still owed. A group the walk has - // yet to reach comes again from it, and the subscriber's delivered set drops the - // repeat. - let owed = match self.next_owed() { - Some(producer) => Some((producer.consume(), Taken::Owed)), - // A fill answered what the walk never reaches: backfill is not in it. - None => match self.next_filled() { - Some(producer) => Some((producer.consume(), Taken::Filled)), - None => self.next_head().map(|group| (group, Taken::Head)), - }, + // What arrived since the last look is owed too, so the pick below sees every group + // held unread, buffered or re-offered by a widening, and hands out the first in the + // subscription's order. A late lower group is owed once it arrives, never passed over. + let arrived = { + let index = Cell::new(self.index); + let arrived = self + .state + .read() + .poll_arrivals(&index, self.floor(), &self.filter.window); + self.index = index.get(); + arrived }; - let (consumer, taken) = match owed { + if let Poll::Ready(Ok(Some(arrived))) = arrived + && self.owe_arrivals(arrived) + { + drift = ready!(self.poll_drift(&self.servable, waiter))?; + } + // Read once, so an update landing mid-pick applies to the next pick whole. + let order = self.subscription.read().order; + ready!(self.write_off_oldest(order, &drift, waiter))?; + // A fill answers what the arrivals never deliver, backfill and heads, which go in the + // same order. A tie goes to the arrival. + let (owed, filled, head) = (self.next_owed(order), self.next_filled(order), self.next_head(order)); + let ascending = order == Order::Ascending; + let keys = [ + owed.as_ref().map(|group| (group.start, Taken::Owed)), + filled.as_ref().map(|group| (group.start, Taken::Filled)), + head.as_ref().map(|group| (group.start, Taken::Head)), + ]; + let pick = keys.into_iter().flatten().reduce(|first, next| { + let goes_first = match ascending { + true => next.0 < first.0, + false => next.0 > first.0, + }; + if goes_first { next } else { first } + }); + // Only the group handed out is consumed. + let first = match pick.map(|(_, taken)| taken) { + Some(Taken::Owed) => owed.map(|group| (group.consume(), Taken::Owed)), + Some(Taken::Filled) => filled.map(|group| (group.consume(), Taken::Filled)), + Some(Taken::Head) => head.map(|group| (group, Taken::Head)), + None => None, + }; + let (consumer, taken) = match first { Some((consumer, taken)) => (consumer, taken), None => { - let floor = self.floor(); let index = Cell::new(self.index); - let polled = self.poll(waiter, |state| { - state.poll_recv_group(&index, floor, &self.filter.window) - }); + let floor = self.floor(); + let polled = self.poll(waiter, |state| state.poll_arrivals(&index, floor, &self.filter.window)); self.index = index.get(); // A moved window moved the servable edge `drift` was judged against. if polled.is_pending() && self.watch_time() { @@ -11554,7 +11639,7 @@ impl Cursor { self.expire_heads(&drift, waiter); continue; } - let Some((producer, found_index)) = ready!(polled)? else { + let Some(arrived) = ready!(polled)? else { // The feed ended, but a fill still owes a group. Its answer wakes us. if self.awaits_fill() { return Poll::Pending; @@ -11563,31 +11648,10 @@ impl Cursor { self.kept_out = None; return Poll::Ready(Ok(None)); }; - let consumer = producer.consume(); - - // The first group to arrive places a live join, which may land above it, - // and a later one may settle where a time end falls. - if !self.filter.window.is_settled() { - self.sync(); - self.admit(); - // The snapshot saw the pending window, which serves everything. - if !self.filter.window.is_pending() { - drift = ready!(self.poll_drift(&self.servable, waiter))?; - } - if consumer.start < self.floor() { - self.index = found_index + 1; - continue; - } - } - - // Pass a group beyond the cap or outside the ranges, holding nothing: a - // widening finds it in the cache again. Keep scanning so an in-range group - // that arrived behind it still flows. - if !self.admits(consumer.start) { - self.index = found_index + 1; - continue; + if self.owe_arrivals(arrived) { + drift = ready!(self.poll_drift(&self.servable, waiter))?; } - (consumer, Taken::Walk(found_index + 1)) + continue; } }; @@ -11610,6 +11674,89 @@ impl Cursor { } } + /// Write off the stale groups at the old end of what a newest-first read holds, owed, + /// filled, or a head, oldest first, until one is fresh: the drift budget gives up the oldest first, and an + /// arrival-order walk judged them before handing out anything newer. So what it gives up + /// is settled before the groups above go out, and a publisher resolving where delivery + /// starts from the lowest group still held finds a fresh one. Each group is judged once. + fn write_off_oldest(&mut self, order: Order, drift: &Drift, waiter: &kio::Waiter) -> Poll> { + if order == Order::Ascending { + return Poll::Ready(Ok(())); + } + loop { + // The lowest of what the arrivals, fills, and heads hold, as a pick ascending would + // take it. + let (owed, filled, head) = ( + self.first_owed(true), + self.next_filled(Order::Ascending), + self.next_head(Order::Ascending), + ); + let keys = [ + owed.as_ref().map(|group| (group.start, Taken::Owed)), + filled.as_ref().map(|group| (group.start, Taken::Filled)), + head.as_ref().map(|group| (group.start, Taken::Head)), + ]; + let lowest = keys + .into_iter() + .flatten() + .reduce(|first, next| if next.0 < first.0 { next } else { first }); + let (consumer, taken) = match lowest.map(|(_, taken)| taken) { + Some(Taken::Owed) => (owed.expect("picked").consume(), Taken::Owed), + Some(Taken::Filled) => (filled.expect("picked").consume(), Taken::Filled), + Some(Taken::Head) => (head.expect("picked"), Taken::Head), + None => break, + }; + if !ready!(self.poll_stale(&consumer, drift, waiter))? { + break; + } + self.advance_arrival(consumer.start, taken); + self.write_off_stale(consumer.start, consumer.content(), drift); + } + Poll::Ready(Ok(())) + } + + /// Owe the `arrived` groups this cursor reads, for [`Self::next_owed`] to pick from. A + /// group beyond the cap or outside the ranges is passed holding nothing: a widening finds + /// it in the cache again. The first group to arrive places a live join, which may land + /// above it, and a later one may settle where a time end falls. Returns whether that + /// moved a placed window, and with it the servable edge a drift was judged against. + fn owe_arrivals(&mut self, arrived: Vec) -> bool { + let moved = !self.filter.window.is_settled() && { + self.sync(); + self.admit(); + // The snapshot saw the pending window, which serves everything. + !self.filter.window.is_pending() + }; + let floor = self.floor(); + for key in arrived { + if key >= floor && self.admits(key) { + self.filter.owed.insert(key..=key); + } + } + self.prune_owed(); + moved + } + + /// Forget every owed run no cached group is left in once the runs outnumber the cache's + /// groups twice over. [`Self::first_owed`] drops such a run only on reaching it, which a + /// newest-first read holding an old group may never do, so this keeps a run per cached + /// group at O(1) per arrival amortized. + fn prune_owed(&mut self) { + let state = self.state.read(); + if self.filter.owed.len() <= state.lookup.len().saturating_mul(2) || !state.serves_bounded(&self.filter.window) + { + return; + } + let gone: Vec<_> = (self.filter.owed.iter()) + .filter(|run| !state.lookup.range((*run).clone()).any(|(_, slot)| slot.is_read())) + .cloned() + .collect(); + drop(state); + for run in gone { + self.filter.owed.remove(run); + } + } + /// Write off group `key`, which the drift budget gave up on, as dropped `Old`: /// skipped for a wider budget to offer again, unless the budget is at its bound. fn write_off_stale(&mut self, key: u64, content: stats::Content, drift: &Drift) { @@ -11635,11 +11782,10 @@ impl Cursor { } } - /// Move the arrival cursor past a group it read: from the walk, to `index`; from what - /// a widening owes, out of the owed spans. + /// Move the arrival read past a group it read: out of the owed spans, the fills + /// answered, or the heads asked. fn advance_arrival(&mut self, key: u64, taken: Taken) { match taken { - Taken::Walk(index) => self.index = index, Taken::Owed => self.filter.owed.remove(key..=key), Taken::Filled => { if let Some(misses) = &mut self.misses { @@ -11775,11 +11921,11 @@ impl Cursor { } } - /// The next head answered and not handed out yet, in the subscription's order. - fn next_head(&self) -> Option { + /// The next head answered and not handed out yet, in `order`. + fn next_head(&self, order: Order) -> Option { let heads = self.heads.as_ref()?; let mut filled = heads.filled.values(); - match self.subscription.read().order { + match order { Order::Ascending => filled.next(), Order::Descending => filled.next_back(), } @@ -12189,11 +12335,14 @@ impl Subscriber { } } - /// The next group in arrival order. + /// The next group to arrive, picking from those held unread in the subscription's + /// [`Order`]. /// - /// Returns each group it delivers exactly once, in the order it landed on the wire, - /// which may be out of key due to network reordering or loss. Use - /// [`Self::ordered`] if you only want groups whose key is higher than any + /// Returns each group it delivers exactly once. A reader that keeps up gets each group + /// as it lands, out of key under network reordering or loss. One holding several unread, + /// a backlog or a replayed cache, gets the newest first unless [`Order::Ascending`]: ask + /// ascending to read them oldest first. A lower group that lands late is still + /// delivered. Use [`Self::ordered`] if you only want groups whose key is higher than any /// previously returned. /// /// Once means once per key: a group the publisher aborts and re-creates, or that @@ -12209,8 +12358,8 @@ impl Subscriber { /// tolerates is skipped rather than handed over, so a single read walks off a whole /// backlog. The default [`Start::LATEST`] takes the live edge and writes the rest off; /// a history range (a time, position, or oldest start) reads every group it covers. [`Consumer::fetch_group`] is the way to ask for one old group outright. - /// Across same-instance route copies, the lowest next buffered group is delivered - /// first; a lower group that arrives later is still delivered in arrival order. + /// Across same-instance route copies, the first group any copy holds in that order is + /// delivered first. /// The budget remains attached to a returned group: if it stalls while newer data /// advances, its pending frame read ends with [`Error::Old`]. /// @@ -12252,7 +12401,7 @@ impl Subscriber { self.poll_group_in(false, admit, waiter) } - /// The next group in arrival order, or in key order for `ordered`, skipping any + /// The next group an arrival read picks, or in key order for `ordered`, skipping any /// already handed out. fn poll_group(&mut self, ordered: bool, waiter: &kio::Waiter) -> Poll>> { self.poll_group_in(ordered, (ops::Bound::Unbounded, ops::Bound::Unbounded), waiter) @@ -12541,11 +12690,21 @@ impl Subscriber { /// Forget the gaps in `delivered` below each group past `budget` now: one landing there /// would be written off. The budget is the reader's whose `delivered` this is, which a - /// front's copy, its ranges raised to a resume point, cannot judge by its own. - pub(super) fn forget_past_budget(&self, delivered: &mut Delivered, budget: Budget) { + /// front's copy, its ranges raised to a resume point, cannot judge by its own. No gap at or + /// above `keep` is forgotten. + pub(super) fn forget_past_budget(&self, delivered: &mut Delivered, budget: Budget, keep: Option) { + match &self.inner { + Inner::Plain(cursor) => cursor.forget_past_budget(delivered, budget, keep), + Inner::Resume(resume, _) => resume.forget_past(delivered, budget, keep), + } + } + + /// How many runs of groups this subscriber's arrival read owes. + #[cfg(test)] + pub(super) fn owed_runs(&self) -> usize { match &self.inner { - Inner::Plain(cursor) => cursor.forget_past_budget(delivered, budget), - Inner::Resume(resume, _) => resume.forget_past(delivered, budget), + Inner::Plain(cursor) => cursor.filter.owed.len(), + Inner::Resume(..) => 0, } } @@ -12772,6 +12931,17 @@ impl Subscriber { } } + /// The lowest group at or above `from` an arrival read holds unread, on any copy it reads: + /// a read handing out the newest first has yet to deliver it, so where its delivery starts + /// is no higher, unless it cannot serve that group. + #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] + pub(crate) fn lowest_unread(&self, from: u64) -> Option { + match &self.inner { + Inner::Plain(cursor) => cursor.lowest_unread(from), + Inner::Resume(resume, _) => resume.lowest_unread(from), + } + } + /// Poll for where the source's feed starts, raised to this cursor's floor, once /// resolved: the first group a publisher tells its peer it serves. A feed starting /// below the floor serves the floor's group too, and a fill this cursor waits on starts it @@ -14730,7 +14900,7 @@ mod test { assert!(lives[0].is_aborted(), "the live copy still arriving ends"); let mut sub = producer.subscribe(Subscription::default().with_ranges([Range::ALL])); assert!(sub.poll_drop(&kio::Waiter::noop()).is_pending()); - for key in 0..2 { + for key in [1, 0] { assert_eq!(sub.assert_group().start, key); } } @@ -15067,7 +15237,7 @@ mod test { } /// A reader that starts at the largest group while it is still empty is at the live edge: - /// it gets that group, which ends with nothing, then the next one. + /// it gets that group, which ends with nothing, and the next one. #[test] fn a_live_edge_reader_starts_on_an_empty_largest_group() { let producer = track_producer("test", None); @@ -15091,15 +15261,16 @@ mod test { next.write_frame(crate::Timestamp::unscaled(next.start), &b"b"[..]) .unwrap(); + // It holds both, so the newer goes first. + let mut group = reader.assert_group(); + assert_eq!(group.start, 2); + assert!(matches!(group.poll_read_frame(&noop), Poll::Ready(Ok(Some(_))))); let mut group = reader.assert_group(); assert_eq!(group.start, 1); assert!( matches!(group.poll_read_frame(&noop), Poll::Ready(Ok(None))), "it ends with nothing" ); - let mut group = reader.assert_group(); - assert_eq!(group.start, 2); - assert!(matches!(group.poll_read_frame(&noop), Poll::Ready(Ok(Some(_))))); } /// A finished track ends the stream while its producer is still held, once the last @@ -15293,7 +15464,8 @@ mod test { let want = vec![(4, (0..8).collect()), (5, (0..8).collect())]; let mut arrival = bounded(); - assert_eq!(read_groups(|waiter| arrival.poll_recv_group(waiter)), want); + let newest_first: Vec<_> = want.iter().rev().cloned().collect(); + assert_eq!(read_groups(|waiter| arrival.poll_recv_group(waiter)), newest_first); let mut ordered = bounded().ordered(); assert_eq!(read_groups(|waiter| ordered.poll_next_group(waiter)), want); } @@ -15888,7 +16060,7 @@ mod test { let mut reader = producer.subscribe(joining(Range::ALL, Duration::from_secs(2))); assert_eq!( ready_groups(&mut reader), - vec![3000, 3500, 4000, 4500, 5000], + vec![5000, 4500, 4000, 3500, 3000], "four groups back" ); assert_eq!(append_half_second(&mut producer), 5500); @@ -15901,7 +16073,7 @@ mod test { .write_frame(Timestamp::from_millis(5900).unwrap(), &b"x"[..]) .unwrap(); let mut reader = producer.subscribe(joining(Range::ALL, Duration::from_secs(2))); - assert_eq!(ready_groups(&mut reader), vec![3500, 4000, 4500, 5000, 5500]); + assert_eq!(ready_groups(&mut reader), vec![5500, 5000, 4500, 4000, 3500]); } /// A live join with no lag joins at the latest group, and a range with no start reaches as @@ -15909,7 +16081,7 @@ mod test { #[test] fn a_range_with_no_start_reaches_back_as_its_budget_keeps() { let producer = half_second_groups(); - let all: Vec = (0..=5000).step_by(500).collect(); + let all: Vec = (0..=10).rev().map(|half| half * 500).collect(); let mut live = producer.subscribe(joining(Range::ALL, Duration::ZERO)); assert_eq!(ready_groups(&mut live), vec![5000]); let mut oldest = producer.subscribe(joining(Range::ALL, None)); @@ -15927,7 +16099,7 @@ mod test { #[test] fn a_live_join_reaches_back_no_further_than_the_cache_or_the_budget() { let producer = half_second_groups(); - let all: Vec = (0..=5000).step_by(500).collect(); + let all: Vec = (0..=10).rev().map(|half| half * 500).collect(); let mut far = producer.subscribe(joining(Range::ALL, Duration::from_secs(60))); assert_eq!(ready_groups(&mut far), all); @@ -15938,7 +16110,7 @@ mod test { })]) .with_max(Duration::from_secs(1)); let mut budget = producer.subscribe(budget); - assert_eq!(ready_groups(&mut budget), vec![4000, 4500, 5000]); + assert_eq!(ready_groups(&mut budget), vec![5000, 4500, 4000]); } /// A join's end bounds it, beside ranges starting at a time. @@ -15952,21 +16124,21 @@ mod test { start: crate::track::Start::Time(1000), end: Some(2000), }, - vec![1000, 1500, 2000], + vec![2000, 1500, 1000], ), ( Range { start: crate::track::Start::Time(4500), end: None, }, - vec![4500, 5000], + vec![5000, 4500], ), ( Range { start: crate::track::Start::Oldest, end: Some(4000), }, - vec![3000, 3500, 4000], + vec![4000, 3500, 3000], ), ( Range { @@ -15993,9 +16165,9 @@ mod test { elapse(&producer, Duration::from_secs(1)); } let mut reader = producer.subscribe(joining(Range::ALL, Duration::from_millis(2500))); - assert_eq!(ready_groups(&mut reader), vec![2, 3, 4]); + assert_eq!(ready_groups(&mut reader), vec![4, 3, 2]); let mut far = producer.subscribe(joining(Range::ALL, Duration::from_secs(10))); - assert_eq!(ready_groups(&mut far), vec![0, 1, 2, 3, 4]); + assert_eq!(ready_groups(&mut far), vec![4, 3, 2, 1, 0]); framed(&producer, 5, 1).finish().unwrap(); assert_eq!(ready_groups(&mut reader), vec![5]); } @@ -16015,9 +16187,9 @@ mod test { group.finish().unwrap(); } let mut reader = producer.subscribe(joining(Range::ALL, Duration::from_secs(2))); - assert_eq!(ready_groups(&mut reader), vec![5, 6, 7, 8, 9]); + assert_eq!(ready_groups(&mut reader), vec![9, 8, 7, 6, 5]); let mut far = producer.subscribe(joining(Range::ALL, Duration::from_secs(60))); - assert_eq!(ready_groups(&mut far), (0..10).collect::>()); + assert_eq!(ready_groups(&mut far), (0..10).rev().collect::>()); } /// A live join reads none of the groups held until one measures the live edge: a copy @@ -16063,7 +16235,7 @@ mod test { append_half_second(&mut producer); } let mut reader = producer.subscribe(joining(Range::ALL, Duration::from_secs(2))); - assert_eq!(ready_groups(&mut reader)[0], 2500); + assert_eq!(ready_groups(&mut reader).last(), Some(&2500)); } /// A Min Age that is not a whole number of ticks rounds up, so the join never starts newer @@ -16079,7 +16251,7 @@ mod test { group.finish().unwrap(); } let mut reader = producer.subscribe(joining(Range::ALL, Duration::from_micros(1500))); - assert_eq!(ready_groups(&mut reader), vec![0, 1, 2]); + assert_eq!(ready_groups(&mut reader), vec![2, 1, 0]); } /// A newest group given up does not move the live edge: the join measures from the content @@ -16090,7 +16262,7 @@ mod test { let aborted = producer.create_group(group::Info { start: 10_000 }).unwrap(); aborted.abort(Error::Cancel).unwrap(); let mut reader = producer.subscribe(joining(Range::ALL, Duration::from_secs(2))); - assert_eq!(ready_groups(&mut reader)[0], 3000); + assert_eq!(ready_groups(&mut reader).last(), Some(&3000)); } /// A live join that has not started yet reaches back by the lag an update replaced it @@ -16104,7 +16276,7 @@ mod test { for _ in (0..=5000).step_by(500) { append_half_second(&mut producer); } - assert_eq!(ready_groups(&mut reader), vec![3000, 3500, 4000, 4500, 5000]); + assert_eq!(ready_groups(&mut reader), vec![5000, 4500, 4000, 3500, 3000]); } /// A live join taken while the copy is idle starts at the live feed's latest group once @@ -16316,7 +16488,7 @@ mod test { let mut producer = idle_copy(); let mut reader = producer.subscribe(replay()); producer.set_live_from(Position::group(0), None); - assert_eq!(ready_groups(&mut reader), vec![0, 1, 2, 3]); + assert_eq!(ready_groups(&mut reader), vec![3, 2, 1, 0]); } /// An end the idle copy has not reached does not make its cache the whole track: until @@ -16334,7 +16506,7 @@ mod test { producer.set_live(Some(Position::group(4)), Some(false), None).unwrap(); framed(&producer, 4, 1).finish().unwrap(); assert_eq!(ready_groups(&mut live), vec![4]); - assert_eq!(ready_groups(&mut oldest), vec![0, 1, 2, 3, 4]); + assert_eq!(ready_groups(&mut oldest), vec![4, 3, 2, 1, 0]); } /// An idle copy that ends without going live makes its cache the whole track, so a live @@ -16587,7 +16759,7 @@ mod test { #[cfg(feature = "async")] async fn delivery_restarts_the_expiry_clock() { let producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(replay()); + let mut subscriber = producer.subscribe(replay().with_order(Order::Ascending)); let mut group = producer.create_group(0u64.into()).unwrap(); group.write_frame(group.key_time(), b"x".as_slice()).unwrap(); @@ -16965,8 +17137,8 @@ mod test { producer.append_next().unwrap().finish().unwrap(); let mut live = producer.append_next().unwrap(); let mut consumer = producer.subscribe(replay()); - assert_eq!(consumer.assert_group().start, 0); assert_eq!(consumer.assert_group().start, 1); + assert_eq!(consumer.assert_group().start, 0); let woken = Arc::new(AtomicBool::new(false)); let waiter = kio::Waiter::new(futures::task::waker(Arc::new(FlagWake(woken.clone())))); @@ -17019,7 +17191,7 @@ mod test { for millis in [0, 10, 20] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut producer.subscribe(replay())), vec![0, 1, 2]); + assert_eq!(drain(&mut producer.subscribe(replay())), vec![2, 1, 0]); // Nothing is written again: media time stands still. elapse(&producer, Duration::from_secs(2)); @@ -17049,9 +17221,9 @@ mod test { append_frozen(&mut producer); // Group 0's successor arrived 800ms ago, group 1's just now. - assert_eq!(drain(&mut producer.subscribe(budget.clone())), vec![0, 1, 2]); + assert_eq!(drain(&mut producer.subscribe(budget.clone())), vec![2, 1, 0]); elapse(&producer, Duration::from_millis(200)); - assert_eq!(drain(&mut producer.subscribe(budget.clone())), vec![1, 2]); + assert_eq!(drain(&mut producer.subscribe(budget.clone())), vec![2, 1]); elapse(&producer, Duration::from_secs(1)); assert_eq!(drain(&mut producer.subscribe(budget)), vec![2]); } @@ -17069,7 +17241,7 @@ mod test { // Group N reaches N + 1 seconds against the 4s edge: groups 0 and 1 are 3s and 2s // behind, past 1.5s. Their successors arrived just now. let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_millis(1500))); - assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3, 2]); } /// A read parked on a superseded group is released by the wall clock alone: nothing is @@ -17928,10 +18100,12 @@ mod test { producer.start_at(3).unwrap(); producer.set_live(Some(Position::group(3)), Some(false), None).unwrap(); framed(&producer, 3, 1).finish().unwrap(); - assert_eq!(read_now(&mut reader, ordered), Some(Some(0)), "cached history"); - // An arrival-order reader may take the live group before its history. - if !bounded && !ordered { - assert_eq!(read_now(&mut reader, ordered), Some(Some(3))); + // An arrival read holding the live group too takes it before the history. + let newest_first = !bounded && !ordered; + let first = if newest_first { 3 } else { 0 }; + assert_eq!(read_now(&mut reader, ordered), Some(Some(first)), "cached history"); + if newest_first { + assert_eq!(read_now(&mut reader, ordered), Some(Some(0))); } assert_eq!(read_now(&mut reader, ordered), None, "the missing run is owed"); let Poll::Ready(Ok(fill)) = requests.poll_requested_fill(&waiter) else { @@ -17985,7 +18159,7 @@ mod test { again .write_frame(Timestamp::from_millis(1000).unwrap(), bytes::Bytes::from_static(b"x")) .unwrap(); - assert_eq!(drain(&mut subscriber), vec![0, 1]); + assert_eq!(drain(&mut subscriber), vec![1, 0]); assert!(subscriber.poll_drop(&waiter).is_pending(), "nothing was given up"); } @@ -18031,7 +18205,12 @@ mod test { for second in 0..5 { append_at(&mut producer, second * 1000); } - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(1))); + // Oldest first, so the catch-up starts behind the edge. + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_secs(1)) + .with_order(Order::Ascending), + ); assert_eq!( subscriber.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 3 @@ -18054,7 +18233,12 @@ mod test { edge.write_frame(Timestamp::from_millis(2000).unwrap(), bytes::Bytes::from_static(b"a")) .unwrap(); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(2))); + // Oldest first, so the catch-up starts behind the edge. + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_secs(2)) + .with_order(Order::Ascending), + ); assert_eq!( subscriber.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 0 @@ -18080,7 +18264,7 @@ mod test { // the edge, and the reach bound is exclusive, so every frame it could hold is // already past the budget. let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(2))); - assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3, 2]); } /// A fetch under the publisher's max age parks on its deadlines even when it returns a @@ -18125,7 +18309,7 @@ mod test { // history it would discard on arrival. let budget = Subscription::default().with_max(Duration::from_secs(2)); let mut subscriber = producer.subscribe(budget); - assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3, 2]); } #[test] @@ -18139,13 +18323,13 @@ mod test { // A named start is a floor for history: every group from it, however far behind the // live edge. let mut subscriber = producer.subscribe(Subscription::default().with_start(1)); - assert_eq!(drain(&mut subscriber), vec![1, 2, 3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3, 2, 1]); let mut subscriber = producer.subscribe(Subscription::default().with_start(3)); - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); // Only a live join's budget decides how far back it reaches. let mut subscriber = producer.subscribe(within(Duration::from_secs(2), None)); - assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3, 2]); } /// A start past the live edge is a time, which the newest group contains until a later @@ -18166,7 +18350,7 @@ mod test { for key in [3000, 4000] { write_group(&producer, key); } - assert_eq!(drain(&mut subscriber), vec![3000, 4000]); + assert_eq!(drain(&mut subscriber), vec![4000, 3000]); } /// A lite-07 copy holds only part of the track, so it places a time start only once it @@ -18481,14 +18665,14 @@ mod test { assert_eq!(start(&mut paused), Some(1400)); write_group(&producer, 2000); assert_eq!(drain(&mut paused), vec![2000]); - assert_eq!(drain(&mut inside), vec![1000, 2000]); + assert_eq!(drain(&mut inside), vec![2000, 1000]); // Expiry forgets the skips while the group stays held: its End alone still proves a time // inside the span, with nothing to ask upstream. producer.forget_drops(1001..2000); let mut later = producer.subscribe(from(1300)); assert_eq!(start(&mut later), Some(1000), "the End proves it"); - assert_eq!(drain(&mut later), vec![1000, 2000]); + assert_eq!(drain(&mut later), vec![2000, 1000]); assert_eq!( start(&mut producer.subscribe(from(1700))), None, @@ -19615,7 +19799,7 @@ mod test { write_group(&producer, 6000); let start = reader.resolved_range(0).map(|resolved| resolved.start); assert_eq!(start, Some(4000), "{min:?}"); - assert_eq!(drain_groups(&mut reader), [4000, 6000], "{min:?}"); + assert_eq!(drain_groups(&mut reader), [6000, 4000], "{min:?}"); let mut later = producer.subscribe(join); let start = later.resolved_range(0).map(|resolved| resolved.start); assert_ne!(start, Some(4000), "{min:?}"); @@ -19711,7 +19895,7 @@ mod test { } let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(5))); - assert_eq!(drain(&mut subscriber), vec![5, 6, 7]); + assert_eq!(drain(&mut subscriber), vec![7, 6, 5]); // Arriving below everything already delivered is not what makes content stale: // the budget is the only gate, and this straggler's timestamp is within it. A @@ -19735,7 +19919,7 @@ mod test { } let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_millis(1500))); - assert_eq!(drain(&mut subscriber), vec![1, 2, 3]); + assert_eq!(drain(&mut subscriber), vec![3, 2, 1]); } #[test] @@ -19783,7 +19967,11 @@ mod test { #[cfg(feature = "async")] async fn a_handed_out_group_wakes_when_a_newer_group_gets_its_first_timestamp() { let mut producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_millis(500))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_millis(500)) + .with_order(Order::Ascending), + ); let mut old = producer.append_next().unwrap(); old.write_frame(old.key_time(), bytes::Bytes::from_static(b"old")) .unwrap(); @@ -19831,7 +20019,11 @@ mod test { const FRAME: u64 = 2500; // micros, one Opus frame per group const PARKED: u64 = 64; let producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_millis(200))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_millis(200)) + .with_order(Order::Ascending), + ); // Left open, so every read parks instead of ending. let _open: Vec<_> = (0..PARKED) .map(|i| { @@ -19908,7 +20100,11 @@ mod test { #[cfg(feature = "async")] fn a_parked_read_wakes_only_once_the_edge_reaches_its_deadline() { let mut producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(10))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_secs(10)) + .with_order(Order::Ascending), + ); let mut head = producer.append_next().unwrap(); head.write_frame(head.key_time(), bytes::Bytes::from_static(b"head")) .unwrap(); @@ -19965,7 +20161,11 @@ mod 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(Duration::from_secs(10))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_secs(10)) + .with_order(Order::Ascending), + ); let mut head = producer.append_next().unwrap(); head.write_frame(Timestamp::from_millis(0).unwrap(), bytes::Bytes::new()) .unwrap(); @@ -20204,7 +20404,11 @@ mod 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(Duration::from_secs(10))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_secs(10)) + .with_order(Order::Ascending), + ); let mut old = producer.append_next().unwrap(); old.write_frame(Timestamp::from_millis(0).unwrap(), bytes::Bytes::new()) .unwrap(); @@ -20245,7 +20449,11 @@ mod test { #[cfg(feature = "async")] fn a_parked_read_watches_its_edge_abort() { let mut producer = track_producer("test", crate::track::Info::timed()); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(5))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_secs(5)) + .with_order(Order::Ascending), + ); let mut head = producer.append_next().unwrap(); head.write_frame(head.key_time(), bytes::Bytes::from_static(b"head")) .unwrap(); @@ -20295,7 +20503,11 @@ mod test { #[cfg(feature = "async")] fn a_parked_read_watches_the_replacement_for_an_aborted_successor() { let mut producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_millis(500))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_millis(500)) + .with_order(Order::Ascending), + ); let mut head = producer.append_next().unwrap(); head.write_frame(head.key_time(), bytes::Bytes::from_static(b"head")) .unwrap(); @@ -20350,7 +20562,11 @@ mod test { #[cfg(feature = "async")] fn a_parked_read_watches_its_overtaken_edge_abort() { let mut producer = track_producer("test", crate::track::Info::timed()); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(5))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_secs(5)) + .with_order(Order::Ascending), + ); let mut head = producer.append_next().unwrap(); head.write_frame(head.key_time(), bytes::Bytes::from_static(b"head")) .unwrap(); @@ -20398,7 +20614,11 @@ mod test { #[cfg(feature = "async")] fn revealing_a_presented_group_wakes_a_read_it_expires() { let mut producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_millis(500))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_millis(500)) + .with_order(Order::Ascending), + ); let mut head = producer.append_next().unwrap(); head.write_frame(head.key_time(), bytes::Bytes::from_static(b"head")) .unwrap(); @@ -20451,7 +20671,7 @@ mod test { .collect(); let mut first = subscriber.assert_group(); let mut second = subscriber.assert_group(); - assert_eq!((first.start, second.start), (0, 1)); + assert_eq!((first.start, second.start), (1, 0)); assert!(subscriber.recv_group().now_or_never().unwrap().unwrap().is_none()); let waiter = kio::Waiter::noop(); @@ -20610,7 +20830,11 @@ mod test { 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(Duration::from_millis(80))); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_max(Duration::from_millis(80)) + .with_order(Order::Ascending), + ); for ms in [0, 100] { let mut group = producer.append_next().unwrap(); group @@ -20785,7 +21009,7 @@ mod test { // Group 0 reaches 1s, a full second behind the 2s edge, so the clamped 500ms // budget drops it. An unclamped ten seconds would have kept it. let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(10))); - assert_eq!(drain(&mut subscriber), vec![1, 2]); + assert_eq!(drain(&mut subscriber), vec![2, 1]); } /// An authored track's default zero max age serves only the live edge: a superseded group is @@ -20825,8 +21049,8 @@ mod test { append_at(&mut explicit, millis); append_at(&mut unlimited, millis); } - assert_eq!(drain(&mut explicit.subscribe(history())), vec![1, 2]); - assert_eq!(drain(&mut unlimited.subscribe(history())), vec![0, 1, 2]); + assert_eq!(drain(&mut explicit.subscribe(history())), vec![2, 1]); + assert_eq!(drain(&mut unlimited.subscribe(history())), vec![2, 1, 0]); } /// A group's age is where its content *ends*, not where it began. A long group whose @@ -20848,7 +21072,7 @@ mod test { // A budget far shorter than the group's own span still keeps it. let mut sub = producer.subscribe(Subscription::default().with_max(Duration::from_millis(500))); - assert_eq!(drain(&mut sub), vec![0, 1]); + assert_eq!(drain(&mut sub), vec![1, 0]); } /// The same group, once its tail has fallen behind, is stale like any other. @@ -20873,7 +21097,7 @@ mod test { append_at(&mut producer, 4000); let mut sub = producer.subscribe(Subscription::default().with_max(Duration::from_millis(500))); - assert_eq!(drain(&mut sub), vec![1, 2]); + assert_eq!(drain(&mut sub), vec![2, 1]); } /// A frameless successor is not content, so the next started group bounds the group @@ -20892,7 +21116,7 @@ mod test { append_at(&mut producer, 11_000); // seq 3 // Groups 0 and 1 both reach at most group 2's start, a second behind the edge: stale. - assert_eq!(drain(&mut subscriber), vec![2, 3]); + assert_eq!(drain(&mut subscriber), vec![3, 2]); } fn untimed_producer() -> Producer { @@ -20947,12 +21171,12 @@ mod test { // Four seconds after group 4 arrived, groups 0 to 2 were superseded 4, 3, and 2 // seconds ago: past a 1.5s budget. Group 3 was superseded 1s ago. let mut patient = producer.subscribe(Subscription::default().with_max(Duration::from_millis(1500))); - assert_eq!(drain(&mut patient), vec![3, 4]); + assert_eq!(drain(&mut patient), vec![4, 3]); // No budget takes the newest group alone, which is never stale. let mut live = producer.subscribe(None); assert_eq!(drain(&mut live), vec![4]); let mut replaying = producer.subscribe(replay()); - assert_eq!(drain(&mut replaying), vec![0, 1, 2, 3, 4]); + assert_eq!(drain(&mut replaying), vec![4, 3, 2, 1, 0]); append_untimed(&mut producer); assert_eq!(drain(&mut live), vec![5], "every later group is delivered"); @@ -20969,7 +21193,7 @@ mod test { } let mut subscriber = producer.subscribe(Subscription::default().with_start(2)); - assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3, 2]); let mut live = producer.subscribe(Subscription::default()); assert_eq!(drain(&mut live), vec![4]); } @@ -21282,7 +21506,7 @@ mod test { .finish() .unwrap(); } - assert_eq!(drain(&mut subscriber), vec![0, 1]); + assert_eq!(drain(&mut subscriber), vec![1, 0]); let fill = |key: u64| { let pending = consumer.fetch_group(key, None); @@ -21405,7 +21629,7 @@ mod test { next.finish().unwrap(); let mut subscriber = producer.subscribe(replay()); - assert_eq!(drain(&mut subscriber), vec![0, 1]); + assert_eq!(drain(&mut subscriber), vec![1, 0]); } #[test] @@ -21426,7 +21650,7 @@ mod test { // A budget that covers it delivers the range, and nothing above it. let mut subscriber = producer.subscribe(within(Duration::from_secs(30), 1)); - assert_eq!(drain(&mut subscriber), vec![0, 1]); + assert_eq!(drain(&mut subscriber), vec![1, 0]); } /// Drift is measured only against groups the ranges cover: a group in the gap between @@ -21505,38 +21729,43 @@ mod test { } /// A history read whose ranges passed over a group outside every range offers it once a - /// range covers it again, as any lowered start does. + /// range covers it again, as any lowered start does. What it holds unread goes in the + /// subscription's order: the buffered groups first read, and the two a widening owes. #[kio::test] #[cfg(feature = "async")] async fn a_widened_history_read_offers_a_group_it_passed_over() { - let producer = track_producer("test", Info::timed()); - let _everything = producer.subscribe(Subscription::default().with_ranges([Range::ALL])); - let mut sub = producer.subscribe(Subscription::default().with_ranges([Range::groups(1..3)])); - for key in 0..5 { - let mut group = producer.create_group(group::Info { start: key }).unwrap(); - group - .write_frame(Timestamp::from_millis(key).unwrap(), bytes::Bytes::from_static(b"x")) - .unwrap(); - group.finish().unwrap(); - } - let mut read = Vec::new(); - let oldest = Range { - start: Start::Oldest, - end: Some(4), - }; - for (range, count) in [(None, 2), (Some(Range::groups(3..4)), 1), (Some(oldest), 2)] { - if let Some(range) = range { - sub.update(Subscription::default().with_ranges([range])).unwrap(); + for (order, want) in [ + (Order::Descending, [2, 1, 3, 4, 0]), + (Order::Ascending, [1, 2, 3, 0, 4]), + ] { + let producer = track_producer("test", Info::timed()); + let _everything = producer.subscribe(Subscription::default().with_ranges([Range::ALL])); + let subscription = |range| Subscription::default().with_ranges([range]).with_order(order); + let mut sub = producer.subscribe(subscription(Range::groups(1..3))); + for key in 0..5 { + let mut group = producer.create_group(group::Info { start: key }).unwrap(); + group + .write_frame(Timestamp::from_millis(key).unwrap(), bytes::Bytes::from_static(b"x")) + .unwrap(); + group.finish().unwrap(); } - for _ in 0..count { - read.push(sub.recv_group().await.unwrap().expect("a group").start); + let mut read = Vec::new(); + let oldest = Range { + start: Start::Oldest, + end: Some(4), + }; + for (range, count) in [(None, 2), (Some(Range::groups(3..4)), 1), (Some(oldest), 2)] { + if let Some(range) = range { + sub.update(subscription(range)).unwrap(); + } + for _ in 0..count { + read.push(sub.recv_group().await.unwrap().expect("a group").start); + } + // Each window ends once read. + assert!(sub.recv_group().await.unwrap().is_none(), "{order:?}: {read:?}"); } - // Each window ends once read. - assert!(sub.recv_group().await.unwrap().is_none(), "{read:?}"); + assert_eq!(read, want, "{order:?}"); } - // The widening owes both; which goes first is the Group Order, not what this pins. - read[3..].sort_unstable(); - assert_eq!(read, [1, 2, 3, 0, 4]); } /// A drift snapshot taken while the window waits on its first group is taken again once @@ -22413,15 +22642,16 @@ mod test { write_group(&producer, key); } let _producer = producer.finish().unwrap(); - for key in 0..3 { + // The arrival read holds them all, so it takes them newest first. + for (key, newest_first) in [(0, 2), (1, 1), (2, 0)] { let Poll::Ready(Ok(Some(Item::Group(group)))) = ordered.poll_next_item(&kio::Waiter::noop()) else { panic!("group {key}, given_up={given_up}") }; assert_eq!(group.start, key); let Poll::Ready(Ok(Some(group))) = arrival.poll_recv_group(&kio::Waiter::noop()) else { - panic!("arrival group {key}, given_up={given_up}") + panic!("arrival group {newest_first}, given_up={given_up}") }; - assert_eq!(group.start, key); + assert_eq!(group.start, newest_first); } // The group given up is reported, then the read ends. if given_up { @@ -22706,8 +22936,8 @@ mod test { let mut arrival = producer.subscribe(replay().with_range(0..)); let mut ordered = producer.subscribe(replay().with_range(0..)).ordered(); - for key in 0..2 { - assert_eq!(arrival.assert_group().start, key); + for (newest_first, key) in [(1, 0), (0, 1)] { + assert_eq!(arrival.assert_group().start, newest_first); assert_eq!(ordered.next_group().await.unwrap().unwrap().start, key); } assert!(matches!(arrival.recv_group().await, Err(Error::App(7)))); @@ -22728,8 +22958,8 @@ mod test { // Unlike an abort, the history stays: a later reader and a fetch still get it. producer.clone().abort(Error::Timeout).unwrap(); let mut late = producer.subscribe(replay().with_range(0..)); - assert_eq!(late.assert_group().start, 0); assert_eq!(late.assert_group().start, 1); + assert_eq!(late.assert_group().start, 0); assert!(matches!(late.recv_group().await, Err(Error::App(7)))); producer.consume().fetch_group(1, None).await.unwrap(); } @@ -22805,7 +23035,7 @@ mod test { .unwrap(); ended.finish_at(30).unwrap(); - let mut reader = producer.subscribe(replay().with_range(0..)); + let mut reader = producer.subscribe(replay().with_range(0..).with_order(Order::Ascending)); let mut first = reader.assert_group(); assert_eq!(first.read_frame().await.unwrap().unwrap().payload, &b"a"[..]); assert_eq!(first.read_frame().await.unwrap().unwrap().payload, &b"b"[..]); @@ -23304,7 +23534,7 @@ mod test { #[cfg(feature = "async")] fn abort_before_the_end_settles_wins() { let mut producer = track_producer("test", Info::timed()); - let mut consumer = producer.subscribe(replay()); + let mut consumer = producer.subscribe(replay().with_order(Order::Ascending)); let head = producer.create_group(group::Info { start: 0 }).unwrap(); head.finish().unwrap(); @@ -23480,8 +23710,8 @@ mod test { let _open = producer.create_group(group::Info { start: 2 }).unwrap(); producer.abort(Error::Timeout).unwrap(); - assert_eq!(arrival.assert_group().start, 0); assert_eq!(arrival.assert_group().start, 1); + assert_eq!(arrival.assert_group().start, 0); let res = arrival.recv_group().now_or_never().expect("should not block"); assert!(matches!(res, Err(Error::Timeout)), "expected the abort"); @@ -23594,8 +23824,8 @@ mod test { group.finish().unwrap(); } producer.finish_at(Position::group(2)).unwrap(); - assert_eq!(consumer.assert_group().start, 0); assert_eq!(consumer.assert_group().start, 1); + assert_eq!(consumer.assert_group().start, 0); producer.abort(Error::Timeout).unwrap(); let res = consumer.recv_group().now_or_never().expect("should not block"); @@ -24376,7 +24606,7 @@ mod test { put(&producer, 0, None); put(&producer, 3, None); put(&producer, 4, None); - assert_eq!(drain(&mut subscriber), [0, 3, 4]); + assert_eq!(drain(&mut subscriber), [4, 3, 0]); elapse(&producer, budget); put(&producer, 5, None); assert_eq!(drain(&mut subscriber), [5]); @@ -25058,7 +25288,7 @@ mod test { let producer = track_producer("test", Info::timed()); let mut consumer = producer.subscribe(replay()).ordered(); - // Seq 3 arrives first, then seq 5. Both should be returned in arrival order. + // Seq 3 arrives first, then seq 5. Both should be returned in key order. producer .create_group(group::Info { start: 3 }) .unwrap() @@ -25120,7 +25350,8 @@ mod test { assert_eq!(cursor.min_key, 0); assert_eq!(cursor.end_key, None); assert_eq!(cursor.index, 0); - assert_eq!(peek(&mut subscriber, false), Poll::Ready(Some(u64::MAX - 2))); + // Both still held, the newer first. + assert_eq!(peek(&mut subscriber, false), Poll::Ready(Some(u64::MAX - 1))); } #[test] @@ -25179,7 +25410,7 @@ mod test { fn taking_a_peeked_group_does_not_substitute_after_eviction() { for ordered in [false, true] { let producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(replay()); + let mut subscriber = producer.subscribe(replay().with_order(Order::Ascending)); for key in [1, 3] { producer .create_group(group::Info { start: key }) @@ -25254,37 +25485,34 @@ mod test { } } + /// The ordered cursor reads in key order and the arrival cursor in the subscription's + /// Group Order, each from what it holds, whichever group arrived first. #[test] #[cfg(feature = "async")] fn ordered_and_arrival_cursors_are_independent() { - let producer = track_producer("test", Info::timed()); - let mut ordered = producer.subscribe(replay()).ordered(); - let mut arrival = producer.subscribe(replay()); - - // Out-of-order arrivals: seq 5 first, then seq 3. - producer - .create_group(group::Info { start: 5 }) - .unwrap() - .finish() - .unwrap(); - producer - .create_group(group::Info { start: 3 }) - .unwrap() - .finish() - .unwrap(); - - // The ordered handle returns the smallest key first, regardless of - // arrival order. - let group = ordered - .next_group() - .now_or_never() - .expect("should not block") - .expect("would have errored") - .expect("track should not be closed"); - assert_eq!(group.start, 3); + for (order, first) in [(Order::Descending, 5), (Order::Ascending, 3)] { + for arrivals in [[5, 3], [3, 5]] { + let producer = track_producer("test", Info::timed()); + let mut ordered = producer.subscribe(replay().with_order(order)).ordered(); + let mut arrival = producer.subscribe(replay().with_order(order)); + for key in arrivals { + producer + .create_group(group::Info { start: key }) + .unwrap() + .finish() + .unwrap(); + } - // The plain handle walks arrivals, so it still starts at seq 5. - assert_eq!(arrival.assert_group().start, 5); + let group = ordered + .next_group() + .now_or_never() + .expect("should not block") + .expect("would have errored") + .expect("track should not be closed"); + assert_eq!(group.start, 3, "{order:?} {arrivals:?}"); + assert_eq!(arrival.assert_group().start, first, "{order:?} {arrivals:?}"); + } + } } #[test] @@ -25456,8 +25684,8 @@ mod test { } consumer.set_range(..2); - assert_eq!(consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 0); assert_eq!(consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 1); + assert_eq!(consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 0); assert!(consumer.recv_group().now_or_never().is_none(), "capped at 2"); consumer.set_range(..); @@ -25500,8 +25728,8 @@ mod test { .finish() .unwrap(); - assert_eq!(consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 0); assert_eq!(consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 1); + assert_eq!(consumer.recv_group().now_or_never().unwrap().unwrap().unwrap().start, 0); assert!(consumer.recv_group().now_or_never().is_none(), "capped at 2"); consumer.set_range(..3); @@ -25660,7 +25888,7 @@ mod test { assert_eq!( everything.recv_group().now_or_never().unwrap().unwrap().unwrap().start, - 0 + 2 ); assert!( empty.recv_group().now_or_never().is_none(), @@ -26812,6 +27040,7 @@ mod test { let mut sub = producer.subscribe(replay().with_range(0..2)); let group = sub.recv_group().now_or_never().unwrap().unwrap().unwrap(); assert_eq!(group.start, 1); + assert!(sub.recv_group().now_or_never().is_none(), "group 0 waits on its head"); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!(request.key(), 0); @@ -28820,8 +29049,8 @@ mod test { assert!(consumer.peek_group(1).is_some(), "refreshed backfill survives"); } - /// A publisher re-creating an aborted key is delivered exactly once, at - /// its actual arrival position: the historical arrival entry is dead. + /// A publisher re-creating an aborted key is delivered exactly once: the historical + /// arrival entry is dead. #[test] fn recreated_key_delivered_once() { let (producer, _pool) = pooled_producer(1 << 40); @@ -28833,13 +29062,9 @@ mod test { producer.create_group(1u64.into()).unwrap().finish().unwrap(); let mut subscriber = producer.subscribe(replay()); - assert_eq!(subscriber.assert_group().start, 0); assert_eq!(subscriber.assert_group().start, 2); - assert_eq!( - subscriber.assert_group().start, - 1, - "replacement arrives at its own position" - ); + assert_eq!(subscriber.assert_group().start, 1, "the replacement, once"); + assert_eq!(subscriber.assert_group().start, 0); subscriber.assert_no_group(); } @@ -28931,17 +29156,16 @@ mod test { // The backfill serves by key, but never in arrival order. assert!(consumer.peek_group(1).is_some()); - let mut walked = Vec::new(); let index = Cell::new(0); let window = { let state = producer.state.read(); Window::new(&replay().ranges, None, &*state) }; - while let Poll::Ready(Ok(Some((group, next)))) = producer.state.read().poll_recv_group(&index, 0, &window) { - walked.push(group.start); - index.set(next + 1); - } - assert_eq!(walked, [0, 2]); + let walked = producer.state.read().poll_arrivals(&index, 0, &window); + assert!( + matches!(walked, Poll::Ready(Ok(Some(ref keys))) if keys == &[0, 2]), + "{walked:?}" + ); // A reader takes it as the fill answer for the group the feed gave up, as it would // have asked a fill for it, and the stale arrival entry adds nothing. let mut subscriber = producer.subscribe(replay()); @@ -29916,7 +30140,7 @@ mod test { while let Poll::Ready(Ok(Some(group))) = subscriber.poll_recv_group(&waiter) { read.push(group.start); } - assert_eq!(read, [2, 3]); + assert_eq!(read, [3, 2]); let Poll::Ready(Ok(fill)) = dynamic.poll_requested_fill(&waiter) else { panic!("below the start is a miss"); }; @@ -29960,7 +30184,7 @@ mod test { write(&producer, 2); write(&producer, 3); let waiter = kio::Waiter::noop(); - assert_eq!(drain_groups(&mut subscriber), [2, 3]); + assert_eq!(drain_groups(&mut subscriber), [3, 2]); assert!( dynamic.poll_requested_fill(&waiter).is_pending(), "below the start is no miss" @@ -29986,7 +30210,7 @@ mod test { write_group(&producer, 2); write_group(&producer, 3); let waiter = kio::Waiter::noop(); - assert_eq!(drain_groups(&mut reader), [2, 3]); + assert_eq!(drain_groups(&mut reader), [3, 2]); assert!( drained_drops(&mut reader).is_empty(), "nothing below the start is given up unasked" @@ -30010,7 +30234,7 @@ mod test { write_group(&producer, 2); write_group(&producer, 3); let waiter = kio::Waiter::noop(); - assert_eq!(drain_groups(&mut reader), [2, 3]); + assert_eq!(drain_groups(&mut reader), [3, 2]); assert!( dynamic.poll_requested_fill(&waiter).is_pending(), "below a declared start is no miss" @@ -31315,7 +31539,7 @@ mod test { fn a_group_evicted_before_its_reader_took_it_is_refilled() { let producer = track_producer("test", Info::timed()); let dynamic = producer.requests(); - let mut subscriber = producer.subscribe(replay()); + let mut subscriber = producer.subscribe(replay().with_order(Order::Ascending)); for key in 0..3 { write_group(&producer, key); } @@ -31339,6 +31563,138 @@ mod test { assert!(drained_drops(&mut subscriber).is_empty(), "nothing was given up"); } + /// A filled group evicted before its reader took it is passed over when finding the lowest + /// it holds unread, as a lite publisher's start does, so the filled group above it counts. + #[test] + #[cfg(feature = "async")] + fn the_lowest_unread_group_passes_over_an_evicted_fill() { + let producer = track_producer("test", Info::timed()); + let dynamic = producer.requests(); + let mut subscriber = producer.subscribe(replay()); + for key in 0..4 { + write_group(&producer, key); + } + evict(&producer, 1); + evict(&producer, 2); + let waiter = kio::Waiter::noop(); + let next = |subscriber: &mut Subscriber| match subscriber.poll_recv_group(&waiter) { + Poll::Ready(Ok(Some(group))) => group.start, + _ => panic!("a group is cached"), + }; + assert_eq!(next(&mut subscriber), 3); + let Poll::Ready(Ok(fill)) = dynamic.poll_requested_fill(&waiter) else { + panic!("groups 1 and 2 are misses"); + }; + assert_eq!((fill.start().group, fill.end()), (1, 3)); + write_filled(fill.accept(1, None), 1); + write_filled(fill.accept(2, None), 2); + drop(fill); + write_group(&producer, 4); + // Newest first, this read takes in the fill's answers and leaves them unread. + assert_eq!(next(&mut subscriber), 4); + assert_eq!(subscriber.lowest_unread(1).map(|group| group.start), Some(1)); + evict(&producer, 1); + assert_eq!(subscriber.lowest_unread(1).map(|group| group.start), Some(2)); + } + + /// Newest first, a stale group a fill answered is written off with the stale owed ones + /// below the first fresh group, so the lowest group held unread, where a lite publisher + /// starts, is one the read still hands out. A widened budget owes it again with the rest. + #[test] + #[cfg(feature = "async")] + fn a_stale_filled_group_is_written_off_before_the_newest_goes_out() { + let budget = Duration::from_millis(100); + let producer = track_producer("test", None); + let dynamic = producer.requests(); + let mut subscriber = producer.subscribe(Subscription::default().with_max(budget)); + let write = |key: u64| { + let mut group = producer.create_group(group::Info { start: key }).unwrap(); + group.write_frame(Timestamp::unscaled(key), &b"x"[..]).unwrap(); + group.finish().unwrap(); + }; + for key in 0..4 { + write(key); + } + evict(&producer, 1); + let waiter = kio::Waiter::noop(); + let next = |subscriber: &mut Subscriber| match subscriber.poll_recv_group(&waiter) { + Poll::Ready(Ok(Some(group))) => group.start, + _ => panic!("a group is cached"), + }; + assert_eq!(next(&mut subscriber), 3); + let Poll::Ready(Ok(fill)) = dynamic.poll_requested_fill(&waiter) else { + panic!("group 1 is a miss"); + }; + // Answered once its successor 2 arrived a full budget ago, so it lands stale. + producer.broadcast.pool.step(budget); + let mut filled = fill.accept(1, None).unwrap().expect("a fresh group"); + filled.write_frame(Timestamp::unscaled(1), &b"x"[..]).unwrap(); + filled.finish().unwrap(); + drop(fill); + write(4); + write(5); + assert_eq!(next(&mut subscriber), 5); + assert_eq!(subscriber.lowest_unread(0).map(|group| group.start), Some(4)); + assert_eq!(next(&mut subscriber), 4); + // A widened budget owes the stale groups again, the filled one included. + subscriber.update(subscriber.subscription().with_max(None)).unwrap(); + let mut widened = Vec::new(); + while let Poll::Ready(Ok(Some(group))) = subscriber.poll_recv_group(&waiter) { + widened.push(group.start); + } + assert_eq!(widened, [2, 1, 0]); + } + + /// A skipped run whose only cached group is a fill's answer is still held for a widening + /// to re-offer, as a run holding a live group is. + #[test] + #[cfg(feature = "async")] + fn a_skipped_run_holding_only_a_fill_answer_is_re_offered() { + let budget = Duration::from_millis(100); + let producer = track_producer("test", None); + let dynamic = producer.requests(); + let mut subscriber = producer.subscribe(Subscription::default().with_max(budget)); + let write = |key: u64| { + let mut group = producer.create_group(group::Info { start: key }).unwrap(); + group.write_frame(Timestamp::unscaled(key), &b"x"[..]).unwrap(); + group.finish().unwrap(); + }; + for key in 0..4 { + write(key); + } + evict(&producer, 1); + let waiter = kio::Waiter::noop(); + let next = |subscriber: &mut Subscriber| match subscriber.poll_recv_group(&waiter) { + Poll::Ready(Ok(Some(group))) => group.start, + _ => panic!("a group is cached"), + }; + assert_eq!(next(&mut subscriber), 3); + let Poll::Ready(Ok(fill)) = dynamic.poll_requested_fill(&waiter) else { + panic!("group 1 is a miss"); + }; + producer.broadcast.pool.step(budget); + let mut filled = fill.accept(1, None).unwrap().expect("a fresh group"); + filled.write_frame(Timestamp::unscaled(1), &b"x"[..]).unwrap(); + filled.finish().unwrap(); + drop(fill); + write(4); + write(5); + assert_eq!(next(&mut subscriber), 5); + assert_eq!(next(&mut subscriber), 4); + // The live groups of the skipped run go, leaving the fill's answer alone in it, and a + // hand-out prunes the skipped runs. + evict(&producer, 0); + evict(&producer, 2); + write(6); + assert_eq!(next(&mut subscriber), 6); + subscriber.update(subscriber.subscription().with_max(None)).unwrap(); + let mut widened = Vec::new(); + while let Poll::Ready(Ok(Some(group))) = subscriber.poll_recv_group(&waiter) { + widened.push(group.start); + } + assert_eq!(widened, [1]); + } + /// A live arrival judged on its own keeps the history a resumed copy's live floor sits /// above: a cached group the reader hasn't taken yet, evicted after, is still refilled. #[test] @@ -31542,7 +31898,7 @@ mod test { fn a_hold_ends_when_its_reader_leaves() { let (producer, pool) = pooled_producer(1 << 20); let dynamic = producer.requests(); - let mut subscriber = producer.subscribe(replay()); + let mut subscriber = producer.subscribe(replay().with_order(Order::Ascending)); for key in 0..3 { write_group(&producer, key); } @@ -31861,7 +32217,7 @@ mod test { fn a_refill_evicted_again_is_asked_again() { let producer = track_producer("test", Info::timed()); let dynamic = producer.requests(); - let mut subscriber = producer.subscribe(replay()); + let mut subscriber = producer.subscribe(replay().with_order(Order::Ascending)); for key in 0..3 { write_group(&producer, key); } @@ -32357,7 +32713,7 @@ mod test { write_group(&producer, key); } producer.finish_at(Position::group(10)).unwrap(); - assert_eq!(drain_groups(&mut subscriber), [0, 1, 2, 4, 5]); + assert_eq!(drain_groups(&mut subscriber), [5, 4, 2, 1, 0]); assert!(drained_drops(&mut subscriber).is_empty(), "group 3 may still arrive"); write_group(&producer, 3); assert_eq!(drain_groups(&mut subscriber), [3]); @@ -32376,7 +32732,7 @@ mod test { while let Poll::Ready(Ok(Some(group))) = subscriber.poll_recv_group(&waiter) { read.push(group.start); } - assert_eq!(read, [2, 3]); + assert_eq!(read, [3, 2]); assert!(drained_drops(&mut subscriber).is_empty()); elapse(&producer, Duration::from_secs(31)); assert_eq!(drained_drops(&mut subscriber), [(0, 2)]); @@ -32729,7 +33085,11 @@ mod test { start: Start::Time(15), end: Some(17), }; - let mut subscriber = producer.subscribe(Subscription::default().with_ranges([join, ahead])); + let mut subscriber = producer.subscribe( + Subscription::default() + .with_ranges([join, ahead]) + .with_order(Order::Ascending), + ); let Poll::Ready(Ok(Some(group))) = subscriber.poll_recv_group(&kio::Waiter::noop()) else { panic!("a group to read") }; @@ -32796,7 +33156,7 @@ mod test { let mut subscriber = producer.subscribe(replay()); write_group(&producer, 0); let open = producer.create_group(group::Info { start: 1 }).unwrap(); - assert_eq!(drain_groups(&mut subscriber), [0, 1]); + assert_eq!(drain_groups(&mut subscriber), [1, 0]); open.abort(Error::Cancel).unwrap(); write_group(&producer, 1); @@ -32823,7 +33183,7 @@ mod test { for key in [0, 1, 2, 4, 5, 6] { write_group(&producer, key); } - assert_eq!(drain_groups(&mut subscriber), [0, 1, 2, 4, 5, 6]); + assert_eq!(drain_groups(&mut subscriber), [6, 5, 4, 2, 1, 0]); // Group 4 reaches until group 5 presents at 5ms, so it is past a 10ms budget once // the edge presents at 15ms. for key in 7..=14 { @@ -32864,6 +33224,39 @@ mod test { assert_eq!(drain_groups(&mut subscriber), [2998]); } + /// A newest-first reader that never drains down to the groups the cache evicted under it + /// owes no more runs than the cache holds groups, however long the track runs. + #[test] + fn a_reader_forgets_the_owed_groups_the_cache_evicted() { + let producer = track_producer("test", Info::timed()); + // Cached throughout, and never stale without a budget, so the oldest-end scan stops here. + write_group(&producer, 0); + let mut subscriber = producer.subscribe(Subscription::default().with_ranges([Range::ALL]).with_max(None)); + let waiter = kio::Waiter::noop(); + let (mut most, mut peak) = (0, 0); + for batch in 1..200u64 { + // Sparse keys, so no two owed groups merge into one run. + let (older, newer) = (batch * 10, batch * 10 + 5); + write_group(&producer, older); + write_group(&producer, newer); + peak = peak.max(producer.state.read().lookup.len()); + let Poll::Ready(Ok(Some(group))) = subscriber.poll_recv_group(&waiter) else { + panic!("batch {batch} hands out a group"); + }; + assert_eq!(group.start, newer, "newest first"); + // The cache lets the older one go before the reader gets down to it, and the + // last batch's newer one, handed out. + evict(&producer, older); + if batch > 1 { + evict(&producer, newer - 10); + } + most = most.max(subscriber.owed_runs()); + } + assert!(most <= 2 * peak, "{most} owed runs for at most {peak} cached groups"); + // Draining down still reads the group the cache kept. + assert_eq!(drain_groups(&mut subscriber), [0]); + } + /// A group of one untimed frame at `key`. fn write_untimed_group(producer: &Producer, key: u64) { let mut group = producer.create_group(group::Info { start: key }).unwrap(); @@ -32913,7 +33306,7 @@ mod test { // All three arrived at once, so however far apart their starts, none is stale yet. assert_eq!( drain_groups(&mut subscribe()), - [base, base + 10_000, base + 20_000], + [base + 20_000, base + 10_000, base], "from {base}" ); // Their successors arrived a full budget ago, so only the newest is left. @@ -32922,6 +33315,22 @@ mod test { } } + /// Retiring a group written off at the bound keeps a lower group still owed: it arrived + /// after a newer one, so its own successor may be fresh. + #[test] + fn a_group_written_off_at_the_bound_keeps_a_fresh_lower_one_owed() { + let budget = Duration::from_millis(100); + let producer = track_producer("test", Info::default().with_max_age(budget)); + let mut reader = producer.subscribe(Subscription::default().with_max(budget)); + write_untimed_group(&producer, 3); + elapse(&producer, Duration::from_millis(140)); + write_untimed_group(&producer, 2); + write_untimed_group(&producer, 1); + // 2 went stale when 3 arrived a full budget ago, but 1's successor 2 arrived 10 ms ago. + elapse(&producer, Duration::from_millis(10)); + assert_eq!(drain_groups(&mut reader), [3, 1]); + } + /// A scale-less group's end is a bare number, no time, so a group finished whole ages only /// once a successor arrives, as any other group does. #[kio::test] @@ -32987,7 +33396,7 @@ mod test { .collect(); assert_eq!( drain_groups(&mut subscriber), - [0].into_iter().chain(2..2 + RUN).collect::>() + (2..2 + RUN).rev().chain([0]).collect::>() ); assert_eq!(subscriber.delivered_runs(), 2, "the floor and the run above the gap"); @@ -33043,7 +33452,7 @@ mod test { .unwrap(); open.push(group); } - assert_eq!(drain_groups(&mut subscriber), [0, 2, 4, 6, 8, 10]); + assert_eq!(drain_groups(&mut subscriber), [10, 8, 6, 4, 2, 0]); for group in open.drain(..5) { group.abort(Error::Cancel).unwrap(); } @@ -33222,7 +33631,7 @@ mod test { assert_eq!(drain(&mut live), Vec::::new()); append_at(&mut producer, 0); append_at(&mut producer, 1); - assert_eq!(drain(&mut live), vec![0, 1]); + assert_eq!(drain(&mut live), vec![1, 0]); } /// A received copy's fetched backfill past the newest group its feed delivered moves no @@ -33284,13 +33693,13 @@ mod test { }); let mut behind = producer.subscribe(Subscription::default().with_ranges([lag])); assert_eq!(producer.subscription().unwrap().ranges, vec![Range::groups(8..), lag]); - assert_eq!(drain(&mut behind), vec![3, 4, 5]); + assert_eq!(drain(&mut behind), vec![5, 4, 3]); for millis in 6..=8 { append_at(&mut producer, millis); } - assert_eq!(drain(&mut behind), vec![6, 7, 8]); - assert_eq!(drain(&mut ahead), vec![5, 6, 7, 8]); + assert_eq!(drain(&mut behind), vec![8, 7, 6]); + assert_eq!(drain(&mut ahead), vec![8, 7, 6, 5]); } /// A join on an untimed track reaching back past every group replays only what the wall @@ -33304,7 +33713,7 @@ mod test { elapse(&producer, Duration::from_secs(1)); } let mut subscriber = producer.subscribe(within(Duration::from_millis(1500), None)); - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); } /// A group `key` whose first frame lands at `millis`, or the write's refusal. A @@ -33509,8 +33918,8 @@ mod test { for second in 0..7 { append_at(&mut producer, second * 1000); } - assert_eq!(drain(&mut everything), vec![0, 1, 2, 3, 4, 5, 6]); - assert_eq!(drain(&mut mine), vec![1, 2, 5, 6]); + assert_eq!(drain(&mut everything), vec![6, 5, 4, 3, 2, 1, 0]); + assert_eq!(drain(&mut mine), vec![6, 5, 2, 1]); assert_eq!(drain_ordered(&mut ordered), vec![1, 2, 5, 6]); } @@ -33524,7 +33933,7 @@ mod test { for second in 0..4 { append_at(&mut producer, second * 1000); } - assert_eq!(drain(&mut subscriber), vec![0, 1]); + assert_eq!(drain(&mut subscriber), vec![1, 0]); subscriber.update(replay().with_range(0..)).unwrap(); assert_eq!( @@ -33651,7 +34060,7 @@ mod test { .finish() .unwrap(); } - assert_eq!(drain(&mut narrow), vec![0, 1]); + assert_eq!(drain(&mut narrow), vec![1, 0]); let Inner::Plain(cursor) = &narrow.inner else { unreachable!() }; @@ -33710,7 +34119,7 @@ mod test { append_at(&mut producer, second * 1000); } let mut subscriber = producer.subscribe(replay()).with_range(4..); - assert_eq!(drain(&mut subscriber), vec![4, 5]); + assert_eq!(drain(&mut subscriber), vec![5, 4]); let mut subscriber = subscriber.with_range(1..); assert_eq!(drain(&mut subscriber), vec![3, 2, 1], "passed below the floor"); @@ -34066,7 +34475,7 @@ mod test { write_group(&producer, 5); assert!(producer.state.read().drops.is_empty()); assert!(subscriber.poll_drop(&waiter).is_pending()); - assert_eq!(drain_groups(&mut subscriber), [2, 5]); + assert_eq!(drain_groups(&mut subscriber), [5, 2]); write_group(&producer, 4); assert_eq!(drain_groups(&mut subscriber), [4]); @@ -34087,7 +34496,7 @@ mod test { producer.append_next().unwrap().finish().unwrap(); assert_eq!(subscriber.poll_drop(&waiter), Poll::Ready((3..5, Hole::Skip))); assert_eq!(subscriber.poll_drop(&waiter), Poll::Ready((6..7, Hole::Skip))); - assert_eq!(drain_groups(&mut subscriber), [2, 5, 7, 8]); + assert_eq!(drain_groups(&mut subscriber), [8, 7, 5, 2]); // The next append only names what was left since this one. write_group(&producer, 10); @@ -34308,7 +34717,7 @@ mod test { let producer = track_producer_pooled("test", pool.clone()); producer.received(); let dynamic = producer.requests(); - let mut subscriber = producer.subscribe(patient()); + let mut subscriber = producer.subscribe(patient().with_order(Order::Ascending)); write_group(&producer, 0); producer.drop_groups(1..2, StreamError::Old); write_group(&producer, 2); @@ -34353,7 +34762,7 @@ mod test { write_group(&producer, 0); write_group(&producer, 6); let mut subscriber = producer.subscribe(Subscription::default().with_range(0..7)); - assert_eq!(drain_groups(&mut subscriber), [0, 6]); + assert_eq!(drain_groups(&mut subscriber), [6, 0]); let mut subscriber = subscriber.with_range(6..7); let waiter = kio::Waiter::noop(); producer.skip_groups(3..6); @@ -34391,7 +34800,7 @@ mod test { write_group(&producer, 0); write_group(&producer, 6); let mut subscriber = producer.subscribe(Subscription::default().with_range(0..7)); - assert_eq!(drain_groups(&mut subscriber), [0, 6]); + assert_eq!(drain_groups(&mut subscriber), [6, 0]); let mut subscriber = subscriber.with_range(6..7); let waiter = kio::Waiter::noop(); producer.skip_groups(3..6); @@ -34438,7 +34847,7 @@ mod test { end: Some(7), }, ])); - assert_eq!(drain_groups(&mut subscriber), [0, 6]); + assert_eq!(drain_groups(&mut subscriber), [6, 0]); let mut subscriber = subscriber.with_range(6..8); let waiter = kio::Waiter::noop(); producer.skip_groups(1..6); @@ -34479,7 +34888,7 @@ mod test { write_group(&producer, 0); write_group(&producer, 6); let mut subscriber = producer.subscribe(Subscription::default().with_range(0..7)); - assert_eq!(drain_groups(&mut subscriber), [0, 6]); + assert_eq!(drain_groups(&mut subscriber), [6, 0]); let mut subscriber = subscriber.with_range(6..7); let waiter = kio::Waiter::noop(); producer.skip_groups(3..6); @@ -34509,7 +34918,7 @@ mod test { write_group(&producer, 0); write_group(&producer, 6); let mut subscriber = producer.subscribe(Subscription::default().with_range(0..7)); - assert_eq!(drain_groups(&mut subscriber), [0, 6]); + assert_eq!(drain_groups(&mut subscriber), [6, 0]); let mut subscriber = subscriber.with_range(6..7); let waiter = kio::Waiter::noop(); producer.skip_groups(3..6); @@ -34755,7 +35164,7 @@ mod test { assert_eq!(producer.state.read().drops.iter().count(), 1); assert_eq!(subscriber.poll_drop(&waiter), Poll::Ready((1..FAR, Hole::Skip))); write_far(&producer); - assert_eq!(drain_groups(&mut subscriber), [0, FAR]); + assert_eq!(drain_groups(&mut subscriber), [FAR, 0]); assert!(subscriber.poll_drop(&waiter).is_pending()); let producer = track_producer("test", Info::timed()); @@ -34765,7 +35174,7 @@ mod test { producer.append_next().unwrap().finish().unwrap(); assert_eq!(producer.state.read().drops.iter().count(), 1); assert_eq!(subscriber.poll_drop(&waiter), Poll::Ready((1..FAR, Hole::Skip))); - assert_eq!(drain_groups(&mut subscriber), [0, FAR, FAR + 1]); + assert_eq!(drain_groups(&mut subscriber), [FAR + 1, FAR, 0]); } /// A dropped key may be created again, as a group stream wins over its drop, such as @@ -34782,7 +35191,7 @@ mod test { assert!(producer.state.read().drops.is_empty()); let mut read = drain_groups(&mut subscriber); read.dedup(); - assert_eq!(read.last(), Some(&1)); + assert_eq!(read, [1, 0]); } /// `skip_groups` leaves a cached group alone, and replaces every drop, final or stale: the @@ -34828,7 +35237,7 @@ mod test { Poll::Ready((4..5, Hole::drop(StreamError::NotFound))) ); assert!(subscriber.poll_drop(&waiter).is_pending()); - assert_eq!(drain_groups(&mut subscriber), [0, 5]); + assert_eq!(drain_groups(&mut subscriber), [5, 0]); // Group 0 arrived, so the skip leaves it; both drops and the gap between become one skip. producer.skip_groups(0..5); @@ -34885,7 +35294,7 @@ mod test { assert!(producer.state.read().drops.is_empty()); assert!(drained_drops(&mut subscriber).is_empty()); write_group(&producer, 3); - assert_eq!(drain_groups(&mut subscriber), [2, 5, 3]); + assert_eq!(drain_groups(&mut subscriber), [5, 3, 2]); } /// A received stale run a new upstream subscription supersedes is unknown again, and a group @@ -34960,7 +35369,7 @@ mod test { #[cfg(feature = "async")] fn a_drop_ends_a_held_group_with_its_error() { let producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(replay()); + let mut subscriber = producer.subscribe(replay().with_order(Order::Ascending)); let mut open = producer.create_group(group::Info { start: 0 }).unwrap(); open.write_frame(open.key_time(), &b"a"[..]).unwrap(); let mut finished = producer.create_group(group::Info { start: 1 }).unwrap(); @@ -35038,10 +35447,11 @@ mod test { .unwrap(); let _producer = producer.finish().unwrap(); - let mut first = arrival.assert_group(); - assert_eq!(first.start, 0); - assert!(matches!(first.read_frame().now_or_never(), Some(Err(Error::App(5))))); + // The arrival read holds both, so it takes the newer first. assert_eq!(arrival.assert_group().start, 1); + let mut cut = arrival.assert_group(); + assert_eq!(cut.start, 0); + assert!(matches!(cut.read_frame().now_or_never(), Some(Err(Error::App(5))))); assert!(matches!(arrival.recv_group().now_or_never(), Some(Ok(None)))); let mut first = ordered.next_group().now_or_never().unwrap().unwrap().unwrap(); @@ -35099,7 +35509,7 @@ mod test { elapse(&producer, Duration::from_secs(1)); pool.sweep(); - let mut late = producer.subscribe(replay()); + let mut late = producer.subscribe(replay().with_order(Order::Ascending)); let mut first = late.assert_group(); assert_eq!(first.start, 0, "the sweep kept the cut"); assert!(matches!(first.read_frame().now_or_never(), Some(Err(Error::App(5))))); @@ -35173,7 +35583,7 @@ mod test { }; let mut seek = producer.subscribe(time(1500, 2000)); - assert_eq!(drain(&mut seek), vec![1000, 2000]); + assert_eq!(drain(&mut seek), vec![2000, 1000]); let mut early = producer.subscribe(time(0, 500)); assert_eq!(drain(&mut early), vec![0]); @@ -35235,7 +35645,7 @@ mod test { let mut through = producer.subscribe(time(0, Some(1700))); assert_eq!( drain(&mut through), - vec![0, 1000], + vec![1000, 0], "a time end in the pause stops after 1000" ); // 2000 has no End, so it spans up to the next start. @@ -35305,7 +35715,7 @@ mod test { start: crate::track::Start::Time(0), end: Some(500), }])); - assert_eq!(drain(&mut subscriber), vec![0, 400]); + assert_eq!(drain(&mut subscriber), vec![400, 0]); assert_eq!( subscriber.resolved_keys([0]), vec![Some(Resolved { @@ -35332,7 +35742,7 @@ mod test { start: crate::track::Start::Time(7), end: Some(10), }])); - assert_eq!(drain(&mut subscriber), vec![5, 10]); + assert_eq!(drain(&mut subscriber), vec![10, 5]); } /// A widened budget re-offers the cached groups the cursor skipped as stale, newest @@ -35349,7 +35759,7 @@ mod test { append_at(&mut producer, millis); } // Groups 1 and 2 reach 2s and 3s, at least 1.5s behind the 6s edge. - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); subscriber.update(narrow.with_max(Duration::from_secs(10))).unwrap(); assert_eq!( @@ -35373,7 +35783,7 @@ mod test { for millis in [1000, 2000, 3000, 6000] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); assert!(!subscriber.taking().may_take(0), "handed out"); assert!(!subscriber.taking().may_take(1), "skipped as stale under this budget"); assert!(subscriber.taking().may_take(5), "not arrived yet"); @@ -35397,7 +35807,7 @@ mod test { for millis in [1000, 2000, 3000, 6000] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); evict(&producer, 3); evict(&producer, 4); assert!(!subscriber.taking().may_take(1), "skipped, and no wider budget yet"); @@ -35422,7 +35832,7 @@ mod test { for millis in [1000, 2000, 3000, 6000] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); subscriber.update(narrow.with_max(Duration::from_secs(10))).unwrap(); assert_eq!(drain(&mut subscriber), Vec::::new(), "still stale at the bound"); @@ -35464,11 +35874,11 @@ mod test { for millis in [1000, 2000, 4000] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut subscriber), vec![2, 3]); + assert_eq!(drain(&mut subscriber), vec![3, 2]); for millis in [5000, 6000, 9000] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut subscriber), vec![5, 6]); + assert_eq!(drain(&mut subscriber), vec![6, 5]); // Group 4 reaches 6s, 3s behind the 9s edge; group 1 reaches 2s, 7s behind. subscriber @@ -35492,7 +35902,7 @@ mod test { let narrow = Subscription::default().with_max(Duration::from_millis(1500)); let mut subscriber = producer.subscribe(narrow.clone()); subscriber.set_range(3..5); - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); for millis in [20_000, 40_000] { append_at(&mut producer, millis); } @@ -35526,7 +35936,7 @@ mod test { for millis in [1000, 2000, 3000, 6000] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); // Groups 3 and 4 are past the budget now, which would write off the gap below them. for millis in [20_000, 40_000] { append_at(&mut producer, millis); @@ -35552,7 +35962,7 @@ mod test { append_at(&mut producer, millis); } let mut subscriber = producer.subscribe(Subscription::default().with_max(Duration::from_secs(10))); - assert_eq!(drain(&mut subscriber), vec![1, 2]); + assert_eq!(drain(&mut subscriber), vec![2, 1]); assert_eq!(skipped_runs(&subscriber), 0); append_at(&mut producer, 3000); assert_eq!(drain(&mut subscriber), vec![3]); @@ -35572,7 +35982,7 @@ mod test { for millis in [1000, 2000, 3000, 6000] { append_at(&mut producer, millis); } - assert_eq!(drain(&mut subscriber), vec![3, 4]); + assert_eq!(drain(&mut subscriber), vec![4, 3]); assert_eq!(skipped_runs(&subscriber), 1); evict(&producer, 1); diff --git a/rs/moq-net/src/model/track/miss.rs b/rs/moq-net/src/model/track/miss.rs index 5809ef3478b..a7fc196130e 100644 --- a/rs/moq-net/src/model/track/miss.rs +++ b/rs/moq-net/src/model/track/miss.rs @@ -363,6 +363,12 @@ impl Misses { !self.filled.is_empty() } + /// The groups at or above `from` a fill answered and not handed out yet, lowest first, + /// including any evicted since that [`Self::next_filled`] has yet to prune. + pub fn filled_from(&self, from: u64) -> impl Iterator + '_ { + self.filled.range(from..).copied() + } + /// The lowest key asked and not answered yet. pub fn lowest_wanted(&self) -> Option { self.wanted.iter().next().map(|run| run.start) @@ -430,6 +436,11 @@ impl Misses { self.pick_up(); } + /// Offer `key`, a fill's answer still cached, again: a widened budget owes it once more. + pub fn refill(&mut self, key: u64) { + self.filled.insert(key); + } + /// Take `key` as handed out, if a fill answered it. pub fn take_filled(&mut self, key: u64) { if self.filled.remove(&key) { diff --git a/rs/moq-net/tests/integration/drop_record.rs b/rs/moq-net/tests/integration/drop_record.rs index 9176fad8745..f0355889320 100644 --- a/rs/moq-net/tests/integration/drop_record.rs +++ b/rs/moq-net/tests/integration/drop_record.rs @@ -502,6 +502,12 @@ async fn an_ordered_reader_is_told_of_every_group_the_origin_evicted() { .write_frame(Timestamp::from_millis(key * 1000).unwrap(), vec![0u8; PAYLOAD]) .unwrap(); group.finish().unwrap(); + // Newest first, the origin would serve the last written: let group 0 take the + // credit before the rest queue behind it. Time is simulated, so this only lets + // every task settle. + if key == 0 { + kio::clock::sleep(Duration::from_millis(1)).await; + } } // Nobody reads the queued groups, so the origin reclaims all but the newest. kio::clock::sleep(EXPIRY * 3).await; diff --git a/rs/moq-net/tests/integration/errored_end.rs b/rs/moq-net/tests/integration/errored_end.rs index 60ce43da62a..6cabc0b4957 100644 --- a/rs/moq-net/tests/integration/errored_end.rs +++ b/rs/moq-net/tests/integration/errored_end.rs @@ -30,9 +30,11 @@ fn produce_origin(hop: u64) -> moq_net::origin::Producer { /// Read every group from the first, frame by frame, returning each group's key and /// payloads, and how the read ended. async fn read(broadcast: &moq_net::broadcast::Consumer) -> (Vec<(u64, Vec>)>, Option) { + // The history oldest first. let subscription = Subscription::default() .with_ranges([support::keys(0..)]) - .with_max(Duration::from_secs(30)); + .with_max(Duration::from_secs(30)) + .with_order(moq_net::track::Order::Ascending); let mut sub = kio::clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(subscription)) .await .expect("subscribe timeout") diff --git a/rs/moq-net/tests/integration/group_end.rs b/rs/moq-net/tests/integration/group_end.rs index b5dc85c1543..ca56989130a 100644 --- a/rs/moq-net/tests/integration/group_end.rs +++ b/rs/moq-net/tests/integration/group_end.rs @@ -94,6 +94,8 @@ async fn round(version: &str) -> (Vec<(u64, Option)>, Option) { let start = group.start; subscribed.push((start, read_to_end(group).await)); } + // Which of the two is read first depends on which lands first, so only the set is checked. + subscribed.sort(); // A second reader fetching group 0 from a hop that never held it. let fetcher = produce_origin(3); diff --git a/rs/moq-net/tests/integration/group_order.rs b/rs/moq-net/tests/integration/group_order.rs index ac5d0c2c965..ef4a650b710 100644 --- a/rs/moq-net/tests/integration/group_order.rs +++ b/rs/moq-net/tests/integration/group_order.rs @@ -106,11 +106,6 @@ fn expected(order: Order) -> Vec { } } -/// Whether `version` can carry an ascending order at all. -fn carries_order(version: &str) -> bool { - version == "moq-lite-07-wip" || version.starts_with("moq-transport") -} - /// Serve one subscriber in `order`, optionally through a relay, and return the order its /// backlog arrived in. async fn round(version: &str, relay: bool, order: Order) -> Vec { @@ -171,12 +166,9 @@ async fn a_backlog_is_served_in_the_subscription_order() { for relay in [false, true] { for order in [Order::Ascending, Order::Descending] { let got = round(version, relay, order).await; - // An older lite wire cannot ask for ascending, so it is served newest first. - let served = match carries_order(version) { - true => order, - false => Order::Descending, - }; - if got != expected(served) { + // An older lite wire cannot ask for ascending, so it is served newest first, but + // the reader holds the whole backlog by then and reads it in its own order. + if got != expected(order) { failures.push(format!("{version} relay={relay} {order:?}: {got:?}")); } } diff --git a/rs/moq-net/tests/integration/ietf_keys.rs b/rs/moq-net/tests/integration/ietf_keys.rs index 11c4e1721fc..b2d15c67dea 100644 --- a/rs/moq-net/tests/integration/ietf_keys.rs +++ b/rs/moq-net/tests/integration/ietf_keys.rs @@ -68,7 +68,8 @@ async fn a_relay_keeps_keys_and_the_gaps_between_them() { .subscribe( Subscription::default() .with_ranges([support::keys(2..=8)]) - .with_max(None), + .with_max(None) + .with_order(moq_net::track::Order::Ascending), ) .await .unwrap(); diff --git a/rs/moq-net/tests/integration/range_union_fit.rs b/rs/moq-net/tests/integration/range_union_fit.rs index cc4e49de18c..9b8c1332889 100644 --- a/rs/moq-net/tests/integration/range_union_fit.rs +++ b/rs/moq-net/tests/integration/range_union_fit.rs @@ -155,13 +155,18 @@ async fn a_union_too_large_for_one_message_asks_a_covering_superset() { write_group(&track, BASE + 3); write_group(&track, BASE + 2 * VIEWERS + 2); write_group(&track, key); - for want in [BASE + 2, BASE + 2 * VIEWERS + 2] { - let got = kio::clock::timeout(TIMEOUT, readers[1].recv_group()) + // Which of its two is read first depends on which lands first, so only the set is checked. + let mut got = Vec::new(); + for _ in 0..2 { + let group = kio::clock::timeout(TIMEOUT, readers[1].recv_group()) .await .unwrap() - .unwrap(); - assert_eq!(got.map(|group| group.start), Some(want)); + .unwrap() + .expect("a group"); + got.push(group.start); } + got.sort(); + assert_eq!(got, [BASE + 2, BASE + 2 * VIEWERS + 2]); let got = kio::clock::timeout(TIMEOUT, live.recv_group()).await.unwrap().unwrap(); assert_eq!( got.map(|group| group.start), diff --git a/rs/moq-net/tests/integration/route_audit/mod.rs b/rs/moq-net/tests/integration/route_audit/mod.rs index f19917688bf..ce01cef0f4d 100644 --- a/rs/moq-net/tests/integration/route_audit/mod.rs +++ b/rs/moq-net/tests/integration/route_audit/mod.rs @@ -351,13 +351,15 @@ impl Reader { }; run += 1; let instance = broadcast.info().instance.clone(); - // From the live edge, and never skipping a group however late. + // From the live edge, and never skipping a group however late. Oldest first, so a + // backlog held across a failure reads in key order, as the report counts it. let prefs = track::Subscription::default() .with_ranges([track::Range::from(track::Start::Live { min: Some(Duration::ZERO), max: None, })]) - .with_max(Duration::from_secs(60)); + .with_max(Duration::from_secs(60)) + .with_order(track::Order::Ascending); let Ok(mut sub) = broadcast.track(TRACK).unwrap().subscribe(prefs).await else { continue; }; diff --git a/rs/moq-net/tests/integration/route_health.rs b/rs/moq-net/tests/integration/route_health.rs index 224be1b162f..977d9cd55bb 100644 --- a/rs/moq-net/tests/integration/route_health.rs +++ b/rs/moq-net/tests/integration/route_health.rs @@ -73,7 +73,11 @@ async fn silent_kill(budget: Duration, detect: Duration) -> Vec { .await .unwrap() .unwrap(); - let prefs = track::Subscription::default().with_max(budget); + // Oldest first, so what the resume loses is the budget's verdict alone, not what reading + // the newest first left to age. + let prefs = track::Subscription::default() + .with_max(budget) + .with_order(track::Order::Ascending); let mut rx = read(remote.track("video").unwrap().subscribe(prefs).await.unwrap()); let m2_e = priced_link(version, &m2, &e, Some(1_000)).await; settle().await; diff --git a/rs/moq-net/tests/integration/settled_end_survives_abort.rs b/rs/moq-net/tests/integration/settled_end_survives_abort.rs index ca44ae2f4ff..757436da035 100644 --- a/rs/moq-net/tests/integration/settled_end_survives_abort.rs +++ b/rs/moq-net/tests/integration/settled_end_survives_abort.rs @@ -70,7 +70,11 @@ async fn round(abort: bool, ordered: bool) -> (Vec, Option) { loop { match consumer.recv_group().await { Ok(Some(group)) => got.push(group.start), - Ok(None) => return (got, None), + // An arrival read takes what it holds newest first, so reversed it is in key order. + Ok(None) => { + got.reverse(); + return (got, None); + } Err(err) => return (got, Some(err)), } } diff --git a/rs/moq-net/tests/integration/subscribe_ranges.rs b/rs/moq-net/tests/integration/subscribe_ranges.rs index f77baca854d..cfdd64f141f 100644 --- a/rs/moq-net/tests/integration/subscribe_ranges.rs +++ b/rs/moq-net/tests/integration/subscribe_ranges.rs @@ -252,9 +252,10 @@ async fn a_live_subscriber_merged_with_one_ahead_still_gets_the_newest_group() { let mut failures = Vec::new(); // In-process the start is time 4, which lies in group 3 until group 4 starts, and a time - // start is history, so that reader gets group 3 too. A wire carries it as group 4. + // start is history, so that reader gets group 3 too, after group 4 since it holds both. A + // wire carries it as group 4. let got = ahead_then_live(None, false).await; - if got != (vec![3, 4], vec![3, 4]) { + if got != (vec![4, 3], vec![3, 4]) { failures.push(format!("in-process: {got:?}")); } for version in LITE.iter().chain(TRANSPORT) { diff --git a/rs/moq-net/verify/resume/ResumeReader.tla b/rs/moq-net/verify/resume/ResumeReader.tla index e4c9ab12cb5..c1d8885e4ca 100644 --- a/rs/moq-net/verify/resume/ResumeReader.tla +++ b/rs/moq-net/verify/resume/ResumeReader.tla @@ -7,18 +7,18 @@ (* The front (`resume::Producer`) serves one copy at a time, switches to *) (* another live one at will, and ends the track. The reader (`Reader`) *) (* keeps one `Copy` per route it read, each with its own cursor over that *) -(* track: a walk in arrival order, the groups a widening owes it, and what *) -(* it took. One poll for a group (`Reader::poll_lowest`) is one atomic *) -(* step, as the reader's lock makes it; so is a switch, which syncs the *) -(* reader as `serve_from` does. *) +(* track, which holds what landed in its window and picks in the *) +(* subscription's Group Order, and what it took. One poll for a group *) +(* (`Reader::poll_first`) is one atomic step, as the reader's lock makes *) +(* it; so is a switch, which syncs the reader as `serve_from` does. *) (* *) (* Scope: whole groups (no frames, so no `Recover`), an unbounded *) (* subscription from the oldest group with an hour's budget (nothing goes *) -(* stale or expires), arrival order, no local range, copies that answer at *) -(* once, and a reader that joins before any group lands. A route declares *) -(* its end once it holds the last group, a gap below it may still land, *) -(* even once its session settled that end, and a route that declared its *) -(* end never fails. *) +(* stale or expires), an arrival read in the default Group Order (newest *) +(* first), no local range, copies that answer at once, and a reader that *) +(* joins before any group lands. A route declares its end once it holds *) +(* the last group, a gap below it may still land, even once its session *) +(* settled that end, and a route that declared its end never fails. *) (***************************************************************************) EXTENDS Integers, Sequences, FiniteSets @@ -83,22 +83,14 @@ Admits(floor, until, g) == NewCopy(id, t, gen, floor, rep, until) == [id |-> id, t |-> t, gen |-> gen, floor |-> floor, rep |-> rep, - until |-> until, done |-> "no", drained |-> 0, idx |-> 1, - took |-> {}, owed |-> {}] + until |-> until, done |-> "no", drained |-> 0, took |-> {}] \* The wire asks for [floor, until] instead (`Copy::cap`, or `Copy::send` on a \* reuse or a widening; neither reopens a drained copy): the cursor -\* passes what its window leaves out, holding nothing, and a widening owes it -\* the cached groups the window newly covers. -Window(c, floor, until) == - [c EXCEPT - !.floor = floor, - !.until = until, - !.owed = {g \in @ : Admits(floor, until, g)} - \cup {g \in Landed(c.t) : - /\ Admits(floor, until, g) - /\ ~Admits(c.floor, c.until, g) - /\ g \notin c.took}] +\* passes what its window leaves out, holding nothing, and a widening offers it +\* the cached groups the window newly covers. Every landed group stays cached +\* for the hour's budget, so the window alone decides what the cursor holds. +Window(c, floor, until) == [c EXCEPT !.floor = floor, !.until = until] \* `Reader::deliverable`. Deliverable(c, g, dlv) == @@ -106,39 +98,24 @@ Deliverable(c, g, dlv) == /\ g \notin dlv \* One `poll_peek_group` on a copy's cursor, skipping what the logical reader -\* already has (`take`, so the cursor moves past it). Returns the cursor moved, -\* and the group it reserves (None when pending or done), and where it came from. -RECURSIVE Peek(_, _, _) -Peek(c, dlv, fuel) == - LET ow == {g \in c.owed : Admits(c.floor, c.until, g) /\ g \notin c.took} - arr == trk[c.t].arr +\* already has (`take`, so the cursor moves past it). It holds what landed in +\* its window and it has not taken, and picks in the subscription's Group Order, +\* the default `Order::Descending`: the newest first. An aborted track still +\* hands out what it holds before its error; once it holds nothing, a complete +\* track ends the cursor and an aborted one fails it. A clean end records the +\* arrivals it saw (`Copy::drained`). Returns the cursor moved and the group it +\* reserves (None when pending or done). +Peek(c, dlv) == + LET unread == {g \in Landed(c.t) : Admits(c.floor, c.until, g) /\ g \notin c.took} + rest == {g \in unread : Deliverable(c, g, dlv)} + c1 == [c EXCEPT !.took = @ \cup (unread \ rest)] IN - IF fuel = 0 THEN [c |-> c, g |-> None, src |-> "none"] - \* What a widening owes comes first, newest first (`Order::Descending`). An - \* aborted track still hands out what it holds before its error. - ELSE IF ow # {} THEN - LET g == Max(ow) IN - IF Deliverable(c, g, dlv) - THEN [c |-> c, g |-> g, src |-> "owed"] - ELSE Peek([c EXCEPT !.took = @ \cup {g}, !.owed = @ \ {g}], dlv, fuel - 1) - \* `TrackState::poll_recv_group`: past the last arrival, a complete track - \* ends the walk, and an aborted one fails it. A clean end records the - \* arrivals it saw (`Copy::drained`). - ELSE IF c.idx > Len(arr) THEN - IF trk[c.t].whole - THEN [c |-> [c EXCEPT !.done = "ok", !.drained = Len(arr)], g |-> None, src |-> "none"] - ELSE IF trk[c.t].failed - THEN [c |-> [c EXCEPT !.done = "err"], g |-> None, src |-> "none"] - ELSE [c |-> c, g |-> None, src |-> "none"] - ELSE - LET g == arr[c.idx] IN - IF ~Admits(c.floor, c.until, g) \/ g \in c.took - THEN Peek([c EXCEPT !.idx = @ + 1], dlv, fuel - 1) - ELSE IF Deliverable(c, g, dlv) - THEN [c |-> c, g |-> g, src |-> "walk"] - ELSE Peek([c EXCEPT !.took = @ \cup {g}, !.idx = @ + 1], dlv, fuel - 1) - -Fuel == 2 * G + 2 + IF rest # {} THEN [c |-> c1, g |-> Max(rest)] + ELSE IF trk[c.t].whole + THEN [c |-> [c1 EXCEPT !.done = "ok", !.drained = Len(trk[c.t].arr)], g |-> None] + ELSE IF trk[c.t].failed + THEN [c |-> [c1 EXCEPT !.done = "err"], g |-> None] + ELSE [c |-> c1, g |-> None] Covers(dlv, lo, hi) == \A g \in lo .. hi - 1 : g \in dlv @@ -152,13 +129,12 @@ MayLand(t, lo, hi, floored, dlv) == /\ g \notin Landed(t) /\ floored \/ (Landed(t) # {} /\ g >= Min(Landed(t))) -\* `track::Subscriber::has_unread_group`: a group the walk has yet to take, or -\* a widening owes, in [Start, end), that the reader lacks. +\* `track::Subscriber::has_unread_group`: a group the cursor has yet to take +\* in [Start, end), that the reader lacks. HasUnread(c, end, dlv) == - LET arr == trk[c.t].arr - ahead == {arr[i] : i \in c.idx .. Len(arr)} \cup c.owed - IN /\ ~trk[c.t].failed - /\ \E g \in ahead : g >= Start(c) /\ g < end /\ g < End(c) /\ g \notin dlv + /\ ~trk[c.t].failed + /\ \E g \in Landed(c.t) \ c.took : + g >= Start(c) /\ g < end /\ g < End(c) /\ g \notin dlv (***************************************************************************) (* The reader. *) @@ -259,8 +235,8 @@ BackfillGaps(r) == gaps == {g \in 0 .. at - 1 : g \notin r.dlv /\ ~drains(g)} IN IF gaps = {} THEN r1 ELSE Backfill(r1, Min(gaps), at) -\* The copy loop of `poll_lowest`: peek each copy, keeping the lowest group; -\* a tie goes to the newer copy. A copy that ran out cleanly is read again +\* The copy loop of `poll_first`: peek each copy, keeping the first group in +\* Group Order, here the highest; a tie goes to the newer copy. A copy that ran out cleanly is read again \* once a group arrived on it since (`Copy::drained`); one arriving on the \* serving copy, which resumed at a floor, may be under it (`late`), as may \* what a replaced copy that just failed still had to drain. @@ -277,26 +253,22 @@ Scan(cs, dlv, gen, i, best, late) == IF c.done # "no" \/ spent THEN Scan(cs, dlv, gen, i + 1, best, late) ELSE - LET p == Peek(c, dlv, Fuel) + LET p == Peek(c, dlv) cs2 == [cs EXCEPT ![i] = p.c] - better == p.g # None /\ (best.g = None \/ p.g <= best.g) + better == p.g # None /\ (best.g = None \/ p.g >= best.g) IN Scan(cs2, dlv, gen, i + 1, - IF better THEN [i |-> i, g |-> p.g, src |-> p.src] ELSE best, + IF better THEN [i |-> i, g |-> p.g] ELSE best, late \/ (reopens /\ serves) \/ (c.rep /\ p.c.done = "err")) -NoBest == [i |-> 0, g |-> None, src |-> "none"] +NoBest == [i |-> 0, g |-> None] \* `Reader::take`: hand out the group. The switch capped every copy it \* replaced already, so the group bounds nothing. Take(r, b) == - LET c == r.copies[b.i] - moved == IF b.src = "walk" - THEN [c EXCEPT !.took = @ \cup {b.g}, !.idx = @ + 1] - ELSE [c EXCEPT !.took = @ \cup {b.g}, !.owed = @ \ {b.g}] - IN [r EXCEPT !.copies[b.i] = moved, - !.newest = Max2(@, b.g), - !.dup = @ \/ b.g \in r.dlv, - !.dlv = @ \cup {b.g}] + [r EXCEPT !.copies[b.i].took = @ \cup {b.g}, + !.newest = Max2(@, b.g), + !.dup = @ \/ b.g \in r.dlv, + !.dlv = @ \cup {b.g}] \* `Copy::retains` for a replaced copy: "wait" while it may still deliver a \* group the reader lacks under its cap, "keep" while it backs a group being @@ -325,7 +297,7 @@ LetGo(r) == IN [copies |-> [k \in 1 .. Cardinality(kept) |-> r.copies[order[k]]], waits |-> \E i \in 1 .. n : ret[i] = "wait"] -\* `Reader::poll_end`, with `poll_lowest`'s guard: a drained serving copy ends +\* `Reader::poll_end`, with `poll_first`'s guard: a drained serving copy ends \* the track only once no copy it replaced may still deliver below the end. PollEnd(r, drained, waits) == LET s == Serving(r) @@ -336,7 +308,7 @@ PollEnd(r, drained, waits) == ELSE IF front.end = "ok" /\ (s = {} \/ \E c \in s : c.done # "no") THEN ok ELSE "no" -\* One `poll_recv_group` on the logical track (`Reader::poll_lowest`, looked +\* One `poll_recv_group` on the logical track (`Reader::poll_first`, looked \* at again while it returns `None`: a late group on the serving copy sets \* `resumed`, so the next pass asks its route for what lies under its floor). RECURSIVE Pass(_) @@ -377,7 +349,7 @@ Late(r) == /\ c.rep /\ c.done = "no" /\ Admits(c.floor, c.until, g) /\ \/ /\ ~trk[c.t].failed - /\ g \in {trk[c.t].arr[k] : k \in c.idx .. Len(trk[c.t].arr)} \cup c.owed + /\ g \in Landed(c.t) \ c.took \/ MayLand(c.t, g, g + 1, c.floor # None, r.dlv)} (***************************************************************************) diff --git a/rs/moq-video/src/encode/capture.rs b/rs/moq-video/src/encode/capture.rs index 92a9e351538..afb1549c80f 100644 --- a/rs/moq-video/src/encode/capture.rs +++ b/rs/moq-video/src/encode/capture.rs @@ -2089,12 +2089,12 @@ mod tests { .track(&name) .unwrap() .subscribe( - moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(Duration::from_secs(5)), max: Some(Duration::from_secs(5)), - }, - )]), + })]) + .with_order(moq_net::track::Order::Ascending), ) .await .unwrap(); @@ -2280,18 +2280,18 @@ mod tests { } } - /// Subscribe to `name` with room to replay what it holds. + /// Subscribe to `name` with room to replay what it holds, oldest first. async fn watch(consumer: &moq_net::broadcast::Consumer, name: &str) -> moq_net::track::Subscriber { consumer .track(name) .unwrap() .subscribe( - moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from( - moq_net::track::Start::Live { + moq_net::track::Subscription::default() + .with_ranges([moq_net::track::Range::from(moq_net::track::Start::Live { min: Some(Duration::from_secs(60)), max: Some(Duration::from_secs(60)), - }, - )]), + })]) + .with_order(moq_net::track::Order::Ascending), ) .await .unwrap() diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index d8cc56e9e77..b945170f88f 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -157,7 +157,9 @@ extension Subscription { /// (zero is the latest group), and an unstated one reaches back as far as `max` allows. A /// `nil` `end` keeps following the live edge. public typealias Range = MoqFFI.MoqRange - /// Which pending group the publisher sends first: `.ascending` or `.descending`. + /// Which group comes first, as the publisher sends them and `recvGroup` returns those held: + /// `.ascending` or `.descending`. Before moq-lite-07 the publisher sends newest first whatever + /// this asks. public typealias Order = MoqFFI.MoqOrder /// moq-net's defaults, whose `delay` (no `min`, a zero `max`) starts at the newest group and diff --git a/swift/Sources/Moq/Track.swift b/swift/Sources/Moq/Track.swift index 6db2b4454ad..0179a224ccd 100644 --- a/swift/Sources/Moq/Track.swift +++ b/swift/Sources/Moq/Track.swift @@ -20,8 +20,9 @@ public final class TrackConsumer: AsyncSequence, Sendable { (try await ffi.nextGroup()).map(GroupConsumer.init) } - /// The next group in arrival order, which may be out of start order. `nil` once - /// the track ends. + /// The next group in arrival order, which may be out of start order: groups + /// already held come in the subscription's group order, newest first unless it + /// asks ascending. `nil` once the track ends. public func recvGroup() async throws -> GroupConsumer? { (try await ffi.recvGroup()).map(GroupConsumer.init) } @@ -62,8 +63,9 @@ public final class TrackConsumer: AsyncSequence, Sendable { ffi.cancel() } - /// Groups in arrival order, including out-of-order deliveries. The default - /// `AsyncSequence` iteration uses start order instead. + /// Groups in arrival order, including out-of-order deliveries. Groups already held come in + /// the subscription's order, newest first unless it asks ascending, as `recvGroup` returns + /// them. The default `AsyncSequence` iteration uses start order instead. public var groupsAsArrived: AsyncThrowingStream { moqStream(cancel: { [ffi] in ffi.cancel() }) { [ffi] in (try await ffi.recvGroup()).map(GroupConsumer.init)