Skip to content

The agent that grows with you

fix(plugins): agent builds wait out a slow provider import; only per-turn callers are bounded

Teknium3a6d709921b1
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index b9b8f72dda8..0c16754eb0a 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -86,7 +86,9 @@ class GatewayAgentCacheMixin:
instance = cls._MEMORY_IDENTITY_PROVIDER_MEMO.get(name)
if instance is None:
from plugins.memory import load_memory_provider
- instance = load_memory_provider(name, register_skills=False)
+ from plugins.plugin_loader import bounded_load_wait
+ with bounded_load_wait(): # runs every turn: never stall on another thread's hung import
+ instance = load_memory_provider(name, register_skills=False)
if instance is None:
return {}
cls._MEMORY_IDENTITY_PROVIDER_MEMO[name] = instance
diff --git a/plugins/plugin_loader.py b/plugins/plugin_loader.py
index 37abb8ae681..038ddc710e1 100644
--- a/plugins/plugin_loader.py
+++ b/plugins/plugin_loader.py
@@ -12,6 +12,7 @@ import logging
import sys
import threading
import time
+from contextvars import ContextVar
from pathlib import Path
from typing import Any, Callable, List, Optional, Tuple
@@ -20,9 +21,11 @@ _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.
+# Inside bounded_load_wait(), 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 bounded callers
+# refuse at once until it finishes. Other callers (agent builds) wait for the load to finish.
_CONCURRENT_LOAD_WAIT_SECS = 10.0
+_BOUNDED_WAIT: ContextVar[bool] = ContextVar("plugin_load_bounded_wait", default=False)
_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
@@ -50,6 +53,17 @@ def _load_would_deadlock(me: int) -> bool:
return False
+def bounded_load_wait():
+ """For per-turn callers that must not stall on another thread's hung plugin import: their
+ loads give up (None) after ``_CONCURRENT_LOAD_WAIT_SECS`` instead of waiting it out."""
+ token = _BOUNDED_WAIT.set(True)
+ try:
+ yield
+ finally:
+ _BOUNDED_WAIT.reset(token)
+
+
def _module_load_lock(module_name: str) -> threading.RLock:
with _MODULE_LOAD_LOCKS_GUARD:
return _MODULE_LOAD_LOCKS.setdefault(module_name, threading.RLock())
@@ -145,10 +159,11 @@ 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.
- # 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.
+ # The wait polls for a cross-thread cycle through importlib's module locks; in a cycle, accept the
+ # partial module like importlib does. It is bounded only inside bounded_load_wait() (per-turn callers).
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)
+ deadline = float("inf") if not _BOUNDED_WAIT.get() else 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):
diff --git a/tests/plugins/test_plugin_loader.py b/tests/plugins/test_plugin_loader.py
index d57e0624d26..5481eada5ba 100644
--- a/tests/plugins/test_plugin_loader.py
+++ b/tests/plugins/test_plugin_loader.py
@@ -73,9 +73,9 @@ def test_successful_sibling_remains_available_on_loaded_module(tmp_path):
sys.modules.pop(name, None)
-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."""
+def test_concurrent_load_waits_for_the_first_load(tmp_path, monkeypatch):
+ """A second caller never receives the half-built shell published mid-load. An agent build waits
+ out a slow first import; a per-turn caller in bounded_load_wait() refuses after the bound instead."""
import plugins.plugin_loader as loader
monkeypatch.setattr(loader, "_CONCURRENT_LOAD_WAIT_SECS", 0.3)
@@ -97,21 +97,31 @@ def test_concurrent_load_waits_bounded_for_the_first_load(tmp_path, monkeypatch)
results[key] = load_plugin_module(module_name, plugin_dir, parents=(),
logger=logging.getLogger(__name__))
+ def bounded(key):
+ with loader.bounded_load_wait():
+ load(key)
+
first = threading.Thread(target=load, args=("first",))
- second = threading.Thread(target=load, args=("second",))
+ build = threading.Thread(target=load, args=("build",))
+ turn = threading.Thread(target=bounded, args=("turn",))
try:
first.start()
assert gate.entered.wait(5)
- second.start()
- 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
+ build.start()
+ build.join(1) # well past the bound
+ assert build.is_alive(), f"agent build gave up on a slow import: {results.get('build')!r}"
+ turn.start()
+ turn.join(5)
+ assert not turn.is_alive(), "per-turn caller blocked on the hung first load"
+ assert results["turn"] is None
+ bounded("stalled") # later bounded callers refuse at once while the import is still hung
assert results["stalled"] is None
gate.release.set()
first.join(10)
+ build.join(10)
assert hasattr(results["first"], "register")
- load("after")
+ assert results["build"] is results["first"]
+ bounded("after")
assert results["after"] is results["first"]
# A cross-thread cycle through importlib's own module lock (thread A imports a helper that