From 08400f4ebdc4954fa2c5f4dde649c955f97e4a34 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 17 Oct 2026 10:15:12 +0800 Subject: [PATCH] gateway: a byte cap after the stream has begun says request_too_large, so Pi compacts (#2533) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A vendor's 413 that came after the stream's headers had gone out (a keepalive sent while the vendor was quiet) reached Pi as a stream error of type api_error saying "413 Request Entity Too Large". Pi compacts only when the error's text says request_too_large (overflow.ts), so the turn stopped. A 413 before the headers was already typed request_too_large (writeErrorSaid, 97f264c7). streamError, which every failure in a stream already begun goes through (failTo and holdWriter's), appends "(request_too_large)" to the text of a 413 that isn't a context overflow and doesn't say it already; the Chat and Anthropic encoders type that event request_too_large. Gemini keeps its own status shape; an overflow stays context_length_exceeded. Review change (on top of ggbdpq's 8a278645): the test matched request_too_large anywhere in the body, so Chat's new type alone passed it: with the text append taken out by hand it stayed green. It now reads the error event's message (what Pi reads) and type. The new TestStreamErrorByteCapInEveryShape runs streamError for Chat, Anthropic, Responses and Gemini, and for a 413 that says the prompt is too long. Run: - With gateway.go, chat.go and anthropic.go put back: both tests FAIL. With only the text append taken out: both FAIL. With only Anthropic's type taken out: TestStreamErrorByteCapInEveryShape FAILs ("anthropic … want "type":"request_too_large""). Restored: ok. - TestBodyRejectionErrorShapes, TestStreamErrorSaysItPasses, TestGroupLastFailureInStreamSaysItPasses: ok. - Full suite, go test -tags nogui -timeout 45m ./... (set -o pipefail, sandbox HOME, load ~350) at 0224e826f (these four commits on ebf3f48f7) plus #2545's patch: every package ok except internal/agent, whose one red (TestRekeyGivesWSLAgentTheSharingKey) is #2545's, which was dropped (problems posted on #2545). internal/agent alone at 0224e826f: ok. Rebased on dccfefdf7 (#2635, internal/library only): build, vet, internal/library ok. gofmt -l clean; go vet darwin (gui), GOOS=linux and GOOS=windows -tags nogui: clean. GUI (i18n-keys, gui-de/ja/zh-TW, import-*, key-import, login-import): all pass except login-import's Chromium case, which fails the same alone on origin/main ebf3f48f7 (#1307, output posted there). Not tried: a real nginx 413 or a real Pi compacting after it. Co-authored-by: ggbdpq --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/anthropic.go | 8 ++- internal/gateway/chat.go | 8 ++- internal/gateway/gateway.go | 16 ++++- internal/gateway/stream_error_passing_test.go | 68 +++++++++++++++++++ 5 files changed, 97 insertions(+), 5 deletions(-) diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 36bb5204e..6fe8e08cb 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -110,7 +110,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`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, #2446, `TestPassthroughStreamCutMidLine`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — 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. +- 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. A 413 byte cap in that stream says `request_too_large` in the error text, and Chat and Anthropic name that type, so Pi compacts; Gemini keeps its own status shape (`TestStreamedByteCapSaysRequestTooLargeToPi`, `TestStreamErrorByteCapInEveryShape`). - 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, after a blank line (two newlines when that write stopped inside a line, `holdWriter.atLine`, #2446), 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 reply passed through in the agent's own protocol is asked again once too, at the fallback loop (`holdWriter.mayReloop`, `letGoLoop`; #2436, lqisgod: pi's Chat stream to WorkBuddy was cut at once): when nothing of the try has reached the agent yet, in any protocol, its held bytes are dropped; when its reasoning is already passing, only a Chat stream goes on, written up to the end of the tripping event, with the next try's chunks after it. An Anthropic or Responses stream already passing still ends with the error, since a second `message_start` or `response.created` can't follow. Each re-ask, in place or at the fallback loop, counts in the usage record's tries. A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`). 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/anthropic.go b/internal/gateway/anthropic.go index 5ea8d69c1..dfe818b44 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "encoding/json" "fmt" + "net/http" "regexp" "slices" "strconv" @@ -1522,7 +1523,12 @@ func (e *anthropicEncoder) event(ev Event) { e.index++ case KError: e.close() - failed := map[string]any{"type": "api_error", "message": ev.Text} + typ := "api_error" + if ev.Status == http.StatusRequestEntityTooLarge && ev.Code != "context_length_exceeded" { + // the same type a 413 JSON body carries (writeErrorSaid) + typ = "request_too_large" + } + failed := map[string]any{"type": typ, "message": ev.Text} if ev.Code != "" { failed["code"] = ev.Code // preserve the upstream error type, including refusals } diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 5e5bd7b37..b6b38ddb6 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -8,6 +8,7 @@ import ( "maps" "mime" "net" + "net/http" "path" "regexp" "slices" @@ -1434,7 +1435,12 @@ func (e *chatEncoder) event(ev Event) { "function": map[string]any{"arguments": ev.Text}}}}, nil, nil) } case KError: - failed := map[string]any{"message": ev.Text, "type": "api_error"} + typ := "api_error" + if ev.Status == http.StatusRequestEntityTooLarge && ev.Code != "context_length_exceeded" { + // the same type a 413 JSON body carries (writeErrorSaid) + typ = "request_too_large" + } + failed := map[string]any{"message": ev.Text, "type": typ} if ev.Code != "" { failed["code"] = ev.Code // preserve the upstream error type, including refusals } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 410d6674b..f162ed72d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6497,10 +6497,22 @@ 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: saysPassing(status, msg), Status: status} - if tooLong(status, msg) { + text := saysPassing(status, msg) + ev := Event{Kind: KError, Text: text, Status: status} + overflow := tooLong(status, msg) + if overflow { ev.Code = "context_length_exceeded" } + // A 413 before the headers go out is typed request_too_large + // (writeErrorSaid). Once they have, Pi reads only this event's text + // (#2372) and does not compact on "Request Entity Too Large". Gemini + // keeps its own status shape. + byteCap := status == http.StatusRequestEntityTooLarge && !overflow + ownShape := proto == provider.Gemini + alreadySaid := strings.Contains(strings.ToLower(text), "request_too_large") + if byteCap && !ownShape && !alreadySaid { + ev.Text = text + " (request_too_large)" + } makeEncoder(proto, sw, &Request{}).event(ev) } diff --git a/internal/gateway/stream_error_passing_test.go b/internal/gateway/stream_error_passing_test.go index 317025120..c9e6af441 100644 --- a/internal/gateway/stream_error_passing_test.go +++ b/internal/gateway/stream_error_passing_test.go @@ -2,11 +2,13 @@ package gateway import ( "net/http" + "net/http/httptest" "regexp" "strings" "testing" "time" + "github.com/tidwall/gjson" "github.com/yetone/magpie/internal/provider" ) @@ -99,3 +101,69 @@ func TestGroupLastFailureInStreamSaysItPasses(t *testing.T) { t.Fatalf("the stream's error %q is one Pi doesn't ask again for: %q", said, body) } } + +// A vendor byte cap that lands after the stream's headers have already +// gone out (a keepalive while the vendor is still quiet) reaches the +// agent as an error event. Pi compacts when that text says +// request_too_large (overflow.ts), the same word a 413 JSON body carries +// before the stream starts. "Request Entity Too Large" does not, so the +// turn stops (@wilsonxuuuu, once the stream is already open). +func TestStreamedByteCapSaysRequestTooLargeToPi(t *testing.T) { + quietFast(t) + fresh(t) + const nginx = "\r\n413 Request Entity Too Large\r\n\r\n

413 Request Entity Too Large

\r\n
nginx
\r\n\r\n\r\n" + piOverflow := regexp.MustCompile(`(?i)request_too_large`) + hang := make(chan struct{}) + scriptedOn(t, "a", provider.Chat, &scripted{hang: hang, replies: []reply{{413, "text/html", nginx}}}) + heard := make(chan struct{}) + go func() { + select { + case <-heard: + case <-time.After(5 * time.Second): + } + close(hang) + }() + code, body, _ := askChat(t, New(), "a/m", heard) + if !strings.Contains(body, ": keepalive") { + t.Fatalf("the stream's headers never went out ahead of the 413: %d %q", code, body) + } + // Pi reads the error's message, not its type: the word is in the text + var msg, typ string + for _, line := range strings.Split(body, "\n") { + if d, ok := strings.CutPrefix(line, "data: "); ok && gjson.Get(d, "error").Exists() { + msg, typ = gjson.Get(d, "error.message").String(), gjson.Get(d, "error.type").String() + } + } + if !piOverflow.MatchString(msg) || typ != "request_too_large" || strings.Contains(body, "context_length_exceeded") { + t.Fatalf("byte cap in a stream already begun: %d %s", code, body) + } +} + +// Every shape a stream already begun says a 413 in (#2533): the text names +// request_too_large for Chat, Anthropic and Responses, and Chat's and +// Anthropic's type is it; Gemini keeps its own status shape; a 413 that +// says the context is too long stays context_length_exceeded. +func TestStreamErrorByteCapInEveryShape(t *testing.T) { + const capped = "A: 413 Request Entity Too Large" + for _, c := range []struct { + proto provider.Protocol + msg string + text, kind string // what the event's message and type say + }{ + {provider.Chat, capped, "request_too_large", `"type":"request_too_large"`}, + {provider.Anthropic, capped, "request_too_large", `"type":"request_too_large"`}, + {provider.Responses, capped, "request_too_large", `"code":"server_error"`}, + {provider.Gemini, capped, "", `"status"`}, + {provider.Chat, "A: 413 prompt is too long: 300000 tokens > 200000 maximum", "", `"code":"context_length_exceeded"`}, + } { + rec := httptest.NewRecorder() + streamError(rec, c.proto, http.StatusRequestEntityTooLarge, c.msg) + body := rec.Body.String() + if !strings.Contains(body, c.kind) { + t.Errorf("%s %q: want %s in %s", c.proto, c.msg, c.kind, body) + } + if said := strings.Contains(body, "(request_too_large)"); said != (c.text != "") { + t.Errorf("%s %q: the text says request_too_large: %v, want %v: %s", c.proto, c.msg, said, c.text != "", body) + } + } +}