Skip to content

perf(javascript): prune typed-array element reference escapes - #5139

Merged
morluto merged 3 commits into
morluto:mainfrom
galleonli:perf/primitive-reference-flow
Oct 22, 2026
Merged

morluto merged 3 commits into
morluto:mainfrom
galleonli:perf/primitive-reference-flow

Conversation

@galleonli

@galleonli galleonli commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Addresses #2498, following the typed-array approach suggested in this comment.

The slow path here comes from treating typed-array elements as possible object references. This patch lets the mutation collector rule those out. On the reported pdf.js file, the CLI went from 824 seconds to 103 seconds, with byte-identical JSON output. Sampled peak memory across the process family went from 3.30 GiB to 1.25 GiB.

Those are single runs on macOS arm64 with Node 24.18.0, a 4 GiB worker heap and a 900-second timeout.

With the default 1 GiB heap and 300-second deadline, the base timed out with a partial observation. The patch finished in 114 seconds with the same analysis content as its larger-budget run.

Problem and expected behavior

For a store like H[e >> 2] = b, the collector follows the possible values assigned to b. In wasm2js output, many are reads from a typed array, so it keeps tracing references through the heap even though these values cannot be objects.

A numeric indexed read from a native typed array returns a number, bigint, or undefined. The element cannot carry an object reference. Writes to the view and escapes of the view itself still need to be tracked.

Change and scope

Add a typed-array origin to the existing mutation analysis. Use the existing global-identity checks to recognize native constructors, and stop reference propagation for reads with a proven Number key or canonical numeric string key. Keep ordinary objects in mixed receiver sets, and keep the existing behavior for custom or unknown properties.

Keep a separate origin for the primitive element itself. Reading a property from that value can still expose a reference: heap[0].constructor, for example, can return Number or BigInt. Those property reads stay conservative, including dynamic properties and reads through aliases. This fixes the missing-reference case raised in review without tracing references through scalar heap stores again.

The actual property key stays part of the projection identity, so different slots in an ordinary array stay separate. Effect sites, timing and analysis budgets are unchanged.

Constructor aliases and general numeric-value inference are outside this change.

Contract and boundary impact

  • Semantic owner and earliest changed stage: observableMutationPaths, before member effects are propagated.
  • Contribution scope: optimization inside the existing static JavaScript analyzer; a separate capability decision is not applicable.
  • CLI/MCP, provider, package, and generated metadata contracts: unchanged.
  • Evidence and provenance: unchanged on the reported input, including partial-coverage markers and retained unknowns.
  • Target selection and cleanup: unchanged. Validation parsed the public file as inert text and did not execute it. Both measured CLI runs exited with no remaining owned processes.

Expected effects of the exercised workflow:

  • Read existing files or captured data.
  • Launch or attach to a process. The existing isolated analyzer process only.
  • Inject instrumentation or run scripts/code in a target.
  • Change target process memory, registers, files, or configuration.
  • Contact network services during analysis.
  • Recover protected code or work around protections.

Evidence and regression coverage

The base revision is a80575c73652d8b43d7340654a48bd20a4eb966d. The initial 54 cases cover native constructors, numeric and custom keys, aliases, reassignment, mixed object receivers, constructor changes, eval, proxies, distinct ordinary-array slots, and retained view writes/escapes. On the base revision, 29 fail and 25 pass. Another 10 cases cover references reached through Number/BigInt element properties; all 10 failed on the first PR commit, 2fcfab5. All 64 pass with the current patch.

The full internal semantic IR is byte-identical, with complete coverage and no omissions. The public CLI output is also byte-identical, but its graph remains partial under the existing per-file caps. Finishing the command does not remove those limits.

Reproduction and measurement details

The fixture is pdfjs-dist@5.3.93, package/wasm/openjpeg_nowasm_fallback.js, 462,316 bytes, SHA-256 53c228428a8861035a34738966af263fc9d4cee6df25a0ad942af947469a0bd9.

The unrestricted internal semantic IR is 32,160,539 bytes. That run fell from 385.8 to 49.6 seconds; peak process RSS fell from 3.37 to 0.88 GiB.

