Skip to content

perf(terminal): bound and de-synchronize cold-restore replay on the main process - #9990

Merged
brennanb2025 merged 4 commits into
mainfrom
fix-9971-cold-restore-replay-bound
Jul 23, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
fix-9971-cold-restore-replay-bound

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9971

Follow-up from the #9441 / #9446 investigation.

Problem

On terminal reattach during startup restore, the main process synchronously replayed up to ~5 MB of persisted history per session through a HeadlessEmulator, with no concurrency bound, and retained multi-MB snapshot/scrollback ANSI strings per session. A profile with dozens of restorable histories could stall startup for seconds and retain hundreds of MB.

The first implementation yielded only between persisted batches. A single batch or checkpoint seed can itself exceed the event-loop budget, so that still allowed the original long main-thread block. It also made header-only sleep/final-checkpoint restores wait behind the global replay semaphore even though they have no replay work.

Fix

  • Read checkpoint/log payloads asynchronously.
  • Admit only one scratch-emulator replay at a time.
  • Replay at most 64 Ki UTF-16 code units or 1,024 non-output operations per event-loop turn, including within one persisted record and the checkpoint seed.
  • Preserve surrogate pairs when a replay slice boundary lands inside Unicode output.
  • Bypass the replay semaphore for header-only final-checkpoint logs.
  • Bound sticky cold-restore payloads to 16 MiB aggregate with LRU eviction and renderer-ACK cleanup.

Reliability contract

  • Invariant: terminal-performance.cold-restore-replay-budget — persisted output remains correct while scratch replay concurrency, per-turn replay work, and retained sticky payload bytes remain bounded; header-only restores do not queue behind replay work.
  • Failure source: Bound and de-synchronize terminal cold-restore replay on the main process #9971, following the startup-load report in [Bug]: macOS app exits during startup when restoring a persisted profile (v1.4.146) #9441.
  • Oracle: deterministic tests pause setImmediate during two large single-batch restores, require exactly one admitted replay/yield at a time, preserve an emoji split at the slice boundary, and require a concurrent header-only checkpoint restore to complete. Cache tests cover LRU/oversize behavior and ACK cleanup.
  • Gate: new experimental/partial entry in config/reliability-gates.jsonc.
  • Coverage: daemon-backed local restore is covered on macOS. The WSL-aware code path is exercised at unit level, but live WSL plus Linux/Windows startup-scale runs remain gaps. SSH, remote-runtime, relay, and mobile do not use this local daemon history reader and are unaffected.
  • Performance budget: one replay globally; 64 Ki/1,024 operations per turn; 16 MiB sticky payload cap; header-only restores consume no replay slot. No polling, subprocesses, session inventory, or renderer wake loops were added.
  • Diagnostics: the reliability-gate assertions identify admission, slice-boundary, output-correctness, bypass, and retained-byte failures independently.
  • Residual gaps: log decoding and final headless snapshot serialization remain synchronous inside the one-at-a-time slot; no live Electron startup test yet covers dozens of near-cap histories.

Verification

  • Focused cold-restore gate: 5 files, 150 tests passed in 5.68s.
  • pnpm run typecheck passed.
  • Targeted oxlint and formatting passed.
  • Reliability manifest and max-lines ratchet checks passed.
  • An expanded concurrent run passed 486 tests and timed out in two unrelated timing-sensitive tests while contending with the full TypeScript build; both timed-out tests passed alone in 33ms.
  • Whole-repo pnpm run lint reaches a pre-existing unrelated switch-exhaustiveness error in src/renderer/src/components/skills/skill-freshness-group.tsx:101; changed-file lint is clean.

@coderabbitai

coderabbitai Bot commented Jul 22, 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: 1c858258-d052-40db-b553-b77510fa48a9

📥 Commits

Reviewing files that changed from the base of the PR and between 42218e3 and 09c1a01.

📒 Files selected for processing (1)
  • config/reliability-gates.jsonc
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/reliability-gates.jsonc

📝 Walkthrough

Walkthrough

