fix(bun): report the real runtime and enforce worker memory budgets on Windows (#1730)

* fix(bun): report the real runtime and enforce worker memory budgets on Windows

Under Bun, REA recorded Node/V8 identity it did not observe and its JavaScript helper processes ran without a memory bound, because Bun ignores the V8 heap flags REA passes. Source-map trace Evidence claimed runtime node-v8 with Bun's synthetic V8 heap limit (the decoder then rejected that limit, so trace_web_source_location always failed), analysis resource failures reported heap limits Bun does not enforce, the HAR decoder claimed a fixed 192 MiB heap, and doctor reported Bun's Node.js compatibility version as the Node version.

Identify the runtime once from process.versions. Source-map reports record id bun with the Bun and Node.js compatibility versions and a null v8_heap_limit_bytes; the decoder checks the heap budget only for V8 reports and rejects a report from a runtime other than the launching one. The analysis worker reports a null heap limit under Bun, HAR limitations and failures omit heap sizes under Bun, and the doctor node check reports Bun and passes when its Node.js compatibility version is supported.

On Windows under Bun, each helper's owned Job Object now carries a commit limit of its heap budget plus a measured 512 MiB Bun runtime reserve (704 MiB for the codec and HAR decoder, 1536 MiB for the default analyzer). The native addon accepts an optional page-aligned job memory limit on process_spawn, verifies it by readback, associates a private completion port before the child is created, and reports a sticky memoryLimitReached and peak job commit on each poll; inspect reports jobMemoryLimit. A requested limit with an artifact lacking the control refuses the launch, and non-Windows launchers refuse a limit.

Reaching the limit is classified by the job notification rather than Bun's exit status: the analyzer fails the current source with a memory resource failure reporting worker_process_memory_limit_bytes, the codec returns a memory resource failure, and the HAR decoder returns its memory failure with process_memory_limit_bytes. Bun source-map Evidence records process_memory_limit_bytes, verified against the launcher. Node.js launches and outputs are unchanged.

* fix(windows): drain memory notifications after observing exit

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
xeropresence
2026-10-11 19:20:00 +08:00
committed by GitHub
co-authored by morluto
parent d412def722
commit 66c21572de
48 changed files with 1630 additions and 196 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ export const createDoctorHostFixture = (
platform: "darwin",
homeDirectory: "/fixture/home",
architecture: "x64",
nodeVersion: "24.18.0",
runtime: { id: "node", version: "24.18.0" },
macosVersion: () => Promise.resolve("14.0"),
linuxDistribution: () => Promise.resolve(undefined),
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
+53 -15
View File
@@ -5,12 +5,64 @@ import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
import { createDoctorHostFixture as host } from "./Doctor.fixture.js";
import { runDoctor } from "./Doctor.js";
describe("doctor runtime check", () => {
it("reports Node 25 as unsupported", async () => {
const result = await runDoctor(
undefined,
host({ runtime: { id: "node", version: "25.1.0" } }),
);
expect(result.healthy).toBe(false);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "node",
ok: false,
detail: "25.1.0",
details: { runtime: "node", version: "25.1.0" },
classification: "missing_dependency",
}),
);
});
it.each([
{ compatibility: "26.3.0", ok: true },
{ compatibility: "25.1.0", ok: false },
])(
"identifies Bun and admits it by Node.js compatibility $compatibility",
async ({ compatibility, ok }) => {
const result = await runDoctor(
undefined,
host({
runtime: {
id: "bun",
version: "1.4.2",
nodeCompatibilityVersion: compatibility,
},
}),
);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "node",
ok,
classification: ok ? "healthy" : "missing_dependency",
details: {
runtime: "bun",
version: "1.4.2",
node_compatibility_version: compatibility,
},
}),
);
},
);
});
describe("doctor", () => {
it("returns exact recovery for every failed diagnostic", async () => {
const result = await runDoctor(
"/missing/app",
host({
nodeVersion: "20.0.0",
runtime: { id: "node", version: "20.0.0" },
macosVersion: () => Promise.resolve("11.7"),
executable: () => Promise.resolve(false),
validTarget: () => Promise.resolve(false),
@@ -28,20 +80,6 @@ describe("doctor", () => {
});
});
it("reports Node 25 as unsupported", async () => {
const result = await runDoctor(undefined, host({ nodeVersion: "25.1.0" }));
expect(result.healthy).toBe(false);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "node",
ok: false,
detail: "25.1.0",
classification: "missing_dependency",
}),
);
});
it.each(["11.7", undefined])(
"rejects unsupported macOS version %s",
async (version) => {
+6 -2
View File
@@ -8,6 +8,10 @@ import { BinaryTargetError } from "../domain/configurationErrors.js";
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
javaScriptRuntime,
type JavaScriptRuntime,
} from "../domain/runtimeVersion.js";
import { installedCaskAppdir, probeHomebrew } from "./homebrew.js";
import {
linuxHopperBinarySupported,
@@ -77,7 +81,7 @@ export interface DoctorProviderInspection {
export interface DoctorHost {
readonly platform: NodeJS.Platform;
readonly architecture: NodeJS.Architecture;
readonly nodeVersion: string;
readonly runtime: JavaScriptRuntime;
readonly homeDirectory: string;
readonly configuredHopperPath?: string;
readonly configuredIlspyCmdPath?: string;
@@ -310,7 +314,7 @@ export const systemDoctorHost = (
return {
platform,
architecture,
nodeVersion: process.versions.node,
runtime: javaScriptRuntime(process.versions),
homeDirectory,
...(environment.HOPPER_LAUNCHER_PATH === undefined
? {}
+28 -3
View File
@@ -91,11 +91,36 @@ export const doctorHealthy = (
);
};
const nodeCheck = (host: DoctorHost): DoctorCheck =>
check("node", supportsNodeVersion(host.nodeVersion), host.nodeVersion, {
/** Bun passes when its reported Node.js compatibility version is supported. */
const nodeCheck = ({ runtime }: DoctorHost): DoctorCheck => {
const failure = {
remediation: `Install ${SUPPORTED_NODE_VERSION_PROSE}.`,
classification: "missing_dependency",
});
} as const;
if (runtime.id === "node")
return {
...check(
"node",
supportsNodeVersion(runtime.version),
runtime.version,
failure,
),
details: { runtime: "node", version: runtime.version },
};
return {
...check(
"node",
supportsNodeVersion(runtime.nodeCompatibilityVersion),
`Bun ${runtime.version} (Node.js ${runtime.nodeCompatibilityVersion} compatibility)`,
failure,
),
details: {
runtime: "bun",
version: runtime.version,
node_compatibility_version: runtime.nodeCompatibilityVersion,
},
};
};
const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
const macosVersion =
@@ -93,6 +93,52 @@ it.each(["digest", "url", "point"])(
expect(response.error._tag).toBe("AnalysisOutputError");
},
);
it.each([
{
runtime: {
id: "node-v8",
version: "v24.18.0",
v8_heap_limit_bytes: 201326592,
},
limitation: "192 MiB old-generation heap and one V8 worker",
},
{
runtime: {
id: "bun",
version: "1.4.2",
node_compatibility_version: "24.3.0",
v8_heap_limit_bytes: null,
process_memory_limit_bytes: 738197504,
},
limitation:
"a Windows Job Object limited its committed memory to 738197504 bytes",
},
{
runtime: {
id: "bun",
version: "1.4.2",
node_compatibility_version: "24.3.0",
v8_heap_limit_bytes: null,
process_memory_limit_bytes: null,
},
limitation: "so no codec heap limit is established",
},
] as const)(
"states the codec memory bound its runtime enforced: $limitation",
async ({ runtime, limitation }) => {
const response = await service(undefined, {
trace: async (input) => {
const decoded = await decoder.trace(input);
if (!decoded.ok) return decoded;
return ok({ ...decoded.value, runtime });
},
}).trace(args);
if (!response.ok) throw response.error;
expect(
response.value.limitations.filter((text) => text.includes(limitation)),
).toHaveLength(1);
},
);
it("honors cancellation both before acquisition and across decoder completion", async () => {
const first = new AbortController();
first.abort();
+18 -3
View File
@@ -49,8 +49,19 @@ const LIMITATIONS = [
"Embedded source hashes identify the UTF-8 encoding of decoded sourcesContent text, not an independently retained original file. Missing or out-of-range original content positions remain explicit.",
"Lookup returns all segments at the greatest generated position not greater than the selected point, including earlier lines and generated-only segments. A mapped point does not establish an executed range or UI causality.",
"Regular maps and inline indexed sections are supported. External section URLs are unsupported; unknown extensions are retained in raw map text and are not interpreted.",
"Complete evidence has a 4 MiB map, 32 MiB reply, 262144 decoded rows/segments and 64-level section budget. The owned codec has a 20-second deadline, 192 MiB old-generation heap and one V8 worker; cleanup may extend the deadline. V8 heap limits do not establish aggregate RSS limits.",
];
const CODEC_BUDGET =
"Complete evidence has a 4 MiB map, 32 MiB reply, 262144 decoded rows/segments and 64-level section budget. The owned codec has a 20-second deadline";
/** Bun accepts but ignores the codec's V8 heap flags; Windows enforces a commit limit instead. */
const codecBudgetLimitation = (
runtime: WebSourceMapReport["runtime"],
): string => {
if (runtime.id === "node-v8")
return `${CODEC_BUDGET}, ${String(WEB_SOURCE_MAP_LIMITS.codecHeapMiB)} MiB old-generation heap and one V8 worker; cleanup may extend the deadline. V8 heap limits do not establish aggregate RSS limits.`;
return runtime.process_memory_limit_bytes === null
? `${CODEC_BUDGET}; cleanup may extend the deadline. The codec ran on Bun, which does not enforce REA's V8 heap flags, so no codec heap limit is established.`
: `${CODEC_BUDGET}; cleanup may extend the deadline. The codec ran on Bun, which does not enforce REA's V8 heap flags; a Windows Job Object limited its committed memory to ${String(runtime.process_memory_limit_bytes)} bytes, which is not a heap or RSS limit.`;
};
/** Join verified captured bytes with an explicitly selected source-map point. */
export class WebSourceLocationService {
@@ -110,6 +121,10 @@ export class WebSourceLocationService {
if (!report.ok) return report;
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const limitations = [
...LIMITATIONS,
codecBudgetLimitation(report.value.runtime),
];
const normalized = webSourceLocationResultSchema.safeParse({
...report.value,
manifest: capturedWebManifestIdentity(data),
@@ -122,7 +137,7 @@ export class WebSourceLocationService {
generated_offset: generatedOffset,
source_authenticity: "unknown",
execution: "unknown",
limitations: LIMITATIONS,
limitations,
});
if (!normalized.success) return invalidOutput(normalized.error.message);
return ok(
@@ -144,7 +159,7 @@ export class WebSourceLocationService {
rawResult: { source_map_text: map.text },
confidence: "derived",
authority: "historical-reference",
limitations: LIMITATIONS,
limitations,
locations: [
data.sourceFile.path,
data.manifestFile.path,
@@ -4,6 +4,7 @@ import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
import { inspectWebNetworkCaptureInputSchema } from "../../domain/webNetworkCapture.js";
import { historicalCaptureFailure } from "./CaptureFailures.js";
import { HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "./CaptureRelease.js";
import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
@@ -51,6 +52,99 @@ it.each([
},
});
expect(JSON.stringify(projected)).not.toContain("rea doctor");
// Bun ignores the decoder's V8 heap flags, so no fixed heap is reported.
const heapLimits = { old_generation_heap_mib: 192, semi_space_heap_mib: 8 };
if (process.versions.bun === undefined)
expect(projected).toMatchObject({
details: { reported_limits: heapLimits },
});
else
expect(projected).not.toMatchObject({
details: { reported_limits: { old_generation_heap_mib: 192 } },
});
},
);
// Measured Bun 1.4.2 outcomes at a Job Object commit limit: a 512 MiB limit
// panicked with exit 3 and a 256 MiB limit threw a JavaScript out-of-memory
// exception with exit 1. Only the job notification identifies both.
it.each([
{ label: "a runtime panic", exitCode: 3, stderr: "panic: out of memory" },
{
label: "a JavaScript exception",
exitCode: 1,
stderr: "RangeError: Out of memory",
},
])(
"reports a reached Job Object memory limit after $label",
({ exitCode, stderr }) => {
const input = inspectWebNetworkCaptureInputSchema.parse({
capture_path: "/selected/input.har",
format: "har",
});
const snapshot = {
stdout: { text: "", bytes: 0, observedBytes: 0 },
stderr: {
text: stderr,
bytes: Buffer.byteLength(stderr),
observedBytes: Buffer.byteLength(stderr),
},
exitCode,
signal: null,
};
const projected = analysisErrorProjectionSchema.parse(
projectAnalysisError(
historicalCaptureFailure(
input,
new OwnedCommandFailure("process", "Decoder failed", {
...snapshot,
memoryLimitReached: true,
}),
"decoder",
),
),
);
expect(projected).toMatchObject({
code: "resource_constraint",
message: expect.stringContaining("Windows Job Object memory limit"),
details: {
resource: "memory",
reported_limits: {
format: "har",
observed_exit_code: exitCode,
observed_signal: null,
},
captured_output: { stderr },
},
});
// The enforced limit is reported only where Bun runs on Windows.
if (HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null)
expect(JSON.stringify(projected)).not.toContain(
"process_memory_limit_bytes",
);
else
expect(projected).toMatchObject({
details: {
reported_limits: {
process_memory_limit_bytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
},
},
remediation: {
action: expect.stringContaining(
`${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes`,
),
},
});
// The same exit without the job notification remains an ordinary failure.
expect(
projectAnalysisError(
historicalCaptureFailure(
input,
new OwnedCommandFailure("process", "Decoder failed", snapshot),
"decoder",
),
),
).toMatchObject({ code: "execution_failure" });
},
);
+27 -3
View File
@@ -18,9 +18,17 @@ import {
type InspectWebNetworkCaptureInput,
} from "../../domain/webNetworkCapture.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import { HAR_CAPTURE_HEAP_LIMITS } from "./CaptureRelease.js";
import {
HAR_CAPTURE_HEAP_ENFORCED,
HAR_CAPTURE_HEAP_LIMITS,
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "./CaptureRelease.js";
const OPERATION = "inspect_web_network_capture";
/** Reason for a decoder whose owned process tree reached its Job Object commit limit. */
export const CAPTURE_PROCESS_MEMORY_LIMIT_REASON =
"The capture decoder reached its Windows Job Object memory limit";
/** Preserve the origin and typed cause of a historical capture failure. */
export const historicalCaptureFailure = (
input: InspectWebNetworkCaptureInput,
@@ -57,6 +65,18 @@ export const historicalCaptureFailure = (
);
if (cause.reason === "output-limit")
return new AnalysisOutputError(OPERATION, cause.message);
// The job's own notification is runtime-independent; Bun's exit status
// and diagnostics for an allocation failure are not.
if (
phase === "decoder" &&
cause.reason === "process" &&
cause.snapshot?.memoryLimitReached === true
)
return captureMemoryFailure(
input,
CAPTURE_PROCESS_MEMORY_LIMIT_REASON,
cause,
);
if (
phase === "decoder" &&
input.format === "har" &&
@@ -176,12 +196,16 @@ export const captureMemoryFailure = (
format: input.format,
maximum_input_bytes: WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
maximum_reply_bytes: WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
...(input.format === "har"
...(input.format === "har" && HAR_CAPTURE_HEAP_ENFORCED
? {
old_generation_heap_mib: HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB,
semi_space_heap_mib: HAR_CAPTURE_HEAP_LIMITS.semiSpaceMiB,
}
: {}),
...(input.format === "har" &&
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null
? { process_memory_limit_bytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }
: {}),
...(cause instanceof OwnedCommandFailure
? {
observed_exit_code: cause.snapshot?.exitCode ?? null,
@@ -191,7 +215,7 @@ export const captureMemoryFailure = (
},
{
cause,
remediationAction: `Use a smaller capture exported by its producer, or another decoder with sufficient capacity for the original capture. Preserve the original for provenance; a subset does not establish complete-capture coverage.${input.format === "har" ? ` REA's HAR old-generation heap is fixed at ${HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB} MiB; inherited NODE_OPTIONS cannot raise it.` : ""}`,
remediationAction: `Use a smaller capture exported by its producer, or another decoder with sufficient capacity for the original capture. Preserve the original for provenance; a subset does not establish complete-capture coverage.${input.format === "har" && HAR_CAPTURE_HEAP_ENFORCED ? ` REA's HAR old-generation heap is fixed at ${HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB} MiB; inherited NODE_OPTIONS cannot raise it.` : ""}${input.format === "har" && HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null ? ` REA's HAR decoder process commit limit is fixed at ${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes.` : ""}`,
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
? {
capturedOutput: {
+11
View File
@@ -1,3 +1,6 @@
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import { javaScriptWorkerMemoryLimitBytes } from "../../process/JavaScriptWorkerMemoryLimit.js";
/** Exact upstream package profile for unchanged offline HAR validation and numeric parsing. */
export const HAR_CAPTURE_PROVIDER_IDENTITY = {
id: "har-schema/lossless-json",
@@ -11,6 +14,14 @@ export const HAR_CAPTURE_HEAP_LIMITS = {
semiSpaceMiB: 8,
} as const;
/** The HAR decoder runs on this executable; Bun accepts but ignores V8 heap flags. */
export const HAR_CAPTURE_HEAP_ENFORCED =
javaScriptRuntime(process.versions).id === "node";
/** Windows Job Object commit limit replacing the ignored heap flags under Bun; otherwise null. */
export const HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES =
javaScriptWorkerMemoryLimitBytes(HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB);
/** Native executable profile verified with unchanged mitmproxy raw-state decoding. */
export const MITMPROXY_CAPTURE_PROVIDER_IDENTITY = {
id: "mitmproxy-native-tnetstring",
+9 -3
View File
@@ -3,15 +3,18 @@ import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAd
import {
HAR_CAPTURE_PROVIDER_IDENTITY,
HAR_CAPTURE_HEAP_LIMITS,
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "./CaptureRelease.js";
/** HAR's parser/schema packages run in one bounded Node heap, without network or target execution. */
export class HarCaptureAdapter implements HistoricalCaptureFormatAdapter {
readonly format = "har";
readonly identity = HAR_CAPTURE_PROVIDER_IDENTITY;
async command(
requestPath: string,
): Promise<{ command: string; arguments: readonly string[] }> {
async command(requestPath: string): Promise<{
command: string;
arguments: readonly string[];
memoryLimitBytes?: number;
}> {
return {
command: process.execPath,
arguments: [
@@ -22,6 +25,9 @@ export class HarCaptureAdapter implements HistoricalCaptureFormatAdapter {
fileURLToPath(new URL("./HarCaptureProcess.js", import.meta.url)),
requestPath,
],
...(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
? {}
: { memoryLimitBytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }),
};
}
}
@@ -1,7 +1,13 @@
import {
CAPTURE_PROCESS_MEMORY_LIMIT_REASON,
historicalCaptureFailure,
captureMemoryFailure,
} from "./CaptureFailures.js";
import {
HAR_CAPTURE_HEAP_ENFORCED,
HAR_CAPTURE_HEAP_LIMITS,
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "./CaptureRelease.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
import { randomUUID } from "node:crypto";
@@ -113,7 +119,7 @@ export class HistoricalCaptureDecoder {
UV_THREADPOOL_SIZE: "1",
};
delete environment.NODE_OPTIONS;
await runOwnedCommand(
const completed = await runOwnedCommand(
{
...command,
runId: `rea-web-capture-${randomUUID()}`,
@@ -126,6 +132,10 @@ export class HistoricalCaptureDecoder {
},
options?.signal === undefined ? {} : { signal: options.signal },
);
// A decoder that survived a failed allocation may still reply; its
// reply is not trusted as complete once the limit was reached.
if (completed.memoryLimitReached === true)
throw captureMemoryFailure(input, CAPTURE_PROCESS_MEMORY_LIMIT_REASON);
let reply: z.output<typeof replySchema>;
try {
const replyFile = await readStableArtifact(
@@ -204,7 +214,7 @@ export class HistoricalCaptureDecoder {
"This is retained producer evidence, without live browser transaction IDs, scenario provenance, execution attribution or deployment authenticity. Recorded URLs are never fetched.",
"Every record is decoded before selection; no partial success is returned on malformed input or a resource limit.",
"Known authentication headers/cookies and explicitly marked literal values are excluded. Unknown extension names do not establish sensitivity.",
"A 32 MiB input, 96 MiB reply and 64-level nesting budget bound complete evidence. HAR uses a 192 MiB Node old-generation heap; native decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.",
`A 32 MiB input, 96 MiB reply and 64-level nesting budget bound complete evidence. ${harMemoryLimitation()}; native decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.`,
],
});
} catch (cause: unknown) {
@@ -244,6 +254,15 @@ export class HistoricalCaptureDecoder {
}
}
/** The HAR decoder runs on this executable; only Node.js enforces its V8 heap flags. */
const harMemoryLimitation = (): string => {
if (HAR_CAPTURE_HEAP_ENFORCED)
return `HAR uses a ${String(HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB)} MiB Node old-generation heap`;
return HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
? "HAR runs on Bun, which does not enforce REA's V8 heap flags"
: `HAR runs on Bun, which does not enforce REA's V8 heap flags, under a ${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)}-byte Windows Job Object commit limit`;
};
const replyFailureReason = (cause: unknown): string => {
if (cause instanceof ArtifactReaderFailure) return cause.message;
if (cause instanceof z.ZodError)
@@ -8,8 +8,13 @@ export interface HistoricalCaptureFormatAdapter {
readonly name: string;
readonly version: string;
};
/** `memoryLimitBytes` requests an enforced commit limit for the decoder process tree. */
command(
requestPath: string,
runtimePath: string,
): Promise<{ command: string; arguments: readonly string[] }>;
): Promise<{
command: string;
arguments: readonly string[];
memoryLimitBytes?: number;
}>;
}
@@ -15,6 +15,7 @@ export const javaScriptAnalysisCoverageLimits = (
const result: ApplicationCoverage["limits"] = [];
for (const key of [
"worker_heap_limit_bytes",
"worker_process_memory_limit_bytes",
"worker_timeout_ms",
"parent_result_budget_bytes",
"semantic_result_budget_bytes",
@@ -42,7 +43,7 @@ export const javaScriptAnalysisResourceControlsSchema = z.strictObject({
.max(16_384)
.optional()
.describe(
"Maximum V8 old-space heap in MiB for the isolated JavaScript source analyzer; defaults to 1024. This does not change the CLI/MCP process heap.",
"Maximum V8 old-space heap in MiB for the isolated JavaScript source analyzer; defaults to 1024. This does not change the CLI/MCP process heap. When REA runs on Bun, which ignores V8 heap flags, Windows instead limits the analyzer's committed memory to this budget plus a 512 MiB runtime reserve; other Bun hosts enforce no limit.",
),
analysis_timeout_ms: z
.number()
+15 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { supportsNodeVersion } from "./runtimeVersion.js";
import { javaScriptRuntime, supportsNodeVersion } from "./runtimeVersion.js";
describe("supported Node.js versions", () => {
it.each([
@@ -24,3 +24,17 @@ describe("supported Node.js versions", () => {
expect(supportsNodeVersion(version)).toBe(expected);
});
});
describe("JavaScript runtime identity", () => {
it("distinguishes Bun from Node.js by its own version", () => {
expect(javaScriptRuntime({ node: "24.18.0" })).toEqual({
id: "node",
version: "24.18.0",
});
expect(javaScriptRuntime({ node: "26.3.0", bun: "1.4.2" })).toEqual({
id: "bun",
version: "1.4.2",
nodeCompatibilityVersion: "26.3.0",
});
});
});
+22
View File
@@ -10,3 +10,25 @@ export const SUPPORTED_NODE_VERSION_PROSE =
/** Return whether a Node.js version satisfies REA's tested runtime families. */
export const supportsNodeVersion = (version: string): boolean =>
satisfies(version, SUPPORTED_NODE_VERSION_RANGE);
/** JavaScript runtime executing REA. Bun also reports a Node.js compatibility version. */
export type JavaScriptRuntime =
| { readonly id: "node"; readonly version: string }
| {
readonly id: "bun";
readonly version: string;
readonly nodeCompatibilityVersion: string;
};
/** Identify the runtime from `process.versions`; only Bun reports `bun`. */
export const javaScriptRuntime = (versions: {
readonly node: string;
readonly bun?: string | undefined;
}): JavaScriptRuntime =>
versions.bun === undefined
? { id: "node", version: versions.node }
: {
id: "bun",
version: versions.bun,
nodeCompatibilityVersion: versions.node,
};
+18 -5
View File
@@ -79,11 +79,22 @@ export const webSourceMapReportSchema = z.strictObject({
source_map_sha256: digestSchema,
url_context: z.string().min(1),
engine: z.strictObject({ id: z.string().min(1), version: z.string().min(1) }),
runtime: z.strictObject({
id: z.string().min(1),
version: z.string().min(1),
v8_heap_limit_bytes: z.number().int().min(1),
}),
runtime: z.discriminatedUnion("id", [
z.strictObject({
id: z.literal("node-v8"),
version: z.string().min(1),
v8_heap_limit_bytes: z.number().int().min(1),
}),
// Bun reports V8-shaped heap statistics but does not enforce V8 heap flags.
// On Windows REA instead enforces a Job Object commit limit on the codec.
z.strictObject({
id: z.literal("bun"),
version: z.string().min(1),
node_compatibility_version: z.string().min(1),
v8_heap_limit_bytes: z.null(),
process_memory_limit_bytes: z.number().int().min(1).nullable(),
}),
]),
format: z.enum(["regular", "indexed"]),
reported_file: z.string().nullable(),
lookup: z.strictObject({
@@ -107,6 +118,8 @@ export const WEB_SOURCE_MAP_LIMITS = {
decodedRecords: 262144,
sectionDepth: 64,
decodeTimeoutMs: 20000,
/** V8 old-generation heap for the codec, and its Bun process budget. */
codecHeapMiB: 192,
} as const;
export type WebSourceMapReport = z.output<typeof webSourceMapReportSchema>;
-1
View File
@@ -54,7 +54,6 @@ const doctorHost = (
createDoctorHostFixture({
platform: "linux",
architecture: "x64",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve(undefined),
linuxDistribution: () =>
Promise.resolve({
@@ -26,10 +26,12 @@ import {
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { ok, err, type Result } from "../../domain/result.js";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import {
PrivateRuntimeRoot,
PrivateRuntimeRootUnavailableError,
} from "../../process/PrivateRuntimeRoot.js";
import { javaScriptWorkerMemoryLimitBytes } from "../../process/JavaScriptWorkerMemoryLimit.js";
import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
@@ -58,6 +60,9 @@ const OPERATION = "analyze_javascript_application";
const PROVIDER = "javascript-static-analysis";
const MIB = 1024 * 1024;
const pendingCleanup = new Set<JavaScriptAnalysisWorker>();
/** The worker runs on this executable; Bun accepts but ignores V8 heap flags. */
const WORKER_HEAP_FLAGS_ENFORCED =
javaScriptRuntime(process.versions).id === "node";
/** One sequential owned worker, retained between source files and closed after analysis. */
export class JavaScriptAnalysisWorker {
@@ -78,6 +83,8 @@ export class JavaScriptAnalysisWorker {
#retainedStaticBytes = 0;
#sourcesRemaining: number | undefined;
readonly #resultBudgetBytes: number;
/** Null when the runtime enforces the V8 heap flags instead. */
readonly #processMemoryLimitBytes: number | null;
readonly #onStdout = (chunk: Buffer | string): void => {
try {
this.#pending +=
@@ -129,6 +136,9 @@ export class JavaScriptAnalysisWorker {
"JavaScript worker source count must be a nonnegative safe integer",
);
this.#sourcesRemaining = sourceCount;
this.#processMemoryLimitBytes = javaScriptWorkerMemoryLimitBytes(
limits.heapMb,
);
// Reserve host-side control, schema/Evidence work and a maximum record's
// transient copies. Admission also accounts for retained earlier files.
this.#resultBudgetBytes = Math.max(
@@ -355,6 +365,9 @@ export class JavaScriptAnalysisWorker {
});
break;
}
// An allocation failure may surface as a protocol failure or be caught
// inside the worker; any reached limit makes this file's result partial.
if (this.#memoryLimitReached()) throw this.#memoryFailure(file.path);
} catch (cause: unknown) {
const error = this.#failure(cause, file.path, deadline, signal);
this.#lastFailure = error;
@@ -449,6 +462,9 @@ export class JavaScriptAnalysisWorker {
cwd: this.#root.path,
hostEnvironment: environment,
stdin: "pipe",
...(this.#processMemoryLimitBytes === null
? {}
: { memoryLimitBytes: this.#processMemoryLimitBytes }),
signal: deadline.signal,
});
this.#supervisor = new ProviderProcessSupervisor(
@@ -468,7 +484,12 @@ export class JavaScriptAnalysisWorker {
OPERATION,
"JavaScript worker emitted facts before its startup handshake",
);
this.#heapLimitBytes = ready.heap_limit_bytes;
if ((ready.heap_limit_bytes === null) === WORKER_HEAP_FLAGS_ENFORCED)
throw new AnalysisOutputError(
OPERATION,
"JavaScript worker heap limit does not match the runtime that launched it",
);
this.#heapLimitBytes = ready.heap_limit_bytes ?? 0;
this.#ready = true;
}
@@ -494,25 +515,27 @@ export class JavaScriptAnalysisWorker {
if (!(await this.#supervisor?.waitForOutputClose(10))) continue;
if (this.#frames.length !== 0) continue;
const drained = this.#supervisor?.snapshot() ?? snapshot;
throw /heap out of memory|heap limit|allocation failed/iu.test(
drained.stderr.text,
)
? new AnalysisResourceConstraintError(
OPERATION,
"memory",
`Owned JavaScript worker exhausted its heap while analyzing ${path} during ${this.#phase}`,
this.#limits(),
{ capturedOutput: this.#captured() },
)
: new ProviderAdapterError(PROVIDER, OPERATION, {
capturedOutput: this.#captured(),
diagnostics: {
source_path: path,
phase: this.#phase,
exit_code: drained.exitCode ?? null,
signal: drained.signal ?? null,
},
});
throw this.#memoryLimitReached()
? this.#memoryFailure(path)
: /heap out of memory|heap limit|allocation failed/iu.test(
drained.stderr.text,
)
? new AnalysisResourceConstraintError(
OPERATION,
"memory",
`Owned JavaScript worker exhausted its heap while analyzing ${path} during ${this.#phase}`,
this.#limits(),
{ capturedOutput: this.#captured() },
)
: new ProviderAdapterError(PROVIDER, OPERATION, {
capturedOutput: this.#captured(),
diagnostics: {
source_path: path,
phase: this.#phase,
exit_code: drained.exitCode ?? null,
signal: drained.signal ?? null,
},
});
}
await waitForAbortableDelay(10, deadline.signal);
}
@@ -585,13 +608,35 @@ export class JavaScriptAnalysisWorker {
#limits() {
return {
worker_old_space_mb: this.limits.heapMb,
...(this.#heapLimitBytes === 0
...(WORKER_HEAP_FLAGS_ENFORCED
? {
worker_old_space_mb: this.limits.heapMb,
...(this.#heapLimitBytes === 0
? {}
: { worker_heap_limit_bytes: this.#heapLimitBytes }),
}
: // Bun enforces no worker heap limit; report it as unavailable.
{ worker_heap_limit_bytes: null }),
...(this.#processMemoryLimitBytes === null
? {}
: { worker_heap_limit_bytes: this.#heapLimitBytes }),
: {
worker_process_memory_limit_bytes: this.#processMemoryLimitBytes,
}),
worker_timeout_ms: this.limits.timeoutMs,
};
}
#memoryLimitReached(): boolean {
return this.#supervisor?.launch.process.memoryLimitReached === true;
}
#memoryFailure(path: string): AnalysisResourceConstraintError {
return new AnalysisResourceConstraintError(
OPERATION,
"memory",
`Owned JavaScript worker reached its ${this.#processMemoryLimitBytes === null ? "" : `${String(this.#processMemoryLimitBytes)}-byte `}process memory limit while analyzing ${path} during ${this.#phase}`,
this.#limits(),
{ capturedOutput: this.#captured() },
);
}
#remainingResultBudget(): number {
// Future sources need their compact observations before current modules
// consume capacity with expanded relationships. A final or sole source
@@ -648,6 +693,13 @@ export class JavaScriptAnalysisWorker {
return new AnalysisTimeoutError(OPERATION, this.limits.timeoutMs, {
capturedOutput: this.#captured(),
});
// A reached process limit explains the worker's exit, broken pipe or
// truncated frame better than the symptom it produced.
if (
this.#memoryLimitReached() &&
!(cause instanceof AnalysisResourceConstraintError)
)
return this.#memoryFailure(path);
if (cause instanceof AnalysisError) return cause;
if (
cause instanceof z.ZodError ||
@@ -39,7 +39,8 @@ const identity = { id: z.uuid() };
export const javaScriptWorkerMessageSchema = z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("ready"),
heap_limit_bytes: z.number().int().positive(),
// Null when the worker runtime (Bun) does not enforce V8 heap flags.
heap_limit_bytes: z.number().int().positive().nullable(),
}),
z.strictObject({
kind: z.literal("phase"),
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { createInterface } from "node:readline";
import { getHeapStatistics } from "node:v8";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import type { JavaScriptStaticAnalysis } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptModuleSemanticIr } from "../../domain/javascript/javascriptModuleSemanticIr.js";
@@ -58,7 +59,10 @@ export const serveJavaScriptAnalysisWorker = async (
const requests = input[Symbol.asyncIterator]();
await send({
kind: "ready",
heap_limit_bytes: getHeapStatistics().heap_size_limit,
heap_limit_bytes:
javaScriptRuntime(process.versions).id === "node"
? getHeapStatistics().heap_size_limit
: null,
});
try {
for (;;) {
+26 -1
View File
@@ -8,6 +8,7 @@ import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
@@ -20,6 +21,7 @@ import {
PrivateRuntimeRootUnavailableError,
} from "../../process/PrivateRuntimeRoot.js";
import { ProviderStartupDeadline } from "../../process/ProviderDeadline.js";
import { javaScriptWorkerMemoryLimitBytes } from "../../process/JavaScriptWorkerMemoryLimit.js";
import { cleanupOwnedProcessGroup } from "../../process/ProcessOwnership.js";
import {
ProviderProcessSupervisor,
@@ -31,6 +33,9 @@ import { prepareProcessOwnershipInspection } from "../../process/ProcessOwnershi
const OPERATION = "trace_web_source_location";
const PROVIDER = "source-map-decoder";
/** Process commit limit enforced on the codec; null where V8 heap flags apply. */
export const SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES =
javaScriptWorkerMemoryLimitBytes(WEB_SOURCE_MAP_LIMITS.codecHeapMiB);
/** Launcher seam retains the actual codec protocol and ownership supervisor. */
export type SourceMapCodecLauncher = (
options: OwnedProviderProcessSpawnOptions,
@@ -147,7 +152,7 @@ class OwnedCodec implements SourceMapCleanupOwner {
)({
command: process.execPath,
arguments: [
"--max-old-space-size=192",
`--max-old-space-size=${String(WEB_SOURCE_MAP_LIMITS.codecHeapMiB)}`,
"--max-semi-space-size=8",
"--v8-pool-size=1",
"--single-threaded",
@@ -158,6 +163,9 @@ class OwnedCodec implements SourceMapCleanupOwner {
runId: this.#runId,
cwd: this.#runtime.path,
hostEnvironment: environment,
...(SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES === null
? {}
: { memoryLimitBytes: SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES }),
signal: this.deadline.signal,
});
this.#supervisor = new ProviderProcessSupervisor(
@@ -191,6 +199,23 @@ class OwnedCodec implements SourceMapCleanupOwner {
while (!(await supervisor.waitForOutputClose(50))) this.check();
this.check();
const snapshot = supervisor.snapshot();
// No partial codec result exists; a reached limit fails the whole trace.
if (snapshot.memoryLimitReached === true)
throw new AnalysisResourceConstraintError(
OPERATION,
"memory",
`Source-map codec reached its ${SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES === null ? "" : `${String(SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES)}-byte `}process memory limit for ${this.path}; no partial evidence was returned.`,
{
codec_process_memory_limit_bytes: SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES,
},
{
capturedOutput: {
stdout: "",
stderr: snapshot.stderr.text,
truncated: snapshot.diagnosticTruncated ?? false,
},
},
);
if (snapshot.exitCode !== 0 || snapshot.signal !== null)
throw new ProviderAdapterError(PROVIDER, OPERATION, {
diagnostics: {
+30 -8
View File
@@ -9,6 +9,7 @@ import {
} from "../../domain/analysisErrorCore.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import { err, ok, type Result } from "../../domain/result.js";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import {
WEB_SOURCE_MAP_LIMITS,
type WebSourceMapReport,
@@ -18,6 +19,7 @@ import {
sourceMapCodecReplySchema,
} from "./SourceMapCodecProtocol.js";
import {
SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES,
SourceMapCleanupFailure,
runSourceMapCommand,
type SourceMapCleanupOwner,
@@ -140,14 +142,10 @@ export class SourceMapDecoder implements WebSourceMapPort {
return err(new AnalysisCancelledError(OPERATION));
if (reply.data.state === "failure")
return codecFailure(input.path, reply.data.reason, reply.data.message);
if (reply.data.report.runtime.v8_heap_limit_bytes > 256 * 1024 * 1024)
return err(
new AnalysisOutputError(
OPERATION,
"Codec reported a V8 heap limit exceeding its independent process budget.",
),
);
return ok(reply.data.report);
const runtimeFailure = codecRuntimeFailure(reply.data.report.runtime);
return runtimeFailure === undefined
? ok(reply.data.report)
: err(new AnalysisOutputError(OPERATION, runtimeFailure));
}
async close(): Promise<void> {
@@ -173,6 +171,30 @@ export class SourceMapDecoder implements WebSourceMapPort {
return undefined;
}
}
/**
* The codec runs on this process's executable. Only a V8 report carries a heap
* limit; a Bun report must name the process limit its launcher enforced.
*/
const codecRuntimeFailure = (
runtime: WebSourceMapReport["runtime"],
): string | undefined => {
if (
runtime.id !==
(javaScriptRuntime(process.versions).id === "bun" ? "bun" : "node-v8")
)
return `Codec reported runtime ${runtime.id}, not the runtime that launched it.`;
if (
runtime.id === "node-v8" &&
runtime.v8_heap_limit_bytes > 256 * 1024 * 1024
)
return "Codec reported a V8 heap limit exceeding its independent process budget.";
if (
runtime.id === "bun" &&
runtime.process_memory_limit_bytes !== SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES
)
return "Codec reported a process memory limit other than the one its launcher enforced.";
return undefined;
};
const codecFailure = (
path: string,
reason: "format" | "unsupported" | "limit",
+21 -5
View File
@@ -8,6 +8,8 @@ import {
type SourceMapSegment,
} from "@jridgewell/trace-mapping";
import { z } from "zod";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import { javaScriptWorkerMemoryLimitBytes } from "../../process/JavaScriptWorkerMemoryLimit.js";
import { webSourceOffset } from "../../domain/webSourcePosition.js";
import {
webSourceMapReportSchema,
@@ -72,15 +74,29 @@ export const traceSourceMap = (
const version = z
.object({ version: z.string().min(1) })
.parse(metadata).version;
const runtime = javaScriptRuntime(process.versions);
return webSourceMapReportSchema.parse({
source_map_sha256: createHash("sha256").update(text).digest("hex"),
url_context: url,
engine: { id: "jridgewell-trace-mapping", version },
runtime: {
id: "node-v8",
version: process.version,
v8_heap_limit_bytes: getHeapStatistics().heap_size_limit,
},
// Bun reports V8-shaped heap statistics but ignores the codec's heap flags.
// Its launcher applies the same runtime policy, and the parent verifies it.
runtime:
runtime.id === "node"
? {
id: "node-v8",
version: process.version,
v8_heap_limit_bytes: getHeapStatistics().heap_size_limit,
}
: {
id: "bun",
version: runtime.version,
node_compatibility_version: runtime.nodeCompatibilityVersion,
v8_heap_limit_bytes: null,
process_memory_limit_bytes: javaScriptWorkerMemoryLimitBytes(
WEB_SOURCE_MAP_LIMITS.codecHeapMiB,
),
},
format: inspected.format,
reported_file: inspected.reportedFile,
lookup: {
@@ -0,0 +1,33 @@
import { expect, it } from "vitest";
import {
BUN_WORKER_RUNTIME_RESERVE_BYTES,
javaScriptWorkerMemoryLimitBytes,
} from "./JavaScriptWorkerMemoryLimit.js";
const MIB = 1024 * 1024;
const bun = { node: "24.3.0", bun: "1.4.2" };
const node = { node: "24.18.0" };
it("limits a Bun worker on Windows to its heap budget plus Bun's runtime reserve", () => {
expect(BUN_WORKER_RUNTIME_RESERVE_BYTES).toBe(512 * MIB);
expect(
javaScriptWorkerMemoryLimitBytes(192, { platform: "win32", versions: bun }),
).toBe(704 * MIB);
expect(
javaScriptWorkerMemoryLimitBytes(1024, {
platform: "win32",
versions: bun,
}),
).toBe(1536 * MIB);
});
it.each([
{ label: "Node.js on Windows", platform: "win32", versions: node },
{ label: "Node.js on Linux", platform: "linux", versions: node },
{ label: "Bun on Linux", platform: "linux", versions: bun },
{ label: "Bun on macOS", platform: "darwin", versions: bun },
] as const)("applies no process limit for $label", ({ platform, versions }) => {
expect(javaScriptWorkerMemoryLimitBytes(192, { platform, versions })).toBe(
null,
);
});
@@ -0,0 +1,41 @@
import { javaScriptRuntime } from "../domain/runtimeVersion.js";
const MIB = 1024 * 1024;
/**
* Commit reserved for Bun itself above a worker's heap budget.
*
* Measured on Windows x64 (Bun 1.4.2, 32 logical processors) as the peak Job
* Object commit of each REA worker on a trivial input: `bun -e 1` commits
* 52 MiB, while the source-map codec (278-368 MiB), HAR decoder (300-345 MiB)
* and JavaScript analysis worker (321-346 MiB) commit up to 368 MiB before any
* real workload because JavaScriptCore commits parsed and compiled module code
* and per-thread runtime state. 512 MiB covers that peak with about 40%
* margin for hosts with other processor counts or module layouts.
*/
export const BUN_WORKER_RUNTIME_RESERVE_BYTES = 512 * MIB;
/** Runtime facts that decide whether V8 heap flags bound a worker. */
export interface JavaScriptWorkerHost {
readonly platform: NodeJS.Platform;
readonly versions: {
readonly node: string;
readonly bun?: string | undefined;
};
}
/**
* Process commit limit for a JavaScript worker launched on `process.execPath`.
*
* Node.js enforces each worker's V8 heap flags, so it receives no process
* limit (null) and its launch is unchanged. Bun ignores those flags; on Windows
* the owned Job Object then enforces the worker's heap budget plus Bun's
* runtime reserve. Bun elsewhere has no owned enforcement and also gets null.
*/
export const javaScriptWorkerMemoryLimitBytes = (
heapBudgetMiB: number,
host: JavaScriptWorkerHost = process,
): number | null =>
host.platform === "win32" && javaScriptRuntime(host.versions).id === "bun"
? heapBudgetMiB * MIB + BUN_WORKER_RUNTIME_RESERVE_BYTES
: null;
+22 -1
View File
@@ -30,6 +30,11 @@ export interface OwnedProviderProcessSpawnOptions {
readonly hostEnvironment?: NodeJS.ProcessEnv;
/** Opt into a writable protocol stream; other providers retain ignored stdin. */
readonly stdin?: "pipe";
/**
* Commit limit in bytes for the whole owned process tree, enforced by its
* Windows Job Object. Other launchers cannot enforce it and refuse it.
*/
readonly memoryLimitBytes?: number;
/** Cancels native ownership preparation before provider process creation. */
readonly signal?: AbortSignal;
}
@@ -52,6 +57,8 @@ 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. */
readonly memoryLimitReached?: boolean;
kill(signal?: NodeJS.Signals | number): boolean;
}
@@ -89,6 +96,8 @@ export interface ProviderProcessSnapshot {
};
readonly exitCode: number | null | undefined;
readonly signal: NodeJS.Signals | null | undefined;
/** Present only when the process tree reached its enforced memory limit. */
readonly memoryLimitReached?: true;
}
/** Resource-safe events emitted without imposing provider protocol semantics. */
@@ -162,7 +171,12 @@ export const spawnOwnedProviderProcess = async (
options.cwd,
environment,
options.windowsVerbatimArguments ?? false,
options.stdin === "pipe",
{
protocolStdin: options.stdin === "pipe",
...(options.memoryLimitBytes === undefined
? {}
: { memoryLimitBytes: options.memoryLimitBytes }),
},
);
return {
process: child,
@@ -175,6 +189,10 @@ export const spawnOwnedProviderProcess = async (
cleanup: () => child.cleanup(),
};
}
if (options.memoryLimitBytes !== undefined)
throw new Error(
"Owned process memory limits require the Windows Job Object launcher; no limit can be enforced on this host.",
);
const child = spawn(options.command, [...options.arguments], {
shell: false,
windowsHide: true,
@@ -277,6 +295,9 @@ export class ProviderProcessSupervisor {
stderr: this.#stderr.snapshot(this.#stderrObservedBytes),
exitCode: this.#exitObservation?.code,
signal: this.#exitObservation?.signal,
...(this.launch.process.memoryLimitReached === true
? { memoryLimitReached: true }
: {}),
};
}
+37
View File
@@ -33,3 +33,40 @@ it("exit does not establish complete output when a producer closes its streams l
supervisor.dispose();
}
});
it("reports a reached process memory limit only when the handle observed one", () => {
let reached = false;
const producer = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: null,
signalCode: null,
kill: () => false,
});
// A live accessor, as on the owned Windows process handle.
Object.defineProperty(producer, "memoryLimitReached", { get: () => reached });
const exitSnapshots: unknown[] = [];
const supervisor = new ProviderProcessSupervisor(
{ process: producer, ownsProcessLifetime: false },
{
onDiagnostic: (event) => {
if (event.type === "exit") exitSnapshots.push(event.snapshot);
},
},
);
try {
expect(supervisor.snapshot()).not.toHaveProperty("memoryLimitReached");
// Owned launchers record the job notification before emitting exit.
reached = true;
producer.emit("exit", 3, null);
expect(supervisor.snapshot()).toMatchObject({
exitCode: 3,
memoryLimitReached: true,
});
expect(exitSnapshots).toEqual([
expect.objectContaining({ memoryLimitReached: true }),
]);
} finally {
supervisor.dispose();
}
});
+21 -3
View File
@@ -7,7 +7,9 @@ import {
type WindowsNativeLoadHost,
} from "./WindowsNativeLoader.js";
const fixture = (protocolStdin?: boolean) => {
const fixture = (
capabilities: { protocolStdin?: boolean; jobMemoryLimit?: unknown } = {},
) => {
const bytes = Buffer.alloc(128);
bytes.write("MZ");
bytes.writeUInt32LE(64, 0x3c);
@@ -51,7 +53,7 @@ const fixture = (protocolStdin?: boolean) => {
privateDacl: true,
atomicJobAssignment: true,
killOnOwnerClose: true,
...(protocolStdin === undefined ? {} : { protocolStdin }),
...capabilities,
}),
};
},
@@ -63,7 +65,7 @@ describe("packaged Windows native admission", () => {
it.each([true, false])(
"preserves protocol stdin capability %s alongside existing job controls",
(protocolStdin) => {
const value = fixture(protocolStdin);
const value = fixture({ protocolStdin });
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
available: true,
authority: {
@@ -76,6 +78,22 @@ describe("packaged Windows native admission", () => {
});
},
);
it("admits the Job Object memory limit control only as an affirmative observation", () => {
expect(
loadWindowsNativeAuthority(fixture({ jobMemoryLimit: true }).host),
).toMatchObject({
available: true,
authority: { inspection: { jobMemoryLimit: true } },
});
// Earlier artifacts omit the control; callers must refuse a limit then.
const earlier = loadWindowsNativeAuthority(fixture().host);
if (!earlier.available) throw new Error(earlier.reason);
expect(earlier.authority.inspection.jobMemoryLimit).toBeUndefined();
expect(
loadWindowsNativeAuthority(fixture({ jobMemoryLimit: false }).host)
.available,
).toBe(false);
});
it("loads only after compatibility and digest checks, preserving producer identity", () => {
const value = fixture();
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
+2
View File
@@ -44,6 +44,8 @@ const inspectionSchema = z.strictObject({
atomicJobAssignment: z.literal(true),
killOnOwnerClose: z.literal(true),
protocolStdin: z.boolean().optional(),
/** Absent from artifacts built before owned Job Object commit limits. */
jobMemoryLimit: z.literal(true).optional(),
});
type NativeCall = (
+161 -1
View File
@@ -1,6 +1,11 @@
import { once } from "node:events";
import { describe, expect, it } from "vitest";
import { quoteWindowsProcessArgument } from "./WindowsOwnedProcess.js";
import type { WindowsNativeAuthority } from "./WindowsNativeLoader.js";
import {
quoteWindowsProcessArgument,
WindowsOwnedProcess,
} from "./WindowsOwnedProcess.js";
describe("Windows process argument representation", () => {
it.each([
@@ -18,3 +23,158 @@ describe("Windows process argument representation", () => {
expect(() => quoteWindowsProcessArgument("a\0b")).toThrow("NUL");
});
});
const LIMIT = 704 * 1024 * 1024;
const settledPoll = {
stdout: Buffer.alloc(0),
stderr: Buffer.from("allocation failed"),
stdoutEnded: true,
stderrEnded: true,
exitCode: 3,
activeProcesses: 0,
};
/** Native authority double that records calls and replays exact poll observations. */
const authority = (
options: {
readonly jobMemoryLimit?: true;
readonly polls?: readonly unknown[];
readonly appliedLimit?: (requested: unknown) => unknown;
} = {},
) => {
const calls: { operation: string; arguments_: readonly unknown[] }[] = [];
const polls = [...(options.polls ?? [])];
const native: WindowsNativeAuthority = {
inspection: {
abiVersion: 1,
nodeApiVersion: 8,
architecture: "x64",
filesystem: {
requestedPath: "C:\\probe",
finalPath: "C:\\probe",
filesystem: "NTFS",
volumeSerial: "0".repeat(16),
fileId: "0".repeat(32),
size: 0,
directory: true,
},
privateDacl: true,
atomicJobAssignment: true,
killOnOwnerClose: true,
protocolStdin: true,
...(options.jobMemoryLimit === undefined ? {} : { jobMemoryLimit: true }),
},
call: (operation, arguments_) => {
calls.push({ operation, arguments_ });
if (operation === "process_spawn")
return {
pid: 42,
handle: {},
jobAssigned: true,
killOnOwnerClose: true,
...(arguments_.length === 6
? {
jobMemoryLimitBytes: (
options.appliedLimit ?? ((value) => value)
)(arguments_[5]),
}
: {}),
};
if (operation === "process_poll") return polls.shift();
if (operation === "process_close") return null;
throw new Error(`Unmodeled native operation ${operation}`);
},
};
return { native, calls };
};
const launch = (
native: WindowsNativeAuthority,
memoryLimitBytes?: number,
): WindowsOwnedProcess =>
new WindowsOwnedProcess(
"C:\\runtime\\bun.exe",
["worker.js"],
"C:\\work",
{},
false,
{
authority: native,
...(memoryLimitBytes === undefined ? {} : { memoryLimitBytes }),
},
);
describe("Windows Job Object memory limits", () => {
it("refuses a requested limit before launch when the artifact lacks the control", () => {
const { native, calls } = authority();
expect(() => launch(native, LIMIT)).toThrow(
"does not support Job Object memory limits",
);
expect(calls).toEqual([]);
});
it("keeps the unlimited launch shape and rejects limit fields it did not request", async () => {
const { native, calls } = authority({
jobMemoryLimit: true,
polls: [
{ ...settledPoll, memoryLimitReached: true, peakJobMemoryBytes: 1 },
],
});
const child = launch(native);
const failure = once(child, "error");
expect(calls[0]?.arguments_).toHaveLength(4);
const [error] = await failure;
expect(error).toBeInstanceOf(Error);
expect(child.memoryLimitReached).toBe(false);
expect(child.peakJobMemoryBytes).toBeUndefined();
});
it("passes the limit, verifies its read-back and reports a reached limit before exit", async () => {
const { native, calls } = authority({
jobMemoryLimit: true,
polls: [
{
...settledPoll,
exitCode: null,
stdoutEnded: false,
stderrEnded: false,
activeProcesses: 1,
memoryLimitReached: false,
peakJobMemoryBytes: 300 * 1024 * 1024,
},
{ ...settledPoll, memoryLimitReached: true, peakJobMemoryBytes: LIMIT },
],
});
const child = launch(native, LIMIT);
expect(calls[0]?.arguments_.slice(4)).toEqual([false, LIMIT]);
const closed = once(child, "close");
const exited = new Promise((resolve) => {
child.once("exit", (code: number) =>
resolve({ code, reached: child.memoryLimitReached }),
);
});
expect(await exited).toEqual({ code: 3, reached: true });
expect(child.peakJobMemoryBytes).toBe(LIMIT);
await closed;
expect(calls.at(-1)?.operation).toBe("process_close");
});
it("rejects a limited poll that omits the job's notification state", async () => {
const { native } = authority({
jobMemoryLimit: true,
polls: [settledPoll],
});
const child = launch(native, LIMIT);
const [error] = await once(child, "error");
expect(error).toBeInstanceOf(Error);
expect(child.memoryLimitReached).toBe(false);
});
it("refuses a launch whose applied limit differs from the request", () => {
const { native } = authority({
jobMemoryLimit: true,
appliedLimit: () => LIMIT - 4096,
});
expect(() => launch(native, LIMIT)).toThrow();
});
});
+77 -14
View File
@@ -24,6 +24,26 @@ const pollSchema = z.strictObject({
exitCode: z.number().int().nonnegative().max(0xffff_ffff).nullable(),
activeProcesses: z.number().int().nonnegative(),
});
// A commit-limited job reports its applied limit at launch and its
// notification state on every poll; an unlimited job reports neither.
const limitedPollSchema = pollSchema.extend({
memoryLimitReached: z.boolean(),
peakJobMemoryBytes: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER),
});
/** Optional native job controls for one owned Windows process tree. */
export interface WindowsOwnedProcessOptions {
/** Open a writable protocol pipe; otherwise stdin is NUL. */
readonly protocolStdin?: boolean;
/** Job Object commit limit for the whole process tree, in bytes. */
readonly memoryLimitBytes?: number;
/** Verified native authority; defaults to the package-owned artifact. */
readonly authority?: WindowsNativeAuthority;
}
/** Encode one ordinary Windows argv token using the CRT backslash rules. */
export const quoteWindowsProcessArgument = (value: string): string => {
@@ -48,6 +68,9 @@ export class WindowsOwnedProcess extends EventEmitter {
#failure: string | undefined;
#timer: NodeJS.Timeout | undefined;
#cleanup: Promise<ProcessCleanupResult> | undefined;
readonly #memoryLimitBytes: number | undefined;
#memoryLimitReached = false;
#peakJobMemoryBytes: number | undefined;
constructor(
command: string,
@@ -55,14 +78,25 @@ export class WindowsOwnedProcess extends EventEmitter {
cwd: string | undefined,
environment: NodeJS.ProcessEnv,
verbatim: boolean,
protocolStdin = false,
options: WindowsOwnedProcessOptions = {},
) {
super();
this.#authority = requireWindowsNativeAuthority();
const protocolStdin = options.protocolStdin === true;
this.#memoryLimitBytes = options.memoryLimitBytes;
this.#authority = options.authority ?? requireWindowsNativeAuthority();
if (protocolStdin && this.#authority.inspection.protocolStdin !== true)
throw new Error(
"The bundled Windows native artifact does not support owned protocol stdin; use a matching current Windows x64 REA package.",
);
// A requested limit is never dropped: an artifact without the control
// refuses the launch instead of starting an unlimited process.
if (
this.#memoryLimitBytes !== undefined &&
this.#authority.inspection.jobMemoryLimit !== true
)
throw new Error(
"The bundled Windows native artifact does not support Job Object memory limits; use a matching current Windows x64 REA package.",
);
const entries = Object.entries(environment)
.filter((entry): entry is [string, string] => entry[1] !== undefined)
.map(([key, value]) => `${key}=${value}`);
@@ -74,15 +108,24 @@ export class WindowsOwnedProcess extends EventEmitter {
verbatim ? value : quoteWindowsProcessArgument(value),
),
].join(" ");
const launched = launchSchema.parse(
this.#authority.call("process_spawn", [
command,
line,
cwd ?? "",
entries,
...(protocolStdin ? [true] : []),
]),
);
// Earlier artifacts accept only 4 or 5 arguments; keep that shape unless
// a commit limit is requested.
let controls: unknown[] = protocolStdin ? [true] : [];
if (this.#memoryLimitBytes !== undefined)
controls = [protocolStdin, this.#memoryLimitBytes];
const spawned = this.#authority.call("process_spawn", [
command,
line,
cwd ?? "",
entries,
...controls,
]);
const launched =
this.#memoryLimitBytes === undefined
? launchSchema.parse(spawned)
: launchSchema
.extend({ jobMemoryLimitBytes: z.literal(this.#memoryLimitBytes) })
.parse(spawned);
this.pid = launched.pid;
this.#handle = launched.handle;
this.stdin = protocolStdin
@@ -125,6 +168,16 @@ export class WindowsOwnedProcess extends EventEmitter {
this.#schedule();
}
/** Whether the job reported reaching its commit limit; sticky once observed. */
get memoryLimitReached(): boolean {
return this.#memoryLimitReached;
}
/** Latest observed peak job commit; undefined for an unlimited job. */
get peakJobMemoryBytes(): number | undefined {
return this.#peakJobMemoryBytes;
}
async #writeInput(chunk: unknown): Promise<void> {
const bytes = z.instanceof(Buffer).parse(chunk);
const written = z
@@ -208,9 +261,19 @@ export class WindowsOwnedProcess extends EventEmitter {
this.#timer = undefined;
if (this.#closed) return;
try {
const state = pollSchema.parse(
this.#authority.call("process_poll", [this.#handle]),
);
const observed: unknown = this.#authority.call("process_poll", [
this.#handle,
]);
let state: z.output<typeof pollSchema>;
if (this.#memoryLimitBytes === undefined)
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;
state = limited;
}
this.#failure = undefined;
if (state.stdout.length > 0) this.stdout.write(state.stdout);
if (state.stderr.length > 0) this.stderr.write(state.stderr);