Skip to content

fix: read complete files across atomic replacements - #181

Merged
abogartz merged 5 commits into
abogartz:mainfrom
WhollyMindless:fix/atomic-read-lines
Oct 29, 2026
Merged

abogartz merged 5 commits into
abogartz:mainfrom
WhollyMindless:fix/atomic-read-lines

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

An atomic replacement can make readLines return a truncated row even when the file on disk is complete. Bun.file(path).exists() or .size caches the old size; if a larger file replaces the path before .text(), the read can crop the replacement to the old byte count. A standalone Windows/Bun 1.4.4 probe returned 23 bytes from a complete 10,018-byte replacement. Callers that subsequently rewrite the read contents can persist the missing rows.

Use node:fs/promises.readFile so the metadata and bytes come from the same opened file. Missing files still return an empty list, and line filtering is unchanged. Other read errors propagate. This deliberately exposes directory and symlink-loop errors (EISDIR / ELOOP) where the old existence check could silently return an empty list. Decoding is explicitly UTF-8: a leading BOM is retained rather than stripped by Bun's text decoder; the logfmt parser accepts it.

test/read-lines-atomic-replace.test.ts primes a real BunFile's metadata, atomically replaces the file with a larger one, and supplies that cached handle only for the tested path. Other paths delegate to the real factory. It mocks no bytes and uses no sleeps. The original reader returns one truncated row instead of two complete rows. Additional coverage pins missing/empty files, whitespace-only-line filtering, and propagation of a non-ENOENT error. The existing concurrent-reader assertion is unchanged by this PR.

Scope: this fixes readLines, not every store reader or concurrent in-place write. The maintainer's Finding A identifies additional sites, including snapshots and undo; those are tracked separately in #184. The follow-up should not be interpreted as fixed by this PR.

Validation on Windows / Bun 1.4.4 after the review updates:

  • Original regression: red before the source fix, green afterward.
  • Focused atomic-reader, logfmt, and concurrency files: 27 pass, including the three Windows handle/rename cases.
  • Full bun run gate: typecheck and lint pass (existing warnings remain), 695 unit tests pass with 12 existing skips, and 11 real-host end-to-end tests pass.
  • All four hosted checks now pass on the refreshed fcf50b0, including Windows. This head includes current main's README changes plus test/comment nits; the runtime reader implementation is unchanged from the approved e418d07.

The deliberately failing regression commit ca7dd09 remains in published history. Recommend squash-merging this PR for bisectability; #174 carries the same stack ancestry and should also be squash-merged if retaining that ancestry. The merge method is the maintainer's choice.

#174 includes this fix for its CI runs. Please consider this PR first; after it merges, I will refresh #174 against main so its remaining diff contains only the CI proposal.

Please feel free to reject or close this PR if you prefer another solution or do not want the change. This is your project; there is no expectation to accept this implementation.

WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 29, 2026

@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.

Verdict: APPROVE (scoped to this two-file diff — see "Finding A", which this PR does not claim to fix but which I measured live at this head)

I found no defect in the diff itself. The fix is correct, it is the right fix, and I reproduced the defect it removes on my own platform without any mock. I am approving, but I do not want this merge to be read as "the store now reads consistently": the same metadata-then-text() pattern sits in five other readers, and one of them — the /undo safety net — is cropping snapshots at a 38% rate under contention on the head commit.

Environment for everything below: macOS darwin 24.6.0 arm64, host Bun 1.4.3; I re-ran the load-bearing experiments a second time with Bun 1.4.4 (bunx --bun [email protected], the version CI pins). No Linux available locally (docker daemon down) and no Windows — those gaps are named explicitly at the end rather than assumed away.


1. The diff is what the body says it is

git diff --stat origin/main...HEAD: src/logfmt.ts +10/−4, test/read-lines-snapshot.test.ts +52 (new), 2 files total. src/logfmt.ts:184-196 replaces Bun.file().exists() + .text() with readFile(file, "utf8") (:189), ENOENT → [] (:191), everything else rethrows (:192), filter unchanged (:194). Nothing else in the tree moves — test/concurrency.test.ts is untouched, confirming "that assertion remains unchanged".

2. The defect is real — and it is not Windows-specific

