Skip to content

fix(agent-hooks): throttle and background last-status.json writes - #26822

Merged
nwparker merged 1 commit into
mainfrom
nwparker/bug-agent-hooks-last-status.json-is-rewritten-wh
Oct 10, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/bug-agent-hooks-last-status.json-is-rewritten-wh

Conversation

@nwparker

@nwparker nwparker commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​320 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​320
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​382 $\color{#cf222e}{\Huge{\mathbf{−}}}$​185 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​197

ELI5

Orca keeps a small file of agent statuses so it can show them again after a crash. It was rewriting that whole file on almost every agent event, and the app's main thread waited for each write. Now Orca writes it at most every 5 seconds, writes it in the background, and still writes immediately when nothing has changed recently or when it matters for security.

What Changed

Before: every status change armed a 250 ms timer that reset on each new event. When the timer fired, the main thread wrote the full agent-hooks/last-status.json (28–36 KB) to a new temp file and renamed it over the old one. On Windows that was about 53 new files a minute for antivirus to scan, each one blocking the main thread.

After:

  • First change written right away, then at most one write per 5 s. After a quiet period, the next change is written on the next tick, faster than the old 250 ms. During a stream of changes, one timer is armed per 5 s window and never pushed back, so constant activity can't put the write off indefinitely. In the reported 171-event trace, writes drop from 171 to about 39.
  • Authority changes skip the window. These are launch-token hashes and the records that tie a pane to the launch that started it. After a crash they decide which spooled hook events are replayed and whether a restored terminal is trusted. Each status change runs a cheap check (revision counters plus the live launch tokens), and any change triggers an immediate write.
  • Writes happen in the background. src/main/stats/stats-snapshot-writer.ts already wrote snapshots asynchronously, merged requests made during a write, and had a synchronous flush for quit that can't be overwritten by a late background rename. It is now src/main/persistence/atomic-snapshot-writer.ts, used by both stats and agent hooks. It gained options for file mode (0600), directory mode (0700), and skipping identical bytes, plus close() so a stopped server can't publish stale or empty state.
  • Unchanged: quit and hook-disable still flush synchronously (stop() stays sync), and startup hydration and its repair rewrite keep their current order. The file format, the rules for what gets saved, hydration, wire formats, and the SSH relay don't change. Old and new builds read each other's file.

Why

The file is a best-effort recovery cache. The live hook-server store is authoritative, restored rows are marked unconfirmed, and normal quit already flushes. Write frequency only matters after an unclean exit, and an older receivedAt is harmless: the timestamp watermark only raises new stamps and never rejects events. The exception is authority data, which is why it bypasses the throttle. Today's 250 ms crash window for it shrinks to roughly the time one write takes.

Alternatives considered:

  • fix: batch status recovery snapshots at bounded intervals #26735 (fixed 5 s trailing window). Makes every isolated update wait 5 s and keeps the synchronous I/O. It also widens the crash window for authority changes from 250 ms to 5 s.
  • SQLite or an append-only journal. Adds a worker, migration, downgrade conversion, and new failure states for about 30 KB of advisory data. Throttling plus background writes fixes the reported problem without changing the format.

Linked Issue

Fixes #26720

Visual Proof

N/A — only changes when and how a background recovery file is written. Nothing visible or interactive changes.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New tests:

  • src/main/agent-hooks/server-status-persist-throttle.test.ts uses a real server and real hook events. It covers:
    • an isolated change written on the next tick
    • a 500 ms stream for 30 s giving exactly 7 writes, with the timer never pushed back
    • a new launch token mid-window writing immediately
    • identical state skipping the write
    • sync flush cancelling the timer
    • stop() → start() leaving no stale write behind
    • a failed write warning once and retrying in the next window
  • src/main/persistence/atomic-snapshot-writer.test.ts covers:
    • requests merging while a write is in flight
    • skipping identical bytes, including after priming with content already on disk
    • a sync write racing an in-flight async write
    • close()
    • file and directory modes

On macOS, pnpm test on src/main/agent-hooks, src/main/stats, the new writer test, and the hook IPC/relay/runtime suites passes: 133 files, 1361 tests. pnpm tc:node and pnpm run check:code-quality:changed pass. I haven't measured on Windows with antivirus yet.

Review

Things to look at:

  • currentAuthorityFingerprint() runs on every scheduled persist. It is O(panes) string comparisons, no hashing or serialization, far cheaper than the full serialize each write used to do.
  • writeSync during an in-flight async write keeps the existing stats-writer behavior: it unlinks the in-flight temp file and uses a generation guard so an older background rename can't overwrite newer bytes.

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.

Notes

  • Windows: fewer new files for antivirus to scan, and the file create/close now runs on the libuv threadpool.
  • SSH: the relay doesn't use this writer, and nothing on the wire changes.
  • Folder workspaces: not affected.
  • Backwards compatibility: same file and format.
  • Durability: unchanged. The file is still not fsynced, same as before.
  • Follow-up: the same report shows the workspace session and worktree metadata rewritten about 3.6 MB a minute, roughly twice this file's traffic. They should move to the same writer in separate PRs.

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)

