mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): give the OpenAI Responses error frame its type discriminator (#4331)
## Description
The buffered-CCR path relays a failure that lands *after* the SSE commit
as a typed stream error, so the client can still read it as a rate limit
and fire its backoff. The OpenAI variant of that frame is malformed for
the Responses API.
`OPENAI_ERROR_FORMAT.sse_event` emits a chat-completions shaped frame:
```
data: {"error": {"message": "...", "type": "rate_limit_error"}}
```
There is no top-level `type`. The Responses API addresses every stream
event by a `type` discriminator, so a client parsing the stream as
Responses events cannot read that frame as an error event at all — it
reads it as a malformed event.
Zed is a concrete case. Its Responses stream parser
(`crates/open_ai/src/responses.rs`) is a `#[serde(tag = "type")]` enum,
so the frame fails to deserialize and the client reports the *parse*
failure instead of the upstream error, taking the whole agent turn with
it:
```
ERROR [open_ai::responses] Failed to parse OpenAI responses stream event: `missing field `type` at line 1 column 120`
ERROR [agent::thread] Turn execution failed: missing field `type` at line 1 column 120
ERROR [agent] Error in model response stream: missing field `type` at line 1 column 120
```
The column offset identifies the frame exactly — 120 for
`rate_limit_error`, 116 for `server_error` — because it is the byte
length of the JSON payload.
The Anthropic twin of the same wrapper already emits `event: error` plus
a top-level `type`, and the Anthropic envelope has no such discriminator
to begin with, which is why it never needed one:
```python
ANTHROPIC_ERROR_FORMAT = BufferedCCRErrorFormat(
...
sse_event=lambda error_type, message: (
"event: error\ndata: "
+ json.dumps({"type": "error", "error": {"type": error_type, "message": message}})
+ "\n\n"
).encode(),
```
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `headroom/proxy/buffered_ccr_response.py` —
`OPENAI_ERROR_FORMAT.sse_event` now emits the Responses shape: `event:
error` plus `{"type": "error", "error": {...}}`. The error type and
message are unchanged, so clients reading the nested `error` object (the
OpenAI SDK among them) keep working, and clients reading the top-level
`type` now get one.
- `tests/test_buffered_ccr_grace_window.py` — new test asserting the
OpenAI late-failure frame carries the `type` discriminator and names its
event. The existing
`test_openai_late_failures_use_the_openai_error_shape` still passes
unchanged, which pins the nested `error` object.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed
### Test Output
```text
$ python -m pytest tests/test_buffered_ccr_grace_window.py tests/test_buffered_ccr_salvage.py \
tests/test_buffered_ccr_accept_header.py tests/test_anthropic_buffered_ccr_usage.py \
tests/test_ccr_buffered_stream_signed_thinking.py tests/test_proxy/test_openai_responses_ccr.py -q
collected 50 items
tests/test_buffered_ccr_grace_window.py .......... [ 20%]
tests/test_buffered_ccr_salvage.py ........ [ 36%]
tests/test_buffered_ccr_accept_header.py ...... [ 48%]
tests/test_anthropic_buffered_ccr_usage.py ....... [ 62%]
tests/test_ccr_buffered_stream_signed_thinking.py .......... [ 82%]
tests/test_proxy/test_openai_responses_ccr.py ......... [100%]
============================= 50 passed in 20.82s ==============================
$ python -m pytest tests/ -q -k "(responses or buffered or ccr) and not langchain" \
--ignore=tests/test_integrations/langchain
== 1311 passed, 41 skipped, 15643 deselected, 4 warnings in 162.29s (0:02:42) ==
$ ruff check headroom/proxy/buffered_ccr_response.py tests/test_buffered_ccr_grace_window.py
All checks passed!
$ ruff format --check headroom/proxy/buffered_ccr_response.py tests/test_buffered_ccr_grace_window.py
2 files already formatted
$ mypy headroom/proxy/buffered_ccr_response.py
Success: no issues found in 1 source file
```
The new test fails on the parent commit and passes on this one:
```text
$ git stash push headroom/proxy/buffered_ccr_response.py && pytest tests/test_buffered_ccr_grace_window.py -q
collected 10 items
tests/test_buffered_ccr_grace_window.py .........F [100%]
FAILED tests/test_buffered_ccr_grace_window.py::test_openai_late_failure_carries_a_responses_type_discriminator
E AssertionError: the error frame must name its event
E assert b'event: error\n' in b': ping\n\ndata: {"error": {"message": "too many", "type": "rate_limit_error"}}\n\n'
```
## Real Behavior Proof
- Environment: macOS 14 (arm64), Python 3.13.16, `headroom` 0.41.0 at
commit `4c7acba` (upstream `main`), client Zed 1.24.4, upstream Ollama
`0.40.7` serving Ollama Cloud models through the proxy at
`http://127.0.0.1:8787`.
- the live run below points the proxy at a local stand-in upstream that
answers `429` after a delay, so the failure lands after the proxy has
committed SSE
- client user agent:
`Zed/1.24.4+stable.376.aed37547d8543000494fb69101c05daec5891068 (macos;
aarch64)`
- Exact command / steps: run the proxy with a client that speaks the
OpenAI Responses API and drives a turn large enough to exceed the
buffered-CCR grace window (`buffered_ccr_grace_seconds`, default 5.0),
let the upstream fail with a 429 after the SSE commit, then read the SSE
frames the proxy emits.
1. Run the proxy with a client that speaks the OpenAI Responses API.
2. Drive a turn large enough to exceed the buffered-CCR grace window.
3. Let the upstream fail with a 429 after the SSE commit.
4. Read the SSE frames the proxy emits.
- Observed result: a live proxy run before and after the change, and the
two captured frames fed through Zed v1.24.4's own Responses parser.
- live proxy, before this change:
```text
: ping
data: {"error": {"message": "An error occurred while processing your
request. Please try again.", "type": "rate_limit_error"}}
```
The client's Responses parser rejects the frame:
```text
ERROR [open_ai::responses] Failed to parse OpenAI responses stream
event: `missing field `type` at line 1 column 120`
ERROR [agent::thread] Turn execution failed: missing field `type` at
line 1 column 120
```
The error type and the message are both in the payload; the client never
gets to read them.
- live proxy, after this change:
```text
: ping
event: error
data: {"type": "error", "error": {"type": "rate_limit_error", "message":
"An error occurred while processing your request. Please try again."}}
```
A client that dispatches on the top-level `type` reads it as an error
event, and one that reads the nested `error` object still finds the same
type and message.
- proxy log for that run: `CCR: buffered upstream returned 429 after the
response was committed as SSE; relaying it as a typed stream error`
- the two captured frames fed through Zed v1.24.4's own Responses parser
(`#[serde(tag = "type")]` enum, `crates/open_ai/src/responses.rs`):
```text
CAPTURED BEFORE -> ERR missing field `type` at line 1 column 70
CAPTURED AFTER -> OK type=Some("rate_limit_error") code=None
message="upstream says no"
```
The "before" column offset is the byte length of that frame, which is
the same mechanism behind the `column 120` / `column 116` offsets in the
production log.
- Not tested: no live Zed session was used to confirm the turn now
completes rather than failing; the client-side behaviour is established
by running the two captured frames through Zed's own parser definition,
reproduced above.
- The client-side symptom is tracked upstream at
zed-industries/zed#63825, which reports the same parse failure for a
non-conforming error envelope.
- No live Zed session was used to confirm the turn now completes rather
than failing; the upstream issue for the client-side symptom is
zed-industries/zed#63825, which reports the same parse failure for a
non-conforming error envelope.
## Runtime Rollout Safety
- Rollout-managed feature(s): none — this is a wire-format fix on an
error path that is currently broken.
- Minimum rollout channel: next patch release.
- Stable/default behavior changed: the OpenAI late-failure SSE frame
only. The nested `error` object, its `type` and `message` are unchanged;
the pre-commit JSON body (`json_body`) is unchanged.
- Kill switch / disable path: `--no-ccr-response-handling` bypasses
response buffering entirely, so the frame is never emitted.
- Unsafe override required: none.
- Qualification impact: none.
- Rollback path: revert this commit.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
### Maintainer current-main requalification
Exact head `de2bfa50bf1cc2c71e1e47ef0810beaa45f6a6f8`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.
Requalified de2bfa50bf after clean
synchronization with upstream main
c01cf07d94. No contributor protocol logic
changed. All 10 buffered-grace tests pass; changed-file Ruff lint,
formatting and main-relative whitespace checks pass. Local tests use the
freshly built current-main native DLL, not a new branch-specific build.
The existing Responses-schema finding still reproduces:
OPENAI_ERROR_FORMAT.sse_event emits a nested error envelope with
type=error; ResponseErrorEvent.model_validate reports missing top-level
message and sequence_number. Please implement endpoint-specific
Responses error formatting and schema-level coverage while preserving
Chat Completions behavior. The author's delayed-429 capture addresses
the earlier runtime-proof concern and is not the remaining hold. Hosted
checks are handled by maintainers; no contributor CI action requested.
Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.
### Maintainer current-main requalification
Exact head `2e88df461e5f33968aca816edc66a17bb792b020`, upstream main
`0ddaa56c21cdc01c4774391fdcc69e987ecc4e5c`.
Clean integration with upstream/main
0ddaa56c21. All 85 integration patches
exactly match the prior-reviewed c01cf07d9 main-to-current-main delta
after diff-location normalization; contributor error-frame policy is
unchanged. Fresh buffered-grace and incoming Vertex/backend/CLI tests:
168 passed, 11 skipped, 1 warning. Forty-five changed main Python files
pass Ruff lint/format; offline lock and whitespace pass.
Existing schema finding freshly reproduces with OpenAI2.41.0
ResponseErrorEvent.model_validate: emitted frame has type=error with
nested error object but is missing top-level message and
sequence_number. Supply endpoint-specific Responses error formatting and
schema-level regression coverage while preserving Chat Completions
behavior. The author's delayed-429 proxy capture and Zed-parser
demonstration address the earlier after-fix runtime-evidence concern;
they are not the remaining blocker. Current author/Devin discussion
read. Static source/test scope review found no unrelated
execution/workflow/dependency change; flagged inherited
workflow-validation job is excluded by unchanged workflow paths.
Complete native input-set/hash and DLL checksum verified before reuse;
no fresh build or live Zed/provider claim. No contributor correctness
rewrite or inherited-main blame. Maintainers handle exact-head checks;
nothing merged.
Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.
---------
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
@@ -42,7 +42,7 @@ import asyncio
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("headroom.proxy")
|
||||
@@ -104,6 +104,26 @@ def _openai_error_type(status: int) -> str:
|
||||
}.get(status, "server_error")
|
||||
|
||||
|
||||
def _openai_responses_error_type(status: int) -> str:
|
||||
"""Map a status onto the error-code vocabulary of the Responses API.
|
||||
|
||||
``ResponseErrorEvent.code`` is a free-form string, but the values clients
|
||||
and OpenAI's docs use are this set -- the same vocabulary as
|
||||
``headroom/backends/litellm.py``'s ``_OPENAI_ERROR_TYPES``. A 429 is
|
||||
``rate_limit_exceeded``, not Chat Completions' ``rate_limit_error``.
|
||||
"""
|
||||
|
||||
return {
|
||||
400: "invalid_request_error",
|
||||
401: "invalid_api_key",
|
||||
403: "permission_error",
|
||||
404: "model_not_found",
|
||||
413: "invalid_request_error",
|
||||
422: "invalid_request_error",
|
||||
429: "rate_limit_exceeded",
|
||||
}.get(status, "server_error")
|
||||
|
||||
|
||||
ANTHROPIC_ERROR_FORMAT = BufferedCCRErrorFormat(
|
||||
provider="anthropic",
|
||||
json_body=lambda message: json.dumps(
|
||||
@@ -119,6 +139,8 @@ ANTHROPIC_ERROR_FORMAT = BufferedCCRErrorFormat(
|
||||
heartbeat=b'event: ping\ndata: {"type":"ping"}\n\n',
|
||||
)
|
||||
|
||||
# Chat Completions' error envelope: the nested OpenAI ``error`` object and
|
||||
# nothing else. The Responses stream has its own, event-typed frame below.
|
||||
OPENAI_ERROR_FORMAT = BufferedCCRErrorFormat(
|
||||
provider="openai",
|
||||
json_body=lambda message: json.dumps(
|
||||
@@ -133,6 +155,51 @@ OPENAI_ERROR_FORMAT = BufferedCCRErrorFormat(
|
||||
heartbeat=b": ping\n\n",
|
||||
)
|
||||
|
||||
# The Responses API is event-typed: every frame carries a top-level ``type``
|
||||
# discriminator, and an error frame without one is not a valid
|
||||
# ``ResponseErrorEvent``. Zed, for one, parses the stream through a
|
||||
# ``#[serde(tag = "type")]`` enum and fails the whole turn with
|
||||
# "missing field `type`" instead of surfacing the error.
|
||||
#
|
||||
# This is a separate format rather than a change to OPENAI_ERROR_FORMAT above:
|
||||
# the shared frame can only satisfy one endpoint, and Chat Completions still
|
||||
# expects the nested-only envelope.
|
||||
#
|
||||
# ``sequence_number`` is mandatory on ``ResponseErrorEvent``. It is synthetic
|
||||
# here because this frame is the first data event on a connection the proxy
|
||||
# has already committed as SSE: no upstream event was forwarded, so there is
|
||||
# no sequence to continue.
|
||||
#
|
||||
# The nested ``error`` object is kept alongside the flat fields because
|
||||
# openai-python only raises its typed ``APIError`` for a stream frame that
|
||||
# carries ``error`` (``openai/_streaming.py``); without it the frame is
|
||||
# delivered as a plain event, and callers that catch the exception never see
|
||||
# a failure.
|
||||
OPENAI_RESPONSES_ERROR_FORMAT = replace(
|
||||
OPENAI_ERROR_FORMAT,
|
||||
sse_event=lambda error_type, message: (
|
||||
"event: error\ndata: "
|
||||
+ json.dumps(
|
||||
{
|
||||
"type": "error",
|
||||
"code": error_type,
|
||||
"message": message,
|
||||
"param": None,
|
||||
"sequence_number": 0,
|
||||
"error": {
|
||||
"type": error_type,
|
||||
"code": error_type,
|
||||
"message": message,
|
||||
"param": None,
|
||||
},
|
||||
}
|
||||
)
|
||||
+ "\n\n"
|
||||
).encode(),
|
||||
error_type_for_status=_openai_responses_error_type,
|
||||
)
|
||||
|
||||
|
||||
_GENERIC_FAILURE_MESSAGE = "An error occurred while processing your request. Please try again."
|
||||
|
||||
|
||||
|
||||
@@ -116,6 +116,7 @@ from headroom.proxy.auth_mode import (
|
||||
from headroom.proxy.buffered_ccr_response import (
|
||||
DEFAULT_BUFFERED_CCR_GRACE_SECONDS,
|
||||
OPENAI_ERROR_FORMAT,
|
||||
OPENAI_RESPONSES_ERROR_FORMAT,
|
||||
buffered_ccr_asgi_call,
|
||||
)
|
||||
from headroom.proxy.compression_decision import CompressionDecision
|
||||
@@ -7771,18 +7772,15 @@ class OpenAIHandlerMixin:
|
||||
"handling; failing closed"
|
||||
)
|
||||
|
||||
async def _residual_ccr_error_sse():
|
||||
error_event = {
|
||||
"type": "error",
|
||||
"error": {
|
||||
"message": "Unable to safely complete streamed CCR retrieval.",
|
||||
},
|
||||
}
|
||||
yield f"event: error\ndata: {json.dumps(error_event)}\n\n".encode()
|
||||
|
||||
return StreamingResponse(
|
||||
_residual_ccr_error_sse(),
|
||||
media_type="text/event-stream",
|
||||
# Same split as the Chat twin: a plain JSON error
|
||||
# works on both sides of the commit. The wrapper
|
||||
# turns it into the typed stream event if SSE is
|
||||
# already on the wire.
|
||||
return Response(
|
||||
content=OPENAI_RESPONSES_ERROR_FORMAT.json_body(
|
||||
"Unable to safely complete streamed CCR retrieval."
|
||||
),
|
||||
media_type="application/json",
|
||||
headers=sse_headers,
|
||||
status_code=502,
|
||||
)
|
||||
@@ -7844,7 +7842,7 @@ class OpenAIHandlerMixin:
|
||||
# differs. See headroom/proxy/buffered_ccr_response.py (#3079).
|
||||
_buffered_call = buffered_ccr_asgi_call(
|
||||
operation=operation,
|
||||
fmt=OPENAI_ERROR_FORMAT,
|
||||
fmt=OPENAI_RESPONSES_ERROR_FORMAT,
|
||||
grace_seconds=getattr(
|
||||
self.config,
|
||||
"buffered_ccr_grace_seconds",
|
||||
|
||||
@@ -27,6 +27,7 @@ import pytest
|
||||
from headroom.proxy.buffered_ccr_response import (
|
||||
ANTHROPIC_ERROR_FORMAT,
|
||||
OPENAI_ERROR_FORMAT,
|
||||
OPENAI_RESPONSES_ERROR_FORMAT,
|
||||
buffered_ccr_asgi_call,
|
||||
)
|
||||
|
||||
@@ -310,5 +311,47 @@ async def test_openai_late_failures_use_the_openai_error_shape() -> None:
|
||||
|
||||
assert b": ping" in rec.body, "OpenAI keepalives are SSE comments, not ping events"
|
||||
payload = json.loads(rec.body.split(b"data: ")[-1].strip())
|
||||
assert payload["error"]["type"] == "rate_limit_error"
|
||||
assert payload["error"]["message"] == "too many"
|
||||
assert payload == {"error": {"message": "too many", "type": "rate_limit_error"}}
|
||||
assert b"event:" not in rec.body, "Chat Completions has no event-typed frames"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_responses_late_failure_is_a_valid_response_error_event() -> None:
|
||||
"""The Responses error frame must satisfy ``ResponseErrorEvent``.
|
||||
|
||||
Responses streams are event-typed: clients dispatch on the top-level
|
||||
``type`` and validate the flat ``message`` and ``sequence_number`` fields.
|
||||
Zed, for one, parses the stream through a ``#[serde(tag = "type")]`` enum,
|
||||
so a frame without the discriminator fails to deserialize and the client
|
||||
reports "missing field `type`" instead of the upstream error -- taking the
|
||||
whole agent turn with it.
|
||||
|
||||
Only the Responses endpoint uses this shape; Chat Completions keeps the
|
||||
nested-only envelope in ``OPENAI_ERROR_FORMAT``. The nested ``error``
|
||||
object here is not decoration: openai-python only raises its typed
|
||||
``APIError`` from a stream frame that carries ``error``.
|
||||
"""
|
||||
|
||||
async def produce():
|
||||
await asyncio.sleep(0.3)
|
||||
return _FakeResult(429, b'{"error":{"message":"too many"}}', {})
|
||||
|
||||
rec = await _drive(produce=produce, grace=0.05, fmt=OPENAI_RESPONSES_ERROR_FORMAT)
|
||||
|
||||
assert b"event: error\n" in rec.body, "the error frame must name its event"
|
||||
payload = json.loads(rec.body.split(b"data: ")[-1].strip())
|
||||
|
||||
# Flat fields: the schema-valid ``ResponseErrorEvent``.
|
||||
assert payload["type"] == "error"
|
||||
assert payload["message"] == "too many"
|
||||
assert payload["code"] == "rate_limit_exceeded"
|
||||
assert payload["param"] is None
|
||||
assert payload["sequence_number"] == 0
|
||||
|
||||
# Nested object: keeps openai-python's stream decoder on its APIError path.
|
||||
assert payload["error"] == {
|
||||
"type": "rate_limit_exceeded",
|
||||
"code": "rate_limit_exceeded",
|
||||
"message": "too many",
|
||||
"param": None,
|
||||
}
|
||||
|
||||
@@ -18,10 +18,12 @@ import pytest
|
||||
|
||||
fastapi = pytest.importorskip("fastapi")
|
||||
httpx = pytest.importorskip("httpx")
|
||||
openai = pytest.importorskip("openai")
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch # noqa: E402
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
from openai.types.responses import ResponseErrorEvent # noqa: E402
|
||||
from starlette.requests import Request # noqa: E402
|
||||
|
||||
from headroom.cache.compression_store import reset_compression_store # noqa: E402
|
||||
@@ -48,12 +50,13 @@ def _reset_store():
|
||||
reset_compression_store()
|
||||
|
||||
|
||||
def _make_app():
|
||||
def _make_app(**overrides):
|
||||
config = ProxyConfig(
|
||||
optimize=False,
|
||||
cache_enabled=False,
|
||||
rate_limit_enabled=False,
|
||||
cost_tracking_enabled=False,
|
||||
**overrides,
|
||||
)
|
||||
app = create_app(config)
|
||||
app.dependency_overrides[require_loopback] = lambda: None
|
||||
@@ -546,3 +549,155 @@ async def test_buffered_responses_ccr_pre_keepalive_exception_returns_json_error
|
||||
payload["error"]["message"]
|
||||
== "An error occurred while processing your request. Please try again."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_buffered_responses_ccr_post_commit_error_is_a_valid_response_error_event():
|
||||
"""Past the grace window, a late 429 must arrive as a valid error event.
|
||||
|
||||
The commit already spent the HTTP status, so the failure has to survive as
|
||||
a typed stream error. Responses clients validate that frame against
|
||||
``ResponseErrorEvent`` (flat ``type``/``message``/``sequence_number``), and
|
||||
openai-python additionally requires the nested ``error`` object to raise
|
||||
its typed ``APIError`` instead of handing the frame over as a plain event.
|
||||
"""
|
||||
app = _make_app(buffered_ccr_grace_seconds=0.01)
|
||||
body = {
|
||||
"model": "gpt-5-codex",
|
||||
"input": "please wait",
|
||||
"tools": [_RETRIEVE_TOOL],
|
||||
"stream": True,
|
||||
}
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": json.dumps(body).encode(), "more_body": False}
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"http_version": "1.1",
|
||||
"method": "POST",
|
||||
"scheme": "http",
|
||||
"path": "/v1/responses",
|
||||
"raw_path": b"/v1/responses",
|
||||
"query_string": b"",
|
||||
"headers": [(b"authorization", b"Bearer sk-test")],
|
||||
"server": ("testserver", 80),
|
||||
"client": ("testclient", 123),
|
||||
"root_path": "",
|
||||
}
|
||||
|
||||
with TestClient(app):
|
||||
server = app.state.proxy
|
||||
|
||||
async def delayed_rate_limit(*args, **kwargs): # noqa: ANN002, ANN003
|
||||
await asyncio.sleep(0.05)
|
||||
return httpx.Response(
|
||||
429,
|
||||
json={"error": {"message": "slow down", "type": "rate_limit_error"}},
|
||||
headers={"content-type": "application/json", "retry-after": "1"},
|
||||
request=httpx.Request("POST", "https://api.openai.com/v1/responses"),
|
||||
)
|
||||
|
||||
server._retry_request = delayed_rate_limit
|
||||
response = await server.handle_openai_responses(Request(scope, receive))
|
||||
|
||||
events: list[dict] = []
|
||||
|
||||
async def send(message): # noqa: ANN001
|
||||
events.append(message)
|
||||
|
||||
await response(scope, receive, send)
|
||||
|
||||
start = next(event for event in events if event["type"] == "http.response.start")
|
||||
bodies = b"".join(event["body"] for event in events if event["type"] == "http.response.body")
|
||||
assert start["status"] == 200, "the grace window already committed the status"
|
||||
assert bodies.startswith(b": ping\n\n"), "the heartbeat must open the stream"
|
||||
|
||||
payload = json.loads(bodies.split(b"data: ")[-1].strip())
|
||||
assert payload["type"] == "error"
|
||||
assert payload["code"] == "rate_limit_exceeded"
|
||||
assert payload["message"] == "slow down"
|
||||
assert payload["param"] is None
|
||||
assert payload["sequence_number"] == 0
|
||||
assert payload["error"] == {
|
||||
"type": "rate_limit_exceeded",
|
||||
"code": "rate_limit_exceeded",
|
||||
"message": "slow down",
|
||||
"param": None,
|
||||
}
|
||||
|
||||
event = ResponseErrorEvent.model_validate(payload)
|
||||
assert event.type == "error"
|
||||
assert event.code == "rate_limit_exceeded"
|
||||
assert event.message == "slow down"
|
||||
assert event.sequence_number == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_buffered_responses_ccr_residual_retrieve_call_fails_closed():
|
||||
"""A retrieve call the handler could not resolve must fail closed.
|
||||
|
||||
Same rule as the Chat twin: before the commit the real 502 and a JSON
|
||||
error body are still deliverable, so they win. The wrapper converts the
|
||||
same body into the typed Responses SSE frame if SSE is already on the
|
||||
wire, which the post-commit test covers.
|
||||
"""
|
||||
app = _make_app()
|
||||
url = "https://api.openai.com/v1/responses"
|
||||
body = {
|
||||
"model": "gpt-5-codex",
|
||||
"input": "unresolvable",
|
||||
"tools": [_RETRIEVE_TOOL],
|
||||
"stream": True,
|
||||
}
|
||||
|
||||
delivered = False
|
||||
|
||||
async def receive():
|
||||
# After the body, block instead of replaying http.request: a real
|
||||
# server-side StreamingResponse parks a disconnect listener on this.
|
||||
nonlocal delivered
|
||||
if not delivered:
|
||||
delivered = True
|
||||
return {"type": "http.request", "body": json.dumps(body).encode(), "more_body": False}
|
||||
await asyncio.Event().wait()
|
||||
raise AssertionError("unreachable")
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"http_version": "1.1",
|
||||
"method": "POST",
|
||||
"scheme": "http",
|
||||
"path": "/v1/responses",
|
||||
"raw_path": b"/v1/responses",
|
||||
"query_string": b"",
|
||||
"headers": [(b"authorization", b"Bearer sk-test")],
|
||||
"server": ("testserver", 80),
|
||||
"client": ("testclient", 123),
|
||||
"root_path": "",
|
||||
}
|
||||
|
||||
with TestClient(app):
|
||||
server = app.state.proxy
|
||||
server._retry_request = AsyncMock(return_value=_tool_call_response(url))
|
||||
# Leave the retrieve call unresolved, which is what trips the guard.
|
||||
server.ccr_response_handler.handle_response = AsyncMock(
|
||||
return_value=_tool_call_response(url).json()
|
||||
)
|
||||
|
||||
response = await server.handle_openai_responses(Request(scope, receive))
|
||||
events: list[dict] = []
|
||||
|
||||
async def send(message): # noqa: ANN001
|
||||
events.append(message)
|
||||
|
||||
await response(scope, receive, send)
|
||||
|
||||
start = next(event for event in events if event["type"] == "http.response.start")
|
||||
assert start["status"] == 502
|
||||
assert dict(start["headers"])[b"content-type"] == b"application/json"
|
||||
bodies = b"".join(event["body"] for event in events if event["type"] == "http.response.body")
|
||||
payload = json.loads(bodies)
|
||||
assert payload["error"]["type"] == "server_error"
|
||||
assert payload["error"]["code"] == "proxy_error"
|
||||
assert payload["error"]["message"] == "Unable to safely complete streamed CCR retrieval."
|
||||
|
||||
Reference in New Issue
Block a user