Skip to content

The agent that grows with you

fix(memory): claim memory teardown on the manager, before the /new cleanup flush

kshitijk4poor3af00c8429f9
diff --git a/agent/memory_manager.py b/agent/memory_manager.py
index dd92e45a509..32ad72b63a4 100644
--- a/agent/memory_manager.py
+++ b/agent/memory_manager.py
@@ -175,6 +175,7 @@ class MemoryManager:
# within a bound, then report exactly what it abandoned.
self._background_futures: dict[Future, str] = {}
self._shutting_down = False
+ self._teardown_claim: Optional[str] = None # see claim_teardown()
self._shutdown_drain_state: dict[str, Any] = {
"status": "not_started", "abandoned_writes": 0, "abandoned_prefetches": 0, "active_tasks": 0,
}
@@ -793,6 +794,18 @@ class MemoryManager:
lambda p: p.on_delegation(task, result, child_session_id=child_session_id, **kwargs),
)
+ def claim_teardown(self, *, session_end: bool) -> bool:
+ """Claim extraction + ``shutdown_all()`` for end-of-session shutdown or soft release. The first
+ claimer wins and the loser skips, so the two never overlap and providers (no idempotency
+ contract) are never shut down twice. Session-end callers may re-claim (the gateway claims before
+ its flush, then ``shutdown_memory_provider`` claims again); a soft release is once-only and also
+ loses to a manager another owner is already draining."""
+ with self._sync_executor_lock:
+ if self._teardown_claim is None and (session_end or not self._shutting_down):
+ self._teardown_claim = "session_end" if session_end else "soft_release"
+ return True
+ return session_end and self._teardown_claim == "session_end"
+
def shutdown_all(self) -> None:
"""Drain the background executor (bounded), then shut providers down in reverse order."""
self._drain_sync_executor()
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index f0277bca10e..9cc69130b55 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -1268,18 +1268,15 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):
return
with suppress(Exception):
if hasattr(agent, "shutdown_memory_provider"):
- # Drain queued memory writes BEFORE teardown (shutdown_all() gives the worker only ~5s, so a
- # /reset or rotation could drop them). Bounded; a failure never blocks teardown.
- # The memory manager persists per-turn sync and end-of-session extraction on a single
- # serialized background worker. shutdown_memory_provider() -> shutdown_all() only gives that
- # worker a ~5s bounded drain and abandons (cancels) anything still queued past it, so a
- # /reset — or any gateway session rotation that reaches this cleanup path — could silently
- # drop writes the session had already handed off. The next session then loads stale memory
- # (#73297). Give pending work a bounded head start through the manager's own barrier first,
- # mirroring the CLI exit path (cli.py). Best-effort: a flush failure must never block
- # teardown.
+ # Drain queued memory writes BEFORE teardown: shutdown_all() gives the single serialized
+ # worker only ~5s and cancels the rest, so a /reset or rotation could drop writes and the
+ # next session loads stale memory (#73297). Bounded, like the CLI exit path; never blocks.
+ # The teardown claim comes first: a /new that stops waiting on this job evicts the agent,
+ # and that soft release must leave extraction + provider shutdown to us.
_mm = getattr(agent, "_memory_manager", None)
- if _mm is not None and hasattr(_mm, "flush_pending"):
+ if _mm is not None:
+ with suppress(Exception):
+ _mm.claim_teardown(session_end=True)
with suppress(Exception):
_mm.flush_pending(timeout=10)
# Pass the real transcript so ``on_session_end`` hooks don't see the empty default.
diff --git a/run_agent.py b/run_agent.py
index 79c3bf7ce9d..b001265d9d6 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -154,21 +154,6 @@ def _quietly(fn: Callable, *args, **kwargs) -> None:
pass
-_MEMORY_TEARDOWN_CLAIM_LOCK = threading.Lock()
-
-
-def _claim_memory_teardown(agent: Any) -> bool:
- """Once-only claim on an agent's memory-provider teardown, shared by end-of-session shutdown
- and soft release. A /new cleanup worker left running past its timeout can still be inside
- ``on_session_end()`` when the same agent is evicted; the loser skips, so extraction and
- ``shutdown_all()`` never run concurrently or twice."""
- with _MEMORY_TEARDOWN_CLAIM_LOCK:
- if getattr(agent, "_memory_teardown_claimed", False):
- return False
- agent._memory_teardown_claimed = True
- return True
-
-
def _call_engine_hook(engine: Any, hook: str, *args, **kwargs) -> None:
"""Invoke an optional context-engine lifecycle hook; failures are logged, never raised."""
if not hasattr(engine, hook):
@@ -889,9 +874,8 @@ class AIAgent(
if getattr(self, "_memory_provider_shutdown", False):
return
self._memory_provider_shutdown = True
- # One claim shared with release_clients(): whichever path claims first owns extraction and
- # shutdown_all(); the other skips, so they never overlap or shut providers down twice.
- if self._memory_manager and _claim_memory_teardown(self):
+ # Shared with release_clients() via the manager's once-only claim (see claim_teardown).
+ if self._memory_manager and self._memory_manager.claim_teardown(session_end=True):
try:
self._memory_manager.on_session_end(messages or [])
except Exception as e:
@@ -952,42 +936,11 @@ class AIAgent(
# The Codex app-server child is an LLM client, not session tool state: the evicted instance is popped
# from the cache and a rebuilt agent spawns its own child, so an unclosed one leaks for the gateway's life.
_quietly(self._close_codex_session)
- # Drain + shut down memory providers WITHOUT on_session_end().
- #
- # Each memory provider instance spawns its own background writer thread
- # (retaindb-writer, openviking-sync, ...). Soft eviction never terminated
- # them: one zombie daemon per evicted agent, each holding stack memory and
- # references to provider clients/queues that block GC. Under a 128-entry
- # cache with heavy turnover (e.g. concurrent 429 retry storms) this piles
- # up dozens of leaked threads and drove the 2026-07-30 gateway liveness
- # crash (exit 75).
- #
- # shutdown_memory_provider() calls on_session_end() first — too heavy for
- # soft eviction: it triggers end-of-session extraction, which a resumed
- # session would duplicate. Instead call shutdown_all() directly: it
- # bounded-drains the sync executor (giving any queued extraction its ~5s)
- # and calls provider shutdown(), which sends each writer its sentinel and
- # joins the thread — no extraction side-effect.
- #
- # Extraction-commit coverage varies by eviction path: the sweep paths
- # (LRU cap, idle TTL, RSS pressure) commit via _commit_then_release_soft()
- # before soft release; direct eviction paths (/new, /model, /login,
- # cross-process) release without a pre-commit, so on those the manager's
- # queue still drains but the final turn's extraction is not committed —
- # pre-existing behavior, unchanged by this fix (before this PR those
- # paths ALSO leaked the writer threads).
- #
- # Safe for resume: an evicted agent is popped from the cache and never
- # re-added, and the resumed session's freshly-built AIAgent creates a new
- # MemoryManager with fresh provider instances. api_server's parked managers
- # are checked out exclusively, so a live shared manager is never reachable
- # here; delegation/review children run skip_memory=True (manager is None).
+ # Stop the memory providers' writer threads (one leaked per evicted agent otherwise), but skip
+ # on_session_end(): sweep evictions already committed it via _commit_then_release_soft(), and a
+ # pending end-of-session teardown (claim_teardown) owns both extraction and shutdown.
_mm = getattr(self, "_memory_manager", None)
- # Claimed before the (bounded, seconds-long) drain, and shared with shutdown_memory_provider():
- # a /new cleanup still inside on_session_end() holds the claim, so this eviction leaves the
- # shutdown to that worker instead of tearing the providers down under its extraction. A manager
- # already draining (shut down by another owner) is left alone too.
- if _mm is not None and not getattr(_mm, "_shutting_down", False) and _claim_memory_teardown(self):
+ if _mm is not None and _mm.claim_teardown(session_end=False):
_quietly(_mm.shutdown_all)
def close(self) -> None:
diff --git a/tests/gateway/test_agent_cache_memory_lifecycle.py b/tests/gateway/test_agent_cache_memory_lifecycle.py
index 3f9c0d92428..21b93c846c9 100644
--- a/tests/gateway/test_agent_cache_memory_lifecycle.py
+++ b/tests/gateway/test_agent_cache_memory_lifecycle.py
@@ -9,66 +9,6 @@ from tests.gateway.test_agent_cache import _make_runner
class TestAgentCacheMemoryLifecycle:
- def test_release_clients_shuts_down_memory_provider(self):
- """release_clients() must call shutdown_all() on the memory manager.
-
- Memory providers spawn background writer threads (retaindb-writer,
- openviking-sync, ...). Without shutdown on soft eviction, these threads
- pile up as zombies — one per evicted agent — eventually causing thread
- proliferation and gateway liveness crashes.
-
- release_clients() must drain + shut the manager down WITHOUT calling
- on_session_end() (end-of-session extraction): the gateway's
- _commit_then_release_soft() already commits extraction via
- commit_memory_session() before soft-releasing, and a resumed session
- builds a fresh manager anyway.
- """
- from run_agent import AIAgent
-
- agent = AIAgent(
- model="anthropic/claude-sonnet-4", api_key="test",
- base_url="https://openrouter.ai/api/v1", provider="openrouter",
- max_iterations=5, quiet_mode=True,
- skip_context_files=True, skip_memory=True,
- session_id="mem-provider-evict-test",
- )
-
- class _MockMM:
- def __init__(self):
- self.shutdown_all_calls = 0
- self.on_session_end_calls = 0
- def shutdown_all(self):
- self.shutdown_all_calls += 1
- def on_session_end(self, messages):
- self.on_session_end_calls += 1
-
- mock_mm = _MockMM()
- agent._memory_manager = mock_mm
-
- try:
- agent.release_clients()
- except Exception:
- pass
- # Snapshot BEFORE the final close(): close() -> shutdown_memory_provider()
- # legitimately calls on_session_end()/shutdown_all() at the hard teardown
- # boundary — the assertions below are about the soft-eviction path only.
- shutdown_calls, session_end_calls = mock_mm.shutdown_all_calls, mock_mm.on_session_end_calls
-
- try:
- agent.close()
- except Exception:
- pass
-
- assert shutdown_calls >= 1, (
- "release_clients() must call shutdown_all() to terminate memory "
- "provider writer threads. Leaked threads cause thread proliferation "
- "under cache turnover."
- )
- assert session_end_calls == 0, (
- "release_clients() must NOT call on_session_end() — that triggers "
- "end-of-session extraction, too heavy for a soft-evicted session."
- )
-
@staticmethod
def _agent_with_writer_provider(session_id, events):
"""Real AIAgent + real MemoryManager whose provider owns a writer thread released only by shutdown()."""
@@ -218,3 +158,37 @@ class TestAgentCacheMemoryLifecycle:
runner._housekeeping_executor.shutdown(wait=True)
assert events == ["on_session_end:start", "on_session_end:done", "shutdown"]
assert not provider.writer.is_alive()
+
+ @pytest.mark.asyncio
+ async def test_eviction_while_reset_cleanup_is_still_flushing_leaves_shutdown_to_it(self, monkeypatch):
+ """/new's cleanup job can still be in its pre-extraction flush (up to 10 s) when /new stops
+ waiting and evicts the agent; that eviction must not shut the providers down first."""
+ import gateway.slash_commands_session as session_cmds
+ from tests.waiting import wait_until
+
+ events = []
+ agent, provider = self._agent_with_writer_provider("mem-reset-flush-test", events)
+ agent._session_messages = [{"role": "user", "content": "remember this"}]
+ in_flush, let_finish = threading.Event(), threading.Event()
+
+ def slow_flush(timeout=None):
+ in_flush.set()
+ assert let_finish.wait(10)
+ return True
+
+ agent._memory_manager.flush_pending = slow_flush
+ key = "agent:main:telegram:dm:1"
+ runner = _make_runner()
+ runner._agent_cache[key] = (agent, "sig")
+ monkeypatch.setattr(session_cmds, "_RESET_CLEANUP_TIMEOUT_S", 0.05)
+ try:
+ await runner._cleanup_old_agent_for_reset(key)
+ assert in_flush.wait(10)
+ runner._evict_cached_agent(key)
+ wait_until(lambda: agent._session_messages == [], what="the soft eviction to finish")
+ assert events == [], "eviction shut providers down before the /new cleanup extracted"
+ finally:
+ let_finish.set()
+ runner._housekeeping_executor.shutdown(wait=True)
+ assert events == ["on_session_end", "shutdown"]
+ assert not provider.writer.is_alive()