The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(honcho): join every plugin thread on shutdown within one budget
Erosikac3a5649aacf9
diff --git a/plugins/memory/honcho/__init__.py b/plugins/memory/honcho/__init__.pyindex 4c480cfd54a..32e72195356 100644--- a/plugins/memory/honcho/__init__.py+++ b/plugins/memory/honcho/__init__.py@@ -22,6 +22,7 @@ from agent.memory_provider import MemoryProvider, is_trivial_prompt, spawn_contefrom agent.turn_author import a2a_keyfrom plugins.memory.honcho.client import HonchoClientConfig, resolve_config_pathfrom plugins.memory.honcho.client import _host_block, _HostLookup+from plugins.memory.honcho.client import join_plugin_threadsfrom plugins.memory.honcho.dialectic import DialecticMixinfrom plugins.memory.honcho.session_peers import assistant_peer_id_for, sanitize_peer_idfrom plugins.memory.honcho.session_context import usable_honcho_summary@@ -305,7 +306,8 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):with self._init_lock if blocking else contextlib.nullcontext():if not self._can_start_init() or (self._init_thread and self._init_thread.is_alive()):return- self._init_thread = spawn_context_thread(lambda: self._run_session_init("background"), name="honcho-session-init")+ self._init_thread = spawn_context_thread(lambda: self._run_session_init("background"),+ name="honcho-session-init", owner=self)self._init_thread.start()if wait_timeout > 0:self._init_thread.join(timeout=wait_timeout)@@ -798,8 +800,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):return tool_error("Honcho memory writes are off during a bot-to-bot turn. Conclusions and profile edits describe the human.")return None- @staticmethod- def _spawn_write(fn: Callable[[], None], name: str, fail_msg: str) -> threading.Thread:+ def _spawn_write(self, fn: Callable[[], None], name: str, fail_msg: str) -> threading.Thread:"""Run a Honcho write off-thread; failures are debug-logged, never raised into the turn."""def _run():try:@@ -807,7 +808,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):except Exception as e:logger.debug(fail_msg, e)- thread = spawn_context_thread(_run, name=name)+ thread = spawn_context_thread(_run, name=name, owner=self)thread.start()return thread@@ -983,21 +984,41 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):logger.error("Honcho tool %s failed: %s", tool_name, e)return tool_error(f"Honcho {tool_name} failed: {e}")+ # Shutdown never joins for less than this; a thread blocked in httpx can hold the HTTP timeout.+ _SHUTDOWN_JOIN_FLOOR = 5.0++ def _shutdown_join_budget(self) -> float:+ """One join window for every plugin thread: the floor, or the configured HTTP timeout when+ that is longer, so a thread blocked in a Honcho call can finish before the interpreter+ finalizes (#33485)."""+ try:+ from plugins.memory.honcho.client_cache import _resolve_timeout_from_sources+ return max(self._SHUTDOWN_JOIN_FLOOR, _resolve_timeout_from_sources(self._config))+ except Exception:+ return self._SHUTDOWN_JOIN_FLOOR+def shutdown(self) -> None:+ """Join the write threads, flush and stop the manager, then join every other thread this+ provider or its manager spawned, all within one budget. A daemon thread still blocked in+ httpx I/O when the interpreter finalizes aborts the process (#37632)."""self._recall_generation = object()- for t in (self._prefetch_thread, self._sync_thread, self._memwrite_thread):+ budget = self._shutdown_join_budget()+ deadline = time.monotonic() + budget+ for t in (self._sync_thread, self._memwrite_thread):if t and t.is_alive():- t.join(timeout=5.0)+ t.join(timeout=max(0.0, deadline - time.monotonic()))manager = self._manager- if not manager or (self._init_thread and self._init_thread.is_alive() and not self._session_initialized):- return- # saveMessages: false skips persistence, but the async-writer thread must still- # be joined so daemon threads aren't left blocked in httpx I/O at interpreter exit.- with contextlib.suppress(Exception):- if getattr(self._config, "save_messages", True):- manager.shutdown() # flush_all() + join the writer- else:- manager.stop_async_writer()+ if manager and not (self._init_thread and self._init_thread.is_alive() and not self._session_initialized):+ # saveMessages: false skips persistence, but the async-writer thread must still be joined.+ with contextlib.suppress(Exception):+ if getattr(self._config, "save_messages", True):+ manager.shutdown() # flush_all() + join the writer+ else:+ manager.stop_async_writer()+ left = join_plugin_threads((self, manager), timeout=max(0.0, deadline - time.monotonic()))+ if left:+ logger.warning("Honcho shutdown timed out after %.1fs with %d thread(s) still running: %s",+ budget, len(left), ", ".join(left))def register(ctx) -> None:diff --git a/plugins/memory/honcho/client.py b/plugins/memory/honcho/client.pyindex 2b18e870aaa..c60bab62881 100644--- a/plugins/memory/honcho/client.py+++ b/plugins/memory/honcho/client.py@@ -7,12 +7,16 @@ flat/global fields, which win over defaults.from __future__ import annotations+import atexitimport contextlibimport hashlibimport ipaddressimport jsonimport loggingimport os+import threading as _threading+import time+import weakref# --- per-identity client cache ------------------------------------------- One slot per client identity,# replacing the single process-wide slot that pinned the first profile's workspace and bearer for every# later profile in multi-profile processes (#69123 multiplexed gateway, #74065 dashboard). The legacy names@@ -22,6 +26,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callablefrom urllib.parse import urlparse+from agent.memory_provider import spawn_context_thread as _spawn_context_threadfrom agent.secret_scope import get_secretfrom hermes_cli.profiles import _get_default_hermes_homefrom hermes_constants import get_hermes_home@@ -506,6 +511,62 @@ class HonchoClientConfig:return self.workspace_id+# Threads the plugin spawned, keyed by the provider or manager that owns them: shutdown joins its own+# threads with one budget and never waits on another agent's work in the same gateway process.+_plugin_threads: "weakref.WeakKeyDictionary[Any, weakref.WeakSet]" = weakref.WeakKeyDictionary()+_plugin_threads_lock = _threading.Lock()+++def spawn_context_thread(+ target, *, name: str, daemon: bool = True, args: tuple = (), owner: Any = None,+) -> "_threading.Thread":+ """agent.memory_provider.spawn_context_thread plus an ``owner``: the thread is registered so+ join_plugin_threads can wait on exactly the threads this provider or manager spawned."""+ thread = _spawn_context_thread(target, name=name, daemon=daemon, args=args)+ if owner is not None:+ with _plugin_threads_lock:+ _plugin_threads.setdefault(owner, weakref.WeakSet()).add(thread)+ return thread+++def join_plugin_threads(owners, timeout: float) -> list[str]:+ """Join every live thread spawned for ``owners`` within one shared ``timeout``. Returns the names+ of the threads still running when the budget ran out."""+ deadline = time.monotonic() + max(0.0, timeout)+ me = _threading.current_thread()+ with _plugin_threads_lock:+ threads = [t for owner in owners if owner is not None+ for t in list(_plugin_threads.get(owner, ())) if t.is_alive() and t is not me]+ for thread in threads:+ thread.join(timeout=max(0.0, deadline - time.monotonic()))+ return [t.name for t in threads if t.is_alive()]+++def close_honcho_clients() -> None:+ """Close the HTTP pool of every cached client and drop the slots. Process exit only: one client+ serves every manager with the same identity, so a per-agent shutdown must never call this."""+ with _client_slots_lock:+ slots = list(_client_slots.values())+ _client_slots.clear()+ for slot in slots:+ close = getattr(getattr(slot.peek(), "_http", None), "close", None)+ if callable(close):+ with contextlib.suppress(Exception):+ close()+++_exit_close_registered = False+++def _register_exit_close() -> None:+ global _exit_close_registered+ with _client_slots_lock:+ if _exit_close_registered:+ return+ _exit_close_registered = True+ atexit.register(close_honcho_clients)++def get_honcho_client(config: HonchoClientConfig | None = None) -> Honcho:"""Get or create the Honcho client for this config's identity. Clients are cached PERIDENTITY (host, workspace, provenance paths, credential fingerprint, timeout) so@@ -583,6 +644,7 @@ def _build_client(config: HonchoClientConfig) -> "Honcho":# strip a trailing version segment from any base_url to avoid "/v3/v3/...".import rekwargs["base_url"] = re.sub(r"/v\d+/*$", "", base_url).rstrip("/")+ _register_exit_close()return Honcho(**kwargs)diff --git a/plugins/memory/honcho/dialectic.py b/plugins/memory/honcho/dialectic.pyindex 1a493533391..24eb9c40f44 100644--- a/plugins/memory/honcho/dialectic.py+++ b/plugins/memory/honcho/dialectic.py@@ -85,7 +85,7 @@ class DialecticMixin:self._dialectic_empty_streak += 1self._prefetch_thread_started_at = time.monotonic()- thread = spawn_context_thread(_run, name=thread_name)+ thread = spawn_context_thread(_run, name=thread_name, owner=self)thread.start()self._prefetch_thread = threadreturn threaddiff --git a/plugins/memory/honcho/session.py b/plugins/memory/honcho/session.pyindex 75c50398bad..ea157d936b6 100644--- a/plugins/memory/honcho/session.py+++ b/plugins/memory/honcho/session.py@@ -116,6 +116,8 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMiself._async_queue: queue.Queue | None = queue.Queue() if self._write_frequency == "async" else Noneself._async_thread: threading.Thread | None = Noneself._async_thread_lock = threading.Lock()+ # Set by shutdown/stop_async_writer: no new threads after the join, late saves flush inline.+ self._shutting_down = False@propertydef honcho(self) -> Honcho:@@ -472,7 +474,9 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMiflushes now; "session" defers until flush_all(); int N flushes every N turns."""self._turn_counter += 1wf = self._write_frequency- if wf == "async":+ if self._shutting_down:+ self._flush_session(session)+ elif wf == "async":if self._async_queue is not None:self._ensure_async_writer()self._async_queue.put(session)@@ -504,17 +508,19 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMireturnwith self._async_thread_lock:if self._async_thread is None or not self._async_thread.is_alive():- self._async_thread = spawn_context_thread(self._async_writer_loop, name="honcho-async-writer")+ self._async_thread = spawn_context_thread(self._async_writer_loop, name="honcho-async-writer", owner=self)self._async_thread.start()def stop_async_writer(self) -> None:"""Join the async writer WITHOUT flushing (saveMessages: false must still exit cleanly)."""+ self._shutting_down = Trueif self._async_queue is not None and self._async_thread is not None and self._async_thread.is_alive():self._async_queue.put(_ASYNC_SHUTDOWN)self._async_thread.join(timeout=10)def shutdown(self) -> None:"""Flush everything, then stop the async writer thread."""+ self._shutting_down = Trueif self._async_queue is not None:self.flush_all()self.stop_async_writer()@@ -522,13 +528,17 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi# ----- Prefetch cache -----def prefetch_context(self, session_key: str, user_message: str | None = None) -> None:- """Fire get_prefetch_context in a background thread; consumed next turn via pop_context_result()."""+ """Fire get_prefetch_context in a background thread; consumed next turn via pop_context_result().+ No-op once shutdown began, so nothing is left running after the join."""+ if self._shutting_down:+ return+def _run():result = self.get_prefetch_context(session_key, user_message)if result:self.set_context_result(session_key, result)- spawn_context_thread(_run, name="honcho-context-prefetch").start()+ spawn_context_thread(_run, name="honcho-context-prefetch", owner=self).start()def set_context_result(self, session_key: str, result: dict[str, str]) -> None:"""Store a prefetched context result in a thread-safe way."""diff --git a/tests/honcho_plugin/test_shutdown.py b/tests/honcho_plugin/test_shutdown.pynew file mode 100644index 00000000000..30b45f0f32e--- /dev/null+++ b/tests/honcho_plugin/test_shutdown.py@@ -0,0 +1,173 @@+"""Provider shutdown joins every plugin thread within one budget (#37632, #33485, #60616)."""++import logging+import threading+import time+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++from plugins.memory.honcho import HonchoMemoryProvider+from plugins.memory.honcho import session as session_module+from plugins.memory.honcho.client import (+ HonchoClientConfig,+ close_honcho_clients,+ join_plugin_threads,+ spawn_context_thread,+)+from plugins.memory.honcho.client_cache import _client_slots, _client_slots_lock+from plugins.memory.honcho.session import HonchoSessionManager+from plugins.plugin_utils import SingletonSlot+++def async_manager(monkeypatch):+ fake = MagicMock()+ monkeypatch.setattr(session_module, "get_honcho_client", lambda *a, **k: fake)+ cfg = HonchoClientConfig(write_frequency="async", api_key="test-key", enabled=True)+ mgr = HonchoSessionManager(honcho=fake, config=cfg)+ mgr.fake_client = fake+ yield mgr+ mgr.shutdown()+++class _Owner:+ pass+++class TestThreadRegistry:+ def test_join_covers_only_the_given_owners(self):+ mine, theirs = _Owner(), _Owner()+ release = threading.Event()+ own = spawn_context_thread(lambda: release.wait(timeout=2), name="own", owner=mine)+ other = spawn_context_thread(lambda: release.wait(timeout=2), name="other", owner=theirs)+ own.start()+ other.start()+ try:+ started = time.monotonic()+ assert join_plugin_threads((theirs, None), timeout=0.05) == ["other"]+ release.set()+ assert join_plugin_threads((mine,), timeout=2) == []+ assert time.monotonic() - started < 1.5+ finally:+ release.set()+ own.join(timeout=1)+ other.join(timeout=1)+++class TestProviderShutdown:+ def _provider(self, manager, cfg=None):+ provider = HonchoMemoryProvider()+ provider._manager = manager+ provider._config = cfg or manager._config+ provider._session_key = "test-session"+ provider._session_initialized = True+ return provider++ def _shutdown_blocks_until(self, provider, release):+ """shutdown() off-thread must still be running until ``release`` is set, then finish."""+ done = threading.Event()+ threading.Thread(target=lambda: (provider.shutdown(), done.set()), daemon=True).start()+ try:+ assert not done.wait(timeout=0.05)+ release.set()+ assert done.wait(timeout=2)+ finally:+ release.set()++ def test_shutdown_waits_for_an_in_flight_context_prefetch(self, async_manager):+ provider = self._provider(async_manager)+ started, release = threading.Event(), threading.Event()++ def slow_prefetch(session_key, user_message=None):+ started.set()+ release.wait(timeout=2)+ return {"representation": "ready"}++ async_manager.get_prefetch_context = slow_prefetch+ async_manager.prefetch_context("test-session", "query")+ assert started.wait(timeout=1)+ self._shutdown_blocks_until(provider, release)+ assert not any(t.name == "honcho-context-prefetch" and t.is_alive() for t in threading.enumerate())++ def test_shutdown_joins_a_stalled_init_thread_within_the_budget(self, monkeypatch, caplog):+ monkeypatch.setattr(HonchoMemoryProvider, "_SHUTDOWN_JOIN_FLOOR", 0.2)+ cfg = HonchoClientConfig(api_key="test-key", enabled=True, timeout=0.1)+ release = threading.Event()+ entered = threading.Event()++ class StalledManager:+ def __init__(self, *args, **kwargs):+ pass++ def get_or_create(self, session_key):+ entered.set()+ release.wait(timeout=5)+ return SimpleNamespace(messages=[])++ def migrate_memory_files(self, *a, **k):+ pass++ monkeypatch.setattr("plugins.memory.honcho.client.HonchoClientConfig.from_global_config", lambda: cfg)+ monkeypatch.setattr("plugins.memory.honcho.client.get_honcho_client", lambda cfg: object())+ monkeypatch.setattr("plugins.memory.honcho.session.HonchoSessionManager", StalledManager)+ provider = HonchoMemoryProvider()+ provider.initialize("session-1", platform="cli")+ try:+ assert entered.wait(timeout=1)+ started = time.monotonic()+ with caplog.at_level(logging.WARNING, logger="plugins.memory.honcho"):+ provider.shutdown()+ assert 0.15 <= time.monotonic() - started < 1.0+ assert "honcho-session-init" in caplog.text+ assert "timed out after 0.2s" in caplog.text+ finally:+ release.set()+ provider._init_thread.join(timeout=2)++ def test_shutdown_joins_the_prewarm_dialectic_thread(self, async_manager):+ provider = self._provider(async_manager)+ release = threading.Event()+ async_manager.dialectic_query = lambda *a, **k: release.wait(timeout=2) and "answer"+ provider._spawn_dialectic("who?", thread_name="honcho-prewarm-dialectic", fired_at=0, log_label="prewarm")+ self._shutdown_blocks_until(provider, release)+ assert not provider._prefetch_thread.is_alive()++ def test_shutdown_does_not_close_the_shared_client(self, async_manager):+ provider = self._provider(async_manager)+ provider.shutdown()+ async_manager.fake_client._http.close.assert_not_called()++[email protected]("timeout, budget", [(60.0, 60.0), (2.0, 5.0), (None, 5.0)])+def test_shutdown_join_budget_is_the_floor_or_the_longer_timeout(timeout, budget):+ provider = HonchoMemoryProvider()+ provider._config = HonchoClientConfig(api_key="k", timeout=timeout) if timeout else SimpleNamespace()+ assert provider._shutdown_join_budget() == budget+++class TestManagerAfterShutdown:+ def test_prefetch_is_skipped_after_shutdown(self, async_manager):+ calls = []+ async_manager.get_prefetch_context = lambda *a, **k: calls.append(a) or {}+ async_manager.shutdown()+ async_manager.prefetch_context("test-session", "query")+ time.sleep(0.05)+ assert calls == []+++def test_close_honcho_clients_closes_every_pool_and_drops_the_slots():+ client = MagicMock()+ slot = SingletonSlot()+ slot.get(lambda: client)+ key = ("test", "close-me")+ with _client_slots_lock:+ _client_slots[key] = slot+ try:+ close_honcho_clients()+ finally:+ with _client_slots_lock:+ _client_slots.pop(key, None)+ client._http.close.assert_called_once_with()+ assert key not in _client_slots