Cold restore detection now uses asynchronous filesystem access and serialized replay admission. Replay output is written through budgeted, UTF-16-safe chunks with yielding, while header-only checkpoint restores bypass replay. Sticky cold-restore payloads use a byte-bounded LRU cache with cleanup callbacks. Adapter and restore tests now await detection, and new tests cover replay serialization, checkpoint-only bypass, cache eviction, and renderer acknowledgment cleanup.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: bounded, async cold-restore replay on the main process.
Description check ✅ Passed The description covers the problem, fix, reliability contract, and verification, though some template sections are omitted.
Linked Issues check ✅ Passed The changes satisfy #9971 by adding async replay, bounded concurrency, cache byte limits, eviction cleanup, and header-only bypass behavior.
Out of Scope Changes check ✅ Passed The modified files are all directly tied to cold-restore replay throttling, cache bounding, and their supporting tests/config.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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: Pro

Run ID: 097a8b3c-cf08-48af-ab22-07c7d95ba498

📥 Commits

Reviewing files that changed from the base of the PR and between 53e018a and 846ad26.

📒 Files selected for processing (10)
  • config/reliability-gates.jsonc
  • src/main/daemon/cold-restore-payload-cache.test.ts
  • src/main/daemon/cold-restore-payload-cache.ts
  • src/main/daemon/cold-restore-replay-writer.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/hibernation-cold-restore-repro.test.ts
  • src/main/daemon/history-reader.test.ts
  • src/main/daemon/history-reader.ts
  • src/main/daemon/terminal-history-incremental-restore.test.ts

…ory file limits

Semantic resolutions where #10179 bounded the same reads this PR made
asynchronous:
- add async variants of the bounded terminal-history readers and use them
  for checkpoint.json, output.log, and legacy scrollback.bin so the reads
  are both off-thread and size/JSON-structure capped
- keep the header-only stat bypass ahead of the replay semaphore; the
  bounded log read now rejects oversized logs inside the slot
- daemon-pty-adapter keeps the shared ColdRestorePayload type from
  cold-restore-payload-cache alongside main's PtyProcessListAdmission
- await the now-async detectColdRestore in main's history-reader-memory
  tests
- extract the legacy scrollback restore path into
  terminal-history-legacy-scrollback-restore.ts to stay within max-lines
@brennanb2025
brennanb2025 merged commit fbd5c61 into main Jul 23, 2026
8 checks passed
nwparker added a commit that referenced this pull request Jul 24, 2026
This reverts commit 8f40ddf (#10179).

Rebased on current main. The revert applied cleanly across the vast majority
of the 1,626-file PR; the remaining work was preserving PRs that had been built
on top of #10179 after it merged. All are preserved:

- #9990  perf(terminal): cold-restore replay
- #10213 fix(codex): TUI settings promotion
- #10135 fix(mobile): images in native chat
- #9387  fix(status-bar): Resource Manager badge + concurrent listSessions
- #9853  fix(app): bound wake/quit paths (phone-session-ended freeze)
- #10237 fix(claude-accounts): quote claude path for Windows (kept shell:false)

Because those PRs were written against helper modules/APIs that #10179
introduced, the minimal, typecheck-verified closure they depend on is kept so
the tree builds and every later-PR test passes:

- bounded file/JSON readers used by #10213/#9990 (agent-state-file-reader,
  node-bounded-file-reader, json-text-structure-limit, terminal-history limits)
- claimed-agent-pty-owner cap API + pty:listSessions admission (#9990/#9387)
- the mobile-E2EE outbound-memory-budget subsystem #9853 builds on
  (e2ee-channel, mobile-e2ee-*, ws-outbound-backpressure-queue,
  remote-runtime-request-frames/-memory-limits, map-with-concurrency, e2ee-crypto)

Everything else #10179 added (~555 files) is deleted; every file it modified
elsewhere is restored to its pre-#10179 state.

Verified: root typecheck (node+cli+web), mobile typecheck, full root test suite,
full mobile test suite, oxlint, localization catalog + coverage, reliability
gates, max-lines ratchet, and the CLI emit build all pass. Two checks fail only
locally and fail identically on clean origin/main (this clone's git-tag
namespace for verify:skill-bundle-manifest; an inherited GIT_CONFIG_* env for
one relay test) — both pass on a clean CI environment.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ain process (stablyai#9990)

* fix(terminal): bound cold restore replay

* fix(terminal): bound cold restore replay slices

* perf(terminal): avoid rescanning cold restore payloads
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.

Bound and de-synchronize terminal cold-restore replay on the main process

1 participant