Skip to content

The agent that grows with you

fix(memory): one orphaned call no longer turns a provider off for the process lifetime

kshitijk4poorb6c8ed0ba5de
diff --git a/agent/memory_manager.py b/agent/memory_manager.py
index 95a3a059e7a..d5a788914ed 100644
--- a/agent/memory_manager.py
+++ b/agent/memory_manager.py
@@ -41,9 +41,13 @@ _LEGACY_PRE_COMPRESS_API_VERSION = 1
_SYNC_DRAIN_TIMEOUT_S = 5.0
_EXTERNAL_PREFETCH_TIMEOUT_S = 8.0
# A background provider call (sync_turn / queue_prefetch) running longer than this is treated as
-# stuck: later calls for the same provider are skipped until it returns. Well above the shutdown
-# drain bound and the prefetch timeout so a slow-but-healthy backend is never skipped.
+# stuck. Well above the shutdown drain bound and the prefetch timeout so a slow-but-healthy backend
+# is never counted.
_BACKGROUND_CALL_STALL_S = 30.0
+# Stuck (overdue) calls tolerated per (home, provider) before later calls are skipped. Python cannot
+# stop a thread, so each one pins a thread until it returns; more than one keeps a recovered backend
+# (one orphaned socket, a healthy replacement connection) usable while bounding the pinned threads.
+_MAX_STUCK_CALLS = 4
# -- Signature introspection (providers are duck-typed; call shapes vary) -----
@@ -128,6 +132,11 @@ def _redact_messages_for_egress(messages: Optional[list[Any]]) -> Optional[list[
return None if messages is None else list(_redact_for_provider(messages))
+def _stuck_calls(inflight: dict[Any, float], now: float) -> int:
+ """How many registered calls are past their deadline."""
+ return sum(now > deadline for deadline in inflight.values())
+
+
def _forget_inflight(registry: dict, key: tuple[str, str], token: object) -> bool:
"""Drop one call's entry from a process-wide in-flight registry (caller holds its lock); the key goes
with its last entry. True when the key is now clear."""
@@ -161,7 +170,7 @@ class MemoryManager:
# (Hermes home, provider name). Python cannot stop a thread, so a call that never returns pins its
# mem-sync worker for the process lifetime; managers are rebuilt per agent, so without a shared
# view every fresh manager would start one more call against the hung backend and pin one more
- # thread. Calls are skipped while any call for the key is stuck past _BACKGROUND_CALL_STALL_S.
+ # thread. Calls are skipped once _MAX_STUCK_CALLS for the key are stuck past _BACKGROUND_CALL_STALL_S.
_BACKGROUND_CALLS: dict[tuple[str, str], dict[object, float]] = {}
_BACKGROUND_SKIPS: dict[tuple[str, str], int] = {}
_BACKGROUND_CALLS_LOCK = threading.Lock()
@@ -316,7 +325,8 @@ class MemoryManager:
def _prefetch_provider(self, provider: MemoryProvider, query: str, *, session_id: str = "") -> str:
"""Run one provider's prefetch; external providers are bounded by a timeout. A stuck external
- call keeps running on its daemon thread and the provider is skipped on later turns until it returns."""
+ call keeps running on its daemon thread; once _MAX_STUCK_CALLS are stuck the provider is skipped
+ on later turns until one returns."""
if provider.name == "builtin":
return provider.prefetch(query, session_id=session_id)
@@ -339,8 +349,9 @@ class MemoryManager:
with self._EXTERNAL_PREFETCH_LOCK:
inflight = self._EXTERNAL_PREFETCH_THREADS.setdefault(key, {})
now = time.monotonic()
- if any(now > deadline for deadline in inflight.values()):
- logger.debug("Memory provider '%s' prefetch is still stuck; skipping this turn", provider.name)
+ if _stuck_calls(inflight, now) >= _MAX_STUCK_CALLS:
+ logger.debug("Memory provider '%s' prefetch has %d stuck calls; skipping this turn",
+ provider.name, _MAX_STUCK_CALLS)
return ""
inflight[thread] = now + self._external_prefetch_timeout
try:
@@ -476,9 +487,9 @@ class MemoryManager:
logger.debug("Inline memory background task failed: %s", e)
def _call_unless_stalled(self, provider: MemoryProvider, call: Callable[[], Any]) -> None:
- """Run a background provider call unless an earlier one for the same provider (any manager in
- this process) is stuck; skipping costs that turn's write/prefetch but keeps the thread count
- bounded. The builtin provider is local and never gated."""
+ """Run a background provider call unless _MAX_STUCK_CALLS earlier ones for the same provider (any
+ manager in this process) are stuck; skipping costs that turn's write/prefetch but keeps the
+ pinned-thread count bounded. The builtin provider is local and never gated."""
if provider.name == "builtin":
call()
return
@@ -487,12 +498,13 @@ class MemoryManager:
now = time.monotonic()
with self._BACKGROUND_CALLS_LOCK:
calls = self._BACKGROUND_CALLS.setdefault(key, {})
- if any(now - started > _BACKGROUND_CALL_STALL_S for started in calls.values()):
+ if _stuck_calls(calls, now - _BACKGROUND_CALL_STALL_S) >= _MAX_STUCK_CALLS:
skips = self._BACKGROUND_SKIPS[key] = self._BACKGROUND_SKIPS.get(key, 0) + 1
if skips == 1 or skips % 100 == 0:
logger.warning(
- "Memory provider '%s' has a background call stuck for over %.0fs; skipping its "
- "sync/prefetch until it returns (%d skipped)", provider.name, _BACKGROUND_CALL_STALL_S, skips,
+ "Memory provider '%s' has %d background calls stuck for over %.0fs; skipping its "
+ "sync/prefetch until one returns (%d skipped)", provider.name, _MAX_STUCK_CALLS,
+ _BACKGROUND_CALL_STALL_S, skips,
)
return
calls[token] = now
diff --git a/tests/agent/test_memory_provider.py b/tests/agent/test_memory_provider.py
index e09695b1001..58f87ddca31 100644
--- a/tests/agent/test_memory_provider.py
+++ b/tests/agent/test_memory_provider.py
@@ -453,7 +453,10 @@ class TestMemoryManager:
# -- Error resilience ---------------------------------------------------
- def test_external_prefetch_timeout_skips_stuck_provider(self):
+ def test_external_prefetch_timeout_skips_stuck_provider(self, monkeypatch):
+ import agent.memory_manager as mm
+
+ monkeypatch.setattr(mm, "_MAX_STUCK_CALLS", 1) # the gate closes on the first stuck call
mgr = MemoryManager(external_prefetch_timeout=0.01)
builtin = FakeMemoryProvider("builtin")
builtin._prefetch_result = "builtin memory"
@@ -493,15 +496,17 @@ class TestMemoryManager:
def test_stuck_prefetch_thread_is_shared_across_managers(self, tmp_path):
"""#134392: a new MemoryManager is built per agent init, so the in-flight
- registry must be process-wide — N fresh managers against one stuck provider
- keep at most one live ``memory-prefetch-*`` thread, not one per manager. It is
- keyed per Hermes home: another profile's same-named provider still recalls.
+ registry must be process-wide — fresh managers against a wedged provider keep at
+ most ``_MAX_STUCK_CALLS`` live ``memory-prefetch-*`` threads, not one per manager. It
+ is keyed per Hermes home: another profile's same-named provider still recalls.
"""
+ import agent.memory_manager as mm
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ stuck = mm._MAX_STUCK_CALLS
external = BlockingPrefetchProvider("cross-manager-stuck")
try:
- for i in range(5):
+ for i in range(stuck + 3):
mgr = MemoryManager(external_prefetch_timeout=0.01)
mgr.add_provider(external)
mgr._prefetch_provider(external, "query", session_id=f"s{i}")
@@ -510,8 +515,8 @@ class TestMemoryManager:
t for t in threading.enumerate()
if t.name.startswith("memory-prefetch-cross-manager-stuck")
]
- assert len(live) == 1
- assert external.prefetch_queries == ["query"]
+ assert len(live) == stuck
+ assert external.prefetch_queries == ["query"] * stuck
other_profile = FakeMemoryProvider("cross-manager-stuck")
other_profile._prefetch_result = "profile b memory"
@@ -523,19 +528,38 @@ class TestMemoryManager:
mgr_b.add_provider(other_profile)
assert mgr_b._prefetch_provider(other_profile, "q", session_id="b") == "profile b memory"
- # Once the stuck call returns, the shared registry clears and a fresh
+ # Once the stuck calls return, the shared registry clears and a fresh
# manager prefetches again.
external.release.set()
- live[0].join(timeout=2.0)
- assert not live[0].is_alive()
+ for thread in live:
+ thread.join(timeout=2.0)
+ assert not thread.is_alive()
assert (mgr._home_key, external.name) not in MemoryManager._EXTERNAL_PREFETCH_THREADS
mgr = MemoryManager(external_prefetch_timeout=1.0)
mgr.add_provider(external)
mgr._prefetch_provider(external, "after", session_id="s-after")
- assert external.prefetch_queries == ["query", "after"]
+ assert external.prefetch_queries == ["query"] * stuck + ["after"]
finally:
external.release.set()
+ def test_healthy_replacement_recalls_behind_an_orphaned_prefetch(self):
+ """One prefetch that never returns must not blank recall for the process lifetime: a fresh
+ manager with a healthy provider instance (the backend recovered) still recalls."""
+ orphan = BlockingPrefetchProvider("orphaned-recall")
+ stuck_mgr = MemoryManager(external_prefetch_timeout=0.01)
+ stuck_mgr.add_provider(orphan)
+ try:
+ stuck_mgr._prefetch_provider(orphan, "q", session_id="stuck")
+ assert orphan.started.wait(timeout=2.0)
+ healthy = FakeMemoryProvider("orphaned-recall")
+ healthy._prefetch_result = "recalled"
+ for i in range(5):
+ mgr = MemoryManager(external_prefetch_timeout=5.0)
+ mgr.add_provider(healthy)
+ assert mgr._prefetch_provider(healthy, "q", session_id=f"s{i}") == "recalled"
+ finally:
+ orphan.release.set()
+
def test_healthy_concurrent_prefetches_from_two_sessions_both_recall(self):
"""Only a TIMED-OUT call gates other managers: a slow-but-healthy prefetch in one session
must not blank the recall of another session that prefetches meanwhile."""
diff --git a/tests/agent/test_memory_stalled_background_call.py b/tests/agent/test_memory_stalled_background_call.py
index a5120801a34..4b3fd7692aa 100644
--- a/tests/agent/test_memory_stalled_background_call.py
+++ b/tests/agent/test_memory_stalled_background_call.py
@@ -1,7 +1,7 @@
"""A background provider call that never returns pins its mem-sync worker thread forever (Python cannot
stop a thread). MemoryManagers are rebuilt per agent, so without a process-wide view every fresh manager
started one more call against the hung backend and pinned one more thread. Calls for a provider are now
-skipped while an earlier call for it is stuck past the stall threshold."""
+skipped once _MAX_STUCK_CALLS earlier calls for it are stuck past the stall threshold."""
import threading
import pytest
@@ -71,32 +71,60 @@ def _mem_sync_threads():
return [t for t in threading.enumerate() if t.name.startswith("mem-sync")]
-def test_stuck_call_stops_fresh_managers_from_pinning_more_threads():
- provider = _HangingProvider()
- first = _manager(provider)
- first.sync_all("hello", "hi")
+def _hang_one_call(name="hangs"):
+ """A manager whose provider's first sync_turn never returns (until released)."""
+ provider = _HangingProvider(name)
+ mgr = _manager(provider)
+ mgr.sync_all("hello", "hi")
assert provider.started.wait(5)
+ return mgr, provider
+
+
+def test_sustained_wedge_pins_at_most_max_stuck_threads():
+ """A backend that stays wedged: every call hangs. Calls keep being admitted until
+ _MAX_STUCK_CALLS are stuck, then later managers are skipped, so pinned threads stay bounded."""
+ hung = [_hang_one_call() for _ in range(mm._MAX_STUCK_CALLS)]
before = len(_mem_sync_threads())
for _ in range(5):
- fresh = _manager(provider)
+ fresh = _manager(_HangingProvider())
fresh.sync_all("again", "reply")
fresh.queue_prefetch_all("query")
- assert fresh.flush_pending(timeout=5) # returns: nothing blocked behind the hung call
+ assert fresh.flush_pending(timeout=5) # returns: nothing blocked behind the hung calls
fresh.shutdown_all()
- assert provider.sync_calls == 1 and provider.prefetch_calls == 0
- assert MemoryManager._BACKGROUND_SKIPS[(first._home_key, provider.name)] == 10
+ key = (hung[0][0]._home_key, hung[0][1].name)
+ assert MemoryManager._BACKGROUND_SKIPS[key] == 10
+ assert len(MemoryManager._BACKGROUND_CALLS[key]) == mm._MAX_STUCK_CALLS
# Idle workers of shut-down executors exit asynchronously.
wait_until(lambda: len(_mem_sync_threads()) <= before, timeout=5, what="idle mem-sync workers to exit")
- provider.release.set()
- assert first.flush_pending(timeout=5)
- assert (first._home_key, provider.name) not in MemoryManager._BACKGROUND_CALLS
- first.sync_all("next", "turn") # calls resume once the stuck one returns
- assert first.flush_pending(timeout=5)
- assert provider.sync_calls == 2
- first.shutdown_all()
+ for _, provider in hung:
+ provider.release.set()
+ for mgr, _ in hung:
+ assert mgr.flush_pending(timeout=5)
+ assert key not in MemoryManager._BACKGROUND_CALLS
+ for mgr, _ in hung:
+ mgr.shutdown_all()
+
+
+def test_healthy_replacement_still_writes_behind_an_orphaned_call():
+ """One call that never returns must not silence the provider for the process lifetime: a fresh
+ manager with a healthy provider instance (the backend recovered) keeps writing."""
+ orphan_mgr, orphan = _hang_one_call()
+ healthy = _HangingProvider()
+ healthy.hang_next = False
+ try:
+ for _ in range(5):
+ fresh = _manager(healthy)
+ fresh.sync_all("again", "reply")
+ fresh.queue_prefetch_all("query")
+ assert fresh.flush_pending(timeout=5)
+ fresh.shutdown_all()
+ assert (healthy.sync_calls, healthy.prefetch_calls) == (5, 5)
+ finally:
+ orphan.release.set()
+ orphan_mgr.shutdown_all()
def test_slow_call_below_threshold_is_not_skipped(monkeypatch):