Skip to content

fix(javascript): retain runtime scope in bundled module relationships - #1577

Merged
N0zoM1z0 merged 1 commit into
morluto:mainfrom
dakjdakd:fix/webpack-runtime-scope
Oct 10, 2026
Merged

N0zoM1z0 merged 1 commit into
morluto:mainfrom
dakjdakd:fix/webpack-runtime-scope

Conversation

@dakjdakd

Copy link
Copy Markdown
Contributor

Summary

Fixes #1576.

Preserve a recovered factory's runtime from static parsing through application graph projection. Previously, two Webpack/Rspack runtimes in the same asset could reuse module IDs and cause one runtime's entrypoint, dependencies and behavior to attach to the other's factories. This change makes module ownership resolve through (asset path, runtime, module ID) and uses collision-free tuple encoding for module and chunk lookups.

The public graph already distinguishes module identities by runtime namespace. This PR makes lookup and finding ownership consistent with those identities, while retaining shared module resolution across chunks of the same runtime.

Problem and expected behavior

Consider two registrations in bundle.js, one named webpackChunkAppA and another named webpackChunkAppB. Both define module 1, which requires module 2 and calls a different endpoint. The graph creates four distinct module nodes, but the lookup used to connect them previously stored only the asset path and module ID. Registering AppB overwrote AppA's entries.

The observable contradiction was an AppA entry edge with runtime: "webpackChunkAppA" and resolution_status: "resolved" pointing at a node with namespace webpackChunkAppB:module. The call to /a retained its AppA source range but originated at AppB module 1. Both require operations could resolve through AppB's 1 and 2 factories. Successful graph construction and complete coverage did not disclose this incorrect attribution.

The expected invariant is straightforward: every bundled finding belongs to its recovered factory's runtime, and a runtime's entry or require lookup may select only that runtime's modules. Registrations in different chunks of the same runtime still share their module namespace. Registration order must not change this meaning.

The identity tuple also needs an unambiguous encoding. A runtime string ending in \0x and a module string beginning with x\0 can collide if variable-length fields are joined with NUL. The added regression includes those strings and analogous chunk keys, so runtime separation covers the actual source-string domain rather than only conventional identifier spellings.

Change and scope

The change starts at the producer instead of recovering ownership from graph labels later, following the existing architecture ownership rules and behavioral testing guidance.

javascriptStaticAnalysisState.ts adds runtime to JavaScriptModuleRange. javascriptStaticAnalysisBundler.ts passes the registration's runtime into factory recovery, including the existing esbuild wrapper runtime names. Each indexed factory range now contains the identity context needed to attribute expressions encountered during the shared traversal.

javascriptStaticAnalysisFindings.ts attaches module_runtime when finalizing a finding inside a recovered factory. Findings outside factories retain their previous shape. javascriptStaticAnalysisTypes.ts and electronStaticAnalysisTypes.ts declare the field as optional, allowing existing internal finding values to remain representable without claiming a runtime they do not contain. The existing range index and its overlap precedence are unchanged.

The application projection consumes that same ownership in every affected path:

  • JavaScriptArtifactGraphContext.ts encodes module and chunk lookup tuples with the existing compositeKey utility. sourceNodeFor requires runtime when selecting a recovered bundled module.
  • JavaScriptArtifactGraphBundlers.ts registers and resolves modules using the registration runtime, including runtime entry loads.
  • JavaScriptArtifactGraphFindings.ts carries runtime into reference, endpoint, storage and discovered-role ownership. Require targets use the source finding's runtime; asynchronous chunk candidate selection also filters by that runtime before using the chunk lookup.
  • ElectronBoundaryGraphContext.ts shares the same source lookup. ElectronBoundaryGraphWindows.ts, ElectronBoundaryGraphIpc.ts and ElectronBoundaryGraphNative.ts pass runtime for windows, bridge APIs, utility processes, IPC operations, sender validations and native-addon findings.

