fix(engine): a heavy page starts only as many capture browsers as the machine's memory holds (#8452)

* fix(engine): a heavy page starts only as many capture browsers as the machine's memory holds

Worker 0 loads the page alone; its browsers' measured memory caps how many more launch, and the frames are split again across the ones kept. A worker phase that starts after the pool was cancelled no longer leaves its own failure unhandled.

* refactor(engine): drop a frame-range update the capped first worker never reads

* chore(engine): its packed size budget grows by the 1,040 bytes the worker memory cap adds

* test(engine): the re-split pool test builds its folder paths the way Windows does
This commit is contained in:
Miguel Ángel
2026-11-22 09:03:34 +00:00
committed by GitHub
parent 3e101f9654
commit 969eeba6ee
5 changed files with 241 additions and 21 deletions
@@ -0,0 +1,71 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { CaptureSession } from "./frameCapture.js";
const GIB = 1024;
describe("a parallel capture whose page is heavier than the memory budget assumes", () => {
afterEach(() => {
vi.resetModules();
vi.doUnmock("./frameCapture.js");
vi.doUnmock("./systemMemory.js");
});
it("launches only the browsers that fit, measured from worker 0's loaded page, and captures every frame", async () => {
const root = mkdtempSync(join(tmpdir(), "hf-memory-fit-"));
const launched: string[] = [];
const captured: number[] = [];
vi.doMock("./systemMemory.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./systemMemory.js")>()),
getSystemTotalMb: () => 24 * GIB,
}));
vi.doMock("./frameCapture.js", () => ({
createCaptureSession: vi.fn(async (_url: string, outputDir: string) => {
launched.push(outputDir.slice(-8));
return {
options: {},
browserConsoleBuffer: [],
chromeMemory: {
sampleOnce: async () => {},
stats: () => ({ samples: 1, rssLastMb: 3_700 }),
},
} as unknown as CaptureSession;
}),
initializeSession: vi.fn(async () => {}),
captureFrame: vi.fn(async (_session: CaptureSession, frameIndex: number) => {
captured.push(frameIndex);
return { path: join(root, `frame_${frameIndex}.png`) };
}),
captureFrameToBuffer: vi.fn(),
captureFrameToBufferPipelined: vi.fn(),
closeCaptureSession: vi.fn(async () => {}),
getCapturePerfSummary: vi.fn(() => ({ frames: 0 })),
}));
try {
const { distributeFrames, executeParallelCapture } = await import("./parallelCoordinator.js");
const tasks = distributeFrames(60, 6, root);
const results = await executeParallelCapture(
"http://127.0.0.1",
root,
tasks,
{ width: 1920, height: 1080, fps: { num: 30, den: 1 } },
() => null,
);
// 24 GiB x 0.5 / 3.7 GiB per browser = 3 browsers, not the 6 the split asked for.
expect(launched).toEqual(["worker-0", "worker-1", "worker-2"]);
expect(results.map((r) => [r.startFrame, r.endFrame])).toEqual([
[0, 20],
[20, 40],
[40, 60],
]);
expect(tasks).toHaveLength(3);
expect([...captured].sort((a, b) => a - b)).toEqual(Array.from({ length: 60 }, (_, i) => i));
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
@@ -78,7 +78,7 @@ describe("executeParallelCapture peer abort", () => {
} as unknown as CaptureSession & { workerId: number };
}),
initializeSession: vi.fn(async (session: CaptureSession & { workerId: number }) => {
if (session.workerId === 0) throw new Error("Composition has zero duration.");
if (session.workerId === 1) throw new Error("Composition has zero duration.");
await Promise.resolve();
}),
captureFrame: vi.fn().mockResolvedValue(undefined),
@@ -1,4 +1,5 @@
import { availableParallelism, totalmem } from "os";
import { join } from "path";
import { getHeapStatistics } from "v8";
import { afterEach, describe, it, expect, vi } from "vitest";
import {
@@ -6,6 +7,7 @@ import {
computeWorkerSizing,
createPoolFailureHandler,
distributeFrames,
distributeFramesInterleaved,
expectedFramesForTask,
flagSilentWorkerExits,
formatPoolFailure,
@@ -16,6 +18,7 @@ import {
selectWorkerDiagnostics,
shouldDisableBrowserPoolForParallelWorker,
shouldVerifyWorkerGpu,
shrinkTasks,
synthesizeSilentWorkerExitError,
withParallelWorkerDeadline,
resolveParallelDeVerifySamples,
@@ -52,6 +55,61 @@ describe("parallel worker phase deadline", () => {
});
});
describe("a worker phase started after the pool was cancelled", () => {
it("rejects as cancelled and leaves no unhandled rejection when the phase fails later", async () => {
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown) => unhandled.push(reason);
process.on("unhandledRejection", onUnhandled);
try {
const controller = new AbortController();
controller.abort();
let failPhase!: (error: Error) => void;
const phase = new Promise<void>((_, reject) => (failPhase = reject));
const diagnostic = {
workerId: 1,
phase: "session_init" as const,
browserExecutable: "chrome",
browserVersion: "unknown",
canvasDrawElement: false,
gpuBackend: "unknown",
};
await expect(
withParallelWorkerDeadline(phase, diagnostic, 0, controller.signal),
).rejects.toThrow("Parallel worker cancelled");
failPhase(new Error("page failed to load"));
await new Promise((settle) => setImmediate(settle));
expect(unhandled).toEqual([]);
} finally {
process.off("unhandledRejection", onUnhandled);
}
});
});
describe("shrinkTasks", () => {
it("re-splits an interleaved pool across the kept workers, covering every frame once", () => {
const tasks = distributeFramesInterleaved(10, 4, "/tmp/work", 100);
expect(shrinkTasks(tasks, 2)).toBe(true);
const frames = tasks.flatMap((task) => {
const out: number[] = [];
for (let f = task.startFrame; f < task.endFrame; f += task.frameStride ?? 1) out.push(f);
return out;
});
expect(tasks.map((task) => task.outputDir)).toEqual([
join("/tmp/work", "worker-0"),
join("/tmp/work", "worker-1"),
]);
expect(frames.sort((a, b) => a - b)).toEqual(Array.from({ length: 10 }, (_, i) => 100 + i));
});
it("leaves a pool it cannot re-split unchanged", () => {
const tasks = distributeFrames(10, 3, "/tmp/work");
tasks[1]!.startFrame = 5;
const before = structuredClone(tasks);
expect(shrinkTasks(tasks, 2)).toBe(false);
expect(tasks).toEqual(before);
});
});
describe("distributeFrames", () => {
it("distributes frames evenly across workers", () => {
const tasks = distributeFrames(100, 4, "/tmp/work");
@@ -153,6 +153,8 @@ type WorkerBrowserPoolDecision = {
// Chrome-under-capture RSS and let memory-constrained hosts overcommit (wild
// 16GB black-slab report; 0.7.66 heap-OOM report on 24GB with 6 auto workers).
const MEMORY_PER_WORKER_MB = 1536;
/** Share of the machine's (or container's) memory the capture browsers may take together. */
const WORKER_MEMORY_SHARE = 0.5;
// Parent-process V8 heap the coordinator itself needs regardless of worker
// count (compile artifacts, puppeteer sessions, encoder state).
const HEAP_RESERVED_MB = 1024;
@@ -358,7 +360,10 @@ export function computeWorkerSizing(
1,
cpuQuota === null ? cpuCount - 2 : Math.min(cpuCount - 2, Math.floor(cpuQuota)),
);
const memoryBasedWorkers = Math.max(1, Math.floor((totalMemoryMb * 0.5) / MEMORY_PER_WORKER_MB));
const memoryBasedWorkers = Math.max(
1,
Math.floor((totalMemoryMb * WORKER_MEMORY_SHARE) / MEMORY_PER_WORKER_MB),
);
const frameBasedWorkers = Math.floor(totalFrames / MIN_FRAMES_PER_WORKER);
const captureCostMultiplier = Math.max(1, config?.captureCostMultiplier ?? 1);
@@ -512,6 +517,55 @@ export function distributeFramesInterleaved(
return tasks;
}
/** Workers whose browsers fit the memory share, at the RSS one browser measured with the page loaded. */
function workersWithinMemory(
requested: number,
browserRssMb: number | undefined,
totalMemoryMb: number = getSystemTotalMb(),
): number {
if (browserRssMb === undefined || browserRssMb <= 0) return requested;
const fit = Math.floor((totalMemoryMb * WORKER_MEMORY_SHARE) / browserRssMb);
return Math.max(MIN_WORKERS, Math.min(requested, fit));
}
/**
* Re-split a contiguous or interleaved pool for its first `keep` workers, in place. Worker 0 keeps its task (its
* page is loaded); the others keep their output folders. Returns false, unchanged, for any other shape of split.
*/
export function shrinkTasks(tasks: WorkerTask[], keep: number): boolean {
const first = tasks[0];
if (!first || keep < 1 || keep >= tasks.length) return false;
const stride = first.frameStride ?? 1;
const contiguous = tasks.every(
(task, i) =>
(task.frameStride ?? 1) === 1 && (i === 0 || task.startFrame === tasks[i - 1]!.endFrame),
);
const interleaved =
stride === tasks.length &&
tasks.every(
(task, i) =>
task.frameStride === stride &&
task.startFrame === first.startFrame + i &&
task.endFrame === first.endFrame,
);
if (!contiguous && !interleaved) return false;
const end = contiguous ? tasks[tasks.length - 1]!.endFrame : first.endFrame;
const split = (contiguous ? distributeFrames : distributeFramesInterleaved)(
end - first.startFrame,
keep,
"",
first.startFrame,
);
split.forEach((range, i) => {
const task = tasks[i]!;
task.startFrame = range.startFrame;
task.endFrame = range.endFrame;
if (interleaved) task.frameStride = range.frameStride;
});
tasks.splice(split.length);
return true;
}
/**
* Decide whether a parallel worker should run the per-worker SwiftShader
* assertion. Gated to worker 0 only: workers within a chunk share the same
@@ -546,7 +600,10 @@ export function withParallelWorkerDeadline<T>(
timeoutMs: number,
signal?: AbortSignal,
): Promise<T> {
if (signal?.aborted) return Promise.reject(new Error("Parallel worker cancelled"));
if (signal?.aborted) {
promise.catch(() => {});
return Promise.reject(new Error("Parallel worker cancelled"));
}
return new Promise<T>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = () => {
@@ -901,6 +958,7 @@ async function executeWorkerTask(
onWorkerPhase?: (diagnostic: ParallelWorkerPhaseDiagnostic) => void,
onWorkerOperation?: (diagnostic: ParallelWorkerPhaseDiagnostic) => void,
gate?: FirstSessionGate,
onLoaded?: (session: CaptureSession) => Promise<void>,
): Promise<WorkerResult> {
const startTime = Date.now();
let framesCaptured = 0;
@@ -969,6 +1027,7 @@ async function executeWorkerTask(
await assertSwiftShader(activeSession.page, readWebGlVendorInfoFromCanvas);
}
await initializeSession(activeSession);
await onLoaded?.(activeSession);
if (gate) await (task.workerId === 0 ? gate.verify(activeSession) : gate.wait());
});
canvasDrawElement = activeSession.captureMode === "drawelement";
@@ -1151,6 +1210,39 @@ export function createPoolFailureHandler(args: {
};
}
/**
* Worker 0 loads the page alone; its browser's memory then caps how many more launch, so a heavy page cannot
* start more browsers than the container holds. The others start when worker 0 is loaded or has failed.
*/
async function launchWithinMemory(
tasks: WorkerTask[],
run: (
task: WorkerTask,
onLoaded?: (session: CaptureSession) => Promise<void>,
) => Promise<WorkerResult>,
): Promise<WorkerResult[]> {
const [first] = tasks;
if (!first || tasks.length === 1) return Promise.all(tasks.map((task) => run(task)));
const requested = tasks.length;
let release!: () => void;
const loaded = new Promise<void>((resolve) => (release = resolve));
const firstResult = run(first, async (session) => {
await session.chromeMemory?.sampleOnce();
const browserRssMb = session.chromeMemory?.stats().rssLastMb;
const keep = workersWithinMemory(requested, browserRssMb);
if (shrinkTasks(tasks, keep)) {
console.warn("[Parallel] capture workers capped to fit memory", {
requested,
keep,
browserRssMb,
});
}
release();
}).finally(release);
await loaded;
return Promise.all([firstResult, ...tasks.slice(1).map((task) => run(task))]);
}
export async function executeParallelCapture(
serverUrl: string,
workDir: string,
@@ -1226,23 +1318,22 @@ export async function executeParallelCapture(
});
const onFailure = failureHandler.onFailure;
const gate = hooks?.verifyFirstSession && createFirstSessionGate(hooks.verifyFirstSession);
const results = await Promise.all(
tasks.map((task) =>
executeWorkerTask(
task,
serverUrl,
workerCaptureOptions,
createBeforeCaptureHook,
workerSignal,
onFrameCaptured,
onFrameBuffer,
config,
parallel,
onFailure,
onWorkerPhase,
hooks?.onWorkerOperation,
gate,
),
const results = await launchWithinMemory(tasks, (task, onLoaded) =>
executeWorkerTask(
task,
serverUrl,
workerCaptureOptions,
createBeforeCaptureHook,
workerSignal,
onFrameCaptured,
onFrameBuffer,
config,
parallel,
onFailure,
onWorkerPhase,
hooks?.onWorkerOperation,
gate,
onLoaded,
),
);
+1 -1
View File
@@ -12,7 +12,7 @@
"unpacked": 4898942
},
"@hyperframes/engine": {
"packed": 510000,
"packed": 511040,
"unpacked": 1742862
},
"@hyperframes/gcp-cloud-run": {