The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): canonical OpenAI-compat idempotency is scoped to the authenticated key namespace
teknium1fba2c4a6973b
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex db441b04224..7d2272e69df 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -530,8 +530,11 @@ class OpenAICompatRoutesMixin:session_history_delivery=("1" if provided_session_id else ""))if getattr(self.gateway_runner, 'session_authority', None) is not None:key = request.headers.get('Idempotency-Key')- run_kwargs.update(request_id=('chat:' + key) if key else None,- history_from_session=bool(provided_session_id))+ # The durable admission identity carries the authenticated namespace: a rotated+ # API key (or another profile) reusing a client key is a new principal, not a retry.+ run_kwargs.update(+ request_id=f'chat:{self._run_idempotency_scope(request)}:{key}' if key else None,+ history_from_session=bool(provided_session_id))if stream:_stream_q = ThreadSafeAsyncQueue()# tool_call_ids with an emitted "running": a "completed" without one (internal/@@ -818,12 +821,15 @@ class OpenAICompatRoutesMixin:if conversation and previous_response_id:return _error_response("Cannot use both 'conversation' and 'previous_response_id'", 400)durable_key = None- if getattr(self.gateway_runner, 'session_authority', None) is not None and request.headers.get('Idempotency-Key'):+ idempotency_key = request.headers.get('Idempotency-Key')+ canonical = getattr(self.gateway_runner, 'session_authority', None) is not None+ if canonical and idempotency_key:# An exact retry replays the committed response BEFORE the conversation name is# expanded: the first success already advanced the conversation, so re-expanding# would build a different admission payload and refuse the retry as a conflict.from gateway.platforms.api_server import _make_request_fingerprint- durable_key = ('idem:' + self._run_idempotency_scope(request) + ':' + request.headers['Idempotency-Key'],+ idempotency_scope = self._run_idempotency_scope(request)+ durable_key = (f'idem:{idempotency_scope}:{idempotency_key}',_make_request_fingerprint(body, keys=_RESPONSES_FINGERPRINT_KEYS))replay = self._response_store.get(durable_key[0])if replay is not None:@@ -903,15 +909,16 @@ class OpenAICompatRoutesMixin: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 getattr(self.gateway_runner, 'session_authority', None) is not None:- key = request.headers.get('Idempotency-Key')- if key:- import hashlib- # A fresh responses request must recover its target before admission.- if not stored_session_id and not gateway_session_key:- session_id = 'response-' + hashlib.sha256(key.encode()).hexdigest()- run_kwargs['session_id'] = session_id- run_kwargs['request_id'] = 'responses:' + key+ 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}'if stream:_stream_q = ThreadSafeAsyncQueue()diff --git a/tests/gateway/test_api_authority_daemon.py b/tests/gateway/test_api_authority_daemon.pyindex 6d1d4740592..5c1ea30e4b7 100644--- a/tests/gateway/test_api_authority_daemon.py+++ b/tests/gateway/test_api_authority_daemon.py@@ -63,7 +63,7 @@ def test_ordinary_daemon_api_ws_fifo_retry(tmp_path):return textpending = asyncio.create_task(follow())async with asyncio.timeout(10):- while not any(row['request_id'] == 'chat:daemon-retry' and row['status'] == 'queued' for row in rows()):+ while not any(row['request_id'].endswith(':daemon-retry') and row['status'] == 'queued' for row in rows()):await asyncio.sleep(.02)peer.release.set()completed = json.loads(await pending)diff --git a/tests/gateway/test_api_crash_recovery.py b/tests/gateway/test_api_crash_recovery.pyindex bde618ef4ca..5a518300ba9 100644--- a/tests/gateway/test_api_crash_recovery.py+++ b/tests/gateway/test_api_crash_recovery.py@@ -38,8 +38,11 @@ def test_api_crash_queue_and_identified_result_retry(tmp_path):pids, epochs = [], []def rows():+ # Canonical OpenAI-compat identities are ``chat:<auth namespace>:<Idempotency-Key>``;+ # index them by the client key so the assertions stay about admission status.with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:- return dict(db.execute('SELECT request_id,status FROM session_admissions'))+ return {('chat:' + rid.rsplit(':', 1)[1] if rid.startswith('chat:') else rid): status+ for rid, status in db.execute('SELECT request_id,status FROM session_admissions')}async def run(client, name, text, session):async with client.post(url + '/runs', json={'input': text, 'session_id': session},diff --git a/tests/gateway/test_api_idempotency_namespace.py b/tests/gateway/test_api_idempotency_namespace.pynew file mode 100644index 00000000000..895734d1a43--- /dev/null+++ b/tests/gateway/test_api_idempotency_namespace.py@@ -0,0 +1,45 @@+"""Canonical OpenAI-compat idempotency is scoped to the authenticated key namespace."""+import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer++from tests.gateway.test_api_cutover_contract import api # noqa: F401+from tests.gateway.test_api_source_binding import owner # noqa: F401++OLD, NEW = 'probe-old-key-long-enough', 'probe-new-key-long-enough'+++def _execute(owner, calls):+ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ text = f'execution-{len(calls)}'+ execution_result.get()['result'] = {'final_response': text, 'messages': []}+ return text+ owner.runner._handle_message = handle+++async def _rotated(api, client, path, body, key):+ outputs = []+ for api_key in (OLD, NEW):+ api._api_key = api_key+ resp = await client.post(path, json=body, headers={'Authorization': 'Bearer ' + api_key, 'Idempotency-Key': key})+ assert resp.status == 200, await resp.text()+ outputs.append(await resp.json())+ return outputs+++async def test_rotated_api_key_is_a_different_principal_for_chat_and_responses(api, owner):+ calls = []+ _execute(owner, calls)+ app = web.Application()+ app.router.add_post('/v1/chat/completions', api._handle_chat_completions)+ app.router.add_post('/v1/responses', api._handle_responses)+ async with TestClient(TestServer(app)) as client:+ chat = await _rotated(api, client, '/v1/chat/completions',+ {'messages': [{'role': 'user', 'content': 'same request'}]}, 'rotate-chat')+ assert [c['choices'][0]['message']['content'] for c in chat] == ['execution-1', 'execution-2']+ responses = await _rotated(api, client, '/v1/responses', {'input': 'fresh rotation'}, 'rotate-responses')+ assert [r['output'][-1]['content'][0]['text'] for r in responses] == ['execution-3', 'execution-4']+ assert len(calls) == 4