fix(gateway): account for streamed failures (#573)

This commit is contained in:
TryWorld
2026-10-02 22:42:40 +08:00
committed by GitHub
parent b92513439f
commit e41cacb42a
7 changed files with 187 additions and 10 deletions
+4 -1
View File
@@ -2128,6 +2128,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if spaces != nil {
w.Write(spaces.flush())
}
if sse {
sniff.drain()
}
if sse && r.Context().Err() == nil && !sniff.whole() {
// the upstream died mid-reply, or ended it short of its last
// event: say so in the stream rather than end it as if whole,
@@ -2150,7 +2153,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
return res.StatusCode, failed, true
}
}
return res.StatusCode, "", true
return res.StatusCode, sniff.failed, true
}
// cutMidReply is what a stream whose read failed mid-reply is ended with:
+1 -1
View File
@@ -56,7 +56,7 @@ func endpointOf(r *http.Request, from, to provider.Protocol) string {
// failedWith fills in what a call that failed said, on a usage record.
func failedWith(rec *usage.Record, status int, msg, errType string) {
if status >= 400 {
if status >= 400 || msg != "" {
rec.Error, rec.ErrType = keepMsg(msg), errType
}
}
+23 -2
View File
@@ -23,6 +23,9 @@ type usageSniffer struct {
// ended: the stream's last event went by (message_stop, [DONE],
// response.completed …) or an error that ends it
ended bool
// failed: what an explicit error event said; a terminal event can end
// the stream successfully or with a failure despite its HTTP 200.
failed string
}
func newSniffer(proto provider.Protocol, contentType string) *usageSniffer {
@@ -60,6 +63,10 @@ func (s *usageSniffer) line(line []byte) {
}
if rest, ok := bytes.CutPrefix(line, []byte("event:")); ok && lastEvent(string(bytes.TrimSpace(rest))) {
s.ended = true // the name says so even when the data is too big to read
switch string(bytes.TrimSpace(rest)) {
case "error", "response.failed":
s.failed = "upstream stream failed"
}
}
if rest, ok := bytes.CutPrefix(line, []byte("data:")); ok {
rest = bytes.TrimPrefix(rest, []byte{' '})
@@ -92,8 +99,11 @@ func (s *usageSniffer) parse(b []byte) {
return
}
var t struct {
Type string `json:"type"`
Error any `json:"error"`
Type string `json:"type"`
Error any `json:"error"`
Response struct {
Error any `json:"error"`
} `json:"response"`
}
if s.sse && json.Unmarshal(b, &t) == nil {
switch {
@@ -102,6 +112,17 @@ func (s *usageSniffer) parse(b []byte) {
case t.Type == "":
s.ended = s.ended || t.Error != nil // a Chat stream's error
}
if t.Type == "error" || t.Type == "response.failed" || t.Type == "" && t.Error != nil {
body := b
if t.Type == "response.failed" {
body = nil
if t.Response.Error != nil {
body, _ = json.Marshal(map[string]any{"error": t.Response.Error})
}
}
s.failed = provider.APIError(body, "upstream stream failed")
s.u.ErrType = provider.ErrorType(body)
}
}
switch s.proto {
case provider.Chat:
+120
View File
@@ -0,0 +1,120 @@
package gateway
import (
"context"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// Once text has been sent, an upstream error leaves the HTTP status at
// 200. It is still a failed request wherever the gateway records it.
func TestStreamFailureAccounting(t *testing.T) {
for _, client := range []struct {
name, path, body, failed, completed string
}{
{"native", "/v1/responses", `{"model":"fake/m1","stream":true,"input":"hi"}`, "event: response.failed", "event: response.completed"},
{"translated", "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`, "event: error", "event: message_stop"},
} {
for _, outcome := range []string{"completed", "failed"} {
t.Run(client.name+"/"+outcome, func(t *testing.T) {
fresh(t)
reply := sse(
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"m1","status":"in_progress"}}`,
`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"partial text"}`,
)
const failure = "synthetic stream failure"
if outcome == "failed" {
reply += sse(`event: response.failed` + "\n" + `data: {"type":"response.failed","response":{"id":"r1","status":"failed","error":{"type":"server_error","message":"` + failure + `"}}}`)
} else {
reply += sse(`event: response.completed` + "\n" + `data: {"type":"response.completed","response":{"id":"r1","model":"m1","status":"completed","usage":{"input_tokens":3,"output_tokens":1}}}`)
}
setup(t, provider.Responses, &fake{reply: reply})
s := New()
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", client.path, strings.NewReader(client.body)))
if w.Code != 200 || !strings.Contains(w.Body.String(), "partial text") {
t.Fatalf("stream: %d %s", w.Code, w.Body)
}
failed := outcome == "failed"
if strings.Contains(w.Body.String(), client.failed) != failed || strings.Contains(w.Body.String(), client.completed) == failed {
t.Fatalf("wrong stream ending: %s", w.Body)
}
recent := s.Recent()
state := s.Trace(context.Background(), 0, 0)
records := usage.Load(time.Time{})
if len(recent) != 1 || len(state.Routes) != 1 || len(records) != 1 {
t.Fatalf("recent=%d routes=%d usage=%d, want one each", len(recent), len(state.Routes), len(records))
}
route, record := state.Routes[0], records[0]
if !route.Done || route.Status != 200 || record.Status != 200 || record.RouteID != route.ID {
t.Fatalf("route: %+v; usage: %+v", route, record)
}
wantError, wantErrors := "", 0
if failed {
wantError, wantErrors = failure, 1
}
if recent[0].Error != wantError || route.Error != wantError || record.Error != wantError || record.Failed() != failed {
t.Errorf("errors: recent=%q route=%q usage=%q failed=%t, want %q", recent[0].Error, route.Error, record.Error, record.Failed(), wantError)
}
if state.Totals.Requests != 1 || state.Totals.Errors != wantErrors {
t.Errorf("totals: %+v, want one request and %d errors", state.Totals, wantErrors)
}
})
}
}
}
// Native stream errors are relayed byte for byte, including an
// error event without a final newline, and still reach the request log.
func TestNativeStreamFailureAccounting(t *testing.T) {
const failure = "synthetic stream failure"
for _, c := range []struct {
name, wantError, wantType string
proto provider.Protocol
path, body, reply string
}{
{"chat", failure, "server_error", provider.Chat, "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`,
sse(`data: {"choices":[{"delta":{"content":"partial text"}}]}`, `data: {"error":{"type":"server_error","message":"`+failure+`"}}`)},
{"anthropic", failure, "server_error", provider.Anthropic, "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`,
anthropicStart + anthropicText + sse(`event: error`+"\n"+`data: {"type":"error","error":{"type":"server_error","message":"`+failure+`"}}`)},
{"responses error", failure, "server_error", provider.Responses, "/v1/responses", `{"model":"fake/m1","stream":true,"input":"hi"}`,
sse(`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"partial text"}`, `event: error`+"\n"+`data: {"type":"error","code":"server_error","message":"`+failure+`"}`)},
{"responses failed without message", "upstream stream failed", "", provider.Responses, "/v1/responses", `{"model":"fake/m1","stream":true,"input":"hi"}`,
sse(`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"partial text"}`, `event: response.failed`+"\n"+`data: {"type":"response.failed","response":{"id":"r1","status":"failed"}}`)},
{"error event without data", "upstream stream failed", "", provider.Anthropic, "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`,
anthropicStart + anthropicText + sse(`event: error`)},
} {
for _, ending := range []string{"newline", "unterminated"} {
t.Run(c.name+"/"+ending, func(t *testing.T) {
fresh(t)
reply := c.reply
if ending == "unterminated" {
reply = strings.TrimRight(reply, "\n")
}
setup(t, c.proto, &fake{reply: reply})
s := New()
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", c.path, strings.NewReader(c.body)))
if w.Code != 200 || w.Body.String() != reply {
t.Fatalf("native stream was changed: %d %s", w.Code, w.Body)
}
state, recent := s.Trace(context.Background(), 0, 0), s.Recent()
if len(state.Routes) != 1 || len(recent) != 1 {
t.Fatalf("routes=%d recent=%d, want one each", len(state.Routes), len(recent))
}
record := lastRecord(t)
if recent[0].Error != c.wantError || state.Routes[0].Error != c.wantError || record.Error != c.wantError || record.ErrType != c.wantType || record.Status != 200 {
t.Errorf("recent error=%q route error=%q; usage: %+v", recent[0].Error, state.Routes[0].Error, record)
}
if state.Totals.Errors != 1 {
t.Errorf("routing errors=%d, want 1", state.Totals.Errors)
}
})
}
}
}
+1 -1
View File
@@ -355,7 +355,7 @@ func (t *trace) update(r *Route, f func(r *Route)) {
t.totals.Rerouted++
}
}
if r.Status >= 400 {
if r.Status >= 400 || r.Error != "" {
t.totals.Errors++
}
if keepRoutes {
+31 -2
View File
@@ -48,6 +48,8 @@ func TestOTelBatchWireAndPrivacy(t *testing.T) {
r := Record{RouteID: 42, Time: time.Now(), Agent: "pi", Provider: "deepseek", Model: "deepseek-chat", Requested: "group/mine", Served: "deepseek-v4", Input: 10, CacheRead: 3, CacheWrite: 2, Output: 4, Reasoning: 1, Millis: 1200, TTFT: 200, Status: 200,
ProviderKeyName: "PRIVATE-ACCOUNT", ProviderKeyID: "PRIVATE-KEY", Session: "PRIVATE-SESSION", Via: "PRIVATE-HOST"}
Append(r)
r.Error, r.ErrType = "PRIVATE-ERROR", "PRIVATE-ERROR-TYPE"
Append(r) // an error in a stream whose HTTP status is already 200
r.Status = 502
Append(r)
stop() // drain without waiting for the periodic batch
@@ -93,9 +95,21 @@ func TestOTelBatchWireAndPrivacy(t *testing.T) {
t.Fatal(err)
}
spans := traces.Resources[0].Scopes[0].Spans
if len(spans) != 2 || len(spans[0].TraceID) != 32 || spans[0].TraceID != spans[1].TraceID || len(spans[0].SpanID) != 16 || spans[0].SpanID == spans[1].SpanID || spans[0].Kind != 3 || spans[1].Status.Code != 2 {
if len(spans) != 3 || len(spans[0].TraceID) != 32 || spans[0].TraceID != spans[1].TraceID || len(spans[0].SpanID) != 16 || spans[0].SpanID == spans[1].SpanID || spans[0].Kind != 3 {
t.Fatalf("spans: %+v", spans)
}
for i, want := range []struct {
status int
http, err string
}{{0, "200", ""}, {2, "200", "stream_error"}, {2, "502", "502"}} {
attrs := map[string]string{}
for _, a := range spans[i].Attributes {
attrs[a.Key] = a.Value["stringValue"] + a.Value["intValue"]
}
if spans[i].Status.Code != want.status || attrs["http.response.status_code"] != want.http || attrs["error.type"] != want.err {
t.Errorf("span %d: status=%d http=%q error.type=%q, want %+v", i, spans[i].Status.Code, attrs["http.response.status_code"], attrs["error.type"], want)
}
}
values := map[string]string{}
for _, a := range spans[0].Attributes {
values[a.Key] = a.Value["stringValue"] + a.Value["intValue"]
@@ -112,6 +126,10 @@ func TestOTelBatchWireAndPrivacy(t *testing.T) {
Histogram struct {
Temporality int `json:"aggregationTemporality"`
Points []struct {
Attributes []struct {
Key string `json:"key"`
Value map[string]string `json:"value"`
} `json:"attributes"`
Count string `json:"count"`
Sum float64 `json:"sum"`
Buckets []string `json:"bucketCounts"`
@@ -129,10 +147,21 @@ func TestOTelBatchWireAndPrivacy(t *testing.T) {
if len(ms) != 2 || ms[0].Name != "gen_ai.client.operation.duration" || ms[0].Unit != "s" || ms[0].Histogram.Temporality != 1 || ms[1].Name != "gen_ai.client.token.usage" {
t.Fatalf("metrics: %+v", ms)
}
categories := map[string]int{}
for _, p := range ms[0].Histogram.Points {
if p.Count != "1" || p.Sum != 1.2 || len(p.Buckets) != len(p.Bounds)+1 {
t.Fatalf("point: %+v", p)
t.Errorf("point: %+v", p)
}
errType := ""
for _, a := range p.Attributes {
if a.Key == "error.type" {
errType = a.Value["stringValue"]
}
}
categories[errType]++
}
if len(categories) != 3 || categories[""] != 1 || categories["stream_error"] != 1 || categories["502"] != 1 {
t.Errorf("metric error categories: %v, want one normal, one stream error and one HTTP 502", categories)
}
}
+7 -3
View File
@@ -36,8 +36,12 @@ func otelAttributes(r Record) []otelAttribute {
if r.Served != "" {
a = append(a, otelString("gen_ai.response.model", r.Served))
}
if r.Status >= 400 {
a = append(a, otelString("error.type", strconv.Itoa(r.Status)))
if r.Failed() {
errType := "stream_error"
if r.Status >= 400 {
errType = strconv.Itoa(r.Status)
}
a = append(a, otelString("error.type", errType))
}
return a
}
@@ -81,7 +85,7 @@ func (e *otelExporter) traces(records []Record) any {
a = append(a, otelString("langfuse.observation.output", otelReplyText(r.BodyOut)))
}
status := 0
if r.Status >= 400 {
if r.Failed() {
status = 2
}
op := r.Operation