Skip to content

fix: refuse shared store writes after lock timeout - #197

Merged
abogartz merged 4 commits into
abogartz:mainfrom
WhollyMindless:fix/write-lock-timeout
Oct 31, 2026
Merged

abogartz merged 4 commits into
abogartz:mainfrom
WhollyMindless:fix/write-lock-timeout

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #196.

A writer that exhausts its store-lock budget currently runs unlocked. An append can report success while another writer holds a read-modify-write snapshot, then disappear when that holder publishes. LOCK_WRITE now uses onTimeout: "fail" for appenders and whole-file publishers, refusing with the existing busy/retry error rather than acknowledging an unsafe write.

Refusal is not rollback: a multi-file operation can publish one file before a later lock fails. This PR also makes those partial outcomes truthful:

  • Supersession batches update a caller-supplied durable-ID sink immediately after each file publishes. Gate drift/canonical retirements and duplicate-update completion retain those receipts even if the batch rejects later.
  • memory_merge_review and memory_update report completed retirements and the error naming the busy file. Merge's description scopes pre-write refusal separately from later partial application.
  • Forget tracks deletions only after each file publishes. Partial forget/decay operations report the completed IDs and emit prune / decay_applied receipts with partial=true when evidence is writable.
  • Viewer edit names its already-persisted replacement and whether the original retired when a later supersession fails. Two active rows can remain; the response directs inspection/undo before retrying rather than implying rollback.
  • Capture records each refused candidate (or partial gate retirement) instead of losing it to the hook's outer error handler, continues the candidate loop, and records lag. The use-ledger comment explicitly documents that contention can drop telemetry; retrieval still remains available.

The five-second production budget, stale-lock recovery, and timeout callback are unchanged. Restore keeps its existing fail-closed policy. The low-level lock helper retains its legacy explicit/default proceed behavior, documented as unsafe for shared store writers.

Validation

  • Eleven timeout regressions cover a queued append and separate-process append, prune, single/batch supersede, clear, viewer delete, block/unblock, tombstone append, and viewer unreject. They assert refusal, exact file bytes and holder token, and a successful retry. The original nine fail on base 525ed89; the tombstone pair fails with main d69691c's lock implementation restored.
  • Nine further tests cover per-file receipts/retry, a pre-publication refusal control, real merge/update partial replies, restore refusal/retry, viewer duplicate-active-row reporting, partial forget/decay receipts, and per-candidate capture refusal/lag.
  • Six partial-outcome probes failed on prior head fbf1d61; the capture probe also failed with that head's handler restored. Changing LOCK_RESTORE.onTimeout to proceed makes the new restore regression fail.
  • Focused validation at acd7a68: Windows/Bun 1.4.4, 79 pass; Linux/WSL/Bun 1.4.4, 76 pass, 3 Windows-only skips. The three skips are the ACL case and two Windows rename-contention cases, which pass on Windows. The original focused lock-only count was Windows-specific (24 pass; one is Windows-only).
  • Full Windows gate: 772 unit tests pass, 11 skipped; 11 real-host E2E tests pass; typecheck and lint pass (409 existing lint warnings). No production deadlines or existing test deadlines widened.

Scope

Main d69691c, including #194, is integrated. Operations spanning files or steps remain non-transactional; earlier changes can survive a later refusal, and audit writes can independently fail. No automatic rollback or lossless telemetry guarantee is added. #198's concurrent-reader append-publication problem is separate and remains open.

Optional contribution—please feel free to decline or close this if the approach does not fit your plans.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Updated to fbf1d61: merged current main d69691c and added deterministic timeout coverage for #194's tombstone append and viewer unreject paths. Both new cases fail with main's old lock policy, pass with this fix, preserve the holder's bytes/token, and verify the exact rejection set after retry. The follow-up adds no runtime behavior beyond the original fail-closed policy.

Full integrated Windows gate passed: 763 unit tests (11 skipped), 11 real-host E2E tests, typecheck, and lint. The PR body now describes this integrated validation instead of the earlier merge-tree-only check. Hosted CI is rerunning for the pushed head; #198's reader-publication work remains separate.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: CHANGES_REQUESTED

