The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): make active turn markers failure-atomic
Dominic Bejar5ff328cc76ec
diff --git a/gateway/session.py b/gateway/session.pyindex 1412e68e84d..933a748f121 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -1567,7 +1567,18 @@ class SessionStore:"gateway.session: state.db routing save failed: %s", exc)if getattr(self, "_write_sessions_json", True) or not db_saved:- self._save_sessions_json(data)+ try:+ self._save_sessions_json(data)+ except Exception as exc:+ if not db_saved:+ raise+ # state.db is authoritative. A failed legacy mirror must not+ # report the already-committed primary write as failed.+ logger.warning(+ "gateway.session: sessions.json mirror save failed "+ "after state.db commit: %s",+ exc,+ )self._persisted_routing_generation = generation# This rewrite supersedes fast records at or below its# generation; newer ones stay for the next delayed full writer.@@ -1624,7 +1635,13 @@ class SessionStore:data, generation = self._snapshot_routing_locked()self._persist_routing_data(data, generation)- def _save_entry(self, session_key: str) -> None:+ def _save_entry(+ self,+ session_key: str,+ *,+ entry_data: Optional[Dict[str, Any]] = None,+ lock_held: bool = False,+ ) -> None:"""Persist ONE routing entry via UPSERT — the per-turn fast path.The steady-state turn only bumps ``updated_at`` /@@ -1665,13 +1682,38 @@ class SessionStore:- No DB, or a failed upsert, falls back to the full rewrite soDB-less installs keep sessions.json — their primary store —durable every turn.++ ``entry_data`` lets a failure-atomic metadata transition persist a+ candidate before publishing it to the live entry. Its full-save+ fallback carries the same candidate instead of re-snapshotting the+ unchanged live value."""- with self._lock:+ def _capture() -> Optional[tuple[str, int, Optional[Dict[str, Any]]]]:entry = self._entries.get(session_key)if entry is None:- return- entry_json = json.dumps(entry.to_dict())+ return None+ serialized_entry = (+ dict(entry_data) if entry_data is not None else entry.to_dict()+ )+ entry_json = json.dumps(serialized_entry)revision = self._next_routing_generation_locked()+ fallback_data: Optional[Dict[str, Any]] = None+ if entry_data is not None:+ fallback_data = {+ key: current.to_dict()+ for key, current in self._entries.items()+ }+ fallback_data[session_key] = serialized_entry+ return entry_json, revision, fallback_data++ if lock_held:+ captured = _capture()+ else:+ with self._lock:+ captured = _capture()+ if captured is None:+ return+ entry_json, revision, fallback_data = captured_db = getattr(self, "_db", None)saver = getattr(_db, "save_gateway_routing_entry", None) if _db else Noneif callable(saver):@@ -1699,7 +1741,10 @@ class SessionStore:"(%s); falling back to full index rewrite",session_key, exc,)- self._save_entries()+ if fallback_data is not None:+ self._persist_routing_data(fallback_data, revision)+ else:+ self._save_entries()def _resolve_profile_for_key(self, source: Optional[SessionSource] = None) -> Optional[str]:"""Return the profile namespace for session keys, or None when off.@@ -2799,16 +2844,24 @@ class SessionStore:if entry is None:return Nonenow = _now()- entry.active_turn_token = token- entry.active_turn_started_at = now+ candidate = entry.to_dict()+ candidate["active_turn_token"] = token+ candidate["active_turn_started_at"] = now.isoformat()# Keep the legacy 120-second startup heuristic effective during a# rolling downgrade/upgrade window where an older binary cannot# understand the exact marker fields.- entry.updated_at = now+ candidate["updated_at"] = now.isoformat()- # This is a per-turn metadata update, so use the existing durable- # single-entry fast path rather than rewriting the full routing index.- self._save_entry(session_key)+ # Persist before publishing the marker in memory. If the durable+ # write raises, a later unrelated save cannot leak an unowned token.+ self._save_entry(+ session_key,+ entry_data=candidate,+ lock_held=True,+ )+ entry.active_turn_token = token+ entry.active_turn_started_at = now+ entry.updated_at = nowreturn tokendef clear_turn_active(self, session_key: str, token: str) -> bool:@@ -2821,10 +2874,19 @@ class SessionStore:entry = self._entries.get(session_key)if entry is None or entry.active_turn_token != token:return False+ candidate = entry.to_dict()+ candidate["active_turn_token"] = None+ candidate["active_turn_started_at"] = None++ # Keep the live token until the clear is durable. A failed write+ # therefore remains retryable instead of becoming a false mismatch.+ self._save_entry(+ session_key,+ entry_data=candidate,+ lock_held=True,+ )entry.active_turn_token = Noneentry.active_turn_started_at = None-- self._save_entry(session_key)return Truedef recover_interrupted_turns(diff --git a/tests/gateway/test_active_turn_recovery.py b/tests/gateway/test_active_turn_recovery.pyindex 50b1e17473e..87609fd82f5 100644--- a/tests/gateway/test_active_turn_recovery.py+++ b/tests/gateway/test_active_turn_recovery.py@@ -39,6 +39,23 @@ def _make_store(tmp_path) -> SessionStore:return store+def _make_db_store(tmp_path) -> SessionStore:+ from hermes_state import SessionDB++ sessions_dir = tmp_path / "sessions"+ store = SessionStore(sessions_dir=sessions_dir, config=GatewayConfig())+ if store._db is not None:+ store._db.close()+ store._db = SessionDB(db_path=tmp_path / "state.db")+ return store+++def _close_store_db(store: SessionStore) -> None:+ db = store._db+ assert db is not None+ db.close()++def _entry_for(store: SessionStore, source: SessionSource) -> SessionEntry:key = store._generate_session_key(source)with store._lock:@@ -117,11 +134,125 @@ def test_mark_and_clear_use_single_entry_persistence(tmp_path):token = store.mark_turn_active(entry.session_key)assert token is not None- store._save_entry.assert_called_once_with(entry.session_key)+ store._save_entry.assert_called_once_with(+ entry.session_key,+ entry_data=store._entries[entry.session_key].to_dict(),+ lock_held=True,+ )store._save_entry.reset_mock()assert store.clear_turn_active(entry.session_key, token) is True- store._save_entry.assert_called_once_with(entry.session_key)+ store._save_entry.assert_called_once_with(+ entry.session_key,+ entry_data=store._entries[entry.session_key].to_dict(),+ lock_held=True,+ )+++def test_failed_mark_persistence_does_not_leak_marker_into_later_save(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)+ real_save_entry = store._save_entry+ store._save_entry = MagicMock(side_effect=OSError("disk unavailable"))++ with pytest.raises(OSError, match="disk unavailable"):+ store.mark_turn_active(entry.session_key)++ current = _entry_for(store, source)+ assert current.active_turn_token is None+ assert current.active_turn_started_at is None++ # A later unrelated save must not make the failed marker durable.+ store._save_entry = real_save_entry+ with store._lock:+ store._entries[entry.session_key].updated_at = datetime.now()+ store._save()++ reloaded = _make_store(tmp_path)+ assert reloaded.recover_interrupted_turns() == 0+ assert _entry_for(reloaded, source).active_turn_token is None+++def test_failed_clear_persistence_keeps_token_retryable_and_durable_clear_wins(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)+ token = store.mark_turn_active(entry.session_key)+ assert token is not None++ real_save_entry = store._save_entry+ store._save_entry = MagicMock(side_effect=OSError("disk unavailable"))++ with pytest.raises(OSError, match="disk unavailable"):+ store.clear_turn_active(entry.session_key, token)++ current = _entry_for(store, source)+ assert current.active_turn_token == token+ assert current.active_turn_started_at is not None++ store._save_entry = real_save_entry+ assert store.clear_turn_active(entry.session_key, token) is True++ reloaded = _make_store(tmp_path)+ persisted = _entry_for(reloaded, source)+ assert persisted.active_turn_token is None+ assert persisted.active_turn_started_at is None+++def test_state_db_failure_atomic_marker_round_trip(tmp_path):+ store = _make_db_store(tmp_path)+ source = _make_source("state-db-active-turn")+ entry = store.get_or_create_session(source)+ real_save_entry = store._save_entry++ store._save_entry = MagicMock(side_effect=OSError("state.db unavailable"))+ with pytest.raises(OSError, match="state.db unavailable"):+ store.mark_turn_active(entry.session_key)+ assert _entry_for(store, source).active_turn_token is None++ store._save_entry = real_save_entry+ token = store.mark_turn_active(entry.session_key)+ assert token is not None++ store._save_entry = MagicMock(side_effect=OSError("state.db unavailable"))+ with pytest.raises(OSError, match="state.db unavailable"):+ store.clear_turn_active(entry.session_key, token)+ assert _entry_for(store, source).active_turn_token == token++ store._save_entry = real_save_entry+ assert store.clear_turn_active(entry.session_key, token) is True+ _close_store_db(store)++ reloaded = _make_db_store(tmp_path)+ assert reloaded.recover_interrupted_turns() == 0+ persisted = _entry_for(reloaded, source)+ assert persisted.active_turn_token is None+ assert persisted.active_turn_started_at is None+ _close_store_db(reloaded)+++def test_state_db_commit_survives_legacy_mirror_failure(tmp_path):+ store = _make_db_store(tmp_path)+ source = _make_source("state-db-mirror-failure")+ entry = store.get_or_create_session(source)+ db = store._db+ assert db is not None+ db.save_gateway_routing_entry = MagicMock(+ side_effect=OSError("fast upsert unavailable")+ )+ store._save_sessions_json = MagicMock(+ side_effect=OSError("legacy mirror unavailable")+ )++ token = store.mark_turn_active(entry.session_key)+ assert token is not None+ _close_store_db(store)++ reloaded = _make_db_store(tmp_path)+ recovered = _entry_for(reloaded, source)+ assert recovered.active_turn_token == token+ _close_store_db(reloaded)def test_exact_old_active_turn_recovers_even_when_updated_at_is_stale(tmp_path):