Skip to content

The agent that grows with you

fix(gateway): a turn's active-session lease is released off the event loop

Teknium00b8340b9d84
diff --git a/gateway/active_lease_io.py b/gateway/active_lease_io.py
new file mode 100644
index 00000000000..d53c2647292
--- /dev/null
+++ b/gateway/active_lease_io.py
@@ -0,0 +1,37 @@
+"""Active-session lease releases off the gateway event loop.
+
+``ActiveSessionLease.release()`` takes the registry's file lock, re-reads and prunes the JSON (a
+liveness probe per entry) and atomically rewrites it. Every turn end ran it on the loop, a measured
+recurring stall with many turns finishing. Releases go to ONE worker so they land in the order the
+turns ended. A release that lands after the same session's next acquire is harmless: the registry
+drops entries by lease id and that acquire re-keyed the entry to its own id. The lease pinned its
+registry path at acquisition, so the worker needs no profile scope.
+"""
+
+from __future__ import annotations
+
+import concurrent.futures
+import logging
+import threading
+
+logger = logging.getLogger(__name__)
+
+_pool: concurrent.futures.ThreadPoolExecutor | None = None
+_pool_lock = threading.Lock()
+
+
+def release_soon(lease) -> None:
+ """Queue *lease*'s release; returns at once."""
+ global _pool
+ with _pool_lock:
+ if _pool is None:
+ _pool = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix="active-lease-io")
+ pool = _pool
+ pool.submit(_release, lease)
+
+
+def _release(lease) -> None:
+ try:
+ lease.release()
+ except Exception:
+ logger.debug("Failed to release active session slot", exc_info=True)
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index d1d86da165e..3e5bee60c58 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -307,10 +307,8 @@ class GatewayAgentCacheMixin:
state = self._peek_session_state(session_key)
if state is not None:
if state.turn.lease is not None:
- try:
- state.turn.lease.release()
- except Exception:
- logger.debug("Failed to release active session slot", exc_info=True)
+ from gateway.active_lease_io import release_soon
+ release_soon(state.turn.lease)
# One structured reset instead of a drifting pop-list. Turn-lease tokens are deliberately NOT
# cleared here — _release_turn_lease owns them.
state.turn.clear()
diff --git a/tests/gateway/test_active_lease_release_off_loop.py b/tests/gateway/test_active_lease_release_off_loop.py
new file mode 100644
index 00000000000..3dd8644be57
--- /dev/null
+++ b/tests/gateway/test_active_lease_release_off_loop.py
@@ -0,0 +1,33 @@
+"""A turn end's active-session lease release never runs on the caller (the gateway loop).
+
+The release takes the registry's file lock and rewrites its JSON; at every turn end that was a
+measured loop stall. It is queued to one ordered worker instead, and still lands.
+"""
+
+import threading
+import time
+
+from gateway.active_lease_io import release_soon
+from hermes_cli import active_sessions
+
+
+def test_a_queued_release_returns_while_the_registry_is_locked_and_lands_after(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ lease, refusal = active_sessions.try_acquire_active_session(
+ session_id='s1', surface='gateway:local', config={}, registry_home=tmp_path)
+ assert refusal is None and lease is not None
+ assert lease.lock_path is not None and lease.state_path is not None
+ held = active_sessions._FileLock(lease.lock_path) # another process mid-rewrite
+ held.__enter__()
+ try:
+ started = time.monotonic()
+ release_soon(lease)
+ assert time.monotonic() - started < 0.5, "the release waited on the registry lock in the caller"
+ assert threading.current_thread() is threading.main_thread()
+ finally:
+ held.__exit__(None, None, None)
+ deadline = time.monotonic() + 5
+ while not lease.released:
+ assert time.monotonic() < deadline, "the queued release never landed"
+ time.sleep(0.02)
+ assert active_sessions._read_entries(lease.state_path) == []