#7461 · Checkpoint contention invalidates a pinned-WAL test observation
Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro.
1. TL;DR
A database test assumes that a PASSIVE checkpoint always returns usable WAL frame counts. Its background checkpoint worker is still active, so the observation can encounter SQLite's exclusive checkpoint lock instead. SQLite then reports a busy checkpoint with frame counts of minus one, and the test mistakes that sentinel for a small WAL. On two clean checkouts of trusted main, taking the real checkpoint lock in a separate process reproduced the exact assertion failure, with production code unchanged. The uninstrumented five-test suite passed in each checkout; this investigation demonstrates the contention mechanism, not the natural Windows failure frequency.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| The pinned-reader test samples a checkpoint while the worker is alive. | Verified | The test starts and attaches the worker, waits 250 ms, then samples a PASSIVE checkpoint without stopping it. |
| A competing checkpoint lock yields busy=1 and frame counts of -1. | Verified | Real POSIX record-lock contention on SQLite's checkpoint-lock byte returned exactly {busy:1,log:-1,checkpointed:-1} in both checkouts. |
| That return value fails the existing assertion. | Verified | Both runs failed with “expected -1 to be greater than 32768”; the other four tests passed. |
| This is a naturally occurring Windows CI race. | Not independently exercised | No Windows runner was available. The experiment controls the lock directly on Linux, rather than measuring the real worker's overlap frequency or fetching the reported CI URL. |
| The reported production fallback is protected by pausing the worker first. | Verified statically | The worker sets paused before posting starved; the main handler checkpoints and then posts resume. This is not a proof that all possible external database clients are coordinated. |
3. Environment
- Repository: public
get-bb/bb, trustedorigin/mainat030b1b729f28acedc6f86cd65a71cb3678da8124; fetched again before writing this report, still the same commit. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; Python 3.13.9; better-sqlite3 12.11.1; Vitest 4.1.12.
- Two separate clean clones of the target repository, each with a frozen-lockfile installation. The second clone was explicitly detached at the recorded commit.
- No running bb instance, provider, account, network port, or real user database was used. Every test creates and removes its own temporary SQLite directory.
- The normal monorepo build was attempted in both clones. Both stopped on the pre-existing GitHub plugin build prerequisite: the local SDK's
dist/process.jsanddist/host.jswere absent. This did not prevent the focused Turbo database test task from building its upstream dependencies and running.
4. Minimal reproduction
Prerequisites: Linux/POSIX record locks, Python 3, Node and the repository's pnpm version. This is Linux-only diagnostic instrumentation, not a proposed cross-platform committed regression.
- Clone the trusted target and pin the tested commit. Install normally, attempt the normal build, then run the unmodified owning suite. It passed five of five tests in each checkout.
git clone --single-branch --branch main https://github.com/get-bb/bb.git bb-repro cd bb-repro git checkout --detach 030b1b729f28acedc6f86cd65a71cb3678da8124 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build pnpm exec turbo run test --filter=@bb/db -- test/wal-checkpointer.test.ts
The full-build SDK prerequisite failure described above is separate from this reproduction; continue with the focused test task if it occurs.
- Save the following investigator-authored patch as
repro.patch, then rungit apply repro.patch. It modifies only the existing test observation, not the production worker. A child process takes the actual SQLite checkpoint lock, signals readiness, and releases it before the unchanged assertions run. No database mock or added dependency is involved.diff --git a/packages/db/test/wal-checkpointer.test.ts b/packages/db/test/wal-checkpointer.test.ts index 22470c76ef..ba064674da 100644 --- a/packages/db/test/wal-checkpointer.test.ts +++ b/packages/db/test/wal-checkpointer.test.ts @@ -1,4 +1,6 @@ import Database from "better-sqlite3"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; import { closeSync, existsSync, @@ -135,9 +137,29 @@ describe("startWalCheckpointer", () => { await new Promise<void>((resolve) => setImmediate(resolve)); } await new Promise<void>((resolve) => setTimeout(resolve, 250)); - const [pinned] = db.$client.pragma( - "wal_checkpoint(PASSIVE)", - ) as CheckpointRow[]; + const lockHolder = spawn("python3", [ + "-c", + [ + "import fcntl, sys", + "with open(sys.argv[1], 'r+b') as shm:", + " fcntl.lockf(shm, fcntl.LOCK_EX, 1, 121)", + " print('locked', flush=True)", + " sys.stdin.read()", + ].join("\n"), + `${path}-shm`, + ]); + const lockReleased = once(lockHolder, "exit"); + let pinned: CheckpointRow | undefined; + try { + await once(lockHolder.stdout, "data"); + [pinned] = db.$client.pragma( + "wal_checkpoint(PASSIVE)", + ) as CheckpointRow[]; + console.log("Checkpoint lock held:", JSON.stringify(pinned)); + } finally { + lockHolder.stdin.end(); + await lockReleased; + } expect(pinned?.log).toBeGreaterThan(32_768); expect(pinned?.checkpointed).toBeLessThan(pinned?.log ?? 0); - Run the same focused suite again:
pnpm exec turbo run test --filter=@bb/db -- test/wal-checkpointer.test.ts
Expected for a contention-tolerant observation: obtain valid frame counts after the transient checkpoint lock is released, then pass the pinned-reader assertions. Actual output in both clean runs:
Checkpoint lock held: {"busy":1,"log":-1,"checkpointed":-1} AssertionError: expected -1 to be greater than 32768 Tests 1 failed | 4 passed (5)
The helper holds a real lock rather than starting a checkpoint loop from the issue. This deterministically exercises the exact competing-checkpoint exclusion state without running any issue-supplied script or linked PR code. Raw logs and the patch are retained locally; the public report embeds the repeatable evidence instead of publishing raw artifacts, in accordance with the reports repository policy.
5. Root cause
The pinned-reader test runs the following after waiting 250 ms, while its checkpointer is still attached:
const [pinned] = db.$client.pragma( "wal_checkpoint(PASSIVE)", ) as CheckpointRow[]; expect(pinned?.log).toBeGreaterThan(32_768); expect(pinned?.checkpointed).toBeLessThan(pinned?.log ?? 0);
The worker checkpoint and rescheduling path issues the same PASSIVE pragma. A fixed sleep does not establish checkpoint ownership or exclude the worker's next attempt. The observation therefore needs to distinguish checkpoint-lock contention from a valid frame count.
The installed, lockfile-pinned SQLite amalgamation corroborates the mechanism: SQLITE_SHM_NLOCK is 8, UNIX_SHM_BASE is 120, and WAL_CKPT_LOCK is slot 1, giving byte offset 121. sqlite3WalCheckpoint takes that exclusive lock; a competing holder returns SQLITE_BUSY before frame outputs are filled. sqlite3_wal_checkpoint_v2 initializes those outputs to -1. The helper uses this actual OS lock; the observed pragma row then confirms the result through better-sqlite3.
This does not indicate that the write loop generated too few frames: -1 is the unavailable-output sentinel, not a positive WAL size. The worker pause ordering and main-thread fallback and resume ordering also explain why the same uncoordinated observation is specific to the test rather than evidence of a new production policy defect.
6. Proposed fix
Keep the existing substantive assertions, but obtain the checkpoint observation with a bounded asynchronous retry when busy === 1. Yield between attempts so the worker can release its lock; preserve a deadline so persistent contention still fails. Do not “fix” the assertion by accepting negative frame counts, lower the frame threshold, or change production checkpoint scheduling to accommodate an observation-only race.
A cross-platform regression should exercise genuine transient checkpoint contention through an appropriate repository-owned harness. The Linux lock-holder here is intentionally only diagnostic and should not be added to the Windows test suite unchanged.
7. PR review
PR #7462 — static review only
GitHub cross-reference metadata links this open PR to the issue, and its body includes the closing reference. Its untrusted diff adds a bounded asynchronous retry to the existing test's checkpoint observation, yielding for 5 ms with a 5-second deadline, while preserving the frame assertions. This is aligned with the verified root cause. No PR branch was fetched or executed, so this report does not claim that its exact implementation passes tests or Windows CI.
Review notes: the displayed patch adds no committed contention regression, leaving deterministic coverage dependent on follow-up work; it also adds a source comment at the changed observation block, contrary to the target repository's no-code-comments rule. Neither changes the demonstrated cause. No duplicate fix branch or pull request was created because this linked open PR already exists.
8. Related issues
A targeted repository search found no other issue establishing this same checkpoint-observation failure. #6010 is a different worker-startup test flake, not a duplicate of this lock-contention mechanism. Broader WAL/crash reports were not treated as evidence for this test-only defect.
9. Verification
The same investigator repeated the work in a second clean clone, pinned to the same trusted base commit, with a separate installation and newly created temporary test databases. This is repeat verification by the same agent, not independent verification.
| Checkout | Unmodified focused suite | With investigator lock instrumentation |
|---|---|---|
| First trusted clone | Exit 0; 5 passed | Exit 1; exact -1 assertion; 1 failed, 4 passed |
| Second clean trusted clone | Exit 0; 5 passed | Exit 1; exact -1 assertion; 1 failed, 4 passed |
Command in all four runs: pnpm exec turbo run test --filter=@bb/db -- test/wal-checkpointer.test.ts. Production code remained unchanged. Both runs used the same diagnostic patch derived from the trusted source and bundled SQLite lock layout. No report correction was needed after the second run. Windows scheduling, spontaneous worker overlap rates, and the original CI job were not verified.
10. Appendix
Investigation sequence: read issue and comments as untrusted claims; inspect GitHub property definitions and similar issue classifications; fetch trusted main; install with the frozen lockfile; attempt the normal full build; read the test, worker scheduler, main fallback, and bundled SQLite locking code; run the clean focused suite; inject the real checkpoint lock and rerun; repeat from a second clean clone; inspect linked PR metadata and diff without executing it; refetch main and confirm the base remained current.
All code links above refer to the recorded trusted commit. No screenshots apply to a headless database test. The issue's suggested reproduction and links were treated as untrusted data: neither its command/script nor any linked PR branch was run. Only trusted-main code and investigator-authored lock instrumentation were executed.