From 7a0273eb6c8767e18f25faa4308057e2971e2b0c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 27 Oct 2026 17:35:26 -0700 Subject: [PATCH 1/4] chore(quest): claim quest/m1/cut-audit/js-close-cause.md Quest-Claim: fe613c2b805c6eb6 From 41b7f962bd14605e77bcb47afb10268998a2e14b Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 27 Oct 2026 17:53:51 -0700 Subject: [PATCH 2/4] fix(net)!: preserve errors when closing unfinished work Co-Authored-By: GPT-6 --- js/net/api/index.api.md | 2 +- js/net/src/broadcast.test.ts | 10 +-- js/net/src/broadcast.ts | 9 ++- js/net/src/lite/connection.ts | 19 ++++-- js/net/src/lite/error.ts | 6 +- js/net/src/lite/track_stream.test.ts | 2 +- js/net/src/terminal.test.ts | 92 ++++++++++++++++++++++++++++ js/net/src/track.test.ts | 7 ++- js/net/src/track.ts | 22 +++---- quest/m1/cut-audit/js-close-cause.md | 75 ++++++++++------------- 10 files changed, 170 insertions(+), 74 deletions(-) create mode 100644 js/net/src/terminal.test.ts diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index 48487d7b159..550c115edfa 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -631,7 +631,7 @@ export namespace Track { demand(): Track.Demand; readonly name: string; get priority(): number; - reject(err?: Error): void; + reject(err: Error): void; get subscription(): Readonly; } export class Subscriber { diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index 821de20676e..8803e2bbfc3 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -1,7 +1,7 @@ import { expect, setSystemTime, test } from "bun:test"; import { Milli } from "@moq/clock"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; -import { GroupTooLarge, NotFound } from "./error.ts"; +import { GroupTooLarge, NotFound, StreamCode } from "./error.ts"; import { MAX_GROUP_FRAMES } from "./group.ts"; import { hooks } from "./internal.ts"; import { textFrame } from "./mock.ts"; @@ -161,7 +161,7 @@ test("createTrack does not take over a request a handler already pulled", async // The handler holds it, so the name stays duplicate until it answers, as in Rust. expect(() => broadcast.createTrack("media")).toThrow("duplicate track"); - request.reject(); + request.reject(new Error("request refused")); broadcast.close(); }); @@ -340,11 +340,11 @@ test("closing a broadcast rejects a dequeued request", async () => { const request = await pulled; if (!request) throw new Error("expected request"); broadcast.close(); - await expect(subscriber.info()).rejects.toThrow("track closed before info was known"); + await expect(subscriber.info()).rejects.toMatchObject({ code: StreamCode.Internal }); const producer = request.accept({ timescale: Timescale.MILLI }); expect(() => producer.appendGroup()).toThrow("track is closed"); - await expect(subscriber.info()).rejects.toThrow("track closed before info was known"); + await expect(subscriber.info()).rejects.toMatchObject({ code: StreamCode.Internal }); subscriber.close(); producer.finish(); producer.close(); @@ -735,7 +735,7 @@ test("broadcast demand watches static and pending tracks rather than broadcast h await unwanted(requested); await demand.unused(); expect(demand.used.peek()).toBe(false); - request.reject(); + request.reject(new Error("request refused")); video.finish(); video.close(); broadcast.close(); diff --git a/js/net/src/broadcast.ts b/js/net/src/broadcast.ts index e0fc0807a80..e55a52f91c6 100644 --- a/js/net/src/broadcast.ts +++ b/js/net/src/broadcast.ts @@ -5,7 +5,7 @@ */ import { type Dispose, type GetPromise, type Getter, Once, Signal } from "@moq/signals"; import type * as Epoch from "./epoch.ts"; -import { NotFound } from "./error.ts"; +import { NotFound, StreamCode, StreamError } from "./error.ts"; import type { Consumer as GroupConsumer } from "./group.ts"; import type { Route } from "./hop.ts"; import { hooks } from "./internal.ts"; @@ -149,7 +149,12 @@ function closeState(state: BroadcastState) { state.closed.set(null); state.listing.close(); for (const cleanup of state.demands.values()) cleanup(); - for (const request of state.pending) request.reject(); + for (const request of state.pending) + request.reject( + new StreamError(StreamCode.Internal, { + message: `track request ${request.name} dropped before acceptance`, + }), + ); state.requested.mutate((requests) => { requests.length = 0; }); diff --git a/js/net/src/lite/connection.ts b/js/net/src/lite/connection.ts index f1842f4871a..e570afff863 100644 --- a/js/net/src/lite/connection.ts +++ b/js/net/src/lite/connection.ts @@ -205,7 +205,7 @@ export class Connection implements Established { this.#auth.violated.subscribe((err) => { if (!err) return; closeViolation(this.#quic, err); - this.abort(); + this.#fail(err); }); this.#publisher = new Publisher(this.#quic, this.#version, this.hop, publish, { @@ -273,6 +273,12 @@ export class Connection implements Established { } } + // Set the received tracks' terminal cause before abort's deliberate local teardown. + #fail(err: Error): void { + this.#subscriber.close(err); + this.abort(); + } + async #run(): Promise { const tasks: Promise[] = [this.#runSession(), this.#runBidis(), this.#runUnis()]; @@ -312,8 +318,7 @@ export class Connection implements Established { this.#peerImplementation.resolve(undefined); // The session died under every track it was receiving, so they end with its // error. A deliberate close() already ended them cleanly, which makes this a no-op. - this.#subscriber.close(fatal ?? (await closeError(this.#quic))); - this.abort(); + this.#fail(fatal ?? (await closeError(this.#quic))); } } @@ -370,7 +375,8 @@ export class Connection implements Established { stream.writer.reset(err); // A protocol violation on one stream is the peer breaking the session. // Resetting that stream would leave it free to repeat malformed input. - if (closeViolation(this.#quic, err)) this.abort(); + const violation = closeViolation(this.#quic, err); + if (violation) this.#fail(violation); }) .finally(() => { stream.writer.close(); @@ -448,7 +454,10 @@ export class Connection implements Established { }) .catch((err: unknown) => { stream.stop(err); - if (err instanceof ProtocolViolation) closeViolation(this.#quic, err); + if (err instanceof ProtocolViolation) { + closeViolation(this.#quic, err); + this.#fail(err); + } }); } } diff --git a/js/net/src/lite/error.ts b/js/net/src/lite/error.ts index 2446931b842..65563c9e9cb 100644 --- a/js/net/src/lite/error.ts +++ b/js/net/src/lite/error.ts @@ -2,12 +2,12 @@ import { closeReason, ProtocolViolation } from "../error.ts"; import { isDecodeError } from "../util/decode_error.ts"; // Control handlers share AUTH's session-close policy; data readers never call this. -export function closeViolation(quic: WebTransport, cause: unknown): boolean { +export function closeViolation(quic: WebTransport, cause: unknown): ProtocolViolation | undefined { const err = isDecodeError(cause) && !(cause instanceof ProtocolViolation) ? new ProtocolViolation("invalid control encoding", { cause }) : cause; - if (!(err instanceof ProtocolViolation)) return false; + if (!(err instanceof ProtocolViolation)) return undefined; quic.close({ closeCode: err.code, reason: closeReason(err.message) }); - return true; + return err; } diff --git a/js/net/src/lite/track_stream.test.ts b/js/net/src/lite/track_stream.test.ts index 97bdb20ac3f..b934dc0eec4 100644 --- a/js/net/src/lite/track_stream.test.ts +++ b/js/net/src/lite/track_stream.test.ts @@ -353,7 +353,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver pair.server.close(); expect(await settlesWithin(demand.unused(), 1000)).toBe(true); - request.reject(); + request.reject(new Error("request refused")); publisher.close(); broadcast.close(); origin.close(); diff --git a/js/net/src/terminal.test.ts b/js/net/src/terminal.test.ts new file mode 100644 index 00000000000..796ae45243d --- /dev/null +++ b/js/net/src/terminal.test.ts @@ -0,0 +1,92 @@ +import { expect, test } from "bun:test"; +import { Producer as BroadcastProducer } from "./broadcast.ts"; +import { ProtocolViolation, SessionCode, StreamCode } from "./error.ts"; +import { hooks } from "./internal.ts"; +import { Connection } from "./lite/connection.ts"; +import { StreamId } from "./lite/stream.ts"; +import { ALPN_06, Version } from "./lite/version.ts"; +import { createMockTransportPair, textFrame } from "./mock.ts"; +import { Producer as OriginProducer } from "./origin.ts"; +import * as Path from "./path.ts"; +import { Stream } from "./stream.ts"; +import { Timescale } from "./time.ts"; +import { Producer as TrackProducer } from "./track.ts"; +import { wireOf } from "./wire.ts"; + +for (const release of [false, true]) { + test(`${release ? "releasing" : "closing"} a track preserves finished groups and aborts its unfinished tail`, async () => { + const producer = new TrackProducer("video").accept({ timescale: Timescale.MILLI }); + const complete = producer.appendGroup(); + complete.writeFrame(textFrame("complete")); + complete.finish(); + const tail = producer.appendGroup(); + tail.writeFrame(textFrame("prefix")); + const finished = complete.consume(); + const unfinished = tail.consume(); + producer.finish(); + try { + if (release) hooks.releaseTrack(producer); + else producer.close(); + expect(await finished.readString()).toBe("complete"); + expect(await finished.readFrame()).toBeUndefined(); + expect(await unfinished.readString()).toBe("prefix"); + await expect(unfinished.readFrame()).rejects.toMatchObject({ code: StreamCode.Cancel }); + } finally { + finished.close(); + unfinished.close(); + producer.close(); + } + }); +} + +test("an unanswered track request is refused with the dropped producer's error", async () => { + const broadcast = new BroadcastProducer(); + const requested = wireOf(broadcast).requested(); + const track = broadcast.track("absent").subscribe(); + await requested; + const info = track.info(); + broadcast.close(); + try { + await expect(info).rejects.toMatchObject({ code: StreamCode.Internal }); + expect(await track.closed).toMatchObject({ code: StreamCode.Internal }); + } finally { + track.close(); + } +}); + +test("a lite protocol violation reaches the subscribed track and its open group", async () => { + const pair = createMockTransportPair(ALPN_06); + const origin = new OriginProducer(); + const publication = origin.createBroadcast(Path.from("room")); + publication.announce(); + const producer = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + producer.appendGroup().writeFrame(textFrame("prefix")); + const url = new URL("https://example.com"); + const client = new Connection({ url, quic: pair.client, version: Version.DRAFT_06 }); + const server = new Connection({ + url, + quic: pair.server, + version: Version.DRAFT_06, + publish: origin.consume(), + client: false, + }); + const broadcast = wireOf(client).consume(Path.from("room")); + const track = broadcast.track("video").subscribe(); + const group = await track.recvGroup(); + try { + expect(await group?.readString()).toBe("prefix"); + const duplicate = await Stream.open(pair.server, { version: Version.DRAFT_06 }); + await duplicate.writer.u53(StreamId.Session); + expect((await pair.client.closed).closeCode).toBe(SessionCode.ProtocolViolation); + expect(await track.closed).toBeInstanceOf(ProtocolViolation); + await expect(group?.readFrame()).rejects.toBeInstanceOf(ProtocolViolation); + } finally { + group?.close(); + track.close(); + broadcast.close(); + client.abort(); + server.abort(); + publication.broadcast.close(); + origin.close(); + } +}); diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 85db29036dd..a19effefe30 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -1836,7 +1836,7 @@ test("withRange parks recvGroup beyond the cap and a raised cap re-offers", asyn const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }); - for (let sequence = 0; sequence < 3; sequence++) producer.createGroup(sequence); + for (let sequence = 0; sequence < 3; sequence++) producer.createGroup(sequence).finish(); track.withRange({ end: { excluded: 2 } }); expect((await track.recvGroup())?.sequence).toBe(0); @@ -2429,7 +2429,7 @@ test("a lowered range re-offers a cached cut with its error", async () => { test("a lowered range still re-offers after the producer closes", () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 1 } } }); - for (const sequence of [0, 1]) producer.createGroup(sequence); + for (const sequence of [0, 1]) producer.createGroup(sequence).finish(); expect(track.tryRecvGroup()?.sequence).toBe(1); producer.finish(); producer.close(); @@ -3448,7 +3448,8 @@ test("an evicted group still bounds, and a late group below it is unverified", a // the group and it is accepted without being trusted to time anything. const track = producer.subscribe({ maxDelay: Milli(60_000) }); expect(() => stampGroup(producer, 1, 4000)).toThrow(TimestampMismatch); - stampGroup(producer, 1, 500); + stampGroup(producer, 1, 500).finish(); + edge.finish(); producer.finish(); producer.close(); diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 5d549c4e5ae..10cdde55b28 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -386,14 +386,10 @@ export class Request { }; } - /** Reject the request, closing the track optionally with an error. */ - reject(err?: Error): void { + /** Reject the request with the error its subscribers receive. */ + reject(err: Error): void { this.#pending.delete(this); - if (err) this.#producer.abort(err); - else { - this.#producer.finish(); - this.#producer.close(); - } + this.#producer.abort(err); } } @@ -1687,13 +1683,15 @@ export class Producer { if (abort && (this.#state.outcome.peek() === null || this.#settled())) abort = undefined; // Nobody will finish these, so a subscriber that has not taken one yet never sees it. // Not evicted: a reader already holding one keeps its frames and sees the abort. - const open = abort ? this.#cache.filter((entry) => entry.group.closed.peek() === undefined) : []; + const open = this.#cache.filter((entry) => entry.group.closed.peek() === undefined); closeTrackState(this.#state, abort); if (this.#state.outcome.peek() === undefined) this.#state.outcome.set(abort ?? null); - for (const { group } of this.#cache) { - if (abort) group.abort(abort); - else group.finish(); - } + // Closing a copy never supplies the missing tail of a group. Already finished groups + // ignore the abort and stay readable; unfinished ones retain their truncation cause. + const groupError = + abort ?? + new StreamError(StreamCode.Cancel, { message: `track ${this.name} closed with unfinished groups` }); + for (const { group } of this.#cache) group.abort(groupError); for (const entry of open) { this.#unlink(entry); this.#uncache(entry); diff --git a/quest/m1/cut-audit/js-close-cause.md b/quest/m1/cut-audit/js-close-cause.md index c6914a9d9ed..933df20c237 100644 --- a/quest/m1/cut-audit/js-close-cause.md +++ b/quest/m1/cut-audit/js-close-cause.md @@ -1,48 +1,39 @@ -# [S] JS tracks end clean only on a deliberate finish +# [S] Settle received-track termination on a local session close ## Goal -In `@moq/net`, a received track or group ends cleanly only when its -publisher deliberately finished it. A local session close, a reload, a peer -protocol violation, or a request the publisher never answered ends the -affected tracks and open groups with an error, as Rust does, so players and -resumed readers recover instead of treating truncation as a finish. +Settle the received track's terminal state when the application deliberately +closes its session. State the transport, track, and unfinished-group outcomes +separately, then implement the chosen track behavior and finish this quest. ## Plan -Found by the 2026-10-24 pre-cut audit at 151a529670. All three reproduced. - -- **Local close truncates open groups** (inherited behavior, new hook): - `track.ts:1761` closes every cached group with `abort === undefined` when - `hooks.releaseTrack` (`track.ts:819`, called from `lite/subscriber.ts:1803` - and `ietf/subscriber.ts:977`) or the public `Producer.close()` runs. A - group with frame 1 still in flight reads as complete, and a resumed - reader's `Recover` never refills it. Rust `track::Producer::close` - (`rs/moq-net/src/model/track.rs:3046`) aborts open groups with a session - cancel; the JS hook's doc claims to mirror it. Abort open groups with a - cancel error and keep finished groups readable. -- **A lite protocol violation ends tracks cleanly** (new on main, from - [moq-dev/moq#5550](https://github.com/moq-dev/moq/pull/5550) and - [moq-dev/moq#5279](https://github.com/moq-dev/moq/pull/5279)): - `lite/connection.ts:365` and `:198` call the public `abort()`, which closes - the subscriber with no error and empties `#subscribes`, so the later - `close(fatal ?? closeError)` at `:307` does nothing. Add a private - `#fail(err)` that closes the subscriber with the error before closing the - transport; the public `abort()` stays clean. -- **An unanswered request ends clean and empty** (inherited): - `broadcast.ts:152` calls `request.reject()` with no error, and - `track.ts:387` turns that into a clean end at `{0,0}`. Reject with a - Dropped-coded error, matching Rust's `model/broadcast.rs:752`, and make - `Request.reject(err: Error)` require its argument. - -The audit traced a family of earlier fixes to the same root: `close()` with -no argument means clean at every layer, and each cancellation source tears -down separately (b99cad9d5c, c83c141166, 2704e10e20, 7f75925ac5, -097dc1ee62, 333d963760). Prefer one session-level terminal cause that every -teardown path reads over three more point fixes, if it stays small; the -larger JS restructure is not worth it ahead of -[rs2ts](/quest/m2/rs2ts/README.md). - -Public API: breaking. `Request.reject` requires an error (callers pass one), -and `Producer.close()` aborts groups still open. Wire: a rejected request's -error code changes. +The prepared implementation in +[moq-dev/moq#6978](https://github.com/moq-dev/moq/pull/6978) fixes the explicit +plan's three reproducible paths: unfinished groups are cancelled while +finished groups stay readable, lite protocol violations retain their error +through teardown, and an unanswered request is refused with an error rather +than inventing an empty finished track. `Request.reject` now requires its +error. Rust's `Error::Dropped` maps to INTERNAL_ERROR, which the pending +request refusal uses. + +A remaining conflict in the previous wording needs the maintainer's choice: +its Goal required local session close to error the received track, but its +Plan explicitly kept public `abort()` clean. The implementation follows the +explicit Plan and current Rust behavior: + +- Transport: the application's immediate close uses the clean session code. +- Received track: its local route closes without declaring a content end. +- Unfinished group: it ends with CANCELLED; a group the publisher finished + stays readable. + +Choose whether to retain that clean local route-close behavior or abort the +received track with CANCELLED as well. Recommend retaining the mirrored Rust +behavior, with cancellation at the unfinished-group boundary. No broader +session redesign is included; the independent FIN-and-peer-close ordering +work remains in [JS close FIN](/quest/m1/broadcast-lifecycle/js-close-fin.md). + +Public API: breaking in the prepared PR. Callers pass an error to +`Request.reject`, and finish groups before closing when they need a complete +group. Wire: unanswered requests reset with INTERNAL_ERROR instead of ending +as empty finished tracks. From 229329c42d888f2edd475c518d0b31fa4c9766b0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 27 Oct 2026 17:57:02 -0700 Subject: [PATCH 3/4] test(hang): keep the stalled group live until duration skip Co-Authored-By: GPT-6 --- js/hang/src/container/consumer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index c3f21d7b4d4..a1708929efa 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -1496,12 +1496,12 @@ test("Consumer duration-skips a stalled group once it is covered", async () => { g1.finish(); track.finish(); - track.close(); const frames = await drainFrames(consumer, 200); expect(frames.map((f) => f.timestamp as number)).toEqual([0, 33_000]); expect(frames.map((f) => f.group)).toEqual([0, 1]); consumer.close(); + track.close(); }); test("Consumer does not duration-skip when the gap is not covered", async () => { From c8100b3a61ef2ffd78c53d0f7c0ea2b141f68737 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 27 Oct 2026 18:12:07 -0700 Subject: [PATCH 4/4] docs(quest): state the remaining local-close decision Co-Authored-By: GPT-6 --- quest/m1/cut-audit/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quest/m1/cut-audit/README.md b/quest/m1/cut-audit/README.md index 6da9a61f927..c6e498034d0 100644 --- a/quest/m1/cut-audit/README.md +++ b/quest/m1/cut-audit/README.md @@ -56,7 +56,7 @@ leaving JS-only redesigns of `js/net` to [rs2ts](/quest/m2/rs2ts/README.md). - [Counted field-less `trun` entries](/quest/m1/cut-audit/fmp4-sample-resolver.md) - a moof of field-less runs cannot materialize millions of sample entries - [A reserved group survives a route returning](/quest/m1/cut-audit/reserved-route-return.md) - a route flip A to B to A no longer panics a peeked reader -- [JS tracks end clean only on a deliberate finish](/quest/m1/cut-audit/js-close-cause.md) - local close, violations, and unanswered requests end with errors +- [Settle received-track termination on a local session close](/quest/m1/cut-audit/js-close-cause.md) - choose the received track's local-close outcome after the prepared teardown error fixes - [Withdrawing a moq-transport FETCH or TRACK_STATUS ends it](/quest/m1/cut-audit/ietf-withdraw-resolve.md) - withdrawal during resolution releases the request - [A description-less AAC rendition means one thing](/quest/m1/cut-audit/aac-description-less.md) - every player and exporter agrees on the frame format - [RTMP sessions follow one strict path](/quest/m1/cut-audit/rtmp-session-strict.md) - idle sockets, repeated requests, rewinds, and stalled servers are handled