Skip to content

SQLite lock-order inversion: concurrent Connection drops deadlock under WAL + multi-handle pattern #131

Closed

Description

@utof

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):

  1. Acquires GLOBAL static mutex (unixBigLock, aka staticMutexes.122+432) via unixEnterMutex near function start
  2. Acquires per-inode mutex via releaseInodeInfo later

Order: GLOBAL → PER-INODE.

Path B — unixLock (called from sqlite3WalClose during WAL close → unixIsSharingShmNode):

  1. Acquires per-inode mutex on entry to unixLock
  2. Calls unixIsSharingShmNode which 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 in futex_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 run for non-doc tests (commit on architecture-audit/v0.6.x); scripts/no-cargo-test.sh enforces 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 Drop on the container).
  • Whether switching to libsql / Turso (alternative SQLite bindings with concurrency improvements) changes anything.
  • Whether loom or shuttle model-checking can prove freedom from this class going forward.

Related

References

Backtraces + full diagnostic available locally on the architecture-audit branch (working-tree-only RESEARCH-sqlite-deadlock.md).

Activity

  1. added
    status/needs-research
    on Apr 23, 2026
  2. utof commented on Apr 23, 2026

    @utof
    OwnerAuthor

    Update — application-level drop-order fix landed

    Commit: 4bc301b (on architecture-audit/v0.6.x).

    The 7 desktop integration tests that still deadlocked under SQLite 3.51.3 (after the upstream unixClose ↔ unixLock fix) 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_metadata constructs three repo handles, each calling writer.sender() to clone the WriteCmd channel sender. The teardown only dropped one of them (vol_repo) before calling writer.join(). The remaining two sender clones kept the channel alive → writer thread parked in flume::Receiver::recv forever → pthread_join on 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 in flume::Hook::wait_recv for next cmd that would never arrive.

    Fix: drop ALL sender-holding repos + the on_persist closure (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 _inner helper could re-introduce it. The longer-term structural prevention (Cluster D / Zed sqlez closure-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.

  3. added a commit that references this issue on Apr 23, 2026
  4. utof commented on Apr 23, 2026

    @utof
    OwnerAuthor

    Both layers landed. Closing per the prior comment. Structural prevention added 2026-04-23 in a follow-up: clippy.toml bans Connection::open workspace-wide, deny.toml restricts rusqlite to 3 first-party crates. See CLAUDE.md "Connection model" section for the discipline summary.

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

    status/needs-research

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions