Skip to content

Retiring one row locks one day file - #373

Merged
abogartz merged 2 commits into
mainfrom
215-lock-narrowing
Nov 9, 2026
Merged

abogartz merged 2 commits into
mainfrom
215-lock-narrowing

Conversation

@abogartz

@abogartz abogartz commented Nov 9, 2026

Copy link
Copy Markdown
Owner

What this does

Superseding one memory used to lock, read and scan every day file in the store, so the cost of retiring a single row grew with the age of the install. It no longer does: it opens the one day file the row actually lives in.

The store is a directory of daily YYYY-MM-DD.logfmt files. Every write path that rewrites a whole file takes a per-file lock first (that is what keeps two sessions from clobbering each other — see #89 and #107). The single-row mutations took that lock on all of them, because the code walked the store looking for the row instead of knowing where it was.

But a row's own ts names its file: appendMemory mints the timestamp at write time and appends to that same day's file, so 2026-01-29T10:00:03.000Z is in 2026-01-29.logfmt. markManySupersededReport, clearSuperseded and releaseQuarantine now try that file first and stop as soon as they have seen the row.

The mapping is treated as a hint, never as proof. A store edited outside the plugin can hold a row in a file its ts does not name, so the walk still runs over the remaining files until the row turns up — that is the behaviour this replaced, just in a better order. A test pins the mis-filed row: it is still found and still retired.

prune (what memory_forget calls) deliberately keeps the full sweep, with a comment and a test saying why: a forget is addressed by scope and type, not by ts, so the only way to know which files match is to look. Narrowing it to a pre-pass would let a row appended during the forget survive it.

Measured

Warm, synthetic store, medians (loadAll = read the whole store once):

store loadAll supersede ONE row, before after
30 day files × 10 rows 1.0 ms 6.9 ms 0.7 ms
365 day files × 10 rows 13 ms 74.8 ms 1.1 ms

The ticket's gate was "within 5× loadAll"; a single-row supersede is now faster than one full read, because a full read still opens every file.

Tests

test/lock-narrowing.test.ts, on a 30-day-file fixture, asserting lock acquisitions — a narrowed sweep and a full sweep leave an identical store, so the only honest assertion is about which files were locked. A hook in holdFileLock records acquisitions; production never installs it and pays one undefined check.

  • RED on main, for exactly the reason the ticket names: supersede / clearSuperseded / releaseQuarantine each locked all 31 files. GREEN: exactly the one containing file.
  • A row whose ts does not name its file is still found and retired.
  • Contention on the containing file still refuses with busy and writes nothing — narrowing the lock set does not narrow the safety.
  • A supersede of a row that does not exist marks nothing (it pays the full sweep, which is the honest cost of a miss).
  • prune still locks more than one file, pinning the deliberate choice above.

One consequence worth calling out

memory_update's PARTIAL message gained a clause. Before, a busy file usually faulted inside the gate's sweep, and the outer handler printed every row the gate had already retired. Now the fault lands later, in the update's own retirement step, whose message named only the replacement and its target — so the gate's completed retirements silently vanished from the reply. The message now names them too. No existing assertion was relaxed; one test that depended on the old wording was satisfied by fixing the message, not the test.

bun run gate green: 1115 unit tests + 30 terminal/BDD tests against a real host, 0 fail. bunx tsc --noEmit clean; lint at main's baseline (536 warnings).

Closes #215.

)

Supersede, clearSuperseded and releaseQuarantine walked the whole store looking
for the row they were told to change, so each took one lock per day of store age
(365-day fixture: 74.8 ms to retire one row, 13 ms to read everything). A row's
ts names the day file appendMemory wrote it to, so those paths now try that file
first and stop once they have seen the row.

The mapping is a hint, not a proof: the walk still covers the remaining files
until the row turns up, which is what a store edited outside the plugin needs.
prune keeps the full sweep on purpose - a forget is addressed by scope/type, so
a pre-pass would let a row appended mid-forget survive it.

