Skip to content

The agent that grows with you

fix(memory): gate other managers' prefetch only on calls past their deadline

kshitijk4poore47911a65184
diff --git a/agent/memory_manager.py b/agent/memory_manager.py
index 6a1c0b4e5a6..2663496e310 100644
--- a/agent/memory_manager.py
+++ b/agent/memory_manager.py
@@ -135,15 +135,16 @@ class MemoryManager:
swallows per-provider exceptions.
"""
- # Process-wide registry of in-flight external prefetch threads, keyed by
+ # Process-wide registry of in-flight external prefetch threads and their deadlines, keyed by
# (Hermes home, provider name). A new MemoryManager is built per agent init, so a
# per-instance registry would let every fresh manager spawn one more stuck thread
- # against the same provider (#134392); shared, a stuck call suppresses new spawns
- # from any manager until it returns. The home is part of the key because one
- # gateway process can serve several profiles, each with its own config and
- # credentials for a same-named provider: one profile's hung backend must not
- # silence another's recall.
- _EXTERNAL_PREFETCH_THREADS: dict[tuple[str, str], threading.Thread] = {}
+ # against the same provider (#134392); shared, any call past its deadline suppresses new
+ # spawns from every manager until it returns. Healthy concurrent prefetches from
+ # different sessions still run side by side, and each thread removes only its own
+ # entry. The home is part of the key because one gateway process can serve several
+ # profiles, each with its own config and credentials for a same-named provider: one
+ # profile's hung backend must not silence another's recall.
+ _EXTERNAL_PREFETCH_THREADS: dict[tuple[str, str], dict[threading.Thread, float]] = {}
_EXTERNAL_PREFETCH_LOCK = threading.Lock()
# Same idea for background writes: start times of in-flight sync_turn / queue_prefetch calls per
# (Hermes home, provider name). Python cannot stop a thread, so a call that never returns pins its
@@ -317,19 +318,23 @@ class MemoryManager:
except Exception as exc: # pragma: no cover - re-raised by caller
result_box["error"] = exc
finally:
- # A timed-out call clears its own entry when it finally returns, so the
- # process-wide registry never pins a finished thread.
+ # Every call removes its own entry when it returns, so the registry never pins
+ # a finished thread and one call's return never forgets another stuck one.
with self._EXTERNAL_PREFETCH_LOCK:
- if self._EXTERNAL_PREFETCH_THREADS.get(key) is thread:
- self._EXTERNAL_PREFETCH_THREADS.pop(key, None)
+ inflight = self._EXTERNAL_PREFETCH_THREADS.get(key)
+ if inflight is not None:
+ inflight.pop(thread, None)
+ if not inflight:
+ self._EXTERNAL_PREFETCH_THREADS.pop(key, None)
thread = spawn_context_thread(_run, name=f"memory-prefetch-{provider.name}")
with self._EXTERNAL_PREFETCH_LOCK:
- existing = self._EXTERNAL_PREFETCH_THREADS.get(key)
- if existing is not None and existing.is_alive():
- logger.debug("Memory provider '%s' prefetch is still running; skipping this turn", provider.name)
+ 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)
return ""
- self._EXTERNAL_PREFETCH_THREADS[key] = thread
+ inflight[thread] = now + self._external_prefetch_timeout
thread.start()
thread.join(self._external_prefetch_timeout)
@@ -340,9 +345,6 @@ class MemoryManager:
)
return ""
- with self._EXTERNAL_PREFETCH_LOCK:
- if self._EXTERNAL_PREFETCH_THREADS.get(key) is thread:
- self._EXTERNAL_PREFETCH_THREADS.pop(key, None)
if "error" in result_box:
raise result_box["error"]
result = result_box.get("value", "")
diff --git a/tests/agent/test_memory_provider.py b/tests/agent/test_memory_provider.py
index b43c8462ab8..95ab84948b9 100644
--- a/tests/agent/test_memory_provider.py
+++ b/tests/agent/test_memory_provider.py
@@ -482,11 +482,7 @@ class TestMemoryManager:
external.release.set()
deadline = time.monotonic() + 1.0
- while (
- (mgr._home_key, external.name) in mgr._EXTERNAL_PREFETCH_THREADS
- and mgr._EXTERNAL_PREFETCH_THREADS[(mgr._home_key, external.name)].is_alive()
- and time.monotonic() < deadline
- ):
+ while (mgr._home_key, external.name) in mgr._EXTERNAL_PREFETCH_THREADS and time.monotonic() < deadline:
time.sleep(0.01)
result = mgr.prefetch_all("query 3")
@@ -527,6 +523,71 @@ class TestMemoryManager:
finally:
external.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."""
+ first = BlockingPrefetchProvider("concurrent-healthy")
+ first._prefetch_result = "session a memory"
+ second = FakeMemoryProvider("concurrent-healthy")
+ second._prefetch_result = "session b memory"
+ mgr_a = MemoryManager(external_prefetch_timeout=5.0)
+ mgr_a.add_provider(first)
+ mgr_b = MemoryManager(external_prefetch_timeout=5.0)
+ mgr_b.add_provider(second)
+ results = {}
+ worker = threading.Thread(target=lambda: results.update(a=mgr_a.prefetch_all("q", session_id="a")))
+ worker.start()
+ try:
+ assert first.started.wait(timeout=2.0)
+ results["b"] = mgr_b.prefetch_all("q", session_id="b")
+ finally:
+ first.release.set()
+ worker.join(timeout=5.0)
+ assert results == {"a": "session a memory", "b": "session b memory"}
+
+ def test_one_stuck_call_returning_does_not_reopen_while_another_is_stuck(self):
+ """Two sessions start a prefetch before either times out and both hang. When one of them
+ finally returns, the other is still stuck, so fresh managers must keep skipping."""
+
+ class PerCallBlocking(FakeMemoryProvider):
+ def __init__(self, name):
+ super().__init__(name=name)
+ self.gates, self.lock = [], threading.Lock()
+
+ def prefetch(self, query, *, session_id=""):
+ gate = threading.Event()
+ with self.lock:
+ self.gates.append(gate)
+ self.prefetch_queries.append(query)
+ gate.wait(timeout=5.0)
+ return ""
+
+ provider = PerCallBlocking("two-stuck")
+ mgr_a = MemoryManager(external_prefetch_timeout=0.3)
+ mgr_a.add_provider(provider)
+ mgr_b = MemoryManager(external_prefetch_timeout=0.3)
+ mgr_b.add_provider(provider)
+ workers = [threading.Thread(target=m.prefetch_all, args=(q,)) for m, q in ((mgr_a, "a"), (mgr_b, "b"))]
+ try:
+ for w in workers:
+ w.start()
+ for w in workers:
+ w.join(timeout=5.0)
+ assert sorted(provider.prefetch_queries) == ["a", "b"] # both started, both timed out
+
+ provider.gates[0].set() # one stuck call returns; the other is still hung
+ deadline = time.monotonic() + 2.0
+ while len(MemoryManager._EXTERNAL_PREFETCH_THREADS.get((mgr_a._home_key, provider.name), {})) > 1:
+ assert time.monotonic() < deadline
+ time.sleep(0.01)
+ fresh = MemoryManager(external_prefetch_timeout=0.3)
+ fresh.add_provider(provider)
+ fresh.prefetch_all("c")
+ assert sorted(provider.prefetch_queries) == ["a", "b"] # "c" was skipped, not spawned
+ finally:
+ for gate in provider.gates:
+ gate.set()
+
def test_stuck_prefetch_registry_is_scoped_per_hermes_home(self, tmp_path):
"""Two profiles served by one process may configure a same-named provider
against different backends; a hung call in one must not suppress the other.