Skip to content

perf(terminal): scan output frames by code unit, not per code point - #10915

Merged
nwparker merged 2 commits into
mainfrom
perf/terminal-frame-chunk-scan
Jul 28, 2026
Merged

nwparker merged 2 commits into
mainfrom
perf/terminal-frame-chunk-scan

Conversation

@nwparker

@nwparker nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

iterateTerminalOutputFrameChunks walked for (const part of data) — materializing a 1–2 character string for every code point and calling terminalStreamByteLength on each — while building the frame text with chunk += part.

The accumulator was never needed. chunk only ever reconstructs the contiguous substring data[chunkStart..end), and the seq arithmetic collapses algebraically:

startSeq + chunkStartOffset + chunk.length
  == startSeq + chunkStart + (end - chunkStart)
  == startSeq + end

So the loop tracks two integer offsets and emits data.slice(chunkStart, end), computing UTF-8 width inline from charCodeAt. The cap gate also short-circuits on UTF-16 length before measuring UTF-8 bytes, which is sound because UTF-8 length is never below UTF-16 length.

This was previously shelved as unshippable on the belief that the chunking loop needed per-part accumulation. It doesn't.

ELI5

To send terminal output, the app splits it into network-sized frames. It was walking the text one character at a time, making a tiny throwaway string for each one just to ask "how many bytes is this?", then gluing them back together one by one.

Now it walks the same text counting bytes as it goes and cuts the finished slice out in one piece — the string was always just a contiguous run, so there was nothing to glue.

Proof of perf improvement

config/scripts/terminal-output-frame-chunk-benchmark.mjs (new). Both arms run the complete production path (including encodeTerminalStreamText and the per-payload gate the real path runs); frames are compared by base64 + seq + opcode before timing; arms alternate lead across an even round count with per-arm medians; every frame's bytes feed a checksum so V8 can't hoist.

fixture frames before after speedup
ascii 4 KiB (typical batch) 1 0.010 ms 0.003 ms 3.1×
ascii 49152 B (at cap) 1 0.116 ms 0.032 ms 3.7×
ascii 64 KiB (batch cap) 2 1.020 ms 0.217 ms 4.7×
mixed TUI 64 KiB 2 1.780 ms 0.312 ms 5.7×
mixed TUI 64 KiB (implicit raw) 2 1.742 ms 0.288 ms 6.1×
emoji 64 KiB (4-byte) 2 0.375 ms 0.153 ms 2.5×
lone surrogates 64 KiB 4 1.306 ms 0.541 ms 2.4×
ascii 512 KiB (snapshot chunking) 11 7.496 ms 1.857 ms 4.0×

Two consecutive runs agree to within 0.1× on every row.

The claim is deliberately 2.4×–6.1×, not higher. Earlier runs produced 9–12× outliers on some rows; those aren't reproducible. The old arm allocates a string per code point, so its absolute time swings with GC (the same 64 KiB fixture varied 1.06–13.1 ms across runs). The conservative band is what reproduces.

The gate short-circuit is a large win when it fires (ASCII, the dominant terminal case) and a ~8% loss on one gate evaluation when it misses — a payload whose UTF-16 length is under the cap but whose UTF-8 length is over. Stating that explicitly rather than reporting only the wins.

Proof of zero regression

  • New equivalence test comparing against the pre-change implementation across 8 meta shapes, sizes 1 B–200 KiB, and adversarial boundaries swept through surrogate pairs and multi-byte runs at CHUNK−4 … CHUNK+4.
  • I verified this independently rather than trusting the supplied test. I transcribed the pre-change implementation verbatim from origin/main and ran my own differential harness: 400+ (data, meta) comparisons across 7 alphabets (ASCII, 2-byte, 3-byte, astral, both surrogate-range extremes, U+10FFFF) × 9 lengths × 8 meta shapes, plus a cap-straddling mixed-width sweep. 0 differences. I then confirmed that harness kills mutants — seq collapse + end → + chunkStart and surrogate width 4 → 3 both fail it.
  • Mutation testing by the author: 19 mutants, 13 killed, 6 proven equivalent (not rounded up). One survivor was a real gap — 0xdbff → 0xdbfe went undetected because no fixture used U+DBFF — and was fixed by adding coverage of both ends of both surrogate ranges.
  • Two guards (if (end === chunkStart) return null, and the if (finalChunk) checks) were found dead by instrumentation over 3,000 near-cap payloads and removed. My differential run at CHUNK sizes 1–3 — the only regime where a single code point exceeds the whole cap, which is exactly what those guards existed for — confirms both arms still agree.
  • src/main/runtime/rpc/: 80 files, 788 tests passing. pnpm typecheck clean, oxlint clean, oxfmt clean.
  • No max-lines suppression added and config/max-lines-baseline.txt is untouched. The extraction is a real seam (chunk emission plus its two types and cap gate), and methods/terminal.ts shrinks by 85 lines.

Reported, not fixed: the shouldDelayFinalSeq / delayedChunk branch is provably unreachable — past the OutputSpan early-return, rawLength === data.length holds, which makes the flag always false (brute-forced over all 288 (data, meta) shapes: 0 reached it). It was equally unreachable before this change. I kept it as defence-in-depth with the invariant documented and a test asserting it, so if a future meta shape reaches it, that test says so. Deleting correct-but-dead wire logic isn't a perf change.

Review loop count + verdict

3 loops, the last an adversarial review tasked with refuting rather than approving. It wrote its own differential harness (784,000 comparisons across parameterized CHUNK values), ran mutants the author hadn't, verified the staleness guards fire, and traced all three call sites for frequency. It found no defect.

