Skip to content

fix: serialize store writes across concurrent sessions - #60

Merged
abogartz merged 2 commits into
mainfrom
fix/store-write-serialization
Oct 23, 2026
Merged

abogartz merged 2 commits into
mainfrom
fix/store-write-serialization

Conversation

@abogartz

@abogartz abogartz commented Oct 23, 2026 •

Copy link
Copy Markdown
Owner

What breaks today

Daily store files (~/.config/opencode/memory/<date>.logfmt) are shared by every opencode session on the machine plus the viewer, which is a separate process. Appending was already atomic (O_APPEND), but four surfaces rewrite the whole file and none of them were serialized against each other:

surface function
supersede in place (memory_update, drift, canonical neutralization, merge review, decay) markSuperseded / clearSuperseded
forget prune (filters rows out)
viewer delete deleteMemory
undo / viewer restore restoreSnapshot

Each one read the file, edited a line in memory, then wrote the file back. Anything another session wrote between the read and the write is gone. Measured on main with the new test/concurrency.test.ts (both red):

  • 40 concurrent appendMemory against 40 markSuperseded on one store → 40 rows on disk instead of 80
  • 4 processes appending + superseding one store → 20 rows instead of 120

Two quieter bugs on the same paths: appendMemory seeded its ts from a scan of the store, so two processes landing in the same millisecond minted the same row identity; and snapshotFiles tested exists() before writing a snapshot name, so a cross-process same-millisecond collision could clobber an earlier, still-undoable snapshot.

The fix

src/lock.ts — withStoreLock(file, fn): one lock per store file, held across the whole read-modify-write.

  • Two layers, one timeout budget. An in-process FIFO hand-off, so contending tasks take a turn instead of spinning (file-lock-only arbitration convoys: 300 same-process supersedes took >5s), plus an O_EXCL lock file, which is atomic across processes and — because the check happens in the kernel — exclusive against our own tasks too.
  • Dead holders are recovered. A lock older than 10s is taken over, and the takeover is audited. Giving up on the wait releases your place in line rather than parking everyone behind a writer that never finishes.
  • Timeout policy (in lock.ts): an ordinary write proceeds past the timeout rather than losing the user's memory (strictly no worse than an unlocked build); memory_undo / viewer restore fails closed, because force deliberately drops rows and must not guess under a live writer. Both cases emit store_lock evidence.
  • Readers stay lock-free. Rewrites publish through writeAtomic (same-directory temp + rename), so recall, injection and the viewer always see a complete store — never the middle of a rewrite, which Bun.write left visible before.
  • Appends take the same lock together with their ts seed: an append cannot land inside a rewrite window, and two processes cannot mint one identity.
  • Snapshot names are claimed with O_EXCL (claimSnapshot).

Covered: appendMemory, markSuperseded, clearSuperseded, prune, addBlock/removeBlock, viewer deleteMemory, and restoreSnapshot — whose divergence check now runs inside the lock, where a stale read could previously wave through a row that landed after it.

Two behaviour changes worth stating

  • prune snapshots only what it rewrote. It used to snapshot every daily file before filtering, unconditionally — so a memory_forget that matched nothing still minted snapshots for the whole store and returned a snapshot path for a deletion that never happened. Now snapshots exist per rewritten file, and a no-op forget returns snapshot: []. Pinned by a test.
  • Force restore now snapshots the file it replaces, from inside the lock, and returns it as RestoreResult.safety (memory_undo names the path; /api/restore reports it as safety). Previously the viewer tried to do this before calling the restore, which missed anything another session appended in between — the exact rows it existed to save — and memory_undo force=true did not snapshot at all. Force still drops those rows from the live store; it no longer destroys the only copy.

Tests

test/lock.test.ts (8): sections never overlap; a failing section releases the lock; different files don't contend; a stale lock is taken over; a fresh lock is not stale and onTimeout: "fail" refuses; proceed runs it and reports the wait; a holder whose lock was taken over never deletes the new one; a second process waits its turn (its line lands after the holder's instead of interleaving).