memory_update's PARTIAL gained the gate's already-retired rows: the fault moved
later, out of the sweep and into the update's own retirement, and the message
that used to name them from the outer handler stopped saying so.

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Follow-up from a user-requested adversarial review using GPT-6 Astra, Claude Opus 5.5, and Qwen 3.8 Thinking. I consolidated the independent reports and replayed the reproducers locally. Findings below identify their specific sources; participation in the batch does not imply all three models found every case.

[P2] Preserve retirement correctness when ordinary appends create a cross-file timestamp collision.
Qwen identified the duplicate-timestamp retirement change. I extended the reproduction to the normal append path, so this case does not require a hand-edited or restored store.

I saw the explicit duplicate-ts exception in the comment after supersede.ts:121. The additional evidence is that appendMemory itself can reach it:

  1. Freeze the test clock at 2026-01-05T23:59:59.999Z; call appendMemory twice with distinct normal rows.
  2. The first row receives that timestamp. The second bumps to 2026-01-06T00:00:00.000Z but remains in 2026-01-05.logfmt, because the file was selected before collision adjustment.
  3. Move the clock to 2026-01-06T00:00:00.000Z and append another row. It receives the same timestamp in 2026-01-06.logfmt; uniqueness is checked only within that file.
  4. Supersede that timestamp, then inspect both copies using loadAll().

Differential result with identical normal-appender steps:

  • Main d0929a6: marked=true, 0 active copies.
  • This head 1a7e47b: marked=true, 1 active copy.

The preferred-file walk stops after seeing the timestamp in one file, leaving the other copy active even though retirement reports success. I checked the baseline's append/supersede source hashes against d0929a6; no files were manually seeded for this differential.

This is a narrow UTC-boundary condition; production frequency is unmeasured. But it undermines the assumption that plugin-written timestamps cannot duplicate across files. Please consider preserving the optimization while ensuring a successful retirement cannot leave such a copy live. The performance direction in #215 remains useful.

Synthetic stores and Bun's process-local test clock only; no system clock changes, live store, or production incident claimed.

 review)

The narrowed supersede trusted a row's ts to name its file. appendMemory broke
that trust itself: it picks the day file from the clock and bumps a colliding ts
inside the lock, so at UTC midnight a row whose ts says 01-06 landed in
01-05.logfmt, and the next append wrote the same identity in 01-06.logfmt. A
supersede then stopped at the first copy it saw and reported success with the
second still live.

Two changes, both pinned RED-first:

appendMemory hands a bumped ts to the file it names and takes that file's lock
instead, carrying the bumped identity so the retry cannot re-read the clock and
file the previous day's instant under the next day.

markManySupersededReport, clearSuperseded and releaseQuarantine now address every
place a plugin-written copy can live: the day the ts names, plus the previous
day's file ONLY when a text scan finds the identity in it. Scanning decides what
to lock; the mutation still re-reads under the lock, so the ordinary single-row
supersede costs one lock (365-day fixture: 1.4 ms, against 74.8 ms on main) and a
duplicate retires in both files. A target neither address held still falls back
to the full sweep, as before.
@abogartz

abogartz commented Nov 9, 2026

Copy link
Copy Markdown
Owner Author

Round 3 (e67b12b): the UTC-boundary finding is fixed, RED-first.

Root cause, confirmed. The reviewer is right, and the narrowed path's premise was broken by appendMemory itself. src/store/files/append.ts picks the day file from dateStr() BEFORE the lock because the file name IS the lock key, and bumps a colliding ts INSIDE that lock. At the boundary the bumped ts names the next day while the row is written to the previous day's file, and the next append mints the same identity in the file that name points at. Reproduced against pinned main (d0929a6) before fixing: 0 active copies; on this branch's head: 1.

Fix 1 — the plugin stops writing a row outside its own day. When the bumped ts leaves the day, appendMemory releases that lock, takes the lock on the file the FINAL ts names, and carries the bumped identity with the move. Re-reading the clock there would file the previous day's instant under the next day: the same lie in the other direction. Bounded retry, never two locks held at once.

