mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
fix(openai): treat a stream cut before its finish as an upstream failure (#20)
An OpenAI-compatible stream that ended with neither a finish_reason nor [DONE] counted as a finished answer. When the d1 model server died mid-reply, the gateway sent the client an empty stream with no finish_reason, and the smart router did not try its next tier. forwardStream now returns errStreamTruncated for such a stream, wrapped in errUpstream. Before any output reaches the client, the request fails over or escalates to the next tier. After output, the client gets an error event and no [DONE]. A stream with [DONE] but no finish_reason keeps its old behaviour.
This commit is contained in:
@@ -1930,6 +1930,14 @@ never a second candidate to try.
|
||||
- **Never mid-stream**: failover only happens while nothing has reached
|
||||
the client yet. Once the first byte of a response is written, status
|
||||
and body are committed and the request is never retried elsewhere.
|
||||
- **Cut streams fail**: an OpenAI-compatible stream that ends with neither
|
||||
a `finish_reason` nor `data: [DONE]` (for example, the model server died
|
||||
mid-reply) counts as an upstream failure, not a finished answer. Before
|
||||
any output it fails over like any other failure. After output, the
|
||||
client gets an error event instead of `[DONE]`: on `/v1/chat/completions`
|
||||
`data: {"error":{"message":"upstream stream ended before the response
|
||||
finished","type":"server_error"}}`, and on `/v1/messages` an Anthropic
|
||||
`event: error`.
|
||||
- **Health signals, kept separate**: the discovery-endpoint health
|
||||
surfaced on the admin dashboard is an ordering hint only — a provider
|
||||
whose `/v1/models` is unhealthy is tried later, never skipped outright,
|
||||
|
||||
@@ -280,8 +280,11 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
|
||||
finish := ""
|
||||
hasOutput := false
|
||||
|
||||
sawDone := false
|
||||
|
||||
err := readSSE(body, func(ev sseEvent) error {
|
||||
if string(ev.data) == sseDoneMarker {
|
||||
sawDone = true
|
||||
sw.writeDone()
|
||||
return nil
|
||||
}
|
||||
@@ -306,6 +309,9 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
|
||||
}
|
||||
return sw.writeData(ev.data)
|
||||
})
|
||||
if err == nil && !sawDone && finish == "" {
|
||||
err = errStreamTruncated
|
||||
}
|
||||
if err != nil {
|
||||
// u carries whatever usage was already captured before the stream
|
||||
// broke — a usage chunk that arrived, then a dropped connection,
|
||||
|
||||
@@ -115,6 +115,10 @@ func readAllLimited(r io.Reader, contentLength, limit int64) ([]byte, error) {
|
||||
// with a non-2xx status.
|
||||
var errUpstream = errors.New("llmgateway: upstream request failed")
|
||||
|
||||
// errStreamTruncated marks an upstream event stream that ended with neither a
|
||||
// finish_reason nor [DONE], as when the model server dies mid-reply.
|
||||
var errStreamTruncated = errors.New("stream ended without finish_reason or [DONE]")
|
||||
|
||||
// errRequestBuildFailed marks an upstreamJSON failure that happened
|
||||
// before any network I/O — http.NewRequestWithContext rejected the
|
||||
// method or URL. It is chained alongside errUpstream (Go's multi-%w), so
|
||||
|
||||
@@ -1309,6 +1309,9 @@ func midStreamErrorMessage(err error, providerName string) (msg, errType string,
|
||||
if _, isRTerr := err.(*responseTranslationError); isRTerr {
|
||||
return "failed to translate provider response", "server_error", true
|
||||
}
|
||||
if errors.Is(err, errStreamTruncated) {
|
||||
return "upstream stream ended before the response finished", "server_error", true
|
||||
}
|
||||
return "upstream connection error", "server_error", true
|
||||
}
|
||||
|
||||
|
||||
@@ -84,9 +84,10 @@ func TestUsageFinishLengthStream(t *testing.T) {
|
||||
func TestUsageFinishLengthStreamCutShortSetsNothing(t *testing.T) {
|
||||
t.Parallel()
|
||||
cut := "data: {\"choices\":[{\"delta\":{\"content\":\"hel\"},\"finish_reason\":null}]}\n\n"
|
||||
length, empty := streamFlags(t, "openai", cut)
|
||||
assert.False(t, length)
|
||||
assert.False(t, empty, "a stream without a finish reason is a cut connection, not an empty answer")
|
||||
u, err := (&openaiAdapter{}).forwardStream(httptest.NewRecorder(), strings.NewReader(cut), false)
|
||||
require.ErrorIs(t, err, errStreamTruncated, "a stream without a finish reason is a cut connection")
|
||||
assert.False(t, u.finishLength)
|
||||
assert.False(t, u.emptyOutput, "a cut connection is not an empty answer")
|
||||
}
|
||||
|
||||
func jsonResponse(body string) *http.Response {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package traefikllmgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const truncatedContentChunk = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hi\"}}]}\n\n"
|
||||
|
||||
func TestOpenAIForwardStream_Truncation(t *testing.T) {
|
||||
const finishChunk = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n"
|
||||
const done = "data: [DONE]\n\n"
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
truncated bool
|
||||
}{
|
||||
{"finish and DONE", truncatedContentChunk + finishChunk + done, false},
|
||||
{"finish without DONE", truncatedContentChunk + finishChunk, false},
|
||||
{"DONE without finish", truncatedContentChunk + done, false},
|
||||
{"neither finish nor DONE", truncatedContentChunk, true},
|
||||
{"no events at all", "", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
_, err := (&openaiAdapter{}).forwardStream(rec, strings.NewReader(tt.body), false)
|
||||
if !tt.truncated {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, errStreamTruncated), "err = %v, want errStreamTruncated", err)
|
||||
assert.True(t, errors.Is(err, errUpstream), "a truncated stream is an upstream failure")
|
||||
assert.NotContains(t, rec.Body.String(), "[DONE]", "a truncated stream must not look finished")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// truncatingServer answers with an event-stream that ends cleanly after
|
||||
// chunks, with no finish_reason and no [DONE].
|
||||
func truncatingServer(chunks ...string) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
for _, c := range chunks {
|
||||
_, _ = w.Write([]byte(c))
|
||||
}
|
||||
w.(http.Flusher).Flush()
|
||||
}))
|
||||
}
|
||||
|
||||
func TestHandleChat_TruncatedStreamBeforeOutput_FailsOver(t *testing.T) {
|
||||
var betaCalls int64
|
||||
alphaSrv := truncatingServer()
|
||||
defer alphaSrv.Close()
|
||||
betaSrv := countingServer(http.StatusOK, successRespBody, &betaCalls)
|
||||
defer betaSrv.Close()
|
||||
|
||||
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), twoProviderFailoverConfig(alphaSrv, betaSrv), "llmgw")
|
||||
require.NoError(t, err)
|
||||
|
||||
body := map[string]any{"model": "shared", "stream": true, "messages": []any{}}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.Equal(t, int64(1), atomic.LoadInt64(&betaCalls), "an empty truncated stream must fail over")
|
||||
assert.Contains(t, rec.Body.String(), "chatcmpl-ok", "the client gets beta's answer")
|
||||
}
|
||||
|
||||
func TestHandleChat_TruncatedStreamAfterOutput_EndsWithErrorEvent(t *testing.T) {
|
||||
var betaCalls int64
|
||||
alphaSrv := truncatingServer(truncatedContentChunk)
|
||||
defer alphaSrv.Close()
|
||||
betaSrv := countingServer(http.StatusOK, successRespBody, &betaCalls)
|
||||
defer betaSrv.Close()
|
||||
|
||||
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), twoProviderFailoverConfig(alphaSrv, betaSrv), "llmgw")
|
||||
require.NoError(t, err)
|
||||
|
||||
body := map[string]any{"model": "shared", "stream": true, "messages": []any{}}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
|
||||
|
||||
const wantErrEvent = "data: {\"error\":{\"message\":\"upstream stream ended before the response finished\",\"type\":\"server_error\"}}\n\n"
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.Equal(t, truncatedContentChunk+wantErrEvent, rec.Body.String())
|
||||
assert.Equal(t, int64(0), atomic.LoadInt64(&betaCalls), "no failover once output reached the client")
|
||||
}
|
||||
|
||||
func TestHandleMessages_Stream_TruncatedUpstreamEndsWithErrorEvent(t *testing.T) {
|
||||
srv := sseUpstream(t, nil, nil, "data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"partial\"}}]}\n\n")
|
||||
defer srv.Close()
|
||||
gw := newMessagesTestGateway(t, "", srv.URL)
|
||||
|
||||
evs := parseAnthropicEvents(t, serveMessages(t, gw, streamMessagesBody("gpt-test")).Body.String())
|
||||
names := eventNames(evs)
|
||||
if len(names) == 0 || names[len(names)-1] != "error" {
|
||||
t.Fatalf("events = %v, want the stream to end with an error event", names)
|
||||
}
|
||||
for _, n := range names {
|
||||
if n == "message_stop" {
|
||||
t.Fatal("a truncated stream must not send message_stop")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouter_TruncatedStreamBeforeOutputEscalates(t *testing.T) {
|
||||
alphaSrv := truncatingServer()
|
||||
defer alphaSrv.Close()
|
||||
a := &routerBackend{srv: alphaSrv}
|
||||
b := newRouterBackend(200, successRespBody)
|
||||
c := newRouterBackend(200, successRespBody)
|
||||
defer closeBackends(b, c)
|
||||
h, _ := buildRouterGateway(t, routerTestConfig(a, b, c, threeTiers()))
|
||||
|
||||
rec := routerChat(t, h, routerName, "hi", map[string]any{"stream": true})
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.Contains(t, rec.Body.String(), "chatcmpl-ok", "the next tier answers")
|
||||
assert.Equal(t, int64(1), b.count()+c.count(), "exactly one later tier serves the request")
|
||||
}
|
||||
Reference in New Issue
Block a user