gateway: an error frame inside a 200 fails at the status it names (#4855)

mycf_711's wps-lingxi rows read status=200: the plugin's stream already
sent its 200, then wrote {"error":{"message":"灵犀上游返回 AIError:
AI服务异常(上游暂时不可用,可重试)(HTTP 503)",...}}. On main a frame
mid-reply was booked at 200 and rested 60s as "other" with the error
"OK: ...", and one as the first event failed at the 502 the words'
guess gives. Routing never saw the 503 (or AuditFailed's 502).

Now the status an error frame names is what it fails, rests and is
booked at:
- a numeric status or code member, 400-599 (skygunner's patch: held
  stream's errOf, errorReply, carriedStatus, and the sniffer's note on
  the try's header for a reply already streaming, kept from the client);
- else "(HTTP 503)" / "(HTTP 503)" in the words, 429 and 5xx only, as a
  quoted 4xx ("the image link answered (HTTP 404)") may not be the
  provider's;
- a mid-reply call is booked at that status in Routing and Usage.
A quoted string code ("429", "1113") is the vendor's own code, not a
status. Words magpie wrote itself (loop guard, empty reply, relooped)
and too-long words name nothing, whatever members they carry: a LAN
peer's loop guard frame carries 502 in its Gemini shape. Such a frame
also no longer rests the route mid-reply (main rested it 60s as
"other" at 200); the model looping is not the provider failing.

Left out of skygunner's patch: streamFailure giving magpie's own Chat
frames a code and status. A peer magpie would read its loop guard frame
as a named 502.

Run (mote, at a1f1810e9 + this change):
- go test -count=1 -run 'TestRelayStreamErrorFrame|TestNamedStatusOf|
  TestGeminiCompat|TestLoop|Stream|Late|Carried|ErrorReply|Rest'
  ./internal/gateway: first run red on TestNamedStatusOf (a quoted
  "429" read as a status through json.Number), fixed. At this commit
  (on 8a8079680; d02b8a000 under it since changes the GUI only), the same -run with
  |Refus|Fallback added: ok (222s); go vet ./internal/gateway on
  darwin, GOOS=linux and GOOS=windows: clean; gofmt -l: nothing.
- The new tests at a1f1810e9 without the change: every subtest of
  TestRelayStreamErrorFrameSaysItsStatus and
  TestRelayStreamErrorFrameNamesItsStatusInWords red except the 4xx
  quoted case (mid-reply rested at 200, first event booked at 502,
  the peer's loop guard rested).
Broken by hand:
- namedStatusOf without textStatus: first_event and TestNamedStatusOf
  red.
- magpieSaid returning false: the peer loop guard subtest and
  TestNamedStatusOf red.
Not tried: a real wps-lingxi account; the full suite (runs after the
push). AuditFailed (the plugin's "audit_blocked") is counted as the 502
it names, not as a refusal of the request's content; whether a content
refusal there should rest nobody was not checked.

Co-authored-by: vincent <vincent@users.noreply.github.com>
Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-04 22:17:49 +08:00
co-authored by vincent MYCF711
parent d02b8a000e
commit 538026e62b
7 changed files with 388 additions and 12 deletions
+1
View File
@@ -184,6 +184,7 @@ recorded as a prediction failure (`noPrediction`).
- A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another.
- A refusal that comes as an error (#2400, Jichao). An error whose own `message` is, whole, `The request was rejected because it was considered high risk` is a refusal with no code beside it (`highRiskRefusal` in `policyRefusal`): in an HTTP error body or a stream's error event, never in an answer's text, which may quote it. The vendor that sends it isn't known; it says the request was turned away, so it goes to the next candidate under `RefusalRetries` like any refusal and rests nobody. A refusal error event before any content ends the try at once (`eventRefusalError`, `stop` as for any error), so an upstream that keeps the stream open doesn't hold the next candidate back; a refusal's stop or finish marker is still read to the end for the usage and terminator after it. After content, every write is read for a late refusal (`refusalAfter`), so one whose `event: error` name and data come in separate writes is still noted, and nothing is replayed. `TestHighRisk*`, `TestRefusalErrorDoesNotWaitForEOF` in [`refusal_error_test.go`](../../internal/gateway/refusal_error_test.go).
- An error's own status beats the words (#4855). A provider that already sent its 200 can only say what went wrong in an in-stream error frame — a plugin's runtime watching a clock, aborting at 285s and emitting `{"error":{…,"code":"upstream_timeout","status":504}}` — and the frame is relayed to the client as it came. The status it names on a member of the error object (`namedStatusOf`, a number 400–599, `status` first, Gemini's relays' `code`; a string code is not one) is what the failure fails and rests as, before `streamStatus` guesses one from the message's words, wherever the frame is read: a held stream's error event (`errOf` in `streamEvent`), a whole 200 body that is only an error (`errorReply`), a carried error's words (`carriedStatus`), and a reply already streaming, whose turn rests at the status the sniffer noted on the try (`namedStatusHeader`, kept from the client; `failedNamed`/`restAfterMarked`) — so a terse frame naming 429 rests as a rate limit, not `other` at a word-guessed 502, and the rest says "Gateway Timeout", not "OK". With no such member, a status the words name as one, "(HTTP 503)" or "(HTTP 503)" (`textStatus`, `httpSaid`), counts too, for a 429 or a 5xx only, since a 4xx a message quotes may be someone else's ("the image link answered (HTTP 404)"): wps-lingxi's AuditFailed and AIError frames name theirs that way (mycf_711). A reply already streaming when its frame came is booked at that status as well, in Routing and Usage, though the client's 200 went out. Words magpie wrote itself (`magpieSaid`: the loop guard's `loopGuardSaid`, `emptyReply`, `reloopedError`) and words saying the request is too long name no status, whatever members they carry: a LAN peer's loop guard frame carries 502 in its Gemini shape, and is no failure of the provider, so it neither rests the route nor is booked as one (`lateRests`). An error naming no status reads exactly as before. `TestRelayStreamErrorFrameSaysItsStatus`, `TestRelayStreamErrorFrameWithoutStatusAsBefore`, `TestRelayStreamErrorFrameNamesItsStatusInWords`, `TestNamedStatusOf` in [`stream_frame_status_test.go`](../../internal/gateway/stream_frame_status_test.go).
- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; so does any other try that failed, billed something and handed the request on, to another account or member or the same one again (`failedRow` in `serve`, written once the next try begins): a Claude subscription run that failed after Anthropic's `message_start` had written the conversation to that account's cache, and the next account wrote it again, while the Usage page counted the second alone (hhxk233 and Kayrainforest on X; `relay` keeps the reply start's usage on a failure, `TestClaudeSubscriptionFailedTryKeepsItsTokens`). A try that failed before anything was billed has no record; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (`codexServed` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays `openai` with no account, as does one whose `chatgpt-account-id` isn't the account Codex's auth.json here is signed in to (a Codex in WSL or under another `CODEX_HOME`), and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (`loggedAnswers`, #1367); a row an account answered, its host `host as email`, still is.
- A failed call is in `app.log` too, not only the Routing page and the usage ledger (wjh66 on Discord: Codex's "error decoding response body" after "reconnecting 5/5", and the log had nothing of the turn). `record` writes each call whose status is 400 or more, or that carries an error, as one line (`failedCallLine`: agent, model, provider, status, time, the error to 300 characters); the same failure again within a minute is counted into the next line, not written (`failedLogEvery`), so a client asking in a loop can't fill the log. A Codex reply relayed from the ChatGPT backend that ends before its last event also says which side ended it (`codexEndedEarly` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)): the read of OpenAI's stream that failed, with its error, or a clean end; and the client gone, a write to it that failed, or the failure passed on as `response.failed`, with the bytes passed on. reqwest, Codex's HTTP client, says "error decoding response body" for any read of a body whose connection broke, so only this line tells the legs apart. A gateway that ends with requests still in flight logs that they were cut (`srv.Shutdown`'s error; on Windows there is no handover, so an update or quit cuts a stream after `shortDrain`) (`TestCodexReplyBrokenOffLogged`, `TestCodexClientGoneLogged`, `TestFailedCallLineOncePerMinute`).
- Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go).
+109 -4
View File
@@ -1857,9 +1857,10 @@ func retryable(status int, body []byte) bool {
// quota. A conversation grown too long for the model, or a request the
// vendor turned away as it reads, would fail the same at the next asked:
// nobody rests for it. Nor does an account rest when a model generated
// empty output (#1221).
// empty output (#1221), nor for any error in magpie's own words, a LAN
// peer's loop guard among them (magpieSaid).
func lateRests(msg string) bool {
return !tooLong(http.StatusBadRequest, msg) && !refusedWords.MatchString(msg) && !protectionWords.MatchString(msg) && !strings.Contains(msg, emptyReply)
return !tooLong(http.StatusBadRequest, msg) && !refusedWords.MatchString(msg) && !protectionWords.MatchString(msg) && !magpieSaid(msg)
}
// unsaidMargin is how far past a model's window a request's estimate
@@ -2452,7 +2453,7 @@ func (h *holdWriter) pass() {
}
dst := h.w.Header()
for k, v := range h.header {
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader && k != keyLimitThereHeader { // magpie's own notes, for restAfter and settle
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader && k != keyLimitThereHeader && k != namedStatusHeader { // magpie's own notes, for restAfter and settle
dst[k] = v
}
}
@@ -2978,7 +2979,7 @@ func (h *holdWriter) keepAlive() {
}
dst := h.w.Header()
for k, v := range src {
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader && k != keyLimitThereHeader && k != "Content-Length" {
if k != resetsHeader && k != refusedHeader && k != zdrHeader && k != answeredThereHeader && k != keyLimitThereHeader && k != namedStatusHeader && k != "Content-Length" {
dst[k] = slices.Clone(v)
}
}
@@ -3695,6 +3696,11 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
if json.Unmarshal(v.Message, &m) == nil && m != "" {
msg += " " + m
}
if said := namedStatusOf(raw); said != 0 {
// the error names its own status, and it is the one it fails
// as (#4855), not the one its words guess
return eventError, said, msg
}
return eventError, streamStatus(msg), msg
}
refusal := func(reason string) (int, int, string) {
@@ -4174,9 +4180,108 @@ func errorReply(body []byte) (status int, msg string, ok bool) {
} else if json.Unmarshal(v.Error, &e) != nil || e.Message == nil && e.Type == nil && e.Code == nil && e.Status == nil {
return 0, "", false
}
if said := namedStatusOf(v.Error); said != 0 {
// the error names its own status (#4855)
return said, provider.APIError(b, "the upstream reported an error"), true
}
return streamStatus(string(wordsOf(b))), provider.APIError(b, "the upstream reported an error"), true
}
// namedStatus is the status an error carried under a 200 names for
// itself (#4855): its error object's own (namedStatusOf), or, as words
// alone (a reply's error text), the status they name (textStatus). 0
// when it names none.
func namedStatus(body []byte) int {
var v struct {
Error json.RawMessage `json:"error"`
}
if b := bytes.TrimSpace(body); len(b) > 0 && b[0] == '{' {
if json.Unmarshal(b, &v) == nil && carries(v.Error) {
return namedStatusOf(v.Error)
}
return 0
}
return textStatus(string(body))
}
// namedStatusOf is the status an error object names for itself (#4855):
// a plugin that ends an OpenAI-compatible stream after its 200 can only
// say what went wrong in the frame, and the status it names there is the
// routing signal. A number 400–599 on a member of its own, status first,
// then code as Gemini's relays carry it (a string code is not a status);
// else the status its message names in words (textStatus). 0 when it
// names none, when its words say the request is too long (its overflow is
// read from the words, wherever it is said), and for magpie's own words,
// which a magpie relayed to says too (magpieSaid).
func namedStatusOf(errRaw []byte) int {
if !carries(errRaw) {
return 0
}
var e struct {
Code json.RawMessage `json:"code"`
Status json.RawMessage `json:"status"`
Message json.RawMessage `json:"message"`
}
var msg string
if json.Unmarshal(errRaw, &msg) != nil {
if json.Unmarshal(errRaw, &e) != nil {
return 0
}
json.Unmarshal(e.Message, &msg)
}
if magpieSaid(msg) || tooLong(http.StatusBadRequest, msg) {
return 0
}
num := func(raw json.RawMessage) int {
// a string code ("429", Zhipu's "1113") is the vendor's own
// code, not a status: json.Number would take a quoted number
var n json.Number
if len(raw) == 0 || raw[0] < '0' || raw[0] > '9' || json.Unmarshal(raw, &n) != nil {
return 0
}
if i, err := n.Int64(); err == nil && i >= 400 && i < 600 {
return int(i)
}
return 0
}
for _, raw := range []json.RawMessage{e.Status, e.Code} {
if n := num(raw); n != 0 {
return n
}
}
return textStatus(msg)
}
// httpSaid is a status an error's words name as one, "(HTTP 503)" or
// "(HTTP 503)": a plugin that can't fail its 200 any more puts its
// upstream's status in its message (mycf_711's wps-lingxi rows,
// "灵犀上游返回 AIError:AI服务异常(上游暂时不可用,可重试)(HTTP 503)").
var httpSaid = regexp.MustCompile(`[((]\s*HTTP\s*(429|5\d\d)\s*[))]`)
// textStatus is the status an error's words name (httpSaid), 0 when they
// name none, or say the request is too long, or are magpie's own. Only a
// rate limit or a server's failure is read so: a 4xx a message quotes may
// be about anything it fetched, not the request.
func textStatus(msg string) int {
if magpieSaid(msg) || tooLong(http.StatusBadRequest, msg) {
return 0
}
m := httpSaid.FindStringSubmatch(msg)
if m == nil {
return 0
}
n, _ := strconv.Atoi(m[1])
return n
}
// magpieSaid says an error is in magpie's own words, not an upstream's:
// its loop guard ending a reply, an empty reply, a reasoning loop asked
// again. Said by a magpie this one relays to (a LAN peer) too, they are
// no failure of the account that answered (#4855).
func magpieSaid(msg string) bool {
return strings.Contains(msg, loopGuardSaid) || strings.Contains(msg, emptyReply) || strings.Contains(msg, reloopedError)
}
// streamStatus is the status an error in a stream stands for, as a vendor
// would have answered it before streaming.
func streamStatus(msg string) int {
+25 -1
View File
@@ -4740,7 +4740,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// and a vendor that failed (not a reply too long, nor one its
// filter refused) rests, so the retry goes to another member. A
// reply the agent stopped itself is booked as before
try.Fail = failureOf(c, call.Status, []byte(call.Error))
try.Fail = failureOf(c, failedNamed(hw.header, call.Status), []byte(call.Error))
// a compaction a rule sent to a model of its own isn't a turn of
// the conversation: it leaves the stick where it was when it
// answers (below), and breaking off mid-reply forgets nothing
@@ -4766,6 +4766,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
rest := s.restAfter(c, call.Status, hw.header, []byte(call.Error))
try.Fail, try.Rest = rest.Why, &rest
}
if hw.looped == "" && !hw.refusedAfter {
// an upstream's error frame that named its status (#4855,
// mycf_711: wps-lingxi's "(HTTP 503)" rows read status=200)
// is booked at it, in the Routing and Usage views, though
// the agent's 200 went out before it
if named := failedNamed(hw.header, namedStatus([]byte(call.Error))); named >= 400 {
call.Status = named
}
}
} else if call.Status < 400 {
servedCandidate(c, call.Usage.Input+call.Usage.Output+call.Usage.CacheRead+call.Usage.CacheWrite)
// a thinking reply that went on to an answer is one more in the
@@ -6743,6 +6752,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
} else {
sniff.settleWhole()
}
if sniff.failedNamed != 0 {
// the stream's error frame named its own status: the failure is
// booked and rested as it (saidStatusHeader, #4855), while the
// frame itself goes to the client as it came
noteSaidStatus(w, sniff.failedNamed)
}
if gather != nil {
// the gathered stream is read here, not by the client: it gets
// every byte, a last line the upstream never ended included, as
@@ -6824,6 +6839,15 @@ func cutMidReply(name string, err error) string {
return name + ": connection lost mid-reply (" + err.Error() + ")"
}
// noteSaidStatus carries the status a relayed stream's error frame named
// for itself onto the try's writer (#4855), for the routing loop and
// restAfter to read (namedStatusHeader); the client never sees it.
func noteSaidStatus(w http.ResponseWriter, status int) {
if h, ok := w.(*holdWriter); ok {
h.note(namedStatusHeader, strconv.Itoa(status))
}
}
// streamFailure is an error event ending a stream in proto, as each
// protocol's own server sends one mid-reply.
func streamFailure(proto provider.Protocol, msg string) []byte {
+6 -2
View File
@@ -100,13 +100,17 @@ func (t loopTrip) message() string {
quoted = append(quoted, fmt.Sprintf("%q", u))
}
if t.runOn {
return fmt.Sprintf("magpie ended this reply: the model's %s was stuck in a loop, its last %d characters the same over and over without a break (%s), and would have run on to its output limit. Ask again, or set Settings › Models › Replies › Stop looping replies off",
return fmt.Sprintf(loopGuardSaid+": the model's %s was stuck in a loop, its last %d characters the same over and over without a break (%s), and would have run on to its output limit. Ask again, or set Settings › Models › Replies › Stop looping replies off",
what, t.window, strings.Join(quoted, " "))
}
return fmt.Sprintf("magpie ended this reply: the model's %s was stuck in a loop, its last %d lines and sentences all among the same %d (%s), and would have run on to its output limit. Ask again, or set Settings › Models › Replies › Stop looping replies off",
return fmt.Sprintf(loopGuardSaid+": the model's %s was stuck in a loop, its last %d lines and sentences all among the same %d (%s), and would have run on to its output limit. Ask again, or set Settings › Models › Replies › Stop looping replies off",
what, t.window, len(t.units), strings.Join(quoted, " "))
}
// loopGuardSaid begins what the loop guard tells the agent of a reply it
// ended: magpie's words, not a vendor's (magpieSaid).
const loopGuardSaid = "magpie ended this reply"
// feed reads b, the next of the reply as the agent is sent it.
func (g *loopGuard) feed(b []byte) (loopTrip, bool) {
g.pending = append(g.pending, b...)
+28 -5
View File
@@ -533,13 +533,18 @@ func wordsOf(body []byte) []byte { return catalog.Words(body) }
// 200 it came with, OpenAI's "Rate limit reached for gpt-6.1-sol … on
// tokens per min (TPM) … Please try again in 6ms." held usedUpWords'
// "limit reached" and rested the account as out of quota (monater on
// Discord), where its 429 is a minute's rate limit. Words streamStatus
// doesn't know (its 502) keep the 200, and read as before; any other
// status is the reply's own.
// Discord), where its 429 is a minute's rate limit. The status the error
// object names for itself comes first (#4855: a plugin's in-stream frame
// is the only place its runtime can say one); words streamStatus doesn't
// know (its 502) keep the 200, and read as before; any other status is
// the reply's own.
func carriedStatus(status int, body []byte) int {
if status < 200 || status >= 400 {
return status
}
if said := namedStatus(body); said != 0 {
return said
}
if said := streamStatus(string(wordsOf(body))); said != http.StatusBadGateway {
return said
}
@@ -1290,8 +1295,9 @@ func (s *Server) restAfter(c candidate, status int, header http.Header, body []b
// translation without putting it in the response sent to the client.
func (s *Server) restAfterMarked(c candidate, status int, header http.Header, body []byte, sharedPool bool) Rest {
// an error carried under a 200 rests as its own status would, and
// says that status where the rest is shown
status = carriedStatus(status, body)
// says that status where the rest is shown — first among equals the
// one its stream's error frame named outright (#4855)
status = failedNamed(header, carriedStatus(status, body))
now := time.Now()
d := fallbackCooldown
why := failureOf(c, status, body)
@@ -1978,6 +1984,23 @@ const refusedHeader = "X-Magpie-Refused"
// leaves it out; one written straight to the agent carries it, harmlessly.
const resetsHeader = "X-Magpie-Resets-At"
// namedStatusHeader carries, from a relayed stream's error frame to the
// routing loop and restAfter, the status the frame named for itself
// (#4855): a plugin that already sent its 200 can only say what went
// wrong in the frame, and the status it names there — not the one its
// message's words guess — is what the failure rests as. The client never
// sees it.
const namedStatusHeader = "X-Magpie-Named-Status"
// failedNamed is status, or the status a relayed stream's error frame named
// for itself (#4855, namedStatusHeader), which the failure reads as.
func failedNamed(h http.Header, status int) int {
if n, err := strconv.Atoi(h.Get(namedStatusHeader)); err == nil && n >= 400 && n < 600 {
return n
}
return status
}
// resetsNoted is how long until the time keepRetry noted, if it did.
func resetsNoted(h http.Header, now time.Time) time.Duration {
n, err := strconv.ParseInt(h.Get(resetsHeader), 10, 64)
+6
View File
@@ -26,6 +26,9 @@ type usageSniffer struct {
// 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
// failedNamed: the status the error frame named for itself, when it
// named one (#4855); 0 when it didn't
failedNamed int
// tail: what a Chat stream's chunks say of its end (chatTail)
tail chatTail
// found: the searches the reply ran by itself (searchTally)
@@ -126,6 +129,9 @@ func (s *usageSniffer) parse(b []byte) {
}
s.failed = provider.APIError(body, "upstream stream failed")
s.u.ErrType = provider.ErrorType(body)
if body != nil {
s.failedNamed = namedStatus(body)
}
}
}
s.found.see(s.proto, b)
@@ -0,0 +1,213 @@
package gateway
import (
"context"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// relayAsks is a Chat request relayed to a provider that speaks Chat itself
// (a plugin's OpenAI-compatible fetch included, #4855).
func relayAsks(t *testing.T, s *Server, reply string) *httptest.ResponseRecorder {
t.Helper()
fresh(t)
setup(t, provider.Chat, &fake{t: t, reply: reply})
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/v1/chat/completions",
strings.NewReader(`{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`)))
return w
}
// A relayed stream's error frame names its own status (#4855): a plugin
// that already sent 200 can only say what went wrong in the frame, and its
// code and status are the routing signal. The frame is relayed as it came
// and the turn fails as it would at the status it named, not as a 200
// whose words name nothing.
func TestRelayStreamErrorFrameSaysItsStatus(t *testing.T) {
const frame = `{"error":{"message":"the upstream timed out","type":"upstream_error","code":"upstream_timeout","status":504}}`
for _, c := range []struct {
name string
reply string
wantStatus int // the try's failure, and the rest's
wantFail, wantText string // what the rest says of it
}{
{"mid-reply", sse(
`data: {"id":"c1","choices":[{"index":0,"delta":{"content":"partial text"}}]}`,
`data: `+frame), 504, failOther, "Gateway Timeout"},
{"terse 429", sse(
`data: {"id":"c1","choices":[{"index":0,"delta":{"content":"partial text"}}]}`,
`data: {"error":{"message":"busy","type":"upstream_error","code":"rate_limit","status":429}}`), 429, failRate, "Too Many Requests"},
} {
t.Run(c.name, func(t *testing.T) {
s := New()
w := relayAsks(t, s, c.reply)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"partial text"`) || !strings.Contains(w.Body.String(), `"status":`+strconv.Itoa(c.wantStatus)) {
t.Fatalf("the frame was not relayed: %d %s", w.Code, w.Body)
}
state := s.Trace(context.Background(), 0, 0)
if len(state.Routes) != 1 {
t.Fatalf("routes %d", len(state.Routes))
}
var try *Try
for i := range state.Routes[0].Tries {
if state.Routes[0].Tries[i].Rest != nil {
try = &state.Routes[0].Tries[i]
}
}
if try == nil {
t.Fatalf("the turn rested nobody: %+v", state.Routes[0].Tries)
}
if try.Fail != c.wantFail || try.Rest.Status != c.wantStatus {
t.Fatalf("failed as %s at %d, want %s at %d", try.Fail, try.Rest.Status, c.wantFail, c.wantStatus)
}
if !strings.Contains(try.Rest.Error, c.wantText) {
t.Fatalf("the rest says %q, want it to name %q", try.Rest.Error, c.wantText)
}
restingUntil.Lock()
var rest *Rest
for _, r := range restingUntil.note {
rest = &r
}
restingUntil.Unlock()
if rest == nil || rest.Status != c.wantStatus || rest.Why != c.wantFail {
t.Fatalf("rested %+v, want %s at %d", rest, c.wantFail, c.wantStatus)
}
})
}
// the frame as the stream's first event, nothing said before it: the
// frame is relayed as it came, and the try fails at the status it
// named, not the 502 its words guess
t.Run("first event", func(t *testing.T) {
s := New()
w := relayAsks(t, s, sse(`data: `+frame))
if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":504`) {
t.Fatalf("stream: %d %s", w.Code, w.Body)
}
state := s.Trace(context.Background(), 0, 0)
if len(state.Routes) != 1 || state.Routes[0].Status != 504 {
t.Fatalf("route: %+v", state.Routes)
}
for _, u := range usage.Load(time.Time{}) {
if u.Status != 504 || !u.Failed() {
t.Fatalf("usage: %+v", u)
}
}
})
}
// An error frame that names no status reads as before: the words guess,
// and a reply whose words name nothing is a 502.
func TestRelayStreamErrorFrameWithoutStatusAsBefore(t *testing.T) {
s := New()
w := relayAsks(t, s, sse(
`data: {"id":"c1","choices":[{"index":0,"delta":{"content":"partial text"}}]}`,
`data: {"error":{"type":"server_error","message":"synthetic stream failure"}}`))
if w.Code != 200 || !strings.Contains(w.Body.String(), "synthetic stream failure") {
t.Fatalf("stream: %d %s", w.Code, w.Body)
}
state := s.Trace(context.Background(), 0, 0)
var try *Try
for i := range state.Routes[0].Tries {
if state.Routes[0].Tries[i].Rest != nil {
try = &state.Routes[0].Tries[i]
}
}
if try == nil || try.Fail != failOther || try.Rest.Status != 200 {
t.Fatalf("a frame that named no status failed as %+v, want other at 200 as before", try)
}
}
// mycf_711's wps-lingxi rows (#4855): the plugin, its 200 sent, puts its
// upstream's status only in the frame's words, "(HTTP 503)", under a
// string code. Main booked the call at 200, its rest "OK: …"; the status
// the words name is the one it fails, rests and is booked at. A 4xx the
// words quote is not read so, and neither is magpie's own loop guard said
// by a magpie this one relays to: no upstream failed for it.
func TestRelayStreamErrorFrameNamesItsStatusInWords(t *testing.T) {
const said503 = `data: {"error":{"message":"灵犀上游返回 AIError:AI服务异常(上游暂时不可用,可重试)(HTTP 503)","type":"upstream_error","code":"upstream_error"}}`
const began = `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"partial text"}}]}`
routeOf := func(t *testing.T, s *Server) (Route, *Try) {
t.Helper()
state := s.Trace(context.Background(), 0, 0)
if len(state.Routes) != 1 {
t.Fatalf("routes %d", len(state.Routes))
}
var try *Try
for i := range state.Routes[0].Tries {
if state.Routes[0].Tries[i].Rest != nil {
try = &state.Routes[0].Tries[i]
}
}
return state.Routes[0], try
}
t.Run("mid-reply", func(t *testing.T) {
s := New()
w := relayAsks(t, s, sse(began, said503))
if w.Code != 200 || !strings.Contains(w.Body.String(), "partial text") || !strings.Contains(w.Body.String(), "(HTTP 503)") {
t.Fatalf("the frame was not relayed: %d %s", w.Code, w.Body)
}
route, try := routeOf(t, s)
if try == nil || try.Rest.Status != 503 || strings.HasPrefix(try.Rest.Error, "OK") {
t.Fatalf("rested %+v, want at 503", try)
}
if route.Status != 503 {
t.Fatalf("route booked at %d, want 503", route.Status)
}
rows := usage.Load(time.Time{})
if len(rows) != 1 || rows[0].Status != 503 || !rows[0].Failed() {
t.Fatalf("usage %+v, want one failed row at 503", rows)
}
})
t.Run("first event", func(t *testing.T) {
s := New()
relayAsks(t, s, sse(said503))
route, _ := routeOf(t, s)
if route.Status != 503 {
t.Fatalf("route booked at %d, want 503 (the words' guess is 502)", route.Status)
}
})
t.Run("a 4xx quoted", func(t *testing.T) {
s := New()
relayAsks(t, s, sse(began, `data: {"error":{"message":"the image link answered (HTTP 404)","type":"upstream_error"}}`))
route, try := routeOf(t, s)
if route.Status != 200 || try == nil || try.Rest.Status != 200 {
t.Fatalf("a quoted 404 was read as the reply's: route %d, try %+v", route.Status, try)
}
})
t.Run("a peer's loop guard", func(t *testing.T) {
s := New()
relayAsks(t, s, sse(began, `data: {"error":{"message":"magpie ended this reply: the model's text was stuck in a loop, its last 400 characters the same over and over without a break (\"ab\"), and would have run on to its output limit (HTTP 502)","type":"api_error","code":502}}`))
route, try := routeOf(t, s)
if try != nil || route.Status != 200 {
t.Fatalf("magpie's own loop guard rested %+v, route at %d", try, route.Status)
}
})
}
// What names a status, and what doesn't (#4855).
func TestNamedStatusOf(t *testing.T) {
for raw, want := range map[string]int{
`{"message":"x","status":504}`: 504,
`{"message":"x","code":429}`: 429,
`{"message":"x","code":"429"}`: 0,
`{"message":"x","status":200}`: 0,
`{"message":"灵犀上游返回 AuditFailed:…(HTTP 502)"}`: 502,
`{"message":"upstream said (HTTP 401)"}`: 0,
`{"message":"prompt is too long (HTTP 503)"}`: 0,
`{"message":"input exceeds the context window","status":500}`: 0,
`"灵犀上游返回 AIError:AI服务异常(HTTP 503)"`: 503,
`{"message":"` + emptyReply + ` (HTTP 502)","status":502}`: 0,
`{"message":"` + loopGuardSaid + `: … (HTTP 502)","status":502}`: 0,
} {
if got := namedStatusOf([]byte(raw)); got != want {
t.Errorf("namedStatusOf(%s) = %d, want %d", raw, got, want)
}
}
}