Repository navigation
perf(javascript): allocate nested evaluation contexts with fixed shapes - #9007
Conversation
nestedContext builds one EvaluationContext per recursive expression step. A conditional object spread forces V8 through the generic property-copy path even when the spread adds no fields, and prevents a stable shape. It was the top self-time frame (25.4%) in a profile of semantic indexing. Use two explicit object literals selected by capturePoint, keeping the same field set, order, values and optionality. Completed analyses are byte-identical across 12 representative sources (36 IR/facts/coverage digests), and member-mutation indexing is 1.47-1.65x faster on the profiled alias-chain workload.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
[Medium impact] The PR appears safe to merge; the allocation change preserves the existing behavior. SummaryReplaces the conditional spread in
Reviews (3) · Last reviewed commit: "chore(ci): sync the nested context perfo..." · Reviewed by Greptile |
|
TL;DR: The test file ResultsI ran head 32c4b6c in a VM.
Not run
Test setupCommandsnpm ci --offline
npm run test:prepare
xvfb-run -a npm run test:focused -- src/domain/javascript/javascriptSemanticValues.memo.test.ts🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
Summary
A CPU profile of JavaScript semantic indexing identified
nestedContextinsrc/domain/javascript/javascriptSemanticValues.tsas the single hottest allocation: 25.4% of self time on a representative member-alias workload. The helper builds one evaluation context per recursive expression step using a conditional object spread, so V8 takes the generic property-copy path even for the common case where the spread contributes no fields, and the result has no stable shape.This replaces the conditional spread with two explicit object literals, one per
capturePointcase. The field set, field order, values and optionality are identical; only the allocation path changes. Completed analyses are byte-for-byte identical, and the measured indexing phase is 1.47–1.65× faster with ~33–53% less process CPU time on the profiled workload.This is an independently found performance improvement from profiling, not a response to an existing issue. No issue is linked; the reason is recorded under "Before merge" below.
Problem and expected behavior
The smallest trigger is any JavaScript source that drives recursive semantic value evaluation — for example a chain of member aliases ending in a write. Every recursive step (
evaluateExpression,evaluateBinding,evaluateMember,provenanceForExpressionand ~20 other call sites) callsnestedContextto derive a childEvaluationContextwhose only changed value isexpressionDepth + 1.The violated invariant is not a correctness contract but the performance priority in
AGENTS.md#performance("Avoid unnecessary work and copies"). The previous constructor was:...(cond ? {} : {...})is a dynamic spread even when it adds nothing. On this path it executes millions of times per analysis, and the two possible results cannot share one hidden class. Expected: the sameEvaluationContextvalues, produced through a direct allocation with two fixed shapes, with lower CPU time and no change to any analysis result.Change and scope
src/domain/javascript/javascriptSemanticValues.tsonly,+25 −11innestedContext:context.capturePoint === undefined. The branch that omitscapturePointstays compatible withexactOptionalPropertyTypes.state,primitiveBindingValues, [capturePoint],expressionDepth,bindings,dependence,memo). All fields other thanexpressionDepthare forwarded by reference exactly as before; no new copying, caching, or normalization is introduced.Intentionally not included: no change to memoization keys, dependency proofs, expression-depth budgets, evaluation order, cache invalidation, or traversal/generator yield positions; no index, cache layer, batching, or new helper API.
AGENTS.mdand.agents/skills/rea-analysis-optimization/SKILL.mdrequire identifying the removed work and its maintenance cost before adding such machinery — none is needed here. This is an ordinary correction inside the existing semantic-value boundary, so the maintainer scope decision for providers, capabilities, target execution, injection, mutation, or protection recovery is not applicable.Contract and boundary impact
src/domain/javascript/javascriptSemanticValues.tsowns construction of nestedEvaluationContextvalues. The earliest changed stage is expression/binding value evaluation during semantic indexing; affected consumers areanalyzeJavaScriptSemantics,analyzeJavaScriptStaticSource, member-mutation fact indexing, and every downstream projection that consumes those values.skills/files are committed.Expected effects: no target interaction is introduced, removed, or changed by this PR. All effect boxes are left unchecked deliberately; unchecked items here do not assert absence of unrelated behavior in REA.
Evidence and regression coverage
Tests added or updated: none. This changes only how an internal helper allocates an object; no observable behavior, contract, or failure path changes.
AGENTS.md#performancestates that changes to helper calls, imports, or representations alone do not require synthetic benchmarks or new tests, and the optimization skill requires correctness checks rather than new machinery for this class of change. Equivalence is established by the existing suite plus an independent oracle below. No new performance assertion test is added because a constant-factor allocation improvement has no stable complexity invariant to assert, and a wall-clock assertion would be flaky in CI.Base reproduction or other evidence:
node --cpu-profon atsc-built ESM checkout, N=128 alias chain, self-time aggregation over all samples. Top frame:nestedContextatjavascriptSemanticValues.js:948, 25.4% (698.2 ms of 2754 ms sampled). Next frames wereevaluateExpressionValue7.5%,evaluateBinding6.5%,union6.1%. The conditional-spread constructor was the dominant cost, not theSetcopies in member-mutation indexing (<1%).export function result() { const alias0 = { child: { value: 1 } }; const aliasN = alias(N-1).child; ...; aliasN.value = replacement; return alias0.child.value; }, driven throughparseJavaScriptSource→indexJavaScriptBindingsWithReceiversSteps→completeSemanticSteps(index.indexMemberMutationFactsSteps()). This isolates the member-mutation indexing phase so parsing and projection do not dilute the measurement.win32), Node v22.22.2,tsc-compiled ESM (not the bundled runtime), single process, no worker. Warm runs only: 2 warmups, 3 measured runs, best elapsed reported. Process CPU time usesprocess.cpuUsage()over the measured interval (includes V8 helper threads); peaks are sampledprocess.memoryUsage()after each run, not process-family RSS accounting.Peak RSS was unchanged within noise (103→103 MB, 106→106 MB, 161→161 MB), so the benefit is CPU/latency rather than retained memory. Small inputs (N=32) improve too, so this is not a large-input-only win.
require/Worker/URL,for-ofiteration, promises, classes, conditional/loop writes). For each, SHA-256 over the stable serialization ofanalyzeJavaScriptSemantics(source),analyzeJavaScriptStaticSource(source), andir.coverage— 36 digests, all identical before and after. Member-mutation fact digests also match for every N in 16, 32, 64, 128, 256, 512. The sources intentionally exercise bothcapturePointbranches.User-visible CLI/MCP output (if applicable): none. Output is unchanged by construction and by the oracle above; no CLI or MCP invocation was run end-to-end (recorded as a gap).
Remaining proof gaps: single host, single engine version, and a single synthetic workload family; no real bundled-application CLI/MCP workflow was timed end-to-end; cold-start and OS file-cache effects were not separated (all measurements are warm, in-process); no process-family memory accounting or peak-RSS methodology beyond
process.memoryUsage()sampling; JIT tiering can shift absolute numbers. No claim is made about token usage, investigation quality, or speedups on other workloads.For evidence-bearing changes:
Boundary and lifecycle regressions: not applicable. This change does not touch a boundary (admission, ownership, cancellation, cleanup, freshness) or a lifecycle transition; the equivalence oracle covers the affected semantic-value consumers instead.
Validation performed
npm run typecheck— pass (0 errors).npm run format:check— pass, 6936 files.npx oxlint src/domain/javascript/javascriptSemanticValues.ts— 0 errors, 9 pre-existing complexity warnings in the file.npm run verify:module-boundaries— pass, 3691 source files.npm run verify:test-discovery— pass, 3090 test files discovered exactly once.npx vitest run --project domain --reporter=dot— 474 files / 10016 tests: 10015 passed, 1 failed. The failure issrc/domain/process/processCapture.comparison.test.ts(ZodError: top-level filesystem snapshots and effects must match the initial and final checkpoints). It was reproduced on the untouchedupstream/mainbase via a stashed-checkout run (1 failed / 24 passed), so it is pre-existing and unrelated to semantic value evaluation.npm run lint— 1 error, 3266 warnings; the error istests/acceptance/webSourceLocationCli.test.ts:19:3(max-lines-per-function, 175 > 150), in a file with an empty diff againstupstream/main, i.e. pre-existing.verify:module-boundarieswas therefore run separately and passed.npx tsc -p tsconfig.json --outDir dist-clean --noEmit false— pass; used only to produce a clean, un-instrumented ESM build for profiling and for the before/after oracle.dist-clean/is not part of the commit.Compatibility, safety, and release
nestedContextremains a private helper with the sameEvaluationContexttype.capturePointis forwarded unchanged and is still omitted when undefined, so no evaluation context gains a field it did not have before.Before merge
type(scope): outcome.Reason for not linking an issue: the bottleneck was found independently by profiling this checkout rather than selected from the repository's open issue list. Opening a new issue only to close it immediately from the same PR would add a bookkeeping entry without a separate reporter, decision, or reproduction. The full reproduction, measurement method, and remaining gaps are recorded above so the change stands on its own evidence.
Author readiness
Human owner: @mshzy