Skip to content

The agent that grows with you

fix(gateway): reset and compress commit memory before evicting the agent

erosika6babbba26f78
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index be24d79f3d0..e66045453a7 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -634,7 +634,7 @@ class GatewayAgentCacheMixin:
)
return hashlib.sha256(repr(key_tuple).encode("utf-8")).hexdigest()
- def _evict_cached_agent(self, session_key: str) -> None:
+ def _evict_cached_agent(self, session_key: str, *, commit_memory: 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
@@ -669,10 +669,17 @@ class GatewayAgentCacheMixin:
# 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():
return
- self._spawn_release_thread(
- self._release_evicted_agent_soft, (agent,), f"agent-evict-{str(session_key)[:24]}", inline_fallback=True,
- session_key=session_key,
- )
+ if commit_memory:
+ target, args = self._commit_then_release_soft, (agent, session_key)
+ else:
+ target, args = self._release_evicted_agent_soft, (agent,)
+ self._spawn_release_thread(target, args, f"agent-evict-{str(session_key)[:24]}", inline_fallback=True,
+ session_key=session_key)
+
+ def _evict_cached_agent_at_boundary(self, session_key: str) -> None:
+ """Reset and compress end the conversation the provider was tracking, so the old agent's
+ transcript is committed (``on_session_end``) before its clients go; a plain evict is not."""
+ self._evict_cached_agent(session_key, commit_memory=True)
def _spawn_release_thread(self, target, args: tuple, name: str, *, inline_fallback: bool,
session_key: Optional[str] = None) -> None:
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index f6246434080..5e97d8a5657 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -114,7 +114,9 @@ async def mutate_session(authority, actor, ref, params):
if operation in {'reset', 'compress'}:
from gateway.session_local_recovery import restore_local_session
restore_local_session(authority, ref.session_id)
- authority.runner._evict_cached_agent(authority.sessions[ref.session_id].route)
+ # A session boundary, not a resource evict: memory providers get on_session_end first.
+ evict = getattr(authority.runner, '_evict_cached_agent_at_boundary', None) or authority.runner._evict_cached_agent
+ evict(authority.sessions[ref.session_id].route)
# Publish the prepared entry, not just its target ID, so fresh-reset and
# per-session counters match cold recovery in this process too.
from hermes_state_local import local_receipt
diff --git a/tests/gateway/test_boundary_evict_commits_memory.py b/tests/gateway/test_boundary_evict_commits_memory.py
new file mode 100644
index 00000000000..80878cfa7e9
--- /dev/null
+++ b/tests/gateway/test_boundary_evict_commits_memory.py
@@ -0,0 +1,83 @@
+"""``/new`` and ``/compress`` are session boundaries for memory providers, not resource evictions."""
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+# session.create's resume path imports this lazily mid-request; importing it whole here keeps the
+# conftest server-state fixture from meeting a half-initialized module at teardown.
+import tui_gateway.server # noqa: F401
+from gateway.run import GatewayRunner
+
+
+def _runner(monkeypatch):
+ runner = GatewayRunner.__new__(GatewayRunner)
+ import threading
+ runner._agent_cache = {}
+ runner._agent_cache_lock = threading.Lock()
+ runner._peek_session_state = lambda key: None
+ runner._running_agent_ids = lambda: set()
+ # Run releases inline so the order of commit and release is observable.
+ monkeypatch.setattr(runner, '_spawn_release_thread',
+ lambda target, args, name, *, inline_fallback, session_key=None: target(*args))
+ return runner
+
+
+def _agent(calls):
+ agent = SimpleNamespace(_memory_manager=MagicMock(), _session_messages=[{'role': 'user', 'content': 'hi'}])
+ agent.commit_memory_session = lambda msgs=None: calls.append(('commit', msgs))
+ agent.release_clients = lambda: calls.append(('release', None))
+ return agent
+
+
+def test_boundary_evict_commits_the_transcript_before_releasing(monkeypatch):
+ runner = _runner(monkeypatch)
+ calls = []
+ runner._agent_cache['route'] = (_agent(calls), 'sig')
+ runner._evict_cached_agent_at_boundary('route')
+ assert calls == [('commit', [{'role': 'user', 'content': 'hi'}]), ('release', None)]
+ assert 'route' not in runner._agent_cache
+
+
+def test_plain_evict_still_skips_the_commit(monkeypatch):
+ """``/model`` and rewind keep the conversation open; only the clients are recycled."""
+ runner = _runner(monkeypatch)
+ calls = []
+ runner._agent_cache['route'] = (_agent(calls), 'sig')
+ runner._evict_cached_agent('route')
+ assert calls == [('release', None)]
+
+
+async def test_reset_and_compress_mutations_use_the_boundary_evict(tmp_path, monkeypatch):
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+ import gateway.run as run
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {'default': 'fixture'}, 'platform_toolsets': {'cli': []}})
+ monkeypatch.setattr(run, '_resolve_gateway_model', lambda config: 'fixture')
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ evicted = {'boundary': [], 'plain': []}
+ runner = run.GatewayRunner.__new__(run.GatewayRunner)
+ runner.adapters = {}
+ runner.session_store = store
+ runner._session_db = store._db
+ runner._draining = False
+ runner._evict_cached_agent = lambda route, **kw: evicted['plain'].append(route)
+ runner._evict_cached_agent_at_boundary = lambda route: evicted['boundary'].append(route)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='test')
+ authority._schedule = lambda ref: None
+ conn = AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {'user_id': 'me'})
+ created = await conn.dispatch({'id': 1, 'method': 'session.create', 'params': {'request_id': 'r', 'source': 'cli', 'cwd': str(tmp_path)}})
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ route = authority.sessions[sid].route
+ reset = await conn.dispatch({'id': 2, 'method': 'session.mutate', 'params': dict(
+ session_id=sid, request_id='reset', expected_revision=0, expected_generation=0, operation='reset', payload={})})
+ assert 'result' in reset, reset
+ assert evicted['boundary'] == [route] and evicted['plain'] == []
+ await conn.close()
+ authority.db.close()