The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): bound accepted Responses idempotency identity with the body store
Teknium9e2561f7a64a
diff --git a/gateway/platforms/api_server_response_store.py b/gateway/platforms/api_server_response_store.pyindex fe2310fff9b..d1ce1d56013 100644--- a/gateway/platforms/api_server_response_store.py+++ b/gateway/platforms/api_server_response_store.py@@ -12,14 +12,34 @@ from typing import Any, Dict, Optionallogger = logging.getLogger("gateway.platforms.api_server")MAX_STORED_RESPONSES = 100+# Settled Idempotency-Key identities retained per response-body slot (see ResponseStore).+IDENTITY_RETENTION_FACTOR = 10+# The stored terminal envelope of a body row; a corrupt body reads as absent, never raises.+_RECORD = "json_extract(CASE WHEN json_valid(data) THEN data END, '$.response"class ResponseStore:"""SQLite-backed LRU store for Responses API state (full conversation history per response- for ``previous_response_id`` chaining). Persists across restarts; in-memory fallback."""-- def __init__(self, max_size: int = MAX_STORED_RESPONSES, db_path: str = None):+ for ``previous_response_id`` chaining). Persists across restarts; in-memory fallback.++ Idempotency-Key identity (``response_keys`` + ``response_admissions`` ++ ``response_output_order``) deliberately outlives body LRU eviction so an exact retry still+ replays, conflicts or reconstructs its terminal result. Its own lifecycle is a count bound:+ at most ``_identity_bound()`` *settled* identities (a terminal idempotency record was+ stored), ``IDENTITY_RETENTION_FACTOR * max_size`` unless ``max_identities`` is given. Past+ the bound the oldest-settled are dropped from all three tables plus their ``idem:`` replay+ record, in the same transaction as body eviction. An unsettled identity (admission pending,+ running, or outcome unknown) neither counts nor is ever dropped; it joins the bound once an+ observer settles it. Public ``delete`` of a settled response drops its identity the same way.++ An expired or deleted key is not a new request: the canonical admission still carries the+ request id, so a reuse is refused with ``admission_conflict`` and never re-executes.+ """++ def __init__(self, max_size: int = MAX_STORED_RESPONSES, db_path: str = None,+ max_identities: Optional[int] = None):self._max_size = max_size+ self._max_identities = max_identitiesif db_path is None:db_path = ":memory:"with suppress(Exception):@@ -51,6 +71,12 @@ class ResponseStore:'PRIMARY KEY(request_key,item_id), UNIQUE(request_key,output_index))')from hermes_cli.sqlite_util import add_column_if_missingadd_column_if_missing(self._conn, 'response_keys', 'model_json', 'model_json TEXT')+ add_column_if_missing(self._conn, 'response_keys', 'settled_at', 'settled_at REAL')+ add_column_if_missing(self._conn, 'response_keys', 'response_id', 'response_id TEXT')+ self._conn.execute('CREATE INDEX IF NOT EXISTS response_keys_settled ON response_keys(settled_at)')+ self._conn.execute('CREATE INDEX IF NOT EXISTS response_keys_response ON response_keys(response_id)')+ # Rows written before settlement was tracked: settled iff their replay record survives.+ self._mark_settled('1', ())self._conn.commit()# Conversation history lives here: owner-only perms, once at init (not per commit).self._tighten_file_permissions()@@ -90,8 +116,32 @@ class ResponseStore:self._conn.execute(insert + " INTO responses (response_id, data, accessed_at) VALUES (?, ?, ?)",(response_id, json.dumps(data, default=str), time.time()))+ if response_id.startswith('idem:'):+ self._mark_settled('request_key = ?', (response_id,))self._evict_and_commit()+ def _mark_settled(self, selector: str, params: tuple) -> None:+ """A stored terminal replay record settles its identity; only then may it age out."""+ self._conn.execute(+ f"UPDATE response_keys SET settled_at=?, response_id=(SELECT {_RECORD}.id') FROM responses "+ "WHERE responses.response_id=request_key) WHERE settled_at IS NULL AND "+ f"{selector} AND EXISTS (SELECT 1 FROM responses WHERE responses.response_id=request_key "+ f"AND {_RECORD}') IS NOT NULL)", (time.time(), *params))++ def _identity_bound(self) -> int:+ return self._max_identities or IDENTITY_RETENTION_FACTOR * self._max_size++ def _forget_identities(self, selector: str, params: tuple) -> int:+ """Drop the selected settled identities from every compact table and their replay record.++ Runs inside the caller's open transaction; ``response_keys`` goes last so the selector+ sees the same rows for each table."""+ keys = f'SELECT request_key FROM response_keys WHERE settled_at IS NOT NULL AND {selector}'+ for table, column in (('response_output_order', 'request_key'),+ ('response_admissions', 'request_key'), ('responses', 'response_id')):+ self._conn.execute(f'DELETE FROM {table} WHERE {column} IN ({keys})', params)+ return self._conn.execute(f'DELETE FROM response_keys WHERE request_key IN ({keys})', params).rowcount+def _evict_and_commit(self) -> None:count = self._conn.execute("SELECT COUNT(*) FROM responses").fetchone()[0]if count > self._max_size:@@ -103,6 +153,13 @@ class ResponseStore:# Conversation mappings pointing at evicted responses go too.self._conn.execute(f"DELETE FROM conversations WHERE response_id IN ({placeholders})", evict_ids)self._conn.execute(f"DELETE FROM responses WHERE response_id IN ({placeholders})", evict_ids)+ excess = self._conn.execute(+ 'SELECT COUNT(*) FROM response_keys WHERE settled_at IS NOT NULL').fetchone()[0] - self._identity_bound()+ if excess > 0:+ self._forget_identities('1 ORDER BY settled_at, rowid LIMIT ?', (excess,))+ # A late observer of an already-retired key may have re-allocated derivative rows.+ for table in ('response_output_order', 'response_admissions'):+ self._conn.execute(f'DELETE FROM {table} WHERE request_key NOT IN (SELECT request_key FROM response_keys)')self._conn.commit()def bind_request_key(self, key: str, fingerprint: str, *, model=None) -> bool:@@ -166,11 +223,13 @@ class ResponseStore:'(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."""+ """Remove a response, conversation mappings to it and its settled Idempotency-Key+ identity (replay record included). True if anything was found and deleted."""self._conn.execute("DELETE FROM conversations WHERE response_id = ?", (response_id,))cursor = self._conn.execute("DELETE FROM responses WHERE response_id = ?", (response_id,))+ forgotten = self._forget_identities('response_id = ?', (response_id,))self._conn.commit()- return cursor.rowcount > 0+ return cursor.rowcount > 0 or forgotten > 0def get_conversation(self, name: str) -> Optional[str]:"""Get the latest response_id for a conversation name."""diff --git a/tests/gateway/test_responses_identity_retention.py b/tests/gateway/test_responses_identity_retention.pynew file mode 100644index 00000000000..8a5e4d23ec5--- /dev/null+++ b/tests/gateway/test_responses_identity_retention.py@@ -0,0 +1,87 @@+"""Accepted Idempotency-Key identity has a bounded lifecycle beside the response-body LRU."""+import asyncio++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer++COMPACT = ('response_keys', 'response_admissions', 'response_output_order')+++def _compact_rows(store):+ return [store._conn.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0] for table in COMPACT]+++def _app(api, owner, calls, gate=None):+ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ if gate is not None and event.text == 'slow':+ gate[0].set()+ await gate[1].wait()+ execution_result.get()['result'] = {'final_response': 'answer ' + event.text, 'messages': []}+ return 'answer ' + event.text+ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ app.router.add_delete('/v1/responses/{response_id}', api._handle_delete_response)+ return app+++async def test_unique_keys_and_deletion_keep_compact_identity_bounded(api, owner):+ calls = []+ store = api._current_response_store()+ store._max_size, store._max_identities = 1, 3+ async with TestClient(TestServer(_app(api, owner, calls))) as client:+ originals = []+ for index in range(6):+ response = await client.post('/v1/responses', json={'input': f'turn {index}'},+ headers={'Idempotency-Key': f'unique-{index}'})+ assert response.status == 200+ originals.append(await response.json())+ # Steady unique traffic: one body, and the compact identity stays at its documented bound.+ assert len(store) == 1+ assert _compact_rows(store) == [3, 3, 3]+ # Inside the window an exact retry still replays after its body was evicted.+ retry = await client.post('/v1/responses', json={'input': 'turn 5'},+ headers={'Idempotency-Key': 'unique-5'})+ assert retry.status == 200 and await retry.json() == originals[5]+ # An expired key is a clear conflict, never a second execution.+ expired = await client.post('/v1/responses', json={'input': 'turn 0'},+ headers={'Idempotency-Key': 'unique-0'})+ assert expired.status == 409+ assert (await expired.json())['error']['code'] == 'admission_conflict'+ # Public deletion retires the identity in every compact table.+ for value in originals[3:]:+ assert (await client.delete('/v1/responses/' + value['id'])).status == 200+ assert _compact_rows(store) == [0, 0, 0]+ deleted = await client.post('/v1/responses', json={'input': 'turn 5'},+ headers={'Idempotency-Key': 'unique-5'})+ assert deleted.status == 409+ assert calls == [f'turn {index}' for index in range(6)]+++async def test_pending_identity_survives_identity_pressure(api, owner):+ calls, gate = [], (asyncio.Event(), asyncio.Event())+ store = api._current_response_store()+ store._max_size, store._max_identities = 1, 1+ slow_headers = {'Idempotency-Key': 'pending-slow'}+ async with TestClient(TestServer(_app(api, owner, calls, gate))) as client:+ slow = asyncio.create_task(client.post('/v1/responses', json={'input': 'slow'}, headers=slow_headers))+ try:+ await asyncio.wait_for(gate[0].wait(), 10)+ for index in range(3):+ response = await client.post('/v1/responses', json={'input': f'fast {index}'},+ headers={'Idempotency-Key': f'fast-{index}'})+ assert response.status == 200+ # Settled identities aged out around it; the running admission's identity did not.+ keys = sorted(row[0].rsplit(':', 1)[1] for row in store._conn.execute('SELECT request_key FROM response_keys'))+ assert keys == ['fast-2', 'pending-slow']+ finally:+ gate[1].set()+ original = await (await slow).json()+ retry = await client.post('/v1/responses', json={'input': 'slow'}, headers=slow_headers)+ assert retry.status == 200 and await retry.json() == original+ assert calls == ['slow', 'fast 0', 'fast 1', 'fast 2']