test/concurrency.test.ts (7): supersede vs. append, prune vs. append, restore vs. append, a force restore racing appends where every row must end up in the store, the safety snapshot or the restored snapshot — never nowhere; a lock-free reader loop that must never see a half-written file (in-process and cross-process); four writer processes that must keep all 120 rows with unique ts and strand no .lock. The supersede race and the four-process case were the two red on main; the prune/restore races won by timing luck there and are pinned here as invariants.

test/undo.test.ts (+2), test/scenarios.test.ts (+1): the two behaviour changes above.

Numbers

tsc clean, biome lint passes (advisory warnings unchanged), 284 unit tests, terminal smoke + BDD against a real opencode host. Published evidence holds: bench/inject-cost.ts and bench/recall-results.md regenerate byte-identically.

Append cost, 4.4k-row store across 21 daily files (throwaway harness, same machine, same seed):

sequential append
main 3.215 ms/op
this branch 0.438 ms/op

The lock costs a write ~0.1 ms; scanning just the file being written for ts collisions (every row it can collide with is in that file — the scan does not need the whole store) more than pays for it. Small single-day stores are a wash (0.45 → 0.56 ms/op), and the shipped bench/write-latency.ts column is unchanged at 15–25 ms.

README: one feature bullet for concurrent-session safety, plus a troubleshooting row for the new memory store is busy message and stray *.lock / *.tmp files.

Closes #36, with the scope corrected: the issue pointed at the canonical registry, which is read-only at runtime (only tests and scripts write canonical.logfmt); the unguarded read-modify-write surfaces were the four above. The per-row supersession cost this review surfaced is filed as #61, deliberately out of scope here.

Whole-file rewrites (supersede, prune, viewer delete, snapshot restore) ran
unlocked against daily store files that every other opencode session and the
viewer are appending to. A writer that read before someone else wrote published
its stale copy: 40 concurrent appends against 40 supersedes left 40 rows on
disk, and four processes writing one store kept 20 of 120.

One lock per store file (in-process FIFO + O_EXCL lock file, shared timeout
budget, dead holders recovered by age) now covers every write to a rewritten
file, including the append and its ts seed; rewrites publish by atomic rename
so lock-free readers never see a truncated store. Snapshot names are claimed
with O_EXCL so a cross-process same-millisecond collision cannot clobber an
undo point. Ordinary writes proceed if they wait out the timeout; restore fails
closed. Contention is audited as store_lock evidence.
@abogartz

Copy link
Copy Markdown
Owner Author

Reviewed as if someone else wrote it. Two real problems, one bloat call, one thing the description doesn't admit. Numbers measured against main (git worktree of 9df2c0e, 400-row store).

Revise before merge

1. The viewer's force-restore safety snapshot is taken outside the lock — so it doesn't do the job its own comment claims.

src/viewer/server.ts:276 snapshots the current file, then calls restoreSnapshot(..., "force"). The comment above it says "Snapshot the current file first so concurrent-session rows lost here stay recoverable." Sequence that still loses data:

  • t0 route snapshots the file → S1 = C0
  • t1 another session appends row R → file is C0+R
  • t2 force restore takes the lock and publishes the snapshot's content

R is dropped, and it is in no snapshot: S1 predates it. The lock made compare+publish atomic but left the recoverability step outside it, which is the one step that matters on the path where rows are deliberately dropped. Same gap in memory_undo with force=true, which takes no safety snapshot at all — that one is at least documented as the exact rollback, this one is not.

Fix inside restoreSnapshot (e.g. a safetySnapshot option, taken after the lock is held, returned on the result so the route can report it). Do not fix it by wrapping restoreRoute in withStoreLock: sections are not re-entrant, so the inner restore would wait on the route's own lock for the full 5s and then hit the onTimeout path — turning a correctness fix into a guaranteed 5s stall plus an unlocked write. Worth a test: force-restore while a second process appends, assert the appended row is both gone from the store and present in the returned safety snapshot.