One process note worth recording: the first draft of a benchmark staleness guard did not fire, because a comment in the implementation contained the same substring the guard searched for. Same trap as a previous round — fixed by matching the assignment form rather than a bare substring.

Verdict: ship.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 27, 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 Plus

Run ID: ca4f9ad6-6af4-4fc1-9fc0-987edd9b8a5b

📥 Commits

Reviewing files that changed from the base of the PR and between 0944fdb and 5d9766c.

📒 Files selected for processing (3)
  • config/scripts/terminal-output-frame-chunk-benchmark.mjs
  • src/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.ts
  • src/main/runtime/rpc/terminal-output-frame-chunks.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/runtime/rpc/terminal-output-frame-chunks.ts
  • src/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.ts
  • config/scripts/terminal-output-frame-chunk-benchmark.mjs

📝 Walkthrough

Walkthrough

Terminal output frame chunking is moved from the terminal RPC method into a shared module with exported metadata and frame types. The new iterator handles output-span encoding, UTF-8 byte limits, surrogate pairs, chunk splitting, and sequence assignment. The RPC batching code now consumes the shared iterator. Equivalence tests cover Unicode boundaries, metadata combinations, fuzz cases, reassembly, and sequence ordering. A CLI benchmark compares the new implementation with the legacy behavior and validates identical emitted frames.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change and testing, but it omits the required template sections Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes. Add the missing template sections with a concise summary, screenshot note, testing checklist, AI review report, security audit, and notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the terminal frame chunking optimization from per-code-point to code-unit scanning.
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 (2)
src/main/runtime/rpc/terminal-output-frame-chunks.ts (1)

46-53: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider dropping the provably dead shouldDelayFinalSeq path.

Past the OutputSpan branch rawLength === data.length always holds, so canPreserveChunkSeq === (typeof meta?.seq === 'number') and shouldDelayFinalSeq is always false — your own test at terminal-output-frame-chunks-equivalence.test.ts Line 442 asserts exactly that. The delayedChunk bookkeeping and both delayed branches (Lines 89-96, 103-110) are unreachable and cost every reader a pass to prove it. Keeping it for legacy-equivalence review is reasonable; consider removing it in a follow-up once the equivalence baseline is retired.

src/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.ts (1)

225-261: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Check the wall-clock cost of this suite on CI.

Every sweepAll runs 8 meta shapes through the legacy per-code-point accumulator (chunk += part plus a measureClipboardTextByteLength call per code point). Combined with the 200 KiB / 90 KiB fixtures here and the 800 near-cap fuzz trials × 3 metas at ~48 KiB each, this suite can dominate the unit-test run. If it exceeds a few seconds, consider trimming the largest fixtures (the cap-boundary cases already cover the splitting logic) or moving the high-volume fuzz into a separately tagged/longer-running suite.

Also applies to: 387-409


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b7aceecb-b9ff-4558-9b7f-1d8fc1d36e7b

📥 Commits

Reviewing files that changed from the base of the PR and between 0e11ec3 and 07be8f7.

📒 Files selected for processing (4)
  • config/scripts/terminal-output-frame-chunk-benchmark.mjs
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.ts
  • src/main/runtime/rpc/terminal-output-frame-chunks.ts

iterateTerminalOutputFrameChunks walked `for (const part of data)`, materializing
a 1-2 character string per code point and calling terminalStreamByteLength on
each, while accumulating the frame text with `chunk += part`.

The accumulator was never needed: `chunk` only ever reconstructs the contiguous
substring data[chunkStart..end), and `startSeq + chunkStartOffset + chunk.length`
collapses algebraically to `startSeq + end`. Track two integer offsets and emit
data.slice(chunkStart, end) instead, computing UTF-8 width inline from charCodeAt.

Also short-circuits the cap gate on UTF-16 length before measuring UTF-8 bytes,
which is sound because UTF-8 length is never below UTF-16 length.

2.4-6.1x across payload shapes, stable across reruns. This runs per terminal
output batch and per snapshot chunk.

Extracted to its own module along a real seam (the chunk-emission concern plus
its two types and cap gate); methods/terminal.ts shrinks by 85 lines. No
max-lines suppression added and the baseline is untouched.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the perf/terminal-frame-chunk-scan branch from 07be8f7 to 0944fdb Compare July 27, 2026 20:08
@nwparker
nwparker merged commit 6943638 into main Jul 28, 2026
22 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#10915)

* perf(terminal): scan output frames by code unit, not per code point

iterateTerminalOutputFrameChunks walked `for (const part of data)`, materializing
a 1-2 character string per code point and calling terminalStreamByteLength on
each, while accumulating the frame text with `chunk += part`.

The accumulator was never needed: `chunk` only ever reconstructs the contiguous
substring data[chunkStart..end), and `startSeq + chunkStartOffset + chunk.length`
collapses algebraically to `startSeq + end`. Track two integer offsets and emit
data.slice(chunkStart, end) instead, computing UTF-8 width inline from charCodeAt.

Also short-circuits the cap gate on UTF-16 length before measuring UTF-8 bytes,
which is sound because UTF-8 length is never below UTF-16 length.

2.4-6.1x across payload shapes, stable across reruns. This runs per terminal
output batch and per snapshot chunk.

Extracted to its own module along a real seam (the chunk-emission concern plus
its two types and cap gate); methods/terminal.ts shrinks by 85 lines. No
max-lines suppression added and the baseline is untouched.

Co-authored-by: Orca <[email protected]>

* fix(terminal): preserve chunk sequence rounding

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
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