This was the claim I most wanted to break, because the shipped test goes through a spyOn and a mocked-away race is worth little. I wrote a standalone probe with no mock at all (probes-181/probe-a-nomock.ts): create a 23-byte file, take a metadata read on a real BunFile, atomically renameSync a 10,042-byte file over the path, then await f.text().

primer on the same handle Bun 1.4.3 (macOS) Bun 1.4.4 (macOS)
await f.exists() then text() 23 of 10,042 bytes — TRUNCATED TRUNCATED
await f.size then text() 23 — TRUNCATED TRUNCATED
exists() twice then text() 23 — TRUNCATED TRUNCATED
no metadata read, text() only 10,042 — full full
await f.lastModified then text() 10,042 — full full

The cached size is never refreshed for that handle (post-replacement exists() → true, size → 23, text() → 23 bytes). So: (a) your Windows/1.4.4 "23 bytes from a complete 10,018-byte replacement" is exactly what this produces here — the mechanism is Bun's BunFile metadata cache, not a Windows quirk; (b) the old readLines was poisoned on every call, because exists() is always the first metadata access; (c) a small correction to the code comment at src/logfmt.ts:185: .size poisons the same cache (src/hits.ts:67 does precisely that — see Finding A).

Real race, no mocks, two processes (probe-d-writer.ts hammers one path with atomic replacements, growing payload, always ending in a well-formed content="END" row; probe-d-reader.ts calls the real readLines from each worktree's src/ and classifies every read):

base 7e72e2f head e418d07
hammered, rep 1 reads 47,967 · 1,042 cropped · 20 torn lines ("ts") reads 66,035 · 0 cropped · 0 torn
hammered, rep 2 reads 67,639 · 1,072 cropped · 13 torn reads 72,386 · 0 · 0
moderate (~1 replace / 2 ms) reads 99,674 · 159 cropped (0.16%) reads 113,337 · 0

Two things follow. The fix eliminates the race completely in ~180k adversarial reads. And the blast radius is bigger than "a truncated row": readLines feeds whole-file read-modify-writes (src/memory.ts:377, :437, :625, src/viewer/mutate.ts:130, src/undo.ts via the same shape), and on POSIX the cropped content is published unconditionally — so the old reader could silently delete every row past the crop on a markSuperseded/prune/viewer-delete. That makes this a data-loss fix, not a read-glitch fix.

For calibration, the repo's own a concurrent reader never sees a half-written file (test/concurrency.test.ts:70) passed 30/30 on base and 30/30 on head here — normal test timing does not hit the window, which is exactly why your deterministic mock is the right call rather than a cop-out.

3. Red-on-base / green-on-head, reproduced

  • scratch worktree at the merge-base 7e72e2f + the new test file (== the tree of ca7dd09): 1 pass / 1 fail, Expected length: 2, Received length: 1 — on Bun 1.4.3 and Bun 1.4.4.
  • PR head e418d07: 2 pass on both versions.
  • The mock is not fabricating the failure: it hands the old reader the pre-rename handle and the old reader then truncates the real 10 KB file (the received value is a cropped real read). No sleeps (grep: no setTimeout/sleep/Date.now in the file). The new reader never calls Bun.file, so the spy is inert there — correct for a regression pin: it fails precisely if someone restores the exists()-then-read shape.

4. Full local gate, head vs base (bun run gate, macOS, Bun 1.4.3)

unit e2e typecheck biome
base 7e72e2f 692 pass / 12 skip / 0 fail (704 tests, 69 files) 11 pass / 0 fail clean 400 warnings, 119 infos (140 files)
head e418d07 694 pass / 12 skip / 0 fail (706 tests, 70 files) 11 pass / 0 fail clean 400 warnings, 120 infos (141 files)

Delta is exactly the two new tests; skip count unchanged; the new test file adds zero lint warnings. Both gates print merge gate: all green. Focused trio (read-lines-snapshot + logfmt + concurrency) here: 23 pass / 3 skip / 0 fail; the 3 skips are the win32-only describe.skipIf(process.platform !== "win32") at test/logfmt.test.ts:136, so your "26 pass" on Windows is consistent, not inflated.

5. Behavior change beyond ENOENT (this is where "unchanged" is not quite true)

probes-181/probe-b-matrix.ts ran both implementations side by side. Identical: missing file, missing parent, broken symlink, empty file, "" path, /dev/null, file mode 000 (EACCES throws in both — the old reader never swallowed that either), CRLF (both keep the \r), FIFO (both block), NUL-byte path (both ERR_INVALID_ARG_VALUE), and the ENOTDIR family (a path component that is a file, a trailing slash — both return [] on Bun). Different:

path old new
directory [] throws EISDIR
symlink → directory [] throws EISDIR
symlink loop [] throws ELOOP
file starting with a UTF-8 BOM BOM stripped \uFEFF kept on line 1
file starting FF FE Bun.text() sniffs UTF-16 → garbage ��ts=1 (arguably better)

I chased whether any of these can actually bite, and the answer is no: memoryFiles() (src/memory.ts:155-166) and src/triggers.ts:324-331 both feed readLines from Bun.Glob("*.logfmt").scan(), and I verified scan does not yield directories (probe-e-dir.ts); every other call site takes a path from memoryFiles(), from evidenceFileFor() (schema-validated date, src/index.ts:942, read at :949) or from an already-located row. So the "store silently looks empty → store throws" flip is a real semantic change with no reachable caller today — I consider throwing the better default (a store that looks empty is what turns a transient FS fault into a whole-file republish), but it is undocumented, so see nit 4. The BOM difference is harmless because parseLine's key regex is [A-Za-z0-9_.-]+=, which skips a leading \uFEFF: I confirmed a BOM'd store file still yields 2/2 valid rows through the new reader.

Equivalence where it matters is pinned by fuzz (probe-f-equiv.ts): a 20,000-line corpus of quoted/escaped/tabbed/CR/unicode/whitespace-only lines produced 15,759 lines, byte-identical between old and new; a 46.8 MB store file reads 200,000/200,000 lines identically and faster (27 ms vs 31 ms). So "keep line filtering unchanged" holds.

6. Finding A — the same pattern is live in five readers this PR leaves alone (not blocking this diff)

The defect is not exists(); it is metadata-then-text() on the same BunFile handle. Grepping that shape in src/:

  1. src/memory.ts:573-576 snapshotFiles() — Bun.file() → exists() → Bun.write(snap, await f.text()), with several syscalls (claimSnapshot) widening the window. I drove it against a hammering writer on this PR's head: 2,568 of 6,712 snapshots (38.3%) were missing the final row and ended mid-line (sample: snapshot 3702B vs live 3627B, last="ts=t19 seq=153 content=\"xxxx). Base is the same (2,617/6,735). This is the snapshot-before-mutate copy that /undo restores from — a cropped snapshot is rows that undo can never bring back.
  2. src/undo.ts:229-230 — (await cur.exists()) ? rows(await cur.text()) : [], feeding the divergence partition and the publish at src/undo.ts:317. A cropped live read during a restore is store data loss.
  3. src/blocklist.ts:60-63 → publishes at :67: a cropped read republishes a shorter blocklist (silently un-blocks rows).
  4. src/hits.ts:66-73 → publishes at :74: .size (the cache poison, see §2) then .text(), halving a possibly-cropped ledger. Telemetry only.
  5. src/portable.ts:302-315 — import file read: a crop means an import silently ingests fewer rows than it reports. (src/status.ts:250-252 is the same shape but wrapped in catch → null, i.e. benign.)

None of this is caused or worsened by the diff, and the PR body never claims to fix it, so I am not holding the PR for it. But the body's one-line principle — "the metadata and bytes come from the same opened file" — is the correct rule for all five, and #1/#2/#3 are read-modify-write publishers, i.e. strictly more dangerous than the site that was fixed. Please file it and apply the same 4-line change there (the test in this PR is a template; probe-g-snapshot.ts is a ready-made red repro).

7. Non-blocking nits

  1. "Other read errors propagate" is claimed but unpinned. Nothing in the suite asserts a non-ENOENT throw. One line (expect(readLines(dir)).rejects.toThrow(/EISDIR/), or a chmod 000 case) would pin the half of the change that is not the ENOENT path.
  2. spyOn(Bun, "file").mockReturnValue(cached) (test :34) returns that handle for any path during the window. mockImplementation((p) => (p === file ? cached : real(p))) would keep it hermetic if readLines ever reads more than one file.
  3. The first commit ca7dd09 is red by construction (I verified its tree: 1 fail). If this merges with a merge commit like the recent ones, git bisect inherits a failing commit — squash on merge, or accept deliberately.
  4. The comment at src/logfmt.ts:185-186 says only exists() caches; .size does too (src/hits.ts:67). Worth one clause so nobody reintroduces the bug through .size. The directory/ELOOP flip (table in §5) also deserves a line, since it is a caller-visible semantic change.
  5. The filename read-lines-snapshot.test.ts promises snapshot coverage; the file tests the reader, and snapshotFiles() — the site that still has the bug — is untouched. Minor naming/expectation mismatch.

8. What I could not verify (not silently accepted)

  • Linux (ubuntu-latest, Bun 1.4.4) — no Linux on this host (docker daemon down). Unverified specifically: that this test goes red on Linux if readLines is reverted. Indirect evidence it does: the defect is Bun's BunFile metadata cache, reproduced here on darwin at both 1.4.3 and 1.4.4 with no mock and no timing dependence; CI green at this head only proves green-after-the-fix. If you want the pin to be provably load-bearing on the gating leg, a one-off git revert push of the src commit on a branch and a look at the Linux test job would settle it in five minutes.
  • Windows share-mode side of the switch — I cannot test Windows. The concern I raised and could not discharge: this repo's own test states node handles "share read/write but NOT delete: rename is blocked" (test/logfmt.test.ts:143), so a node:fs reader may block a Windows rename-over where Bun's own reader did not, i.e. more transient EPERM in handoverRename. Why I judged it acceptable rather than fine: all seven whole-file publishes at this head pass a since anchor (src/hits.ts:74, src/undo.ts:317, src/viewer/mutate.ts:137, src/memory.ts:389, :462, :644, src/blocklist.ts:67), so a reader-blocked handover lands inside the 2 s anchored retry (src/logfmt.ts:159-182); libuv/node handles on the very same store files already exist on main — every append is appendFile (src/logfmt.ts:96), and node handles are used for the snapshot and export paths (src/memory.ts:558, src/portable.ts:120); and the win32-only tests that exercise exactly handle-vs-rename contention (test/logfmt.test.ts:136-240) are in the 26 you ran green, with test-windows green at this head. Still: I did not run them, so that leg rests on your Windows run, not on my evidence.
  • The #174 / 854ca46 Linux partial-row observation — out of scope for this review (I stayed off other PR/issue threads). My §2 torn-line results independently show that class of failure is real on darwin; I make no claim about that specific job.
  • Multi-hour / real-store exposure — my probes are synthetic; I did not run a long-lived dogfood.

Thanks for the deterministic-repro-then-fix split and for keeping the ENOENT contract explicit; the probe agreement across macOS 1.4.3/1.4.4 is what makes this worth merging ahead of the CI-parallelism discussion. Ship it, and please open the follow-up for snapshotFiles/restoreSnapshot/removeBlock/rotateIfNeeded.

@WhollyMindless

WhollyMindless commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the independent verification and the scoped approval. Finding A is now tracked in #184. I reproduced the snapshotFiles crop locally on Windows / Bun 1.4.4: a real cached handle supplied through a path-specific test seam produced a 23-byte snapshot of a complete 10,040-byte replacement. The issue distinguishes that deterministic repro from your no-mock macOS measurements and from the other sites that still need caller-level regression coverage.

Addressed the small nits at fcf50b0, after merging main's README update:

  • Added a real-directory case that requires EISDIR to propagate.
  • Limited the Bun.file spy to the source path; other paths use the real factory.
  • Renamed the test to read-lines-atomic-replace.test.ts so it does not suggest snapshotFiles coverage.
  • Expanded the source comment to include .size and documented the error/decoding differences in the PR description.

The runtime implementation is unchanged from the approved head. The full Windows gate passes: 695 unit tests, 12 existing skips, 11 end-to-end tests, typecheck, and lint. The focused reader/logfmt/concurrency run passes all 27 cases, including all three Windows-only rename-contention cases. CI update: all four hosted checks now pass on fcf50b0, including Windows. Linux red-on-base remains an explicitly unverified point rather than something inferred from green CI.

I recommend squash-merging to avoid retaining the intentionally red ca7dd09 in main's bisect history. #174 carries the same original stack commits, so that consideration also applies there if its ancestry is retained. I have preserved published history and left the merge method to you. The remaining reader fixes stay in #184 so they can be tested and reviewed separately.

@abogartz
abogartz merged commit 2e829b4 into abogartz:main Oct 29, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.14.20 🎉

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.

2 participants