Repository navigation
perf(terminal): release oversized backing strings behind pending controls - #19396
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between feb81fa and 5c55b92ad41dedcc292fa0b100e1a8e398c4a62b. 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughPending ANSI, OSC status, and OSC title parsers now re-own retained UTF-16 tails when consumed input is substantially larger than the retained tail. New tests cover bounded memory retention, UTF-16 preservation, control completion, and copy avoidance. An experimental reliability gate records coverage, invariants, validation results, performance budgets, known gaps, and promotion or demotion criteria. Priority: ⬇️ Low Merge Risk: 🔵 Low · up to This change makes retained terminal control fragments own their own string storage so large PTY chunks can be released, reducing memory growth. Behavior for ordinary terminal output is unchanged. Two known follow-ups remain: one input shape (a chunk ending in a lone escape) can still hold on to its oversized buffer, and the over-limit drop path for pending status frames is not yet exercised by a test. Mergeable with owner awareness of those follow-ups. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the change, motivation, implementation, testing, limitations, and follow-up work. However, it omits several required template sections, including the linked issue, explicit visual-proof status, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the Checklist. It also uses “What this does” instead of the required “What Changed” heading. Resolution Add the missing required sections and information. Provide a linked issue after “Fixes #”. Add “Visual Proof” with Full details: Docstring CoverageExplanation Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 8 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/runtime/terminal-ansi-normalization.ts (1)
103-103: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winCopy a lone trailing escape before storing it.
Line 103 stores
combined.slice(index)when a large chunk ends in only\x1b. That one-code-unit pending tail can retain the fullcombinedbacking string. Apply the same ownership condition in this branch. Add a regression case for a large prefix followed by\x1b.Proposed fix
if (index + 1 >= combined.length) { - return { text: parts.join(''), pendingAnsi: combined.slice(index) } + const pendingAnsi = combined.slice(index) + return { + text: parts.join(''), + pendingAnsi: + combined.length > pendingAnsi.length * 2 + ? copyUtf16SuffixToOwnedString(pendingAnsi, pendingAnsi.length) + : pendingAnsi + } }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 7e3ba109-c3be-4dc1-b5d2-18bb99c0ff6d
📒 Files selected for processing (7)
config/reliability-gates.jsoncsrc/main/runtime/terminal-ansi-normalization.tssrc/main/runtime/terminal-ansi-pending-retention.test.tssrc/shared/agent-status-osc-pending-retention.test.tssrc/shared/agent-status-osc.tssrc/shared/osc-title-scan-tail-retention.test.tssrc/shared/osc-title-scan-tail.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor manifest nit inline.
Reviewed changes
- Owned-suffix release for three pending-control paths —
agent-status-osc.ts,terminal-ansi-normalization.ts, andosc-title-scan-tail.tsnow copy their retained pending tails through the existingcopyUtf16SuffixToOwnedStringonly when discarded output dominates the tail, breaking the sliced-string retention of oversized backing buffers without recopying growing fragments. - Retention test suites — three new forced-GC suites assert retained heap stays under 2 MiB while continuations complete faithfully, surrogate pairs survive, and 512-unit growth triggers no copies.
- Reliability gate — a new
terminal-performance.pending-control-storageexperimental gate records the invariant, oracle, red/green evidence, and known gaps.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| "coveredProviders": ["local", "daemon", "ssh", "remote-runtime"], | ||
| "coverageNotes": "Shared code-unit and production normalizer/parser tests cover provider-independent behavior on macOS; existing buffer contracts cover normalized output. Native execution, process ownership, wire formats and mobile UI are unchanged. Folder/git identity is not inspected by these string functions.", | ||
| "motivatingLinks": [ | ||
| "https://github.com/stablyai/orca/blob/main/src/shared/agent-status-osc.test.ts" |
There was a problem hiding this comment.
motivatingLinks points at a source test file; every other gate in this manifest links the issue or PR that motivated the work. Consider linking the tracking issue/PR here instead.
There was a problem hiding this comment.
Important
The new src/shared/own-retained-string.ts embeds a literal NUL byte in its ROUND_TRIP_PROBE string, so git classifies the file as binary — the entire primitive is invisible in the GitHub diff and in every future diff that touches it. Escape the NUL (\u0000) before merging.
Reviewed changes
- Replaced the gated block copier with an unconditional
ownRetainedStringprimitive — aBuffer.from(value, 'utf16le').toString('utf16le')round trip, resolved once behind a lone-surrogate self-check with a code-unit block-copier fallback for renderer/mobile, now applied unconditionally at all three pending-control sites (dropping the~2xdiscarded-dominates gate). - Reworked the retention tests — the three flake-prone forced-GC suites became deterministic
vi.spyOn(ownership, 'ownRetainedString')assertions, plus a single forced-GC test for the primitive itself (32 × 1 Miparents vs4 Kitails), byte-exact round-trip cases, and a Buffer-free fallback equivalence check. - Updated the reliability gate —
terminal-performance.pending-control-storagenow documents the new oracle, red/green evidence, performance budget, and known gaps.
⚠️ New primitive file is committed as binary
src/shared/own-retained-string.ts contains a raw NUL byte (0x00) inside the ROUND_TRIP_PROBE string literal, so git classifies the file as binary. git diff --stat reports Bin 0 -> 1715 bytes, and the PR diff shows "Binary files ... differ" — the 46 lines of the primitive this entire change routes through are not visible to reviewers, and every future change to the file will also render as an opaque blob.
Technical details
# Escape the NUL byte in ROUND_TRIP_PROBE so the file diffs as text
## Affected sites
- src/shared/own-retained-string.ts — `const ROUND_TRIP_PROBE = '\ud800a\udfff<0x00>漢'` (raw NUL between `\udfff` and `漢`).
## Required outcome
- The file must not contain a raw NUL byte; git must classify it as text and render its contents in the PR diff.
- Runtime behavior unchanged: the probe still exercises the lone lead surrogate `\ud800`, unpaired trail `\udfff`, NUL code unit, and a two-byte BMP char across the `utf16le` round trip.
## Suggested approach
- Rewrite the literal as `'\ud800a\udfff\u0000漢'` (escape the NUL; optionally `\u6f22` for `漢`). Behavior-identical, since a raw NUL and `\u0000` are the same code unit inside a JS string.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
cf28130 to
430a5fb
Compare
Every row in the 2000-row retained tail is sliced from the PTY chunk it arrived in, so a spinner workload — CR-redraw frames, exactly what Claude Code and Codex emit — makes a ~5 KB tail pin one whole chunk per row. Measured on 400 x 64 Ki-char chunks: a 5,090-char tail retained 37.5 MB. At 16 Ki x 1600 it was 46.9 MB. Own the two values the plain tail path actually retains, newlyCompletedLines and the partial line, at the point they enter the tail: 37.5 MB -> 0.18 MB and 46.9 MB -> 0.09 MB, with per-chunk cost unchanged within noise. The transcript keeps the same row objects, so it is covered transitively. The multiline redraw builder never slices normalizedChunk — it writes rows character by character — so only its partial line, which is re-sliced from its own row on every frame, needs owning. Owning its rows as well measured no retention gain and cost CPU on fullscreen TUI floods. Also own the wait-blocked keywordCarry: 31 characters that pinned a full lowercased copy of the chunk, per PTY. Follow-up to #19396, which introduced ownRetainedString for the much smaller pending-control fragments.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: e2b24c81-3402-41ad-b61d-be7c94e8904a
📒 Files selected for processing (9)
config/reliability-gates.jsoncsrc/main/runtime/terminal-ansi-normalization.tssrc/main/runtime/terminal-ansi-pending-retention.test.tssrc/shared/agent-status-osc-pending-retention.test.tssrc/shared/agent-status-osc.tssrc/shared/osc-title-scan-tail-retention.test.tssrc/shared/osc-title-scan-tail.tssrc/shared/own-retained-string.test.tssrc/shared/own-retained-string.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| const pending = marker + ' '.repeat(64 * 1024 - marker.length) | ||
| for (let offset = 0; offset < pending.length; offset += 512) { | ||
| process(pending.slice(offset, offset + 512)) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Exercise the over-cap branch.
pending has exactly 64 * 1024 code units, so the processor retains it because the drop condition is strictly greater than MAX_PENDING. Add one code unit before the terminator. Then assert cleanData: '\x07after', payloads: [], and lastPayloadCleanOffset: null.
430a5fb to
feb81fa
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
Every row in the 2000-row retained tail is sliced from the PTY chunk it arrived in, so a spinner workload — CR-redraw frames, exactly what Claude Code and Codex emit — makes a ~5 KB tail pin one whole chunk per row. Measured on 400 x 64 Ki-char chunks: a 5,090-char tail retained 37.5 MB. At 16 Ki x 1600 it was 46.9 MB. Own the two values the plain tail path actually retains, newlyCompletedLines and the partial line, at the point they enter the tail: 37.5 MB -> 0.18 MB and 46.9 MB -> 0.09 MB, with per-chunk cost unchanged within noise. The transcript keeps the same row objects, so it is covered transitively. The multiline redraw builder never slices normalizedChunk — it writes rows character by character — so only its partial line, which is re-sliced from its own row on every frame, needs owning. Owning its rows as well measured no retention gain and cost CPU on fullscreen TUI floods. Also own the wait-blocked keywordCarry: 31 characters that pinned a full lowercased copy of the chunk, per PTY. Follow-up to #19396, which introduced ownRetainedString for the much smaller pending-control fragments.
feb81fa to
5c55b92
Compare
There was a problem hiding this comment.
ℹ️ No new issues. The NUL-escape fix is clean and resolves the prior binary-file finding; the only thing keeping this from approval is a still-open earlier nit on
config/reliability-gates.jsonc(motivatingLinksstill points atsrc/shared/agent-status-osc.test.tsrather than the tracking issue/PR).
Reviewed changes
- Escaped the NUL byte in the round-trip probe —
src/shared/own-retained-string.tsnow writesROUND_TRIP_PROBEas'\ud800a\udfff\u0000\u6f22', so the file no longer contains a raw NUL and git renders it as a normal text diff instead ofBin 0 -> 1715 bytes. Runtime behavior is unchanged, since a raw NUL and\u0000are the same code unit inside a JS string.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…tive The pending-control ownership landed with a charCodeAt block copier (10 us at 4 Ki, 170 us at 64 Ki), so it needed a "copy only when discarded output dominates the tail" gate to stay affordable. That gate was the whole cost problem: on adversarial streams it fires every chunk and pays the slow copy (+45% on 16 Ki ANSI chunks, +81..111% on 194 Ki status chunks), and it also skipped ownership on fragments too small to be sliced strings anyway. ownRetainedString replaces it with a Buffer utf16le round trip (0.57 us at 4 Ki, 21.9 us at 64 Ki) and returns anything below V8's SlicedString kMinLength unchanged. Buffer is absent in the renderer and on mobile, so the copier is resolved once behind a lone-surrogate round-trip self-check and falls back to the block copier. With a ~1 us copy the gate is unnecessary: ownership is now unconditional at all three retention sites and the adversarial cases land within noise of the un-owned parsers. The three forced-GC threshold fixtures are replaced by one forced-GC test for the primitive plus deterministic spy assertions that each site routes its retained value through ownRetainedString. All fidelity and differential coverage is kept.
A raw NUL byte in the source made git treat the file as binary, so its diffs and blame were unreadable. Escapes are equivalent at runtime.
5c55b92 to
75400fc
Compare
Every row in the 2000-row retained tail is sliced from the PTY chunk it arrived in, so a spinner workload — CR-redraw frames, exactly what Claude Code and Codex emit — makes a ~5 KB tail pin one whole chunk per row. Measured on 400 x 64 Ki-char chunks: a 5,090-char tail retained 37.5 MB. At 16 Ki x 1600 it was 46.9 MB. Own the two values the plain tail path actually retains, newlyCompletedLines and the partial line, at the point they enter the tail: 37.5 MB -> 0.18 MB and 46.9 MB -> 0.09 MB, with per-chunk cost unchanged within noise. The transcript keeps the same row objects, so it is covered transitively. The multiline redraw builder never slices normalizedChunk — it writes rows character by character — so only its partial line, which is re-sliced from its own row on every frame, needs owning. Owning its rows as well measured no retention gain and cost CPU on fullscreen TUI floods. Also own the wait-blocked keywordCarry: 31 characters that pinned a full lowercased copy of the chunk, per PTY. Follow-up to #19396, which introduced ownRetainedString for the much smaller pending-control fragments.
…nks (#19528) Every row in the 2000-row retained tail is sliced from the PTY chunk it arrived in, so a spinner workload — CR-redraw frames, exactly what Claude Code and Codex emit — makes a ~5 KB tail pin one whole chunk per row. Measured on 400 x 64 Ki-char chunks: a 5,090-char tail retained 37.5 MB. At 16 Ki x 1600 it was 46.9 MB. Own the two values the plain tail path actually retains, newlyCompletedLines and the partial line, at the point they enter the tail: 37.5 MB -> 0.18 MB and 46.9 MB -> 0.09 MB, with per-chunk cost unchanged within noise. The transcript keeps the same row objects, so it is covered transitively. The multiline redraw builder never slices normalizedChunk — it writes rows character by character — so only its partial line, which is re-sliced from its own row on every frame, needs owning. Owning its rows as well measured no retention gain and cost CPU on fullscreen TUI floods. Also own the wait-blocked keywordCarry: 31 characters that pinned a full lowercased copy of the chunk, per PTY. Follow-up to #19396, which introduced ownRetainedString for the much smaller pending-control fragments.

ELI5
When a terminal is partway through receiving a special marker — an agent status update or a window title — and that marker gets cut in half between two batches of output, Orca has to hold onto the half it already has until the rest shows up. Because of how JavaScript stores pieces of text, hanging onto that tiny fragment could quietly keep the entire batch of output it was cut from — sometimes several megabytes — alive in memory for as long as the terminal sat idle. This change makes Orca take a small standalone copy of just the fragment, so the big batch of output behind it can be thrown away. Taking that copy turns out to be cheap enough (about a microsecond) that Orca now just always does it, instead of trying to guess when it is worth it — the guessing was what made it expensive.
What this does
bigChunk.slice(a, b)is a V8SlicedStringthat pins the whole parent. Three places keep a small fragment of a consumed PTY chunk across calls, so an idle terminal could pin megabytes:src/shared/agent-status-osc.ts— the pending OSC 9999 frame.src/main/runtime/terminal-ansi-normalization.ts—pendingAnsi.src/shared/osc-title-scan-tail.ts— the incomplete title tail.New
src/shared/own-retained-string.tsexportsownRetainedString(value), applied unconditionally at all three sites.Why the design changed
The first revision of this PR reused
copyUtf16SuffixToOwnedString, which copies unit-by-unit through an array plusString.fromCharCode(...spread). Measured (min of 12 rounds × 500, isolated processes, two-byte input with a lone surrogate):charCodeAtblock copierBuffer.from(s,'utf16le').toString('utf16le')Because the copy was slow, the first revision gated it behind "copy only when discarded content dominates the retained tail". That gate was the actual cost problem, not the copy: it fires on every chunk of an adversarial stream and pays the slow copy each time. Interleaved min-of-15 comparisons against the un-owned parsers (µs per chunk):
A second run reproduced the direction (+15.0% / +81.2% for the gate; −3.6% / −7.6% for unconditional ownership). Streams with no pending control never call the primitive at all.
So the gate is gone.
Nis already capped at 4 Ki (ANSI/title) and 64 Ki (status), and at ~1 µs per copy unconditional ownership costs less than the parser's own scan. Dropping it also removes the sub-13-unit waste:ownRetainedStringreturns anything shorter than V8'sSlicedString::kMinLength(13) unchanged, because such a slice is already flat.Bufferis unavailable in the renderer and on mobile, andagent-status-osc.tsruns in both. The copier is resolved once behind a lone-surrogate round-trip self-check and falls back to the existing block copier; a test asserts the two are byte-identical.Retention evidence
Forced-GC probe, 32 × 1 Mi parents each pinned by one 4 Ki tail:
ownRetainedString: 1.13 MB retainedTests
The three flake-prone forced-GC threshold fixtures are replaced by:
src/shared/own-retained-string.test.ts), with both an absolute bound and a relativeowned < sliced / 8bound;vi.spyOn(ownership, 'ownRetainedString')assertions that each retention site routes its retained value through the primitive on every chunk, including growing fragments.The "no repeated copy while a fragment grows" test is deleted: re-owning a growing fragment on every chunk is now the intended contract.
All fidelity and differential coverage is kept — exact UTF-16, lone and split surrogates through BEL/ST completion, introducer-preserving ANSI/title trimming at and past the cap, payload ordering, and clean-output offsets.
Red/green: removing
ownRetainedStringfromterminal-ansi-normalization.tsfails the spy assertion while all ten fidelity cases still pass, confirming the retention contract is carried by the new assertions.Validation
pnpm teston the gate's nine files: 114 passed.src/renderer/src/components/automations: 101 files / 796 tests passed (the pre-existingcopyUtf16SuffixToOwnedStringconsumer is untouched).oxlintclean;pnpm run check:code-quality:changed: 0 new findings across 8 files;pnpm tc:webclean.node config/scripts/check-reliability-gates.mjs: passed for 110 gates.Reliability gate
terminal-performance.pending-control-storageis updated to the new oracle. Execution authority, folder/git identity, wire formats and mobile UI are unchanged. Live Electron/native Linux/Windows/WSL/SSH measurement, production incidence and whole-process memory impact remain unmeasured; already-sliced provider input can hide a larger ancestor, so this is not a universal heap cap.Follow-up
The pending tails fixed here pin at most one chunk per PTY. The far larger instance of the same pattern is
appendNormalizedToTailBuffer, which retains up to 2000 rows each sliced from its chunk. That is handled in a separate follow-up PR.This PR is independent of the forward-search optimization in #19373 and the other performance fixes; its status parser retains the original terminator-search algorithm.