Skip to content

Skip no-op state writes and bound save postponement in persistence - #7092

Merged
nwparker merged 2 commits into
mainfrom
nwparker/persistence-write-churn
Jul 2, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/persistence-write-churn

Conversation

@nwparker

@nwparker nwparker commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #7068/#7088 (fseventsd + write-churn audit): second of the deferred write-churn findings.

Problem

orca-data.json (1.6MB on the reference machine) is rewritten in full — pretty-printed serialize, tmp write, rename — on every debounced save, even when state content hasn't changed. Measured on an idle production instance: 3 rewrites/min, ~9.8MB written per 2 minutes (~7GB/day at idle rate; active use peaks far higher at the old 300ms cadence). Warm starts additionally trigger a sync-flush storm: every restored terminal re-asserts an identical PTY binding through persistPtyBinding, each forcing a full synchronous multi-MB write.

Two defects compound:

  • No content guard: mutation bursts that net out to already-persisted state (or no-op re-binds) still rewrite the file.
  • The 300ms trailing debounce resets on every mutation with no upper bound — sustained sub-interval mutations either rewrite ~3×/s or postpone the write indefinitely.

Fix

  • Content-hash guard in both writers: each write computes a sha1 of the compact plaintext state; if it matches the last successful write, the serialize + tmp + rename is skipped entirely. Hashing plaintext rather than the on-disk payload because encrypt() uses a random IV per call (byte-identical state produces different ciphertext every time). Safe under flushOrThrow's durability contract: a matching hash means the file already contains exactly this state. The hash is only recorded after a successful rename (and, on the async path, only when the write-generation check passes, so a racing sync flush's fresher hash is never clobbered).
  • Debounce 300ms → 1s trailing + 5s max-wait: bursts coalesce, and the max-wait fixes the pre-existing unbounded-postponement edge — crash staleness is now hard-capped at 5s (was theoretically unbounded under sustained mutations, typically 300ms).

Evidence

condition orca-data.json rewrites
production (old code), idle, 2 min 6 (~9.8MB written)
dev build (fixed), settled idle, 2 min 3 — and consecutive-snapshot diffing confirms each remaining write is a genuine content change (periodic hosted-review/github cache refreshes stored in persisted state), i.e. zero byte-identical rewrites remain

(The residual writer — poll-refreshed cache entries with timestamps living inside the durable state file — is a separate design question, noted for follow-up.)

Unit (asserted): a mutation burst that returns to already-persisted state produces no write (inode unchanged — every real write is a tmp+rename, so an unchanged inode proves no I/O); flush() on clean state skips; an identical persistPtyBinding re-bind (the warm-start storm) skips; sustained 500ms-interval mutations still hit disk within the 5s max-wait. 326 persistence tests pass (10 existing timing tests updated 300ms → 1s), plus 108 tests in adjacent suites.

Trade-offs

  • Crash-loss window for un-flushed mutations grows from ~300ms to ≤5s (1s typical). Quit/sleep still flush synchronously; PTY bindings still flush synchronously at spawn; and the previous behavior was already unbounded under sustained mutation, so the worst case strictly improves.
  • Each real (content-changing) save pays one extra compact JSON.stringify + sha1 (~5-8ms on 1.6MB, off the critical path); no-op saves get dramatically cheaper (no serialize-for-disk, no I/O).
  • Backup rotation only runs on real writes — unchanged in practice since rotating a byte-identical state file has no value.

Review

An independent adversarial review traced six invariants (hash-vs-disk coherence across all writer interleavings, flushOrThrow durability at every call site, max-wait math, backup rotation, startup seeding, external writers). It confirmed the design — including that backup rotation strictly improves (the old idle churn rotated five identical hourly snapshots, aging out distinct history) — and found one real race, fixed in the second commit: recording the hash after the async rename needed a write-generation re-check, and a hash-matching sync flush must force-write when an async rename was already dispatched, so the sync write always lands last.

Made with Orca 🐋

nwparker and others added 2 commits July 2, 2026 01:42
orca-data.json (1.6MB live) was fully rewritten (pretty-print + tmp +
rename) on every debounced save even when the state content had not
changed - measured 3 rewrites/min (~5MB/min) on an idle production
instance, and a sync-flush storm of identical multi-MB writes at every
warm start via persistPtyBinding re-binds.

