Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions core/changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
- fix: openai - a Responses stream that ends with `[DONE]` but no terminal event (`response.completed`, `response.incomplete`, `response.failed` or `error`) is reported as truncated instead of closing silently (#10287) (thanks [@ahmedabdou14](https://github.com/ahmedabdou14)!)
- fix: stop stripping thinking on prefix binding 400s and forward block_binding to Azure
- [fix]: Anthropic requests send every custom tool `input_schema` with a `"type":"object"` root, which Anthropic requires. A chat function tool whose `parameters` root has no `type` was sent without `input_schema`, and the Responses converter sent such a root without `type`; both were rejected with a 400. A root `anyOf` / `oneOf` / `allOf` is now rewritten into an object schema, as for a typed root, and any other typeless root (`{}`, a bare `properties`, `description` or `$ref` object) gets `"type":"object"` with its other keys kept [@KamilDziemba](https://github.com/KamilDziemba)
- [fix]: Anthropic-compatible responses report stop_reason "stop_sequence" with the matched stop_sequence instead of end_turn/null when Claude (Anthropic or Vertex) stops on a requested stop sequence, in both streaming and non-streaming responses. The matched sequence now survives the Bifrost Responses round trip via an optional stop_sequence field; OpenAI-style "stop" finishes still map to end_turn [@jimseiwert](https://github.com/jimseiwert)
Expand Down
11 changes: 5 additions & 6 deletions core/providers/openai/openai.go
Original file line number Diff line number Diff line change
Expand Up @@ -2629,12 +2629,11 @@ func HandleOpenAIResponsesStreaming(

// The loop returns as soon as a terminal event (completed / incomplete /
// failed / error) arrives, so falling out of it means the body ended without

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (follow-up, not caused by this PR): SendStreamTruncatedError bills what it finds in BifrostContextKeyStreamAccumulatedUsage (core/providers/utils/utils.go:4491), but this Responses loop never sets that key (only the chat paths do, openai.go:741 and :1488), and Responses usage only arrives on response.completed. So a stream truncated after many deltas is logged and billed with zero tokens. Not needed here, but worth an issue: either record usage from response.in_progress / output deltas into that key, or state that truncated Responses streams are unbilled.

// one. A plain io.EOF cannot distinguish that from a healthy close, so
// surface it rather than closing the channel silently — a silent close is
// indistinguishable to the client from a stream that just stopped emitting.
if !providerUtils.SSEStreamEndedOnMarker(sseReader) {
providerUtils.SendStreamTruncatedError(ctx, postHookRunner, responseChan, logger, postHookSpanFinalizer, jsonBody)
}
// one. A Responses stream must end with a terminal event, so this is a
// truncation even when [DONE] arrived. Surface it rather than closing the
// channel silently: with no error and no final chunk, the client and the
// post-hooks never see the request end.
providerUtils.SendStreamTruncatedError(ctx, postHookRunner, responseChan, logger, postHookSpanFinalizer, jsonBody)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this handler is shared by 14 providers' Responses streams (Azure, xAI, Fireworks, OpenRouter, Perplexity, vLLM, Databricks, Bedrock runtime and Mantle, Bedrock Mantle, BytePlus, OpenCode, GitHub Copilot, Baseten), so from this change any of those upstreams that ends a Responses stream with [DONE] and no response.completed now returns a mid-stream event: error (a 502-class upstream connection error) on every streamed request, and an empty [DONE]-only stream becomes a retryable first-chunk error that triggers retries and fallbacks. I agree with the call, and the unit tests in all 13 of those provider packages still pass with it. AGENTS.md (Gotcha 6) asks for this case: "Any change to OpenAI converter logic affects all of them. Always test broadly: make test-core (all providers)." Could you say in the PR body which of these you ran live with Responses streaming, or list the ones you did not, so a self-hosted upstream like vLLM that skips the terminal event is a known risk and not a surprise?

}()

return responseChan, nil
Expand Down
10 changes: 4 additions & 6 deletions core/providers/openai/responseslifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,12 +372,10 @@ func (provider *OpenAIProvider) ResponsesRetrieveStream(ctx *schemas.BifrostCont
providerUtils.ProcessAndSendResponse(ctx, postHookRunner, providerUtils.GetBifrostResponseForStreamResponse(nil, nil, &response, nil, nil, nil), responseChan, postHookSpanFinalizer)
}

// Falling out of the loop means the body ended without a terminal event.
// A plain io.EOF cannot distinguish that from a healthy close, so surface it
// instead of closing the channel silently.
if !providerUtils.SSEStreamEndedOnMarker(sseReader) {
providerUtils.SendStreamTruncatedError(ctx, postHookRunner, responseChan, provider.logger, postHookSpanFinalizer, nil)
}
// Falling out of the loop means the body ended without a terminal event,
// which is a truncation even when [DONE] arrived. Surface it instead of
// closing the channel silently.
providerUtils.SendStreamTruncatedError(ctx, postHookRunner, responseChan, provider.logger, postHookSpanFinalizer, nil)
}()

return responseChan, nil
Expand Down
67 changes: 67 additions & 0 deletions core/providers/openai/streamtruncation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,73 @@ func TestResponsesStreamTruncatedBeforeCompleted(t *testing.T) {
assertTruncationError(t, chunks[len(chunks)-1].BifrostError)
}

// A Responses stream must end with a terminal event. [DONE] alone does not end
// it: without the truncation error, no final chunk or error reaches the client
// or the post-hooks, so the request never looks finished.
func TestResponsesStreamDoneWithoutTerminalEvent(t *testing.T) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const (
created = `data: {"type":"response.created","sequence_number":0,"response":{"id":"r1","object":"response","created_at":1,"model":"repro-model","status":"in_progress"}}` + "\n\n"
delta = `data: {"type":"response.output_text.delta","sequence_number":1,"delta":"partial"}` + "\n\n"
completed = `data: {"type":"response.completed","sequence_number":2,"response":{"id":"r1","object":"response","created_at":1,"model":"repro-model","status":"completed"}}` + "\n\n"
done = "data: [DONE]\n\n"
)
request := &schemas.BifrostResponsesRequest{
Provider: schemas.OpenAI,
Model: "repro-model",
Input: []schemas.ResponsesMessage{{
Type: schemas.Ptr(schemas.ResponsesMessageTypeMessage),
Role: schemas.Ptr(schemas.ResponsesInputMessageRoleUser),
Content: &schemas.ResponsesMessageContent{ContentStr: schemas.Ptr("hi")},
}},
}
streams := map[string]func(*OpenAIProvider) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError){
"create": func(p *OpenAIProvider) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) {
return p.ResponsesStream(newStreamTestContext(), passthroughPostHook, nil, testKey(), request)
},
"retrieve": func(p *OpenAIProvider) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) {
return p.ResponsesRetrieveStream(newStreamTestContext(), passthroughPostHook, nil, testKey(), &schemas.BifrostResponsesRetrieveRequest{Provider: schemas.OpenAI, ResponseID: "r1"})
},
}
for name, open := range streams {
t.Run(name+"/done without terminal event is truncated", func(t *testing.T) {
server := completeSSEServer(t, created+delta+done)
defer server.Close()

stream, bifrostErr := open(newStreamTestProvider(server.URL))
if bifrostErr != nil {
t.Fatalf("stream setup failed: %v", bifrostErr)
}
chunks := collectChunks(t, stream)
if len(chunks) == 0 {
t.Fatal("expected at least the error chunk")
}
assertTruncationError(t, chunks[len(chunks)-1].BifrostError)
})
t.Run(name+"/completed then done ends cleanly", func(t *testing.T) {
server := completeSSEServer(t, created+delta+completed+done)
defer server.Close()

stream, bifrostErr := open(newStreamTestProvider(server.URL))
if bifrostErr != nil {
t.Fatalf("stream setup failed: %v", bifrostErr)
}
chunks := collectChunks(t, stream)
if len(chunks) == 0 {
t.Fatal("expected the stream to emit chunks")
}
for i, chunk := range chunks {
if chunk.BifrostError != nil {
t.Fatalf("chunk %d unexpectedly carried an error: %+v", i, chunk.BifrostError)
}
}
last := chunks[len(chunks)-1].BifrostResponsesStreamResponse
if last == nil || last.Type != schemas.ResponsesStreamResponseTypeCompleted {
t.Fatalf("expected the last chunk to be response.completed, got %+v", last)
}
})
}
}