The CLI comparison used the extracted wasm directory as fixture_dir:

node scripts/rea.mjs analyze-javascript-application "$fixture_dir" \
  --source-path openjpeg_nowasm_fallback.js \
  --max-heap-mb 4096 --analysis-timeout-ms 900000 --json

Both CLI outputs are 52,499,954 bytes, SHA-256 eaa210ede669a57492de9bc424e336def71049ebf5583b80df5b3c73bef913fd. Their semantic graphs remain partial under the unchanged default per-file caps: 20,000 nodes, 32,675 relations, and 20,000 unknowns retained. Completed CLI execution does not mean complete graph coverage.

CLI CPU time was 871.81 seconds before and 110.20 seconds after. Process-family memory was sampled by summing descendant ps RSS every 200 ms; shared pages may be counted more than once and short peaks may be missed. The internal IR measurements use process maxRSS, a different accounting method. Each comparison used fresh processes on the same host with no concurrent test or build job. The patched runs were repeated after the property-reference fix; the baseline measurements are unchanged.

At default resource limits, the base returned provider_timeout. The patched analysis matches its larger-budget run; only the recorded heap/timeout parameters and the derived Evidence ID differ. This checks completion under the defaults, not a speedup against a completed baseline.

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

Validation performed

  • JavaScript domain tests: 2,469 passed across 90 files, including the 64 new cases.
  • npm run check: typecheck, compilation, lint, formatting, knip, metadata, and architecture guards passed.
  • npm run verify:test-discovery: all 1,597 test files discovered exactly once on the first PR commit; the follow-up adds cases to the same test file.
  • git diff --check: passed.
  • A controlled Node probe checked 180 cases across 12 built-in typed-array constructors, including inherited numeric properties and noncanonical own properties; all passed before the property-reference follow-up.

Compatibility, safety, and release

No public API, dependency, migration or target-execution change. The full repository suite, other operating systems and MCP transport were not tested. The timings above apply to this input and machine.

Author readiness

Human owner: @galleonli

  • 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.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved; this stays within existing static-analysis boundaries.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked.
  • Tests cover changed behavior and meaningful conservative fallbacks.
  • No owning docs, public contracts, or generated metadata need changes.
  • Representative CLI output and its coverage limits are described above.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

@galleonli
galleonli marked this pull request as ready for review October 19, 2026 01:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

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-10-21T05:53:42.907874Z
We couldn’t complete this review. Comment @codex review to try again.
1e075c2 New commits
ℹ️ 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.

@greptile-apps

greptile-apps Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge; no actionable defect was found.

Summary

This PR stops following object references through proven numeric reads from native typed arrays.

  • Numeric typed-array reads stop creating reference escapes.

The previous and current commits have different merge bases with the target commit, so the full PR diff was reviewed. No numbered previous review threads were supplied.

