Skip to content

perf(main): stop allocating a debug snapshot on every PTY delivery event - #7541

Merged
nwparker merged 1 commit into
mainfrom
nwparker/perf-pty-pressure-no-alloc
Jul 6, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/perf-pty-pressure-no-alloc

Conversation

@nwparker

@nwparker nwparker commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Part of a fresh adversarially-verified perf/memory audit (10 finders → 3-skeptic refute-by-default verify → synthesis). Survived 3/3 skeptic votes, zero-behavior-change fix.

1. Description

recordPtyRendererDeliveryPressure() runs on every PTY delivery event — per send in sendPtyDataToRenderer, per flush in flushPendingData, and per onData append. Each call invoked readCurrentPtyRendererDeliveryDebugSnapshot(), which allocates a fresh 13-field object (and walks pendingData + rendererInFlightCharsByPty), purely so four peak* fields could be read back out. Those peaks feed diagnostics only (getPtyRendererDeliveryDebugSnapshot, consumed exclusively by tests) and never affect delivery.

This change computes the four peaks inline from the same sources, dropping the per-event object allocation. The two map walks — inherent to computing the max-per-PTY peaks — remain, and they're O(active PTYs) ≈ a handful. readCurrentPtyRendererDeliveryDebugSnapshot() is untouched and still backs the debug getter when it's actually read.

2. Undeniable evidence + measurable improvement

  • Zero-behavior proof (existing coverage, no test changes): all 215 pty.test.ts tests pass, including the 6 that assert exact peak* values via getPtyRendererDeliveryDebugSnapshot(). Because the peaks are computed from the identical sources, the values are byte-identical — the existing peak assertions are the regression guard.
  • The diff is the evidence: one throwaway 13-field object per delivery event → zero. During a redraw-heavy TUI or cat of a large file, delivery events fire at display cadence per active PTY; each previously minted (and immediately discarded) a snapshot object. Attach an allocation profiler to the main process during an output flood and the readCurrentPtyRendererDeliveryDebugSnapshot allocation frames disappear.

3. ELI5

Every time a terminal delivered text, the app built a little 13-slot scorecard of debug stats, copied four numbers off it, and threw the scorecard away. We just read those four numbers directly now — no scorecard, no litter.

4. Trade-offs that regress the end experience

None. Peaks are diagnostics-only and remain byte-identical, so the debug tooling is unaffected and no product behavior changes. Honest magnitude: this is a small, steady garbage-reduction on a hot path, not a dramatic CPU win — the object is short-lived and cheap for V8's young-gen GC. It's real, free waste to remove, but I'd rank it minor rather than "OMFG."

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b7192a6a-245a-458f-88f4-444d2e7aa2ab

📥 Commits

Reviewing files that changed from the base of the PR and between 5c5f958757fccd3d66b89bbd0a3f7f90d8b4b2ee and ff87d90.

📒 Files selected for processing (1)
  • src/main/ipc/pty.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/ipc/pty.ts

📝 Walkthrough

Walkthrough

In src/main/ipc/pty.ts, recordPtyRendererDeliveryPressure() now computes peak pending and in-flight diagnostic values directly from the current counters instead of creating a full debug snapshot on each call. The updated logic still tracks pending total chars, max pending chars by PTY, and max in-flight chars by PTY. No public or exported declarations changed.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change well but omits required template sections like Screenshots, Testing, AI Review Report, Security Audit, and Notes. Restructure the PR body to match the template and add the missing sections, including testing checklist status, screenshot note, AI review report, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: removing a per-event PTY debug snapshot allocation for a perf improvement.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 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 coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/ipc/pty.ts (1)

1437-1457: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Correct, but the pending-chars loop is now duplicated with readCurrentPtyRendererDeliveryDebugSnapshot.

The inline peak computation here is semantically identical to the same loop in readCurrentPtyRendererDeliveryDebugSnapshot() (Lines 1413-1419). Since the PR's stated invariant is that peak values stay byte-identical between the two, having the loop duplicated means a future edit to one path but not the other silently breaks that invariant on a hot path.

Consider extracting a small shared helper, e.g. computePendingPeaks(): { pendingChars: number; maxPendingCharsByPty: number }, used by both functions to guarantee they can't drift.

