wrolpi/wrolpi/test/test_db.py
Roland daf2ba39d4 db: write intent is the opt-in, not a second session helper
Three "database is locked" failures on the docker WROLPi, one cause each:

  * `INSERT INTO download` from POST /api/download -- a user creating a
    video download while a refresh ran (2026-08-06 14:06:46);
  * six `INSERT INTO file_group` from `upsert_file`, uploads landing in
    the same three-minute window;
  * `UPDATE download SET status` from `renew_recurring_downloads`.

All three are the deferred read-then-write trap: a transaction that
begins as a reader and upgrades at its first write is refused
*instantly* when another connection wrote in between, because
busy_timeout is skipped for lock upgrades.  `get_immediate_db_session`
existed to avoid it, but an opt-in helper only works if every author
remembers, and read-then-write is the ordinary shape of a write.  So it
is gone: `get_db_session(commit=True)` -- the existing declaration of
write intent -- now begins IMMEDIATE.  Rails 7.1 and Django 5.1 made the
same call, defaulting SQLite transactions to IMMEDIATE rather than
asking application code to opt in.

That default is only safe if write transactions stay short, and one did
not.  `video_cleanup` ran its whole Channel-claiming join --
`UPDATE video ... FROM channel ... LEFT JOIN file_group`, O(channels x
file_groups) -- inside one write transaction: 110 to 130 seconds each of
the eight times it appears in the log, on a library with ~1500 channels.
While it ran, *every* writer on the box failed, including ones that
began IMMEDIATE, because the hold far exceeds the 30s busy_timeout.  The
14:04-14:06 failures above sit inside its 130-second window.  The join
is now a read -- WAL readers never block writers -- and only the
resulting UPDATEs take the lock, 500 rows per transaction.
`claim_videos_for_channels` had the same join and the same fix; channel
import calls it with every channel in channels.yaml.

Also here:

  * `renew_recurring_downloads` was a read session with an inner commit;
    it is a write session now.  Its computed `next_download` values now
    persist even when nothing was renewed -- that is the point of
    computing them.
  * POST /api/download no longer writes through `request.ctx.session`.
    That session is committed by the response middleware, so a writer
    would hold the lock across the whole request; a write session
    commits before the handler returns, ahead of the background dispatch
    it fires.
  * `_immediate_txn` is a ContextVar, not a threading.local.  The
    writers that set it include coroutines, and one asyncio thread runs
    many of them interleaved.
  * `write_lock_held_briefly` moved from the move tests into conftest,
    since two suites now need it.

Both regression tests were verified by mutation: reverting either site
alone fails its own test, and the API one fails with the production
error verbatim.

Sources: fractaledmind.com/2023/12/11/sqlite-on-rails-improving-concurrency,
tenthousandmeters.com/blog/sqlite-concurrent-writes-and-database-is-locked-errors,
berthub.eu/articles/posts/a-brief-post-on-sqlite3-database-locked-despite-timeout

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 20:15:50 -06:00

152 lines
6.8 KiB
Python

