Skip to content

fix(javascript): stop overflowing the stack on large module factories - #3035

Closed
LeonBytes wants to merge 1 commit into
morluto:mainfrom
LeonBytes:fix/symbolic-module-completion-stack-overflow
Closed

LeonBytes wants to merge 1 commit into
morluto:mainfrom
LeonBytes:fix/symbolic-module-completion-stack-overflow

Conversation

@LeonBytes

@LeonBytes LeonBytes commented Oct 13, 2026 •

Copy link
Copy Markdown

Summary

Analysis fails for a whole file when a loaded module's factory contains a very large array literal. #moduleCompletionPoint did pending.push(...childNodes(node)), and spreading a million children overflows the call stack. The worker reports Maximum call stack size exceeded as a memory resource_constraint and suggests retrying with more memory, which doesn't help.

This swaps the hand-written walk for the existing traverseJavaScriptAst. No issue exists for this; I found it while reading the code.

Problem and expected behavior

A load()-ed module whose factory holds a huge array literal should be analyzed like any other module. With rea analyze-javascript-application <dir> --json:

  • 1,000 and 200,000 elements: fine (the worker runs with --stack_size=2048).
  • 1,000,000 elements (3.5 MB main.js): analysis_failure, code resource_constraint, resource memory, reason main.js: Maximum call stack size exceeded.

The graph for main.js goes from one unknown node plus the asset node (6 nodes overall) to 4 module nodes, 1 chunk node and the asset node (18 overall). I didn't measure the exact element count where it starts failing; it depends on stack size and host.

Fixture generator
// node make-fixture.mjs <dir> 1000000
import { mkdirSync, writeFileSync } from "node:fs";
const [dir, n] = [process.argv[2], Number(process.argv[3])];
mkdirSync(dir, { recursive: true });
writeFileSync(`${dir}/package.json`, '{"name":"demo","version":"1.0.0","main":"main.js"}');
const data = Array.from({ length: n }, (_, i) => i % 251).join(",");
writeFileSync(`${dir}/main.js`, `(() => {
  const modules = {
    4(module) { module.exports = require("electron"); },
    8(module, exports, load) {
      const electron = load(4);
      const TABLE = [${data}];
      exports.sender = function(channel) { return (...args) => electron.ipcRenderer.send(channel, ...args); };
    },
    12(module, exports, load) {
      const helpers = load(8);
      const api = { copy: helpers.sender("test:copy") };
      require("electron").contextBridge.exposeInMainWorld("api", api);
    }
  };
  function load(id) { const m = {exports:{}}; modules[id](m,m.exports,load); return m.exports; }
  load(12);
})();
`);

Change and scope

#moduleCompletionPoint now calls traverseJavaScriptAst(factory.body, { skip, enter }). The body root is still always entered, nested functions and classes are still skipped, and the earliest ReturnStatement is still picked by start. The unused childNodes import is removed. Since childNodes is documented as the single place that expands AST children, this removes a duplicate walker instead of adding a helper.

I read the other push(...) spreads in src/domain/javascript (javascriptAstFingerprint.ts, javascriptSemanticObjectReferences.ts) and left them alone: their sizes come from one node's tokens or one class's fields, not from a source-sized child list. That is from reading, not testing.

Not touched: the failure classification. A stack overflow shows up as a memory resource_constraint, which is misleading, but that is your call.

Contract and boundary impact

  • Semantic owner and earliest changed stage: symbolic bindings in src/domain/javascript (Electron wrapped call paths).

  • Contribution scope fit and linked maintainer decision: fix inside existing boundaries; not applicable.

  • CLI and MCP/tool-catalog contract: unchanged. For the affected input, a per-file failure becomes the normal graph.

  • Provider, bridge, target-format, or platform compatibility: none; static analysis only.

  • Evidence, artifact, provenance, or reconstruction contract: unchanged.

  • Target selection, authority, upstream behavior, and cleanup details: not applicable.

  • Generated metadata, package, or installation impact: none.

  • 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: src/domain/javascript/javascriptSymbolicBindings.test.ts, "completes a loaded module at its earliest return past a very large array literal". It replaces the elements of a parsed array with 1,000,000 synthetic numeric literals (faster than parsing a 3.5 MB source) and checks the loaded namespace completes at the factory's earliest bare return. The size matters: 200,000 elements didn't overflow in the test worker either.

  • Base reproduction: with only the source change stashed, the file shows 27 tests | 1 failed (the new one); with the change all 27 pass.

  • User-visible CLI/MCP output: see the numbers above.

  • Remaining proof gaps: no real-provider, Windows or macOS run; exact stack threshold not measured.

  • 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

