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
@@ -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;
}>;
}