mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 14:01:00 +00:00
perf(javascript): reuse preload-discovery static checkpoints in the normal pass
When any .js source belongs to a module package, preload discovery statically analyzes every source and the normal pass analyzes each one again. The worker now keeps the complete static checkpoint discovery computed, keyed by container, path, text digest, package type, precision and member-mutation allowance, and the normal pass of the same source writes that checkpoint instead of recomputing it. Static analysis is deterministic for those inputs, so the parent reads, validates and charges byte-identical facts. A discovered preload whose package type changes, a source discovery could not checkpoint, and a replaced worker all recompute. Retained checkpoints are consumed once and bounded to one eighth of the worker's V8 heap limit. Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
This commit is contained in:
1 parent
2a581ed953
commit
5b280e1f9f
3 files changed
+419
-116
No files matched your search
@@ -50,6 +50,17 @@ export interface JavaScriptSourceWorkerAnalyzer {
|
||||
phase: "parse" | "static" | "semantic" | "projection",
|
||||
) => Promise<void>;
|
||||
readonly checkpoint: (facts: JavaScriptStaticAnalysis) => Promise<number>;
|
||||
/**
|
||||
* 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<number>;
|
||||
},
|
||||
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<string, RetainedStaticCheckpoint>();
|
||||
let retainedStaticBytes = 0;
|
||||
|
||||
export const javaScriptStaticReuseKey = (
|
||||
request: ReturnType<typeof javaScriptWorkerRequestSchema.parse>,
|
||||
): 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<void> => {
|
||||
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<number> => {
|
||||
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,
|
||||
|
||||
@@ -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()]);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user