diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b59f067..7779866 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -104,7 +104,9 @@ jobs: uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 env: # Authenticated github.com requests avoid the anonymous rate limit. + # 502/503 are accepted too: github.com throttles blob pages crawled + # from Actions runners with 503, while a broken link is a 404. GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - args: --no-progress --max-retries 2 --accept 200,201,204,429 --exclude '^https?://(localhost|127\.0\.0\.1)' --exclude 'ghcr\.io' --exclude 'npmjs\.com' --exclude 'raw\.githubusercontent\.com/.*/leaderboard' README.md 'docs/**/*.md' + args: --no-progress --max-retries 2 --accept 200,201,204,429,502,503 --exclude '^https?://(localhost|127\.0\.0\.1)' --exclude 'ghcr\.io' --exclude 'npmjs\.com' --exclude 'raw\.githubusercontent\.com/.*/leaderboard' README.md 'docs/**/*.md' fail: true diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 77e320c..6817c8d 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -3,6 +3,7 @@ import json import re import sqlite3 +import time import uuid from contextlib import contextmanager from contextvars import ContextVar @@ -138,12 +139,37 @@ def _now() -> str: } +# RunRepository setup retries these on a fresh connection (see __init__). +_TRANSIENT_OPEN_ERRORS = ("database is locked", "database schema has changed") +_OPEN_RETRY_SECONDS = 10.0 + + class RunRepository: def __init__(self, db_path: Path | None = None) -> None: ensure_store_dirs() self.db_path = db_path or _default_db_path.get() or DB_PATH self.db_path.parent.mkdir(parents=True, exist_ok=True) - self._conn = sqlite3.connect(self.db_path) + # Several skills open the store at once in their own threads. On a + # new or pre-WAL database two setup steps can fail without waiting + # for busy_timeout: switching to WAL needs an exclusive lock that + # SQLite does not wait for ("database is locked"), and statements + # can lose the race against another connection creating the tables + # ("database schema has changed"). Every setup step is idempotent, + # so setup is retried on a fresh connection until a deadline. + deadline = time.monotonic() + _OPEN_RETRY_SECONDS + while True: + self._conn = sqlite3.connect(self.db_path) + try: + self._set_up() + return + except sqlite3.OperationalError as exc: + self._conn.close() + transient = any(message in str(exc) for message in _TRANSIENT_OPEN_ERRORS) + if not transient or time.monotonic() >= deadline: + raise + time.sleep(0.05) + + def _set_up(self) -> None: self._conn.row_factory = sqlite3.Row self._conn.execute("PRAGMA foreign_keys = ON") # Skills run concurrently in separate threads, each with its own @@ -154,8 +180,9 @@ def __init__(self, db_path: Path | None = None) -> None: # dashboard) proceed without blocking on a concurrent writer (a # run in progress) -- readers otherwise wait behind the default # rollback-journal's writer lock. Requires local disk, not - # NFS/EFS-backed storage, for the portal host. - self._conn.execute("PRAGMA journal_mode = WAL") + # NFS/EFS-backed storage, for the portal host. The mode persists in + # the file, so only the first open ever switches it. + self._conn.execute("PRAGMA journal_mode = WAL").fetchone() self._conn.executescript(SCHEMA_PATH.read_text(encoding="utf-8")) self._conn.commit() self._migrate() diff --git a/tests/test_storage/test_run_status_migration.py b/tests/test_storage/test_run_status_migration.py index f17d612..950619a 100644 --- a/tests/test_storage/test_run_status_migration.py +++ b/tests/test_storage/test_run_status_migration.py @@ -3,6 +3,7 @@ import sqlite3 import threading +import traceback import typing import pytest @@ -153,3 +154,79 @@ def test_runs_without_any_status_check_are_left_alone(tmp_path): conn.close() RunRepository(db_path=db).close() assert "CHECK (status" not in _runs_sql(db) + + +@pytest.mark.parametrize("make_db", ["old", "missing"]) +def test_parallel_first_opens_never_fail(tmp_path, make_db): + """Switching a database to WAL takes an exclusive lock that SQLite does + not wait for, and a connection can lose the race against another one + creating the tables; parallel first opens used to fail about 1 in 20 + times with "database is locked" or "database schema has changed".""" + for attempt in range(25): + db = tmp_path / f"{attempt}.db" + if make_db == "old": + _old_db(db) + errors = [] + barrier = threading.Barrier(6) + + def open_repo(db=db, barrier=barrier, errors=errors): + try: + barrier.wait() + RunRepository(db_path=db).close() + except Exception: # noqa: BLE001 -- surfaced by the assert below + errors.append(traceback.format_exc()) + + threads = [threading.Thread(target=open_repo) for _ in range(6)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert not errors, "\n".join(errors) + with sqlite3.connect(db) as conn: + assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "wal" + + +@pytest.mark.parametrize("message", ["database is locked", "database schema has changed"]) +def test_setup_retries_a_transient_error_on_a_fresh_connection(tmp_path, monkeypatch, message): + real_set_up = RunRepository._set_up + connections = [] + + def flaky_set_up(self): + connections.append(self._conn) + if len(connections) < 3: + raise sqlite3.OperationalError(message) + real_set_up(self) + + monkeypatch.setattr(RunRepository, "_set_up", flaky_set_up) + repo = RunRepository(db_path=tmp_path / "s.db") + try: + assert len(connections) == 3 and len({id(c) for c in connections}) == 3 + assert repo._conn is connections[-1] + assert repo._conn.execute("SELECT count(*) FROM runs").fetchone()[0] == 0 + finally: + repo.close() + with pytest.raises(sqlite3.ProgrammingError): # the failed attempts' connections were closed + connections[0].execute("SELECT 1") + + +def test_setup_does_not_retry_other_errors(tmp_path, monkeypatch): + calls = [] + + def broken_set_up(self): + calls.append(1) + raise sqlite3.OperationalError("no such table: runs") + + monkeypatch.setattr(RunRepository, "_set_up", broken_set_up) + with pytest.raises(sqlite3.OperationalError, match="no such table"): + RunRepository(db_path=tmp_path / "s.db") + assert calls == [1] + + +def test_setup_gives_up_after_the_deadline(tmp_path, monkeypatch): + from secfoo.storage import repository + + monkeypatch.setattr(repository, "_OPEN_RETRY_SECONDS", 0.2) + monkeypatch.setattr(RunRepository, "_set_up", lambda self: (_ for _ in ()).throw( + sqlite3.OperationalError("database is locked"))) + with pytest.raises(sqlite3.OperationalError, match="locked"): + RunRepository(db_path=tmp_path / "s.db")