Linux, Node v22.22.0 (.nvmrc pins 24.18.0), npm 10.9.4 (packageManager is [email protected]), npm ci --ignore-scripts.

  • npx tsc --noEmit: exit 0
  • npx oxfmt --check and npx oxlint on the two changed files: format passes; no new lint warnings
  • npm run verify:module-boundaries: pass
  • npx knip: exit 0
  • npx vitest run --project domain --project services src/domain/javascript src/application/javascript: 69 files, 1558 tests passed
  • On the base revision, before the change: domain, services, composition, conformance and evaluation projects: 285 files, 4077 passed, 4 skipped
  • npm run build:cached and node scripts/rea.mjs analyze-javascript-application <fixture> --json on the 1,000,000-element fixture: fails before the change, no analysis_failure after it

Not run: npm run check, npm run check:pr, npm run docs:check, the boundary, cli-boundary, mcp-boundary, acceptance and process projects, and the real-provider lanes.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable; not run.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no new I/O, process or network behavior; only how a parsed AST is walked changes.

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.

#moduleCompletionPoint expanded every child of each visited node with
`pending.push(...childNodes(node))`. A node's child count follows the source
(array elements, call arguments, statements), so a loaded module factory that
holds a very large array literal overflowed the call stack. The analysis
worker then reported the RangeError as a memory resource_constraint, dropped
the file's module and chunk graph, and advised retrying with more memory.

Walk the factory body with the shared traverseJavaScriptAst, which owns child
expansion and can skip nested functions and classes, and remove the now unused
childNodes import. The earliest-return selection is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CRnrm8wZ6Q4MXQPQda6zvF
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-13T23:11:34.694936Z 0105d2d 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 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: 0105d2d38d

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

