Repository navigation
Description
Summary
The bundled SQLite library (rusqlite 0.38, SQLite ~3.46) exhibits a lock-order inversion between two close-path codepaths. When two rusqlite::Connection handles to the same DB file are dropped concurrently (typical: writer thread + r2d2 ReadPool teardown), the AB-BA cycle deadlocks indefinitely.
Reproduced 2026-04-23 via cargo test -p perima-db --lib (then verified persistent under --test-threads 1). Two gdb backtraces captured.
Lock-order cycle
Path A — unixClose (called from Connection::drop → sqlite3_close):
- Acquires GLOBAL static mutex (
unixBigLock, akastaticMutexes.122+432) viaunixEnterMutexnear function start - Acquires per-inode mutex via
releaseInodeInfolater
Order: GLOBAL → PER-INODE.
Path B — unixLock (called from sqlite3WalClose during WAL close → unixIsSharingShmNode):
- Acquires per-inode mutex on entry to
unixLock - Calls
unixIsSharingShmNodewhich acquires GLOBAL static mutex
Order: PER-INODE → GLOBAL.
When two threads close their respective Connections simultaneously and one goes down each path, classic AB-BA deadlock.
Captured backtrace (focused — 2 contending threads)
Thread A (test ending, r2d2 PoolInternals dropping a pool Connection):
rusqlite::Connection::drop → sqlite3_close → sqlite3PagerClose → sqlite3WalClose
→ sqlite3OsLock → unixLock(eFileLock=4)
→ unixIsSharingShmNode → unixEnterMutex ← waiting for GLOBAL static mutex
Thread B (writer thread exiting, dropping its writable Connection):
rusqlite::Connection::drop → sqlite3_close → sqlite3PagerClose → unixClose
→ sqlite3_mutex_enter (per-inode mutex) ← waiting for PER-INODE mutex
Both are on Linux x86_64, glibc 2.x, NPTL pthreads. SQLite compiled via rusqlite's bundled feature.
Reproduction
- Default
cargo test: ~20% of runs hang silently (test binary stuck infutex_do_wait). cargo test --test-threads 1: still ~33% hang (within-test internal threads still race).cargo nextest run: 0% hangs in 4/4 verified runs (process-per-test isolation eliminates the concurrent-close race).
Production exposure
The bug is reachable in production code, not just tests. Each binary (crates/cli, crates/desktop) opens one writer Connection (in SqliteWriter) plus 4 read-only Connections (in r2d2_sqlite::Pool) all to the same DB file. Under load:
- A scan COMMIT in flight (writer Connection in
walFrames→unixShmBarrier) - A query being served (read Connection in
walBeginReadTransaction) - A watch event triggering metadata lookup (another pool Connection)
- App shutdown dropping all of these
…can theoretically hit the same inversion. No production crash report yet, but the code shape that triggers it exists.
Mitigations adopted
- Repo-wide adoption of
cargo nextest runfor non-doc tests (commit onarchitecture-audit/v0.6.x);scripts/no-cargo-test.shenforces no regression.
What this issue tracks
- Investigation of whether this is upstream SQLite bug (search SQLite mailing list / forum / Trac).
- Whether newer SQLite has a fix (rusqlite 0.39+ may bundle).
- Whether our production close-ordering can be made deterministic to avoid the race (e.g. always drop ReadPool BEFORE writer, with explicit
Dropon the container). - Whether switching to libsql / Turso (alternative SQLite bindings with concurrency improvements) changes anything.
- Whether
loomorshuttlemodel-checking can prove freedom from this class going forward.
Related
- Adopt cargo-nextest with per-test slow-timeout for workspace tests #121 — adopt cargo-nextest (closed alongside this work).
- Intermittent deadlock: perima CLI hangs at startup under concurrent cargo test load #122 — earlier observation of an intermittent CLI startup hang likely sharing root cause.
- proptest harness hangs after writer-actor migration: two racing SQLite write-connections #124 — proptest harness hang (closed by cap reduction; was likely the same class).
- Consolidate SqliteWriter construction to a single per-process site #125 — multiple
SqliteWriter::startcallsites (same code-pattern surface).
References
- Linux man-page on pthread mutex ordering: https://man7.org/linux/man-pages/man3/pthread_mutex_lock.3p.html
- SQLite WAL mode docs: https://sqlite.org/wal.html
- SQLite locking and concurrency: https://sqlite.org/lockingv3.html
- rusqlite bundled SQLite version per release: https://docs.rs/rusqlite/0.38.0/rusqlite/
Backtraces + full diagnostic available locally on the architecture-audit branch (working-tree-only RESEARCH-sqlite-deadlock.md).
Activity
test(desktop): ignore 3 _inner tests deadlocking via SQLite #131
test(desktop): ignore 4 more deadlocking _inner integration tests
test(db): retry FTS5 proptests up to 2x on intermittent SQLite race
fix(deps): bump rusqlite 0.38 → 0.39 to escape SQLite 3.51.1 deadlock
fix(desktop): drop all sender clones before writer.join() in scan _inner
utof commentedon Apr 23, 2026
Update — application-level drop-order fix landed
Commit:
4bc301b(onarchitecture-audit/v0.6.x).The 7 desktop integration tests that still deadlocked under SQLite 3.51.3 (after the upstream
unixClose ↔ unixLockfix) turned out to be a SECOND, application-level bug — not an upstream SQLite issue.Root cause:
crates/desktop/src/commands.rs::run_scan_inner_with_metadataconstructs three repo handles, each callingwriter.sender()to clone the WriteCmd channel sender. The teardown only dropped one of them (vol_repo) before callingwriter.join(). The remaining two sender clones kept the channel alive → writer thread parked influme::Receiver::recvforever →pthread_joinon the writer hung indefinitely.Evidence: gdb backtrace 2026-04-23. Test thread blocked on
__futex_abstimed_wait_common64(expected=<writer-tid>)(pthread_join syscall). Writer thread blocked influme::Hook::wait_recvfor next cmd that would never arrive.Fix: drop ALL sender-holding repos + the
on_persistclosure (which borrows&sentinel_repo) before joining the writer. 5-line change. See commit body for full details.Verification:
cargo nextest run -p perima-desktop --test commands_test --run-ignored all→ 8/8 PASS in 335ms (was 80s × 7 deadlocks).This is exactly the GRDB.swift #739 lesson + the predecessor research action item #7: "await each reader close() before the writer". Not a SQLite library bug — application-level drop-ordering bug. The bug class (multiple Connections to same file with non-deterministic drop ordering) STILL exists structurally — a future
_innerhelper could re-introduce it. The longer-term structural prevention (Cluster D / Zedsqlezclosure-only Connection API) is worth tracking separately.Status of original issue
The SQLite 3.51.0–3.51.1 lock-order inversion described in this issue is FIXED in SQLite 3.51.2 (shipped via rusqlite 0.39 / libsqlite3-sys 0.37). For our workload (single writer + r2d2 read pool, dropped in the right order) it does not recur. Closing as resolved by the upstream + the application-level drop-order fix.
Merge pull request #130 from utof/architecture-audit/v0.6.x
utof commentedon Apr 23, 2026
Both layers landed. Closing per the prior comment. Structural prevention added 2026-04-23 in a follow-up: clippy.toml bans
Connection::openworkspace-wide, deny.toml restricts rusqlite to 3 first-party crates. See CLAUDE.md "Connection model" section for the discipline summary.chore(workspace): ban Connection::open + scope rusqlite via cargo-deny
refactor(db,desktop): WriteCmd::Shutdown + explicit join eliminate ma…