Skip to content

The agent that grows with you

refactor(gateway): simplify witness-probe ambiguity arms; sweep stale tick-socket nodes; clean test tempdirs

Kshitij Kapoorb48540701c33
diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.py
index 646f081ac9c..a7dc5b1c4de 100644
--- a/gateway/shutdown_watchdog.py
+++ b/gateway/shutdown_watchdog.py
@@ -530,6 +530,37 @@ async def loop_heartbeat_forever(
try:
tick_socket_path = get_loop_tick_socket_path(home)
tick_socket_path.parent.mkdir(parents=True, exist_ok=True)
+ # Re-bind over a leftover node from a dead process (os._exit(75) /
+ # SIGKILL skip the finally-unlink; PID reuse re-lands on this
+ # PID-suffixed path) is handled by asyncio itself:
+ # create_unix_server os.remove()s an existing socket node before
+ # binding — guarded by test_producer_rebinds_over_stale_socket_node.
+ # What asyncio does NOT do is clean up SIBLING nodes from other
+ # dead PIDs, so sweep those to keep state/ from accumulating
+ # gateway.loop-tick.*.sock nodes across crash-restart cycles.
+ # POSIX-only: os.kill(pid, 0) is a liveness probe here, but on
+ # Windows os.kill calls TerminateProcess for non-CTRL signals —
+ # and AF_UNIX server nodes are never created there anyway.
+ if os.name == "posix":
+ try:
+ for _stale in tick_socket_path.parent.glob(
+ "gateway.loop-tick.*.sock"
+ ):
+ if _stale == tick_socket_path:
+ continue
+ try:
+ _stale_pid = int(_stale.name.split(".")[-2])
+ except (ValueError, IndexError):
+ _stale.unlink(missing_ok=True)
+ continue
+ try:
+ os.kill(_stale_pid, 0)
+ except OSError:
+ _stale.unlink(missing_ok=True)
+ except Exception:
+ logger.debug(
+ "stale loop-tick socket sweep failed", exc_info=True
+ )
tick_server = await asyncio.start_unix_server(
_tick_socket_handler, path=str(tick_socket_path)
)
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 1ad6f3eb05b..4c18203e100 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -501,21 +501,16 @@ def _probe_loop_tick_socket_sustained(
None — a probe found no socket node (witness vanished mid-window, or
legacy producer): not evidence either way.
"""
- saw_node = False
total = max(int(strikes), 0)
for attempt in range(total):
result = _probe_loop_tick_socket(pid, home, timeout=timeout)
if result is True:
return True
if result is None:
- # The witness is gone — it is no longer answering, but its
- # absence is not a miss. Ambiguity, never a wedge.
- if not saw_node:
- return None
- # A node that existed and went silent mid-window: the witness
- # disappeared. Treat as ambiguity too.
+ # No socket node this attempt — either the witness never
+ # existed (legacy producer) or it vanished mid-window. Both
+ # are ambiguity, never a wedge: absence is not a miss.
return None
- saw_node = True
if attempt < total - 1 and gap_s > 0:
time.sleep(gap_s)
return False
diff --git a/tests/hermes_cli/test_update_wedged_gateway.py b/tests/hermes_cli/test_update_wedged_gateway.py
index 608abb941bf..858ec4c828a 100644
--- a/tests/hermes_cli/test_update_wedged_gateway.py
+++ b/tests/hermes_cli/test_update_wedged_gateway.py
@@ -12,6 +12,7 @@ path — including the in-flight cron drain floor from #86684.
import asyncio
import json
import os
+import shutil
import socket
import tempfile
import threading
@@ -41,7 +42,11 @@ def tmp_path():
under the system temp root keeps the socket path well under the limit
on every platform.
"""
- return Path(tempfile.mkdtemp(prefix="hwg-"))
+ path = Path(tempfile.mkdtemp(prefix="hwg-"))
+ try:
+ yield path
+ finally:
+ shutil.rmtree(path, ignore_errors=True)
def _write_heartbeat(home, pid, age_s=0.0):
@@ -786,6 +791,47 @@ class TestLoopTickWitness:
== gateway_cli.GATEWAY_LOOP_UNKNOWN
)
+ @pytest.mark.asyncio
+ async def test_producer_rebinds_over_stale_socket_node(self, tmp_path):
+ """A leftover node from a dead process must not disarm the witness.
+
+ os._exit(75) / SIGKILL skip the finally-unlink, and PID reuse then
+ re-lands on the same PID-suffixed path. Without the pre-bind unlink
+ the bind fails EADDRINUSE, the except disarms the witness
+ (loop_tick_socket:false), and a stale heartbeat can never classify
+ WEDGED — precisely on crash-restart loops.
+ """
+ sock_path = get_loop_tick_socket_path(tmp_path)
+ _silent_socket_node(sock_path) # dead process's leftover node
+ assert sock_path.exists()
+
+ task = asyncio.create_task(
+ loop_heartbeat_forever(interval_s=0.2, home=tmp_path)
+ )
+ try:
+ for _ in range(50):
+ hb = get_loop_heartbeat_path(tmp_path)
+ if hb.exists():
+ payload = json.loads(hb.read_text(encoding="utf-8"))
+ if payload.get("loop_tick_socket"):
+ break
+ await asyncio.sleep(0.05)
+ else:
+ raise AssertionError(
+ "witness never armed over the stale socket node"
+ )
+ # And it actually answers: the node is live, not the leftover.
+ reader, writer = await asyncio.open_unix_connection(str(sock_path))
+ data = await asyncio.wait_for(reader.read(64), timeout=2)
+ writer.close()
+ assert data, "re-bound tick socket gave no answer"
+ finally:
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
def test_transient_stall_below_wedge_budget_never_escalates(
self, tmp_path, monkeypatch
):