Skip to content

fix(javascript): bound self-alias mutation paths that never prune - #1767

Merged
N0zoM1z0 merged 2 commits into
morluto:mainfrom
flitzrrr:fix/javascript-self-alias-mutation-paths
Oct 11, 2026
Merged

N0zoM1z0 merged 2 commits into
morluto:mainfrom
flitzrrr:fix/javascript-self-alias-mutation-paths

Conversation

@flitzrrr

@flitzrrr flitzrrr commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Since the getter-receiver fix for #1665 (7956934), analyze_javascript_application can exhaust its semantic worker heap on code that walks a self alias such as node = node[key], or node = node.next on a class instance. jquery-3.2.0.min.js (Sizzle's :nth-child matcher) loses its whole semantic graph, even with --max-heap-mb 4096. This PR makes such cycles terminate while keeping every possibly affected fact unknown.

Follow-up to #1665. I did not open a separate issue because the PR carries the two-line reproduction below.

Problem and expected behavior

Smallest trigger:

var m = {};
while ((m = m[p])) m.nodeName.toLowerCase();

collectSemanticMemberMutationsSteps closes an alias cycle only when a binding is revisited at the same capture with exactly the same path. 7956934 added the path to that key so that getter receivers can revisit a capture with a shorter path. A self alias, however, prepends its projection on every cycle: ["nodeName"], then [null, "nodeName"], then [null, null, "nodeName"], and so on. The key therefore never repeats. When the binding's origin is opaque (a dynamic-key read or a class instance) or cyclic, observableMutationPaths keeps every path, so the traversal grows until the worker heap is exhausted.

Expected: the analysis terminates, and values that the loop may reach stay unknown.

Change and scope

The fix applies to a revisit whose earlier path on the same alias chain is a suffix of the current path. In that case observableMutationPaths.repeatsUnpruned projects the added prefix repeatedly. Projection origins depend only on the source origins and the key, so once an origin set repeats, normalization can never prune a longer path. The collector then records one escape at the repeated prefix and stops the cycle. That escape covers every longer write or escape, including writes below shared children. Finite cycles, where a projection runs out of origins, keep their exact paths as before.

Alternatives considered:

  • Closing the cycle on any longer revisit, as before 7956934, terminates but drops deeper writes. For example, alias = flag ? alias.child : alias; alias.value = 2 would then report shared.child.value as the stale literal 1. A new regression case covers this.
  • Escaping on every longer revisit is sound, but it also widens finite static-key loops. The existing case "bounds a loop that reassigns one reference through many members" would then lose its literal.

Known precision cost: a dynamic-key self alias escapes its repeated [null] prefix, so every child becomes unknown. In node = node[key]; node.name.toLowerCase(), seed.child.value is now unknown; before this change the analysis did not terminate. A static key without that slot keeps its literal.

Not included: no changes to the semantic graph budgets or the output size.

Contract and boundary impact

  • Semantic owner and earliest changed stage: domain JavaScript member-mutation collection (src/domain/javascript/javascriptSemanticMemberMutations.ts), before IR projection.
  • CLI and MCP/tool-catalog contract: none; schemas and tools are unchanged.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: affected effects are recorded as an escape at the repeated prefix, and values below it become unknown. Previously the file fell back to resource-limit unknowns for every semantic family.
  • Process execution, authorization, cleanup, or containment impact: none; the owned worker no longer exhausts its heap on these inputs.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none.

Evidence and regression coverage

  • Tests added or updated: src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts
    • Four self-alias shapes with a 2 s bound: dynamic key with receiver escape, call escape and write, and a class instance with a static-key write.
    • One deeper-write soundness case (shared.child.value through repeated alias = flag ? alias.child : alias).
  • Base reproduction: running the self-alias cases on the base revision crashes the Vitest worker with heap exhaustion (NODE_OPTIONS=--max-old-space-size=768). The deeper-write case passes on the base revision; a probe build with a plain cycle cut reported the stale literal for this shape.
  • User-visible CLI/MCP output: rea analyze-javascript-application <dir containing jquery-3.2.0.min.js> --artifact-format directory --format json
    • Before (2165045): the limitation Owned JavaScript worker exhausted its heap while analyzing jquery-3.2.0.min.js during semantic, and a semantic graph with only resource-limit unknowns. This took 20 s at the default heap, and 134 s with 4.5 GB RSS at --max-heap-mb 4096.
    • After: completes in 5.5 s with 555 MB RSS, has no resource limitation, and produces 20,000 nodes and 27,947 relations. The semantic IR step alone takes 0.28 s with 186 MB RSS.
  • Remaining proof gaps: growth whose earlier path is not a suffix (cycles that strip and re-prepend keys) still relies on normalization for termination; I found no trigger for it. Directories that also contain other large bundles can now reach the shared semantic graph budget with jQuery, which is reported as a resource limit for the later file (existing behavior).

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.

Validation performed

On macOS (Darwin 27.0, Apple Silicon), Node 24.18.0:

  • npm run test:fast — 375 files, 4274 passed, 7 skipped (before the rebase onto 062723e; the intervening commits do not touch JavaScript analysis)
  • npx vitest run src/domain/javascript/ after the rebase — 43 files, 821 passed
  • npm run check — passed
  • npm run verify:test-discovery — 813 test files discovered exactly once
  • npm run build:cached and the CLI run above — passed

Review follow-up

  • f2dac07 caches the repeated-prefix check per binding and prefix; 7663df9 skips the suffix scan on first capture visits.
  • Measured (macOS, Node 24.18.0), finite self-alias chain of 200 links: 24.9 s on origin/main, about 27 s here. That cost predates this PR. 300 aliases × depth 300: 1.75 s on main, 1.73 s here.
  • npx vitest run src/domain/javascript/ — 821 passed; npm run check:fast — passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable (static JavaScript analysis); macOS only.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: removes an unbounded memory path that a small untrusted script could trigger; no new process or file access.

