The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): recover exact turns after unclean exits
Dominic Bejar6774760b6fe3
diff --git a/gateway/run.py b/gateway/run.pyindex 83342c39591..aa6bde878aa 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -10778,6 +10778,22 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewexcept Exception:logger.debug("Failed to cancel gateway loop floor timer", exc_info=True)+ async def _recover_unclean_sessions(self) -> tuple[int, int]:+ """Recover exact active turns, then run the legacy recency fallback."""+ exact = 0+ fallback = 0+ try:+ exact = await self.async_session_store.recover_interrupted_turns()+ except Exception as exc:+ logger.warning("Exact active-turn recovery on startup failed: %s", exc)+ try:+ fallback = await self.async_session_store.suspend_recently_active(+ max_age_seconds=120+ )+ except Exception as exc:+ logger.warning("Legacy session recovery on startup failed: %s", exc)+ return exact, fallback+async def start(self) -> bool:"""Start the gateway and all configured platform adapters.@@ -11113,10 +11129,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewexcept Exception as e:logger.warning("Process checkpoint recovery: %s", e)- # Suspend sessions that were active when the gateway last exited.- # This prevents stuck sessions from being blindly resumed on restart,- # which can create an unrecoverable loop (#7536). Suspended sessions- # auto-reset on the next incoming message, giving the user a clean start.+ # Recover sessions that were active when the gateway last exited.+ # Exact durable turn markers cover long-running work; the 120-second+ # recency heuristic remains as an upgrade fallback for turns started by+ # older Hermes versions that did not write exact markers.## SKIP suspension after a clean (graceful) shutdown — the previous# process already drained active agents, so sessions aren't stuck.@@ -11125,17 +11141,30 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_clean_marker = _hermes_home / ".clean_shutdown"if _clean_marker.exists():logger.info("Previous gateway exited cleanly — skipping session suspension")+ try:+ discarded = await self.async_session_store.discard_active_turn_markers()+ if discarded:+ logger.info(+ "Discarded %d orphan active-turn marker(s) after clean shutdown",+ discarded,+ )+ except Exception as exc:+ logger.warning("Clean-start marker cleanup failed: %s", exc)try:_clean_marker.unlink()except Exception:passelse:- try:- suspended = await self.async_session_store.suspend_recently_active()- if suspended:- logger.info("Marked %d in-flight session(s) as resumable from previous run", suspended)- except Exception as e:- logger.warning("Session suspension on startup failed: %s", e)+ exact, fallback = await self._recover_unclean_sessions()+ recovered = exact + fallback+ if recovered:+ logger.info(+ "Marked %d in-flight session(s) as resumable from previous run "+ "(%d exact, %d legacy)",+ recovered,+ exact,+ fallback,+ )# Stuck-loop detection (#7536): if a session has been active across# 3+ consecutive restarts, it's probably stuck in a loop (the same@@ -15923,6 +15952,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# and interrupt alike.self._restore_moa_one_shot(event, _quick_key)self._restore_pending_one_turn_model_override(_quick_key)+ # Normal completion/exception/interrupt owns and clears this exact+ # durable marker. SIGKILL/OOM skips finally, leaving the marker for+ # the next unclean startup's recovery pass.+ await self._clear_durable_active_turn(event)# Unconditional release covers every exit path. _release_running_agent_state# is idempotent (pop-on-absent is harmless) and, called without a# run_generation guard, always clears the slot regardless of which@@ -16453,6 +16486,59 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._async_session_store = facadereturn facade+ async def _mark_durable_active_turn(+ self,+ event: "MessageEvent",+ session_key: str,+ ) -> bool:+ """Persist the exact resolved routing key for this running turn."""+ try:+ token = await self.async_session_store.mark_turn_active(session_key)+ except Exception as exc:+ logger.warning(+ "Could not persist active-turn marker for %s: %s",+ session_key,+ exc,+ )+ return False+ if not token:+ return False+ # Private event attributes are process-local ownership state. Keep the+ # token out of public metadata, transcripts, and platform payloads.+ setattr(event, "_gateway_active_turn_session_key", session_key)+ setattr(event, "_gateway_active_turn_token", token)+ return True++ async def _clear_durable_active_turn(self, event: "MessageEvent") -> bool:+ """Best-effort CAS clear of the marker owned by *event*."""+ session_key = getattr(event, "_gateway_active_turn_session_key", None)+ token = getattr(event, "_gateway_active_turn_token", None)+ try:+ if not session_key or not token:+ return False+ return bool(+ await self.async_session_store.clear_turn_active(session_key, token)+ )+ except Exception as exc:+ # Never let marker cleanup block in-memory agent/lease release. A+ # stale marker is safer than wedging the live routing slot and is+ # bounded by recover_interrupted_turns' maximum age.+ logger.warning(+ "Could not clear active-turn marker for %s: %s",+ session_key,+ exc,+ )+ return False+ finally:+ for attr in (+ "_gateway_active_turn_session_key",+ "_gateway_active_turn_token",+ ):+ try:+ delattr(event, attr)+ except AttributeError:+ pass+def _get_cached_session_source(self, session_key: str):if not session_key:return Nonediff --git a/gateway/session.py b/gateway/session.pyindex fa019133c05..903c74526a3 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -852,6 +852,13 @@ class SessionEntry:resume_reason: Optional[str] = None # e.g. "restart_timeout"last_resume_marked_at: Optional[datetime] = None+ # Durable ownership marker for the agent turn currently executing on this+ # routing entry. A normal unwind clears it with compare-and-swap semantics;+ # SIGKILL/OOM leaves it behind so the next unclean startup can recover the+ # exact interrupted session instead of guessing from ``updated_at``.+ active_turn_token: Optional[str] = None+ active_turn_started_at: Optional[datetime] = None+# Session-scoped /model override (model/provider/base_url ONLY — never# credentials). ``_session_model_overrides`` in the gateway runner is# in-memory, so before this field a gateway restart silently reverted@@ -888,6 +895,12 @@ class SessionEntry:if self.last_resume_marked_atelse None),+ "active_turn_token": self.active_turn_token,+ "active_turn_started_at": (+ self.active_turn_started_at.isoformat()+ if self.active_turn_started_at+ else None+ ),"is_fresh_reset": self.is_fresh_reset,"was_auto_reset": self.was_auto_reset,"auto_reset_reason": self.auto_reset_reason,@@ -923,6 +936,20 @@ class SessionEntry:except (TypeError, ValueError):last_resume_marked_at = None+ active_turn_started_at = None+ _atsa = data.get("active_turn_started_at")+ if _atsa:+ try:+ active_turn_started_at = datetime.fromisoformat(_atsa)+ except (TypeError, ValueError):+ active_turn_started_at = None+ active_turn_token = data.get("active_turn_token")+ if not isinstance(active_turn_token, str) or not active_turn_token:+ # The token/timestamp pair is written atomically. A partial or+ # malformed pair is not trustworthy enough to auto-resume.+ active_turn_token = None+ active_turn_started_at = None+session_key = data["session_key"]session_id = data["session_id"]@@ -965,6 +992,8 @@ class SessionEntry:resume_pending=data.get("resume_pending", False),resume_reason=data.get("resume_reason"),last_resume_marked_at=last_resume_marked_at,+ active_turn_token=active_turn_token,+ active_turn_started_at=active_turn_started_at,is_fresh_reset=data.get("is_fresh_reset", False),was_auto_reset=data.get("was_auto_reset", False),auto_reset_reason=data.get("auto_reset_reason"),@@ -2756,6 +2785,125 @@ class SessionStore:return Truereturn False+ def mark_turn_active(self, session_key: str) -> Optional[str]:+ """Persist exact ownership of the agent turn running for *session_key*.++ The opaque token is returned to the caller and must be supplied to+ :meth:`clear_turn_active`. Re-marking replaces the previous token so+ a stale asynchronous unwind cannot clear a newer turn.+ """+ token = uuid.uuid4().hex+ with self._lock:+ self._ensure_loaded_locked()+ entry = self._entries.get(session_key)+ if entry is None:+ return None+ now = _now()+ entry.active_turn_token = token+ entry.active_turn_started_at = now+ # 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++ # 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)+ return token++ def clear_turn_active(self, session_key: str, token: str) -> bool:+ """Compare-and-swap clear an active-turn marker.++ Returns ``False`` when the entry disappeared or a newer turn owns it.+ """+ with self._lock:+ self._ensure_loaded_locked()+ entry = self._entries.get(session_key)+ if entry is None or entry.active_turn_token != token:+ return False+ entry.active_turn_token = None+ entry.active_turn_started_at = None++ self._save_entry(session_key)+ return True++ def recover_interrupted_turns(+ self,+ max_age_seconds: int = 7 * 24 * 60 * 60,+ ) -> int:+ """Promote exact crash-left turn markers into ``resume_pending``.++ This must only be called by the unclean-startup path. Old or invalid+ markers are cleared without resuming so a downgrade/re-upgrade cycle+ cannot revive arbitrarily stale work. Explicitly suspended sessions+ are likewise never re-armed.++ Returns the number of newly promoted sessions.+ """+ from datetime import timedelta++ now = _now()+ max_age = timedelta(seconds=max(0, max_age_seconds))+ promoted = 0+ changed = False++ with self._lock:+ self._ensure_loaded_locked()+ for entry in self._entries.values():+ if not entry.active_turn_token:+ continue++ started_at = entry.active_turn_started_at+ try:+ marker_is_stale = (+ started_at is None+ or (max_age_seconds > 0 and now - started_at > max_age)+ )+ except TypeError:+ # Mixed aware/naive timestamps are invalid for this local+ # marker. Clear rather than risking an unsafe old resume.+ marker_is_stale = True++ if not marker_is_stale and not entry.suspended:+ if entry.resume_pending:+ # A drain-timeout marker is more specific than the+ # generic crash reason; preserve it and its freshness.+ if entry.last_resume_marked_at is None:+ entry.last_resume_marked_at = now+ else:+ entry.resume_pending = True+ entry.resume_reason = "restart_interrupted"+ # Freshness starts when recovery is discovered, not+ # when a potentially hours-long turn began.+ entry.last_resume_marked_at = now+ promoted += 1++ entry.active_turn_token = None+ entry.active_turn_started_at = None+ changed = True++ if changed:+ # Cold-start batch: one durable rewrite is clearer and cheaper+ # than an upsert per interrupted routing entry.+ self._save()++ return promoted++ def discard_active_turn_markers(self) -> int:+ """Clear orphan turn markers after a verified clean shutdown."""+ cleared = 0+ with self._lock:+ self._ensure_loaded_locked()+ for entry in self._entries.values():+ if not entry.active_turn_token and entry.active_turn_started_at is None:+ continue+ entry.active_turn_token = None+ entry.active_turn_started_at = None+ cleared += 1+ if cleared:+ self._save()+ return cleared+def mark_resume_pending(self,session_key: str,diff --git a/tests/gateway/test_active_turn_recovery.py b/tests/gateway/test_active_turn_recovery.pynew file mode 100644index 00000000000..b410a3f3d58--- /dev/null+++ b/tests/gateway/test_active_turn_recovery.py@@ -0,0 +1,308 @@+"""Regression tests for exact durable active-turn restart recovery.++A long-running gateway turn can outlive the legacy 120-second+``updated_at`` crash heuristic. These tests require an exact persisted+marker, compare-and-swap cleanup, and promotion into the existing+``resume_pending`` recovery path after an unclean exit.+"""++from datetime import datetime, timedelta+from types import SimpleNamespace+from typing import Any, cast+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import GatewayConfig, Platform+from gateway.run import GatewayRunner+from gateway.session import SessionEntry, SessionSource, SessionStore+++ACTIVE_TURN_MAX_AGE_SECONDS = 7 * 24 * 60 * 60+++def _make_source(chat_id: str = "active-turn-chat") -> SessionSource:+ return SessionSource(+ platform=Platform.DISCORD,+ chat_id=chat_id,+ user_id="user-1",+ chat_type="channel",+ thread_id="thread-1",+ )+++def _make_store(tmp_path) -> SessionStore:+ store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())+ # Exercise the legacy JSON fallback deterministically. ``_save_entry``+ # must still persist correctly when state.db is unavailable.+ store._db = None+ return store+++def _entry_for(store: SessionStore, source: SessionSource) -> SessionEntry:+ key = store._generate_session_key(source)+ with store._lock:+ store._ensure_loaded_locked()+ return store._entries[key]+++def test_active_turn_fields_round_trip_and_legacy_payload_defaults(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++ payload = _entry_for(store, source).to_dict()+ assert payload["active_turn_token"] == token+ assert payload["active_turn_started_at"] is not None++ restored = SessionEntry.from_dict(payload)+ assert restored.active_turn_token == token+ assert restored.active_turn_started_at is not None++ payload.pop("active_turn_token")+ payload.pop("active_turn_started_at")+ legacy = SessionEntry.from_dict(payload)+ assert legacy.active_turn_token is None+ assert legacy.active_turn_started_at is None++ payload["active_turn_token"] = {"invalid": "not-a-token"}+ payload["active_turn_started_at"] = datetime.now().isoformat()+ corrupt = SessionEntry.from_dict(payload)+ assert corrupt.active_turn_token is None+ assert corrupt.active_turn_started_at is None+++def test_mark_refreshes_updated_at_for_legacy_upgrade_fallback(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)+ old_updated_at = datetime.now() - timedelta(hours=2)+ with store._lock:+ store._entries[entry.session_key].updated_at = old_updated_at++ token = store.mark_turn_active(entry.session_key)++ assert token is not None+ assert _entry_for(store, source).updated_at > old_updated_at+++def test_active_turn_clear_is_compare_and_swap(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)++ first = store.mark_turn_active(entry.session_key)+ second = store.mark_turn_active(entry.session_key)+ assert first is not None+ assert second is not None+ assert first != second++ assert store.clear_turn_active(entry.session_key, first) is False+ assert _entry_for(store, source).active_turn_token == second++ assert store.clear_turn_active(entry.session_key, second) is True+ current = _entry_for(store, source)+ assert current.active_turn_token is None+ assert current.active_turn_started_at is None+++def test_mark_and_clear_use_single_entry_persistence(tmp_path):+ store = _make_store(tmp_path)+ entry = store.get_or_create_session(_make_source())+ real_save_entry = store._save_entry+ store._save_entry = MagicMock(wraps=real_save_entry)++ 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.reset_mock()+ assert store.clear_turn_active(entry.session_key, token) is True+ store._save_entry.assert_called_once_with(entry.session_key)+++def test_exact_old_active_turn_recovers_even_when_updated_at_is_stale(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)++ with store._lock:+ current = store._entries[entry.session_key]+ current.updated_at = datetime.now() - timedelta(hours=2)+ current.active_turn_started_at = datetime.now() - timedelta(hours=2)+ store._save()++ # Prove the marker survives a fresh SessionStore and is not relying on the+ # in-memory object that wrote it.+ reloaded = _make_store(tmp_path)+ assert reloaded.recover_interrupted_turns(+ max_age_seconds=ACTIVE_TURN_MAX_AGE_SECONDS+ ) == 1++ recovered = _entry_for(reloaded, source)+ assert recovered.resume_pending is True+ assert recovered.resume_reason == "restart_interrupted"+ assert recovered.last_resume_marked_at is not None+ assert recovered.last_resume_marked_at > datetime.now() - timedelta(seconds=5)+ assert recovered.active_turn_token is None+ assert recovered.active_turn_started_at is None+ assert token+++def test_suspended_active_turn_is_cleared_without_resume(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)+ store.mark_turn_active(entry.session_key)++ with store._lock:+ store._entries[entry.session_key].suspended = True++ assert store.recover_interrupted_turns() == 0+ recovered = _entry_for(store, source)+ assert recovered.suspended is True+ assert recovered.resume_pending is False+ assert recovered.active_turn_token is None+ assert recovered.active_turn_started_at is None+++def test_existing_resume_reason_and_freshness_are_preserved(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)+ store.mark_turn_active(entry.session_key)+ original_mark = datetime.now() - timedelta(minutes=2)++ with store._lock:+ current = store._entries[entry.session_key]+ current.resume_pending = True+ current.resume_reason = "shutdown_timeout"+ current.last_resume_marked_at = original_mark++ assert store.recover_interrupted_turns() == 0+ recovered = _entry_for(store, source)+ assert recovered.resume_pending is True+ assert recovered.resume_reason == "shutdown_timeout"+ assert recovered.last_resume_marked_at == original_mark+ assert recovered.active_turn_token is None+ assert recovered.active_turn_started_at is None+++def test_ancient_active_marker_is_cleared_without_auto_resume(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)+ store.mark_turn_active(entry.session_key)++ with store._lock:+ current = store._entries[entry.session_key]+ current.active_turn_started_at = datetime.now() - timedelta(days=8)++ assert store.recover_interrupted_turns(+ max_age_seconds=ACTIVE_TURN_MAX_AGE_SECONDS+ ) == 0+ recovered = _entry_for(store, source)+ assert recovered.resume_pending is False+ assert recovered.active_turn_token is None+ assert recovered.active_turn_started_at is None+++def test_clean_startup_discards_orphan_markers_without_resuming(tmp_path):+ store = _make_store(tmp_path)+ source = _make_source()+ entry = store.get_or_create_session(source)+ store.mark_turn_active(entry.session_key)++ assert store.discard_active_turn_markers() == 1++ recovered = _entry_for(store, source)+ assert recovered.resume_pending is False+ assert recovered.active_turn_token is None+ assert recovered.active_turn_started_at is None+++async def test_runner_active_turn_carrier_clears_the_exact_resolved_key():+ runner = object.__new__(GatewayRunner)+ runner.session_store = MagicMock()+ mark_active = AsyncMock(return_value="token-1")+ clear_active = AsyncMock(return_value=True)+ setattr(+ runner,+ "_async_session_store",+ SimpleNamespace(+ _store=runner.session_store,+ mark_turn_active=mark_active,+ clear_turn_active=clear_active,+ ),+ )+ event = SimpleNamespace()++ await runner._mark_durable_active_turn(+ cast(Any, event), "resolved-session-key"+ )++ assert event._gateway_active_turn_session_key == "resolved-session-key"+ assert event._gateway_active_turn_token == "token-1"++ await runner._clear_durable_active_turn(cast(Any, event))++ clear_active.assert_awaited_once_with("resolved-session-key", "token-1")+ assert not hasattr(event, "_gateway_active_turn_session_key")+ assert not hasattr(event, "_gateway_active_turn_token")+++async def test_runner_active_turn_clear_is_best_effort():+ runner = object.__new__(GatewayRunner)+ runner.session_store = MagicMock()+ setattr(+ runner,+ "_async_session_store",+ SimpleNamespace(+ _store=runner.session_store,+ clear_turn_active=AsyncMock(side_effect=OSError("disk unavailable")),+ ),+ )+ event = SimpleNamespace(+ _gateway_active_turn_session_key="resolved-session-key",+ _gateway_active_turn_token="token-1",+ )++ await runner._clear_durable_active_turn(cast(Any, event))++ assert not hasattr(event, "_gateway_active_turn_session_key")+ assert not hasattr(event, "_gateway_active_turn_token")+++async def test_unclean_recovery_promotes_exact_markers_before_legacy_fallback():+ runner = object.__new__(GatewayRunner)+ calls: list[str] = []++ async def _recover():+ calls.append("exact")+ return 1++ async def _fallback(*, max_age_seconds):+ assert max_age_seconds == 120+ calls.append("fallback")+ return 2++ runner.session_store = MagicMock()+ setattr(+ runner,+ "_async_session_store",+ SimpleNamespace(+ _store=runner.session_store,+ recover_interrupted_turns=_recover,+ suspend_recently_active=_fallback,+ ),+ )++ assert await runner._recover_unclean_sessions() == (1, 2)+ assert calls == ["exact", "fallback"]