The remaining two files provide the behavioral regression and strengthen the existing producer coverage. These 14 files implement one ownership correction across the producer and its consumers; there is no new service, dependency or alternate graph-building path.

This does not add cross-file runtime reconstruction or change ordinary source-module resolution. If an older internal finding lacks runtime, it cannot select a bundled module by ID alone. Existing unresolved-reference projection remains available, rather than confidently choosing another runtime's factory.

Contract and boundary impact

  • Semantic owner and earliest changed stage: Factory recovery owns the registration runtime. Its indexed range now retains that ownership before static finding finalization; application and Electron projection consume it.
  • CLI and MCP/tool-catalog contract: No request, operation, public JSON Schema or tool-catalog changes. The existing analyze-javascript-application output has corrected relationship ownership. module_runtime is intermediate static-analysis data and is not added to the public normalized result schema.
  • Provider, bridge, target-format, or platform compatibility: Shared static JavaScript projection covers existing Webpack/Rspack registrations and esbuild wrappers. No bridge or provider protocol changes. Validation ran on Windows; the tuple and attribution changes have no platform-specific branch.
  • Evidence, artifact, provenance, or reconstruction contract: Module nodes keep their existing runtime namespaces and artifact-bound identities. Relationships keep the original source ranges, digests and evidence kinds. Their source/target selection now agrees with the recovered runtime. Module/chunk lookup encoding is internal and does not replace public node identity formatting.
  • Process execution, authorization, cleanup, or containment impact: None. Target JavaScript continues to be parsed as data. No application factories, network calls or Electron constructors in the fixture are executed.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: None. No dependency, package version, installation logic, authored skill or tracked generated contract changes. Generated-document checks passed, and build outputs are excluded from the commit.

Evidence and regression coverage

  • Tests added or updated: tests/boundary/cli/javascriptBundlerRuntimeScopes.test.ts adds seven compiled CLI scenarios. src/domain/javascript/javascriptStaticAnalysisModuleIndex.test.ts now checks runtime as well as module key for recovered references across its existing factory-range fixture.
  • Base reproduction or other evidence: The regression fixtures reproduce incorrect ownership with colliding IDs, reversed registration order and mixed Webpack/Rspack runtimes on the affected implementation. Single-runtime, disjoint-ID and same-runtime cross-chunk controls distinguish runtime identity loss from general parsing failure. The source-string tuple fixture demonstrates why NUL-containing runtime/module keys must remain distinct. All seven scenarios pass with this correction.
  • User-visible CLI/MCP output: The new tests invoke the compiled CLI, parse its returned Evidence through the public result schema, and inspect the actual application graph. AppA's entry target and /a owner are now AppA module 1; its require target is AppA module 2. The corresponding AppB relationships stay in AppB. Storage, BrowserWindow and factory-level async-chunk relationships are checked in the same returned graph.
  • Remaining proof gaps: Verification establishes bounded static reconstruction through the compiled CLI on Windows; MCP shares the application workflow but was not separately exercised for these fixtures. The full deterministic suite remains a CI check. These fixtures do not establish arbitrary bootstrap equivalence, production incidence, or additional cross-file recovery behavior.

The seven CLI scenarios cover reused numeric IDs, reversed registrations, one runtime, disjoint IDs, mixed Webpack/Rspack runtimes, multiple chunks sharing one runtime, and delimiter-containing runtime/module/chunk strings. The existing self-reference CLI tests also run alongside them to preserve the graph's self-edge omission behavior. Existing esbuild/Vite and Electron composition tests verify the affected consumer families without introducing another fixture framework.

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

