From cf979613a3ff4586be7fe819545cba02e1b24311 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:09:11 -0500 Subject: [PATCH] perf(workers/browser/cli): buffer JSON writes, wake on signal, optimize queues (#13698) * perf(workers/browser/cli): buffer JSON writes, wake on signal, optimize queues * fix(workers): wake on owned memory refusal and bound CLI JSON counting --- src/browser/CdpCaptureDocuments.ts | 14 ++++- src/browser/WebBundleAnalysisWorkerServer.ts | 4 +- .../network/PlaywrightScenarioNetwork.ts | 19 +++++-- .../JavaScriptAnalysisWorker.startup.test.ts | 49 +++++++++++++++++ .../analysis/JavaScriptAnalysisWorker.ts | 52 +++++++++---------- src/process/OwnedMcpStdioTransport.ts | 7 +++ src/process/ProviderProcess.ts | 12 ++++- src/windows/WindowsOwnedProcess.test.ts | 17 ++++++ src/windows/WindowsOwnedProcess.ts | 8 ++- 9 files changed, 146 insertions(+), 36 deletions(-) diff --git a/src/browser/CdpCaptureDocuments.ts b/src/browser/CdpCaptureDocuments.ts index 00dc7459cff..d695d8b8f6d 100644 --- a/src/browser/CdpCaptureDocuments.ts +++ b/src/browser/CdpCaptureDocuments.ts @@ -284,14 +284,24 @@ export function* captureDom( const { nodeType, nodeName, nodeValue, parent, attributes } = admitted.value; const nodeIndex = baseIndex + index; - const attributeSet = new Set(attributes.map(([name]) => name)); - const attributeNames = [...attributeSet]; + let attributeSet: Set | undefined; + let attributeNames: string[]; + if (attributes.length === 0) { + attributeNames = []; + } else { + attributeSet = new Set(); + for (let a = 0; a < attributes.length; a += 1) { + attributeSet.add(attributes[a]![0]); + } + attributeNames = [...attributeSet]; + } const domElement = domXmlElement(ancestry, index); const htmlTagName = domHtmlTagName(nodeName, domElement); if (domElement.xmlDocument === undefined) completeness?.exclude("metadata", "invalid_protocol_value"); let svgQuery: DomSvgNodeQuery | null | undefined; if ( + attributeSet !== undefined && domElement.xmlDocument === false && nodeType === 1 && attributeSet.has("xlink:href") && diff --git a/src/browser/WebBundleAnalysisWorkerServer.ts b/src/browser/WebBundleAnalysisWorkerServer.ts index 69d0768dad5..91cdb09a955 100644 --- a/src/browser/WebBundleAnalysisWorkerServer.ts +++ b/src/browser/WebBundleAnalysisWorkerServer.ts @@ -18,7 +18,7 @@ import { ArtifactResourceScope, readStableArtifact, } from "../resources/index.js"; -import { jsonParts } from "../domain/jsonSerialization.js"; +import { bufferedJsonParts, jsonParts } from "../domain/jsonSerialization.js"; import type { IncludedScript } from "../domain/webBundleAnalyzerState.js"; import { webBundleScriptAnalysisSchema, @@ -194,7 +194,7 @@ const analyzeJob = async ( resources, undefined, async (handle) => { - for (const part of jsonParts(result)) { + for (const part of bufferedJsonParts(jsonParts(result))) { const chunk = Buffer.from(part); bytes += chunk.length; if (bytes > request.result_budget_bytes) diff --git a/src/browser/network/PlaywrightScenarioNetwork.ts b/src/browser/network/PlaywrightScenarioNetwork.ts index 37655f3f052..ad266c897cd 100644 --- a/src/browser/network/PlaywrightScenarioNetwork.ts +++ b/src/browser/network/PlaywrightScenarioNetwork.ts @@ -147,6 +147,7 @@ export class PlaywrightScenarioNetwork { /** One request and one response-content job at most per admitted transaction. */ private readonly pending: Promise[] = []; private readonly queuedReads: QueuedContentRead[] = []; + private queuedReadsHead = 0; private readonly gaps = new Set(); private accepting = true; private activeReads = 0; @@ -761,9 +762,21 @@ export class PlaywrightScenarioNetwork { } private pumpContentReads(): void { - while (this.activeReads < 16 && this.queuedReads.length > 0) { - const job = this.queuedReads.shift(); - if (job === undefined) return; + while ( + this.activeReads < 16 && + this.queuedReadsHead < this.queuedReads.length + ) { + const job = this.queuedReads[this.queuedReadsHead++]!; + if (this.queuedReadsHead >= this.queuedReads.length) { + this.queuedReads.length = 0; + this.queuedReadsHead = 0; + } else if ( + this.queuedReadsHead >= 64 && + this.queuedReadsHead * 2 >= this.queuedReads.length + ) { + this.queuedReads.splice(0, this.queuedReadsHead); + this.queuedReadsHead = 0; + } this.activeReads += 1; void job .run() diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts index 0c6ba5c14b8..a5f01f461b8 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts @@ -4,10 +4,13 @@ import { JavaScriptAnalysisWorker } from "./JavaScriptAnalysisWorker.js"; import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; import { AnalysisOutputError, + AnalysisResourceConstraintError, AnalysisTimeoutError, } from "../../domain/analysisErrorCore.js"; import { primaryAnalysisError } from "../../domain/analysisErrorBase.js"; import { spawnOwnedProviderProcess } from "../../process/ProviderProcess.js"; +import { WorkerFrameSignal } from "../../process/WorkerFrameSignal.js"; +import { EventEmitter } from "node:events"; import { phaseArrival } from "../../../tests/support/lifecycleHarness.js"; const text = "export const observed = 1;"; @@ -100,3 +103,49 @@ it("times out a worker whose ready frame never arrives and stops it", async () = expect(fixture.pids).toHaveLength(1); expect(fixture.pids.filter(alive)).toEqual([]); }); + +it("wakes a silent worker on an owned memory refusal before the deadline", async () => { + const fixture = standInWorker("setInterval(() => {}, 1000);"); + let notify: (() => void) | undefined; + const worker = new JavaScriptAnalysisWorker( + { heapMb: 128, timeoutMs: 30_000 }, + async (options) => { + const owned = await fixture.launcher(options); + let reached = false; + Object.defineProperty(owned.process, "memoryLimitReached", { + get: () => reached, + }); + if (!(owned.process instanceof EventEmitter)) + throw new Error("Expected an event-emitting worker"); + const child = owned.process; + notify = () => { + reached = true; + child.emit("memory-limit"); + }; + return owned; + }, + ); + onTestFinished(() => worker.close()); + const waiting = phaseArrival(); + const original = WorkerFrameSignal.prototype.wait; + const wait = vi + .spyOn(WorkerFrameSignal.prototype, "wait") + .mockImplementation(function (this: WorkerFrameSignal, signal) { + const pending = original.call(this, signal); + waiting.arrive(); + return pending; + }); + onTestFinished(() => { + wait.mockRestore(); + }); + const analysis = worker.analyze(file, budget); + await waiting.reached(analysis, "silent worker waiting for a frame"); + if (notify === undefined) throw new Error("Worker was not launched"); + notify(); + const refused = await analysis; + if (refused.ok) throw new Error("Expected a memory refusal"); + const primary = primaryAnalysisError(refused.error.error); + expect(primary).toBeInstanceOf(AnalysisResourceConstraintError); + expect(primary).toMatchObject({ resource: "memory" }); + expect(refused.error.error.cleanupIncomplete).toBe(false); +}); diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts index 54c9eba8f7d..5fb034577a6 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts @@ -79,10 +79,7 @@ import { processWorkerCleanup, } from "../../process/OwnedWorkerRuntime.js"; import { prepareProcessOwnershipInspection } from "../../process/ProcessOwnershipObservation.js"; -import { - ProviderStartupDeadline, - waitForAbortableDelay, -} from "../../process/ProviderDeadline.js"; +import { ProviderStartupDeadline } from "../../process/ProviderDeadline.js"; import { readJavaScriptAnalysisTransfer, javaScriptForwardedTransferRemediation, @@ -237,6 +234,7 @@ export class JavaScriptAnalysisWorker { // budget or a stack trace that overflowed it cannot hide it. runtime: "v8", onDiagnostic: (event) => this.#observeProcessDiagnostic(event), + onMemoryLimit: () => this.#observeMemoryLimit(), }, onInputFailure: (cause) => this.#latchInputFailure(cause), }); @@ -841,7 +839,7 @@ export class JavaScriptAnalysisWorker { if (outcome === "frame") continue; throw this.#selectedWorkerFailure(path); } - await waitForAbortableDelay(10, deadline.signal); + await this.#frameSignal.wait(deadline.signal); } } @@ -1100,28 +1098,30 @@ export class JavaScriptAnalysisWorker { }; this.#frameSignal.wake("failure"); } - if (event.type === "exit" && (event.code !== 0 || event.signal !== null)) { - if (this.#primaryFailure === undefined) - this.#primaryFailure = { - kind: "exit", - code: event.code, - signal: event.signal, - heapExhaustion: event.snapshot.runtimeExhaustion !== undefined, - ...(event.snapshot.runtimeExhaustion === undefined - ? {} - : { exhaustion: event.snapshot.runtimeExhaustion }), - }; - else if ( - this.#primaryFailure.kind === "exit" && - event.snapshot.runtimeExhaustion !== undefined - ) { - this.#primaryFailure = { - ...this.#primaryFailure, - heapExhaustion: true, - exhaustion: event.snapshot.runtimeExhaustion, - }; - this.#frameSignal.wake("failure"); + if (event.type === "exit") { + if (event.code !== 0 || event.signal !== null) { + if (this.#primaryFailure === undefined) + this.#primaryFailure = { + kind: "exit", + code: event.code, + signal: event.signal, + heapExhaustion: event.snapshot.runtimeExhaustion !== undefined, + ...(event.snapshot.runtimeExhaustion === undefined + ? {} + : { exhaustion: event.snapshot.runtimeExhaustion }), + }; + else if ( + this.#primaryFailure.kind === "exit" && + event.snapshot.runtimeExhaustion !== undefined + ) { + this.#primaryFailure = { + ...this.#primaryFailure, + heapExhaustion: true, + exhaustion: event.snapshot.runtimeExhaustion, + }; + } } + this.#frameSignal.wake("failure"); } } #observeMemoryLimit(): void { diff --git a/src/process/OwnedMcpStdioTransport.ts b/src/process/OwnedMcpStdioTransport.ts index cfe61227553..0ed86f8eb30 100644 --- a/src/process/OwnedMcpStdioTransport.ts +++ b/src/process/OwnedMcpStdioTransport.ts @@ -408,6 +408,13 @@ export class OwnedMcpStdioTransport implements Transport { ); return; } + if (this.#frameLength === 0 && newline !== -1) { + // Preserve a leading BOM so the JSON-RPC parser can reject it. + const line = decodeStrictUtf8(fragment, "preserve"); + this.onmessage?.(deserializeMessage(line)); + offset = newline + 1; + continue; + } this.#appendFrame(fragment, frameBytes); if (newline === -1) return; // Preserve a leading BOM so the JSON-RPC parser can reject it. diff --git a/src/process/ProviderProcess.ts b/src/process/ProviderProcess.ts index 9350a3bf9dc..3cea6d38c92 100644 --- a/src/process/ProviderProcess.ts +++ b/src/process/ProviderProcess.ts @@ -108,7 +108,9 @@ export interface ProviderProcessHandle extends Pick< readonly stderr: Readable | null; readonly exitCode: number | null; readonly signalCode: NodeJS.Signals | null; - /** True once an enforced process memory limit reported an allocation failure. */ + /** True once an enforced process memory limit reported an allocation failure. + * A live owner emits `memory-limit` on the first transition to true. + */ readonly memoryLimitReached?: boolean; /** True if a Windows backpressured stream was destroyed before output drained. */ readonly outputIncomplete?: boolean; @@ -258,6 +260,8 @@ export interface ProviderProcessSupervisorOptions { */ readonly diagnosticRetention?: "head" | "tail"; readonly onDiagnostic?: (event: ProviderProcessDiagnostic) => void; + /** Wake a waiter when a live process owner first observes a memory refusal. */ + readonly onMemoryLimit?: () => void; } /** One output token located before retention applies, so it survives an exhausted budget. */ @@ -505,6 +509,9 @@ export class ProviderProcessSupervisor { } this.#outputClose.resolve(undefined); }; + readonly #onMemoryLimit = (): void => { + this.#options.onMemoryLimit?.(); + }; readonly #onError = (cause: Error): void => { this.#options.onDiagnostic?.({ type: "error", @@ -551,6 +558,8 @@ export class ProviderProcessSupervisor { launch.process.once("exit", this.#onExit); launch.process.once("close", this.#onClose); launch.process.on("error", this.#onError); + if (this.#options.onMemoryLimit !== undefined) + launch.process.once("memory-limit", this.#onMemoryLimit); if (launch.process.exitCode !== null || launch.process.signalCode !== null) this.#recordExit(launch.process.exitCode, launch.process.signalCode); } @@ -910,6 +919,7 @@ export class ProviderProcessSupervisor { this.launch.process.off("exit", this.#onExit); this.launch.process.off("close", this.#onClose); this.launch.process.off("error", this.#onError); + this.launch.process.off("memory-limit", this.#onMemoryLimit); } /** Release event-loop references so incomplete cleanup does not prevent host exit. */ diff --git a/src/windows/WindowsOwnedProcess.test.ts b/src/windows/WindowsOwnedProcess.test.ts index 6d08d3e184c..7b7d46b14fd 100644 --- a/src/windows/WindowsOwnedProcess.test.ts +++ b/src/windows/WindowsOwnedProcess.test.ts @@ -250,11 +250,27 @@ describe("Windows Job Object memory limits", () => { memoryLimitReached: false, peakJobMemoryBytes: 300 * 1024 * 1024, }, + { + ...settledPoll, + exitCode: null, + stdoutEnded: false, + stderrEnded: false, + activeProcesses: 1, + memoryLimitReached: true, + peakJobMemoryBytes: LIMIT, + }, { ...settledPoll, memoryLimitReached: true, peakJobMemoryBytes: LIMIT }, ], }); const child = launch(native, LIMIT); expect(calls[0]?.arguments_.slice(4)).toEqual([false, LIMIT]); + const notifications: { exitCode: number | null; reached: boolean }[] = []; + child.on("memory-limit", () => { + notifications.push({ + exitCode: child.exitCode, + reached: child.memoryLimitReached, + }); + }); const closed = once(child, "close"); const exited = new Promise((resolve) => { child.once("exit", (code: number) => @@ -264,6 +280,7 @@ describe("Windows Job Object memory limits", () => { expect(await exited).toEqual({ code: 3, reached: true }); expect(child.peakJobMemoryBytes).toBe(LIMIT); await closed; + expect(notifications).toEqual([{ exitCode: null, reached: true }]); expect(calls.at(-1)?.operation).toBe("process_close"); }); diff --git a/src/windows/WindowsOwnedProcess.ts b/src/windows/WindowsOwnedProcess.ts index c228da2ca5b..bb4d66c028c 100644 --- a/src/windows/WindowsOwnedProcess.ts +++ b/src/windows/WindowsOwnedProcess.ts @@ -535,9 +535,13 @@ export class WindowsOwnedProcess extends EventEmitter { state = pollSchema.parse(observed); else { const limited = limitedPollSchema.parse(observed); - // Recorded before exit is emitted, so exit listeners observe it. - this.#memoryLimitReached ||= limited.memoryLimitReached; this.#peakJobMemoryBytes = limited.peakJobMemoryBytes; + // Publish the first allocation refusal even if the job stays alive + // and the poll contains no output. + if (!this.#memoryLimitReached && limited.memoryLimitReached) { + this.#memoryLimitReached = true; + this.emit("memory-limit"); + } state = limited; } this.#failure = undefined;