Skip to content

The agent that grows with you

fix(tui-gateway): grant the WS orphan-reap grace in awake time

Hermes Agenteda61f644e33
diff --git a/tests/tui_gateway/test_ws_orphan_races.py b/tests/tui_gateway/test_ws_orphan_races.py
index 30a38709717..8b27874c5a6 100644
--- a/tests/tui_gateway/test_ws_orphan_races.py
+++ b/tests/tui_gateway/test_ws_orphan_races.py
@@ -267,3 +267,102 @@ def test_late_rpc_from_closed_socket_keeps_orphan_reap_armed(monkeypatch, path,
else:
assert session["transport"] is transport
assert sid not in server._pending_ws_reaps
+
+
+def test_ws_orphan_reap_rearms_after_system_sleep(monkeypatch):
+ """A reap timer the host slept through re-arms instead of reaping.
+
+ Regression for #44183: threading.Timer's wait elapses in wall-clock time
+ on macOS, so closing the lid for longer than the grace made the timer
+ fire at the instant of wake — before the Desktop app could reconnect —
+ and every >20s sleep/wake cycle 404'd the open session. The reap must
+ grant the full grace window in *awake* (monotonic) time.
+ """
+ timers = []
+
+ class Timer:
+ def __init__(self, interval, callback):
+ self.interval = interval
+ self.callback = callback
+ timers.append(self)
+
+ def start(self):
+ pass
+
+ def cancel(self):
+ pass
+
+ sid = "slept-through-grace"
+ reaped = []
+ clock = {"now": 1000.0}
+ session = dict(transport=server._detached_ws_transport, running=False)
+ monkeypatch.setattr(server, "_sessions", {sid: session})
+ monkeypatch.setattr(server, "_pending_ws_reaps", {})
+ monkeypatch.setattr(server.threading, "Timer", Timer)
+ monkeypatch.setattr(server.time, "monotonic", lambda: clock["now"])
+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 20)
+ monkeypatch.setattr(server, "_pop_session_by_id", lambda s: reaped.append(s) or session)
+
+ server._schedule_ws_orphan_reap(sid)
+ assert len(timers) == 1
+ assert timers[0].interval == 20
+
+ # Host sleeps 2s into the grace: the wall-clock wait expires during the
+ # sleep and the timer fires at wake with only 2s of awake time elapsed —
+ # spared, re-armed for the remaining 18s.
+ clock["now"] += 2.0
+ timers[0].callback()
+ assert reaped == []
+ assert len(timers) == 2
+ assert abs(timers[1].interval - 18.0) < 1e-9
+ assert server._pending_ws_reaps[sid] is timers[1]
+
+ # The re-armed timer runs its full remainder awake: reap proceeds.
+ clock["now"] += 18.0
+ timers[1].callback()
+ assert reaped == [sid]
+
+
+def test_ws_orphan_reap_rearm_spares_post_wake_reconnect(monkeypatch):
+ """A session that reconnects within the post-wake grace is not reaped."""
+ timers = []
+
+ class Timer:
+ def __init__(self, interval, callback):
+ self.interval = interval
+ self.callback = callback
+ timers.append(self)
+
+ def start(self):
+ pass
+
+ def cancel(self):
+ pass
+
+ class LiveTransport:
+ def write(self, *a, **kw):
+ return True
+
+ sid = "woke-and-reconnected"
+ reaped = []
+ clock = {"now": 1000.0}
+ session = dict(transport=server._detached_ws_transport, running=False)
+ monkeypatch.setattr(server, "_sessions", {sid: session})
+ monkeypatch.setattr(server, "_pending_ws_reaps", {})
+ monkeypatch.setattr(server.threading, "Timer", Timer)
+ monkeypatch.setattr(server.time, "monotonic", lambda: clock["now"])
+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 20)
+ monkeypatch.setattr(server, "_pop_session_by_id", lambda s: reaped.append(s) or session)
+
+ server._schedule_ws_orphan_reap(sid)
+ clock["now"] += 2.0
+ timers[0].callback()
+ assert len(timers) == 2 # slept through the wait — re-armed
+
+ # Desktop reconnects (session.resume re-binds a live transport) before
+ # the re-armed remainder elapses: the reap is a no-op and the chain stops.
+ server._cancel_ws_orphan_reap(sid)
+ session["transport"] = LiveTransport()
+ clock["now"] += 18.0
+ timers[1].callback()
+ assert reaped == []
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 39d447ecfaf..66a9c6067f9 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -132,6 +132,11 @@ def _resolve_ws_orphan_reap_grace() -> float:
_WS_ORPHAN_REAP_GRACE_S = _resolve_ws_orphan_reap_grace()
+# If the reap timer fires with more than this much of the grace still unelapsed on the
+# monotonic clock, the host slept through the wall-clock wait — re-arm for the remainder
+# instead of reaping (#44183). Big enough to ignore timer jitter and wall-clock NTP
+# nudges, small relative to any real sleep.
+_WS_ORPHAN_REAP_SLEEP_SLACK_S = 0.5
# A detached RUNNING turn is interrupted only once its activity clock (API waits, stream tokens, tool
# heartbeats) idled this long; 600s = the turn-liveness watchdog so "wedged" means the same. 0 disables.
_WS_ORPHAN_ACTIVITY_STALE_S = _ws_orphan_setting("HERMES_TUI_WS_ORPHAN_ACTIVITY_STALE_S", "ws_orphan_activity_stale_s", 600.0)
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index 0beeb087b67..0742472525b 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -751,11 +751,36 @@ def _schedule_ws_orphan_reap(
sid: str, *, delay_s: float | None = None, _expected_timer: threading.Timer | None = None,
) -> None:
"""After a grace window, reap session ``sid`` iff it's still orphaned. Called from the WS-disconnect path; a
- reconnect or ``session.resume`` cancels the reap by re-binding a live transport. Disabled when grace is 0."""
+ reconnect or ``session.resume`` cancels the reap by re-binding a live transport. Disabled when grace is 0.
+
+ The grace is measured in AWAKE (monotonic) time: ``threading.Timer``'s wait elapses in wall-clock time on
+ platforms without a monotonic condvar (macOS lacks ``pthread_condattr_setclock``), so a system sleep makes
+ the timer fire "early" in awake-time terms. Without the monotonic deadline check below, closing a laptop lid
+ for longer than the grace reaped the parked session at the instant of wake — before the Desktop's WS
+ reconnect or ``session.resume`` could re-bind a transport — so every sleep/wake cycle 404'd the open chat
+ (#44183)."""
if _WS_ORPHAN_REAP_GRACE_S <= 0:
return
+ # time.monotonic() (mach_absolute_time / CLOCK_MONOTONIC) does not advance while the
+ # host is asleep, so this deadline measures awake time only.
+ deadline = time.monotonic() + (_WS_ORPHAN_REAP_GRACE_S if delay_s is None else max(0.0, delay_s))
def _reap() -> None:
+ # The wall-clock timer fired. If the monotonic (awake-time) clock says the grace
+ # hasn't actually elapsed — the host slept through the wait — re-arm for the
+ # remainder so the Desktop reconnect gets its full grace of awake time. The
+ # slack keeps ordinary timer jitter and wall-clock NTP nudges from re-arming
+ # a legitimately-expired reap.
+ remaining = deadline - time.monotonic()
+ if remaining > _WS_ORPHAN_REAP_SLEEP_SLACK_S:
+ with _sessions_lock:
+ if _pending_ws_reaps.get(sid) is not timer:
+ return
+ rearm = threading.Timer(remaining, _reap)
+ rearm.daemon = True
+ _pending_ws_reaps[sid] = rearm
+ rearm.start()
+ return
# Serialize the re-check against session.resume (rebinds under _session_resume_lock). Claim teardown by popping
# under both locks, then release the resume lock before slow finalization. Order: resume_lock -> sessions_lock.
reschedule_delay = interrupt_session = session = None