Reviews (3) · Last reviewed commit: "Merge origin/main into perf/primitive-re..." · Reviewed by Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2fcfab5bf9

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (origin === "typed-array") {
// Custom properties can hold references; only canonical numeric
// indices have the native Number/BigInt/undefined result contract.
if (!numericIndex) add("opaque");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve projected references from typed-array element primitives

When a proven numeric read is followed by another member selection, for example const n = new Int32Array(1)[0]; consume(n.constructor), this branch leaves the read observer with no origin, so normalize(..., "escape") also prunes every descendant projection. The element itself is primitive, but property lookup boxes Number/BigInt and can return object references such as constructor, toString, or a prototype getter; those objects then escape without any mutation effect being recorded. Preserve a primitive/prototype origin for nonempty paths and prune only the element value itself.

AGENTS.md reference: AGENTS.md:L37-L39

Useful? React with 👍 / 👎.

@CassieFox23 CassieFox23 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TL;DR: I checked the one open bot thread against f75b17f. It was real on the first commit, 2fcfab5, and it does not reproduce on the current head. The new tests pass on Node 22, 24 and 26, and I did not re-measure the speed or memory numbers.

Edit (21 Oct): Retested on 1e075c2 after the merge of main. It still works. See the retest.

Finding and verdict

Head f75b17f. The PR changes 3 files against a80575c (+410 -10). "Reproduces" means the escape was lost.

Thread Sev Verdict What I saw
Preserve projected references from typed-array element primitives P1 Fixed in f75b17f The bot's own snippet, const n = new Int32Array(1)[0]; consume(n.constructor), lost its escape on 2fcfab5 and keeps it on head, as it does on the base. On head I also tried 11 other reads off an element, and all kept the escape: n['constructor'], n?.constructor, n.toString as a value, an alias, a conditional alias, n.constructor.prototype, n[prop], n[0], a getter added to Number.prototype, a destructured constructor, and a view read through heap[index >> 2]. The snippet with BigInt64Array kept it too. The plain consume(n) is still pruned, so the speed-up path stays. On 2fcfab5 the 10 property tests the PR body mentions all fail, as the body says

The thread still shows as open, but GitHub marks it outdated, and the fix came after it was written.

I noticed one more behaviour change. It is not in the bot thread. consume(n.toString()) on a typed-array element no longer records the call as an escape of n. A plain const n = 5 already behaved that way. It looks fine to me, since a primitive receiver is not an object reference, but I only checked that one shape.

What the PR says about speed and memory

The body gives single runs on macOS arm64 (Node 24.18.0). The pdf.js CLI run goes from 824 s to 103 s. Peak memory across the process family goes from 3.30 GiB to 1.25 GiB. I did not re-run any of it. As far as I can tell the new tests check the behaviour the change keeps (which reads are pruned and which are not). They do not check speed.

Not run

  • Any speed or memory measurement, and the pdf.js file itself.
  • The rest of the JavaScript domain suite, npm run check and lint.
  • This PR on top of current main. The JavaScript domain folder has not changed on main since a80575c.
  • Method calls through a getter on Number.prototype.
  • macOS, and the CLI path.

Thanks, galleonli, for the quick follow-up fix and the clear write-up.

Test results
Node Result
24.18.0 javascriptSemanticAnalysis.typed_array_references.test.ts: 64 passed, plus 17 of my probe tests
22.23.1 same: 64 passed, 17 probe tests passed
26.11.1 same: 64 passed, 17 probe tests passed

On 2fcfab5 the same file had 10 failures. All were in the group references reached through typed-array element properties. 13 of my probe cases failed there too.

Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 22.23.1, 24.18.0, 26.11.1
  • Head / base: f75b17f / a80575c
  • Other: the box was shared with other test jobs, so I report no timings. The probe file is mine, not in the PR.
Commands
npm ci --ignore-scripts; npm run build:cached; npm run test:prepare   (Node 24, tree at f75b17fda)
npm run test:focused -- src/domain/javascript/javascriptSemanticAnalysis.typed_array_references.test.ts src/domain/javascript/ev5139Probe.test.ts   (Node 22, 24, 26)
git diff --shortstat a80575c73 f75b17fda
git diff --shortstat a80575c73 974487f00 -- src/domain/javascript

The probe uses the PR test file's own helper and reads the escaped paths of one named variable. It checks the finding's snippet, the 11 other reads listed above, and three controls (the element itself, a view read through heap[index >> 2], and an alias) that must still be pruned. To compare, I swapped in the member-mutations source from 2fcfab5 and from a80575c and ran the same file.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

Keep this branch's typed-array and typed-array-element mutation origins beside main's new function origin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

Merged latest main into this branch (1e075c2) to clear the merge conflict. No force-push; your commit is untouched.

What changed and why

Validation (local macOS, merged head)

  • tsc --noEmit: clean
  • npm run test:focused on every src/domain/javascript/*SemanticAnalysis* and *Mutation* test, including your typed-array references suite: 34 files, 1054 passed
  • check:fast, format:check: pass

@CassieFox23

CassieFox23 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR: I retested head 1e075c2, which merges main into the branch. The merge is clean. The PR's change is the same patch as on f75b17f. kaoru0822-kitauji fixed the one conflict as the note says. The PR's 64 tests, 34 related test files and the typecheck pass, and the earlier Codex P1 case still keeps its escape.

Findings

I tested head 1e075c2 on main a00e4ac. I compared the PR's change before and after the merge, then ran the tests.

Check Result
Files and size Same 3 files, +410 -10, as on f75b17f
javascriptSemanticTypedArrays.ts and the new test file Identical to f75b17f (same git blob)
javascriptSemanticMemberMutations.ts The patch is the same. Only line offsets differ, plus one new context line, | "function", from main
The conflict Main's #4941 added "function" to MutationObservableOrigin next to the PR's "typed-array" and "typed-array-element". The union now holds all three, as kaoru0822-kitauji wrote
Anything lost from main No. The whole difference between 1e075c2 and main a00e4ac is these 3 files
New escapedPaths fields from main's #4941 They do not break the PR's tests. All 64 pass

Test results, same on every Node:

Check Node 22.23.1 Node 24.18.0 Node 26.11.1
PR test file javascriptSemanticAnalysis.typed_array_references.test.ts 64 passed 64 passed 64 passed
34 test files that cover this area (names with SemanticAnalysis or Mutation), 1,054 tests, plus 16 of my probe tests 1,070 passed 1,070 passed 1,070 passed
tsc --noEmit not run clean not run

The 1,054 matches the count kaoru0822-kitauji gave on macOS.

The Codex P1 thread (link) is still the only review thread. It is outdated and has no reply. Its case does not reproduce on 1e075c2. The bot's snippet, const n = new Int32Array(1)[0]; consume(n.constructor), keeps its escape, as it did on f75b17f. So do 12 other reads off an element. They include BigInt64Array, n['constructor'], n?.constructor, n.toString as a value, an alias, a conditional alias, n.constructor.prototype, n[prop], n[0]. A getter on Number.prototype, a destructured constructor and a heap[index >> 2] view read do too. The plain consume(n) is still pruned, so the speed-up path stays.

No new bot thread has appeared since f75b17f. Codex reported that its own review of 1e075c2 failed to run, so it has no findings on this head.

Not run

  • Lint, knip, format check, and the rest of the JavaScript suite. I ran the 34 related files and the typecheck.
  • The typecheck on Node 22 and 26.
  • This PR on top of current main, which has moved on since a00e4ac.
  • The speed and memory numbers in the PR body, and the macOS runs by kaoru0822-kitauji.
  • The old probes on 2fcfab5. My earlier review has that run.
Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.11
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 22.23.1, 24.18.0, 26.11.1
  • Head / base: 1e075c2 / a00e4ac
  • Other: build on Node 24 with npm install scripts off. The probe file is mine, not in the PR. I rewrote it, because my earlier copy was gone.
Commands
npm ci; npm run prepare; npm run build:cached; npm run test:prepare   (Node 24, tree at 1e075c223)
npm run test:focused -- src/domain/javascript/javascriptSemanticAnalysis.typed_array_references.test.ts   (Node 22, 24, 26)
npm run test:focused -- <the 34 files> src/domain/javascript/ev5139Probe.test.ts   (Node 22, 24, 26)
npm run typecheck   (Node 24)
git diff a80575c73 f75b17fda         (the earlier change)
git diff a00e4ac363 1e075c223        (the change after the merge)
git rev-parse <sha>:<path>           (blob ids of the 3 files at both heads)

The probe uses the PR test file's own helper and reads the escaped paths of one named variable. It checks the finding's snippet and 12 other reads that must keep the escape, and 3 controls (the element itself, a view read through heap[index >> 2], and an alias) that must stay pruned.

🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊

@morluto
morluto merged commit 6d73515 into morluto:main Oct 22, 2026
5 checks passed
@morluto morluto mentioned this pull request Oct 25, 2026
3 tasks done
@morluto morluto added the performance Performance regressions, scaling limits, and bounded-resource work label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance regressions, scaling limits, and bounded-resource work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants