Skip to content

The agent that grows with you

fix(state): make the v2->v3 topic heal atomic and non-silent on failure

liuhao10247ef48e2e51d8
diff --git a/hermes_state_telegram.py b/hermes_state_telegram.py
index 8afd59543bc..04383fb2907 100644
--- a/hermes_state_telegram.py
+++ b/hermes_state_telegram.py
@@ -97,8 +97,8 @@ _UNLINKED_SCOPE_CLAUSES = """ AND COALESCE(NULLIF(TRIM(s.pr
class SessionTelegramTopicsMixin:
"""Telegram DM topic-mode tables, bindings and lookups. Read paths tolerate absent
- tables (nobody ran ``/topic``) by returning their empty value; only
- ``enable``/``bind`` run the migration."""
+ 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
@@ -109,16 +109,31 @@ class SessionTelegramTopicsMixin:
except sqlite3.OperationalError as exc:
if "no such column: profile_name" not in str(exc):
return None
- self.apply_telegram_topic_migration()
+ 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."""
+ try:
+ self.apply_telegram_topic_migration()
+ 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,
+ )
+
def apply_telegram_topic_migration(self) -> None:
- """Create Telegram DM topic-mode tables on explicit /topic opt-in. Deliberately NOT
- part of startup reconciliation: operators can upgrade and keep the old bot
- behavior until a user runs /topic. Schema versions: v1 initial; v2 session_id FK
+ """Create Telegram DM topic-mode tables on explicit /topic opt-in and self-heal
+ pre-v3 tables on read (#103363); absent tables stay read-only, and startup
+ reconciliation never runs this. Schema versions: v1 initial; v2 session_id FK
ON DELETE CASCADE (pruning clears bindings); v3 ``profile_name`` on both tables so
multiplexed gateways sharing one state.db isolate topic state per profile.
@@ -131,23 +146,29 @@ class SessionTelegramTopicsMixin:
if "profile_name" in have:
continue
# v1/v2 → v3. SQLite can't ALTER a PK or FK, so rebuild (also supplies v2's
- # ON DELETE CASCADE). Legacy rows land in "default" only.
+ # ON DELETE CASCADE). Legacy rows land in "default" only. Plain execute()
+ # keeps every statement inside _execute_write's BEGIN IMMEDIATE:
+ # executescript would implicitly commit the open transaction and run each
+ # statement in autocommit, so a crash after the DROP strands legacy rows
+ # in {table}_new (#42004 diagnosed the same shape for v1→v2) and breaks
+ # the whole-callback retry contract.
legacy_columns = columns.replace("profile_name, ", "", 1)
- conn.executescript(f"""
- CREATE TABLE {table}_new ({ddl});
- INSERT INTO {table}_new ({columns})
- SELECT 'default', {legacy_columns} FROM {table};
- DROP TABLE {table};
- ALTER TABLE {table}_new RENAME TO {table};
- """)
+ conn.execute(f"CREATE TABLE {table}_new ({ddl})")
+ conn.execute(
+ f"INSERT INTO {table}_new ({columns}) "
+ f"SELECT 'default', {legacy_columns} FROM {table}"
+ )
+ conn.execute(f"DROP TABLE {table}")
+ conn.execute(f"ALTER TABLE {table}_new RENAME TO {table}")
# Indexes after any rebuild: the user index needs profile_name.
- conn.executescript("""
- CREATE UNIQUE INDEX IF NOT EXISTS idx_telegram_dm_topic_bindings_session
- ON telegram_dm_topic_bindings(session_id);
-
- CREATE INDEX IF NOT EXISTS idx_telegram_dm_topic_bindings_user
- ON telegram_dm_topic_bindings(profile_name, user_id, chat_id);
- """)
+ conn.execute(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_telegram_dm_topic_bindings_session "
+ "ON telegram_dm_topic_bindings(session_id)"
+ )
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_telegram_dm_topic_bindings_user "
+ "ON telegram_dm_topic_bindings(profile_name, user_id, chat_id)"
+ )
conn.execute(
"INSERT INTO state_meta (key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -245,7 +266,7 @@ class SessionTelegramTopicsMixin:
if "no such column: profile_name" not in str(exc):
return []
# Same pre-v3 self-heal as _topic_read_one (issue #103363).
- self.apply_telegram_topic_migration()
+ 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",
diff --git a/tests/gateway/test_telegram_topic_read_selfheal_103363.py b/tests/gateway/test_telegram_topic_read_selfheal_103363.py
index 4f593624345..bdc6b448db8 100644
--- a/tests/gateway/test_telegram_topic_read_selfheal_103363.py
+++ b/tests/gateway/test_telegram_topic_read_selfheal_103363.py
@@ -8,8 +8,10 @@ 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
@@ -106,3 +108,83 @@ def test_absent_tables_still_read_empty_and_are_not_created(tmp_path: Path):
assert "telegram_dm_topic_bindings" not in tables
assert "telegram_dm_topic_mode" not in tables
db.close()
+
+
+def test_heal_rebuild_rolls_back_atomically(tmp_path: Path):
+ """The v2→v3 rebuild must stay inside _execute_write's transaction.
+
+ Pre-fix the rebuild ran via executescript, which implicitly commits the
+ open transaction and then autocommits each statement: a failure once the
+ rebuild reaches the DROP strands legacy rows in {table}_new (#42004
+ diagnosed the same shape for the v1→v2 rebuild) and the retry then builds
+ an empty v3 table. The same mid-rebuild failure must now roll back to the
+ intact v2 table so the next read can heal cleanly.
+ """
+ db_path = tmp_path / "v2-upgrade.db"
+ _create_v2_state(db_path)
+ db = SessionDB(db_path=db_path)
+
+ ok = getattr(sqlite3, "SQLITE_OK", 0)
+ deny = getattr(sqlite3, "SQLITE_DENY", 2)
+ drop_table = getattr(sqlite3, "SQLITE_DROP_TABLE", 11)
+
+ def deny_topic_rebuild_drop(action, arg1, arg2, db_name, trigger):
+ if action == drop_table and arg1 and arg1.startswith("telegram_dm_topic"):
+ return deny
+ return ok
+
+ db._conn.set_authorizer(deny_topic_rebuild_drop)
+ try:
+ # The guarded read degrades to "off" instead of raising...
+ assert not db.is_telegram_topic_mode_enabled(
+ chat_id=CHAT, user_id=CHAT, profile_name="default",
+ )
+ finally:
+ db._conn.set_authorizer(None)
+
+ # ...and the interrupted rebuild rolled back completely: the v2 table and
+ # its legacy row are intact, with nothing stranded in *_new.
+ tables = {
+ row[0]
+ for row in db._conn.execute(
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
+ ).fetchall()
+ }
+ assert "telegram_dm_topic_mode" in tables
+ assert not any(t.endswith("_new") for t in tables)
+ mode_row = db._conn.execute(
+ "SELECT enabled FROM telegram_dm_topic_mode WHERE chat_id = ?", (CHAT,)
+ ).fetchone()
+ assert mode_row is not None and mode_row[0] == 1
+
+ # Idempotent under retry (the _execute_write contract): the next clean
+ # read heals and keeps the legacy rows.
+ assert db.is_telegram_topic_mode_enabled(
+ 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()