The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): gate delivery_obligations.adapter_profile on column presence
teknium148381196a549
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex ca1b1776617..d437bdc7e0d 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -128,22 +128,25 @@ _ORPHAN_CONTIGUITY_DONORS_SQL = f"""ORDER BY last_active DESCLIMIT 2"""-_TOPIC_TABLE_NAMES = ("telegram_dm_topic_mode", "telegram_dm_topic_bindings")+_OPTIONAL_TABLE_NAMES = (+ "telegram_dm_topic_mode", "telegram_dm_topic_bindings", "delivery_obligations")-def _topic_table_columns(conn) -> Dict[str, Set[str]]:- """Live column sets of the Telegram topic tables that exist (``{}`` when none do).+def _optional_table_columns(conn) -> Dict[str, Set[str]]:+ """Live column sets of the lazily-created tables that exist (``{}`` when none do).``apply_telegram_topic_migration`` runs only on explicit ``/topic`` opt-in, so a store- can hold supported v1/v2 tables without ``profile_name`` for its whole life. Identity- settlement must gate its ``profile_name`` SQL on the column actually being there rather- than on table existence, and must not force that migration (#113757).+ can hold supported v1/v2 tables without ``profile_name`` for its whole life; likewise the+ delivery ledger adds ``delivery_obligations.adapter_profile`` only when a gateway opens+ it. Identity settlement must gate its column SQL on the column actually being there+ rather than on table existence, and must not force those migrations (#113757)."""existing = {row[0] for row in conn.execute(- "SELECT name FROM sqlite_master WHERE type='table' AND name IN (?, ?)", _TOPIC_TABLE_NAMES)}+ "SELECT name FROM sqlite_master WHERE type='table' AND name IN (?, ?, ?)",+ _OPTIONAL_TABLE_NAMES)}return {table: {row[1] for row in conn.execute(f"PRAGMA table_info('{table}')")}- for table in _TOPIC_TABLE_NAMES if table in existing+ for table in _OPTIONAL_TABLE_NAMES if table in existing}@@ -577,7 +580,7 @@ class SessionGatewayMixin:def _do(conn):existing = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()}- topic_columns = _topic_table_columns(conn)+ topic_columns = _optional_table_columns(conn)collision = conn.execute("SELECT old.scope, ? || substr(old.session_key, ?) ""FROM gateway_routing AS old JOIN gateway_routing AS target "@@ -628,9 +631,10 @@ class SessionGatewayMixin:counts["sessions_origin_json"] = origin_countif "delivery_obligations" in existing:- counts["delivery_obligations_adapter_profile"] = conn.execute(- "UPDATE delivery_obligations SET adapter_profile = ? WHERE adapter_profile = ?",- (new, old)).rowcount+ if "adapter_profile" in topic_columns.get("delivery_obligations", set()):+ counts["delivery_obligations_adapter_profile"] = conn.execute(+ "UPDATE delivery_obligations SET adapter_profile = ? WHERE adapter_profile = ?",+ (new, old)).rowcountcounts["delivery_obligations_session_key"] = conn.execute("UPDATE delivery_obligations SET session_key = ? || substr(session_key, ?) ""WHERE substr(session_key, 1, ?) = ?",@@ -706,7 +710,7 @@ class SessionGatewayMixin:def _do(conn):existing = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()}- topic_columns = _topic_table_columns(conn)+ topic_columns = _optional_table_columns(conn)if "gateway_routing" in existing:counts["gateway_routing"] = conn.execute("DELETE FROM gateway_routing WHERE substr(session_key, 1, ?) = ?",@@ -718,11 +722,15 @@ class SessionGatewayMixin:# Terminalize, never hard-delete: a pending obligation is delivery state someone may# still care about, and the ledger's own retention prunes abandoned rows. Only# non-terminal rows are touched — delivered history is left exactly as it was.+ # A ledger created before ``adapter_profile`` existed matches on namespace alone.+ by_profile = ("adapter_profile = ? OR "+ if "adapter_profile" in topic_columns.get("delivery_obligations", set())+ else "")+ params = (time.time(), name, ns_len, ns) if by_profile else (time.time(), ns_len, ns)counts["delivery_obligations"] = conn.execute("UPDATE delivery_obligations SET state='abandoned', updated_at=? "- "WHERE (adapter_profile = ? OR substr(session_key, 1, ?) = ?) "- "AND state NOT IN ('delivered', 'abandoned')",- (time.time(), name, ns_len, ns)).rowcount+ f"WHERE ({by_profile}substr(session_key, 1, ?) = ?) "+ "AND state NOT IN ('delivered', 'abandoned')", params).rowcountif "profile_name" in topic_columns.get("telegram_dm_topic_mode", set()):counts["telegram_dm_topic_mode"] = conn.execute("DELETE FROM telegram_dm_topic_mode WHERE profile_name = ?", (name,)).rowcountdiff --git a/tests/hermes_state/test_purge_profile_state.py b/tests/hermes_state/test_purge_profile_state.pyindex b150d569c3a..9e1f3e30268 100644--- a/tests/hermes_state/test_purge_profile_state.py+++ b/tests/hermes_state/test_purge_profile_state.py@@ -44,6 +44,24 @@ def _create_legacy_v2_topic_tables(db):""")+def _create_legacy_ledger_without_adapter_profile(db):+ """The delivery_obligations shape before ``adapter_profile`` was added (ledger never reopened)."""+ db._write_sql("""+ CREATE TABLE delivery_obligations (+ obligation_id TEXT PRIMARY KEY, session_key TEXT NOT NULL,+ platform TEXT NOT NULL, chat_id TEXT NOT NULL, thread_id TEXT, content TEXT NOT NULL,+ state TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,+ created_at REAL NOT NULL, updated_at REAL NOT NULL,+ owner_pid INTEGER, owner_started_at INTEGER, last_error TEXT+ )+ """)+ for oid, key in (("ob_gone", "agent:gone:feishu:dm:chatA"), ("ob_keep", "agent:keepme:feishu:dm:chatB")):+ db._write_sql(+ "INSERT INTO delivery_obligations (obligation_id, session_key, platform, chat_id, "+ "content, state, created_at, updated_at) VALUES (?, ?, 'feishu', 'c', 'hi', 'pending', 1, 1)",+ (oid, key))++def _write_obligation(db, monkeypatch, obligation_id, session_key, chat_id, profile,state="pending"):"""delivery_obligations is created lazily by the delivery ledger against the same state.db."""@@ -203,3 +221,14 @@ class TestPurgeProfileState:assert db._read_one("SELECT session_key FROM telegram_dm_topic_bindings WHERE chat_id = ?", ("chatB",))["session_key"] == "agent:keepme:telegram:dm:chatB"++ def test_purges_legacy_ledger_without_adapter_profile_by_session_key(self, db):+ """A ledger created before adapter_profile existed is settled on its namespace alone."""+ _create_legacy_ledger_without_adapter_profile(db)++ counts = db.purge_profile_state("gone")++ assert counts["delivery_obligations"] == 1+ states = {row["obligation_id"]: row["state"] for row in db._read_all(+ "SELECT obligation_id, state FROM delivery_obligations")}+ assert states == {"ob_gone": "abandoned", "ob_keep": "pending"}diff --git a/tests/hermes_state/test_rekey_profile_state.py b/tests/hermes_state/test_rekey_profile_state.pyindex 3a7e856b597..7b4ac3feb5b 100644--- a/tests/hermes_state/test_rekey_profile_state.py+++ b/tests/hermes_state/test_rekey_profile_state.py@@ -44,6 +44,24 @@ def _create_legacy_v2_topic_tables(db):""")+def _create_legacy_ledger_without_adapter_profile(db):+ """The delivery_obligations shape before ``adapter_profile`` was added (ledger never reopened)."""+ db._write_sql("""+ CREATE TABLE delivery_obligations (+ obligation_id TEXT PRIMARY KEY, session_key TEXT NOT NULL,+ platform TEXT NOT NULL, chat_id TEXT NOT NULL, thread_id TEXT, content TEXT NOT NULL,+ state TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,+ created_at REAL NOT NULL, updated_at REAL NOT NULL,+ owner_pid INTEGER, owner_started_at INTEGER, last_error TEXT+ )+ """)+ for oid, key in (("ob_gone", "agent:gone:feishu:dm:chatA"), ("ob_keep", "agent:keepme:feishu:dm:chatB")):+ db._write_sql(+ "INSERT INTO delivery_obligations (obligation_id, session_key, platform, chat_id, "+ "content, state, created_at, updated_at) VALUES (?, ?, 'feishu', 'c', 'hi', 'pending', 1, 1)",+ (oid, key))++class TestRekeyProfileState:def test_rekeys_session_key_namespace_and_profile_columns(self, db):# A session owned by the old profile, keyed in its namespace.@@ -194,3 +212,16 @@ class TestRekeyProfileState:assert db._read_one("SELECT session_key FROM telegram_dm_topic_bindings WHERE chat_id = ?", ("chatB",))["session_key"] == "agent:keepme:telegram:dm:chatB"++ def test_rekeys_legacy_ledger_without_adapter_profile_by_session_key(self, db):+ """A ledger created before adapter_profile existed is rekeyed on its namespace alone."""+ _create_legacy_ledger_without_adapter_profile(db)++ counts = db.rekey_profile_state("gone", "newname")++ assert "delivery_obligations_adapter_profile" not in counts+ assert counts["delivery_obligations_session_key"] == 1+ keys = {row["obligation_id"]: row["session_key"] for row in db._read_all(+ "SELECT obligation_id, session_key FROM delivery_obligations")}+ assert keys == {"ob_gone": "agent:newname:feishu:dm:chatA",+ "ob_keep": "agent:keepme:feishu:dm:chatB"}