- Content-hash guard in both writers: a save whose plaintext state hash
  matches the last successful write skips serialize+write+rename
  entirely. Hashing plaintext (not the payload) because encrypt() uses
  a random IV per call. Safe under flushOrThrow's durability contract:
  a matching hash means the file already holds exactly this state.
- Debounce 300ms -> 1s trailing with a 5s max-wait. The old timer reset
  on every mutation with no bound, so sustained sub-interval mutation
  bursts could postpone the write indefinitely; now staleness is capped
  at 5s while bursts coalesce.

Co-authored-by: Orca <[email protected]>
From adversarial review: an async writer that had already passed its
generation check and dispatched the rename could have a sync flush
interleave during the await, write fresher state, and record its hash -
the async continuation then clobbered lastWrittenStateHash with a value
describing content NOT on disk, making later saves (including the quit
flush) silently skip. Re-check writeGeneration before recording.

Twin edge: a hash-matching sync flush could skip its write while a
stale dispatched rename lands afterwards, leaving stale content
unchallenged. flushOrThrow now forces the sync write whenever an async
write chain was in flight at entry, restoring the sync-write-last disk
ordering.

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

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Caution

Review failed

An error occurred during the review process. Please try again later.


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 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: adc3e06f-cef9-4bbf-bb17-e491ce7f7bfd

📥 Commits

Reviewing files that changed from the base of the PR and between 6142ec1 and 5b25d05.

📒 Files selected for processing (2)
  • src/main/persistence.test.ts
  • src/main/persistence.ts

📝 Walkthrough

Walkthrough

This change modifies the Store persistence write strategy in src/main/persistence.ts to use SHA-1 content hashing and a bounded debounce/max-wait mechanism, skipping redundant disk writes when state content is unchanged. New fields track the last written state hash and burst start time, and writeToDiskAsync/writeToDiskSync/flushOrThrow are updated to coordinate generation-guarded writes and forced durability during flush. Corresponding tests in src/main/persistence.test.ts are updated to use a 1000ms debounce interval (previously 300ms) and new tests are added covering write-skipping scenarios based on content/inode equality.

Changes

Cohort / File(s) Summary
Persistence write logic (src/main/persistence.ts) Adds content hashing, bounded debounce/max-wait scheduling, generation-guarded async writes, force-aware sync writes, and flush coordination
Persistence tests (src/main/persistence.test.ts) Updates timer advancement to 1000ms across existing tests; adds new content-hash write-skipping test coverage

Sequence Diagram(s)

Included in the hidden review stack artifact above.

Related Issues: Unable to determine from provided context.

Related PRs: Unable to determine from provided context.

Suggested labels: persistence, tests, performance

Suggested reviewers: Unable to determine from provided context.

🐰 A hash to check before I write,
A debounce timer, bounded tight,
No more scribbling twice the same,
Inodes still, no write to blame,
The Store now skips redundant flight.

✨ 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
…tablyai#7092)

* Skip no-op state writes and bound save postponement in persistence

orca-data.json (1.6MB live) was fully rewritten (pretty-print + tmp +
rename) on every debounced save even when the state content had not
changed - measured 3 rewrites/min (~5MB/min) on an idle production
instance, and a sync-flush storm of identical multi-MB writes at every
warm start via persistPtyBinding re-binds.

- Content-hash guard in both writers: a save whose plaintext state hash
  matches the last successful write skips serialize+write+rename
  entirely. Hashing plaintext (not the payload) because encrypt() uses
  a random IV per call. Safe under flushOrThrow's durability contract:
  a matching hash means the file already holds exactly this state.
- Debounce 300ms -> 1s trailing with a 5s max-wait. The old timer reset
  on every mutation with no bound, so sustained sub-interval mutation
  bursts could postpone the write indefinitely; now staleness is capped
  at 5s while bursts coalesce.

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

* Guard the state-hash against sync-flush interleaving mid-rename

From adversarial review: an async writer that had already passed its
generation check and dispatched the rename could have a sync flush
interleave during the await, write fresher state, and record its hash -
the async continuation then clobbered lastWrittenStateHash with a value
describing content NOT on disk, making later saves (including the quit
flush) silently skip. Re-check writeGeneration before recording.

Twin edge: a hash-matching sync flush could skip its write while a
stale dispatched rename lands afterwards, leaving stale content
unchallenged. flushOrThrow now forces the sync write whenever an async
write chain was in flight at entry, restoring the sync-write-last disk
ordering.

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