From 174d381ab3d1922f20678dbe0f9d1b9260ef3c0a Mon Sep 17 00:00:00 2001 From: Satyanarayana Vuppala Date: Fri, 20 Nov 2026 18:31:29 +0000 Subject: [PATCH 1/3] fix: retry the WAL switch instead of failing parallel first opens Switching a database to WAL takes an exclusive lock, and SQLite returns 'database is locked' for it at once instead of honouring busy_timeout. Several skills opening a new or pre-WAL database at the same moment failed about 1 open in 20; the #159 concurrency test hit it intermittently. The switch now retries briefly. WAL persists in the file, so only the first open ever switches it. Co-Authored-By: Claude Opus 5.5 --- src/secfoo/storage/repository.py | 18 +++++++++++- .../test_storage/test_run_status_migration.py | 28 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 77e320c..2d1e135 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 @@ -155,13 +156,28 @@ def __init__(self, db_path: Path | None = None) -> None: # 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") + self._enable_wal() self._conn.executescript(SCHEMA_PATH.read_text(encoding="utf-8")) self._conn.commit() self._migrate() self._conn.executescript(SCHEMA_INDEXES_PATH.read_text(encoding="utf-8")) self._conn.commit() + def _enable_wal(self, attempts: int = 100) -> None: + """Switches the file to WAL (persistent, so this is a no-op after the + first open). Switching a rollback-journal database needs an exclusive + lock, and SQLite returns "database is locked" for it at once instead + of honouring busy_timeout, so the first parallel open of a new or + pre-WAL database (several skills at once) retries briefly.""" + for attempt in range(attempts): + try: + self._conn.execute("PRAGMA journal_mode = WAL").fetchone() + return + except sqlite3.OperationalError as exc: + if "locked" not in str(exc) or attempt == attempts - 1: + raise + time.sleep(0.05) + def _migrate(self) -> None: existing = {row["name"] for row in self._conn.execute("PRAGMA table_info(runs)").fetchall()} for column, ddl in _RUNS_MIGRATIONS.items(): diff --git a/tests/test_storage/test_run_status_migration.py b/tests/test_storage/test_run_status_migration.py index f17d612..4c3aa91 100644 --- a/tests/test_storage/test_run_status_migration.py +++ b/tests/test_storage/test_run_status_migration.py @@ -153,3 +153,31 @@ 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_see_database_is_locked(tmp_path, make_db): + """Switching a database to WAL takes an exclusive lock that SQLite does + not wait for; parallel first opens used to fail about 1 in 20 times.""" + 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 as exc: # noqa: BLE001 -- surfaced by the assert below + errors.append(exc) + + threads = [threading.Thread(target=open_repo) for _ in range(6)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert errors == [] + with sqlite3.connect(db) as conn: + assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "wal" From cbec6143bbf9d7a8b4904165d5aa3c9f372427e4 Mon Sep 17 00:00:00 2001 From: Satyanarayana Vuppala Date: Fri, 20 Nov 2026 18:31:29 +0000 Subject: [PATCH 2/3] ci: do not fail the link check on github.com 503s github.com throttles blob pages crawled from Actions runners with 503, which turned main red twice on 2026-11-20 with 1 and 18 'errors' on pages that exist. A broken link is a 404, which still fails. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 From 50799aee710b02478a60aed9d34f5fbf25ef6222 Mon Sep 17 00:00:00 2001 From: Satyanarayana Vuppala Date: Fri, 20 Nov 2026 19:11:27 +0000 Subject: [PATCH 3/3] fix: retry store setup on 'database schema has changed' too CI (Python 3.10, Linux) showed parallel first opens of a new database can also fail with 'database schema has changed' while another connection creates the tables, not only with the WAL switch's 'database is locked'. Every setup step is idempotent, so the whole setup is now retried on a fresh connection for either error, until a 10-second deadline; any other error raises at once. Deterministic tests inject each error; the parallel stress test now prints the failing tracebacks. Co-Authored-By: Claude Opus 5.5 --- src/secfoo/storage/repository.py | 47 +++++++++------ .../test_storage/test_run_status_migration.py | 59 +++++++++++++++++-- 2 files changed, 83 insertions(+), 23 deletions(-) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 2d1e135..6817c8d 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -139,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 @@ -155,29 +180,15 @@ 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._enable_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() self._conn.executescript(SCHEMA_INDEXES_PATH.read_text(encoding="utf-8")) self._conn.commit() - def _enable_wal(self, attempts: int = 100) -> None: - """Switches the file to WAL (persistent, so this is a no-op after the - first open). Switching a rollback-journal database needs an exclusive - lock, and SQLite returns "database is locked" for it at once instead - of honouring busy_timeout, so the first parallel open of a new or - pre-WAL database (several skills at once) retries briefly.""" - for attempt in range(attempts): - try: - self._conn.execute("PRAGMA journal_mode = WAL").fetchone() - return - except sqlite3.OperationalError as exc: - if "locked" not in str(exc) or attempt == attempts - 1: - raise - time.sleep(0.05) - def _migrate(self) -> None: existing = {row["name"] for row in self._conn.execute("PRAGMA table_info(runs)").fetchall()} for column, ddl in _RUNS_MIGRATIONS.items(): diff --git a/tests/test_storage/test_run_status_migration.py b/tests/test_storage/test_run_status_migration.py index 4c3aa91..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 @@ -156,9 +157,11 @@ def test_runs_without_any_status_check_are_left_alone(tmp_path): @pytest.mark.parametrize("make_db", ["old", "missing"]) -def test_parallel_first_opens_never_see_database_is_locked(tmp_path, make_db): +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; parallel first opens used to fail about 1 in 20 times.""" + 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": @@ -170,14 +173,60 @@ def open_repo(db=db, barrier=barrier, errors=errors): try: barrier.wait() RunRepository(db_path=db).close() - except Exception as exc: # noqa: BLE001 -- surfaced by the assert below - errors.append(exc) + 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 errors == [] + 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")