Repository navigation
spec: automatic session resume after gateway restart #11852
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
e2be46b
5619fa0
75c1d43
4861e04
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -533,6 +533,43 @@ def _parse_session_key(session_key: str) -> "dict | None": | |
| return None | ||
|
|
||
|
|
||
| def _prepend_restart_recovery_note( | ||
| message: str, | ||
| agent_history: list[dict], | ||
| *, | ||
| resume_pending: bool, | ||
| ) -> str: | ||
| """Prepend the appropriate interrupted-turn recovery note.""" | ||
| has_tool_tail = bool(agent_history and agent_history[-1].get("role") == "tool") | ||
| if resume_pending: | ||
| if has_tool_tail: | ||
| note = ( | ||
| "[System note: Your previous turn in this same session was interrupted by " | ||
| "a gateway restart. Continue from the existing transcript. There are " | ||
| "unfinished tool results in the conversation history, so process those " | ||
| "results first, summarize what was accomplished, then answer the user's " | ||
| "new message below.]" | ||
| ) | ||
| else: | ||
| note = ( | ||
| "[System note: Your previous turn in this same session was interrupted by " | ||
| "a gateway restart. Continue from the existing transcript and preserve " | ||
| "session continuity when answering the user's new message below.]" | ||
| ) | ||
| return note + "\n\n" + message | ||
|
|
||
| if has_tool_tail: | ||
| return ( | ||
| "[System note: Your previous turn was interrupted before you could " | ||
| "process the last tool result(s). The conversation history contains " | ||
| "tool outputs you haven't responded to yet. Please finish processing " | ||
| "those results and summarize what was accomplished, then address the " | ||
| "user's new message below.]\n\n" | ||
| + message | ||
| ) | ||
| return message | ||
|
|
||
|
|
||
| def _format_gateway_process_notification(evt: dict) -> "str | None": | ||
| """Format a watch pattern event from completion_queue into a [SYSTEM:] message.""" | ||
| evt_type = evt.get("type", "completion") | ||
|
|
@@ -1537,13 +1574,6 @@ async def _notify_active_sessions_of_shutdown(self) -> None: | |
| return | ||
|
|
||
| action = "restarting" if self._restart_requested else "shutting down" | ||
| hint = ( | ||
| "Your current task will be interrupted. " | ||
| "Send any message after restart to resume where it left off." | ||
| if self._restart_requested | ||
| else "Your current task will be interrupted." | ||
| ) | ||
| msg = f"⚠️ Gateway {action} — {hint}" | ||
|
|
||
| notified: set = set() | ||
| for session_key in active: | ||
|
|
@@ -1571,6 +1601,19 @@ async def _notify_active_sessions_of_shutdown(self) -> None: | |
| thread_id = _parsed.get("thread_id") | ||
| metadata = {"thread_id": thread_id} if thread_id else None | ||
|
|
||
| if self._restart_requested: | ||
| lane_hint = ( | ||
| "Send a message in this thread/topic to continue." | ||
| if thread_id | ||
| else "Send a message in this chat to continue." | ||
| ) | ||
| msg = ( | ||
| f"⚠️ Gateway {action} — I'll try to resume this session " | ||
| f"after restart. {lane_hint}" | ||
| ) | ||
| else: | ||
| msg = f"⚠️ Gateway {action} — Your current task will be interrupted." | ||
|
|
||
| await adapter.send(chat_id, msg, metadata=metadata) | ||
| notified.add(dedup_key) | ||
| logger.info( | ||
|
|
@@ -1670,6 +1713,8 @@ def _suspend_stuck_loop_sessions(self) -> int: | |
| entry = self.session_store._entries.get(session_key) | ||
| if entry and not entry.suspended: | ||
| entry.suspended = True | ||
| entry.resume_pending = False | ||
| entry.resume_reason = None | ||
| suspended += 1 | ||
| logger.warning( | ||
| "Auto-suspended stuck session %s (active across %d " | ||
|
|
@@ -2368,11 +2413,25 @@ async def _stop_impl() -> None: | |
| timeout = self._restart_drain_timeout | ||
| active_agents, timed_out = await self._drain_active_agents(timeout) | ||
| if timed_out: | ||
| timed_out_session_keys = set(self._running_agents.keys()) | ||
| logger.warning( | ||
| "Gateway drain timed out after %.1fs with %d active agent(s); interrupting remaining work.", | ||
| timeout, | ||
| self._running_agent_count(), | ||
| ) | ||
| if timed_out_session_keys: | ||
| for session_key in timed_out_session_keys: | ||
| try: | ||
| self.session_store.mark_resume_pending( | ||
| session_key, | ||
| reason="restart_timeout" if self._restart_requested else "shutdown_timeout", | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Semantic mismatch: when Result: a user who was told their task is simply interrupted will get a recovery note on next startup that wrongly blames a restart. Either skip |
||
| ) | ||
| except Exception as e: | ||
| logger.debug( | ||
| "Failed to mark session %s resume-pending during shutdown: %s", | ||
| session_key[:30], | ||
| e, | ||
| ) | ||
| self._interrupt_running_agents( | ||
| "Gateway restarting" if self._restart_requested else "Gateway shutting down" | ||
| ) | ||
|
|
@@ -2466,8 +2525,8 @@ async def _stop_impl() -> None: | |
| else: | ||
| logger.info( | ||
| "Skipping .clean_shutdown marker — drain timed out with " | ||
| "interrupted agents; next startup will suspend recently " | ||
| "active sessions." | ||
| "interrupted agents; resumable recovery metadata was " | ||
| "persisted for those sessions." | ||
| ) | ||
|
|
||
| # Track sessions that were active at shutdown for stuck-loop | ||
|
|
@@ -3611,7 +3670,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): | |
| if getattr(session_entry, 'was_auto_reset', False): | ||
| reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'idle' | ||
| if reset_reason == "suspended": | ||
| context_note = "[System note: The user's previous session was stopped and suspended. This is a fresh conversation with no prior context.]" | ||
| context_note = "[System note: The user's previous session was interrupted repeatedly during restart recovery, so Hermes started a fresh conversation to avoid getting stuck. This is a fresh conversation with no prior context.]" | ||
| elif reset_reason == "daily": | ||
| context_note = "[System note: The user's session was automatically reset by the daily schedule. This is a fresh conversation with no prior context.]" | ||
| else: | ||
|
|
@@ -3640,20 +3699,30 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): | |
| adapter = self.adapters.get(source.platform) | ||
| if adapter: | ||
| if reset_reason == "suspended": | ||
| reason_text = "previous session was stopped or interrupted" | ||
| notice = ( | ||
| "◐ This session was interrupted repeatedly during restart " | ||
| "recovery, so Hermes started a fresh session to avoid " | ||
| "getting stuck. Use /resume if you want the old transcript." | ||
| ) | ||
| elif reset_reason == "daily": | ||
| reason_text = f"daily schedule at {policy.at_hour}:00" | ||
| notice = ( | ||
| f"◐ Session automatically reset ({reason_text}). " | ||
| f"Conversation history cleared.\n" | ||
| f"Use /resume to browse and restore a previous session.\n" | ||
| f"Adjust reset timing in config.yaml under session_reset." | ||
| ) | ||
| else: | ||
| hours = policy.idle_minutes // 60 | ||
| mins = policy.idle_minutes % 60 | ||
| duration = f"{hours}h" if not mins else f"{hours}h {mins}m" if hours else f"{mins}m" | ||
| reason_text = f"inactive for {duration}" | ||
| notice = ( | ||
| f"◐ Session automatically reset ({reason_text}). " | ||
| f"Conversation history cleared.\n" | ||
| f"Use /resume to browse and restore a previous session.\n" | ||
| f"Adjust reset timing in config.yaml under session_reset." | ||
| ) | ||
| notice = ( | ||
| f"◐ Session automatically reset ({reason_text}). " | ||
| f"Conversation history cleared.\n" | ||
| f"Use /resume to browse and restore a previous session.\n" | ||
| f"Adjust reset timing in config.yaml under session_reset." | ||
| ) | ||
| try: | ||
| session_info = self._format_session_info() | ||
| if session_info: | ||
|
|
@@ -4034,6 +4103,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): | |
| source=source, | ||
| session_id=session_entry.session_id, | ||
| session_key=session_key, | ||
| session_entry=session_entry, | ||
| event_message_id=event.message_id, | ||
| channel_prompt=event.channel_prompt, | ||
| ) | ||
|
|
@@ -4074,6 +4144,16 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): | |
| # restarts where the session was active (never completed). | ||
| if session_key: | ||
| self._clear_restart_failure_count(session_key) | ||
| if getattr(session_entry, "resume_pending", False): | ||
| try: | ||
| if not agent_result.get("failed") and not agent_result.get("interrupted"): | ||
| self.session_store.clear_resume_pending(session_key) | ||
| session_entry.resume_pending = False | ||
| session_entry.resume_reason = None | ||
| session_entry.resume_attempts = 0 | ||
| session_entry.last_resume_marked_at = None | ||
| except Exception as e: | ||
| logger.debug("Failed to clear resume-pending state for %s: %s", session_key[:30], e) | ||
|
|
||
| # Surface error details when the agent failed silently (final_response=None) | ||
| if not response and agent_result.get("failed"): | ||
|
|
@@ -8492,6 +8572,7 @@ async def _run_agent( | |
| source: SessionSource, | ||
| session_id: str, | ||
| session_key: str = None, | ||
| session_entry: Any = None, | ||
| _interrupt_depth: int = 0, | ||
| event_message_id: Optional[str] = None, | ||
| channel_prompt: Optional[str] = None, | ||
|
|
@@ -9251,20 +9332,11 @@ def _approval_notify_sync(approval_data: dict) -> None: | |
| if _msn: | ||
| message = _msn + "\n\n" + message | ||
|
|
||
| # Auto-continue: if the loaded history ends with a tool result, | ||
| # the previous agent turn was interrupted mid-work (gateway | ||
| # restart, crash, SIGTERM). Prepend a system note so the model | ||
| # finishes processing the pending tool results before addressing | ||
| # the user's new message. (#4493) | ||
| if agent_history and agent_history[-1].get("role") == "tool": | ||
| message = ( | ||
| "[System note: Your previous turn was interrupted before you could " | ||
| "process the last tool result(s). The conversation history contains " | ||
| "tool outputs you haven't responded to yet. Please finish processing " | ||
| "those results and summarize what was accomplished, then address the " | ||
| "user's new message below.]\n\n" | ||
| + message | ||
| ) | ||
| message = _prepend_restart_recovery_note( | ||
| message, | ||
| agent_history, | ||
| resume_pending=bool(getattr(session_entry, "resume_pending", False)), | ||
| ) | ||
|
|
||
| _approval_session_key = session_key or "" | ||
| _approval_session_token = set_current_session_key(_approval_session_key) | ||
|
|
@@ -9881,6 +9953,7 @@ async def _notify_long_running(): | |
| source=next_source, | ||
| session_id=session_id, | ||
| session_key=session_key, | ||
| session_entry=session_entry, | ||
| _interrupt_depth=_interrupt_depth + 1, | ||
| event_message_id=next_message_id, | ||
| channel_prompt=next_channel_prompt, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -377,6 +377,14 @@ class SessionEntry: | |
| # this session (create a new session_id) so the user starts fresh. | ||
| # Set by /stop to break stuck-resume loops (#7536). | ||
| suspended: bool = False | ||
|
|
||
| # Restart/crash recovery state. Unlike `suspended`, this keeps the user | ||
| # on the same session_id for the next same-lane message so transcript | ||
| # reload and continuation can resume in place. | ||
| resume_pending: bool = False | ||
| resume_reason: Optional[str] = None | ||
| resume_attempts: int = 0 | ||
| last_resume_marked_at: Optional[datetime] = None | ||
|
|
||
| def to_dict(self) -> Dict[str, Any]: | ||
| result = { | ||
|
|
@@ -397,6 +405,14 @@ def to_dict(self) -> Dict[str, Any]: | |
| "cost_status": self.cost_status, | ||
| "memory_flushed": self.memory_flushed, | ||
| "suspended": self.suspended, | ||
| "resume_pending": self.resume_pending, | ||
| "resume_reason": self.resume_reason, | ||
| "resume_attempts": self.resume_attempts, | ||
| "last_resume_marked_at": ( | ||
| self.last_resume_marked_at.isoformat() | ||
| if self.last_resume_marked_at | ||
| else None | ||
| ), | ||
| } | ||
| if self.origin: | ||
| result["origin"] = self.origin.to_dict() | ||
|
|
@@ -434,6 +450,14 @@ def from_dict(cls, data: Dict[str, Any]) -> "SessionEntry": | |
| cost_status=data.get("cost_status", "unknown"), | ||
| memory_flushed=data.get("memory_flushed", False), | ||
| suspended=data.get("suspended", False), | ||
| resume_pending=data.get("resume_pending", False), | ||
| resume_reason=data.get("resume_reason"), | ||
| resume_attempts=data.get("resume_attempts", 0), | ||
| last_resume_marked_at=( | ||
| datetime.fromisoformat(data["last_resume_marked_at"]) | ||
| if data.get("last_resume_marked_at") | ||
| else None | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
|
|
@@ -713,6 +737,10 @@ def get_or_create_session( | |
| # broke a stuck loop — #7536). | ||
| if entry.suspended: | ||
| reset_reason = "suspended" | ||
| elif entry.resume_pending: | ||
| entry.updated_at = now | ||
| self._save() | ||
| return entry | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This early-return bypasses If the user never returns to the interrupted thread, the session stays permanently stuck in |
||
| else: | ||
| reset_reason = self._should_reset(entry, source) | ||
| if not reset_reason: | ||
|
|
@@ -798,10 +826,53 @@ def suspend_session(self, session_key: str) -> bool: | |
| self._ensure_loaded_locked() | ||
| if session_key in self._entries: | ||
| self._entries[session_key].suspended = True | ||
| self._entries[session_key].resume_pending = False | ||
| self._entries[session_key].resume_reason = None | ||
| self._save() | ||
| return True | ||
| return False | ||
|
|
||
| def mark_resume_pending( | ||
| self, | ||
| session_key: str, | ||
| *, | ||
| reason: str = "restart_timeout", | ||
| increment_attempts: bool = True, | ||
| ) -> bool: | ||
| """Mark a session as resumable after restart interruption.""" | ||
| with self._lock: | ||
| self._ensure_loaded_locked() | ||
| entry = self._entries.get(session_key) | ||
| if not entry: | ||
| return False | ||
| entry.resume_pending = True | ||
| entry.resume_reason = reason | ||
| entry.last_resume_marked_at = _now() | ||
| if increment_attempts: | ||
| entry.resume_attempts += 1 | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The only escalation that exists is the existing stuck-loop mechanism in |
||
| self._save() | ||
| return True | ||
|
|
||
| def clear_resume_pending( | ||
| self, | ||
| session_key: str, | ||
| *, | ||
| reset_attempts: bool = True, | ||
| ) -> bool: | ||
| """Clear resumable restart state after recovery succeeds.""" | ||
| with self._lock: | ||
| self._ensure_loaded_locked() | ||
| entry = self._entries.get(session_key) | ||
| if not entry: | ||
| return False | ||
| entry.resume_pending = False | ||
| entry.resume_reason = None | ||
| entry.last_resume_marked_at = None | ||
| if reset_attempts: | ||
| entry.resume_attempts = 0 | ||
| self._save() | ||
| return True | ||
|
|
||
| def prune_old_entries(self, max_age_days: int) -> int: | ||
| """Drop SessionEntry records older than max_age_days. | ||
|
|
||
|
|
@@ -869,7 +940,11 @@ def suspend_recently_active(self, max_age_seconds: int = 120) -> int: | |
| with self._lock: | ||
| self._ensure_loaded_locked() | ||
| for entry in self._entries.values(): | ||
| if not entry.suspended and entry.updated_at >= cutoff: | ||
| if ( | ||
| not entry.suspended | ||
| and not entry.resume_pending | ||
| and entry.updated_at >= cutoff | ||
| ): | ||
| entry.suspended = True | ||
| count += 1 | ||
| if count: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
active_agents.keys()instead ofself._running_agents.keys()here.active_agentsis the authoritative snapshot returned by_drain_active_agents()— it contains exactly the sessions that were still running at timeout. Re-readingself._running_agentsis normally equivalent, but it introduces a subtle TOCTOU hazard: if any agent completes (and removes itself from_running_agents) in the window between_drain_active_agents()returning and this line executing, those sessions would be missed. The return value is the right source of truth.