Reviewed at head 877b690 on macOS / Bun 1.4.3 (your gate and CI are Windows / 1.4.4). The production change is right and the test work is strong. One thing has to be fixed first: widening fail-closed makes abort-after-durable-publish reachable for the first time, and one tool then reports the opposite of what happened on disk.

What I verified independently

  • The mechanism in #196 is exactly as described. On clean 525ed89 a child append inside a held whole-file RMW window reported {"ok":true}, the row was present while the holder held the lock, and it was absent after the holder republished its saved copy (bytes 88 → 88). Not delayed — destroyed. The same loss reproduces in-process, so the queued-append case is meaningful.
  • Red on base / green at head: the nine new cases give 0 pass / 9 fail on a clean 525ed89 + only the two new files, and 9 pass at head (3 consecutive runs). Suite delta is exactly +9 (722/12/0 → 731/12/0), lint 409 → 409 warnings for +2 files, typecheck clean, e2e 11/0.
  • Both fail branches are load-bearing in the tests: deleting onTimeout: "fail" kills all nine; making the cross-process deadline unable to fail kills the 8 separate-process cases; the in-process one kills the same-process case plus the pre-existing "a fresh lock is NOT stale" test.
  • Self-contention — the question I most expected to bite — is clean. Every acquisition site was enumerated: appendMemory, stampRow, the batch supersede loop, prune (whose logDeletion appends to deletions.logfmt, a RESERVED name that memoryFiles() never locks), blocklist add/remove, recordHits (whose rotateIfNeeded rewrites the same file with no nested lock), restore, viewer delete, and the two tool-transaction locks (update-order, which is not a *.logfmt and is always taken before the store). Nothing holds one store lock while taking another, all multi-file takers walk memoryFiles() in the same sorted order holding one file at a time, and LOCK_WRITE.onEvent → record() appends to evidence without locking. The "proceed silently tolerated re-entrancy" hazard does not materialise in src/.
  • Stale-lock recovery still works (abandoned lock with mtime −11 s is taken over, 3/3 isolated runs, lock cleaned) and a live holder still costs the full production budget: refusal at 5009 ms, 0 rows written. DEFAULT_TIMEOUT_MS, STALE_MS and onEvent are untouched, and shrinking the default to 50 ms kills 12 existing tests, so the budget really is pinned.

BLOCKING — memory_merge_review says "nothing was done" after it has retired the row

markManySupersededReport (src/memory.ts:421-473) takes one lock per file in a sorted loop, and markSuperseded(ts, …) is just that batch with one entry — so it still walks every day file and can refuse at file k+1 after publishing file k. I reproduced it from scratch at your head (two day files, later file held with a fresh lock):

markSuperseded: THREW Error: memory store is busy: 2026-10-30.logfmt has been locked for 5006ms — retry
loser row superseded_by on disk: "SURVIVOR"

The loser is retired on disk. mutated in src/index.ts:1053 flips only after that promise resolves, so the catch at :1090-1099 takes the !mutated arm and the user reads:

merge_review blocked: the store was busy past the lock budget — nothing was done. Retry.

The tool description still promises "Fails closed (no partial apply)", and your own new README row says the opposite. Three further instances of the same root, all created by this PR (on 525ed89 the same probes never throw):

  • markManySuperseded partial: threw busy with 2026-01-01.logfmt already carrying superseded_by=SURVIVOR-TS and today's row untouched.
  • src/gates.ts:480-484 pushes into ctx.durable only after the awaited batch, so a drift/canonical batch that lands in file 1 and refuses at file 2 leaves the ledger empty and memory_update prints "Nothing was written." over tombstones that exist — the exact lie gateDurable was introduced in #158 to kill. (Code-level inference on top of the primitive I did prove; I did not stage a live GATE-2 drift.)
  • memory_forget (prune) and memory_decay abort mid-run and surface a raw busy error — honest wording, but no prune/decay_applied line names the partial that landed.

