mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 15:33:56 +08: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:
committed by
Ysopwnable
co-authored by
gensokyo-dev
parent
2a581ed953
commit
5b280e1f9f
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user