Skip to content

The agent that grows with you

review: fail-awake work accounting + rename is_idle param to active_work_count

Ben Barclay021593052694
diff --git a/gateway/run.py b/gateway/run.py
index 55a212235ce..5b58e0001c9 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -8672,17 +8672,33 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
def _scale_to_zero_is_idle(self) -> bool:
from gateway.scale_to_zero import is_idle
- # _active_work_count(), NOT _running_agent_count(): cron jobs run
- # through a standalone AIAgent on the scheduler's own thread pool and
- # API-server runs live on the adapter — both entirely outside
- # _running_agents (the same blind spot as the #60432 shutdown drain).
- # Counting agents alone let the idle predicate read True DURING a
- # running cron job; a suspend then freezes the job mid-flight.
- # Observed live on staging 2026-08-20: is_idle held True throughout a
- # cron run at 10:45:04-22 — only watcher-tick timing (next tick 9s
- # after the job finished) avoided a mid-job freeze.
+ # The FULL work aggregate, not _running_agent_count(): cron jobs run
+ # on the scheduler's own thread pool and API-server runs live on the
+ # adapter — both outside _running_agents (the #60432 blind spot), so
+ # counting agents alone let a suspend land mid-cron-job.
+ #
+ # Fail-AWAKE accounting: the shared shutdown-drain counters
+ # (_active_cron_job_count/_active_api_run_count) swallow exceptions to
+ # 0, which is fine for a drain but unsafe for a suspend predicate — a
+ # transient read failure would make live work look idle and reopen the
+ # mid-job freeze. Here an unreadable source counts as work (sentinel 1)
+ # so the machine stays awake until the source is readable again.
+ try:
+ from cron.scheduler import get_running_job_ids
+
+ cron_count = len(get_running_job_ids())
+ except Exception: # noqa: BLE001 - unreadable source => assume busy
+ logger.debug("scale-to-zero: cron work count unreadable — staying awake", exc_info=True)
+ cron_count = 1
+ try:
+ adapter = getattr(self, "adapters", {}).get(Platform.API_SERVER)
+ helper = getattr(adapter, "active_agent_work_count", None)
+ api_count = max(0, int(helper())) if callable(helper) else 0
+ except Exception: # noqa: BLE001 - unreadable source => assume busy
+ logger.debug("scale-to-zero: api work count unreadable — staying awake", exc_info=True)
+ api_count = 1
return is_idle(
- running_agent_count=self._active_work_count(),
+ active_work_count=self._running_agent_count() + cron_count + api_count,
seconds_since_last_inbound=time.time() - self._last_inbound_at,
idle_timeout_seconds=self._scale_to_zero_idle_timeout_seconds(),
has_live_background_work=self._scale_to_zero_has_live_background_work(),
diff --git a/gateway/scale_to_zero.py b/gateway/scale_to_zero.py
index 60b68e9d019..4e16937c105 100644
--- a/gateway/scale_to_zero.py
+++ b/gateway/scale_to_zero.py
@@ -133,18 +133,25 @@ def should_arm(
def is_idle(
*,
- running_agent_count: int,
+ active_work_count: int,
seconds_since_last_inbound: float,
idle_timeout_seconds: float,
has_live_background_work: bool,
) -> bool:
"""The idle predicate (D2/D3/F7). Pure — composes the three conjuncts.
- Idle iff: no in-flight agent turn, no inbound within the timeout window, and
- no live background work (backgrounded delegate_task / kanban / bg terminal).
- Any active work keeps the gateway awake — suspending mid-flight would lose it.
+ Idle iff: no counted active work (in-flight agent turns + cron jobs +
+ API-server runs — the caller aggregates every foreground work source),
+ no inbound within the timeout window, and no live background work
+ (backgrounded delegate_task / kanban / bg terminal). Any active work
+ keeps the gateway awake — suspending mid-flight would lose it.
+
+ ``active_work_count`` deliberately names the BROAD aggregate, not just
+ agents: a caller passing only ``len(_running_agents)`` reopens the
+ mid-cron-job suspend hole. Callers that cannot read a work source must
+ fail AWAKE (pass a positive sentinel), never fail to 0.
"""
- if running_agent_count > 0:
+ if active_work_count > 0:
return False
if has_live_background_work:
return False
diff --git a/tests/gateway/test_scale_to_zero.py b/tests/gateway/test_scale_to_zero.py
index 570d4f5f17b..9fc6f11a9fb 100644
--- a/tests/gateway/test_scale_to_zero.py
+++ b/tests/gateway/test_scale_to_zero.py
@@ -71,7 +71,7 @@ def test_arm_blocked_without_wake_url():
def _idle_kwargs(**over):
base = dict(
- running_agent_count=0,
+ active_work_count=0,
seconds_since_last_inbound=600.0,
idle_timeout_seconds=300.0,
has_live_background_work=False,
@@ -81,7 +81,7 @@ def _idle_kwargs(**over):
def test_not_idle_with_running_agent():
- assert is_idle(**_idle_kwargs(running_agent_count=1)) is False
+ assert is_idle(**_idle_kwargs(active_work_count=1)) is False
def test_idle_exactly_at_threshold():
diff --git a/tests/gateway/test_scale_to_zero_watcher.py b/tests/gateway/test_scale_to_zero_watcher.py
index 35094df99b5..46e3c650e95 100644
--- a/tests/gateway/test_scale_to_zero_watcher.py
+++ b/tests/gateway/test_scale_to_zero_watcher.py
@@ -460,3 +460,38 @@ def test_active_api_run_blocks_idle(monkeypatch):
def test_idle_true_when_all_work_sources_quiet(monkeypatch):
r = _work_count_runner(monkeypatch)
assert r._scale_to_zero_is_idle() is True
+
+
+def test_unreadable_cron_source_fails_awake(monkeypatch):
+ """A transient failure reading the cron work source must count as WORK
+ (stay awake), not as idle — fail-open accounting would reopen the
+ mid-job-freeze hole exactly when bookkeeping is broken."""
+ r = _work_count_runner(monkeypatch)
+
+ def _boom():
+ raise RuntimeError("registry unavailable")
+
+ monkeypatch.setattr("cron.scheduler.get_running_job_ids", _boom)
+ assert r._scale_to_zero_is_idle() is False
+
+
+def test_unreadable_api_source_fails_awake(monkeypatch):
+ from types import SimpleNamespace
+
+ def _boom():
+ raise RuntimeError("adapter wedged")
+
+ r = _work_count_runner(monkeypatch)
+ from gateway.platforms.base import Platform
+
+ r.adapters = {Platform.API_SERVER: SimpleNamespace(active_agent_work_count=_boom)}
+ assert r._scale_to_zero_is_idle() is False
+
+
+def test_missing_api_adapter_is_not_work(monkeypatch):
+ """No api_server adapter at all (common: relay-only instance before the
+ key existed) is a NORMAL state, not an unreadable source — must not hold
+ the machine awake."""
+ r = _work_count_runner(monkeypatch)
+ r.adapters = {}
+ assert r._scale_to_zero_is_idle() is True