From 1e1c860b0156e59858f972cb6f89171f023d1e5b Mon Sep 17 00:00:00 2001 From: Matt McClure Date: Wed, 7 Oct 2026 21:41:24 +0000 Subject: [PATCH 1/6] fix(spf): end published tracks with PUBLISH_DONE track ended MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit moq-relay 0.17.0 reports a bare FIN on an upstream subscription as PUBLISH_DONE "internal error" to every viewer, so an intentional unpublish looked like a failed track. Send PUBLISH_DONE (TRACK_ENDED) with the exact Stream Count before the FIN, as §10.12 and MSF §11.3 intend; the relay then forwards "track ended". Track publishers count the data streams each subscription received at the subgroup-header commit, and the session adds its fill streams. A track without a counter reports the 2^64-1 unknown sentinel. A superseded subscription still ends with a bare FIN, since it is not a track end. Older moq-relay builds abort a track on any byte after SUBSCRIBE_OK and are no longer supported. --- .../templates/moq-publisher/loopback-relay.ts | 39 +++++++---- internal/design/spf/features/moq-publish.md | 12 ++-- .../spf/src/network/moqt/control-messages.ts | 15 +++- .../moqt/tests/publish-direction.test.ts | 7 ++ .../actors/tests/track-publisher.test.ts | 21 ++++++ .../spf/src/publish/actors/track-publisher.ts | 12 ++++ .../behaviors/setup-track-publishers.ts | 16 +++-- .../tests/open-publish-session.test.ts | 25 ++++--- .../tests/track-publish-stats.test.ts | 2 +- .../engines/moq/tests/cross-engine.test.ts | 10 +-- .../moq/tests/publish-transport.test.ts | 4 +- .../src/publish/session/publish-session.ts | 64 ++++++++++++----- .../session/tests/publish-session.test.ts | 70 ++++++++++++++++--- .../src/publish/tests/helpers/relay-hub.ts | 35 ++++++---- .../spf/src/publish/tests/relay-hub.test.ts | 10 ++- 15 files changed, 255 insertions(+), 87 deletions(-) diff --git a/apps/sandbox/templates/moq-publisher/loopback-relay.ts b/apps/sandbox/templates/moq-publisher/loopback-relay.ts index 0a867e1ef5..c45b216c76 100644 --- a/apps/sandbox/templates/moq-publisher/loopback-relay.ts +++ b/apps/sandbox/templates/moq-publisher/loopback-relay.ts @@ -37,6 +37,7 @@ const MESSAGE_TYPE = { REQUEST_ERROR: 0x5, REQUEST_OK: 0x7, NAMESPACE: 0x8, + PUBLISH_DONE: 0xb, NAMESPACE_DONE: 0xe, FETCH: 0x16, PUBLISH: 0x1d, @@ -662,8 +663,8 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp /** * One live upstream subscription per track: SUBSCRIBE, bind the SUBSCRIBE_OK's alias for the data-stream router, - * then hold the stream open. It ends by FIN alone (no PUBLISH_DONE exists in this flow) — the publisher's, ending - * the track for good, or our own via `handle.release()`, withdrawing a track no player watches. + * then hold the stream open. It ends with the publisher's PUBLISH_DONE and FIN, ending the track for good, or with + * our own FIN via `handle.release()`, withdrawing a track no player watches. */ const runUpstreamSubscription = async ( track: TrackBuffer, @@ -692,7 +693,7 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp const reason = fields.string(); if (errorCode === ERROR_DOES_NOT_EXIST && track.ended) { - // Done, not late: the publisher FINed this track and has + // Done, not late: the publisher ended this track and has // not re-registered it, so DOES_NOT_EXIST is terminal — // mirror the real relay, which aborts the request rather // than retrying, by ending the late subscribers. Each @@ -767,20 +768,32 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp `upstream SUBSCRIBE ${track.name} → alias ${trackAlias}${timescale === undefined ? '' : ` (timescale ${timescale})`}` ); - // Hold for the FIN — the publisher's clean track end, or our own - // release. A subscription ends by FIN *alone*: any byte after - // SUBSCRIBE_OK is a protocol violation, and the real relay - // aborts the track for every viewer — mirror that by ending each - // downstream subscription rather than silently draining. + // Hold for the end — the publisher's PUBLISH_DONE then FIN (the + // clean track end), or our own release. Anything else after + // SUBSCRIBE_OK aborts the track for every viewer. + let publishDone = false; + if (!(await reader.atEnd())) { - log(`upstream ${track.name}: data after SUBSCRIBE_OK — aborting the track for its viewers`); + const message = await readControlFrame(reader); - for (const subscriber of [...track.subscribers]) subscriber.end(); - } else if (handle.released) { + publishDone = message.type === MESSAGE_TYPE.PUBLISH_DONE && (await reader.atEnd()); + + if (!publishDone) { + log( + `upstream ${track.name}: unexpected 0x${message.type.toString(16)} after SUBSCRIBE_OK — aborting the track` + ); + + for (const subscriber of [...track.subscribers]) subscriber.end(); + + return; + } + } + + if (handle.released && !publishDone) { log(`upstream unsubscribe ${track.name} — no player interest`); } else { - // The publisher's FIN is the END of the track: propagate it — - // the same clean FIN toward every attached viewer — so no + // The publisher's PUBLISH_DONE + FIN is the END of the track: + // propagate it — a clean FIN toward every attached viewer — so no // player hangs on a dead track and a later publisher session // cannot resume stale subscriptions. The downstream teardowns' // releaseUpstream calls land after this routine's finally has diff --git a/internal/design/spf/features/moq-publish.md b/internal/design/spf/features/moq-publish.md index 1526f4b6f3..dea17ee7a0 100644 --- a/internal/design/spf/features/moq-publish.md +++ b/internal/design/spf/features/moq-publish.md @@ -49,7 +49,7 @@ none is separately composable today. |---|---|---| | Capture | Device enumeration (`devicechange`-reactive, label refresh on grant); capture-source acquisition (`getUserMedia` camera, `getDisplayMedia` + microphone-merge screen share, re-acquire on selection-identity change, stale-async guards); preview mirroring via `srcObject` (forced muted + playsInline); mute toggles via `track.enabled` (capture keeps running) | **Implemented** | | Encode | `isConfigSupported` probing over a candidate ladder (default `avc1.42E01F` in `avc` bitstream format with a `vp8` fallback; Opus with a 48 kHz fallback; `config.video.codec` prepends rather than replaces); `selectEncoderConfig` strategy resolves support → active encodings; per-kind WebCodecs encoder actors, each stamping one epoch of the kind's `TrackTimeline` — a rebuilt actor (capture-source switch, encoding change) continues the track's published clock domain plus the real monotonic acquisition gap instead of opening a fresh wallclock anchor; frame pumping with a timestamp-driven forced-keyframe cadence so **GoP = MoQ group** (`groupDurationSec`, default 2 s); LOC packaging of every chunk (Timestamp / Timescale / Config-on-keyframes) | **Implemented** | -| Transport | Publish session speaking draft-19 with **announce-and-serve ingest** (see the decision below): SETUP exchange; inbound SUBSCRIBE_NAMESPACE solicitations answered with REQUEST_OK and held as the announce carrier; the namespace announced as a NAMESPACE entry on every covering solicitation (`'live'` = announced); inbound SUBSCRIBEs answered with SUBSCRIBE_OK carrying alias = the request ID and a microsecond TIMESCALE track property; REQUEST_UPDATE routing; GOAWAY → `draining`; track end = a bare FIN of each subscription stream; close retracts the announce (NAMESPACE_DONE) and sends **no GOAWAY**; one `TrackPublisherActor` per track writing subgroup streams **only while bound to a live subscription** (video: new group per keyframe, joins at the next keyframe on bind; audio + catalog: group-per-frame; catalog replays its latest frame on every bind); MSF catalog derivation re-sent on any input-identity change | **Implemented** | +| Transport | Publish session speaking draft-19 with **announce-and-serve ingest** (see the decision below): SETUP exchange; inbound SUBSCRIBE_NAMESPACE solicitations answered with REQUEST_OK and held as the announce carrier; the namespace announced as a NAMESPACE entry on every covering solicitation (`'live'` = announced); inbound SUBSCRIBEs answered with SUBSCRIBE_OK carrying alias = the request ID and a microsecond TIMESCALE track property; REQUEST_UPDATE routing; GOAWAY → `draining`; track end = PUBLISH_DONE (TRACK_ENDED, exact Stream Count) then FIN on each subscription stream; close retracts the announce (NAMESPACE_DONE) and sends **no GOAWAY**; one `TrackPublisherActor` per track writing subgroup streams **only while bound to a live subscription** (video: new group per keyframe, joins at the next keyframe on bind; audio + catalog: group-per-frame; catalog replays its latest frame on every bind); MSF catalog derivation re-sent on any input-identity change | **Implemented** | | Observability | ~1 Hz `publishStats` sampling from the encoder actor counters (`encodedFps`, bitrates, `droppedFrames`, `bytesSent`) | **Implemented** — `droppedGroups` is counted on the track publishers but not yet folded into `publishStats`; `subscriberCount` is tracked on the session actor but surfaces as `NaN` | ### Ingest model: announce-and-serve (2026-08-07) @@ -78,10 +78,12 @@ own reference clients use: next keyframe; the catalog track replays its latest frame on every bind because catalog frames flow on change, and a fresh subscription must not wait for the next one. -- **Three peer-verified teardown rules** (moq-relay 0.14.7 source): - a track ends by a bare FIN of the subscription stream — any trailing - byte (the old PUBLISH_DONE) makes the relay *abort* the track for - every viewer; a client GOAWAY closes the whole session (code 17); and +- **Three peer-verified teardown rules**: a track ends with + PUBLISH_DONE (TRACK_ENDED, exact Stream Count) then a FIN of the + subscription stream — moq-relay 0.17.0 forwards that as "track ended", + but reports a bare FIN as "internal error" (older moq-relay builds + abort the track on any byte after SUBSCRIBE_OK; they are not + supported); a client GOAWAY closes the whole session (code 17); and SUBSCRIBE_OK should declare the TIMESCALE track property or the relay discards object TIMESTAMP extensions and re-stamps frames on arrival. - **Per-stream failures are ordinary lifecycle now** — the relay resets diff --git a/packages/spf/src/network/moqt/control-messages.ts b/packages/spf/src/network/moqt/control-messages.ts index 5329201dd6..d759f2030d 100644 --- a/packages/spf/src/network/moqt/control-messages.ts +++ b/packages/spf/src/network/moqt/control-messages.ts @@ -1028,12 +1028,21 @@ export function encodeSubscribeOk( return frameMessage(MESSAGE_TYPE.SUBSCRIBE_OK, body); } -/** PUBLISH_DONE (§10.12). */ -export function encodePublishDone(statusCode: number, streamCount: number, reason = ''): Uint8Array { +/** 2^64−1, PUBLISH_DONE's "unknown" Stream Count, has one encoding: the 9-byte form with every bit set. */ +const UNKNOWN_STREAM_COUNT = new Uint8Array(9).fill(0xff); + +/** + * PUBLISH_DONE (§10.12). An `undefined` Stream Count is the publisher that cannot count its streams, encoded as the + * 2^64−1 sentinel the draft mandates (and `readCountVarint` reads back as `undefined`). + */ +export function encodePublishDone(statusCode: number, streamCount: number | undefined, reason = ''): Uint8Array { const body = new ByteWriter(); body.writeVarint(statusCode); - body.writeVarint(streamCount); + + if (streamCount === undefined) body.writeBytes(UNKNOWN_STREAM_COUNT); + else body.writeVarint(streamCount); + writeReasonPhrase(body, reason); return frameMessage(MESSAGE_TYPE.PUBLISH_DONE, body); } diff --git a/packages/spf/src/network/moqt/tests/publish-direction.test.ts b/packages/spf/src/network/moqt/tests/publish-direction.test.ts index e23394ff33..faf05148f9 100644 --- a/packages/spf/src/network/moqt/tests/publish-direction.test.ts +++ b/packages/spf/src/network/moqt/tests/publish-direction.test.ts @@ -66,6 +66,13 @@ describe('encodePublishDone', () => { reason: 'stopped', }); }); + + it('encodes an unknown stream count as the 2^64−1 sentinel', () => { + const bytes = encodePublishDone(PUBLISH_DONE_STATUS.TRACK_ENDED, undefined); + + expect(bytes.subarray(-10, -1)).toEqual(new Uint8Array(9).fill(0xff)); + expect(decodeOne(bytes)).toMatchObject({ kind: 'publish-done', streamCount: undefined, reason: '' }); + }); }); describe('encodeSubscribeOk', () => { diff --git a/packages/spf/src/publish/actors/tests/track-publisher.test.ts b/packages/spf/src/publish/actors/tests/track-publisher.test.ts index c0228255f4..c68c812126 100644 --- a/packages/spf/src/publish/actors/tests/track-publisher.test.ts +++ b/packages/spf/src/publish/actors/tests/track-publisher.test.ts @@ -338,6 +338,27 @@ describe('createTrackPublisherActor', () => { ]); }); + it('counts the data streams opened under each subscription alias', async () => { + const factory = makeStreamFactory(); + const publisher = createTrackPublisherActor({ openUniStream: factory.openUniStream, groupPerFrame: true }); + const frame = (timestampUs: number) => + ({ type: 'frame', payload: new Uint8Array([1]), properties: [], keyframe: true, timestampUs }) as const; + + // Unbound frames open nothing and count for no one. + publisher.send(frame(0)); + publisher.send({ type: 'bind', trackAlias: 3 }); + publisher.send(frame(1)); + publisher.send(frame(2)); + await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(2)); + + publisher.send({ type: 'bind', trackAlias: 5 }); + publisher.send(frame(3)); + await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(3)); + + expect([publisher.streamCount(3), publisher.streamCount(5), publisher.streamCount(7)]).toEqual([2, 1, 0]); + publisher.destroy(); + }); + it('ignores delta frames before the first keyframe', async () => { const factory = makeStreamFactory(); const publisher = createTrackPublisherActor({ openUniStream: factory.openUniStream }); diff --git a/packages/spf/src/publish/actors/track-publisher.ts b/packages/spf/src/publish/actors/track-publisher.ts index b9397d7c47..b4429efe46 100644 --- a/packages/spf/src/publish/actors/track-publisher.ts +++ b/packages/spf/src/publish/actors/track-publisher.ts @@ -111,6 +111,12 @@ export interface TrackPublisherActor extends MessageActor< * as it is written.) */ flushed(): Promise; + /** + * Data streams opened under the subscription bound as `trackAlias` — PUBLISH_DONE's Stream Count (§10.12). Counted at + * the commit to writing the subgroup header (the `openedGroups` boundary), so a stream reset before its header — one + * the peer cannot attribute to the subscription — is excluded. + */ + streamCount(trackAlias: number): number; } export interface TrackPublisherOptions { @@ -191,6 +197,8 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track let currentGroupFrames: Extract[] = []; /** Detached FIN settlements (see `finishCell`) — `flushed()` waits on them past the runner. */ const pendingFins = new Set>(); + /** Opened data streams per subscription alias (see `streamCount`). */ + const streamsByAlias = new Map(); // Assigned right after createMachineActor returns; the runner tasks only // complete asynchronously, well after construction. @@ -296,6 +304,7 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track // counting at queue time inflated the opened-stream count with // groups that were dropped before they ever opened one. inner?.send({ type: 'group-opened' }); + streamsByAlias.set(cell.trackAlias, (streamsByAlias.get(cell.trackAlias) ?? 0) + 1); cell.writer = createSubgroupWriter(stream, { trackAlias: cell.trackAlias, groupId: cell.groupId, @@ -590,6 +599,9 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track await runner.settled; await Promise.all(pendingFins); }, + streamCount(trackAlias: number): number { + return streamsByAlias.get(trackAlias) ?? 0; + }, destroy(): void { // Every opened stream must end deterministically: the open group // (or the one `{type:'end'}` just closed gracefully) gets a diff --git a/packages/spf/src/publish/behaviors/setup-track-publishers.ts b/packages/spf/src/publish/behaviors/setup-track-publishers.ts index ae966a87b3..844a54ff0f 100644 --- a/packages/spf/src/publish/behaviors/setup-track-publishers.ts +++ b/packages/spf/src/publish/behaviors/setup-track-publishers.ts @@ -21,9 +21,10 @@ * Cluster-owner reactor per the per-type setup-actor convention: the encoder chunk router (the engine's default * `chunkSink`) and `deriveCatalog` only read the slots — they never create the actors. On session loss, endpoint * change, or teardown the actors are destroyed in reverse creation order, each track's live subscriptions get their - * clean FIN (`handle.end()`), and the slots are cleared. When the session is still serving at teardown, the broadcast - * is ending on purpose, so the catalog track's last group is the MSF end-of-broadcast catalog (§11.3) — never on a - * session loss, which may yet reconnect and must not mark the broadcast complete. + * clean end — PUBLISH_DONE with TRACK_ENDED, then FIN (`handle.end()`) — and the slots are cleared. When the session is + * still serving at teardown, the broadcast is ending on purpose, so the catalog track's last group is the MSF + * end-of-broadcast catalog (§11.3) — never on a session loss, which may yet reconnect and must not mark the broadcast + * complete. * * Sole writer of the track-publisher context slots (the four media slots plus `dataTrackProducers`). Per-stream * failures are deliberately not surfaced as `publishError` anymore: under pull-through ingest the peer resets in-flight @@ -317,6 +318,9 @@ function addTrackPublisher( return largestGroupId >= 0 ? { group: largestGroupId, object: largestObjectId } : undefined; }, + // ...and the streams it opened per subscription, for the Stream Count + // a track end reports in PUBLISH_DONE (§10.12). + getStreamCount: (trackAlias) => publisher.streamCount(trackAlias), }); cluster.created.push({ handle, publisher, boundAlias: undefined }); @@ -472,10 +476,8 @@ function setupTrackPublishersSetup({ } // Quiesce: 'end' FINs the open group, then the track's - // live subscriptions get their clean stream FIN (the - // clean track end — no trailing message; a relay - // aborts the track on any post-SUBSCRIBE_OK byte), then - // destroy() force-ends whatever is left. + // live subscriptions get PUBLISH_DONE (TRACK_ENDED) and + // a FIN, then destroy() force-ends whatever is left. publisher.send({ type: 'end' }); handle.end(); publisher.destroy(); diff --git a/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts b/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts index 84b3bd15a5..248aee5f7a 100644 --- a/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts +++ b/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { createComposition } from '../../../core/composition/create-composition'; import { signal } from '../../../core/signals/primitives'; +import { PUBLISH_DONE_STATUS } from '../../../network/moqt/control-messages'; import { createMoqtSession } from '../../../network/moqt/session'; import { type RawRequest, rawSubscribe, solicitNamespace } from '../../../network/moqt/tests/helpers/raw-peer'; import { createTransportPair, type TransportPair } from '../../../network/moqt/tests/helpers/transport-pair'; @@ -217,7 +218,7 @@ describe('openPublishSession', () => { }); // Hold live subscriptions on both tracks so the teardown's clean - // end (a bare stream FIN) is observable, and open one video group + // end (PUBLISH_DONE + FIN) is observable, and open one video group // so an in-flight data stream rides through the teardown too. subscriptions.catalog = await rawSubscribe(pair.server, ENDPOINT.namespace, 'catalog', 11); subscriptions.video = await rawSubscribe(pair.server, ENDPOINT.namespace, 'video', 13); @@ -237,7 +238,17 @@ describe('openPublishSession', () => { return { composition, subscriptions, goLive }; } - it('FINs every track subscription cleanly when the composition is destroyed', async () => { + /** The clean track end: PUBLISH_DONE with TRACK_ENDED, then FIN. Video carried exactly the one group `goLive` sent. */ + function expectTrackEnded(subscriptions: { catalog: RawRequest; video: RawRequest }) { + for (const subscription of [subscriptions.catalog, subscriptions.video]) { + expect(subscription.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); + expect(subscription.received[1]).toMatchObject({ statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED }); + } + + expect(subscriptions.video.received[1]).toMatchObject({ streamCount: 1 }); + } + + it('ends every track subscription cleanly when the composition is destroyed', async () => { const pair = createTransportPair(); const { composition, subscriptions, goLive } = makeTransportStage(pair); @@ -250,13 +261,10 @@ describe('openPublishSession', () => { expect(subscriptions.catalog.ended()).toBe(true); expect(subscriptions.video.ended()).toBe(true); }); - // A bare FIN is the clean track end — any trailing message - // (the old PUBLISH_DONE) makes moq-lite-rs abort the track instead. - expect(subscriptions.catalog.received.map((m) => m.kind)).toEqual(['subscribe-ok']); - expect(subscriptions.video.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expectTrackEnded(subscriptions); }); - it('FINs every track subscription when unpublish collapses the gate', async () => { + it('ends every track subscription cleanly when unpublish collapses the gate', async () => { const pair = createTransportPair(); const { composition, subscriptions, goLive } = makeTransportStage(pair); @@ -268,8 +276,7 @@ describe('openPublishSession', () => { expect(subscriptions.catalog.ended()).toBe(true); expect(subscriptions.video.ended()).toBe(true); }); - expect(subscriptions.catalog.received.map((m) => m.kind)).toEqual(['subscribe-ok']); - expect(subscriptions.video.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expectTrackEnded(subscriptions); // An orderly stop, not a failure. await vi.waitFor(() => { expect(composition.state.sessionStatus.get()).toBe('closed'); diff --git a/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts b/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts index 99dc918b7e..0e57ca7d9c 100644 --- a/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts +++ b/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts @@ -83,7 +83,7 @@ function makePublisher(counters: Partial): TrackPublishe context: { ...ZERO_PUBLISHER_COUNTERS, ...counters }, }); - return { snapshot, send: () => {}, flushed: async () => {}, destroy: () => {} }; + return { snapshot, send: () => {}, flushed: async () => {}, streamCount: () => 0, destroy: () => {} }; } function makeSessionActor(subscriberCount: number): PublishSessionActor { diff --git a/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts b/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts index 873979335a..855f1496db 100644 --- a/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts +++ b/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { PUBLISH_DONE_STATUS } from '../../../../network/moqt/control-messages'; import { createRelayHub } from '../../../tests/helpers/relay-hub'; import { createMoqPublishEngine } from '../engine'; import { createSubscriber, makeSyntheticStream } from './helpers/cross-engine-harness'; @@ -219,13 +220,14 @@ describe('publish engine ↔ playback engine (relay hub)', () => { expect(hub.publisherConnections()).toBe(connectionsBeforeScreen); expect(publisher.state.sessionStatus.get()).toBe('live'); - // Orderly unpublish ends every track — now including screen — by - // FINing the hub's subscribe streams (a bare FIN is the clean track - // end; PUBLISH_DONE never appears under announce-and-serve). + // Orderly unpublish ends every track — now including screen — with + // PUBLISH_DONE (TRACK_ENDED) and a FIN on the hub's subscribe streams. publisher.state.publishActivated.set(false); await vi.waitFor( () => { - const endedTracks = hub.trackEnds.filter((end) => end.kind === 'subscribe-fin').map((end) => end.trackName); + const endedTracks = hub.trackEnds + .filter((end) => end.kind === 'track-end' && end.statusCode === PUBLISH_DONE_STATUS.TRACK_ENDED) + .map((end) => (end.kind === 'track-end' ? end.trackName : '')); expect(endedTracks).toContain('video'); expect(endedTracks).toContain('screen'); diff --git a/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts b/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts index 9eb853514b..2db841da2e 100644 --- a/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts +++ b/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts @@ -221,8 +221,8 @@ describe('MoqPublishMediaMixin transport (M3)', () => { expect(overlay.objects[0]!.objectId).toBe(0); // Unpublish: the announce is retracted with NAMESPACE_DONE on the - // solicitation stream (each subscribe stream ends with a bare FIN — - // PUBLISH_DONE never appears) and the session returns to idle. + // solicitation stream (each subscribe stream ends with PUBLISH_DONE + // and a FIN) and the session returns to idle. media.unpublish(); await vi.waitFor( () => { diff --git a/packages/spf/src/publish/session/publish-session.ts b/packages/spf/src/publish/session/publish-session.ts index 769e2bfd49..5bcf0b210d 100644 --- a/packages/spf/src/publish/session/publish-session.ts +++ b/packages/spf/src/publish/session/publish-session.ts @@ -12,11 +12,12 @@ * (upstream `de336492`: every PUBLISH is answered with a request error), and it solicits namespaces itself — one * SUBSCRIBE_NAMESPACE per authorized prefix, sent immediately after SETUP. Announcing rides the solicitation stream as * NAMESPACE entries (suffix-relative, parameterless — the relay treats even an empty parameter count as malformed); - * data flows only on aliases bound by our own SUBSCRIBE_OKs, per subscription. Three hard-won peer constraints shape - * the teardown paths: a subscription ends by FIN alone (any byte after SUBSCRIBE_OK — a PUBLISH_DONE, say — makes the - * relay abort the track for every viewer instead of finishing it), a client-sent GOAWAY closes the whole session (code - * 17), and a track alias bound to two live request IDs closes it too (code 12) — so aliases are the peer's own request - * IDs, unique by construction. + * data flows only on aliases bound by our own SUBSCRIBE_OKs, per subscription. A track end sends each subscription + * PUBLISH_DONE (TRACK_ENDED, with the exact count of data streams it received) and then FINs it — moq-relay 0.17.0 + * forwards that downstream as "track ended", where a bare FIN reaches viewers as "internal error" (older moq-relay + * builds abort the track on any byte after SUBSCRIBE_OK; they are not supported). Two more hard-won peer constraints + * shape the teardown paths: a client-sent GOAWAY closes the whole session (code 17), and a track alias bound to two + * live request IDs closes it too (code 12) — so aliases are the peer's own request IDs, unique by construction. * * Deliberately callback-shaped with NO signals, mirroring the subscribe driver — signal awareness enters at the * `publish/` behavior layer through the actor below. Lives in `publish/` rather than `network/moqt` so the parent-owned @@ -32,6 +33,7 @@ import { decodeControlMessage, encodeNamespace, encodeNamespaceDone, + encodePublishDone, encodeRequestError, encodeRequestOk, encodeSetup, @@ -41,6 +43,7 @@ import { type KeyValuePair, type Location, MESSAGE_TYPE, + PUBLISH_DONE_STATUS, type MessageParameters, MOQT_PROTOCOL_ID, REQUEST_ERROR_CODE, @@ -118,13 +121,18 @@ export interface RegisterTrackOptions { * parameter is left off. */ getLargestObject?: () => Location | undefined; + /** + * Data streams opened under the subscription with this alias — the PUBLISH_DONE Stream Count (§10.12) the track's end + * reports, plus the fill streams the session opens itself. Omitted, the count is reported as unknown (2^64−1). + */ + getStreamCount?: (trackAlias: number) => number; } export interface RegisteredTrack { readonly trackName: string; /** - * End the track: FIN every live subscription's request stream (a FIN with no trailing bytes is the clean track end) - * and refuse future SUBSCRIBEs with DOES_NOT_EXIST. Idempotent. + * End the track: send every live subscription PUBLISH_DONE with TRACK_ENDED and its Stream Count, FIN its request + * stream, and refuse future SUBSCRIBEs with DOES_NOT_EXIST. Idempotent. * * `after` holds the FINs (not the refusal) until it settles, so a last object still in flight — the MSF * end-of-broadcast catalog — reaches subscribers before their subscription ends. An orderly `close()` waits on it @@ -171,7 +179,10 @@ export const CLOSE_FLUSH_TIMEOUT_MS = 250; interface SubscriberStream { requestId: number; trackAlias: number; + /** Bare FIN — ends a subscription the peer superseded, which is not a track end. */ fin(): Promise; + /** PUBLISH_DONE, then FIN — the track ended (§10.12). */ + done(statusCode: number, streamCount: number | undefined): Promise; cancel(): Promise; /** SUBSCRIBE_OK reached the wire — only accepted subscriptions may carry the binding. */ accepted: boolean; @@ -182,6 +193,8 @@ interface SubscriberStream { finished: boolean; /** Includes pending stream opens, so cancellation also catches late arrivals. */ fills: Set; + /** Fill streams opened for this subscription — they count toward PUBLISH_DONE's Stream Count. */ + fillStreams: number; } interface FillStream { @@ -203,6 +216,8 @@ interface TrackRecord { doneFlushed?: Promise; /** Reads the track's Largest Object for responses (see `RegisterTrackOptions.getLargestObject`). */ getLargestObject?: () => Location | undefined; + /** Reads a subscription's data-stream count (see `RegisterTrackOptions.getStreamCount`). */ + getStreamCount?: (trackAlias: number) => number; } /** One accepted inbound SUBSCRIBE_NAMESPACE — the announce carrier. */ @@ -358,11 +373,11 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { } /** - * Orderly close: closing the transport discards queued data (WebTransport semantics), so the subscription FINs and - * NAMESPACE_DONE retractions must be given a bounded window to land first — a peer should observe every track ending - * cleanly, not an abrupt transport end. Neither GOAWAY nor PUBLISH_DONE is sent: moq-lite-rs closes the session on a - * client GOAWAY, and treats any post-SUBSCRIBE_OK byte on a subscribe stream as an error that aborts the track (see - * the module doc). + * Orderly close: closing the transport discards queued data (WebTransport semantics), so the track ends (PUBLISH_DONE + * + * - FIN per subscription) and NAMESPACE_DONE retractions must be given a bounded window to land first — a peer should + * observe every track ending cleanly, not an abrupt transport end. No GOAWAY is sent: moq-lite-rs closes the + * session on a client GOAWAY (see the module doc). */ async #drainAndClose(closeCode: number, reason: string): Promise { // One macrotask beat before the last-resort sweep below: track owners @@ -501,6 +516,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { done: false, pendingFins: [], getLargestObject: options.getLargestObject, + getStreamCount: options.getStreamCount, }; this.#tracks.set(track.key, track); @@ -520,9 +536,9 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { } /** - * FIN every live subscription's request stream — with no trailing bytes, which is the clean track end — and refuse - * future SUBSCRIBEs. The aggregated write completion lands on `track.doneFlushed` so `close()` can hold the transport - * open until the FINs reach the wire. + * End every live subscription with PUBLISH_DONE (TRACK_ENDED) and a FIN, and refuse future SUBSCRIBEs. The aggregated + * write completion lands on `track.doneFlushed` so `close()` can hold the transport open until the ends reach the + * wire. */ #endTrack(track: TrackRecord, after?: Promise): void { if (track.done) return; @@ -547,7 +563,13 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { for (const subscriber of track.subscribers) { if (!subscriber.finished) { subscriber.finished = true; - writes.push(subscriber.fin().catch(() => {})); + // Read at the end, not at subscribe time: the count must cover + // every stream the subscription received (§10.12). + const streamCount = track.getStreamCount + ? track.getStreamCount(subscriber.trackAlias) + subscriber.fillStreams + : undefined; + + writes.push(subscriber.done(PUBLISH_DONE_STATUS.TRACK_ENDED, streamCount).catch(() => {})); } // The local end is authoritative: report each live subscription @@ -644,6 +666,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { // writes a header it cannot preserve through the reset. if (!hasMethods(writer, ['commit'])) return; + subscriber.fillStreams++; await writer.write(encodeFetchHeader(requestId)); if (!subscriber.fills.has(fill) || subscriber.finished) return; @@ -985,6 +1008,11 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { this.#resetFills(subscriber); return writer.close(); }, + done: async (statusCode, streamCount) => { + this.#resetFills(subscriber); + await writer.write(encodePublishDone(statusCode, streamCount)); + await writer.close(); + }, cancel: async () => { subscriber.finished = true; this.#resetFills(subscriber); @@ -1003,6 +1031,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { forwarding: subscribe.parameters.forward !== 0, finished: false, fills: new Set(), + fillStreams: 0, }; // Use one snapshot for both the response and its fill range, even if @@ -1169,8 +1198,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { } else { // The subscribe driver treats REQUEST_OK as the update's // completion (`onUpdateOk`). Strictly reactive: a peer that - // never sends REQUEST_UPDATE (moq-lite-rs parks on end-of- - // stream after SUBSCRIBE_OK) never sees a trailing byte. + // never sends REQUEST_UPDATE sees nothing here. void writer.write(encodeRequestOk(largestObject ? { largestObject } : {})).catch(() => {}); if (fillRequested) this.#openAndResetFill(message.requestId, subscriber); diff --git a/packages/spf/src/publish/session/tests/publish-session.test.ts b/packages/spf/src/publish/session/tests/publish-session.test.ts index de352ea07f..c9e4fdb77d 100644 --- a/packages/spf/src/publish/session/tests/publish-session.test.ts +++ b/packages/spf/src/publish/session/tests/publish-session.test.ts @@ -14,6 +14,7 @@ import { encodeRequestUpdate, encodeSetup, encodeSubscribe, + PUBLISH_DONE_STATUS, REQUEST_ERROR_CODE, SETUP_OPTION, TRACK_PROPERTY, @@ -534,7 +535,7 @@ describe('createMoqtPublishSession', () => { subscriber.destroy(); }); - it('ends a track by FINing its subscription streams with no trailing message', async () => { + it('ends a track with PUBLISH_DONE (TRACK_ENDED and the stream count), then FIN', async () => { const endedRequests: number[] = []; const bindings: (number | undefined)[] = []; const { pair, session, subscriber } = makePublishHarness({ @@ -543,7 +544,11 @@ describe('createMoqtPublishSession', () => { }); await session.ready; - const track = session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'video' }); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getStreamCount: (trackAlias) => (trackAlias === 21 ? 4 : 0), + }); const subscribe = await rawSubscribe(pair.server, 'video', 21); @@ -560,10 +565,10 @@ describe('createMoqtPublishSession', () => { await vi.waitFor(() => { expect(subscribe.ended()).toBe(true); }); - // A bare FIN is the clean track end. Any byte after - // SUBSCRIBE_OK — the old PUBLISH_DONE — makes moq-lite-rs abort the - // track for every downstream viewer instead of finishing it. - expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + // moq-relay 0.17.0 forwards this as "track ended"; a bare FIN + // reaches viewers as "internal error". + expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); + expect(subscribe.received[1]).toMatchObject({ statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, streamCount: 4 }); // The peer closing its side afterwards must not double-report. void subscribe.fin(); @@ -600,7 +605,13 @@ describe('createMoqtPublishSession', () => { await vi.waitFor(() => { expect(subscribe.ended()).toBe(true); }); - expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + // No stream-count source registered: the count is the 2^64−1 + // "unknown" sentinel, which decodes as undefined. + expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); + expect(subscribe.received[1]).toMatchObject({ + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: undefined, + }); subscriber.destroy(); }); @@ -1088,6 +1099,45 @@ describe('createMoqtPublishSession', () => { await finish(); }); + it('counts fill fetch streams in the PUBLISH_DONE Stream Count (§10.12)', async () => { + const { pair, session, fills, finish } = await makeFillHarness(); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getLargestObject: () => ({ group: 4, object: 2 }), + getStreamCount: () => 3, + }); + const request = await openRawRequest( + pair.server, + encodeSubscribe({ + requestId: 207, + trackNamespace: NAMESPACE, + trackName: 'video', + parameters: { + forward: 1, + locationFilter: { type: 'next-object' }, + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + }, + }) + ); + + await vi.waitFor(() => { + expect(fills).toEqual([{ requestId: 207, reset: true }]); + }); + + track.end(); + await vi.waitFor(() => { + expect(request.ended()).toBe(true); + }); + // Three data streams from the track publisher plus the reset fill. + expect(request.received.at(-1)).toMatchObject({ + kind: 'publish-done', + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: 4, + }); + await finish(); + }); + it('opens no fill fetch stream for an empty fill range (§5.1.3)', async () => { const { pair, session, fills, finish } = await makeFillHarness(); let largest: { group: number; object: number } | undefined; @@ -1432,12 +1482,12 @@ describe('createMoqtPublishSession', () => { session.close(); await vi.waitFor(() => { - // The announce is retracted and the subscription FINed cleanly - // before the transport goes away. + // The announce is retracted and the track ended cleanly before the + // transport goes away. expect(solicitation.received.map((m) => m.kind)).toEqual(['request-ok', 'namespace', 'namespace-done']); expect(subscribe.ended()).toBe(true); }); - expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); expect(controlFrames.map((m) => m.kind)).toEqual(['setup']); }); diff --git a/packages/spf/src/publish/tests/helpers/relay-hub.ts b/packages/spf/src/publish/tests/helpers/relay-hub.ts index a1bb7925bb..271e8c61a4 100644 --- a/packages/spf/src/publish/tests/helpers/relay-hub.ts +++ b/packages/spf/src/publish/tests/helpers/relay-hub.ts @@ -8,8 +8,8 @@ * one upstream SUBSCRIBE per track (downstream demand dedupes onto it), with the publisher's SUBSCRIBE_OK assigning the * alias its subgroup data streams carry. A proactive PUBLISH is answered with REQUEST_ERROR 400 "PUBLISH is not * supported" exactly like the real relay, so a regression to the old ingest model fails loudly. The publisher ends a - * track by FINing the hub's SUBSCRIBE stream — no PUBLISH_DONE ever arrives — and retracts a namespace with - * NAMESPACE_DONE; both land in `trackEnds`, the churn signal the source-switch regression tests assert on. + * track with PUBLISH_DONE and a FIN on the hub's SUBSCRIBE stream, and retracts a namespace with NAMESPACE_DONE; both + * land in `trackEnds`, the churn signal the source-switch regression tests assert on. * * Subscriber side (`connectSubscriber`): answers SUBSCRIBE with SUBSCRIBE_OK (carrying LARGEST_OBJECT once the track * has content) and forwards objects one-per-subgroup-stream, resolving the request's Location Filter (draft-20 §5.1.2) @@ -17,8 +17,9 @@ * (catalog joins), `relative-group 0` forwards only groups that start after the subscribe (video joins), and * `next-object` is strict: nothing already published is replayed (audio joins). FETCH is answered with REQUEST_ERROR; * the draft-20 player never sends one. A downstream subscribe registers standing upstream demand for its track; an - * upstream FIN ends the track's downstream subscriptions with PUBLISH_DONE, the way a real relay ends the track for - * every viewer. + * upstream end ends the track's downstream subscriptions with PUBLISH_DONE, the way a real relay ends the track for + * every viewer — forwarding the publisher's status like moq-relay 0.17.0, which reports a bare FIN (no PUBLISH_DONE) as + * INTERNAL_ERROR. * * Tracks and demand persist across publisher sessions (a reconnecting publisher is re-solicited and its demanded tracks * re-subscribed), so the hub can also observe teardown/reconnect churn instead of crashing on it. @@ -83,12 +84,12 @@ interface TrackRecord { } /** - * One upstream end observed from the publisher. Under announce-and-serve there is no PUBLISH_DONE: a bare FIN on the - * hub's SUBSCRIBE stream is the clean track end, and NAMESPACE_DONE retracts an announce. These replace the old - * `publishDones` as the source-switch churn signal. + * One upstream end observed from the publisher: a track's SUBSCRIBE stream ending cleanly (with the PUBLISH_DONE that + * preceded the FIN, if any — `statusCode` is `undefined` for a bare FIN), or NAMESPACE_DONE retracting an announce. The + * source-switch churn signal. */ export type ObservedTrackEnd = - | { kind: 'subscribe-fin'; trackName: string } + | { kind: 'track-end'; trackName: string; statusCode: number | undefined; streamCount?: number | undefined } | { kind: 'namespace-done'; namespace: TrackNamespace }; export interface RelayHub { @@ -308,8 +309,8 @@ export function createRelayHub( /** * Pull one announced track: a fresh bidi stream per SUBSCRIBE, alias recorded from the publisher's SUBSCRIBE_OK, - * held open until one side ends it. A bare FIN from the publisher is the clean track end — recorded as churn, and - * forwarded to the track's downstream subscribers as PUBLISH_DONE the way a real relay ends the track. + * held open until one side ends it. The publisher's FIN (after its PUBLISH_DONE) is the track end — recorded as + * churn, and forwarded to the track's downstream subscribers as PUBLISH_DONE the way a real relay ends the track. */ const subscribeUpstream = (trackName: string): void => { if (destroyed || connectionClosed || upstreamTracks.has(trackName)) return; @@ -325,6 +326,7 @@ export function createRelayHub( nextRequestId += 2; const track = trackFor(trackName); let accepted = false; + let publishDone: Extract | undefined; try { await writer.write( @@ -352,6 +354,8 @@ export function createRelayHub( if (message.kind === 'subscribe-ok') { accepted = true; aliasToTrack.set(message.trackAlias, track); + } else if (message.kind === 'publish-done') { + publishDone = message; } else if (message.kind === 'request-error') { // DOES_NOT_EXIST usually means the demand raced the // publisher's registerTrack — retry while the demand stands @@ -365,9 +369,16 @@ export function createRelayHub( } if (accepted) { - trackEnds.push({ kind: 'subscribe-fin', trackName }); + trackEnds.push({ + kind: 'track-end', + trackName, + statusCode: publishDone?.statusCode, + streamCount: publishDone?.streamCount, + }); + + const status = publishDone?.statusCode ?? PUBLISH_DONE_STATUS.INTERNAL_ERROR; - for (const subscriber of [...track.subscribers]) subscriber.end(PUBLISH_DONE_STATUS.TRACK_ENDED); + for (const subscriber of [...track.subscribers]) subscriber.end(status); track.subscribers.clear(); } diff --git a/packages/spf/src/publish/tests/relay-hub.test.ts b/packages/spf/src/publish/tests/relay-hub.test.ts index 80be5135f4..d90ee928c5 100644 --- a/packages/spf/src/publish/tests/relay-hub.test.ts +++ b/packages/spf/src/publish/tests/relay-hub.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vite-plus/test'; +import { PUBLISH_DONE_STATUS } from '../../network/moqt/control-messages'; import { createSubgroupWriter } from '../../network/moqt/subgroup-writer'; import { createMoqtPublishSession } from '../session/publish-session'; import { createRelayHub } from './helpers/relay-hub'; @@ -78,11 +79,14 @@ describe('createRelayHub', () => { expect(served).toEqual(['video']); }); - // The publisher ends the track: a bare FIN on the hub's SUBSCRIBE - // stream, recorded as the churn signal. + // The publisher ends the track: PUBLISH_DONE + FIN on the hub's + // SUBSCRIBE stream, recorded as the churn signal. No stream-count + // source was registered, so the count is unknown. first.end(); await vi.waitFor(() => { - expect(hub.trackEnds).toEqual([{ kind: 'subscribe-fin', trackName: 'video' }]); + expect(hub.trackEnds).toEqual([ + { kind: 'track-end', trackName: 'video', statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, streamCount: undefined }, + ]); }); // The same name comes back in the same session — the churn shape the From f4e6977dcfc1d61283c62c8f4ca2b4cc4e195b39 Mon Sep 17 00:00:00 2001 From: Matt McClure Date: Wed, 7 Oct 2026 21:56:16 +0000 Subject: [PATCH 2/6] fix(spf): close a track's data streams before its PUBLISH_DONE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Draft-20 §10.12: a sender MUST NOT send PUBLISH_DONE until it has closed every stream for the subscription. Media teardown wrote PUBLISH_DONE while the open group's FIN was still queued, and the catalog path raced destroy() against it on a flush timeout. Every track now ends the same way: end, a bounded flush (half the close drain, so PUBLISH_DONE still fits), destroy() to FIN or reset what is left, then PUBLISH_DONE and FIN. Also prune superseded aliases from the per-subscription stream counts on each new bind, keeping the current alias across a Forward State toggle. --- internal/design/spf/features/moq-publish.md | 7 ++- .../actors/tests/track-publisher.test.ts | 15 ++++- .../spf/src/publish/actors/track-publisher.ts | 10 +++- .../behaviors/setup-track-publishers.ts | 57 ++++++++++--------- .../tests/setup-track-publishers.test.ts | 37 ++++++++++++ 5 files changed, 93 insertions(+), 33 deletions(-) diff --git a/internal/design/spf/features/moq-publish.md b/internal/design/spf/features/moq-publish.md index dea17ee7a0..8c69433b9a 100644 --- a/internal/design/spf/features/moq-publish.md +++ b/internal/design/spf/features/moq-publish.md @@ -146,7 +146,7 @@ Behaviors (`packages/spf/src/publish/behaviors/`; DOM-bound ones under | `pumpMediaFrames` | `dom/pump-media-frames.ts` | `MediaStreamTrackProcessor` read loops → `encode` messages; keyframe cadence | | `trackPublishStats` | `track-publish-stats.ts` | Sample encoder counters into `publishStats` (DOM-free via a structural actor view) | | `openPublishSession` | `open-publish-session.ts` | Own the publish session actor; gate on `endpoint` + `publishActivated` + capture `'active'`; mirror lifecycle into `sessionStatus` | -| `setupTrackPublishers` | `setup-track-publishers.ts` | Register each track on the session's serve registry; own the per-track publisher actors; sync subscription bindings into them; FIN each track's subscriptions on teardown | +| `setupTrackPublishers` | `setup-track-publishers.ts` | Register each track on the session's serve registry; own the per-track publisher actors; sync subscription bindings into them; on teardown, close each track's data streams, then end its subscriptions with PUBLISH_DONE (TRACK_ENDED) and a FIN | | `deriveCatalog` | `derive-catalog.ts` | Build + send the MSF catalog as object 0 of a fresh group on every input change | Actors and session: @@ -269,8 +269,9 @@ publisher initiates no requests, so there is no response to bound. half (solicitation acceptance, suffix-relative NAMESPACE entries, announce-loss → `onAnnounceEnded`, NAMESPACE_DONE + no-GOAWAY close) and the serve half (alias = request ID, TIMESCALE declaration, - newest-subscription binding with clean replacement FINs, bare-FIN - track end) through `network/moqt/tests/helpers/raw-peer.ts`, the relay's + newest-subscription binding with bare-FIN ends for superseded + subscriptions, PUBLISH_DONE + FIN track end with exact Stream Counts) + through `network/moqt/tests/helpers/raw-peer.ts`, the relay's side of the flow the subscribe driver does not initiate. - **Full pipeline** — `publish/engines/moq/tests/publish-transport.test.ts`: real capture diff --git a/packages/spf/src/publish/actors/tests/track-publisher.test.ts b/packages/spf/src/publish/actors/tests/track-publisher.test.ts index c68c812126..315535b42a 100644 --- a/packages/spf/src/publish/actors/tests/track-publisher.test.ts +++ b/packages/spf/src/publish/actors/tests/track-publisher.test.ts @@ -338,7 +338,7 @@ describe('createTrackPublisherActor', () => { ]); }); - it('counts the data streams opened under each subscription alias', async () => { + it('counts the data streams opened under each subscription alias, pruning superseded ones', async () => { const factory = makeStreamFactory(); const publisher = createTrackPublisherActor({ openUniStream: factory.openUniStream, groupPerFrame: true }); const frame = (timestampUs: number) => @@ -351,11 +351,20 @@ describe('createTrackPublisherActor', () => { publisher.send(frame(2)); await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(2)); - publisher.send({ type: 'bind', trackAlias: 5 }); + // A Forward State toggle unbinds and rebinds the same alias: its + // count must survive, or PUBLISH_DONE would under-report. + publisher.send({ type: 'unbind' }); + publisher.send({ type: 'bind', trackAlias: 3 }); publisher.send(frame(3)); await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(3)); + expect(publisher.streamCount(3)).toBe(3); + + // A new alias supersedes the old subscription, whose count is pruned. + publisher.send({ type: 'bind', trackAlias: 5 }); + publisher.send(frame(4)); + await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(4)); - expect([publisher.streamCount(3), publisher.streamCount(5), publisher.streamCount(7)]).toEqual([2, 1, 0]); + expect([publisher.streamCount(3), publisher.streamCount(5), publisher.streamCount(7)]).toEqual([0, 1, 0]); publisher.destroy(); }); diff --git a/packages/spf/src/publish/actors/track-publisher.ts b/packages/spf/src/publish/actors/track-publisher.ts index b4429efe46..494bceb4e9 100644 --- a/packages/spf/src/publish/actors/track-publisher.ts +++ b/packages/spf/src/publish/actors/track-publisher.ts @@ -197,7 +197,7 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track let currentGroupFrames: Extract[] = []; /** Detached FIN settlements (see `finishCell`) — `flushed()` waits on them past the runner. */ const pendingFins = new Set>(); - /** Opened data streams per subscription alias (see `streamCount`). */ + /** Opened data streams per subscription alias (see `streamCount`); pruned to the current alias on each bind. */ const streamsByAlias = new Map(); // Assigned right after createMachineActor returns; the runner tasks only @@ -530,6 +530,14 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track boundAlias = msg.trackAlias; + // A new alias binds only after the session has ended every + // older subscription on the track, so their counts are dead + // weight. The current alias keeps its count across an unbind + // (a Forward State toggle rebinds the same alias). + for (const alias of streamsByAlias.keys()) { + if (alias !== msg.trackAlias) streamsByAlias.delete(alias); + } + // Instant join: catalog-shaped tracks re-send their latest // change-driven frame (queued behind this message, boundAlias // already set); keyframe-grouped tracks replay the in-progress diff --git a/packages/spf/src/publish/behaviors/setup-track-publishers.ts b/packages/spf/src/publish/behaviors/setup-track-publishers.ts index 844a54ff0f..9ff117efe6 100644 --- a/packages/spf/src/publish/behaviors/setup-track-publishers.ts +++ b/packages/spf/src/publish/behaviors/setup-track-publishers.ts @@ -20,11 +20,11 @@ * * Cluster-owner reactor per the per-type setup-actor convention: the encoder chunk router (the engine's default * `chunkSink`) and `deriveCatalog` only read the slots — they never create the actors. On session loss, endpoint - * change, or teardown the actors are destroyed in reverse creation order, each track's live subscriptions get their - * clean end — PUBLISH_DONE with TRACK_ENDED, then FIN (`handle.end()`) — and the slots are cleared. When the session is - * still serving at teardown, the broadcast is ending on purpose, so the catalog track's last group is the MSF - * end-of-broadcast catalog (§11.3) — never on a session loss, which may yet reconnect and must not mark the broadcast - * complete. + * change, or teardown the actors are ended in reverse creation order: each track's data streams close first, then its + * live subscriptions get their clean end — PUBLISH_DONE with TRACK_ENDED, then FIN (`handle.end()`) — and the slots are + * cleared. When the session is still serving at teardown, the broadcast is ending on purpose, so the catalog track's + * last group is the MSF end-of-broadcast catalog (§11.3) — never on a session loss, which may yet reconnect and must + * not mark the broadcast complete. * * Sole writer of the track-publisher context slots (the four media slots plus `dataTrackProducers`). Per-stream * failures are deliberately not surfaced as `publishError` anymore: under pull-through ingest the peer resets in-flight @@ -243,10 +243,31 @@ function hasEncoding(encodings: ActiveEncodingsFacts | undefined): boolean { const textEncoder = new TextEncoder(); /** - * End the catalog track with the MSF end-of-broadcast catalog (§11.3: `isComplete`, no tracks) as its last group. The - * subscription FINs wait for that group to land — bounded by the session's close drain window, so a stalled stream - * cannot hold the teardown — and only then is the publisher destroyed. + * How long a track's teardown waits for its last groups to flush. Half the session's close drain window: the + * PUBLISH_DONE that follows still has to reach the wire before the drain closes the transport. */ +const TRACK_FLUSH_TIMEOUT_MS = CLOSE_FLUSH_TIMEOUT_MS / 2; + +/** + * End one track in the order §10.12 requires — every data stream closed before PUBLISH_DONE: `end` FINs the open group, + * the queued groups get a bounded window to flush, `destroy()` FINs or resets whatever is left, and only then does the + * session send each subscription PUBLISH_DONE and its FIN. + */ +function endTrack(handle: RegisteredTrack, publisher: TrackPublisherActor): void { + publisher.send({ type: 'end' }); + + let timer: ReturnType | undefined; + const flushed = Promise.race([ + publisher.flushed(), + new Promise((resolve) => { + timer = setTimeout(resolve, TRACK_FLUSH_TIMEOUT_MS); + }), + ]).finally(() => clearTimeout(timer)); + + handle.end({ after: flushed.then(() => publisher.destroy()) }); +} + +/** End the catalog track with the MSF end-of-broadcast catalog (§11.3: `isComplete`, no tracks) as its last group. */ function endCatalogTrack( handle: RegisteredTrack, publisher: TrackPublisherActor, @@ -260,18 +281,7 @@ function endCatalogTrack( keyframe: true, timestampUs: 0, }); - publisher.send({ type: 'end' }); - - let timer: ReturnType | undefined; - const flushed = Promise.race([ - publisher.flushed(), - new Promise((resolve) => { - timer = setTimeout(resolve, CLOSE_FLUSH_TIMEOUT_MS); - }), - ]).finally(() => clearTimeout(timer)); - - handle.end({ after: flushed }); - void flushed.then(() => publisher.destroy()); + endTrack(handle, publisher); } /** @@ -475,12 +485,7 @@ function setupTrackPublishersSetup({ continue; } - // Quiesce: 'end' FINs the open group, then the track's - // live subscriptions get PUBLISH_DONE (TRACK_ENDED) and - // a FIN, then destroy() force-ends whatever is left. - publisher.send({ type: 'end' }); - handle.end(); - publisher.destroy(); + endTrack(handle, publisher); } }; }, diff --git a/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts b/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts index 5849cdf903..9dd4a03f9c 100644 --- a/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts +++ b/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts @@ -333,6 +333,43 @@ describe('setupTrackPublishers', () => { expect(onSubgroupReset).not.toHaveBeenCalled(); }); + it("closes a track's open group before its PUBLISH_DONE (§10.12)", async () => { + const { actor, peer, server } = makeSessionActor(); + const { state, context } = setupBehavior(); + const events: string[] = []; + + state.endpoint.set(ENDPOINT); + state.activeEncodings.set({ camera: VIDEO_CONFIG }); + context.publishSessionActor.set(actor); + void solicitNamespace(server, []); + await vi.waitFor(() => expect(context.videoTrackPublisher.get()).toBeDefined()); + peer.subscribe( + { trackNamespace: ENDPOINT.namespace, trackName: 'video' }, + { + onObject: (object) => events.push(`object g${object.groupId}`), + onSubgroupEnd: ({ groupId }) => events.push(`fin g${groupId}`), + onDone: (done) => events.push(`done status=${done.statusCode} streams=${done.streamCount}`), + } + ); + await vi.waitFor(() => expect(actor.snapshot.get().context.trackBindings.video).toBeDefined()); + // A keyframe opens group 0 and leaves it open — only the next + // keyframe or the track's end FINs it. + context.videoTrackPublisher.get()!.send({ + type: 'frame', + payload: new Uint8Array([1]), + properties: [], + keyframe: true, + timestampUs: 0, + }); + await vi.waitFor(() => expect(events).toEqual(['object g0'])); + + context.publishSessionActor.set(undefined); + actor.destroy(); + + await vi.waitFor(() => expect(events).toHaveLength(3)); + expect(events).toEqual(['object g0', 'fin g0', 'done status=2 streams=1']); + }); + it('never marks the broadcast complete when the session is lost', async () => { const { actor, server, client } = makeSessionActor(); const { state, context } = setupBehavior(); From 10606e84e847f4fa007ad5034e2ca324598f57bf Mon Sep 17 00:00:00 2001 From: Matt McClure Date: Wed, 7 Oct 2026 21:56:20 +0000 Subject: [PATCH 3/6] fix(sandbox): forward PUBLISH_DONE to loopback players The loopback relay reduced the publisher's PUBLISH_DONE to a FIN toward its players, which the SPF subscriber ignores, so a viewer only noticed the track end through its stall watchdog. Forward the upstream status with a per-subscription Stream Count, like moq-relay 0.17.0, and end viewers with INTERNAL_ERROR when the upstream subscription stream carries anything else, including a malformed frame. --- .../templates/moq-publisher/loopback-relay.ts | 64 +++++++++++++------ 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/apps/sandbox/templates/moq-publisher/loopback-relay.ts b/apps/sandbox/templates/moq-publisher/loopback-relay.ts index c45b216c76..c8ef534155 100644 --- a/apps/sandbox/templates/moq-publisher/loopback-relay.ts +++ b/apps/sandbox/templates/moq-publisher/loopback-relay.ts @@ -44,6 +44,9 @@ const MESSAGE_TYPE = { SUBSCRIBE_NAMESPACE: 0x50, } as const; +/** PUBLISH_DONE status codes (§10.12) this relay sends its players. */ +const PUBLISH_DONE_INTERNAL_ERROR = 0x0; + /** REQUEST_ERROR code for "nothing published in that range" (§10.6.1). */ const ERROR_INVALID_RANGE = 0x11; @@ -335,6 +338,11 @@ function encodeSubscribeOk(trackAlias: number): Uint8Array { return frame(MESSAGE_TYPE.SUBSCRIBE_OK, new Writer().varint(trackAlias).varint(0).toBytes()); } +function encodePublishDone(statusCode: number, streamCount: number): Uint8Array { + // Status Code + Stream Count + an empty Reason Phrase. + return frame(MESSAGE_TYPE.PUBLISH_DONE, new Writer().varint(statusCode).varint(streamCount).varint(0).toBytes()); +} + /** * SUBSCRIBE_NAMESPACE toward the publisher (§10.18): the empty prefix solicits every namespace the publisher will * announce — the same solicitation moq-relay 0.14.7 opens right after SETUP. @@ -415,10 +423,11 @@ interface PlayerSubscription { trackAlias: number; deliver(object: BufferedObject): void; /** - * End this subscription from the relay side: FIN toward the player and cancel its request stream, so its teardown - * removes the entry. Used when the upstream track is aborted for every viewer. + * End this subscription from the relay side: with a `statusCode`, PUBLISH_DONE (§10.12, counting the streams this + * subscription was sent) and then FIN; without one, a bare FIN. Then cancel its request stream, so its teardown + * removes the entry. */ - end(): void; + end(statusCode?: number): void; } interface TrackBuffer { @@ -771,29 +780,32 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp // Hold for the end — the publisher's PUBLISH_DONE then FIN (the // clean track end), or our own release. Anything else after // SUBSCRIBE_OK aborts the track for every viewer. - let publishDone = false; + let publishDoneStatus: number | undefined; if (!(await reader.atEnd())) { - const message = await readControlFrame(reader); + // A truncated or malformed frame aborts the track too — never + // leave its viewers attached to an upstream that is gone. + const message = await readControlFrame(reader).catch(() => undefined); + const clean = message?.type === MESSAGE_TYPE.PUBLISH_DONE && (await reader.atEnd().catch(() => false)); - publishDone = message.type === MESSAGE_TYPE.PUBLISH_DONE && (await reader.atEnd()); + if (!message || !clean) { + const what = message ? `unexpected 0x${message.type.toString(16)}` : 'malformed frame'; - if (!publishDone) { - log( - `upstream ${track.name}: unexpected 0x${message.type.toString(16)} after SUBSCRIBE_OK — aborting the track` - ); + log(`upstream ${track.name}: ${what} after SUBSCRIBE_OK — aborting the track`); - for (const subscriber of [...track.subscribers]) subscriber.end(); + for (const subscriber of [...track.subscribers]) subscriber.end(PUBLISH_DONE_INTERNAL_ERROR); return; } + + publishDoneStatus = new Reader(message.body).varint(); } - if (handle.released && !publishDone) { + if (handle.released && publishDoneStatus === undefined) { log(`upstream unsubscribe ${track.name} — no player interest`); } else { // The publisher's PUBLISH_DONE + FIN is the END of the track: - // propagate it — a clean FIN toward every attached viewer — so no + // propagate it to every attached viewer, so no // player hangs on a dead track and a later publisher session // cannot resume stale subscriptions. The downstream teardowns' // releaseUpstream calls land after this routine's finally has @@ -806,7 +818,11 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp // handed the final frames of a track that is over. track.groups.clear(); - for (const subscriber of [...track.subscribers]) subscriber.end(); + // Forward the publisher's status, the way moq-relay 0.17.0 does + // — a bare FIN reaches its viewers as INTERNAL_ERROR. + for (const subscriber of [...track.subscribers]) { + subscriber.end(publishDoneStatus ?? PUBLISH_DONE_INTERNAL_ERROR); + } } } catch { // Stream reset or session teardown — the close path owns cleanup. @@ -1247,15 +1263,25 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp // Announce-and-serve: player interest is what makes the relay // SUBSCRIBE upstream (catalog first, then the catalog's tracks). requestUpstreamTrack?.(track); + // One stream per delivered object — the PUBLISH_DONE Stream Count. + let deliveredStreams = 0; + subscription = { trackAlias, - deliver: (object) => + deliver: (object) => { + deliveredStreams++; publishObject( encodeObjectStream(trackAlias, object.groupId, object.objectId, object.properties, object.payload) - ), - end: () => { - // FIN toward the player (the clean track end), then cancel - // our read side — the loop's teardown removes the entry. + ); + }, + end: (statusCode) => { + // PUBLISH_DONE (when ending with a status) and FIN toward the + // player, then cancel our read side — the loop's teardown + // removes the entry. + if (statusCode !== undefined) { + void writer.write(encodePublishDone(statusCode, deliveredStreams)).catch(() => {}); + } + writer.close().catch(() => {}); abort(); }, From f1067b323e2690e41b1fa3455cf33a1348c8d6bf Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 8 Oct 2026 07:59:25 -0700 Subject: [PATCH 4/6] fix(spf): serve relay pulls whose fill cannot be reset reliably MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Moq-relay (0.14.17 through 0.17.0) subscribes upstream with Next Object plus FILL_PARAMETERS for the current group. Once a track has content that fill range is nonempty, and the publish session refused the whole SUBSCRIBE with NOT_SUPPORTED when the transport's writers lack WebTransport's commit() (RESET_STREAM_AT). Chromium 147 has no commit(), so in the browser a relay's second pull of a live track always failed: the real subscribe after a cross-relay TRACK_INFO probe, or any re-subscribe after the last viewer left. Players on another relay never got a catalog. Serve the subscription, and fail the fill as before: write the FETCH_HEADER, commit it where the writer can, and reset. Without commit() the reset may discard the header, and the subscriber sees no fill, which leaves its join at the next group boundary, as a failed fill does. REQUEST_UPDATE fills get the same treatment instead of ending the subscription. Stacked on #62, which ends tracks with PUBLISH_DONE and an exact Stream Count. There the fill counted only past the commit() gate this change removes. It now counts wherever the session opens one, whether or not its header survives the reset: §10.12 counts the streams the publisher opened, fill fetch streams included. A subscriber waits out a timeout for a stream reset before its header, but one that receives more streams than the count may close the session. moq-relay 0.17.0 never closes on either: it ends the track once the counted streams and the fill have arrived, or after a 1 s grace. A lost fill header leaves its fill outstanding, so that track end waits out the grace whatever the count says. The relay hub can now model a transport without commit(). The session tests cover the relay's probe-then-subscribe sequence, and the Stream Count of a fill reset without commit(), with its header delivered and lost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ts6nhCDi2pBF9h5ooBNbss --- packages/spf/src/network/moqt/session.ts | 6 +- .../src/publish/session/publish-session.ts | 42 ++--- .../session/tests/publish-session.test.ts | 178 +++++++++++++++--- .../src/publish/tests/helpers/relay-hub.ts | 8 +- .../spf/src/publish/tests/relay-hub.test.ts | 95 +++++----- 5 files changed, 234 insertions(+), 95 deletions(-) diff --git a/packages/spf/src/network/moqt/session.ts b/packages/spf/src/network/moqt/session.ts index 105b4f1d74..e849db2543 100644 --- a/packages/spf/src/network/moqt/session.ts +++ b/packages/spf/src/network/moqt/session.ts @@ -60,9 +60,9 @@ import { type BidirectionalStreamLike, openRequestStream, type RequestStream } f * Structural subset of `WebTransport` the session driver needs. A real `WebTransport` instance satisfies this; tests * provide an in-memory fake (the same seam pattern as SPF's fetch injection). * - * Publish-side fill failure signaling requires writers with WebTransport's `commit()` method, which preserves the - * written prefix across a reset. Support is detected on the control stream's writer and must be consistent across - * outgoing streams. Without it, nonempty fill requests are rejected with NOT_SUPPORTED. + * Publish-side fill failure signaling uses WebTransport's `commit()` writer method where it exists, which preserves the + * written FETCH_HEADER across the reset. Without it the subscription is still served, and the reset that fails the fill + * may discard its header. */ export interface MoqtTransport { readonly incomingUnidirectionalStreams: ReadableStream>; diff --git a/packages/spf/src/publish/session/publish-session.ts b/packages/spf/src/publish/session/publish-session.ts index 5bcf0b210d..458b36e44e 100644 --- a/packages/spf/src/publish/session/publish-session.ts +++ b/packages/spf/src/publish/session/publish-session.ts @@ -643,8 +643,15 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { * Answer a nonempty fill request (see `#fillRequested`). This origin serves no fills, so it meets the §5.1.3.1 * requirement the honest way: open a uni stream, write the FETCH_HEADER carrying the initiating Request ID so the * subscriber can correlate the failure, then reset it. A reset is the fill-failure signal — a FIN would falsely claim - * the fill range was delivered in full. Moq-relay 0.14.17 requests the current group this way; the reliable reset - * keeps that join from waiting on a fill that never arrives. + * the fill range was delivered in full. Moq-relay requests the current group this way (0.14.17 through 0.17.0) on + * every upstream SUBSCRIBE once the track has content. + * + * The header survives the reset only where the writer has WebTransport's `commit()` (RESET_STREAM_AT's reliable + * prefix). Without it (Chromium as of 147) the subscription is still served: the reset may discard the header, and + * the subscriber then sees no fill at all — which, like a failed one, leaves its join at the next group boundary. + * Refusing the SUBSCRIBE instead would fail every relay's second pull of a live track (the real subscribe after a + * cross-relay TRACK_INFO probe, or any re-subscribe after the last viewer left), so nothing would play across a relay + * mesh. */ #openAndResetFill(requestId: number, subscriber: SubscriberStream): void { const fill: FillStream = {}; @@ -660,20 +667,20 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { if (!subscriber.fills.has(fill) || subscriber.finished) return; - // All WebTransport writers expose the same capabilities, probed - // on the control writer before accepting a nonempty fill. Check - // this stream too so an inconsistent injected transport never - // writes a header it cannot preserve through the reset. - if (!hasMethods(writer, ['commit'])) return; - + // PUBLISH_DONE's Stream Count is the streams this side opened, + // fill fetch streams included (§10.12), so count this one even + // when the reset may discard its header. The subscriber waits + // out a timeout for a stream reset before its header; a count + // short of the streams it does receive may close the session. subscriber.fillStreams++; await writer.write(encodeFetchHeader(requestId)); if (!subscriber.fills.has(fill) || subscriber.finished) return; // write() only hands bytes to the transport. commit() includes - // them in the reliable prefix of RESET_STREAM_AT. - writer.commit(); + // them in the reliable prefix of RESET_STREAM_AT; without it the + // reset below is best-effort for the header. + if (hasMethods(writer, ['commit'])) writer.commit(); } catch { // Session closing or the peer went away before the header landed. } finally { @@ -1044,18 +1051,6 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { subscribe.parameters.fillParameters ); - if (fillRequested && !hasMethods(this.#controlWriter, ['commit'])) { - try { - await writer.write(encodeRequestError(REQUEST_ERROR_CODE.NOT_SUPPORTED, 'fill requires reliable stream reset')); - await writer.close(); - } catch { - // Peer cancelled. - } - - await reader.cancel(); - return; - } - track.subscribers.push(subscriber); // STOP_SENDING on the response direction cancels the subscription @@ -1166,7 +1161,6 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { // here, immediately resets) a fill fetch stream keyed by the // update's own Request ID (§5.1.3.1); an empty range opens none. const fillRequested = this.#fillRequested(largestObject, subscriber, subscribe.parameters, fillParameters); - const unsupportedFill = fillRequested && !hasMethods(this.#controlWriter, ['commit']); this.#callbacks.onRequestUpdate?.({ requestId: subscribe.requestId, @@ -1175,7 +1169,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { }); if (!subscriber.finished) { - if (Object.keys(unsupported).length > 0 || unsupportedFill) { + if (Object.keys(unsupported).length > 0) { // Acknowledging an update we did not apply would leave the // peer serving stale expectations (a filter or range it // believes is in effect). Forward State is applied above diff --git a/packages/spf/src/publish/session/tests/publish-session.test.ts b/packages/spf/src/publish/session/tests/publish-session.test.ts index c9e4fdb77d..8c080c3d9a 100644 --- a/packages/spf/src/publish/session/tests/publish-session.test.ts +++ b/packages/spf/src/publish/session/tests/publish-session.test.ts @@ -80,9 +80,11 @@ function collectTrack( async function makeFillHarness({ reliableReset = true, openFillStream, + callbacks, }: { reliableReset?: boolean; openFillStream?: () => Promise>; + callbacks?: MoqtPublishSessionCallbacks; } = {}) { const pair = createTransportPair(); const openUniStream = pair.client.createUnidirectionalStream.bind(pair.client); @@ -102,7 +104,7 @@ async function makeFillHarness({ return stream; }; - const session = createMoqtPublishSession(pair.client); + const session = createMoqtPublishSession(pair.client, { callbacks }); const fills: { requestId: number; reset: boolean }[] = []; const streams = pair.server.incomingUnidirectionalStreams.getReader(); @@ -146,8 +148,11 @@ async function makeFillHarness({ }; } -/** A buffered send stream: reset discards everything except the explicitly committed prefix. */ -function makeBufferedFillStream() { +/** + * A buffered send stream: reset discards everything except the explicitly committed prefix. Without `reliableReset` the + * writer has no `commit()` — a browser WebTransport today — so a reset discards everything still unread. + */ +function makeBufferedFillStream({ reliableReset = true }: { reliableReset?: boolean } = {}) { const chunks: Uint8Array[] = []; let committed = 0; let readIndex = 0; @@ -188,12 +193,14 @@ function makeBufferedFillStream() { }); const getWriter = writable.getWriter.bind(writable); - writable.getWriter = () => - Object.assign(getWriter(), { - commit() { - committed = chunks.length; - }, - }); + if (reliableReset) { + writable.getWriter = () => + Object.assign(getWriter(), { + commit() { + committed = chunks.length; + }, + }); + } return { writable, readable, reset: () => reset }; } @@ -1320,39 +1327,164 @@ describe('createMoqtPublishSession', () => { await finish(); }); - it('rejects nonempty fills without reliable reset support while allowing ordinary subscriptions', async () => { - const { pair, session, fills, finish } = await makeFillHarness({ reliableReset: false }); + it("serves a relay's second pull of a live track without reliable reset support", async () => { + const bindings: (number | undefined)[] = []; + const { pair, session, fills, finish } = await makeFillHarness({ + reliableReset: false, + callbacks: { onTrackBinding: ({ trackAlias }) => bindings.push(trackAlias) }, + }); + let largest: { group: number; object: number } | undefined; + + session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'catalog', getLargestObject: () => largest }); + + // Moq-relay's upstream SUBSCRIBE (0.14.17 through 0.17.0): Next Object, + // plus a fill of the current group's head. + const relayPull = (requestId: number) => + openRawRequest( + pair.server, + encodeSubscribe({ + requestId, + trackNamespace: NAMESPACE, + trackName: 'catalog', + parameters: { + forward: 1, + subscriberPriority: 128, + locationFilter: { type: 'next-object' }, + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + groupOrder: 'descending', + includeProperties: 1, + }, + }) + ); + + // A cross-relay viewer's first pull is the relay's TRACK_INFO probe: + // nothing published yet, so there is nothing to fill. + const probe = await relayPull(235); + + await vi.waitFor(() => expect(probe.received.map((m) => m.kind)).toEqual(['subscribe-ok'])); + + // The probe's bind put the catalog on the wire, then the relay + // cancelled it and pulled again for the viewer — now with a nonempty + // fill this transport cannot fail reliably. The pull is served anyway. + largest = { group: 0, object: 0 }; + await probe.reset(); + const pull = await relayPull(237); + + await vi.waitFor(() => { + expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expect(bindings.at(-1)).toBe(237); + expect(fills).toEqual([{ requestId: 237, reset: true }]); + }); + expect(pull.ended()).toBe(false); + + // A fill requested by REQUEST_UPDATE is acknowledged and failed the same way. + await pull.send( + encodeRequestUpdate(239, { fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } } }) + ); + await vi.waitFor(() => { + expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'request-ok']); + expect(fills).toEqual([ + { requestId: 237, reset: true }, + { requestId: 239, reset: true }, + ]); + }); + expect(pull.ended()).toBe(false); + await finish(); + }); + + it('still resets the fill when the reset may discard its header (no reliable reset)', async () => { + const fill = makeBufferedFillStream({ reliableReset: false }); + const { pair, session, finish } = await makeFillHarness({ + reliableReset: false, + openFillStream: async () => fill.writable, + }); session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'video', getLargestObject: () => ({ group: 4, object: 2 }), }); - const rejected = await openRawRequest( + const sub = await openRawRequest( pair.server, encodeSubscribe({ - requestId: 235, + requestId: 241, trackNamespace: NAMESPACE, trackName: 'video', parameters: { fillParameters: {} }, }) ); - await vi.waitFor(() => expect(rejected.ended()).toBe(true)); - expect(rejected.received).toMatchObject([{ kind: 'request-error', errorCode: REQUEST_ERROR_CODE.NOT_SUPPORTED }]); + await vi.waitFor(() => { + expect(sub.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expect(fill.reset()).toBeDefined(); + }); - const sub = await rawSubscribe(pair.server, 'video', 237); + // Nothing preserved the header through the reset: the peer sees only + // the reset, and the subscription is unaffected. + const reader = new StreamReader(fill.readable); - await vi.waitFor(() => expect(sub.received[0]?.kind).toBe('subscribe-ok')); - await sub.send(encodeRequestUpdate(239, { fillParameters: { locationFilter: { type: 'next-object' } } })); - await vi.waitFor(() => expect(sub.received[1]?.kind).toBe('request-ok')); - await sub.send(encodeRequestUpdate(241, { fillParameters: {} })); - await vi.waitFor(() => expect(sub.ended()).toBe(true)); - expect(sub.received[2]).toMatchObject({ kind: 'request-error', errorCode: REQUEST_ERROR_CODE.NOT_SUPPORTED }); - expect(fills).toEqual([]); + await expect(reader.readVarint()).rejects.toThrow('fill fetch streams are not served'); + expect(sub.ended()).toBe(false); await finish(); }); + it.each([{ headerSurvives: true }, { headerSurvives: false }])( + 'counts a fill reset without reliable reset in the PUBLISH_DONE Stream Count (header survives: $headerSurvives)', + async ({ headerSurvives }) => { + const buffered = makeBufferedFillStream({ reliableReset: false }); + const { pair, session, fills, finish } = await makeFillHarness({ + reliableReset: false, + openFillStream: headerSurvives ? undefined : async () => buffered.writable, + }); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getLargestObject: () => ({ group: 4, object: 2 }), + getStreamCount: () => 3, + }); + const sub = await openRawRequest( + pair.server, + encodeSubscribe({ + requestId: 243, + trackNamespace: NAMESPACE, + trackName: 'video', + parameters: { fillParameters: {} }, + }) + ); + + await vi.waitFor(() => { + expect(sub.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + + if (headerSurvives) expect(fills).toEqual([{ requestId: 243, reset: true }]); + else expect(buffered.reset()).toBeDefined(); + }); + + if (!headerSurvives) { + // The peer saw only the reset, so it cannot tell the stream + // belonged to this subscription. + await expect(new StreamReader(buffered.readable).readVarint()).rejects.toThrow( + 'fill fetch streams are not served' + ); + } + + track.end(); + await vi.waitFor(() => { + expect(sub.ended()).toBe(true); + }); + // §10.12 counts the streams the publisher opened, fill fetch + // streams included: three from the track publisher plus the fill, + // whether or not its header outlived the reset. A subscriber waits + // out a timeout for a stream reset before its header, but one that + // receives more streams than the count may close the session. + expect(sub.received.at(-1)).toMatchObject({ + kind: 'publish-done', + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: 4, + }); + await finish(); + } + ); + it('rejects a subscription update it cannot apply instead of acknowledging it', async () => { const endedRequests: number[] = []; const bindings: (number | undefined)[] = []; diff --git a/packages/spf/src/publish/tests/helpers/relay-hub.ts b/packages/spf/src/publish/tests/helpers/relay-hub.ts index 271e8c61a4..bca23d1027 100644 --- a/packages/spf/src/publish/tests/helpers/relay-hub.ts +++ b/packages/spf/src/publish/tests/helpers/relay-hub.ts @@ -178,6 +178,11 @@ export function createRelayHub( options: { /** Delay individual downstream object streams to exercise jitter and late arrivals. */ deliveryDelayMs?: (trackName: string, object: Readonly) => number; + /** + * Give the publisher's stream writers WebTransport's `commit()` (RESET_STREAM_AT). Default `true`; `false` models + * the browsers that ship WebTransport without it (Chromium 147). + */ + reliableReset?: boolean; } = {} ): RelayHub { let destroyed = false; @@ -254,7 +259,8 @@ export function createRelayHub( // These zero-buffer pipes settle writes only after the peer reads // them, so the reliable prefix is already delivered at commit time. - stream.getWriter = () => Object.assign(getWriter(), { commit() {} }); + if (options.reliableReset !== false) stream.getWriter = () => Object.assign(getWriter(), { commit() {} }); + return stream; }; diff --git a/packages/spf/src/publish/tests/relay-hub.test.ts b/packages/spf/src/publish/tests/relay-hub.test.ts index d90ee928c5..e0033621a3 100644 --- a/packages/spf/src/publish/tests/relay-hub.test.ts +++ b/packages/spf/src/publish/tests/relay-hub.test.ts @@ -10,54 +10,61 @@ import { createRelayHub } from './helpers/relay-hub'; * cross-engine suites are too coarse to pin down. */ describe('createRelayHub', () => { - it.each([false, true])('follows live after a relay 0.14.17 pull (existing content: %s)', async (hasContent) => { - const hub = createRelayHub(); - const { transport } = hub.connectPublisher({ url: 'https://relay.test/moq', namespace: ['live'] }); - const onSubscribe = vi.fn(); - const onTrackBinding = vi.fn(); - const onClosed = vi.fn(); - const session = createMoqtPublishSession(transport, { callbacks: { onSubscribe, onTrackBinding, onClosed } }); + it.each([ + { hasContent: false, reliableReset: true }, + { hasContent: true, reliableReset: true }, + { hasContent: true, reliableReset: false }, + ])( + 'follows live after a relay 0.14.17 pull (existing content: $hasContent, reliable reset: $reliableReset)', + async ({ hasContent, reliableReset }) => { + const hub = createRelayHub({ reliableReset }); + const { transport } = hub.connectPublisher({ url: 'https://relay.test/moq', namespace: ['live'] }); + const onSubscribe = vi.fn(); + const onTrackBinding = vi.fn(); + const onClosed = vi.fn(); + const session = createMoqtPublishSession(transport, { callbacks: { onSubscribe, onTrackBinding, onClosed } }); - try { - await session.ready; - session.announce(['live']); - session.registerTrack({ - trackNamespace: ['live'], - trackName: 'video', - getLargestObject: () => (hasContent ? { group: 255, object: 128 } : undefined), - }); - hub.subscribeUpstream('video'); - await vi.waitFor(() => { - expect(onSubscribe).toHaveBeenCalledWith( - expect.objectContaining({ - parameters: expect.objectContaining({ - subscriberPriority: 255, - locationFilter: { type: 'next-object' }, - fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, - }), - }) - ); - expect(onTrackBinding).toHaveBeenCalledWith({ trackName: 'video', trackAlias: expect.any(Number) }); - expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); - }); + try { + await session.ready; + session.announce(['live']); + session.registerTrack({ + trackNamespace: ['live'], + trackName: 'video', + getLargestObject: () => (hasContent ? { group: 255, object: 128 } : undefined), + }); + hub.subscribeUpstream('video'); + await vi.waitFor(() => { + expect(onSubscribe).toHaveBeenCalledWith( + expect.objectContaining({ + parameters: expect.objectContaining({ + subscriberPriority: 255, + locationFilter: { type: 'next-object' }, + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + }), + }) + ); + expect(onTrackBinding).toHaveBeenCalledWith({ trackName: 'video', trackAlias: expect.any(Number) }); + expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); + }); - const trackAlias = onTrackBinding.mock.calls[0]![0].trackAlias; - const stream = createSubgroupWriter(await session.openUniStream(), { - trackAlias, - groupId: 256, - endOfGroup: true, - }); + const trackAlias = onTrackBinding.mock.calls[0]![0].trackAlias; + const stream = createSubgroupWriter(await session.openUniStream(), { + trackAlias, + groupId: 256, + endOfGroup: true, + }); - await stream.writeObject({ objectId: 0, payload: Uint8Array.of(1, 2, 3) }); - await stream.fin(); - await vi.waitFor(() => expect(hub.objectCount('video')).toBe(1)); - expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); - expect(onClosed).not.toHaveBeenCalled(); - } finally { - session.destroy(); - hub.destroy(); + await stream.writeObject({ objectId: 0, payload: Uint8Array.of(1, 2, 3) }); + await stream.fin(); + await vi.waitFor(() => expect(hub.objectCount('video')).toBe(1)); + expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); + expect(onClosed).not.toHaveBeenCalled(); + } finally { + session.destroy(); + hub.destroy(); + } } - }); + ); it('re-pulls a track the publisher ended and re-registered while demand stands', async () => { const hub = createRelayHub(); From 8f3e84fe5a61215378d47cadbecfd32f0b36135a Mon Sep 17 00:00:00 2001 From: "mux-hermoq[bot]" <332784920+mux-hermoq[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:06:37 +0000 Subject: [PATCH 5/6] test(spf): state the fill Stream Count rule and pin a fill opening at end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review (cubic, #63) read the fill counter's comment as "count every stream this side opens" and flagged a fill whose stream is still opening when the track ends: PUBLISH_DONE goes out without it. That is the intended rule, the one the track publisher applies to subgroup streams (#62): a stream counts in the step that commits it to its header, so a stream reset before its header, which the subscriber cannot attribute to the subscription, is left out. The late fill is reset with no header, so the count can never fall short of the streams the subscriber can tie to the subscription. Reword the comment to say so, including the over-count side (a counted fill whose reset discards its header, or whose write rejects), which §10.12 covers with the subscriber's timeout. Add a test that ends the track while the fill's open is pending, with and without reliable reset: Stream Count 3, the fill stream gets no write and is aborted. --- .../src/publish/session/publish-session.ts | 16 +++++-- .../session/tests/publish-session.test.ts | 48 +++++++++++++++++++ 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/packages/spf/src/publish/session/publish-session.ts b/packages/spf/src/publish/session/publish-session.ts index 458b36e44e..9424d1f32f 100644 --- a/packages/spf/src/publish/session/publish-session.ts +++ b/packages/spf/src/publish/session/publish-session.ts @@ -667,11 +667,17 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { if (!subscriber.fills.has(fill) || subscriber.finished) return; - // PUBLISH_DONE's Stream Count is the streams this side opened, - // fill fetch streams included (§10.12), so count this one even - // when the reset may discard its header. The subscriber waits - // out a timeout for a stream reset before its header; a count - // short of the streams it does receive may close the session. + // PUBLISH_DONE's Stream Count includes fill fetch streams + // (§10.12). Count in the same synchronous step that commits this + // stream to its FETCH_HEADER — the track publisher's rule for + // subgroup streams — so any PUBLISH_DONE covers every fill that + // carries a header. A fill still opening when the track ended + // was stopped by the guard above: it is reset with no header, so + // the subscriber cannot attribute it to this subscription and + // leaving it uncounted cannot put the subscriber over the count. + // A counted fill whose reset discards its header (no commit()) + // or whose write rejects over-counts by one; for that §10.12 has + // the subscriber fall back to a timeout. subscriber.fillStreams++; await writer.write(encodeFetchHeader(requestId)); diff --git a/packages/spf/src/publish/session/tests/publish-session.test.ts b/packages/spf/src/publish/session/tests/publish-session.test.ts index 8c080c3d9a..e1ad95f29c 100644 --- a/packages/spf/src/publish/session/tests/publish-session.test.ts +++ b/packages/spf/src/publish/session/tests/publish-session.test.ts @@ -1327,6 +1327,54 @@ describe('createMoqtPublishSession', () => { await finish(); }); + it.each([{ reliableReset: true }, { reliableReset: false }])( + 'leaves a fill still opening when the track ends out of the Stream Count, headerless (reliable reset: $reliableReset)', + async ({ reliableReset }) => { + let resolveOpen!: (stream: WritableStream) => void; + const openFillStream = vi.fn( + () => + new Promise>((resolve) => { + resolveOpen = resolve; + }) + ); + const { pair, session, finish } = await makeFillHarness({ reliableReset, openFillStream }); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getLargestObject: () => ({ group: 4, object: 2 }), + getStreamCount: () => 3, + }); + const sub = await rawSubscribe(pair.server, 'video', 245); + + await vi.waitFor(() => expect(sub.received[0]?.kind).toBe('subscribe-ok')); + await sub.send(encodeRequestUpdate(247, { fillParameters: {} })); + await vi.waitFor(() => expect(openFillStream).toHaveBeenCalledOnce()); + + // The track ends while the fill's stream is still opening. + track.end(); + await vi.waitFor(() => expect(sub.ended()).toBe(true)); + + const write = vi.fn(); + const abort = vi.fn(); + + resolveOpen(new WritableStream({ write, abort })); + await vi.waitFor(() => expect(abort).toHaveBeenCalledOnce()); + + // A fill is counted in the same step that commits it to its + // FETCH_HEADER, as the track publisher counts subgroup streams. + // This one opened after PUBLISH_DONE, so it gets no header and is + // reset bare: the peer cannot attribute it to the subscription, so + // leaving it out of the count cannot put the peer over it. + expect(write).not.toHaveBeenCalled(); + expect(sub.received.at(-1)).toMatchObject({ + kind: 'publish-done', + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: 3, + }); + await finish(); + } + ); + it("serves a relay's second pull of a live track without reliable reset support", async () => { const bindings: (number | undefined)[] = []; const { pair, session, fills, finish } = await makeFillHarness({ From f0577b432d4ea0dbad691cb310aca9e2c24c959c Mon Sep 17 00:00:00 2001 From: "mux-hermoq[bot]" <332784920+mux-hermoq[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:13:54 +0000 Subject: [PATCH 6/6] test(spf): cover a relay probe whose end lands after the second pull Review (cubic, #63) suspected the probe's unbind could land after pull 237's bind and leave the binding undefined. It cannot: a subscription's end reports the newest live binding, not an unbind, and pull 237 is already accepted. Run the relay test both ways, with the probe cancelled before and after the second pull, and check the binding is still 237 once the probe's end has been handled. Reporting an unbind there fails the new case. --- .../session/tests/publish-session.test.ts | 130 ++++++++++-------- 1 file changed, 74 insertions(+), 56 deletions(-) diff --git a/packages/spf/src/publish/session/tests/publish-session.test.ts b/packages/spf/src/publish/session/tests/publish-session.test.ts index e1ad95f29c..099e38f975 100644 --- a/packages/spf/src/publish/session/tests/publish-session.test.ts +++ b/packages/spf/src/publish/session/tests/publish-session.test.ts @@ -1375,70 +1375,88 @@ describe('createMoqtPublishSession', () => { } ); - it("serves a relay's second pull of a live track without reliable reset support", async () => { - const bindings: (number | undefined)[] = []; - const { pair, session, fills, finish } = await makeFillHarness({ - reliableReset: false, - callbacks: { onTrackBinding: ({ trackAlias }) => bindings.push(trackAlias) }, - }); - let largest: { group: number; object: number } | undefined; + it.each([{ probeEnds: 'before' }, { probeEnds: 'after' }])( + "serves a relay's second pull of a live track without reliable reset support (probe ends $probeEnds the pull)", + async ({ probeEnds }) => { + const bindings: (number | undefined)[] = []; + const ended: number[] = []; + const { pair, session, fills, finish } = await makeFillHarness({ + reliableReset: false, + callbacks: { + onTrackBinding: ({ trackAlias }) => bindings.push(trackAlias), + onSubscribeEnd: ({ requestId }) => ended.push(requestId), + }, + }); + let largest: { group: number; object: number } | undefined; + + session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'catalog', getLargestObject: () => largest }); + + // Moq-relay's upstream SUBSCRIBE (0.14.17 through 0.17.0): Next Object, + // plus a fill of the current group's head. + const relayPull = (requestId: number) => + openRawRequest( + pair.server, + encodeSubscribe({ + requestId, + trackNamespace: NAMESPACE, + trackName: 'catalog', + parameters: { + forward: 1, + subscriberPriority: 128, + locationFilter: { type: 'next-object' }, + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + groupOrder: 'descending', + includeProperties: 1, + }, + }) + ); - session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'catalog', getLargestObject: () => largest }); + // A cross-relay viewer's first pull is the relay's TRACK_INFO probe: + // nothing published yet, so there is nothing to fill. + const probe = await relayPull(235); - // Moq-relay's upstream SUBSCRIBE (0.14.17 through 0.17.0): Next Object, - // plus a fill of the current group's head. - const relayPull = (requestId: number) => - openRawRequest( - pair.server, - encodeSubscribe({ - requestId, - trackNamespace: NAMESPACE, - trackName: 'catalog', - parameters: { - forward: 1, - subscriberPriority: 128, - locationFilter: { type: 'next-object' }, - fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, - groupOrder: 'descending', - includeProperties: 1, - }, - }) - ); + await vi.waitFor(() => expect(probe.received.map((m) => m.kind)).toEqual(['subscribe-ok'])); - // A cross-relay viewer's first pull is the relay's TRACK_INFO probe: - // nothing published yet, so there is nothing to fill. - const probe = await relayPull(235); + // The probe's bind put the catalog on the wire, then the relay + // cancelled it and pulled again for the viewer — now with a nonempty + // fill this transport cannot fail reliably. The pull is served anyway. + largest = { group: 0, object: 0 }; - await vi.waitFor(() => expect(probe.received.map((m) => m.kind)).toEqual(['subscribe-ok'])); + if (probeEnds === 'before') await probe.reset(); - // The probe's bind put the catalog on the wire, then the relay - // cancelled it and pulled again for the viewer — now with a nonempty - // fill this transport cannot fail reliably. The pull is served anyway. - largest = { group: 0, object: 0 }; - await probe.reset(); - const pull = await relayPull(237); + const pull = await relayPull(237); - await vi.waitFor(() => { - expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + await vi.waitFor(() => { + expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expect(bindings.at(-1)).toBe(237); + expect(fills).toEqual([{ requestId: 237, reset: true }]); + }); + + // The probe's end may be handled after the pull is bound: it reports + // the newest live binding, not an unbind, so the pull keeps it. + if (probeEnds === 'after') await probe.reset(); + + await vi.waitFor(() => expect(ended).toContain(235)); expect(bindings.at(-1)).toBe(237); - expect(fills).toEqual([{ requestId: 237, reset: true }]); - }); - expect(pull.ended()).toBe(false); + expect(pull.ended()).toBe(false); - // A fill requested by REQUEST_UPDATE is acknowledged and failed the same way. - await pull.send( - encodeRequestUpdate(239, { fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } } }) - ); - await vi.waitFor(() => { - expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'request-ok']); - expect(fills).toEqual([ - { requestId: 237, reset: true }, - { requestId: 239, reset: true }, - ]); - }); - expect(pull.ended()).toBe(false); - await finish(); - }); + // A fill requested by REQUEST_UPDATE is acknowledged and failed the same way. + await pull.send( + encodeRequestUpdate(239, { + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + }) + ); + await vi.waitFor(() => { + expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'request-ok']); + expect(fills).toEqual([ + { requestId: 237, reset: true }, + { requestId: 239, reset: true }, + ]); + }); + expect(pull.ended()).toBe(false); + await finish(); + } + ); it('still resets the fill when the reset may discard its header (no reliable reset)', async () => { const fill = makeBufferedFillStream({ reliableReset: false });