fix(javascript): isolate source analysis and retain bounded partial evidence (#1651)
* refactor(javascript): validate transferable file projections * test(javascript): consume decoded module and static facts * fix(javascript): isolate source analysis and retain bounded partial evidence * test(javascript): verify cleanup retention and repeated source paths
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
|
||||
|
||||
const source = (path: string, value: string): JavaScriptArtifactFile => ({
|
||||
path,
|
||||
sha256: createHash("sha256").update(value).digest("hex"),
|
||||
container_sha256: "1".repeat(64),
|
||||
bytes: Buffer.byteLength(value),
|
||||
inventory_artifact_id: "fixture-source",
|
||||
kind: "javascript",
|
||||
unpacked: false,
|
||||
text: { included: true, value },
|
||||
});
|
||||
|
||||
it("reuses one real owned analyzer while retaining distinct source identities and exported returns", async () => {
|
||||
const launches: number[] = [];
|
||||
const worker = new JavaScriptAnalysisWorker(
|
||||
{ heapMb: 128, timeoutMs: 30_000 },
|
||||
async (request) => {
|
||||
const spawned = await spawnOwnedProviderProcess(request);
|
||||
const pid = spawned.process.pid;
|
||||
if (pid === undefined)
|
||||
throw new Error("Owned analyzer has no observed PID");
|
||||
launches.push(pid);
|
||||
return spawned;
|
||||
},
|
||||
);
|
||||
try {
|
||||
const first = source(
|
||||
"first.mjs",
|
||||
"export function create() { return { observed: 7 }; }",
|
||||
);
|
||||
const second = source(
|
||||
"second.mjs",
|
||||
"export function next() { return { observed: 8 }; }",
|
||||
);
|
||||
for (const [index, file] of [first, second].entries()) {
|
||||
const result = await worker.analyze(file, 100);
|
||||
if (!result.ok) throw result.error.error;
|
||||
expect(result.value.javascript.parse_status).toBe("complete");
|
||||
expect(
|
||||
result.value.module?.callables[0]?.returnSites[0]?.value,
|
||||
).toMatchObject({
|
||||
status: "object",
|
||||
properties: [
|
||||
{ name: "observed", value: { status: "literal", value: index + 7 } },
|
||||
],
|
||||
});
|
||||
expect(
|
||||
result.value.projection?.nodes.every(
|
||||
({ identity }) => identity.artifact_sha256 === file.sha256,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.value.projection?.nodes.some(
|
||||
({ identity }) => identity.module_path === file.path,
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
expect(launches).toHaveLength(1);
|
||||
} finally {
|
||||
await worker.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports an actual startup deadline and closes its owned resources before subsequent analysis", async () => {
|
||||
const file = source("app.mjs", "export const observed = 7;");
|
||||
const expired = new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 1 });
|
||||
try {
|
||||
const result = await expired.analyze(file, 100);
|
||||
if (result.ok)
|
||||
throw new Error(
|
||||
"A one-millisecond fresh process deadline unexpectedly completed",
|
||||
);
|
||||
expect(result.error.error).toMatchObject({
|
||||
_tag: "AnalysisTimeoutError",
|
||||
timeoutMs: 1,
|
||||
});
|
||||
} finally {
|
||||
await expired.close();
|
||||
}
|
||||
const next = new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 30_000 });
|
||||
try {
|
||||
const result = await next.analyze(file, 100);
|
||||
if (!result.ok) throw result.error.error;
|
||||
expect(result.value.javascript.parse_status).toBe("complete");
|
||||
} finally {
|
||||
await next.close();
|
||||
}
|
||||
});
|
||||
@@ -12,9 +12,10 @@ import {
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("stops a cancelled SDK request on the server, retains prior Evidence, and accepts subsequent work", async () => {
|
||||
it("retains completed source facts and prior Evidence after SDK cancellation, then accepts subsequent work", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-js-cancellation-");
|
||||
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
|
||||
await writeFile(join(root, "second.js"), "export const pending = 2;\n");
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error(
|
||||
"Static JavaScript analysis must not start a binary provider",
|
||||
@@ -74,7 +75,12 @@ it("stops a cancelled SDK request on the server, retains prior Evidence, and acc
|
||||
},
|
||||
{
|
||||
signal: controller.signal,
|
||||
onprogress() {
|
||||
onprogress(update) {
|
||||
if (
|
||||
!update.message?.startsWith("parse_javascript_source:") ||
|
||||
!update.message.includes("second.js")
|
||||
)
|
||||
return;
|
||||
requested = true;
|
||||
controller.abort(new Error("SDK cancellation verification"));
|
||||
},
|
||||
@@ -89,15 +95,38 @@ it("stops a cancelled SDK request on the server, retains prior Evidence, and acc
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const records = z
|
||||
.object({
|
||||
result: z.object({
|
||||
records: z.array(z.object({ evidence_id: z.string() })),
|
||||
}),
|
||||
})
|
||||
.parse(bundle.structuredContent).result.records;
|
||||
expect(records).toContainEqual({ evidence_id: prior.evidence_id });
|
||||
const partial = records.find(
|
||||
({ evidence_id }) => evidence_id !== prior.evidence_id,
|
||||
);
|
||||
if (partial === undefined)
|
||||
throw new Error("Cancelled analysis discarded its completed source facts");
|
||||
expect(
|
||||
z
|
||||
.object({
|
||||
result: z.object({
|
||||
records: z.array(z.object({ evidence_id: z.string() })),
|
||||
statistics: z.object({
|
||||
parsed_javascript_files: z.number(),
|
||||
parse_failures: z.number(),
|
||||
}),
|
||||
})
|
||||
.parse(bundle.structuredContent).result.records,
|
||||
).toEqual([{ evidence_id: prior.evidence_id }]);
|
||||
.parse(session.evidenceById(partial.evidence_id)?.normalized_result)
|
||||
.statistics,
|
||||
).toEqual({ parsed_javascript_files: 1, parse_failures: 0 });
|
||||
const view = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "retained-evidence", evidence_id: partial.evidence_id },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
expect(view.isError, JSON.stringify(view)).not.toBe(true);
|
||||
const next = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: {
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("retains every static finding through public module views when application expansion exceeds memory, then accepts more work", async () => {
|
||||
const root = await createTestTempDirectory("rea-js-resource-boundary-");
|
||||
const nextRoot = await createTestTempDirectory("rea-js-resource-recovery-");
|
||||
await writeFile(join(nextRoot, "main.js"), "export const recovered = 9;\n");
|
||||
const source = Array.from(
|
||||
{ length: 4000 },
|
||||
(_, index) =>
|
||||
`import { observed as binding${String(index)} } from "./target.js";`,
|
||||
).join("\n");
|
||||
const path = join(root, "main.js");
|
||||
await writeFile(path, source);
|
||||
await writeFile(join(root, "target.js"), "export const observed = 7;\n");
|
||||
const digest = createHash("sha256").update(source).digest("hex");
|
||||
const { client, transport, diagnostics } = createResourceClient();
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const response = await client.callTool(
|
||||
{
|
||||
name: "analyze_javascript_application",
|
||||
arguments: {
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
max_heap_mb: 128,
|
||||
detail: "summary",
|
||||
},
|
||||
},
|
||||
{ timeout: 60000 },
|
||||
);
|
||||
expect(response.isError).not.toBe(true);
|
||||
const summary = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
parent_evidence_id: z.string(),
|
||||
summary: z.object({
|
||||
coverage: z.object({
|
||||
application: z.object({ status: z.string() }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(response.structuredContent).normalized_result;
|
||||
expect(summary.summary.coverage.application.status).toBe("partial");
|
||||
const retained = {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: summary.parent_evidence_id,
|
||||
};
|
||||
const pageResponse = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: retained,
|
||||
view: { kind: "page", collection: "modules", offset: 0, limit: 100 },
|
||||
},
|
||||
});
|
||||
expect(pageResponse.isError).not.toBe(true);
|
||||
const page = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
node_id: z.string(),
|
||||
kind: z.string(),
|
||||
path: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.parse(pageResponse.structuredContent).normalized_result;
|
||||
const module = page.items.find(
|
||||
(item) => item.kind === "javascript-asset" && item.path === "main.js",
|
||||
);
|
||||
if (module === undefined)
|
||||
throw new Error("The analyzed file disappeared from public module views");
|
||||
const itemResponse = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: retained,
|
||||
view: {
|
||||
kind: "item",
|
||||
collection: "modules",
|
||||
selector: { node_id: module.node_id },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(itemResponse.isError).not.toBe(true);
|
||||
const item = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
item: z.object({
|
||||
identity: z.object({ sha256: z.string() }),
|
||||
observations: z.array(
|
||||
z.object({
|
||||
properties: z.object({
|
||||
static_analysis: z
|
||||
.object({
|
||||
parse_status: z.string(),
|
||||
references: z.array(
|
||||
z.object({
|
||||
specifier: z.string(),
|
||||
location: z.object({
|
||||
start: z.object({ line: z.number() }),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(itemResponse.structuredContent).normalized_result.item;
|
||||
expect(item.identity.sha256).toBe(digest);
|
||||
const facts = item.observations.find(
|
||||
(observation) => observation.properties.static_analysis !== undefined,
|
||||
)?.properties.static_analysis;
|
||||
if (facts === undefined)
|
||||
throw new Error("Completed static observations were discarded");
|
||||
expect(facts.parse_status).toBe("complete");
|
||||
expect(
|
||||
facts.references.map((reference) => [
|
||||
reference.specifier,
|
||||
reference.location.start.line,
|
||||
]),
|
||||
).toEqual(
|
||||
Array.from({ length: 4000 }, (_, index) => ["./target.js", index + 1]),
|
||||
);
|
||||
await client.ping();
|
||||
const next = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: {
|
||||
input_path: nextRoot,
|
||||
format: "directory",
|
||||
max_heap_mb: 128,
|
||||
detail: "summary",
|
||||
},
|
||||
});
|
||||
expect(next.isError).not.toBe(true);
|
||||
await client.ping();
|
||||
expect(
|
||||
createHash("sha256")
|
||||
.update(await readFile(path))
|
||||
.digest("hex"),
|
||||
).toBe(digest);
|
||||
expect(diagnostics()).not.toMatch(/FATAL ERROR:.*heap/iu);
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
}, 90000);
|
||||
|
||||
it("returns a directly usable partial analysis reference for an oversized timeout observation", async () => {
|
||||
const root = await createTestTempDirectory("rea-js-large-timeout-");
|
||||
for (let offset = 0; offset < 1500; offset += 50)
|
||||
await Promise.all(
|
||||
Array.from({ length: 50 }, (_, index) =>
|
||||
writeFile(
|
||||
join(root, `file-${String(offset + index)}.js`),
|
||||
"export const observed = 7;\n",
|
||||
),
|
||||
),
|
||||
);
|
||||
const nextRoot = await createTestTempDirectory("rea-js-timeout-recovery-");
|
||||
await writeFile(join(nextRoot, "main.js"), "export const recovered = 9;\n");
|
||||
const { client, transport, diagnostics } = createResourceClient();
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const response = await client.callTool(
|
||||
{
|
||||
name: "analyze_javascript_application",
|
||||
arguments: {
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
max_heap_mb: 128,
|
||||
analysis_timeout_ms: 1,
|
||||
},
|
||||
},
|
||||
{ timeout: 60000 },
|
||||
);
|
||||
expect(response.isError).toBe(true);
|
||||
const text = response.content.find((item) => item.type === "text");
|
||||
if (text?.type !== "text")
|
||||
throw new Error("Missing actionable timeout response");
|
||||
const projected = z
|
||||
.object({
|
||||
error: z.object({
|
||||
code: z.string(),
|
||||
details: z.object({
|
||||
partial_observation: z.object({
|
||||
kind: z.literal("retained-evidence"),
|
||||
evidence_id: z.string(),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(JSON.parse(text.text));
|
||||
expect(projected.error.code).toBe("provider_timeout");
|
||||
const summaryResponse = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: projected.error.details.partial_observation,
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
expect(summaryResponse.isError).not.toBe(true);
|
||||
const summary = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
summary: z.object({
|
||||
statistics: z.object({
|
||||
relevant_files: z.number(),
|
||||
parsed_javascript_files: z.number(),
|
||||
parse_failures: z.number(),
|
||||
}),
|
||||
coverage: z.object({ semantic_unknowns: z.number() }),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(summaryResponse.structuredContent).normalized_result.summary;
|
||||
expect(summary.statistics).toEqual({
|
||||
relevant_files: 1500,
|
||||
parsed_javascript_files: 0,
|
||||
parse_failures: 0,
|
||||
});
|
||||
expect(summary.coverage.semantic_unknowns).toBeGreaterThan(1500);
|
||||
await verifyRepeatedSourcePaths(
|
||||
client,
|
||||
projected.error.details.partial_observation,
|
||||
);
|
||||
await client.ping();
|
||||
const next = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: {
|
||||
input_path: nextRoot,
|
||||
format: "directory",
|
||||
max_heap_mb: 128,
|
||||
detail: "summary",
|
||||
},
|
||||
});
|
||||
expect(next.isError).not.toBe(true);
|
||||
await client.ping();
|
||||
expect(diagnostics()).not.toMatch(/FATAL ERROR:.*heap/iu);
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
}, 90000);
|
||||
|
||||
const createResourceClient = () => {
|
||||
const client = new Client({ name: "javascript-resources", version: "1" });
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
NODE_OPTIONS: "--max-old-space-size=512 --max-semi-space-size=8",
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
let diagnostics = "";
|
||||
transport.stderr?.on("data", (chunk: Buffer) => {
|
||||
if (diagnostics.length < 262144) diagnostics += chunk.toString();
|
||||
});
|
||||
return { client, transport, diagnostics: () => diagnostics };
|
||||
};
|
||||
|
||||
const verifyRepeatedSourcePaths = async (
|
||||
client: Client,
|
||||
source: { readonly kind: "retained-evidence"; readonly evidence_id: string },
|
||||
): Promise<void> => {
|
||||
const page = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source,
|
||||
view: { kind: "page", collection: "modules", offset: 0, limit: 4 },
|
||||
},
|
||||
});
|
||||
expect(page.isError).not.toBe(true);
|
||||
const modules = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
items: z.array(z.object({ kind: z.string(), node_id: z.string() })),
|
||||
}),
|
||||
})
|
||||
.parse(page.structuredContent);
|
||||
const asset = modules.normalized_result.items.find(
|
||||
({ kind }) => kind === "javascript-asset",
|
||||
);
|
||||
if (asset === undefined)
|
||||
throw new Error(
|
||||
"Identical source files disappeared from the retained graph",
|
||||
);
|
||||
const item = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source,
|
||||
view: {
|
||||
kind: "item",
|
||||
collection: "modules",
|
||||
selector: { node_id: asset.node_id },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(item.isError).not.toBe(true);
|
||||
const observations = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
item: z.object({
|
||||
observations: z.array(z.object({ label: z.string() })),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(item.structuredContent).normalized_result.item.observations;
|
||||
expect(observations.map(({ label }) => label).sort()).toEqual(
|
||||
Array.from(
|
||||
{ length: 1500 },
|
||||
(_, index) => `file-${String(index)}.js`,
|
||||
).sort(),
|
||||
);
|
||||
};
|
||||
+134
-3
@@ -3,7 +3,7 @@ import {
|
||||
primitiveByteExpansionSource,
|
||||
} from "../../fixtures/javascriptPrimitiveExpansion.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
@@ -23,7 +23,20 @@ import { buildJavaScriptArtifactGraph } from "../../../src/application/javascrip
|
||||
import {
|
||||
buildJavaScriptSemanticGraph,
|
||||
createJavaScriptSemanticGraphProjection,
|
||||
projectJavaScriptSemanticFileSteps,
|
||||
} from "../../../src/application/javascript/JavaScriptSemanticGraphBuilder.js";
|
||||
import {
|
||||
projectJavaScriptModuleSemantics,
|
||||
type JavaScriptModuleSemanticIr,
|
||||
} from "../../../src/domain/javascript/javascriptModuleSemanticIr.js";
|
||||
import type { JavaScriptStaticAnalysis } from "../../../src/domain/javascript/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
|
||||
import { completeJavaScriptAnalysisSteps } from "../../../src/application/javascript/JavaScriptAnalysisControl.js";
|
||||
import {
|
||||
writeJavaScriptAnalysisTransfer,
|
||||
readJavaScriptAnalysisTransfer,
|
||||
} from "../../../src/javascript/analysis/JavaScriptAnalysisTransfer.js";
|
||||
import { javaScriptWorkerStaticAnalysisSchema } from "../../../src/javascript/analysis/JavaScriptAnalysisWorkerSchemas.js";
|
||||
import { createJavaScriptArtifactReader } from "../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
|
||||
import {
|
||||
scanCanonicalArtifactInventory,
|
||||
@@ -31,7 +44,10 @@ import {
|
||||
} from "../../fixtures/artifactInventory.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createJavaScriptSemanticGraph } from "../../../src/domain/javascript/javascriptSemanticGraph.js";
|
||||
import {
|
||||
createJavaScriptSemanticGraph,
|
||||
isValidatedImmutableJavaScriptSemanticGraph,
|
||||
} from "../../../src/domain/javascript/javascriptSemanticGraph.js";
|
||||
import { parseJavaScriptSemanticGraph } from "../../../src/domain/javascript/javascriptSemanticGraphSerialization.js";
|
||||
import { writeJavaScriptArtifactFixture } from "../../fixtures/javascriptArtifactApplication.js";
|
||||
|
||||
@@ -48,7 +64,10 @@ it("reports file progress and honors cancellation before the next source", async
|
||||
}
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: "cancelled" });
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisCancelledError",
|
||||
partialObservation: { operation: "analyze_javascript_application" },
|
||||
});
|
||||
expect(progress).toHaveLength(2);
|
||||
expect(progress[0]).not.toBe(progress[1]);
|
||||
});
|
||||
@@ -61,6 +80,7 @@ it("preserves graph commitments and export shapes when consuming file-local IR",
|
||||
import { readFile } from "node:fs";
|
||||
export { readFile as read };
|
||||
export function create(value) { return { value, nested: { enabled: true } }; }
|
||||
export function configured(condition) { return { values: [1, null, undefined], choice: condition ? 1 : 2, ...external }; }
|
||||
function unexported() { return "private"; }
|
||||
`,
|
||||
);
|
||||
@@ -96,6 +116,7 @@ it("preserves graph commitments and export shapes when consuming file-local IR",
|
||||
);
|
||||
expect(exported?.semantic?.ir.callables.map(({ name }) => name)).toEqual([
|
||||
"create",
|
||||
"configured",
|
||||
]);
|
||||
expect(
|
||||
full.files
|
||||
@@ -103,11 +124,121 @@ it("preserves graph commitments and export shapes when consuming file-local IR",
|
||||
?.semantic?.ir.callables.map(({ name }) => name),
|
||||
).toContain("unexported");
|
||||
expect(parseJavaScriptSemanticGraph(semantic)).toEqual(semantic);
|
||||
const transferred = createJavaScriptSemanticGraphProjection();
|
||||
const wireRoot = await createTestTempDirectory("rea-javascript-transfer-");
|
||||
const decodedModules = new Map<string, JavaScriptModuleSemanticIr>();
|
||||
const decodedStatic = new Map<string, JavaScriptStaticAnalysis>();
|
||||
let rejectedInvalidTransfer = false;
|
||||
for (const [index, analyzed] of full.files.entries()) {
|
||||
if (analyzed.javascript !== null) {
|
||||
const raw: unknown = JSON.parse(JSON.stringify(analyzed.javascript));
|
||||
const decodedFacts = javaScriptWorkerStaticAnalysisSchema.parse(raw);
|
||||
expect(decodedFacts).toEqual(analyzed.javascript);
|
||||
decodedStatic.set(analyzed.file.path, decodedFacts);
|
||||
}
|
||||
if (analyzed.semantic === null) continue;
|
||||
const fragment = await completeJavaScriptAnalysisSteps(
|
||||
projectJavaScriptSemanticFileSteps(
|
||||
analyzed.file,
|
||||
analyzed.semantic.ir,
|
||||
transferred.remainingFileNodeBudget(),
|
||||
),
|
||||
);
|
||||
const module = projectJavaScriptModuleSemantics(analyzed.semantic.ir);
|
||||
const wirePath = join(wireRoot, `${String(index)}.jsonl`);
|
||||
const descriptor = await writeJavaScriptAnalysisTransfer(
|
||||
wirePath,
|
||||
module,
|
||||
fragment,
|
||||
);
|
||||
const decoded = await readJavaScriptAnalysisTransfer(
|
||||
wirePath,
|
||||
descriptor,
|
||||
analyzed.file,
|
||||
);
|
||||
expect(decoded.module).toEqual(module);
|
||||
decodedModules.set(analyzed.file.path, decoded.module);
|
||||
transferred.adoptFileProjection(decoded.projection);
|
||||
if (!rejectedInvalidTransfer) {
|
||||
await rejectInvalidTransfer(
|
||||
wirePath,
|
||||
descriptor,
|
||||
analyzed.file,
|
||||
wireRoot,
|
||||
);
|
||||
rejectedInvalidTransfer = true;
|
||||
}
|
||||
}
|
||||
const decodedGraph = buildJavaScriptArtifactGraph(snapshot, files, {
|
||||
...compact,
|
||||
files: compact.files.map((analyzed) => {
|
||||
const module = decodedModules.get(analyzed.file.path);
|
||||
return {
|
||||
...analyzed,
|
||||
javascript:
|
||||
decodedStatic.get(analyzed.file.path) ?? analyzed.javascript,
|
||||
semantic: module === undefined ? analyzed.semantic : { ir: module },
|
||||
};
|
||||
}),
|
||||
});
|
||||
expect(decodedGraph).toEqual(graph);
|
||||
const resealed = await completeJavaScriptAnalysisSteps(
|
||||
transferred.finishImmutableSteps(
|
||||
snapshot.manifest.root_sha256,
|
||||
decodedGraph,
|
||||
),
|
||||
);
|
||||
expect(resealed).toEqual(semantic);
|
||||
expect(isValidatedImmutableJavaScriptSemanticGraph(resealed)).toBe(true);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
const rejectInvalidTransfer = async (
|
||||
wirePath: string,
|
||||
descriptor: Awaited<ReturnType<typeof writeJavaScriptAnalysisTransfer>>,
|
||||
file: JavaScriptArtifactFile,
|
||||
wireRoot: string,
|
||||
): Promise<void> => {
|
||||
await expect(
|
||||
readJavaScriptAnalysisTransfer(wirePath, descriptor, {
|
||||
...file,
|
||||
sha256: "0".repeat(64),
|
||||
}),
|
||||
).rejects.toThrow("different artifact source");
|
||||
await expect(
|
||||
readJavaScriptAnalysisTransfer(
|
||||
wirePath,
|
||||
{ ...descriptor, sha256: "0".repeat(64) },
|
||||
file,
|
||||
),
|
||||
).rejects.toThrow("digest does not match");
|
||||
const wire = await readFile(wirePath, "utf8");
|
||||
const duplicate = wire
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith('{"kind":"node"'));
|
||||
if (duplicate === undefined)
|
||||
throw new Error("Fixture emitted no semantic node record");
|
||||
const invalid = `${wire}${duplicate}\n`;
|
||||
const invalidPath = join(wireRoot, "duplicate.jsonl");
|
||||
await writeFile(invalidPath, invalid);
|
||||
await expect(
|
||||
readJavaScriptAnalysisTransfer(
|
||||
invalidPath,
|
||||
{
|
||||
...descriptor,
|
||||
bytes: Buffer.byteLength(invalid),
|
||||
records: descriptor.records + 1,
|
||||
graph_bytes: descriptor.graph_bytes + Buffer.byteLength(duplicate) + 1,
|
||||
graph_records: descriptor.graph_records + 1,
|
||||
sha256: createHash("sha256").update(invalid).digest("hex"),
|
||||
},
|
||||
file,
|
||||
),
|
||||
).rejects.toThrow("Duplicate JavaScript transfer node identity");
|
||||
};
|
||||
|
||||
it("reports semantic value resource limits in application graph coverage", async () => {
|
||||
const root = await createTestTempDirectory("rea-javascript-semantic-limit-");
|
||||
await writeFile(join(root, "app.js"), primitiveCandidateExpansionSource());
|
||||
|
||||
Reference in New Issue
Block a user