Skip to content

fix(analysis): append large inventories without exceeding call-argument limits - #8568

Closed
kaoru0822-kitauji wants to merge 10 commits into
mainfrom
fix/8545-bulk-append-overflow
Closed

kaoru0822-kitauji wants to merge 10 commits into
mainfrom
fix/8545-bulk-append-overflow

Conversation

@kaoru0822-kitauji

@kaoru0822-kitauji kaoru0822-kitauji commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

What broke: Several owners appended a data-sized collection with target.push(...items) (or spread it into splice, Math.max/Math.min or a variadic helper). Above roughly 125,000 elements V8 runs out of stack for the arguments, so valid large inputs failed with RangeError: Maximum call stack size exceeded: managed/native verification exited with execution_failure, and import-reference-source exited with UNKNOWN.
Fix: Add one domain helper, appendAll(target, items), which appends in place and in order without turning elements into arguments. Use it at every production push/splice spread site, remove the data-sized Math.max/Math.min and variadic spreads, and add the lint rule rea/no-bulk-append-spread so the pattern cannot come back.
Risk: Low per site. Each edit is mechanical, the append order is the same, and appending an array to itself still duplicates it. The diff is wide (72 production files), so merge conflicts with in-flight PRs are the main cost. One line overlaps the draft #8457 (InvestigationEvidence.ts).

Summary

Fixes #8545.

Inputs that existing budgets admit now complete instead of overflowing the engine stack. A real resource allowance still refuses with its typed failure and its actual bound. This change adds no new inventory cap.

Problem and expected behavior

Spreading an array into a call passes every element as a separate argument, so array cardinality becomes argument count. At about 125,000 arguments V8 throws RangeError; I measured 124,517 for push at top level under Node 26.5. On base:

  • verify-managed-native-boundaries with authenticated Mach-O Evidence holding 130,000 exports exits 1 with generic execution_failure and rea doctor guidance (collectNativeSymbols).
  • import-reference-source <root> --detail summary --json on a directory with 130,000 empty child directories exits 1 with {"code":"UNKNOWN","message":"Maximum call stack size exceeded"} (ReferenceSourceReaderEntries).
  • DirectoryArtifactReader.entries with a 130,000-entry allowance lists every child, then throws RangeError while it schedules them (DirectoryArtifactReader.ts:301).
  • JavaScript export-binding selection (semanticRuntimeExportValueSources) throws on export const [v0, …, v129999] = … when the Electron app-path predicate inspects the export.

Expected: these inputs complete within their existing budgets, and smaller selected allowances still refuse with a typed failure.

Change and scope

  • src/domain/arrayAppend.ts: appendAll(target, items). It reads the length once and pushes element by element. It makes no intermediate copy and has the same order and self-append behavior as a spread.
  • Converted every production push(...x) site (about 110) and the five Ghidra splice(0, n, ...x) replacements, which now use a local replaceLimitations. Data-sized sites include native symbols, directory scheduling, IDA/JADX pages, web-bundle observations, JavaScript fingerprints and loader queues, dylib edges and process trees. Converting the small sites as well keeps the rule simple and stops the bound from depending on producers outside the call site.
  • Removed other data-sized argument expansion:
    • the Electron export generator spread, now a for…of loop;
    • the variadic enqueue/enqueueAt loader queue in javascriptSemanticRequireOrigin.ts, which now takes an array;
    • Math.max/Math.min over observed tool groups and write history in environmentManifestRules.ts, EnvironmentStateWriteSimulation.ts and environmentStateWriteAttribution.ts, now loops.
  • Lint guard rea/no-bulk-append-spread (scripts/lint/rules/): it rejects spread arguments to push/unshift/splice in src/**/*.ts, excluding tests and fixtures. It looks through optional chains, parentheses and TypeScript wrappers (!, as, satisfies, <T>) around the callee. The rule is documented in docs/testing.md.
  • Left alone, because the spread is structurally bounded well below the limit:
    • unshift of symlink-target segments in dyldPaths.ts and ElectronFusePath.ts, where readlink text is bounded by the host's PATH_MAX;
    • Uninstall.ts unshift, one item per literal name;
    • the byte pushes in artifactPathSyntax.ts and the GDB string decoder, at most four UTF-8 bytes per code point.
    • Each of these carries a disable comment that names its bound.
  • Not covered by the rule but audited:
    • Math.min/Math.max over at most 128 FAT slices, known Bun record sizes, repo-authored tool schemas, the ESP chip table and Devicetree two-element tuples;
    • String.fromCharCode over a 255-byte DfuSe field, a FIT prefix of at most 4,096 bytes, an S0 header of at most 255 bytes, and Android JNI 4,096-unit chunks;
    • rest-parameter forwarding of fixed-arity calls (direct analysis, ADB, server dispatch, export-text retention, sampling diagnostics, one or two SQLite parameters);
    • path join/resolve segments.
  • *.fixture.ts files are test-controlled and unchanged.