Validation used Node.js 24.18.0 and npm 11.16.0, as pinned by the repository. The branch was rebased onto main revision c19e15a2b3f09b3f693d7eab5263d83f4d2d1cd4; the CLI, source, full static and generated-document checks below were rerun on that baseline. The branch contains one focused fix commit, 294426d5.

  • npm run test:focused -- tests/boundary/cli/javascriptBundlerRuntimeScopes.test.ts tests/boundary/cli/javascriptBundlerSelfReferences.test.ts — 10 tests passed across two files: seven runtime-scope cases and three existing self-reference cases. This also built the runtime required by the compiled CLI boundary.
  • npm run test:local -- src/domain/javascript/javascriptStaticAnalysisModuleIndex.test.ts tests/composition/javascript-applications/javascriptBundlerAdapters.test.ts tests/composition/javascript-applications/electronApplicationAnalysis.test.ts — 13 tests passed across three files. The strengthened module-index assertions were also rerun successfully.
  • npm run check — passed, including typecheck, lint, resolved module boundaries, repository formatting, knip, metadata and architecture guards.
  • npm run docs:check — passed against the final implementation, including the generated catalog, skill, evidence and error-schema freshness checks.
  • npm run verify:test-discovery — passed; all 736 test files were discovered exactly once.
  • npm run verify:architecture-guards — passed across 1,025 source files.
  • git diff --check — passed. The pre-commit formatting and lint checks also passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: None. Public requests and result schemas are unchanged. Corrected graph relationships may change graph content and derived graph digests for previously misattributed bundles, which is the intended behavioral correction.
  • Real Hopper/Ghidra, browser, or OS coverage: The real compiled REA CLI was exercised on Windows with inert JavaScript fixtures, matching the static analysis boundary changed here.
  • Package or release metadata impact: None. No version bump, lockfile update, package-layout change or generated artifact is included.
  • Security, privacy, process, or containment review: Source strings remain data, including NUL-containing keys. Tuple encoding prevents distinct source identities from aliasing in lookup maps. The fix adds no target execution, external communication, credentials or filesystem mutation beyond existing test fixture materialization.

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.

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

@N0zoM1z0

Copy link
Copy Markdown
Collaborator

I am independently reviewing the frozen head 294426d5 for #1576. I will reproduce the small inert bundle on current main through the actual Linux CLI and pinned SDK MCP stdio, then verify runtime/module/chunk ownership and controls before updating or merging this PR. This extends the existing Windows CLI proof with an actual MCP check; it does not claim live Electron or arbitrary runtime execution.

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

Independent review of the final source head against current main 0d899783: the complete reviewed tree equals the source/main merge tree. All 26 affected tests across six files and eight static/documentation/architecture/discovery checks passed. Fresh compiled public CLI/pinned-SDK MCP checks passed for the original 411-byte reproduction, a 572-byte dual-runtime behavior control, a 161-byte same-runtime shared-chunk control and a corrected 356-byte NUL-key control. They preserve source bytes, complete same-version CLI/MCP results and Evidence IDs, text/structured parity and subsequent ping. Runtime entrypoints, requires and findings remain within their recovered factory ownership; same-runtime chunks still share modules. All 20 checks and both exact-source-head workflows are successful. This independently verifies static JavaScript on Linux; it does not establish live Electron/native-provider behavior.

@N0zoM1z0
N0zoM1z0 merged commit c1217e7 into morluto:main Oct 10, 2026
20 checks passed
@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: This merged while I tested, as c1217e711, and I re-ran the key checks on it. Fixed: two Webpack runtimes in one file can reuse module IDs and keep their own entries, calls and requires. My four real inputs hold no Webpack chunks, so they only show that the merged output matches main byte for byte.

I tested main 11e3fae69 and your head 294426d5f (parent c19e15a2b). Main had changed 14 files under the two JavaScript source folders since your parent. So I also ran the parent, to tell your change from main's drift. On every small case below, the parent and main behave the same. The PR then merged (1:36 PM EDT) as c1217e711, on top of 0d8997833. I built that too. It gives the same results as the head in every row below.

