Skip to content

The agent that grows with you

fix(gateway): stop blocking the event loop — off-loop hot sites + ASYNC lint ratchet

kshitijk4poorc0ff25a1f876
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.py
index f13dddd1c29..1ff741f1e25 100644
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@ -1382,7 +1382,14 @@ class WebhookAdapter(BasePlatformAdapter):
)
try:
- result = subprocess.run(
+ # Off-loop: `gh` does network I/O and can take its full 30s
+ # timeout. Running it inline froze every adapter and timer on
+ # the gateway event loop for the duration (Pattern A, #91912
+ # class). asyncio.to_thread keeps the loop serving while the
+ # subprocess runs; the worker thread is bounded by the
+ # subprocess timeout below.
+ result = await asyncio.to_thread(
+ subprocess.run,
[
"gh",
"pr",
diff --git a/gateway/run.py b/gateway/run.py
index 79383c25dca..1634a8e858f 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -31290,7 +31290,10 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
if not _pid_exists(existing_pid):
old_gateway_exited = True
break # Process is gone
- time.sleep(0.5)
+ # start_gateway is async: a blocking sleep here froze the
+ # event loop (signal handlers, health checks, every other
+ # coroutine) for up to 10s per replacement (#36163).
+ await asyncio.sleep(0.5)
else:
# Still alive after 10s — force kill
logger.warning(
@@ -31314,7 +31317,8 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
if not _pid_exists(existing_pid):
old_gateway_exited = True
break
- time.sleep(0.25)
+ # Async context — never block the loop (#36163).
+ await asyncio.sleep(0.25)
if not old_gateway_exited:
logger.error(
"Old gateway (PID %d) still appears alive after SIGKILL; "
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index bb7d451cd4a..88078335f7a 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -4799,9 +4799,16 @@ class GatewaySlashCommandsMixin:
temp_dir = tempfile.mkdtemp(prefix="hermes_save_")
temp_path = os.path.join(temp_dir, filename)
try:
- content = render_session_for_save(export_data, fmt)
- with open(temp_path, "w", encoding="utf-8") as f:
- f.write(content)
+ # Off-loop: rendering a long session and writing it to disk are
+ # CPU/disk-bound and scale with transcript size (multi-MB for
+ # long sessions). Inline they stall every other chat on the
+ # gateway event loop (Pattern A). One thread hop covers both.
+ def _render_and_write() -> None:
+ rendered = render_session_for_save(export_data, fmt)
+ with open(temp_path, "w", encoding="utf-8") as f:
+ f.write(rendered)
+
+ await asyncio.to_thread(_render_and_write)
adapter = self.get_adapter(source.platform)
if adapter:
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 73b2014e8e9..9aad4fd8e43 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -5576,16 +5576,23 @@ async def speak_text(payload: TTSSpeakRequest, profile: Optional[str] = None):
".flac": "audio/flac",
}.get(ext, "audio/mpeg")
+ def _read_and_unlink() -> bytes:
+ # Off-loop: synthesized audio can be several MB; reading it inline
+ # blocks the uvicorn event loop (Pattern A). Unlink rides the same
+ # thread hop so the temp file cannot outlive an early return.
+ try:
+ with open(file_path, "rb") as fh:
+ return fh.read()
+ finally:
+ try:
+ os.unlink(file_path)
+ except OSError:
+ pass
+
try:
- with open(file_path, "rb") as fh:
- audio_bytes = fh.read()
+ audio_bytes = await asyncio.to_thread(_read_and_unlink)
except OSError as exc:
raise HTTPException(status_code=500, detail=f"Could not read audio: {exc}")
- finally:
- try:
- os.unlink(file_path)
- except OSError:
- pass
encoded = base64.b64encode(audio_bytes).decode("ascii")
return {
diff --git a/pyproject.toml b/pyproject.toml
index d1f213e492e..8d132447943 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -497,12 +497,44 @@ preview = true # required for PLW1514 (unspecified-encoding) — preview rule
# which silently corrupts any non-ASCII file content. We had three
# separate Windows sandbox regressions in one debug session before
# adding the explicit encoding. This rule keeps new code honest.
-select = ["PLW1514"]
+#
+# ASYNC210/220/221/251: blocking calls inside `async def` freeze the whole
+# gateway/uvicorn event loop — every adapter, timer, and health check stops
+# until the call returns. Real incidents: a 17-minute getaddrinfo hang took
+# the backend down (#91912); `time.sleep` in start_gateway froze restarts
+# for 10s (#36163). The fix pattern is `await asyncio.to_thread(...)` (or
+# `loop.run_in_executor`), `asyncio.create_subprocess_exec`, and
+# `await asyncio.sleep`. These four are the direct freeze vectors:
+# ASYNC210 — blocking HTTP call in async fn (urllib/requests/httpx-sync)
+# ASYNC220 — subprocess.Popen in async fn
+# ASYNC221 — subprocess.run / os.system in async fn
+# ASYNC251 — time.sleep in async fn
+# ASYNC230 (blocking open()) and ASYNC240 (blocking path methods) are real
+# but ~180 legacy sites deep; they graduate to this list once the backlog
+# is burned down (see per-file-ignores below for the frozen baseline).
+select = ["PLW1514", "ASYNC210", "ASYNC220", "ASYNC221", "ASYNC251"]
[tool.ruff.lint.per-file-ignores]
# Tests can intentionally exercise locale-encoding edge cases.
-"tests/**" = ["PLW1514"]
+"tests/**" = ["PLW1514", "ASYNC210", "ASYNC220", "ASYNC221", "ASYNC251"]
# Skills and plugins are partially user-authored — their own conventions.
"skills/**" = ["PLW1514"]
"optional-skills/**" = ["PLW1514"]
+# Plugin platform adapters run ON the gateway event loop — the ASYNC gate
+# applies to them with full force; only PLW1514 stays relaxed.
"plugins/**" = ["PLW1514"]
+# ---------------------------------------------------------------------------
+# ASYNC ratchet baseline — legacy blocking sites that predate the gate.
+# Each entry is an EXISTING violation being fixed in its own PR; do NOT add
+# new files here. Remove the entry when the file's sites are fixed.
+# ---------------------------------------------------------------------------
+# Detached restart watchers: Popen of a fully-detached, fire-and-forget
+# process (no wait), an accepted momentary spawn cost pending a dedicated
+# async-subprocess sweep.
+"gateway/run.py" = ["ASYNC220"]
+"gateway/slash_commands.py" = ["ASYNC220"]
+# Off-loop sweep for these routers is in flight (PR #84376).
+"hermes_cli/web_routers/profiles.py" = ["ASYNC220", "ASYNC221"]
+# Legacy blocking spawn sites in platform adapters, pending their own fixes.
+"plugins/platforms/whatsapp/adapter.py" = ["ASYNC220", "ASYNC221"]
+"plugins/platforms/photon/adapter.py" = ["ASYNC220"]
diff --git a/tests/gateway/test_webhook_offloop_delivery.py b/tests/gateway/test_webhook_offloop_delivery.py
new file mode 100644
index 00000000000..c33083e9d35
--- /dev/null
+++ b/tests/gateway/test_webhook_offloop_delivery.py
@@ -0,0 +1,96 @@
+"""Event-loop liveness for webhook GitHub-comment delivery (Pattern A).
+
+``_deliver_github_comment`` shells out to ``gh`` with a 30s timeout. Before
+the off-loop fix it called ``subprocess.run`` inline from an ``async def``,
+freezing the entire gateway event loop — every adapter, timer, and health
+check — for up to the full timeout while the network call ran.
+
+The contract under test is behavioral, not structural: while delivery is
+awaiting the subprocess, OTHER coroutines on the same loop must keep
+running. A ticker coroutine sampled at the moment delivery returns proves
+it — on the blocking implementation it manages ~1 tick during a 1-second
+``gh`` run; off-loop it manages ~20.
+"""
+
+import asyncio
+import os
+import stat
+import sys
+
+import pytest
+
+from gateway.platforms.webhook import WebhookAdapter
+
+
+def fake_gh(tmp_path, monkeypatch):
+ """A ``gh`` stub that sleeps 1s then succeeds, prepended to PATH."""
+ if sys.platform.startswith("win"):
+ pytest.skip("POSIX shell stub")
+ gh = tmp_path / "gh"
+ gh.write_text("#!/bin/bash\nsleep 1\necho posted\nexit 0\n", encoding="utf-8")
+ gh.chmod(gh.stat().st_mode | stat.S_IXUSR)
+ monkeypatch.setenv("PATH", f"{tmp_path}{os.pathsep}{os.environ['PATH']}")
+ return gh
+
+
+class TestGithubCommentDeliveryOffLoop:
+ @pytest.mark.asyncio
+ async def test_loop_stays_live_during_gh_subprocess(self, fake_gh):
+ """Concurrent coroutines keep ticking while ``gh`` runs (~1s)."""
+ adapter = WebhookAdapter.__new__(WebhookAdapter)
+
+ ticks = []
+ stop = False
+
+ async def ticker():
+ while not stop:
+ ticks.append(1)
+ await asyncio.sleep(0.05)
+
+ task = asyncio.create_task(ticker())
+ await asyncio.sleep(0) # let the ticker take its first turn
+
+ result = await adapter._deliver_github_comment(
+ "test body",
+ {"deliver_extra": {"repo": "owner/repo", "pr_number": "1"}},
+ )
+ ticks_during_delivery = len(ticks)
+
+ stop = True
+ try:
+ await asyncio.wait_for(task, timeout=2)
+ except asyncio.TimeoutError:
+ task.cancel()
+
+ assert result.success is True
+ # Blocking implementation: ~1 tick (loop frozen for the 1s gh run).
+ # Off-loop implementation: ~20 ticks. 10 is a comfortable midpoint
+ # that stays robust on slow CI runners.
+ assert ticks_during_delivery >= 10, (
+ f"event loop starved during gh delivery: only "
+ f"{ticks_during_delivery} ticker turns ran in ~1s"
+ )
+
+ @pytest.mark.asyncio
+ async def test_delivery_result_faithful_off_loop(self, fake_gh):
+ """Off-loop offload must not change the SendResult contract."""
+ adapter = WebhookAdapter.__new__(WebhookAdapter)
+ result = await adapter._deliver_github_comment(
+ "body",
+ {"deliver_extra": {"repo": "owner/repo", "pr_number": "7"}},
+ )
+ assert result.success is True
+
+ @pytest.mark.asyncio
+ async def test_invalid_inputs_still_rejected_before_subprocess(self):
+ """Validation short-circuits stay synchronous and unchanged."""
+ adapter = WebhookAdapter.__new__(WebhookAdapter)
+ bad_repo = await adapter._deliver_github_comment(
+ "body", {"deliver_extra": {"repo": "not a repo!", "pr_number": "1"}}
+ )
+ assert bad_repo.success is False
+ bad_pr = await adapter._deliver_github_comment(
+ "body", {"deliver_extra": {"repo": "owner/repo", "pr_number": "-2"}}
+ )
+ assert bad_pr.success is False