Skip to content

perf(runtime): cut main's per-chunk terminal tail scanning cost - #27170

Closed
outof-place wants to merge 1 commit into
stablyai:mainfrom
outof-place:perf/terminal-tail-scan
Closed

outof-place wants to merge 1 commit into
stablyai:mainfrom
outof-place:perf/terminal-tail-scan

Conversation

@outof-place

@outof-place outof-place commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

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 cat of 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:

  • Line splitting (splitRetainedTerminalTailSegments) walked the chunk one code unit at a time, three times, reading value[index]. It now jumps between newlines with indexOf. This was the single largest cost for plain log output.
  • Normalization (normalizeTerminalChunk) read combined[index], which creates a one-character string per code unit and allocates for every non-Latin-1 character (box drawing, spinners, emoji). It now reads charCodeAt and 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.
  • Blocked-prompt sentinel index tested every newly produced row against the sentinel regex on every append. The index is only read by the wait check, which is throttled to every 50 ms, and by the per-leaf path. Each new tail array now carries the match positions of the rows it kept and how many of its rows were tested; the regex runs on the untested rows when the index is first read. Rows a flood pushes out of the tail before that read are never tested. An entry holds positions only, never an earlier tail array, so no evicted row stays alive.

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 main pointed to the three hot spots above.

Alternatives considered:

  • Lowercasing rows for the sentinel, or one regex over all new rows joined. Benchmarked; neither beat the per-row case-insensitive test, because the cost is per character, not per call. Testing fewer rows is what helps.
  • A faster ownRetainedString copy. 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.
  • One owned copy per chunk instead of per row. Fewer copies, but a long-lived row would pin every row of its chunk, so retained memory would no longer track the retained tail.
  • A case-insensitive keyword regex instead of lowercasing the wait-check window. 5–30% faster on that step, but it changes which Unicode case foldings match, so it is left out.

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, containsTerminalVerticalLineControl and splitRetainedTerminalTailSegments returned exactly what the previous versions return.

  • New unit tests in terminal-tail-sentinel-index.test.ts:

    • a read after a flood of 6000 lines tests at most the 2000 retained rows (the previous index tested 6001, so the test fails without the change);
    • six seeded random sequences that read the index only now and then: positions must equal a from-scratch scan at every read.
  • 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):

    ms per MiB normalize before after tail before after
    agent-TUI frames 3.6 1.9 4.7 3.1
    plain log lines 2.7 1.5 7.7 3.5
  • 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's process.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 of main (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:

    Fixture main This PR Change
    Agent-TUI frames 64.1 ms/MB (p25–p75 62.9–66.2) 57.2 ms/MB (56.5–57.9) −6.9 ms/MB (−11%)
    Plain log lines 50.8 ms/MB (49.0–51.9) 47.8 ms/MB (46.4–48.7) −3.0 ms/MB (−6%)
  • Unit suites (pnpm test --maxWorkers=4 src/main/runtime src/shared src/main/ports): 24,512 pass. The 2 failures are in run-terminal-shell-alone.node-pty.test.ts and fail the same way on a clean main in this environment. The full pnpm test, pnpm lint and pnpm build were left to CI.

  • pnpm tc and 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

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Trade-offs

  • Merge risk. Normalization and line splitting run on every byte main receives, so a mistake would garble previews, terminal wait text and blocked-prompt detection for every terminal. Mitigations:

    • the rewrites are output-identical, checked against the previous functions by the 400,000-chunk fuzz above;
    • the deferred index is checked by the existing carried-window guards and property runs, plus the new flood test and sparse-read property runs;
    • scope: three files in the main-side tail pipeline; no wire, schema, settings or renderer change.

    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:

    • retained tail per terminal: unchanged, 390 KiB (agent-TUI) and 256 KiB (plain log) in both builds;
    • peak heap during the run: 33.8 → 29.2 MiB (agent-TUI), 31.6 → 31.6 MiB (plain log).
  • 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: isTerminalPreviewLineControlFinal lists the six finals isTerminalPreviewLineControl can 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

  • Cross-platform, SSH and mobile. The code is platform-neutral and runs wherever main's tail runs, SSH panes included.
  • No wire, schema or settings changes.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4bd28ad0-d39e-4abb-bf21-c55777f4e36e


📥 Commits

Reviewing files that changed from the base of the PR and between 6b6fc943cc9c53bd45ff8d737c18556c53632cdf and 1e944bf.



📒 Files selected for processing (1)
  • src/main/runtime/terminal-tail-sentinel-index.ts


Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.




📝 Walkthrough
📝 Walkthrough

Walkthrough

ANSI parsing and normalization now share escape-sequence end detection. Chunk normalization preserves eligible CSI line controls and updates handling of CRLF and control characters. Terminal-tail segment scanning uses newline searches. Sentinel indexing tracks scanned rows and defers tests of new rows until a read; tests compare indexed results with full scans.



Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 1e944

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 | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 29.41% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check Passed The title clearly and concisely identifies the main performance improvement: reducing per-chunk terminal tail scanning cost.
Description check Passed The description is detailed and covers the required explanation, changes, rationale, linked issue, visual proof, testing, AI disclosure, scope, trade-offs, and checklist. It also reports known test fa…

  • Fix all pre-merge checks with AI
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

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.ts
  • src/main/runtime/terminal-tail-line-controls.ts
  • src/main/runtime/terminal-tail-sentinel-index.test.ts
  • src/main/runtime/terminal-tail-sentinel-index.ts
  • src/shared/own-retained-string.test.ts
  • src/shared/own-retained-string.ts
  • src/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

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.

🎯 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]>
@nwparker

Copy link
Copy Markdown
Contributor

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.

@nwparker nwparker closed this Oct 11, 2026
nwparker added a commit that referenced this pull request Oct 11, 2026
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]>
nwparker added a commit that referenced this pull request Oct 11, 2026
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]>
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.

2 participants