Skip to content

perf(main): stop a module-level Error from pinning load-time code and buffers - #27335

Closed
outof-place wants to merge 1 commit into
stablyai:mainfrom
outof-place:perf/module-error-sentinel
Closed

outof-place wants to merge 1 commit into
stablyai:mainfrom
outof-place:perf/module-error-sentinel

Conversation

@outof-place

Copy link
Copy Markdown
Contributor

ELI5

When JavaScript creates an Error, V8 remembers the call stack it was created in, including the functions on it, until someone reads error.stack. One file in main creates an Error once, while the bundle loads, and keeps it forever as a marker. Nobody ever reads its stack. So that one marker kept the whole bundle's start-up function and the 9 MiB buffer the bundle was read from alive for the life of the app. This PR creates the error only when it's thrown, so the start-up leftovers can be freed.

What Changed

Before: journal-item-appender.ts had const NOTHING_RESOLVED = new Error('journal_item_resolved_to_nothing') at module level, thrown and compared by identity. In a heap snapshot of an idle --serve main process, that Error's stack frames retain:

  • the bundle's top-level function, with 5.2 MiB of compiled code and 0.9 MiB of bytecode. That function runs once at load; without the Error, V8 drops its code after load.
  • a closure in Node's module loader (its translator, which loads Electron's main entry), whose context holds the 9.1 MiB Buffer index.js was read into.

After: the appender throws new NothingResolvedError(...) when a resolve finds nothing, and checks instanceof NothingResolvedError. A heap snapshot of the same idle process has neither the large code object nor the 9.1 MiB Buffer, and nothing retains the top-level function. An idle main process uses about 6 MiB less memory, and about 9 MiB less after a full GC.

Behavior is unchanged: a resolve that returns null still writes no row and resolves null; any other error still propagates.

Why

Alternatives considered:

  • Read NOTHING_RESOLVED.stack once at load. V8 then keeps the formatted string and drops the frames. It works, but it's a side effect a reader would delete as dead code.
  • Throw a non-Error sentinel (a Symbol or frozen object). No stack at all, but a thrown non-Error is a worse surprise if it ever escapes, and catch code that expects an Error would mishandle it.
  • A fresh Error per throw (this PR) costs one allocation on the null path, which already runs a full journal write callback. Its frames are freed with it.

I looked for other holders: in the heap snapshot after this change, nothing retains the top-level function. A search for module-level const X = new Error(...), AbortSignal.abort() or new DOMException(...) in src/main and src/shared finds none outside test harnesses.

Linked Issue

None. Found while measuring the main process's memory with no windows open.

Visual Proof

N/A: no UI or behavior change.

Testing

  • New test in journal-write-queue.test.ts: a resolved append that finds nothing resolves null, writes no row, and the next write lands. It passes before and after this change: it pins the behavior the change must keep, not the memory effect.

  • pnpm test journal-write-queue.test.ts structured-agent-session-event-sink.test.ts, pnpm tc:node, oxlint on the changed files and pnpm run check:code-quality:changed pass.

  • Heap snapshots of an idle --serve main process (pnpm run build:electron-vite, private profile, 45 s after start), before and after:

    • before: the largest InstructionStream is 5.2 MiB; its only retainer path is this Error's stack frames. A 9.1 MiB JSArrayBufferData is retained through the same frames, via the loader closure's translateContext.source Buffer.
    • after: neither object exists, and the largest InstructionStream is 176 KB.
  • Main-process footprint A/B: see Memory under Trade-offs.

  • I manually tested these changes locally (not done: only the builds, heap snapshots, A/B runs and checks above ran)

  • Automated tests added/updated, or explained why not below

AI Disclosure

Implemented with Claude Opus 5.5 via Claude Code: investigation, code, tests and measurements. A human (outof-place) directed the work.

