fix(gateway): on_session_open opens behind a hung one stay bounded; no consumer, no thread

Second independent review of #151120:

- P2: every open queued its own task behind its predecessor with no bound, so
  under `plugins.hook_callback_timeout: 0` a hung callback let every later open
  of that session pile up (41 pending tasks in the review's probe). Now at most
  one delivery runs and one queues per (profile, session); opens arriving while
  that one still queues join it and fire once after the running one, with the
  latest open's payload (an open is setup, so firing it once is enough). The
  first join logs one WARNING.
- P3: the delivery thread started before `has_hook('on_session_open')` was
  checked. The loop now asks `hook_known_unused` first, under the owning
  profile's home override: safe mode, or that profile's plugins already loaded
  with no callback for a hook no first-party observer handles, answers without
  discovering plugins or reading config, and no thread starts. A profile whose
  plugins are not loaded yet still goes to the thread, which discovers and
  checks `has_hook` off the loop as before.
This commit is contained in:
Teknium
2026-11-08 01:26:58 -08:00
parent 32e147dcb1
commit d9028f3088
5 changed files with 156 additions and 35 deletions

View File

@@ -6,6 +6,7 @@ attached to: once per open, never for a snapshot poll on an attachment it alread
reconnect. The open is registered before the attach yields and delivered on a thread of its own under
the owning profile's scope (that profile's plugin manager), so the reply never waits on a plugin; the
session's next claimed turn waits for it (``settled``), so plugins see the open before the model does.
A profile whose loaded plugins hold no consumer starts no thread.
``on_session_start`` stays the first-turn hook.
"""
import asyncio
@@ -14,8 +15,8 @@ from pathlib import Path
logger = logging.getLogger(__name__)
# (profile id, session id) -> the open still pending or running for it. In-flight work only: an
# entry leaves when its delivery ends, so this never dedupes and holds one open per opening session.
# (profile id, session id) -> its latest open delivery still queued or running. In-flight work only:
# an entry leaves when its delivery ends, so this never dedupes and holds one per opening session.
_PENDING = {}
# Longest a turn waits on an open when ``plugins.hook_callback_timeout`` is 0 (callbacks never
@@ -35,37 +36,43 @@ def _reason(db, session_id):
class _Open:
"""One pending open: registered before the attach, then ``fire``d with the session's policy, or
``release``d (not a local session, a failed attach) so no turn waits on it."""
"""One session's open delivery, standing for every open that joined it while it queued.
def __init__(self, authority, ref):
self.ref, self.db = ref, authority.db
key = (ref.profile_id, ref.session_id)
Each open holds a gate (``open_local``) its attach ``fire``s with the session's policy, or
``release``s (not a local session, a failed attach) so no turn waits on it. Bounded: at most
one delivery runs per (profile, session) and one queues behind it; opens arriving while that
one still queues join it, so a hung callback (``hook_callback_timeout: 0``) holds two tasks and
one thread however often the session is opened meanwhile. An open is setup, so the joined opens
fire once, after the running one, with the latest gate's payload."""
def __init__(self, ref, db, ahead):
self.ref, self.db, self.ahead = ref, db, ahead
# The profile's ``plugins.hook_callback_timeout``, read by the delivery (off-loop, in that
# profile's scope, only for a session that loads plugins); 0 until then.
self.callback_timeout = 0.0
self.gate = asyncio.get_running_loop().create_future()
previous = _live(key)
self.task = asyncio.ensure_future(self._run(previous and previous.task))
_PENDING[key] = self
self.task.add_done_callback(lambda _done: _PENDING.pop(key) if _PENDING.get(key) is self else None)
self.started = self.coalesced = False
self.unsettled, self.opened = set(), None # gates not yet fired or released; latest payload
self.task = asyncio.ensure_future(self._run())
def fire(self, policy, route):
# A bypass launch (``--safe-mode`` / ``--ignore-user-config``) loads no plugin: nothing fires.
if not self.gate.done():
self.gate.set_result(None if policy is None or policy.ignore_user_config else (policy, route))
def joinable(self):
return not self.started and self.ahead is not None and not self.ahead.task.done()
def release(self):
if not self.gate.done():
self.gate.set_result(None)
async def _run(self, previous):
opened = await self.gate
if previous is not None: # two viewers opening at once: one session's opens fire in order
await asyncio.wait({previous})
if opened is not None:
async def _run(self):
if self.ahead is not None: # two viewers opening at once: one session's opens fire in order
await asyncio.wait({self.ahead.task})
self.started = True
while self.unsettled:
await asyncio.wait(set(self.unsettled))
from hermes_cli.lifecycle import hook_known_unused
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
token = set_hermes_home_override(self.ref.profile_id)
try: # the owning profile's loaded plugins, read without discovery or config: no consumer, no thread
unused = hook_known_unused('on_session_open')
finally:
reset_hermes_home_override(token)
if self.opened is not None and not unused:
from gateway.session_commands import _on_own_thread
await _on_own_thread(lambda: self._deliver(*opened))
await _on_own_thread(lambda: self._deliver(*self.opened))
def _deliver(self, policy, route):
from gateway.run import _profile_runtime_scope
@@ -76,7 +83,7 @@ class _Open:
sid = self.ref.session_id
try:
with _profile_runtime_scope(Path(self.ref.profile_id)), scoped_session_key(route):
if has_hook('on_session_open'): # no consumer in this profile: no read, no call
if has_hook('on_session_open'): # plugins not loaded until now: none of them consumes it
self.callback_timeout = _resolve_hook_callback_timeout()
invoke_hook('on_session_open', session_id=sid, platform=SURFACES.get(policy.source, policy.source),
reason=_reason(self.db, sid))
@@ -84,9 +91,39 @@ class _Open:
logger.warning('on_session_open delivery failed for %s', sid, exc_info=True)
class _Gate:
"""One open's hold on its delivery: the delivery waits until every gate is fired or released."""
def __init__(self, delivery):
self.delivery, self.future = delivery, asyncio.get_running_loop().create_future()
delivery.unsettled.add(self.future)
def fire(self, policy, route):
# A bypass launch (``--safe-mode`` / ``--ignore-user-config``) loads no plugin: nothing fires.
if not self.future.done() and policy is not None and not policy.ignore_user_config:
self.delivery.opened = (policy, route)
self.release()
def release(self):
if not self.future.done():
self.future.set_result(None)
self.delivery.unsettled.discard(self.future)
def open_local(authority, ref):
"""Register *ref*'s open before anything can start its next turn; the caller fires or releases it."""
return _Open(authority, ref)
"""Register *ref*'s open before anything can start its next turn; the caller fires or releases
the returned gate."""
key = (ref.profile_id, ref.session_id)
delivery = _live(key)
if delivery is None or not delivery.joinable():
delivery = _PENDING[key] = _Open(ref, authority.db, delivery)
delivery.task.add_done_callback(lambda _done, mine=delivery: _PENDING.pop(key)
if _PENDING.get(key) is mine else None)
elif not delivery.coalesced:
delivery.coalesced = True
logger.warning('on_session_open for %s: an earlier delivery is still running; the opens meanwhile '
'fire once, after it', ref.session_id)
return _Gate(delivery)
def _live(key):

