Skip to content

perf(javascript): allocate nested evaluation contexts with fixed shapes - #9007

Merged
morluto merged 2 commits into
morluto:mainfrom
mshzy:perf/nested-context-shapes
Nov 20, 2026
Merged

morluto merged 2 commits into
morluto:mainfrom
mshzy:perf/nested-context-shapes

Conversation

@mshzy

@mshzy mshzy commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A CPU profile of JavaScript semantic indexing identified nestedContext in src/domain/javascript/javascriptSemanticValues.ts as 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 capturePoint case. 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, provenanceForExpression and ~20 other call sites) calls nestedContext to derive a child EvaluationContext whose only changed value is expressionDepth + 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:

const nestedContext = (context: EvaluationContext): EvaluationContext => ({
  state: context.state,
  primitiveBindingValues: context.primitiveBindingValues,
  ...(context.capturePoint === undefined
    ? {}
    : { capturePoint: context.capturePoint }),
  expressionDepth: context.expressionDepth + 1,
  bindings: context.bindings,
  dependence: context.dependence,
  memo: context.memo,
});

...(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 same EvaluationContext values, 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.ts only, +25 −11 in nestedContext:

  • Two explicit object literals selected by context.capturePoint === undefined. The branch that omits capturePoint stays compatible with exactOptionalPropertyTypes.
  • Both literals keep the original field order (state, primitiveBindingValues, [capturePoint], expressionDepth, bindings, dependence, memo). All fields other than expressionDepth are forwarded by reference exactly as before; no new copying, caching, or normalization is introduced.
  • A comment records why the spread is deliberately not reintroduced.

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.md and .agents/skills/rea-analysis-optimization/SKILL.md require 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

  • Semantic owner and earliest changed stage: src/domain/javascript/javascriptSemanticValues.ts owns construction of nested EvaluationContext values. The earliest changed stage is expression/binding value evaluation during semantic indexing; affected consumers are analyzeJavaScriptSemantics, analyzeJavaScriptStaticSource, member-mutation fact indexing, and every downstream projection that consumes those values.
  • Contribution scope fit and linked maintainer decision: not applicable; no new provider, capability, target execution, injection, mutation, or protection recovery.
  • CLI and MCP/tool-catalog contract: unchanged. No tool, parameter, result shape, or catalog entry changes.
  • Provider, bridge, target-format, or platform compatibility: unchanged. Pure JavaScript, platform independent; no native artifact, bridge, or provider code is touched.
  • Evidence, artifact, provenance, or reconstruction contract: unchanged. The IR, static-analysis facts and coverage payloads are byte-identical before and after (see oracle below); no artifact identity or source provenance is recomputed differently.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable. No target is selected, launched, or cleaned up by this change.
  • Generated metadata, package, or installation impact: none. No build outputs, catalogs, or 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.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

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#performance states 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:

    • Profiler: node --cpu-prof on a tsc-built ESM checkout, N=128 alias chain, self-time aggregation over all samples. Top frame: nestedContext at javascriptSemanticValues.js:948, 25.4% (698.2 ms of 2754 ms sampled). Next frames were evaluateExpressionValue 7.5%, evaluateBinding 6.5%, union 6.1%. The conditional-spread constructor was the dominant cost, not the Set copies in member-mutation indexing (<1%).
    • Workload: export function result() { const alias0 = { child: { value: 1 } }; const aliasN = alias(N-1).child; ...; aliasN.value = replacement; return alias0.child.value; }, driven through parseJavaScriptSource → indexJavaScriptBindingsWithReceiversSteps → completeSemanticSteps(index.indexMemberMutationFactsSteps()). This isolates the member-mutation indexing phase so parsing and projection do not dilute the measurement.
    • Host: Windows 11 (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 uses process.cpuUsage() over the measured interval (includes V8 helper threads); peaks are sampled process.memoryUsage() after each run, not process-family RSS accounting.
    N before elapsed after elapsed speedup before CPU after CPU before heap peak after heap peak
    32 27.06 ms 18.41 ms 1.47× 16 ms 16 ms 34.8 MB 31.6 MB
    64 166.52 ms 104.67 ms 1.59× 188 ms 125 ms 36.6 MB 36.5 MB
    128 388.13 ms 235.81 ms 1.65× 500 ms 235 ms 69.3 MB 67.5 MB

    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.

    • Correctness oracle, independent of the changed implementation: 12 representative sources (plain member writes, alias chains, getters/setters, closure captures, template keys, destructuring, logical assignment, require/Worker/URL, for-of iteration, promises, classes, conditional/loop writes). For each, SHA-256 over the stable serialization of analyzeJavaScriptSemantics(source), analyzeJavaScriptStaticSource(source), and ir.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 both capturePoint branches.
  • 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:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

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 is src/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 untouched upstream/main base 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 is tests/acceptance/webSourceLocationCli.test.ts:19:3 (max-lines-per-function, 175 > 150), in a file with an empty diff against upstream/main, i.e. pre-existing. verify:module-boundaries was 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.
  • Correctness oracle and A/B benchmark described above — all 36 digests identical; measurements as tabulated.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. No public or module-exported signature changes; nestedContext remains a private helper with the same EvaluationContext type.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable. The changed path is platform-independent JavaScript semantic analysis; no provider or native tool is involved. Measurements were taken on Windows only.
  • Package or release metadata impact: none. No version, manifest, catalog, or generated file changes.
  • Security, privacy, process, or containment review: no change to admission, identity, authority, containment, or freshness checks. The optional capturePoint is forwarded unchanged and is still omitted when undefined, so no evaluation context gains a field it did not have before.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

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

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-05T11:05:18.742060Z
We couldn’t complete this review. Comment @codex review to try again.
32c4b6c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@greptile-apps

greptile-apps Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; the allocation change preserves the existing behavior.

Summary

Replaces the conditional spread in nestedContext with two explicit object literals.

  • JavaScript analysis builds nested contexts with fixed object shapes.

Reviews (3) · Last reviewed commit: "chore(ci): sync the nested context perfo..." · Reviewed by Greptile

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The test file src/domain/javascript/javascriptSemanticValues.memo.test.ts passed on Node 22.23.4, 24.22.1 and 26.12.1. The CI run on head 32c4b6c is completed/action_required and shows none of the test jobs. I ran no timing comparison and no wider domain tests.

Results

I ran head 32c4b6c in a VM.

Check Node 22.23.4 Node 24.22.1 Node 26.12.1
Test Files pass, 1 passed (1) pass, 1 passed (1) pass, 1 passed (1)
Tests pass, 16 passed (16) pass, 16 passed (16) pass, 16 passed (16)
  • The PR changes 1 file against the merge base, src/domain/javascript/javascriptSemanticValues.ts. It adds no tests. I ran the existing javascriptSemanticValues.memo.test.ts, which imports the changed module. A pass shows no change in behaviour there. It says nothing about speed.
  • Head 32c4b6c is 199 commits behind main c78c8ae.
  • I read CI live with gh. The author is mshzy, mergeable is true, state is blocked, and draft is false.
  • Workflow runs: CI and CodeQL production are each completed/action_required. PR title has 2 runs, both completed/action_required.
  • PR readiness has 2 runs: one completed/failure and one completed/success.
  • Check runs: Validate author declaration has 1 failure and 1 success. Greptile Review is a success. The commit status PR readiness is success.
  • The CI run has no Source tests, Portable tests or Test shard jobs in its check runs.

Not run

  • A repeated same-machine A/B at N=32/64/128 on base and head, comparing process.cpuUsage()
  • A run of npx vitest run --project domain src/domain/javascript on base and head
  • A merge with current main, c78c8ae
Test setup
  • Box: Fedora 44 VM (4 vCPUs, 8 GB) on my Nobara 44 PC, Linux 7.2.11
  • Node: 22.23.4, 24.22.1, 26.12.1
  • Head / base: 32c4b6c / fe677f6 (merge base with main)
  • Install: npm ci --offline and npm run test:prepare on Node 24.22.1
Commands
npm 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 🦊

@morluto
morluto merged commit d9df0f9 into morluto:main Nov 20, 2026
18 checks passed
@morluto morluto added performance Performance regressions, scaling limits, and bounded-resource work area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior performance Performance regressions, scaling limits, and bounded-resource work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants