diff --git a/src/composition/javascriptAnalysisWorkerProcess.ts b/src/composition/javascriptAnalysisWorkerProcess.ts index 40ed28ffb22..b62dd647143 100644 --- a/src/composition/javascriptAnalysisWorkerProcess.ts +++ b/src/composition/javascriptAnalysisWorkerProcess.ts @@ -40,49 +40,16 @@ const analyze: JavaScriptSourceWorkerAnalyzer = async ( return null; } await callbacks.phase("static"); - let facts: JavaScriptStaticAnalysis; - try { - facts = await completeJavaScriptAnalysisSteps( - analyzeParsedJavaScriptStaticSourceSteps( - file.text.value, - parsed, - precision, - memberMutationAllowance, - ), - ); - } catch (cause: unknown) { - // The semantic phase indexes the same mutations under the same - // allowance, so it is not started; the syntax facts cross first. - if (purpose === "analysis" && isJavaScriptMemberMutationRefusal(cause)) - await callbacks.checkpoint( - memberMutationRefusedJavaScriptStaticAnalysis( - file.text.value, - parsed, - cause, - ), - ); - throw cause; - } - if (purpose === "preload-discovery") { - // Only declarations cross this preliminary pass. The normal pass owns - // full static/semantic facts and their result reservations. - const empty = failedJavaScriptStaticAnalysis(); - await callbacks.checkpoint({ - ...empty, - parse_status: facts.parse_status, - parse_error_count: facts.parse_error_count, - analysis_coverage: facts.analysis_coverage, - visited_ast_nodes: facts.visited_ast_nodes, - limitations: facts.limitations, - electron: { - ...empty.electron, - browser_windows: facts.electron.browser_windows, - }, - }); - return null; - } - const resultBudgetBytes = await callbacks.checkpoint(facts); - if (facts.parse_status === "failed") return null; + const static_ = await staticCheckpoint( + file.text.value, + parsed, + callbacks, + purpose, + precision, + memberMutationAllowance, + ); + if (static_ === null) return null; + const { resultBudgetBytes, callPaths } = static_; if (resultBudgetBytes === 0) throw new AnalysisResourceConstraintError( "analyze_javascript_application", @@ -120,16 +87,79 @@ const analyze: JavaScriptSourceWorkerAnalyzer = async ( ); await callbacks.phase("projection"); const projection = await completeJavaScriptAnalysisSteps( - projectJavaScriptSemanticFileSteps( - file, - ir, - capacity, - facts.electron.call_paths, - ), + projectJavaScriptSemanticFileSteps(file, ir, capacity, callPaths), ); return { module, projection }; }; +/** + * Checkpoint static facts, reusing the ones preload discovery retained for + * this exact request. Null ends the job: discovery returns only declarations, + * and a failed parse has no semantic phase. + */ +const staticCheckpoint = async ( + source: string, + parsed: NonNullable>, + callbacks: Parameters[2], + purpose: Parameters[4], + precision: Parameters[5], + memberMutationAllowance: Parameters[6], +): Promise<{ + readonly resultBudgetBytes: number; + readonly callPaths: JavaScriptStaticAnalysis["electron"]["call_paths"]; +} | null> => { + const reused = purpose === "analysis" ? callbacks.reusedStatic() : undefined; + if (reused !== undefined) { + const resultBudgetBytes = await callbacks.checkpointReused(reused); + return reused.parse_status === "failed" + ? null + : { resultBudgetBytes, callPaths: reused.call_paths }; + } + let facts: JavaScriptStaticAnalysis; + try { + facts = await completeJavaScriptAnalysisSteps( + analyzeParsedJavaScriptStaticSourceSteps( + source, + parsed, + precision, + memberMutationAllowance, + ), + ); + } catch (cause: unknown) { + // The semantic phase indexes the same mutations under the same + // allowance, so it is not started; the syntax facts cross first. + if (purpose === "analysis" && isJavaScriptMemberMutationRefusal(cause)) + await callbacks.checkpoint( + memberMutationRefusedJavaScriptStaticAnalysis(source, parsed, cause), + ); + throw cause; + } + if (purpose === "preload-discovery") { + // Only declarations cross this preliminary pass. The normal pass owns + // full static/semantic facts and their result reservations; the worker + // keeps the complete checkpoint so that pass need not recompute it. + callbacks.retainStatic(facts); + const empty = failedJavaScriptStaticAnalysis(); + await callbacks.checkpoint({ + ...empty, + parse_status: facts.parse_status, + parse_error_count: facts.parse_error_count, + analysis_coverage: facts.analysis_coverage, + visited_ast_nodes: facts.visited_ast_nodes, + limitations: facts.limitations, + electron: { + ...empty.electron, + browser_windows: facts.electron.browser_windows, + }, + }); + return null; + } + const resultBudgetBytes = await callbacks.checkpoint(facts); + return facts.parse_status === "failed" + ? null + : { resultBudgetBytes, callPaths: facts.electron.call_paths }; +}; + try { await serveJavaScriptAnalysisWorker(analyze); } catch (cause: unknown) { diff --git a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts index 9e9e4e6b70c..45ea0d21408 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts @@ -50,6 +50,17 @@ export interface JavaScriptSourceWorkerAnalyzer { phase: "parse" | "static" | "semantic" | "projection", ) => Promise; readonly checkpoint: (facts: JavaScriptStaticAnalysis) => Promise; + /** + * Preload discovery computed these complete facts; keep their checkpoint + * so the normal pass of the same source can skip static analysis. + */ + readonly retainStatic: (facts: JavaScriptStaticAnalysis) => void; + /** Static facts that preload discovery retained for this exact request. */ + readonly reusedStatic: () => ReusedJavaScriptStatic | undefined; + /** Checkpoint retained facts exactly as the static phase would have. */ + readonly checkpointReused: ( + reused: ReusedJavaScriptStatic, + ) => Promise; }, packageType: JavaScriptPackageType, purpose: "analysis" | "preload-discovery", @@ -61,6 +72,123 @@ export interface JavaScriptSourceWorkerAnalyzer { } | null>; } +/** The facts the normal pass reads after a reused static checkpoint. */ +export interface ReusedJavaScriptStatic { + readonly parse_status: JavaScriptStaticAnalysis["parse_status"]; + readonly call_paths: JavaScriptStaticAnalysis["electron"]["call_paths"]; +} + +export interface RetainedStaticCheckpoint extends ReusedJavaScriptStatic { + readonly text: string; + readonly retainedBytes: number; +} + +/** + * Static checkpoints from preload discovery, consumed by the normal pass of + * the same worker. Static analysis is deterministic for the request fields in + * the key, so a reused checkpoint is byte-identical to a recomputed one. The + * store keeps at most one eighth of the V8 heap limit and stays empty where + * the runtime does not report one; a miss recomputes. + */ +const retainedStatics = new Map(); +let retainedStaticBytes = 0; + +export const javaScriptStaticReuseKey = ( + request: ReturnType, +): string => + JSON.stringify([ + request.file.container_sha256, + request.file.path, + request.text_sha256, + request.package_type, + request.semantic_precision ?? null, + request.member_mutation_allowance, + ]); + +const staticReuseCapacityBytes = (): number => + javaScriptRuntime(process.versions).id === "node" + ? Math.floor(getHeapStatistics().heap_size_limit / 8) + : 0; + +export const retainJavaScriptStaticCheckpoint = ( + key: string, + facts: JavaScriptStaticAnalysis, +): void => { + let text: string; + let retainedBytes: number; + try { + text = encodeJavaScriptStaticCheckpoint(facts); + // UTF-16 strings and the retained call-path objects, conservatively. + retainedBytes = + 2 * text.length + + 2 * (JSON.stringify(facts.electron.call_paths) ?? "").length; + } catch { + // Reuse is only an optimization: the normal pass recomputes and reports + // the same refusal, so retention never fails preload discovery. + return; + } + const previous = retainedStatics.get(key); + if (previous !== undefined) { + retainedStatics.delete(key); + retainedStaticBytes -= previous.retainedBytes; + } + if (retainedStaticBytes + retainedBytes > staticReuseCapacityBytes()) return; + retainedStatics.set(key, { + text, + retainedBytes, + parse_status: facts.parse_status, + call_paths: facts.electron.call_paths, + }); + retainedStaticBytes += retainedBytes; +}; + +export const takeJavaScriptStaticCheckpoint = ( + key: string, +): RetainedStaticCheckpoint | undefined => { + const retained = retainedStatics.get(key); + if (retained === undefined) return undefined; + retainedStatics.delete(key); + retainedStaticBytes -= retained.retainedBytes; + return retained; +}; + +/** Validate, fit and bound static facts as the checkpoint the parent reads. */ +export const encodeJavaScriptStaticCheckpoint = ( + facts: JavaScriptStaticAnalysis, +): string => { + let value = javaScriptWorkerStaticAnalysisSchema.parse(facts); + if (value.routes !== undefined) { + const { routes, ...existing } = value; + // This is schema-checked, producer-owned JSON. Interface optional + // members can only make the size estimate conservative. + const available = + DEFAULTS.checkpointBytes - + jsonValueByteLength(existing as JsonValue, DEFAULTS.checkpointBytes) - + Buffer.byteLength(',"routes":'); + const admitted = fitJavaScriptRouteSourceFacts(routes, available); + value = + admitted === undefined ? existing : { ...existing, routes: admitted }; + } + const text = JSON.stringify(value); + const bytes = Buffer.byteLength(text); + if (bytes > DEFAULTS.checkpointBytes) + throw new AnalysisResourceConstraintError( + "analyze_javascript_application", + "transport", + `JavaScript static checkpoint exceeds its ${String(DEFAULTS.checkpointBytes)}-byte complete-fact ceiling. This release has no runtime override.`, + { + checkpoint_bytes: bytes, + checkpoint_limit_bytes: DEFAULTS.checkpointBytes, + }, + { + remediationAction: javaScriptCheckpointCeilingRemediation( + DEFAULTS.checkpointBytes, + ), + }, + ); + return text; +}; + const send = async (input: JavaScriptWorkerMessage): Promise => { const value = javaScriptWorkerMessageSchema.parse(input); const frame = `${JSON.stringify(value)}\n`; @@ -130,6 +258,41 @@ const analyzeJob = async ( throw new TypeError( "JavaScript worker source text digest does not match its request", ); + const reuseKey = javaScriptStaticReuseKey(request); + // Write one checkpoint and wait for the parent's semantic admission. + const writeStaticCheckpoint = async (text: string): Promise => { + const bytes = Buffer.byteLength(text); + await writeFile(join(root, `${request.id}.static.json`), text, { + flag: "wx", + mode: 0o600, + }); + await send({ + kind: "static", + id: request.id, + bytes, + sha256: sha256Hex(text), + }); + const next = await requests.next(); + if ( + !next.done && + !next.value.ok && + next.value.error._tag === "ControlLineMalformedUtf8" + ) + throw new TypeError( + "JavaScript worker admission frame is not valid UTF-8", + ); + if (next.done || !next.value.ok) + throw new TypeError( + "JavaScript worker admission frame is missing or oversized", + ); + const raw: unknown = JSON.parse(next.value.value); + const admission = javaScriptWorkerAdmissionSchema.parse(raw); + if (admission.id !== request.id) + throw new TypeError( + "JavaScript worker admission names a different source job", + ); + return admission.semantic_result_budget_bytes; + }; const result = await analyze( { ...request.file, @@ -138,74 +301,18 @@ const analyzeJob = async ( { nodes: request.node_budget, unknowns: request.unknown_budget }, { phase: async (phase) => send({ kind: "phase", id: request.id, phase }), - checkpoint: async (facts) => { - let value = javaScriptWorkerStaticAnalysisSchema.parse(facts); - if (value.routes !== undefined) { - const { routes, ...existing } = value; - // This is schema-checked, producer-owned JSON. Interface optional - // members can only make the size estimate conservative. - const available = - DEFAULTS.checkpointBytes - - jsonValueByteLength( - existing as JsonValue, - DEFAULTS.checkpointBytes, - ) - - Buffer.byteLength(',"routes":'); - const admitted = fitJavaScriptRouteSourceFacts(routes, available); - value = - admitted === undefined - ? existing - : { ...existing, routes: admitted }; - } - const text = JSON.stringify(value); - const bytes = Buffer.byteLength(text); - if (bytes > DEFAULTS.checkpointBytes) - throw new AnalysisResourceConstraintError( - "analyze_javascript_application", - "transport", - `JavaScript static checkpoint exceeds its ${String(DEFAULTS.checkpointBytes)}-byte complete-fact ceiling. This release has no runtime override.`, - { - checkpoint_bytes: bytes, - checkpoint_limit_bytes: DEFAULTS.checkpointBytes, - }, - { - remediationAction: javaScriptCheckpointCeilingRemediation( - DEFAULTS.checkpointBytes, - ), - }, - ); - await writeFile(join(root, `${request.id}.static.json`), text, { - flag: "wx", - mode: 0o600, - }); - await send({ - kind: "static", - id: request.id, - bytes, - sha256: sha256Hex(text), - }); - const next = await requests.next(); - if ( - !next.done && - !next.value.ok && - next.value.error._tag === "ControlLineMalformedUtf8" - ) - throw new TypeError( - "JavaScript worker admission frame is not valid UTF-8", - ); - if (next.done || !next.value.ok) - throw new TypeError( - "JavaScript worker admission frame is missing or oversized", - ); - const raw: unknown = JSON.parse(next.value.value); - const admission = javaScriptWorkerAdmissionSchema.parse(raw); - if (admission.id !== request.id) - throw new TypeError( - "JavaScript worker admission names a different source job", - ); - resultBudgetBytes = admission.semantic_result_budget_bytes; - return resultBudgetBytes; + checkpoint: async (facts) => + (resultBudgetBytes = await writeStaticCheckpoint( + encodeJavaScriptStaticCheckpoint(facts), + )), + retainStatic: (facts) => { + retainJavaScriptStaticCheckpoint(reuseKey, facts); }, + reusedStatic: () => takeJavaScriptStaticCheckpoint(reuseKey), + checkpointReused: async (reused) => + (resultBudgetBytes = await writeStaticCheckpoint( + (reused as RetainedStaticCheckpoint).text, + )), }, request.package_type, request.purpose, diff --git a/src/javascript/analysis/JavaScriptStaticCheckpointReuse.test.ts b/src/javascript/analysis/JavaScriptStaticCheckpointReuse.test.ts new file mode 100644 index 00000000000..ef1951088cc --- /dev/null +++ b/src/javascript/analysis/JavaScriptStaticCheckpointReuse.test.ts @@ -0,0 +1,166 @@ +import { spawn } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { once } from "node:events"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { createInterface } from "node:readline"; +import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; +import { analyzeJavaScriptStaticSource } from "../../../tests/fixtures/javascriptStaticAnalysis.js"; +import { + javaScriptWorkerAdmissionSchema, + javaScriptWorkerMessageSchema, + javaScriptWorkerRequestSchema, +} from "./JavaScriptAnalysisWorkerProtocol.js"; +import { + encodeJavaScriptStaticCheckpoint, + javaScriptStaticReuseKey, + retainJavaScriptStaticCheckpoint, + takeJavaScriptStaticCheckpoint, +} from "./JavaScriptAnalysisWorkerServer.js"; + +const declaring = `const { BrowserWindow } = require("electron"); +new BrowserWindow({ webPreferences: { preload: require("path").join(__dirname, "preload.js") } }); +module.exports = { ready: true };`; +const digest = (text: string) => + createHash("sha256").update(text).digest("hex"); +const request = ( + id: string, + source: string, + purpose: "analysis" | "preload-discovery", + overrides: { path?: string; package_type?: "module" | "commonjs" } = {}, +) => + javaScriptWorkerRequestSchema.parse({ + id, + unknown_budget: purpose === "analysis" ? 1000 : 0, + node_budget: purpose === "analysis" ? 1000 : 0, + text_sha256: digest(source), + file: { + path: overrides.path ?? "main.js", + sha256: digest(source), + container_sha256: "a".repeat(64), + bytes: Buffer.byteLength(source), + inventory_artifact_id: "static-reuse-source", + kind: "javascript", + unpacked: false, + }, + package_type: overrides.package_type ?? "commonjs", + purpose, + member_mutation_allowance: { alias_states: 524_288, source: "default" }, + }); + +it("retains a discovery checkpoint once for the exact request, including sources without call paths", () => { + // A plain module records no Electron call paths. + const plain = "module.exports = 1;"; + const facts = analyzeJavaScriptStaticSource(plain); + const key = javaScriptStaticReuseKey( + request(randomUUID(), plain, "analysis"), + ); + retainJavaScriptStaticCheckpoint(key, facts); + const retained = takeJavaScriptStaticCheckpoint(key); + expect(retained?.text).toBe(encodeJavaScriptStaticCheckpoint(facts)); + expect(retained?.parse_status).toBe(facts.parse_status); + expect(takeJavaScriptStaticCheckpoint(key)).toBeUndefined(); + + // Request ids differ between passes; every result-affecting field is keyed. + const base = request(randomUUID(), plain, "analysis"); + retainJavaScriptStaticCheckpoint(javaScriptStaticReuseKey(base), facts); + for (const other of [ + request(randomUUID(), plain, "analysis", { package_type: "module" }), + request(randomUUID(), plain, "analysis", { path: "other.js" }), + request(randomUUID(), `${plain}\n`, "analysis"), + ]) + expect( + takeJavaScriptStaticCheckpoint(javaScriptStaticReuseKey(other)), + ).toBeUndefined(); + expect( + takeJavaScriptStaticCheckpoint( + javaScriptStaticReuseKey(request(randomUUID(), plain, "analysis")), + )?.text, + ).toBe(encodeJavaScriptStaticCheckpoint(facts)); +}); + +/** Start the production worker entrypoint in its own private root. */ +const startWorker = async () => { + const root = await createTestTempDirectory("rea-js-static-reuse-"); + const entry = new URL( + "../../composition/javascriptAnalysisWorkerProcess.ts", + import.meta.url, + ).href; + const child = spawn( + process.execPath, + [ + "--import", + import.meta.resolve("tsx"), + "--input-type=module", + "-e", + `await import(${JSON.stringify(entry)});`, + ], + { cwd: root, stdio: ["pipe", "pipe", "pipe"] }, + ); + const closed = once(child, "close"); + let stderr = ""; + child.stderr.setEncoding("utf8").on("data", (chunk: string) => { + stderr += chunk; + }); + const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); + const messages = lines[Symbol.asyncIterator](); + const next = async () => { + const line = await messages.next(); + if (line.done) throw new Error(`Worker output ended: ${stderr}`); + return javaScriptWorkerMessageSchema.parse(JSON.parse(line.value)); + }; + expect(await next()).toMatchObject({ kind: "ready" }); + /** Run one job and return its static checkpoint text and terminal frame. */ + const job = async (purpose: "analysis" | "preload-discovery") => { + const id = randomUUID(); + await writeFile(join(root, `${id}.source`), declaring, { flag: "wx" }); + child.stdin.write(`${JSON.stringify(request(id, declaring, purpose))}\n`); + let checkpoint: string | undefined; + for (;;) { + const message = await next(); + if (message.kind === "static") { + checkpoint = await readFile(join(root, `${id}.static.json`), "utf8"); + const admission = javaScriptWorkerAdmissionSchema.parse({ + id, + semantic_result_budget_bytes: 1024 * 1024, + }); + child.stdin.write(`${JSON.stringify(admission)}\n`); + } + if (message.kind === "complete" || message.kind === "failure") + return { checkpoint, terminal: message }; + } + }; + return { + job, + close: async () => { + child.stdin.end(); + await closed; + lines.close(); + }, + }; +}; + +it("checkpoints the discovery-retained static facts byte-for-byte as a recomputation", async () => { + const reusing = await startWorker(); + const fresh = await startWorker(); + try { + const discovery = await reusing.job("preload-discovery"); + expect(discovery.terminal).toMatchObject({ kind: "complete" }); + // Discovery crosses only declarations. + expect( + JSON.parse(discovery.checkpoint!).electron.browser_windows, + ).toHaveLength(1); + const reused = await reusing.job("analysis"); + const recomputed = await fresh.job("analysis"); + expect(reused.terminal).toMatchObject({ kind: "complete" }); + expect(recomputed.terminal).toMatchObject({ kind: "complete" }); + expect(reused.checkpoint).toBe(recomputed.checkpoint); + // The retained checkpoint is consumed; a repeat recomputes the same bytes. + expect((await reusing.job("analysis")).checkpoint).toBe( + recomputed.checkpoint, + ); + } finally { + await Promise.all([reusing.close(), fresh.close()]); + } +});