Skip to content

The agent that grows with you

fix(gateway): read the RPC owner scope and ancillary polls off the event loop

kshitijk4poor8e13a8090a93
diff --git a/gateway/run.py b/gateway/run.py
index 94b141951b6..51cea0b66e1 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1794,7 +1794,7 @@ def _load_profile_secret_scope(profile_home: Path) -> dict:
@_contextmanager
def _profile_runtime_scope(
profile_home: Path, prepared_secret_scope: Optional[dict] = None, *,
- hydrate_secrets: bool = True):
+ hydrate_secrets: bool = True, prepared_terminal_scope: Optional[dict] = None):
"""Scope config/skills/memory AND credentials to a profile for one turn (multiplexed path only).
``set_hermes_home_override`` is a contextvar (reaches the agent worker via ``copy_context()``);
``set_secret_scope`` makes the profile ``.env`` the credential source without mutating
@@ -1818,7 +1818,7 @@ def _profile_runtime_scope(
# pinned (first-writer-wins backend leak; #68559).
from tools.terminal_scope import install_and_reset_profile_terminal_scope
- with install_and_reset_profile_terminal_scope(Path(profile_home)):
+ with install_and_reset_profile_terminal_scope(Path(profile_home), prepared=prepared_terminal_scope):
yield
finally:
if secret_token is not None:
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.py
index ba940b91828..3683400a267 100644
--- a/gateway/session_ancillary.py
+++ b/gateway/session_ancillary.py
@@ -234,7 +234,14 @@ async def read(connection, ref, params, *, kind):
if ref.session_id not in authority.sessions:
raise RuntimeStoreError('not_found')
authorize(connection, ref, params, 'session:read')
- live = authority.sessions[ref.session_id]
+ # In a worker thread (it inherits the dispatch's owner scope): the projection takes the session's
+ # event lock, which every streamed token takes too, reads state.db (compression lineage, local
+ # receipt, control meta) and the process registry under its lock. Clients poll these every 1-5 s per
+ # open session, so on the loop they were a large share of loop time with many sessions running.
+ return await asyncio.to_thread(_read_projection, authority, authority.sessions[ref.session_id], ref, params, kind)
+
+
+def _read_projection(authority, live, ref, params, kind):
with live.event_stream.lock:
if kind == 'control':
# Persisted per session id, never the route's live objects: readable after a messaging
diff --git a/gateway/session_authorities.py b/gateway/session_authorities.py
index f89e2808f64..3cf0e143156 100644
--- a/gateway/session_authorities.py
+++ b/gateway/session_authorities.py
@@ -12,6 +12,7 @@ scoped or not, exactly as before.
from __future__ import annotations
import asyncio
+from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -282,6 +283,52 @@ def holds_admission(authority, session_id) -> bool:
return True
+def _prepare_owner_scope(home: Path):
+ """``(secrets, terminal scope)`` of the profile at *home*, built the way ``_profile_runtime_scope``
+ builds them on entry (under the home override, the terminal policy under the secret scope);
+ ``None`` when *home* is not a directory (``owner_scope`` binds nothing then)."""
+ if not home.is_dir():
+ return None
+ from agent.secret_scope import reset_secret_scope, set_secret_scope
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from tools.terminal_scope import prepare_profile_terminal_scope
+ from tui_gateway.launch_profile_policy import owner_secret_scope
+ home_token = set_hermes_home_override(str(home))
+ try:
+ secrets = owner_secret_scope(home)
+ secret_token = set_secret_scope(secrets, profile_home=str(home))
+ try:
+ return secrets, prepare_profile_terminal_scope(home)
+ finally:
+ reset_secret_scope(secret_token)
+ finally:
+ reset_hermes_home_override(home_token)
+
+
+@asynccontextmanager
+async def async_owner_scope(authority):
+ """``owner_scope`` for a coroutine on the gateway loop: the profile's ``.env``, ``config.yaml`` and
+ terminal policy are read in a worker thread, then only the context variables are set here.
+
+ Every RPC a client sends enters its owner's scope, and the classic CLI, Ink and Desktop poll
+ ``subagent.list`` / ``process.list`` every 1-5 s per session: built on the loop, that scope was the
+ largest single cost of RPC dispatch on a multiplexed gateway with many sessions open."""
+ runner = getattr(authority, 'runner', None)
+ home = Path(str(authority.profile_id))
+ if not getattr(getattr(runner, 'config', None), 'multiplex_profiles', False) or not home.is_absolute():
+ with owner_scope(authority): # the launch scope (frozen sources) or nullcontext: no profile files
+ yield
+ return
+ prepared = await asyncio.to_thread(_prepare_owner_scope, home)
+ if prepared is None:
+ yield
+ return
+ from gateway.run import _profile_runtime_scope
+ secrets, terminal = prepared
+ with _profile_runtime_scope(home, secrets, prepared_terminal_scope=terminal):
+ yield
+
+
def owner_scope(authority, *, hydrate_secrets=False):
"""Runtime scope of the profile that owns *authority* — under multiplex only.
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 769bb04acc8..15c3ea61159 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -344,9 +344,9 @@ class AuthorityConnection:
# ``_load_gateway_config`` / ``build_policy(get_hermes_home())`` never snapshot the
# launch profile's config into a served secondary's session. Under a single profile
# the scope is that profile's own home, so behaviour is unchanged.
- from gateway.session_authorities import owner_scope
+ from gateway.session_authorities import async_owner_scope
from gateway.session_connections import METHODS as CONNECTION_METHODS, session_owned
- with owner_scope(self.authority):
+ async with async_owner_scope(self.authority):
if method in GROUP_METHODS or method == 'profiles.list':
result = await dispatch_group_control(self, method, params)
elif method not in handlers or (method in CONNECTION_METHODS and not session_owned(params)):
diff --git a/tests/gateway/test_rpc_scope_off_loop.py b/tests/gateway/test_rpc_scope_off_loop.py
new file mode 100644
index 00000000000..f56a759abdb
--- /dev/null
+++ b/tests/gateway/test_rpc_scope_off_loop.py
@@ -0,0 +1,103 @@
+"""RPC dispatch enters its owner's profile scope without reading profile files on the event loop.
+
+Every client RPC (and the classic CLI / Ink / Desktop poll ``subagent.list`` and ``process.list``
+every 1-5 s per open session) runs under ``owner_scope``. On a multiplexed gateway that scope reads
+the profile's ``.env``, ``config.yaml`` and terminal policy; on the loop it was the largest single
+cost of dispatch with many sessions open (gateway disconnects under load).
+"""
+
+import asyncio
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+
+def _authority(home, multiplex=True):
+ return SimpleNamespace(profile_id=str(home),
+ runner=SimpleNamespace(config=SimpleNamespace(multiplex_profiles=multiplex)))
+
+
+def _bound():
+ from agent.secret_scope import current_secret_scope, current_secret_scope_home
+ from hermes_constants import get_hermes_home_override
+ from tools.terminal_scope import get_terminal_scope
+ secrets = current_secret_scope()
+ terminal = get_terminal_scope()
+ return (get_hermes_home_override(), dict(secrets) if secrets is not None else None,
+ current_secret_scope_home(), dict(terminal) if terminal is not None else None, type(terminal).__name__)
+
+
+def profile(tmp_path):
+ home = tmp_path / "profiles" / "worker"
+ home.mkdir(parents=True)
+ (home / ".env").write_text("LOOPSTALL_PROBE_KEY=from-profile\nTERMINAL_TIMEOUT=77\n", encoding="utf-8")
+ (home / "config.yaml").write_text("terminal:\n backend: local\n cwd: /srv/work\n", encoding="utf-8")
+ return home
+
+
+async def test_async_owner_scope_binds_what_owner_scope_binds_with_the_reads_off_the_loop(profile, monkeypatch):
+ from gateway import session_authorities
+ from tools import terminal_scope
+
+ authority = _authority(profile)
+ with session_authorities.owner_scope(authority):
+ expected = _bound()
+ assert expected[0] == str(profile) and expected[1]["LOOPSTALL_PROBE_KEY"] == "from-profile"
+ assert expected[3]["TERMINAL_TIMEOUT"] == "77"
+
+ loop_thread = threading.get_ident()
+ build_threads = []
+ real_build = terminal_scope.build_profile_terminal_scope
+
+ def build(*args, **kwargs):
+ build_threads.append(threading.get_ident())
+ return real_build(*args, **kwargs)
+
+ monkeypatch.setattr(terminal_scope, "build_profile_terminal_scope", build)
+ before = _bound()
+ async with session_authorities.async_owner_scope(authority):
+ got = _bound()
+ await asyncio.sleep(0) # the scope spans awaits, as a dispatched handler's does
+ assert _bound() == got
+ assert got == expected
+ assert build_threads and loop_thread not in build_threads, "the terminal policy was built on the event loop"
+ assert _bound() == before, "the scope leaked past the async with"
+
+
+async def test_async_owner_scope_keeps_owner_scope_for_unrouted_owners(tmp_path):
+ """A single-profile gateway, a symbolic test owner and a vanished home bind exactly what
+ ``owner_scope`` binds (nothing, or the launch scope), without a worker hop."""
+ from gateway.session_authorities import async_owner_scope, owner_scope
+
+ for authority in (_authority(tmp_path, multiplex=False), _authority("fixture"),
+ _authority(tmp_path / "gone")):
+ with owner_scope(authority):
+ expected = _bound()
+ async with async_owner_scope(authority):
+ assert _bound() == expected
+
+
+async def test_ancillary_polls_project_off_the_loop(monkeypatch):
+ """``subagent.list`` / ``process.list`` / ``session.control.read`` build their projection in a worker:
+ it takes the session's event lock (held by every streamed token) and reads state.db."""
+ from gateway import session_ancillary
+
+ loop_thread = threading.get_ident()
+ seen = []
+
+ def projection(authority, live, ref, params, kind):
+ seen.append((threading.get_ident(), kind))
+ return {'subagents': [], 'delegations': []}
+
+ monkeypatch.setattr(session_ancillary, "_read_projection", projection)
+ monkeypatch.setattr(session_ancillary, "authorize", lambda *a, **k: None)
+ ref = SimpleNamespace(session_id="s1", profile_id="fixture")
+ connection = SimpleNamespace(authority=SimpleNamespace(sessions={"s1": object()}))
+ result = await session_ancillary.read(connection, ref, {"session_id": "s1"}, kind="subagents")
+ assert result == {'subagents': [], 'delegations': []}
+ assert seen and seen[0][0] != loop_thread, "the projection ran on the event loop"
diff --git a/tools/terminal_scope.py b/tools/terminal_scope.py
index ce50cdf164e..c9a631dec22 100644
--- a/tools/terminal_scope.py
+++ b/tools/terminal_scope.py
@@ -216,20 +216,31 @@ def _resolve_scope_cwd_placeholder(scope: dict[str, str]) -> None:
scope["TERMINAL_CWD"] = resolved
-def install_profile_terminal_scope(
- hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> Token:
- """Build AND install a profile's policy; on failure install the refusal scope. Never raises."""
+def prepare_profile_terminal_scope(
+ hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> dict[str, str]:
+ """The scope ``install_profile_terminal_scope`` installs: the profile's policy, or the refusal scope
+ when it cannot be resolved. Never raises. File reads only, so it can run in a worker thread and be
+ installed on the loop (``install_and_reset_profile_terminal_scope(prepared=...)``)."""
try:
- return set_terminal_scope(build_profile_terminal_scope(hermes_home, env_overlay=env_overlay))
+ return build_profile_terminal_scope(hermes_home, env_overlay=env_overlay)
except TerminalPolicyUnavailable as exc:
logger.warning("terminal policy unavailable: %s", exc)
- return _terminal_scope_var.set(TerminalPolicyRefusal(str(exc)))
+ return TerminalPolicyRefusal(str(exc))
+
+
+def install_profile_terminal_scope(
+ hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> Token:
+ """Build AND install a profile's policy; on failure install the refusal scope. Never raises."""
+ return set_terminal_scope(prepare_profile_terminal_scope(hermes_home, env_overlay=env_overlay))
@contextmanager
-def install_and_reset_profile_terminal_scope(hermes_home: Any) -> Iterator[None]:
- """Install the profile's terminal policy for a bounded turn/fire. Never raises."""
- token = install_profile_terminal_scope(hermes_home)
+def install_and_reset_profile_terminal_scope(
+ hermes_home: Any, *, prepared: Optional[dict[str, str]] = None) -> Iterator[None]:
+ """Install the profile's terminal policy for a bounded turn/fire. Never raises. *prepared* is a
+ ``prepare_profile_terminal_scope`` result built earlier (off the loop); without it the policy is
+ built here."""
+ token = set_terminal_scope(prepared) if prepared is not None else install_profile_terminal_scope(hermes_home)
try:
yield
finally: