Files
magpie/internal/gateway/stream_error_passing_test.go
T
JoeyWu-tech 47175a68ff gateway: an error in a kept-alive stream names the model the agent asked for (#3728)
jilen (#3728): fx asked magpie for codex/gpt-6.1-sol on
/v1/chat/completions and showed "system: InvalidChunk: Invalid Chat
Completions response at model (event 1).", while the usage log had the
vendor's 502, an EOF from chatgpt.com. No stream was saved, but fx's
InvalidChunk at event 1 says one had begun: magpie had kept fx alive
with the stream's headers and comments, so the failure went as an
event of that stream (streamError). The encoder streamError made, from
an empty Request, began the message before the error with a Chat chunk
whose "model" was "". fx takes a chunk with an empty model for a broken
one and stops there, so it never read the error after it. Anthropic's
message_start and Responses' response.created, response.in_progress
and response.failed went out with an empty model the same way.

keptAlive now keeps the model the request names when serve takes it,
as magpie spells it there: a flat id (a~m) is its catalog id, a dashed
Claude id its dotted one, and Codex's own model through magpie's
accounts codex/<model>. An effort the agent put on the model is kept on
it (a/m:high), the name it asked by. serve has it from the body it
already read for askedAt; on Codex's own sign-in (codexUpstreamOn) it
is the model Codex wrote, which its turn already read. Neither reads
the body again. streamError begins with that model, from failTo,
holdWriter.release and Codex's failWith. Gemini's error names no model,
as before. docs/subsystems/gateway-routing.md says so.

fx still shows no reason. Its Chat reader ends the stream with
ProviderError at an event with an "error" key and keeps nothing of it
(src/gateway/chat_completions_protocol.zig:723 in fx 0.0.14, :710 on
fx's main e71a663b); only an error status's body reaches its message.
So fx says ProviderError where it said InvalidChunk, and the vendor's
EOF is in the stream and magpie's usage log, not in fx.

Not changed: an error after a reply that already went, a loop cut's
(cutLoop), starts a message of its own after the vendor's, under a new
id. A model in it wouldn't help, fx stops at the new id: #3792. Nor the
error's shape: the encoders still begin a message ahead of it. fx looks
for an event's "error" before its id and model, so an error alone would
get past it too, but no other agent was tried on one; that is #3792's
question as well.

What was run (tree 908b9857, on origin/main 2beed3b0, go1.26.8,
linux/amd64):
- TestStreamErrorNamesTheModel, new: streamError in each protocol with
  the report's model and message. Chat's, Anthropic's and Responses'
  events name that model and no other, Gemini's none, and each has the
  message.
- TestKeptAliveChatErrorNamesTheModel, new: a Chat stream through serve,
  kept alive while the vendor says nothing, then the vendor gone with no
  reply (the EOF), or answering 502, 413, a 200 that isn't a stream, or
  a JSON 200 that is no reply. In each, the stream's first chunk names
  a/m and the error follows; the 413's says request_too_large. Asked
  for a/m:high, the vendor gone, the first chunk names a/m:high.
- TestKeptAliveChatOnCodexErrorNamesTheModel, new: the report's route, a
  Chat stream on magpie's codex provider (Codex's sign-in), the ChatGPT
  backend a local server that says nothing until the stream was kept
  alive and then hangs up, each time it is asked. The first chunk names
  codex/gpt-5.5, and the error after it has the backend's EOF.
- TestKeptAliveCodexErrorNamesTheModel, new: Codex on its own sign-in,
  the backend overloaded, Codex kept alive while the turn waits to be
  asked again, then the backend gone. Every model its events name is
  gpt-5.5, the model Codex asked for, and they name one.
- The four, -count=50: ok.
- -race -count=20 -cpu 1,2 over them and the stream tests beside them
  (TestStreamError*, TestGroupLastFailureInStreamSaysItPasses,
  TestStreamedByteCap, TestLoopEnds, TestLoopCutMidLine,
  TestCodexOneAccountOverload, the Quiet ones): ok, no race.
- Broken by hand, each red:
  - streamError's encoder made from an empty Request again:
    TestStreamErrorNamesTheModel, every case of
    TestKeptAliveChatErrorNamesTheModel,
    TestKeptAliveChatOnCodexErrorNamesTheModel and
    TestKeptAliveCodexErrorNamesTheModel.
  - serve's keptAlive with no model: every case of
    TestKeptAliveChatErrorNamesTheModel and
    TestKeptAliveChatOnCodexErrorNamesTheModel.
  - keptAlive given the model without its effort: the a/m:high case
    alone.
  - failTo naming none: the 413 case.
  - holdWriter.release naming none for a reply that is no reply: the
    JSON 200's case; for an error status: the vendor gone, a/m:high,
    the 502, the 200 that isn't a stream, and
    TestKeptAliveChatOnCodexErrorNamesTheModel.
  - Codex's keptAlive with no model, or its failWith naming none:
    TestKeptAliveCodexErrorNamesTheModel.
- A real run: magpie built at 2beed3b0 and at this tree (go build
  -tags nogui -buildvcs=false), magpie serve in a sandbox HOME, a
  provider (a local server) that holds its first answer 20s and then
  hangs up, or answers 502, and fx 0.0.14 asking it through
  /v1/chat/completions (fx ask, its settings' provider
  openai-chat-completions at the gateway), with --json and without.
  fx exits 1 after about 53s each time: InvalidChunk at 2beed3b0, all
  four times (hang-up and 502, --json and not), ProviderError at this
  tree, all four. curl asking the same: ": keepalive" lines, then a
  first chunk with "model":"" (2beed3b0) or "model":"up/m" (this
  tree), then the error with the vendor's EOF or 502.
- gofmt -l; go vet -tags nogui and go build -tags nogui for linux,
  windows and darwin, and go vet and go build for windows without the
  tag: exit 0 each. go vet and go build without the tag on linux: exit
  1 (this box has no GTK or WebKitGTK dev packages).
- go test -tags nogui -count=1 -timeout 45m ./..., Bun 1.4.2 on PATH:
  67 ok, and 7 red, none in what this changes: agent
  TestCodexDriftReached (#3398); TestInstalledVersion,
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); davsync
  TestSyncTeraCloudStillSeesOtherWrites (#3420); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (#3640);
  gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649); provider's "close of synctest channel from outside bubble"
  from TestUnreadLoginsWriteErrorsKeepCredentials (#3632).

Not tried: the real chatgpt.com (it needs a ChatGPT account); the
ChatGPT backend was a local server that hangs up. fx's interactive
view, where the report's line came from.

Review (yetone/magpie maintainer agent), for jilen's #3728:
- Read every line. The only encoder built with an empty Request is
  streamError's; its five callers (failTo, holdWriter.release's two
  cases, cutLoop, Codex's failWith) are each given a model, cutLoop ""
  on purpose (#3792).
- Red by hand at c711c3391 on 1cbdda25b, macOS, go1.27: streamError
  back to &Request{}: all four new tests red; keptAlive built without
  model: the two Chat kept-alive tests red; Codex's kept.model unset:
  TestKeptAliveCodexErrorNamesTheModel red. Green restored.
- go test -tags nogui -race ./internal/gateway -run
  'NamesTheModel|TestStreamError': ok. Full go test -tags nogui
  -timeout 45m ./internal/gateway: ok (573s).
- gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
  ./internal/gateway: ok.
- Real run: magpie serve (base and patched builds) in a sandbox HOME, a
  fake Chat vendor that holds 20s then answers 502, a streamed
  /v1/chat/completions for fakev/fake-model. Base: the kept-alive first
  chunk says "model":"", then the error. Patched: "model":
  "fakev/fake-model", then the same error.
- Rebased onto ab546a4ee (gateway changed since): gofmt, vet linux and
  windows, and go test ./internal/gateway -run
  'NamesTheModel|StreamError|KeptAlive|KeepAlive|Alive|Codex' again
  there: ok. The full package ran at the earlier base only.
- Not tried: fx itself, the real ChatGPT backend.
2026-10-27 16:05:50 +08:00

170 lines
7.2 KiB
Go

package gateway
import (
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"time"
"github.com/tidwall/gjson"
"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)
}
}
// 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 = "<html>\r\n<head><title>413 Request Entity Too Large</title></head>\r\n<body>\r\n<center><h1>413 Request Entity Too Large</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\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, "a/m", 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)
}
}
}