2. prune changed the snapshot contract and the description doesn't say so. It used to snapshot every daily file before filtering, unconditionally — including on a memory_forget that matched nothing (snapshot spam, and res.snapshot[0] was a real path even when nothing was deleted). It now snapshots only files it actually rewrote. Better behaviour; also a visible change in what memory_forget and pruneMemory's evidence line return. State it in the description and pin it with a test (no-op forget → zero snapshots), otherwise the next person "restores" the old shape thinking it was accidental.

Bloat

3. src/storelock.ts is a new module whose entire content is two constants. The layering excuse doesn't apply here: lock.ts → evidence.ts is not a cycle (evidence.ts imports only config, logfmt, state), so LOCK_WRITE / LOCK_RESTORE can sit in lock.ts and the file goes away, along with two imports in four consumers. If you want mechanism and policy in separate files as a matter of taste, say so in one line in the PR and I'll drop it — but a 20-line policy module is the kind of surface this repo's comment policy exists to trim.

4. appendMemory holds the lock across a full-store scan. existingTs() reads every daily file, and it is now inside the critical section — it is the bulk of the hold time. Its only job is avoiding a duplicate ts, and every ts it can collide with is in the file it is about to write. Scoping the scan to the target file makes the hold one read of one file; the only thing given up is protection against a hand-made fixture that parks today's ts in yesterday's file. Cost as shipped, for the record: sequential append 0.453 → 0.599 ms/op, 20 concurrent appends 9.4 → 14.0 ms total, i.e. ~1% of a 15–25 ms gate. Not urgent — flagged so the choice is deliberate rather than a side effect of where the lock happened to land.

Not this PR

5. memory_decay still rewrites the file once per row. N rows → N full-file reads, N renames, N snapshots, each acquiring and releasing the lock in between (index.ts:543 snapshots, then loops markSuperseded). Now that a per-file lock exists, one pass over the file under one lock (markManySuperseded(ts[])) is strictly better and would also stop decay interleaving with itself. File a ticket; growing this PR to cover it is worse.

Checked and clean

  • Every whole-file write to a rewritten store file goes through writeAtomic under the lock. The remaining Bun.writes are: snapshot files (now O_EXCL-claimed), per-session status JSON (display-only, no RMW), the export file, and write-if-missing command mirrors.
  • No withStoreLock section nests another lock — checked every call site: stampRow, prune, deleteMemory, removeBlock, restoreSnapshot call only reads, snapshotFiles, logDeletion (append-only, different file) and writeAtomic. So no self-deadlock, and the "sections run flat" comment is honest.
  • The give-up path releases the queue slot instead of parking every writer behind a stuck one — and the FIFO is what keeps 300 same-process supersedes off the spin path (file-lock-only arbitration measured >5s, i.e. the convoy I hit while writing this).
  • Bookkeeping files can't leak into reads: *.lock and *.<pid>.tmp don't match the *.logfmt glob, the viewer's snapshot list, or the e2e row scanner.
  • Not flaky-prone: heaviest new test 436ms against the 5s default; published benches regenerate byte-identically.

Nits

  • expect(runs.map((r) => r.err.trim())).toEqual(["", "", "", ""]) makes any unrelated runtime warning from a child process fail a test about row loss. Assert exit codes; keep stderr as diagnostic output.
  • appendMemory computes the day file from dateStr() before taking the lock, so a ts bumped across midnight would land under the previous day's file. Harmless (readers glob every file, decay compares ts), but say so in one line — otherwise the next reader will "fix" it by moving the file computation inside the lock, which would change the lock key mid-flight.

Force restore took its safety snapshot outside the lock, so rows another
session appended between that snapshot and the rollback were dropped from the
store and present in no snapshot. restoreSnapshot now takes it while holding
the lock and returns it as RestoreResult.safety; the viewer stops pre-snapshotting
and memory_undo names the path. check and merge drop nothing and take none.

prune snapshots only the files it rewrote rather than every file in the store,
so a forget that matches nothing mints no undo point — now stated by a test.