import sqlite3
from wrolpi.conftest import production_like_sessions
from wrolpi.db import get_db_session, _configure_sqlite_connection
class _FakeCursor:
"""A minimal DBAPI cursor that records executed statements and simulates WAL rejection.
A FAT/exFAT/NTFS drive rejects WAL either by raising `disk I/O error` (`fail_wal`) or by
silently keeping the current rollback journal — `PRAGMA journal_mode` returns the mode SQLite
actually selected, so a WAL request can return e.g. 'delete' without raising (`wal_returns`)."""
def __init__(self, fail_wal: bool, wal_returns: str = 'wal'):
self.fail_wal = fail_wal
self.wal_returns = wal_returns
self.executed = []
self._last_row = None
def execute(self, statement):
if statement == 'PRAGMA journal_mode=WAL':
if self.fail_wal:
raise sqlite3.OperationalError('disk I/O error')
self._last_row = (self.wal_returns,)
elif statement.startswith('PRAGMA journal_mode='):
self._last_row = (statement.split('=', 1)[1].lower(),)
else:
self._last_row = None
self.executed.append(statement)
def fetchone(self):
return self._last_row
def close(self):
pass
class _FakeConnection:
def __init__(self, fail_wal: bool, wal_returns: str = 'wal'):
self._cursor = _FakeCursor(fail_wal, wal_returns)
self.isolation_level = 'DEFERRED'
def cursor(self):
return self._cursor
def test_configure_connection_uses_wal_when_supported():
"""On a normal filesystem the connection is configured for WAL + synchronous=NORMAL."""
conn = _FakeConnection(fail_wal=False)
mode = _configure_sqlite_connection(conn)
assert mode == 'WAL'
assert conn.isolation_level is None
assert 'PRAGMA journal_mode=WAL' in conn._cursor.executed
assert 'PRAGMA synchronous=NORMAL' in conn._cursor.executed
assert 'PRAGMA busy_timeout=30000' in conn._cursor.executed
assert 'PRAGMA foreign_keys=ON' in conn._cursor.executed
def test_configure_connection_falls_back_to_rollback_journal_on_wal_failure():
"""When WAL raises `disk I/O error` (exFAT/FAT/NTFS), fall back to a crash-safe rollback journal.
Regression test for the whole-API outage on 10.0.0.8: an exFAT media drive made
`PRAGMA journal_mode=WAL` raise on every connection. The connection must still come up, using
a TRUNCATE rollback journal with synchronous=FULL (WROLPi is off-grid; power loss is expected)."""
conn = _FakeConnection(fail_wal=True)
mode = _configure_sqlite_connection(conn)
assert mode == 'TRUNCATE'
assert 'PRAGMA journal_mode=TRUNCATE' in conn._cursor.executed
assert 'PRAGMA synchronous=FULL' in conn._cursor.executed
# WAL's less-durable synchronous setting must NOT be applied on a rollback journal.
assert 'PRAGMA synchronous=NORMAL' not in conn._cursor.executed
# The connection is still fully configured.
assert 'PRAGMA busy_timeout=30000' in conn._cursor.executed
assert 'PRAGMA foreign_keys=ON' in conn._cursor.executed
def test_configure_connection_falls_back_when_wal_silently_refused():
"""SQLite can refuse WAL WITHOUT raising, returning the still-active rollback mode instead.
The requested mode is not always the applied mode, so we must confirm `PRAGMA journal_mode`'s
return value. Here WAL 'succeeds' but reports 'delete'; that must trigger the durable fallback
(TRUNCATE + synchronous=FULL), not cache WAL with the weaker synchronous=NORMAL."""
conn = _FakeConnection(fail_wal=False, wal_returns='delete')
mode = _configure_sqlite_connection(conn)
assert mode == 'TRUNCATE'
assert 'PRAGMA journal_mode=TRUNCATE' in conn._cursor.executed
assert 'PRAGMA synchronous=FULL' in conn._cursor.executed
assert 'PRAGMA synchronous=NORMAL' not in conn._cursor.executed
def test_configure_connection_does_not_reattempt_wal_once_ruled_out():
"""Once WAL is known-unavailable for an engine, later connections skip (and don't re-log) it."""
conn = _FakeConnection(fail_wal=True)
# `journal_mode='TRUNCATE'` is the remembered decision from a previous connection.
mode = _configure_sqlite_connection(conn, journal_mode='TRUNCATE')
assert mode == 'TRUNCATE'
assert 'PRAGMA journal_mode=WAL' not in conn._cursor.executed
assert 'PRAGMA journal_mode=TRUNCATE' in conn._cursor.executed
def _probe_write_lock_is_held(db_file: str) -> bool:
"""Return True if a competing connection cannot immediately take the write lock.
Uses a zero busy-timeout so the probe fails instantly if another connection holds a
RESERVED (write) lock, rather than waiting. In WAL mode a plain reader holds no such
lock, so this only returns True when a writer transaction is actually in progress.
"""
probe = sqlite3.connect(db_file, timeout=0)
try:
probe.execute('PRAGMA busy_timeout=0')
try:
probe.execute('BEGIN IMMEDIATE')
except sqlite3.OperationalError as e:
if 'database is locked' in str(e):
return True
raise
probe.execute('ROLLBACK')
return False
finally:
probe.close()
def test_write_session_takes_write_lock_up_front(test_session):
"""`get_db_session(commit=True)` must acquire the SQLite write lock at BEGIN.
Regression test for `database is locked` on `UPDATE download SET last_download_attempt`:
a deferred (read-then-write) transaction that tries to upgrade its lock while another
connection holds the write lock gets SQLITE_BUSY *immediately* — busy_timeout is ignored
for lock upgrades to avoid deadlock. Taking the write lock up front (BEGIN IMMEDIATE)
lets busy_timeout absorb the contention instead of erroring instantly. `commit=True` is
the declaration of write intent, so it is what arms this — no opt-in helper to forget.
"""
db_file = test_session.get_bind().url.database
with production_like_sessions(test_session):
with get_db_session(commit=True) as session:
# Trigger the transaction's BEGIN with a trivial read (as the download dispatcher
# does before writing). This session already holds the write lock.
session.execute('SELECT 1')
assert _probe_write_lock_is_held(db_file), \
'immediate session did not hold the write lock after BEGIN'
def test_read_session_does_not_take_write_lock(test_session):
"""A read-only `get_db_session()` must stay deferred so WAL read-concurrency is preserved."""
db_file = test_session.get_bind().url.database
with production_like_sessions(test_session):
with get_db_session() as session:
session.execute('SELECT 1')
assert not _probe_write_lock_is_held(db_file), \
'read-only session unexpectedly holds the write lock'