fix(pairing): take the write lock before reading expired pairings
POST /v1/pairing sometimes fails with a 503 ("database is locked") after about 0.2 s, even though the busy timeout is 30 s. The expired-pairing cleanup fails the same way.
Cause: pairing::delete_expired started its transaction with a SELECT of the expired IDs and only then deleted them, and create calls it first. In a deferred SQLite transaction that has already read, the upgrade to a write lock returns SQLITE_BUSY immediately when another connection is writing. SQLite doesn't call the busy handler there.
Fix: delete_expired now deletes with RETURNING id first and then removes the pending account sessions, so every pairing transaction writes before it reads. This works on SQLite and PostgreSQL. I used this instead of immediate_transaction because diesel-async's AsyncFunc bound is private, so a generic per-backend wrapper isn't possible.
Audit: every other write transaction already starts with a write (the account row lock, lock_account_quota, or a direct insert, update or delete). encrypted_sync::read_since only reads.
Test: create_waits_for_a_concurrent_writer holds BEGIN IMMEDIATE on a second connection to a WAL file database and checks that create waits instead of failing, then succeeds after the commit. Before the fix it failed right away. cargo test --workspace --locked (108 passed), clippy and fmt are clean, and the PostgreSQL build compiles.
Made by Claude Opus 5.5 in Claude Code.