Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dest>"` — 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
Expand Down
5 changes: 5 additions & 0 deletions src/panopticon/taskservice/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
32 changes: 31 additions & 1 deletion src/panopticon/taskservice/store_sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,21 @@
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 (``<db>-wal``, ``<db>-shm``); copy the DB with the service stopped, or via
``sqlite3 <db> .backup``. In-memory engines are left alone (WAL means nothing there).
"""

from __future__ import annotations

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,
Expand Down Expand Up @@ -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."""
Expand All @@ -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) ----


Expand Down Expand Up @@ -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
)
Expand Down
52 changes: 52 additions & 0 deletions tests/core/test_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
22 changes: 22 additions & 0 deletions tests/sessionservice/test_home_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading