orca icon indicating copy to clipboard operation
orca copied to clipboard

feat(diagnostics): name the nested container that grows in memory breadcrumbs

Open nwparker opened this issue 4 months ago • 2 comments

What this is

DIAGNOSTICS, not a fix. It stops no crash. Nothing here frees a byte of memory or changes any behavior a user can see. It exists so that the next renderer heap-exhaustion crash report contains the name of the container that grew.

Why

53 crash reports of renderer heap exhaustion (macOS renderer exit=5, Windows oom). Five hypothesis families were eliminated by measurement, not guessing:

  1. V8 sliced-string retention in OSC titles — overwrite-bounded; ~0.01 MiB at the production 16 KiB chunk size.
  2. Store payload caches (prCache / hostedReviewCache / settings / browserUrlHistory / openFiles) — all hard-capped; 2.94 MiB combined at the worst cardinality across all 143 reports.
  3. xterm scrollback / WebGL atlases — external ArrayBuffers, structurally invisible to usedHeapSize (3 GiB of that shape moved V8's used_heap_size by -0.2 MB); ~2.5 MB per terminal.
  4. All ~115 recurring renderer timers / rAF / self-rescheduling loops, module-level singletons, and all 161 preload ipcRenderer.on registrations — every one bounded; every visibility-gated timer is cleared on hide (window-visibility-interval.ts:41).
  5. All 22 main-process setIntervals, all 136 main→renderer channels traced into their renderer handlers, and all 64 nested Zustand containers — saturating the entire nested family at every cap simultaneously yields 205.79 MB: 5.14% of the 4007 MB peak, and a ceiling, not a rate.

The leak's measured signature, from 30,000+ memory samples across 143 crash bundles:

  • Live V8 JS objects. At the 4007 MB peak: mallocedMB median 1, blinkAllocatedMB median 25 — together 0.6% of heap. Not buffers, not DOM/Blink, not GPU.
  • Live, not garbage. used/total median 0.943, p90 1.000. V8 compacts and cannot free it. Strong references.
  • Wall-clock linear (median R²=0.973), event-independent (max event correlation r=0.21), and it runs through total idle with the window hidden. Report 4a2c1155: +1723 MB over 259 minutes while emitting zero spans.
  • Invisible to every existing breadcrumb. Slope vs domNodes -0.044, terminalElements -0.066, repos -0.021, sum-of-all-store-collections -0.442. Report a7e7f1d7: +799 MB while domNodes stayed 638→638 and terminalElements stayed 1.
  • Rate 31–161 MB/min per user (median 36.9 = 630 KB/s), constant per user (CV=0.09) but 5x between users.
  • 12 affected users; 3 of them produce 74% of reports and appear in no other cluster.

The instrumentation gap: summarizeStateCollectionSizes (renderer-memory-profile.ts:88-102) walks only top-level state keys, one level deep. That is exactly why 53 crash reports could not localize a leak they prove exists. Anything nested inside a slice value, or outside the Zustand store entirely, is invisible. diffComments has no top-level key at all.

Evidence

Real output. A store of 300 panes and 120 worktrees; between the two samples stateHistory grows 20 → 900 entries per pane (~260k newly retained objects).

Before — the existing breadcrumb, byte-identical across the growth:

BEFORE-t0  {"agentStatusByPaneKey":300,"repos":6,"worktreesByRepo":1}
BEFORE-t90 {"agentStatusByPaneKey":300,"repos":6,"worktreesByRepo":1}

After — the walker names both nested containers and the number moves 45x:

AFTER-t0   {"counts":{"agentStatusByPaneKey[].stateHistory":6000,"worktreesByRepo[][].diffComments":3600,"worktreesByRepo[]":120},"nodesVisited":8623,"truncated":false,"estimated":true}
AFTER-t90  {"counts":{"agentStatusByPaneKey[].stateHistory":270000,"worktreesByRepo[][].diffComments":3600,"worktreesByRepo[]":120},"nodesVisited":10675,"truncated":false,"estimated":true}

The path-preserving sampler reports the true 3,600 diff comments in this homogeneous fixture; the first implementation reported 569 because a high-cardinality sibling path replaced the rare path's frames.

Privacy, verbatim, on a store keyed by repo names, a branch name, and an absolute path:

PRIVACY ["settingsByRepo[].branches","draftsByBranch[].comments","pathKeyed[].files"]

Mutation testing. Twelve mutants were applied one at a time, tested, and reverted. All are killed: removing recursion, the entry budget, deadline checks, cycle/class guards, live registry reads, repeated-shape classification, the sibling-key scan, the fixed label vocabulary, or per-path sample scaling causes a focused failure.

Two mutants survived the first pass and exposed real test gaps: the entry budget had no array-only stress case, and the sibling-key test was tautological because repeated-shape classification already caught its input. Both tests now exercise the intended guard directly.

pnpm vitest run <three PR test files>
Test Files  3 passed (3)
     Tests  65 passed (65)

pnpm test
Test Files  3767 passed | 10 skipped (3777)
     Tests  39838 passed | 72 skipped (39910)

The focused files pass under raw pnpm vitest run with no special flags. The repository-wide canonical command is pnpm test, which supplies config/vitest.config.ts; bare repo-wide Vitest omits that config and fails pre-existing alias resolution, so it is not used to attribute failures to this PR.

Perf budget

This runs on the main thread of a renderer already at 95% of its heap limit, moments before OOM. It runs only on the existing memory-profile path — the existing 60s sampler, one-shot at the 60% and 80% highwater ratios, so at most twice per session. No new timer.

Measured after the final hardening, on the same realistic fixture:

Measurement Time
Existing top-level summary 0.007 ms
Walker alone 1.385 ms
Existing + walker 1.400 ms
Marginal combined cost +1.393 ms
Walker on the 300 x900 leaking fixture 1.739 ms

Allocation was re-measured with V8's allocation sampling profiler at a 128-byte interval:

existing summary       6.3 KiB/run
walker              1429.6 KiB/run
existing + walker   1442.5 KiB/run

The earlier 17.6 KiB claim was wrong; it measured retained heap after garbage collection, not transient allocation. The corrected cost is about 1.40 MiB transient per run, at most twice per session, and the walker retains none of the objects it visits.

Enforced bounds: MAX_ENTRY_VISITS=4000, MAX_KEYS_SCANNED=30000, MAX_KEYS_PER_CONTAINER=20000, depth 3, MAX_FRAMES_PER_LEVEL=128, MAX_TRACKED_PATHS=96, and a MAX_WALK_MS=25 wall-clock deadline.

The deadline exists because node budgets cannot bound wall time: for...in materializes V8's enumeration cache for the whole object before yielding its first key. A 10 x300k-key classifier fixture takes about 131 ms with the deadline and about 3.9 seconds when the deadline mutant is applied. Deadline checks cover the level loop, every entry path, key counting, repeated-shape classification, sibling-key classification, and field signatures; the residual over 25 ms is one uninterruptible V8 enumeration. Expiry always collapses labels to [].

Every exotic input tested returns without throwing: throwing Proxies, accessors, null-prototype objects, typed arrays, WeakMaps, Promises, frozen trees, cycles, and sparse arrays. Plain-object and array accessors are inspected without invocation, collection subclasses are rejected, class/DOM/React shapes are not entered, and a per-run WeakSet breaks cycles without retaining the graph after the call.

ELI5

The app keeps a big filing cabinet of state. When memory gets dangerously high we write a note listing how many folders are in each drawer. The problem: we only ever counted the drawers. If one folder inside a drawer quietly grew to a million pages, our note said "3 drawers" — same as always — and told us nothing. That's why 53 crash reports never fingered the culprit.

This adds a quick peek a few levels into each drawer and writes down the name and size of the biggest thing found: agentStatusByPaneKey[].stateHistory: 262213. It's on a strict timer and a strict budget, because the peek happens when the app is already nearly out of memory and must not be the thing that tips it over. It writes down shapes and counts only — never what's written on the pages.

Trade-offs

  • Added diagnostic cost. About 1.39 ms and 1.40 MiB of transient allocation on a realistic store, at most twice per session. The allocation is materially higher than first reported, but remains bounded and is not retained.
  • Privacy: arbitrary runtime keys cannot become labels. The final authorization boundary is a fixed, source-owned label vocabulary. Repeated entry shapes and the sibling-wide lowerCamelCase scan remain independent defense-in-depth signals that collapse dictionaries to []; expiry and unreadable shapes also collapse in the safe direction. Adversarial cases include one-entry camelCase repo names, differing-shape camelCase branch names, approved-looking runtime keys, absolute paths, and secrets.
  • This only helps NEW crash reports. It cannot retroactively explain the 53 we have. Its value is entirely forward-looking.
  • It counts entries, not bytes. A container holding 500 MB in three huge strings reports 3. Given the signature is live JS objects growing linearly, entry count is the right first probe — but not a complete one.
  • Known blind spots, stated plainly: containers deeper than 3 levels; growth in class-instance-held containers (deliberately not entered — that guard is what keeps xterm/fibers/DOM out); and module-level containers nobody registered. If the leak lives in one of those, this walker says nothing, and that itself is information.

Adversarial review

  • Privacy: found raw repo/branch/path keys reaching uploaded breadcrumbs. Added repeated-shape and sibling-wide syntax guards, then defeated both with one-entry and all-camelCase inputs; a fixed source vocabulary is now the final label boundary.
  • Deadline: found shape classification outside the node budgets. Deadline callbacks now cover every classifier loop and expire in the privacy-safe direction.
  • Safety: accessors are never invoked, collection subclasses and class/DOM/React shapes are rejected, cycles are bounded, and all traversal state is call-local.
  • Correctness: found global frame replacement drowning a rare path (diffComments: 569 instead of 3,600). Frames are now retained and scaled per path.
  • Tests: twelve manually applied mutants are killed; focused raw Vitest, the canonical full suite, typecheck, and the full lint/reliability/max-lines pipeline pass.
  • Perf: corrected the misleading retained-heap allocation claim to a V8-sampled ~1.40 MiB transient allocation per run.

Note on process: there is no /perf skill in this environment. The performance review above was a manual one — reading every loop for accidental quadratics and measuring cost, allocation and worst-case wall time directly. Saying so plainly rather than implying a tool run.

Next step

This is instrumentation, not a diagnosis. The fastest path to the actual bug is a real heap snapshot: three users (codeg, seankwon, riccodecarvalho) reproduce reliably in 26–134 minutes and produce 74% of reports. One Developer Tools → Memory → Take heap snapshot from any of them at ~2 GB would end this investigation outright — it gives byte-level attribution and retainer chains, which entry counts cannot.

Either way, this breadcrumb should name the container on the next crash report — and if it names nothing, that eliminates the entire nested-store family in one shot, which is itself the most valuable negative result available.

Made with Orca 🐋

nwparker avatar Jul 29 '26 09:07 nwparker

Review Change Stack

[!WARNING]

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f6d31ed0-12c0-419c-9e94-6373758f835b

📥 Commits

Reviewing files that changed from the base of the PR and between 4eca7ee26de8fd066b1581f805c0b84eb42ad959 and 2cf19a7a5b2719326dd928e095c7ac1e7f391111.

📒 Files selected for processing (3)
  • src/renderer/src/lib/nested-collection-path-reporting.ts
  • src/renderer/src/lib/nested-collection-size-walker.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
📝 Walkthrough

Walkthrough

Adds a bounded module singleton size registry with error handling, finite-value filtering, and disposal. Adds privacy-safe nested container classification, sampling, path aggregation, cycle protection, and traversal budgets. Integrates nested and singleton metrics into renderer memory profiles. Instruments pull request, terminal watchdog, runtime graph, and session-tab caches, with tests covering registry behavior, traversal safety, budgets, and watchdog size updates.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it doesn't follow the required template and omits Screenshots, Testing, AI Review Report, Security Audit, and Notes. Reformat it to the template and add Summary, Screenshots, Testing checkboxes, AI Review Report with cross-platform checks, Security Audit, and Notes.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly describes the diagnostic change to nested-container memory breadcrumbs.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • [ ] Create stacked PR
  • [ ] Commit on current branch

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.

coderabbitai[bot] avatar Jul 29 '26 09:07 coderabbitai[bot]

Greptile Summary

This PR adds two purely diagnostic systems to renderer memory breadcrumbs: a bounded recursive state walker (walkNestedCollectionSizes) that names nested containers the existing one-level summary cannot see, and a module-singleton registry (registerModuleSingletonSize) that makes long-lived module-scope Maps/Sets visible. No behaviour changes; the walk runs at most twice per session on the existing memory-profile path.

  • Nested walker: BFS up to 3 levels deep with hard caps on entry visits (4 000), key scans (30 000), wall time (25 ms), and tracked paths (96). Sampling with path-preserving reservoir replacement and per-path scale-up keeps counts growing with the leak even past the budget. The fixed APPROVED_PATH_FIELD_NAMES vocabulary is the final privacy gate before labels reach crash reports.
  • Module-singleton registry: opt-in, capped at 32 names, each limited to 48 characters. Returns live .size counts at breadcrumb time with no timer or retention; errors are isolated per entry.
  • Integration: both contributors are wired into registerRendererMemoryProfileContributor in store/index.ts, and 12 module-scope Maps across PullRequestPage, sync-runtime-graph, web-session-tabs-sync, and terminal-delivery-watchdog are registered.

Confidence Score: 5/5

Purely additive diagnostic instrumentation — no renderer behaviour, user-visible logic, or existing code paths are modified.

All new code is read-only diagnostics invoked on the existing memory-profile path. The walker's budgets, deadline, cycle guard, and privacy vocabulary are correctly implemented and extensively tested. No pre-existing code is changed beyond additive registerModuleSingletonSize call sites.

Files Needing Attention: No files require special attention for correctness. module-singleton-size-registry.test.ts has a minor test-ordering fragility in the production wiring describe block.

Important Files Changed

Filename Overview
src/renderer/src/lib/nested-collection-size-walker.ts New file: bounded BFS walker with dual budgets, wall-clock deadline, WeakSet cycle guard, and per-path reservoir sampling. Implementation is thorough with correct scale propagation.
src/renderer/src/lib/nested-container-shape.ts New file: shape classifiers. Fixed vocabulary is the final privacy gate; hasRepeatedEntryShape and hasOnlyFieldNameShapedKeys are defence-in-depth with correct deadline-safe fallbacks.
src/renderer/src/lib/nested-collection-level-sampling.ts New file: per-path reservoir sampling. Round-robin replacement within a path and over-represented path eviction are both correct; scale multiplication cascades properly to children.
src/renderer/src/lib/module-singleton-size-registry.ts New file: simple opt-in registry with correct identity-guarded disposer, per-error isolation, and finite-value filtering. Cap of 32 entries prevents crowding.
src/renderer/src/lib/module-singleton-size-registry.test.ts New test file: good coverage of caps, disposers, and error isolation. The production wiring describe relies on module evaluation order being the first import; the top-level afterEach applies to this describe too, making it fragile if the module is loaded before the test runs.
src/renderer/src/store/index.ts Wires both new contributors into the existing memory-profile framework. Spread of walk.counts alongside metadata fields is safe because all path labels contain '.' or '[]' and cannot collide with the plain names used for metadata.
src/renderer/src/runtime/web-session-tabs-sync.ts Registers all four module-scope Maps including lastHostTerminalTabCountByWorktree, addressing the previously raised concern about that map's growth profile.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[walkNestedCollectionSizes] --> B{isWalkableContainer?}
    B -- No --> Z[return empty walk]
    B -- Yes --> C[describeFrame root depth=0]
    C --> D[walkLevels BFS loop]
    D --> E{budget or deadline?}
    E -- exceeded --> F[truncated=true, return]
    E -- ok --> G[compute perFrame allowance]
    G --> H[scanFrame each frame in level]
    H --> I[scanFrameEntries array/Map/object]
    I --> J[visitChild per entry]
    J --> K{isCountableContainer?}
    K -- No --> L[skip]
    K -- Yes --> M{seen WeakSet?}
    M -- cycle --> N[skip]
    M -- new --> O[createNestedCollectionChildPath]
    O -- null/too long --> P[skip]
    O -- ok --> Q[describeFrame child]
    Q --> R{depth>=1 and reportable?}
    R -- Yes --> S[addNestedCollectionPathTotal]
    R -- No --> T[skip report]
    S --> U{depth < MAX_FRAME_DEPTH?}
    T --> U
    U -- Yes --> V[queueNestedCollectionFrame into next]
    U -- No --> W[leaf, done]
    V --> X[scaleNestedCollectionFrames path-level scale]
    X --> D
    D -- level empty --> Y[largestNestedCollectionPaths top-12]
    Y --> Z2[return counts + nodesVisited + flags]

Reviews (3): Last reviewed commit: "chore(diagnostics): document and complet..." | Re-trigger Greptile

greptile-apps avatar Jul 29 '26 09:07 greptile-apps

Moving this PR to draft because it has been untouched for more than 80 days (latest recorded PR activity or commit timestamp: 2026-07-30T01:22:55Z; checked on 2026-10-27). This keeps the review queue focused on active work while preserving the proposal. Please mark it ready for review when work resumes.

OrcaWin avatar Oct 27 '26 09:10 OrcaWin