The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): deleting a session also removes its launch policy and API binding receipts
Teknium1a8f3bdf69d7
diff --git a/gateway/session_api.py b/gateway/session_api.pyindex fd00284ddad..e66ac32f28b 100644--- a/gateway/session_api.py+++ b/gateway/session_api.py@@ -7,8 +7,7 @@ from gateway.session import SessionEntry, SessionSource, _is_path_unsafefrom gateway.session_contract import SessionReffrom hermes_state_runtime import RuntimeStoreError, _epoch, _json-_BINDING_PREFIX = 'gateway.api.binding.v1.'-_DECLARED_PREFIX = 'gateway.api.conversation.v1.'+from hermes_state_local import API_BINDING_PREFIX as _BINDING_PREFIX, API_DECLARED_PREFIX as _DECLARED_PREFIXdef declared_api_session(db, key):@@ -76,6 +75,9 @@ def bind_api_session(authority, session_id, *, hosted_dispatch=None, declared_kedef write(conn):_epoch(conn, authority.epoch)+ from hermes_state_mutation_retirement import RETIRED_PREFIX+ if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (RETIRED_PREFIX + session_id,)).fetchone():+ raise RuntimeStoreError('not_found')saved = conn.execute('SELECT value FROM state_meta WHERE key=?',(_BINDING_PREFIX + session_id,)).fetchone()if saved is not None:diff --git a/hermes_state_local.py b/hermes_state_local.pyindex 1884db545e4..6430011ebb1 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -5,6 +5,8 @@ import timefrom hermes_state_runtime import RuntimeStoreError, _epoch, _jsonPOLICY_PREFIX = 'gateway.local_policy.v1:'+API_BINDING_PREFIX = 'gateway.api.binding.v1.'+API_DECLARED_PREFIX = 'gateway.api.conversation.v1.'def commit_local_session(db, *, epoch, receipt):@@ -27,6 +29,11 @@ def commit_local_session(db, *, epoch, receipt):if not same:raise RuntimeStoreError('invalid_params')return saved+ from hermes_state_mutation_retirement import RETIRED_PREFIX+ if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (RETIRED_PREFIX + sid,)).fetchone():+ # Deleted: its receipt was retired with the transcript; a create/cron retry must not+ # resurrect the row (and re-fire its prompt) under the same deterministic id.+ raise RuntimeStoreError('not_found')if ('legacy_session_id' not in receipt andconn.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone()):raise RuntimeStoreError('storage_unavailable')@@ -50,6 +57,25 @@ def commit_local_session(db, *, epoch, receipt):return db._execute_write(write)+def retire_local_receipts(conn, session_ids):+ """Deletion fence half for owner receipts. A local creation policy carries the launch request+ (``request_json``: a cron fire's job and raw prompt), so it goes exactly when its route does:+ when the receipt's current physical target is deleted (a pruned reset ancestor whose logical+ session lives on in a child keeps it). An API binding and the declared conversation key that+ resolves to it go with their id, so that key starts a fresh session."""+ targets = set(session_ids)+ if not targets:+ return+ # Prefix scans (GLOB uses the key index), not one LIKE per id: a prune retires thousands.+ gone = [key for key, value in conn.execute('SELECT key,value FROM state_meta WHERE key GLOB ?',+ (POLICY_PREFIX + '*',))+ if json.loads(value).get('entry', {}).get('session_id') in targets]+ gone += [key for key, value in conn.execute('SELECT key,value FROM state_meta WHERE key GLOB ?',+ (API_DECLARED_PREFIX + '*',)) if value in targets]+ gone += [API_BINDING_PREFIX + sid for sid in targets]+ conn.executemany('DELETE FROM state_meta WHERE key=?', [(key,) for key in gone])++def local_receipt(db, session_id):with db._read_ctx() as conn:row = conn.execute('SELECT value FROM state_meta WHERE key=?', (POLICY_PREFIX + session_id,)).fetchone()diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.pyindex eaecebcc5f2..b811de21477 100644--- a/hermes_state_mutation_retirement.py+++ b/hermes_state_mutation_retirement.py@@ -87,6 +87,8 @@ def retire_sessions(conn, session_ids):``delete_session*``, prunes and sweeps) must publish the whole fence, so it lives here once."""retire_terminal_receipts(conn, session_ids)retire_routes(conn, session_ids)+ from hermes_state_local import retire_local_receipts+ retire_local_receipts(conn, session_ids)def retire_prunable(conn, session_ids):diff --git a/tests/gateway/test_local_session_recovery.py b/tests/gateway/test_local_session_recovery.pyindex de170ec81a3..0ecd3a393de 100644--- a/tests/gateway/test_local_session_recovery.py+++ b/tests/gateway/test_local_session_recovery.py@@ -134,3 +134,41 @@ async def test_branch_and_local_entries_keep_the_routing_prune_sweep_running(tmpcold._entries[telegram.session_key].updated_at -= timedelta(days=90)assert cold.prune_old_entries(30) == 1assert cold.lookup_by_session_key(telegram.session_key) is None+++async def test_delete_retires_owner_receipts_and_never_resurrects_the_id(tmp_path, monkeypatch):+ """The deletion fence takes the local policy receipt (a cron policy's ``request_json`` holds+ the job and raw prompt) and the API binding + declared conversation key with the transcript;+ a later create/cron/API retry of the same deterministic id is refused instead of recreating it."""+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_api import bind_api_session+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from gateway.session_mutations import mutate_session+ from gateway import run+ from hermes_state_runtime import RuntimeStoreError++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False)+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='first')+ actor = Principal('owner', 'fixture', frozenset({'session:create', 'session:read', 'session:control'}), 'socket')+ params = {'request_id': 'r', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []}+ local = create_local_session(authority, actor, params)+ api = bind_api_session(authority, 'api-owner', declared_key='conversation')+ for ref in (local, api):+ await mutate_session(authority, actor, ref, dict(session_id=ref.session_id, request_id='delete',+ expected_revision=0, expected_generation=0, operation='delete', payload={}))+ with authority.db._read_ctx() as conn:+ left = [k for (k,) in conn.execute("SELECT key FROM state_meta WHERE key LIKE 'gateway.local_policy.v1:%' "+ "OR key LIKE 'gateway.api.%'")]+ assert left == []+ with pytest.raises(RuntimeStoreError, match='not_found'):+ create_local_session(authority, actor, params)+ with pytest.raises(RuntimeStoreError, match='not_found'):+ bind_api_session(authority, 'api-owner')+ assert authority.db.get_session(local.session_id) is None+ assert authority.db.get_session('api-owner') is None