Not included: #8455 (retained Evidence closure). Its line is converted here because the lint rule covers it, but its MCP regression stays in the draft #8457.

Contract and boundary impact

  • Semantic owner and earliest changed stage: each owner's append, in domain, provider adapters and application workflows. The new appendAll lives in src/domain, so every layer can use it.
  • Contribution scope fit and linked maintainer decision: ordinary fix within existing boundaries; not applicable.
  • CLI and MCP/tool-catalog contract: no schema or catalog change. The previously failing CLI calls now return their normal results.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: unchanged. Same items in the same order. The admitted 130,000-export input verifies the same P/Invoke outcome as the 3-export control.
  • Target selection, authority, upstream behavior, and cleanup details: not applicable. Traversal cancellation and examined-entry refusals are preserved and tested.
  • Generated metadata, package, or installation impact: none.

Expected effects:

  • 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 (all regressions use 130,000 items, about 4% above the measured limit):

    • tests/boundary/cli/managedNativeVerificationLargeInventory.test.ts: public CLI with file input, 130,000 exports against the 3-export control. Summary and P/Invoke outcomes are identical apart from the native Evidence id, and the result is verified:1.
    • tests/boundary/filesystem/wideDirectoryTraversal.test.ts: one shallow tree of 130,000 empty directories, created once and removed in afterAll, shared by both traversal owners.
      • DirectoryArtifactReader: a 130,000-entry allowance lists every child. A cancellation requested after the wide listing is reported as cancelled at the next checkpoint, which comes after the children are scheduled. A 2,000-entry allowance still refuses with limit, examinedEntries: 2000, maximumEntries: 2000.
      • readReferenceSource: all 130,000 directories are read.
    • tests/boundary/javascript/wideExportBindings.test.ts: production parse plus static analysis of a 130,000-binding export gives the same app-path change as a 3-binding control. It runs in the forked boundary project because the analyzer runs on a child process main-thread stack. Worker-thread projects such as domain have a 4 MiB stack and do not reproduce it.
    • tests/evaluation/bulkAppendSpreadRule.test.ts: 24 rule cases, including callee wrapped in !, as, satisfies or <T>.
    • src/domain/arrayAppend.test.ts: order and self-append.
  • Base reproduction, with base sources and a base npm run compile:

    • managed CLI test: exit 1, execution_failure;
    • both traversal tests: RangeError: Maximum call stack size exceeded;
    • JS test: RangeError with the base javascriptModuleDeclaration.ts.
    • Direct base CLI runs printed the issue's exact execution_failure and UNKNOWN outputs.
  • Cost of the large-input tests (local macOS arm64, APFS, Node 26.5, one worker; peak = maximum RSS of the largest process; an empty vitest run is about 211 MB):

    Test Elapsed Peak RSS
    managed CLI (15.2 MB input) 1.7 s test, 2.3 s wall 324 MB
    wide traversal, both owners 33.8 s wall 509 MB
    JS export bindings 0.43 s test, 1.2 s wall 463 MB
    • Wide traversal breakdown: about 5 s creating the tree, 6.2 s artifact reader, 17.3 s reference reader, about 4 s removing it. APFS metadata calls dominate; Linux CI filesystems are expected to be much faster, but this was not measured.
    • The managed CLI child alone took 0.95 s and 313 MB.
  • User-visible CLI/MCP output: the managed and reference-import commands now exit 0 with their normal results. For example, the 130,000-directory import-reference-source --detail summary reports counts.directories: 130000.

  • Remaining proof gaps:

    • The reference-import regression is at the reader boundary, not the CLI: the full CLI took 21.4 s with a peak RSS of about 1.0 GB, mostly graph projection. I ran that command by hand on the fixed build; it printed the normal summary with entry_count: 130000.
    • MCP admits these managed inputs only with a larger REA_MCP_MAX_INPUT_ELEMENTS. Under the default allowance it refuses before execution with a typed resource_constraint, so MCP was not run for the large case.
    • A full Electron application CLI analysis of the wide export was not run: semantic analysis of that file did not finish within 3 minutes.