The ts collision scan moved inside appendMemory's lock and narrowed to the file
being written: the rows it can collide with are only the ones that file
receives. On a 4.4k-row / 21-file store that takes a sequential append from
3.215ms to 0.438ms, paying back the ~0.1ms the lock costs.

The two lock-policy constants did not need a module of their own (evidence.ts
imports nothing that touches the lock, so there was no cycle to avoid); they
live in lock.ts and storelock.ts is gone. A child process's stderr is
diagnostic in the four-writer test rather than an assertion.
@abogartz

Copy link
Copy Markdown
Owner Author

Review round applied (9d9ff1c)

1 — force restore's safety snapshot moved inside the lock (the blocking one). restoreSnapshot now takes it while holding the lock and returns it as RestoreResult.safety. The viewer no longer pre-snapshots, and /api/restore returns safety; memory_undo names the path in its output. (The rolledBack count was already computed at restore time, but outside the lock — rows landing between the compare and the publish were not counted; now they are.) check and merge drop nothing, so they take none — asserted. As flagged, the route is not wrapped in withStoreLock: sections aren't re-entrant, and doing it that way would have cost a guaranteed 5s wait and then written unlocked. Two tests: undo.test.ts pins that a force restore leaves the newer row in safety while the store rolls back; concurrency.test.ts runs a force restore against live appends and asserts every row ends up in the store, the safety snapshot or the restored snapshot — lost must be empty, never silently nowhere.

2 — prune's snapshot contract disclosed and pinned. Description now states it, and scenarios.test.ts has a no-op forget test: deleted.length === 0, snapshot: [], store intact, no deletions.logfmt.

3 — src/storelock.ts deleted. Both constants live in lock.ts; four importers lost a line. You were right that there was no cycle to avoid — evidence.ts pulls in config, logfmt, state, none of which touch the lock.

4 — the ts scan is scoped and it was not cosmetic. existingTs(file) reads only the file being written, since the rows it can collide with are only the ones that file receives. Measured on a 4.4k-row store across 21 daily files, same harness both sides:

sequential append
main 3.215 ms/op
this branch 0.438 ms/op

My original estimate said "not urgent" off a single-day 400-row store, where it is indeed a wash (0.45 → 0.56 ms/op) — the multi-day shape is the one that matters and it is 7.3×. The lock itself costs ~0.1 ms/op; narrowing the critical section pays for it several times over. Numbers are in the description.

5 — filed as #61, per-row supersession in decay (N reads / N snapshots / N renames, now worth collapsing into one pass under one lock). Not in this PR.

Nits: the four-writer test asserts exit codes and keeps child stderr as diagnostic instead of requiring an empty stderr; appendMemory documents that the day file is chosen before the lock because it is the lock key, so the midnight-bump grouping isn't "fixed" into a changing lock key later.

Gate after these changes: tsc clean, biome lint passes, 284 unit tests, terminal smoke + BDD green against a real opencode host.

@abogartz
abogartz merged commit 357ecaf into main Oct 23, 2026
3 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.8.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

@WhollyMindless

Copy link
Copy Markdown
Contributor

A small post-merge finding about what the undo list shows while a snapshot is being written. On Windows with Bun 1.4.4, I took 60 snapshots of a 1,263,000-byte day file while a second task called listSnapshots and read the newly listed files.

  • Before fix: serialize store writes across concurrent sessions #60 (9df2c0e): 0 empty reads out of 60.
  • PR head (9d9ff1c): 150 empty reads out of 210.
  • Current main (c34abe1): 63 empty reads out of 123. The undo list reported zero bytes on all 63. These are read attempts, so a reader can see the same in-progress snapshot more than once.

The exclusive create reserves the final filename before the snapshot contents are written. Readers can therefore see a valid-looking undo candidate during that interval. Every snapshot had its full size after writing finished. We did not observe a restore losing rows. A regression test for any future fix could check that a snapshot is complete the first time the undo list offers it, while retaining the collision protection this PR added.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

P0: Lock read-modify-write paths (canonical registry, snapshot restore) — two-writer stress

2 participants