Repository navigation
perf(terminal): scan output frames by code unit, not per code point - #10915
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughTerminal 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)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 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.
🧹 Nitpick comments (2)
src/main/runtime/rpc/terminal-output-frame-chunks.ts (1)
46-53: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider dropping the provably dead
shouldDelayFinalSeqpath.Past the OutputSpan branch
rawLength === data.lengthalways holds, socanPreserveChunkSeq === (typeof meta?.seq === 'number')andshouldDelayFinalSeqis alwaysfalse— your own test atterminal-output-frame-chunks-equivalence.test.tsLine 442 asserts exactly that. ThedelayedChunkbookkeeping 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 valueCheck the wall-clock cost of this suite on CI.
Every
sweepAllruns 8 meta shapes through the legacy per-code-point accumulator (chunk += partplus ameasureClipboardTextByteLengthcall 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
📒 Files selected for processing (4)
config/scripts/terminal-output-frame-chunk-benchmark.mjssrc/main/runtime/rpc/methods/terminal.tssrc/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.tssrc/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]>
07be8f7 to
0944fdb
Compare
Co-authored-by: Orca <[email protected]>
…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]>
Description
iterateTerminalOutputFrameChunkswalkedfor (const part of data)— materializing a 1–2 character string for every code point and callingterminalStreamByteLengthon each — while building the frame text withchunk += part.The accumulator was never needed.
chunkonly ever reconstructs the contiguous substringdata[chunkStart..end), and the seq arithmetic collapses algebraically:So the loop tracks two integer offsets and emits
data.slice(chunkStart, end), computing UTF-8 width inline fromcharCodeAt. 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 (includingencodeTerminalStreamTextand 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.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
origin/mainand 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 → + chunkStartand surrogate width4 → 3both fail it.0xdbff → 0xdbfewent undetected because no fixture used U+DBFF — and was fixed by adding coverage of both ends of both surrogate ranges.if (end === chunkStart) return null, and theif (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 typecheckclean, oxlint clean, oxfmt clean.max-linessuppression added andconfig/max-lines-baseline.txtis untouched. The extraction is a real seam (chunk emission plus its two types and cap gate), andmethods/terminal.tsshrinks by 85 lines.Reported, not fixed: the
shouldDelayFinalSeq/delayedChunkbranch is provably unreachable — past theOutputSpanearly-return,rawLength === data.lengthholds, 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 🐋