Skip to content

The agent that grows with you

fix(state): v2→v3 topic rebuild survives orphan bindings and a stranded scratch table

kshitijk4poor83b50f6bea90
diff --git a/hermes_state_telegram.py b/hermes_state_telegram.py
index c73a6d51627..a54775443f0 100644
--- a/hermes_state_telegram.py
+++ b/hermes_state_telegram.py
@@ -100,29 +100,33 @@ 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(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
+ def _topic_read(self, read, empty):
+ """Run ``read()``; 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 read(sql, params)
+ return read()
except sqlite3.OperationalError as exc:
if "no such column: profile_name" not in str(exc):
return empty
try:
self.apply_telegram_topic_migration()
- return read(sql, params)
except sqlite3.Error:
logger.warning("telegram topic tables are pre-v3 and the heal failed; reading as empty", exc_info=True)
return empty
+ return read()
def _topic_read_one(self, sql: str, params):
- return self._topic_read(self._read_one, sql, params, None)
+ return self._topic_read(lambda: self._read_one(sql, params), None)
+
+ def _topic_read_all(self, sql: str, params):
+ return self._topic_read(lambda: self._read_all(sql, params), [])
def apply_telegram_topic_migration(self) -> None:
- """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
+ """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. Also invoked by ``_topic_read`` to heal a
+ pre-v3 table an upgrade left behind (#103363). 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.
@@ -135,17 +139,19 @@ 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. 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.
+ # ON DELETE CASCADE). Legacy rows land in "default" only. execute(), not
+ # executescript(): executescript COMMITs the open BEGIN IMMEDIATE, so a crash after
+ # the DROP strands rows in {table}_new (#42004). A {table}_new left by such a crash
+ # on an older build is dropped first; the legacy table is still intact to re-copy.
+ # v1 bindings had no ON DELETE CASCADE, so pruned sessions left orphan rows that
+ # the v3 FK (foreign_keys=ON on the writer) would reject — copy only live ones.
legacy_columns = columns.replace("profile_name, ", "", 1)
+ live = " WHERE EXISTS (SELECT 1 FROM sessions s WHERE s.id = session_id)" if "session_id" in columns else ""
+ conn.execute(f"DROP TABLE IF EXISTS {table}_new")
conn.execute(f"CREATE TABLE {table}_new ({ddl})")
conn.execute(
f"INSERT INTO {table}_new ({columns}) "
- f"SELECT 'default', {legacy_columns} FROM {table}"
+ f"SELECT 'default', {legacy_columns} FROM {table}{live}"
)
conn.execute(f"DROP TABLE {table}")
conn.execute(f"ALTER TABLE {table}_new RENAME TO {table}")
@@ -246,10 +252,9 @@ 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)
- rows = self._topic_read(
- self._read_all,
+ rows = self._topic_read_all(
"SELECT * FROM telegram_dm_topic_bindings WHERE profile_name = ? AND chat_id = ? ORDER BY updated_at DESC",
- (profile_name, str(chat_id)), [],
+ (profile_name, str(chat_id)),
)
return [dict(row) for row in rows]
diff --git a/tests/hermes_state/test_telegram_topic_selfheal.py b/tests/hermes_state/test_telegram_topic_selfheal.py
index 4a3b3d28c6f..82d7a1f1c52 100644
--- a/tests/hermes_state/test_telegram_topic_selfheal.py
+++ b/tests/hermes_state/test_telegram_topic_selfheal.py
@@ -52,6 +52,11 @@ def _create_v2_state(db_path: Path) -> None:
);
INSERT INTO telegram_dm_topic_bindings
VALUES ('{CHAT}', '99', '{CHAT}', 'k', 'legacy-sess', 'auto', 1.0, 1.0);
+ -- v1 had no ON DELETE CASCADE: a pruned session leaves an orphan binding behind.
+ INSERT INTO telegram_dm_topic_bindings
+ VALUES ('{CHAT}', '7', '{CHAT}', 'k7', 'pruned-sess', 'auto', 1.0, 1.0);
+ -- an older build's executescript rebuild crashed after CREATE: the scratch table is stranded.
+ CREATE TABLE telegram_dm_topic_mode_new (profile_name TEXT, chat_id TEXT);
"""
)
conn.close()
@@ -70,8 +75,10 @@ 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"
+ # The orphan row is dropped (a v2/v3 CASCADE would have removed it) and the stranded scratch table is gone.
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_telegram_topic_binding(chat_id=CHAT, thread_id="7", profile_name="default") is None
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(
@@ -87,15 +94,9 @@ def test_absent_tables_still_read_empty_and_are_not_created(tmp_path: Path):
assert not db.is_telegram_topic_mode_enabled(chat_id=CHAT, user_id=CHAT)
assert db.get_telegram_topic_binding(chat_id=CHAT, thread_id="99") is None
assert db.list_telegram_topic_bindings_for_chat(chat_id=CHAT) == []
- # The deliberate "reads never create the tables" contract is preserved.
- tables = {
- row[0]
- for row in db._conn.execute(
- "SELECT name FROM sqlite_master WHERE type = 'table'"
- ).fetchall()
- }
- assert "telegram_dm_topic_bindings" not in tables
- assert "telegram_dm_topic_mode" not in tables
+ # The deliberate "reads never create the tables" contract is preserved: the migration is the only
+ # creator and always stamps the schema version in the same transaction.
+ assert db.get_meta("telegram_dm_topic_schema_version") is None
db.close()
@@ -113,14 +114,10 @@ def test_heal_rebuild_rolls_back_atomically(tmp_path: Path):
_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
+ if action == sqlite3.SQLITE_DROP_TABLE and arg1 and arg1.startswith("telegram_dm_topic"):
+ return sqlite3.SQLITE_DENY
+ return sqlite3.SQLITE_OK
db._conn.set_authorizer(deny_topic_rebuild_drop)
try:
@@ -131,21 +128,9 @@ def test_heal_rebuild_rolls_back_atomically(tmp_path: Path):
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
-
+ # ...and the interrupted rebuild rolled back completely (a stranded *_new or a dropped original
+ # would make the retry below read as off, and the version stamp rolled back with it).
+ assert db.get_meta("telegram_dm_topic_schema_version") == "2"
# Idempotent under retry (the _execute_write contract): the next clean
# read heals and keeps the legacy rows.
assert db.is_telegram_topic_mode_enabled(