Skip to content

The agent that grows with you

fix(memory): claim soft-release memory teardown before draining

kshitijk4poor512a6c4a5d43
diff --git a/run_agent.py b/run_agent.py
index 0c6b5f10d1b..a6c73d24925 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -969,8 +969,10 @@ class AIAgent(
# here; delegation/review children run skip_memory=True (manager is None).
_mm = getattr(self, "_memory_manager", None)
if _mm is not None and not getattr(_mm, "_shutting_down", False):
- _quietly(_mm.shutdown_all)
+ # Claimed before the (bounded, seconds-long) drain so a close() racing it skips the
+ # extraction and second provider shutdown instead of running them mid-teardown.
self._memory_providers_released = True
+ _quietly(_mm.shutdown_all)
def close(self) -> None:
"""Release every resource this agent holds (idempotent); each phase is guarded so one failure never
diff --git a/tests/gateway/test_agent_cache.py b/tests/gateway/test_agent_cache.py
index 2068de489b8..900088aabb6 100644
--- a/tests/gateway/test_agent_cache.py
+++ b/tests/gateway/test_agent_cache.py
@@ -680,6 +680,30 @@ class TestAgentCacheIdleResume:
assert events == ["shutdown"]
assert not provider.writer.is_alive()
+ def test_close_racing_an_in_progress_soft_release_does_not_reextract(self):
+ """close() arriving while release_clients() is still inside the provider shutdown must not
+ start extraction or a second shutdown against the providers being torn down."""
+ events = []
+ agent, provider = self._agent_with_writer_provider("mem-release-race-test", events)
+ in_shutdown, let_finish = threading.Event(), threading.Event()
+ real_shutdown = provider.shutdown
+
+ def slow_shutdown():
+ in_shutdown.set()
+ assert let_finish.wait(5)
+ real_shutdown()
+
+ provider.shutdown = slow_shutdown
+ releaser = threading.Thread(target=agent.release_clients)
+ releaser.start()
+ try:
+ assert in_shutdown.wait(5)
+ agent.close()
+ finally:
+ let_finish.set()
+ releaser.join(timeout=5)
+ assert events == ["shutdown"]
+
def test_gateway_soft_evict_commits_memory_before_provider_shutdown(self):
"""The sweep eviction path must run end-of-session extraction BEFORE release_clients()
shuts the providers down (a shut-down provider can no longer commit)."""