From 601d30e5699d200ec4e89457ccae6fd7ff5b29e1 Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Sun, 9 Aug 2026 23:51:32 -0700 Subject: [PATCH] fix(core): unwire an LFO when its effect is disposed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The §4c item here was "four hand-rolled wet/dry shells whose dispose lists have already drifted". Reading them, the drift is one specific thing and it is a leak, not an untidiness: the chorus and the phaser stopped their LFO and left it out of the nodes they disconnect. So every chain rebuild that dropped a modulated effect left a modulator still wired to the delay or the allpass bank it had been driving. Nothing audible came of it — the shell around it was disconnected — but the nodes stayed reachable, and a session of edits to a modulated track piled them up. Same shape as the worklet leak fixed earlier on this stack. `stopLfo` becomes `retireLfo` and does both halves, which is the whole fix. The consolidation the item also asks for is not here: the four shells are wired differently enough (a feedback loop, a modulated delay, six allpass stages between two trims, a convolver) that one factory over them would need a config surface bigger than the four dispose lines it replaces. The leak was the part with a defect behind it. Also folds the two artifact build scripts together — 50 lines each, differing in five names. That one is a genuine copy, and the copy is where a divergence would hide: whichever stopped being edited would go on producing a subtly different artifact with nothing to say so. Output is byte-identical, which `check:position-edits-render` proves by diffing the tracked artifact. Falsified: dropping the `disconnect` fails the new test. core 1726 passing (110 files), engine services 736 passing / 3 skipped. --- .../core/scripts/build-audio-fx-runtime.ts | 55 +++---------- .../scripts/build-position-edits-render.ts | 57 +++----------- .../core/scripts/buildInjectedArtifact.ts | 78 +++++++++++++++++++ packages/core/src/audio/audioFxGraph.test.ts | 15 ++++ packages/core/src/audio/audioFxGraph.ts | 18 ++++- 5 files changed, 125 insertions(+), 98 deletions(-) create mode 100644 packages/core/scripts/buildInjectedArtifact.ts diff --git a/packages/core/scripts/build-audio-fx-runtime.ts b/packages/core/scripts/build-audio-fx-runtime.ts index eb6c841a51..29d74d6e7c 100644 --- a/packages/core/scripts/build-audio-fx-runtime.ts +++ b/packages/core/scripts/build-audio-fx-runtime.ts @@ -1,50 +1,13 @@ /** Build the injectable audio-FX runtime artifact from the canonical runtime. */ -import { mkdirSync, writeFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { buildSync } from "esbuild"; -import { execFileSync } from "node:child_process"; +import { buildInjectedArtifact } from "./buildInjectedArtifact.js"; -const thisDir = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(thisDir, ".."); -const entry = resolve(repoRoot, "stubs/audio-fx-runtime-entry.ts"); -const generatedDir = resolve(repoRoot, "src/generated"); -const outPath = resolve(generatedDir, "audio-fx-runtime-inline.ts"); - -const result = buildSync({ - entryPoints: [entry], - bundle: true, - write: false, - platform: "browser", - format: "iife", - target: ["es2020"], - minify: true, - legalComments: "none", +buildInjectedArtifact({ + scriptUrl: import.meta.url, + entry: "stubs/audio-fx-runtime-entry.ts", + out: "audio-fx-runtime-inline.ts", + constName: "AUDIO_FX_RUNTIME_IIFE", + fnName: "getAudioFxRuntimeScript", + what: "audio-FX runtime IIFE", + event: "audio_fx_runtime_generated", }); -const iife = result.outputFiles[0]?.text ?? ""; -if (!iife) throw new Error("esbuild produced no output for audio-fx-runtime-entry.ts"); - -mkdirSync(generatedDir, { recursive: true }); -writeFileSync( - outPath, - [ - "// AUTO-GENERATED by scripts/build-audio-fx-runtime.ts - do not edit", - `const AUDIO_FX_RUNTIME_IIFE: string = ${JSON.stringify(iife)};`, - "", - "/** Returns the pre-built audio-FX runtime IIFE as a string constant. */", - "export function getAudioFxRuntimeScript(): string {", - " return AUDIO_FX_RUNTIME_IIFE;", - "}", - "", - ].join("\n"), - "utf8", -); - -try { - execFileSync("bun", ["x", "oxfmt", outPath], { stdio: "ignore" }); -} catch { - // Formatting is best effort when the generator runs in a minimal environment. -} - -console.log(JSON.stringify({ event: "audio_fx_runtime_generated", outPath, bytes: iife.length })); diff --git a/packages/core/scripts/build-position-edits-render.ts b/packages/core/scripts/build-position-edits-render.ts index e4ed0ef981..a750cd791e 100644 --- a/packages/core/scripts/build-position-edits-render.ts +++ b/packages/core/scripts/build-position-edits-render.ts @@ -1,52 +1,13 @@ /** Build the injectable position-edits render artifact from the canonical runtime. */ -import { mkdirSync, writeFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { buildSync } from "esbuild"; -import { execFileSync } from "node:child_process"; +import { buildInjectedArtifact } from "./buildInjectedArtifact.js"; -const thisDir = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(thisDir, ".."); -const entry = resolve(repoRoot, "stubs/position-edits-render-entry.ts"); -const generatedDir = resolve(repoRoot, "src/generated"); -const outPath = resolve(generatedDir, "position-edits-render-inline.ts"); - -const result = buildSync({ - entryPoints: [entry], - bundle: true, - write: false, - platform: "browser", - format: "iife", - target: ["es2020"], - minify: true, - legalComments: "none", +buildInjectedArtifact({ + scriptUrl: import.meta.url, + entry: "stubs/position-edits-render-entry.ts", + out: "position-edits-render-inline.ts", + constName: "POSITION_EDITS_RENDER_IIFE", + fnName: "getPositionEditsRenderScript", + what: "position-edits render IIFE", + event: "position_edits_render_generated", }); -const iife = result.outputFiles[0]?.text ?? ""; -if (!iife) throw new Error("esbuild produced no output for position-edits-render-entry.ts"); - -mkdirSync(generatedDir, { recursive: true }); -writeFileSync( - outPath, - [ - "// AUTO-GENERATED by scripts/build-position-edits-render.ts - do not edit", - `const POSITION_EDITS_RENDER_IIFE: string = ${JSON.stringify(iife)};`, - "", - "/** Returns the pre-built position-edits render IIFE as a string constant. */", - "export function getPositionEditsRenderScript(): string {", - " return POSITION_EDITS_RENDER_IIFE;", - "}", - "", - ].join("\n"), - "utf8", -); - -try { - execFileSync("bun", ["x", "oxfmt", outPath], { stdio: "ignore" }); -} catch { - // Formatting is best effort when the generator runs in a minimal environment. -} - -console.log( - JSON.stringify({ event: "position_edits_render_generated", outPath, bytes: iife.length }), -); diff --git a/packages/core/scripts/buildInjectedArtifact.ts b/packages/core/scripts/buildInjectedArtifact.ts new file mode 100644 index 0000000000..b7faa7d0f7 --- /dev/null +++ b/packages/core/scripts/buildInjectedArtifact.ts @@ -0,0 +1,78 @@ +/** + * Bundle a stub entry into an injectable IIFE, wrapped as a TypeScript constant. + * + * Two artifacts are built this way — the audio-FX runtime and the position-edits + * render — and the engine injects both into the headless browser as a script tag. + * They were two copies of this file differing in five names, which is a poor + * place for a divergence to hide: whichever copy stopped being edited would go on + * producing a subtly different artifact with nothing to say so. + */ + +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { buildSync } from "esbuild"; + +export interface InjectedArtifact { + /** The build script's own `import.meta.url`, so paths resolve beside it. */ + scriptUrl: string; + /** Entry stub, relative to the package root. */ + entry: string; + /** Output file name inside `src/generated`. */ + out: string; + /** SCREAMING_CASE name for the string constant holding the IIFE. */ + constName: string; + /** The accessor the rest of the codebase imports. */ + fnName: string; + /** What that accessor returns, for its doc comment: "the pre-built X". */ + what: string; + /** Structured log event name. */ + event: string; +} + +export function buildInjectedArtifact(spec: InjectedArtifact): void { + const scriptDir = dirname(fileURLToPath(spec.scriptUrl)); + const scriptName = spec.scriptUrl.split("/").pop() ?? ""; + const repoRoot = resolve(scriptDir, ".."); + const entry = resolve(repoRoot, spec.entry); + const generatedDir = resolve(repoRoot, "src/generated"); + const outPath = resolve(generatedDir, spec.out); + + const result = buildSync({ + entryPoints: [entry], + bundle: true, + write: false, + platform: "browser", + format: "iife", + target: ["es2020"], + minify: true, + legalComments: "none", + }); + const iife = result.outputFiles[0]?.text ?? ""; + if (!iife) throw new Error(`esbuild produced no output for ${spec.entry.split("/").pop()}`); + + mkdirSync(generatedDir, { recursive: true }); + writeFileSync( + outPath, + [ + `// AUTO-GENERATED by scripts/${scriptName} - do not edit`, + `const ${spec.constName}: string = ${JSON.stringify(iife)};`, + "", + `/** Returns the pre-built ${spec.what} as a string constant. */`, + `export function ${spec.fnName}(): string {`, + ` return ${spec.constName};`, + "}", + "", + ].join("\n"), + "utf8", + ); + + try { + execFileSync("bun", ["x", "oxfmt", outPath], { stdio: "ignore" }); + } catch { + // Formatting is best effort when the generator runs in a minimal environment. + } + + console.log(JSON.stringify({ event: spec.event, outPath, bytes: iife.length })); +} diff --git a/packages/core/src/audio/audioFxGraph.test.ts b/packages/core/src/audio/audioFxGraph.test.ts index d0b4f12ec2..181bf08269 100644 --- a/packages/core/src/audio/audioFxGraph.test.ts +++ b/packages/core/src/audio/audioFxGraph.test.ts @@ -436,6 +436,21 @@ describe("levels and per-channel state", () => { expect(src?.playbackRate.value).toBeCloseTo(2, 6); }); + /** + * A source node is not retired by disconnecting what it feeds. The chorus and + * phaser stopped their LFO and left it out of the nodes they disconnect, so + * every rebuild that dropped one left a modulator still wired to the delay or + * the allpass bank it had been driving. + */ + it("unwires a modulated effect's LFO when the effect is disposed", () => { + for (const type of ["chorus", "phaser"]) { + const c = ctx(); + buildFxNode(asCtx(c), type, defaultAudioFxParams(type)).dispose(); + const lfo = c.created.find((node) => node.kind === "bufferSource"); + expect(lfo?.disconnected, `${type} left its LFO connected`).toBe(true); + } + }); + it("starts the LFO at zero for a render, which always begins at the clip's start", () => { const c = ctx(); buildFxNode(asCtx(c), "phaser", defaultAudioFxParams("phaser")); diff --git a/packages/core/src/audio/audioFxGraph.ts b/packages/core/src/audio/audioFxGraph.ts index 908f791568..c49db5e468 100644 --- a/packages/core/src/audio/audioFxGraph.ts +++ b/packages/core/src/audio/audioFxGraph.ts @@ -144,13 +144,23 @@ function lfoSource( return src; } -/** Stop an LFO that may already have been stopped, on the way to disposal. */ -function stopLfo(src: AudioBufferSourceNode): void { +/** + * Retire an LFO: stopped *and* unwired. + * + * Both halves. The old oscillators were stopped and left in their builder's + * dispose list — so every chain rebuild that dropped a chorus or a phaser left a + * modulator still connected to the delay or the allpass bank it had been + * driving. Nothing audible came out of it, because the shell around it was + * disconnected, but the nodes stayed reachable and a session of edits to a + * modulated track accumulated them. Same shape as the worklet leak above. + */ +function retireLfo(src: AudioBufferSourceNode): void { try { src.stop(); } catch { /* already stopped */ } + src.disconnect(); } /** A wet/dry pair: the dry side is whatever the wet side is not. */ @@ -365,7 +375,7 @@ const chorusLfo: Builder = (ctx, p, elapsed) => { mix: mixTargets(wet.gain, dry.gain), }, dispose: () => { - stopLfo(lfo); + retireLfo(lfo); [input, out, dl, depth, wet, dry].forEach((x) => x.disconnect()); }, }; @@ -438,7 +448,7 @@ const allpassPhaser: Builder = (ctx, p, elapsed) => { out_gain: [{ param: outTrim.gain }], }, dispose: () => { - stopLfo(lfo); + retireLfo(lfo); [input, out, inTrim, outTrim, depth, wet, dry, ...stages].forEach((x) => x.disconnect()); }, };