View File

@@ -65,6 +65,24 @@ def has_hook(hook_name: str) -> bool:
return plugins.has_hook(hook_name)
def hook_known_unused(hook_name: str) -> bool:
"""True when nothing in the active profile can consume *hook_name*, decided without loading
plugins or reading config, so an event loop may ask before spending a thread on it: safe mode,
or this profile's plugins already loaded with none registered for a hook no first-party observer
handles. False means it may be consumed: ask :func:`has_hook` off the loop."""
from agent.safe_worker_policy import safe_worker_enabled
if safe_worker_enabled():
return True
from hermes_cli.observability.relay_shared_metrics import HANDLED_HOOKS
if hook_name in HANDLED_HOOKS:
return False
from hermes_cli import plugins
return plugins.hook_unused_nowait(hook_name)
def session_end_messages(results: Any) -> list[str]:
"""User-facing text from ``on_session_finalize`` results: a non-empty ``str`` or ``{"message": str}``.

View File

@@ -1035,6 +1035,13 @@ def has_hook(hook_name: str) -> bool:
return _delivery_manager().has_hook(hook_name)
def hook_unused_nowait(hook_name: str) -> bool:
"""True when this home's plugins are loaded and none handles *hook_name*. Never discovers (an
unloaded home answers False), so it is safe on an event loop."""
manager = get_plugin_manager()
return manager._discovered and not manager.has_hook(hook_name)
def iter_hook_callbacks(hook_name: str) -> tuple[Callable, ...]:
"""Return a stable snapshot of callbacks registered for a hook."""
return get_plugin_manager().iter_hook_callbacks(hook_name)

View File

@@ -150,13 +150,16 @@ async def _hung_open(monkeypatch, sid, release):
from gateway.session_contract import SessionRef
monkeypatch.setattr(session_open, '_UNBOUNDED_TURN_WAIT_S', 0.5, raising=False)
entered = threading.Event()
monkeypatch.setattr(session_open._Open, '_deliver', lambda self, *a: (entered.set(), release.wait(20)))
delivered = []
monkeypatch.setattr(session_open._Open, '_deliver',
lambda self, *a: (delivered.append(a), entered.set(), release.wait(20)))
ref = SessionRef('p', sid)
opening = session_open.open_local(SimpleNamespace(db=None), ref)
opening.fire(SimpleNamespace(ignore_user_config=False), 'route')
gate = session_open.open_local(SimpleNamespace(db=None), ref)
gate.fire(SimpleNamespace(ignore_user_config=False), 'route')
opening = gate.delivery
import asyncio
assert await asyncio.to_thread(entered.wait, 10), 'the open delivery never started'
return ref, opening
return ref, opening, delivered
@pytest.mark.asyncio
@@ -178,7 +181,7 @@ async def test_a_hung_open_never_wedges_the_turn_or_its_executing_stamp(monkeypa
return 'ok'
monkeypatch.setattr(session_finite, 'execute_finite_admission', turn)
try:
ref, opening = await _hung_open(monkeypatch, 'hung-open', release)
ref, opening, _delivered = await _hung_open(monkeypatch, 'hung-open', release)
live = LiveSession(SimpleNamespace(chat_id=ref.session_id), 'route')
owner = SimpleNamespace(executing={ref.session_id: 7}) # as _stamp_claim left it
task = asyncio.ensure_future(SessionAuthority._execute_claimed(owner, ref, live, {'admission_id': 'a'}))
@@ -194,3 +197,59 @@ async def test_a_hung_open_never_wedges_the_turn_or_its_executing_stamp(monkeypa
assert ref.session_id not in owner.executing, owner.executing
assert task.cancelled() if cancel else (task.result() == ('ok', 'completed') and ran == ['a'])
await asyncio.wait({opening.task}, timeout=5)
@pytest.mark.asyncio
async def test_opens_behind_a_hung_open_stay_bounded_and_fire_once_after_it(monkeypatch):
"""With callbacks never abandoned, a session reopened 40 times behind a hung ``on_session_open``
holds one queued delivery, not 40; once the hang ends the opens meanwhile fire once, after it."""
import asyncio
import threading
from types import SimpleNamespace
from gateway import session_open
release = threading.Event()
try:
ref, first, delivered = await _hung_open(monkeypatch, 'reopened', release)
before = len(asyncio.all_tasks())
for n in range(40):
gate = session_open.open_local(SimpleNamespace(db=None), ref)
gate.fire(SimpleNamespace(ignore_user_config=False), f'route-{n}')
for _ in range(20): # yields only: each queued delivery reaches its wait on the hung one
await asyncio.sleep(0)
held = len(asyncio.all_tasks()) - before
finally:
release.set()
queued = session_open._PENDING[(ref.profile_id, ref.session_id)]
await asyncio.wait({first.task, queued.task}, timeout=10)
assert held == 1, f'{held} deliveries queued behind the hung one'
assert [route for _policy, route in delivered] == ['route', 'route-39'], delivered
@pytest.mark.asyncio
async def test_a_profile_with_no_consumer_starts_no_delivery_thread(monkeypatch, tmp_path):
"""A profile whose plugins are loaded with no ``on_session_open`` callback spends no thread on an
open, and one that registers a callback does."""
import asyncio
from types import SimpleNamespace
from gateway import session_commands, session_open
from gateway.session_contract import SessionRef
from hermes_cli import plugins
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
threads = []
async def own_thread(fn):
threads.append(fn)
monkeypatch.setattr(session_commands, '_on_own_thread', own_thread)
token = set_hermes_home_override(str(tmp_path))
try:
manager = plugins.get_plugin_manager()
finally:
reset_hermes_home_override(token)
manager._discovered = True
for consumer in (False, True):
if consumer:
manager._hooks['on_session_open'] = [lambda **kw: None]
gate = session_open.open_local(SimpleNamespace(db=None), SessionRef(str(tmp_path), f's-{consumer}'))
gate.fire(SimpleNamespace(ignore_user_config=False), 'route')
await asyncio.wait({gate.delivery.task}, timeout=5)
assert len(threads) == consumer, (consumer, threads)

View File

@@ -973,7 +973,7 @@ def my_callback(session_id: str, platform: str, reason: str, **kwargs):
| `platform` | `str` | The surface that created it: `cli`, `tui`, `desktop`, `acp`, ... |
| `reason` | `str` | `create` while the session has no messages yet (a new chat), `resume` once it has a conversation (a stored chat being reopened) |
**Fires:** In the gateway (`gateway/session_open.py`), when a client connection attaches to a local session it was not already attached to. Once per open: a client re-reading a session it already has open, or reconnecting after a dropped socket, does not fire it again. Two clients opening the same session fire it twice. It runs in the profile that owns the session, so on a gateway serving several profiles each profile's plugins see only their own sessions. The callback runs on its own thread: opening the session never waits for it, but the session's next turn does, for up to 5 s or `plugins.hook_callback_timeout` if that is longer; past that the turn proceeds and the callback keeps running. `--safe-mode` / `--ignore-user-config` sessions fire nothing. Messaging chats (Telegram, Discord, ...) do not fire it: their first message starts the session, so use `on_session_start` there.
**Fires:** In the gateway (`gateway/session_open.py`), when a client connection attaches to a local session it was not already attached to. Once per open: a client re-reading a session it already has open, or reconnecting after a dropped socket, does not fire it again. Two clients opening the same session fire it twice. It runs in the profile that owns the session, so on a gateway serving several profiles each profile's plugins see only their own sessions. The callback runs on its own thread: opening the session never waits for it, but the session's next turn does, for up to 5 s or `plugins.hook_callback_timeout` if that is longer; past that the turn proceeds and the callback keeps running. While a callback for a session is still running, further opens of that session wait behind it as a single call: they fire once when it ends, with the latest open's details. `--safe-mode` / `--ignore-user-config` sessions fire nothing. Messaging chats (Telegram, Discord, ...) do not fire it: their first message starts the session, so use `on_session_start` there.
**Return value:** Ignored.