Skip to content

The agent that grows with you

fix(dashboard): preserve maintenance writes on read polling

joelbrilliant57197cd48d84
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 548d9bdd463..d708ae46eaf 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -90,12 +90,12 @@ def get_sessions(
if profile:
profile_name, _ = _cron_profile_home(profile)
try:
- db = _open_session_db_for_profile(profile)
+ # Auto-archive is the only configured write on this GET path. Run it
+ # through a dedicated maintenance connection, close that writer, then
+ # open the listing connection read-only.
+ _maybe_auto_archive_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
- # Opportunistic, config-gated, double-throttled stale-session
- # sweep — the only auto_archive hook that fires for Desktop's
- # `hermes serve` backend. No-op when disabled or run recently.
- _maybe_auto_archive_for_profile(db, profile)
min_message_count = max(0, min_messages)
archived_only = archived == "only"
include_archived = archived == "include"
@@ -182,7 +182,7 @@ async def search_sessions(
if not q or not q.strip():
return {"results": []}
try:
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
safe_limit = max(1, min(int(limit or 20), 100))
source_filter = source or None
@@ -421,7 +421,7 @@ async def bulk_delete_sessions_endpoint(body: BulkDeleteSessions):
detail="ids must contain at most 500 entries",
)
def _delete() -> int:
- db = _open_session_db_for_profile(body.profile)
+ db = _open_session_db_for_profile(body.profile, read_only=False)
try:
return db.delete_sessions(body.ids)
finally:
@@ -466,7 +466,7 @@ async def count_empty_sessions_endpoint(profile: Optional[str] = None):
that does nothing. Cheap, single-COUNT query.
"""
def _count() -> int:
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
return db.count_empty_sessions()
finally:
@@ -496,7 +496,7 @@ async def delete_empty_sessions_endpoint(profile: Optional[str] = None):
the two delete endpoints' DB-vs-disk behaviour consistent.
"""
def _delete() -> int:
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=False)
try:
return db.delete_empty_sessions()
finally:
@@ -513,7 +513,7 @@ async def get_session_stats(profile: Optional[str] = None):
Registered before ``/api/sessions/{session_id}`` so the literal ``stats``
path isn't captured as a session id by the parameterized route.
"""
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
total = db.session_count(include_archived=True)
active_store = db.session_count(include_archived=False)
@@ -540,7 +540,7 @@ async def get_session_stats(profile: Optional[str] = None):
@manage_router.get("/api/sessions/{session_id}")
async def get_session_detail(session_id: str, profile: Optional[str] = None):
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
sid = db.resolve_session_id(session_id)
session = db.get_session(sid) if sid else None
@@ -567,7 +567,7 @@ async def get_session_latest_descendant(
profile: Optional[str] = None,
):
def _lookup():
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
return _session_latest_descendant(session_id, db)
finally:
@@ -592,7 +592,7 @@ async def get_session_messages(
offset: int = Query(0, ge=0),
):
def _read():
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
sid = db.resolve_session_id(session_id)
if not sid:
@@ -625,7 +625,7 @@ async def delete_session_endpoint(session_id: str, profile: Optional[str] = None
# opening its state.db directly. Remote profiles never reach here — the
# desktop routes their DELETE to the remote backend. Omit for current/default.
def _delete():
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=False)
try:
# Resolve exact ids / unique prefixes like every other session endpoint
# (detail, messages, rename, export all do). A session that no longer
@@ -656,7 +656,7 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):
session from the auto-archive sweep). Any field may be omitted. ``profile``
targets another profile's session.
"""
- db = _open_session_db_for_profile(body.profile)
+ db = _open_session_db_for_profile(body.profile, read_only=False)
try:
sid = db.resolve_session_id(session_id)
if not sid:
@@ -690,7 +690,7 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):
async def export_session_endpoint(session_id: str, profile: Optional[str] = None):
"""Export a single session (metadata + messages) as JSON."""
def _export():
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
sid = db.resolve_session_id(session_id)
return db.export_session(sid) if sid else None
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index a9a922aa547..2f4ace574b1 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -10989,7 +10989,7 @@ async def _read_session_import_body(request: Request) -> bytes:
def _import_sessions_for_profile(profile: Optional[str], sessions: List[Dict[str, Any]]) -> Dict[str, Any]:
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=False)
try:
return db.import_sessions(sessions)
finally:
@@ -11021,19 +11021,82 @@ from hermes_cli.web_routers.sessions import ( # noqa: E402,F401 — legacy re-e
-def _open_session_db_for_profile(profile: Optional[str]):
- """Open a SessionDB for read paths, optionally for another profile.
+# Serialises the one-time writable schema bootstrap for read-only opens.
+# Concurrent first-load polls otherwise race sqlite file creation: the losers
+# open mode=ro against a store whose schema is still being written and every
+# query raises "no such table: sessions".
+_session_db_bootstrap_lock = threading.Lock()
- ``profile`` None/empty → this process's own ``state.db`` (the common,
- single-profile case). A named profile opens that profile's on-disk
- ``state.db`` directly so the primary backend can serve cross-profile reads
- (transcripts, detail) without spawning that profile's backend.
+# Stale-schema probe for read-only opens: compiled against the newest columns
+# the dashboard read paths query. Reads at most one row per table. Read-only
+# opens skip _reconcile_columns(), so an older store would otherwise 500 on
+# every poll until something opened it writable.
+_SESSION_DB_READ_PROBE_SQL = (
+ "SELECT (SELECT archived FROM sessions LIMIT 1), "
+ "(SELECT pinned FROM sessions LIMIT 1), "
+ "(SELECT active FROM messages LIMIT 1), "
+ "(SELECT compacted FROM messages LIMIT 1)"
+)
+
+
+def _open_session_db_for_profile(profile: Optional[str], *, read_only: bool):
+ """Open a SessionDB with an explicit access mode for a profile.
+
+ ``profile`` None/empty selects this process's own ``state.db``. A named
+ profile opens that profile's on-disk store directly.
+
+ Writable opens keep the full init and repair path. Read-only opens
+ bootstrap a missing or zero-byte store once, and heal an older or
+ malformed schema through one writable open before reopening read-only.
+ The healthy read path never takes a write lock or requests a checkpoint.
"""
- from hermes_state import SessionDB
- if not profile:
- return SessionDB()
- _name, home = _cron_profile_home(profile)
- return SessionDB(db_path=Path(home) / "state.db")
+ import sqlite3
+
+ from hermes_state import SessionDB, _default_db_path, is_malformed_db_error
+
+ if profile:
+ _name, home = _cron_profile_home(profile)
+ db_path = Path(home) / "state.db"
+ else:
+ db_path = Path(_default_db_path())
+ if not read_only:
+ return SessionDB(db_path=db_path, read_only=False)
+
+ def _needs_bootstrap() -> bool:
+ try:
+ return db_path.stat().st_size == 0
+ except FileNotFoundError:
+ return True
+ except OSError:
+ return False
+
+ if _needs_bootstrap():
+ with _session_db_bootstrap_lock:
+ if _needs_bootstrap():
+ SessionDB(db_path=db_path, read_only=False).close()
+
+ def _open_probed():
+ db = SessionDB(db_path=db_path, read_only=True)
+ # Unit-test fakes may replace SessionDB without exposing a raw
+ # connection. Probe only real connections.
+ conn = getattr(db, "_conn", None)
+ if conn is not None:
+ try:
+ conn.execute(_SESSION_DB_READ_PROBE_SQL).fetchone()
+ except BaseException:
+ db.close()
+ raise
+ return db
+
+ try:
+ return _open_probed()
+ except sqlite3.DatabaseError as exc:
+ message = str(exc).lower()
+ stale_schema = "no such table" in message or "no such column" in message
+ if not stale_schema and not is_malformed_db_error(exc):
+ raise
+ SessionDB(db_path=db_path, read_only=False).close()
+ return _open_probed()
# In-process throttle for the opportunistic auto-archive trigger, keyed by
@@ -11044,7 +11107,7 @@ _AUTO_ARCHIVE_CHECK_INTERVAL_S = 300.0
_last_auto_archive_check: Dict[str, float] = {}
-def _maybe_auto_archive_for_profile(db, profile: Optional[str]) -> None:
+def _maybe_auto_archive_for_profile(profile: Optional[str]) -> None:
"""Run the config-gated stale-session auto-archive for ``profile``.
The Desktop backend is spawned as ``hermes serve`` — it runs neither the
@@ -11065,10 +11128,14 @@ def _maybe_auto_archive_for_profile(db, profile: Optional[str]) -> None:
cfg = (_load_full_config().get("sessions") or {})
if not cfg.get("auto_archive", False):
return
- db.maybe_auto_archive(
- idle_days=float(cfg.get("auto_archive_days", 3)),
- min_interval_hours=int(cfg.get("min_interval_hours", 24)),
- )
+ db = _open_session_db_for_profile(profile, read_only=False)
+ try:
+ db.maybe_auto_archive(
+ idle_days=float(cfg.get("auto_archive_days", 3)),
+ min_interval_hours=int(cfg.get("min_interval_hours", 24)),
+ )
+ finally:
+ db.close()
except Exception as exc:
_log.debug("opportunistic auto-archive skipped: %s", exc)
@@ -11086,11 +11153,7 @@ async def _auto_archive_ticker_loop(
"""
def _sweep() -> None:
- db = _open_session_db_for_profile(None)
- try:
- _maybe_auto_archive_for_profile(db, None)
- finally:
- db.close()
+ _maybe_auto_archive_for_profile(None)
await asyncio.sleep(initial_delay_s)
while True:
@@ -11138,7 +11201,7 @@ def _prune_sessions(body: SessionPrune):
if has_window or (_attr_filters_set and not _older_than_explicit):
_effective_older_than = None
profile_home = _cron_profile_home(body.profile)[1] if body.profile else get_hermes_home()
- db = _open_session_db_for_profile(body.profile)
+ db = _open_session_db_for_profile(body.profile, read_only=False)
try:
filters = dict(
older_than_days=_effective_older_than,
@@ -11563,7 +11626,7 @@ def _list_cron_job_runs_sync(job_id: str, profile: Optional[str] = None, limit:
except (TypeError, ValueError):
limit_n = 20
- db = _open_session_db_for_profile(selected)
+ db = _open_session_db_for_profile(selected, read_only=True)
try:
runs = db.list_cron_job_runs(canonical, limit=limit_n, offset=0)
now = time.time()
@@ -13891,7 +13954,7 @@ def _aux_task_summary(aux_rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
def _get_usage_analytics(days: int = 30, profile: Optional[str] = None):
from agent.insights import InsightsEngine
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
cutoff = time.time() - (days * 86400)
cur = db._conn.execute("""
@@ -13980,7 +14043,7 @@ def _get_models_analytics(days: int = 30, profile: Optional[str] = None):
Returns token/cost/session breakdown per model plus capability metadata
from models.dev (context window, vision, tools, reasoning, etc.).
"""
- db = _open_session_db_for_profile(profile)
+ db = _open_session_db_for_profile(profile, read_only=True)
try:
cutoff = time.time() - (days * 86400)
@@ -14623,7 +14686,8 @@ def _resolve_chat_argv(
if resume:
_resume_db = _open_session_db_for_profile(
- requested if profile_dir is not None else None
+ requested if profile_dir is not None else None,
+ read_only=True,
)
try:
latest_resume, _latest_path = _session_latest_descendant(resume, _resume_db)
diff --git a/hermes_state.py b/hermes_state.py
index 4f7b6453461..ef4c7e9b0e0 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1911,6 +1911,21 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
isolation_level=None,
)
self._conn.row_factory = sqlite3.Row
+ # FTS capability flags normally come from writable schema
+ # initialisation. Probe existing virtual tables with SELECTs
+ # only so read-only search keeps its FTS and trigram paths.
+ cursor = self._conn.cursor()
+ self._fts_enabled = (
+ self._fts_table_probe(cursor, "messages_fts") is True
+ )
+ if self._fts_enabled:
+ self._trigram_available = (
+ self._fts_table_probe(
+ cursor,
+ "messages_fts_trigram",
+ )
+ is True
+ )
return
self.db_path.parent.mkdir(parents=True, exist_ok=True)
@@ -2627,8 +2642,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""Close the database connection.
Drains queued token deltas first (the background writer needs the
- connection), then attempts a TRUNCATE WAL checkpoint so that
- exiting processes help shrink the WAL file.
+ connection). Writable connections then attempt a TRUNCATE WAL
+ checkpoint so exiting writer processes help shrink the WAL file.
+ Read-only connections never request a checkpoint.
"""
self._stop_token_writer()
# The atexit hook holds a strong reference to this instance (bound
@@ -2656,10 +2672,14 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
self._read_local.conn = None
with self._lock:
if self._conn:
- try:
- self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
- except Exception as exc:
- logger.debug("WAL checkpoint (TRUNCATE) at close failed: %s", exc)
+ if not self.read_only:
+ try:
+ self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ except Exception as exc:
+ logger.debug(
+ "WAL checkpoint (TRUNCATE) at close failed: %s",
+ exc,
+ )
self._conn.close()
self._conn = None
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 1233fa8c20c..1a24d40e948 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -6,6 +6,7 @@ import json
import shutil
import sys
import threading
+import time
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch, MagicMock
@@ -257,6 +258,177 @@ class TestWebServerEndpoints:
self.client = TestClient(app)
self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+ def test_get_sessions_poll_preserves_pending_wal(self):
+ """Repeated GET-only polls must not checkpoint another writer's WAL."""
+ import sqlite3
+
+ from hermes_cli import web_server
+ from hermes_constants import get_hermes_home
+ from hermes_state import SessionDB
+
+ web_server._last_auto_archive_check.clear()
+ db_path = get_hermes_home() / "state.db"
+ wal_path = Path(f"{db_path}-wal")
+ writer = SessionDB(db_path=db_path)
+ monitor = None
+ try:
+ writer._conn.execute("PRAGMA wal_autocheckpoint=0")
+ writer.create_session("poll-wal", source="cli")
+ writer.append_message(
+ "poll-wal",
+ role="user",
+ content="pending writer frame " + ("x" * 65_536),
+ )
+
+ monitor = sqlite3.connect(str(db_path), isolation_level=None)
+ wal_bytes_before = wal_path.stat().st_size
+ data_version_before = monitor.execute(
+ "PRAGMA data_version"
+ ).fetchone()[0]
+ counts_before = monitor.execute(
+ "SELECT (SELECT COUNT(*) FROM sessions), "
+ "(SELECT COUNT(*) FROM messages)"
+ ).fetchone()
+
+ responses = [
+ self.client.get(
+ "/api/sessions?limit=50&offset=0&order=created"
+ )
+ for _ in range(3)
+ ]
+
+ wal_bytes_after = wal_path.stat().st_size
+ data_version_after = monitor.execute(
+ "PRAGMA data_version"
+ ).fetchone()[0]
+ counts_after = monitor.execute(
+ "SELECT (SELECT COUNT(*) FROM sessions), "
+ "(SELECT COUNT(*) FROM messages)"
+ ).fetchone()
+
+ assert all(response.status_code == 200 for response in responses)
+ assert all(response.json()["total"] == 1 for response in responses)
+ assert wal_bytes_before > 0
+ assert wal_bytes_after == wal_bytes_before
+ assert data_version_after == data_version_before
+ assert counts_after == counts_before == (1, 1)
+ finally:
+ if monitor is not None:
+ monitor.close()
+ writer.close()
+
+ def test_get_sessions_auto_archive_uses_maintenance_writer(self):
+ from hermes_cli import web_server
+ from hermes_cli.config import load_config, save_config
+ from hermes_constants import get_hermes_home
+ from hermes_state import SessionDB
+
+ db_path = get_hermes_home() / "state.db"
+ seed = SessionDB(db_path=db_path)
+ try:
+ seed.create_session("stale", source="cli")
+ seed.create_session("fresh", source="cli")
+ seed._conn.execute(
+ "UPDATE sessions SET started_at = ? WHERE id = ?",
+ (time.time() - 30 * 86400, "stale"),
+ )
+ finally:
+ seed.close()
+
+ config = load_config()
+ config.setdefault("sessions", {}).update(
+ {
+ "auto_archive": True,
+ "auto_archive_days": 3,
+ "min_interval_hours": 0,
+ }
+ )
+ save_config(config)
+ web_server._last_auto_archive_check.clear()
+
+ response = self.client.get("/api/sessions?limit=50&offset=0")
+
+ assert response.status_code == 200
+ assert [row["id"] for row in response.json()["sessions"]] == ["fresh"]
+ verify = SessionDB(db_path=db_path, read_only=True)
+ try:
+ assert verify.get_session("stale")["archived"] == 1
+ assert verify.get_meta("last_auto_archive")
+ finally:
+ verify.close()
+
+ def test_get_sessions_fresh_store_returns_empty_list(self):
+ response = self.client.get("/api/sessions?limit=50&offset=0")
+
+ assert response.status_code == 200
+ assert response.json()["sessions"] == []
+ assert response.json()["total"] == 0
+
+ @pytest.mark.parametrize("missing_column", ["archived", "pinned"])
+ def test_get_sessions_heals_stale_schema_store(self, missing_column):
+ import sqlite3
+
+ from hermes_constants import get_hermes_home
+ from hermes_state import SessionDB
+
+ db_path = get_hermes_home() / "state.db"
+ seed = SessionDB(db_path=db_path)
+ try:
+ seed.create_session("stale-schema", source="cli")
+ finally:
+ seed.close()
+
+ legacy = sqlite3.connect(str(db_path))
+ try:
+ legacy.execute(f"ALTER TABLE sessions DROP COLUMN {missing_column}")
+ legacy.commit()
+ finally:
+ legacy.close()
+
+ response = self.client.get("/api/sessions?limit=50&offset=0")
+
+ assert response.status_code == 200
+ assert [row["id"] for row in response.json()["sessions"]] == [
+ "stale-schema"
+ ]
+ healed = sqlite3.connect(str(db_path))
+ try:
+ columns = {
+ row[1] for row in healed.execute("PRAGMA table_info(sessions)")
+ }
+ finally:
+ healed.close()
+ assert missing_column in columns
+
+ def test_get_sessions_zero_byte_store_returns_empty_list(self):
+ from hermes_constants import get_hermes_home
+
+ db_path = get_hermes_home() / "state.db"
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ db_path.touch()
+
+ response = self.client.get("/api/sessions?limit=50&offset=0")
+
+ assert response.status_code == 200
+ assert response.json()["sessions"] == []
+ assert response.json()["total"] == 0
+
+ def test_concurrent_first_load_reads_all_succeed_on_fresh_store(self):
+ from concurrent.futures import ThreadPoolExecutor
+
+ paths = [
+ "/api/sessions?limit=50&offset=0",
+ "/api/sessions/stats",
+ "/api/sessions/empty/count",
+ "/api/sessions?limit=10&offset=0&order=recent",
+ ] * 2
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ responses = list(pool.map(self.client.get, paths))
+
+ assert [response.status_code for response in responses] == [
+ 200
+ ] * len(paths)
+
@@ -3639,5 +3811,3 @@ class TestDashboardComponentHealth:
assert self.ws.DASHBOARD_HEALTH.selftest_status == "failing"
assert self.ws.DASHBOARD_HEALTH.selftest_http_status == 500
assert self.ws.DASHBOARD_HEALTH.snapshot()["status"] == "degraded"
-
-
diff --git a/tests/hermes_cli/test_web_server_session_search.py b/tests/hermes_cli/test_web_server_session_search.py
index 8d0faa88a65..46a0f986707 100644
--- a/tests/hermes_cli/test_web_server_session_search.py
+++ b/tests/hermes_cli/test_web_server_session_search.py
@@ -13,6 +13,10 @@ class _FakeSessionDB:
"""
closed = False
+ opened_read_only = None
+
+ def __init__(self, *args, **kwargs):
+ type(self).opened_read_only = kwargs.get("read_only")
@staticmethod
def _source_allowed(row, source=None, sources=None, exclude_sources=None):
@@ -93,6 +97,7 @@ class _FakeSessionDB:
def test_desktop_session_search_merges_id_matches_before_content_matches(monkeypatch):
+ _FakeSessionDB.opened_read_only = None
monkeypatch.setattr("hermes_state.SessionDB", _FakeSessionDB)
response = asyncio.run(web_server.search_sessions(q="20260603", limit=2))
@@ -123,3 +128,4 @@ def test_desktop_session_search_merges_id_matches_before_content_matches(monkeyp
},
]
}
+ assert _FakeSessionDB.opened_read_only is True
diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py
index 1df2a91c60a..9bbe5b16f61 100644
--- a/tests/test_hermes_state.py
+++ b/tests/test_hermes_state.py
@@ -77,6 +77,64 @@ def db(tmp_path):
session_db.close()
+# =========================================================================
+# Connection lifecycle
+# =========================================================================
+
+
+class TestConnectionLifecycle:
+ def test_read_only_close_never_requests_wal_checkpoint(self, tmp_path):
+ db_path = tmp_path / "state.db"
+ writable = SessionDB(db_path=db_path)
+ writable.create_session("s1", source="cli")
+ writable.close()
+
+ executed = []
+ read_only = SessionDB(db_path=db_path, read_only=True)
+ read_only._conn.set_trace_callback(executed.append)
+ read_only.close()
+
+ assert not any("wal_checkpoint" in sql.lower() for sql in executed)
+
+ def test_writable_close_retains_truncate_checkpoint(self, tmp_path):
+ db_path = tmp_path / "state.db"
+ writable = SessionDB(db_path=db_path)
+ executed = []
+ writable._conn.set_trace_callback(executed.append)
+
+ writable.close()
+
+ assert any(
+ "pragma wal_checkpoint(truncate)" == " ".join(sql.lower().split())
+ for sql in executed
+ )
+
+ def test_read_only_connection_keeps_fts_search_available(self, tmp_path):
+ db_path = tmp_path / "state.db"
+ writable = SessionDB(db_path=db_path)
+ writable.create_session("fts-read-only", source="cli")
+ writable.append_message(
+ "fts-read-only",
+ role="user",
+ content="readonlywoodpecker 大别山项目",
+ )
+ writable.close()
+
+ read_only = SessionDB(db_path=db_path, read_only=True)
+ try:
+ base_matches = read_only.search_messages("readonlywoodpecker")
+ trigram_matches = read_only.search_messages("大别山")
+ finally:
+ read_only.close()
+
+ assert [match["session_id"] for match in base_matches] == [
+ "fts-read-only"
+ ]
+ assert [match["session_id"] for match in trigram_matches] == [
+ "fts-read-only"
+ ]
+
+
# =========================================================================
# Session lifecycle
# =========================================================================
diff --git a/tests/test_web_server_sessiondb_eventloop.py b/tests/test_web_server_sessiondb_eventloop.py
index 7f014471c7c..c8277c48655 100644
--- a/tests/test_web_server_sessiondb_eventloop.py
+++ b/tests/test_web_server_sessiondb_eventloop.py
@@ -74,9 +74,24 @@ def test_sessiondb_handlers_open_connections_inside_executor_helpers():
assert db_open_owners, f"{name} does not offload SessionDB open + work"
+def test_sessiondb_opens_declare_access_mode():
+ for mod in (web_server, web_sessions):
+ tree = ast.parse(Path(mod.__file__).read_text(encoding="utf-8"))
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and _call_name(node) == "_open_session_db_for_profile"
+ ]
+ assert calls
+ for call in calls:
+ assert any(keyword.arg == "read_only" for keyword in call.keywords)
+
+
def test_bulk_delete_sessiondb_work_runs_off_event_loop(monkeypatch):
loop_thread = threading.get_ident()
db_threads: list[int] = []
+ db_modes: list[bool] = []
class _DB:
def delete_sessions(self, ids):
@@ -87,7 +102,12 @@ def test_bulk_delete_sessiondb_work_runs_off_event_loop(monkeypatch):
def close(self):
db_threads.append(threading.get_ident())
- monkeypatch.setattr(web_server, "_open_session_db_for_profile", lambda profile=None: _DB())
+ def _open_db(profile=None, *, read_only):
+ assert profile is None
+ db_modes.append(read_only)
+ return _DB()
+
+ monkeypatch.setattr(web_server, "_open_session_db_for_profile", _open_db)
result = asyncio.run(
web_server.bulk_delete_sessions_endpoint(
@@ -96,5 +116,6 @@ def test_bulk_delete_sessiondb_work_runs_off_event_loop(monkeypatch):
)
assert result == {"ok": True, "deleted": 2}
+ assert db_modes == [False]
assert db_threads
assert all(thread_id != loop_thread for thread_id in db_threads)