Skip to content

The agent that grows with you

fix(sessions): read-only store message, drift_only flag, honest v32 comment

Teknium6335bd74c823
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index c10f2b423ab..59aa12953b5 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -109,14 +109,15 @@ def _cmd_repair(args):
# A missing canonical sessions table is not additive upgrade drift: creating
# an empty one could hide lost history. Preserve corruption/recovery routing.
reason = _db_opens_cleanly(db_path)
- repair = repair_state_db_schema
- if reason is None:
+ # Opens cleanly but lags SCHEMA_SQL: additive drift (snapshot reconcile), not corruption surgery.
+ drift_only = reason is None
+ if drift_only:
try:
reason = schema_drift_reason(db_path)
except (sqlite3.Error, OSError) as exc:
print(f"✗ Could not check session schema: {exc}")
return 1
- repair = repair_declarative_schema
+ repair = repair_declarative_schema if drift_only else repair_state_db_schema
if reason is None:
print(f"✓ {db_path} opens cleanly — no repair needed.")
return
@@ -130,14 +131,14 @@ def _cmd_repair(args):
print(f" backup: {report['backup_path']}")
print(f" strategy: {report.get('strategy')}")
try:
- with SessionDB(db_path=db_path, read_only=repair is repair_declarative_schema) as _repair_db:
+ with SessionDB(db_path=db_path, read_only=drift_only) as _repair_db:
n = _repair_db._conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]
print(f"✓ Repaired — {n} sessions recovered.")
except Exception:
print("✓ Repaired.")
return
print(f"✗ Repair failed: {report.get('error')}")
- if repair is repair_declarative_schema:
+ if drift_only:
if report.get('backup_path'):
print(f" A backup is preserved at: {report['backup_path']}")
return 1
diff --git a/hermes_state_common.py b/hermes_state_common.py
index 343b6fc8222..c3b0a08cc7b 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -282,10 +282,10 @@ def _sql_session_last_active_by_id(session_id_expr: str) -> str:
# v32 (#140315): no data migration. #106742 added runtime_epoch, session_admissions, worker_executions,
-# worker_receipts and three columns to SCHEMA_SQL while v31 stayed, so a store missing them read as
-# current. The bump makes that store detectably behind; its catch-up is the declarative
+# worker_receipts and three columns to SCHEMA_SQL under v31. Drift is detected by the schema read probe
+# (schema_read_probe_statements), never by this number, and its catch-up is the declarative
# executescript(SCHEMA_SQL) + _reconcile_columns() every writable open already runs (additive,
-# idempotent). Bump again whenever SCHEMA_SQL gains a table or column.
+# idempotent). The bump only records that the declared shape changed; a new table or column needs no bump.
SCHEMA_VERSION = 32
# Auto-maintenance VACUUMs only above this freelist fraction; below it a rewrite costs more I/O than it returns.
diff --git a/hermes_state_reconcile.py b/hermes_state_reconcile.py
index 2cba992d8c5..32be34edc54 100644
--- a/hermes_state_reconcile.py
+++ b/hermes_state_reconcile.py
@@ -7,6 +7,7 @@ surgery (:func:`repair_declarative_schema`). Neither runs while a gateway owns t
"""
import contextlib
import logging
+import os
import sqlite3
import threading
from contextlib import closing
@@ -59,7 +60,6 @@ def _reconcile_snapshot(path, guard):
_copy_database_snapshot(scratch, path, destination_connection=guard)
finally:
if error := _unlink_db_triple(scratch):
- import logging
logging.getLogger(__name__).warning('Could not remove reconciliation snapshot: %s', error)
@@ -461,8 +461,22 @@ def reconcile_drift_for_browse(path: Path) -> bool:
raise DeclarativeDriftError(
f"Session store for profile '{label}' changed while browsing verified it "
f'({reason}); nothing was changed. Retry in a moment; the list was not cleared.')
+ def not_writable(why):
+ return DeclarativeDriftError(
+ f"Session store for profile '{label}' is behind this Hermes version ({reason}), "
+ f'but {why} is not writable by this user, so browsing cannot add the missing '
+ f'tables/columns; nothing was changed. Fix the permissions, then reload.')
+ # The shared column reconciler logs a readonly ALTER failure and continues, so check
+ # first: the file plus its directory (SQLite creates its journal/WAL beside it).
+ for target in (path, path.parent):
+ if not os.access(target, os.W_OK):
+ raise not_writable(str(target))
try:
_apply_additive_schema(path, budget)
+ except sqlite3.OperationalError as exc:
+ if 'readonly' in str(exc).lower():
+ raise not_writable(str(path)) from exc
+ raise
except DeclarativeDriftError as exc:
raise DeclarativeDriftError(
f"Session store for profile '{label}' is behind this Hermes version and could not "
diff --git a/tests/hermes_cli/test_browse_schema_drift.py b/tests/hermes_cli/test_browse_schema_drift.py
index 47798f409c4..e5e34bad0bb 100644
--- a/tests/hermes_cli/test_browse_schema_drift.py
+++ b/tests/hermes_cli/test_browse_schema_drift.py
@@ -970,3 +970,27 @@ def test_owned_refusal_names_the_owning_multiplexers_restart(tmp_path):
assert caught.value.status_code == 503 and "running gateway owns it" in detail
assert "`hermes gateway restart`" in detail
assert "-p scribe gateway restart" not in detail
+
+
[email protected]("linux", "macos")
+def test_read_only_lagging_store_gets_a_permissions_message(tmp_path):
+ """alt-glitch S5: a read-only state.db got the generic "restart the gateway" text. A `readonly
+ database` error from the catch-up names the permission problem and the path; history untouched."""
+ import os
+
+ if os.geteuid() == 0:
+ pytest.skip("root writes read-only files")
+ path = _lagging_store_with_history(_profile_home(tmp_path), rows=10)
+ before = _file_state(path)
+ path.chmod(0o444)
+ try:
+ with pytest.raises(HTTPException) as caught:
+ _open_session_db_at_path(path, read_only=True)
+ finally:
+ path.chmod(0o600)
+ detail = str(caught.value.detail)
+ assert caught.value.status_code == 503
+ assert "not writable" in detail and str(path) in detail
+ assert "nothing was changed" in detail
+ assert "restart" not in detail.lower()
+ assert _file_state(path) == before
diff --git a/tests/hermes_cli/test_sessions_repair_declarative.py b/tests/hermes_cli/test_sessions_repair_declarative.py
index 6c402d45280..abe51d5b916 100644
--- a/tests/hermes_cli/test_sessions_repair_declarative.py
+++ b/tests/hermes_cli/test_sessions_repair_declarative.py
@@ -16,6 +16,9 @@ def _volume_headroom(monkeypatch):
"""The backup/snapshot guards reserve 2% of the volume: hermetic on a nearly full dev disk."""
import hermes_state_repair as repair
monkeypatch.setattr(repair, '_REPAIR_BACKUP_FREE_FRACTION', 0.0)
+ # The holder scan sees every process on the host: a developer's running Hermes would hold a
+ # real state.db and refuse these tmp_path repairs. Same stub as test_state_db_repair_non_destructive.
+ monkeypatch.setattr(repair, '_live_writer_holds_db', lambda _path: False)
def _legacy_store(tmp_path, monkeypatch):