Case main PR
Issue repro, IDs 1 and 2 AppA entry and /a call land on AppB module 1. Coverage says complete. Each runtime links to its own modules. Complete.
Three runtimes AppA and AppB entries both land on AppC module 1. Each entry lands on its own module.
IDs overlap in part (1 to 3, 2 to 4) AppA module 1 requires AppB modules 2 and 3. AppA module 1 requires AppA modules 2 and 3.
String IDs home and util AppA entry lands on AppB home. Each entry lands on its own home.
Webpack and Rspack names Rspack entry lands on the Webpack module. Each entry lands on its own module.
Source order swapped AppB still wins. Each runtime keeps its own modules.
Real webpack 5.111.1 (MIT, LICENSE) output /a call lands on AppB. Entry link missing. Coverage partial. /a call and requires stay in AppA. Entry link still missing. Partial.
Two runtimes in two files Each runtime keeps its own modules. Each runtime keeps its own modules. Same output as the parent.
One runtime The runtime keeps its own modules. The runtime keeps its own modules. Same output as the parent.
  • You wrote that swapping the order changes the winner. On my fixtures it did not. On main, the name that sorts last wins. Source order does not matter. AppB won both ways. With names AppZ then AppA, AppZ won. Your revision 0e19db9fc also sorts registrations by runtime name, so I can't say why your swap changed the winner.
  • Real Webpack 5 output gives no entry link on main or on the PR, and coverage says partial. Its runtime calls __webpack_require__(moduleId) with a variable. The entry edge in your repro needs a literal ID, as in (req) => req(1).
  • Not changed: two esbuild __commonJS wrappers with the same key share one module node. Both use the runtime name esbuild-commonjs. A Webpack 4 style webpackJsonp global is not recovered at all. Both act the same on main and on the PR.

On my four real inputs, nothing has a Webpack or Rspack chunk, so there was nothing to re-attribute. Your head gave the same app graph ID, semantic graph ID and Evidence SHA-256 as its parent on all four. Main gave other IDs on all four, because of main's own changes. The merge c1217e711 matches main 11e3fae69 byte for byte on all four. The names, licences and IDs are in the fold.

I saw no slowdown. For the launcher, the median of 3 was 44.1 s on the parent, 45.2 s on main and 43.6 s with the PR. The other three inputs are in the fold.

Both changed test files pass on Node 22, 24 and 26 (11 tests), on the head and on the merge. Your new CLI test file fails on main in 3 of 7 cases: colliding IDs, reversed order, and Webpack with Rspack. The other 4 pass. npm run check:fast passes on a clean clone of the head and of the merge.

Not run

  • A real Webpack bundle from a shipped app. None is on this box, and the four real inputs have no chunks.
  • Run time on the merge, beyond one run per input.
  • The launcher, the 1,200 file and the N = 2,000 file over MCP. I ran MCP on four small cases and the Hermes chunk only.
  • Windows and macOS.
  • The full test suite and CI.
  • Builds on Node 22 and 26. I built on Node 24 only, and ran the tests on all three.
  • My own Electron window, storage and async chunk cases. Your test covers them, and it passes.

Thanks, dakjdakd, for the clear repro and the test that covers delimiter strings.

All variant cases

Each row ran on the parent, main and the PR. "Own" means each runtime's entry, calls and requires land on its own modules.

Case Parent and main PR
Issue repro AppA lands on AppB own
Three runtimes AppA and AppB land on AppC own
IDs overlap in part AppA requires land on AppB own
String IDs AppA lands on AppB own
Webpack 5, function(r){ return r(1); } AppA lands on AppB own
Webpack 5, real output AppA call lands on AppB, no entry link calls own, no entry link
Webpack 4 style, webpackJsonp no modules recovered same
Webpack 4 style entry [[1, 0]] no entry link, call lands on AppB calls own, no entry link
Webpack and Rspack Rspack lands on Webpack own
Source order swapped AppA lands on AppB own
Names AppZ then AppA AppA lands on AppZ own
Two files own own
One runtime own own
Same runtime, two chunks own own
Two esbuild wrappers, same key one shared node same
Real inputs: IDs and run time

