Skip to content

The agent that grows with you

fix(gateway): fence a secondary delete's routes in the shared routing store

Tekniume6afb6573836
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index c1bcd600ca0..420b2ec1be3 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -311,25 +311,31 @@ def _project_committed(authority, ref, operation, result):
if operation == 'delete':
# Repeat local retirement on an exact retry too: publication may have
# failed after the transaction committed. Never repeat the event.
- retire_live_sessions(authority, result['deleted_ids'])
+ retire_live_sessions(authority, result['deleted_ids'], require_fence=True)
-def retire_live_sessions(authority, session_ids):
+def retire_live_sessions(authority, session_ids, *, require_fence=False):
"""Drop committed deletions from this owner's memory: routes, launch secrets, live sessions
- and their cached agents. Shared by canonical delete and the owner-run bulk prune."""
+ and their cached agents. Shared by canonical delete and the owner-run bulk prune.
+ ``require_fence``: refuse ``storage_unavailable`` when the shared routing fence could not be
+ written (canonical delete, whose exact retry replays the receipt and repeats this call)."""
store = getattr(authority.runner, 'session_store', None)
+ fence_error = None
if store is not None:
store.retire_runtime_sessions(session_ids)
- # The delete transaction dropped routing rows in the owning store; a multiplexed
- # secondary's routes live in the launch home's shared index, so drop them there too
- # rather than wait for the next whole-index save (a crash in between left a route to
- # a deleted session, #138826).
+ # The delete transaction fenced and dropped routes in the owning store; a multiplexed
+ # secondary's routes live in the launch home's shared index, so the store fences them
+ # there too (markers + drop in one transaction). Without the marker in THAT database a
+ # whole-index snapshot taken before this delete and saved after it restored the route
+ # (#138826). A failure surfaces after the rest of the cleanup: an exact retry replays the
+ # committed receipt and repeats this fence.
routing = getattr(store, '_routing_db', None)
if session_ids and routing is not None and routing.db_path != authority.db.db_path:
try:
- routing._delete_routing_entries_for_sessions(set(session_ids))
- except Exception:
- logger.warning('could not drop shared routing rows for deleted sessions', exc_info=True)
+ store.fence_retired_routes(session_ids)
+ except Exception as exc:
+ logger.warning('could not fence shared routing rows for deleted sessions', exc_info=True)
+ fence_error = exc
from gateway.session_policy import release_launch_secrets
release_launch_secrets(authority, session_ids)
from tools.async_delegation import allow_for_session
@@ -345,3 +351,5 @@ def retire_live_sessions(authority, session_ids):
release_editor_mcp(authority, session_ids)
from gateway.session_worker_construct import release_session_prefill
release_session_prefill(authority, session_ids)
+ if fence_error is not None and require_fence:
+ raise RuntimeStoreError('storage_unavailable') from fence_error
diff --git a/gateway/session_persistence.py b/gateway/session_persistence.py
index 05553d46b0e..b47ba6a9f9a 100644
--- a/gateway/session_persistence.py
+++ b/gateway/session_persistence.py
@@ -50,6 +50,16 @@ class SessionPersistenceMixin:
for sid in targets:
self._session_owner_hints.pop(sid, None)
+ def fence_retired_routes(self, session_ids) -> None:
+ """Durably retire *session_ids* in the routing index's own database (markers + route
+ drop in one transaction). A delete committed in another profile's store fences only that
+ store; the shared index lives in the launch home, so its saves need the fence here too.
+ Raises when the routing store cannot take the fence: the delete must not report success."""
+ retire = self._routing_db_method("retire_gateway_routes")
+ if retire is None:
+ raise RuntimeError("routing store unavailable for deletion fence")
+ retire(session_ids)
+
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
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index 0cd57878349..ebad0035f33 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -403,6 +403,27 @@ class SessionGatewayMixin:
self._write_sql("DELETE FROM gateway_routing WHERE scope = ? AND session_key = ?", doomed, many=True)
return len(doomed)
+ def retire_gateway_routes(self, session_ids) -> None:
+ """Publish deletion fences for *session_ids* in THIS (routing) database and drop the
+ routes naming them, in one transaction. Routing saves skip any entry whose session id
+ carries a marker here, so a whole-index snapshot taken before a delete in another
+ profile's store cannot restore the route when it is saved after it."""
+ ids = sorted({str(sid) for sid in session_ids if sid})
+ if not ids:
+ return
+
+ def _do(conn):
+ from hermes_state_mutation_retirement import RETIRED_PREFIX, entry_session_id
+ retired = json.dumps({"retired_at": time.time()})
+ conn.executemany("INSERT OR REPLACE INTO state_meta(key,value) VALUES(?,?)",
+ [(RETIRED_PREFIX + sid, retired) for sid in ids])
+ targets = set(ids)
+ doomed = [(row[0], row[1]) for row in conn.execute(
+ "SELECT scope, session_key, entry_json FROM gateway_routing").fetchall()
+ if entry_session_id(row[2]) in targets]
+ conn.executemany("DELETE FROM gateway_routing WHERE scope = ? AND session_key = ?", doomed)
+ self._execute_write(_do)
+
def prune_never_active_keyed_sessions(
self, *, older_than_days: float, sessions_dir: Optional[Path] = None,
deleted_ids: Optional[list] = None) -> tuple[int, int, int]:
diff --git a/tests/gateway/test_delete_secondary_profile_multiplex.py b/tests/gateway/test_delete_secondary_profile_multiplex.py
index bb6221ccccb..b4f36924119 100644
--- a/tests/gateway/test_delete_secondary_profile_multiplex.py
+++ b/tests/gateway/test_delete_secondary_profile_multiplex.py
@@ -63,6 +63,55 @@ async def test_delete_of_secondary_profile_session_does_not_409(tmp_path, monkey
process_ownership.release(home)
+async def test_a_stale_routing_save_cannot_restore_a_deleted_secondary_route(tmp_path, monkeypatch):
+ """A whole-index snapshot taken before a secondary profile's delete, saved after it, must not
+ put the deleted session's route back in the launch home's shared index: the deletion fence
+ has to live in the routing database, not only in the secondary's own store."""
+ from gateway import run
+ from gateway.run import _profile_runtime_scope
+ from gateway.run_runtime import initialize_gateway_runtime
+ from gateway.runtime_ownership import process_ownership
+ from gateway.session import SessionEntry
+ from gateway.session_contract import Principal
+ from gateway.session_local import create_local_session
+ from gateway.session_mutations import mutate_session
+
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ root, homes = _reserve_homes(tmp_path, monkeypatch, names=('alpha',))
+ process_ownership.reserve([home for _, home in homes])
+ runner = None
+ try:
+ runner = _runner(root, homes)
+ await initialize_gateway_runtime(runner)
+ _name, home = homes[1]
+ authority = runner.session_authorities.for_home(home)
+ actor = Principal('owner', authority.profile_id,
+ frozenset({'session:create', 'session:read', 'session:control'}), 'socket')
+ store = runner.session_store
+ key = 'agent:main:telegram:222'
+ with _profile_runtime_scope(home, {}):
+ ref = create_local_session(authority, actor, {'request_id': 'r', 'source': 'gui',
+ 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})
+ now = datetime.now(UTC)
+ store._entries[key] = SessionEntry(session_key=key, session_id=ref.session_id,
+ created_at=now, updated_at=now)
+ with store._lock:
+ stale = store._snapshot_routing_locked() # a worker's snapshot, saved late
+ await mutate_session(authority, actor, ref, dict(
+ session_id=ref.session_id, request_id='delete', expected_revision=0,
+ expected_generation=0, operation='delete', payload={}))
+ store._persist_routing_data(*stale)
+ routing_db = store._routing_db
+ assert key not in routing_db.load_gateway_routing_entries(scope=store._routing_scope())
+ assert authority.db.get_session(ref.session_id) is None
+ finally:
+ for a in list(getattr(runner, 'session_authorities', None) or []):
+ a.db.close()
+ for _, home in homes:
+ process_ownership.release(home)
+
+
def test_runtime_owns_authority_requires_runner_membership():
from gateway.session_mutations import _runtime_owns_authority
launch, secondary = SimpleNamespace(runner=None), SimpleNamespace(runner=None)
@@ -81,3 +130,27 @@ def test_runtime_owns_authority_requires_runner_membership():
legacy.runner = legacy_runner
assert _runtime_owns_authority(legacy)
assert not _runtime_owns_authority(SimpleNamespace(runner=legacy_runner))
+
+
+def test_a_failed_shared_fence_fails_the_canonical_delete_not_the_prune(monkeypatch):
+ """The shared-index fence must be durable before a delete reports success: a canonical
+ delete refuses ``storage_unavailable`` (its exact retry repeats the fence); a bulk prune,
+ which has no retry receipt, keeps its committed result and only logs."""
+ from gateway.session_mutations import retire_live_sessions
+ from hermes_state_runtime import RuntimeStoreError
+
+ for target in ('gateway.session_policy.release_launch_secrets',
+ 'gateway.session_local_mcp.release_editor_mcp',
+ 'gateway.session_worker_construct.release_session_prefill'):
+ monkeypatch.setattr(target, lambda *a, **k: None)
+
+ def broken(ids):
+ raise OSError('disk gone')
+ store = SimpleNamespace(retire_runtime_sessions=lambda ids: None, fence_retired_routes=broken,
+ _routing_db=SimpleNamespace(db_path='/launch/state.db'))
+ authority = SimpleNamespace(runner=SimpleNamespace(session_store=store), profile_id='p',
+ db=SimpleNamespace(db_path='/secondary/state.db'), sessions={})
+ with pytest.raises(RuntimeStoreError) as raised:
+ retire_live_sessions(authority, ['gone'], require_fence=True)
+ assert raised.value.reason == 'storage_unavailable'
+ retire_live_sessions(authority, ['gone'])