The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: retire native session routes with deletion receipts
Teknium10b155bfc084
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex e2d20e35621..f36757d6096 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -24,7 +24,15 @@ async def mutate_session(authority, actor, ref, params):if 'session:create' not in actor.capabilities:raise RuntimeStoreError('permission_denied')else:- authority.authorize(actor, ref, 'session:control')+ from hermes_state_mutation_retirement import has_mutation_receipt+ if actor.profile_id != authority.profile_id or ref.profile_id != authority.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if 'session:control' not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ # A receipt authorizes only its original principal's exact retry; the+ # transaction still verifies the entire digest and current epoch.+ if not has_mutation_receipt(authority.db, actor.subject, ref.session_id, params['request_id']):+ authority.authorize(actor, ref, 'session:control')authority._require_admission_open()live = authority.sessions.get(ref.session_id)@@ -40,10 +48,9 @@ async def mutate_session(authority, actor, ref, params):if candidate is not None and candidate.task is not None and not candidate.task.done():raise RuntimeStoreError('session_busy')if operation == 'delete':- # Route retirement must commit with deletion, not recreate the same- # physical ID on the next native message. Do not fake that handoff.store = getattr(authority.runner, 'session_store', None)- if store is not None and any(store.lookup_by_session_id(sid) is not None for sid in targets):+ if store is not None and (store._routing_db is None+ or store._routing_db.db_path != authority.db.db_path):raise RuntimeStoreError('runtime_coordination_required')if operation == 'rewind' and not callable(getattr(authority.runner, '_evict_cached_agent', None)):raise RuntimeStoreError('runtime_coordination_required')@@ -55,6 +62,18 @@ async def mutate_session(authority, actor, ref, params):principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),operation=operation, payload=params['payload'], _live_guard=live_guard)+ if operation == 'delete':+ # Repeat local retirement on an exact retry too: publication may have+ # failed after the transaction committed. Never repeat the event.+ store = getattr(authority.runner, 'session_store', None)+ if store is not None:+ store.retire_runtime_sessions(result['deleted_ids'])+ for sid in result['deleted_ids']:+ candidate = authority.sessions.pop(sid, None)+ if candidate is not None:+ evict = getattr(authority.runner, '_evict_cached_agent', None)+ if callable(evict):+ evict(candidate.route)if applied and live is not None:if operation == 'rewind':authority.runner._evict_cached_agent(live.route)diff --git a/gateway/session_persistence.py b/gateway/session_persistence.pyindex f9b8ad3dc1c..0bdf8623aef 100644--- a/gateway/session_persistence.py+++ b/gateway/session_persistence.py@@ -42,6 +42,16 @@ def _is_live_system_guard(exc: BaseException) -> bool:class SessionPersistenceMixin:"""SessionStore storage plumbing: SessionDB handle resolution and routing-index load/save."""+ def retire_runtime_sessions(self, session_ids):+ """Publish committed retirement; durable fences reject delayed saves."""+ with self._lock:+ targets = set(session_ids)+ for key, entry in list(self._entries.items()):+ if entry.session_id in targets:+ del self._entries[key]+ for sid in targets:+ self._session_owner_hints.pop(sid, None)+def _open_session_db_for_active_scope(self, db_path: Optional[Path] = None):"""SessionDB for the active profile scope. ``db_path`` pins the store; otherwise``_default_db_path()`` follows the context-local HERMES_HOME (resolved per call so@@ -296,6 +306,10 @@ class SessionPersistenceMixin:type(entry_data).__name__)continuetry:+ from hermes_state_mutation_retirement import retired_session+ db = self._routing_db+ if db is not None and retired_session(db, entry_data['session_id']):+ continueself._entries[key] = SessionEntry.from_dict(entry_data)imported += 1except (ValueError, KeyError, TypeError) as e:diff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex 27f330badf6..27c4a90e55a 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -258,11 +258,12 @@ class SessionGatewayMixin:returnself._write_sql("""INSERT INTO gateway_routing (scope, session_key, entry_json, updated_at)- VALUES (?, ?, ?, ?)+ SELECT ?, ?, ?, ? WHERE NOT EXISTS (+ SELECT 1 FROM state_meta WHERE key='gateway.retired_session.v1.' || json_extract(?, '$.session_id'))ON CONFLICT(scope, session_key) DO UPDATE SETentry_json = excluded.entry_json,updated_at = excluded.updated_at""",- (scope, session_key, entry_json, time.time()),+ (scope, session_key, entry_json, time.time(), entry_json),)def replace_gateway_routing_entries(self, entries: Dict[str, str], *, scope: str = "") -> None:@@ -274,8 +275,9 @@ class SessionGatewayMixin:if entries:conn.executemany("INSERT INTO gateway_routing (scope, session_key, entry_json, updated_at) "- "VALUES (?, ?, ?, ?)",- [(scope, k, v, now) for k, v in entries.items() if k and v])+ "SELECT ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM state_meta "+ "WHERE key='gateway.retired_session.v1.' || json_extract(?, '$.session_id'))",+ [(scope, k, v, now, v) for k, v in entries.items() if k and v])self._execute_write(_do)def load_gateway_routing_entries(self, *, scope: str = "") -> Dict[str, str]:diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.pynew file mode 100644index 00000000000..b8b0a26466c--- /dev/null+++ b/hermes_state_mutation_retirement.py@@ -0,0 +1,31 @@+"""Durable deletion fences outside prunable transcript rows."""+import json+from hermes_state_runtime import admission_fingerprint, _text++RETIRED_PREFIX = 'gateway.retired_session.v1.'+++def retired_session(db, session_id):+ with db._read_ctx() as conn:+ return conn.execute('SELECT 1 FROM state_meta WHERE key=?',+ (RETIRED_PREFIX + session_id,)).fetchone() is not None+++def has_mutation_receipt(db, principal_id, session_id, request_id):+ for value in (principal_id, session_id, request_id):+ _text(value)+ key = 'gateway.mutation.v1.' + admission_fingerprint(+ canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})+ with db._read_ctx() as conn:+ return conn.execute('SELECT 1 FROM state_meta WHERE key=?', (key,)).fetchone() is not None+++def retire_routes(conn, session_ids):+ for sid in session_ids:+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',+ (RETIRED_PREFIX + sid, '{}'))+ targets = set(session_ids)+ for row in conn.execute('SELECT scope,session_key,entry_json FROM gateway_routing').fetchall():+ if json.loads(row['entry_json']).get('session_id') in targets:+ conn.execute('DELETE FROM gateway_routing WHERE scope=? AND session_key=?',+ (row['scope'], row['session_key']))diff --git a/hermes_state_mutations.py b/hermes_state_mutations.pyindex 758bb072627..4a2b0611d91 100644--- a/hermes_state_mutations.py+++ b/hermes_state_mutations.py@@ -55,6 +55,8 @@ def _delete(db, conn, session_id, payload):if (conn.execute('SELECT 1 FROM session_admissions WHERE target_session_id=? LIMIT 1', (sid,)).fetchone()or conn.execute('SELECT 1 FROM worker_executions WHERE session_id=? LIMIT 1', (sid,)).fetchone()):raise RuntimeStoreError('retained_receipts')+ from hermes_state_mutation_retirement import retire_routes+ retire_routes(conn, targets)for sid in targets:conn.execute('UPDATE sessions SET parent_session_id=NULL, runtime_revision=runtime_revision+1 WHERE parent_session_id=?', (sid,))conn.execute('DELETE FROM messages WHERE session_id=?', (sid,))diff --git a/tests/gateway/test_session_mutation_retirement.py b/tests/gateway/test_session_mutation_retirement.pynew file mode 100644index 00000000000..4199044ef6a--- /dev/null+++ b/tests/gateway/test_session_mutation_retirement.py@@ -0,0 +1,83 @@+"""Native deletion retires routing and keeps only exact authorized retries."""+import asyncio+import json+import sqlite3++import httpx+import pytest+from websockets.asyncio.client import connect+from tests.gateway.test_native_http_auth import daemon, ticket, headers+++async def create(home, descriptor):+ async with connect(descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws',+ subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket(home, descriptor, 'interactive')]) as ws:+ await ws.send(json.dumps({'id': 1, 'method': 'session.create', 'params': {+ 'request_id': 'retirement', 'source': 'gui'}}))+ while True:+ response = json.loads(await ws.recv())+ if response.get('id') == 1:+ assert 'result' in response, response+ return response['result']['session_id']++[email protected]_only+def test_native_delete_exact_retry_survives_owner_restart(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ sid = asyncio.run(create(home, descriptor))+ path = '/api/sessions/' + sid+ snapshot = client.get(path + '/mutation-snapshot', headers=headers(ticket(home, descriptor))).json()+ params = dict(request_id='delete', expected_revision=snapshot['runtime_revision'],+ expected_generation=snapshot['runtime_generation'])+ deleted = client.delete(path, params=params, headers=headers(ticket(home, descriptor)))+ assert deleted.status_code == 200, deleted.text+ receipt = deleted.json()+ assert client.get(path, headers=headers(ticket(home, descriptor))).status_code == 404+ with sqlite3.connect(home / 'state.db') as db:+ assert not any(json.loads(row[0])['session_id'] == sid for row in db.execute('SELECT entry_json FROM gateway_routing'))+ assert client.delete(path, params=params, headers=headers(ticket(home, descriptor))).json() == receipt+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ retry = client.delete(path, params=params, headers=headers(ticket(home, descriptor)))+ assert retry.status_code == 200 and retry.json() == receipt, retry.text+ changed = client.delete(path, params=params | {'expected_revision': 99}, headers=headers(ticket(home, descriptor)))+ assert changed.status_code == 409 and 'admission_conflict' in changed.text+ fresh = client.delete(path, params=params | {'request_id': 'different'}, headers=headers(ticket(home, descriptor)))+ assert fresh.status_code != 200+ foreign = client.delete(path, params=params, headers={'Authorization': 'Bearer normal-http-owner'})+ assert foreign.status_code != 200+ print(json.dumps({'native_delete_restart': receipt, 'changed_retry': changed.json(),+ 'fresh_request_status': fresh.status_code, 'foreign_status': foreign.status_code}))+++def test_route_retirement_rolls_back_with_receipt_and_rejects_stale_mirror(tmp_path):+ from gateway.config import GatewayConfig, Platform+ from gateway.session import SessionStore, SessionSource+ from hermes_state import SessionDB+ import hermes_state_runtime as rt+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ store._db = db+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='owned')+ entry = store.get_or_create_session(source)+ sid = entry.session_id+ if db.get_session(sid) is None:+ db.create_session(sid, source='telegram')+ serialized = json.dumps(entry.to_dict())+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ args = dict(epoch=epoch, principal_id='human', session_id=sid, request_id='delete',+ expected_revision=0, expected_generation=0, operation='delete', payload={})+ db._execute_write(lambda conn: conn.execute("CREATE TRIGGER reject_receipt BEFORE INSERT ON state_meta WHEN NEW.key LIKE 'gateway.mutation.v1.%' BEGIN SELECT RAISE(ABORT,'receipt unavailable'); END"))+ with pytest.raises(sqlite3.IntegrityError, match='receipt unavailable'):+ rt.mutate_runtime_session(db, **args)+ assert db.get_session(sid) is not None+ assert db.load_gateway_routing_entries(scope=store._routing_scope())+ db._execute_write(lambda conn: conn.execute('DROP TRIGGER reject_receipt'))+ rt.mutate_runtime_session(db, **args)+ assert not db.load_gateway_routing_entries(scope=store._routing_scope())+ db.save_gateway_routing_entry(entry.session_key, serialized, scope=store._routing_scope())+ db.replace_gateway_routing_entries({entry.session_key: serialized}, scope=store._routing_scope())+ assert not db.load_gateway_routing_entries(scope=store._routing_scope())+ # The pre-commit mirror remains on disk as in a crash before publication.+ restored = SessionStore(store.sessions_dir, GatewayConfig())+ restored._db = db+ assert restored.lookup_by_session_id(sid) is None