The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): preserve admitted Responses identity across retries and eviction
David Dudok de Wit54a5a5e39bf8
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex 4768925a744..5a56a09e2db 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -80,13 +80,16 @@ def _finish_reason(completed, is_partial, is_failed, err_msg, agent_error=None)_RESPONSES_FINGERPRINT_KEYS = ("input", "instructions", "previous_response_id", "conversation", "conversation_history", "model",- "provider", "model_options", "tools",+ "provider", "model_options", "tools", "truncation",)-def _idempotency_conflict():- from gateway.platforms.api_server import _openai_error- return web.json_response(_openai_error('admission_conflict', code='admission_conflict'), status=409)+def _response_identity(store, durable_key):+ if durable_key is not None:+ import hashlib+ return ('resp_' + hashlib.sha256(durable_key[0].encode()).hexdigest()[:28],+ store.request_created_at(durable_key[0]))+ return f'resp_{uuid.uuid4().hex[:28]}', int(time.time())def _response_status(result):@@ -239,13 +242,16 @@ class _ResponsesStream:def __init__(self, adapter, response, *, response_id: str, model: str, created_at: int,conversation_history: List[Dict[str, str]], user_message: str,- instructions: Optional[str], conversation: Optional[str], store: bool, session_id: str):+ instructions: Optional[str], conversation: Optional[str], store: bool, session_id: str,+ durable_key=None, terminal_replay=False):from gateway.platforms import api_server as apiself._api = apiself.adapter, self.response, self.response_id = adapter, response, response_idself.model, self.created_at, self.conversation_history = model, created_at, conversation_historyself.user_message, self.instructions = user_message, instructionsself.conversation, self.store, self.session_id = conversation, store, session_id+ self.durable_key = durable_key+ self.terminal_replay = terminal_replay# Resolved in the request's profile scope: a snapshot written after it (disconnect) must not follow another.self.response_store = adapter._current_response_store()self.final_text_parts: List[str] = []@@ -254,7 +260,10 @@ class _ResponsesStream:self.output_index = 0self.call_counter = 0 # call_id fallback when the agent supplies no tool_call_idself.sequence_number = 0- self.message_item_id = f"msg_{uuid.uuid4().hex[:24]}"+ self._identity_counts = {}+ self._published_output_ids = []+ self._suppress_incremental = False+ self.message_item_id = self._item_id('message')self.message_output_index: Optional[int] = Noneself.message_opened = Falseself.reasoning_item: Optional[Dict[str, Any]] = None # open ``reasoning`` output item@@ -270,12 +279,40 @@ class _ResponsesStream:self._batch_lock = asyncio.Lock()async def write_event(self, event_type: str, data: Dict[str, Any]) -> None:+ if self.durable_key and 'output_index' in data:+ if self._suppress_incremental:+ return+ index = data['output_index']+ if event_type == 'response.output_item.added':+ valid = index == len(self._published_output_ids)+ if valid:+ self._published_output_ids.append(data['item']['id'])+ else:+ identity = data.get('item_id') or data.get('item', {}).get('id')+ valid = 0 <= index < len(self._published_output_ids) and (+ identity is None or self._published_output_ids[index] == identity)+ if not valid:+ # A late/backpressured observer may miss a globally allocated prefix. Keep the+ # prefix it already published; complete from the canonical terminal snapshot.+ self._suppress_incremental = True+ returnif "sequence_number" not in data:data["sequence_number"] = self.sequence_numberself.sequence_number += 1self.recorded_events.append((event_type, data))await self.response.write(self._api._sse_frame(data, event=event_type))+ def _item_id(self, kind, *, call_id=None, commentary=False):+ from gateway.platforms.api_server_response_identity import next_item_id+ return next_item_id(self.response_id, self._identity_counts, kind,+ call_id=call_id, commentary=commentary)++ def _output_index(self, item_id):+ index = (self.response_store.output_index(self.durable_key[0], item_id)+ if self.durable_key else self.output_index)+ self.output_index = max(self.output_index, index + 1)+ return index+def envelope(self, status: str) -> Dict[str, Any]:return {"id": self.response_id, "object": "response", "status": status,"created_at": self.created_at, "model": self.model}@@ -285,7 +322,8 @@ class _ResponsesStream:env = self.envelope(status)env["output"] = outputif error is not None:- env["error"] = {"message": error, "type": "server_error"}+ env["error"] = ({"code": "agent_error", "message": error} if self.durable_key+ else {"message": error, "type": "server_error"})env["usage"] = self._api._responses_usage_payload(self.usage)return env@@ -295,12 +333,16 @@ class _ResponsesStream:def persist_snapshot(self, response_env: Dict[str, Any], *, history=None, session_id=None):if not self.store:return+ if self.durable_key and self.response_store.get(self.durable_key[0]) is not None:+ return # A concurrent observer already committed the exact terminal envelope.+ advance_conversation = self.conversation and (not self.terminal_replay+ or self.response_store.get_conversation(self.conversation) in (None, self.response_id))self.response_store.put(self.response_id, {"response": response_env,"conversation_history": self._history_with_user() if history is None else history,"instructions": self.instructions,"session_id": session_id or self.session_id})- if self.conversation:+ if advance_conversation:self.response_store.set_conversation(self.conversation, self.response_id)def persist_incomplete_if_needed(self) -> None:@@ -320,21 +362,24 @@ class _ResponsesStream:env = self.envelope("in_progress")env["output"] = []await self.write_event("response.created", {"type": "response.created", "response": env})- self.persist_snapshot(env)+ if not self.terminal_replay:+ self.persist_snapshot(env)async def _open_message_item(self) -> None:"""Emit output_item.added for the assistant message on the first text delta."""if self.message_opened:returnself.message_opened = True- self.message_output_index = self.output_index- self.output_index += 1+ self.message_output_index = self._output_index(self.message_item_id)await self.write_event("response.output_item.added", {"type": "response.output_item.added", "output_index": self.message_output_index,"item": {"id": self.message_item_id, "type": "message", "status": "in_progress","role": "assistant", "content": []}})async def emit_text_delta(self, delta_text: str) -> None:+ if self.terminal_replay:+ self.final_text_parts.append(delta_text)+ returnawait self.close_reasoning_item()await self._open_message_item()self.final_text_parts.append(delta_text)@@ -347,10 +392,9 @@ class _ResponsesStream:"""Responses reasoning-summary family (#99552): one ``reasoning`` output item perthinking burst, closed before the next message/tool item opens."""if self.reasoning_item is None:- item = {"id": f"rs_{uuid.uuid4().hex[:24]}", "type": "reasoning", "status": "in_progress",+ item = {"id": self._item_id('reasoning'), "type": "reasoning", "status": "in_progress","summary": []}- self.reasoning_item = {"item": item, "output_index": self.output_index, "parts": []}- self.output_index += 1+ self.reasoning_item = {"item": item, "output_index": self._output_index(item['id']), "parts": []}await self.write_event("response.output_item.added", {"type": "response.output_item.added","output_index": self.reasoning_item["output_index"], "item": item})@@ -386,10 +430,9 @@ class _ResponsesStream:item stays clean (#67580). Closes any open reasoning item first so a reasoning itemnever straddles a message item."""await self.close_reasoning_item()- item = {"id": f"msg_{uuid.uuid4().hex[:24]}", "status": "completed", "phase": "commentary",+ item = {"id": self._item_id('message', commentary=True), "status": "completed", "phase": "commentary",**_message_item(text)}- idx = self.output_index- self.output_index += 1+ idx = self._output_index(item['id'])self.emitted_items.append({"phase": "commentary", **_message_item(text)})for event in ("response.output_item.added", "response.output_item.done"):await self.write_event(event, {"type": event, "output_index": idx, "item": item})@@ -402,10 +445,9 @@ class _ResponsesStream:args = payload.get("arguments", {})arguments_str = json.dumps(args) if isinstance(args, dict) else str(args)name = payload.get("name", "")- item = {"id": f"fc_{uuid.uuid4().hex[:24]}", "type": "function_call",+ item = {"id": self._item_id('function_call', call_id=call_id), "type": "function_call","status": "in_progress", "name": name, "call_id": call_id, "arguments": arguments_str}- idx = self.output_index- self.output_index += 1+ idx = self._output_index(item['id'])self.pending_tool_calls.append({"call_id": call_id, "name": name, "arguments": arguments_str, "item_id": item["id"],"output_index": idx})@@ -430,10 +472,9 @@ class _ResponsesStream:result = payload.get("result", "")result_str = result if isinstance(result, str) else json.dumps(result)output_parts = [{"type": "input_text", "text": result_str}]- output_item = {"id": f"fco_{uuid.uuid4().hex[:24]}", "type": "function_call_output",+ output_item = {"id": self._item_id('function_call_output', call_id=call_id), "type": "function_call_output","call_id": pending["call_id"], "output": output_parts, "status": "completed"}- idx = self.output_index- self.output_index += 1+ idx = self._output_index(output_item['id'])self.emitted_items.append({"type": "function_call_output", "call_id": pending["call_id"], "output": output_parts})for event in ("response.output_item.added", "response.output_item.done"):@@ -455,6 +496,8 @@ class _ResponsesStream:async def dispatch(self, item: Any) -> None:"""Route one queue item: tagged tuples emit immediately, strings are batched, others dropped."""+ if self.terminal_replay:+ returnif isinstance(item, tuple) and len(item) == 2 and isinstance(item[0], str):tag, payload = itemawait self.flush_batch()@@ -499,6 +542,13 @@ class _ResponsesStream:self.result = resultself.usage = agent_usage or self.usageagent_final = result.get("final_response", "") if isinstance(result, dict) else ""+ if self.terminal_replay:+ # The receipt already contains the transformed final; it is not a raw provider+ # stream onto which a verifier/footer transform should be applied a second time.+ self.final_response_text = agent_final or self._api._redact_api_error_text(+ result.get('error', '(No response generated)'))+ self.final_text_parts = [self.final_response_text]+ returntail, appended = _post_stream_transform(result)if tail and self.final_text_parts:if appended:@@ -553,7 +603,12 @@ class _ResponsesStream:async def emit_completed(self) -> Dict[str, Any]:result = self.resultstatus = _response_status(result)- env = self.terminal_envelope(status, self._final_items(),+ output = self._final_items()+ if self.durable_key:+ start = self.adapter._response_messages_turn_start_index(self.conversation_history, self.user_message, result)+ output = self.adapter._extract_output_items(result, start_index=start, response_id=self.response_id)+ output = self.response_store.order_output(self.durable_key[0], output)+ env = self.terminal_envelope(status, output,error=self._api._redact_api_error_text(result.get('error') or 'The admitted turn failed.')if status == 'failed' else None)full_history = self.adapter._build_response_conversation_history(@@ -565,6 +620,14 @@ class _ResponsesStream:self.persist_snapshot(env, history=full_history, session_id=sid if isinstance(sid, str) and sid else None)self.terminal_snapshot_persisted = True+ if self.durable_key:+ headers = {k: v for k, v in self.response.headers.items() if k.startswith('X-Hermes-')}+ terminal_event = {'type': 'response.' + status, 'response': env, 'sequence_number': self.sequence_number}+ self.response_store.put(self.durable_key[0], {+ 'fingerprint': self.durable_key[1], 'response': env, 'headers': headers,+ 'events': [*self.recorded_events, ('response.' + status, terminal_event)]})+ env = self.response_store.get(self.durable_key[0])['response']+ status = env['status']await self.write_event('response.' + status, {'type': 'response.' + status, 'response': env})return env@@ -690,7 +753,7 @@ class OpenAICompatRoutesMixin:self._release_run_owner_if_forgotten(completion_id)return _approval_notify, _on_done- def _spawn_stream_agent(self, stream_q, *, on_done=None, **run_kwargs) -> tuple:+ def _spawn_stream_agent(self, stream_q, *, on_done=None, run_agent=None, **run_kwargs) -> tuple:"""Start ``_run_agent`` for an SSE writer -> ``(agent_task, agent_ref)``. ``agent_ref[0]``lets the writer interrupt on disconnect; the EOS sentinel is enqueued from the task's donecallback so drain loops never race a polled ``agent_task.done()``. ``on_done(task)`` runs@@ -714,7 +777,7 @@ class OpenAICompatRoutesMixin:if text:stream_q.put_threadsafe(("__status__", {"kind": str(kind), "text": text}))agent_ref = [None]- agent_task = asyncio.ensure_future(self._run_agent(+ agent_task = asyncio.ensure_future((run_agent or self._run_agent)(stream_delta_callback=_on_delta, reasoning_callback=_on_reasoning, status_callback=_on_status,agent_ref=agent_ref, **run_kwargs))def _done(fut):@@ -1072,7 +1135,7 @@ class OpenAICompatRoutesMixin:self, request: "web.Request", response_id: str, model: str, created_at: int, stream_q,agent_task, agent_ref, conversation_history: List[Dict[str, str]], user_message: str,instructions: Optional[str], conversation: Optional[str], store: bool, session_id: str,- gateway_session_key: Optional[str] = None, durable_key=None) -> "web.StreamResponse":+ gateway_session_key: Optional[str] = None, durable_key=None, terminal_replay=False) -> "web.StreamResponse":"""Write the SSE stream for POST /v1/responses.Events: ``response.created`` -> ``output_text.delta/done`` + ``output_item.added/done``@@ -1088,7 +1151,8 @@ class OpenAICompatRoutesMixin:st = _ResponsesStream(self, response, response_id=response_id, model=model, created_at=created_at,conversation_history=conversation_history, user_message=user_message,- instructions=instructions, conversation=conversation, store=store, session_id=session_id)+ instructions=instructions, conversation=conversation, store=store, session_id=session_id,+ durable_key=durable_key, terminal_replay=terminal_replay)try:await st.emit_created()async for item in _iter_stream_items(stream_q, agent_task, response):@@ -1100,15 +1164,10 @@ class OpenAICompatRoutesMixin:await st.flush_batch()await st.collect_result(agent_task)await st.close_message_item()- if st.agent_error:+ if st.agent_error and not (durable_key and st.result):await st.emit_failed()else:- env = await st.emit_completed()- if durable_key is not None:- headers = {k: v for k, v in response.headers.items() if k.startswith('X-Hermes-')}- self._response_store.claim(durable_key[0], {- 'fingerprint': durable_key[1], 'response': env, 'headers': headers,- 'events': st.recorded_events})+ await st.emit_completed()except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError):st.persist_incomplete_if_needed()await _abandon_agent_task(agent_ref, agent_task, "SSE client disconnected")@@ -1166,12 +1225,19 @@ class OpenAICompatRoutesMixin:idempotency_scope = self._run_idempotency_scope(request)durable_key = (f'idem:{idempotency_scope}:{idempotency_key}',_make_request_fingerprint(body, keys=_RESPONSES_FINGERPRINT_KEYS))- # A record without ``response`` is a claim held by a request still running (or never- # settled): a different body under it conflicts exactly as under a settled one.- replay = self._response_store.get(durable_key[0])- if replay is not None and replay.get('fingerprint') != durable_key[1]:- return durable_key, idempotency_scope, idempotency_key, _idempotency_conflict()- if replay is not None and replay.get('response') is not None:+ from gateway.platforms.api_server import _openai_error+ from gateway.platforms.api_server_response_admissions import request_binding+ response_store = self._current_response_store()+ binding = request_binding(self, request, durable_key)+ if not response_store.request_key_matches(durable_key[0], binding):+ return durable_key, idempotency_scope, idempotency_key, web.json_response(+ _openai_error('admission_conflict', code='admission_conflict'), status=409)+ replay = response_store.get(durable_key[0])+ if replay is not None:+ if replay.get('fingerprint') != durable_key[1]:+ from gateway.platforms.api_server import _openai_error+ return durable_key, idempotency_scope, idempotency_key, web.json_response(+ _openai_error('admission_conflict', code='admission_conflict'), status=409)if stream:return (durable_key, idempotency_scope, idempotency_key,await self._replay_sse_responses(request, replay))@@ -1182,8 +1248,8 @@ class OpenAICompatRoutesMixin:async def _handle_responses(self, request: "web.Request") -> "web.Response":"""POST /v1/responses — OpenAI Responses API format."""from gateway.platforms.api_server import (- ThreadSafeAsyncQueue, _auto_truncate_response_history, _coerce_request_bool,- _content_has_visible_payload, _error_response, _invalid_request, _redact_api_error_text,+ ThreadSafeAsyncQueue, _coerce_request_bool,+ _error_response, _invalid_request, _redact_api_error_text,_resolve_media_to_data_urls, _responses_usage_payload)# Bound total in-flight agent runs (configurable; #7483).limited = self._concurrency_limited_response()@@ -1196,8 +1262,6 @@ class OpenAICompatRoutesMixin:body = await request.json()except Exception:return _invalid_request("Invalid JSON in request body")- from gateway.platforms.api_server import _request_relay_metadata- relay_metadata = _request_relay_metadata(body)raw_input = body.get("input")if raw_input is None:return _error_response("Missing 'input' field", 400)@@ -1212,72 +1276,23 @@ class OpenAICompatRoutesMixin:request, body, stream)if replayed is not None:return replayed- if conversation:- # A conversation name resolves to its latest response_id (unknown = new conversation).- previous_response_id = self._current_response_store().get_conversation(conversation)-- input_messages, input_err = _parse_responses_input(raw_input)- if input_err is not None:- return input_err-- # Explicit conversation_history (stateless clients) beats previous_response_id chaining.- conversation_history: List[Dict[str, Any]] = []- raw_history = body.get("conversation_history")- if raw_history:- conversation_history, history_err = _parse_conversation_history(raw_history)- if history_err is not None:- return history_err- if previous_response_id:- logger.debug("Both conversation_history and previous_response_id provided; using conversation_history")- stored_session_id = None- if not conversation_history and previous_response_id:- stored = self._current_response_store().get(previous_response_id)- if stored is None:- return _error_response(f"Previous response not found: {previous_response_id}", 404)- conversation_history = list(stored.get("conversation_history", []))- stored_session_id = stored.get("session_id")- if instructions is None:- instructions = stored.get("instructions")- # All input messages but the last become history; the last is the user message.- conversation_history.extend(input_messages[:-1])- user_message: Any = input_messages[-1].get("content", "") if input_messages else ""- if not _content_has_visible_payload(user_message):- return _error_response("No user message found in input", 400)- if body.get("truncation") == "auto":- conversation_history = _auto_truncate_response_history(conversation_history)-- # Session precedence: previous_response_id chain > declared X-Hermes-Session-Key > fresh- # id. Binding the declared key follows the same precedence: a chain-selected session must- # not have its routing key rewritten to this header.- _declared_selected = not stored_session_id and bool(gateway_session_key)- session_id = (- stored_session_id- or await asyncio.to_thread(self._declared_conversation_session, gateway_session_key)- or str(uuid.uuid4()))- route, agent_overrides, selection_error = self._select_request_route(- body, session_id=session_id, gateway_session_key=gateway_session_key,- model_alias=body.get("model"))- if selection_error is not None:- return selection_error- run_kwargs = dict(- user_message=user_message, conversation_history=conversation_history,- ephemeral_system_prompt=instructions, session_id=session_id,- gateway_session_key=gateway_session_key, bind_declared_conversation=_declared_selected,- **agent_overrides, route=route, relay_metadata=relay_metadata)- if durable_key is not None:- import hashlib- # A fresh responses request must recover its target before admission; the target and- # the request identity carry the authenticated namespace so a rotated API key never- # lands on (or replays) another principal's admission.- if not stored_session_id and not gateway_session_key:- session_id = 'response-' + hashlib.sha256(- f'{idempotency_scope}\0{idempotency_key}'.encode()).hexdigest()- run_kwargs['session_id'] = session_id- run_kwargs['request_id'] = f'responses:{idempotency_scope}:{idempotency_key}'- # Claimed for this body before admission: the first writer keeps the key, so a different- # body racing it is refused here rather than admitted beside it (and replayed later).- if self._response_store.claim(durable_key[0], {'fingerprint': durable_key[1]})['fingerprint'] != durable_key[1]:- return _idempotency_conflict()+ from gateway.platforms.api_server_response_admissions import prepare_context+ from hermes_state_runtime import RuntimeStoreError+ try:+ context, error = await prepare_context(+ self, request, body, gateway_session_key, durable_key, idempotency_scope, idempotency_key)+ except RuntimeStoreError as exc:+ from gateway.platforms.api_server import _openai_error+ return web.json_response(_openai_error(exc.reason, code=exc.reason), status=409)+ if error is not None:+ return error+ session_id, user_message = context['session_id'], context['user_message']+ conversation_history, instructions = context['conversation_history'], context['instructions']+ run_kwargs, run_agent = context['run_kwargs'], context['run_agent']+ response_id, created_at = _response_identity(self._current_response_store(), durable_key)+ response_model = body.get('model', self._model_name)+ if durable_key:+ response_model = self._current_response_store().request_model(durable_key[0], response_model)if stream:_stream_q = ThreadSafeAsyncQueue()@@ -1300,32 +1315,34 @@ class OpenAICompatRoutesMixin:if not already_streamed and isinstance(text, str) and text.strip():_stream_q.put_threadsafe(("__commentary__", {"text": text}))agent_task, agent_ref = self._spawn_stream_agent(- _stream_q, tool_progress_callback=_on_tool_progress,+ _stream_q, run_agent=run_agent, tool_progress_callback=_on_tool_progress,tool_start_callback=_on_tool_start, tool_complete_callback=_on_tool_complete,interim_assistant_callback=_on_commentary, **run_kwargs)return await self._write_sse_responses(- request=request, response_id=f"resp_{uuid.uuid4().hex[:28]}",- model=body.get("model", self._model_name), created_at=int(time.time()),+ request=request, response_id=response_id,+ model=response_model, created_at=created_at,stream_q=_stream_q, agent_task=agent_task, agent_ref=agent_ref,conversation_history=conversation_history, user_message=user_message,instructions=instructions, conversation=conversation, store=store,session_id=session_id, gateway_session_key=gateway_session_key,- durable_key=durable_key)+ durable_key=durable_key, terminal_replay=context.get('terminal_replay', False))async def _compute_response():- return await self._run_agent(**run_kwargs)+ return await run_agent(**run_kwargs)outcome, err = await self._run_idempotent(request, body, _compute_response, log_label="responses",fingerprint_keys=list(_RESPONSES_FINGERPRINT_KEYS), route="responses",)if err is not None:return err+ if durable_key is not None:+ replay = self._current_response_store().get(durable_key[0])+ if replay is not None:+ return web.json_response(replay['response'], headers=replay.get('headers') or {})result, usage = outcomefinal_response = _resolve_media_to_data_urls(result.get("final_response", ""))if not final_response:final_response = _redact_api_error_text(result.get("error", "(No response generated)"))- response_id = f"resp_{uuid.uuid4().hex[:28]}"- created_at = int(time.time())full_history = self._build_response_conversation_history(conversation_history, user_message, result, final_response,tool_output_max_chars=self._history_tool_output_max_chars)@@ -1340,24 +1357,29 @@ class OpenAICompatRoutesMixin:conversation_history, user_message, result)response_data = {"id": response_id, "object": "response", "status": _response_status(result),- "created_at": created_at, "model": body.get("model", self._model_name),- "output": self._extract_output_items(result, start_index=output_start_index),+ "created_at": created_at, "model": response_model,+ "output": self._extract_output_items(result, start_index=output_start_index,+ **({'response_id': response_id} if durable_key else {})),"usage": _responses_usage_payload(usage)}+ if durable_key:+ response_data['output'] = self._current_response_store().order_output(durable_key[0], response_data['output'])if response_data['status'] == 'failed':response_data['error'] = {'code': 'agent_error', 'message': _redact_api_error_text(result.get('error') or 'The admitted turn failed.')}if store:response_store = self._current_response_store()+ advance_conversation = conversation and (not context.get('terminal_replay')+ or response_store.get_conversation(conversation) in (None, response_id))response_store.put(response_id, {"response": response_data, "conversation_history": full_history,"instructions": instructions, "session_id": _effective_session_id})- if conversation:+ if advance_conversation:response_store.set_conversation(conversation, response_id)response_headers = {"X-Hermes-Session-Id": _effective_session_id}if gateway_session_key:response_headers["X-Hermes-Session-Key"] = gateway_session_keyif durable_key is not None:- self._response_store.claim(durable_key[0], {+ self._current_response_store().put(durable_key[0], {'fingerprint': durable_key[1], 'response': response_data, 'headers': response_headers})return web.json_response(response_data, headers=response_headers)@@ -1448,7 +1470,7 @@ class OpenAICompatRoutesMixin:return out@staticmethod- def _extract_output_items(result: Dict[str, Any], start_index: int = 0) -> List[Dict[str, Any]]:+ def _extract_output_items(result: Dict[str, Any], start_index: int = 0, *, response_id=None) -> List[Dict[str, Any]]:"""Output items from ``result["messages"][start_index:]``: ``function_call`` per assistanttool_call, ``function_call_output`` per tool message, then the final ``message``."""from gateway.platforms.api_server import _redact_api_error_text@@ -1481,4 +1503,7 @@ class OpenAICompatRoutesMixin:final = result.get("final_response", "") or _redact_api_error_text(result.get("error", "(No response generated)"))items.append(_message_item(final))+ if response_id is not None:+ from gateway.platforms.api_server_response_identity import identify_output+ return identify_output(items, response_id)return itemsdiff --git a/gateway/platforms/api_server_response_admissions.py b/gateway/platforms/api_server_response_admissions.pynew file mode 100644index 00000000000..be67603f207--- /dev/null+++ b/gateway/platforms/api_server_response_admissions.py@@ -0,0 +1,163 @@+"""Responses retries observe their original admission before resolving mutable conversation names."""+from functools import partial+import hashlib+import json+import uuid++from hermes_state_runtime import RuntimeStoreError+++def request_binding(adapter, request, durable_key):+ from gateway.platforms.api_server import _make_request_fingerprint+ return _make_request_fingerprint({'request': durable_key[1],+ 'declared_session_key': adapter._parse_session_key_header(request)[0]},+ keys=('request', 'declared_session_key'))+++def _request_admission_rows(db, request_id):+ """A lost derivative pointer cannot erase accepted identity on retirement."""+ from hermes_state_terminal import ADMISSION_PREFIX+ with db._read_ctx() as conn:+ rows = [dict(row) for row in conn.execute(+ "SELECT * FROM session_admissions WHERE principal_id='api' AND request_id=?", (request_id,))]+ retired = conn.execute(+ "SELECT value FROM state_meta WHERE key GLOB ? "+ "AND json_extract(value, '$.principal_id')='api' AND json_extract(value, '$.request_id')=?",+ (ADMISSION_PREFIX + '*', request_id))+ rows.extend(json.loads(row[0]) for row in retired)+ return rows+++def find_admission(adapter, durable_key, request_id):+ """Scope comes from authenticated profile/key identity, never a caller-supplied session id.++ The compact pointer survives response-cache eviction and transcript retirement. A process+ loss between the authority commit and pointer commit is repaired from that exact request id.+ """+ from gateway.session_authorities import active_authority+ from gateway.session_contract import SessionRef+ from hermes_state_runtime import get_session_admission, _row+ authority = active_authority(adapter.gateway_runner)+ if authority is None or adapter._ensure_session_db() is not authority.db:+ raise RuntimeStoreError('profile_mismatch')+ store = adapter._current_response_store()+ admission_id = store.request_admission(durable_key[0])+ if admission_id:+ row = get_session_admission(authority.db, admission_id=admission_id)+ if row is None:+ raise RuntimeStoreError('storage_unavailable')+ else:+ rows = _request_admission_rows(authority.db, request_id)+ if len(rows) > 1:+ raise RuntimeStoreError('admission_conflict')+ if not rows:+ return None+ row = _row(rows[0])+ if row['principal_id'] != 'api' or row['request_id'] != request_id:+ raise RuntimeStoreError('permission_denied')+ if store.request_created_at(durable_key[0]) is None:+ # An older admission with no wire fingerprint cannot authorize a changed request just+ # because its caller reused the same key. Existing completed cache records still replay.+ raise RuntimeStoreError('admission_conflict')+ store.bind_request_admission(durable_key[0], row['admission_id'])+ ref = SessionRef(authority.profile_id, row['target_session_id'])+ if row['status'] in {'queued', 'started'}:+ from gateway.session_api import restore_api_session+ from gateway.session_api_turn import check_api_turn+ restore_api_session(authority, ref.session_id)+ check_api_turn(authority, ref, row['payload'])+ return authority, ref, row+++def admitted_context(admitted, *, replay=False):+ from gateway.session_api_turn import observe_api_turn+ _, ref, row = admitted+ payload = row['payload']+ data = payload.get('api_turn_v1', {})+ return dict(session_id=ref.session_id, user_message=payload.get('text', ''),+ conversation_history=data.get('history') or [],+ instructions=data.get('settings', {}).get('ephemeral_system_prompt'),+ run_kwargs={}, run_agent=partial(observe_api_turn, admitted),+ terminal_replay=replay or row['status'] == 'terminal')+++def _admit(adapter, durable_key, request_id, binding, run_kwargs, model):+ """No await between the final lookup and admission: simultaneous observers converge."""+ from gateway.session_api_turn import admit_api_turn+ store = adapter._current_response_store()+ if not store.bind_request_key(durable_key[0], binding, model=model):+ raise RuntimeStoreError('admission_conflict')+ admitted = find_admission(adapter, durable_key, request_id)+ replay = admitted is not None+ if admitted is None:+ try:+ admitted = admit_api_turn(adapter, request_id=request_id,+ **{'route_source': 'global', 'confirmed_runtime_lock': False,+ 'session_history_delivery': '', **run_kwargs})+ except Exception:+ # A definite pre-admission refusal does not reserve a poisoned identity. If storage+ # cannot prove absence, leave the binding intact for later recovery.+ if find_admission(adapter, durable_key, request_id) is None:+ store.forget_unadmitted_request(durable_key[0])+ raise+ store.bind_request_admission(durable_key[0], admitted[2]['admission_id'])+ return admitted_context(admitted, replay=replay)+++async def prepare_context(adapter, request, body, gateway_session_key, durable_key, scope, key):+ """Validate first-time requests; exact retries use the accepted payload and result only."""+ import asyncio+ from gateway.platforms.api_server import (+ _auto_truncate_response_history, _content_has_visible_payload, _error_response)+ from gateway.platforms.api_server_openai_routes import _parse_responses_input, _parse_conversation_history+ request_id = f'responses:{scope}:{key}' if durable_key else None+ if durable_key:+ admitted = find_admission(adapter, durable_key, request_id)+ if admitted is not None:+ return admitted_context(admitted, replay=True), None+ previous = body.get('previous_response_id')+ if body.get('conversation'):+ previous = adapter._current_response_store().get_conversation(body['conversation'])+ messages, error = _parse_responses_input(body['input'])+ if error is not None:+ return None, error+ history = []+ if body.get('conversation_history'):+ history, error = _parse_conversation_history(body['conversation_history'])+ if error is not None:+ return None, error+ stored_session_id = None+ instructions = body.get('instructions')+ if not history and previous:+ stored = adapter._current_response_store().get(previous)+ if stored is None:+ return None, _error_response(f'Previous response not found: {previous}', 404)+ history = list(stored.get('conversation_history', []))+ stored_session_id = stored.get('session_id')+ if instructions is None:+ instructions = stored.get('instructions')+ history.extend(messages[:-1])+ user_message = messages[-1].get('content', '') if messages else ''+ if not _content_has_visible_payload(user_message):+ return None, _error_response('No user message found in input', 400)+ if body.get('truncation') == 'auto':+ history = _auto_truncate_response_history(history)+ declared_selected = not stored_session_id and bool(gateway_session_key)+ session_id = stored_session_id or await asyncio.to_thread(+ adapter._declared_conversation_session, gateway_session_key) or str(uuid.uuid4())+ if durable_key and not stored_session_id and not gateway_session_key:+ session_id = 'response-' + hashlib.sha256(f'{scope}\0{key}'.encode()).hexdigest()+ route, overrides, error = adapter._select_request_route(body, session_id=session_id,+ gateway_session_key=gateway_session_key, model_alias=body.get('model'))+ if error is not None:+ return None, error+ from gateway.platforms.api_server import _request_relay_metadata+ run_kwargs = dict(user_message=user_message, conversation_history=history,+ ephemeral_system_prompt=instructions, session_id=session_id,+ gateway_session_key=gateway_session_key, bind_declared_conversation=declared_selected,+ **overrides, route=route, relay_metadata=_request_relay_metadata(body))+ if durable_key:+ return _admit(adapter, durable_key, request_id, request_binding(adapter, request, durable_key),+ run_kwargs, body.get('model', adapter._model_name)), None+ return dict(session_id=session_id, user_message=user_message, conversation_history=history,+ instructions=instructions, run_kwargs=run_kwargs, run_agent=adapter._run_agent), Nonediff --git a/gateway/platforms/api_server_response_identity.py b/gateway/platforms/api_server_response_identity.pynew file mode 100644index 00000000000..0d0f0dcb79a--- /dev/null+++ b/gateway/platforms/api_server_response_identity.py@@ -0,0 +1,25 @@+"""Stable presentation identity for a durable Responses admission.++The model label, creation time and compact ID/index ordering survive response-body eviction.+Item IDs derive from response identity and occurrence; no additional transcript/output copy is retained.+"""+import hashlib+import json++_PREFIXES = {'function_call': 'fc', 'function_call_output': 'fco', 'reasoning': 'rs', 'message': 'msg'}+++def next_item_id(response_id, counters, kind, *, call_id=None, commentary=False):+ # The final message is distinct from any live commentary, which is not part of the answer.+ key = (kind, call_id, bool(commentary))+ occurrence = counters.get(key, 0)+ counters[key] = occurrence + 1+ digest = hashlib.sha256(json.dumps([response_id, *key, occurrence], separators=(',', ':')).encode()).hexdigest()+ return _PREFIXES[kind] + '_' + digest[:24]+++def identify_output(items, response_id):+ counters = {}+ return [dict(item, id=next_item_id(response_id, counters, item['type'],+ call_id=item.get('call_id'), commentary=item.get('phase') == 'commentary'))+ for item in items]diff --git a/gateway/platforms/api_server_response_store.py b/gateway/platforms/api_server_response_store.pyindex b5137a922be..a3114a44f83 100644--- a/gateway/platforms/api_server_response_store.py+++ b/gateway/platforms/api_server_response_store.py@@ -39,6 +39,18 @@ class ResponseStore:"response_id TEXT PRIMARY KEY, data TEXT NOT NULL, accessed_at REAL NOT NULL)")self._conn.execute("CREATE TABLE IF NOT EXISTS conversations (name TEXT PRIMARY KEY, response_id TEXT NOT NULL)")+ # Compact immutable request identity outlives the LRU response bodies.+ # Distinct canonical session targets must not turn a global retry key+ # into a last-writer-wins response cache entry.+ self._conn.execute(+ "CREATE TABLE IF NOT EXISTS response_keys (request_key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, created_at INTEGER NOT NULL)")+ self._conn.execute(+ "CREATE TABLE IF NOT EXISTS response_admissions (request_key TEXT PRIMARY KEY, admission_id TEXT NOT NULL)")+ self._conn.execute('CREATE TABLE IF NOT EXISTS response_output_order '+ '(request_key TEXT NOT NULL, item_id TEXT NOT NULL, output_index INTEGER NOT NULL, '+ 'PRIMARY KEY(request_key,item_id), UNIQUE(request_key,output_index))')+ from hermes_cli.sqlite_util import add_column_if_missing+ add_column_if_missing(self._conn, 'response_keys', 'model_json', 'model_json TEXT')self._conn.commit()# Conversation history lives here: owner-only perms, once at init (not per commit).self._tighten_file_permissions()@@ -74,8 +86,9 @@ class ResponseStore:def put(self, response_id: str, data: Dict[str, Any]) -> None:"""Store a response, evicting the oldest if at capacity."""+ insert = 'INSERT OR IGNORE' if response_id.startswith('idem:') else 'INSERT OR REPLACE'self._conn.execute(- "INSERT OR REPLACE INTO responses (response_id, data, accessed_at) VALUES (?, ?, ?)",+ insert + " INTO responses (response_id, data, accessed_at) VALUES (?, ?, ?)",(response_id, json.dumps(data, default=str), time.time()))self._evict_and_commit()@@ -108,6 +121,66 @@ class ResponseStore:self._conn.execute(f"DELETE FROM responses WHERE response_id IN ({placeholders})", evict_ids)self._conn.commit()+ def bind_request_key(self, key: str, fingerprint: str, *, model=None) -> bool:+ """Reserve one immutable digest before any canonical admission can run."""+ with self._conn:+ self._conn.execute('INSERT OR IGNORE INTO response_keys '+ '(request_key,fingerprint,created_at,model_json) VALUES (?,?,?,?)',+ (key, fingerprint, int(time.time()), json.dumps(model)))+ row = self._conn.execute('SELECT fingerprint FROM response_keys WHERE request_key=?', (key,)).fetchone()+ return row[0] == fingerprint++ def request_model(self, key: str, fallback):+ """The accepted wire label survives route changes and response-body LRU eviction."""+ with self._conn:+ # Upgrade older compact bindings only on a cache miss; their existing cached+ # envelopes keep replaying byte-for-byte through the ordinary fast path.+ self._conn.execute('UPDATE response_keys SET model_json=? WHERE request_key=? AND model_json IS NULL',+ (json.dumps(fallback), key))+ row = self._conn.execute('SELECT model_json FROM response_keys WHERE request_key=?', (key,)).fetchone()+ return json.loads(row[0]) if row is not None else fallback++ def output_index(self, key: str, item_id: str) -> int:+ """Allocate before live publication; retries and parallel observers share this order.++ One compact id/integer pair per output item survives body LRU eviction. No tool output,+ reasoning text or cumulative conversation is copied into this identity table.+ """+ with self._conn:+ self._conn.execute('INSERT OR IGNORE INTO response_output_order '+ '(request_key,item_id,output_index) SELECT ?,?,COALESCE(MAX(output_index)+1,0) '+ 'FROM response_output_order WHERE request_key=?', (key, item_id, key))+ row = self._conn.execute('SELECT output_index FROM response_output_order WHERE request_key=? AND item_id=?',+ (key, item_id)).fetchone()+ return row[0]++ def order_output(self, key: str, items):+ return sorted(items, key=lambda item: self.output_index(key, item['id']))++ def request_created_at(self, key: str) -> Optional[int]:+ row = self._conn.execute('SELECT created_at FROM response_keys WHERE request_key=?', (key,)).fetchone()+ return row[0] if row else None++ def request_key_matches(self, key: str, fingerprint: str) -> bool:+ row = self._conn.execute('SELECT fingerprint FROM response_keys WHERE request_key=?', (key,)).fetchone()+ return row is None or row[0] == fingerprint++ def request_admission(self, key: str) -> Optional[str]:+ row = self._conn.execute('SELECT admission_id FROM response_admissions WHERE request_key=?', (key,)).fetchone()+ return row[0] if row else None++ def bind_request_admission(self, key: str, admission_id: str) -> None:+ from hermes_state_runtime import RuntimeStoreError+ with self._conn:+ self._conn.execute('INSERT OR IGNORE INTO response_admissions VALUES (?,?)', (key, admission_id))+ if self.request_admission(key) != admission_id:+ raise RuntimeStoreError('admission_conflict')++ def forget_unadmitted_request(self, key: str) -> None:+ with self._conn:+ self._conn.execute('DELETE FROM response_keys WHERE request_key=? AND NOT EXISTS '+ '(SELECT 1 FROM response_admissions WHERE request_key=?)', (key, key))+def delete(self, response_id: str) -> bool:"""Remove a response (and conversation mappings to it). True if found and deleted."""self._conn.execute("DELETE FROM conversations WHERE response_id = ?", (response_id,))diff --git a/tests/gateway/test_adversarial_responses_eviction.py b/tests/gateway/test_adversarial_responses_eviction.pynew file mode 100644index 00000000000..891e2cdf0d2--- /dev/null+++ b/tests/gateway/test_adversarial_responses_eviction.py@@ -0,0 +1,153 @@+"""Independent review: durable exact retries keep output after response-body LRU eviction."""+import json++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer++[email protected]('stream', [False, True])[email protected]('first_stream', [False, True])+async def test_terminal_retry_after_cache_eviction_preserves_result(api, owner, stream, first_stream):+ calls = []+ api._model_name = 'accepted-model'+ async def handle(event):+ from gateway.session_results import execution_result+ from gateway.session_api_turn import publish_api_tool_event+ calls.append(event.text)+ sid = event.source.chat_id+ generation = owner.sessions[sid].event_stream.execution['execution_generation']+ publish_api_tool_event(owner, sid, generation, 'tool.start', 'call_1', 'read_file', {'path': 'a'})+ publish_api_tool_event(owner, sid, generation, 'tool.complete', 'call_1', 'read_file', {'path': 'a'}, 'read')+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': [+ {'role': 'assistant', 'content': '', 'reasoning': 'reasoned', 'tool_calls': [+ {'id': 'call_1', 'type': 'function', 'function': {'name': 'read_file', 'arguments': '{"path":"a"}'}}]},+ {'role': 'tool', 'tool_call_id': 'call_1', 'content': 'read'},+ {'role': 'assistant', 'content': 'answer'}]}+ return 'answer'+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ body, headers = {'input': 'work', 'stream': first_stream}, {'Idempotency-Key': 'evicted-terminal'}+ async with TestClient(TestServer(app)) as client:+ first = await client.post('/v1/responses', json=body, headers=headers)+ assert first.status == 200+ if first_stream:+ frames = [json.loads(line[6:]) for line in (await first.text()).splitlines() if line.startswith('data: ')]+ original = frames[-1]['response']+ final_ids = {item['id'] for item in original['output']}+ live_ids = {frame['item']['id'] for frame in frames if frame['type'] == 'response.output_item.added'}+ assert live_ids <= final_ids+ else:+ original = await first.json()+ api._model_name = 'changed-after-acceptance'+ store = api._current_response_store()+ store._max_size = 1+ store.put('newer-unrelated-response', {'response': {}, 'conversation_history': []})+ assert store.get(original['id']) is None+ retry = await client.post('/v1/responses', json={**body, 'stream': stream}, headers=headers)+ assert retry.status == 200+ if stream:+ events = [json.loads(line[6:]) for line in (await retry.text()).splitlines() if line.startswith('data: ')]+ repeated = events[-1]['response']+ else:+ repeated = await retry.json()+ assert calls == ['work']+ assert repeated == original+++async def test_failed_terminal_retry_after_eviction_keeps_envelope(api, owner):+ calls = []+ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ execution_result.get()['result'] = {'final_response': '', 'failed': True, 'error': 'provider unavailable', 'messages': []}+ return ''+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ headers = {'Idempotency-Key': 'failed-eviction'}+ async with TestClient(TestServer(app)) as client:+ response = await client.post('/v1/responses', json={'input': 'work'}, headers=headers)+ original = await response.json()+ store = api._current_response_store()+ store._max_size = 1+ store.put('unrelated', {'response': {}})+ retry = await client.post('/v1/responses', json={'input': 'work', 'stream': True}, headers=headers)+ frames = [json.loads(line[6:]) for line in (await retry.text()).splitlines() if line.startswith('data: ')]+ assert calls == ['work']+ assert frames[-1]['response'] == original++[email protected]('stream', [False, True])+async def test_retired_terminal_retry_after_eviction_keeps_compact_outcome(api, owner, stream):+ calls = []+ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': [+ {'role': 'assistant', 'content': '', 'tool_calls': [+ {'id': 'call_1', 'type': 'function', 'function': {'name': 'read_file', 'arguments': '{"path":"deleted-sentinel"}'}}]},+ {'role': 'assistant', 'content': 'answer'}]}+ return 'answer'+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ headers = {'Idempotency-Key': 'retired-eviction'}+ async with TestClient(TestServer(app)) as client:+ response = await client.post('/v1/responses', json={'input': 'work'}, headers=headers)+ original = await response.json()+ assert owner.db.delete_session(response.headers['X-Hermes-Session-Id'])+ store = api._current_response_store()+ store._max_size = 1+ store.put('unrelated', {'response': {}})+ repeated = await client.post('/v1/responses', json={'input': 'work', 'stream': stream}, headers=headers)+ assert repeated.status == 200+ if stream:+ frames = [json.loads(line[6:]) for line in (await repeated.text()).splitlines() if line.startswith('data: ')]+ value = frames[-1]['response']+ assert all('output_index' not in frame for frame in frames)+ else:+ value = await repeated.json()+ assert calls == ['work']+ assert value['id'] == original['id'] and value['status'] == original['status']+ assert 'deleted-sentinel' not in str(value)+ assert value['output'][-1]['content'][0]['text'] == 'answer'++[email protected]('stream', [False, True])+async def test_terminal_replay_does_not_roll_named_conversation_back(api, owner, stream):+ calls = []+ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ execution_result.get()['result'] = {'final_response': event.text, 'messages': []}+ return event.text+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ first_headers = {'Idempotency-Key': 'first-conversation-turn'}+ body = {'input': 'first', 'conversation': 'shared'}+ async with TestClient(TestServer(app)) as client:+ first = await client.post('/v1/responses', json=body, headers=first_headers)+ original = await first.json()+ later = await client.post('/v1/responses', json={'input': 'later', 'conversation': 'shared'},+ headers={'Idempotency-Key': 'later-conversation-turn'})+ latest = await later.json()+ store = api._current_response_store()+ store._max_size = 4+ for index in range(3):+ store.get(latest['id'])+ store.put('cache-pressure-' + str(index), {'response': {}})+ assert store.get(original['id']) is None+ assert store.get_conversation('shared') == latest['id']+ store._max_size = 100+ repeated = await client.post('/v1/responses', json={**body, 'stream': stream}, headers=first_headers)+ assert repeated.status == 200+ await repeated.read()+ assert store.get_conversation('shared') == latest['id']+ assert calls == ['first', 'later']diff --git a/tests/gateway/test_adversarial_responses_pending.py b/tests/gateway/test_adversarial_responses_pending.pynew file mode 100644index 00000000000..954530697a3--- /dev/null+++ b/tests/gateway/test_adversarial_responses_pending.py@@ -0,0 +1,170 @@+"""An in-flight Responses identity cannot acquire a second target via a moving conversation."""+import asyncio++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer+++async def test_pending_retry_pins_named_conversation_target(api, owner):+ entered, duplicate, release = asyncio.Event(), asyncio.Event(), asyncio.Event()+ calls = []++ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ if event.text == 'slow':+ entered.set()+ if calls.count('slow') > 1:+ duplicate.set()+ await release.wait()+ execution_result.get()['result'] = {'final_response': 'reply', 'messages': []}+ return 'reply'++ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ first_body = {'input': 'slow', 'conversation': 'shared'}+ first_headers = {'Idempotency-Key': 'pending-original'}+ requests = []+ async with TestClient(TestServer(app)) as client:+ try:+ requests.append(asyncio.create_task(client.post('/v1/responses', json=first_body, headers=first_headers)))+ await asyncio.wait_for(entered.wait(), 10)+ advanced = await client.post('/v1/responses', json={'input': 'fast', 'conversation': 'shared'},+ headers={'Idempotency-Key': 'concurrent-other'})+ assert advanced.status == 200+ requests.append(asyncio.create_task(client.post('/v1/responses', json=first_body, headers=first_headers)))+ try:+ await asyncio.wait_for(duplicate.wait(), 2)+ except TimeoutError:+ pass+ release.set()+ responses = await asyncio.gather(*requests)+ assert all(response.status == 200 for response in responses)+ assert calls.count('slow') == 1, 'retry executed the same request on the newly mapped session'+ assert await responses[0].json() == await responses[1].json()+ assert responses[0].headers['X-Hermes-Session-Id'] == responses[1].headers['X-Hermes-Session-Id']+ finally:+ release.set()+ await asyncio.gather(*requests, return_exceptions=True)+++async def test_unknown_retry_recovers_admission_after_pointer_commit_loss(api, owner):+ from gateway.session_contract import SessionRef+ from hermes_state_runtime import begin_runtime_epoch, recover_session_inputs+ from gateway.platforms.api_server_response_store import ResponseStore+ started, release = asyncio.Event(), asyncio.Event()+ calls = []++ async def handle(event):+ calls.append(event.text)+ started.set()+ await release.wait()+ return 'done'++ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ body, headers = {'input': 'uncertain', 'conversation': 'shared'}, {'Idempotency-Key': 'lost-owner'}+ async with TestClient(TestServer(app)) as client:+ first = asyncio.create_task(client.post('/v1/responses', json=body, headers=headers))+ try:+ await asyncio.wait_for(started.wait(), 10)+ row = owner.db._read_one('SELECT * FROM session_admissions')+ task = owner.sessions[row['target_session_id']].task+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ owner.epoch = begin_runtime_epoch(owner.db, instance_id='restarted')+ recover_session_inputs(owner.db, epoch=owner.epoch)+ owner._pause(SessionRef(owner.profile_id, row['target_session_id']), 'unknown_execution')+ assert (await first).status == 409+ # Crash after the ledger commit but before its response-store pointer was saved.+ store = api._current_response_store()+ store._conn.execute('DELETE FROM response_admissions')+ store._conn.commit()+ path = store._db_path+ store.close()+ api._response_store = ResponseStore(db_path=path)+ api._response_store.put('different', {'session_id': 'different-target', 'conversation_history': []})+ api._response_store.set_conversation('shared', 'different')+ retry = await client.post('/v1/responses', json=body, headers=headers)+ assert retry.status == 409+ assert (await retry.json())['error']['code'] == 'unknown_execution'+ assert calls == ['uncertain']+ assert owner.db._read_one('SELECT COUNT(*) FROM session_admissions')[0] == 1+ assert api._response_store._conn.execute('SELECT admission_id FROM response_admissions').fetchone()[0] == row['admission_id']+ finally:+ release.set()+ await asyncio.gather(first, return_exceptions=True)+++async def test_validation_refusal_does_not_reserve_retry_key(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/responses', api._handle_responses)+ headers = {'Idempotency-Key': 'corrected-request'}+ async with TestClient(TestServer(app)) as client:+ refused = await client.post('/v1/responses', json={'input': 42}, headers=headers)+ assert refused.status == 400+ assert api._current_response_store()._conn.execute('SELECT COUNT(*) FROM response_keys').fetchone()[0] == 0+ accepted = await client.post('/v1/responses', json={'input': 'valid'}, headers=headers)+ assert accepted.status == 200+ assert calls == ['valid']++[email protected]('stream', [False, True])+async def test_concurrent_exact_responses_share_terminal_envelope(api, owner, stream):+ import json+ started, release = asyncio.Event(), asyncio.Event()+ async def handle(event):+ from gateway.session_results import execution_result+ started.set()+ await release.wait()+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': [+ {'role': 'assistant', 'content': '', 'tool_calls': [+ {'id': 'call_1', 'type': 'function', 'function': {'name': 'read_file', 'arguments': '{"path":"a"}'}}]},+ {'role': 'tool', 'tool_call_id': 'call_1', 'content': 'read'},+ {'role': 'assistant', 'content': 'answer'}]}+ return 'answer'+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ body, headers = {'input': 'work', 'stream': stream}, {'Idempotency-Key': 'concurrent-exact'}+ pending = []+ async with TestClient(TestServer(app)) as client:+ try:+ pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))+ await asyncio.wait_for(started.wait(), 10)+ pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))+ # Observe both HTTP requests before the turn can settle.+ deadline = asyncio.get_running_loop().time() + 5+ while sum(len(observers) for observers in getattr(owner, 'api_observers', {}).values()) < 2:+ assert asyncio.get_running_loop().time() < deadline+ await asyncio.sleep(.01)+ release.set()+ responses = await asyncio.gather(*pending)+ if stream:+ frames = [[json.loads(line[6:]) for line in (await response.text()).splitlines()+ if line.startswith('data: ')] for response in responses]+ values = [events[-1]['response'] for events in frames]+ assert frames[0][0]['response'] == frames[1][0]['response']+ else:+ values = [await response.json() for response in responses]+ assert values[0] == values[1]+ retry = await client.post('/v1/responses', json={**body, 'stream': False}, headers=headers)+ assert await retry.json() == values[0]+ assert owner.db._read_one('SELECT COUNT(*) FROM session_admissions')[0] == 1+ finally:+ release.set()+ await asyncio.gather(*pending, return_exceptions=True)diff --git a/tests/gateway/test_adversarial_responses_pointer_retirement.py b/tests/gateway/test_adversarial_responses_pointer_retirement.pynew file mode 100644index 00000000000..9b75015e7dd--- /dev/null+++ b/tests/gateway/test_adversarial_responses_pointer_retirement.py@@ -0,0 +1,49 @@+"""A lost response pointer must remain recoverable after the accepted transcript is retired."""+import asyncio++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer+++async def test_pointer_commit_loss_then_retirement_cannot_reexecute_moved_conversation(api, owner, monkeypatch):+ from gateway.session_contract import SessionRef+ from gateway.session_results import execution_result++ calls = []++ async def handle(event):+ calls.append(event.text)+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': []}+ return 'answer'++ owner.runner._handle_message = handle+ store = api._current_response_store()+ bind = store.bind_request_admission+ def lose_pointer(*args):+ raise RuntimeError('simulated process loss after admission commit')+ monkeypatch.setattr(store, 'bind_request_admission', lose_pointer)+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ body = {'input': 'original-once', 'conversation': 'moving'}+ headers = {'Idempotency-Key': 'lost-pointer'}+ async with TestClient(TestServer(app)) as client:+ failed = await client.post('/v1/responses', json=body, headers=headers)+ assert failed.status == 500+ monkeypatch.setattr(store, 'bind_request_admission', bind)+ admitted = owner.db._read_one('SELECT * FROM session_admissions')+ assert admitted['status'] == 'queued'+ # Owner recovery executes the committed request even though no HTTP response was saved.+ ref = SessionRef(owner.profile_id, admitted['target_session_id'])+ owner._schedule(ref)+ await asyncio.wait_for(owner.sessions[ref.session_id].task, 10)+ assert calls == ['original-once']+ assert owner.db.delete_session(ref.session_id)+ # A later request advances the name to an independent live target.+ advanced = await client.post('/v1/responses', json={'input': 'new-target', 'conversation': 'moving'},+ headers={'Idempotency-Key': 'successor'})+ assert advanced.status == 200+ retry = await client.post('/v1/responses', json=body, headers=headers)+ await retry.read()+ assert calls.count('original-once') == 1, 'retired tombstone was missed and the retry executed again'diff --git a/tests/gateway/test_adversarial_responses_stream_backpressure.py b/tests/gateway/test_adversarial_responses_stream_backpressure.pynew file mode 100644index 00000000000..1fe89bf9ade--- /dev/null+++ b/tests/gateway/test_adversarial_responses_stream_backpressure.py@@ -0,0 +1,68 @@+"""A completed observer cannot assign indexes ahead of a delayed live stream's items."""+import asyncio+import json++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer+++async def test_nonstream_observer_does_not_create_gaps_in_delayed_live_stream(api, owner, monkeypatch):+ from gateway.platforms.api_server_openai_routes import _ResponsesStream+ blocked, release_stream, release_agent = asyncio.Event(), asyncio.Event(), asyncio.Event()+ emit = _ResponsesStream.emit_tool_started+ async def held(self, payload):+ blocked.set()+ await release_stream.wait()+ await emit(self, payload)+ monkeypatch.setattr(_ResponsesStream, 'emit_tool_started', held)++ async def handle(event):+ from gateway.session_api_turn import publish_api_tool_event+ from gateway.session_results import execution_result+ sid = event.source.chat_id+ generation = owner.sessions[sid].event_stream.execution['execution_generation']+ publish_api_tool_event(owner, sid, generation, 'tool.start', 'call_1', 'read_file', {'path': 'a'})+ publish_api_tool_event(owner, sid, generation, 'tool.complete', 'call_1', 'read_file', {'path': 'a'}, 'read')+ await release_agent.wait()+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': [+ {'role': 'assistant', 'content': '', 'reasoning': 'reasoned', 'tool_calls': [+ {'id': 'call_1', 'type': 'function', 'function': {'name': 'read_file', 'arguments': '{"path":"a"}'}}]},+ {'role': 'tool', 'tool_call_id': 'call_1', 'content': 'read'},+ {'role': 'assistant', 'content': 'answer'}]}+ return 'answer'+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ headers, body = {'Idempotency-Key': 'backpressured-stream'}, {'input': 'work'}+ pending = []+ async with TestClient(TestServer(app)) as client:+ try:+ pending.append(asyncio.create_task(client.post('/v1/responses', json={**body, 'stream': True}, headers=headers)))+ await asyncio.wait_for(blocked.wait(), 5)+ pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))+ async with asyncio.timeout(5):+ while sum(map(len, owner.api_observers.values())) < 2:+ await asyncio.sleep(.01)+ release_agent.set()+ observer = await asyncio.wait_for(pending[1], 5)+ assert observer.status == 200+ await observer.read()+ release_stream.set()+ original = await pending[0]+ frames = [json.loads(line[6:]) for line in (await original.text()).splitlines()+ if line.startswith('data: ')]+ accumulated = []+ for frame in frames:+ if frame['type'] == 'response.created':+ accumulated = frame['response']['output'][:]+ elif frame['type'] == 'response.output_item.added':+ assert frame['output_index'] == len(accumulated), 'nonstream observer inserted output indexes ahead of the live stream'+ accumulated.append(frame['item'])+ elif 'output_index' in frame:+ assert frame['output_index'] < len(accumulated)+ finally:+ release_agent.set()+ release_stream.set()+ await asyncio.gather(*pending, return_exceptions=True)diff --git a/tests/gateway/test_adversarial_responses_stream_projection.py b/tests/gateway/test_adversarial_responses_stream_projection.pynew file mode 100644index 00000000000..3e3dd93ab71--- /dev/null+++ b/tests/gateway/test_adversarial_responses_stream_projection.py@@ -0,0 +1,91 @@+"""Incremental output indexes retain their identity in the terminal Responses envelope."""+import json+import asyncio++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer+++async def test_live_tool_output_index_identifies_same_terminal_item(api, owner):+ async def handle(event):+ from gateway.session_api_turn import publish_api_tool_event+ from gateway.session_results import execution_result+ sid = event.source.chat_id+ generation = owner.sessions[sid].event_stream.execution['execution_generation']+ publish_api_tool_event(owner, sid, generation, 'tool.start', 'call_1', 'read_file', {'path': 'a'})+ publish_api_tool_event(owner, sid, generation, 'tool.complete', 'call_1', 'read_file', {'path': 'a'}, 'read')+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': [+ {'role': 'assistant', 'content': '', 'reasoning': 'reasoned', 'tool_calls': [+ {'id': 'call_1', 'type': 'function', 'function': {'name': 'read_file', 'arguments': '{"path":"a"}'}}]},+ {'role': 'tool', 'tool_call_id': 'call_1', 'content': 'read'},+ {'role': 'assistant', 'content': 'answer'}]}+ return 'answer'++ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ async with TestClient(TestServer(app)) as client:+ response = await client.post('/v1/responses', json={'input': 'work', 'stream': True},+ headers={'Idempotency-Key': 'stable-output-index'})+ assert response.status == 200+ frames = [json.loads(line[6:]) for line in (await response.text()).splitlines()+ if line.startswith('data: ')]+ terminal = frames[-1]['response']['output']+ for frame in frames:+ if frame['type'] in {'response.output_item.added', 'response.output_item.done'}:+ assert terminal[frame['output_index']]['id'] == frame['item']['id']+++async def test_late_stream_observer_receives_defined_output_indices(api, owner):+ entered, release = asyncio.Event(), asyncio.Event()+ async def handle(event):+ from gateway.session_api_turn import publish_api_tool_event+ from gateway.session_results import execution_result+ sid = event.source.chat_id+ generation = owner.sessions[sid].event_stream.execution['execution_generation']+ publish_api_tool_event(owner, sid, generation, 'tool.start', 'call_1', 'read_file', {'path': 'a'})+ publish_api_tool_event(owner, sid, generation, 'tool.complete', 'call_1', 'read_file', {'path': 'a'}, 'read')+ entered.set()+ await release.wait()+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': [+ {'role': 'assistant', 'content': '', 'tool_calls': [+ {'id': 'call_1', 'type': 'function', 'function': {'name': 'read_file', 'arguments': '{"path":"a"}'}}]},+ {'role': 'tool', 'tool_call_id': 'call_1', 'content': 'read'},+ {'role': 'assistant', 'content': 'answer'}]}+ return 'answer'+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ headers, body = {'Idempotency-Key': 'late-stream-observer'}, {'input': 'work', 'stream': True}+ pending = []+ async with TestClient(TestServer(app)) as client:+ try:+ pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))+ await asyncio.wait_for(entered.wait(), 5)+ # Ensure the first stream actually published the tool items before the retry joins.+ async with asyncio.timeout(5):+ while api._current_response_store()._conn.execute('SELECT COUNT(*) FROM response_output_order').fetchone()[0] < 2:+ await asyncio.sleep(.01)+ pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))+ async with asyncio.timeout(5):+ while sum(map(len, owner.api_observers.values())) < 2:+ await asyncio.sleep(.01)+ release.set()+ responses = await asyncio.gather(*pending)+ second = [json.loads(line[6:]) for line in (await responses[1].text()).splitlines()+ if line.startswith('data: ')]+ accumulated = []+ for frame in second:+ if frame['type'] == 'response.created':+ accumulated = frame['response']['output'][:]+ elif frame['type'] == 'response.output_item.added':+ assert frame['output_index'] == len(accumulated), 'late observer was given an output index with missing earlier items'+ accumulated.append(frame['item'])+ elif 'output_index' in frame:+ assert frame['output_index'] < len(accumulated)+ finally:+ release.set()+ await asyncio.gather(*pending, return_exceptions=True)diff --git a/tests/gateway/test_responses_output_order.py b/tests/gateway/test_responses_output_order.pynew file mode 100644index 00000000000..75531083808--- /dev/null+++ b/tests/gateway/test_responses_output_order.py@@ -0,0 +1,70 @@+"""Sequential/parallel tool emission and every observer keep one durable output-index mapping."""+import asyncio+import json++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer++[email protected]('parallel', [False, True])[email protected]('viewers', [1, 2])+async def test_output_indices_survive_completion_order_and_eviction(api, owner, parallel, viewers):+ entered, release = asyncio.Event(), asyncio.Event()+ calls = []+ async def handle(event):+ from gateway.session_api_turn import publish_api_tool_event+ from gateway.session_results import execution_result+ calls.append(event.text)+ entered.set()+ await release.wait()+ sid = event.source.chat_id+ generation = owner.sessions[sid].event_stream.execution['execution_generation']+ order = [('tool.start', 'a'), ('tool.start', 'b'), ('tool.complete', 'b'), ('tool.complete', 'a')] if parallel else [+ ('tool.start', 'a'), ('tool.complete', 'a'), ('tool.start', 'b'), ('tool.complete', 'b')]+ for kind, call in order:+ publish_api_tool_event(owner, sid, generation, kind, call, 'read_file', {'path': call}, 'read ' + call)+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': [+ {'role': 'assistant', 'content': '', 'reasoning': 'available only in terminal receipt', 'tool_calls': [+ {'id': call, 'type': 'function', 'function': {'name': 'read_file', 'arguments': json.dumps({'path': call})}}+ for call in ('a', 'b')]},+ *[{'role': 'tool', 'tool_call_id': call, 'content': 'read ' + call} for call in ('a', 'b')],+ {'role': 'assistant', 'content': 'answer'}]}+ return 'answer'+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ headers, body = {'Idempotency-Key': 'ordered'}, {'input': 'work', 'stream': True}+ pending = []+ async with TestClient(TestServer(app)) as client:+ try:+ pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))+ await asyncio.wait_for(entered.wait(), 5)+ if viewers == 2:+ pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))+ async with asyncio.timeout(5):+ while sum(map(len, owner.api_observers.values())) < 2:+ await asyncio.sleep(.01)+ release.set()+ responses = await asyncio.gather(*pending)+ terminal = []+ for response in responses:+ frames = [json.loads(line[6:]) for line in (await response.text()).splitlines() if line.startswith('data: ')]+ final = frames[-1]['response']+ terminal.append(final)+ for frame in frames:+ if 'output_index' in frame:+ identity = frame.get('item_id') or frame.get('item', {}).get('id')+ if identity:+ assert final['output'][frame['output_index']]['id'] == identity+ assert all(value == terminal[0] for value in terminal)+ store = api._current_response_store()+ store._max_size = 1+ store.put('evict', {'response': {}})+ retry = await client.post('/v1/responses', json={**body, 'stream': False}, headers=headers)+ assert await retry.json() == terminal[0]+ assert calls == ['work']+ finally:+ release.set()+ await asyncio.gather(*pending, return_exceptions=True)diff --git a/tests/gateway/test_responses_request_identity.py b/tests/gateway/test_responses_request_identity.pynew file mode 100644index 00000000000..ec4f498db8e--- /dev/null+++ b/tests/gateway/test_responses_request_identity.py@@ -0,0 +1,47 @@+"""Canonical response retry identity is fixed before concurrent admission."""+import asyncio++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer+++async def test_concurrent_changed_conversation_cannot_replace_response_key(api, owner):+ api._api_key = 'identity-fixture'+ started = asyncio.Event()+ release = asyncio.Event()+ calls = []++ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ started.set()+ if event.text == 'first':+ await release.wait()+ execution_result.get()['result'] = {'final_response': 'first answer', 'messages': []}+ return 'first answer'++ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ headers = {'Idempotency-Key': 'same-request', 'X-Hermes-Session-Key': 'first-room',+ 'Authorization': 'Bearer identity-fixture'}+ async with TestClient(TestServer(app)) as client:+ first = asyncio.create_task(client.post('/v1/responses', json={'input': 'first'}, headers=headers))+ await asyncio.wait_for(started.wait(), 5)+ try:+ changed = await client.post('/v1/responses', json={'input': 'different'},+ headers={**headers, 'X-Hermes-Session-Key': 'second-room'})+ assert changed.status == 409+ finally:+ release.set()+ original = await first+ assert original.status == 200+ saved = await original.json()+ replay = await client.post('/v1/responses', json={'input': 'first'}, headers=headers)+ assert await replay.json() == saved+ changed_target = await client.post('/v1/responses', json={'input': 'first'},+ headers={**headers, 'X-Hermes-Session-Key': 'second-room'})+ assert changed_target.status == 409+ assert calls == ['first']