Skip to content

The agent that grows with you

fix(gateway): release a one-turn agent once its turn ends

Tekniumacb633c952e7
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index 1674e201f54..d1d86da165e 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -314,6 +314,12 @@ class GatewayAgentCacheMixin:
# One structured reset instead of a drifting pop-list. Turn-lease tokens are deliberately NOT
# cleared here — _release_turn_lease owns them.
state.turn.clear()
+ retired, state.turn.retired_agents = state.turn.retired_agents, []
+ for agent in retired:
+ # Evicted mid-turn (a one-turn agent): its turn no longer uses it.
+ self._spawn_release_thread(self._release_evicted_agent_soft, (agent,),
+ f"agent-retire-{str(session_key)[:24]}", inline_fallback=True,
+ session_key=session_key)
# Turn boundary: a running-agent slot was just released; persist the new (lower) in-flight count
# so the dashboard readout stays current. Preserves gateway_state (see _persist_active_agents).
self._persist_active_agents()
@@ -813,7 +819,8 @@ class GatewayAgentCacheMixin:
)
return hashlib.sha256(repr(key_tuple).encode("utf-8")).hexdigest()
- def _evict_cached_agent(self, session_key: str, *, commit_memory: bool = False) -> None:
+ def _evict_cached_agent(self, session_key: str, *, commit_memory: bool = False,
+ release_after_turn: bool = False) -> None:
"""Remove a cached agent (/new, /model, ...) and soft-release its LLM client pool (AIAgent
holds reference cycles; without it RSS grows across /new). Soft = frees clients and child
subagents but PRESERVES terminal sandbox / browser / bg processes since the session may
@@ -825,6 +832,9 @@ class GatewayAgentCacheMixin:
reference cycles (callbacks, tool state) that delay refcount collection, so a manual release is
required to keep gateway RSS flat across many /new, /model, undo and reset operations (#29298, same
leak class as #25315).
+
+ ``release_after_turn``: an agent still mid-turn is released when that turn's running slot
+ clears (``_release_running_agent_state``) instead of being left to the garbage collector.
"""
from gateway.run import _AGENT_PENDING_SENTINEL
# Prompt-stability state rides the agent-cache lifecycle: a fresh agent must re-render its
@@ -846,7 +856,11 @@ class GatewayAgentCacheMixin:
evicted = _cache.pop(session_key, None)
agent = _first_agent(evicted)
# Never tear down an agent that's mid-turn — its client, sandbox and child subagents are in use.
- if agent is None or agent is _AGENT_PENDING_SENTINEL or id(agent) in self._running_agent_ids():
+ if agent is None or agent is _AGENT_PENDING_SENTINEL:
+ return
+ if id(agent) in self._running_agent_ids():
+ if release_after_turn and state is not None:
+ state.turn.retired_agents.append(agent)
return
if commit_memory:
target, args = self._commit_then_release_soft, (agent, session_key, True)
diff --git a/gateway/session_local_inventory.py b/gateway/session_local_inventory.py
index 9e983a574e7..ae9bbb44a06 100644
--- a/gateway/session_local_inventory.py
+++ b/gateway/session_local_inventory.py
@@ -227,7 +227,8 @@ def publish_settled_info(turn, agent) -> None:
A ``model_override`` admission (``/model --once``, ``/moa``) built its agent on the one-turn
route. That agent must not become the route Desktop, the TUI, and resume read. Drop it from
- the cache and publish the policy model and provider."""
+ the cache (released once this turn's running slot clears) and publish the policy model and
+ provider."""
if agent is None:
return
with contextlib.suppress(Exception):
@@ -245,7 +246,7 @@ def publish_settled_info(turn, agent) -> None:
evict = getattr(getattr(turn, "_runner", None), "_evict_cached_agent", None)
if live is not None and callable(evict):
try:
- evict(live.route)
+ evict(live.route, release_after_turn=True)
except Exception:
logger.debug("one-turn agent cache drop failed", exc_info=True)
ref = SessionRef(authority.profile_id, session_id)
diff --git a/gateway/session_state.py b/gateway/session_state.py
index 4e36b8a7aba..2033fc0d2cd 100644
--- a/gateway/session_state.py
+++ b/gateway/session_state.py
@@ -31,6 +31,9 @@ class TurnState:
# token for their own generation, so a displaced turn's unwind frees only its own lease and
# never a successor's (an evicted turn and its replacement may both hold one briefly).
lease_tokens: dict[int, Any] = field(default_factory=dict)
+ # Agents taken out of the cache while this turn still ran them (a one-turn ``model_override``
+ # agent): ``_release_running_agent_state`` releases them once the slot clears.
+ retired_agents: list[Any] = field(default_factory=list)
def clear(self) -> None:
"""Reset the per-turn slot. The caller pops ``lease`` first to release it."""
diff --git a/tests/gateway/test_one_turn_route_publish.py b/tests/gateway/test_one_turn_route_publish.py
index 4ede20117ca..ba0c1e4f7d0 100644
--- a/tests/gateway/test_one_turn_route_publish.py
+++ b/tests/gateway/test_one_turn_route_publish.py
@@ -15,7 +15,7 @@ def test_settled_info_publishes_the_policy_route_and_drops_the_cached_agent(monk
turn = SimpleNamespace(
_ctx=SimpleNamespace(inbound_message_id="adm", session_key="route-1"),
_approval_owner=(authority, "s", 1),
- _runner=SimpleNamespace(_evict_cached_agent=lambda key: evicted.append(key)),
+ _runner=SimpleNamespace(_evict_cached_agent=lambda key, **_k: evicted.append(key)),
_publish_execution=lambda kind, payload: published.append((kind, payload)),
)
agent = SimpleNamespace(model="once-model", provider="anthropic", tools=None, _cached_system_prompt="",
@@ -84,3 +84,57 @@ def test_same_provider_override_reshapes_the_opencode_endpoint_for_its_wire(monk
monkeypatch, "opencode-zen", "minimax-m2.7", "anthropic_messages", "https://opencode.ai/zen",
{"base_url": "https://opencode.ai/zen/v1", "api_mode": "chat_completions"})
assert (runtime["api_mode"], runtime["base_url"]) == ("anthropic_messages", "https://opencode.ai/zen")
+
+
+def _running_runner(route, agent):
+ """A real ``GatewayRunner`` whose cache holds *agent* while its turn still owns the running slot."""
+ import threading
+ from collections import OrderedDict
+ from gateway.run import GatewayRunner
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner._agent_cache = OrderedDict()
+ runner._agent_cache_lock = threading.Lock()
+ runner._agent_cache[route] = (agent, "sig-once", 0, "s")
+ runner._running_agents[route] = agent
+ runner._persist_active_agents = lambda: None
+ return runner
+
+
+def test_a_one_turn_agent_is_released_once_its_running_slot_clears(monkeypatch):
+ """Review of #140969: evicting the one-turn agent while its turn still ran skipped the release
+ (``_evict_cached_agent`` never tears down a running agent) and nothing retried it, so its clients
+ (and a Codex app-server child) outlived every sweep."""
+ import threading
+ from unittest.mock import MagicMock
+ from gateway import session_local, session_policy
+ from gateway.session_local_inventory import publish_settled_info
+ from tests.waiting import wait_until
+ route = "agent:main:local:dm:s"
+ agent = MagicMock()
+ agent.model, agent.provider, agent.tools, agent._cached_system_prompt = "once-model", "anthropic", None, ""
+ agent.context_compressor = None
+ released = threading.Event()
+ agent.release_clients.side_effect = lambda: released.set()
+ runner = _running_runner(route, agent)
+ live = SimpleNamespace(route=route, source=SimpleNamespace())
+ authority = SimpleNamespace(profile_id="p", sessions={"s": live}, runner=runner)
+ published = []
+ turn = SimpleNamespace(_ctx=SimpleNamespace(inbound_message_id="adm", session_key=route),
+ _approval_owner=(authority, "s", 1), _runner=runner,
+ _publish_execution=lambda kind, payload: published.append(payload))
+ policy = SimpleNamespace(current_model=lambda _a: "session-model", provider="openrouter")
+ monkeypatch.setattr(session_local, "local_session_info", lambda *_a, **_k: {"model": "once-model"})
+ monkeypatch.setattr(session_policy, "policy_for_source", lambda *_a, **_k: policy)
+
+ with cli_turn_scope("adm", {"model_override": {"model": "once-model", "provider": "anthropic"}}):
+ publish_settled_info(turn, agent)
+
+ assert published, "session.info was not published"
+ # Out of the cache at once, so nothing (resume, Desktop) reads the one-turn route off it ...
+ assert route not in runner._agent_cache
+ # ... and not torn down while its turn still runs.
+ assert not agent.release_clients.called
+ runner._release_running_agent_state(route) # the turn ends
+ assert wait_until(released.is_set, timeout=5, what="the one-turn agent was released")
+ assert agent.release_clients.call_count == 1
+