Skip to content

The agent that grows with you

fix(gateway): route loop-wakeup DB calls through the context-preserving executor

kshitijk4poor98428d20bc8d
diff --git a/gateway/run.py b/gateway/run.py
index 0cd9bdbd2c3..bebb709220f 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -24715,15 +24715,17 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# init on the loop thread before the first read.
await self._warm_goals_session_db("loop wakeup")
- # Run list_active_loops() in an executor to avoid blocking the event loop.
- # list_active_loops() calls list_meta_prefix() which acquires self._lock,
- # and that lock is also held by writers doing BEGIN IMMEDIATE and periodic
- # FTS5-merge/WAL-checkpoint work. A slow write holding the lock while the
- # watcher blocks the entire event loop on the same lock froze it for 90+
- # seconds until the liveness watchdog force-exited. Moving this off the
- # loop thread prevents the freeze.
- loop = asyncio.get_running_loop()
- active_loops = await loop.run_in_executor(None, list_active_loops)
+ # Every SessionDB call in this scan runs off the loop thread.
+ # fire_tick()/complete_tick() are writes (BEGIN IMMEDIATE) that
+ # take the writer lock; a slow writer elsewhere (FTS merge, WAL
+ # checkpoint, a long flush) holding it while the watcher blocked
+ # the loop on the same lock froze the gateway for 90+ s until
+ # the liveness watchdog force-exited. list_active_loops() reads
+ # via _read_ctx (lock-free under WAL) but still convoys on the
+ # writer lock when WAL is unavailable, so it goes off-loop too.
+ # _run_in_executor_with_context keeps the profile HERMES_HOME
+ # override alive under multiplex, like the warm-up above.
+ active_loops = await self._run_in_executor_with_context(list_active_loops)
now = time.time()
for sid, state in active_loops:
@@ -24774,10 +24776,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
mgr = LoopManager(session_id=sid)
if not mgr.is_due(now):
continue
- # fire_tick() is a write (BEGIN IMMEDIATE) that acquires self._lock,
- # same contention source as list_meta_prefix(). Run it in an executor
- # to avoid blocking the event loop.
- wakeup = await loop.run_in_executor(None, mgr.fire_tick)
+ wakeup = await self._run_in_executor_with_context(mgr.fire_tick)
if not wakeup:
continue
try:
@@ -24797,10 +24796,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# path and never hit the post-turn completion hook —
# complete the tick immediately (caps + scheduling).
if wakeup.lstrip().startswith("/"):
- # complete_tick() is a write (BEGIN IMMEDIATE) that acquires
- # self._lock, same contention source as list_meta_prefix().
- # Run it in an executor to avoid blocking the event loop.
- await loop.run_in_executor(None, mgr.complete_tick, "")
+ await self._run_in_executor_with_context(mgr.complete_tick, "")
except Exception as exc:
logger.warning("loop wakeup injection failed for %s: %s", sid, exc)
try:
diff --git a/tests/gateway/test_loop_command.py b/tests/gateway/test_loop_command.py
index 7e8caee8fc1..b6a920e446d 100644
--- a/tests/gateway/test_loop_command.py
+++ b/tests/gateway/test_loop_command.py
@@ -1,6 +1,8 @@
"""Gateway /loop command tests — dispatch, routing capture, mid-run guard."""
+import asyncio
import logging
+import threading
import time
from unittest.mock import AsyncMock, Mock
@@ -255,3 +257,69 @@ async def test_post_turn_session_resolution_failure_is_logged(loop_env, caplog):
)
assert "post-turn session resolution failed: store unavailable" in caplog.text
+
+
+async def test_loop_wakeup_watcher_keeps_event_loop_responsive_under_writer_lock(loop_env):
+ """The wakeup scan's SessionDB calls (list_active_loops / fire_tick /
+ complete_tick) must run off the loop thread. A slow writer holding the
+ SessionDB writer lock used to block the whole gateway event loop for the
+ duration of the hold (#92413)."""
+ runner = _make_runner()
+ runner._running = True
+ runner._running_agents = {}
+ runner.adapters = {}
+
+ # Persist an active loop that is due now, routed to a platform with no
+ # adapter (so the scan exits after list_active_loops(), before fire_tick).
+ await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m poll CI"))
+ state = loops.load_loop("sid-gateway-loop")
+ state.next_due_at = time.time() - 1
+ loops.save_loop("sid-gateway-loop", state)
+
+ db = loops._get_session_db()
+ hold_s = 0.6
+ released = threading.Event()
+
+ def _hold_writer_lock():
+ with db._lock:
+ time.sleep(hold_s)
+ released.set()
+
+ # Force the read path onto the writer lock (non-WAL degradation) so the
+ # test binds the offload regardless of the host SQLite's WAL support.
+ db._wal_active = False
+
+ # One scan only: patch asyncio.sleep inside the watcher to stop the loop
+ # after the first iteration.
+ orig_sleep = asyncio.sleep
+ calls = {"n": 0}
+
+ async def _one_pass_sleep(delay):
+ calls["n"] += 1
+ if calls["n"] >= 2: # first call is the 5s connect grace, second ends the scan
+ runner._running = False
+ return await orig_sleep(0)
+
+ holder = threading.Thread(target=_hold_writer_lock)
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(asyncio, "sleep", _one_pass_sleep)
+ holder.start()
+ time.sleep(0.05) # ensure the lock is held before the scan starts
+ watcher = asyncio.ensure_future(GatewayRunner._loop_wakeup_watcher(runner, interval=0))
+
+ # Heartbeat coroutine: measures the longest gap between loop turns
+ # while the watcher is (supposedly) blocked in the executor.
+ gaps = []
+ last = time.monotonic()
+ while not watcher.done():
+ await orig_sleep(0.01)
+ now = time.monotonic()
+ gaps.append(now - last)
+ last = now
+ await watcher
+ holder.join()
+
+ assert released.is_set()
+ # If the DB call ran on the loop thread, one heartbeat gap would be ~hold_s.
+ assert max(gaps) < hold_s / 2, f"event loop stalled for {max(gaps):.3f}s"