Skip to content

The agent that grows with you

refactor(state): one heal-and-retry helper for every topic read; trim tests

kshitijk4poord612e2d15aa1
diff --git a/hermes_state_telegram.py b/hermes_state_telegram.py
index 04383fb2907..c73a6d51627 100644
--- a/hermes_state_telegram.py
+++ b/hermes_state_telegram.py
@@ -100,35 +100,24 @@ class SessionTelegramTopicsMixin:
tables (nobody ran ``/topic``) by returning their empty value and never create them;
pre-v3 tables left by an upgrade are self-healed on read."""
- def _topic_read_one(self, sql: str, params):
- """``fetchone`` that treats an unmigrated table as None. A pre-v3 table left by an
- upgrade (issue #103363) is healed to v3 once and the read retried, so topic mode
- keeps working on existing installs instead of silently reading as empty."""
+ def _topic_read(self, read, sql: str, params, empty):
+ """Run ``read(sql, params)``; an absent table reads as ``empty``. A pre-v3 table left by an
+ upgrade (#103363) raises ``no such column: profile_name`` — heal it and retry, otherwise the
+ write-only migration is never reached and topic mode silently reads as off forever."""
try:
- return self._read_one(sql, params)
+ return read(sql, params)
except sqlite3.OperationalError as exc:
if "no such column: profile_name" not in str(exc):
- return None
- self._heal_pre_v3_topic_tables()
- try:
- return self._read_one(sql, params)
- except sqlite3.OperationalError:
- return None
-
- def _heal_pre_v3_topic_tables(self) -> None:
- """Heal pre-v3 topic tables left by an upgrade. A failed heal (lock timeout,
- cross-process race) warns once instead of surfacing through the readers as the
- silent-return shape they exist to avoid; the next read retries the heal."""
+ return empty
try:
self.apply_telegram_topic_migration()
+ return read(sql, params)
except sqlite3.Error:
- if not getattr(self, "_topic_heal_warned", False):
- self._topic_heal_warned = True
- logger.warning(
- "telegram topic self-heal to v3 failed; reads keep hitting the "
- "pre-v3 schema and read as empty until the heal succeeds",
- exc_info=True,
- )
+ logger.warning("telegram topic tables are pre-v3 and the heal failed; reading as empty", exc_info=True)
+ return empty
+
+ def _topic_read_one(self, sql: str, params):
+ return self._topic_read(self._read_one, sql, params, None)
def apply_telegram_topic_migration(self) -> None:
"""Create Telegram DM topic-mode tables on explicit /topic opt-in and self-heal
@@ -257,23 +246,11 @@ class SessionTelegramTopicsMixin:
) -> List[Dict[str, Any]]:
"""All bindings for one chat, newest first ([] when the table is absent)."""
profile_name = _normalize_telegram_topic_profile_name(profile_name)
- try:
- rows = self._read_all(
- "SELECT * FROM telegram_dm_topic_bindings WHERE profile_name = ? AND chat_id = ? ORDER BY updated_at DESC",
- (profile_name, str(chat_id)),
- )
- except sqlite3.OperationalError as exc:
- if "no such column: profile_name" not in str(exc):
- return []
- # Same pre-v3 self-heal as _topic_read_one (issue #103363).
- self._heal_pre_v3_topic_tables()
- try:
- rows = self._read_all(
- "SELECT * FROM telegram_dm_topic_bindings WHERE profile_name = ? AND chat_id = ? ORDER BY updated_at DESC",
- (profile_name, str(chat_id)),
- )
- except sqlite3.OperationalError:
- return []
+ rows = self._topic_read(
+ self._read_all,
+ "SELECT * FROM telegram_dm_topic_bindings WHERE profile_name = ? AND chat_id = ? ORDER BY updated_at DESC",
+ (profile_name, str(chat_id)), [],
+ )
return [dict(row) for row in rows]
def get_telegram_topic_binding_by_session(self, *, session_id: str) -> Optional[Dict[str, Any]]:
diff --git a/tests/gateway/test_telegram_topic_read_selfheal_103363.py b/tests/hermes_state/test_telegram_topic_selfheal.py
similarity index 80%
rename from tests/gateway/test_telegram_topic_read_selfheal_103363.py
rename to tests/hermes_state/test_telegram_topic_selfheal.py
index bdc6b448db8..4a3b3d28c6f 100644
--- a/tests/gateway/test_telegram_topic_read_selfheal_103363.py
+++ b/tests/hermes_state/test_telegram_topic_selfheal.py
@@ -1,4 +1,4 @@
-"""Issue #103363 — reading pre-v3 telegram topic tables self-heals to v3.
+"""Regression for #103363 — reading pre-v3 telegram topic tables self-heals to v3.
Upgrades that enabled DM topic mode before #76423 keep v2 tables (no
``profile_name`` column). Reads used to swallow ``no such column`` as an empty
@@ -8,10 +8,8 @@ migration was never reached. Reads now heal the table once and retry.
from __future__ import annotations
-import logging
import sqlite3
from pathlib import Path
-from unittest import mock
from hermes_state import SessionDB
@@ -72,6 +70,8 @@ def test_topic_reads_selfheal_pre_v3_tables(tmp_path: Path):
binding = db.get_telegram_topic_binding(chat_id=CHAT, thread_id="99", profile_name="default")
assert binding is not None
assert binding["session_id"] == "legacy-sess"
+ rows = db.list_telegram_topic_bindings_for_chat(chat_id=CHAT, profile_name="default")
+ assert [row["session_id"] for row in rows] == ["legacy-sess"]
assert db.get_meta("telegram_dm_topic_schema_version") == "3"
# Profile isolation still holds after the heal.
assert not db.is_telegram_topic_mode_enabled(
@@ -81,17 +81,6 @@ def test_topic_reads_selfheal_pre_v3_tables(tmp_path: Path):
db.close()
-def test_list_bindings_selfheals_pre_v3_table(tmp_path: Path):
- db_path = tmp_path / "v2-upgrade.db"
- _create_v2_state(db_path)
- db = SessionDB(db_path=db_path)
-
- rows = db.list_telegram_topic_bindings_for_chat(chat_id=CHAT, profile_name="default")
- assert [row["session_id"] for row in rows] == ["legacy-sess"]
- assert db.get_meta("telegram_dm_topic_schema_version") == "3"
- db.close()
-
-
def test_absent_tables_still_read_empty_and_are_not_created(tmp_path: Path):
db = SessionDB(db_path=tmp_path / "fresh.db")
@@ -163,28 +152,3 @@ def test_heal_rebuild_rolls_back_atomically(tmp_path: Path):
chat_id=CHAT, user_id=CHAT, profile_name="default",
)
db.close()
-
-
-def test_failed_heal_warns_once_and_degrades_to_empty(tmp_path: Path, caplog):
- """A failing heal (lock timeout, cross-process race) must not surface as the
- silent-return shape the readers exist to fix: one warning per instance,
- reads keep returning their empty value."""
- db_path = tmp_path / "v2-upgrade.db"
- _create_v2_state(db_path)
- db = SessionDB(db_path=db_path)
-
- def locked(*args, **kwargs):
- raise sqlite3.OperationalError("database is locked")
-
- with mock.patch.object(SessionDB, "apply_telegram_topic_migration", locked):
- with caplog.at_level(logging.WARNING, logger="hermes_state"):
- assert not db.is_telegram_topic_mode_enabled(
- chat_id=CHAT, user_id=CHAT, profile_name="default",
- )
- assert db.get_telegram_topic_binding(
- chat_id=CHAT, thread_id="99", profile_name="default",
- ) is None
- assert db.list_telegram_topic_bindings_for_chat(chat_id=CHAT) == []
- # One warning across every reader, not one per read.
- assert len([r for r in caplog.records if "self-heal" in r.getMessage()]) == 1
- db.close()