The four real inputs. One is the Beyond All Reason launcher. Its code, spring-launcher, is MIT (LICENSE). Its Flathub build is GPL-2.0-or-later, as its metadata file says. One is a vendor chunk from Hermes Desktop (MIT, LICENSE). The other two are your 1,200-function file and the #1495 file with N = 2,000. None of the four has a Webpack or Rspack chunk push, and none yields a chunk node. On the 1,200 file and the Hermes chunk, main's other IDs trace to changed labels, such as :return-shapes on exposes edges.

Median of 3 runs on Node 24, in seconds. Load counts the programs that ran or waited for one of the box's 24 CPU threads. It is a one-minute average, read at the start of each run. It was 2.2 to 6.0, because I ran another test job on the box at the same time.

Input Parent main PR Peak memory, MB (parent / main / PR)
Launcher 44.1 45.2 43.6 1,629 / 1,838 / 1,673
Hermes chunk 7.8 7.9 8.0 752 / 790 / 756
1,200 file 2.9 2.9 2.9 436 / 441 / 434
N = 2,000 file 4.6 4.6 4.5 505 / 553 / 502

The runs were interleaved: parent, main, PR, input by input. The 3 runs of one input and tree differ by up to 7%. One Hermes parent run took 11.3 s, against 7.7 s and 7.8 s in the other two. I don't know why.

App graph ID, semantic graph ID, Evidence SHA-256 (of the CLI JSON), first 8 to 14 characters:

Input Tree App graph Semantic graph Evidence SHA-256
Launcher parent / PR jag_f4b950a05c jsrg_9688166e4 124ca08a
Launcher main jag_655d199efe jsrg_d777f05cc f5d38d91
Hermes chunk parent / PR jag_d6d7e759cf jsrg_9bbda37eb 9c0205dd
Hermes chunk main jag_ff416338f5 jsrg_6b592288e 0d24875e
1,200 file parent / PR jag_7954b29172 jsrg_5bf209a51 17cb50ed
1,200 file main jag_d3ec319531 jsrg_bae7769cb 007697c4
N = 2,000 file parent / PR jag_0806420630 jsrg_cf6d6cd05 fd6677be
N = 2,000 file main jag_74fb651f19 jsrg_a9ce0d978 7d7b5366

Every run of one tree gave the same bytes (3 of 3). The merge c1217e711 gave the same stdout SHA-256, Evidence ID and IDs as main on all four (one run each). Its times were 45.8 s, 7.9 s, 2.9 s and 4.7 s, in the table's row order, at a load of 5.1 to 8.2. Inputs: launcher app.asar SHA-256 595810df…5d83ad6f03 (26,870,695 bytes), Hermes chunk 8e7a4c3b…0b7f93, 1,200 file 1c6cafca…7711, N = 2,000 file f452d7d2…0e9883.

Fixtures

The issue repro, as one bundle.js, is in the issue. The other cases use the same shape with changes:

  • Three runtimes: add globalThis.webpackChunkAppC.push(...) with the same two IDs.
  • Partial overlap: AppA has modules 1, 2 and 3. AppB has 2, 3 and 4. AppA enters at 1 and requires 2 and 3. AppB enters at 2 and requires 3 and 4.
  • String IDs: the keys are "home" and "util" in both runtimes.
  • Webpack 5 push: (self.webpackChunkAppA = self.webpackChunkAppA || []).push([["a"], {...}, function(r){ return r(1); }]).
  • Webpack 4 style: (self.webpackJsonpA = self.webpackJsonpA || []).push([["a"], {...}, [[1, 0]]]). The webpackChunkAppA variant keeps the same third part.
  • Real Webpack 5: two builds with webpack 5.111.1. Each build has one runtime chunk and deterministic module IDs. The relative paths match, so both chunks use IDs 44 and 253. The two main.js files are joined into one bundle.js.
  • Two files: a.js holds AppA and b.js holds AppB.
  • Names AppZ then AppA: AppZ registers first, AppA second.
  • Two esbuild wrappers: two __commonJS({ "src/x.js"(exports, module) { ... } }) calls.