// Azure/OpenAI Responses can accept a request with HTTP 200, emit lifecycle
// events, and then report a semantic failure in a terminal SSE event. The
// transport status is already committed, so the shared decoder must preserve
Expand Down
18 changes: 18 additions & 0 deletions tests/e2e/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,24 @@ Start the fixture and the isolated gateway as in
make run-provider-harness-test PROVIDER=openai FEATURE="zero provider cost" BASE_URL=http://localhost:8790 ENV_FILE=tmp/content-length-truncation.env.json COMPAT=off DB_VERIFY=0 SKIP_STREAM_CANCEL=1
```

## Responses stream ending with [DONE]

Folder 416 pins that a Responses stream that ends with `[DONE]` and no terminal event
(`response.completed`, `response.incomplete`, `response.failed` or `error`) is reported as
truncated, on create (`POST /v1/responses`) and on retrieve (`GET /v1/responses/{id}?stream=true`).
The fixture model `upstream-responses-done-only` and response id `resp_fixture_done_only` stream
`response.created`, one text delta and `[DONE]`; the client must receive an `error` event saying
the provider closed the stream before a completion marker. `upstream-responses-completed` and
`resp_fixture_completed` add `response.completed` and must end without an error. These cases make
no live provider calls and are skipped unless `providerErrorFixture=1`.

Start the fixture and the isolated gateway as in
[Fixed-length response truncation](#fixed-length-response-truncation), then run:

```bash
make run-provider-harness-test PROVIDER=openai FEATURE="responses done truncation" BASE_URL=http://localhost:8790 ENV_FILE=tmp/content-length-truncation.env.json COMPAT=off DB_VERIFY=0 SKIP_STREAM_CANCEL=1
```

## Provider 5xx failover and 429 retry-hint propagation

These deterministic cases use a local HTTP fixture and an isolated gateway. They make no live
Expand Down
236 changes: 236 additions & 0 deletions tests/e2e/api/collections/provider-harness.json
Original file line number Diff line number Diff line change
Expand Up @@ -372368,6 +372368,242 @@
}
}
]
},
{
"name": "416. Responses stream that ends with [DONE] and no terminal event (responses done truncation) (#10287 / PR #10288)",
"description": "Local fixture regression, no live provider calls. Start provider-error-fixture.mjs and an isolated gateway using provider-error-fixture.config.json; enable providerErrorFixture=1. The fixture streams response.created and one text delta, then [DONE]. Models upstream-responses-done-only (create) and response id resp_fixture_done_only (retrieve stream) never send a terminal event; the client must get an error event saying the provider closed the stream before a completion marker, not a clean end. upstream-responses-completed and resp_fixture_completed add response.completed before [DONE] and must end without an error. Setup and scoped run commands are in tests/e2e/api/README.md under Responses stream ending with [DONE].",
"item": [
{
"name": "416.1 openai openai/upstream-responses-done-only create stream reports truncation (responses done truncation) - #10287",
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"if (pm.variables.get('providerErrorFixture') !== '1') {",
" pm.execution.skipRequest();",
"}"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"var raw = pm.response.text() || '';",
"pm.test('stream starts with the partial output', function () {",
" pm.expect(pm.response.code, 'unexpected status: ' + raw).to.equal(200);",
" pm.expect(pm.response.headers.get('content-type'), raw).to.include('text/event-stream');",
" pm.expect(raw, 'partial output missing: ' + raw).to.include('response.output_text.delta');",
"});",
"pm.test('[DONE] without a terminal event reaches the client as a truncation error', function () {",
" pm.expect(raw, 'truncated stream was accepted as complete: ' + raw).to.include('event: error');",
" pm.expect(raw, 'truncation message missing: ' + raw).to.include('provider closed the stream before sending a completion marker');",
" pm.expect(raw, 'truncated stream must not report a completion: ' + raw).to.not.include('response.completed');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"model\": \"openai/upstream-responses-done-only\",\n \"input\": \"hi\",\n \"max_output_tokens\": 16,\n \"stream\": true\n}"
},
"url": {
"raw": "{{baseUrl}}/v1/responses",
"host": [
"{{baseUrl}}"
],
"path": [
"v1",
"responses"
]
}
}
},
{
"name": "416.2 openai openai/upstream-responses-done-only resp_fixture_done_only retrieve stream reports truncation (responses done truncation) - #10287",
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"if (pm.variables.get('providerErrorFixture') !== '1') {",
" pm.execution.skipRequest();",
"}"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"var raw = pm.response.text() || '';",
"pm.test('stream starts with the partial output', function () {",
" pm.expect(pm.response.code, 'unexpected status: ' + raw).to.equal(200);",
" pm.expect(pm.response.headers.get('content-type'), raw).to.include('text/event-stream');",
" pm.expect(raw, 'partial output missing: ' + raw).to.include('response.output_text.delta');",
"});",
"pm.test('[DONE] without a terminal event reaches the client as a truncation error', function () {",
" pm.expect(raw, 'truncated stream was accepted as complete: ' + raw).to.include('event: error');",
" pm.expect(raw, 'truncation message missing: ' + raw).to.include('provider closed the stream before sending a completion marker');",
" pm.expect(raw, 'truncated stream must not report a completion: ' + raw).to.not.include('response.completed');",
"});"
]
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{baseUrl}}/v1/responses/resp_fixture_done_only?provider=openai&stream=true",
"host": [
"{{baseUrl}}"
],
"path": [
"v1",
"responses",
"resp_fixture_done_only"
],
"query": [
{
"key": "provider",
"value": "openai"
},
{
"key": "stream",
"value": "true"
}
]
}
}
},
{
"name": "416.3 openai openai/upstream-responses-completed create stream ends cleanly (responses done truncation) - #10287",
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"if (pm.variables.get('providerErrorFixture') !== '1') {",
" pm.execution.skipRequest();",
"}"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"var raw = pm.response.text() || '';",
"pm.test('stream with a terminal event ends cleanly', function () {",
" pm.expect(pm.response.code, 'unexpected status: ' + raw).to.equal(200);",
" pm.expect(pm.response.headers.get('content-type'), raw).to.include('text/event-stream');",
" pm.expect(raw, 'partial output missing: ' + raw).to.include('response.output_text.delta');",
" pm.expect(raw, 'terminal event missing: ' + raw).to.include('event: response.completed');",
" pm.expect(raw, 'a complete stream must not carry an error: ' + raw).to.not.include('event: error');",
"});"
]
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"model\": \"openai/upstream-responses-completed\",\n \"input\": \"hi\",\n \"max_output_tokens\": 16,\n \"stream\": true\n}"
},
"url": {
"raw": "{{baseUrl}}/v1/responses",
"host": [
"{{baseUrl}}"
],
"path": [
"v1",
"responses"
]
}
}
},
{
"name": "416.4 openai openai/upstream-responses-completed resp_fixture_completed retrieve stream ends cleanly (responses done truncation) - #10287",
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"if (pm.variables.get('providerErrorFixture') !== '1') {",
" pm.execution.skipRequest();",
"}"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"var raw = pm.response.text() || '';",
"pm.test('stream with a terminal event ends cleanly', function () {",
" pm.expect(pm.response.code, 'unexpected status: ' + raw).to.equal(200);",
" pm.expect(pm.response.headers.get('content-type'), raw).to.include('text/event-stream');",
" pm.expect(raw, 'partial output missing: ' + raw).to.include('response.output_text.delta');",
" pm.expect(raw, 'terminal event missing: ' + raw).to.include('event: response.completed');",
" pm.expect(raw, 'a complete stream must not carry an error: ' + raw).to.not.include('event: error');",
"});"
]
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{baseUrl}}/v1/responses/resp_fixture_completed?provider=openai&stream=true",
"host": [
"{{baseUrl}}"
],
"path": [
"v1",
"responses",
"resp_fixture_completed"
],
"query": [
{
"key": "provider",
"value": "openai"
},
{
"key": "stream",
"value": "true"
}
]
}
}
}
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
"upstream-zero-cost",
"upstream-transcribe-empty",
"upstream-transcribe-newline",
"upstream-responses-done-only",
"upstream-responses-completed",
"gpt-5-pro"
],
"weight": 1
Expand Down
Loading