Review

  1. journal-item-appender.ts: the error class and the instanceof check.
  2. The new test in journal-write-queue.test.ts.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Trade-offs

  • Merge risk. Low. One sentinel changes from identity to instanceof. The class is module-private, so nothing else can throw it, and every other error still propagates. The new test covers the null path.
  • Memory. Main-process phys_footprint of an idle --serve host, private profile, macOS arm64:
    • sampled over 40 s after a 60 s settle: 154.0 MiB before, 147.7 MiB after, −6.4 MiB (median of 3 runs before and 2 after);
    • after a full GC forced through the inspector, 65 s after start: 152.8 MiB before (both runs), 145.2 and 141.7 MiB after, −7.6 to −11.1 MiB. The inspector adds memory in both builds.
      The heap snapshots show 15.2 MiB becoming unreachable: 5.2 MiB code, 0.9 MiB bytecode and the 9.1 MiB read buffer. How much of that leaves the footprint, and when, depends on V8's next full GC and on how much freed heap it keeps for reuse.
  • CPU. One Error allocation per resolved append that finds nothing (a few microseconds, with a short stack). Nothing on any other path.
  • Disk. None.
  • Maintenance. +5/−3 lines and a 10-line test. The comment says why the sentinel must not be module-level, so it doesn't come back.
  • Verdict: free win. 6–11 MiB less main-process memory for every user, for one allocation on a rare path.

Notes

  • The same retention would come back from any Error, DOMException or AbortSignal.abort() created at module level in main. All of them capture a stack during load, and with it the bundle's top-level frame.
  • Cross-platform: no platform-specific code.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

🤖 Generated with Claude Code

… buffers

journal-item-appender created its "resolved to nothing" sentinel as a
module-level Error. V8 keeps an Error's captured stack frames, with
their functions, until something reads .stack, and nothing ever did.
That Error was created while index.js loaded, so its frames held:

- the bundle's top-level function, and with it 5.2 MiB of compiled code
  and 0.9 MiB of bytecode that would otherwise be dropped after load;
- Electron's loader closure, whose context holds the 9.1 MiB Buffer
  index.js was read into.

The appender now throws a fresh NothingResolvedError per null resolve
and checks it with instanceof. A heap snapshot of an idle --serve main
no longer has the large code object or the Buffer; its footprint is
6.4 MiB lower at idle and 7.6-11.1 MiB lower after a full GC.

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

coderabbitai Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e9a5c46f-24ee-4ff3-be48-9a8b0d8309a2

📥 Commits

Reviewing files that changed from the base of the PR and between a90e5d9 and fbdb95a.


📒 Files selected for processing (2)
  • src/main/native-chat/agent-session-journal/journal-item-appender.ts
  • src/main/native-chat/agent-session-journal/journal-write-queue.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.



📝 Walkthrough

Walkthrough

When resolve() returns null, appendResolved throws a new NothingResolvedError instance. Its rejection handler returns null for that error and rethrows other errors. A test checks that this result does not change the journal sequence and that a subsequent append succeeds.


Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to fbdb9

Null resolutions remain no-ops and later journal writes proceed; no concrete merge-blocking risk is established.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check Warning The description is detailed and covers the change, rationale, testing, trade-offs, and checklist. However, the required Linked Issue is explicitly listed as "None," which does not satisfy the reposito… Add a valid linked issue in the "Linked Issue" section. If the author is a repository maintainer and the exception applies, state that explicitly and explain why no issue is required.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main performance change: replacing a module-level Error that retains load-time code and buffers.
Docstring Coverage Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 2…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.

Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, trade-offs, and checklist. However, the required Linked Issue is explicitly listed as "None," which does not satisfy the repository template for outside contributors.


  • Fix all pre-merge checks with AI
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@nwparker

Copy link
Copy Markdown
Contributor

Superseded by #27342, which credits @outof-place and adopts the focused fresh-error fix with regression coverage. Independent real Electron heap snapshots show 15.19 MiB of retained startup code/bytecode/read-buffer allocations become collectible; no RSS claim. The replacement preserves journal outcomes and passes focused tests, node typecheck and quality checks. Closing this original in favor of the reviewed replacement.

@nwparker nwparker closed this Oct 11, 2026
nwparker added a commit that referenced this pull request Oct 11, 2026
Credit to outof-place for identifying the retention and proposing the focused fix in #27335. Independently validated 15.19 MiB of collectible startup allocations.

Co-authored-by: outof-place <[email protected]>
nwparker added a commit that referenced this pull request Oct 11, 2026
)

Credit to outof-place for identifying the retention and proposing the focused fix in #27335. Independently validated 15.19 MiB of collectible startup allocations.

Co-authored-by: outof-place <[email protected]>
@outof-place
outof-place deleted the perf/module-error-sentinel branch November 7, 2026 08:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants