Skip to content

The agent that grows with you

fix(acp): warm numpy with the memory provider so hindsight is covered too (#58083)

teknium180f4c6d6bfe5
diff --git a/acp_adapter/entry.py b/acp_adapter/entry.py
index 9f855e36519..0851ad16766 100644
--- a/acp_adapter/entry.py
+++ b/acp_adapter/entry.py
@@ -158,16 +158,11 @@ def _run_setup_browser(assume_yes: bool = False) -> int:
def _warm_memory_provider_import(logger: logging.Logger) -> None:
- """Import ``memory.provider``'s module (no provider instance) before any thread exists."""
- try:
- from hermes_cli.config import load_config
- from plugins.memory import import_memory_provider_module
+ """Import ``memory.provider``'s module + numpy (no provider instance) before the ACP threads start."""
+ from plugins.memory import import_memory_provider_module
- name = str(((load_config() or {}).get("memory") or {}).get("provider") or "").strip()
- if name and not import_memory_provider_module(name):
- logger.debug("memory provider %r not warmed; agent init will report the real error", name)
- except Exception:
- logger.debug("memory provider warm-up skipped", exc_info=True)
+ if not import_memory_provider_module():
+ logger.debug("memory provider not warmed (none configured or import failed; agent init reports that)")
def main(argv: list[str] | None = None) -> None:
@@ -195,11 +190,12 @@ def main(argv: list[str] | None = None) -> None:
import acp
from .server import HermesACPAgent
- # Windows: import the configured memory provider on the main thread while it is still
- # the ONLY thread. A first-time native-extension import (numpy via holographic /
- # mnemosyne / hindsight) racing the MCP-discovery or ACP stdin-reader thread's import
- # chain deadlocked in create_module and session/new never answered (#58083). After
- # this the off-loop agent build finds the module in sys.modules.
+ # Windows: import the configured memory provider (and numpy) on the main thread before
+ # the MCP-discovery and ACP stdin-reader threads start (hermes_cli's ~150 ms
+ # plugin-discovery thread is the only one already running). A first-time
+ # native-extension import (numpy via holographic / mnemosyne / hindsight) racing another
+ # thread's import chain deadlocked in create_module and session/new never answered
+ # (#58083). After this the off-loop agent build finds the modules in sys.modules.
if sys.platform == "win32":
_warm_memory_provider_import(logger)
diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.py
index 8c293e2887e..c1a06c8f8d0 100644
--- a/plugins/memory/__init__.py
+++ b/plugins/memory/__init__.py
@@ -31,6 +31,8 @@ ENTRY_POINTS_GROUP = "hermes_agent.memory_providers"
# Per Hermes home (plugin managers are per home too): pruning under one multiplexed profile must
# only retract that profile's provider skills, never a sibling profile's.
_REGISTERED_MEMORY_PROVIDER_SKILLS: dict[str, dict[str, Path]] = {}
+# Native extensions whose first import must not race another thread (#58083 warm-up).
+_NATIVE_WARM_IMPORTS: Tuple[str, ...] = ("numpy",)
def _registered_skills_for_active_home() -> dict[str, Path]:
@@ -209,25 +211,39 @@ def load_memory_provider(name: str, *, register_skills: Optional[bool] = None) -
return _loader.load_named(name, provider_dir, _load, kind="Memory provider", noun="provider", logger=logger)
-def import_memory_provider_module(name: str) -> bool:
- """Import the configured provider's module WITHOUT constructing a provider — the
- later ``load_memory_provider`` then hits ``sys.modules`` instead of a fresh native
- extension load. Exists so ``hermes acp`` can pay the heavy import (numpy / ML stack)
- on the main thread before any other thread starts: on Windows a first-time native
- import racing another thread's import chain deadlocked ``session/new`` (#58083).
- False when the provider is unknown or its import fails (agent init reports that)."""
+def import_memory_provider_module(name: Optional[str] = None) -> bool:
+ """Import the provider's module (default: the configured ``memory.provider``) WITHOUT
+ constructing a provider — the later ``load_memory_provider`` then hits ``sys.modules``
+ instead of a fresh native extension load. Exists so ``hermes acp`` can pay the heavy
+ import (numpy / ML stack) on the main thread before any other thread starts: on Windows
+ a first-time native import racing another thread's import chain deadlocked
+ ``session/new`` (#58083). False when no provider is configured, the provider is
+ unknown or its import fails (agent init reports that)."""
+ name = name or _get_active_memory_provider()
+ if not name:
+ return False
+ imported = False
try:
if provider_dir := find_provider_dir(name):
- return _loader.load_plugin_module(
+ imported = _loader.load_plugin_module(
_module_name(provider_dir, name), provider_dir, parents=("plugins", "plugins.memory"),
logger=logger, synthetic_namespace=None if _is_bundled(provider_dir) else _USER_NAMESPACE,
) is not None
- if (entry_point := find_provider_entry_point(name)) is not None:
+ elif (entry_point := find_provider_entry_point(name)) is not None:
entry_point.load()
- return True
+ imported = True
except Exception:
logger.debug("memory provider '%s' warm-up import failed", name, exc_info=True)
- return False
+ if imported:
+ # The deadlock is numpy's lazy ``_core`` init; hindsight defers that import to
+ # ``is_available()`` (sentence_transformers), so the provider module alone leaves
+ # it unwarmed. Every reporter's workaround was a plain ``import numpy`` up front.
+ for module in _NATIVE_WARM_IMPORTS:
+ try:
+ importlib.import_module(module)
+ except Exception:
+ logger.debug("warm-up import of %s skipped", module, exc_info=True)
+ return imported
def _instantiate_subclass(namespace) -> Optional["MemoryProvider"]:
diff --git a/tests/acp_adapter/test_session_construction_off_loop.py b/tests/acp_adapter/test_session_construction_off_loop.py
index 465dd866326..8ed943476d4 100644
--- a/tests/acp_adapter/test_session_construction_off_loop.py
+++ b/tests/acp_adapter/test_session_construction_off_loop.py
@@ -12,6 +12,8 @@ import time
import pytest
+from acp.schema import TextContentBlock
+
from acp_adapter.server import HermesACPAgent
from acp_adapter.session import SessionManager
@@ -47,6 +49,41 @@ async def test_new_session_keeps_the_event_loop_free():
assert ticks >= 5, f"event loop was blocked during session construction (ticks={ticks})"
+ lambda s: s.prompt([TextContentBlock(type="text", text="hi")], "gone"),
+ lambda s: s.cancel("gone"),
+ lambda s: s.set_session_model("m", "gone"),
+ lambda s: s.set_session_mode("ask", "gone"),
+ lambda s: s.set_config_option("edit_approval_policy", "gone", "ask"),
+])
+async def test_handlers_restore_unknown_sessions_off_the_loop(call):
+ """``get_session`` on a not-in-memory id restores from the DB (full agent build) and
+ waits on the restore lock; the per-session handlers must not do that on the loop."""
+ manager = SessionManager(agent_factory=_slow_factory)
+
+ def slow_restore(session_id):
+ time.sleep(BUILD_SECONDS)
+ return None
+
+ manager._restore = slow_restore
+ server = HermesACPAgent(session_manager=manager)
+ ticks = 0
+ done = asyncio.Event()
+
+ async def ticker():
+ nonlocal ticks
+ while not done.is_set():
+ ticks += 1
+ await asyncio.sleep(0.02)
+
+ task = asyncio.ensure_future(ticker())
+ await call(server)
+ done.set()
+ await task
+ assert ticks >= 5, f"event loop was blocked during the session restore (ticks={ticks})"
+
+
def test_concurrent_restores_of_one_session_build_a_single_agent():
"""Off-loop restores can now overlap: two ``get_session`` calls for the same
not-in-memory id must share one DB restore, not construct two agents."""
@@ -73,11 +110,13 @@ def test_concurrent_restores_of_one_session_build_a_single_agent():
def test_import_memory_provider_module_imports_without_constructing(tmp_path, monkeypatch):
"""The ACP startup warm-up (Windows main-thread pre-import, #58083) imports the
- configured provider's module and nothing more: no provider instance, no register()."""
+ configured provider's module plus the native stack it defers (hindsight imports numpy
+ only in ``is_available()``), and nothing more: no provider instance, no register()."""
import sys
from plugins import memory as memory_plugins
+
provider = tmp_path / "plugins" / "warmprov"
provider.mkdir(parents=True)
(provider / "__init__.py").write_text(
@@ -86,6 +125,11 @@ def test_import_memory_provider_module_imports_without_constructing(tmp_path, mo
"def register(ctx):\n sys.modules['_warmprov_registered'] = True\n",
encoding="utf-8",
)
+ native = tmp_path / "plugins" / "_warm_native.py"
+ native.write_text("import sys\nsys.modules['_warm_native_marker'] = True\n", encoding="utf-8")
+ monkeypatch.syspath_prepend(str(tmp_path / "plugins"))
+ monkeypatch.setattr(memory_plugins, "_NATIVE_WARM_IMPORTS", ("_warm_native",), raising=False)
+ sys.modules.pop("_warm_native_marker", None)
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
monkeypatch.setattr(memory_plugins, "_external_source_dirs", lambda: [tmp_path / "plugins"])
sys.modules.pop("_warmprov_marker", None)
@@ -93,5 +137,6 @@ def test_import_memory_provider_module_imports_without_constructing(tmp_path, mo
assert memory_plugins.import_memory_provider_module("warmprov") is True
assert sys.modules.get("_warmprov_marker") is True
+ assert sys.modules.get("_warm_native_marker") is True
assert "_warmprov_registered" not in sys.modules
assert memory_plugins.import_memory_provider_module("no-such-provider") is False