Review checklist

  • This PR addresses a concrete problem or an agreed enhancement.
  • 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.

🤖 Generated with Claude Code

7956934 added the path to the member-mutation cycle key so getter
receivers can revisit a capture with a shorter path. A self alias such
as `node = node[key]` or `node = node.next` on a class instance revisits
its capture with one more prefix on every cycle, so the exact key never
repeats. Under an opaque or cyclic origin the path normalizer cannot
prune it either, and the traversal grew until the worker ran out of
heap: two lines of source were enough, and jquery-3.2.0.min.js lost its
whole semantic graph even with a 4 GB heap.

On a revisit whose earlier path is a suffix of the current one, check
whether repeating the added prefix keeps reaching the same origin set.
Projection origins depend only on source origins and key, so a repeated
set can never be pruned. In that case record one escape at the repeated
prefix, which covers every longer write or escape, and stop the cycle.
Finite cycles keep their exact paths.

jquery-3.2.0.min.js semantic analysis: heap exhaustion -> 0.3 s IR,
5.5 s for the full CLI analysis.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 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 ✅ Completed 2026-10-11T09:35:23.125593Z f2dac07 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.

@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: d0366686ac

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

Comment on lines +970 to +972
const signatures = new Set<string>();
while (observer !== undefined && prefix.length > 0) {
observer = project(observer, prefix);

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 Memoize finite-prefix reachability across path revisits

In a finite self-alias over a long static chain (for example const n2={}; const n1={next:n2}; const n0={next:n1}; ...; while (node = node.next) node.value = 1), each longer mutation path invokes this function again with the same (bindingId, ["next"]). Because signatures is local, every call walks the full N-level projection chain and repeatedly maps/sorts its shrinking origin sets before returning false, turning the previously cached O(N²)-scale normalization into O(N³)-scale synchronous work and making a modest generated file capable of hanging or exhausting the semantic worker. Memoize the result per binding/prefix or otherwise share this walk across revisits.

AGENTS.md reference: AGENTS.md:L42-L42

Useful? React with 👍 / 👎.

@flitzrrr flitzrrr Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added the cache in f2dac07. Measured it, though: the same 200-link chain takes 24.9 s on origin/main without this PR and ~27 s with it, so the cubic cost is pre-existing finite path expansion (path-keyed cycles from 7956934), not this check. Better handled in a separate fix.

🤖 Addressed by Claude Code

repeatsUnpruned depends only on the binding and the repeated prefix, so cache its answer instead of re-projecting the prefix on every longer revisit of the same chain.

@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: f2dac0792c

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

Comment on lines +143 to +145
for (let start = 1; start <= current.path.length; start++) {
const suffix = current.path.slice(start);
if (!current.bindings.has(JSON.stringify([...capture, suffix])))

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 Avoid quadratic suffix scans on first binding visits

For a deep known-object write propagated through many zero-projection aliases (for example, a generated const a1=a0; …; const aB=aB1; aB.p1...pL=1), each alias is a first visit for its binding, so none of these suffix lookups can match, yet the loop slices and JSON-serializes all L shrinking paths. That is Θ(L²) allocation per alias and Θ(BL²) overall (cubic when both dimensions grow), allowing a linear-size input to monopolize or exhaust the semantic worker even though the old normalization only walked each retained path once per alias; index visited paths by capture or skip the scan when that capture has no prior paths.

AGENTS.md reference: AGENTS.md:L42-L42

Useful? React with 👍 / 👎.

@flitzrrr flitzrrr Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 7663df9: the suffix scan now runs only when the capture is already on the alias chain. Measured 300 aliases × depth 300: 1.73 s, same as origin/main (1.75 s).

🤖 Addressed by Claude Code

@flitzrrr flitzrrr Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

#1767 merged before that commit landed; the change is in #1789.

🤖 Addressed by Claude Code

@N0zoM1z0 N0zoM1z0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed f2dac07 integrated with current main 85ccef3. The observer binding sources are seeded before the initial fixpoint; projected origins are settled before memoization, supporting both cached outcomes. The repeated-prefix escape preserves conservative effects and the deeper-write/finite-path regressions. No blocking finding.

Independent Linux / Node 24.18.0 verification:

  • A 95-byte walk(p) inert artifact returned provider_timeout on main with 256 MB worker heap and a 1,000 ms analysis deadline. The same public CLI and SDK stdio MCP inputs succeed with this revision. Entire Evidence envelopes authenticate and normalized results match; no resource omissions, with semantic unknowns preserved. REA did not execute the fixture.
  • 43 domain JavaScript files / 821 tests passed, including 109 reference-lifetime cases. Single-threaded full typecheck, lint/module boundaries, changed-file formatting and architecture guards passed.
  • Flameox 0.2.9 preserved complete stdout/stderr and native profiles for baseline, candidate and the broad tests. Candidate full CLI workload: 2.07 s including startup, collector family RSS ~504 MB. Profiles cover launchers, not isolated analysis/test workers; these measurements do not establish general memory gains or allocation behavior.

No independent jQuery/macOS/Windows reproduction claimed. Root main and contributor fork were not modified. Heavy commands used a 2 GiB / 90 s family guard; local threaded hooks were bypassed for the private integration commit and replaced by the checks above. CI for the exact source head is still being monitored before merge.

@N0zoM1z0
N0zoM1z0 merged commit e365f37 into morluto:main Oct 11, 2026
28 checks passed
@morluto morluto mentioned this pull request Oct 13, 2026
3 tasks done
@morluto morluto added bug Something isn't working area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior labels Oct 14, 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 bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants