Skip to content

The agent that grows with you

fix(api): cancelled API observers unregister and callbacks are isolated (X10, reported by @Xipong)

teknium12797380560f2
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index 3a472e94282..38d32f64d53 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -173,13 +173,20 @@ async def observe_api_turn(admitted, **kwargs):
observers = getattr(authority, 'api_observers', None)
if observers is None:
observers = authority.api_observers = {}
- observers.setdefault(row['admission_id'], []).append({
- key: kwargs[key] for key in ('stream_delta_callback', 'tool_start_callback', 'tool_complete_callback')
- if kwargs.get(key) is not None})
- authority._publish_pending(ref)
- authority._schedule(ref)
- await asyncio.shield(waiter)
- observers.pop(row['admission_id'], None)
+ observer = {key: kwargs[key] for key in ('stream_delta_callback', 'tool_start_callback', 'tool_complete_callback')
+ if kwargs.get(key) is not None}
+ registered = observers.setdefault(row['admission_id'], [])
+ registered.append(observer)
+ try:
+ authority._publish_pending(ref)
+ authority._schedule(ref)
+ await asyncio.shield(waiter)
+ finally:
+ # Shielding keeps the canonical turn alive past a cancelled request; only this
+ # request's observer leaves, and the entry itself goes once the last one is gone.
+ registered.remove(observer)
+ if not registered:
+ observers.pop(row['admission_id'], None)
saved = admission_result(authority.db, row['admission_id'])
if saved is None:
from hermes_state_runtime import get_session_admission
@@ -238,13 +245,22 @@ def _api_observers(authority, session_id):
return tuple(getattr(authority, 'api_observers', {}).get(admission_id, ()))
-def publish_api_event(authority, session_id, event_type, payload):
- if event_type != 'message.delta':
- return
+def _notify_observers(authority, session_id, key, *args):
+ """Observer callbacks are request-owned sinks; one that raises (closed socket, torn-down
+ loop) must not abort canonical execution or starve the other observers."""
+ import logging
for observer in _api_observers(authority, session_id):
- callback = observer.get('stream_delta_callback')
+ callback = observer.get(key)
if callback:
- callback(payload['text'])
+ try:
+ callback(*args)
+ except Exception:
+ logging.getLogger(__name__).warning('API observer %s failed for %s', key, session_id, exc_info=True)
+
+
+def publish_api_event(authority, session_id, event_type, payload):
+ if event_type == 'message.delta':
+ _notify_observers(authority, session_id, 'stream_delta_callback', payload['text'])
def publish_api_tool_event(authority, session_id, generation, event_type, call_id, tool_name, args, result=None):
@@ -256,15 +272,10 @@ def publish_api_tool_event(authority, session_id, generation, event_type, call_i
authority.check_approval_generation(session_id, generation)
except RuntimeStoreError:
return
- for observer in _api_observers(authority, session_id):
- if event_type == 'tool.start':
- callback = observer.get('tool_start_callback')
- if callback:
- callback(call_id, tool_name, args or {})
- elif event_type == 'tool.complete':
- callback = observer.get('tool_complete_callback')
- if callback:
- callback(call_id, tool_name, args or {}, result)
+ if event_type == 'tool.start':
+ _notify_observers(authority, session_id, 'tool_start_callback', call_id, tool_name, args or {})
+ elif event_type == 'tool.complete':
+ _notify_observers(authority, session_id, 'tool_complete_callback', call_id, tool_name, args or {}, result)
def prepare_api_runtime(model, runtime_kwargs):
diff --git a/tests/gateway/test_api_canonical_projection.py b/tests/gateway/test_api_canonical_projection.py
index 9953584c234..db610547f2f 100644
--- a/tests/gateway/test_api_canonical_projection.py
+++ b/tests/gateway/test_api_canonical_projection.py
@@ -166,3 +166,44 @@ async def test_exact_responses_retry_replays_before_conversation_expansion(api,
statuses.append((resp.status, (await resp.json()).get('status')))
assert statuses == [(200, 'completed'), (200, 'completed')]
assert calls == ['hello']
+
+
+async def test_cancelled_observer_is_unregistered_and_never_breaks_the_survivor(api, owner):
+ """Two request tasks observe one admission. Cancelling one (client disconnect) must drop
+ exactly its observer entry; the other keeps streaming, and a raising callback on the
+ owner path is isolated from canonical execution."""
+ from gateway.session_api_turn import observe_api_turn
+ admitted = admit_api_turn(api, session_id='observers', user_message='hello', conversation_history=[])
+ _, ref, row = admitted
+ started, release = asyncio.Event(), asyncio.Event()
+ survivor, cancelled_saw = [], []
+
+ def broken(*args):
+ raise RuntimeError('client sink is gone')
+
+ async def handle(event):
+ from gateway.session_results import execution_result
+ started.set()
+ await release.wait()
+ turn = _turn_runner(owner, ref)
+ turn.combined_tool_complete_callback('call-1', 'read_file', {'path': 'a.txt'}, 'body')
+ execution_result.get()['result'] = {'final_response': 'ok'}
+ return 'ok'
+ owner.runner._handle_message = handle
+ first = asyncio.ensure_future(observe_api_turn(admitted, tool_complete_callback=lambda *a: cancelled_saw.append(a)))
+ second = asyncio.ensure_future(observe_api_turn(admitted, tool_complete_callback=lambda *a: survivor.append(a)))
+ await asyncio.wait_for(started.wait(), timeout=5)
+ first.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first
+ assert len(owner.api_observers[row['admission_id']]) == 1
+ # A sink that raises on the owner path must not abort the turn or starve the survivor.
+ third = asyncio.ensure_future(observe_api_turn(admitted, tool_complete_callback=broken))
+ await asyncio.sleep(0)
+ release.set()
+ (result, _), (third_result, _) = await asyncio.wait_for(asyncio.gather(second, third), timeout=5)
+ assert result['final_response'] == third_result['final_response'] == 'ok'
+ assert survivor == [('call-1', 'read_file', {'path': 'a.txt'}, 'body')]
+ assert cancelled_saw == []
+ assert row['admission_id'] not in owner.api_observers