Commands
PATH=$HOME/.local/opt/node24/bin:$PATH
git archive <sha> | tar -x -C <dir>      # parent, PR head, main
npm ci && npm run build                   # fake HOME, HUSKY=0, Node 24
node scripts/rea.mjs analyze-javascript-application <dir> --artifact-format directory --json
node scripts/rea.mjs analyze-javascript-application app.asar --artifact-format asar --json
npm run test:focused -- tests/boundary/cli/javascriptBundlerRuntimeScopes.test.ts src/domain/javascript/javascriptStaticAnalysisModuleIndex.test.ts
npm run check:fast

The merge ran the same commands. Main also ran your new test file copied into its tree, with the same test:focused command. MCP runs used rea.mjs mcp with the repo's MCP client, then export_evidence_bundle. Over MCP on Node 24, four small cases gave the same app graph IDs as the CLI on all three trees. The Hermes chunk was too big for the MCP reply, and the server says so. Its exported Evidence gave the same app graph ID as the CLI.

Raw output

Tests, Node 22.23.1, 24.18.0 and 26.11.1, on the PR head: 2 files passed, 11 tests passed, on all three.

Your new CLI test file on main (Node 24):

✓ keeps source-derived runtime, module and chunk tuples collision-free
× keeps bundled relationships within their runtime for colliding module IDs
× keeps bundled relationships within their runtime for reversed registrations
✓ keeps bundled relationships within their runtime for single runtime
✓ keeps bundled relationships within their runtime for disjoint module IDs
× keeps bundled relationships within their runtime for Webpack and Rspack collision
✓ shares module IDs across chunks only within the same runtime
Tests  3 failed | 4 passed (7)

On the parent c19e15a2b the first test fails too (4 failed, 3 passed). Main already uses the collision-free key for chunks.

npm run check:fast on a clean clone of 294426d5f: typecheck and lint, 2 of 2 tasks passed, exit 0.

Issue repro on main, edges that matter:

chunk AppA --loads[bundler-entry-module, runtime=webpackChunkAppA, res=resolved]--> module AppB#1
module AppB#1 --calls--> endpoint /a
module AppB#1 --calls--> endpoint /b
module AppB#1 --imports[require, spec=2]--> module AppB#2   (two copies)

Issue repro on the PR:

chunk AppA --loads[bundler-entry-module, runtime=webpackChunkAppA, res=resolved]--> module AppA#1
module AppA#1 --calls--> endpoint /a
module AppA#1 --imports[require, spec=2]--> module AppA#2
module AppB#1 --calls--> endpoint /b
module AppB#1 --imports[require, spec=2]--> module AppB#2
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 (npm 11.16.0 on Node 24)
  • Head / base: 294426d5f / main 11e3fae69, plus the parent c19e15a2b and the merge c1217e711
  • Other: webpack 5.111.1 (MIT) built the real Webpack 5 fixture
  • Main moved to 0d8997833 during the run. That commit is Android-only. It changes no file under the JavaScript source folders, package.json or package-lock.json. The merge c1217e711 is the squash of the PR on top of it. Three of the 14 files differ from the head, because main had changed them.

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

@N0zoM1z0

Copy link
Copy Markdown
Collaborator

Merged as c1217e71 after all 20 exact-source-head checks and both workflows passed. The actual merged tree exactly matches the independently reviewed source/current-main combination, with the original author preserved and a noreply committer. All four public CLI/pinned-SDK MCP controls were rerun successfully on the merged version; source bytes, same-version full results/Evidence IDs, text/structured parity and subsequent ping are intact. #1576 is closed. No live Electron/native-provider verification is claimed.

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 area: runtime Process capture and runtime observation bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Reused module IDs across Webpack runtimes cross-wire application graph relationships

4 participants