Skip to content

The agent that grows with you

fix(gateway): count API-server runs before the adapters are released; include deferred workers

kshitijk4poord66be7649152
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index ce8714ea7fe..cdf668f5cc5 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -156,6 +156,9 @@ class GatewayShutdownMixin:
active_agents: dict = dataclasses.field(default_factory=dict)
timed_out: bool = False
drain_elapsed: float = 0.0
+ # API-server runs still live when the adapters were released; the adapter map is empty by the
+ # time the SessionDB close gate runs, so the count has to be taken before ``adapters.clear()``.
+ api_live: int = 0
def elapsed(self) -> float:
return time.monotonic() - self.started_at
@@ -1837,6 +1840,7 @@ class GatewayShutdownMixin:
# CancelledError into this _stop_impl and skip _shutdown_event.set() / _exit_code = 75 (#12875). It
# self-terminates anyway.
self._background_tasks.clear()
+ ctx.api_live = self._active_api_run_count()
self.adapters.clear()
for _session_key in list(self._running_agents):
self._release_running_agent_state(_session_key)
@@ -1907,15 +1911,18 @@ class GatewayShutdownMixin:
)
return
logger.info("Shutdown phase: executor quiesced at +%.2fs", ctx.elapsed())
- # Cron jobs run on the scheduler's own pool and API-server runs on the loop's default executor,
- # not self._executor, so the join above never sees them. A writer that outlived the drain is
- # mid-write for the same #101093 reasons; the drain already spent its budget, so no second wait —
- # leave the handles open (#102198).
- _outside_live = self._active_cron_job_count() + self._active_api_run_count()
- if _outside_live:
+ # Cron jobs (scheduler pool), API-server runs and deferred hygiene workers (both on the loop's
+ # default executor) never touch self._executor, so the join above cannot see them. A writer that
+ # outlived the drain is mid-write for the same #101093 reasons; the drain already spent its
+ # budget, so no second wait — leave the handles open (#102198). The API count is the snapshot
+ # taken before the adapters were released; a run whose handler task was cancelled at disconnect
+ # has already left it, so this term under-counts rather than over-counts.
+ _cron_live, _api_live, _deferred_live = self._active_cron_job_count(), ctx.api_live, ctx.deferred_count()
+ if _cron_live or _api_live or _deferred_live:
logger.warning(
- "Shutdown phase: %d cron/API-server job(s) still running after the drain — skipping the "
- "SessionDB close/checkpoint, leaving state.db open for the live writer (#102198)", _outside_live,
+ "Shutdown phase: %d cron job(s) / %d API-server run(s) / %d deferred worker(s) still running "
+ "after the executor quiesce — skipping the SessionDB close/checkpoint, leaving state.db open "
+ "for the live writer (#102198)", _cron_live, _api_live, _deferred_live,
)
return
_step = GatewayShutdownMixin._quiet_step
diff --git a/tests/gateway/test_shutdown_executor_quiesce.py b/tests/gateway/test_shutdown_executor_quiesce.py
index 225a19a10c9..ad54c4c2362 100644
--- a/tests/gateway/test_shutdown_executor_quiesce.py
+++ b/tests/gateway/test_shutdown_executor_quiesce.py
@@ -78,8 +78,10 @@ class _FakeGateway:
def _active_cron_job_count(self):
return 0
- def _active_api_run_count(self):
- return 0
+ # Real hook + counter: 0 while ``adapters`` is empty, the API-server count once a fake adapter is in.
+ _api_server_hook = gw_mod.GatewayShutdownMixin._api_server_hook
+ _active_api_run_count = gw_mod.GatewayShutdownMixin._active_api_run_count
+ _active_deferred_agent_worker_count = gw_mod.GatewayShutdownMixin._active_deferred_agent_worker_count
def _update_runtime_status(self, *_a, **_kw):
pass
@@ -213,12 +215,38 @@ async def test_stuck_worker_skips_the_session_db_close():
assert "worker_write" in events, "worker never finished"
+def _arm_cron(gw):
+ gw._active_cron_job_count = lambda: 1
+
+
+def _arm_api(gw):
+ # Through the real hook: the adapter map is cleared one phase before the close gate, so the
+ # gate must use the count taken before the clear, not a live lookup.
+ from gateway.config import Platform
+
+ class _ApiAdapter:
+ def active_agent_work_count(self):
+ return 1
+
+ async def _teardown(adapter, platform, *, profile=None):
+ pass # the run keeps going on the default executor after the transport is torn down
+
+ gw.adapters[Platform.API_SERVER] = _ApiAdapter()
+ gw._bounded_adapter_teardown = _teardown
+
+
+def _arm_deferred(gw):
+ # A hygiene worker on the loop's default executor, never finished.
+ gw._deferred_agent_workers = {asyncio.get_event_loop().create_future(): object()}
+
+
@pytest.mark.asyncio
[email protected]("counter", ["_active_cron_job_count", "_active_api_run_count"])
-async def test_live_writer_outside_the_executor_skips_the_session_db_close(monkeypatch, counter):
- """A cron job or API-server run that outlived the drain must not have state.db closed under it (#102198).
[email protected]("arm", [_arm_cron, _arm_api, _arm_deferred], ids=["cron", "api", "deferred"])
+async def test_live_writer_outside_the_executor_skips_the_session_db_close(monkeypatch, arm):
+ """A cron job, API-server run or deferred worker that outlived the drain must not have state.db
+ closed under it (#102198).
- Both run outside ``self._executor`` (scheduler pool / loop default executor), so the executor
+ None of them run on ``self._executor`` (scheduler pool / loop default executor), so the executor
join above the close block never sees them; the close has to consult their counters too.
The executor must still be sealed on this path (#101118).
"""
@@ -226,7 +254,7 @@ async def test_live_writer_outside_the_executor_skips_the_session_db_close(monke
events = []
gw = _FakeGateway(events)
- monkeypatch.setattr(gw, counter, lambda: 1)
+ arm(gw)
monkeypatch.setattr(
hermes_state_registry, "close_all", lambda: events.append("close_all") or 0
)
@@ -234,7 +262,7 @@ async def test_live_writer_outside_the_executor_skips_the_session_db_close(monke
await gw_mod.GatewayRunner.stop(gw)
assert "close:session_db" not in events and "close_all" not in events, (
- f"SessionDB closed despite a live {counter} writer: {events}"
+ f"SessionDB closed despite a live {arm.__name__[5:]} writer: {events}"
)
assert gw._executor_closing is True, "executor left unsealed on the outside-writer path"