Skip to content

Bound hot-terminal full-snapshot checkpoints with a per-session cooldown - #7088

Merged
nwparker merged 2 commits into
mainfrom
nwparker/checkpoint-cooldown
Jul 2, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/checkpoint-cooldown

Conversation

@nwparker

@nwparker nwparker commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #7068 (the fseventsd load audit): this addresses the top deferred finding — terminal-history checkpoints are Orca's dominant self-generated disk write source.

Problem

The daemon adapter checkpoints dirty PTY sessions every 5s. For calm sessions that's a cheap increment append. But a streaming session (build logs, test runners, yes-style floods) hits the full-snapshot path on nearly every tick, two ways:

  • takePendingOutput overflow: >2MB of output accumulated within one 5s tick, or
  • the 5MB increment-log cap (needs-checkpoint) — recurring every ~5MB of output.

Each full snapshot is a multi-hundred-KB-to-multi-MB checkpoint.json write + rename + output.log header rewrite — up to 12×/min per hot session, i.e. hundreds of MB/min of disk writes from a single busy terminal, and the largest Orca-generated contribution to system-wide filesystem event volume (see #7068 for why that matters on macOS).

Live baseline on an affected machine (146-worktree workload, quiet evening load): 72 file touches and ~1.3MB growth per 2 minutes in terminal-history/, 231MB accumulated across 2,851 files.

Fix

Cap/overflow-triggered full snapshots now honor a 45s per-session cooldown:

  • While cooling down, the session's checkpoint work is deferred entirely — no takePendingOutput RPC, no increment appends. Appending past a dropped range would leave a hole in the log, so skipping keeps the on-disk state a consistent (merely stale) prefix that the eventual full snapshot re-anchors from the live emulator.
  • Deferred sessions stay dirty, so the 5s timer keeps retrying until the cooldown expires (also self-heals across transient daemon RPC failures — verified live).
  • Bypassed where staleness is not acceptable: final/teardown checkpoints (app quit, sleep shutdown, clean disconnect) and a session's first-ever snapshot (cold-restore re-anchor is never delayed).
  • The legacy non-incremental protocol path (pre-v13 daemons) is unchanged.

An independent adversarial review of the first commit traced six invariants through the restore/reattach/respawn paths; the second commit hardens the edges it found:

  • Warm reattach re-anchor: an adapter attaching to a daemon session it wasn't already managing (app relaunch) now forces a full snapshot before any increment appends — the previous adapter may have drained daemon records it never persisted, and appending past that unknown drain point would put a seq gap in the log, which the restore reader rejects wholesale (this window existed pre-cooldown at ~ms width; it's now closed entirely).
  • Cold-restore re-anchor clears any cooldown inherited from the pre-crash generation (daemon respawn within one adapter), so a revived session's first snapshot is never deferred.
  • Exit-event routing clears the cooldown timestamp (reused ptyIds can't inherit a dead session's cooldown); backward wall-clock jumps count as expired rather than extending the deferral.

Evidence

Unit (asserted in daemon-pty-adapter.test.ts): 24 consecutive hot-session ticks (~2 simulated minutes of overflow) produce 1 full snapshot and zero further daemon RPCs while cooling down; previously every tick produced one. Final checkpoints bypass; log-cap deferrals follow the same cycle.

Live (dev build, real daemon, yes flooding a PTY): first overflow snapshot lands immediately (423KB checkpoint.json), then the session defers — output.log stays at its 9-byte header instead of cycling 5MB generations, and checkpoint.json rewrites at the cooldown cadence instead of every 5s. Steady-state hot-session write volume drops from ~5MB/min (12 × 423KB) plus ~1MB/min log cycling to ~0.6MB/min — ~9× less, with proportionally fewer filesystem events.

The live run also exercised an unplanned failure mode: the daemon client connection dropped mid-stream, the deferred session retried each tick (surfaced as [history] checkpoint failed ... Not connected, identical to old behavior under RPC failure), and the flagged snapshot landed on reconnect.

Trade-off

For a session that is mid-stream when the machine hard-crashes (daemon dies too — power loss, kernel panic), cold restore can be up to 45s more stale for that session's tail scrollback. Warm reattach (daemon survives, e.g. app restart), quit/sleep-time final checkpoints, and calm sessions are unaffected. Increment appends for normal typing/output cadence are untouched.

Notes

  • pty-subprocess.test.ts has one WSL env-import test failing on main at this base commit — pre-existing, unrelated.
  • Observed during testing (pre-existing, filed for follow-up consideration): a PTY with no renderer consumer ACKing data lets the main-process delivery queue grow to its 512MB cap under sustained flood before dropping. Real terminal panes ACK and are unaffected.

Made with Orca 🐋

nwparker and others added 2 commits July 2, 2026 01:13
A streaming session (build logs, yes) re-triggered a full multi-MB
checkpoint.json tmp+rename on every 5s tick via pending-buffer overflow
or the 5MB log cap - hundreds of MB/min of disk writes from one busy
terminal, and the dominant Orca-generated filesystem event volume.

Cap/overflow-triggered full snapshots now honor a 45s per-session
cooldown: while cooling down the session's checkpoint work is deferred
entirely (no takePendingOutput RPC, no increment appends - appending
past a dropped range would leave a hole in the log, so the on-disk
state stays a consistent, merely stale, prefix) and the session stays
dirty so the timer retries until the cooldown expires. Final/teardown
checkpoints (quit, sleep, clean disconnect) bypass the cooldown, and a
session's first-ever snapshot is never delayed, so cold-restore
fidelity changes only for hot sessions mid-stream: at most 45s of
tail scrollback staleness after a hard crash.

