The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): persisted active_agents returns to zero after an owner turn
Tekniumda7eac48af50
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex ff3b78911f5..a5b554a2f12 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -219,6 +219,8 @@ class SessionAuthority:if live.task is None or live.task.done():live.task = asyncio.create_task(self._drain(ref))live.task.add_done_callback(_log_drain_failure)+ from gateway.session_runtime_workers import persist_work_count+ live.task.add_done_callback(lambda task: persist_work_count(self, task))def wake_after_worker(self, session_id):"""A worker execution on ``session_id`` (a logical owner or its compression continuation)diff --git a/gateway/session_bot_mailbox.py b/gateway/session_bot_mailbox.pyindex 66945ffb3b4..59f079b316e 100644--- a/gateway/session_bot_mailbox.py+++ b/gateway/session_bot_mailbox.py@@ -20,6 +20,8 @@ async def mailbox_lock(authority):yieldfinally:active.discard(task)+ from gateway.session_runtime_workers import persist_work_count+ persist_work_count(authority)async def _mailbox_io(operation, *args):diff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.pyindex 4e8b159c6aa..a0525d111d2 100644--- a/gateway/session_runtime_workers.py+++ b/gateway/session_runtime_workers.py@@ -23,6 +23,16 @@ def uncounted_runtime_work(runner):+ sum(len(mutation_tasks(authority)) for authority in authorities))+def persist_work_count(authority, _task=None):+ """Re-publish the runner's in-flight count when owner work it counts (a drain, a tracked+ mutation, a mailbox operation) ends: the agent-slot release that last wrote+ ``gateway_state.json`` ran while that work was still live, so without this write the+ persisted count never returns to zero."""+ persist = getattr(getattr(authority, 'runner', None), '_persist_active_agents', None)+ if persist is not None:+ persist()++def mutation_tasks(authority):tasks = {*getattr(authority, '_mutation_tasks', ()), *getattr(authority, '_bot_mailbox_operations', ())}return [task for task in tasks if not task.done()]@@ -38,6 +48,7 @@ def track_mutation(authority, operation):tasks.discard(done)if not done.cancelled():done.exception() # the observer may already have disconnected+ persist_work_count(authority)task.add_done_callback(finished)return taskdiff --git a/tests/gateway/test_runtime_worker_shutdown.py b/tests/gateway/test_runtime_worker_shutdown.pyindex a99929787a1..0f7c6beddb6 100644--- a/tests/gateway/test_runtime_worker_shutdown.py+++ b/tests/gateway/test_runtime_worker_shutdown.py@@ -137,3 +137,31 @@ async def test_unserve_keeps_ownership_without_aborting_the_reconcile(tmp_path,assert result['removed'] == ['stuck', 'gone']assert released == [gone] and closed == [gone], 'ownership of the stuck profile was released'assert runner._served_profile_homes == {}+++async def test_persisted_work_count_returns_to_zero_when_the_drain_ends():+ """gateway_state.json's active_agents is written at the agent-slot release, while the owner's+ drain (counted until it ends) is still live; the drain's end must write it again, or the+ persisted count stays at 1 after every messaging turn and the gateway never reads idle."""+ from gateway.session_authority import SessionAuthority+ from gateway.session_runtime_workers import uncounted_runtime_work++ persisted, release = [], asyncio.Event()+ authority = SessionAuthority.__new__(SessionAuthority)+ runner = SimpleNamespace(_running_agents={}, session_authority=authority,+ _persist_active_agents=lambda: persisted.append(uncounted_runtime_work(runner)))+ live = SimpleNamespace(task=None, route='route', event_stream=SimpleNamespace(execution={'execution_generation': 1}))+ authority.runner, authority.sessions, authority._managed_workers = runner, {'s': live}, {}++ async def drain(_ref):+ await release.wait()++ authority._drain = drain+ authority._schedule(SimpleNamespace(session_id='s'))+ await asyncio.sleep(0)+ assert uncounted_runtime_work(runner) == 1+ release.set()+ await live.task+ await asyncio.sleep(0)+ assert persisted and persisted[-1] == 0