Skip to content

The agent that grows with you

fix(gateway): auto-resume freshness survives a DST change

alt-glitch39a30e137e45
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index d18c27d6316..8492b2b42ca 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -16,7 +16,6 @@ import signal
import time
from contextlib import nullcontext, suppress
from contextvars import copy_context
-from datetime import datetime
from pathlib import Path
from gateway.config import Platform
from gateway.delivery import looks_like_telegram_private_chat_id
@@ -577,16 +576,19 @@ class GatewayStartupMixin:
``_is_resume_pending`` injection path owns the wording). Sessions whose adapter is offline stay
``resume_pending`` for the reconnect watcher, which re-calls this scoped to that ``platform``;
sessions with a running agent are skipped so none is resumed twice."""
- from gateway.run import _AGENT_PENDING_SENTINEL, _auto_continue_freshness_window
+ from gateway.run import (
+ _AGENT_PENDING_SENTINEL, _auto_continue_freshness_window, _is_fresh_gateway_interruption,
+ )
window = _auto_continue_freshness_window()
candidates = self._resume_pending_candidates(platform)
if candidates is None:
return 0
- now = datetime.now()
scheduled = 0
for entry in candidates:
+ # Epoch math: the marker was stamped naive-local by the previous process, possibly
+ # on the other side of a DST change; wall-clock subtraction is off by the shift.
marker = entry.last_resume_marked_at or entry.updated_at
- if marker is not None and (now - marker).total_seconds() > window:
+ if not _is_fresh_gateway_interruption(marker, window_secs=window):
continue
# Already being resumed (e.g. scheduled at startup, still in-flight) — no second turn.
if self._is_session_running(entry.session_key):
diff --git a/tests/gateway/test_restart_resume_pending.py b/tests/gateway/test_restart_resume_pending.py
index b36d5f73a6e..c7ef176fbe6 100644
--- a/tests/gateway/test_restart_resume_pending.py
+++ b/tests/gateway/test_restart_resume_pending.py
@@ -25,8 +25,9 @@ PRs #9850, #9934, #7536):
"""
import asyncio
+import os
import time
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -659,6 +660,61 @@ async def test_reconnect_reschedule_is_platform_scoped():
assert event.source == tg_source
[email protected](not hasattr(time, "tzset"), reason="needs a POSIX process timezone switch")
[email protected]("aware_marker", [False, True], ids=["naive-local", "aware-utc"])
+async def test_startup_auto_resume_freshness_survives_spring_forward(monkeypatch, aware_marker):
+ """A session marked 20 minutes before boot is inside a 60-minute window even when a DST
+ spring-forward falls between the two (naive wall-clock subtraction read it as 80 minutes)."""
+ runner, adapter = make_restart_runner()
+ source = make_restart_source(chat_id="dst-chat")
+ monkeypatch.setenv("HERMES_AUTO_CONTINUE_FRESHNESS", "3600")
+ original_tz = os.environ.get("TZ")
+ try:
+ os.environ["TZ"] = "America/New_York"
+ time.tzset()
+ # 2026-03-08: clocks jump 02:00 -> 03:00, so 01:50 -> 03:10 is 20 real minutes.
+ marked = datetime(2026, 3, 8, 1, 50)
+ now = datetime(2026, 3, 8, 3, 10)
+ if aware_marker:
+ marked = datetime.fromtimestamp(marked.timestamp(), tz=timezone.utc)
+
+ class _FrozenDatetime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return now if tz is None else datetime.fromtimestamp(now.timestamp(), tz=tz)
+
+ # Freeze both wall clocks the startup path could read.
+ monkeypatch.setattr("gateway.run_startup.datetime", _FrozenDatetime, raising=False)
+ monkeypatch.setattr(time, "time", lambda: now.timestamp())
+ entry = SessionEntry(
+ session_key="agent:main:telegram:dm:dst-chat",
+ session_id="sid-dst",
+ created_at=marked,
+ updated_at=marked,
+ origin=source,
+ platform=Platform.TELEGRAM,
+ chat_type="dm",
+ resume_pending=True,
+ resume_reason="restart_interrupted",
+ last_resume_marked_at=marked,
+ )
+ runner.session_store._entries = {entry.session_key: entry}
+ adapter.handle_message = AsyncMock()
+
+ scheduled = runner._schedule_resume_pending_sessions()
+ finally:
+ if original_tz is None:
+ os.environ.pop("TZ", None)
+ else:
+ os.environ["TZ"] = original_tz
+ time.tzset()
+ await asyncio.sleep(0)
+
+ assert scheduled == 1
+ adapter.handle_message.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_served_profile_reconnect_resumes_what_boot_deferred():
"""A served profile's session whose own bot is offline at boot is deferred (never answered from the