Co-authored-by: Orca <[email protected]>
From adversarial review of the cooldown commit:
- Warm reattach by an adapter that was not already managing the session
  now forces a full-snapshot re-anchor: the previous adapter may have
  drained daemon records it never persisted (deferred hot-session tick),
  and appending past that unknown drain point would put a seq gap in the
  log, which the restore reader rejects wholesale. This also closes the
  pre-existing (previously ~ms-wide) drain-vs-persist crash window.
- Cold-restore re-anchor clears any cooldown inherited from the
  pre-crash generation (daemon respawn within one adapter), so the
  revived session's first snapshot is never deferred.
- Exit-event routing clears lastFullCheckpointAt (reused ptyIds must not
  inherit a dead session's cooldown); fanoutSyntheticExits now clears
  sessionsNeedingFullCheckpoint for consistency.
- Backward wall-clock jumps count as expired instead of extending the
  deferral.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker merged commit 9fc61aa into main Jul 2, 2026
2 checks passed
@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0c9d1a62-e04b-42f3-9083-16d2fe3ffff6

📥 Commits

Reviewing files that changed from the base of the PR and between 6dafe8c and 0f6f61e.

📒 Files selected for processing (3)
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/history-reader.ts

📝 Walkthrough

Walkthrough

This change introduces a cooldown mechanism for full-snapshot checkpointing in DaemonPtyAdapter, tracked via a per-session lastFullCheckpointAt map and a FULL_CHECKPOINT_COOLDOWN_MS constant. checkpointSession now returns 'done' or 'deferred' to distinguish completed checkpoints from those deferred due to cooldown, while the worker loop only marks sessions completed on 'done'. Cooldown state is reset across cold-restore, warm reattach, shutdown, synthetic exit, dispose, disconnect, and exit-event handling paths to avoid stale inheritance. Tests were added covering cooldown rate-limiting, final-checkpoint bypass, needs-checkpoint deferral, and re-anchoring scenarios. A documentation comment in history-reader.ts was also clarified.

Sequence Diagram(s)

sequenceDiagram
  participant Worker as Checkpoint Worker
  participant Adapter as DaemonPtyAdapter
  participant Snapshot as takeSnapshotAndCheckpoint

  Worker->>Adapter: checkpointSession(sessionId, opts)
  alt opts.final or no prior checkpoint
    Adapter->>Snapshot: take full snapshot
    Snapshot-->>Adapter: success
    Adapter->>Adapter: lastFullCheckpointAt.set(sessionId, now)
    Adapter-->>Worker: 'done'
  else cooling down
    Adapter->>Adapter: sessionsNeedingFullCheckpoint.add(sessionId)
    Adapter-->>Worker: 'deferred'
  end
  Worker->>Worker: mark session completed only if 'done'
Loading

Compact Metadata

Type: Enhancement/Bug fix
Impact: Medium — modifies checkpoint scheduling behavior in daemon PTY adapter
Files touched: 3

Related issues: None referenced
Related PRs: None referenced
Suggested labels: daemon, checkpointing, needs-review
Suggested reviewers: None determinable from provided information

Poem

A rabbit watched the snapshots race too fast,
So cooldown timers now hold sessions steadfast.
Deferred but not forgotten, they wait their turn,
Reattach and restore, the state won't churn.
Hop by hop, the checkpoints stay in sync at last. 🐇⏱️

✨ 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.

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

* Bound hot-terminal full-snapshot checkpoints with a per-session cooldown

A streaming session (build logs, yes) re-triggered a full multi-MB
checkpoint.json tmp+rename on every 5s tick via pending-buffer overflow
or the 5MB log cap - hundreds of MB/min of disk writes from one busy
terminal, and the dominant Orca-generated filesystem event volume.

Cap/overflow-triggered full snapshots now honor a 45s per-session
cooldown: while cooling down the session's checkpoint work is deferred
entirely (no takePendingOutput RPC, no increment appends - appending
past a dropped range would leave a hole in the log, so the on-disk
state stays a consistent, merely stale, prefix) and the session stays
dirty so the timer retries until the cooldown expires. Final/teardown
checkpoints (quit, sleep, clean disconnect) bypass the cooldown, and a
session's first-ever snapshot is never delayed, so cold-restore
fidelity changes only for hot sessions mid-stream: at most 45s of
tail scrollback staleness after a hard crash.

Co-authored-by: Orca <[email protected]>

* Harden checkpoint cooldown against crash-boundary and reuse edges

From adversarial review of the cooldown commit:
- Warm reattach by an adapter that was not already managing the session
  now forces a full-snapshot re-anchor: the previous adapter may have
  drained daemon records it never persisted (deferred hot-session tick),
  and appending past that unknown drain point would put a seq gap in the
  log, which the restore reader rejects wholesale. This also closes the
  pre-existing (previously ~ms-wide) drain-vs-persist crash window.
- Cold-restore re-anchor clears any cooldown inherited from the
  pre-crash generation (daemon respawn within one adapter), so the
  revived session's first snapshot is never deferred.
- Exit-event routing clears lastFullCheckpointAt (reused ptyIds must not
  inherit a dead session's cooldown); fanoutSyntheticExits now clears
  sessionsNeedingFullCheckpoint for consistency.
- Backward wall-clock jumps count as expired instead of extending the
  deferral.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[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.

1 participant