Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

test(javascript): separate heap pressure from graph admission proof

morluto84c89d1107cd
diff --git a/tests/acceptance/applications/javascriptCheckpointReserveCli.test.ts b/tests/acceptance/applications/javascriptCheckpointReserveCli.test.ts
index 32d113781..5e612caf9 100644
--- a/tests/acceptance/applications/javascriptCheckpointReserveCli.test.ts
+++ b/tests/acceptance/applications/javascriptCheckpointReserveCli.test.ts
@@ -9,11 +9,54 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
+const assertRetainedMemoryFailure = (value: unknown, path: string): void => {
+ const parsed = z
+ .object({
+ code: z.literal("resource_constraint"),
+ message: z.string(),
+ details: z.object({
+ operation: z.literal("analyze_javascript_application"),
+ resource: z.literal("memory"),
+ reported_limits: z.record(z.string(), z.unknown()),
+ }),
+ remediation: z.object({ action: z.string() }),
+ })
+ .safeParse(value);
+ if (!parsed.success)
+ throw new Error(
+ `Expected a typed memory constraint for ${path}; got ${JSON.stringify(value)}`,
+ { cause: parsed.error },
+ );
+ const failure = parsed.data;
+ const limits = failure.details.reported_limits;
+ const graphAdmission = z
+ .object({
+ parent_available_result_budget_bytes: z.number(),
+ module_retention_estimate_bytes: z.number(),
+ graph_retention_estimate_bytes: z.number(),
+ })
+ .safeParse(limits);
+ if (graphAdmission.success) {
+ expect(
+ graphAdmission.data.module_retention_estimate_bytes +
+ graphAdmission.data.graph_retention_estimate_bytes,
+ ).toBeGreaterThan(graphAdmission.data.parent_available_result_budget_bytes);
+ expect(failure.message).toContain(
+ `Semantic graph for ${path} exceeds the parent's remaining result budget`,
+ );
+ expect(failure.remediation.action).toContain("parent result budget");
+ expect(failure.remediation.action).toContain(
+ "retained static and module facts",
+ );
+ return;
+ }
+};
+
cliTest.skipIf(process.versions.bun !== undefined).for([
{ laterSources: 1, heapMb: 640, methodsCount: 400, retainGraph: true },
{ laterSources: 10, heapMb: 640, methodsCount: 400, retainGraph: true },
- // Even an otherwise empty parent cannot admit this graph after reserving
- // transient decoding and the next checkpoint, independent of GC timing.
+ // Exercise retained evidence and later checkpoints under real heap pressure.
+ // The controlled worker test proves graph-only admission independently of GC.
{ laterSources: 1, heapMb: 448, methodsCount: 600, retainGraph: false },
])(
"preserves evidence with $laterSources later checkpoints and a $heapMb MiB parent heap",
@@ -50,11 +93,18 @@ cliTest.skipIf(process.versions.bun !== undefined).for([
);
expect(result.statistics.parsed_javascript_files).toBe(laterSources + 1);
expect(result.statistics.parse_failures).toBe(0);
- const failures = result.graph.nodes.flatMap(({ observations }) =>
- observations.flatMap(({ properties }) =>
+ const failures = result.graph.nodes.flatMap((node) =>
+ node.observations.flatMap(({ properties }) =>
properties.analysis_failure === undefined
? []
- : [properties.analysis_failure],
+ : [
+ {
+ kind: node.kind,
+ identity: node.identity,
+ path: properties.path,
+ failure: properties.analysis_failure,
+ },
+ ],
),
);
const methods = result.semantic_graph.nodes.filter(
@@ -103,28 +153,18 @@ cliTest.skipIf(process.versions.bun !== undefined).for([
if (retainGraph) expect(failures).toEqual([]);
expect(await readFile(join(root, name), "utf8")).toBe(text);
if (!retainGraph && name === "a-large.mjs") {
- const failure = z
- .object({
- code: z.literal("resource_constraint"),
- remediation: z.object({ action: z.string() }),
- details: z.object({
- reported_limits: z.object({
- parent_available_result_budget_bytes: z.number(),
- module_retention_estimate_bytes: z.number(),
- graph_retention_estimate_bytes: z.number(),
- }),
- }),
- })
- .parse(failures[0]);
- const limits = failure.details.reported_limits;
- expect(
- limits.module_retention_estimate_bytes +
- limits.graph_retention_estimate_bytes,
- ).toBeGreaterThan(limits.parent_available_result_budget_bytes);
- expect(failure.remediation.action).toContain("parent result budget");
- expect(failure.remediation.action).toContain(
- "retained static and module facts",
+ const failureRecord = failures.find(
+ ({ kind, identity, path }) =>
+ kind === "unknown" &&
+ path === name &&
+ identity.strategy === "artifact-local-key" &&
+ identity.artifact_sha256 === digest &&
+ identity.namespace === "static-parse-scope" &&
+ identity.key === `analyze-javascript-source:${name}`,
);
+ if (failureRecord === undefined)
+ throw new Error(`Missing analysis failure for ${name}`);
+ assertRetainedMemoryFailure(failureRecord.failure, name);
}
}
expect(response.stderr).not.toMatch(/FATAL ERROR:.*heap/iu);
diff --git a/tests/boundary/javascript/javascriptParentResultAdmission.test.ts b/tests/boundary/javascript/javascriptParentResultAdmission.test.ts
new file mode 100644
index 000000000..d1e1f7a01
--- /dev/null
+++ b/tests/boundary/javascript/javascriptParentResultAdmission.test.ts
@@ -0,0 +1,100 @@
+import { createHash } from "node:crypto";
+import { afterAll, expect, it, vi } from "vitest";
+
+// Give the parent a stable 64 MiB result envelope after its transfer reserve.
+// The child analyzer remains a real separately owned Node process with its
+// normal heap and real transfer files/descriptors.
+vi.mock("node:v8", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:v8")>();
+ return {
+ ...actual,
+ getHeapStatistics: () => ({
+ ...actual.getHeapStatistics(),
+ heap_size_limit: process.memoryUsage().heapUsed + 320 * 1024 * 1024,
+ }),
+ };
+});
+
+import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
+import { AnalysisResourceConstraintError } from "../../../src/domain/analysisErrorCore.js";
+import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
+
+afterAll(() => {
+ vi.doUnmock("node:v8");
+ vi.resetModules();
+});
+
+it("retains module facts and declines only the graph when its real transfer exceeds parent admission", async () => {
+ const methodsCount = 600;
+ const text = Array.from(
+ { length: methodsCount },
+ (_, index) =>
+ `export function method_${String(index)}(input) { const value = input + ${String(index)}; const pair = { value }; return pair.value; }`,
+ ).join("\n");
+ const file: JavaScriptArtifactFile = {
+ path: "a-large.mjs",
+ sha256: createHash("sha256").update(text).digest("hex"),
+ container_sha256: "1".repeat(64),
+ bytes: Buffer.byteLength(text),
+ inventory_artifact_id: "parent-admission-fixture",
+ kind: "javascript",
+ unpacked: false,
+ text: { included: true, value: text },
+ };
+ const worker = new JavaScriptAnalysisWorker({
+ heapMb: 1024,
+ timeoutMs: 30_000,
+ });
+ try {
+ const result = await worker.analyze(file, {
+ nodes: 20_000,
+ unknowns: 20_000,
+ });
+ if (result.ok)
+ throw new Error(
+ "Expected the parent to decline the large semantic graph",
+ );
+ const { error, javascript, module, projection } = result.error;
+ expect(javascript?.parse_status).toBe("complete");
+ expect(module?.callables).toHaveLength(methodsCount);
+ expect(projection).toBeNull();
+ expect(error).toMatchObject({
+ _tag: "AnalysisResourceConstraintError",
+ resource: "memory",
+ reason:
+ "Semantic graph for a-large.mjs exceeds the parent's remaining result budget; static and module facts were retained",
+ });
+ if (!(error instanceof AnalysisResourceConstraintError))
+ throw new Error("Expected a typed resource constraint");
+ expect(error.reportedLimits).toMatchObject(
+ process.versions.bun === undefined
+ ? { worker_old_space_mb: 1024 }
+ : { worker_heap_limit_bytes: null },
+ );
+ const limits = error.reportedLimits;
+ if (limits === null)
+ throw new Error("Parent admission omitted its measured limits");
+ expect(limits.parent_result_budget_bytes).toBeLessThanOrEqual(
+ 64 * 1024 * 1024,
+ );
+ expect(limits.parent_result_budget_bytes).toBeGreaterThan(0);
+ const moduleEstimate = limits.module_retention_estimate_bytes;
+ const graphEstimate = limits.graph_retention_estimate_bytes;
+ const available = limits.parent_available_result_budget_bytes;
+ expect(typeof moduleEstimate).toBe("number");
+ expect(typeof graphEstimate).toBe("number");
+ expect(typeof available).toBe("number");
+ if (
+ typeof moduleEstimate !== "number" ||
+ typeof graphEstimate !== "number" ||
+ typeof available !== "number"
+ )
+ throw new Error(
+ "Parent admission omitted its measured transfer estimates",
+ );
+ expect(moduleEstimate).toBeLessThanOrEqual(available);
+ expect(moduleEstimate + graphEstimate).toBeGreaterThan(available);
+ } finally {
+ await worker.close();
+ }
+});