Skip to content

The agent that grows with you

test(api): consolidate Responses identity regressions and drop dead claim()

Tekniumed728cf07a0a
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.py
index 5a56a09e2db..9917cff78ad 100644
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@ -1235,7 +1235,6 @@ class OpenAICompatRoutesMixin:
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:
diff --git a/gateway/platforms/api_server_response_store.py b/gateway/platforms/api_server_response_store.py
index a3114a44f83..fe2310fff9b 100644
--- a/gateway/platforms/api_server_response_store.py
+++ b/gateway/platforms/api_server_response_store.py
@@ -92,22 +92,6 @@ class ResponseStore:
(response_id, json.dumps(data, default=str), time.time()))
self._evict_and_commit()
- def claim(self, response_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
- """First writer keeps an idempotency record: insert when absent, settle a pending one (no
- ``response`` yet) with the same ``fingerprint``, never replace a settled or foreign one.
- Returns the record now stored, so the caller compares its fingerprint."""
- encoded = json.dumps(data, default=str)
- self._conn.execute(
- "INSERT OR IGNORE INTO responses (response_id, data, accessed_at) VALUES (?, ?, ?)",
- (response_id, encoded, time.time()))
- self._conn.execute(
- "UPDATE responses SET data = ? WHERE response_id = ? AND json_extract(data, '$.response') IS NULL"
- " AND json_extract(data, '$.fingerprint') = json_extract(?, '$.fingerprint')",
- (encoded, response_id, encoded))
- stored = self._conn.execute("SELECT data FROM responses WHERE response_id = ?", (response_id,)).fetchone()
- self._evict_and_commit()
- return json.loads(stored[0])
-
def _evict_and_commit(self) -> None:
count = self._conn.execute("SELECT COUNT(*) FROM responses").fetchone()[0]
if count > self._max_size:
diff --git a/tests/gateway/test_adversarial_responses_eviction.py b/tests/gateway/test_adversarial_responses_eviction.py
index 891e2cdf0d2..ac8df6dc576 100644
--- a/tests/gateway/test_adversarial_responses_eviction.py
+++ b/tests/gateway/test_adversarial_responses_eviction.py
@@ -1,4 +1,4 @@
-"""Independent review: durable exact retries keep output after response-body LRU eviction."""
+"""Durable exact Responses retries keep their output after response-body LRU eviction."""
import json
import pytest
@@ -7,9 +7,7 @@ from aiohttp.test_utils import TestClient, TestServer
@pytest.mark.asyncio
[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):
+async def test_terminal_retry_after_cache_eviction_preserves_result(api, owner):
calls = []
api._model_name = 'accepted-model'
async def handle(event):
@@ -29,30 +27,23 @@ async def test_terminal_retry_after_cache_eviction_preserves_result(api, owner,
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'}
+ body, headers = {'input': 'work', 'stream': True}, {'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()
+ 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
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)
+ retry = await client.post('/v1/responses', json={**body, 'stream': False}, 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()
+ repeated = await retry.json()
assert calls == ['work']
assert repeated == original
@@ -82,8 +73,7 @@ async def test_failed_terminal_retry_after_eviction_keeps_envelope(api, owner):
@pytest.mark.asyncio
[email protected]('stream', [False, True])
-async def test_retired_terminal_retry_after_eviction_keeps_compact_outcome(api, owner, stream):
+async def test_retired_terminal_retry_after_eviction_keeps_compact_outcome(api, owner):
calls = []
async def handle(event):
from gateway.session_results import execution_result
@@ -104,14 +94,11 @@ async def test_retired_terminal_retry_after_eviction_keeps_compact_outcome(api,
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)
+ repeated = await client.post('/v1/responses', json={'input': 'work', 'stream': True}, 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()
+ 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)
assert calls == ['work']
assert value['id'] == original['id'] and value['status'] == original['status']
assert 'deleted-sentinel' not in str(value)
@@ -119,8 +106,7 @@ async def test_retired_terminal_retry_after_eviction_keeps_compact_outcome(api,
@pytest.mark.asyncio
[email protected]('stream', [False, True])
-async def test_terminal_replay_does_not_roll_named_conversation_back(api, owner, stream):
+async def test_terminal_replay_does_not_roll_named_conversation_back(api, owner):
calls = []
async def handle(event):
from gateway.session_results import execution_result
@@ -146,7 +132,7 @@ async def test_terminal_replay_does_not_roll_named_conversation_back(api, owner,
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)
+ repeated = await client.post('/v1/responses', json=body, headers=first_headers)
assert repeated.status == 200
await repeated.read()
assert store.get_conversation('shared') == latest['id']
diff --git a/tests/gateway/test_adversarial_responses_pending.py b/tests/gateway/test_adversarial_responses_pending.py
index 954530697a3..38facfae1a0 100644
--- a/tests/gateway/test_adversarial_responses_pending.py
+++ b/tests/gateway/test_adversarial_responses_pending.py
@@ -1,5 +1,6 @@
-"""An in-flight Responses identity cannot acquire a second target via a moving conversation."""
+"""A Responses retry stays pinned to its first admission's target, including after pointer loss."""
import asyncio
+import json
import pytest
from aiohttp import web
@@ -123,9 +124,7 @@ async def test_validation_refusal_does_not_reserve_retry_key(api, owner):
@pytest.mark.asyncio
[email protected]('stream', [False, True])
-async def test_concurrent_exact_responses_share_terminal_envelope(api, owner, stream):
- import json
+async def test_concurrent_exact_responses_share_terminal_envelope(api, owner):
started, release = asyncio.Event(), asyncio.Event()
async def handle(event):
from gateway.session_results import execution_result
@@ -140,7 +139,7 @@ async def test_concurrent_exact_responses_share_terminal_envelope(api, owner, st
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'}
+ body, headers = {'input': 'work', 'stream': True}, {'Idempotency-Key': 'concurrent-exact'}
pending = []
async with TestClient(TestServer(app)) as client:
try:
@@ -154,13 +153,10 @@ async def test_concurrent_exact_responses_share_terminal_envelope(api, owner, st
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]
+ 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']
assert values[0] == values[1]
retry = await client.post('/v1/responses', json={**body, 'stream': False}, headers=headers)
assert await retry.json() == values[0]
@@ -168,3 +164,46 @@ async def test_concurrent_exact_responses_share_terminal_envelope(api, owner, st
finally:
release.set()
await asyncio.gather(*pending, return_exceptions=True)
+
+
+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_pointer_retirement.py b/tests/gateway/test_adversarial_responses_pointer_retirement.py
deleted file mode 100644
index 9b75015e7dd..00000000000
--- a/tests/gateway/test_adversarial_responses_pointer_retirement.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""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.py
deleted file mode 100644
index 1fe89bf9ade..00000000000
--- a/tests/gateway/test_adversarial_responses_stream_backpressure.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""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.py
deleted file mode 100644
index 3e3dd93ab71..00000000000
--- a/tests/gateway/test_adversarial_responses_stream_projection.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""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_api_responses_stream_retry.py b/tests/gateway/test_api_responses_stream_retry.py
index bdd5760b6a2..c174620ad78 100644
--- a/tests/gateway/test_api_responses_stream_retry.py
+++ b/tests/gateway/test_api_responses_stream_retry.py
@@ -118,11 +118,10 @@ def test_idempotency_record_keeps_its_first_writer(tmp_path):
from gateway.platforms.api_server_response_store import ResponseStore
store = ResponseStore(db_path=str(tmp_path / 'responses.db'))
try:
- assert store.claim('idem:k', {'fingerprint': 'A'}) == {'fingerprint': 'A'}
- assert store.claim('idem:k', {'fingerprint': 'B', 'response': {'id': 'b'}}) == {'fingerprint': 'A'}
settled = {'fingerprint': 'A', 'response': {'id': 'a'}}
- assert store.claim('idem:k', settled) == settled
- assert store.claim('idem:k', {'fingerprint': 'A', 'response': {'id': 'late'}}) == settled
+ store.put('idem:k', settled)
+ store.put('idem:k', {'fingerprint': 'B', 'response': {'id': 'b'}})
+ store.put('idem:k', {'fingerprint': 'A', 'response': {'id': 'late'}})
assert store.get('idem:k') == settled
finally:
store.close()
diff --git a/tests/gateway/test_responses_output_order.py b/tests/gateway/test_responses_output_order.py
index 75531083808..625708ab19b 100644
--- a/tests/gateway/test_responses_output_order.py
+++ b/tests/gateway/test_responses_output_order.py
@@ -1,4 +1,4 @@
-"""Sequential/parallel tool emission and every observer keep one durable output-index mapping."""
+"""Responses output ids and indexes stay identical across observers, late joiners and eviction."""
import asyncio
import json
@@ -8,9 +8,7 @@ from aiohttp.test_utils import TestClient, TestServer
@pytest.mark.asyncio
[email protected]('parallel', [False, True])
[email protected]('viewers', [1, 2])
-async def test_output_indices_survive_completion_order_and_eviction(api, owner, parallel, viewers):
+async def test_output_indices_survive_completion_order_and_eviction(api, owner):
entered, release = asyncio.Event(), asyncio.Event()
calls = []
async def handle(event):
@@ -21,8 +19,8 @@ async def test_output_indices_survive_completion_order_and_eviction(api, owner,
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')]
+ # Parallel tools completing out of start order.
+ order = [('tool.start', 'a'), ('tool.start', 'b'), ('tool.complete', 'b'), ('tool.complete', 'a')]
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': [
@@ -41,11 +39,10 @@ async def test_output_indices_survive_completion_order_and_eviction(api, owner,
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)
+ 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 = []
@@ -68,3 +65,56 @@ async def test_output_indices_survive_completion_order_and_eviction(api, owner,
finally:
release.set()
await asyncio.gather(*pending, return_exceptions=True)
+
+
+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)