Fix 2 — a single-row mutation retires every address a copy can have. markManySupersededReport, clearSuperseded and releaseQuarantine now share one filesHoldingTs(ts): the file the ts names, plus the previous day's file ONLY when a text scan finds ts=<value> in it. That is the only shape the plugin can write, so the scan is complete. Scanning decides what to lock; the mutation still re-reads under the lock it takes. A target neither address holds (a store edited outside the plugin, a renamed day file) still falls back to the full sweep.

Cost stays. 365-day fixture, supersede one row: median 1.4 ms vs 74.8 ms on main — one lock on the normal path, because the neighbour is scanned rather than locked.

Pins. the boundary invariant via setSystemTime; a planted duplicate retiring in BOTH files; the existing lock-acquisition contract, unchanged.

Gates. typecheck clean; lint 531 warnings / 147 infos (branch baseline 536/147); 1117 unit tests; e2e 30/30 on a clean serial run.

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified e67b12bb3bd09967c608a6445ea0a88d4abcac69; this supersedes my earlier changes request for the UTC-boundary retirement finding.

I filed #215 and reported the boundary case; this fix is maintainer-authored, and I independently checked the revision in an isolated source archive.

  • Replayed the normal-appender failure across ordinary midnight, year end and leap day: identities now remain distinct and every row lands in the day its final timestamp names.
  • Seeded the legacy neighbouring-file duplicate and verified both copies retire, revive and release quarantine, preserving unrelated tags.
  • Checked 24 concurrent appends at the boundary: all rows remain present with distinct identities and matching day files.
  • The same five probes fail on prior head 1a7e47b and pass here. The existing one-lock normal path, misfiled-row fallback and busy refusal tests also pass.

Validation: 73 focused repository tests plus five independent probes pass on Windows/Bun 1.4.4; typecheck passes. These results cover the reviewed correction and adjacent mutation paths; I did not rerun the full suite, live host or performance benchmark. No additional actionable finding in this revision.

@abogartz
abogartz merged commit e10a550 into main Nov 9, 2026
4 checks passed
abogartz-opencode-self-improvement Bot pushed a commit that referenced this pull request Nov 9, 2026
# [0.21.0](v0.20.0...v0.21.0) (2026-11-09)

### Bug Fixes

* **capture:** a compaction rejection after teardown writes no evidence ([#211](#211) review) ([64b6d37](64b6d37)), closes [#138](#138)
* **capture:** check disposal after every await that can outlive teardown ([#367](#367) review) ([9623129](9623129))
* **capture:** lagSince reads time.created/time.completed — live capture_lag lines carried no lag= ([895237f](895237f))
* **capture:** no user turn also withholds a model-supplied guided quote ([#364](#364) review) ([2c1e07f](2c1e07f))
* **capture:** scan the quote, and quote one fact per row ([#364](#364) review) ([d0e1ee6](d0e1ee6)), closes [#205](#205)
* **capture:** stop a disposed plugin from running the write gate ([#211](#211)) ([49474b0](49474b0))
* **capture:** user provenance comes from structured turns, not labels ([#364](#364) review) ([0fdd8a6](0fdd8a6))
* **retrieval:** guided promotion recomputes tracked epochs (fix A, FINDINGS 2026-11-08 §4b) ([9ff014f](9ff014f))
* **store:** retire every copy; never file a ts outside its own day ([#373](#373) review) ([e67b12b](e67b12b))

### Features

* **capture:** deterministic guided-candidate pre-pass (captureGuidedRules, default off) ([de5ba0e](de5ba0e)), closes [#345](#345)
* **retrieval:** verbatim user quote on guided rows + stage telemetry for hint-miss attribution ([0af9fc4](0af9fc4))

### Performance Improvements

* **store:** a single-row mutation locks the day file its ts names ([#215](#215)) ([1a7e47b](1a7e47b))
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.21.0 🎉

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.

Proposal: reduce unnecessary day-file locks for single-row mutations

2 participants