Skip to content

The agent that grows with you

fix(api): an exact streaming retry after delete replays its receipt, not a KeyError

Teknium6795bd3339ff
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index 5b3075b8fb7..be82c8ac31f 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -394,7 +394,12 @@ def observe_api_controls(admitted, sink):
either in the snapshot or arrives live (never both), and one already answered is absent."""
from hermes_state_runtime import get_session_admission
authority, ref, row = admitted
- live = authority.sessions[ref.session_id]
+ live = authority.sessions.get(ref.session_id)
+ if live is None:
+ # Deleted or pruned: only an exact retry of a settled (retired) receipt reaches here,
+ # and a settled admission has no prompts left to project.
+ yield
+ return
events = live.event_stream
def observer(frame):
diff --git a/tests/gateway/test_api_observer_gone_session.py b/tests/gateway/test_api_observer_gone_session.py
new file mode 100644
index 00000000000..6feea3e87df
--- /dev/null
+++ b/tests/gateway/test_api_observer_gone_session.py
@@ -0,0 +1,35 @@
+"""An exact streaming Chat retry after its session was deleted replays the receipt, not a 500."""
+import json
+
+import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+
+async def test_streaming_retry_after_delete_replays_terminal_receipt(api, owner):
+ calls = []
+
+ async def handle(event):
+ from gateway.session_results import execution_result
+ calls.append(event.text)
+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': []}
+ return 'answer'
+ owner.runner._handle_message = handle
+ app = web.Application()
+ app.router.add_post('/v1/chat/completions', api._handle_chat_completions)
+ body = {'messages': [{'role': 'user', 'content': 'work'}], 'stream': True}
+ headers = {'Idempotency-Key': 'deleted-stream'}
+ async with TestClient(TestServer(app)) as client:
+ first = await client.post('/v1/chat/completions', json=body, headers=headers)
+ assert first.status == 200, await first.text()
+ assert 'answer' in await first.text()
+ sid = first.headers['X-Hermes-Session-Id']
+ assert owner.db.delete_session(sid)
+ owner.sessions.pop(sid, None) # the owner's prune drops the live session with the row
+ retry = await client.post('/v1/chat/completions', json=body, headers=headers)
+ text = await retry.text()
+ assert retry.status == 200, text
+ chunks = [json.loads(line[6:]) for line in text.splitlines() if line.startswith('data: {')]
+ assert 'answer' in ''.join(c['choices'][0]['delta'].get('content') or '' for c in chunks if c.get('choices'))
+ assert calls == ['work']