The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): strip a retired route from sessions.json when it is retired
unsupportedpastelsa4e5a656ddc0
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex c819e41fe9b..0ab17714d57 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -344,6 +344,15 @@ def retire_live_sessions(authority, session_ids, *, require_fence=False):except Exception as exc:logger.warning('could not fence shared routing rows for deleted sessions', exc_info=True)fence_error = exc+ # The dropped routes stay in sessions.json until the next full save, which an idle gateway+ # may not make before a prune's fence ages out; the next start would then import them back.+ # Strip them now, after the fences, whatever write_sessions_json says.+ strip = getattr(store, 'strip_retired_mirror_routes', None)+ if session_ids and callable(strip):+ try:+ strip(session_ids)+ except Exception:+ logger.warning('could not strip retired routes from sessions.json', exc_info=True)from gateway.session_policy import release_launch_secretsrelease_launch_secrets(authority, session_ids)from tools.async_delegation import allow_for_sessiondiff --git a/gateway/session_persistence.py b/gateway/session_persistence.pyindex 6f1d7313d3a..feda98b8378 100644--- a/gateway/session_persistence.py+++ b/gateway/session_persistence.py@@ -61,6 +61,32 @@ class SessionPersistenceMixin:raise RuntimeError("routing store unavailable for deletion fence")retire(session_ids, namespace=namespace, expiring=expiring)+ def strip_retired_mirror_routes(self, session_ids=None) -> None:+ """Drop from an existing sessions.json every route a routing save now skips as retired+ (``route_retired``, the check ``replace_gateway_routing_entries`` applies), only those naming+ *session_ids* when given. Runs whatever ``write_sessions_json`` says and never creates the+ file: the mirror is derived, and a retired route left in it would come back through the+ next start's legacy import once a prune's fence ages out."""+ db = self._routing_db+ sessions_file = self.sessions_dir / "sessions.json"+ if db is None or not sessions_file.exists():+ return+ from hermes_state_mutation_retirement import route_retired+ targets = None if session_ids is None else set(session_ids)+ with self._lazy("_save_lock", threading.Lock): # never interleaves with a full save's write+ with open(sessions_file, "r", encoding="utf-8-sig") as f:+ data = json.load(f)+ if not isinstance(data, dict):+ return+ kept = {}+ for key, entry in data.items():+ sid = entry.get("session_id") if isinstance(entry, dict) else None+ if (key.startswith("_") or not isinstance(sid, str) or (targets is not None and sid not in targets)+ or not route_retired(db, key, json.dumps({"session_id": sid}))):+ kept[key] = entry+ if len(kept) < len(data):+ atomic_json_write(sessions_file, kept, mode=0o600)+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@@ -337,6 +363,13 @@ class SessionPersistenceMixin:# Rewrite the mirror while the fences that kept those routes out still hold: a prune's# ages out, and the import would then restore the retired route.self._save()+ if not getattr(self, "_write_sessions_json", True):+ # That save left an existing mirror as it was: strip the routes from it directly,+ # or every later start imports them again.+ try:+ self.strip_retired_mirror_routes()+ except Exception:+ logger.warning("gateway.session: could not strip retired routes from sessions.json", exc_info=True)# A hard crash skips graceful shutdown and leaves sessions.json pointing at ended sessions.self._prune_stale_sessions_locked()diff --git a/tests/gateway/test_secondary_route_fence_scope.py b/tests/gateway/test_secondary_route_fence_scope.pyindex 29f8b076455..a9b1ec00fc1 100644--- a/tests/gateway/test_secondary_route_fence_scope.py+++ b/tests/gateway/test_secondary_route_fence_scope.py@@ -340,13 +340,17 @@ async def test_a_secondary_delete_fence_outlives_the_horizon_while_a_prune_fence@pytest.mark.asyncio-async def test_a_start_within_the_horizon_strips_a_pruned_route_from_an_older_mirror(tmp_path, monkeypatch):[email protected]('mirror', [True, False], ids=['default', 'write_sessions_json-false'])+async def test_a_start_within_the_horizon_strips_a_pruned_route_from_an_older_mirror(tmp_path, monkeypatch, mirror):"""A sessions.json an earlier release wrote unfiltered (or one left by a crash before the next- save) still names the pruned route. The first start while the fence holds skips it and rewrites- the mirror, so the route cannot come back once the fence ages out."""+ save) still names the pruned route. The first start while the fence holds skips it and strips+ it from the mirror, so the route cannot come back once the fence ages out. With+ ``gateway.write_sessions_json: false`` that start's save writes state.db only, and an existing+ mirror is still stripped."""async with _served(tmp_path, monkeypatch) as served:store = served.storekey, _sid, stale = await _pruned_alpha_route(served, tmp_path)+ store._write_sessions_json = mirrorstore._save_sessions_json(stale[0])_restart(store)assert key not in store._entries@@ -356,6 +360,60 @@ async def test_a_start_within_the_horizon_strips_a_pruned_route_from_an_older_miassert key not in store._entries, 'a pruned route came back on startup after its fence aged out'+def _routed_entry(key, sid, chat):+ """A routing entry with the origin native recovery binds a session's route by."""+ from gateway.config import Platform+ from gateway.session import SessionSource+ entry = _entry(key, sid)+ entry.origin = SessionSource(platform=Platform.TELEGRAM, chat_id=chat, chat_type='dm', user_id='u' + chat)+ return entry++[email protected]('mirror', [True, False], ids=['default', 'write_sessions_json-false'])+async def test_a_pruned_route_stays_out_of_the_mirror_and_a_reused_id_keeps_one_route(tmp_path, monkeypatch, mirror):+ """Alpha's routed session is pruned through the owner path. Per-turn saves never touch+ sessions.json, so with no full save before the prune's fence aged out (an idle week), or with+ ``gateway.write_sessions_json: false`` and the mirror a full save left earlier, the next start+ imported the route back. When the launch profile then reused the id, two routes named it and+ native recovery refused both with ``admission_conflict``, leaving a queued turn queued."""+ from gateway.run import _profile_runtime_scope+ from gateway.session_local import create_local_session+ async with _served(tmp_path, monkeypatch) as served:+ store, key, launch_key = served.store, 'agent:alpha:telegram:333', 'agent:main:telegram:444'+ with _profile_runtime_scope(served.home, {}):+ ref = create_local_session(served.alpha, served.actor, {+ 'request_id': 'r', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})+ sid = ref.session_id+ store._entries[key] = _routed_entry(key, sid, '333')+ with store._lock:+ store._save() # a full save while mirror writes are on+ assert key in _mirror(store)+ store._write_sessions_json = mirror+ await _prune(served, ref)+ if not mirror:+ _restart(store)+ assert key not in store._entries, 'a start inside the horizon restored the pruned route'+ _age_retirements(served.alpha.db, served.launch.db) # a quiet week: no full save, no restart+ _restart(store)+ assert key not in store._entries, 'the first start past the horizon restored the pruned route'+ assert key not in _mirror(store)++ status, text = await _create(served, sid) # the launch profile reuses the id+ assert status == 201, text+ store._entries[launch_key] = _routed_entry(launch_key, sid, '444')+ with store._lock:+ store._save()+ _restart(store)+ routes = sorted(k for k, v in _durable(store).items() if json.loads(v).get('session_id') == sid)+ assert routes == [launch_key], routes+ bindings = [(sid, entry.origin, None) for entry in store.list_sessions()+ if entry.session_id == sid and entry.origin is not None]+ assert len(bindings) == 1, bindings+ verdict = await served.launch.recover_native_sessions(bindings)+ assert 'admission_conflict' not in str(verdict), verdict++@pytest.mark.asyncioasync def test_deleting_the_launch_session_keeps_an_earlier_releases_shared_fence_on_every_route(tmp_path, monkeypatch):"""Before the upgrade, alpha deleted its ``user-42`` while the launch profile had a live