Repository navigation
perf(terminal): drop the headless snapshot cache, keep the spawn lock - #17752
Conversation
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 SummaryRemoves per-emulator snapshot memoization and rebuilds snapshots directly from current terminal state, reducing long-lived memory retention while preserving the shared/exclusive spawn lock.
Confidence Score: 5/5The 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.
|
| 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
📝 WalkthroughWalkthrough
Merge Risk: 🔵 Low · up to 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)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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 checkExplanation 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
✨ 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.
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 winPreserve restored OSC links on an equal-size resize.
At Line 234, an equal-size resize clears
restoredOscLinksalthough the buffer coordinates do not change.collectHeadlessOscLinkRangesuses 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
restoredOscLinksonly 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
📒 Files selected for processing (3)
src/main/daemon/headless-emulator-snapshot-cache.test.tssrc/main/daemon/headless-emulator.tssrc/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.
There was a problem hiding this comment.
✅ 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.tsremoved — the memoized snapshot assembly module is deleted outright.headless-emulator-snapshot-cache.test.tsremoved — 230 lines of cache-specific tests, including the prototype-surface freeze guard that existed only to protect the now-deleted invalidation contract.headless-emulator.tsrestored —getSnapshot()inlines the previously cached assembly back to recompute-on-every-call, andmarkMutated/markWrittenplus the no-opresizeequality 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
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.
|
thanks for reporting. looking into it |
…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.
…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.

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 theHeadlessSnapshotCachemodule.headless-emulator.tsreturns 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
optionsphase is pure lock queueing, so it isolates the lock exactly. 4-tab worktree activation, per tab:optionsUnaffected by this PR.
Given up: nothing measurable
Controlled A/B on merged main — same worktree, same sessions, same machine — reattach
stable_adoptionper session: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), whichheadless-emulator.ts:87hands 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
requestedRowsto[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 atDAEMON_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
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.tsalready 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/daemonand the runtime suites;pnpm tcclean; changed-code quality gate clean. Main-process/daemon only — no renderer, wire, or persisted-format change.