Skip to content

The agent that grows with you

fix(honcho): keep a failed late save reachable for flush_all after an eviction

Erosika3861167d639f
diff --git a/plugins/memory/honcho/session.py b/plugins/memory/honcho/session.py
index 2ab6bebc562..9ba60d2b5de 100644
--- a/plugins/memory/honcho/session.py
+++ b/plugins/memory/honcho/session.py
@@ -74,6 +74,8 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi
self._runtime_user_peer_name = runtime_user_peer_name
self._runtime_user_peer_name_alt = runtime_user_peer_name_alt
self._cache: dict[str, HonchoSession] = {}
+ # Sessions whose flush failed after a newer object took their cache key; flush_all() retries them.
+ self._retry_sessions: list[HonchoSession] = []
self._cache_lock = threading.RLock()
self._peers_cache: dict[str, Any] = {}
# honcho_session_id -> author peer IDs already joined to that session.
@@ -484,6 +486,20 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi
except Exception as e:
logger.error("Honcho async writer error: %s", e)
+ def _retain_for_retry(self, session: HonchoSession) -> None:
+ """Keep a session with unsynced messages where flush_all() looks. An evicted key takes it back; a key a
+ newer object owns keeps that object, and this one waits in the retry list."""
+ with self._cache_lock:
+ if not self._has_unsynced(session):
+ return
+ current = self._cache.get(session.key)
+ if current is session or any(s is session for s in self._retry_sessions):
+ return
+ if current is None:
+ self._cache[session.key] = session
+ else:
+ self._retry_sessions.append(session)
+
def _keep_until_flushed(self, session: HonchoSession) -> None:
"""Put an evicted session that still holds unsynced messages back where flush_all() looks. When a
newer object already owns the key, this one's batch is written now instead."""
@@ -494,7 +510,12 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi
if current is None:
self._cache[session.key] = session
return
- self._flush_session(session)
+ self._flush_now(session)
+
+ def _flush_now(self, session: HonchoSession) -> None:
+ """A save-time flush whose failed batch stays reachable for flush_all(), even after an eviction."""
+ if not self._flush_session(session):
+ self._retain_for_retry(session)
def save(self, session: HonchoSession) -> None:
"""Save messages per write_frequency: "async" enqueues for the background thread, "turn"
@@ -508,9 +529,9 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi
self._ensure_async_writer_locked()
self._async_queue.put(session)
return
- self._flush_session(session)
+ self._flush_now(session)
elif self._shutting_down or wf == "turn" or (isinstance(wf, int) and wf > 0 and self._turn_counter % wf == 0):
- self._flush_session(session)
+ self._flush_now(session)
else:
self._keep_until_flushed(session)
@@ -520,6 +541,7 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi
deadline = None if timeout is None else time.monotonic() + timeout
with self._cache_lock:
sessions = list(self._cache.values())
+ sessions += [s for s in self._retry_sessions if not any(s is c for c in sessions)]
skipped: list[HonchoSession] = []
for session in sessions:
try:
@@ -527,6 +549,8 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi
skipped.append(session)
except Exception as e:
logger.error("Honcho flush_all error for %s: %s", session.key, e)
+ with self._cache_lock:
+ self._retry_sessions = [s for s in self._retry_sessions if self._has_unsynced(s)]
skipped.extend(self._drain_async_queue(deadline))
left = [s for s in {id(s): s for s in skipped}.values() if self._has_unsynced(s)]
if left:
diff --git a/tests/test_honcho_session_cache_bounds.py b/tests/test_honcho_session_cache_bounds.py
index 755571556e3..cffb3da7c55 100644
--- a/tests/test_honcho_session_cache_bounds.py
+++ b/tests/test_honcho_session_cache_bounds.py
@@ -349,3 +349,72 @@ def test_deferred_save_flushes_inline_when_a_newer_object_owns_the_key():
assert flushed == [stale]
assert mgr._cache["k"] is newer
+
+
+def _failing_then_recording_uploads(mgr, session):
+ """The SDK session for ``session`` refuses the first batch; ``restore()`` swaps in one that records."""
+ uploads = []
+
+ def refuse(messages):
+ raise ConnectionError("upload refused")
+
+ mgr._get_or_create_peer = lambda peer_id: SimpleNamespace(message=lambda content: content)
+ mgr._sessions_cache[session.honcho_session_id] = SimpleNamespace(add_messages=refuse)
+
+ def restore():
+ mgr._sessions_cache[session.honcho_session_id] = SimpleNamespace(add_messages=lambda ms: uploads.extend(ms))
+
+ return uploads, restore
+
+
+def test_failed_turn_save_after_an_eviction_is_retried_by_flush_all():
+ """A clean session can be evicted while its caller still holds it. The caller's next save flushes inline in
+ turn mode, and a failed upload used to leave that object nowhere flush_all() could find it."""
+ mgr = _manager()
+ session = _session(key="k")
+ mgr._cache["k"] = session
+ with mgr._cache_lock:
+ mgr._evict_session_locked("k", session)
+ session.add_message("user", "late")
+ uploads, restore = _failing_then_recording_uploads(mgr, session)
+
+ mgr.save(session)
+ assert mgr._cache["k"] is session
+ restore()
+ mgr.flush_all()
+
+ assert uploads == ["late"]
+ assert session.messages[0]["_synced"] is True
+
+
+def test_failed_collision_flush_waits_for_flush_all_without_displacing_the_newer_object():
+ mgr = _manager()
+ mgr._write_frequency = "session"
+ newer = _session(key="k")
+ mgr._cache["k"] = newer
+ stale = _session(key="k")
+ stale.add_message("user", "late")
+ uploads, restore = _failing_then_recording_uploads(mgr, stale)
+
+ mgr.save(stale)
+ assert mgr._cache["k"] is newer
+ assert mgr._retry_sessions == [stale]
+ restore()
+ mgr.flush_all()
+
+ assert uploads == ["late"]
+ assert mgr._retry_sessions == []
+ assert mgr._cache["k"] is newer
+
+
+def test_a_retained_session_is_listed_once_across_repeated_failures():
+ mgr = _manager()
+ mgr._cache["k"] = _session(key="k")
+ stale = _session(key="k")
+ stale.add_message("user", "late")
+ _failing_then_recording_uploads(mgr, stale)
+
+ mgr.save(stale)
+ mgr.save(stale)
+
+ assert mgr._retry_sessions == [stale]