Ask: make the report what it already claims to be — push into a caller-supplied durable sink per published file (or throw an error carrying marked[]), flip mutated per durable publish, reword the two messages to name the file the batch stopped at, and drop or scope the "no partial apply" sentence in the tool description.

Residual — silent loss moves from the store to telemetry

  • captureSession has no local catch, so a busy throw skips both the per-candidate auto_capture_* line and recordCaptureLag, and is eaten by catch {} / guarded() (src/index.ts:1583-1604, 282-288). Before this change the row at least reached disk; now a candidate can vanish with no trace at all. Consider catching the busy error in the capture loop and recording auto_capture_refused.
  • recordHits swallows the new refusal (src/hits.ts:119-131), so use-ledger lines can be dropped under contention. Decay and consolidation read that ledger, so a missing "used" line makes a live row look dead. A comment or a counter in memory_status would be enough.

Nits

  • "Focused lock suites: 22 pass, 0 fail" is 21 pass + 1 skip off Windows — the skipped one is the win32-only ACL block at test/lock.test.ts:212. Say "22 tests, the 22nd Windows-only".
  • LOCK_RESTORE's fail policy is unpinned. Flipping it to "proceed" kills 0 tests (undo.test.ts + undo-ownership.test.ts + lock.test.ts: 33 pass / 1 skip), and nothing in the suite references LOCK_RESTORE. Pre-existing gap, but this PR's new README sentence tells users a restore refuses when busy, so please add the one test that holds a file and asserts a restore refuses.
  • viewer editMemory under contention is untested (mutate.ts:71-115): appendMemory then markSuperseded are two separate locks, so if the second refuses, the edited row survives beside an active original. Not a false success, but the duplicate-active-row state is new here.
  • Your test/supersede-batch.test.ts:167-171 comment rewrite sits inside a describe.skipIf(process.platform !== "win32") block — I could not exercise the defence whose justification it changes, so that edit travels on your Windows run, not on mine.

No test theater: exact-byte and exact-owner-token assertions, toHaveLength(2), no >= 1, no mocks, real entry points driven in a real child process behind the requireTempPath guard. Scope is tight — the logfmt.ts and supersede-batch.test.ts edits only retire claims this change makes false.

Not verified here: anything Windows/Bun 1.4.4-specific (the ACL test, the win32 comment, and your 731/12/0 gate numbers, which I re-ran on darwin/1.4.3), and scripts/merge-gate.ts as a single command (I ran its four components separately).

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Addressed in acd7a68. The blocker reproduces on fbf1d61 too: my real-lock probes observed the loser retired while merge said “nothing was done,” and a canonical retirement on disk while update said “Nothing was written.”

Blocking outcome reporting

  • markManySupersededReport now appends to a caller-supplied durable sink immediately after EACH file publish, before returning/unlocking or attempting the next file. The single-row/count wrappers pass that sink through. Gate drift/canonical batches, duplicate-update completion, and merge consume it; they no longer depend on the whole promise resolving to learn about a durable retirement.
  • Merge/update partial replies name completed IDs and include the busy filename from the underlying error. Merge's description now distinguishes pre-write refusals from later partial application.
  • Forget uses a per-file deletion receipt that is updated only after publication. Partial forget/decay emit receipts naming the rows actually changed, with partial=true, and return partial-result guidance. A refused later tombstone write is also covered by forget's partial-result path. This is reporting, not transactional rollback.

Residuals and nits

  • Capture records auto_capture_refused for each failed candidate, or auto_capture_partial with completed gate-retirement IDs; the loop continues and lag is recorded. A two-candidate real-contention test checks both receipts, lag, and unchanged store bytes. With the old handler restored, capture exits without the lag receipt and the test fails.
  • Documented use-ledger contention loss at recordHits' catch. No claim of lossless telemetry or a new counter.
  • Corrected the platform qualification in the PR body. Current focused validation is 79 pass on Windows and 76 pass / 3 Windows-only skips on Linux/WSL, both Bun 1.4.4.
  • Added a real held-file restore refusal/retry test using the actual LOCK_RESTORE policy. Switching that policy to proceed makes the test fail.
  • Added the viewer edit interleave: the replacement persists while retirement of the held original refuses. Both active rows are asserted; the thrown PARTIAL error names both IDs and says the original was not retired by this edit.
  • Both Windows-only supersede retry tests pass in the focused run and full gate.

