Skip to content

The agent that grows with you

fix(gateway): the loop watchdog's own heartbeat can freeze the loop it watches

rodrigof39931afd99d
diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.py
index 13d61af4d79..57bd014f65c 100644
--- a/gateway/shutdown_watchdog.py
+++ b/gateway/shutdown_watchdog.py
@@ -443,21 +443,50 @@ async def loop_heartbeat_forever(
) -> None:
"""Rewrite the loop heartbeat file on a cadence until cancelled / gated off.
- Runs as an asyncio task on the gateway loop — if the loop freezes, this
- task stops and the file mtime/updated_at goes stale for external monitors.
+ Runs as an asyncio task on the gateway loop — if the loop freezes, this task
+ stops and the file mtime/updated_at goes stale for external monitors. That
+ property is load-bearing and is preserved below: the write is still
+ *initiated* by the loop, so a frozen loop still lets the file age.
+
+ The write itself is handed to a thread, because it is not free. It ends in
+ ``atomic_json_write`` -> ``os.fsync``, and on a filesystem that stalls, that
+ fsync blocks whatever thread runs it. Doing it inline meant the loop-liveness
+ watchdog's own heartbeat could block the loop it exists to monitor: the probe
+ times out at ``DEFAULT_LOOP_WATCHDOG_TIMEOUT_S`` (10s) and gives up after
+ ``DEFAULT_LOOP_WATCHDOG_MAX_STRIKES`` (3), a ~90-120s budget, while a WSL2
+ VHDX under io pressure was measured stalling a trivial stat-and-fsync probe
+ at p99 31s and max 112s. So the watchdog killed the loop for being
+ unresponsive at the moment it was blocked inside the watchdog's own write.
+
+ Awaited, not fire-and-forget: an unawaited task would keep the file fresh
+ while the loop was wedged, which is exactly the signal the docstring above
+ promises. And a single in-flight write at a time, so a 112s stall cannot pile
+ up one queued thread per interval behind it.
"""
try:
interval = max(float(interval_s), 1.0)
except (TypeError, ValueError):
interval = DEFAULT_HEARTBEAT_INTERVAL_S
+ async def _write_off_loop() -> None:
+ # write_loop_heartbeat never raises, so a failure here is an executor
+ # problem (shutdown, saturation) and must not kill the heartbeat task.
+ try:
+ await asyncio.to_thread(
+ write_loop_heartbeat, start_time=start_time, home=home
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.debug("Loop heartbeat write failed off-loop", exc_info=True)
+
# Immediate first write so monitors see a fresh file as soon as the
# gateway is running, not after the first interval.
- write_loop_heartbeat(start_time=start_time, home=home)
+ await _write_off_loop()
while True:
if should_continue is not None and not should_continue():
return
await asyncio.sleep(interval)
if should_continue is not None and not should_continue():
return
- write_loop_heartbeat(start_time=start_time, home=home)
+ await _write_off_loop()
diff --git a/tests/gateway/test_loop_liveness_watchdog.py b/tests/gateway/test_loop_liveness_watchdog.py
index ca5e64e861f..db8779c81cd 100644
--- a/tests/gateway/test_loop_liveness_watchdog.py
+++ b/tests/gateway/test_loop_liveness_watchdog.py
@@ -3,6 +3,8 @@
from __future__ import annotations
import asyncio
+import pathlib
+import inspect
import threading
import time
from unittest.mock import MagicMock, patch
@@ -10,6 +12,7 @@ from unittest.mock import MagicMock, patch
import pytest
from gateway.shutdown_watchdog import (
+ loop_heartbeat_forever,
_arm_loop_floor_timer,
start_loop_liveness_watchdog,
)
@@ -310,3 +313,72 @@ def test_gateway_runner_liveness_guards_start_and_stop():
floor_timer.cancel.assert_called_once_with()
assert runner._loop_liveness_watchdog is None
assert runner._loop_floor_timer_handle is None
+def test_heartbeat_write_does_not_block_the_loop_it_monitors():
+ """The heartbeat write must not freeze the loop the watchdog is watching.
+
+ ``write_loop_heartbeat`` ends in ``atomic_json_write`` -> ``os.fsync``, and on
+ a stalling filesystem that fsync blocks whichever thread runs it. Run inline,
+ that thread was the gateway loop — so the loop-liveness watchdog would time
+ out its probe (10s, 3 strikes, a ~90-120s budget) and kill the loop for being
+ unresponsive at the moment it was blocked inside the watchdog's own write. A
+ WSL2 VHDX under io pressure was measured stalling a trivial stat-and-fsync
+ probe at p99 31s, max 112s — longer than the whole budget.
+
+ Bounded by a fixed sleep rather than an Event handshake on purpose: if the
+ write ever goes back on-loop this fails on the tick count instead of hanging.
+ """
+ block_s = 0.30
+
+ def slow_write(**_kwargs):
+ time.sleep(block_s)
+ return pathlib.Path("/dev/null")
+
+ async def scenario() -> int:
+ ticks = 0
+
+ async def ticker() -> None:
+ nonlocal ticks
+ deadline = time.monotonic() + block_s
+ while time.monotonic() < deadline:
+ await asyncio.sleep(0.02)
+ ticks += 1
+
+ with patch(
+ "gateway.shutdown_watchdog.write_loop_heartbeat", slow_write
+ ):
+ # should_continue False -> exactly one write, then return.
+ hb = asyncio.create_task(
+ loop_heartbeat_forever(interval_s=60.0, should_continue=lambda: False)
+ )
+ await ticker()
+ await asyncio.wait_for(hb, timeout=5.0)
+ return ticks
+
+ ticks = asyncio.run(scenario())
+ # Off-loop, the ticker gets roughly block_s / 0.02 ticks. Inline it gets at
+ # most one, because the loop cannot run anything while fsync blocks it.
+ assert ticks >= 5, (
+ "the loop made only %d tick(s) while the heartbeat was writing — "
+ "the write is blocking the loop again" % ticks
+ )
+
+
+def test_heartbeat_write_is_awaited_so_a_frozen_loop_still_goes_stale():
+ """The staleness signal external monitors rely on must survive the fix.
+
+ The docstring on ``loop_heartbeat_forever`` promises that a frozen loop lets the file
+ age, which is how an outside supervisor notices. Handing the write to a thread
+ keeps that promise only because the loop still *initiates* it and awaits it —
+ fire-and-forget would refresh the file from a thread while the loop was
+ wedged, destroying exactly that signal.
+ """
+ src = pathlib.Path(
+ inspect.getsourcefile(loop_heartbeat_forever) or ""
+ ).read_text()
+ body = src[src.index("async def loop_heartbeat_forever("):]
+ body = body[: body.index("\ndef ") if "\ndef " in body else len(body)]
+ assert "await asyncio.to_thread(" in body, "the write is not handed to a thread"
+ assert "create_task(" not in body, (
+ "the heartbeat write is fire-and-forget; a frozen loop would keep the "
+ "file fresh and the staleness signal would be lost"
+ )