♻️ Proposed refactor
+  function computePendingPeaks(): { pendingChars: number; maxPendingCharsByPty: number } {
+    let pendingChars = 0
+    let maxPendingCharsByPty = 0
+    for (const pending of pendingData.values()) {
+      const chars = pending.data.length
+      pendingChars += chars
+      maxPendingCharsByPty = Math.max(maxPendingCharsByPty, chars)
+    }
+    return { pendingChars, maxPendingCharsByPty }
+  }
+
   function readCurrentPtyRendererDeliveryDebugSnapshot(): PtyRendererDeliveryDebugSnapshot {
-    let pendingChars = 0
-    let maxPendingCharsByPty = 0
-    for (const pending of pendingData.values()) {
-      const chars = pending.data.length
-      pendingChars += chars
-      maxPendingCharsByPty = Math.max(maxPendingCharsByPty, chars)
-    }
+    const { pendingChars, maxPendingCharsByPty } = computePendingPeaks()
     return {
       pendingPtyCount: pendingData.size,
       ...
     }
   }

   function recordPtyRendererDeliveryPressure(): void {
     // Why: ...
-    let pendingChars = 0
-    let maxPendingCharsByPty = 0
-    for (const pending of pendingData.values()) {
-      const chars = pending.data.length
-      pendingChars += chars
-      maxPendingCharsByPty = Math.max(maxPendingCharsByPty, chars)
-    }
+    const { pendingChars, maxPendingCharsByPty } = computePendingPeaks()
     peakPendingChars = Math.max(peakPendingChars, pendingChars)
     ...
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4b11e71e-baff-4891-b998-1dd102ac24d2

📥 Commits

Reviewing files that changed from the base of the PR and between 3b081c1 and 5c5f958757fccd3d66b89bbd0a3f7f90d8b4b2ee.

📒 Files selected for processing (1)
  • src/main/ipc/pty.ts

recordPtyRendererDeliveryPressure() ran on every PTY delivery event (per
send, per flush, per onData append) and called
readCurrentPtyRendererDeliveryDebugSnapshot(), which allocates a fresh
13-field object just to read four fields back out for the peak trackers.
Those peaks feed diagnostics only.

Compute the four peaks inline from the same sources instead, dropping the
per-event object allocation. Peak values are byte-identical, so the debug
snapshot getter and its tests are unchanged.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/perf-pty-pressure-no-alloc branch from 5c5f958 to ff87d90 Compare July 6, 2026 08:33
@nwparker
nwparker merged commit 2e44f72 into main Jul 6, 2026
1 check passed
@nwparker
nwparker deleted the nwparker/perf-pty-pressure-no-alloc branch July 6, 2026 09:00
Jinwoo-H added a commit that referenced this pull request Jul 6, 2026
74 commits from main, including the STA-1278 ai-vault transcript perf work,
terminal flicker fix (#7540), renderer V8 heap raise (#7531), scrollbar
position preservation (#7472), and the per-delivery debug-snapshot
allocation removal (#7541).

Conflict resolutions (our structure, main's semantics):
- agent-detection: kept the split-module barrel; grafted main's Gemini/Pi
  title-detection refinements (path-fragment false positives, legacy Pi
  synthetic titles) into agent-title-core, dropped the superseded
  PI_IDLE_PREFIX.
- orca-runtime wait-blocked detection: kept the throttled
  scheduleWaitBlockedCheck (branch §1 optimization) and ported it to main's
  new cached TerminalTailWaitState API; main's per-chunk cached scan stays
  on the leaf mismatch path where it auto-merged. pty.tailWaitState is
  deliberately never populated on this branch (throttle owns the pty
  record), so the leaf mirror copy invalidates rather than shares — the
  fromTail exactness contract is never violated by stale state.
- recordPtyRendererDeliveryPressure: took main's allocation-free peak
  update (#7541) and derived per-pty in-flight from this branch's
  cumulative sent/acked accounting instead of the removed
  rendererInFlightCharsByPty map.
- rpc/methods/terminal detach: kept both sides — our
  flushAllAckPendingOutput and main's exitWaiterAbort release.
- pty-connection: kept our single-policy handleCommandFinished (invariant)
  alongside main's new sampleVisiblePaneForegroundAgent (bodies were
  byte-identical where they overlapped).
- e2e pressure scenarios: kept the Phase-4 hidden-gate contract assertions
  and the extracted pressure-script module; adopted main's
  MAX_WORST_KEY_LATENCY_UNDER_LOAD_MS budget.

Also documents the renderer-pull delivery watchdog in the branch guide.

Gates: typecheck clean; ipc/daemon/terminal-pane/pane-manager suites 4256
passed; both fuzz suites pass.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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.

1 participant