Skip to content

readLines can return a partial trailing record during concurrent append #198

Closed

Description

@WhollyMindless

Follow-up from #189's Linux CI failure, independently reproduced on current main d69691c (Bun 1.4.4, Linux under WSL). This is separate from #189's evidence-attribution change and from the cached-BunFile replacement reads fixed in #181/#184/#187.

Observed behavior

readLines uses node:fs/promises.readFile(file, "utf8"). During the existing three-child-process append workload, it can return a trailing fragment of a row. The file is complete on the immediate next read. This can expose incomplete row content to readers; I have not established permanent on-disk loss or traced the underlying syscall/runtime mechanism.

On untouched current main:

bun test test/concurrency.test.ts --test-name-pattern 'a reader process always parses a complete file' --rerun-each 100

One of 100 repetitions failed (partial !== 0). This corroborates the earlier 3/100 reproduction on 525ed89 recorded in #189. These are synthetic workload observations, not a field failure rate.

A second 100-repetition pass added ONLY diagnostic reads/logging to readLines before its existing split/return:

if (text && !text.endsWith("\n")) {
  const after = await readFile(file, "utf8");
  console.error(JSON.stringify({
    bytes: Buffer.byteLength(text), tail: text.slice(-140),
    nextBytes: Buffer.byteLength(after), nextTail: after.slice(-140),
  }));
}

It captured four partial reads, all 24,576 bytes long; immediate rereads were 24,592, 24,608, 24,606, and 24,608 bytes and ended with complete rows/newlines. Two representative first-read tails:

... ts=2026-10-30T21:45:12.953Z type=learning scope=stress content="ch
... ts=2026-10-30T21:45:18.685Z type=learning scope=str

The immediate next reads complete these as content="child row 15 <pid>"\n. The 24,576-byte boundary suggests a page/buffer boundary worth investigating; it does not by itself identify whether the runtime or concurrent file visibility is responsible.

The test also misses one shape

The diagnostic pass reported three failed repetitions despite four observed fragments. The current assertion checks only startsWith("ts=") and includes(" content="). A trailing content="ch satisfies both despite truncation. So tightening the test to validate the complete expected row/payload is part of the work, not merely obtaining a green repeat.

Suggested investigation / acceptance

Hosted failure that led here: https://github.com/abogartz/opencode-self-improvement/actions/runs/41106043386/job/124236024583

This records the inherited blocker without expanding #189 into a store-I/O rewrite. No fix is claimed yet.

