fix(server): wait for concurrent SQLite writers instead of failing with SQLITE_BUSY #5134
main fromrefs/pull/5134/head·merged by juliusmarminge View on GitHubFixes #5099
Concurrent writes to the state database from separate processes — e.g. t3 auth session issue while a server is running, or a few CLI invocations in parallel — intermittently fail with database is locked. The persistence layer never sets busy_timeout, so SQLite gives up on a contended write lock immediately instead of waiting for it to clear.
The shared setup layer now applies PRAGMA busy_timeout = 5000 (the value scripts/t3-sqlite-state.ts already uses) ahead of the WAL/foreign-keys pragmas and migrations, so it covers the server, the CLI, and both the node and bun clients through the one place every writable connection goes through.
Verified:
- New test reproduces the failure cross-process: a child process holds
BEGIN IMMEDIATEon the same file while the layer writes. It fails withdatabase is lockedon main and passes with the fix (a second test pins the pragma value). Stable across repeated runs. - The repro from the issue: on main, parallel
t3 auth session issueruns against one state dir failed intermittently with the exact stack from the issue (AuthSessionRepository.create→database is locked); with the fix, 24/24 runs succeeded.
Scope: this only makes writers wait out short-lived lock contention; it does not change WAL or durability behavior.
Written by Claude (Fable 5) in Claude Code, directed and reviewed by @ostapondo.
Note
Low Risk Localized persistence tuning with no auth or schema changes; writers may block briefly under contention but behavior otherwise matches prior WAL/durability setup.
Overview
Fixes intermittent database is locked / SQLITE_BUSY when the server and CLI (or parallel CLI runs) write the same state DB by having every writable connection wait up to 5 seconds for a lock instead of failing immediately.
The shared SQLite setup layer in Sqlite.ts now runs PRAGMA busy_timeout = 5000 before foreign keys, WAL, and migrations, so server, CLI, and in-memory test layers all pick it up from one place.
Sqlite.test.ts adds a cross-process repro (child holds BEGIN IMMEDIATE while the layer inserts) and asserts the pragma is 5000 via SqlitePersistenceMemory.
Note
Fix SQLite busy_timeout to wait up to 5s instead of failing with SQLITE_BUSY#
Sets PRAGMA busy_timeout = 5000 in the SQLite layer setup in Sqlite.ts, applied before enabling foreign keys and WAL mode. Adds tests in Sqlite.test.ts that verify the pragma value and confirm concurrent write locks are waited out rather than causing immediate failures.
- Behavioral Change: SQLite operations that previously failed immediately with
SQLITE_BUSYunder write contention now block for up to 5 seconds before failing.
Summary by CodeRabbit#
Bug Fixes
- Improved SQLite handling for concurrent writes.
- Write operations now wait up to five seconds when the database is temporarily locked, reducing immediate failures during simultaneous CLI and server activity.
Tests
- Added coverage for concurrent write handling and the shared database lock timeout configuration.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
@coderabbitai review
✅ Action performed
Review finished.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XS
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@apps/server/src/persistence/Layers/Sqlite.test.ts`: - Around line 15-24: Update the lock-holder setup around lockHolderSource so it does not require node:sqlite when tests run under Bun. Use a Bun-compatible bun:sqlite helper for Bun, or conditionally run the existing process.execPath/node:sqlite lock simulation only on Node while preserving the lock behavior.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
dcdb76e1-b225-477a-bbcf-3c56dda9454b📥 Commits
Reviewing files that changed from the base of the PR and between a041981276b4c789fed8132e3b8a320749bf25e8 and 0b0f6d33b56b1a722ba80539f416ec00d64c4ec2.
📒 Files selected for processing (2)
apps/server/src/persistence/Layers/Sqlite.test.tsapps/server/src/persistence/Layers/Sqlite.ts
apps/server/src/persistence/Layers/Sqlite.test.ts lines 15 to 24Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+import * as NodeOS from "node:os";5+import * as NodePath from "node:path";6+7+import * as NodeServices from "@effect/platform-node/NodeServices";8+import { assert, it } from "@effect/vitest";9+import * as Effect from "effect/Effect";10+import * as Layer from "effect/Layer";11+import * as SqlClient from "effect/unstable/sql/SqlClient";12+13+import { SqlitePersistenceMemory, makeSqlitePersistenceLive } from "./Sqlite.ts";14+15+const lockHolderSource = `16+const { DatabaseSync } = require("node:sqlite");17+const db = new DatabaseSync(process.argv[1]);18+db.exec("BEGIN IMMEDIATE");19+process.stdout.write("locked\\n");20+setTimeout(() => {21+ db.exec("COMMIT");22+ db.close();23+}, Number(process.argv[2]));24+`;🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
What is the current stability status of node:sqlite in the latest Node.js LTS release, and does Bun fully support node:sqlite as of its latest stable release?💡 Result:
As of July 31, 2026, the node:sqlite module in Node.js is classified with a stability index of 1.2, which designates it as a release candidate [1][2]. While the module has been unflagged—meaning it no longer requires the --experimental-sqlite flag—it has not yet been declared fully stable [3][4]. The release candidate status indicates that while no further breaking changes are anticipated, they may still occur in response to user feedback or specification developments [4]. Regarding Bun, it does not support the node:sqlite module [5][6]. Bun natively provides its own high-performance SQLite driver through the bun:sqlite module, which is the recommended alternative for use within the Bun runtime [5][7]. Users requiring cross-runtime compatibility between Node.js and Bun typically must use conditional imports or implement a wrapper to handle the differences between the node:sqlite and bun:sqlite APIs [6].
Citations:
- 1: https://nodejs.org/api/sqlite.html
- 2: http://nodejs.org/dist/latest/docs/api/sqlite.html
- 3: https://github.com/nodejs/node/issues/57445
- 4: https://github.com/nodejs/node/pull/61262
- 5: https://bun.sh/reference/node/sqlite
- 6: https://github.com/oven-sh/bun/issues/31402
- 7: https://bun.com/docs/runtime/sqlite
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== repo files relevant to runtime/package config ==" git ls-files | rg '(^|/)(package\.json|pnpm-lock\.yaml|bun\.lockb|bun\.lock|README\.md|\.env|\.github/workflows/.+\.ya?ml|vitest\.config\..+|vite\.config\..+|bunfig\.toml|bun\.doc|package\.lock\.json|yarn\.lock)$' || true echo echo "== package.json files ==" for f in $(git ls-files 'package.json'); do echo "--- $f" cat "$f" done echo echo "== references to bun/script engines/tests ==" rg -n '"bun"|"typecheck:bun"|bun (test|run)|pnpm test|vitest|node:sqlite|Vite_HTTP_URL|VITE_HTTP_URL|VITE_WS_URL' -S . || true echo echo "== target test file excerpt ==" sed -n '1,90p' apps/server/src/persistence/Layers/Sqlite.test.tsRepository: pingdotgg/t3code
Length of output: 50372
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== target test file excerpt ==" sed -n '1,90p' apps/server/src/persistence/Layers/Sqlite.test.ts echo echo "== GitHub workflow commands mentioning bun node pnpm test ==" for f in .github/workflows/*.yml .github/workflows/*.yaml; do [ -f "$f" ] || true done | xargs -r -n1 sh -c ' echo "--- $0" rg -n "bun|node|pnpm test|test:" "$0" || true ' sh echo echo "== package/runtime config focused ==" rg -n '"node"|engines|packageManager|bun run|bun (test|run)|pnpm test|node:sqlite' package.json Apps/server/package.json apps/server/package.json package-lock.json pnpm-lock.yaml .github/workflows/ci.yml || trueRepository: pingdotgg/t3code
Length of output: 50372
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== target test file excerpt ==" sed -n '1,90p' apps/server/src/persistence/Layers/Sqlite.test.ts echo echo "== GitHub workflow commands mentioning bun node pnpm test ==" for f in .github/workflows/*.yml .github/workflows/*.yaml; do [ -f "$f" ] || continue echo "--- $f" rg -n "bun|node|pnpm test|test:" "$f" || true done echo echo "== engine/runtime config focused ==" rg -n '"node"|engines|packageManager|bun run|bun test|pnpm test|node:sqlite' package.json apps/server/package.json pnpm-lock.yaml .github/workflows/ci.yml || trueRepository: pingdotgg/t3code
Length of output: 50372
Keep the lock-helper on a runtime-specific path.
lockHolderSourcespawnsprocess.execPathand requiresnode:sqlite. Bun does not providenode:sqlite, so this helper breaks under Bun despite the PR mentioning Node and Bun writable connections. Use a Bun/Nativebun:sqlitehelper here, or structure the test to run this Node-specific lock simulation only on Node.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server/src/persistence/Layers/Sqlite.test.ts` around lines 15 - 24, Update the lock-holder setup around lockHolderSource so it does not require node:sqlite when tests run under Bun. Use a Bun-compatible bun:sqlite helper for Bun, or conditionally run the existing process.execPath/node:sqlite lock simulation only on Node while preserving the lock behavior.The suite only runs under Node, so the helper can't hit the missing-
node:sqlitepath: CI's Test job sets up Node (node-version-file: package.json) and runsvp run test— vitest withenvironment: node; there is no Bun test path in the repo. The existing suite already carries this constraint:NodeSqliteClient.test.tsimportsNodeSqliteClient.ts, which importsnode:sqliteat module scope. The node/bun mention in the description is about the production clients — both get the pragma through the sharedsetuplayer, which the second test pins; the lock-holder child is test scaffolding only. Happy to add askipIf(process.versions.bun)guard if you'd rather make the Node-only assumption explicit.🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo '== Relevant file locations ==' fd -a -t f '^(package\.json|.*vitest.*|.*Sqlite.*\.(test\.)?ts|.*NodeSqliteClient.*\.ts)$' . \ | sort echo echo '== Test scripts and runtime declarations ==' for file in package.json apps/server/package.json; do if [ -f "$file" ]; then echo "--- $file" rg -n -C 3 '"(test|test:.*|packageManager|engines)"\s*:' "$file" || true fi done echo echo '== CI test commands and Node setup ==' if [ -d .github/workflows ]; then rg -n -i -C 4 '(node-version-file|setup-node|vp run test|bun|vitest|test:)' .github/workflows || true fi echo echo '== Vitest environment configuration ==' vitest_files="$(fd -a -t f -i 'vitest.config.*' . || true)" if [ -n "$vitest_files" ]; then while IFS= read -r file; do echo "--- $file" rg -n -C 3 '(environment|test)' "$file" || true done <<< "$vitest_files" fi echo echo '== Existing node:sqlite imports in server tests and implementation ==' rg -n -C 3 'from "node:sqlite"|require\("node:sqlite"\)' apps/server || true echo echo '== Reviewed test excerpt ==' sed -n '1,75p' apps/server/src/persistence/Layers/Sqlite.test.tsLength of output: 37985
@ostapondo, verified. The test suite has a Node-only execution contract.CI configures Node from
package.jsonand runsvp run test. The repository also already importsnode:sqliteat module scope inapps/server/src/persistence/NodeSqliteClient.ts. This test directly uses Node built-ins and@effect/platform-node/NodeServices.The Node/Bun production support does not require the lock-holder test scaffold to support Bun. The shared setup test covers the shared
busy_timeoutconfiguration.No
skipIf(process.versions.bun)guard is needed for the current test contract. I am withdrawing this finding.
You are interacting with an AI system.✏️ Learnings added
Learnt from: ostapondo Repo: pingdotgg/t3code PR: 5134 File: apps/server/src/persistence/Layers/Sqlite.test.ts:15-24 Timestamp: 2026-07-31T17:30:20.576Z Learning: The repository test suite is Node-only: `.github/workflows/ci.yml` configures Node from the root `package.json` and runs `vp run test`. Node-specific test scaffolding is valid in `apps/server/src/persistence/Layers/Sqlite.test.ts`; this includes the `lockHolderSource` child process that uses `node:sqlite`. The production SQLite layer still supports Node and Bun through shared setup, but tests do not run under Bun.Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
Approvability#
Verdict: Approved dd2121d
This PR adds a single SQLite PRAGMA setting to configure busy_timeout, preventing SQLITE_BUSY errors when CLI and server write concurrently. The change is minimal, follows existing patterns, and includes thorough tests.
You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
juliusmarminge merged thisc0f9d91
juliusmarminge closed this
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
SQLite initialization now sets
PRAGMA busy_timeout = 5000before other pragmas. Tests cover concurrent writer handling and verify the timeout value for shared in-memory persistence.Changes#
SQLite busy timeout
apps/server/src/persistence/Layers/Sqlite.tsapps/server/src/persistence/Layers/Sqlite.test.tsEstimated code review effort: 2 (Simple) | ~10 minutes
Suggested reviewers:
juliusmarminge🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#5099.#5099.✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share