@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 11 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 10360bc9-9ee2-44f8-a55b-8b8d3dd0aba4

📥 Commits

Reviewing files that changed from the base of the PR and between 5bbc394 and 0364add.


📒 Files selected for processing (11)
  • src/main/agent-hooks/server-status-persist-throttle.test.ts
  • src/main/agent-hooks/server/revisioned-map.ts
  • src/main/agent-hooks/server/server-constants.ts
  • src/main/agent-hooks/server/server-hydration.ts
  • src/main/agent-hooks/server/server-lifecycle.ts
  • src/main/agent-hooks/server/server-persistence.ts
  • src/main/agent-hooks/server/server-state.ts
  • src/main/persistence/atomic-snapshot-writer.test.ts
  • src/main/persistence/atomic-snapshot-writer.ts
  • src/main/stats/collector.ts
  • src/main/stats/stats-snapshot-writer.ts

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: 59d6eadf-42af-45cd-bf9c-8b355ec1d793

📥 Commits

Reviewing files that changed from the base of the PR and between 39a01f9 and 5bbc394.


📒 Files selected for processing (11)
  • src/main/agent-hooks/server-status-persist-throttle.test.ts
  • src/main/agent-hooks/server/revisioned-map.ts
  • src/main/agent-hooks/server/server-constants.ts
  • src/main/agent-hooks/server/server-hydration.ts
  • src/main/agent-hooks/server/server-lifecycle.ts
  • src/main/agent-hooks/server/server-persistence.ts
  • src/main/agent-hooks/server/server-state.ts
  • src/main/persistence/atomic-snapshot-writer.test.ts
  • src/main/persistence/atomic-snapshot-writer.ts
  • src/main/stats/collector.ts
  • src/main/stats/stats-snapshot-writer.ts

💤 Files with no reviewable changes (1)
  • src/main/stats/stats-snapshot-writer.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

The pull request adds AtomicSnapshotWriter and replaces the stats-specific writer with it. Agent-hook status persistence now uses the shared writer and a 5,000 ms minimum-interval throttle. Changes to the authority fingerprint can trigger an urgent write. The pull request also adds revision-tracked maps, persistence baseline and lifecycle handling, and tests for writer behavior and status persistence.


Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 5bbc3

This change moves agent-hook status persistence to throttled background writes, which should reduce main-thread disk activity on Windows. No blocking concerns are identified. Windows performance has not been measured.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: throttling and background persistence for last-status.json writes.
Description check Passed The description is detailed and follows the repository template. It explains the change, motivation, linked issue, testing, compatibility impact, and checklist status. The full lint, typecheck, test, …
Linked Issues check Passed Issue #26720 requires status persistence that scales with restart-recovery needs instead of hook-event frequency. The PR implements a 5-second leading-edge throttle in scheduleStatusPersist() withou…
Out of Scope Changes check Passed The changes remain connected to #26720. AtomicSnapshotWriter supports the required background atomic writes and is shared with the existing stats writer. File modes, unchanged-byte skipping, lifecyc…
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…

✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR

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

