litellm/tests/integration/providers/test_responses_lifecycle_wire.py
simonp9 250af8f027
fix(spend)!: save streamed /v1/responses spend rows under the encrypted resp_ id the client received (#49493)
* fix(responses): log the encrypted response id on streamed /v1/responses spend rows

With response id security on, the stream hook encrypts the resp_ id on every
frame, but logging had already received the SDK's own copy of the terminal
response, so the spend row, the standard logging payload and callbacks got the
managed id (or the chatcmpl id on a bridged stream) the client never saw. The
hook now records the exact id it advertises on the request's logging object,
and the logging layer stamps that id on the logged streamed response

* fix(responses): return the id the client sent on GET and cancel, and keep read rows off the create row's id

Every GET /v1/responses/{id} re-encrypted the response id, so a client that continued a bridged conversation with the
id a GET returned referenced a ciphertext no spend row was filed under. The follow-up lost turn 1 and opened a new
session. GET and cancel now answer with the exact id the client sent when it is an id this proxy issued and it decodes
to the response the provider returned. A create with previous_response_id still gets a fresh id for its own response,
and a raw provider id still gets a managed id

Because a read now carries the create's id, a GET or cancel spend row is filed as <id>_retrieve_<call id> or
<id>_cancel_<call id>. That keeps one row per read, as before, and a read row can never take the create row's
request_id, so the create row survives whichever row is written first and a follow-up replays turn 1 once. The
background settlement row keeps <id>_background_cost, and the cost poll's own status checks keep the response id

* fix(responses): log a fresh id for each read and cancel, echo the held id only to its owner

A GET or cancel of a stored response now logs a new encrypted id of its own,
so callbacks and spend rows never reuse the create's id, while the owner of
the id still gets back the exact id they sent. An admin reading someone
else's response gets an id bound to the admin, as before. The spend row id
suffix for reads and cancels is gone, so with response id security off the
rows and session history match the default branch. A streamed GET follows
the same rules.

* fix(responses): echo the sent id to every reader that passes the response access check

A GET, streamed GET or cancel of a response now answers with the id the caller sent whenever the caller passed
the access check, not only when the caller is the user or team the id was issued to. An admin, the master key
or a teammate who read someone else's streamed response got a fresh id back, and the session lookup could not
reach the first turn from it, so a bridged follow-up through that id lost the conversation history

Every read and cancel still logs a fresh id bound to the reader, never the create's id

* fix(responses): keep a read or cancel row in session history only when it brings new output

A GET, streamed GET or cancel sent with a session header joins the
create's session, and its stored response repeats the create's output.
The replay then sent the same assistant turn once per read.

Session history now keeps an aget_responses or acancel_responses row
only when its stored Responses output has an item id that no earlier
kept row carried. A polled background response keeps the first poll
that returns the finished output, since its queued create row has none,
and later polls of the same output are dropped. Every other row keeps
today's rule

* fix(responses): replay each history item once, echo the sent id on delete, keep background cost files apart

A create row now owns its output items in session history, and a read or cancel row adds only items no
create and no earlier read carried, in one linear pass, so a background response polled while it grows,
or a read that ends before its streamed create, replays the answer once and after its prompt

DELETE /v1/responses/{id} answers with the id the caller sent, on a copy, and logs a fresh encrypted id
like a read does

Azure Data Lake Storage per-event files and unbatched GCS objects are named after the event's spend row
id, so a streamed background create and its cost event, which now share the client's id, keep separate
files

The integration tests that decoded the managed id now match the exact id the client received

* fix(responses): keep main's answer for a raw-id delete and main's storage names outside background cost events

A DELETE by a raw provider id returns the provider's id as main did, and logging still records a fresh
encrypted id. A streamed GET matches the held id by upstream response id, like a plain GET

Only a background response's cost event gets the _background_cost suffix on its Azure Data Lake Storage
file and unbatched GCS object, so batch retrieves and events with no id keep main's names

An item a session read replays takes the newest read's copy at the first read's place, so an item a
poll caught half written replays finished

Tests pin the client's id over the router's continued response id, and the storage test no longer reads
the clock after the upload

* fix(spend): give background cost events their own OpenMeter and DynamoDB ids, replay id-less read items

A streamed background create and its later cost event share the client's
id, so OpenMeter dropped the second event and DynamoDB overwrote the
create's item. Both now key the cost event as <id>_background_cost, like
its spend row and storage file.

Session history again replays a read's output items that carry no id,
as main did.

* fix(integrations): keep OpenMeter and DynamoDB logging working without the proxy extras

* fix(integrations): give background cost events their own ClickHouse request id and DeepEval span id

A streamed background create and its later cost event now share the id the
client received, so ClickHouse and DeepEval saw both events under one id.
Route both through logged_event_key, the way the Azure storage, GCS,
OpenMeter and DynamoDB loggers already do, so the cost event's ClickHouse
request_id matches its spend row's `<id>_background_cost` and its DeepEval
span gets its own uuid. ClickHouse response_id stays the raw provider id.

* test(deepeval): annotate the background cost span test's locals with Final

* test(responses): run the DELETE wire test that pins the echoed client id

DELETE /v1/responses/{id} now answers with the id the caller sent, so the
skip that marked it as a known bug no longer applies. The test passes on
the /v1, /openai/v1 and bare routes.

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-02 14:13:17 -08:00

818 lines
36 KiB
Python

from __future__ import annotations
import json
import os
import threading
import uuid
from collections.abc import Callable
from types import MappingProxyType
from typing import Final, Literal
from urllib.parse import parse_qsl, urlsplit
import httpx
import openai
import pytest
from integration._support.client import Gateway, Scenario, eventually, object_value, string_value
from integration._support.responses_vendor import same_response
from integration._support.wire import Reply, Request, Wire, wire_server
from integration._support.worker_readiness import wait_for_worker_readiness
from openai.types.responses import Response, ResponseCreatedEvent, ResponseStreamEvent
from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
_MODEL: Final = "gpt-5"
_API_KEY: Final = "synthetic-responses-key"
_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
_PROXY_WORKERS: Final = max(1, int(os.environ.get("INTEGRATION_PROXY_WORKERS", "1")))
_ALIASES: Final = ("/v1", "", "/openai/v1")
class _DeleteResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
object: Literal["response"]
deleted: bool
def _deployments_in_group(gateway: Gateway, group: str) -> int:
entries: Final = gateway.get("/model/info")["data"]
assert isinstance(entries, list), entries
return sum(object_value(entry).get("model_name") == group for entry in entries)
def _wait_for_workers(gateway: Gateway, group: str, deployments: int) -> None:
wait_for_worker_readiness(gateway, group, deployments, _PROXY_WORKERS)
def model_discovery_reply(model: str) -> Reply:
return Reply(
body=json.dumps(
{"object": "list", "data": [{"id": model, "object": "model", "created": 1, "owned_by": "openai"}]}
).encode()
)
def drain_contract_requests(wire: Wire) -> tuple[Request, ...]:
requests: Final = wire.drain()
discovery: Final = tuple(request for request in requests if request.target == "/v1/models")
assert all(request.method == "GET" and request.body == b"" for request in discovery), requests
return tuple(request for request in requests if request.target != "/v1/models")
def _retrieve_or_missing_deployment(client: openai.OpenAI, response_id: str) -> Response | openai.BadRequestError:
try:
return client.responses.retrieve(response_id)
except openai.BadRequestError as refusal:
if "no healthy deployments" not in str(refusal).lower():
raise
return refusal
def _response(identity: str, status: str = "completed") -> bytes:
return json.dumps(
{
"id": identity,
"object": "response",
"created_at": 1,
"status": status,
"model": _MODEL,
"output": [],
}
).encode()
def _stream(identity: str) -> tuple[bytes, ...]:
return tuple(
f"data: {json.dumps(event)}\n\n".encode()
for event in (
{"type": "response.created", "response": json.loads(_response(identity, "in_progress"))},
{"type": "response.completed", "response": json.loads(_response(identity))},
)
) + (b"data: [DONE]\n\n",)
def _deployment(
scenario: Scenario, wire: Wire, api_key: str = _API_KEY, provider: str = "openai", **parameters: JsonValue
) -> str:
model: Final = scenario.model(
model=f"{provider}/{_MODEL}",
api_key=api_key,
api_base=f"{wire.url}/v1",
**parameters,
)
_wait_for_workers(scenario.gateway, model, 1)
return model
def _stream_response_events(
client: openai.OpenAI, response_id: str
) -> tuple[tuple[ResponseStreamEvent, ...], str | None]:
try:
return (
tuple(
client.responses.retrieve(
response_id,
stream=True,
starting_after=3,
include=["reasoning.encrypted_content"],
)
),
None,
)
except openai.InternalServerError as error:
return (), error.response.text
def _register_preferred_in_group(scenario: Scenario, wire: Wire, group: str, api_key: str) -> None:
existing: Final = _deployments_in_group(scenario.gateway, group)
created: Final = scenario.gateway.post(
"/model/new",
{
"model_name": group,
"litellm_params": {
"model": f"openai/{_MODEL}",
"api_key": api_key,
"api_base": f"{wire.url}/v1",
"order": 1,
},
"model_info": {},
},
)
deployment_id: Final = string_value(object_value(created["model_info"])["id"])
scenario.cleanups.callback(scenario.delete_model, deployment_id)
_wait_for_workers(scenario.gateway, group, existing + 1)
def _client(gateway: Gateway, key: str, prefix: str) -> openai.OpenAI:
return openai.OpenAI(
base_url=f"{gateway.client.base_url}{prefix}",
api_key=key,
max_retries=0,
)
@pytest.mark.parametrize("prefix", _ALIASES)
def test_retrieve_routes_to_the_deployment_that_created_the_response(
gateway: Gateway,
prefix: str,
) -> None:
raw_id: Final = f"resp_affinity_{uuid.uuid4().hex}"
wire_b_key: Final = "synthetic-responses-key-b"
wire_a_key: Final = "synthetic-responses-key-a"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
if request.method == "POST":
return Reply(body=_response(raw_id))
return Reply(body=_response(raw_id))
with wire_server(respond) as wire_b, wire_server(respond) as wire_a, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire_b, wire_b_key)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="create for affinity")
client_id: Final = created.id
assert client_id.startswith("resp_") and client_id != raw_id, created.model_dump_json()
_register_preferred_in_group(scenario, wire_a, model, wire_a_key)
retrieved: Final = client.responses.retrieve(client_id)
assert retrieved.id != raw_id, retrieved.model_dump_json()
assert same_response(retrieved.id, client_id), retrieved.model_dump_json()
assert retrieved.model_dump(mode="json", exclude_none=True) == {
"id": retrieved.id,
"object": "response",
"created_at": 1.0,
"status": "completed",
"model": _MODEL,
"output": [],
}, retrieved.model_dump_json()
requests: Final = drain_contract_requests(wire_b)
assert [(request.method, request.target, request.body) for request in requests] == [
("POST", "/v1/responses", requests[0].body),
("GET", f"/v1/responses/{raw_id}", b""),
], requests
assert _JSON_OBJECT.validate_json(requests[0].body) == {
"model": _MODEL,
"input": "create for affinity",
}, requests[0].body
assert all(request.headers["authorization"] == f"Bearer {wire_b_key}" for request in requests), requests
assert requests[1].body == b"", requests[1]
assert drain_contract_requests(wire_a) == (), (
f"{prefix or '/responses'} did not preserve response deployment affinity"
)
@pytest.mark.parametrize("prefix", _ALIASES)
def test_retrieve_returns_the_id_the_client_holds(gateway: Gateway, prefix: str) -> None:
raw_id: Final = f"resp_retrieve_id_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
assert request.headers["authorization"] == f"Bearer {_API_KEY}", dict(request.headers)
if request.method == "POST":
assert request.target == "/v1/responses"
assert _JSON_OBJECT.validate_json(request.body) == {"model": _MODEL, "input": "retrieve client id"}, (
request.body
)
return Reply(body=_response(raw_id))
assert request.method == "GET"
assert request.target == f"/v1/responses/{raw_id}", request.target
assert request.body == b""
return Reply(body=_response(raw_id))
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="retrieve client id")
client_id: Final = created.id
retrieved: Final = client.responses.retrieve(client_id)
requests: Final = drain_contract_requests(wire)
assert [(request.method, request.target, request.body) for request in requests] == [
("POST", "/v1/responses", requests[0].body),
("GET", f"/v1/responses/{raw_id}", b""),
], requests
assert _JSON_OBJECT.validate_json(requests[0].body) == {
"model": _MODEL,
"input": "retrieve client id",
}, requests[0].body
assert retrieved.id == client_id, (retrieved.model_dump_json(), requests)
@pytest.mark.parametrize("prefix", _ALIASES)
def test_streamed_response_ids_are_stable_and_retrievable_on_each_alias(
gateway: Gateway,
prefix: str,
) -> None:
raw_id: Final = f"resp_stream_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
assert request.headers["authorization"] == f"Bearer {_API_KEY}", dict(request.headers)
if request.method == "POST":
assert request.target == "/v1/responses"
assert _JSON_OBJECT.validate_json(request.body) == {
"model": _MODEL,
"input": "stream lifecycle",
"stream": True,
}, request.body
return Reply(content_type="text/event-stream", chunks=_stream(raw_id))
return Reply(body=_response(raw_id))
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
team: Final = scenario.team(models=[model])
user: Final = scenario.member(team)
key: Final = scenario.key(team_id=team, user_id=user, models=[model])
client: Final = _client(gateway, key, prefix)
stream: Final = client.responses.create(model=model, input="stream lifecycle", stream=True)
events: Final = list(stream)
response_ids: Final = tuple(event.response.id for event in events if hasattr(event, "response"))
assert response_ids and all(response_id == response_ids[0] for response_id in response_ids), events
streamed_id: Final = response_ids[0]
assert streamed_id.startswith("resp_") and streamed_id != raw_id, events
retrieved: Final = eventually(
lambda: _retrieve_or_missing_deployment(client, streamed_id),
lambda outcome: not isinstance(outcome, openai.BadRequestError),
seconds=60,
)
assert isinstance(retrieved, Response), retrieved
assert same_response(retrieved.id, streamed_id), retrieved.model_dump_json()
assert retrieved.model_dump(mode="json", exclude_none=True) == {
"id": retrieved.id,
"object": "response",
"created_at": 1.0,
"status": "completed",
"model": _MODEL,
"output": [],
}, retrieved.model_dump_json()
requests: Final = drain_contract_requests(wire)
assert [(request.method, urlsplit(request.target).path, request.body) for request in requests] == [
("POST", "/v1/responses", requests[0].body),
("GET", f"/v1/responses/{raw_id}", b""),
], requests
assert _JSON_OBJECT.validate_json(requests[0].body) == {
"model": _MODEL,
"input": "stream lifecycle",
"stream": True,
}, requests[0].body
assert all(request.headers["authorization"] == f"Bearer {_API_KEY}" for request in requests), requests
@pytest.mark.parametrize("prefix", _ALIASES)
def test_retrieve_query_reaches_the_provider(gateway: Gateway, prefix: str) -> None:
normal_raw_id: Final = f"resp_query_normal_{uuid.uuid4().hex}"
stream_raw_id: Final = f"resp_query_stream_{uuid.uuid4().hex}"
normal_include: Final = ["message.output_text.logprobs", "reasoning.encrypted_content"]
stream_include: Final = ["reasoning.encrypted_content"]
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
if request.method == "POST" and urlsplit(request.target).path == "/v1/responses":
body: Final = _JSON_OBJECT.validate_json(request.body)
identity: Final = stream_raw_id if body.get("input") == "query retrieve stream" else normal_raw_id
return Reply(body=_response(identity))
if urlsplit(request.target).path == f"/v1/responses/{stream_raw_id}":
return Reply(content_type="text/event-stream", chunks=_stream(stream_raw_id))
return Reply(body=_response(normal_raw_id))
with wire_server(respond) as wire:
sdk_client: Final = openai.OpenAI(base_url=f"{wire.url}/v1", api_key=_API_KEY, max_retries=0)
sdk_client.responses.retrieve(normal_raw_id, include=normal_include)
tuple(
sdk_client.responses.retrieve(
stream_raw_id,
stream=True,
starting_after=3,
include=stream_include,
)
)
sdk_requests: Final = drain_contract_requests(wire)
assert [request.method for request in sdk_requests] == ["GET", "GET"], sdk_requests
expected_queries: Final = tuple(
tuple(sorted(parse_qsl(urlsplit(request.target).query, keep_blank_values=True))) for request in sdk_requests
)
with gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
normal_created: Final = client.responses.create(model=model, input="query retrieve normal")
stream_created: Final = client.responses.create(model=model, input="query retrieve stream")
retrieved_response: Final = client.responses.with_raw_response.retrieve(
normal_created.id,
include=normal_include,
)
retrieved: Final = retrieved_response.parse()
assert retrieved.id != normal_raw_id and same_response(retrieved.id, normal_created.id), (
retrieved_response.text
)
assert retrieved.model_dump(mode="json", exclude_none=True) == {
"id": retrieved.id,
"object": "response",
"created_at": 1.0,
"status": "completed",
"model": _MODEL,
"output": [],
}, retrieved_response.text
stream_result: Final = _stream_response_events(client, stream_created.id)
stream_events: Final = stream_result[0]
stream_error_text: Final = stream_result[1]
if stream_error_text is not None:
requests: Final = drain_contract_requests(wire)
assert [(request.method, urlsplit(request.target).path, request.body) for request in requests[2:]] == [
("GET", f"/v1/responses/{normal_raw_id}", b""),
("GET", f"/v1/responses/{stream_raw_id}", b""),
], stream_error_text
actual_queries: Final = tuple(
tuple(sorted(parse_qsl(urlsplit(request.target).query, keep_blank_values=True)))
for request in requests[2:]
)
assert actual_queries == expected_queries, (
requests[2:],
actual_queries,
expected_queries,
stream_error_text,
)
pytest.fail(f"Streaming retrieval returned an API error: {stream_error_text}")
completed_events: Final = tuple(event for event in stream_events if event.type == "response.completed")
assert len(completed_events) == 1, stream_events
completed: Final = completed_events[0]
assert completed.response.id != stream_raw_id and same_response(completed.response.id, stream_created.id), (
stream_events
)
assert completed.model_dump(mode="json", exclude_none=True) == {
"type": "response.completed",
"response": {
"id": completed.response.id,
"object": "response",
"created_at": 1.0,
"status": "completed",
"model": _MODEL,
"output": [],
},
}, stream_events
requests: Final = drain_contract_requests(wire)
assert [(request.method, urlsplit(request.target).path, request.body) for request in requests] == [
("POST", "/v1/responses", requests[0].body),
("POST", "/v1/responses", requests[1].body),
("GET", f"/v1/responses/{normal_raw_id}", b""),
("GET", f"/v1/responses/{stream_raw_id}", b""),
], requests
assert _JSON_OBJECT.validate_json(requests[0].body) == {
"model": _MODEL,
"input": "query retrieve normal",
}, requests[0].body
assert _JSON_OBJECT.validate_json(requests[1].body) == {
"model": _MODEL,
"input": "query retrieve stream",
}, requests[1].body
actual_queries: Final = tuple(
tuple(sorted(parse_qsl(urlsplit(request.target).query, keep_blank_values=True)))
for request in requests[2:]
)
assert actual_queries == expected_queries, requests
def _resumed_delta() -> bytes:
event: Final = {
"type": "response.output_text.delta",
"sequence_number": 4,
"item_id": "msg_resumed",
"output_index": 0,
"content_index": 0,
"delta": "resumed",
"logprobs": [],
}
return f"data: {json.dumps(event)}\n\n".encode()
def _sorted_query(request: Request) -> tuple[tuple[str, str], ...]:
return tuple(sorted(parse_qsl(urlsplit(request.target).query, keep_blank_values=True)))
@pytest.mark.parametrize("prefix", _ALIASES)
def test_resuming_past_the_last_event_ends_the_stream_without_events(gateway: Gateway, prefix: str) -> None:
raw_id: Final = f"resp_resume_end_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
if request.method == "POST":
return Reply(body=_response(raw_id))
return Reply(content_type="text/event-stream", chunks=())
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="resume past the end")
events: Final = tuple(client.responses.retrieve(created.id, stream=True, starting_after=7))
requests: Final = drain_contract_requests(wire)
assert events == ()
assert [(request.method, urlsplit(request.target).path) for request in requests] == [
("POST", "/v1/responses"),
("GET", f"/v1/responses/{raw_id}"),
], requests
assert _sorted_query(requests[1]) == (("starting_after", "7"), ("stream", "true")), requests[1]
@pytest.mark.parametrize("prefix", _ALIASES)
def test_a_client_leaving_a_resumed_stream_releases_the_provider_connection(gateway: Gateway, prefix: str) -> None:
raw_id: Final = f"resp_resume_leave_{uuid.uuid4().hex}"
release: Final = threading.Event()
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
if request.method == "POST":
return Reply(body=_response(raw_id))
return Reply(
content_type="text/event-stream",
chunks=(_resumed_delta(), b"data: [DONE]\n\n"),
gate_after_first=release,
heartbeat=b": keepalive\n\n",
pause_between_chunks=0.05,
)
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="leave a resumed stream")
stream: Final = client.responses.retrieve(created.id, stream=True, starting_after=3)
try:
first: Final = next(iter(stream))
stream.close()
left_from: Final = wire.disconnected.get(timeout=30)
finally:
release.set()
assert first.type == "response.output_text.delta"
assert urlsplit(left_from).path == f"/v1/responses/{raw_id}"
def _created_then(raw_id: str, read: Reply) -> Callable[[Request], Reply]:
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
if request.method == "POST":
return Reply(body=_response(raw_id))
return read
return respond
def _event_types(answer: httpx.Response) -> list[JsonValue]:
return [
_JSON_OBJECT.validate_json(line.removeprefix("data: "))["type"]
for line in answer.text.splitlines()
if line.startswith("data: {")
]
_MALFORMED_RESUMES: Final = MappingProxyType(
{
"stream": {"stream": "maybe"},
"starting_after": {"stream": "true", "starting_after": "-1"},
}
)
@pytest.mark.parametrize("param", tuple(_MALFORMED_RESUMES))
@pytest.mark.parametrize("prefix", _ALIASES)
def test_a_malformed_resume_query_is_refused_without_calling_the_provider(
gateway: Gateway, prefix: str, param: str
) -> None:
raw_id: Final = f"resp_malformed_{uuid.uuid4().hex}"
replay: Final = Reply(content_type="text/event-stream", chunks=_stream(raw_id))
with wire_server(_created_then(raw_id, replay)) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
created: Final = _client(gateway, gateway.key, prefix).responses.create(model=model, input="malformed resume")
refused: Final = gateway.request("GET", f"{prefix}/responses/{created.id}", params=_MALFORMED_RESUMES[param])
requests: Final = drain_contract_requests(wire)
assert refused.status_code == 400, refused.text
assert object_value(_JSON_OBJECT.validate_json(refused.content)["error"])["param"] == param, refused.text
assert [request.method for request in requests] == ["POST"], requests
@pytest.mark.parametrize("prefix", _ALIASES)
def test_a_malformed_resume_cursor_replays_the_whole_stream_when_drop_params_is_on(
gateway: Gateway, prefix: str
) -> None:
raw_id: Final = f"resp_malformed_dropped_{uuid.uuid4().hex}"
replay: Final = Reply(content_type="text/event-stream", chunks=_stream(raw_id))
with wire_server(_created_then(raw_id, replay)) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire, drop_params=True)
created: Final = _client(gateway, gateway.key, prefix).responses.create(model=model, input="dropped cursor")
replayed: Final = gateway.request(
"GET", f"{prefix}/responses/{created.id}", params=_MALFORMED_RESUMES["starting_after"]
)
requests: Final = drain_contract_requests(wire)
assert replayed.status_code == 200, replayed.text
assert _event_types(replayed) == ["response.created", "response.completed"], replayed.text
assert [request.method for request in requests] == ["POST", "GET"], requests
assert _sorted_query(requests[1]) == (("stream", "true"),), requests[1]
@pytest.mark.parametrize("prefix", _ALIASES)
def test_resuming_on_a_provider_that_cannot_replay_is_refused_without_calling_it(gateway: Gateway, prefix: str) -> None:
raw_id: Final = f"resp_no_replay_{uuid.uuid4().hex}"
with wire_server(_created_then(raw_id, Reply(body=_response(raw_id)))) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire, provider="litellm_proxy")
created: Final = _client(gateway, gateway.key, prefix).responses.create(model=model, input="cannot replay")
refused: Final = gateway.request(
"GET", f"{prefix}/responses/{created.id}", params={"stream": "true", "starting_after": "3"}
)
requests: Final = drain_contract_requests(wire)
assert refused.status_code == 400, refused.text
message: Final = string_value(object_value(_JSON_OBJECT.validate_json(refused.content)["error"])["message"])
assert "litellm_proxy does not support streaming a stored response" in message, refused.text
assert [request.method for request in requests] == ["POST"], requests
@pytest.mark.parametrize("prefix", _ALIASES)
def test_resuming_on_a_provider_that_cannot_replay_answers_the_stored_response_when_drop_params_is_on(
gateway: Gateway, prefix: str
) -> None:
raw_id: Final = f"resp_no_replay_dropped_{uuid.uuid4().hex}"
with wire_server(_created_then(raw_id, Reply(body=_response(raw_id)))) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire, provider="litellm_proxy", drop_params=True)
created: Final = _client(gateway, gateway.key, prefix).responses.create(model=model, input="dropped replay")
answered: Final = gateway.request(
"GET", f"{prefix}/responses/{created.id}", params={"stream": "true", "starting_after": "3"}
)
requests: Final = drain_contract_requests(wire)
assert answered.status_code == 200, answered.text
body: Final = _JSON_OBJECT.validate_json(answered.content)
assert (body["object"], body["status"], same_response(string_value(body["id"]), created.id)) == (
"response",
"completed",
True,
), answered.text
assert [request.method for request in requests] == ["POST", "GET"], requests
assert _sorted_query(requests[1]) == (), requests[1]
@pytest.mark.parametrize("prefix", _ALIASES)
def test_a_resumed_stream_waits_out_the_stream_timeout_not_the_request_timeout(gateway: Gateway, prefix: str) -> None:
raw_id: Final = f"resp_slow_replay_{uuid.uuid4().hex}"
slow: Final = Reply(content_type="text/event-stream", chunks=_stream(raw_id), pause_between_chunks=2)
with wire_server(_created_then(raw_id, slow)) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire, timeout=1, stream_timeout=30)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="slow replay")
events: Final = tuple(client.responses.retrieve(created.id, stream=True, starting_after=3))
assert [event.type for event in events] == ["response.created", "response.completed"], events
@pytest.mark.parametrize("prefix", _ALIASES)
def test_a_plain_retrieve_on_a_deployment_set_to_stream_answers_the_response_object(
gateway: Gateway, prefix: str
) -> None:
raw_id: Final = f"resp_streaming_deployment_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
if request.method == "POST":
return Reply(content_type="text/event-stream", chunks=_stream(raw_id))
return Reply(body=_response(raw_id))
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire, stream=True)
events: Final = tuple(
_client(gateway, gateway.key, prefix).responses.create(model=model, input="forced stream", stream=True)
)
created_id: Final = next(event.response.id for event in events if isinstance(event, ResponseCreatedEvent))
retrieved: Final = gateway.request("GET", f"{prefix}/responses/{created_id}")
requests: Final = drain_contract_requests(wire)
assert retrieved.status_code == 200, retrieved.text
assert retrieved.headers["content-type"].startswith("application/json"), retrieved.headers
body: Final = _JSON_OBJECT.validate_json(retrieved.content)
assert (body["object"], body["status"], same_response(string_value(body["id"]), created_id)) == (
"response",
"completed",
True,
), retrieved.text
assert [request.method for request in requests] == ["POST", "GET"], requests
assert _sorted_query(requests[1]) == (), requests[1]
@pytest.mark.parametrize("prefix", _ALIASES)
def test_delete_forwards_the_provider_id_once_and_reports_deletion(
gateway: Gateway,
prefix: str,
) -> None:
raw_id: Final = f"resp_delete_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
assert request.headers["authorization"] == f"Bearer {_API_KEY}", dict(request.headers)
if request.method == "POST":
assert request.target == "/v1/responses"
assert _JSON_OBJECT.validate_json(request.body) == {"model": _MODEL, "input": "delete lifecycle"}, (
request.body
)
return Reply(body=_response(raw_id))
assert request.method == "DELETE"
assert request.body == b""
return Reply(body=json.dumps({"id": raw_id, "object": "response", "deleted": True}).encode())
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="delete lifecycle")
deleted: Final = client.responses.with_raw_response.delete(created.id)
assert deleted.status_code == 200, deleted.text
parsed: Final = _DeleteResponse.model_validate_json(deleted.content)
assert same_response(parsed.id, created.id), deleted.text
assert parsed.model_dump(mode="json", exclude={"id"}) == {
"object": "response",
"deleted": True,
}, deleted.text
requests: Final = drain_contract_requests(wire)
assert [(request.method, request.target, request.body) for request in requests] == [
("POST", "/v1/responses", requests[0].body),
("DELETE", f"/v1/responses/{raw_id}", b""),
], requests
@pytest.mark.parametrize("prefix", _ALIASES)
def test_delete_returns_the_client_held_id_not_the_provider_id(
gateway: Gateway,
prefix: str,
) -> None:
raw_id: Final = f"resp_delete_id_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
assert request.headers["authorization"] == f"Bearer {_API_KEY}", dict(request.headers)
if request.method == "POST":
assert request.target == "/v1/responses"
assert _JSON_OBJECT.validate_json(request.body) == {"model": _MODEL, "input": "delete client id"}, (
request.body
)
return Reply(body=_response(raw_id))
assert request.method == "DELETE"
assert request.target == f"/v1/responses/{raw_id}", request.target
assert request.body == b""
return Reply(body=json.dumps({"id": raw_id, "object": "response", "deleted": True}).encode())
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="delete client id")
deleted: Final = client.responses.with_raw_response.delete(created.id)
assert deleted.status_code == 200, deleted.text
parsed: Final = _DeleteResponse.model_validate_json(deleted.content)
requests: Final = drain_contract_requests(wire)
assert [(request.method, request.target, request.body) for request in requests] == [
("POST", "/v1/responses", requests[0].body),
("DELETE", f"/v1/responses/{raw_id}", b""),
], requests
assert _JSON_OBJECT.validate_json(requests[0].body) == {
"model": _MODEL,
"input": "delete client id",
}, requests[0].body
assert parsed.id != raw_id, (deleted.text, requests)
assert parsed.model_dump(mode="json") == {
"id": created.id,
"object": "response",
"deleted": True,
}, deleted.text
@pytest.mark.parametrize("prefix", _ALIASES)
def test_cancel_forwards_provider_id_and_returns_cancelled_response(
gateway: Gateway,
prefix: str,
) -> None:
raw_id: Final = f"resp_cancel_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
assert request.headers["authorization"] == f"Bearer {_API_KEY}", dict(request.headers)
if request.method == "POST" and request.target == "/v1/responses":
assert _JSON_OBJECT.validate_json(request.body) == {
"model": _MODEL,
"input": "cancel lifecycle",
"background": True,
}, request.body
return Reply(body=_response(raw_id, "queued"))
assert request.body in (b"", b"{}")
return Reply(body=_response(raw_id, "cancelled"))
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="cancel lifecycle", background=True)
cancelled: Final = client.responses.cancel(created.id)
assert cancelled.id != raw_id and same_response(cancelled.id, created.id), cancelled.model_dump_json()
assert cancelled.model_dump(mode="json", exclude_none=True) == {
"id": cancelled.id,
"object": "response",
"created_at": 1.0,
"status": "cancelled",
"model": _MODEL,
"output": [],
}, cancelled.model_dump_json()
requests: Final = drain_contract_requests(wire)
assert [(request.method, request.target) for request in requests] == [
("POST", "/v1/responses"),
("POST", f"/v1/responses/{raw_id}/cancel"),
], requests
assert requests[1].body == b"{}", requests[1]
@pytest.mark.parametrize("prefix", _ALIASES)
def test_input_items_pagination_query_reaches_the_provider(gateway: Gateway, prefix: str) -> None:
pytest.skip(
"BUG: GET /v1/responses/{id}/input_items drops pagination and include query params; "
"upstream receives limit=20&order=desc without after or include"
)
raw_id: Final = f"resp_input_items_{uuid.uuid4().hex}"
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target == "/v1/models":
return model_discovery_reply(_MODEL)
if request.method == "POST":
return Reply(body=_response(raw_id))
return Reply(body=b'{"data":[],"has_more":false,"object":"list"}')
with wire_server(respond) as wire, gateway.scenario() as scenario:
model: Final = _deployment(scenario, wire)
client: Final = _client(gateway, gateway.key, prefix)
created: Final = client.responses.create(model=model, input="list response input items")
page: Final = client.responses.input_items.list(
created.id,
limit=2,
order="asc",
after="item_after",
include=["message.output_text.logprobs"],
)
assert page.data == [], page.model_dump_json()
requests: Final = drain_contract_requests(wire)
assert [(request.method, request.target) for request in requests] == [
("POST", "/v1/responses"),
(
"GET",
f"/v1/responses/{raw_id}/input_items?limit=2&order=asc&after=item_after"
"&include=message.output_text.logprobs",
),
], requests
assert all(request.headers["authorization"] == f"Bearer {_API_KEY}" for request in requests), requests
assert requests[1].body == b"", requests[1]