Nine tests added in this follow-up. Six partial-outcome cases were red on the prior head; the pre-publication control and restore case were green, and the separate capture old-handler probe was red. The batch retry test also confirms already-retired rows are not counted again.

Full Windows gate passed: 772 unit tests, 11 skipped; 11 E2E tests; typecheck and lint (409 existing warnings). The PR body is rewritten around the final behavior; hosted CI is running on the new head. Please re-review the partial-outcome changes when convenient.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2: APPROVED

Re-verified at acd7a68 (macOS / Bun 1.4.3). This is the fix I asked for, in the shape I asked for, and it closes the residuals too.

The blocking case, re-run against the new head. Same probe as round 1 — two day files, later file held with a fresh lock, retire a row that lives in the publishable file:

markSuperseded: THREW | Error: memory store is busy: 2026-10-31.logfmt has been locked for 502…
durable sink: ["2026-01-09T00:00:00.000Z"]
loser superseded_by on disk: "SURVIVOR"
=> merge_review would print: PARTIAL (names the retired row)

markManySupersededReport pushes ids into the caller's sink immediately after writeAtomic, inside the per-file lock (src/memory.ts:467-470), so a rejected promise can no longer erase what landed; markSuperseded and markManySuperseded thread it through, and prune reuses one accumulator object for the same reason. The mutated boolean is gone — the decision is now made from durable facts rather than from where a promise settled.

Also closed, all of them:

  • memory_update now says PARTIAL and names the rows the gate already retired (the "Nothing was written." lie is gone), and the gate pushes into ctx.durable via the sink instead of after the awaited batch.
  • memory_forget and memory_decay catch the mid-run refusal, name the published rows, and write an audit line (decay_applied … partial=true) that survives — my round-1 complaint was that a partial left no evidence naming it.
  • Residual 1: capture now records auto_capture_refused, or auto_capture_partial when some candidates landed, and still records lag. That was the one place the change could lose data with zero trace.
  • Residual 2: recordHits carries the comment stating the ledger is best-effort under contention, so decay/consolidate must not read a missing line as proof of non-use.
  • NIT-2: viewer editMemory now throws a message that distinguishes "replacement IS on disk; original WAS / WAS NOT retired" — the duplicate-active-row state is at least named.
  • NIT-3: restore uses its real fail-closed policy and preserves the held file is the missing LOCK_RESTORE pin; it passes on the pre-fix tree, as it should (the policy was already correct — the promise in the README was what was unpinned).
  • Tool description no longer claims "no partial apply", and the README row tells the operator what a PARTIAL reply means before they retry.

Verification

  • New test/lock-partial-outcomes.test.ts: 9 pass at head; on the pre-fix merge c9af78e 8 of 9 fail (batch receipt, first-file refusal, merge_review, canonical update, viewer edit, forget, decay, capture). The one that passes pre-fix is the restore-policy pin, so nothing in that file is theater.
  • Gates at head: typecheck clean, biome exit 0 at 409 warnings — flat versus main, unit 772 pass / 11 skip / 0 fail, real-host e2e 11 pass / 0 fail. Hosted CI: lint / test / test-windows / smoke all green.
  • Round-1 verifications still hold (I did not re-run all of them): the nine fail-on-base contention regressions, the clean self-contention audit, stale-lock takeover, and the untouched 5 s production budget.

One thing I still cannot verify here: the Windows-only ACL case and Bun 1.4.4 behaviour generally — my numbers are darwin/1.4.3, and CI is the authority for that half.

@abogartz
abogartz merged commit 79f5238 into abogartz:main Oct 31, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.14.26 🎉

The release is available on:

Your semantic-release bot 📦🚀

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.

Whole-file publishers proceed UNLOCKED past the 5s lock budget — documented as never losing a write, silently destroys rows

2 participants