Skip to content

The agent that grows with you

fix: managed worker drains pending memory work before retiring the agent

Tekniumc17c686802d1
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index dc4b5eb886c..1bf3b02cad4 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -190,6 +190,11 @@ def retire_agent(agent):
"""A settled admission is a turn boundary, not the end of the session: the owner's
in-process agent keeps its background processes, sandbox and browser between turns
(release_clients), so the worker must too. Only memory extraction is turn-final work."""
+ # A boundary task queued this turn (LLM-bound extraction) would be cancelled by the
+ # provider shutdown's short drain; give it the same bounded head start cli_shutdown does.
+ manager = getattr(agent, '_memory_manager', None)
+ if manager is not None:
+ manager.flush_pending(timeout=10)
messages = getattr(agent, '_session_messages', None)
agent.shutdown_memory_provider(messages if isinstance(messages, list) else None)
agent.release_clients()
diff --git a/tests/gateway/test_managed_worker_retire.py b/tests/gateway/test_managed_worker_retire.py
new file mode 100644
index 00000000000..d41588a58c3
--- /dev/null
+++ b/tests/gateway/test_managed_worker_retire.py
@@ -0,0 +1,25 @@
+"""A managed worker's turn-final memory work drains before the provider shuts down."""
+
+
+def test_retire_agent_flushes_pending_memory_before_shutdown():
+ from agent.managed_worker import retire_agent
+
+ calls = []
+
+ class Manager:
+ def flush_pending(self, timeout=None):
+ calls.append(('flush', timeout))
+ return True
+
+ class Agent:
+ _memory_manager = Manager()
+ _session_messages = [{'role': 'user', 'content': 'hi'}]
+
+ def shutdown_memory_provider(self, messages):
+ calls.append(('shutdown', len(messages)))
+
+ def release_clients(self):
+ calls.append(('release',))
+
+ retire_agent(Agent())
+ assert calls == [('flush', 10), ('shutdown', 1), ('release',)]