diff --git a/wrolpi/db.py b/wrolpi/db.py index 33c078ce..4b899098 100644 --- a/wrolpi/db.py +++ b/wrolpi/db.py @@ -57,6 +57,45 @@ def get_db_uri() -> str: return f'sqlite:///{get_db_file()}' +def _configure_sqlite_connection(dbapi_conn, journal_mode: str = None) -> str: + """Apply WROLPi's PRAGMAs to a raw DBAPI connection; returns the journal mode actually set. + + WAL is preferred (readers never block writers, so the Sanic workers stay concurrent). But + FAT/exFAT/NTFS drives — common when a USB drive is formatted for Windows compatibility — + cannot support WAL: it needs mmap'd shared-memory those filesystems don't provide, so + `PRAGMA journal_mode=WAL` raises `disk I/O error`. There we fall back to a TRUNCATE rollback + journal so the drive still works, at the cost of write-concurrency; `synchronous=FULL` keeps + it crash-safe (WROLPi is off-grid, so power loss is expected). + + `journal_mode` is the mode chosen on a previous connection of the same engine: once WAL has + been ruled out we skip re-attempting (and re-logging) it on every fresh NullPool connection.""" + # Driver-level autocommit; the `begin` listener emits BEGIN so SQLAlchemy's transactions still + # work. (pysqlite's implicit BEGIN is broken for SQLAlchemy, and PRAGMA journal_mode cannot + # run inside a transaction.) + dbapi_conn.isolation_level = None + curs = dbapi_conn.cursor() + try: + if journal_mode != 'TRUNCATE': + try: + curs.execute('PRAGMA journal_mode=WAL') + curs.execute('PRAGMA synchronous=NORMAL') + journal_mode = 'WAL' + except sqlite3.OperationalError: + logger.warning('SQLite WAL is unavailable on this filesystem (exFAT/FAT/NTFS?); ' + 'falling back to a slower TRUNCATE rollback journal with reduced ' + 'write-concurrency. Reformat the media drive as ext4 for best performance.') + journal_mode = 'TRUNCATE' + if journal_mode == 'TRUNCATE': + curs.execute('PRAGMA journal_mode=TRUNCATE') + curs.execute('PRAGMA synchronous=FULL') + curs.execute('PRAGMA busy_timeout=30000') + curs.execute('PRAGMA foreign_keys=ON') + curs.execute('PRAGMA recursive_triggers=ON') + return journal_mode + finally: + curs.close() + + def create_wrolpi_engine(target: Union[str, pathlib.Path]) -> sqlalchemy.engine.Engine: """Create a SQLAlchemy engine for a WROLPi SQLite database. @@ -70,24 +109,18 @@ def create_wrolpi_engine(target: Union[str, pathlib.Path]) -> sqlalchemy.engine. connect_args=dict(check_same_thread=False, timeout=30), ) + # The journal mode is decided on the first connection and reused for the engine's life, so WAL + # is not re-attempted (and re-logged) on every fresh NullPool connection. + journal_state = {'mode': None} + @event.listens_for(engine, 'connect') def _sqlite_on_connect(dbapi_conn, _): - # Driver-level autocommit; the `begin` listener below emits BEGIN so SQLAlchemy's - # transactions still work. (pysqlite's implicit BEGIN is broken for SQLAlchemy, and - # PRAGMA journal_mode cannot run inside a transaction.) - dbapi_conn.isolation_level = None - curs = dbapi_conn.cursor() - curs.execute('PRAGMA journal_mode=WAL') - curs.execute('PRAGMA busy_timeout=30000') - curs.execute('PRAGMA synchronous=NORMAL') - curs.execute('PRAGMA foreign_keys=ON') - curs.execute('PRAGMA recursive_triggers=ON') - curs.close() + journal_state['mode'] = _configure_sqlite_connection(dbapi_conn, journal_state['mode']) @event.listens_for(engine, 'begin') def _sqlite_do_begin(conn): # `get_immediate_db_session()` sessions take the write lock up front; everything else stays - # deferred so WAL readers never block (see `_immediate_txn`). + # deferred so readers never block (in WAL; see `_immediate_txn`). if getattr(_immediate_txn, 'active', False): conn.execute('BEGIN IMMEDIATE') else: diff --git a/wrolpi/db_bootstrap.py b/wrolpi/db_bootstrap.py index 22b66ac8..f0527bb2 100644 --- a/wrolpi/db_bootstrap.py +++ b/wrolpi/db_bootstrap.py @@ -26,6 +26,12 @@ MINIMUM_SQLITE_VERSION = (3, 40, 0) # WAL locking is unsafe on network filesystems; refuse to run there. NETWORK_FS_TYPES = {'nfs', 'nfs4', 'cifs', 'smb3', 'smbfs', 'fuse.sshfs', 'fuse.rclone', '9p'} +# FAT/exFAT/NTFS drives (common when a USB drive is formatted for Windows compatibility) cannot +# support SQLite WAL: it needs mmap'd shared-memory that these filesystems do not provide. These +# are still usable — the engine degrades to a rollback journal (see `_configure_sqlite_connection`) +# — but with reduced write-concurrency, so we warn the user to prefer ext4. +WAL_INCOMPATIBLE_FS_TYPES = {'vfat', 'exfat', 'msdos', 'ntfs', 'ntfs3', 'fuseblk'} + def _media_fs_type(path: Path) -> Optional[str]: """The filesystem type of the mount containing `path` (Linux only).""" @@ -55,6 +61,11 @@ def check_sqlite_environment(db_file: Path) -> Optional[str]: fs_type = _media_fs_type(db_file.parent if db_file.parent.exists() else db_file.parent.parent) if fs_type in NETWORK_FS_TYPES: return f'Refusing to use a database on a network filesystem ({fs_type}); WAL locking is unsafe there' + if fs_type in WAL_INCOMPATIBLE_FS_TYPES: + # Usable, but WAL is impossible here so the engine will use a slower rollback journal. + logger.warning(f'Media filesystem is {fs_type}: SQLite WAL is unavailable, so the database will use a ' + f'slower rollback journal with reduced write-concurrency. Reformat the drive as ext4 ' + f'for best performance.') return None diff --git a/wrolpi/test/test_db.py b/wrolpi/test/test_db.py index aa353c2e..23c9f4c8 100644 --- a/wrolpi/test/test_db.py +++ b/wrolpi/test/test_db.py @@ -1,7 +1,74 @@ import sqlite3 from wrolpi.conftest import production_like_sessions -from wrolpi.db import get_db_session, get_immediate_db_session +from wrolpi.db import get_db_session, get_immediate_db_session, _configure_sqlite_connection + + +class _FakeCursor: + """A minimal DBAPI cursor that records executed statements and can be told to fail WAL. + + Simulates a FAT/exFAT/NTFS drive, where `PRAGMA journal_mode=WAL` raises `disk I/O error`.""" + + def __init__(self, fail_wal: bool): + self.fail_wal = fail_wal + self.executed = [] + + def execute(self, statement): + if self.fail_wal and statement == 'PRAGMA journal_mode=WAL': + raise sqlite3.OperationalError('disk I/O error') + self.executed.append(statement) + + def close(self): + pass + + +class _FakeConnection: + def __init__(self, fail_wal: bool): + self._cursor = _FakeCursor(fail_wal) + 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_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: diff --git a/wrolpi/test/test_db_bootstrap.py b/wrolpi/test/test_db_bootstrap.py index b34122c7..9af28dab 100644 --- a/wrolpi/test/test_db_bootstrap.py +++ b/wrolpi/test/test_db_bootstrap.py @@ -92,6 +92,38 @@ def test_check_sqlite_environment_version_gate(test_directory): assert db_bootstrap.check_sqlite_environment(get_db_file()) is None +@pytest.mark.parametrize('fs_type', ['vfat', 'exfat', 'msdos', 'ntfs', 'fuseblk']) +def test_check_sqlite_environment_allows_wal_incompatible_fs_with_warning(test_directory, fs_type): + """A FAT/exFAT/NTFS drive is allowed (with a warning), not refused. + + These filesystems cannot support SQLite WAL — it needs mmap shared-memory they don't provide, + so `PRAGMA journal_mode=WAL` raises `(sqlite3.OperationalError) disk I/O error` (the failure + seen on 10.0.0.8; the tell-tale sign was `Media directory has the wrong permissions: 0o40777`, + since these filesystems can't store Unix permission bits). Rather than crash the whole API, + the engine degrades to a rollback journal, so the environment check must NOT refuse the drive + — it only warns that performance is reduced.""" + with mock.patch.object(db_bootstrap, '_media_fs_type', return_value=fs_type), \ + mock.patch.object(db_bootstrap.logger, 'warning') as mock_warning: + assert db_bootstrap.check_sqlite_environment(get_db_file()) is None + assert mock_warning.call_count == 1 + assert 'WAL is unavailable' in mock_warning.call_args.args[0], 'expected a WAL-unavailable warning' + + +@pytest.mark.parametrize('fs_type', ['ext4', 'btrfs', 'xfs', 'f2fs']) +def test_check_sqlite_environment_allows_wal_compatible_fs(test_directory, fs_type): + """Ordinary Linux filesystems support WAL and must not be refused.""" + with mock.patch.object(db_bootstrap, '_media_fs_type', return_value=fs_type): + assert db_bootstrap.check_sqlite_environment(get_db_file()) is None + + +@pytest.mark.parametrize('fs_type', ['nfs', 'nfs4', 'cifs', 'fuse.sshfs']) +def test_check_sqlite_environment_refuses_network_fs(test_directory, fs_type): + """Network filesystems remain refused: their locking is unsafe and no journal mode fixes it.""" + with mock.patch.object(db_bootstrap, '_media_fs_type', return_value=fs_type): + error = db_bootstrap.check_sqlite_environment(get_db_file()) + assert error and fs_type in error + + def test_unmounted_production_guard(test_directory): """An unmounted production media directory blocks DB creation/migration and db_up.