From 9667c9a15bfbca313bc5d155f972ba7398fe6dff Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:15:39 -0700 Subject: [PATCH 1/7] quest: claim Hang contribution reference Co-Authored-By: GPT-5.4 From 4a5948703ec2dd48ebfcd27b418df448316da4a5 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 10 Oct 2026 17:42:49 -0700 Subject: [PATCH 2/7] feat(hang): add lazy contribution broadcast references Co-Authored-By: Codex --- doc/concept/hang.md | 1 + drafts/draft-lcurley-moq-hang.md | 13 ++++ js/hang/src/catalog/root.ts | 7 ++- js/watch/src/broadcast.ts | 43 ++++++++++++- js/watch/src/contribution.test.ts | 100 ++++++++++++++++++++++++++++++ rs/hang/src/catalog/consumer.rs | 7 +++ rs/hang/src/catalog/root.rs | 29 ++++++++- 7 files changed, 196 insertions(+), 4 deletions(-) create mode 100644 js/watch/src/contribution.test.ts diff --git a/doc/concept/hang.md b/doc/concept/hang.md index cd055cd1003..c807ae7f3ef 100644 --- a/doc/concept/hang.md +++ b/doc/concept/hang.md @@ -65,6 +65,7 @@ A few things the catalog can express beyond decoder config: - **Labels.** Any rendition may carry a human-readable `label` for a track picker. The map key stays the rendition's ID, so labels need not be unique and renaming one doesn't rename the track. - **Renditions in another broadcast.** A rendition may point at a relative broadcast path, so a transcoder can publish a ladder that adds low rungs and references the source's original rendition without re-publishing its bytes. The path resolves against where the consumer found the catalog, so a reference that escapes above the root names nothing and the catalog is rejected. A consumer reads each referenced path from the first broadcast it resolves there. An optional `epoch` beside the path names the [publisher instance](/concept/moq-lite#publisher-epochs) it expects: a route proving another instance fails the rendition instead of falling back to it, while a route without an epoch (an older version) cannot prove one, so there it is best effort. - **Track names.** The map key is a rendition's ID and, by default, its track name. A rendition sets `track` only when the two must differ, such as two renditions of same-named tracks in different broadcasts, or a rendition whose media changed and so needs a new name; readers subscribe to `track` when present. An ID can't name both a video and an audio rendition. +- **Whole contributions.** A catalog can list relative broadcast references without fetching their catalogs. Explicit selection opens a contribution, whose rendition names remain separate from the source. `@moq/watch` exposes this as a scoped child broadcast; listing contributions alone never starts their media producers. - **Jitter.** A rendition can say how far its frames fell behind the media clock before the publisher flushed them, in whole milliseconds rounded up. Encoders report the spread of lateness above each rendition's own recent minimum, so a constant encoder delay is not jitter; container imports estimate batch spans without counting ingest delay. It describes the publisher, never the network, only grows over the life of a stream, and a player sizes its buffer to at least this much. A `0` is read as absent. - **Delay.** A rendition can also say how far its frames reach the transport behind the broadcast's earliest rendition, measured the same way from each rendition's minimum lateness, so a video encoder running 200 ms behind audio advertises `delay: 200` on video. It follows the same rules as jitter. A player holds the largest `delay + jitter` among the renditions it subscribes to, and never subtracts one rendition's `delay` from another's. - **Disabled renditions.** An audio or video rendition with `enabled: false` has no frames coming, and a player must not select it. Pausing a rendition in `@moq/publish` keeps it in the catalog this way rather than removing it, so a mute is a one-field update; a disabled video rendition encodes one black keyframe first, so a player that predates the field shows black instead of a frozen picture. The field is written only when false. The older video `stalled` field is no longer written, and readers ignore it. diff --git a/drafts/draft-lcurley-moq-hang.md b/drafts/draft-lcurley-moq-hang.md index b8d5ee5f8ef..8747c799e02 100644 --- a/drafts/draft-lcurley-moq-hang.md +++ b/drafts/draft-lcurley-moq-hang.md @@ -123,6 +123,7 @@ The root of the catalog is a JSON document with the following schema: ~~~ type Catalog = { + "contributions": Record | undefined, "audio": AudioSchema | undefined, "video": VideoSchema | undefined, "archive": ArchiveSchema | undefined, @@ -144,6 +145,16 @@ The `json` and `binary` sections ({{data}}) are how a track like that is listed. This specification defines audio, video, and text media tracks, plus an optional `archive` entry ({{archive-catalog}}) naming the timeline track ({{timeline}}) that indexes each track, an optional root `clock` entry ({{clock}}) mapping content time to wall time, and the application data tracks in {{data}}. +## Contributions {#contributions} +The optional `contributions` map names whole broadcasts whose catalogs describe their renditions. +Each entry MUST contain a string `broadcast`, resolved relative to this catalog's broadcast using {{field-broadcast}}. +A malformed entry or a reference escaping the root MUST cause the catalog to be rejected. + +Listing an entry MUST NOT subscribe to the contribution; a consumer opens its catalog only upon explicit selection. +A contribution's rendition identifiers belong to that contribution and MUST NOT replace identifiers in the referring catalog. +An unavailable contribution does not invalidate the referring catalog. +References are not recursively expanded: each further contribution requires an explicit selection. + ## Clock {#clock} The catalog's root `clock` field is the broadcast's one continuous clock: @@ -1160,6 +1171,8 @@ This document has no IANA actions. - Specified conversion between relative broadcast references and MSF track namespaces without changing track identity, reading a namespace aligned with the catalog path's trailing segments as the catalog itself. - Added optional audio and video `warmup` durations, rounded up to whole milliseconds, and allowed video groups to start at convergent random access pictures. +- Added optional whole-broadcast `contributions` with explicit lazy selection and scoped rendition identifiers. + - Defined encoder `jitter` as flush lateness above the rendition's own recent minimum, replacing fixed frame-duration hints; container batches retain media-span estimates. - Timed CMAF samples from the frame timestamp, which is the fragment's earliest presentation time; `tfdt` is only relative within the fragment, and places the samples of an untimed frame. A timed CMAF track counts in its `mdhd` ticks. - Allowed a DVR to delete timeline objects no checkpoint recovery needs, oldest first. diff --git a/js/hang/src/catalog/root.ts b/js/hang/src/catalog/root.ts index d8e7c459ee9..a66075ad82d 100644 --- a/js/hang/src/catalog/root.ts +++ b/js/hang/src/catalog/root.ts @@ -8,7 +8,7 @@ import { BinarySchema } from "./binary"; import { ClockSchema } from "./clock"; import { TRACK } from "./format"; import { JsonSchema } from "./json"; -import type { RelativeBroadcast } from "./path"; +import { type RelativeBroadcast, RelativeBroadcastSchema } from "./path"; import { PRIORITY } from "./priority"; import { section } from "./section"; import { TextSchema } from "./text"; @@ -20,7 +20,7 @@ import { VideoSchema } from "./video"; * The media sections are `video`, `audio`, and `text`, alongside the broadcast's `archive` * (the segment index and any durable recording) and its `clock` (the one wall-clock mapping); * `json` and `binary` list application data tracks that aren't media. A section is omitted - * when it holds no tracks. + * when it holds no tracks. `contributions` lists whole broadcasts without opening them. * * This is a *loose* object: unknown root sections pass through validation untouched, so an * application can add its own sections (e.g. `scte35`) without modifying hang. A base consumer @@ -28,6 +28,8 @@ import { VideoSchema } from "./video"; * built via `z.extend(RootSchema, { ... })`. */ export const RootSchema = z.looseObject({ + // Whole broadcasts are listed without opening their catalogs. IDs stay scoped to each broadcast. + contributions: z.optional(z.record(z.string(), z.object({ broadcast: RelativeBroadcastSchema }))), video: z.optional(VideoSchema), audio: z.optional(AudioSchema), // An incompatible archive disables seeking/recording, not the rest of the catalog. @@ -108,6 +110,7 @@ export function checkResolvable(root: Root, base: Moq.Path.Valid): Root { root.text?.renditions, root.json?.tracks, root.binary?.tracks, + root.contributions, ]; for (const section of sections) { for (const { broadcast } of Object.values(section ?? {})) { diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index 5a0f9ab8a26..5fca06a670b 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -300,7 +300,15 @@ export class Broadcast { const catalog = effect.get(this.in.catalog); let accepted: Catalog.Root | undefined; try { - accepted = catalog && Catalog.checkResolvable(Catalog.checkRenditions(catalog), name); + accepted = + catalog && + Catalog.checkResolvable( + Catalog.checkRenditions({ + ...catalog, + contributions: Catalog.RootSchema.shape.contributions.parse(catalog.contributions), + }), + name, + ); } catch (err) { console.error("rejecting catalog", name, err); } @@ -436,6 +444,39 @@ export class Broadcast { return this.#requestBroadcast(effect, origin, target.path); } + /** + * Select a whole contribution, opening its catalog only while the caller owns this effect. + * Wire the returned broadcast into a media source inside a nested effect. Its rendition + * IDs stay local to that broadcast, so they never replace the parent catalog's IDs. + * + * ```ts + * effects.run((effect) => { + * const child = broadcast.contribution(effect, "extra"); + * if (!child) return; + * const source = new Video.Source({ broadcast: child, supported: Video.Decoder.supported }); + * effect.cleanup(() => source.close()); + * const decoder = new Video.Decoder({ source, sync }); + * effect.cleanup(() => decoder.close()); + * // Feed decoder.out.frame into your renderer. + * }); + * ``` + */ + contribution(effect: Effect, id: string): Broadcast | undefined { + const catalog = effect.get(this.out.catalog); + const entry = catalog?.contributions?.[id]; + if (!entry || !Object.hasOwn(catalog?.contributions ?? {}, id)) return undefined; + const name = Path.tryResolve(effect.get(this.in.name), entry.broadcast); + if (name === undefined) throw new Catalog.EscapingBroadcast(entry.broadcast); + const child = new Broadcast({ + origin: this.in.origin, + name, + enabled: this.in.enabled, + announced: this.in.announced, + }); + effect.cleanup(() => child.close()); + return child; + } + close() { this.#signals.close(); for (const entry of this.#references.values()) entry.request.close(); diff --git a/js/watch/src/contribution.test.ts b/js/watch/src/contribution.test.ts new file mode 100644 index 00000000000..5a30286b123 --- /dev/null +++ b/js/watch/src/contribution.test.ts @@ -0,0 +1,100 @@ +import { expect, it } from "bun:test"; +import * as Catalog from "@moq/hang/catalog"; +import { Origin, Path } from "@moq/net"; +import { Effect } from "@moq/signals"; +import { Broadcast } from "./broadcast"; +import { Source } from "./video/source"; + +it("lists contributions without demand and keeps selected rendition IDs in their own broadcast", async () => { + const origin = new Origin.Producer(); + const parent = origin.createBroadcast(Path.from("room/main.hang")); + const contribution = origin.createBroadcast(Path.from("room/extra.hang")); + parent.announce(); + contribution.announce(); + const track = contribution.createTrack(Catalog.TRACK); + const catalog = Catalog.RootSchema.parse({ + video: { renditions: { video: { codec: "avc1.42001f", container: { kind: "legacy" } } } }, + contributions: { extra: { broadcast: "./extra.hang" }, missing: { broadcast: "./absent.hang" } }, + }); + const source = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog, + announced: false, + }); + const selection = new Effect(); + for (const [publisher, content] of [ + [parent, "source frames"], + [contribution, "contribution frames"], + ] as const) { + publisher.createTrack("video").writeFrame({ payload: new TextEncoder().encode(content) }); + } + try { + await source.out.catalog.changed(); + expect(source.out.catalog.peek()?.contributions).toEqual(catalog.contributions); + // Listing the reference does not subscribe to its existing catalog track. + expect(contribution.demand().used.peek()).toBe(false); + const child = source.contribution(selection, "extra"); + expect(child).toBeDefined(); + if (!child) throw new Error("missing selected contribution"); + await contribution.demand().used.changed(); + expect(contribution.demand().used.peek()).toBe(true); + track.writeFrame({ + timestamp: undefined, + payload: new TextEncoder().encode( + JSON.stringify({ + video: { renditions: { video: { codec: "vp8", container: { kind: "legacy" } } } }, + }), + ), + }); + await child.out.catalog.changed(); + expect(child.out.catalog.peek()?.video?.renditions.video.codec).toBe("vp8"); + expect(source.out.catalog.peek()?.video?.renditions.video.codec).toBe("avc1.42001f"); + const media = new Source({ broadcast: child, target: { name: "video" }, supported: async () => true }); + selection.cleanup(() => media.close()); + await media.out.config.changed(); + expect(media.out.track.peek()).toBe("video"); + const selected = child.relativeBroadcast(selection, media.out.config.peek()?.broadcast); + const frames = selected + ?.track(media.out.track.peek() ?? "") + .subscribe() + .ordered(); + const original = source.relativeBroadcast(selection, undefined)?.track("video").subscribe().ordered(); + try { + expect(await frames?.readString()).toBe("contribution frames"); + expect(await original?.readString()).toBe("source frames"); + } finally { + frames?.close(); + original?.close(); + } + expect(source.contribution(selection, "unknown")).toBeUndefined(); + const absent = origin.dynamic(Path.from("room/absent.hang")); + selection.cleanup(() => absent.close()); + const requests = absent.requested(); + const missing = source.contribution(selection, "missing"); + if (!missing) throw new Error("missing contribution selection"); + const { value: request } = await requests.next(); + expect(request?.path).toBe(Path.from("room/absent.hang")); + request?.reject(new Error("contribution unavailable")); + await missing.out.error.changed(); + expect(missing.out.active.peek()).toBeUndefined(); + expect(missing.out.error.peek()?.message).toBe("contribution unavailable"); + expect(source.out.catalog.peek()?.video?.renditions.video.codec).toBe("avc1.42001f"); + selection.close(); + await contribution.demand().unused(); + expect(contribution.demand().used.peek()).toBe(false); + } finally { + selection.close(); + source.close(); + origin.close(); + } +}); + +it("refuses malformed and escaping contribution entries", () => { + for (const entry of [null, {}, { broadcast: 42 }]) { + expect(() => Catalog.RootSchema.parse({ contributions: { extra: entry } })).toThrow(); + } + const catalog = Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "../../escape" } } }); + expect(() => Catalog.checkResolvable(catalog, Path.from("room/main.hang"))).toThrow(Catalog.EscapingBroadcast); +}); diff --git a/rs/hang/src/catalog/consumer.rs b/rs/hang/src/catalog/consumer.rs index aa67dd7c70a..53d82cc1633 100644 --- a/rs/hang/src/catalog/consumer.rs +++ b/rs/hang/src/catalog/consumer.rs @@ -66,6 +66,7 @@ fn check_resolvable(base: &PathOwned, catalog: &Catalog) -> Result<()> { .chain(text.map(|(_, config)| config.broadcast.as_ref())) .chain(json.map(|(_, config)| config.broadcast.as_ref())) .chain(binary.map(|(_, config)| config.broadcast.as_ref())) + .chain(catalog.contributions.values().map(|entry| Some(&entry.broadcast))) .flatten() { if !rel.is_empty() && base.try_resolve(rel).is_none() { @@ -80,6 +81,12 @@ fn check_resolvable(base: &PathOwned, catalog: &Catalog) -> Result<()> { mod test { use super::*; + #[test] + fn contributions_cannot_escape_the_root() { + let catalog = Catalog::<()>::from_str(r#"{"contributions":{"extra":{"broadcast":"../../escape"}}}"#).unwrap(); + assert!(check_resolvable(&PathOwned::from("room/main.hang"), &catalog).is_err()); + } + #[tokio::test] async fn subscribe_reads_a_typed_root() { let broadcast = moq_net::broadcast::Info::new().produce(); diff --git a/rs/hang/src/catalog/root.rs b/rs/hang/src/catalog/root.rs index 3698856fbb2..890d3e6873a 100644 --- a/rs/hang/src/catalog/root.rs +++ b/rs/hang/src/catalog/root.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; /// `archive` (each track's timeline and any durable recording), the optional `clock` (the /// broadcast's one wall-clock mapping), the data sections /// (`json`, `binary`) for application tracks that aren't media, and the optional `m2ts` (a -/// transport stream carried whole). +/// transport stream carried whole). `contributions` names whole broadcasts for explicit selection. /// Applications extend it with their own root sections (e.g. `scte35`) through `E`. The catalog /// does not deny unknown fields, so a base consumer ignores the extra sections and an extended /// catalog stays wire-compatible. See the `extension_roundtrip` test. @@ -29,6 +29,10 @@ use serde::{Deserialize, Serialize}; #[serde(bound(serialize = "E: Serialize", deserialize = "E: DeserializeOwned + Default"))] #[non_exhaustive] pub struct Catalog { + /// Whole broadcasts offered for explicit, lazy selection, keyed by contribution ID. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub contributions: std::collections::BTreeMap, + /// Video track information with multiple renditions. /// /// Contains a map of video track renditions that the viewer can choose from @@ -112,6 +116,13 @@ pub struct Catalog { pub ext: E, } +/// A whole broadcast whose catalog describes its own renditions. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct Contribution { + /// Reference resolved relative to the catalog broadcast. + pub broadcast: moq_net::path::RelativeOwned, +} + impl Catalog<()> { /// The default name for the catalog track. pub const DEFAULT_NAME: &str = "catalog.json"; @@ -167,6 +178,7 @@ impl Catalog { /// Copy the media sections into a catalog with no application extension. pub fn media(&self) -> Catalog<()> { Catalog { + contributions: self.contributions.clone(), video: self.video.clone(), audio: self.audio.clone(), archive: self.archive.clone(), @@ -338,6 +350,21 @@ mod test { } } + #[test] + fn contributions_round_trip_and_refuse_malformed_entries() { + let json = r#"{"contributions":{"extra":{"broadcast":"./extra.hang"}}}"#; + let catalog = Catalog::<()>::from_str(json).unwrap(); + assert_eq!(catalog.contributions["extra"].broadcast.as_str(), "extra.hang"); + assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog); + for json in [ + r#"{"contributions":{"extra":null}}"#, + r#"{"contributions":{"extra":{}}}"#, + r#"{"contributions":{"extra":{"broadcast":42}}}"#, + ] { + assert!(Catalog::<()>::from_str(json).is_err()); + } + } + #[test] fn cross_kind_duplicate_id_is_refused() { let catalog = Catalog::<()>::from_str( From 2a6337f2bd9c724937ea337d70a09f0decfb656d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 10 Oct 2026 18:04:46 -0700 Subject: [PATCH 3/7] fix(watch): retain selected contributions through catalog updates Co-Authored-By: Codex --- js/watch/src/broadcast.ts | 23 ++++++----- js/watch/src/contribution.test.ts | 64 ++++++++++++++++++++++++++++++- 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index 5fca06a670b..af334a7c65e 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -3,7 +3,7 @@ import * as Json from "@moq/json"; import * as Msf from "@moq/msf"; import type * as Moq from "@moq/net"; import { Error as NetError, Path, StreamCode } from "@moq/net"; -import { Effect, type Getter, getter, type Inputs, type Readonlys, readonlys, Signal } from "@moq/signals"; +import { Derived, Effect, type Getter, getter, type Inputs, type Readonlys, readonlys, Signal } from "@moq/signals"; import { toHang } from "./msf"; @@ -446,13 +446,13 @@ export class Broadcast { /** * Select a whole contribution, opening its catalog only while the caller owns this effect. + * An absent entry leaves the child disabled; adding or replacing it updates the child. * Wire the returned broadcast into a media source inside a nested effect. Its rendition * IDs stay local to that broadcast, so they never replace the parent catalog's IDs. * * ```ts * effects.run((effect) => { * const child = broadcast.contribution(effect, "extra"); - * if (!child) return; * const source = new Video.Source({ broadcast: child, supported: Video.Decoder.supported }); * effect.cleanup(() => source.close()); * const decoder = new Video.Decoder({ source, sync }); @@ -461,16 +461,19 @@ export class Broadcast { * }); * ``` */ - contribution(effect: Effect, id: string): Broadcast | undefined { - const catalog = effect.get(this.out.catalog); - const entry = catalog?.contributions?.[id]; - if (!entry || !Object.hasOwn(catalog?.contributions ?? {}, id)) return undefined; - const name = Path.tryResolve(effect.get(this.in.name), entry.broadcast); - if (name === undefined) throw new Catalog.EscapingBroadcast(entry.broadcast); + contribution(effect: Effect, id: string): Broadcast { + const selected = effect.computed((run) => { + const catalog = run.get(this.out.catalog); + const entry = catalog?.contributions?.[id]; + if (!entry || !Object.hasOwn(catalog?.contributions ?? {}, id)) return undefined; + const name = Path.tryResolve(run.get(this.in.name), entry.broadcast); + if (name === undefined) throw new Catalog.EscapingBroadcast(entry.broadcast); + return name; + }); const child = new Broadcast({ origin: this.in.origin, - name, - enabled: this.in.enabled, + name: new Derived([selected], (name) => name ?? Path.empty()), + enabled: new Derived([selected, this.in.enabled], (name, enabled) => name !== undefined && enabled), announced: this.in.announced, }); effect.cleanup(() => child.close()); diff --git a/js/watch/src/contribution.test.ts b/js/watch/src/contribution.test.ts index 5a30286b123..34d72a2e828 100644 --- a/js/watch/src/contribution.test.ts +++ b/js/watch/src/contribution.test.ts @@ -1,7 +1,7 @@ import { expect, it } from "bun:test"; import * as Catalog from "@moq/hang/catalog"; import { Origin, Path } from "@moq/net"; -import { Effect } from "@moq/signals"; +import { Effect, Signal } from "@moq/signals"; import { Broadcast } from "./broadcast"; import { Source } from "./video/source"; @@ -68,7 +68,7 @@ it("lists contributions without demand and keeps selected rendition IDs in their frames?.close(); original?.close(); } - expect(source.contribution(selection, "unknown")).toBeUndefined(); + expect(source.contribution(selection, "unknown").in.enabled.peek()).toBe(false); const absent = origin.dynamic(Path.from("room/absent.hang")); selection.cleanup(() => absent.close()); const requests = absent.requested(); @@ -98,3 +98,63 @@ it("refuses malformed and escaping contribution entries", () => { const catalog = Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "../../escape" } } }); expect(() => Catalog.checkResolvable(catalog, Path.from("room/main.hang"))).toThrow(Catalog.EscapingBroadcast); }); + +it("keeps a reactive selection through unrelated catalog updates and follows replacement and removal", async () => { + const origin = new Origin.Producer(); + const main = origin.createBroadcast(Path.from("room/main.hang")); + main.announce(); + const first = origin.createBroadcast(Path.from("room/first.hang")); + const second = origin.createBroadcast(Path.from("room/second.hang")); + for (const publisher of [first, second]) { + publisher.announce(); + publisher.createTrack(Catalog.TRACK).writeFrame({ payload: new TextEncoder().encode("{}") }); + } + const catalog = new Signal(Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./first.hang" } } })); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog, + announced: false, + }); + const selected = new Signal(undefined); + let selections = 0; + const owner = new Effect((effect) => { + selections += 1; + effect.set(selected, parent.contribution(effect, "extra")); + }); + try { + const child = await selected.changed(); + if (!child) throw new Error("selection did not create a child"); + await child.out.catalog.changed(); + const active = child.out.active.peek(); + let withdrawals = 0; + const dispose = first.demand().used.subscribe((used) => { + if (!used) withdrawals += 1; + }); + owner.cleanup(dispose); + catalog.set( + Catalog.RootSchema.parse({ + contributions: { extra: { broadcast: "./first.hang" }, other: { broadcast: "./other.hang" } }, + metadata: "changed", + }), + ); + await parent.out.catalog.changed(); + // The next selected-path update fences the unrelated update without a timer or flush count. + catalog.set(Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./second.hang" } } })); + await second.demand().used.changed(); + expect(selections).toBe(1); + expect(selected.peek()).toBe(child); + expect(active?.path).toBe(Path.from("room/first.hang")); + expect(child.out.active.peek()?.path).toBe(Path.from("room/second.hang")); + expect(withdrawals).toBe(1); + catalog.set(Catalog.RootSchema.parse({})); + await second.demand().unused(); + expect(child.in.enabled.peek()).toBe(false); + expect(selections).toBe(1); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); From 6d06e12f732baea2beac29cf98b7add979d7fbd3 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:23:16 -0700 Subject: [PATCH 4/7] feat(hang): pin whole contribution references Co-Authored-By: GPT-5.4 --- doc/concept/hang.md | 2 +- drafts/draft-lcurley-moq-hang.md | 10 +++- js/hang/src/catalog/root.test.ts | 2 + js/hang/src/catalog/root.ts | 6 ++- js/watch/src/broadcast.ts | 41 +++++++++++--- js/watch/src/contribution.test.ts | 89 +++++++++++++++++++++++++++---- rs/hang/src/catalog/root.rs | 17 +++++- 7 files changed, 145 insertions(+), 22 deletions(-) diff --git a/doc/concept/hang.md b/doc/concept/hang.md index c807ae7f3ef..77030fcc80b 100644 --- a/doc/concept/hang.md +++ b/doc/concept/hang.md @@ -65,7 +65,7 @@ A few things the catalog can express beyond decoder config: - **Labels.** Any rendition may carry a human-readable `label` for a track picker. The map key stays the rendition's ID, so labels need not be unique and renaming one doesn't rename the track. - **Renditions in another broadcast.** A rendition may point at a relative broadcast path, so a transcoder can publish a ladder that adds low rungs and references the source's original rendition without re-publishing its bytes. The path resolves against where the consumer found the catalog, so a reference that escapes above the root names nothing and the catalog is rejected. A consumer reads each referenced path from the first broadcast it resolves there. An optional `epoch` beside the path names the [publisher instance](/concept/moq-lite#publisher-epochs) it expects: a route proving another instance fails the rendition instead of falling back to it, while a route without an epoch (an older version) cannot prove one, so there it is best effort. - **Track names.** The map key is a rendition's ID and, by default, its track name. A rendition sets `track` only when the two must differ, such as two renditions of same-named tracks in different broadcasts, or a rendition whose media changed and so needs a new name; readers subscribe to `track` when present. An ID can't name both a video and an audio rendition. -- **Whole contributions.** A catalog can list relative broadcast references without fetching their catalogs. Explicit selection opens a contribution, whose rendition names remain separate from the source. `@moq/watch` exposes this as a scoped child broadcast; listing contributions alone never starts their media producers. +- **Whole contributions.** A catalog can list relative broadcast references without fetching their catalogs. Explicit selection opens and pins a contribution, optionally requiring its `epoch`; later catalog updates cannot retarget the selection. Its rendition names remain separate from the source. `@moq/watch` exposes this as a scoped child broadcast, and listing contributions alone never starts their media producers. - **Jitter.** A rendition can say how far its frames fell behind the media clock before the publisher flushed them, in whole milliseconds rounded up. Encoders report the spread of lateness above each rendition's own recent minimum, so a constant encoder delay is not jitter; container imports estimate batch spans without counting ingest delay. It describes the publisher, never the network, only grows over the life of a stream, and a player sizes its buffer to at least this much. A `0` is read as absent. - **Delay.** A rendition can also say how far its frames reach the transport behind the broadcast's earliest rendition, measured the same way from each rendition's minimum lateness, so a video encoder running 200 ms behind audio advertises `delay: 200` on video. It follows the same rules as jitter. A player holds the largest `delay + jitter` among the renditions it subscribes to, and never subtracts one rendition's `delay` from another's. - **Disabled renditions.** An audio or video rendition with `enabled: false` has no frames coming, and a player must not select it. Pausing a rendition in `@moq/publish` keeps it in the catalog this way rather than removing it, so a mute is a one-field update; a disabled video rendition encodes one black keyframe first, so a player that predates the field shows black instead of a frozen picture. The field is written only when false. The older video `stalled` field is no longer written, and readers ignore it. diff --git a/drafts/draft-lcurley-moq-hang.md b/drafts/draft-lcurley-moq-hang.md index 8747c799e02..01f41b00d2f 100644 --- a/drafts/draft-lcurley-moq-hang.md +++ b/drafts/draft-lcurley-moq-hang.md @@ -123,7 +123,10 @@ The root of the catalog is a JSON document with the following schema: ~~~ type Catalog = { - "contributions": Record | undefined, + "contributions": Record | undefined, "audio": AudioSchema | undefined, "video": VideoSchema | undefined, "archive": ArchiveSchema | undefined, @@ -147,10 +150,13 @@ This specification defines audio, video, and text media tracks, plus an optional ## Contributions {#contributions} The optional `contributions` map names whole broadcasts whose catalogs describe their renditions. -Each entry MUST contain a string `broadcast`, resolved relative to this catalog's broadcast using {{field-broadcast}}. +Each entry MUST contain a string `broadcast`, resolved relative to this catalog's broadcast using {{field-broadcast}}, and MAY contain an `epoch` using {{field-epoch}}. A malformed entry or a reference escaping the root MUST cause the catalog to be rejected. Listing an entry MUST NOT subscribe to the contribution; a consumer opens its catalog only upon explicit selection. +A selected contribution stays on the first publisher instance it resolves for the referring catalog instance. +When `epoch` is present, a route proving another instance MUST fail the selection; without it, a route carrying no Epoch cannot authorize stitching onto a replacement. +A later catalog update MUST NOT retarget a resolved selection, while a new referring catalog instance resolves it afresh. A contribution's rendition identifiers belong to that contribution and MUST NOT replace identifiers in the referring catalog. An unavailable contribution does not invalidate the referring catalog. References are not recursively expanded: each further contribution requires an explicit selection. diff --git a/js/hang/src/catalog/root.test.ts b/js/hang/src/catalog/root.test.ts index 15e96a3dddc..e4800dbf3d1 100644 --- a/js/hang/src/catalog/root.test.ts +++ b/js/hang/src/catalog/root.test.ts @@ -49,6 +49,7 @@ test("rendition broadcast reference is parsed and normalized", () => { test("every reference-bearing section carries an optional epoch", () => { const EPOCH = "01890a5d-ac96-774b-bcce-b302099a8057" as ReferenceEpoch; const catalog = (epoch: string) => ({ + contributions: { c: { broadcast: "./a", epoch } }, video: { renditions: { v: { broadcast: "./a", epoch, codec: "avc1.64001f", container: { kind: "legacy" } }, @@ -81,6 +82,7 @@ test("every reference-bearing section carries an optional epoch", () => { expect(parsed.json?.tracks.j?.epoch).toBe(EPOCH); expect(parsed.binary?.tracks.b?.epoch).toBe(EPOCH); expect(parsed.archive?.replayEpoch).toBe(EPOCH); + expect(parsed.contributions?.c?.epoch).toBe(EPOCH); // A malformed or noncanonical epoch refuses the catalog, as in Rust. for (const bad of ["not-a-uuid", EPOCH.toUpperCase(), "01890a5d-ac96-474b-bcce-b302099a8057"]) { diff --git a/js/hang/src/catalog/root.ts b/js/hang/src/catalog/root.ts index a66075ad82d..bb8d24d38f6 100644 --- a/js/hang/src/catalog/root.ts +++ b/js/hang/src/catalog/root.ts @@ -8,7 +8,7 @@ import { BinarySchema } from "./binary"; import { ClockSchema } from "./clock"; import { TRACK } from "./format"; import { JsonSchema } from "./json"; -import { type RelativeBroadcast, RelativeBroadcastSchema } from "./path"; +import { EpochSchema, type RelativeBroadcast, RelativeBroadcastSchema } from "./path"; import { PRIORITY } from "./priority"; import { section } from "./section"; import { TextSchema } from "./text"; @@ -29,7 +29,9 @@ import { VideoSchema } from "./video"; */ export const RootSchema = z.looseObject({ // Whole broadcasts are listed without opening their catalogs. IDs stay scoped to each broadcast. - contributions: z.optional(z.record(z.string(), z.object({ broadcast: RelativeBroadcastSchema }))), + contributions: z.optional( + z.record(z.string(), z.object({ broadcast: RelativeBroadcastSchema, epoch: z.optional(EpochSchema) })), + ), video: z.optional(VideoSchema), audio: z.optional(AudioSchema), // An incompatible archive disables seeking/recording, not the rest of the catalog. diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index af334a7c65e..c8f9d1c4e57 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -89,6 +89,9 @@ export type BroadcastInput = { // The broadcast name. name: Getter; + // The publisher instance to request. Omitted for an unpinned broadcast. + epoch: Getter; + // Whether to wait for the broadcast to be announced before subscribing. // Defaults to true; pass false to subscribe immediately without waiting for an announcement. announced: Getter; @@ -162,6 +165,7 @@ export class Broadcast { this.in = { origin: getter(props?.origin), name: getter(props?.name ?? Path.empty()), + epoch: getter(props?.epoch), enabled: getter(props?.enabled ?? true), announced: getter(props?.announced ?? true), catalogFormat: getter(props?.catalogFormat), @@ -248,11 +252,12 @@ export class Broadcast { if (!origin) return; const name = effect.get(this.in.name); + const epoch = effect.get(this.in.epoch); const announced = effect.get(this.in.announced); let request: Moq.Origin.Requesting; try { - request = origin.request(name, { announced }); + request = origin.request(name, { announced, epoch }); } catch (err) { effect.set(this.#out.error, err instanceof Error ? err : new Error(String(err)), undefined); return; @@ -264,6 +269,12 @@ export class Broadcast { if (active) resolved = true; nested.set(this.#out.active, active, undefined); }); + if (epoch !== undefined) { + effect.run((nested) => { + if (!nested.get(request.unroutable)) return; + nested.set(this.#out.error, new Error(`broadcast ${name} does not serve epoch ${epoch}`), undefined); + }); + } effect.run((nested) => { const closed = nested.get(request.closed); if (!closed) return; @@ -462,19 +473,37 @@ export class Broadcast { * ``` */ contribution(effect: Effect, id: string): Broadcast { - const selected = effect.computed((run) => { + type Selection = { parent: Moq.Broadcast.Consumer | undefined; name: Moq.Path.Valid; epoch?: Moq.Epoch.Valid }; + const pinned = new Signal(undefined); + const selected = effect.computed((run): Selection | undefined => { + const parent = run.get(this.out.active); + const existing = run.get(pinned); + if (existing && existing.parent === parent) return existing; const catalog = run.get(this.out.catalog); const entry = catalog?.contributions?.[id]; if (!entry || !Object.hasOwn(catalog?.contributions ?? {}, id)) return undefined; const name = Path.tryResolve(run.get(this.in.name), entry.broadcast); if (name === undefined) throw new Catalog.EscapingBroadcast(entry.broadcast); - return name; + return { parent, name, epoch: entry.epoch }; }); const child = new Broadcast({ origin: this.in.origin, - name: new Derived([selected], (name) => name ?? Path.empty()), - enabled: new Derived([selected, this.in.enabled], (name, enabled) => name !== undefined && enabled), - announced: this.in.announced, + name: new Derived([selected], (selection) => selection?.name ?? Path.empty()), + epoch: new Derived([selected], (selection) => selection?.epoch), + enabled: new Derived( + [selected, this.in.enabled], + (selection, enabled) => selection !== undefined && enabled, + ), + // A contribution follows no replacement. With an explicit epoch the request enforces it; + // without one, a blind request retains the first resolved publisher handle. + announced: false, + }); + effect.run((run) => { + const active = run.get(child.out.active); + const selection = run.get(selected); + const existing = run.get(pinned); + if (!active || !selection || existing?.parent === selection.parent) return; + pinned.set({ ...selection, epoch: selection.epoch ?? active.epoch }); }); effect.cleanup(() => child.close()); return child; diff --git a/js/watch/src/contribution.test.ts b/js/watch/src/contribution.test.ts index 34d72a2e828..325ba8a4f1d 100644 --- a/js/watch/src/contribution.test.ts +++ b/js/watch/src/contribution.test.ts @@ -1,6 +1,6 @@ import { expect, it } from "bun:test"; import * as Catalog from "@moq/hang/catalog"; -import { Origin, Path } from "@moq/net"; +import { Epoch, Origin, Path } from "@moq/net"; import { Effect, Signal } from "@moq/signals"; import { Broadcast } from "./broadcast"; import { Source } from "./video/source"; @@ -92,14 +92,14 @@ it("lists contributions without demand and keeps selected rendition IDs in their }); it("refuses malformed and escaping contribution entries", () => { - for (const entry of [null, {}, { broadcast: 42 }]) { + for (const entry of [null, {}, { broadcast: 42 }, { broadcast: "./extra.hang", epoch: "not-an-epoch" }]) { expect(() => Catalog.RootSchema.parse({ contributions: { extra: entry } })).toThrow(); } const catalog = Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "../../escape" } } }); expect(() => Catalog.checkResolvable(catalog, Path.from("room/main.hang"))).toThrow(Catalog.EscapingBroadcast); }); -it("keeps a reactive selection through unrelated catalog updates and follows replacement and removal", async () => { +it("pins the first resolved contribution through catalog retargeting and removal", async () => { const origin = new Origin.Producer(); const main = origin.createBroadcast(Path.from("room/main.hang")); main.announce(); @@ -140,17 +140,19 @@ it("keeps a reactive selection through unrelated catalog updates and follows rep }), ); await parent.out.catalog.changed(); - // The next selected-path update fences the unrelated update without a timer or flush count. + // Once resolved, neither a changed path nor removing the entry retargets this selection. catalog.set(Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./second.hang" } } })); - await second.demand().used.changed(); + await parent.out.catalog.changed(); expect(selections).toBe(1); expect(selected.peek()).toBe(child); expect(active?.path).toBe(Path.from("room/first.hang")); - expect(child.out.active.peek()?.path).toBe(Path.from("room/second.hang")); - expect(withdrawals).toBe(1); + expect(child.out.active.peek()?.path).toBe(Path.from("room/first.hang")); + expect(second.demand().used.peek()).toBe(false); + expect(withdrawals).toBe(0); catalog.set(Catalog.RootSchema.parse({})); - await second.demand().unused(); - expect(child.in.enabled.peek()).toBe(false); + await parent.out.catalog.changed(); + expect(child.in.enabled.peek()).toBe(true); + expect(child.out.active.peek()?.path).toBe(Path.from("room/first.hang")); expect(selections).toBe(1); } finally { owner.close(); @@ -158,3 +160,72 @@ it("keeps a reactive selection through unrelated catalog updates and follows rep origin.close(); } }); + +it("pins and validates a contribution epoch before reading its catalog", async () => { + const origin = new Origin.Producer(); + const main = origin.createBroadcast(Path.from("room/main.hang")); + main.announce(); + const contribution = origin.createBroadcast(Path.from("room/extra.hang")); + const epoch = Epoch.mint(); + contribution.announce({ epoch }); + contribution.createTrack(Catalog.TRACK).writeFrame({ payload: new TextEncoder().encode("{}") }); + const other = Epoch.mint(); + const catalog = new Signal( + Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./extra.hang", epoch } } }), + ); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog, + announced: false, + }); + const owner = new Effect(); + try { + const child = parent.contribution(owner, "extra"); + await child.out.catalog.changed(); + expect(child.out.active.peek()?.epoch).toBe(epoch); + expect(child.in.epoch.peek()).toBe(epoch); + + catalog.set( + Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./extra.hang", epoch: other } } }), + ); + await parent.out.catalog.changed(); + expect(child.in.epoch.peek()).toBe(epoch); + expect(child.out.active.peek()?.epoch).toBe(epoch); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); + +it("refuses a contribution served by another known epoch", async () => { + const origin = new Origin.Producer(); + const main = origin.createBroadcast(Path.from("room/main.hang")); + main.announce(); + const contribution = origin.createBroadcast(Path.from("room/extra.hang")); + contribution.announce({ epoch: Epoch.mint() }); + const track = contribution.createTrack(Catalog.TRACK); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog: Catalog.RootSchema.parse({ + contributions: { extra: { broadcast: "./extra.hang", epoch: Epoch.mint() } }, + }), + announced: false, + }); + const owner = new Effect(); + try { + const child = parent.contribution(owner, "extra"); + await child.out.error.changed(); + expect(child.out.active.peek()).toBeUndefined(); + expect(contribution.demand().used.peek()).toBe(false); + expect(track.demand().used.peek()).toBe(false); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); diff --git a/rs/hang/src/catalog/root.rs b/rs/hang/src/catalog/root.rs index 890d3e6873a..21752b8b14f 100644 --- a/rs/hang/src/catalog/root.rs +++ b/rs/hang/src/catalog/root.rs @@ -117,10 +117,16 @@ pub struct Catalog { } /// A whole broadcast whose catalog describes its own renditions. +#[serde_with::serde_as] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Contribution { /// Reference resolved relative to the catalog broadcast. pub broadcast: moq_net::path::RelativeOwned, + + /// The publisher instance the contribution must resolve to, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde_as(as = "Option")] + pub epoch: Option, } impl Catalog<()> { @@ -315,6 +321,7 @@ mod test { const EPOCH: &str = "01890a5d-ac96-774b-bcce-b302099a8057"; let encoded = format!( r#"{{ + "contributions": {{"c": {{"broadcast": "./a", "epoch": "{EPOCH}"}}}}, "video": {{"renditions": {{"v": {{"broadcast": "./a", "epoch": "{EPOCH}", "codec": "avc1.64001f", "container": {{"kind": "legacy"}}}}}}}}, "audio": {{"renditions": {{"a": {{"broadcast": "./a", "epoch": "{EPOCH}", "codec": "opus", "sampleRate": 48000, "numberOfChannels": 2, "container": {{"kind": "legacy"}}}}}}}}, "text": {{"renditions": {{"t": {{"broadcast": "./a", "epoch": "{EPOCH}", "format": "vtt"}}}}}}, @@ -335,7 +342,8 @@ mod test { for reference in references { assert_eq!(reference.epoch(), Some(&epoch)); } - assert_eq!(catalog.archive.as_ref().unwrap().replay_epoch, Some(epoch)); + assert_eq!(catalog.archive.as_ref().unwrap().replay_epoch.as_ref(), Some(&epoch)); + assert_eq!(catalog.contributions["c"].epoch.as_ref(), Some(&epoch)); assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog); // Omitted stays omitted, and a malformed or noncanonical epoch refuses the catalog. @@ -352,14 +360,19 @@ mod test { #[test] fn contributions_round_trip_and_refuse_malformed_entries() { - let json = r#"{"contributions":{"extra":{"broadcast":"./extra.hang"}}}"#; + let json = r#"{"contributions":{"extra":{"broadcast":"./extra.hang","epoch":"01890a5d-ac96-774b-bcce-b302099a8057"}}}"#; let catalog = Catalog::<()>::from_str(json).unwrap(); assert_eq!(catalog.contributions["extra"].broadcast.as_str(), "extra.hang"); + assert_eq!( + catalog.contributions["extra"].epoch.as_ref().unwrap().to_string(), + "01890a5d-ac96-774b-bcce-b302099a8057" + ); assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog); for json in [ r#"{"contributions":{"extra":null}}"#, r#"{"contributions":{"extra":{}}}"#, r#"{"contributions":{"extra":{"broadcast":42}}}"#, + r#"{"contributions":{"extra":{"broadcast":"./extra.hang","epoch":"not-an-epoch"}}}"#, ] { assert!(Catalog::<()>::from_str(json).is_err()); } From 1bac3252f50b0d75d3ad0a2d22610b2369aa3583 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 16 Oct 2026 18:11:48 -0700 Subject: [PATCH 5/7] fix(watch): resolve a contribution like any other catalog reference A selected contribution pinned its first publisher instance for the parent catalog's lifetime and requested it blind, so a contributor that restarted vanished until the parent did, and an `epoch` passed to the origin refused every epochless (default lite-06) route. @moq/watch follows announcements for rendition references, so a contribution now does the same: an entry without `epoch` follows restarts, one with `epoch` reads as offline while its broadcast proves another instance, and an epochless route stays best effort. The draft points at the existing reference rules instead of restating different ones. Rust `Contribution` gains `#[non_exhaustive]` and `new` like the other catalog entries. Co-Authored-By: Claude Opus 5.5 --- doc/concept/hang.md | 2 +- drafts/draft-lcurley-moq-hang.md | 4 +- js/watch/src/broadcast.ts | 72 +++++--------- js/watch/src/contribution.test.ts | 150 ++++++++++++++++++------------ rs/hang/src/catalog/root.rs | 13 ++- 5 files changed, 131 insertions(+), 110 deletions(-) diff --git a/doc/concept/hang.md b/doc/concept/hang.md index e9876cbe21a..e61b2a71d30 100644 --- a/doc/concept/hang.md +++ b/doc/concept/hang.md @@ -65,7 +65,7 @@ A few things the catalog can express beyond decoder config: - **Labels.** Any rendition may carry a human-readable `label` for a track picker. The map key stays the rendition's ID, so labels need not be unique and renaming one doesn't rename the track. - **Renditions in another broadcast.** A rendition may point at a relative broadcast path, so a transcoder can publish a ladder that adds low rungs and references the source's original rendition without re-publishing its bytes. The path resolves against where the consumer found the catalog, so a reference that escapes above the root names nothing and the catalog is rejected. A consumer reads each referenced path from the first broadcast it resolves there. An optional `epoch` beside the path names the [publisher instance](/concept/moq-lite#publisher-epochs) it expects: a route proving another instance fails the rendition instead of falling back to it, while a route without an epoch (an older version) cannot prove one, so there it is best effort. - **Track names.** The map key is a rendition's ID and, by default, its track name. A rendition sets `track` only when the two must differ, such as two renditions of same-named tracks in different broadcasts, or a rendition whose media changed and so needs a new name; readers subscribe to `track` when present. An ID can't name both a video and an audio rendition. -- **Whole contributions.** A catalog can list relative broadcast references without fetching their catalogs. Explicit selection opens and pins a contribution, optionally requiring its `epoch`; later catalog updates cannot retarget the selection. Its rendition names remain separate from the source. `@moq/watch` exposes this as a scoped child broadcast, and listing contributions alone never starts their media producers. +- **Whole contributions.** A catalog can list relative broadcast references without fetching their catalogs. Explicit selection opens a contribution, which resolves like a rendition's reference, including its optional `epoch`. Its rendition names remain separate from the source. `@moq/watch` exposes this as a scoped child broadcast, and listing contributions alone never starts their media producers. - **Jitter.** A rendition can say how far its frames fell behind the media clock before the publisher flushed them, in whole milliseconds rounded up. Encoders report the spread of lateness above each rendition's own recent minimum, so a constant encoder delay is not jitter; container imports estimate batch spans without counting ingest delay. It describes the publisher, never the network, only grows over the life of a stream, and a player sizes its buffer to at least this much. A `0` is read as absent. - **Delay.** A rendition can also say how far its frames reach the transport behind the broadcast's earliest rendition, measured the same way from each rendition's minimum lateness, so a video encoder running 200 ms behind audio advertises `delay: 200` on video. It follows the same rules as jitter. A player holds the largest `delay + jitter` among the renditions it subscribes to, and never subtracts one rendition's `delay` from another's. - **Disabled renditions.** An audio or video rendition with `enabled: false` has no frames coming, and a player must not select it. Pausing a rendition in `@moq/publish` keeps it in the catalog this way rather than removing it, so a mute is a one-field update; a disabled video rendition encodes one black keyframe first, so a player that predates the field shows black instead of a frozen picture. The field is written only when false. The older video `stalled` field is no longer written, and readers ignore it. diff --git a/drafts/draft-lcurley-moq-hang.md b/drafts/draft-lcurley-moq-hang.md index f10d8fb625b..e1bc528e7d1 100644 --- a/drafts/draft-lcurley-moq-hang.md +++ b/drafts/draft-lcurley-moq-hang.md @@ -154,9 +154,7 @@ Each entry MUST contain a string `broadcast`, resolved relative to this catalog' A malformed entry or a reference escaping the root MUST cause the catalog to be rejected. Listing an entry MUST NOT subscribe to the contribution; a consumer opens its catalog only upon explicit selection. -A selected contribution stays on the first publisher instance it resolves for the referring catalog instance. -When `epoch` is present, a route proving another instance MUST fail the selection; without it, a route carrying no Epoch cannot authorize stitching onto a replacement. -A later catalog update MUST NOT retarget a resolved selection, while a new referring catalog instance resolves it afresh. +A selected contribution resolves like a rendition's reference, under the same rules for `epoch` and restarts ({{field-epoch}}). A contribution's rendition identifiers belong to that contribution and MUST NOT replace identifiers in the referring catalog. An unavailable contribution does not invalidate the referring catalog. References are not recursively expanded: each further contribution requires an explicit selection. diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index c8f9d1c4e57..87632f05d79 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -89,7 +89,8 @@ export type BroadcastInput = { // The broadcast name. name: Getter; - // The publisher instance to request. Omitted for an unpinned broadcast. + // The publisher instance to read: a broadcast proven to be another one reads as offline. + // A route without an epoch cannot prove one, so there it is best effort. Omitted to accept any. epoch: Getter; // Whether to wait for the broadcast to be announced before subscribing. @@ -252,12 +253,13 @@ export class Broadcast { if (!origin) return; const name = effect.get(this.in.name); - const epoch = effect.get(this.in.epoch); const announced = effect.get(this.in.announced); + // The epoch is checked against the stamped one rather than passed to the origin, which + // would refuse every epochless route and so break best effort on older sessions. let request: Moq.Origin.Requesting; try { - request = origin.request(name, { announced, epoch }); + request = origin.request(name, { announced }); } catch (err) { effect.set(this.#out.error, err instanceof Error ? err : new Error(String(err)), undefined); return; @@ -267,14 +269,13 @@ export class Broadcast { effect.run((nested) => { const active = nested.get(request.active); if (active) resolved = true; + const epoch = nested.get(this.in.epoch); + if (active && epoch !== undefined && active.epoch !== undefined && active.epoch !== epoch) { + console.warn("ignoring broadcast: it serves another epoch", name, active.epoch, epoch); + return; + } nested.set(this.#out.active, active, undefined); }); - if (epoch !== undefined) { - effect.run((nested) => { - if (!nested.get(request.unroutable)) return; - nested.set(this.#out.error, new Error(`broadcast ${name} does not serve epoch ${epoch}`), undefined); - }); - } effect.run((nested) => { const closed = nested.get(request.closed); if (!closed) return; @@ -311,15 +312,7 @@ export class Broadcast { const catalog = effect.get(this.in.catalog); let accepted: Catalog.Root | undefined; try { - accepted = - catalog && - Catalog.checkResolvable( - Catalog.checkRenditions({ - ...catalog, - contributions: Catalog.RootSchema.shape.contributions.parse(catalog.contributions), - }), - name, - ); + accepted = catalog && Catalog.checkResolvable(Catalog.checkRenditions(catalog), name); } catch (err) { console.error("rejecting catalog", name, err); } @@ -457,7 +450,9 @@ export class Broadcast { /** * Select a whole contribution, opening its catalog only while the caller owns this effect. - * An absent entry leaves the child disabled; adding or replacing it updates the child. + * The child tracks the catalog entry and resolves like a rendition's reference (see + * `relativeBroadcast`): without an `epoch` it follows restarts, and with one it is offline + * while its broadcast proves another instance. An absent entry leaves the child disabled. * Wire the returned broadcast into a media source inside a nested effect. Its rendition * IDs stay local to that broadcast, so they never replace the parent catalog's IDs. * @@ -473,37 +468,20 @@ export class Broadcast { * ``` */ contribution(effect: Effect, id: string): Broadcast { - type Selection = { parent: Moq.Broadcast.Consumer | undefined; name: Moq.Path.Valid; epoch?: Moq.Epoch.Valid }; - const pinned = new Signal(undefined); - const selected = effect.computed((run): Selection | undefined => { - const parent = run.get(this.out.active); - const existing = run.get(pinned); - if (existing && existing.parent === parent) return existing; - const catalog = run.get(this.out.catalog); - const entry = catalog?.contributions?.[id]; - if (!entry || !Object.hasOwn(catalog?.contributions ?? {}, id)) return undefined; - const name = Path.tryResolve(run.get(this.in.name), entry.broadcast); - if (name === undefined) throw new Catalog.EscapingBroadcast(entry.broadcast); - return { parent, name, epoch: entry.epoch }; + // Deduplicated, so a catalog update that leaves this entry alone keeps the child's request. + const target = effect.computed((run): { name: Moq.Path.Valid; epoch?: Moq.Epoch.Valid } | undefined => { + const contributions = run.get(this.out.catalog)?.contributions; + if (!contributions || !Object.hasOwn(contributions, id)) return undefined; + const { broadcast, epoch } = contributions[id]; + const name = Path.tryResolve(run.get(this.in.name), broadcast); + return name === undefined ? undefined : { name, epoch }; }); const child = new Broadcast({ origin: this.in.origin, - name: new Derived([selected], (selection) => selection?.name ?? Path.empty()), - epoch: new Derived([selected], (selection) => selection?.epoch), - enabled: new Derived( - [selected, this.in.enabled], - (selection, enabled) => selection !== undefined && enabled, - ), - // A contribution follows no replacement. With an explicit epoch the request enforces it; - // without one, a blind request retains the first resolved publisher handle. - announced: false, - }); - effect.run((run) => { - const active = run.get(child.out.active); - const selection = run.get(selected); - const existing = run.get(pinned); - if (!active || !selection || existing?.parent === selection.parent) return; - pinned.set({ ...selection, epoch: selection.epoch ?? active.epoch }); + name: new Derived([target], (target) => target?.name ?? Path.empty()), + epoch: new Derived([target], (target) => target?.epoch), + enabled: new Derived([target, this.in.enabled], (target, enabled) => target !== undefined && enabled), + announced: this.in.announced, }); effect.cleanup(() => child.close()); return child; diff --git a/js/watch/src/contribution.test.ts b/js/watch/src/contribution.test.ts index 325ba8a4f1d..c949093f431 100644 --- a/js/watch/src/contribution.test.ts +++ b/js/watch/src/contribution.test.ts @@ -99,7 +99,21 @@ it("refuses malformed and escaping contribution entries", () => { expect(() => Catalog.checkResolvable(catalog, Path.from("room/main.hang"))).toThrow(Catalog.EscapingBroadcast); }); -it("pins the first resolved contribution through catalog retargeting and removal", async () => { +const settle = async (): Promise => { + for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0)); +}; + +async function quietly(fn: () => Promise): Promise { + const warn = console.warn; + console.warn = () => {}; + try { + return await fn(); + } finally { + console.warn = warn; + } +} + +it("tracks the contribution entry without reopening it on unrelated catalog updates", async () => { const origin = new Origin.Producer(); const main = origin.createBroadcast(Path.from("room/main.hang")); main.announce(); @@ -117,43 +131,40 @@ it("pins the first resolved contribution through catalog retargeting and removal catalog, announced: false, }); - const selected = new Signal(undefined); - let selections = 0; - const owner = new Effect((effect) => { - selections += 1; - effect.set(selected, parent.contribution(effect, "extra")); - }); + const owner = new Effect(); try { - const child = await selected.changed(); - if (!child) throw new Error("selection did not create a child"); + const child = parent.contribution(owner, "extra"); await child.out.catalog.changed(); const active = child.out.active.peek(); + expect(active?.path).toBe(Path.from("room/first.hang")); + + // An update that leaves the entry alone keeps the same request. let withdrawals = 0; - const dispose = first.demand().used.subscribe((used) => { - if (!used) withdrawals += 1; - }); - owner.cleanup(dispose); + owner.cleanup( + first.demand().used.subscribe((used) => { + if (!used) withdrawals += 1; + }), + ); catalog.set( Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./first.hang" }, other: { broadcast: "./other.hang" } }, metadata: "changed", }), ); - await parent.out.catalog.changed(); - // Once resolved, neither a changed path nor removing the entry retargets this selection. - catalog.set(Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./second.hang" } } })); - await parent.out.catalog.changed(); - expect(selections).toBe(1); - expect(selected.peek()).toBe(child); - expect(active?.path).toBe(Path.from("room/first.hang")); - expect(child.out.active.peek()?.path).toBe(Path.from("room/first.hang")); - expect(second.demand().used.peek()).toBe(false); + await settle(); + expect(child.out.active.peek()).toBe(active); expect(withdrawals).toBe(0); + + // A changed path is a different reference, so the child follows it. + catalog.set(Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./second.hang" } } })); + await settle(); + expect(child.out.active.peek()?.path).toBe(Path.from("room/second.hang")); + + // Removing the entry disables the child. catalog.set(Catalog.RootSchema.parse({})); - await parent.out.catalog.changed(); - expect(child.in.enabled.peek()).toBe(true); - expect(child.out.active.peek()?.path).toBe(Path.from("room/first.hang")); - expect(selections).toBe(1); + await settle(); + expect(child.in.enabled.peek()).toBe(false); + expect(child.out.active.peek()).toBeUndefined(); } finally { owner.close(); parent.close(); @@ -161,68 +172,91 @@ it("pins the first resolved contribution through catalog retargeting and removal } }); -it("pins and validates a contribution epoch before reading its catalog", async () => { +it("follows a restarted contribution only for an entry that names no epoch", async () => { const origin = new Origin.Producer(); const main = origin.createBroadcast(Path.from("room/main.hang")); main.announce(); - const contribution = origin.createBroadcast(Path.from("room/extra.hang")); - const epoch = Epoch.mint(); - contribution.announce({ epoch }); - contribution.createTrack(Catalog.TRACK).writeFrame({ payload: new TextEncoder().encode("{}") }); - const other = Epoch.mint(); - const catalog = new Signal( - Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./extra.hang", epoch } } }), - ); + const [oldEpoch, newEpoch] = [Epoch.mint(), Epoch.mint()]; + const old = origin.createBroadcast(Path.from("room/extra.hang")); + old.announce({ epoch: oldEpoch }); const parent = new Broadcast({ origin, name: Path.from("room/main.hang"), catalogFormat: "manual", - catalog, - announced: false, + catalog: Catalog.RootSchema.parse({ + contributions: { + following: { broadcast: "./extra.hang" }, + pinned: { broadcast: "./extra.hang", epoch: oldEpoch }, + }, + }), }); const owner = new Effect(); try { - const child = parent.contribution(owner, "extra"); - await child.out.catalog.changed(); - expect(child.out.active.peek()?.epoch).toBe(epoch); - expect(child.in.epoch.peek()).toBe(epoch); + const following = parent.contribution(owner, "following"); + const pinned = parent.contribution(owner, "pinned"); + await settle(); + expect(following.out.active.peek()?.epoch).toBe(oldEpoch); + expect(pinned.out.active.peek()?.epoch).toBe(oldEpoch); - catalog.set( - Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./extra.hang", epoch: other } } }), - ); - await parent.out.catalog.changed(); - expect(child.in.epoch.peek()).toBe(epoch); - expect(child.out.active.peek()?.epoch).toBe(epoch); + // The announcement is the online signal: the plain entry follows the restart, while the + // one naming the old instance goes offline rather than reading the new one. + const replacement = origin.createBroadcast(Path.from("room/extra.hang")); + replacement.announce({ epoch: newEpoch }); + await quietly(settle); + expect(following.out.active.peek()?.epoch).toBe(newEpoch); + expect(pinned.out.active.peek()).toBeUndefined(); + expect(pinned.out.status.peek()).toBe("offline"); + replacement.close(); } finally { owner.close(); parent.close(); + old.close(); origin.close(); } }); -it("refuses a contribution served by another known epoch", async () => { +it("never reads a contribution proven to be another epoch, but reads an epochless route", async () => { const origin = new Origin.Producer(); const main = origin.createBroadcast(Path.from("room/main.hang")); main.announce(); - const contribution = origin.createBroadcast(Path.from("room/extra.hang")); - contribution.announce({ epoch: Epoch.mint() }); - const track = contribution.createTrack(Catalog.TRACK); + const served = Epoch.mint(); + const proven = origin.createBroadcast(Path.from("room/proven.hang")); + proven.announce({ epoch: served }); + const track = proven.createTrack(Catalog.TRACK); + const plain = origin.createBroadcast(Path.from("room/plain.hang")); + plain.announce(); + plain.createTrack(Catalog.TRACK).writeFrame({ payload: new TextEncoder().encode("{}") }); + const named = Epoch.mint(); + const contributions = (epoch: Epoch.Valid) => + Catalog.RootSchema.parse({ + contributions: { + proven: { broadcast: "./proven.hang", epoch }, + plain: { broadcast: "./plain.hang", epoch: named }, + }, + }); + const catalog = new Signal(contributions(named)); const parent = new Broadcast({ origin, name: Path.from("room/main.hang"), catalogFormat: "manual", - catalog: Catalog.RootSchema.parse({ - contributions: { extra: { broadcast: "./extra.hang", epoch: Epoch.mint() } }, - }), + catalog, announced: false, }); const owner = new Effect(); try { - const child = parent.contribution(owner, "extra"); - await child.out.error.changed(); - expect(child.out.active.peek()).toBeUndefined(); - expect(contribution.demand().used.peek()).toBe(false); + const refused = parent.contribution(owner, "proven"); + const accepted = parent.contribution(owner, "plain"); + await quietly(settle); + expect(refused.out.active.peek()).toBeUndefined(); + expect(refused.out.error.peek()).toBeUndefined(); expect(track.demand().used.peek()).toBe(false); + // An epochless route cannot prove its instance, so the epoch cannot refuse it. + expect(accepted.out.active.peek()?.path).toBe(Path.from("room/plain.hang")); + + // A catalog update naming the served epoch admits the instance the request already holds. + catalog.set(contributions(served)); + await settle(); + expect(refused.out.active.peek()?.epoch).toBe(served); } finally { owner.close(); parent.close(); diff --git a/rs/hang/src/catalog/root.rs b/rs/hang/src/catalog/root.rs index 21752b8b14f..ea6c1c5a3b5 100644 --- a/rs/hang/src/catalog/root.rs +++ b/rs/hang/src/catalog/root.rs @@ -117,18 +117,29 @@ pub struct Catalog { } /// A whole broadcast whose catalog describes its own renditions. +/// +/// Marked `#[non_exhaustive]` so optional fields can be added later. External callers build one +/// with [`Contribution::new`]. #[serde_with::serde_as] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[non_exhaustive] pub struct Contribution { /// Reference resolved relative to the catalog broadcast. pub broadcast: moq_net::path::RelativeOwned, - /// The publisher instance the contribution must resolve to, when known. + /// The publisher instance the contribution names, with a rendition `epoch`'s meaning. #[serde(default, skip_serializing_if = "Option::is_none")] #[serde_as(as = "Option")] pub epoch: Option, } +impl Contribution { + /// A contribution at `broadcast`, accepting whichever instance resolves. + pub fn new(broadcast: moq_net::path::RelativeOwned) -> Self { + Self { broadcast, epoch: None } + } +} + impl Catalog<()> { /// The default name for the catalog track. pub const DEFAULT_NAME: &str = "catalog.json"; From 802900b69e6b18059dcdeeebb6be451e4c5e32aa Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 16 Oct 2026 18:23:00 -0700 Subject: [PATCH 6/7] fix(watch): resolve a contribution through the parent's references A contribution's child requested its path on its own, so it could resolve a path the parent already held to a different instance, a self-reference opened a second request instead of reusing the parent's handle, and an epoch-only catalog update reopened the request because Derived relays every notification. The child now resolves through the parent's relativeBroadcast, sharing its request and epoch check, and each input is a deduplicated computed. This drops the public BroadcastInput.epoch it no longer needs. An unavailable contribution reads as offline, like a rendition reference. Found by a Codex adversarial review. Co-Authored-By: Claude Opus 5.5 --- js/watch/src/broadcast.ts | 46 +++++++++++----------- js/watch/src/contribution.test.ts | 63 ++++++++++++++++++++++++++++++- 2 files changed, 86 insertions(+), 23 deletions(-) diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index 87632f05d79..67e01a4a996 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -89,10 +89,6 @@ export type BroadcastInput = { // The broadcast name. name: Getter; - // The publisher instance to read: a broadcast proven to be another one reads as offline. - // A route without an epoch cannot prove one, so there it is best effort. Omitted to accept any. - epoch: Getter; - // Whether to wait for the broadcast to be announced before subscribing. // Defaults to true; pass false to subscribe immediately without waiting for an announcement. announced: Getter; @@ -156,6 +152,10 @@ export class Broadcast { // strands the filtered copy on the previous contents. readonly #raw = new Signal(undefined); + // Set only on a contribution: its broadcast resolves through the parent catalog's references, + // so the two never resolve one path independently. + readonly #resolve = new Signal<((effect: Effect) => Moq.Broadcast.Consumer | undefined) | undefined>(undefined); + #signals: Effect; constructor(props?: Inputs) { @@ -166,7 +166,6 @@ export class Broadcast { this.in = { origin: getter(props?.origin), name: getter(props?.name ?? Path.empty()), - epoch: getter(props?.epoch), enabled: getter(props?.enabled ?? true), announced: getter(props?.announced ?? true), catalogFormat: getter(props?.catalogFormat), @@ -249,14 +248,18 @@ export class Broadcast { const enabled = effect.get(this.in.enabled); if (!enabled) return; + const resolve = effect.get(this.#resolve); + if (resolve) { + effect.set(this.#out.active, resolve(effect), undefined); + return; + } + const origin = effect.get(this.in.origin); if (!origin) return; const name = effect.get(this.in.name); const announced = effect.get(this.in.announced); - // The epoch is checked against the stamped one rather than passed to the origin, which - // would refuse every epochless route and so break best effort on older sessions. let request: Moq.Origin.Requesting; try { request = origin.request(name, { announced }); @@ -269,11 +272,6 @@ export class Broadcast { effect.run((nested) => { const active = nested.get(request.active); if (active) resolved = true; - const epoch = nested.get(this.in.epoch); - if (active && epoch !== undefined && active.epoch !== undefined && active.epoch !== epoch) { - console.warn("ignoring broadcast: it serves another epoch", name, active.epoch, epoch); - return; - } nested.set(this.#out.active, active, undefined); }); effect.run((nested) => { @@ -468,21 +466,27 @@ export class Broadcast { * ``` */ contribution(effect: Effect, id: string): Broadcast { - // Deduplicated, so a catalog update that leaves this entry alone keeps the child's request. - const target = effect.computed((run): { name: Moq.Path.Valid; epoch?: Moq.Epoch.Valid } | undefined => { + // Each computed only notifies on a real change, so an update that leaves the child's path + // alone (such as a new `epoch`) never restarts its catalog. + const entry = effect.computed((run) => { const contributions = run.get(this.out.catalog)?.contributions; - if (!contributions || !Object.hasOwn(contributions, id)) return undefined; - const { broadcast, epoch } = contributions[id]; - const name = Path.tryResolve(run.get(this.in.name), broadcast); - return name === undefined ? undefined : { name, epoch }; + return contributions && Object.hasOwn(contributions, id) ? contributions[id] : undefined; }); + const name = effect.computed((run) => { + const broadcast = run.get(entry)?.broadcast; + return broadcast && Path.tryResolve(run.get(this.in.name), broadcast); + }); + const enabled = effect.computed((run) => run.get(entry) !== undefined); const child = new Broadcast({ origin: this.in.origin, - name: new Derived([target], (target) => target?.name ?? Path.empty()), - epoch: new Derived([target], (target) => target?.epoch), - enabled: new Derived([target, this.in.enabled], (target, enabled) => target !== undefined && enabled), + name: new Derived([name], (name) => name ?? Path.empty()), + enabled: new Derived([enabled], (enabled) => enabled === true), announced: this.in.announced, }); + child.#resolve.set((run) => { + const selected = run.get(entry); + return selected && this.relativeBroadcast(run, selected.broadcast, selected.epoch); + }); effect.cleanup(() => child.close()); return child; } diff --git a/js/watch/src/contribution.test.ts b/js/watch/src/contribution.test.ts index c949093f431..74d7e7ce4b5 100644 --- a/js/watch/src/contribution.test.ts +++ b/js/watch/src/contribution.test.ts @@ -77,9 +77,10 @@ it("lists contributions without demand and keeps selected rendition IDs in their const { value: request } = await requests.next(); expect(request?.path).toBe(Path.from("room/absent.hang")); request?.reject(new Error("contribution unavailable")); - await missing.out.error.changed(); + await settle(); + // Like a rendition's reference, an unavailable contribution is offline. expect(missing.out.active.peek()).toBeUndefined(); - expect(missing.out.error.peek()?.message).toBe("contribution unavailable"); + expect(missing.out.status.peek()).toBe("offline"); expect(source.out.catalog.peek()?.video?.renditions.video.codec).toBe("avc1.42001f"); selection.close(); await contribution.demand().unused(); @@ -263,3 +264,61 @@ it("never reads a contribution proven to be another epoch, but reads an epochles origin.close(); } }); + +it("shares the parent's resolution, so a new epoch checks the held handle", async () => { + const origin = new Origin.Producer(); + const [served, other] = [Epoch.mint(), Epoch.mint()]; + const main = origin.createBroadcast(Path.from("room/main.hang")); + main.announce({ epoch: served }); + const extra = origin.createBroadcast(Path.from("room/extra.hang")); + extra.announce({ epoch: served }); + const entries = (epoch?: Epoch.Valid) => + Catalog.RootSchema.parse({ + contributions: { + sibling: { broadcast: "./extra.hang", epoch }, + self: { broadcast: "./main.hang", epoch }, + }, + }); + const catalog = new Signal(entries()); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog, + announced: false, + }); + const owner = new Effect(); + try { + const sibling = parent.contribution(owner, "sibling"); + const self = parent.contribution(owner, "self"); + await settle(); + const held = sibling.out.active.peek(); + expect(held?.epoch).toBe(served); + // A self-reference is the parent's own handle, not a request of its own. + expect(self.out.active.peek()).toBe(parent.out.active.peek()); + + let withdrawals = 0; + owner.cleanup( + extra.demand().used.subscribe((used) => { + if (!used) withdrawals += 1; + }), + ); + + // Naming the held instance keeps the same handle rather than resolving the path again. + catalog.set(entries(served)); + await settle(); + expect(sibling.out.active.peek()).toBe(held); + expect(self.out.active.peek()).toBe(parent.out.active.peek()); + expect(withdrawals).toBe(0); + + // Naming another instance fails the held one. + catalog.set(entries(other)); + await quietly(settle); + expect(sibling.out.active.peek()).toBeUndefined(); + expect(self.out.active.peek()).toBeUndefined(); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); From 3980cb833f5567f42cd5f25c3654ac0b8433fe99 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 16 Oct 2026 18:30:38 -0700 Subject: [PATCH 7/7] fix(watch): name an empty contribution reference after its catalog An empty `broadcast` is a present reference to the catalog's own broadcast, but the falsy check left the child named "", so its own relative references resolved against the wrong base. Found by a Codex adversarial review. Co-Authored-By: Claude Opus 5.5 --- js/watch/src/broadcast.ts | 5 +++-- js/watch/src/contribution.test.ts | 8 +++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index 67e01a4a996..be3a14df7bd 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -473,8 +473,9 @@ export class Broadcast { return contributions && Object.hasOwn(contributions, id) ? contributions[id] : undefined; }); const name = effect.computed((run) => { - const broadcast = run.get(entry)?.broadcast; - return broadcast && Path.tryResolve(run.get(this.in.name), broadcast); + // An empty reference is present: it names the catalog's own broadcast. + const selected = run.get(entry); + return selected && Path.tryResolve(run.get(this.in.name), selected.broadcast); }); const enabled = effect.computed((run) => run.get(entry) !== undefined); const child = new Broadcast({ diff --git a/js/watch/src/contribution.test.ts b/js/watch/src/contribution.test.ts index 74d7e7ce4b5..1cdedbdcb05 100644 --- a/js/watch/src/contribution.test.ts +++ b/js/watch/src/contribution.test.ts @@ -277,6 +277,7 @@ it("shares the parent's resolution, so a new epoch checks the held handle", asyn contributions: { sibling: { broadcast: "./extra.hang", epoch }, self: { broadcast: "./main.hang", epoch }, + empty: { broadcast: "", epoch }, }, }); const catalog = new Signal(entries()); @@ -294,8 +295,13 @@ it("shares the parent's resolution, so a new epoch checks the held handle", asyn await settle(); const held = sibling.out.active.peek(); expect(held?.epoch).toBe(served); - // A self-reference is the parent's own handle, not a request of its own. + // A self-reference is the parent's own handle, not a request of its own. An empty one is + // too, and is named like the parent, so its own references resolve against the same base. expect(self.out.active.peek()).toBe(parent.out.active.peek()); + const empty = parent.contribution(owner, "empty"); + await settle(); + expect(empty.in.name.peek()).toBe(Path.from("room/main.hang")); + expect(empty.in.enabled.peek()).toBe(true); let withdrawals = 0; owner.cleanup(