The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): give a new header-less chat a new session after a delete
unsupportedpastels24f07b3f1336
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex 9fe4c626a8e..bb7bd81de5e 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -882,6 +882,9 @@ class OpenAICompatRoutesMixin:first_user = next((cm.get("content", "") for cm in conversation_messages if cm.get("role") == "user"), "")session_id = _derive_chat_session_id(system_prompt, first_user, _api_request_profile.get())+ session_id, lookup_error = await self._implicit_chat_session(request, session_id)+ if lookup_error is not None:+ return lookup_errorcompletion_id = f"chatcmpl-{uuid.uuid4().hex[:29]}"model_name = body.get("model", self._model_name)created = int(time.time())@@ -901,13 +904,7 @@ class OpenAICompatRoutesMixin:# id from a header-less client is NOT: delegate_task keeps its forced-sync fallback# there — the wake would hard-fail or land in history that client never reloads.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')- # 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), run_owner_scope=self._run_idempotency_scope(request))+ run_kwargs.update(self._authority_chat_kwargs(request, provided_session_id))# This is presentation only. The ordinary API-key/session authorization# above still applies; it grants no internal ingress or control authority.if provided_session_id and body.get("hermes_notification_category") == "diagnostic":@@ -1010,6 +1007,45 @@ class OpenAICompatRoutesMixin:response_headers["X-Hermes-Error"] = _redact_api_error_text(err_msg, limit=200)return web.json_response(response_data, headers=response_headers)+ def _chat_request_id(self, request: web.Request) -> Optional[str]:+ """Durable admission identity of a Chat Completions Idempotency-Key. It carries the+ authenticated namespace: a rotated API key (or another profile) reusing a client key is a+ new principal, not a retry."""+ key = request.headers.get('Idempotency-Key')+ return f'chat:{self._run_idempotency_scope(request)}:{key}' if key else None++ def _authority_chat_kwargs(self, request: web.Request, provided_session_id) -> dict:+ """Admission identity of a Chat Completions turn under session authority; none before it."""+ if getattr(self.gateway_runner, 'session_authority', None) is None:+ return {}+ return dict(request_id=self._chat_request_id(request), history_from_session=bool(provided_session_id),+ run_owner_scope=self._run_idempotency_scope(request))++ async def _implicit_chat_session(self, request: web.Request, session_id: str) -> tuple:+ """A derived (header-less) id whose session was deleted names a new conversation with the+ same opening: the owning profile's store picks its generation (``implicit_api_session``).+ -> ``(session_id, None)`` or ``(session_id, 500 response)``: a store that cannot answer+ gets the same OpenAI error envelope as ``_run_idempotent``, before either response starts."""+ if getattr(self.gateway_runner, 'session_authority', None) is None:+ return session_id, None+ from gateway.session_api import implicit_api_session+ from gateway.session_authorities import active_authority+ authority = active_authority(self.gateway_runner)+ if authority is None:+ return session_id, None # admission refuses the unserved profile with its own verdict+ from hermes_state_runtime import RuntimeStoreError+ try:+ return await asyncio.to_thread(implicit_api_session, authority.db, session_id,+ self._chat_request_id(request)), None+ except RuntimeStoreError as exc:+ from gateway.platforms.api_server import _openai_error+ from gateway.platforms.api_server_authority_runs import store_error_response+ return session_id, store_error_response(_openai_error, exc)+ except Exception as e:+ from gateway.platforms.api_server import _error_response+ logger.error("Error resolving the chat completions session: %s", e, exc_info=True)+ return session_id, _error_response(f"Internal server error: {e}", 500, err_type="server_error")+async def _run_idempotent(self, request: web.Request, body: dict[str, Any], compute, *,log_label: str, fingerprint_keys: list[str], route: str) -> tuple:diff --git a/gateway/session_api.py b/gateway/session_api.pyindex b229674d20e..5758357c62b 100644--- a/gateway/session_api.py+++ b/gateway/session_api.py@@ -25,6 +25,27 @@ def declared_api_session(db, key):return legacy['id'] if legacy else None+def implicit_api_session(db, session_id, request_id=None):+ """The session a header-less Chat Completions turn lands on. Its id is derived from the+ conversation's opening, and a deleted id stays retired for good, so a NEW conversation that+ opens like a deleted one moves to the next generation of that opening, the way a deleted Bot+ Chat is replaced: the first ``api-<digest(id, n)>`` that is not retired. Read from durable rows+ only, so every later turn of that conversation (same opening) lands on the same session. An+ exact retry stays on the generation holding its request id's terminal identity; explicit ids+ never come here."""+ from hermes_state_mutation_retirement import RETIRED_PREFIX+ from hermes_state_terminal import identity_key+ candidate, generation = session_id, 0+ with db._read_ctx() as conn:+ while conn.execute('SELECT 1 FROM state_meta WHERE key=?', (RETIRED_PREFIX + candidate,)).fetchone():+ if request_id and conn.execute('SELECT 1 FROM state_meta WHERE key=?',+ (identity_key('api', candidate, request_id),)).fetchone():+ break+ generation += 1+ candidate = 'api-' + hashlib.sha256(f'{session_id}\0{generation}'.encode()).hexdigest()[:16]+ return candidate++def _served_profile(authority):"""Name of the profile *authority* serves; None for the launch profile (and for bare runnerswithout a registry), which is what ``SessionSource.profile`` means on the wire."""diff --git a/tests/gateway/test_api_implicit_session_after_delete.py b/tests/gateway/test_api_implicit_session_after_delete.pynew file mode 100644index 00000000000..2e1de8f0be0--- /dev/null+++ b/tests/gateway/test_api_implicit_session_after_delete.py@@ -0,0 +1,158 @@+"""A header-less Chat Completions conversation that opens like a deleted one is a new conversation.++The header-less session id is derived from the system prompt + first user message, and a deleted+session's id stays retired for good. A new conversation with the same opening moves to the next+generation of that opening instead of being refused forever; its later turns keep landing there.+An explicit X-Hermes-Session-Id and a spent Idempotency-Key are never moved.+"""+import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer+++_API_KEY = 'implicit-session-after-delete-key'+_OPENING = [{'role': 'system', 'content': 'be brief'}, {'role': 'user', 'content': 'hi'}]+++def _execute(owner, calls):+ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ text = f'answer {len(calls)}'+ execution_result.get()['result'] = {'final_response': text, 'messages': []}+ return text+ owner.runner._handle_message = handle+++def _app(api):+ app = web.Application()+ app.router.add_post('/v1/chat/completions', api._handle_chat_completions)+ app.router.add_delete('/api/sessions/{session_id}', api._handle_delete_session)+ return app+++async def _post(client, messages, *, session_id=None, key=None):+ headers = {'Authorization': 'Bearer ' + _API_KEY}+ if session_id:+ headers['X-Hermes-Session-Id'] = session_id+ if key:+ headers['Idempotency-Key'] = key+ response = await client.post('/v1/chat/completions', json={'model': 'hermes-agent', 'messages': messages},+ headers=headers)+ return response.status, await response.json(), response.headers.get('X-Hermes-Session-Id')+++async def _delete(client, session_id):+ deleted = await client.delete('/api/sessions/' + session_id, headers={'Authorization': 'Bearer ' + _API_KEY})+ assert deleted.status == 200, await deleted.text()+ assert (await deleted.json())['deleted'] is True+++def _prune_past_horizon(owner):+ from hermes_state_mutation_retirement import prune_retired_tombstones+ owner.db._execute_write(lambda conn: prune_retired_tombstones(conn, older_than=0))+++def _content(payload):+ return payload['choices'][0]['message']['content']+++def served(api, owner):+ calls = []+ api._api_key = _API_KEY+ _execute(owner, calls)+ return calls++[email protected]('past_horizon', [False, True], ids=['within-horizon', 'past-horizon'])+async def test_a_new_conversation_with_a_deleted_opening_gets_a_new_session(api, owner, served, past_horizon):+ async with TestClient(TestServer(_app(api))) as client:+ status, first, deleted_sid = await _post(client, _OPENING)+ assert status == 200, first+ await _delete(client, deleted_sid)+ if past_horizon:+ _prune_past_horizon(owner)++ status, opened, new_sid = await _post(client, _OPENING)+ assert status == 200, opened+ assert new_sid and new_sid != deleted_sid+ follow_up = [*_OPENING, {'role': 'assistant', 'content': _content(opened)}, {'role': 'user', 'content': 'next'}]+ status, second, same_sid = await _post(client, follow_up)+ assert status == 200, second+ assert same_sid == new_sid, 'the second turn of the new conversation left its session'+ assert served == ['hi', 'hi', 'next']+ assert owner.db.get_session(deleted_sid) is None, 'the deleted session was recreated'+ assert owner.db.get_session(new_sid) is not None++ # Deleting the replacement moves the next new conversation on again, never back.+ await _delete(client, new_sid)+ status, third, third_sid = await _post(client, _OPENING)+ assert status == 200, third+ assert third_sid not in (deleted_sid, new_sid)+++async def test_an_explicit_session_id_of_a_deleted_session_is_still_refused(api, owner, served):+ async with TestClient(TestServer(_app(api))) as client:+ status, first, deleted_sid = await _post(client, _OPENING)+ assert status == 200, first+ await _delete(client, deleted_sid)+ _prune_past_horizon(owner)+ status, refused, _sid = await _post(client, _OPENING, session_id=deleted_sid)+ assert status != 200 and refused['error']['code'] == 'not_found', refused+ assert served == ['hi']+ assert owner.db.get_session(deleted_sid) is None+++async def test_an_idempotency_key_retry_keeps_its_deleted_session(api, owner, served):+ """An exact retry replays its original answer on the deleted id; a changed payload under the+ same key conflicts. Neither is moved to a new generation or run again."""+ async with TestClient(TestServer(_app(api))) as client:+ status, first, deleted_sid = await _post(client, _OPENING, key='once')+ assert status == 200, first+ await _delete(client, deleted_sid)+ status, replay, replay_sid = await _post(client, _OPENING, key='once')+ assert status == 200 and _content(replay) == _content(first), replay+ assert replay_sid == deleted_sid+ changed_body = [*_OPENING, {'role': 'assistant', 'content': 'x'}, {'role': 'user', 'content': 'changed'}]+ status, changed, _sid = await _post(client, changed_body, key='once')+ assert status == 409 and changed['error']['code'] == 'admission_conflict', changed+ assert served == ['hi']+ assert owner.db.get_session(deleted_sid) is None++[email protected]('stream', [False, True], ids=['json', 'stream'])+async def test_a_store_that_cannot_answer_the_lookup_returns_an_openai_error(api, owner, served, monkeypatch, stream):+ import sqlite3++ def unreadable(*_a, **_k):+ raise sqlite3.OperationalError('disk I/O error')++ monkeypatch.setattr('gateway.session_api.implicit_api_session', unreadable)+ async with TestClient(TestServer(_app(api))) as client:+ response = await client.post('/v1/chat/completions',+ json={'model': 'hermes-agent', 'messages': _OPENING, 'stream': stream},+ headers={'Authorization': 'Bearer ' + _API_KEY})+ assert response.status == 500+ assert response.content_type == 'application/json', await response.text()+ payload = await response.json()+ assert payload['error']['type'] == 'server_error', payload+ assert served == []+++async def test_a_key_spent_on_another_session_stays_spent_on_a_new_generation(api, owner, served):+ async with TestClient(TestServer(_app(api))) as client:+ status, first, deleted_sid = await _post(client, _OPENING)+ assert status == 200, first+ status, other, _sid = await _post(client, [{'role': 'user', 'content': 'elsewhere'}],+ session_id='other-session', key='spent')+ assert status == 200, other+ await _delete(client, deleted_sid)+ status, refused, _sid = await _post(client, _OPENING, key='spent')+ assert status == 409 and refused['error']['code'] == 'admission_conflict', refused+ assert served == ['hi', 'elsewhere']