Skip to content

perf(terminal): drop the headless snapshot cache, keep the spawn lock - #17752

Merged
nwparker merged 1 commit into
mainfrom
nwparker/remove-headless-snapshot-cache
Aug 31, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/remove-headless-snapshot-cache

Conversation

@nwparker

@nwparker nwparker commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 0 $\color{#cf222e}{\Huge{\mathbf{−}}}$​230 $\color{#cf222e}{\Huge{\mathbf{−}}}$​230
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​38 $\color{#cf222e}{\Huge{\mathbf{−}}}$​202 $\color{#cf222e}{\Huge{\mathbf{−}}}$​164

ELI5

Orca got two speed fixes in #17667. One of them turned out not to earn its keep, and it was the one that cost memory — so this removes it and leaves the other alone.

The removed one remembered a picture of each terminal's contents so it wouldn't have to redraw it. Sensible idea, except reconnecting to a terminal only ever asks for the last 1000 lines, and redrawing 1000 lines is already cheap. So the remembering saved almost nothing while holding onto several megabytes per terminal, forever, for as long as that terminal existed.

The fix that's staying is the one that actually made switching worktrees faster: terminals used to reconnect one at a time, each waiting for the one before it. Now they go together. That costs no memory at all.

What this removes

The snapshot memoization from #17667 and everything serving it: the mutation epoch, markMutated/markWritten, the no-op resize gate, and the HeadlessSnapshotCache module. headless-emulator.ts returns to its pre-#17667 shape.

The shared/exclusive spawn lock from #17667 stays. It is the half carrying the measured win.

Perf differential — what is kept vs given up

Kept: the spawn lock (no memory cost)

The options phase is pure lock queueing, so it isolates the lock exactly. 4-tab worktree activation, per tab:

before #17667 after, and still true here
options 0 / 125 / 212 / 291ms 1 / 1 / 1 / 1ms
total per tab 493 / 566 / 647 / 677ms 226 / 253 / 282 / 309ms

Unaffected by this PR.

Given up: nothing measurable

Controlled A/B on merged main — same worktree, same sessions, same machine — reattach stable_adoption per session:

config per-session
cache + resize gate (as merged) 16 / 67 / 78 / 87ms
cache off, gate on 17 / 55 / 68 / 80ms
cache off, gate off 13 / 62 / 73 / 83ms

Indistinguishable; the spread between repeat samples of the same config exceeded the spread between configs. Cold 4-tab activation was likewise unchanged: 217–296ms without the cache vs 226–309ms with — expected, since a first attach is always a miss.

Why it under-delivered

The serialize is bounded by what the session retains, not by what a client asks for. A live daemon session is constructed with scrollback: resolveDaemonSessionScrollbackRows() (terminal-host-session-create.ts:126), which headless-emulator.ts:87 hands to xterm as the retained buffer capacity — DAEMON_SESSION_SCROLLBACK_ROWS = 1000, override bounded 100–5000 (daemon-session-scrollback-window.ts:8). The cap exists because unbounded retention once OOM-killed a host owning 100+ terminals.

A client may request far more — the snapshot RPC clamps requestedRows to [0, 50_000] (daemon-request-router.ts:222-225) — but it still gets only the ~1000 rows the buffer holds. So the serialize the cache was built to avoid is cheap on every live-session path.

Worse, the cache keyed on the requested value. A client asking 50,000 and one asking 5,000 produced two distinct keys for byte-identical content, thrashing a 2-entry cache (MAX_CACHED_SNAPSHOT_WINDOWS = 2). The one genuinely larger window — durable-history restore at DAEMON_RESTORE_SCROLLBACK_ROWS = 5000 (history-reader.ts:284) — builds a fresh emulator per restore and snapshots it once, which a per-instance cache is structurally incapable of helping.

The original PR optimized a serialize without first measuring how expensive that serialize is on the paths that call it.

(Earlier revisions of this description misdescribed the mechanism — first as attach "not requesting the full buffer", then as a 1000-row request window. It is a 1000-row retention cap. The conclusion was unchanged throughout; the corrected framing is stronger evidence for removal, not weaker.)

What removing it buys

  • Up to ~8MB per emulator of steady-state retention returned (4MB/entry × 2 windows), held for the session's lifetime with no aggregate budget across sessions. Sessions with a runtime-side mirror have two emulators.
  • Deletes an invalidation contract that produced three separate over-invalidation bugs during review — the zero-byte parse fence, setCwd/setLastTitle, and the no-op resize — each of which silently reduced the cache's own hit rate. That contract was convention-enforced, so every future mutator had to remember it.

If we want it back

The honest version needs an aggregate byte budget across sessions (cold-restore-payload-cache.ts already implements exactly that one directory over) and a workload where the attach-path serialize is actually expensive. Neither exists today.

Tests / risk

2972 pass across src/main/daemon and the runtime suites; pnpm tc clean; changed-code quality gate clean. Main-process/daemon only — no renderer, wire, or persisted-format change.

Removes the snapshot memoization added in #17667 and everything that served
it: the epoch, markMutated/markWritten, the no-op resize gate, and the
HeadlessSnapshotCache module. The shared/exclusive spawn lock from the same PR
stays — it is the half that carries the measured win.

Why: a controlled A/B on merged main could not show the cache paying for its
memory. Same worktree, same sessions, reattach stable_adoption per session:

  cache + resize gate (as merged)   16 / 67 / 78 / 87 ms
  cache off, gate on                17 / 55 / 68 / 80 ms
  cache off, gate off               13 / 62 / 73 / 83 ms

Indistinguishable. Cold 4-tab activation was likewise unchanged (217-296ms
without the cache vs 226-309ms with), which is expected — a first attach is
always a miss.

The reason it under-delivers is a design fact the original PR missed: attach
does not request the full buffer. terminal-host-session-create.ts passes
resolveDaemonSessionScrollbackRows() — a deliberate 1000-row live window,
capped because unbounded retention once OOM-killed a host. Serializing 1000
rows is cheap, so there was little for a cache to save on that path.

Against that, the cache retained up to MAX_CACHED_SNAPSHOT_BYTES (4MB) per
entry across MAX_CACHED_SNAPSHOT_WINDOWS (2) entries per emulator, for the
session's lifetime, with no aggregate budget across sessions. It also carried
an invalidation contract that produced three separate over-invalidation bugs
during review (the parse fence, setCwd/setLastTitle, and the no-op resize).

The lock fix is unaffected and independently measured: the `options` phase,
which is pure queueing, went 0/125/212/291ms -> 1/1/1/1ms across a 4-tab
worktree activation and stays there.
@greptile-apps

greptile-apps Bot commented Aug 31, 2026

Copy link
Copy Markdown

Greptile Summary

Removes per-emulator snapshot memoization and rebuilds snapshots directly from current terminal state, reducing long-lived memory retention while preserving the shared/exclusive spawn lock.

  • Deletes the snapshot cache implementation and its cache-specific regression suite.
  • Removes mutation-epoch invalidation from writes, resize, scrollback clearing, and restored-link updates.
  • Restores direct assembly of terminal snapshot fields in HeadlessEmulator.getSnapshot.

Confidence Score: 5/5

The PR appears safe to merge with no concrete correctness or security regressions identified.

Snapshot construction retains the prior field assembly while removing cache retention and invalidation bookkeeping; investigated resize and disposal paths did not establish a reachable failure.

Important Files Changed

Filename Overview
src/main/daemon/headless-emulator.ts Removes cache invalidation machinery and reconstructs each snapshot directly from the live headless terminal state.
src/main/daemon/headless-snapshot-cache.ts Deletes the bounded two-window snapshot cache and its cloning and invalidation behavior.
src/main/daemon/headless-emulator-snapshot-cache.test.ts Deletes tests that exclusively verified the removed snapshot cache and its invalidation contract.

Reviews (1): Last reviewed commit: "perf(terminal): drop the headless snapsh..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

HeadlessSnapshotCache and its tests were deleted. HeadlessEmulator.getSnapshot now serializes terminal state on every call and assembles the snapshot directly. Cache mutation tracking was removed from write and state-update paths. The implementation uses dedicated helpers for cursor serialization, ANSI splitting, OSC link collection, rehydrate sequences, and frame-restore fields.

Merge Risk: 🔵 Low · up to b36f1

An equal-size terminal resize may clear restored hyperlink metadata, causing rehydrated terminals to lose OSC link information in later snapshots. The risk is localized and mergeable with explicit owner follow-up to clear the metadata only when dimensions change.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, rationale, performance results, memory impact, testing, and scope. However, it does not follow the required template fully: it omits the Linked Issue section, Visu… Add the missing required template sections. Provide a linked issue in the Fixes # field, add visual proof or state N/A with a reason, document testing and platform coverage, complete the applicable AI Disclosure and review sections, add…
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 1…
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 summarizes the main change: removing the headless snapshot cache while retaining the spawn lock.
Full details: Docstring Coverage

Explanation

No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 1 files.

Full details: Description check

Explanation

The description explains the change, rationale, performance results, memory impact, testing, and scope. However, it does not follow the required template fully: it omits the Linked Issue section, Visual Proof or an explicit N/A statement, the Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

Resolution

Add the missing required template sections. Provide a linked issue in the Fixes # field, add visual proof or state N/A with a reason, document testing and platform coverage, complete the applicable AI Disclosure and review sections, address the Agent skill upstream boundary, Notes, and Checklist items, and retain the existing technical explanation.

  • Fix all pre-merge checks with AI
✨ 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/daemon/headless-emulator.ts (1)

234-234: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve restored OSC links on an equal-size resize.

At Line 234, an equal-size resize clears restoredOscLinks although the buffer coordinates do not change. collectHeadlessOscLinkRanges uses these ranges when it builds the next snapshot. A rehydrated terminal can therefore lose its restored hyperlink metadata after a no-op resize.

Keep the unconditional terminal resize if it is required, but clear restoredOscLinks only when either dimension changes.

Proposed fix
-    this.restoredOscLinks = []
+    if (cols !== this.terminal.cols || rows !== this.terminal.rows) {
+      this.restoredOscLinks = []
+    }
     this.terminal.resize(cols, rows)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 9f0024f9-bb65-4c31-872b-81ee0e274134

📥 Commits

Reviewing files that changed from the base of the PR and between 20a12a6 and b36f17e.

📒 Files selected for processing (3)
  • src/main/daemon/headless-emulator-snapshot-cache.test.ts
  • src/main/daemon/headless-emulator.ts
  • src/main/daemon/headless-snapshot-cache.ts
💤 Files with no reviewable changes (2)
  • src/main/daemon/headless-snapshot-cache.ts
  • src/main/daemon/headless-emulator-snapshot-cache.test.ts

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

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

A clean, single-commit revert of the headless snapshot cache half of #17667, keeping the spawn lock. Three files:

  • headless-snapshot-cache.ts removed — the memoized snapshot assembly module is deleted outright.
  • headless-emulator-snapshot-cache.test.ts removed — 230 lines of cache-specific tests, including the prototype-surface freeze guard that existed only to protect the now-deleted invalidation contract.
  • headless-emulator.ts restored — getSnapshot() inlines the previously cached assembly back to recompute-on-every-call, and markMutated/markWritten plus the no-op resize equality gate are removed.

The emulator file is byte-identical to its pre-#17667 state (4ca232c159^), so the change is a faithful revert rather than a reimplementation. getSnapshot's return type and shape are unchanged, so there is no renderer, wire, or persisted-format impact, and the spawn lock in worktree-terminal-mutation-lock.ts is untouched.

The only behavioral delta relative to current main is resize() returning to always clearing restoredOscLinks and always calling terminal.resize(). The equality gate was added in #17667 purely to keep the cache warm on reattach (its incidental preservation of restoredOscLinks on a no-op resize was a side effect, not the motivation); with the cache gone, restoring the pre-#17667 shape is the correct move and is long-shipped behavior rather than a new regression. No dangling references to the removed module or symbols remain in the tree, and headless-emulator.test.ts still covers getSnapshot output (OSC 8 links, alternate screen, restore round-trips) independently of the deleted cache suite.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit a5be108 into main Aug 31, 2026
35 checks passed
nwparker added a commit that referenced this pull request Sep 1, 2026
Cold restore seeded a checkpoint's OSC-8 link ranges and then replayed records
that resize, so any resize record after the checkpoint dropped them and
restored hyperlinks in scrollback lost clickability. Same-size resize records
reach the durable log routinely, because every attach re-asserts the pane's
dimensions and session-output-plane records each one without a same-size
dedupe — so an ordinary reattach was enough to lose the links.

Restored ranges are row-indexed, so clearing them on a reflow is right; a
resize to the size already applied is not a reflow. Gate on the dimensions
actually changing.

Introduced in d46349c ("fix: improve mobile link modifier handling",
#5597), which added setRestoredOscLinks along with unconditional clearing in
both resize() and clearScrollback(). clearScrollback's clearing is correct and
is unchanged, with a test pinning it.

Found during adversarial review of #17752 and filed as #17756. Not a
regression from that PR: #17667 had incidentally masked it by gating no-op
resizes to protect a snapshot cache, and removing the cache removed the gate.
The same gate returns here on its own terms — as a correctness fix with tests,
rather than as a side effect of a cache.
@AmethystLiang

Copy link
Copy Markdown
Contributor

thanks for reporting. looking into it

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#17752)

Removes the snapshot memoization added in stablyai#17667 and everything that served
it: the epoch, markMutated/markWritten, the no-op resize gate, and the
HeadlessSnapshotCache module. The shared/exclusive spawn lock from the same PR
stays — it is the half that carries the measured win.

Why: a controlled A/B on merged main could not show the cache paying for its
memory. Same worktree, same sessions, reattach stable_adoption per session:

  cache + resize gate (as merged)   16 / 67 / 78 / 87 ms
  cache off, gate on                17 / 55 / 68 / 80 ms
  cache off, gate off               13 / 62 / 73 / 83 ms

Indistinguishable. Cold 4-tab activation was likewise unchanged (217-296ms
without the cache vs 226-309ms with), which is expected — a first attach is
always a miss.

The reason it under-delivers is a design fact the original PR missed: attach
does not request the full buffer. terminal-host-session-create.ts passes
resolveDaemonSessionScrollbackRows() — a deliberate 1000-row live window,
capped because unbounded retention once OOM-killed a host. Serializing 1000
rows is cheap, so there was little for a cache to save on that path.

Against that, the cache retained up to MAX_CACHED_SNAPSHOT_BYTES (4MB) per
entry across MAX_CACHED_SNAPSHOT_WINDOWS (2) entries per emulator, for the
session's lifetime, with no aggregate budget across sessions. It also carried
an invalidation contract that produced three separate over-invalidation bugs
during review (the parse fence, setCwd/setLastTitle, and the no-op resize).

The lock fix is unaffected and independently measured: the `options` phase,
which is pure queueing, went 0/125/212/291ms -> 1/1/1/1ms across a 4-tab
worktree activation and stays there.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#17759)

Cold restore seeded a checkpoint's OSC-8 link ranges and then replayed records
that resize, so any resize record after the checkpoint dropped them and
restored hyperlinks in scrollback lost clickability. Same-size resize records
reach the durable log routinely, because every attach re-asserts the pane's
dimensions and session-output-plane records each one without a same-size
dedupe — so an ordinary reattach was enough to lose the links.

Restored ranges are row-indexed, so clearing them on a reflow is right; a
resize to the size already applied is not a reflow. Gate on the dimensions
actually changing.

Introduced in 10fe9a0 ("fix: improve mobile link modifier handling",
stablyai#5597), which added setRestoredOscLinks along with unconditional clearing in
both resize() and clearScrollback(). clearScrollback's clearing is correct and
is unchanged, with a test pinning it.

Found during adversarial review of stablyai#17752 and filed as stablyai#17756. Not a
regression from that PR: stablyai#17667 had incidentally masked it by gating no-op
resizes to protect a snapshot cache, and removing the cache removed the gate.
The same gate returns here on its own terms — as a correctness fix with tests,
rather than as a side effect of a cache.
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.

3 participants