The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(e2e): record and replay streamed provider responses chunk-for-chunk
mateo-berriec47bbaaaaf4
diff --git a/tests/e2e/CLAUDE.md b/tests/e2e/CLAUDE.mdindex 15bd2c19ca9..e0ee40a65c5 100644--- a/tests/e2e/CLAUDE.md+++ b/tests/e2e/CLAUDE.md@@ -77,7 +77,7 @@ Mark live tests with `@pytest.mark.e2e` (on the class or the module). Pure coverThe seam is `provider_edge.py`: `start_provider_edge` boots an in-process HTTP server (one shared instance per pytest process, `e2e_config.provider_edge_base` is the accessor) that mounts each supported provider under a path prefix (`EDGE_MOUNTS`: `/openai` -> `https://api.openai.com`, `/anthropic` -> `https://api.anthropic.com`). A test participates by registering its deployment with `api_base=provider_edge_base("openai")` plus the provider's path suffix; `quota_management/spend_tracking/test_provider_edge_spend_e2e.py` is the reference. In live mode the accessor returns None and the deployment defaults to the real provider, so an edge-wired test runs in all three modes unchanged. Non-wired tests hit their providers live in every mode. The edge binds `E2E_PROVIDER_EDGE_BIND_HOST` (default 127.0.0.1) and advertises `E2E_PROVIDER_EDGE_ADVERTISE_HOST` in the api_base it hands out, for proxies running in containers-A bundle (default `tests/e2e/.fixtures`, override with `E2E_FIXTURE_DIR`) is a directory: `manifest.json` carries the record timestamp, harness git version, and format version, and each test gets a subdirectory holding one JSON file per provider call in call order (`0000-post-openai-v1-chat-completions.json`). Request headers are never stored (provider credentials never touch disk), non-JSON request bodies store a canonicalized sha256 digest instead of the bytes, `multipart/form-data` bodies store their ordinary fields plus a JSON list of the uploaded parts' `[field, filename, content-type]` triples and a digest of their content, so the per-request random boundary and the envelope never reach the key, and responses store status, filtered headers, and the verbatim body base64-encoded, which is part of why bundles are gitignored. `fixture_bundle.py` owns the format. Record serves the proxy the same filtered stored response replay will serve later, so the two modes are byte-identical from the proxy's side of the socket+A bundle (default `tests/e2e/.fixtures`, override with `E2E_FIXTURE_DIR`) is a directory: `manifest.json` carries the record timestamp, harness git version, and format version, and each test gets a subdirectory holding one JSON file per provider call in call order (`0000-post-openai-v1-chat-completions.json`). Request headers are never stored (provider credentials never touch disk), non-JSON request bodies store a canonicalized sha256 digest instead of the bytes, `multipart/form-data` bodies store their ordinary fields plus a JSON list of the uploaded parts' `[field, filename, content-type]` triples and a digest of their content, so the per-request random boundary and the envelope never reach the key, and responses store status, filtered headers, and the verbatim body base64-encoded, which is part of why bundles are gitignored. Responses come in two shapes told apart by a `kind` tag: an ordinary one holding a single base64 body, and, for a response the provider streamed (`content-type: text/event-stream`), one holding its transfer chunks in order plus why the stream ended early if it did, so replay reproduces the split points the provider chose instead of one coalesced body. `fixture_bundle.py` owns the format, and `BUNDLE_FORMAT_VERSION` is checked on load, so a bundle recorded under older rules is refused by name rather than partially read. Record serves the proxy the same filtered stored response replay will serve later, chunk for chunk on a stream, so the two modes are byte-identical from the proxy's side of the socketMultipart identity is the fiddly corner, and the rules exist because each one had a collision behind it. A part counts as an upload when it carries a filename or declares its own content type, and everything else is an ordinary field. Field names get a `name[n]` suffix on repeats, with a literal `[` doubled first, so a form that repeats `purpose` never keys the same as one that literally sends `purpose[1]`. A field whose name reads as a credential is stored as `<secret>`, which stays key-preserving because the key is recomputed from the stored request rather than saved alongside it, so the live request carrying the real value still matches its redacted fixture. A field value that is not UTF-8 is stored as a base64 sha256 digest, base64 and not hex because the canonicalizer rewrites any 64-character hex run to `<sha256>` and would fold every binary value onto one key. The uploaded parts contribute a JSON list rather than a `field:filename` string, so a separator inside a filename cannot impersonate a field boundary, and their byte length is stored for a reader's benefit but deliberately left out of the key, since the canonicalizer absorbs timestamp and id drift inside a file that changes its length@@ -87,7 +87,7 @@ A replayed response carries the recorded provider response id, and `LiteLLM_SpenThe same id reuse reaches the managed-object tables. A replayed `/v1/files` or `/v1/batches` response carries the recorded provider object id, and `LiteLLM_ManagedObjectTable.model_object_id` is unique, so a unified batch create replayed against a database that still holds the record run's row fails on a Prisma unique-constraint violation, which surfaces as a 500, makes the router retry, and exhausts the recording. Replay the batches suite against a fresh database, or truncate `LiteLLM_ManagedObjectTable` and `LiteLLM_ManagedFileTable` before the run-Edge-wired today: `quota_management/spend_tracking/test_provider_edge_spend_e2e.py` (the reference), `llm_translation/test_chat_completions_contract_e2e.py`, the OpenAI registrations in `llm_translation/test_embeddings_endpoint_e2e.py`, the Anthropic deployments in `llm_translation/test_messages_e2e.py` except the streaming test, and the OpenAI batch deployment behind `batches/` (`capabilities.openai_batch_params`). The mount base is not the same for both providers: OpenAI deployments register `f"{base}/v1"`, Anthropic deployments register `base` on its own, because litellm's Anthropic handler appends `/v1/messages` to `api_base` itself where the OpenAI handler appends only `/chat/completions`. Recording one suite locally is two runs against a proxy you already have up:+Edge-wired today: `quota_management/spend_tracking/test_provider_edge_spend_e2e.py` (the reference), `llm_translation/test_chat_completions_contract_e2e.py`, the OpenAI registrations in `llm_translation/test_embeddings_endpoint_e2e.py`, the Anthropic deployments in `llm_translation/test_messages_e2e.py` including the streaming test, and the OpenAI batch deployment behind `batches/` (`capabilities.openai_batch_params`). The mount base is not the same for both providers: OpenAI deployments register `f"{base}/v1"`, Anthropic deployments register `base` on its own, because litellm's Anthropic handler appends `/v1/messages` to `api_base` itself where the OpenAI handler appends only `/chat/completions`. Recording one suite locally is two runs against a proxy you already have up:```bashE2E_FIXTURE_MODE=record E2E_FIXTURE_DIR=/tmp/e2e-fixtures E2E_RESET_SPEND_LOGS=1 uv run pytest tests/e2e/llm_translation/test_chat_completions_contract_e2e.py@@ -96,7 +96,7 @@ E2E_FIXTURE_MODE=replay E2E_FIXTURE_DIR=/tmp/e2e-fixtures E2E_RESET_SPEND_LOGS=1Point the proxy at bogus provider credentials for the replay run and it still has to pass: that is the whole proof that nothing left the process. Bundles are never committed. `tests/e2e/.fixtures` is gitignored because a bundle holds verbatim provider response bodies and hard-fails after seven days, and publishing one for CI is LIT-5748-Current limits: streaming chunk fidelity is LIT-5742 (a streamed response records as one buffered body), CI wiring is LIT-5748, Bedrock cannot be mounted (SigV4 signs the Host header, so a rewritten api_base fails signature verification), deployments baked into the proxy's config file cannot be edge-wired (only `/model/new` registrations can carry the edge api_base), and a file upload routed by `custom_llm_provider` through the proxy's `files_settings` block never passes a deployment at all, so the batches `model_param` and `provider_fallback` scenarios keep uploading live in every mode+Current limits: CI wiring is LIT-5748, Bedrock cannot be mounted (SigV4 signs the Host header, so a rewritten api_base fails signature verification), deployments baked into the proxy's config file cannot be edge-wired (only `/model/new` registrations can carry the edge api_base), and a file upload routed by `custom_llm_provider` through the proxy's `files_settings` block never passes a deployment at all, so the batches `model_param` and `provider_fallback` scenarios keep uploading live in every mode## Typingdiff --git a/tests/e2e/CONTRIBUTING.md b/tests/e2e/CONTRIBUTING.mdindex 29778b06d7a..75261b301bd 100644--- a/tests/e2e/CONTRIBUTING.md+++ b/tests/e2e/CONTRIBUTING.md@@ -65,7 +65,7 @@ Bundles stay local. `tests/e2e/.fixtures` is gitignored because a bundle holds vOne sharp edge: a replayed response reuses the recorded provider response id, and that id is the primary key of `LiteLLM_SpendLogs`, so replaying against a database that still holds the record run's rows silently dedupes the spend writes and a spend assertion fails with zero rows. Run both commands above with `E2E_RESET_SPEND_LOGS=1` (and `DATABASE_URL` set in the pytest env) so each session truncates the spend log table after itself, or point replay at a fresh database-Replay answers any provider call that drifted from the recording with an HTTP 599 whose body names the computed and closest recorded keys, so the test fails loudly instead of silently going live, and a bundle older than seven days fails at collection time naming its age; either way the fix is to re-record. Only tests that register edge-wired deployments participate: everything else hits its provider live in every mode, so record exactly the suite you replay. If the proxy runs in a container, set `E2E_PROVIDER_EDGE_ADVERTISE_HOST` (e.g. `host.docker.internal`) so the api_base the proxy stores can reach the edge on the pytest host, and `E2E_PROVIDER_EDGE_BIND_HOST=0.0.0.0` so the edge accepts it. The suites wired to the edge today are `quota_management/spend_tracking/test_provider_edge_spend_e2e.py`, `llm_translation/test_chat_completions_contract_e2e.py`, the OpenAI registrations in `llm_translation/test_embeddings_endpoint_e2e.py`, the non-streaming Anthropic tests in `llm_translation/test_messages_e2e.py`, and the OpenAI batch deployment behind `batches/`. See `CLAUDE.md` in this directory for the bundle format, the edge design, and the current limits (streaming, Bedrock)+Replay answers any provider call that drifted from the recording with an HTTP 599 whose body names the computed and closest recorded keys, so the test fails loudly instead of silently going live, and a bundle older than seven days fails at collection time naming its age; either way the fix is to re-record. Only tests that register edge-wired deployments participate: everything else hits its provider live in every mode, so record exactly the suite you replay. If the proxy runs in a container, set `E2E_PROVIDER_EDGE_ADVERTISE_HOST` (e.g. `host.docker.internal`) so the api_base the proxy stores can reach the edge on the pytest host, and `E2E_PROVIDER_EDGE_BIND_HOST=0.0.0.0` so the edge accepts it. The suites wired to the edge today are `quota_management/spend_tracking/test_provider_edge_spend_e2e.py`, `llm_translation/test_chat_completions_contract_e2e.py`, the OpenAI registrations in `llm_translation/test_embeddings_endpoint_e2e.py`, the Anthropic tests in `llm_translation/test_messages_e2e.py`, streamed and not, and the OpenAI batch deployment behind `batches/`. A streamed response replays as the chunk sequence the provider sent rather than one buffered body. See `CLAUDE.md` in this directory for the bundle format, the edge design, and the current limits (Bedrock, CI wiring)Tests marked `@pytest.mark.e2e` hard-fail when no proxy answers `/health/liveliness`, so a run that goes red with `No live proxy` at setup means the proxy isn't up; they never skip for a missing proxy, so an absent proxy can't be mistaken for a passdiff --git a/tests/e2e/e2e_http.py b/tests/e2e/e2e_http.pyindex 03f201e946e..bc76eb3ea7a 100644--- a/tests/e2e/e2e_http.py+++ b/tests/e2e/e2e_http.py@@ -4,6 +4,11 @@ Enforced by tests/code_coverage_tests/check_e2e_no_raw_requests.py. Every requesbody / query / header / response is a pydantic model; outcomes are a tagged union(``Result[R]``) so callers ``match`` on them instead of catching exceptions.+``forward`` relays one provider-bound request for the provider edge and buffers+the whole body; ``forward_stream`` relays the same request but hands back the+response head plus a lazy iterator over the upstream's own transfer chunks, which+is what lets a recording keep the split points a streamed response arrived on.+Named e2e_http (not http) so it does not shadow the stdlib ``http`` package thatrequests itself imports."""@@ -12,7 +17,8 @@ from __future__ import annotationsimport timefrom collections.abc import Callable-from typing import Generic, Iterator, Literal, NewType, Protocol, TypeVar, cast+from dataclasses import dataclass+from typing import Generator, Generic, Iterator, Literal, NewType, Protocol, TypeVar, castimport pytestimport requests@@ -681,3 +687,88 @@ def forward(headers={name.lower(): value for name, value in resp.headers.items()},body=resp.content,)+++@dataclass(frozen=True, slots=True)+class StreamChunk:+ """One transfer chunk of a response body, exactly as the upstream framed it."""++ data: bytes+++@dataclass(frozen=True, slots=True)+class StreamTruncation:+ """The body ended without its terminator, i.e. the upstream hung up mid-message.+ Always the last step, and ``reason`` is the transport's own description of it."""++ reason: str+++type StreamStep = StreamChunk | StreamTruncation+++@dataclass(frozen=True, slots=True)+class StreamHead:+ """An upstream response whose head has arrived and whose body has not been read.++ A dataclass rather than a BaseModel because it owns a live socket: ``steps`` is+ consumed once, in order, and closing it closes the underlying response."""++ status_code: int+ headers: dict[str, str]+ steps: Generator[StreamStep, None, None]+++def _stream_steps(resp: requests.Response) -> Generator[StreamStep, None, None]:+ """The body as the upstream framed it, one step per transfer chunk.++ ``chunk_size=None`` is the whole point: urllib3 then returns exactly one piece+ per wire chunk, so the provider's split points survive into the recording. Any+ integer would re-slice the body into fixed-size pieces instead. Empty pieces are+ dropped because a zero-length chunk is the terminator on the wire, and a failure+ part way through becomes a final truncation step rather than an exception, since+ the chunks already delivered are exactly what makes a mid-stream failure+ different from a request that never streamed at all."""+ try:+ for piece in cast("Iterator[bytes]", resp.iter_content(chunk_size=None)):+ if piece:+ yield StreamChunk(data=piece)+ except requests.RequestException as exc:+ yield StreamTruncation(reason=str(exc))+ finally:+ resp.close()+++def forward_stream(+ method: str,+ url: str,+ *,+ headers: dict[str, str],+ body: bytes | None,+ timeout: float = 60.0,+) -> StreamHead | NetworkError:+ """Relay one provider-bound request for the provider edge and return as soon as+ the response head arrives, with the body left unread behind ``StreamHead.steps``.++ Same contract as ``forward`` otherwise: no retries, no redirects, no schema. A+ failure before the head arrives is still a ``NetworkError``; one raised while the+ body streams arrives as the last step. With ``stream=True`` the timeout bounds+ each socket read rather than the whole body, which is the right bound for a+ stream and strictly more permissive for a long generation."""+ try:+ resp = requests.request(+ method,+ url,+ headers=headers,+ data=body,+ timeout=timeout,+ allow_redirects=False,+ stream=True,+ )+ except requests.RequestException as exc:+ return NetworkError(message=str(exc))+ return StreamHead(+ status_code=resp.status_code,+ headers={name.lower(): value for name, value in resp.headers.items()},+ steps=_stream_steps(resp),+ )diff --git a/tests/e2e/fixture_bundle.py b/tests/e2e/fixture_bundle.pyindex aa0ba100b6c..7c9dab1a687 100644--- a/tests/e2e/fixture_bundle.py+++ b/tests/e2e/fixture_bundle.py@@ -6,15 +6,17 @@ per provider-bound interaction in call order. Bundles older than``MAX_BUNDLE_AGE`` hard-fail replay at collection time (see conftest), so agreen replay run can never certify against fixtures that have drifted more thana week from the live providers. Bump ``BUNDLE_FORMAT_VERSION`` whenever a change-moves recorded keys: a bundle recorded under the old rules then fails naming-both versions instead of quietly missing on every call.+moves recorded keys or changes the stored shape: a bundle recorded under the old+rules then fails naming both versions instead of quietly missing on every call.This module owns the format only. The provider-edge server that produces and-consumes it lives in provider_edge.py (LIT-5745) and the canonical match keys-it computes live in fixture_canonical.py (LIT-5741); streaming chunk fidelity-is a follow-up (LIT-5742). Every interaction file stores the full redacted-request because replay matches on its canonicalized content, and the response-as the raw HTTP status, filtered headers, and base64 body the provider sent.+consumes it lives in provider_edge.py (LIT-5745) and the canonical match keys it+computes live in fixture_canonical.py (LIT-5741). Every interaction file stores+the full redacted request because replay matches on its canonicalized content,+and a response in one of two shapes, told apart by their ``kind`` tag: an+ordinary ``RecordedHttpResponse`` holding one base64 body, or, for a response the+provider streamed, a ``RecordedStreamedResponse`` holding its transfer chunks in+order so replay reproduces the same split points (LIT-5742)."""from __future__ import annotations@@ -26,11 +28,11 @@ import subprocessfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom pathlib import Path-from typing import Final+from typing import Annotated, Final, Literal-from pydantic import BaseModel, JsonValue+from pydantic import BaseModel, Field, JsonValue-BUNDLE_FORMAT_VERSION: Final = 3+BUNDLE_FORMAT_VERSION: Final = 4MAX_BUNDLE_AGE: Final = timedelta(days=7)MANIFEST_FILENAME: Final = "manifest.json"@@ -74,14 +76,38 @@ class RecordedHttpResponse(BaseModel):volatile entries (see provider_edge.py), and the body as base64 so binarypayloads survive JSON."""+ kind: Literal["http"] = "http"status_code: intheaders: dict[str, str]body_b64: str+class RecordedStreamedResponse(BaseModel):+ """A response the provider streamed, kept chunk by chunk instead of buffered.++ ``chunks_b64`` holds one entry per upstream transfer chunk, in order, so replay+ reproduces the split points the provider chose rather than one coalesced body.+ ``truncated`` is None for a stream that reached its terminator and otherwise+ says why it did not, prefixed by which side ended it (``upstream:`` for a+ provider that hung up mid-stream, ``downstream:`` for a proxy that stopped+ reading). Replay behaves the same for any truncation, delivering the recorded+ chunks and then closing; the reason is there for whoever reads the bundle."""++ kind: Literal["streamed"] = "streamed"+ status_code: int+ headers: dict[str, str]+ chunks_b64: list[str]+ truncated: str | None = None+++type RecordedResponse = Annotated[+ RecordedHttpResponse | RecordedStreamedResponse, Field(discriminator="kind")+]++class Interaction(BaseModel):request: RecordedRequest- response: RecordedHttpResponse+ response: RecordedResponsedef slugify(raw: str, *, limit: int = 60) -> str:@@ -128,7 +154,7 @@ class BundleRecorder:root: Path_ordinals: dict[str, int] = field(default_factory=dict)- def record(self, *, test_key: str, request: RecordedRequest, response: RecordedHttpResponse) -> None:+ def record(self, *, test_key: str, request: RecordedRequest, response: RecordedResponse) -> None:slug = slug_for_test(test_key)ordinal = self._ordinals.get(slug, 0)self._ordinals[slug] = ordinal + 1@@ -200,14 +226,27 @@ def _read_manifest(root: Path) -> Manifest | UnreadableBundle:return UnreadableBundle(reason=f"{MANIFEST_FILENAME} is invalid: {exc}")-def check_freshness(root: Path, *, now: datetime) -> BundleFreshness:+def _supported_manifest(root: Path) -> Manifest | UnreadableBundle:+ """The manifest, refused when it was written under a different format version.+ A bundle is atomic (record wipes and rewrites the whole directory and never+ merges), so a foreign version is a hard reject rather than a partial read."""manifest = _read_manifest(root)if isinstance(manifest, UnreadableBundle):return manifestif manifest.format_version != BUNDLE_FORMAT_VERSION:return UnreadableBundle(- reason=f"format_version {manifest.format_version} != supported {BUNDLE_FORMAT_VERSION}"+ reason=(+ f"format_version {manifest.format_version} != supported {BUNDLE_FORMAT_VERSION}; "+ "re-record with E2E_FIXTURE_MODE=record"+ ))+ return manifest+++def check_freshness(root: Path, *, now: datetime) -> BundleFreshness:+ manifest = _supported_manifest(root)+ if isinstance(manifest, UnreadableBundle):+ return manifestrecorded_at = (manifest.recorded_atif manifest.recorded_at.tzinfo is not None@@ -231,7 +270,7 @@ class LoadedBundle:def load_bundle(root: Path) -> LoadedBundle | UnreadableBundle:- manifest = _read_manifest(root)+ manifest = _supported_manifest(root)if isinstance(manifest, UnreadableBundle):return manifestinteractions = {diff --git a/tests/e2e/llm_translation/test_messages_e2e.py b/tests/e2e/llm_translation/test_messages_e2e.pyindex 7f81a5e3946..d43446e4b5a 100644--- a/tests/e2e/llm_translation/test_messages_e2e.py+++ b/tests/e2e/llm_translation/test_messages_e2e.py@@ -33,6 +33,25 @@ class _OptionalMessagesBody(BaseModel):max_tokens: int | None = None+class _MessagesEventDelta(BaseModel):+ text: str = ""+++class _MessagesEventUsage(BaseModel):+ output_tokens: int | None = None+++class _MessagesStreamEvent(BaseModel):+ """One Anthropic SSE event, keeping only what the stream's shape is asserted on.++ ``delta.text`` is populated on ``content_block_delta`` and absent on the+ ``message_delta`` that closes the turn, which is the event carrying ``usage``."""++ type: str+ delta: _MessagesEventDelta | None = None+ usage: _MessagesEventUsage | None = None++ANTHROPIC_BACKEND = "anthropic/claude-haiku-4-5"WEATHER_TOOL = AnthropicCustomTool(@@ -137,13 +156,14 @@ class TestAnthropicMessages:def test_messages_streams_completion(self, endpoints_client: EndpointsClient, resources: ResourceManager) -> None:- """Stays on a live Anthropic deployment in every mode: the edge buffers a- streamed response into one body, so chunk fidelity waits on LIT-5742."""- model, key = self._register(- endpoints_client,- resources,- LiteLLMParamsBody(model=ANTHROPIC_BACKEND, api_key="os.environ/ANTHROPIC_API_KEY"),- )+ """Edge-wired like its non-streaming siblings, so record and replay both+ carry the streamed response.++ Asserts the shape of the event sequence, not just that deltas and a stop+ appeared somewhere in it: the answer arrives across several deltas, and the+ usage event sits between the last of them and ``message_stop``. A replay that+ coalesced the response into one buffered body could not satisfy either."""+ model, key = self._register(endpoints_client, resources)result = endpoints_client.proxy.messages_stream(key,@@ -158,11 +178,35 @@ class TestAnthropicMessages:assert result.is_streaming, f"response was not streamed: {result.headers}"assert not result.stream_error, f"stream errored: {result.stream_error}"assert result.stream_events, "stream produced no SSE events"- assert any("content_block_delta" in event for event in result.stream_events), (- "stream carried no content deltas"++ events = [+ _MessagesStreamEvent.model_validate_json(event) for event in result.stream_events+ ]+ types = [event.type for event in events]+ delta_positions = [+ index for index, event in enumerate(events) if event.type == "content_block_delta"+ ]+ assert len(delta_positions) >= 2, (+ f"stream carried {len(delta_positions)} content deltas, so it was not "+ f"incremental: {types}"+ )+ text = "".join(+ event.delta.text+ for event in events+ if event.type == "content_block_delta" and event.delta is not None)- assert any("message_stop" in event for event in result.stream_events), (- "stream never reached message_stop"+ assert text.strip(), f"content deltas assembled to no text: {result.stream_events[:5]}"++ usage_positions = [+ index+ for index, event in enumerate(events)+ if event.type == "message_delta" and event.usage is not None+ ]+ assert usage_positions, f"stream never reported usage: {types}"+ assert "message_stop" in types, f"stream never reached message_stop: {types}"+ stop_position = types.index("message_stop")+ assert delta_positions[-1] < usage_positions[0] < stop_position, (+ f"usage did not land between the last content delta and message_stop: {types}")@pytest.mark.covers("llm.messages.anthropic.tool_use.nonstream.works")diff --git a/tests/e2e/provider_edge.py b/tests/e2e/provider_edge.pyindex 25a1e8043ed..6cedf633a3e 100644--- a/tests/e2e/provider_edge.py+++ b/tests/e2e/provider_edge.py@@ -19,10 +19,21 @@ headers must never touch disk. An unmatched replay call returns HTTP``REPLAY_MISS_STATUS`` naming the closest recorded interaction, which theproxy relays as a provider error the failing test surfaces.+A response the provider streamed (one whose content type names+``text/event-stream``) is relayed and stored chunk by chunk instead of buffered+(LIT-5742): the edge reads one piece per upstream transfer chunk, writes each+one downstream in chunked framing as it arrives, and records the sequence, so+replay hands the proxy the same number of chunks split in the same places. A+provider that hangs up mid-stream is recorded as the chunks it did deliver plus+a truncation, and replays as those chunks followed by a connection close with no+terminator, which is the same incomplete chunked read the live failure produced+rather than a clean 502 that erases it. Everything else keeps the buffered+shape, byte for byte, framed with a content-length as before.+v1 limits: only the mounts in ``EDGE_MOUNTS`` (SigV4 providers like Bedrock-sign the Host header, so a forwarding edge breaks their signatures), streaming-fidelity is LIT-5742, and CI wiring is LIT-5748. Suites that do not wire the-edge keep hitting providers live in every mode.+sign the Host header, so a forwarding edge breaks their signatures), and CI+wiring is LIT-5748. Suites that do not wire the edge keep hitting providers+live in every mode."""from __future__ import annotations@@ -34,24 +45,34 @@ import hashlibimport reimport threadingfrom collections import deque-from collections.abc import Mapping+from collections.abc import Mapping, Sequence+from contextlib import closingfrom dataclasses import dataclass, fieldfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom itertools import islicefrom pathlib import Pathfrom types import MappingProxyType-from typing import Final, Literal, assert_never+from typing import Final, Generator, Literal, assert_neverfrom urllib.parse import parse_qsl, urlsplitfrom pydantic import JsonValue, TypeAdapter-from e2e_http import NetworkError, RawResponse, forward+from e2e_http import (+ NetworkError,+ StreamChunk,+ StreamHead,+ StreamStep,+ StreamTruncation,+ forward_stream,+)from fixture_bundle import (BundleRecorder,Interaction,LoadedBundle,RecordedHttpResponse,RecordedRequest,+ RecordedResponse,+ RecordedStreamedResponse,UnreadableBundle,UnsafeBundleDir,interaction_filename,@@ -479,11 +500,28 @@ type EdgeBackend = RecordEdge | ReplayEdge@dataclass(frozen=True, slots=True)class EdgeReply:+ """A whole response the edge already holds: written with a content-length."""+status_code: intheaders: dict[str, str]body: bytes+@dataclass(frozen=True, slots=True)+class EdgeStream:+ """A response the edge relays chunk by chunk: written in chunked framing, one+ transfer chunk per step, so the split points reach the proxy intact. Record and+ replay both produce one of these, driven by different step sources, which is+ what makes their framing identical by construction rather than by inspection."""++ status_code: int+ headers: dict[str, str]+ steps: Generator[StreamStep, None, None]+++type EdgeOutcome = EdgeReply | EdgeStream++def _text_reply(status_code: int, message: str) -> EdgeReply:return EdgeReply(status_code=status_code,@@ -492,34 +530,87 @@ def _text_reply(status_code: int, message: str) -> EdgeReply:)-def _reply_from_recorded(response: RecordedHttpResponse) -> EdgeReply:- return EdgeReply(- status_code=response.status_code,- headers=dict(response.headers),- body=base64.b64decode(response.body_b64),- )+def _recorded_steps(+ chunks_b64: Sequence[str], truncated: str | None+) -> Generator[StreamStep, None, None]:+ """Replay's step source: the recorded chunks in recorded order, as fast as the+ socket takes them (inter-chunk delays are deliberately not reproduced), then the+ recorded truncation if the stream ended without a terminator."""+ for chunk in chunks_b64:+ yield StreamChunk(data=base64.b64decode(chunk))+ if truncated is not None:+ yield StreamTruncation(reason=truncated)-def _recorded_response(outcome: RawResponse | NetworkError) -> RecordedHttpResponse:- match outcome:- case RawResponse(status_code=status_code, headers=headers, body=body):- return RecordedHttpResponse(+def _recorded_outcome(response: RecordedResponse) -> EdgeOutcome:+ match response:+ case RecordedHttpResponse(status_code=status_code, headers=headers, body_b64=body_b64):+ return EdgeReply(status_code=status_code,- headers={- name: value- for name, value in headers.items()- if name not in _RESPONSE_DROPPED_HEADERS- },- body_b64=base64.b64encode(body).decode("ascii"),+ headers=dict(headers),+ body=base64.b64decode(body_b64),)- case NetworkError(message=message):- return RecordedHttpResponse(- status_code=502,- headers={"content-type": "text/plain; charset=utf-8"},- body_b64=base64.b64encode(- f"provider edge could not reach the provider: {message}".encode()- ).decode("ascii"),+ case RecordedStreamedResponse(+ status_code=status_code, headers=headers, chunks_b64=chunks_b64, truncated=truncated+ ):+ return EdgeStream(+ status_code=status_code,+ headers=dict(headers),+ steps=_recorded_steps(chunks_b64, truncated),)+ case _:+ assert_never(response)+++def _filtered_response_headers(headers: Mapping[str, str]) -> dict[str, str]:+ """What the edge stores and serves: the provider's headers minus hop-by-hop and+ volatile entries. Framing headers are in that set, so a stored header can never+ contradict the framing the edge chooses when it serves the response."""+ return {+ name: value for name, value in headers.items() if name not in _RESPONSE_DROPPED_HEADERS+ }+++def _network_error_response(message: str) -> RecordedHttpResponse:+ return RecordedHttpResponse(+ status_code=502,+ headers={"content-type": "text/plain; charset=utf-8"},+ body_b64=base64.b64encode(+ f"provider edge could not reach the provider: {message}".encode()+ ).decode("ascii"),+ )+++def _buffered_response(+ status_code: int, headers: Mapping[str, str], body: bytes+) -> RecordedHttpResponse:+ return RecordedHttpResponse(+ status_code=status_code,+ headers=_filtered_response_headers(headers),+ body_b64=base64.b64encode(body).decode("ascii"),+ )+++def _streamed_response(+ status_code: int, headers: Mapping[str, str], chunks: Sequence[bytes], truncated: str | None+) -> RecordedStreamedResponse:+ return RecordedStreamedResponse(+ status_code=status_code,+ headers=_filtered_response_headers(headers),+ chunks_b64=[base64.b64encode(chunk).decode("ascii") for chunk in chunks],+ truncated=truncated,+ )+++def _is_streamed(headers: Mapping[str, str]) -> bool:+ """Whether a response is one to relay incrementally, decided by content type.++ ``transfer-encoding: chunked`` would be the wrong signal: chunking is a+ transport choice providers make freely for ordinary JSON, so keying off it would+ move nearly every recording to the streamed shape for no gain. The content type+ is the header that says "consume this as it arrives", and it is already how the+ harness defines streaming everywhere else."""+ return "text/event-stream" in _header_value(headers, "content-type").lower()def _upstream_url(upstream_base: str, upstream_path: str, query: str) -> str:@@ -527,6 +618,70 @@ def _upstream_url(upstream_base: str, upstream_path: str, query: str) -> str:return f"{url}?{query}" if query else url+def _persist(+ backend: RecordEdge, test_key: str, request: RecordedRequest, response: RecordedResponse+) -> None:+ with backend.lock:+ backend.recorder.record(test_key=test_key, request=request, response=response)+++def _recording_steps(+ backend: RecordEdge, test_key: str, request: RecordedRequest, head: StreamHead+) -> Generator[StreamStep, None, None]:+ """Record mode's step source: hand each upstream chunk downstream as it arrives+ while collecting it, then persist the whole sequence once, under the lock.+ Relaying incrementally keeps record exercising the proxy's incremental parser+ the way a live run does.++ The ``finally`` also covers the proxy hanging up mid-stream, which closes this+ generator: what arrived is still recorded, marked truncated, because recording a+ cut-short stream as a clean one would let a later replay serve a well-terminated+ fraction of the response and pass a test that should have gone red."""+ collected: list[bytes] = []+ truncated: str | None = None+ delivered = False+ try:+ with closing(head.steps) as steps:+ for step in steps:+ match step:+ case StreamChunk(data=data):+ collected.append(data)+ case StreamTruncation(reason=reason):+ truncated = f"upstream: {reason}"+ case _:+ assert_never(step)+ yield step+ delivered = True+ finally:+ if not delivered and truncated is None:+ truncated = f"downstream: relay closed after {len(collected)} chunks"+ _persist(+ backend,+ test_key,+ request,+ _streamed_response(head.status_code, head.headers, collected, truncated),+ )+++def _drain_to_response(head: StreamHead) -> RecordedHttpResponse:+ """A response the detection rule did not call streamed: drain the same step+ iterator, join the pieces, and store today's buffered shape byte for byte. A+ truncation part way through degrades to the synthetic 502 exactly as the eager+ read did, because storing half a JSON body under a content-length as though it+ were whole would be a worse lie than failing."""+ pieces: list[bytes] = []+ with closing(head.steps) as steps:+ for step in steps:+ match step:+ case StreamChunk(data=data):+ pieces.append(data)+ case StreamTruncation(reason=reason):+ return _network_error_response(reason)+ case _:+ assert_never(step)+ return _buffered_response(head.status_code, head.headers, b"".join(pieces))++def _handle_record(backend: RecordEdge,request: RecordedRequest,@@ -536,23 +691,37 @@ def _handle_record(headers: Mapping[str, str],body: bytes | None,timeout: float,-) -> EdgeReply:+) -> EdgeOutcome:+ test_key: Final = current_test_key()forwarded: Final = {name: value for name, value in headers.items() if name.lower() not in _REQUEST_DROPPED_HEADERS}- outcome: Final = forward(method, url, headers=forwarded, body=body, timeout=timeout)- response: Final = _recorded_response(outcome)- with backend.lock:- backend.recorder.record(test_key=current_test_key(), request=request, response=response)- return _reply_from_recorded(response)+ head: Final = forward_stream(method, url, headers=forwarded, body=body, timeout=timeout)+ match head:+ case NetworkError(message=message):+ unreachable: Final = _network_error_response(message)+ _persist(backend, test_key, request, unreachable)+ return _recorded_outcome(unreachable)+ case StreamHead() if _is_streamed(head.headers):+ return EdgeStream(+ status_code=head.status_code,+ headers=_filtered_response_headers(head.headers),+ steps=_recording_steps(backend, test_key, request, head),+ )+ case StreamHead():+ buffered: Final = _drain_to_response(head)+ _persist(backend, test_key, request, buffered)+ return _recorded_outcome(buffered)+ case _:+ assert_never(head)-def _handle_replay(source: ReplaySource, request: RecordedRequest) -> EdgeReply:+def _handle_replay(source: ReplaySource, request: RecordedRequest) -> EdgeOutcome:try:interaction: Final = source.next_interaction(request)except ReplayMiss as miss:return _text_reply(REPLAY_MISS_STATUS, str(miss))- return _reply_from_recorded(interaction.response)+ return _recorded_outcome(interaction.response)def handle_edge_request(@@ -564,7 +733,7 @@ def handle_edge_request(body: bytes | None,*,timeout: float,-) -> EdgeReply:+) -> EdgeOutcome:"""The edge's pure core, one HTTP exchange in and out: resolve the mountprefix, then record (forward + persist) or replay (serve from the bundle).Socket-free so unit tests exercise every branch without a server."""@@ -618,7 +787,7 @@ class _EdgeHandler(BaseHTTPRequestHandler):assert isinstance(edge_server, _EdgeHTTPServer)length: Final = int(self.headers.get("content-length") or "0")body: Final = self.rfile.read(length) if length else None- reply: Final = handle_edge_request(+ outcome: Final = handle_edge_request(edge_server.backend,edge_server.mounts,self.command,@@ -627,6 +796,15 @@ class _EdgeHandler(BaseHTTPRequestHandler):body,timeout=edge_server.forward_timeout,)+ match outcome:+ case EdgeReply():+ self._write_reply(outcome)+ case EdgeStream():+ self._write_stream(outcome)+ case _:+ assert_never(outcome)++ def _write_reply(self, reply: EdgeReply) -> None:self.send_response(reply.status_code)for name, value in reply.headers.items():self.send_header(name, value)@@ -634,6 +812,32 @@ class _EdgeHandler(BaseHTTPRequestHandler):self.end_headers()self.wfile.write(reply.body)+ def _write_stream(self, stream: EdgeStream) -> None:+ """Write a streamed outcome in chunked framing, one transfer chunk per step.++ ``wbufsize`` is 0 on BaseHTTPRequestHandler, so ``wfile`` sends each write+ straight down the socket and no flush is needed. A truncation step ends the+ message without its terminator and closes the connection, which the stdlib+ shuts down write-side first: the proxy sees a graceful close mid-message,+ which is the incomplete chunked read a provider hanging up produces, and not+ the reset that could discard the chunks already in flight."""+ self.send_response(stream.status_code)+ for name, value in stream.headers.items():+ self.send_header(name, value)+ self.send_header("transfer-encoding", "chunked")+ self.end_headers()+ with closing(stream.steps) as steps:+ for step in steps:+ match step:+ case StreamChunk(data=data):+ self.wfile.write(b"%x\r\n%s\r\n" % (len(data), data))+ case StreamTruncation():+ self.close_connection = True+ return+ case _:+ assert_never(step)+ self.wfile.write(b"0\r\n\r\n")+def log_message(self, format: str, *args: object) -> None:"""Silence the per-request stderr line BaseHTTPRequestHandler emits."""diff --git a/tests/e2e/test_fixture_bundle.py b/tests/e2e/test_fixture_bundle.pyindex b49ab565e39..c01d0b34fb5 100644--- a/tests/e2e/test_fixture_bundle.py+++ b/tests/e2e/test_fixture_bundle.py@@ -22,6 +22,7 @@ from fixture_bundle import (Manifest,RecordedHttpResponse,RecordedRequest,+ RecordedStreamedResponse,StaleBundle,UnreadableBundle,UnsafeBundleDir,@@ -186,3 +187,45 @@ class TestRecordAndLoad:slug_for_test("suite/test_a.py::test_one"),slug_for_test("suite/test_b.py::test_two"),}++ def test_a_streamed_response_round_trips_through_the_bundle(self, tmp_path: Path) -> None:+ """LIT-5742: the two response shapes share one file format and are told apart+ by their ``kind`` tag, so a streamed recording comes back with its chunk list+ intact rather than as a buffered response with an empty body."""+ root = tmp_path / "bundle"+ recorder = prepared(root)+ key = "suite/test_mod.py::test_streamed"+ recorder.record(+ test_key=key,+ request=plain_request("/messages"),+ response=RecordedStreamedResponse(+ status_code=200,+ headers={"content-type": "text/event-stream"},+ chunks_b64=["Zmly", "c3Q="],+ truncated="upstream: hung up",+ ),+ )+ loaded = load_bundle(root)+ assert isinstance(loaded, LoadedBundle)+ (interaction,) = loaded.interactions[slug_for_test(key)]+ response = interaction.response+ assert isinstance(response, RecordedStreamedResponse)+ assert response.chunks_b64 == ["Zmly", "c3Q="]+ assert response.truncated == "upstream: hung up"++ def test_load_bundle_rejects_a_foreign_format_version(self, tmp_path: Path) -> None:+ """A bundle is written atomically, so a manifest from another format version+ means every response inside it may have a shape this code cannot read. Loading+ has to refuse it by name, the way the freshness gate does, rather than parse+ what it happens to understand."""+ root = tmp_path / "bundle"+ prepared(root).record(+ test_key="suite/test_mod.py::test_old",+ request=plain_request("/chat"),+ response=plain_response(),+ )+ write_manifest(root, NOW, format_version=BUNDLE_FORMAT_VERSION - 1)+ loaded = load_bundle(root)+ assert isinstance(loaded, UnreadableBundle)+ assert f"format_version {BUNDLE_FORMAT_VERSION - 1}" in loaded.reason+ assert "E2E_FIXTURE_MODE=record" in loaded.reasondiff --git a/tests/e2e/test_provider_edge.py b/tests/e2e/test_provider_edge.pyindex 14a9fd53393..6fe6d3cac0b 100644--- a/tests/e2e/test_provider_edge.py+++ b/tests/e2e/test_provider_edge.py@@ -11,12 +11,20 @@ computed and closest recorded canonical keys (LIT-5741; the pure canonicalizeris pinned in test_fixture_canonical.py). Requests are made through``e2e_http.forward`` so the whole HTTP surface of the edge is exercised; thepure ``handle_edge_request`` core is pinned socket-free alongside.++Streaming fidelity (LIT-5742) is pinned at the transfer layer, because that is+the only layer where it is visible: a chunked provider sends a known list of+transfer chunks, one of which deliberately splits an SSE event mid-token, and a+raw-socket client reads the edge's own reply back as HTTP chunks. Counting SSE+events at the client would prove nothing, since a coalesced body carries the+same events as a chunk-per-event one."""from __future__ import annotationsimport base64import json+import socketimport threadingfrom collections.abc import Generator, Mappingfrom concurrent.futures import ThreadPoolExecutor@@ -36,6 +44,7 @@ from fixture_bundle import (LoadedBundle,RecordedHttpResponse,RecordedRequest,+ RecordedStreamedResponse,load_bundle,prepare_bundle,slug_for_test,@@ -44,6 +53,7 @@ from fixture_mode import current_test_keyfrom provider_edge import (REPLAY_MISS_STATUS,EdgeBackend,+ EdgeReply,ProviderEdge,RecordEdge,ReplayEdge,@@ -116,10 +126,175 @@ def fake_provider() -> Generator[_FakeProvider]:server.server_close()-def provider_url(server: _FakeProvider) -> str:+def provider_url(server: ThreadingHTTPServer) -> str:return f"http://127.0.0.1:{server.server_address[1]}"+STREAM_PATH = "/openai/v1/messages"+STREAM_BODY = json.dumps({"model": "claude", "stream": True}).encode()+MID_EVENT_HEAD = b'data: {"type":"content_bl'+MID_EVENT_TAIL = b'ock_delta","delta":{"text":" two"}}\n\n'+SSE_CHUNKS: tuple[bytes, ...] = (+ b'data: {"type":"content_block_delta","delta":{"text":"one"}}\n\n',+ MID_EVENT_HEAD,+ MID_EVENT_TAIL,+ b'data: {"type":"message_delta","usage":{"output_tokens":7}}\n\n',+ b"data: [DONE]\n\n",+)+JSON_CHUNKS: tuple[bytes, ...] = (b'{"echo":"one",', b'"chunked":true}')+++class _ChunkedProvider(ThreadingHTTPServer):+ """A provider that frames its response as a known list of transfer chunks, each+ flushed on its own, and optionally hangs up part way through without writing the+ terminating chunk. The chunk list is what the recording has to reproduce."""++ daemon_threads = True++ def __init__(+ self,+ bind: tuple[str, int],+ *,+ chunks: tuple[bytes, ...],+ content_type: str,+ abort_after: int | None,+ ) -> None:+ super().__init__(bind, _ChunkedProviderHandler)+ self.chunks = chunks+ self.content_type = content_type+ self.abort_after = abort_after+ self.hits: list[str] = []+++class _ChunkedProviderHandler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def do_POST(self) -> None:+ provider = self.server+ assert isinstance(provider, _ChunkedProvider)+ length = int(self.headers.get("content-length") or "0")+ if length:+ self.rfile.read(length)+ provider.hits.append(f"{self.command} {self.path}")+ self.send_response(200)+ self.send_header("content-type", provider.content_type)+ self.send_header("transfer-encoding", "chunked")+ self.end_headers()+ limit = len(provider.chunks) if provider.abort_after is None else provider.abort_after+ for chunk in provider.chunks[:limit]:+ self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))+ self.wfile.flush()+ if limit < len(provider.chunks):+ self.close_connection = True+ return+ self.wfile.write(b"0\r\n\r\n")+ self.wfile.flush()++ def log_message(self, format: str, *args: object) -> None:+ """Silence the per-request stderr line BaseHTTPRequestHandler emits."""+++@contextmanager+def chunked_provider(+ *,+ chunks: tuple[bytes, ...] = SSE_CHUNKS,+ content_type: str = "text/event-stream",+ abort_after: int | None = None,+) -> Generator[_ChunkedProvider]:+ server = _ChunkedProvider(+ ("127.0.0.1", 0), chunks=chunks, content_type=content_type, abort_after=abort_after+ )+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield server+ finally:+ server.shutdown()+ server.server_close()+++def response_header(head: str, name: str) -> str | None:+ wanted = f"{name.lower()}:"+ for line in head.splitlines()[1:]:+ if line.lower().startswith(wanted):+ return line.split(":", 1)[1].strip()+ return None+++def _read_chunked(sock: socket.socket, buffered: bytes) -> tuple[list[bytes], str]:+ """A chunked body read back one entry per HTTP chunk, plus how the message ended.++ The framing is parsed rather than ``recv`` calls counted, because TCP is free to+ coalesce two chunks into one segment or split one across two, so a read count+ says nothing about how the sender framed the message."""+ chunks: list[bytes] = []+ try:+ while True:+ while b"\r\n" not in buffered:+ piece = sock.recv(65536)+ if not piece:+ return chunks, "truncated"+ buffered += piece+ line, _, buffered = buffered.partition(b"\r\n")+ size = int(line.split(b";")[0], 16)+ if size == 0:+ return chunks, "terminated"+ while len(buffered) < size + 2:+ piece = sock.recv(65536)+ if not piece:+ return chunks, "truncated"+ buffered += piece+ chunks.append(buffered[:size])+ buffered = buffered[size + 2 :]+ except ConnectionResetError:+ return chunks, "reset"+++def _read_fixed(sock: socket.socket, buffered: bytes, length: int) -> tuple[list[bytes], str]:+ while len(buffered) < length:+ piece = sock.recv(65536)+ if not piece:+ return ([buffered] if buffered else []), "truncated"+ buffered += piece+ return ([buffered[:length]] if length else []), "terminated"+++def raw_stream_post(port: int, path: str, body: bytes) -> tuple[str, list[bytes], str]:+ """POST over a raw socket and read the reply at the transfer layer: the response+ head, one entry per HTTP chunk (or the whole body for a content-length reply),+ and how the message ended, ``terminated`` when its terminator arrived,+ ``truncated`` on a graceful close before it, ``reset`` on an abortive one.++ ``call_edge`` goes through ``forward``, which buffers, so it cannot see any of+ this; the streaming tests need the framing itself, so they read the socket."""+ sock = socket.create_connection(("127.0.0.1", port), timeout=15)+ try:+ sock.sendall(+ (+ f"POST {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n"+ f"content-type: application/json\r\ncontent-length: {len(body)}\r\n\r\n"+ ).encode()+ + body+ )+ buffered = b""+ while b"\r\n\r\n" not in buffered:+ piece = sock.recv(65536)+ if not piece:+ break+ buffered += piece+ head_bytes, _, rest = buffered.partition(b"\r\n\r\n")+ head = head_bytes.decode("latin-1")+ if (response_header(head, "transfer-encoding") or "").lower() == "chunked":+ chunks, ending = _read_chunked(sock, rest)+ else:+ chunks, ending = _read_fixed(+ sock, rest, int(response_header(head, "content-length") or 0)+ )+ return head, chunks, ending+ finally:+ sock.close()++@contextmanagerdef running_edge(backend: EdgeBackend, mounts: Mapping[str, str]) -> Generator[ProviderEdge]:running = start_provider_edge(backend, mounts=mounts, bind_host="127.0.0.1")@@ -787,6 +962,207 @@ class TestConcurrentReplay:assert source.leftover_error(current_test_key()) is None+def record_stream(root: Path, *, abort_after: int | None = None) -> tuple[str, list[bytes], str]:+ with chunked_provider(abort_after=abort_after) as provider:+ with running_edge(record_backend(root), {"openai": provider_url(provider)}) as edge:+ return raw_stream_post(edge.port, STREAM_PATH, STREAM_BODY)+++def replay_stream(root: Path) -> tuple[str, list[bytes], str]:+ with running_edge(ReplayEdge(source=replay_source(root)), REPLAY_MOUNTS) as edge:+ return raw_stream_post(edge.port, STREAM_PATH, STREAM_BODY)+++def only_recorded_response(root: Path) -> RecordedHttpResponse | RecordedStreamedResponse:+ files = this_tests_files(root)+ assert len(files) == 1, [file.name for file in files]+ return Interaction.model_validate_json(files[0].read_text(encoding="utf-8")).response+++def recorded_stream(root: Path) -> RecordedStreamedResponse:+ response = only_recorded_response(root)+ assert isinstance(response, RecordedStreamedResponse), response+ return response+++def stream_chunks(response: RecordedStreamedResponse) -> list[bytes]:+ return [base64.b64decode(chunk) for chunk in response.chunks_b64]+++class TestStreamingFidelity:+ """LIT-5742: a streamed response records and replays as the chunk sequence the+ provider actually sent, not as one coalesced body. The unit of fidelity is the+ HTTP transfer chunk, so every assertion here is made at the transfer layer."""++ def test_a_streamed_response_records_its_chunk_boundaries(self, tmp_path: Path) -> None:+ root = tmp_path / "bundle"+ record_stream(root)++ recorded = recorded_stream(root)+ assert recorded.status_code == 200+ assert stream_chunks(recorded) == list(SSE_CHUNKS)+ assert recorded.truncated is None++ def test_replay_reproduces_the_recorded_split_points(self, tmp_path: Path) -> None:+ root = tmp_path / "bundle"+ record_stream(root)++ head, chunks, ending = replay_stream(root)+ assert head.startswith("HTTP/1.1 200 OK")+ assert response_header(head, "transfer-encoding") == "chunked"+ assert response_header(head, "content-type") == "text/event-stream"+ assert len(chunks) > 1+ assert chunks == list(SSE_CHUNKS)+ assert ending == "terminated"++ def test_record_mode_relays_the_stream_chunked_like_replay_will(self, tmp_path: Path) -> None:+ """Record/replay parity at the framing level: what record serves the proxy+ must be what replay serves it later, chunk for chunk."""+ root = tmp_path / "bundle"+ recorded_head, recorded_chunks, recorded_ending = record_stream(root)+ replayed_head, replayed_chunks, replayed_ending = replay_stream(root)++ assert response_header(recorded_head, "transfer-encoding") == "chunked"+ assert recorded_chunks == list(SSE_CHUNKS)+ assert recorded_chunks == replayed_chunks+ assert recorded_ending == replayed_ending == "terminated"+ assert response_header(recorded_head, "transfer-encoding") == response_header(+ replayed_head, "transfer-encoding"+ )++ def test_a_chunk_split_inside_an_event_survives_replay(self, tmp_path: Path) -> None:+ """The anti-tautology test. One provider chunk ends mid-token, so the two+ halves of that SSE event must arrive as two chunks; an implementation that+ joins the body and re-splits it on event boundaries cannot pass this."""+ root = tmp_path / "bundle"+ record_stream(root)++ _, chunks, _ = replay_stream(root)+ split_at = SSE_CHUNKS.index(MID_EVENT_HEAD)+ assert chunks[split_at] == MID_EVENT_HEAD+ assert chunks[split_at + 1] == MID_EVENT_TAIL+ assert b"content_block_delta" not in chunks[split_at]+ assert b"content_block_delta" in chunks[split_at] + chunks[split_at + 1]++ def test_the_usage_chunk_replays_in_its_recorded_position(self, tmp_path: Path) -> None:+ root = tmp_path / "bundle"+ record_stream(root)+ recorded = stream_chunks(recorded_stream(root))++ _, replayed, _ = replay_stream(root)+ usage_positions = [+ index for index, chunk in enumerate(recorded) if b"output_tokens" in chunk+ ]+ assert usage_positions == [+ index for index, chunk in enumerate(replayed) if b"output_tokens" in chunk+ ]+ assert usage_positions == [len(replayed) - 2]+ assert replayed[-1] == SSE_CHUNKS[-1]++ def test_a_mid_stream_upstream_failure_records_the_delivered_chunks_and_the_truncation(+ self, tmp_path: Path+ ) -> None:+ """The provider delivers two chunks and hangs up. The deltas it did send are+ the difference between a stream that died and a request that never streamed,+ so they are recorded, and the recording says the stream never terminated."""+ root = tmp_path / "bundle"+ head, chunks, ending = record_stream(root, abort_after=2)++ assert head.startswith("HTTP/1.1 200 OK")+ assert chunks == list(SSE_CHUNKS[:2])+ assert ending == "truncated"+ recorded = recorded_stream(root)+ assert recorded.status_code == 200+ assert stream_chunks(recorded) == list(SSE_CHUNKS[:2])+ assert recorded.truncated is not None+ assert recorded.truncated.startswith("upstream: ")++ def test_a_truncated_recording_replays_as_a_truncated_stream(self, tmp_path: Path) -> None:+ root = tmp_path / "bundle"+ record_stream(root, abort_after=2)++ head, chunks, ending = replay_stream(root)+ assert head.startswith("HTTP/1.1 200 OK")+ assert response_header(head, "transfer-encoding") == "chunked"+ assert chunks == list(SSE_CHUNKS[:2])+ assert ending == "truncated"++ def test_a_non_streamed_response_keeps_the_buffered_shape(self, tmp_path: Path) -> None:+ """No-churn guard: an ordinary JSON response records and is framed exactly as+ it was before streaming existed."""+ root = tmp_path / "bundle"+ with fake_provider() as provider:+ with running_edge(record_backend(root), {"openai": provider_url(provider)}) as edge:+ head, chunks, ending = raw_stream_post(edge.port, CHAT_PATH, chat_body("hi"))++ response = only_recorded_response(root)+ assert isinstance(response, RecordedHttpResponse)+ assert response_header(head, "transfer-encoding") is None+ assert response_header(head, "content-length") is not None+ assert ending == "terminated"+ assert json_object(b"".join(chunks))["echo"] == chat_body("hi").decode()++ def test_a_chunked_non_sse_response_stays_buffered(self, tmp_path: Path) -> None:+ """Detection keys off the content type, not the transfer encoding: providers+ chunk ordinary JSON freely, and treating that as streamed would move nearly+ every recording to the chunk-list shape for no gain."""+ root = tmp_path / "bundle"+ with chunked_provider(chunks=JSON_CHUNKS, content_type="application/json") as provider:+ with running_edge(record_backend(root), {"openai": provider_url(provider)}) as edge:+ head, chunks, _ = raw_stream_post(edge.port, CHAT_PATH, chat_body("hi"))++ response = only_recorded_response(root)+ assert isinstance(response, RecordedHttpResponse)+ assert base64.b64decode(response.body_b64) == b"".join(JSON_CHUNKS)+ assert response_header(head, "transfer-encoding") is None+ assert b"".join(chunks) == b"".join(JSON_CHUNKS)++ def test_replay_of_a_stream_makes_no_provider_connection(self, tmp_path: Path) -> None:+ root = tmp_path / "bundle"+ with chunked_provider() as provider:+ with running_edge(record_backend(root), {"openai": provider_url(provider)}) as edge:+ raw_stream_post(edge.port, STREAM_PATH, STREAM_BODY)+ hits_after_record = list(provider.hits)+ with running_edge(+ ReplayEdge(source=replay_source(root)), {"openai": provider_url(provider)}+ ) as edge:+ _, chunks, ending = raw_stream_post(edge.port, STREAM_PATH, STREAM_BODY)+ assert provider.hits == hits_after_record == ["POST /v1/messages"]+ assert chunks == list(SSE_CHUNKS)+ assert ending == "terminated"++ def test_concurrent_streams_each_record_their_own_chunks(self, tmp_path: Path) -> None:+ """The edge relays streams on concurrent threads and each one takes the+ recorder lock once, at the end, so neither recording loses or borrows a chunk+ from the other."""+ root = tmp_path / "bundle"+ bodies = [+ json.dumps({"model": "claude", "stream": True, "n": index}).encode()+ for index in range(2)+ ]+ barrier = threading.Barrier(len(bodies))+ with chunked_provider() as provider:+ with running_edge(record_backend(root), {"openai": provider_url(provider)}) as edge:++ def consume(body: bytes) -> tuple[list[bytes], str]:+ barrier.wait()+ _, chunks, ending = raw_stream_post(edge.port, STREAM_PATH, body)+ return chunks, ending++ with ThreadPoolExecutor(max_workers=len(bodies)) as executor:+ served = list(executor.map(consume, bodies))++ assert served == [(list(SSE_CHUNKS), "terminated")] * len(bodies)+ files = this_tests_files(root)+ assert len(files) == len(bodies)+ for file in files:+ response = Interaction.model_validate_json(+ file.read_text(encoding="utf-8")+ ).response+ assert isinstance(response, RecordedStreamedResponse), response+ assert stream_chunks(response) == list(SSE_CHUNKS)++class TestHandleEdgeRequestPure:def test_unknown_mount_404s_naming_the_known_mounts(self, tmp_path: Path) -> None:root = tmp_path / "bundle"@@ -800,6 +1176,7 @@ class TestHandleEdgeRequestPure:b"{}",timeout=1.0,)+ assert isinstance(reply, EdgeReply)assert reply.status_code == 404assert b"unknown provider mount 'bedrock'" in reply.bodyassert b"anthropic, openai" in reply.body@@ -824,6 +1201,7 @@ class TestHandleEdgeRequestPure:json.dumps({"prompt": "x"}).encode(),timeout=1.0,)+ assert isinstance(reply, EdgeReply)assert reply.status_code == 201assert reply.body == b"ok"assert reply.headers == {"x-upstream": "fake"}