The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): decode errors now reach the heal path and fail loud in TUI (residual #98924 surfaces)
Alvin T. Veroye17fd0a70889
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 7b10fa16f8e..e99a90a98ea 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -12420,15 +12420,21 @@ def _open_session_db_at_path(db_path: Path, *, read_only: bool):try:return _open_probed()- except sqlite3.DatabaseError as exc:+ except (sqlite3.DatabaseError, UnicodeDecodeError) 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_schema_error(exc):+ if not stale_schema and not (+ # UnicodeDecodeError = pysqlite could not decode SQLite's own+ # error message because corrupt file bytes were embedded in it+ # (#98924). The one-writable-open heal is the only repair path,+ # so route it through the same dispatch as malformed schema.+ is_malformed_schema_error(exc) or isinstance(exc, UnicodeDecodeError)+ ):raiseSessionDB(db_path=db_path, read_only=False).close()try:return _open_probed()- except sqlite3.DatabaseError as still_stale:+ except (sqlite3.DatabaseError, UnicodeDecodeError) as still_stale:message = str(still_stale).lower()if "no such table" not in message and "no such column" not in message:raisediff --git a/hermes_state_schema.py b/hermes_state_schema.pyindex 7313e4270eb..5dcf9756df3 100644--- a/hermes_state_schema.py+++ b/hermes_state_schema.py@@ -517,7 +517,7 @@ class SessionSchemaMixin:"""Body of :meth:`_recover_stale_fts`; caller holds rebuild authority."""try:trigram_status = self._fts_table_probe(cursor, "messages_fts_trigram")- except sqlite3.DatabaseError:+ except (sqlite3.DatabaseError, UnicodeDecodeError):# A corrupt vtable may fail even a LIMIT 0 probe. It still needs# to be included in the drop-and-recreate recovery below.trigram_status = Truediff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex d6feee8ab68..f0591b241d2 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -628,6 +628,36 @@ class TestWebServerEndpoints:assert opens == [True]+ def test_decode_error_triggers_writable_heal(self, tmp_path, monkeypatch):+ """UnicodeDecodeError — pysqlite failing to decode SQLite's own error+ message over corrupt file bytes (#98924) — must route through the+ same one-writable-open heal as malformed schema."""+ import hermes_state+ from hermes_cli import web_server++ db_path = tmp_path / "state.db"+ db_path.write_bytes(b"not-empty")+ opens = []++ class _OkDB:+ _conn = None++ def close(self):+ pass++ def scripted_open(*_args, **kwargs):+ opens.append(kwargs.get("read_only", False))+ if opens == [True]:+ raise UnicodeDecodeError("utf-8", b"\x81", 0, 1, "invalid start byte")+ return _OkDB()++ monkeypatch.setattr(hermes_state, "SessionDB", scripted_open)++ db = web_server._open_session_db_at_path(db_path, read_only=True)++ assert isinstance(db, _OkDB)+ assert opens == [True, False, True]+def test_get_sessions_zero_byte_store_returns_empty_list(self):from hermes_constants import get_hermes_homediff --git a/tests/test_state_db_malformed_repair.py b/tests/test_state_db_malformed_repair.pyindex 819fa6bee22..df0f6b422be 100644--- a/tests/test_state_db_malformed_repair.py+++ b/tests/test_state_db_malformed_repair.py@@ -840,3 +840,42 @@ def test_repair_honors_configured_delete_mode(tmp_path, monkeypatch):assert report["repaired"] is Trueassert _mode_of(db_path) == "delete"+++# ── #98924 companion: recovery surface beyond the probe fix (#98935) ───────++# The probe itself is fixed in #98935; this test must not depend on it.+def test_fts_recovery_includes_vtables_that_raise_decode_errors(tmp_path):+ """Drop-and-recreate recovery must include corrupt vtables whose probe+ raises UnicodeDecodeError, not only sqlite3.DatabaseError (#98924)."""+ db_path = tmp_path / "state.db"+ db = SessionDB(db_path=db_path)+ sid = db.create_session(session_id=str(uuid.uuid4()), source="cli")+ db.append_message(sid, role="user", content="searchable needle")+ cursor = db._conn.cursor()++ original_probe = db._fts_table_probe++ def _decode_boom(probe_cursor, table_name):+ if table_name == "messages_fts_trigram":+ raise UnicodeDecodeError("utf-8", b"\x81", 0, 1, "invalid start byte")+ return original_probe(probe_cursor, table_name)++ db._fts_table_probe = _decode_boom+ try:+ assert db._recover_stale_fts(cursor, legacy=False) is True+ finally:+ db.close()++ check = sqlite3.connect(str(db_path))+ try:+ names = {+ row[0]+ for row in check.execute(+ "SELECT name FROM sqlite_master WHERE name LIKE 'messages_fts%'"+ )+ }+ finally:+ check.close()+ assert "messages_fts" in names+ assert "messages_fts_trigram" in namesdiff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex 4ac97a3f200..d73a9f196e3 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -14276,6 +14276,61 @@ def test_get_db_degrades_cleanly_when_sessiondb_init_fails(monkeypatch):assert server._db_error == "locking protocol"+def test_ensure_session_db_row_false_when_store_unavailable(monkeypatch):+ """Store unavailable → False, so prompt.submit can fail the send loudly+ instead of streaming into a store that will never save it (#98924)."""+ fake_mod = types.ModuleType("hermes_state")++ class _BrokenSessionDB:+ def __init__(self):+ raise RuntimeError("utf-8 boom")++ fake_mod.SessionDB = _BrokenSessionDB+ monkeypatch.setitem(sys.modules, "hermes_state", fake_mod)+ monkeypatch.setattr(server, "_db", None)+ monkeypatch.setattr(server, "_db_error", None)++ assert server._ensure_session_db_row({"session_key": "k1"}) is False+++def test_ensure_session_db_row_true_when_row_persisted(monkeypatch):+ created = []++ class _FakeDB:+ def create_session(self, key, **_kwargs):+ created.append(key)++ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())+ monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")++ assert server._ensure_session_db_row({"session_key": "k1", "cwd": "/tmp"}) is True+ assert created == ["k1"]+++def test_prompt_submit_fails_loudly_when_store_unavailable(monkeypatch):+ """A send with no persistable store must fail the RPC with a real error+ (desktop maps it to a toast) instead of streaming the message into a+ store that will never save it (#98924)."""+ monkeypatch.setattr(server, "_load_cfg", lambda: {"dashboard": {}})+ monkeypatch.setattr(server, "_get_db", lambda: None)+ monkeypatch.setattr(server, "_db_error", "utf-8 decode failure")++ server._sessions["lost-sid"] = _session()+ try:+ resp = server.handle_request(+ {+ "id": "lost",+ "method": "prompt.submit",+ "params": {"session_id": "lost-sid", "text": "will vanish"},+ }+ )+ finally:+ server._sessions.pop("lost-sid", None)++ assert resp["error"]["code"] == 5072+ assert "session storage unavailable" in resp["error"]["message"]++@pytest.mark.real_agent_prewarmdef test_session_create_continues_when_state_db_is_unavailable(monkeypatch):class _FakeWorker:diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 2143259ac42..f14b46cbce0 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -937,7 +937,17 @@ def _(rid, params: dict) -> dict:# Disk-full must fail the RPC (not stream silently): desktop maps the error# string to a "disk full" toast so the user knows why the send vanished.try:- _ensure_session_db_row(session)+ if _ensure_session_db_row(session) is False:+ # Store unavailable: failing the RPC is the only user-visible+ # signal — same principle as the disk-full path above (#98924).+ # _db_error carries the SessionDB open failure for the toast.+ return _err(+ rid,+ 5072,+ "session storage unavailable: "+ f"{_db_error or 'state.db could not be opened'} — the message "+ "was not saved; repair state.db and try again",+ )# A branch becomes real here: copy its parent's transcript into the row so it# resumes with full context (the agent won't persist the seed itself)._persist_branch_seed(session)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex fcc5cac0b1b..2b43d7434e1 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -3788,13 +3788,17 @@ def _register_session_cwd(session: dict | None) -> None:pass-def _ensure_session_db_row(session: dict) -> None:+def _ensure_session_db_row(session: dict) -> bool:"""Idempotently persist the session's DB row on first real activity.Called from prompt.submit so a row only exists once the user actually sendsa message — abandoned drafts never leave an empty "Untitled" session behind.Uses INSERT OR IGNORE under the hood, so re-calls (and the AIAgent's ownlazy create) are no-ops.+ Returns False only when the store is unavailable (no openable state.db);+ prompt.submit turns that into an RPC error so a send fails loudly with a+ toast instead of streaming into a store that will never save it (#98924).+ Every other outcome — no key, best-effort attempt, success — is True.A cwd the user *chose* is always persisted. When they made no explicitchoice the launch directory stands in, and whether that is meaningful@@ -3824,13 +3828,13 @@ def _ensure_session_db_row(session: dict) -> None:db = SessionDB(db_path=Path(profile_home) / "state.db")except Exception:logger.debug("failed to open profile db for session row", exc_info=True)- return+ return Falseclose_db = Trueelse:db = _get_db()close_db = Falseif db is None:- return+ return False# The session's own model/effort/fast pick — the composer override shipped on# session.create, or a restored /model switch — must own the row's model +# model_config. The agent isn't built yet at first prompt.submit, so derive@@ -3949,6 +3953,7 @@ def _ensure_session_db_row(session: dict) -> None:db.close()except Exception:pass+ return Truedef _persist_branch_seed(session: dict) -> None: