Skip to content

The agent that grows with you

fix(gateway): the turn executor hands work to parked threads instead of starting one on the loop (#142061)

Teknium1754e49dd0fe
diff --git a/gateway/turn_executor.py b/gateway/turn_executor.py
index 3e642a1aae7..822c5df3686 100644
--- a/gateway/turn_executor.py
+++ b/gateway/turn_executor.py
@@ -3,60 +3,123 @@
from __future__ import annotations
import concurrent.futures
+import contextvars
+import logging
+import queue
import threading
+logger = logging.getLogger(__name__)
+
+# A parked worker exits after this long without work, so a burst's threads do not outlive it by much.
+_IDLE_TIMEOUT_S = 60.0
+
+
+class _Worker:
+ __slots__ = ("inbox", "thread")
+
+ def __init__(self) -> None:
+ self.thread: threading.Thread | None = None
+ self.inbox: queue.SimpleQueue = queue.SimpleQueue()
+
class _UnboundedThreadExecutor(concurrent.futures.Executor):
- """One thread per submitted work item; no queue, no cap.
+ """Every submitted item starts at once on its own thread; no queue, no cap.
``ThreadPoolExecutor(max_workers=None)`` is NOT unbounded (it is ``min(32, cpu_count + 4)``),
- which is the same silent queue at a larger number. Exposes ``_threads`` and ``_shutdown`` like
- ``ThreadPoolExecutor`` so ``_stop_pool`` / ``_shutdown_executor`` join and count its workers.
- Not ``tools.daemon_pool.DaemonThreadPoolExecutor(sys.maxsize)``: that keeps idle workers alive
- until shutdown, whereas here each thread exits when its turn ends.
+ which is the same silent queue at a larger number. An item goes to a parked (idle) worker when
+ one exists, otherwise to a new thread. Reuse matters because ``submit`` runs on the event loop
+ and ``Thread.start()`` waits there until the new thread gets the GIL: with many turns running,
+ every submit (the handoff watcher's 2 s idle gates included) froze the loop (#142061). Handing an
+ item to a parked worker is a queue put. A worker parked for ``idle_timeout`` exits.
+
+ A reused thread must look fresh to its next item: each item runs in an empty
+ ``contextvars.Context`` (what a new thread starts with), and ``reset_reused_thread_state`` drops
+ the thread-keyed state a turn leaves behind before the worker parks. A worker whose reset fails
+ is retired, never reused.
+
+ ``_threads`` holds the BUSY threads only, as before: ``_stop_pool`` / ``_shutdown_executor`` join
+ and count those. A parked worker holds no work; shutdown wakes it to exit.
"""
- def __init__(self, thread_name_prefix: str = ""):
+ def __init__(self, thread_name_prefix: str = "", idle_timeout: float = _IDLE_TIMEOUT_S):
self._prefix = thread_name_prefix
self._threads: set = set()
+ self._idle: list[_Worker] = []
self._shutdown = False
self._lock = threading.Lock()
self._n = 0
+ self._idle_timeout = idle_timeout
def submit(self, fn, /, *args, **kwargs):
fut: concurrent.futures.Future = concurrent.futures.Future()
-
- def _run():
- try:
- if not fut.set_running_or_notify_cancel():
- return
- try:
- fut.set_result(fn(*args, **kwargs))
- except BaseException as exc:
- fut.set_exception(exc)
- finally:
- # Blocks until submit() has registered this thread, so the discard never races the add.
- with self._lock:
- self._threads.discard(threading.current_thread())
-
- # One critical section for check + start + register (as ThreadPoolExecutor.submit does), so a
+ item = (fut, fn, args, kwargs)
+ # One critical section for check + hand-off/start + register (as ThreadPoolExecutor.submit does), so a
# concurrent shutdown() either refuses this item or sees its thread; never a live, uncounted one.
with self._lock:
if self._shutdown:
raise RuntimeError("cannot schedule new futures after shutdown")
+ if self._idle:
+ worker = self._idle.pop() # LIFO: the warmest thread; the coldest time out
+ self._threads.add(worker.thread)
+ worker.inbox.put(item)
+ return fut
self._n += 1
- t = threading.Thread(target=_run, name=f"{self._prefix}_{self._n}", daemon=True)
+ worker = _Worker()
+ # health: allow HX012 -- a worker serves many items; each runs in the context its caller captured (ctx.run)
+ t = threading.Thread(target=self._work, args=(worker, item), name=f"{self._prefix}_{self._n}", daemon=True)
+ worker.thread = t
# Start BEFORE registering: at the OS thread limit start() raises, and an unstarted thread
# left in _threads would make shutdown's join() raise and skip the quiesce decision.
t.start()
self._threads.add(t)
return fut
+ def _work(self, worker: _Worker, item) -> None:
+ while item is not None:
+ fut, fn, args, kwargs = item
+ del item
+ if fut.set_running_or_notify_cancel():
+ try:
+ fut.set_result(contextvars.Context().run(fn, *args, **kwargs))
+ except BaseException as exc: # health: allow BLE001 -- delivered to the item's future, as ThreadPoolExecutor does
+ fut.set_exception(exc)
+ del fut, fn, args, kwargs # a parked worker must not pin the last item's arguments
+ item = self._park(worker)
+
+ def _park(self, worker: _Worker):
+ """Reset this thread, then wait for its next item; None means exit."""
+ from gateway.turn_thread_reset import reset_reused_thread_state
+
+ try:
+ reset_reused_thread_state()
+ reusable = True
+ except Exception:
+ logger.warning("turn worker state reset failed; retiring the thread", exc_info=True)
+ reusable = False
+ # Taking the lock also waits for submit() to finish registering this thread.
+ with self._lock:
+ self._threads.discard(worker.thread)
+ if self._shutdown or not reusable:
+ return None
+ self._idle.append(worker)
+ try:
+ return worker.inbox.get(timeout=self._idle_timeout)
+ except queue.Empty:
+ with self._lock:
+ if worker in self._idle:
+ self._idle.remove(worker)
+ return None
+ # submit() claimed this worker as the timeout fired: its item is already on the way.
+ return worker.inbox.get()
+
def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
# cancel_futures is accepted for API parity only: there is no queue, so nothing is pending.
with self._lock:
self._shutdown = True
threads = list(self._threads)
+ idle, self._idle = self._idle, []
+ for worker in idle:
+ worker.inbox.put(None)
if wait:
for t in threads:
t.join()
diff --git a/gateway/turn_thread_reset.py b/gateway/turn_thread_reset.py
new file mode 100644
index 00000000000..cb6dcc74869
--- /dev/null
+++ b/gateway/turn_thread_reset.py
@@ -0,0 +1,50 @@
+"""Make a reused turn-executor thread look like a new one to its next item.
+
+Turn code keys some state by the running thread instead of by turn: ``tools.interrupt`` bits and
+reasons by thread id, per-turn callbacks in module ``threading.local`` objects, and the sudo
+password cache's thread scope (the fallback when a turn has no session key). A new thread starts
+with none of it; a parked executor worker (gateway/turn_executor.py) must drop all of it before it
+takes another session's turn, or turn 1's interrupt, approval callback or cached sudo password is
+live in turn 2. Context variables need nothing here: every item runs in a fresh context.
+
+Modules are looked up in ``sys.modules`` only: one that was never imported holds no state.
+A new per-turn ``threading.local`` in turn code belongs in ``_PER_TURN_THREAD_LOCALS``.
+"""
+
+from __future__ import annotations
+
+import sys
+import threading
+
+_PER_TURN_THREAD_LOCALS = (
+ ("tools.terminal_tool", "_callback_tls"),
+ ("tools.environments.base", "_activity_callback_local"),
+ ("tools.feishu_lark", "_local"),
+ ("agent.vault_backends.unlock", "_callback_tls"),
+ ("agent.vault_backends.unlock", "_current_session_tls"),
+ ("agent.auxiliary_client", "_aux_probe_state"),
+ ("agent.auxiliary_client", "_aux_interrupt_protection"),
+ ("agent.auxiliary_client", "_aux_progress"),
+ ("agent.auxiliary_client", "_aux_dispatch"),
+ ("agent.auxiliary_client", "_aux_provider_response"),
+ ("agent.auxiliary_client", "_aux_stream_deadline"),
+ ("agent.local_prompt_progress", "_reading"),
+ ("hermes_cli.plugins", "_thread_tool_whitelist"),
+ ("hermes_cli.observability.shared_metrics_events", "_compression_attempt"),
+)
+
+
+def reset_reused_thread_state() -> None:
+ """Drop the calling thread's turn-keyed state (call from the worker itself, between items)."""
+ tid = threading.get_ident()
+ interrupt = sys.modules.get("tools.interrupt")
+ if interrupt is not None:
+ interrupt.set_interrupt(False, tid) # clears the bit, its reason and a pending yield
+ sudo = sys.modules.get("tools.terminal_tool_sudo")
+ if sudo is not None:
+ with sudo._sudo_password_cache_lock:
+ sudo._sudo_password_cache.pop(f"thread:{tid}", None)
+ for module_name, attr in _PER_TURN_THREAD_LOCALS:
+ local = getattr(sys.modules.get(module_name), attr, None)
+ if local is not None:
+ local.__dict__.clear() # a threading.local's __dict__ is the calling thread's namespace
diff --git a/tests/gateway/test_turn_executor_reuse.py b/tests/gateway/test_turn_executor_reuse.py
new file mode 100644
index 00000000000..d2841d79aef
--- /dev/null
+++ b/tests/gateway/test_turn_executor_reuse.py
@@ -0,0 +1,85 @@
+"""The turn executor reuses parked workers, and a reused thread carries nothing from its last turn.
+
+``submit`` runs on the gateway loop. Starting a thread there waits until the new thread gets the
+GIL, which froze the loop on every submit while many turns ran (#142061); a parked worker takes
+the item with a queue put instead. Reuse is only safe if turn 1's thread-keyed state (interrupt
+bit, per-turn thread-locals, the thread-scoped sudo cache, context variables) is gone in turn 2.
+"""
+
+from __future__ import annotations
+
+import contextvars
+import threading
+import time
+
+from gateway.turn_executor import _UnboundedThreadExecutor
+
+
+def _wait_parked(ex, n=1):
+ deadline = time.monotonic() + 5
+ while len(getattr(ex, "_idle", ())) < n: # a thread-per-item executor never parks one
+ assert time.monotonic() < deadline, "the worker never parked"
+ time.sleep(0.01)
+
+
+def test_a_reused_worker_sees_none_of_the_previous_turns_thread_state():
+ from hermes_constants import get_hermes_home, set_hermes_home_override
+ from tools import interrupt, terminal_tool
+ from tools import terminal_tool_sudo as sudo
+
+ fresh_home = contextvars.Context().run(get_hermes_home)
+ ex = _UnboundedThreadExecutor("reuse-probe")
+ try:
+ def turn_one():
+ interrupt.set_interrupt(True, reason="user pressed stop")
+ terminal_tool._callback_tls.approval = "session-a approval callback"
+ set_hermes_home_override("/profiles/session-a") # left set: the turn never resets it
+ sudo._sudo_password_cache[f"thread:{threading.get_ident()}"] = "session-a sudo password"
+ return threading.get_ident()
+
+ first = ex.submit(turn_one).result(5)
+ _wait_parked(ex)
+
+ def turn_two():
+ return dict(
+ tid=threading.get_ident(),
+ interrupted=interrupt.is_interrupted(),
+ reason=interrupt.get_interrupt_reason(),
+ approval=getattr(terminal_tool._callback_tls, "approval", None),
+ home=get_hermes_home(),
+ sudo=sudo._sudo_password_cache.get(f"thread:{threading.get_ident()}"),
+ )
+
+ seen = ex.submit(turn_two).result(5)
+ assert seen.pop("tid") == first, "the parked worker was not reused"
+ assert seen == dict(interrupted=False, reason=None, approval=None, home=fresh_home, sudo=None)
+ finally:
+ ex.shutdown(wait=True)
+
+
+def test_submit_to_a_parked_worker_starts_no_thread_and_shutdown_releases_it(monkeypatch):
+ from gateway.run import GatewayRunner
+
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner._executor_lock = threading.Lock()
+ runner._executor = None
+ runner._housekeeping_executor = None
+ runner._executor_closing = False
+ ex = runner._get_executor()
+ assert isinstance(ex, _UnboundedThreadExecutor)
+ ex.submit(lambda: None).result(5)
+ _wait_parked(ex)
+ parked = ex._idle[0].thread
+ assert parked is not None
+
+ def no_thread_start(self):
+ raise AssertionError("submit started a thread on the event loop while a worker was parked")
+
+ with monkeypatch.context() as m:
+ m.setattr(threading.Thread, "start", no_thread_start)
+ assert ex.submit(lambda: "ran").result(5) == "ran"
+ _wait_parked(ex)
+ # A parked worker holds no work: shutdown counts nothing live and the worker exits.
+ assert runner._shutdown_executor(drain_timeout=5) == 0
+ parked.join(5)
+ assert not parked.is_alive()