diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index dda2ac4b0..af5e381b4 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -106,6 +106,7 @@ recorded as a prediction failure (`noPrediction`). - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. - A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A reply passed through in its own protocol isn't read this way. - A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). +- An error that reaches the agent in a stream already begun can't carry its status, so `streamError` says it in the words (`saysPassing`, #2372, zminds): for a status that may pass (408, 429, 5xx) whose text names none of the words a text-judging agent retries on (Pi decides by its `errorMessage` alone), it appends `(: you can retry your request)`; a request's own fault (400, 401, 404 …) and a text that already says so are left as they were. `TestStreamErrorSaysItPasses` holds Pi's own lists; `TestGroupLastFailureInStreamSaysItPasses` runs a group whose last member fails after the keepalive. - Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held. - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off. - A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a5b2f78bf..4de5f04a1 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6248,13 +6248,33 @@ func failTo(w http.ResponseWriter, a *keptAlive, proto provider.Protocol, status func streamError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) { sw := newSSEWriter(w) sw.begun = true - ev := Event{Kind: KError, Text: msg, Status: status} + ev := Event{Kind: KError, Text: saysPassing(status, msg), Status: status} if tooLong(status, msg) { ev.Code = "context_length_exceeded" } makeEncoder(proto, sw, &Request{}).event(ev) } +// passingSaid matches the words an agent that reads only an error's text +// takes for a failure worth asking again (Pi's isRetryableError, #2372): +// one of the usual statuses, a timeout, a rate limit, a busy or +// unreachable server. +var passingSaid = regexp.MustCompile(`(?i)\b(429|500|502|503|504)\b|timed? ?out|rate.?limit|too many requests|overloaded|service.?unavailable|server.?error|internal.?error|connection.?(error|refused|reset)|retry your request|try your request again`) + +// saysPassing is msg, an error sent in a stream whose status the agent +// can no longer be told, with the status said in it when it is one a +// moment may clear (408, 429, 5xx) and msg says so in no words an agent +// knows: "Upstream service temporarily unavailable" and "no first token in +// 30s" reached Pi, which judges by the text alone, as errors not worth +// asking again, while Claude Code and Codex, told the same as a status, +// asked again and were answered (#2372). +func saysPassing(status int, msg string) string { + if status != http.StatusRequestTimeout && status != http.StatusTooManyRequests && status < 500 || passingSaid.MatchString(msg) { + return msg + } + return fmt.Sprintf("%s (%d: you can retry your request)", msg, status) +} + // writeError answers in the client's own error shape. func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) int { return writeErrorSaid(w, proto, status, msg, nil, nil) diff --git a/internal/gateway/stream_error_passing_test.go b/internal/gateway/stream_error_passing_test.go new file mode 100644 index 000000000..317025120 --- /dev/null +++ b/internal/gateway/stream_error_passing_test.go @@ -0,0 +1,101 @@ +package gateway + +import ( + "net/http" + "regexp" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// piRetryable is Pi's isRetryableError (agent-session.ts, 1.2.0), as +// zminds quoted it on #2372: the text alone decides, a deny-list first. +var ( + piRetry = regexp.MustCompile(`(?i)overloaded|rate.?limit|too many requests|429|500|502|503|504|520|524|service.?unavailable|server.?error|internal.?error|timed? out|timeout|terminated|connection.?error|connection.?refused|ended without|socket hang up|fetch failed|ENOTFOUND|EAI_AGAIN|websocket closed|retry delay|you can retry your request|try your request again|please retry your request|ResourceExhausted`) + piDeny = regexp.MustCompile(`(?i)insufficient_quota|quota exceeded|available balance|out of budget|billing|GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|subscription_sharing_usage_limit_exceeded`) +) + +func piRetries(msg string) bool { return !piDeny.MatchString(msg) && piRetry.MatchString(msg) } + +// An error that reaches the agent in a stream already begun can't say its +// status, and the words of one a moment may clear are said for it: Pi +// judges an error by its text alone, and ended the turn on each of these, +// which Claude Code and Codex asked again (#2372, the texts zminds' Pi +// sessions recorded). A request's own fault is left as it was said. +func TestStreamErrorSaysItPasses(t *testing.T) { + for _, c := range []struct { + status int + msg string + }{ + {503, "Upstream service temporarily unavailable"}, + {502, "Upstream response stream was interrupted"}, + {504, "A: no first token in 30s"}, + {502, "Upstream request failed"}, + {502, "Upstream HTTP/2 stream failed"}, + {521, "521 status code (no body)"}, + {503, "The service is temporarily unavailable. Please retry later."}, + {429, "Too many pending requests, please retry later"}, + {408, "the request took too long"}, + } { + if got := saysPassing(c.status, c.msg); !piRetries(got) || !strings.HasPrefix(got, c.msg) { + t.Errorf("%d %q is told %q", c.status, c.msg, got) + } + } + for _, msg := range []string{"Upstream rate limit exceeded, please retry later", "503: Service temporarily unavailable", "connection error"} { + if got := saysPassing(503, msg); got != msg { + t.Errorf("%q, already said, is told %q", msg, got) + } + } + for _, c := range []struct { + status int + msg string + }{ + {400, "Invalid request parameters"}, + {401, "invalid api key"}, + {404, "model not found"}, + } { + if got := saysPassing(c.status, c.msg); got != c.msg { + t.Errorf("%d %q is told %q", c.status, c.msg, got) + } + } +} + +// Through a group: a member let go for no first token, the stream's +// headers sent to keep the agent alive meanwhile, and the last member +// failing with a relay's words — the agent's stream error says what Pi +// asks again for, in each protocol it reads. +func TestGroupLastFailureInStreamSaysItPasses(t *testing.T) { + old := retryPause + retryPause = time.Millisecond + t.Cleanup(func() { retryPause = old }) + k := keepHeldAfter + keepHeldAfter = 30 * time.Millisecond + t.Cleanup(func() { keepHeldAfter = k }) + fresh(t) + keepFast(t, keepaliveGap, 20*time.Millisecond, keepaliveLongest) + a := &slowStart{wait: 10 * time.Second} + b := &scripted{replies: []reply{{503, "application/json", `{"error":{"message":"Upstream service temporarily unavailable","type":"upstream_error"}}`}}} + slowOn(t, "a", a) + scriptedOn(t, "b", provider.Chat, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered, FirstToken: 1}); err != nil { + t.Fatal(err) + } + s := New() + code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != http.StatusOK || !strings.Contains(body, ": keepalive") { + t.Fatalf("the agent wasn't sent the stream's headers first: %d %q", code, body) + } + i := strings.Index(body, "Upstream service temporarily unavailable") + if i < 0 { + t.Fatalf("no error in the stream: %q", body) + } + said := body[i:] + if j := strings.Index(said, `"`); j >= 0 { + said = said[:j] + } + if !piRetries(said) { + t.Fatalf("the stream's error %q is one Pi doesn't ask again for: %q", said, body) + } +}