Repository navigation
fix: serialize store writes across concurrent sessions - #60
Conversation
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.
|
Reviewed as if someone else wrote it. Two real problems, one bloat call, one thing the description doesn't admit. Numbers measured against Revise before merge1. The viewer's force-restore safety snapshot is taken outside the lock — so it doesn't do the job its own comment claims.
Fix inside 2. Bloat3. 4. Not this PR5. Checked and clean
Nits
|
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.
Review round applied (
|
| 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.
|
🎉 This PR is included in version 0.8.1 🎉 The release is available on: Your semantic-release bot 📦🚀 |
|
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
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. |
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:memory_update, drift, canonical neutralization, merge review, decay)markSuperseded/clearSupersededprune(filters rows out)deleteMemoryrestoreSnapshotEach 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
mainwith the newtest/concurrency.test.ts(both red):appendMemoryagainst 40markSupersededon one store → 40 rows on disk instead of 80Two quieter bugs on the same paths:
appendMemoryseeded itstsfrom a scan of the store, so two processes landing in the same millisecond minted the same row identity; andsnapshotFilestestedexists()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.O_EXCLlock file, which is atomic across processes and — because the check happens in the kernel — exclusive against our own tasks too.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, becauseforcedeliberately drops rows and must not guess under a live writer. Both cases emitstore_lockevidence.writeAtomic(same-directory temp + rename), so recall, injection and the viewer always see a complete store — never the middle of a rewrite, whichBun.writeleft visible before.tsseed: an append cannot land inside a rewrite window, and two processes cannot mint one identity.O_EXCL(claimSnapshot).Covered:
appendMemory,markSuperseded,clearSuperseded,prune,addBlock/removeBlock, viewerdeleteMemory, andrestoreSnapshot— 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
prunesnapshots only what it rewrote. It used to snapshot every daily file before filtering, unconditionally — so amemory_forgetthat 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 returnssnapshot: []. Pinned by a test.RestoreResult.safety(memory_undonames the path;/api/restorereports it assafety). 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 — andmemory_undo force=truedid 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 andonTimeout: "fail"refuses;proceedruns 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 uniquetsand strand no.lock. The supersede race and the four-process case were the two red onmain; 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
tscclean,biome lintpasses (advisory warnings unchanged), 284 unit tests, terminal smoke + BDD against a real opencode host. Published evidence holds:bench/inject-cost.tsandbench/recall-results.mdregenerate byte-identically.Append cost, 4.4k-row store across 21 daily files (throwaway harness, same machine, same seed):
mainThe lock costs a write ~0.1 ms; scanning just the file being written for
tscollisions (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 shippedbench/write-latency.tscolumn is unchanged at 15–25 ms.README: one feature bullet for concurrent-session safety, plus a troubleshooting row for the new
memory store is busymessage and stray*.lock/*.tmpfiles.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.