Boundary regressions: large or wide inventories at the producer, a typed capacity refusal at the selected bound, and cancellation after the wide stage. No lifecycle ownership changed.

  • 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

  • The four regression files above, against the fix: pass. Against base sources and a base build: fail as described.
  • npm run check:fast (typecheck, lint, module boundaries): pass, re-run after merging origin/main at 85013da0c. The rule reports no new sites in the merged sources. npx oxlint --quiet: no errors.
  • npm run format:check: pass.
  • npm run test:changed (source projects, 685 files): 14,242 pass, 4 fail. The same 4 tests fail identically on base sources on this machine: src/setupEnvironment.test.ts ×2, ZipArtifactReader zstd truncated frame, and JavaScriptRuntimeScope.cancellation.
  • Related compiled boundary suites (116 files: filesystem directory/reference/desktop/Interface Builder, CLI reference-source/managed, MCP managed/investigation, JavaScript boundary): 1,406 pass, 3 fail. The failures are environmental and outside the changed code: environmentServeRemediation gets EADDRNOTAVAIL instead of ENOTFOUND because the local resolver answers .invalid, and javascriptWorkerFinalizationCancellation ×2 hit the known Node 26 stripTypeScriptTypes transform rejection.
  • npm run test:local -- tests/conformance/readmeConsistency.test.ts: 9 pass.
  • Not run locally: npm run docs:check, because under local Node 26 stripTypeScriptTypes rejects mode transform. CI runs it on the pinned Node 24.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not run. No real Ghidra, IDA, JADX or Hopper on this machine, so the Ghidra, IDA and JADX conversions are covered only by typecheck and existing source tests. Only macOS arm64 was measured locally.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no new reads, writes or processes. Inputs that crashed now run to completion under their existing budgets.

Author readiness

Human owner: @kaoru0822-kitauji

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

🤖 Generated with Claude Code

…nt limits

Spreading a data-sized collection into push, splice, Math.max/min or a
variadic helper turns each element into a call argument. Above roughly
125,000 elements V8 runs out of stack, so admitted inputs failed with
RangeError: managed/native verification exited with execution_failure,
import-reference-source with UNKNOWN, and DirectoryArtifactReader and
JavaScript export-binding selection threw.

Add appendAll in src/domain/arrayAppend.ts, which appends in place and in
order without expanding elements into arguments, and use it at every
production push/splice spread site. Replace the data-sized Math.max/min and
variadic loader-queue spreads with loops or array parameters. Add the
rea/no-bulk-append-spread lint rule so the pattern cannot return; the few
structurally bounded spreads keep disable comments naming their bound.

Fixes #8545

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kaoru0822-kitauji kaoru0822-kitauji added bug Something isn't working track:bugs Small-bug loop track PRs labels Nov 1, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T10:55:10.585779Z e9d620b 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 Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Medium impact] The PR appears safe to merge; no actionable issue remains in the reviewed changes.

Summary

Replaces data-sized call spreads with appendAll and ordered loops, without adding an inventory cap.

  • Large inventories are appended without becoming call arguments.
  • Production lint flags spreads that pass whole collections to array methods.

Reviews (2) · Last reviewed commit: "fix(lint): see through type-only wrapper..." · Reviewed by Greptile

kaoru0822-kitauji and others added 2 commits November 1, 2026 17:02
rea/no-bulk-append-spread unwrapped only optional chains, so
`target.push!(...items)`, `(target.push as T)(...items)`, satisfies and
angle-bracket assertions reached the call with a non-member callee and
were not reported. Strip TypeScript wrapper and grouping nodes before
matching the method, and cover those forms and wrapped receivers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@morluto

morluto commented Nov 5, 2026

Copy link
Copy Markdown
Owner

Hey @kaoru0822-kitauji, thanks for this! The fix looks good. What's left: it has merge conflicts with main in src/application/native/NativeUiActionTrace.ts and src/ghidra/GhidraProviderClient.ts (merging main into the branch is fine). Happy to get this in once that's sorted out.

Keep main's newer observations and route every data-sized append through
appendAll so the bulk-spread limit still holds.
Keep appendAll at the merged Bun and capture call sites, and use the
recoverable reader limits from main.
A capture that does not record selected-path kind must not gain an
unknown kind on the export plan. An oversized Windows Ghidra endpoint
whose close fails stays an invalid endpoint and keeps that cleanup.
The export result lists task summaries on tasks. The seed-policy check
was still looking for a single task object.
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator Author

Maintenance claim: this Codex session (backlog-b4-20261112, isolated worktree /tmp/rea-backlog-b4-8568-20261112) is updating fix/8545-bulk-append-overflow from 217c84ea7bf0. Scope: merge current main, resolve conflicts using current owners, run focused regression/static checks, update validation evidence, and push normally to this PR branch. Existing readiness declarations and PR status are preserved; no scope expansion.

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 track:bugs Small-bug loop track PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Large inventories overflow bulk appends in verification and directory traversal

3 participants