// The shared traversal owns child expansion. A node's child count follows
// the source (array elements, call arguments, statements), so it must never
// be spread into call arguments, which overflows the stack on large data.
traverseJavaScriptAst(factory.body, {

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 Record before/after resource measurements

For this million-child performance/resource fix, the validation supplied with the commit reports only failure/success and graph counts; it does not give elapsed time, CPU time, peak process-family memory, or cold/warm context for an equivalent completed workload (for example, the 200,000-element case that completes on both revisions). Without those measurements, the new traversal's per-node generator/frame overhead and the added capacity test have not been shown to remain within safe resource bounds, despite the repository explicitly requiring these comparisons for cost-affecting changes.

AGENTS.md reference: AGENTS.md:L52-L55

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium impact] This PR appears safe to merge.

Summary

This PR replaces the manual walk in #moduleCompletionPoint with traverseJavaScriptAst.

  • Loaded modules with huge arrays no longer overflow during completion-point discovery.

No actionable issues or introduced security concerns were found. Tests were not run during this review. Supersession could not be checked because GitHub access required authentication.

Reviews (1) · Last reviewed commit: "fix(javascript): walk module factories w..." · Reviewed by Greptile

@morluto morluto added area: domain Domain logic, errors, and pure functions bug Something isn't working labels Oct 13, 2026
morluto added a commit that referenced this pull request Oct 14, 2026
Preserve CommonJS literal paths and confined ESM URL semantics, including package main fallback, directory intent, Unicode identity, and present opaque modules. Parse extraction inputs at their AST/source owner, retain skipped HTML and source-map coverage, and distinguish endpoint candidates from proven receiver facts. Version structural fingerprints with computed literal contents and propagate them through worker contracts.

Reviewed fixes include #1810, #1840, #2642, #2700, #2702, #2714, #2803, #2960, #2968, #2986, #3035, and #3036.

Validation: 158 resolver tests passed; public CLI/MCP module lookup controls, package-main/Unicode workflows, and six builtin workflows passed in the current compiled lane. Worker schema/fingerprint regressions passed. Large public pdf.js completion and real Electron analysis remain unverified.
@kaoru0822-kitauji kaoru0822-kitauji added the ci-fix-wip Claimed by the CI-fix track label Oct 14, 2026
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

CI-fix track: this change is already on main. b58adaf lists #3035 among its reviewed fixes, and main's #moduleCompletionPoint uses the same traverseJavaScriptAst walk with skip for nested functions and classes in place of the spread childNodes stack. After merging current main and resolving the two conflicts, no file differs from main, and javascriptSymbolicBindings tests pass there (37). I didn't push an empty merge. This PR looks safe to close as superseded.

@kaoru0822-kitauji kaoru0822-kitauji removed the ci-fix-wip Claimed by the CI-fix track label Oct 14, 2026
@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The fix works on Node 22, 24 and 26. Without it, Node 24.18.0 overflows the stack at about 261,000 elements, and with it files far past that size complete. Main already holds the same walk (b58adaf), so this may be superseded.

I tested head 0105d2d as pushed. GitHub now says it conflicts with main eb44921. For "before", I reverted the one source file to the merge-base b9b3a90.

Results

Check Node 22.23.1 Node 24.18.0 Node 26.11.1
PR test file, head (27 tests) pass pass pass
PR test file, before not run 1 fails: Maximum call stack size exceeded not run
CLI, 1,000,000 elements, before stack overflow stack overflow stack overflow
CLI, 1,000,000 elements, head completes completes completes

Threshold, before, Node 24.18.0: 260,937 elements pass. 261,718 fail with the stack error. Three runs at each size agreed.

Head, Node 24.18.0: 1,000,000 elements pass. Between 1,437,500 and 1,468,750 the worker runs out of its default 1 GiB heap. That is a different limit. With --max-heap-mb 4096, head passes at 2,000,000 and 4,000,000 elements. Before still overflows the stack at both.

Time and memory (the Codex question)

Both builds complete the 200,000-element file. Four runs each, interleaved, medians:

Metric Before Head
Wall time 7.83 s 8.01 s
User CPU 9.57 s 10.05 s
Largest single process 470 MiB 467 MiB
Whole process family, sampled 755 MiB 743 MiB

Run-to-run spread is about the same size as the gap. Output at 200,000 elements is byte-identical between the builds. At 1,000,000 elements, head takes 18.2 s and before takes 5.9 s. Before stops early with a failure, so that is not like for like.

Not run

  • Main's own walk is untimed.
  • Cold cache: I cannot drop the page cache here.
  • The cost of the single function alone is unmeasured.
  • Windows, macOS, and the boundary and acceptance tests.
  • Head merged onto current main.

Thanks, LeonBytes, for the fix and the generator.

Another test job ran on this box. Load average (busy tasks over 1 minute, on 24 threads) was 0.9 to 2.3.

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: 0105d2d
  • Base: b9b3a90
  • Other: main eb44921; GNU time 1.9; fixture from the PR body generator
Commands
npm ci && npm run build
node scripts/run-development-tests.mjs focused src/domain/javascript/javascriptSymbolicBindings.test.ts
node scripts/rea.mjs analyze-javascript-application <fixture> --json [--max-heap-mb 4096]
/usr/bin/time -v node scripts/rea.mjs analyze-javascript-application <fixture> --json

Each run sat under systemd-run --user --scope -p MemoryMax=8G. The family peak is the sum of resident memory over the process and its children, sampled every 50 ms. The cgroup peak (memory.peak) ran 20 to 55 MiB below that sum. The two measures count memory differently, and the cgroup figure is the lower one.

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

@CassieFox23

Copy link
Copy Markdown
Contributor

Heads up: main already has this change in b58adaf. The code is in src/domain/javascript/javascriptSymbolicBindings.ts, and completes a loaded module past a very large array without stack overflow covers it. It is listed on tracker #3582. If this PR still adds something main doesn't have, please say so here and I'll take it off the list. Thanks for the fix!

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

@morluto

morluto commented Oct 18, 2026

Copy link
Copy Markdown
Owner

Thanks @LeonBytes. Closing this PR as superseded by b58adafa4 on main.

Main uses a bounded iterative AST traversal instead of spreading source-sized children into call arguments, and includes the large-array stack-overflow regression.

This is an unmerged closure: it does not label this PR as merged or remove contributor history/credit. The decision uses the current source diff and existing validation record; no new local test or provider run is claimed.

@morluto morluto closed this Oct 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: domain Domain logic, errors, and pure functions bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants