Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
589 changes: 589 additions & 0 deletions docs/specs/auto-resume-after-restart-pr-spec.md

Large diffs are not rendered by default.

135 changes: 104 additions & 31 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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 "
Expand Down Expand Up @@ -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())

Copy link
Copy Markdown
Contributor Author

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 of self._running_agents.keys() here.

active_agents is the authoritative snapshot returned by _drain_active_agents() — it contains exactly the sessions that were still running at timeout. Re-reading self._running_agents is 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.

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",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semantic mismatch: when _restart_requested=False (clean shutdown with drain timeout), sessions are marked resume_pending=True with reason="shutdown_timeout" — but the shutdown banner on line ~1608 tells the user only "Your current task will be interrupted" with no recovery promise, and _prepend_restart_recovery_note() always says "interrupted by a gateway restart" regardless of the reason.

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 mark_resume_pending for non-restart shutdowns, or thread resume_reason through to the system note copy.

)
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"
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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"):
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
77 changes: 76 additions & 1 deletion gateway/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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()
Expand Down Expand Up @@ -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
),
)


Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early-return bypasses _should_reset() entirely, including idle-timeout and daily-reset policies. last_resume_marked_at is stored but never consulted here.

If the user never returns to the interrupted thread, the session stays permanently stuck in resume_pending=True and will never idle-reset. Consider adding a recovery-window guard — e.g., if _now() - entry.last_resume_marked_at > recovery_window_seconds, fall through to the normal _should_reset() path instead of returning early.

else:
reset_reason = self._should_reset(entry, source)
if not reset_reason:
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resume_attempts is incremented here but never checked against a threshold anywhere in the codebase. The spec promises "third interrupted restart → convert to suspended=True" as the escalation path for poisoned sessions, but without a threshold check this counter is purely decorative.

The only escalation that exists is the existing stuck-loop mechanism in _suspend_stuck_loop_sessions() (which clears resume_pending when it fires), but that fires on restart-count watermarks, not attempt-count. A session that hangs silently (never triggering stuck-loop detection) would accumulate resume_attempts forever without ever escalating.

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.

Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading