The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a crash no longer re-answers every recently active chat
teknium1360b9697ac97
diff --git a/gateway/delivery_ledger.py b/gateway/delivery_ledger.pyindex e846402ccd5..6b4b45549fa 100644--- a/gateway/delivery_ledger.py+++ b/gateway/delivery_ledger.py@@ -285,6 +285,28 @@ def record_obligation(*, obligation_id: str, session_key: str, platform: str, ch_prune_unlocked(conn, now)+def record_crash_left_reply(*, obligation_id: str, session_key: str, platform: str, chat_id: str,+ thread_id: Optional[str], content: str, since: float,+ adapter_profile: Optional[str] = None) -> None:+ """Adopt a reply a killed process persisted but never ledgered. Unowned, so this boot's sweep+ claims it, and 'attempting', because a streamed reply may already be on screen: it is+ redelivered once, with the recovered marker. A no-op when the same reply was already ledgered+ since *since* (the turn start), and idempotent across boots that die before their sweep."""+ now = time.time()+ with _DB_LOCK, _transaction() as conn:+ conn.execute(+ """INSERT OR IGNORE INTO delivery_obligations+ (obligation_id, session_key, platform, chat_id, thread_id,+ content, state, attempts, created_at, updated_at,+ owner_pid, owner_started_at, adapter_profile)+ SELECT ?, ?, ?, ?, ?, ?, 'attempting', 0, ?, ?, NULL, NULL, ?+ WHERE NOT EXISTS (SELECT 1 FROM delivery_obligations+ WHERE session_key = ? AND content = ? AND created_at >= ?)""",+ (obligation_id, session_key, platform, str(chat_id), str(thread_id) if thread_id else None,+ content, now, now, str(adapter_profile).strip() if adapter_profile else "default",+ session_key, content, since))++def mark_attempting(obligation_id: str) -> None:_update_state(obligation_id, "attempting")diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 4eb1ab4c08f..d938cdc793c 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -4267,12 +4267,21 @@ class BasePlatformAdapter(ABC):len(text_content), event.source.chat_id)obligation_id = await self._record_delivery_obligation(event, session_key, text_content, delivery_adapter, is_ephemeral_response)+ if obligation_id is not None:+ await self._release_turn_marker(event) # the ledger now owns the crash recoveryresult = await delivery_adapter._send_with_retry(chat_id=event.source.chat_id, content=text_content, reply_to=reply_to, metadata=metadata)if obligation_id is not None:await self._finalize_delivery_obligation(obligation_id, result, event, delivery_adapter)return result, delivery_adapter+ async def _release_turn_marker(self, event: MessageEvent) -> None:+ """Clear the crash-recovery marker the runner handed to this delivery lifecycle+ (``_turn_marker_handoff``): only once the final reply is ledgered or nothing more is owed,+ so no kill leaves a persisted reply with neither marker nor ledger row. Idempotent."""+ if getattr(event, "_turn_marker_handoff", False) and getattr(event, "_gateway_active_turn_token", None):+ await self.gateway_runner._clear_durable_active_turn(event)+async def _send_final_text(self, event: MessageEvent, session_key: str, text_content: str, metadata: Dict[str, Any],is_ephemeral_response: bool, ephemeral_ttl: int, record_delivery: Callable) -> None:@@ -4442,6 +4451,7 @@ class BasePlatformAdapter(ABC):typing_task = self._start_typing_refresh(event, interrupt_event, _thread_metadata)try:await self._run_processing_hook("on_processing_start", event)+ event._turn_marker_handoff = self.gateway_runner is not None # it can release the markerresponse = await self._message_handler(event)# A muted diagnostic wake ran for the session; its reply is not presented. The# policy read binds the routed profile; delivery itself stays in the launch scope.@@ -4501,6 +4511,7 @@ class BasePlatformAdapter(ABC):event, extracted, _final_thread_metadata,anything_sent=delivery_attempted or _tts_caption_delivered,record_delivery=_record_delivery)+ await self._release_turn_marker(event)processing_ok = delivery_succeeded if delivery_attempted else not bool(response)# Clean up the per-turn streaming-TTS flag.self._streaming_tts_completed_turns.discard(self._streaming_tts_turn_key(@@ -4533,6 +4544,8 @@ class BasePlatformAdapter(ABC):if isinstance(e, (SystemExit, KeyboardInterrupt)):raisefinally:+ await self._release_turn_marker(event)+ event._turn_marker_handoff = False # a later run of this object clears its own marker# Stop typing BEFORE the post-delivery callback: a stuck callback must not keep it# alive.await self._stop_typing_refresh(event.source.chat_id, typing_task, metadata=_thread_metadata)diff --git a/gateway/run.py b/gateway/run.pyindex 3f334263cc3..3f028576ee3 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -4047,8 +4047,9 @@ class GatewayRunner(_STUCK_LOOP_THRESHOLD = 3 # restarts while active before auto-suspend_STUCK_LOOP_FILE = ".restart_failure_counts"- # Reasons set by _stop_impl() on force-interrupt; "restart_interrupted" by suspend_recently_active()- # on crash recovery (no .clean_shutdown marker). All mean "killed mid-turn" -> startup auto-resume.+ # Reasons set by _stop_impl() on force-interrupt; "restart_interrupted" by recover_interrupted_turns()+ # for a crash-left turn marker (no .clean_shutdown marker). All mean "killed mid-turn" -> startup+ # auto-resume._AUTO_RESUME_REASONS = frozenset({"restart_timeout", "shutdown_timeout", "restart_interrupted"})_MAX_SUPERVISED_RESTARTS = 5diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex e893dab2725..48d793d7a72 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -1375,8 +1375,11 @@ class GatewayInboundMixin:# exception, interrupt); the generation guard makes a displaced turn's finalizer a no-op.self._restore_pending_one_turn_model_override(_quick_key, _run_generation)# SIGKILL/OOM skips finally, leaving the durable marker for the next unclean startup's- # recovery pass.- await self._clear_durable_active_turn(event)+ # recovery pass. A turn the adapter delivers hands its marker to that lifecycle, which+ # clears it only once the reply is in the delivery ledger (else a kill in between+ # left neither marker nor ledger row and the persisted reply was never sent).+ if not getattr(event, "_turn_marker_handoff", False):+ await self._clear_durable_active_turn(event)# Release only this turn's generation. Eviction may immediately admit a replacement# through the cold path; an unconditional release here would then clear the replacement# sentinel/agent and lease. Reset/stop release their stale slot before installing adiff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex b9f7ea8667c..d555a046160 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1329,7 +1329,7 @@ class GatewayShutdownMixin:atomic_json_write(path, {key: counts.get(key, 0) + 1 for key in active_session_keys}, indent=None)def _suspend_stuck_loop_sessions(self) -> int:- """Suspend sessions active across too many restarts (startup, AFTER suspend_recently_active())."""+ """Suspend sessions active across too many restarts (startup, AFTER crash-turn recovery)."""path = self._stuck_loop_counts_path()if not path.exists():return 0@@ -2043,15 +2043,15 @@ class GatewayShutdownMixin:from gateway.status import remove_pid_file, release_gateway_runtime_lockremove_pid_file()release_gateway_runtime_lock()- # Clean-shutdown marker skips suspend_recently_active() next boot; a timed-out drain left- # half-finished sessions, so no marker — the next startup suspends them.+ # Clean-shutdown marker skips crash-turn recovery next boot; a timed-out drain left+ # half-finished sessions, so no marker — the next startup recovers their turn markers.if not ctx.timed_out:with suppress(Exception):(_hermes_home / ".clean_shutdown").touch()else:logger.info("Skipping .clean_shutdown marker — drain timed out with "- "interrupted agents; next startup will suspend recently active sessions."+ "interrupted agents; next startup will recover their interrupted turns.")# Stuck-loop counter: sessions active across 3 consecutive restarts are auto-suspended next boot.if ctx.active_agents:diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex a4e1448afcd..e7f46ac769a 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -708,18 +708,60 @@ class GatewayStartupMixin:return discardedasync def _recover_unclean_sessions(self) -> tuple[int, int]:- """Recover exact active turns, then run the legacy recency fallback."""+ """Recover only the turns the dead process left marked: one whose reply is already in the+ transcript is owed delivery, not a new answer; any other resumes once. An unmarked session+ finished its turn (the marker is held until the reply is ledgered), so nothing re-runs it —+ the old 120 s recency sweep re-answered every recently active chat. Returns (resumed,+ ledgered)."""from gateway.run import _float_env- exact = 0- fallback = 0+ resumed = ledgered = 0+ max_age = max(60 * 60, int(max(1.0, _float_env("HERMES_AGENT_TIMEOUT", 1800)) * 2))+ with _log_suppressed(logging.WARNING, "Crash-left reply recovery on startup failed: %s"):+ ledgered = await self._ledger_crash_left_replies(max_age)with _log_suppressed(logging.WARNING, "Exact active-turn recovery on startup failed: %s"):- agent_timeout = max(1.0, _float_env("HERMES_AGENT_TIMEOUT", 1800))- exact = await self.async_session_store.recover_interrupted_turns(- max_age_seconds=max(60 * 60, int(agent_timeout * 2))- )- with _log_suppressed(logging.WARNING, "Legacy session recovery on startup failed: %s"):- fallback = await self.async_session_store.suspend_recently_active(max_age_seconds=120)- return exact, fallback+ resumed = await self.async_session_store.recover_interrupted_turns(max_age_seconds=max_age)+ return resumed, ledgered++ async def _ledger_crash_left_replies(self, max_age_seconds: int) -> int:+ """Hand every marked turn whose final reply was persisted to the delivery ledger and clear+ its marker, so the boot sweep delivers the stored reply instead of auto-resume+ regenerating it. Without the ledger such turns stay marked and resume."""+ from gateway.delivery_ledger import compute_obligation_id, ledger_enabled, record_crash_left_reply+ from gateway.platforms.base import _strip_media_directives+ from gateway.run import _sanitize_gateway_final_response+ if not await asyncio.to_thread(ledger_enabled):+ return 0+ cutoff = time.time() - max_age_seconds # older markers are cleared, never acted on+ with self.session_store._lock: # noqa: SLF001 — snapshot under lock+ self.session_store._ensure_loaded_locked() # noqa: SLF001+ marked = [+ (e.session_key, e.session_id, e.active_turn_token, e.active_turn_started_at, e.origin,+ e.transport_profile)+ for e in self.session_store._entries.values() # noqa: SLF001+ if e.active_turn_token and e.active_turn_started_at and e.origin and not e.suspended+ ]+ ledgered = 0+ for key, session_id, token, started_at, origin, profile in marked:+ history = await self.async_session_store.load_transcript(session_id)+ last = next((m for m in reversed(history) if m.get("role") not in ("session_meta", "system")), None)+ if (started_at.timestamp() < cutoff or not last or last.get("role") != "assistant"+ or last.get("tool_calls")+ or not isinstance(last.get("content"), str)+ or float(last.get("timestamp") or 0) < started_at.timestamp()):+ continue # the turn never produced its final reply: it resumes+ text = _strip_media_directives(+ _sanitize_gateway_final_response(origin.platform, last["content"])).strip()+ if not text:+ continue+ await asyncio.to_thread(+ record_crash_left_reply,+ obligation_id=compute_obligation_id(key, f"crash:{token}", text), session_key=key,+ platform=str(getattr(origin.platform, "value", origin.platform)), chat_id=origin.chat_id,+ thread_id=origin.thread_id, content=text, since=started_at.timestamp(),+ adapter_profile=profile)+ if await self.async_session_store.clear_turn_active(key, token):+ ledgered += 1+ return ledgered@staticmethoddef _start_hosted_room_worker_sync():@@ -1041,8 +1083,8 @@ class GatewayStartupMixin:recovered += self._recover_secondary_process_checkpoints(process_registry)if recovered:logger.info("Recovered %s background process(es) from previous run", recovered)- # Recover sessions active at last exit (exact turn markers + 120s recency fallback for- # marker-less older turns). SKIP after a clean exit — the previous process already drained.+ # Recover the turns the last process left marked (in flight, or reply not yet ledgered).+ # SKIP after a clean exit — the previous process already drained._clean_marker = _hermes_home / ".clean_shutdown"if _clean_marker.exists():logger.info("Previous gateway exited cleanly — skipping session suspension")@@ -1057,11 +1099,11 @@ class GatewayStartupMixin:if discarded:logger.info("Discarded %d orphan active-turn marker(s) after clean shutdown", discarded)else:- exact, fallback = await self._recover_unclean_sessions()- if exact + fallback:+ resumed, ledgered = await self._recover_unclean_sessions()+ if resumed + ledgered:logger.info(- "Marked %d in-flight session(s) as resumable from previous run "- "(%d exact, %d legacy)", exact + fallback, exact, fallback,+ "Recovered %d interrupted turn(s) from previous run (%d to resume, %d reply(ies) "+ "owed delivery)", resumed + ledgered, resumed, ledgered,)# Stuck-loop detection: a session active across 3+ consecutive restarts is auto-suspended.with _log_suppressed(logging.DEBUG, "Stuck-loop detection failed: %s"):diff --git a/gateway/session_lifecycle.py b/gateway/session_lifecycle.pyindex 47b3a95489f..e1815afde77 100644--- a/gateway/session_lifecycle.py+++ b/gateway/session_lifecycle.py@@ -241,23 +241,3 @@ class SessionLifecycleMixin:logger.info("SessionStore pruned %d entries older than %d days",len(removed_keys), max_age_days)return len(removed_keys)-- def suspend_recently_active(self, max_age_seconds: int = 120) -> int:- """Mark sessions active within *max_age_seconds* as ``resume_pending`` after a crash/fast- restart (already-pending and suspended entries are skipped). Returns the number marked.-- Called on gateway startup after a crash or fast restart to preserve in-flight sessions instead of- destroying their conversation history (#7536). Only marks sessions updated within *max_age_seconds*- to avoid touching long-idle sessions. Sets ``resume_pending=True`` so the next incoming message on- the same session_key auto-resumes from the existing transcript.- """- cutoff = _now() - timedelta(seconds=max_age_seconds)-- def _mark(entry: SessionEntry) -> bool:- if entry.resume_pending or entry.suspended or entry.updated_at < cutoff:- return False- entry.resume_pending = True- entry.resume_reason = "restart_interrupted"- entry.last_resume_marked_at = _now()- return True- return self._update_all_entries_locked(_mark)diff --git a/tests/gateway/test_active_turn_recovery.py b/tests/gateway/test_active_turn_recovery.pyindex 5fa76c112a7..3c2ecd1bdb5 100644--- a/tests/gateway/test_active_turn_recovery.py+++ b/tests/gateway/test_active_turn_recovery.py@@ -458,35 +458,53 @@ async def test_runner_active_turn_clear_stops_after_bounded_retries():assert not hasattr(event, "_gateway_active_turn_token")-async def test_unclean_recovery_promotes_exact_markers_before_legacy_fallback(- monkeypatch,-):+def _db_runner(tmp_path) -> tuple[GatewayRunner, SessionStore]:runner = object.__new__(GatewayRunner)- calls: list[str] = []+ runner.session_store = _make_db_store(tmp_path)+ return runner, runner.session_store- monkeypatch.delenv("HERMES_AGENT_TIMEOUT", raising=False)- async def _recover(*, max_age_seconds):- assert max_age_seconds == ACTIVE_TURN_MAX_AGE_SECONDS- calls.append("exact")- return 1+def _turn(store: SessionStore, chat_id: str, *, marked: bool, reply: str | None) -> SessionSource:+ source = _make_source(chat_id)+ entry = store.get_or_create_session(source)+ if marked:+ store.mark_turn_active(entry.session_key)+ store.append_to_transcript(entry.session_id, {"role": "user", "content": f"question {chat_id}"})+ if reply is not None:+ store.append_to_transcript(entry.session_id, {"role": "assistant", "content": reply})+ return source- 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,- ),- )+async def test_unclean_restart_resumes_only_the_turn_left_in_flight(tmp_path):+ """A kill re-arms the marked turn that had no reply yet, never a chat whose turn finished just+ before it (the removed 120 s recency sweep re-answered every recently active chat)."""+ runner, store = _db_runner(tmp_path)+ finished = _turn(store, "finished", marked=False, reply="answered and delivered")+ in_flight = _turn(store, "in-flight", marked=True, reply=None)++ assert await runner._recover_unclean_sessions() == (1, 0)++ assert not _entry_for(store, finished).resume_pending+ resumed = _entry_for(store, in_flight)+ assert (resumed.resume_pending, resumed.resume_reason) == (True, "restart_interrupted")+ _close_store_db(store)- assert await runner._recover_unclean_sessions() == (1, 2)- assert calls == ["exact", "fallback"]++async def test_unclean_restart_delivers_a_persisted_unledgered_reply_instead_of_regenerating(tmp_path):+ """Killed after the reply was persisted but before it reached the delivery ledger: the stored+ reply is ledgered for this boot's sweep (marked, it may already be on screen), not resumed."""+ from gateway.delivery_ledger import sweep_recoverable++ runner, store = _db_runner(tmp_path)+ source = _turn(store, "replied", marked=True, reply="the stored answer")++ assert await runner._recover_unclean_sessions() == (0, 1)++ entry = _entry_for(store, source)+ assert (entry.resume_pending, entry.active_turn_token) == (False, None)+ rows = sweep_recoverable(deliverable_platforms={"discord"})+ assert [(r["content"], r["needs_marker"], r["chat_id"], r["thread_id"]) for r in rows] == [+ ("the stored answer", True, "replied", "thread-1")]+ _close_store_db(store)diff --git a/tests/gateway/test_clean_shutdown_marker.py b/tests/gateway/test_clean_shutdown_marker.pyindex 25c79f674b3..e9dca67cb46 100644--- a/tests/gateway/test_clean_shutdown_marker.py+++ b/tests/gateway/test_clean_shutdown_marker.py@@ -2,9 +2,7 @@When the gateway shuts down gracefully (hermes update, gateway restart, /restart),it writes a .clean_shutdown marker. On the next startup, if the marker exists,-suspend_recently_active() is skipped so users don't lose their sessions.--After a crash (no marker), suspension still fires as a safety net for stuck sessions.+crash-turn recovery is skipped and orphan turn markers are discarded."""from datetime import datetime, timedelta@@ -28,28 +26,6 @@ def _make_store(tmp_path):return SessionStore(sessions_dir=tmp_path, config=config)-# ----------------------------------------------------------------------------# SessionStore.suspend_recently_active-# -----------------------------------------------------------------------------class TestSuspendRecentlyActive:- """Verify suspend_recently_active only marks recent sessions."""-- def test_suspends_recently_active_sessions(self, tmp_path):- store = _make_store(tmp_path)- source = _make_source()- entry = store.get_or_create_session(source)- assert not entry.suspended-- count = store.suspend_recently_active()- assert count == 1-- # Re-fetch — should be resume_pending (preserved, not wiped)- refreshed = store.get_or_create_session(source)- assert refreshed.resume_pending- assert refreshed.session_id == entry.session_id # same session preserved--# ---------------------------------------------------------------------------# Clean shutdown marker integration# ---------------------------------------------------------------------------@@ -100,32 +76,6 @@ class TestCleanShutdownMarker:assert marker.exists(), ".clean_shutdown marker should exist after graceful stop"- def test_no_marker_triggers_suspension(self, tmp_path, monkeypatch):- """Without .clean_shutdown marker (crash), suspension should fire."""- monkeypatch.setattr("gateway.run._hermes_home", tmp_path)-- marker = tmp_path / ".clean_shutdown"- assert not marker.exists()-- # Create a store with a recently active session- store = _make_store(tmp_path)- source = _make_source()- entry = store.get_or_create_session(source)- assert not entry.suspended-- # Simulate what start() does:- if marker.exists():- marker.unlink()- else:- store.suspend_recently_active()-- # Session SHOULD be resume_pending (crash recovery preserves history)- with store._lock:- store._ensure_loaded_locked()- resume_count = sum(1 for e in store._entries.values() if e.resume_pending)- assert resume_count == 1, "Session should be resume_pending after crash (no marker)"--# ---------------------------------------------------------------------------# resume_pending freshness gate (#46934)# ---------------------------------------------------------------------------diff --git a/tests/gateway/test_restart_resume_pending.py b/tests/gateway/test_restart_resume_pending.pyindex 1646395e7e2..9ac01429752 100644--- a/tests/gateway/test_restart_resume_pending.py+++ b/tests/gateway/test_restart_resume_pending.py@@ -7,9 +7,8 @@ PRs #9850, #9934, #7536):1. When a gateway restart drain times out and agents are force-interrupted,the affected sessions are flagged ``resume_pending=True`` — not``suspended`` — so the next user message on the same session_key- auto-resumes from the existing transcript instead of getting routed- through ``suspend_recently_active()`` and converted into a fresh- session.+ auto-resumes from the existing transcript instead of being converted+ into a fresh session.2. ``suspended=True`` (from ``/stop`` or stuck-loop escalation) stillwins over ``resume_pending`` — the forced-wipe path is preserved.@@ -246,25 +245,6 @@ class TestGetOrCreateResumePending:mock_tip.assert_called_with(original_sid)-# ----------------------------------------------------------------------------# SessionStore.suspend_recently_active skip behaviour-# ------------------------------------------------------------------------------class TestSuspendRecentlyActiveSkipsResumePending:- def test_resume_pending_entries_not_suspended(self, tmp_path):- store = _make_store(tmp_path)- source = _make_source()- entry = store.get_or_create_session(source)- store.mark_resume_pending(entry.session_key)-- count = store.suspend_recently_active()- assert count == 0- e = store._entries[entry.session_key]- assert e.suspended is False- assert e.resume_pending is True--# ---------------------------------------------------------------------------# Restart-resume system-note injection# ---------------------------------------------------------------------------@@ -552,7 +532,7 @@ class TestFreshnessHelpers:async def test_drain_timeout_marks_resume_pending():"""End-to-end: a drain timeout during gateway stop should flag everyactive session as resume_pending BEFORE the interrupt fires, so the- next startup's suspend_recently_active() does not destroy them."""+ next startup auto-resumes them."""runner, adapter = make_restart_runner()adapter.disconnect = AsyncMock()runner._restart_drain_timeout = 0.05diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.pyindex d30f62c4d73..48764de4031 100644--- a/tests/gateway/test_session.py+++ b/tests/gateway/test_session.py@@ -1136,8 +1136,6 @@ class TestSessionMetadata:assert store.set_session_metadata(entry.session_key, "k", "v")assert entry.updated_at == idle- # And the restart freshness gate must still see it as idle.- assert store.suspend_recently_active(max_age_seconds=120) == 0class TestRewriteTranscriptPreservesReasoning:diff --git a/tests/gateway/test_session_store_runtime_stale_guard.py b/tests/gateway/test_session_store_runtime_stale_guard.pyindex 782db55e0c9..8d12e4a72fe 100644--- a/tests/gateway/test_session_store_runtime_stale_guard.py+++ b/tests/gateway/test_session_store_runtime_stale_guard.py@@ -221,4 +221,3 @@ class TestAdvanceCompressionSession:assert result is not Noneassert result.updated_at == idle- assert store.suspend_recently_active(max_age_seconds=120) == 0diff --git a/tests/gateway/test_startup_restart_race.py b/tests/gateway/test_startup_restart_race.pyindex 71573634315..356e862573b 100644--- a/tests/gateway/test_startup_restart_race.py+++ b/tests/gateway/test_startup_restart_race.py@@ -88,7 +88,6 @@ def make_startup_runner(tmp_path):runner.hooks.discover_and_load = MagicMock()runner.hooks.emit = AsyncMock()runner.session_store = MagicMock()- runner.session_store.suspend_recently_active.return_value = 0runner.delivery_router = MagicMock()runner.delivery_router.adapters = {}diff --git a/website/docs/developer-guide/gateway-session-lifecycle.md b/website/docs/developer-guide/gateway-session-lifecycle.mdindex 2df83f49cc5..d92802bc523 100644--- a/website/docs/developer-guide/gateway-session-lifecycle.md+++ b/website/docs/developer-guide/gateway-session-lifecycle.md@@ -98,7 +98,7 @@ behavior on the next access.| `is_fresh_reset` | `bool` | `False` | Set by explicit `/new` or `/reset`. Triggers topic/channel skill re-injection on first message. Distinguished from `was_auto_reset` to avoid misleading "session expired" notices. || `expiry_finalized` | `bool` | `False` | Historical finalization fence retained for recovery; no timer writes it. || `suspended` | `bool` | `False` | Hard force-wipe signal. Set by `/stop` or stuck-loop escalation (3+ consecutive restart failures). On next `get_or_create_session()`, forces a new `session_id` regardless of `resume_pending`. |-| `resume_pending` | `bool` | `False` | Soft recovery marker. Set by `suspend_recently_active()` (crash recovery) or drain timeout. On next access, preserves the existing `session_id` — the user continues on the same transcript. Cleared after the next successful turn completes. |+| `resume_pending` | `bool` | `False` | Soft recovery marker. Set by `recover_interrupted_turns()` (crash recovery of a marked, unreplied turn) or drain timeout. On next access, preserves the existing `session_id` — the user continues on the same transcript. Cleared after the next successful turn completes. || `resume_reason` | `Optional[str]` | `None` | Why resume was marked: `"restart_timeout"`, `"shutdown_timeout"`, `"restart_interrupted"`. || `last_resume_marked_at` | `Optional[datetime]` | `None` | Timestamp of the last resume-pending marking. |@@ -174,7 +174,7 @@ SessionStore(sessions_dir: Path, config: GatewayConfig, has_active_processes_fn=| `suspend_session(session_key)` | Mark session as `suspended=True` (from `/stop`). Forces auto-reset on next access. || `mark_resume_pending(session_key, reason)` | Mark session as `resume_pending=True` (from drain timeout). Preserves session_id on next access. Will NOT override `suspended=True`. || `clear_resume_pending(session_key)` | Clear `resume_pending` after a successful resumed turn. Called from gateway after `run_conversation()` returns. |-| `suspend_recently_active(max_age_seconds=120)` | Crash recovery: mark recently-active sessions as `resume_pending=True`. Skips already-pending and already-suspended entries. Called on startup after unclean shutdown. |+| `recover_interrupted_turns(max_age_seconds)` | Crash recovery: promote durable active-turn markers the dead process left behind to `resume_pending=True` (`restart_interrupted`). Sessions without a marker finished their turn and are left alone. Called on startup after unclean shutdown. || `prune_old_entries(max_age_days)` | Drop entries older than `max_age_days` (based on `updated_at`). Skips `suspended` entries and sessions with active processes. || `list_sessions(active_minutes=None)` | Return all sessions, optionally filtered by recent activity. Sorted by `updated_at` descending. || `lookup_by_session_id(session_id)` | Find the active `SessionEntry` for a persisted session ID. |@@ -324,8 +324,10 @@ Gateway starts│ Missing▼┌───────────────────────────────┐-│ session_store │── Marks sessions updated within-│ .suspend_recently_active() │ last 120 seconds as resume_pending+│ _recover_unclean_sessions() │── Marked turn with a persisted reply+│ │ → delivery ledger (sent, marked);+│ │ marked turn without one →+│ │ resume_pending (once)└───────────────────────────────┘│▼@@ -351,15 +353,25 @@ Gateway starts└───────────────────────────────┘```-### suspend_recently_active(max_age_seconds=120)+### Crash recovery (`_recover_unclean_sessions`)-Called on gateway startup when no `.clean_shutdown` marker exists (indicating a crash or-unexpected exit). For each session updated within the last 120 seconds:+Called on gateway startup when no `.clean_shutdown` marker exists (a crash or unexpected+exit). It acts only on durable active-turn markers, never on recency: a chat that was merely+active shortly before the crash finished its turn and is not answered again.-- Sets `resume_pending=True`, `resume_reason="restart_interrupted"`,- `last_resume_marked_at=now`.-- Skips entries already `resume_pending=True` (no double-mark).-- Skips entries explicitly `suspended=True` (hard wipe should stay).+The marker is set when a turn starts and is held until the final reply is in the delivery+ledger (the adapter releases it right after `record_delivery_obligation`), or until nothing+more is owed (streamed reply, suppressed or empty response). So a marker left at startup means+one of two things:++- **The reply was persisted but never ledgered.** The stored transcript reply is recorded as+ an unowned ledger row and the marker is cleared; the boot sweep delivers it once with the+ "Recovered reply" notice. The turn is not regenerated.+- **No reply was persisted.** `recover_interrupted_turns()` sets `resume_pending=True`,+ `resume_reason="restart_interrupted"`, and the turn auto-resumes once.++A turn already in the ledger is redelivered by the ledger sweep, which also clears any+`resume_pending` for that session, so it is never both delivered and re-answered.### Stuck-Loop Detection (`_suspend_stuck_loop_sessions`)@@ -374,7 +386,7 @@ session that was mid-turn when the drain timeout fired. Reasons:- `"restart_timeout"` — killed during restart drain- `"shutdown_timeout"` — killed during shutdown drain-- `"restart_interrupted"` — crash recovery (from `suspend_recently_active`)+- `"restart_interrupted"` — crash recovery of a marked, unreplied turn (from `recover_interrupted_turns`)All three reasons are in `_AUTO_RESUME_REASONS` and eligible for startup auto-resume.@@ -395,8 +407,8 @@ When `get_or_create_session()` encounters `resume_pending=True`:Written at the end of a graceful shutdown. On next startup:-- If present: skip `suspend_recently_active()` entirely. Active agents were already- drained, so no sessions are stuck.+- If present: skip crash recovery entirely and discard orphan turn markers. Active agents+ were already drained, so no sessions are stuck.- Then delete the marker.This prevents unwanted auto-resets after `hermes update`, `hermes gateway restart`,diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.mdindex 9650818e8cd..1ad23739641 100644--- a/website/docs/user-guide/messaging/index.md+++ b/website/docs/user-guide/messaging/index.md@@ -862,6 +862,8 @@ Set `typing_indicator: false` on any platform where the indicator is unwanted. SWhen the gateway shuts down with an in-flight tool call or generation, the affected sessions are flagged as `restart_interrupted`. On the next startup, the gateway schedules an auto-resume for each one — the user gets a short heads-up in the chat ("Send any message after restart and I'll try to resume where you left off.") and the session picks up from the last committed turn when they reply.+Only turns that were actually in flight are resumed, and each resumes once. A chat whose turn had already finished is never answered again just because it was active shortly before a crash. If the gateway was killed after the agent finished a reply but before it was sent, the stored reply is delivered (with a "Recovered reply" notice) instead of being regenerated.+This behaviour is on by default and is logged at gateway start:```