Activity

  1. WhollyMindless commented on Oct 30, 2026

    @WhollyMindless
    ContributorAuthor

    Claiming the investigation: no other assignee, claim, or matching PR is visible. I will isolate concurrent append visibility from read-size handling, preserve static unterminated-file compatibility, and pin the failing boundary before proposing a fix. Please redirect if someone has started this elsewhere.

  2. WhollyMindless commented on Oct 30, 2026

    @WhollyMindless
    ContributorAuthor

    Investigation update: the partial-record observation is reproducible outside Bun. A standalone Python probe uses one os.write(fd, row) per 103-byte newline-terminated row on an O_APPEND descriptor, while another process opens and reads the file. It observed both intermediate file sizes and reads ending inside a row. Example: fstat reported 83,121 bytes (a complete-row boundary), but the following read returned 90,112 bytes (90 bytes into a row). Another fstat returned 176,128 bytes (101 bytes into a row). The final file was complete. This establishes that switching from Bun's reader alone cannot guarantee record-complete concurrent reads.

    I also tested a scratch-only prototype, based on main d69691c:

    • Inside appendMemory's existing writer lock, reuse the full day-file read already needed for timestamp uniqueness, then publish the old bytes plus the new row through writeAtomic rather than in-place append.
    • Apply fix: refuse shared store writes after lock timeout #197's fail-closed LOCK_WRITE policy so a timed-out writer cannot overwrite the holder's changes.
    • Leave readLines unchanged, including its static unterminated-file behavior.

    Results on Linux/WSL, Bun 1.4.4: the original reader test passed 100/100 repetitions; the entire concurrency file passed 7/7. These are supporting stress results, not a deterministic proof or a completed fix. The prototype is not pushed and has not had a full gate or Windows validation.

    The implementation decision needs care: atomic replacement changes a daily append into a whole-file write, increases I/O and Windows rename contention, and does not solve concurrent append visibility in evidence/deletion logs. Applying it blindly to every appendLog call would impose whole-log rewrite costs and require exclusion for callers that do not currently share a writer lock. Conversely, trimming the unterminated tail in readLines would silently discard legitimate static last rows. A stable-size check or arbitrary retry count is not a record-commit guarantee either.

    My recommendation is to evaluate atomic publication for daily memory files after/on top of #197, with deterministic publication-boundary tests, large-day-file cost measurements, and Windows rename tests; handle append-only log framing as an explicit separate scope. This is the concrete candidate now under investigation, not a claim that #198 is resolved.

    Native reproducer (temporary synthetic data only):

    import os, tempfile, multiprocessing as mp, json
    row = b'x' * 102 + b'\n'
    def writer(path, ready):
        fd = os.open(path, os.O_WRONLY | os.O_APPEND)
        ready.set()
        for _ in range(100000):
            os.write(fd, row)
        os.close(fd)
    if __name__ == '__main__':
        with tempfile.TemporaryDirectory(prefix='osi198-native-') as root:
            path = root + '/rows'
            with open(path, 'wb') as f:
                f.write(row * 230)
            ready = mp.Event()
            p = mp.Process(target=writer, args=(path, ready))
            p.start(); ready.wait()
            bad = []
            while p.is_alive():
                fd = os.open(path, os.O_RDONLY)
                size = os.fstat(fd).st_size
                data = os.read(fd, 20_000_000)
                os.close(fd)
                if size % len(row) or len(data) % len(row):
                    bad.append({'size': size, 'read': len(data)})
                    if len(bad) >= 5:
                        break
            p.join()
            print(json.dumps({'observations': bad, 'final': os.stat(path).st_size}))
  3. WhollyMindless commented on Oct 30, 2026

    @WhollyMindless
    ContributorAuthor

    Further local validation of the daily-memory atomic-publication prototype (main d69691c plus #197's fail-closed LOCK_WRITE policy; no PR or push yet):

    • Strengthened the existing reader stress check to validate the complete expected payload, check child-process exit status, preserve all 200 seed rows, and verify all 50 row indices from each of three writers. This closes the truncated-quoted-content blind spot described above. 100/100 repetitions passed on Windows and 100/100 on Linux/WSL, Bun 1.4.4.
    • Added a deterministic publication-boundary probe: deliberately write only a fragment of the replacement temporary file, read the destination at that exact point, then finish publication. The destination remains the complete old file; afterward both old and new records are intact.
    • Verified an existing static row without a trailing newline remains readable and survives a subsequent append as a separate row. The original appendMemory concatenates the new record onto that row; the candidate inserts the missing separator.
    • Verified the Windows contention contract with a real open reader handle, first proving that the handle blocks rename. An append fails after the existing replacement retry window, leaves the original bytes intact, and cleans up its temp/lock files. Retrying after releasing the handle succeeds. This is a real behavior tradeoff: the old in-place append succeeds under that same reader handle. The candidate favors complete publication and an explicit retryable failure.
    • The full Windows gate passed: typecheck, lint, 755 unit tests (11 skipped), and 11 real-host integration tests. The focused publication/logfmt/concurrency run also passed (27 tests).
    • A local 10 MiB synthetic day-file exercise preserved the entire original byte prefix and all rows across ten new appends. This is a capacity sanity check, not a throughput benchmark or a bound on larger stores.

    The two publication probes also passed on Linux; the Windows handle probe is intentionally skipped there. The new probes fail against the original appendMemory implementation, although the handle probe specifies the candidate's changed behavior rather than asserting that the old successful append is itself defective.

    My recommendation remains a focused daily-memory publication change built on #197, with whole-file-write cost and Windows retry behavior stated explicitly. Evidence, hits, blocklist, tombstone, and deletion/audit append paths remain outside this prototype; #198 should not be represented as fully resolved by the daily-file change. I would welcome direction on that scope before turning this into another PR. If the write-cost/availability tradeoff is not wanted, it is fine to decline the approach; these experiments can remain investigation evidence.

  4. WhollyMindless commented on Oct 31, 2026

    @WhollyMindless
    ContributorAuthor

    The daily-memory candidate is now posted as #203 at 7c1dfc4, refreshed onto main bf9f4d2 after #197. It intentionally references this issue without closing it.

    The current Windows full gate passes (832 unit/scenario tests, 11 skipped; 11 real-host integration tests; typecheck/lint). Focused publication/concurrency tests also pass on Linux/WSL (9 pass, one Windows-only skip). The PR includes paired measurements at 0.1/1/10/50 MiB, raw samples, reproduction instructions, and an explicit test of the Windows held-reader refusal/retry tradeoff.

    This remains an optional daily-memory publication approach. Evidence/use/rejection/blocklist/audit logs are outside its scope, and declining the write-cost or Windows-availability tradeoff is entirely fine.

  5. added
    bug
    severity:medium
    verified-on-main
    on Nov 1, 2026
  6. abogartz commented on Nov 1, 2026

    @abogartz
    Owner

    Verified fixed on main (054815a, v0.15.4): readLines now reads metadata and bytes through one readFile handle (src/logfmt.ts:181-192), closing the cached-size crop, and the publication-boundary behavior is pinned by test/append-publication-198.test.ts (merged via PR #203). No partial trailing record is observable on the fixed path. Closing as shipped left to maintainer.

  7. abogartz commented on Nov 2, 2026

    @abogartz
    Owner

    Closing on the verified-on-main call. Fixed by PR #203: src/store/files/append.ts reads the prior file once and publishes the complete replacement through writeAtomic with a fileIdentity anchor (line 146, 173), so a concurrent reader sees either the whole old file or the whole new one, never a partial trailing record.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugseverity:mediumverified-on-main

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions