diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go index da3991d45..808923ff0 100644 --- a/internal/gateway/codeassist.go +++ b/internal/gateway/codeassist.go @@ -1373,7 +1373,10 @@ func (d *codeAssistDecoder) decode(data string, emit func(Event)) error { return nil } if ch.Error != nil { - emit(Event{Kind: KError, Text: cmp.Or(ch.Error.Message, streamErrorText(data))}) + // at the status it names, Google's code: a 400 INVALID_ARGUMENT + // is the request's fault, never asked again nor the account's + // (sse_bare.go) + emit(Event{Kind: KError, Text: cmp.Or(ch.Error.Message, streamErrorText(data)), Status: namedStatus([]byte(data))}) return nil } c := ch.geminiChunk diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index 9f85576e3..80d2cf243 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -419,6 +419,9 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov } var failed, failedCode string var failedStatus int + // errNamed: the status the last try's error event named for itself, + // 0 when it named none or the try failed otherwise + var errNamed int var cut, errSent bool var empty bool // a reply in this protocol that says nothing fails (#667) // counts: a reply in this protocol counts its tokens, and one that @@ -470,9 +473,14 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov if ev.Code == "" && cont.possible() && !inGroupTry(r.Context()) { // held while the reply may yet go on; sent when it can't failed, failedCode, failedStatus, cut = ev.Text, ev.Code, ev.Status, true + errNamed = ev.Status return } failed, failedCode, failedStatus = ev.Text, ev.Code, ev.Status + if ev.Code == "" { + // a refusal's status is magpie's, told by its code + errNamed = ev.Status + } errSent = true case KStart: // the tries are each billed, so their usages are summed into @@ -514,6 +522,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov // continuation's prefill away cutBy, cutCode, cutErr := failed, failedCode, serr failed, failedCode, failedStatus, cut, serr = "", "", 0, false, nil + errNamed = 0 var held func() // what a textCallSee of this try holds back req := request if cont.resume { @@ -738,6 +747,13 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov failed += " — " + hint } u.ErrType = turnedAwayErrType + } else if errNamed >= 400 && errNamed < 600 && serr == nil { + // the upstream's error event named its own status (Google's 400 + // INVALID_ARGUMENT in a 200 stream): the failure is booked and + // rested as it, a request's fault as one, as a relayed stream's + // is (namedStatusHeader, #4855). Antigravity's turning a prompt + // away is its own, above + noteSaidStatus(w, errNamed) } if !errSent { enc.event(Event{Kind: KError, Text: failed, Code: failedCode}) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index bd74b83a8..49ed8fc0c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4890,6 +4890,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // refused one before any of it was said (#248): the account // is at fault no more for it, and nobody rests try.Fail = failRefused + } else if named := failedNamed(hw.header, namedStatus([]byte(call.Error))); named >= 400 && named < 500 && !retryable(named, []byte(call.Error)) { + // the error frame named a status that is the request's + // fault, as it would be before the stream: Antigravity's + // 400 INVALID_ARGUMENT after its thinking (zRain on + // Discord, sse_bare.go) fails the same on every account, + // and nobody rests, as for that 400 sent before the 200 } else if lateRests(call.Error) { rest := s.restAfter(c, call.Status, hw.header, []byte(call.Error)) try.Fail, try.Rest = rest.Why, &rest @@ -7150,14 +7156,17 @@ func streamFailure(proto provider.Protocol, msg string) []byte { // 0.0s"). A JSON or binary body never begins with a line of an event // stream. func eventStream(res *http.Response) (io.Reader, bool) { + // an error the upstream wrote as a JSON line of its own goes on as + // the data event it means (bareErrors): to a decoder, a sniffer and + // a client the stream is relayed to alike if strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") { - return res.Body, true + return bareErrors(res.Body), true } br := bufio.NewReaderSize(res.Body, 4<<10) head, _ := br.Peek(16) if eventsStart(bytes.TrimLeft(head, " \t\r\n")) { res.Header.Set("Content-Type", "text/event-stream") - return br, true + return bareErrors(br), true } return br, false } diff --git a/internal/gateway/sse.go b/internal/gateway/sse.go index 24d682896..927cd5f80 100644 --- a/internal/gateway/sse.go +++ b/internal/gateway/sse.go @@ -18,8 +18,13 @@ func readSSE(r io.Reader, fn func(event, data string) error) error { // readSSEAlive is readSSE that also calls alive, when not nil, after each // event and each comment: every sign that the stream is alive, a -// keepalive (": keepalive") as much as an answer. +// keepalive (": keepalive") as much as an answer. An error the upstream +// wrote as a JSON line of its own is read as the data event it means +// (bareErrors). func readSSEAlive(r io.Reader, fn func(event, data string) error, alive func()) error { + if _, ok := r.(*bareErrorReader); !ok { + r = bareErrors(r) + } sc := bufio.NewScanner(r) sc.Buffer(make([]byte, 0, 64<<10), 32<<20) var event string diff --git a/internal/gateway/sse_bare.go b/internal/gateway/sse_bare.go new file mode 100644 index 000000000..3665f54be --- /dev/null +++ b/internal/gateway/sse_bare.go @@ -0,0 +1,218 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "io" +) + +// An upstream's event stream can end with its error written as a JSON +// object on a line of its own, no "data:" before it: Antigravity's Code +// Assist answered gemini-4-argon-high with a 200 stream, a few thinking +// events, then +// +// {"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}} +// +// and the end of the body (zRain on Discord). SSE has no such field, so +// every reader skipped the line, and the reply was told as one that +// "ended before it was complete" instead of the vendor's 400 (a request +// fault, not the account's). bareErrors hands such a line on as the data +// event it means, for every reader of the stream: the translated routes' +// decoders, a relayed stream's sniffer and held-stream scan, and the +// client a stream is relayed to as it came. + +// bareLimit is how much of a bare JSON value is held while its lines come: +// past it, it is no error object, and goes on as it came. +const bareLimit = 1 << 20 + +// bareErrors is r with every line that is a JSON error object of its own +// (bareError) written as a data event. Lines that start anything else go +// on as they come, a line not yet ended included; only a line that may +// be such an object is held, until it ends (Google writes its errors +// pretty-printed elsewhere, so the lines after it too, until they parse). +func bareErrors(r io.Reader) io.Reader { + return &bareErrorReader{r: r, blank: true} +} + +type bareErrorReader struct { + r io.Reader + in []byte // read and not yet judged: a line not ended + out []byte // judged, to hand on + err error + // mid: what went on last stopped inside a line, whose rest goes on + // as it comes + mid bool + // bare is a JSON value's lines so far, held until they parse + bare []byte + // blank: the last line handed on was blank, or none was; an event + // written in is set apart from a data line before it otherwise + blank bool + scratch []byte +} + +func (b *bareErrorReader) Read(p []byte) (int, error) { + for len(b.out) == 0 { + if b.err != nil { + if len(b.in) > 0 || len(b.bare) > 0 { + b.judge(true) + continue + } + return 0, b.err + } + if b.scratch == nil { + b.scratch = make([]byte, 32<<10) + } + n, err := b.r.Read(b.scratch) + b.in = append(b.in, b.scratch[:n]...) + b.err = err + if n > 0 { + b.judge(false) + } + } + n := copy(p, b.out) + b.out = b.out[n:] + if len(b.out) == 0 { + b.out = nil + } + return n, nil +} + +// judge moves what of in can be judged to out; at the body's end +// (eof) all of it. +func (b *bareErrorReader) judge(eof bool) { + for len(b.in) > 0 || eof && len(b.bare) > 0 { + i := bytes.IndexByte(b.in, '\n') + if b.mid { + // the rest of a line that went on already + if i < 0 { + b.out = append(b.out, b.in...) + b.in = b.in[:0] + return + } + b.out = append(b.out, b.in[:i+1]...) + b.in = b.in[i+1:] + b.mid, b.blank = false, false + continue + } + var line []byte + switch { + case i >= 0: + line, b.in = b.in[:i+1], b.in[i+1:] + case eof: + line, b.in = b.in, b.in[:0] + case b.bare == nil && !mayBeBare(b.in): + // a line under way that can't be one: on now, as it came + b.out = append(b.out, b.in...) + b.in = b.in[:0] + b.mid = true + return + default: + return // held until it ends + } + t := bytes.TrimSpace(line) + if b.bare != nil { + if len(t) == 0 || sseField(t) { + // an event's line: what was held was no JSON of its own + b.release() + } else { + b.bare = append(b.bare, line...) + b.settle() + continue + } + } + if len(line) == 0 { + continue + } + if len(t) > 0 && (t[0] == '{' || t[0] == '[') { + b.bare = append([]byte{}, line...) + b.settle() + continue + } + b.out = append(b.out, line...) + b.blank = len(t) == 0 + } +} + +// settle hands on the bare value held once it parses: as a data event +// when it is an error, as it came when it isn't. One grown past +// bareLimit goes as it came. +func (b *bareErrorReader) settle() { + t := bytes.TrimSpace(b.bare) + if !json.Valid(t) { + if len(b.bare) > bareLimit { + b.release() + } + return + } + data, ok := bareError(t) + if !ok { + b.release() + return + } + if !b.blank { + b.out = append(b.out, '\n') + } + b.out = append(b.out, "data: "...) + b.out = append(b.out, data...) + b.out = append(b.out, "\n\n"...) + b.bare, b.blank = nil, true +} + +func (b *bareErrorReader) release() { + b.out = append(b.out, b.bare...) + b.blank = len(bytes.TrimSpace(b.bare)) == 0 + b.bare = nil +} + +// mayBeBare says whether a line begun with start may be a bare JSON +// value: nothing yet but spaces, or a { or [ first. +func mayBeBare(start []byte) bool { + t := bytes.TrimLeft(start, " \t\r") + return len(t) == 0 || t[0] == '{' || t[0] == '[' +} + +// sseField says whether a line is one of SSE's own: a field or a comment. +func sseField(t []byte) bool { + for _, f := range [][]byte{[]byte("data:"), []byte("event:"), []byte("id:"), []byte("retry:"), []byte(":")} { + if bytes.HasPrefix(t, f) { + return true + } + } + return false +} + +// bareError is the data event a JSON value written on its own in an +// event stream stands for, when it is an error: Google's +// {"error":{"code","message","status"}}, OpenAI's {"error":{"message", +// "type","code"}}, Anthropic's {"type":"error","error":{…}}, or a list +// of one of them (Google's JSON array stream). On one line, its member +// order kept. Anything else is no event: SSE ignores it, as before. +func bareError(t []byte) ([]byte, bool) { + if len(t) > 0 && t[0] == '[' { + var list []json.RawMessage + if json.Unmarshal(t, &list) != nil || len(list) != 1 { + return nil, false + } + t = bytes.TrimSpace(list[0]) + } + if len(t) == 0 || t[0] != '{' { + return nil, false + } + var v struct { + Type json.RawMessage `json:"type"` + Error json.RawMessage `json:"error"` + } + if json.Unmarshal(t, &v) != nil { + return nil, false + } + var typ string + json.Unmarshal(v.Type, &typ) + if !carries(v.Error) && typ != "error" { + return nil, false + } + var one bytes.Buffer + if json.Compact(&one, t) != nil { + return nil, false + } + return one.Bytes(), true +} diff --git a/internal/gateway/sse_bare_test.go b/internal/gateway/sse_bare_test.go new file mode 100644 index 000000000..e951863fd --- /dev/null +++ b/internal/gateway/sse_bare_test.go @@ -0,0 +1,168 @@ +package gateway + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/iotest" + + "github.com/yetone/magpie/internal/provider" +) + +// agBareError is the line Antigravity ended zRain's gemini-4-argon-high +// stream with, after its 200 and a few thinking events (Discord +// #feedback, v0.1.3039/v0.1.3041, Windows): no "data:" before it, and +// nothing after it but the end of the body. +const agBareError = `{"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}}` + +// agThinking is Code Assist's thinking events before it, as Antigravity +// streams them (CRLF, each in its {response} wrapper); the reporter's own +// were not sent, only described. +const agThinking = "data: {\"response\": {\"candidates\": [{\"content\": {\"role\": \"model\",\"parts\": [{\"text\": \"**Weighing the request**\\n\\n\",\"thought\": true}]}}],\"usageMetadata\": {\"promptTokenCount\": 5210,\"totalTokenCount\": 5210},\"modelVersion\": \"gemini-4-argon\"},\"traceId\": \"9d1c0e2f\"}\r\n\r\n" + + "data: {\"response\": {\"candidates\": [{\"content\": {\"role\": \"model\",\"parts\": [{\"text\": \"I'll look at the files first.\",\"thought\": true}]}}],\"usageMetadata\": {\"promptTokenCount\": 5210,\"totalTokenCount\": 5230},\"modelVersion\": \"gemini-4-argon\"},\"traceId\": \"9d1c0e2f\"}\r\n\r\n" + +// the bare error ended as it came: with a line end, a CRLF, or none +var agBareEnds = map[string]string{ + "LF": agThinking + agBareError + "\n", + "CRLF": agThinking + agBareError + "\r\n", + "EOF": agThinking + agBareError, +} + +func readEvents(t *testing.T, r io.Reader) []string { + t.Helper() + var got []string + if err := readSSE(r, func(_, data string) error { + got = append(got, data) + return nil + }); err != nil { + t.Fatal(err) + } + return got +} + +// The bare error is the stream's last event, as if it had come as data, +// however the body is split; an event of the stream's own is untouched. +func TestBareErrorLineIsAnEvent(t *testing.T) { + for name, body := range agBareEnds { + for _, split := range []bool{false, true} { + var r io.Reader = strings.NewReader(body) + if split { + r = iotest.OneByteReader(r) + } + got := readEvents(t, r) + if len(got) != 3 || got[2] != agBareError || !strings.Contains(got[1], "look at the files") { + t.Errorf("%s (one byte at a time %v): %q", name, split, got) + } + } + } + + // Google's own pretty-printed error, a list of one (its JSON array + // stream), OpenAI's and Anthropic's shapes, right after a data line + // with no blank line between + for _, tc := range []struct{ bare, want string }{ + {"{\n \"error\": {\n \"code\": 400,\n \"message\": \"Request contains an invalid argument.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", agBareError}, + {"[{\n \"error\": {\n \"code\": 429,\n \"message\": \"Resource has been exhausted (e.g. check quota).\",\n \"status\": \"RESOURCE_EXHAUSTED\"\n }\n}\n]\n", `{"error":{"code":429,"message":"Resource has been exhausted (e.g. check quota).","status":"RESOURCE_EXHAUSTED"}}`}, + {`{"error":{"message":"bad","type":"invalid_request_error","code":null}}` + "\n", `{"error":{"message":"bad","type":"invalid_request_error","code":null}}`}, + {`{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}` + "\n", `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`}, + } { + got := readEvents(t, iotest.OneByteReader(strings.NewReader("data: {\"a\":1}\n"+tc.bare))) + if len(got) != 2 || got[0] != `{"a":1}` || got[1] != tc.want { + t.Errorf("%q: %q", tc.bare, got) + } + } + + // what isn't an error goes as it came, and SSE skips it as before + for _, other := range []string{ + `{"candidates":[]}`, + `{"error":null}`, + `[{"error":{"code":1}},{"error":{"code":2}}]`, + `{"error": {"code": 400,`, + `not json`, + } { + body := "data: {\"a\":1}\n\n" + other + "\ndata: {\"b\":2}\n\n" + out, _ := io.ReadAll(bareErrors(iotest.OneByteReader(strings.NewReader(body)))) + if string(out) != body { + t.Errorf("%q changed: %q", other, out) + } + } + + // a stream with no bare line goes byte for byte + for _, body := range []string{vertexThought, agThinking, "data: x\r\n\r\n: ping\r\nevent: e\r\ndata: y"} { + out, _ := io.ReadAll(bareErrors(iotest.OneByteReader(strings.NewReader(body)))) + if string(out) != body { + t.Errorf("a stream changed: %q", out) + } + } +} + +// A line under way goes on before it ends: only one that may be a bare +// JSON value waits for its end, so a relayed stream isn't held back. +func TestBareErrorsHoldsNothingElse(t *testing.T) { + pr, pw := io.Pipe() + r := bareErrors(pr) + go pw.Write([]byte("data: {\"text\":\"hel")) + buf := make([]byte, 64) + n, err := r.Read(buf) + if err != nil || string(buf[:n]) != "data: {\"text\":\"hel" { + t.Fatalf("a data line's start was held: %q %v", buf[:n], err) + } + pw.Close() +} + +// zRain's case end to end: Antigravity's 200 stream that ends on the bare +// error is told as the 400 it is, with Google's words, not as a reply +// that "ended before it was complete". It is the request's fault: the +// account doesn't rest, and the route books the 400. +func TestAntigravityBareErrorIsTheVendors(t *testing.T) { + for name, reply := range agBareEnds { + for _, stream := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/stream=%v", name, stream), func(t *testing.T) { + s, _ := antigravityTurnedAwayGroup(t, []string{"u@example.com"}, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, reply) + }) + code, out := turnOn(t, s, directTurn("You are a helpful assistant.", stream)) + if !strings.Contains(out, "Request contains an invalid argument.") || strings.Contains(out, "ended before") { + t.Fatalf("the client wasn't told Google's error (%d): %s", code, out) + } + if !stream && code != http.StatusBadRequest { + t.Errorf("a whole reply's error is at %d, not Google's 400: %s", code, out) + } + if _, ok := restOf("antigravity@u@example.com"); ok { + t.Fatalf("the account rests for a request Google turned away: %v", rests()) + } + r := lastRoute(s) + // a stream's try is at the 200 its agent was sent, its + // error Google's; a whole reply's at Google's 400 + if len(r.Tries) == 0 || r.Tries[0].Rest != nil || !strings.Contains(r.Tries[0].Error, "invalid argument") || !stream && r.Tries[0].Status != http.StatusBadRequest { + t.Fatalf("the try: %+v", r.Tries) + } + }) + } + } +} + +// A Gemini stream relayed as it came (a custom provider's Gemini URL) +// reaches its client with the bare error as Gemini's own error event, +// which Google's SDK reads, and magpie appends no "ended before" of its +// own after it. +func TestGeminiRelayBareError(t *testing.T) { + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "data: {\"candidates\": [{\"content\": {\"role\": \"model\",\"parts\": [{\"text\": \"Weighing.\",\"thought\": true}]}}]}\r\n\r\n"+agBareError) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"gemini-3.8-flash"}, Gemini: up.URL + "/v1beta"}); err != nil { + t.Fatal(err) + } + _, body := post(t, "/v1beta/models/up/gemini-3.8-flash:streamGenerateContent?alt=sse", + `{"contents":[{"role":"user","parts":[{"text":"Is 391 prime?"}]}]}`) + if !strings.Contains(body, "data: "+agBareError) || strings.Contains(body, "ended before") { + t.Fatalf("the relayed stream: %s", body) + } +} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 29c7f9465..3f1d9fa8e 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -2,6 +2,7 @@ package gateway import ( "bytes" + "cmp" "encoding/json" "strings" @@ -171,6 +172,10 @@ func carriedError(data string) (ev Event, ok bool) { return Event{}, false } code, status, said := filterRefused(data) + if status == 0 { + // the status the error names for itself (#4855) + status = cmp.Or(namedStatusOf(r.Error), namedStatusOf(v.Error)) + } return Event{Kind: KError, Text: streamErrorText(data, r.Error, v.Error), Code: code, Status: status, Said: said}, true }