perf(javascript): index feature, semantic, IPC, and source map lookups (#13319)

perf(javascript): eliminate double preload AST pass and index feature/semantic/IPC/sourcemap lookups
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 03:43:13 -05:00
1 parent 79887f7a3b
commit fde2c87b86
17 files changed
+1860 -535

No files matched your search

@@ -67,21 +67,12 @@ export const createElectronIpcContext = (
const owners = new Map(
records.map((record) => [record.key, applicationOwner(record.file)]),
);
const handlers = records.filter(isMainHandler);
const handlerIndex = indexMainHandlers(records);
const states: ElectronIpcPairingState[] = records
.filter(isPairableRendererTransmission)
.map((transmission) => {
const owner = owners.get(transmission.key);
const channel = transmission.finding.channel;
const matching =
channel === null
? []
: handlers.filter(
(handler) =>
(handler.finding.channel === channel ||
mayReceiveChannel(handler, channel)) &&
compatibleIpcModes(transmission.finding, handler.finding),
);
const matching = matchingMainHandlers(handlerIndex, transmission.finding);
const candidates = matching.filter(
(handler) => owners.get(handler.key) === owner,
);
@@ -127,6 +118,84 @@ export const createElectronIpcContext = (
return { records, owners, states, pairings };
};
interface MainHandlerIndex {
readonly exactByChannel: ReadonlyMap<string, readonly ElectronIpcRecord[]>;
readonly guardedByChannel: ReadonlyMap<string, readonly ElectronIpcRecord[]>;
readonly wildcardDynamic: readonly ElectronIpcRecord[];
}
const pushRecordBucket = (
map: Map<string, ElectronIpcRecord[]>,
key: string,
record: ElectronIpcRecord,
): void => {
const bucket = map.get(key);
if (bucket === undefined) map.set(key, [record]);
else bucket.push(record);
};
/**
* Index main handlers by literal channel, guarded literal invocation channels,
* or wildcard dynamic receivers. An unresolved channel may receive any literal
* channel, so it competes without ever pairing; a wrapper site whose
* invocations all supplied literal channels is represented by their findings,
* except guarded invocations, which still compete for their own channels.
*/
const indexMainHandlers = (
records: readonly ElectronIpcRecord[],
): MainHandlerIndex => {
const exactByChannel = new Map<string, ElectronIpcRecord[]>();
const guardedByChannel = new Map<string, ElectronIpcRecord[]>();
const wildcardDynamic: ElectronIpcRecord[] = [];
for (const record of records) {
if (!isMainHandler(record)) continue;
const { finding } = record;
if (finding.channel !== null) {
pushRecordBucket(exactByChannel, finding.channel, record);
continue;
}
if (
finding.receiver === undefined &&
finding.invocation_channels === "literal"
) {
for (const channel of new Set(finding.guarded_invocation_channels ?? []))
pushRecordBucket(guardedByChannel, channel, record);
continue;
}
wildcardDynamic.push(record);
}
return { exactByChannel, guardedByChannel, wildcardDynamic };
};
const matchingMainHandlers = (
index: MainHandlerIndex,
transmission: ElectronIpcFinding,
): ElectronIpcRecord[] => {
const channel = transmission.channel;
if (channel === null) return [];
const exact = index.exactByChannel.get(channel);
const guarded = index.guardedByChannel.get(channel);
const wildcard = index.wildcardDynamic;
const matching: ElectronIpcRecord[] = [];
let buckets = 0;
for (const list of [exact, guarded, wildcard]) {
if (list === undefined || list.length === 0) continue;
let addedFromList = false;
for (const handler of list) {
if (!compatibleIpcModes(transmission, handler.finding)) continue;
matching.push(handler);
addedFromList = true;
}
if (addedFromList) buckets += 1;
}
// Each individual bucket preserves `records` order; sort only when merging multiple buckets.
if (buckets > 1)
matching.sort((left, right) =>
compareUnicodeCodePoints(left.key, right.key),
);
return matching;
};
/**
* Whether one analyzed source loads an Electron module.
*
@@ -412,21 +481,6 @@ const isRendererTransmission = ({ finding }: ElectronIpcRecord): boolean =>
const isPairableRendererTransmission = (record: ElectronIpcRecord): boolean =>
isRendererTransmission(record) && record.finding.operation !== "send-to-host";
/**
* An unresolved channel may receive any literal channel, so it competes without
* ever pairing. A wrapper site whose invocations all supplied literal channels
* is represented by their findings, except guarded invocations, which have none
* and still compete for their own channels.
*/
const mayReceiveChannel = (
{ finding }: ElectronIpcRecord,
channel: string,
): boolean =>
finding.channel === null &&
(finding.receiver !== undefined ||
finding.invocation_channels !== "literal" ||
finding.guarded_invocation_channels?.includes(channel) === true);
/** Only an ipcMain registration on the same literal channel can be paired. */
const isExactIpcHandler = (handler: ElectronIpcRecord | undefined): boolean =>
handler !== undefined &&
@@ -150,6 +150,7 @@ export const addElectronCallPaths = (
projected.push({ file, path, coverage, nodes });
}
}
const projectedByKey = indexProjectedPaths(projected);
const wrapperCandidates = [
...ipc.pairings.map((pairing) => ({ ...pairing, coverageLimited: false })),
...ipc.states.flatMap(({ transmission, coverageLimitedCandidate }) =>
@@ -165,11 +166,15 @@ export const addElectronCallPaths = (
),
];
for (const { transmission, handler, coverageLimited } of wrapperCandidates) {
const sources = projected.filter(
(p) => p.path.entry_kind === "bridge-member" && matches(p, transmission),
const sources = lookupProjectedPaths(
projectedByKey,
"bridge-member",
transmission,
);
const targets = projected.filter(
(p) => p.path.entry_kind === "ipc-handler" && matches(p, handler),
const targets = lookupProjectedPaths(
projectedByKey,
"ipc-handler",
handler,
);
for (const from of sources)
for (const to of targets) {
@@ -213,6 +218,55 @@ export const addElectronCallPaths = (
}
};
type ProjectedPathIndex = Readonly<
Record<
"bridge-member" | "ipc-handler",
ReadonlyMap<string, ReadonlyMap<string, readonly ProjectedPath[]>>
>
>;
const indexProjectedPaths = (
projected: readonly ProjectedPath[],
): ProjectedPathIndex => {
const indexed: Record<
"bridge-member" | "ipc-handler",
Map<string, Map<string, ProjectedPath[]>>
> = {
"bridge-member": new Map(),
"ipc-handler": new Map(),
};
for (const entry of projected) {
const { entry_kind: entryKind, channel } = entry.path;
if (
channel === null ||
(entryKind !== "bridge-member" && entryKind !== "ipc-handler")
)
continue;
let byChannel = indexed[entryKind].get(entry.file.path);
if (byChannel === undefined) {
byChannel = new Map();
indexed[entryKind].set(entry.file.path, byChannel);
}
const bucket = byChannel.get(channel);
if (bucket === undefined) byChannel.set(channel, [entry]);
else bucket.push(entry);
}
return indexed;
};
const lookupProjectedPaths = (
indexed: ProjectedPathIndex,
entryKind: "bridge-member" | "ipc-handler",
record: ElectronIpcRecord,
): ProjectedPath[] => {
const channel = record.finding.channel;
if (channel === null) return [];
const candidates = indexed[entryKind].get(record.file.path)?.get(channel);
return candidates === undefined
? []
: candidates.filter((entry) => matches(entry, record));
};
const matches = (
projected: ProjectedPath,
record: ElectronIpcRecord,
@@ -1,3 +1,10 @@
import {
canBorrowParsedJsonSnapshot,
freezeJsonSnapshot,
immutableJsonSnapshotMember,
isImmutableJsonSnapshot,
} from "../../domain/immutableJson.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import {
JAVASCRIPT_APPLICATION_PROVIDER,
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
@@ -125,41 +132,70 @@ export const parseApplicationGraphEvidence = (
const evidence = parseEvidenceInput(input);
const owned = ownedApplicationSources.get(evidence);
if (owned !== undefined) return owned;
const immutable =
isImmutableEvidence(evidence) && isImmutableJsonSnapshot(evidence);
let source: ApplicationGraphEvidenceSource;
if (evidence.operation === "analyze_javascript_application") {
requirePredicate(evidence, "rea.javascript-application-analysis", path);
requireProvider(evidence, JAVASCRIPT_APPLICATION_PROVIDER, path);
return staticApplicationSource(evidence, path);
}
if (evidence.operation === "reconcile_javascript_runtime") {
source = staticApplicationSource(evidence, path, immutable);
} else if (evidence.operation === "reconcile_javascript_runtime") {
requirePredicate(evidence, "rea.javascript-runtime-reconciliation", path);
requireProvider(
evidence,
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
path,
);
return staticRuntimeSource(evidence, path);
}
if (evidence.operation === "project_managed_application_graph") {
source = staticRuntimeSource(evidence, path, immutable);
} else if (evidence.operation === "project_managed_application_graph") {
requirePredicate(evidence, "rea.managed-application-graph", path);
requireProvider(evidence, MANAGED_WORKFLOW_PROVIDER, path);
return managedApplicationSource(evidence, path);
source = managedApplicationSource(evidence, path, immutable);
} else {
throw invalidEvidence(
path,
"operation",
"Expected authenticated JavaScript analysis, runtime reconciliation, or managed application graph Evidence.",
);
}
throw invalidEvidence(
path,
"operation",
"Expected authenticated JavaScript analysis, runtime reconciliation, or managed application graph Evidence.",
);
if (immutable) {
const cached = Object.freeze(source);
ownedApplicationSources.set(evidence, cached);
return cached;
}
return source;
});
const borrowOrSealNormalizedResult = <Parsed extends JsonValue>(
evidence: Evidence,
parsed: Parsed,
immutable: boolean,
memberKeys: readonly string[],
): Parsed => {
if (!immutable) return parsed;
const snapshot = immutableJsonSnapshotMember(evidence, "normalized_result");
const owned =
snapshot !== undefined && canBorrowParsedJsonSnapshot(snapshot, parsed)
? (snapshot as Parsed)
: freezeJsonSnapshot(parsed);
for (const key of memberKeys) immutableJsonSnapshotMember(owned, key);
return owned;
};
const staticApplicationSource = (
evidence: Evidence,
path: readonly (string | number)[],
immutable: boolean,
): ApplicationGraphEvidenceSource => {
const result = parseCallerValue(
const parsed = parseCallerValue(
(input) => javascriptApplicationAnalysisResultSchema.parse(input),
evidence.normalized_result,
[...path, "normalized_result"],
);
const result = borrowOrSealNormalizedResult(evidence, parsed, immutable, [
"graph",
"semantic_graph",
]);
return staticApplicationSourceForResult(evidence, result, path);
};
@@ -201,6 +237,7 @@ const staticApplicationSourceForResult = (
const staticRuntimeSource = (
evidence: Evidence,
path: readonly (string | number)[],
immutable: boolean,
): ApplicationGraphEvidenceSource => {
if (
evidence.authority !== "analyst-inference" ||
@@ -211,11 +248,14 @@ const staticRuntimeSource = (
"authority",
"Runtime reconciliation Evidence must use analyst-inference authority and inferred confidence.",
);
const result = parseCallerValue(
const parsed = parseCallerValue(
(input) => javascriptRuntimeReconciliationResultSchema.parse(input),
evidence.normalized_result,
[...path, "normalized_result"],
);
const result = borrowOrSealNormalizedResult(evidence, parsed, immutable, [
"graph",
]);
assertResultEvidenceLinksInEnvelope(
result.evidence_links,
evidence,
@@ -243,6 +283,7 @@ const staticRuntimeSource = (
const managedApplicationSource = (
evidence: Evidence,
path: readonly (string | number)[],
immutable: boolean,
): ApplicationGraphEvidenceSource => {
if (
evidence.authority !== "analyst-inference" ||
@@ -253,11 +294,14 @@ const managedApplicationSource = (
"authority",
"Managed application graph Evidence must use analyst-inference authority and inferred confidence.",
);
const result = parseCallerValue(
const parsed = parseCallerValue(
(input) => managedApplicationGraphResultSchema.parse(input),
evidence.normalized_result,
[...path, "normalized_result"],
);
const result = borrowOrSealNormalizedResult(evidence, parsed, immutable, [
"graph",
]);
assertResultEvidenceLinksInEnvelope(
result.evidence_links,
evidence,
@@ -121,6 +121,7 @@ const addBundlerModuleNodes = (
input: BundlerModuleProjectionInput,
): void => {
const { file, registration, chunk, coverage, limitations } = input;
const entryModuleKeys = new Set(registration.entry_module_keys);
for (const moduleValue of registration.modules) {
const module = context.accumulator.addNode({
kind: "javascript-module",
@@ -139,9 +140,7 @@ const addBundlerModuleNodes = (
chunk_keys: registration.chunk_keys,
module_key: moduleValue.module_key,
factory_require_name: moduleValue.factory_require_name,
runtime_entry: registration.entry_module_keys.includes(
moduleValue.module_key,
),
runtime_entry: entryModuleKeys.has(moduleValue.module_key),
source_sha256: moduleValue.source_sha256,
structural_fingerprint_sha256:
moduleValue.structural_fingerprint_sha256,
@@ -30,6 +30,7 @@ export const createJavaScriptRuntimeReconciliationEvidence = (
limitations: result.limitations,
evidenceLinks: result.evidence_links,
},
{ immutable: true },
);
const parameters = (
@@ -111,6 +111,7 @@ const createManagedApplicationGraphEvidence = (
limitations: result.limitations,
evidenceLinks: result.evidence_links,
},
{ immutable: true },
);
const subjectTarget = (