The agent status recovery snapshot was rewritten whole, synchronously on the
main thread, after a 250 ms trailing debounce on almost every hook event
(about 53 new files a minute on the reporter's Windows machine).

- Leading-edge throttle: the first change after idle is written on the next
  turn; a stream gets at most one write per 5 s and cannot postpone it.
- Changes to persisted launch-token authority skip the window, since spool
  replay and restored-terminal attestation read them after a crash.
- Writes run off the event loop through the stats snapshot writer, now
  generalized as AtomicSnapshotWriter. Quit and hook-disable still flush
  synchronously; the file format is unchanged.

Fixes #26720
@nwparker
nwparker force-pushed the nwparker/bug-agent-hooks-last-status.json-is-rewritten-wh branch from 5bbc394 to 0364add Compare October 10, 2026 05:07
@nwparker
nwparker merged commit c527344 into main Oct 10, 2026
46 checks passed
brennanb2025 added a commit that referenced this pull request Oct 14, 2026
Re-applies saved native chat statuses onto main's agent status store: chat
saves and drops go through the throttled background writer (#26822), the
newer-build-file guard moves into the snapshot writer, the sink wiring moves
to agent-hook-runtime-deps, and permissionMode joins the record-owned summary
fields. host.restoreReadableSessions stays public as on main, so tests that
only renamed its call keep main's text; startup reaches the saved-status
restore through the host's restore collaborator.
brennanb2025 added a commit that referenced this pull request Oct 15, 2026
…ca (#27731)

* perf(notifications): save mobile dismissal history off the main thread

Every agent notification recorded its id in mobile-notification-dismissals.json
through the secure-file writer. On Windows that writer runs about five
synchronous icacls launches per write, so each notification froze every Orca
window (STA-9692).

The file holds notification ids, sequence numbers and session ids, not
credentials, so it now goes through the existing AtomicSnapshotWriter: async
temp-plus-rename, mode 0600, bursts coalesced into one write of the latest
entries. Memory stays authoritative, so delivery and retirement are unchanged.
The pending write is flushed in the quit barrier after chat and RPC teardown,
and in the pre-relaunch hook, since renderer relaunch exits without the quit
pipeline.

* perf(notifications): flush dismissal history when a headless host shuts down

orcad never runs the desktop quit barrier, so its cleanup list awaits the
pending dismissal write after RPC stops.

* fix(persistence): drain a snapshot write requested just after a drain ends

AtomicSnapshotWriter cleared its pending-write promise one microtask after
the drain loop saw no more requests. A write() in that gap set
writeRequested, got the settling promise back, and nothing drained it, so
the newest bytes stayed unwritten and waitForPendingWrite() (the dismissal
store's flush) resolved without them. The drain now clears the pending
promise in the same tick its loop exits, on success and failure, so a later
write() always starts a new drain.

* test(notifications): flush dismissal writes before deleting temp state dirs

Dismissal history now saves asynchronously, and the writer recreates its
directory before each write. Tests that deleted their temp dir with a write
still pending left recreated dirs behind in the system temp folder and could
race the delete on Windows. They now await the controller's flush first.

* perf(notifications): close dismissal history at committed exits

The shutdown flush only waited for writes already queued. A notification
recorded after it (orcad cleanups still running, or the 150 ms before a
renderer relaunch calls app.exit) started an async write the exit dropped,
so the phone could keep an alert the desktop could no longer withdraw.

The store's flush() becomes close(): it waits for the pending write, and
every later record saves synchronously through the snapshot writer's
existing writeSync (plain fs, no icacls; a failure only warns). It is called
only where the exit can no longer be vetoed: the will-quit teardown, a new
exit-only hook that app:relaunch runs before app.exit(0) (restart and
profile switches share onBeforeRelaunch but quit through will-quit), and
orcad's cleanup after RPC stops.

The quit test now holds chat teardown and RPC stop and proves the close
starts only after both settle, in either order. The orcad push-startup
runtime mock gains the method the entry now calls.

* fix(notifications): bound the dismissal close before a renderer relaunch

app:relaunch waited on the dismissal store's close with no limit, so a
stalled userData disk left Restart stuck on "Restarting…" with a half-quit
app saving synchronously. The close now races a 2 s cap through the
existing settleWithinMs helper, the same cap the restart path's auth
preservation uses, and logs when it gives up.

* test(notifications): keep async dismissal writes under test between reads

Mid-test disk reads used closeDismissals() as a barrier, which switched
every later record to the exit-only synchronous path. The store gains a
non-closing flush() (close() = mark closed + flush), exposed on the
controller as flushDismissals for tests; mid-test barriers use it, and
close stays only where a test simulates an exit or teardown. Also notes why
the writer's pendingWrite assignment is safe, renames a store test to what
it covers, and groups the orcad cleanup-order test under a describe.

(cherry picked from commit 3fb4b06)

Backport to 1.4.224: this base has no AtomicSnapshotWriter (src/main/persistence/atomic-snapshot-writer.ts, added by #26822, is not on 1.4.224), so the dismissal store saves through the existing StatsSnapshotWriter, its predecessor with the same async temp-plus-rename and writeSync. StatsSnapshotWriter gains an optional fileMode (0o600 for the dismissal file; stats unchanged) and the PR's drain-race fix; the writer regression test moves to a new stats-snapshot-writer.test.ts. The two conflicting e2e tests keep 1.4.224's shape with the PR's async liveDeliveries()/closeDismissals() edits applied, and the same edit is applied to structured-attention-relay-settlement.unit.test.ts, which exists only on this base.
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.

[Bug]: agent-hooks/last-status.json is rewritten whole on almost every hook event (about 53 times a minute)

1 participant