The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): bound and cycle-check the concurrent plugin load wait
Teknium1f11e7fa23f5
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex f1e22dbcce3..57cbab1c06a 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -2977,27 +2977,19 @@ def _pre_compress_memory_context(agent: Any, messages: list, checkpoint_requiredmemory_context = ""memory_manager = getattr(agent, "_memory_manager", None)evidence_messages = _direct_messages_for_pre_compress_memory(messages)- # Detached review/side-question forks cannot persist checkpoints by design. Their- # isolated compressor has no memory manager, session database, or persistence.- # Do not weaken the fork's configured flag globally: native compaction still uses it.- if (checkpoint_required and getattr(agent, "_persist_disabled", False)- and getattr(agent, "_session_db", None) is None- and memory_manager is None):- checkpoint_required = False+ # A detached review/side-question fork (no memory manager, session DB or persistence) cannot checkpoint by design.+ if checkpoint_required and getattr(agent, "_persist_disabled", False) and memory_manager is None:+ checkpoint_required = getattr(agent, "_session_db", None) is not Noneif checkpoint_required:supports_checkpoint = getattr(memory_manager, "supports_pre_compress_checkpoint", None)if memory_manager is None or not callable(supports_checkpoint):- raise _checkpoint_incapable(- f"no active provider implements checkpoint API v{PRE_COMPRESS_CHECKPOINT_API_VERSION}"- )+ raise _checkpoint_incapable(f"no active provider implements checkpoint API v{PRE_COMPRESS_CHECKPOINT_API_VERSION}")try:compatible = bool(supports_checkpoint(PRE_COMPRESS_CHECKPOINT_API_VERSION))except Exception as exc:raise _checkpoint_blocked("provider capability probe failed") from excif not compatible:- raise _checkpoint_incapable(- f"active provider does not implement checkpoint API v{PRE_COMPRESS_CHECKPOINT_API_VERSION}"- )+ raise _checkpoint_incapable(f"active provider does not implement checkpoint API v{PRE_COMPRESS_CHECKPOINT_API_VERSION}")try:_maybe_ctx = memory_manager.on_pre_compress(messages, evidence_messages=evidence_messages, require_checkpoint=True,diff --git a/plugins/plugin_loader.py b/plugins/plugin_loader.pyindex c9f2893e410..37abb8ae681 100644--- a/plugins/plugin_loader.py+++ b/plugins/plugin_loader.py@@ -11,6 +11,7 @@ import importlib.utilimport loggingimport sysimport threading+import timefrom pathlib import Pathfrom typing import Any, Callable, List, Optional, Tuple@@ -19,6 +20,34 @@ _log = logging.getLogger(__name__)_PLUGINS_ROOT = Path(__file__).parent_MODULE_LOAD_LOCKS: dict[str, threading.RLock] = {}_MODULE_LOAD_LOCKS_GUARD = threading.Lock()+# How long a second caller waits for another thread's in-flight load of the same module. Past it+# the module is marked stalled (a hung import) and later callers refuse at once until it finishes.+_CONCURRENT_LOAD_WAIT_SECS = 10.0+_STALLED_LOADS: set[str] = set()+_LOAD_OWNERS: dict[str, int] = {} # module -> thread id running its load+_LOAD_WAITERS: dict[int, str] = {} # thread id -> module whose load it waits for+++def _waits_for(tid: int) -> set:+ """Threads *tid* is blocked on: a loader lock owner, or an importlib module-lock owner."""+ owners = {_LOAD_OWNERS.get(_LOAD_WAITERS.get(tid, ""))}+ blocked = getattr(importlib._bootstrap, "_blocking_on", {}).get(tid) # list on 3.12+, lock on 3.11+ owners.update(getattr(lk, "owner", None) for lk in (blocked if isinstance(blocked, list) else [blocked]))+ return owners - {None}+++def _load_would_deadlock(me: int) -> bool:+ """Whether the wait graph (loader locks + importlib's module locks) leads back to *me*.+ importlib cannot see the loader lock in its own deadlock check, so walk both kinds here."""+ seen, todo = set(), list(_waits_for(me))+ while todo:+ tid = todo.pop()+ if tid == me:+ return True+ if tid not in seen:+ seen.add(tid)+ todo.extend(_waits_for(tid))+ return Falsedef _module_load_lock(module_name: str) -> threading.RLock:@@ -116,41 +145,72 @@ def load_plugin_module(module_name: str, plugin_dir: Path, *, parents: Tuple[str# _new_module publishes a package shell before executing it so sibling relative# imports work. Serialize the complete load so another thread cannot observe# that half-built shell as a loaded plugin.- with _module_load_lock(module_name):- # A synthetic package shell has no __file__; only reuse modules loaded from disk.- cached = sys.modules.get(module_name)- if cached is not None and getattr(cached, "__file__", None):- return cached- for parent in parents:- parent_path = _PLUGINS_ROOT.joinpath(*parent.split(".")[1:])- if parent not in sys.modules and (parent_path / "__init__.py").exists():- _exec(_new_module(parent, parent_path / "__init__.py", [str(parent_path)]))- if synthetic_namespace:- register_synthetic_package(synthetic_namespace, [])- # Reserve the name before siblings exec so their relative imports resolve.- mod = _new_module(module_name, init_file, [str(plugin_dir)])- if mod is None:- return None- loaded_submodules = []- for sub_file in plugin_dir.glob("*.py"):- full_sub_name = f"{module_name}.{sub_file.stem}"- if sub_file.name == "__init__.py" or full_sub_name in sys.modules:- continue- sub_mod = _new_module(full_sub_name, sub_file)- if _exec(sub_mod, logger):- loaded_submodules.append((sub_file.stem, sub_mod))- else:- sys.modules.pop(full_sub_name, None)- if not _exec(mod, logger):- sys.modules.pop(module_name, None)- return None- parent_name, child_name = module_name.rsplit(".", 1)- parent_mod = sys.modules.get(parent_name)- if parent_mod is not None:- setattr(parent_mod, child_name, mod)- for sub_name, sub_mod in loaded_submodules:- setattr(mod, sub_name, sub_mod)- return mod+ # The wait is bounded (a hung import must not block every caller) and polls for a cross-thread+ # cycle through importlib's module locks; in a cycle, accept the partial module like importlib does.+ lock, me = _module_load_lock(module_name), threading.get_ident()+ deadline = time.monotonic() + (0 if module_name in _STALLED_LOADS else _CONCURRENT_LOAD_WAIT_SECS)+ _LOAD_WAITERS[me] = module_name+ try:+ while not lock.acquire(timeout=0.05):+ if _load_would_deadlock(me):+ logger.debug("Concurrent circular load of %s; using the partial module", module_name)+ return sys.modules.get(module_name)+ if time.monotonic() >= deadline:+ _STALLED_LOADS.add(module_name)+ logger.warning("Skipping plugin %s: another thread's load of it has not finished "+ "(import still running after %.0fs)", module_name, _CONCURRENT_LOAD_WAIT_SECS)+ return None+ finally:+ _LOAD_WAITERS.pop(me, None)+ outermost = module_name not in _LOAD_OWNERS # the RLock re-enters on this thread's recursive loads+ _LOAD_OWNERS.setdefault(module_name, me)+ try:+ return _load_plugin_module_locked(module_name, plugin_dir, init_file, parents, logger,+ synthetic_namespace)+ finally:+ if outermost:+ _LOAD_OWNERS.pop(module_name, None)+ _STALLED_LOADS.discard(module_name)+ lock.release()+++def _load_plugin_module_locked(module_name: str, plugin_dir: Path, init_file: Path,+ parents: Tuple[str, ...], logger: logging.Logger,+ synthetic_namespace: Optional[str]) -> Optional[Any]:+ # A synthetic package shell has no __file__; only reuse modules loaded from disk.+ cached = sys.modules.get(module_name)+ if cached is not None and getattr(cached, "__file__", None):+ return cached+ for parent in parents:+ parent_path = _PLUGINS_ROOT.joinpath(*parent.split(".")[1:])+ if parent not in sys.modules and (parent_path / "__init__.py").exists():+ _exec(_new_module(parent, parent_path / "__init__.py", [str(parent_path)]))+ if synthetic_namespace:+ register_synthetic_package(synthetic_namespace, [])+ # Reserve the name before siblings exec so their relative imports resolve.+ mod = _new_module(module_name, init_file, [str(plugin_dir)])+ if mod is None:+ return None+ loaded_submodules = []+ for sub_file in plugin_dir.glob("*.py"):+ full_sub_name = f"{module_name}.{sub_file.stem}"+ if sub_file.name == "__init__.py" or full_sub_name in sys.modules:+ continue+ sub_mod = _new_module(full_sub_name, sub_file)+ if _exec(sub_mod, logger):+ loaded_submodules.append((sub_file.stem, sub_mod))+ else:+ sys.modules.pop(full_sub_name, None)+ if not _exec(mod, logger):+ sys.modules.pop(module_name, None)+ return None+ parent_name, child_name = module_name.rsplit(".", 1)+ parent_mod = sys.modules.get(parent_name)+ if parent_mod is not None:+ setattr(parent_mod, child_name, mod)+ for sub_name, sub_mod in loaded_submodules:+ setattr(mod, sub_name, sub_mod)+ return modclass NoopPluginContext:diff --git a/tests/plugins/test_plugin_loader.py b/tests/plugins/test_plugin_loader.pyindex 34915b624a9..d57e0624d26 100644--- a/tests/plugins/test_plugin_loader.py+++ b/tests/plugins/test_plugin_loader.py@@ -2,6 +2,7 @@from __future__ import annotations+import importlibimport loggingimport sysimport threading@@ -72,8 +73,12 @@ def test_successful_sibling_remains_available_on_loaded_module(tmp_path):sys.modules.pop(name, None)-def test_concurrent_load_waits_for_the_first_load_to_finish(tmp_path):- """A second caller must never receive the half-built shell published mid-load."""+def test_concurrent_load_waits_bounded_for_the_first_load(tmp_path, monkeypatch):+ """A second caller never receives the half-built shell published mid-load, and a hung import+ in the first caller does not block it forever: it refuses after the bounded wait."""+ import plugins.plugin_loader as loader++ monkeypatch.setattr(loader, "_CONCURRENT_LOAD_WAIT_SECS", 0.3)plugin_dir = tmp_path / "plugin"plugin_dir.mkdir()gate_name = "_test_plugin_loader_race_gate"@@ -89,8 +94,8 @@ def test_concurrent_load_waits_for_the_first_load_to_finish(tmp_path):results = {}def load(key):- mod = load_plugin_module(module_name, plugin_dir, parents=(), logger=logging.getLogger(__name__))- results[key] = hasattr(mod, "register")+ results[key] = load_plugin_module(module_name, plugin_dir, parents=(),+ logger=logging.getLogger(__name__))first = threading.Thread(target=load, args=("first",))second = threading.Thread(target=load, args=("second",))@@ -98,15 +103,48 @@ def test_concurrent_load_waits_for_the_first_load_to_finish(tmp_path):first.start()assert gate.entered.wait(5)second.start()- second.join(0.5)+ second.join(5)+ assert not second.is_alive(), "second caller blocked on the hung first load"+ assert results["second"] is None+ load("stalled") # later callers refuse at once while the import is still hung+ assert results["stalled"] is Nonegate.release.set()first.join(10)- second.join(10)-- assert results == {"first": True, "second": True}+ assert hasattr(results["first"], "register")+ load("after")+ assert results["after"] is results["first"]++ # A cross-thread cycle through importlib's own module lock (thread A imports a helper that+ # loads the plugin; thread B loads the plugin, which imports the helper) must not deadlock.+ monkeypatch.setattr(loader, "_CONCURRENT_LOAD_WAIT_SECS", 60)+ cyc_dir, helper = tmp_path / "cyc", "_test_plugin_loader_cycle_helper"+ cyc_dir.mkdir()+ cyc_name = "test_plugin_loader_package.cycle"+ gate.helper, gate.loader = threading.Event(), threading.Event()+ monkeypatch.syspath_prepend(str(tmp_path))+ (tmp_path / f"{helper}.py").write_text(+ f"import sys, logging, pathlib\nfrom plugins.plugin_loader import load_plugin_module\n"+ f"gate = sys.modules[{gate_name!r}]\ngate.helper.set()\ngate.loader.wait(10)\n"+ f"mod = load_plugin_module({cyc_name!r}, pathlib.Path({str(cyc_dir)!r}), parents=(),"+ " logger=logging.getLogger('x'))\n", encoding="utf-8")+ (cyc_dir / "__init__.py").write_text(+ f"import sys\nsys.modules[{gate_name!r}].loader.set()\nimport {helper}\n"+ "def register(ctx):\n pass\n", encoding="utf-8")+ a = threading.Thread(target=importlib.import_module, args=(helper,), daemon=True)+ b = threading.Thread(target=load_plugin_module, args=(cyc_name, cyc_dir),+ kwargs={"parents": (), "logger": logging.getLogger(__name__)}, daemon=True)+ a.start()+ assert gate.helper.wait(5)+ b.start()+ a.join(5)+ b.join(5)+ assert not a.is_alive() and not b.is_alive(), "loader lock and import lock deadlocked"+ assert hasattr(sys.modules[cyc_name], "register")finally:gate.release.set()+ getattr(gate, "loader", threading.Event()).set()sys.modules.pop(gate_name, None)+ sys.modules.pop("_test_plugin_loader_cycle_helper", None)for name in tuple(sys.modules):- if name == module_name or name.startswith(f"{module_name}."):+ if name.startswith("test_plugin_loader_package."):sys.modules.pop(name, None)