From 6b2312e642cffa5ae91f5b4bb4f16a750c62c7d6 Mon Sep 17 00:00:00 2001 From: Charlie Scherer <27368115+tildesrc@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:03:24 +0000 Subject: [PATCH] Run the task service's SQLite database in WAL mode The on-disk store left SQLite at its default rollback journal, so a committing writer locked every reader out. Under ~25 live agents the dashboard's long-poll reads failed with `database is locked` (500s). Set journal_mode=WAL, synchronous=NORMAL and a 30 s busy_timeout on every new connection to a file-backed SQLite DB (in-memory engines untouched). The legacy-location DB move now carries any -wal/-shm sidecars with it, and the README notes the sidecars and how to back the DB up. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- README.md | 5 ++ src/panopticon/taskservice/__main__.py | 5 ++ .../taskservice/store_sqlalchemy.py | 32 +++++++++++- tests/core/test_store.py | 52 +++++++++++++++++++ tests/sessionservice/test_home_migration.py | 22 ++++++++ 6 files changed, 117 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 07c31ade4..23c09a4f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,8 @@ src/panopticon/ # discovery.py = scan the package + an optional path for Workflow subclasses # (the registry build_app runs on; drop a module in → registered, ADR 0004) taskservice/ # control plane: TaskService, FastAPI REST API, the SQLAlchemy store - # adapter (in-memory or on-disk SQLite), filesystem artifact store + # adapter (in-memory or on-disk SQLite — the latter in WAL mode, so reads + # never block behind writes), filesystem artifact store # (per-task + per-repo artifacts, the latter with nested names), MCP # server (mcp.py: operations=tools, artifacts=resources; FastMCP) mounted at /mcp sessionservice/ # the runner: Runner ABC + StubRunner (in-process) + LocalRunner diff --git a/README.md b/README.md index 605f8e7fc..97c4701bc 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,11 @@ variable (resolution is `$PANOPTICON_*` → `$XDG_*_HOME/panopticon` → the def | Layers, secrets, workflows | `~/.config/panopticon/` | `PANOPTICON_CONFIG` (workflows also via the `--workflows-path` flag) | | Per-repo clone cache | `~/.cache/panopticon/repos/` | `PANOPTICON_CACHE` | +The database runs in SQLite's WAL mode, so it is `panopticon.db` plus `panopticon.db-wal` and +`panopticon.db-shm` beside it. To back it up, stop the service first (`make stop`) or use +`sqlite3 ~/.local/share/panopticon/panopticon.db ".backup "` — copying the `.db` alone while +the service runs can miss recent commits. + ## Managing your install - **Bring it back up** after a reboot or after you quit: `panopticon start` starts the services and diff --git a/src/panopticon/taskservice/__main__.py b/src/panopticon/taskservice/__main__.py index 728fa175d..25c9223e8 100644 --- a/src/panopticon/taskservice/__main__.py +++ b/src/panopticon/taskservice/__main__.py @@ -62,6 +62,11 @@ def migrate_db_to_home(db_url: str) -> None: logging.info("panopticon: migrating %s → %s", old.resolve(), new) new.parent.mkdir(parents=True, exist_ok=True) old.rename(new) + # A WAL-mode DB keeps uncheckpointed commits in its sidecars — they move with it. + for suffix in ("-wal", "-shm"): + sidecar = old.with_name(old.name + suffix) + if sidecar.is_file(): + sidecar.rename(new.with_name(new.name + suffix)) return diff --git a/src/panopticon/taskservice/store_sqlalchemy.py b/src/panopticon/taskservice/store_sqlalchemy.py index 8b7cfc5e6..e97455a5c 100644 --- a/src/panopticon/taskservice/store_sqlalchemy.py +++ b/src/panopticon/taskservice/store_sqlalchemy.py @@ -23,6 +23,13 @@ reproduces this exact schema, and ``tests/test_migrations.py`` guards the two against drift. On a persistent deployment, run ``alembic upgrade head`` to apply migrations; ``alembic stamp head`` aligns a dev database that ``create_all`` already bootstrapped. + +Concurrency: a file-backed SQLite DB runs in **WAL** mode (set on every new connection, see +:func:`_set_sqlite_pragmas`) so the dashboard's reads never block behind the agents' writes — +the default rollback journal locks readers out while a writer commits, which surfaced as +``database is locked`` 500s under a few dozen live agents. WAL keeps two sidecar files next to +the DB (``-wal``, ``-shm``); copy the DB with the service stopped, or via +``sqlite3 .backup``. In-memory engines are left alone (WAL means nothing there). """ from __future__ import annotations @@ -30,7 +37,7 @@ from collections.abc import Sequence from typing import Any -from sqlalchemy import JSON, ForeignKey, ForeignKeyConstraint, select +from sqlalchemy import JSON, ForeignKey, ForeignKeyConstraint, event, select from sqlalchemy.ext.asyncio import ( AsyncSession, async_sessionmaker, @@ -64,6 +71,10 @@ _IN_MEMORY = ("sqlite://", "sqlite:///:memory:") +#: How long a connection waits on another writer's lock before failing with ``database is +#: locked`` (the driver default is 5 s). With WAL only writers contend, so this just queues them. +_SQLITE_BUSY_TIMEOUT_MS = 30_000 + def _to_async_url(url: str) -> str: """Translate a plain ``sqlite://`` URL to its ``sqlite+aiosqlite://`` equivalent.""" @@ -72,6 +83,23 @@ def _to_async_url(url: str) -> str: return url +def _set_sqlite_pragmas(dbapi_conn: Any, _record: Any) -> None: + """Put a fresh file-backed SQLite connection in WAL mode (an engine ``connect`` listener). + + ``journal_mode=WAL`` lets readers proceed while a writer commits (and is persisted in the + file, so Alembic's sync engine inherits it); ``synchronous=NORMAL`` is WAL's standard + pairing — durable across an app crash, only the newest commits at risk on power loss; + ``busy_timeout`` makes colliding writers wait rather than fail. + """ + cursor = dbapi_conn.cursor() + try: + cursor.execute("PRAGMA journal_mode=WAL") + cursor.execute("PRAGMA synchronous=NORMAL") + cursor.execute(f"PRAGMA busy_timeout={_SQLITE_BUSY_TIMEOUT_MS}") + finally: + cursor.close() + + # -- ORM row classes (mutable; live only in this adapter; own their translation) ---- @@ -388,6 +416,8 @@ def __init__(self, url: str = "sqlite://") -> None: ) else: self._engine = create_async_engine(async_url) + if async_url.startswith("sqlite+aiosqlite://"): + event.listen(self._engine.sync_engine, "connect", _set_sqlite_pragmas) self._session: async_sessionmaker[AsyncSession] = async_sessionmaker( self._engine, class_=AsyncSession, expire_on_commit=False ) diff --git a/tests/core/test_store.py b/tests/core/test_store.py index 8e882e136..00e146302 100644 --- a/tests/core/test_store.py +++ b/tests/core/test_store.py @@ -8,6 +8,8 @@ from __future__ import annotations +import asyncio +import sqlite3 from collections.abc import AsyncIterator from dataclasses import MISSING, fields, is_dataclass, replace from pathlib import Path @@ -442,6 +444,56 @@ async def test_current_entry_responsibilities_persist_in_place(store: Store) -> assert got.history[-1].responsibilities[0].status is Status.MET +# -- SQLite journal mode (WAL) ------------------------------------------------------ + + +async def _pragma(store: SqlAlchemyStore, name: str) -> Any: + async with store._engine.connect() as conn: + return (await conn.exec_driver_sql(f"PRAGMA {name}")).scalar() + + +async def test_on_disk_sqlite_runs_in_wal_mode(tmp_path: Path) -> None: + store = SqlAlchemyStore(f"sqlite:///{tmp_path / 'tasks.db'}") + await store.init() + try: + assert await _pragma(store, "journal_mode") == "wal" + assert await _pragma(store, "synchronous") == 1 # NORMAL + assert await _pragma(store, "busy_timeout") == rs._SQLITE_BUSY_TIMEOUT_MS + finally: + await store.close() + + +async def test_in_memory_sqlite_is_left_alone() -> None: + store = SqlAlchemyStore("sqlite://") + await store.init() + try: + assert await _pragma(store, "journal_mode") == "memory" + finally: + await store.close() + + +async def test_reads_proceed_while_another_connection_holds_the_write_lock( + tmp_path: Path, +) -> None: + # The bug WAL fixes: under the rollback journal an exclusive writer locks every reader out + # (the dashboard's long-poll read failed with `database is locked`). In WAL it doesn't. + db = tmp_path / "tasks.db" + store = SqlAlchemyStore(f"sqlite:///{db}") + await store.init() + await _seed_repo(store) + await _new_task(store) + writer = sqlite3.connect(db, timeout=0) + try: + writer.execute("BEGIN EXCLUSIVE") + writer.execute("UPDATE task SET slug = 'uncommitted'") + tasks = await asyncio.wait_for(store.list_tasks_summary(), timeout=5) + assert [t.slug for t in tasks] == [None] # sees the last committed state + finally: + writer.rollback() + writer.close() + await store.close() + + # -- domain / persistence sync ------------------------------------------------------ # # Two reflective guards so the ORM rows and the domain dataclasses can't drift apart: diff --git a/tests/sessionservice/test_home_migration.py b/tests/sessionservice/test_home_migration.py index 7bc4ed7eb..752778011 100644 --- a/tests/sessionservice/test_home_migration.py +++ b/tests/sessionservice/test_home_migration.py @@ -74,6 +74,28 @@ def test_migrate_db_noop_when_old_absent(tmp_path: Path, monkeypatch: pytest.Mon assert not Path(fake_url[len("sqlite:///") :]).exists() +def test_migrate_db_moves_wal_sidecars_with_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.chdir(tmp_path) + (tmp_path / "panopticon.db").write_bytes(b"sqlite-data") + (tmp_path / "panopticon.db-wal").write_bytes(b"wal") + (tmp_path / "panopticon.db-shm").write_bytes(b"shm") + + fake_url = _make_fake_db_url(tmp_path) + monkeypatch.setattr("panopticon.taskservice.__main__.DB_URL", fake_url) + + from panopticon.taskservice.__main__ import migrate_db_to_home + + migrate_db_to_home(fake_url) + + new = Path(fake_url[len("sqlite:///") :]) + assert (new.parent / "panopticon.db-wal").read_bytes() == b"wal" + assert (new.parent / "panopticon.db-shm").read_bytes() == b"shm" + assert not (tmp_path / "panopticon.db-wal").exists() + assert not (tmp_path / "panopticon.db-shm").exists() + + def test_migrate_db_skips_custom_url(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.chdir(tmp_path) old = tmp_path / "panopticon.db"