Repository navigation
perf(runtime): cut main's per-chunk terminal tail scanning cost - #27170
outof-place wants to merge 1 commit into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
📝 Walkthrough
Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to The inspected paths preserve split escape sequences and do not expose a sentinel-index regression. No actionable merge risk remains after normal checks. Pre-merge checks |
|
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:
af698b29-06b1-4ba4-a3f9-9143ff34e26e
📥 Commits
Reviewing files that changed from the base of the PR and between f307391 and 6b6fc943cc9c53bd45ff8d737c18556c53632cdf.
📒 Files selected for processing (7)
src/main/runtime/terminal-ansi-normalization.tssrc/main/runtime/terminal-tail-line-controls.tssrc/main/runtime/terminal-tail-sentinel-index.test.tssrc/main/runtime/terminal-tail-sentinel-index.tssrc/shared/own-retained-string.test.tssrc/shared/own-retained-string.tssrc/shared/terminal-osc133-carry-retention.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| return null | ||
| } | ||
| return { kind: 'other', endIndex: escapeIndex + 1 } | ||
| return escapeIndex + 1 |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Keep intermediate escape sequences pending until their final byte.
The classifier marks ESC ( as intermediate, but this return treats ESC ( as complete. As a result, normalizeTerminalChunk('\x1b(B') emits B instead of removing the complete designation sequence. If a chunk ends at ESC (, the function also loses the pending sequence. Scan intermediate sequences through their final byte, and return -1 when that byte has not arrived.
Main normalizes every PTY chunk and folds it into a retained text tail for previews, waits and blocked-prompt detection. Under heavy output that work costs about as much as main's terminal emulator. - Split tail lines with indexOf instead of a per-code-unit walk. - Normalize with charCodeAt and spans; build CSI params only for the six finals the preview keeps. - Defer the blocked-sentinel index until the throttled wait check reads it, so rows a flood evicts before that read are never tested. Entries carry match positions, never an earlier tail array, so retained memory is unchanged. Output is unchanged: a fuzz of 400k random escape sequences gives identical normalize, parse, vertical-control and split results. Co-Authored-By: Claude Opus 5.5 <[email protected]>
6b6fc94 to
1e944bf
Compare
|
Superseded by #27344, crediting @outof-place. Exact replay found this PR’s newline splitter 4.75x slower on dense blank lines and duplicate scans of retained cursor parameters. The replacement changes only normalization, keeps line splitting/tail indexing behavior, and improves captured Codex tail-processing CPU by about 68% with parity/adverse-input checks and 210 tests. Closing this original in favor of the narrower reviewed change. |
Adapted from outof-place normalization work in #27170. Preserve tail behavior while avoiding repeated CSI scans and newline-density regressions. Co-authored-by: outof-place <[email protected]>
Adapted from outof-place normalization work in #27170. Preserve tail behavior while avoiding repeated CSI scans and newline-density regressions. Co-authored-by: outof-place <[email protected]>
ELI5
For every chunk a terminal prints, Orca's main process keeps a short plain-text copy of the end of the output. It uses that copy for previews,
terminal wait, and spotting agent prompts that need an answer. Building the copy was slow on fast output, about as slow as main's whole terminal emulator. This PR makes the same copy about half as expensive, with identical results.What Changed
Before: under a fast stream (a
catof a large log, or an agent TUI redrawing), main spent about as much time keeping the text tail as it spent in its terminal emulator. That cost lands on the main thread, which also forwards keystrokes and serves IPC for every other terminal.After: the tail work per MiB of output drops by about 40% for agent-TUI frames and by about half for plain log lines (micro-benchmark below). The retained tail, previews, wait states and blocked-prompt detection stay the same, and so does the memory they hold.
The mechanism, in three independent changes:
splitRetainedTerminalTailSegments) walked the chunk one code unit at a time, three times, readingvalue[index]. It now jumps between newlines withindexOf. This was the single largest cost for plain log output.normalizeTerminalChunk) readcombined[index], which creates a one-character string per code unit and allocates for every non-Latin-1 character (box drawing, spinners, emoji). It now readscharCodeAtand copies whole spans. It also sliced and regex-matched the parameters of every escape sequence, colour codes included, although only six cursor and erase finals (K A G \D C) are ever kept. Those six still go through the existing parser; every other sequence is only skipped to its end.containsTerminalVerticalLineControl` uses the same skip.Why
#27023 profiled main under a 16 MiB agent-TUI stream. The tail buffers, normalization and sentinel scans took about 13 ms/MB, as much as main's emulator (about 10 ms/MB). A new profile on current
mainpointed to the three hot spots above.Alternatives considered:
ownRetainedStringcopy. A concat-then-slice copy saved another 0.9–1.5 ms/MiB in the micro-benchmark, but each retained row then carried a sliced-string header: 17–22 more bytes per row, measured, about 40–80 KiB per terminal. A first revision of this PR shipped it; it is dropped so that memory stays flat.Linked Issue
Part of #27023 (the tail-buffer, normalize and sentinel item measured there)
Visual Proof
N/A: no UI or behavior change. Normalized text, retained tails, previews and wait states are the same, which the tests and the fuzz below check.
Testing
Equivalence fuzz (local, not committed): 400,000 random chunks built from escape fragments (CSI, OSC with BEL and ST, DCS/SOS/PM/APC, C0/C1 controls, DEL, CRLF, lone surrogates, astral characters), with and without carried pending escapes, plus 30 chunks above the 2000-line cap. The new
normalizeTerminalChunk,parseAnsiControlSequence,containsTerminalVerticalLineControlandsplitRetainedTerminalTailSegmentsreturned exactly what the previous versions return.New unit tests in
terminal-tail-sentinel-index.test.ts:Existing tests cover the rest: the sentinel index's carried-window guards and property runs, tail-buffer, redraw-window equivalence, and row retention.
Targeted suites (
pnpm test --maxWorkers=4 src/main/runtime/terminal-tail-sentinel-index.test.ts src/main/runtime/terminal-tail src/main/runtime/terminal-ansi src/main/runtime/terminal-wait): 15 files, 176 tests pass.Micro-benchmark (Electron's V8, the [Feature]: Parse local daemon terminal output in main only when main needs the model #27023 fixtures, 64 KiB chunks, the index read every 13 chunks to match the 50 ms wait-check cadence at that rate; median of 7, three interleaved runs; the final tail state hashes identically):
In-app A/B: headless E2E on minified builds; nobody used the app by hand. Each run
cats 16 MiB into a visible pane and records main'sprocess.cpuUsage()until main goes quiet, so the numbers include main's terminal emulator, IPC and stream framing, not only the tail. Runs alternated between a build ofmain(1a6d570) and a build of this branch on the same commit, n=10 each, with host load between 12.9 and 54 on 16 cores:mainUnit suites (
pnpm test --maxWorkers=4 src/main/runtime src/shared src/main/ports): 24,512 pass. The 2 failures are inrun-terminal-shell-alone.node-pty.test.tsand fail the same way on a cleanmainin this environment. The fullpnpm test,pnpm lintandpnpm buildwere left to CI.pnpm tcand the changed-code quality gate (ORCA_CODE_QUALITY_BASE=1a6d570412 pnpm run check:code-quality:changed) pass.I manually tested these changes locally (not done: only the headless E2E runs, micro-benchmarks and tests listed above ran)
Automated tests added/updated, or explained why not below
AI Disclosure
Implemented with Claude Opus 5.5 via Claude Code: profiling, code, tests and measurements. A human (outof-place) directed the work.
Review
Each change is independent and can be read on its own:
terminal-tail-line-controls.ts(split),terminal-ansi-normalization.ts(normalize and parse),terminal-tail-sentinel-index.ts(deferred index).Agent skill upstream boundary
Trade-offs
Merge risk. Normalization and line splitting run on every byte main receives, so a mistake would garble previews,
terminal waittext and blocked-prompt detection for every terminal. Mitigations:There is no kill switch. The change is a rewrite with identical output, not a behavior change, and a switch would keep two copies of the hot path alive; reverting the commit is the rollback.
CPU. Main: −11% on agent-TUI frames and −6% on plain logs in the app (n=10). Micro, tail plus normalize: 8.3 → 5.0 ms/MiB (agent-TUI), 10.4 → 5.0 ms/MiB (plain log).
Memory. Measured in the micro-benchmark with
--expose-gc, 16 MiB per run, three interleaved runs:Latency. Sentinel tests move from every append to the first read, the throttled wait check. That read tests the rows added since the last read: at most the 2,000 retained rows (
MAX_TAIL_LINES), measured at 0.21 ms p50 and 0.23 ms p90 in the micro-benchmark. The wait check runs at most every 50 ms, and nothing waits on it per keystroke.Disk. None.
Maintenance. +129/−87 lines in three source files and +38 lines of tests. One new concept: an index entry's tested-row count. One coupling:
isTerminalPreviewLineControlFinallists the six finalsisTerminalPreviewLineControlcan keep, so the two must change together; a comment ties them.Verdict: free win. Main CPU drops, memory is flat, and output is identical.
Notes
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)🤖 Generated with Claude Code