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.
This commit is contained in:
JoeyWu-tech
2026-10-27 16:05:50 +08:00
committed by yetone
parent ff16f6c552
commit 47175a68ff
6 changed files with 269 additions and 12 deletions
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -964,6 +964,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
who = "Codex's API key"
}
model := modelOf(body)
kept.model = model // only a turn is kept alive (overload)
effort = requestEffort(provider.Responses, body)
seat := Weighed{ID: "codex", Provider: "openai", Name: "OpenAI", Icon: "openai", Who: who, Kind: "account", Agent: "codex", Model: model}
link := s.titlePrompts.observe(r, body, metadata, kind, start)
@@ -1031,7 +1032,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
// error once it was sent the stream's headers while it waited
failWith := func(status int, msg string) {
if kept.sent {
streamError(w, provider.Responses, status, msg)
streamError(w, provider.Responses, kept.model, status, msg)
return
}
writeError(w, provider.Responses, status, msg)
+8 -3
View File
@@ -1979,7 +1979,9 @@ func (h *holdWriter) cutLoop(b []byte, t loopTrip) (int, error) {
} else {
io.WriteString(h.w, "\n\n")
}
streamError(h.w, proto, http.StatusBadGateway, msg)
// no model: the reply went ahead under its own id and model, and an
// error that starts a message of its own after it is #3792
streamError(h.w, proto, "", http.StatusBadGateway, msg)
h.looped, h.ended = msg, true
h.flush()
if h.stop != nil {
@@ -2231,6 +2233,9 @@ var keepHeldAfter = holdLongest
// a reply: the stream's headers and SSE comments, nothing of the reply.
type keptAlive struct {
proto provider.Protocol
// model is the one the agent asked for, which an error sent in the
// stream names (streamError, #3728)
model string
sent bool // the stream's 200 and headers went out
at time.Time // the last comment
// told is when the agent was last sent anything of a reply, else when
@@ -2508,10 +2513,10 @@ func (h *holdWriter) release() {
case h.failure != 0:
// a 200 that is no reply of the protocol's (settle)
who := cmp.Or(h.header.Get(providerHeader), "the provider")
streamError(h.w, h.alive.proto, h.failure, who+" "+h.failMsg)
streamError(h.w, h.alive.proto, h.alive.model, h.failure, who+" "+h.failMsg)
case h.status >= 400:
// an error status, once the agent has a stream: told as its error
streamError(h.w, h.alive.proto, h.status, provider.APIError(h.held.Bytes(), http.StatusText(h.status)))
streamError(h.w, h.alive.proto, h.alive.model, h.status, provider.APIError(h.held.Bytes(), http.StatusText(h.status)))
default:
// a reply given whole by a vendor that ignored stream:true,
// after the agent was kept alive: sent as the stream it asked
+11 -6
View File
@@ -1705,7 +1705,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
// a model asked for at an effort of its own (a Claude Code tier, #536)
// is the model, every try of it asked for that effort
asked, askedEffort := askedAt(modelOf(body))
askedFor := modelOf(body) // as it reaches serve, which an error in its stream names (keptAlive)
asked, askedEffort := askedAt(askedFor)
if askedEffort != "" {
body = rewriteModel(body, asked)
plain = rewriteModel(plain, asked)
@@ -2438,7 +2439,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
unlisted, unlistedW = nil, nil
}
// what the tries' held streams sent the agent ahead of a reply (#751)
kept := &keptAlive{proto: from, told: start}
kept := &keptAlive{proto: from, model: askedFor, told: start}
if k := handedOnOf(r); k != nil {
// Codex's own sign-in waited for first, with Codex kept alive
kept = k
@@ -7351,13 +7352,17 @@ func failTo(w http.ResponseWriter, a *keptAlive, proto provider.Protocol, status
if a == nil || !a.sent {
return writeError(w, proto, status, msg)
}
streamError(w, proto, status, msg)
streamError(w, proto, a.model, status, msg)
return status
}
// streamError writes an error as an event of the client's stream, its
// headers already sent.
func streamError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) {
// headers already sent. Wherever the protocol says a model with it (Chat's
// first chunk, Anthropic's message_start, Responses' response.created and
// the events after it), it is model, the one the agent asked for, none
// from cutLoop (#3792): with none, fx took Chat's first chunk for a broken
// one and stopped there (#3728).
func streamError(w http.ResponseWriter, proto provider.Protocol, model string, status int, msg string) {
sw := newSSEWriter(w)
sw.begun = true
text := saysPassing(status, msg)
@@ -7376,7 +7381,7 @@ func streamError(w http.ResponseWriter, proto provider.Protocol, status int, msg
if byteCap && !ownShape && !alreadySaid {
ev.Text = text + " (request_too_large)"
}
makeEncoder(proto, sw, &Request{}).event(ev)
makeEncoder(proto, sw, &Request{Model: model}).event(ev)
}
// passingSaid matches the words an agent that reads only an error's text
+246
View File
@@ -0,0 +1,246 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// streamModels is every "model" the data lines of an SSE body hold, at
// any depth.
func streamModels(t *testing.T, body string) []string {
t.Helper()
var models []string
var walk func(v any)
walk = func(v any) {
switch v := v.(type) {
case map[string]any:
if m, ok := v["model"].(string); ok {
models = append(models, m)
}
for _, x := range v {
walk(x)
}
case []any:
for _, x := range v {
walk(x)
}
}
}
for _, line := range strings.Split(body, "\n") {
d, ok := strings.CutPrefix(line, "data: ")
if !ok || d == "[DONE]" {
continue
}
var v any
if err := json.Unmarshal([]byte(d), &v); err != nil {
t.Fatalf("a data line that isn't JSON: %q", d)
}
walk(v)
}
return models
}
// lateUpstream is a vendor that says nothing until the agent has heard a
// keepalive (or 5s), then answers x; with no code, it hangs up with no
// reply, the Go client's "EOF", as chatgpt.com's in #3728.
func lateUpstream(t *testing.T, heard <-chan struct{}, x reply) *httptest.Server {
t.Helper()
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
select {
case <-heard:
case <-time.After(5 * time.Second):
}
if x.code != 0 {
w.Header().Set("Content-Type", x.ctype)
w.WriteHeader(x.code)
io.WriteString(w, x.body)
return
}
if c, _, err := w.(http.Hijacker).Hijack(); err == nil {
c.Close()
}
}))
t.Cleanup(up.Close)
return up
}
// An error sent in a stream already begun names the model the agent
// asked for wherever its protocol says one ahead of it (#3728). Chat's
// first chunk went with "model":"", which fx takes for a broken chunk:
// it stopped there and never read the error after it. Anthropic's
// message_start and Responses' response.created, response.in_progress and
// response.failed had it empty too. Gemini's error says no model.
func TestStreamErrorNamesTheModel(t *testing.T) {
const asked = "codex/gpt-6.1-sol"
for _, c := range []struct {
proto provider.Protocol
named bool // the protocol says a model ahead of the error
}{
{provider.Chat, true},
{provider.Anthropic, true},
{provider.Responses, true},
{provider.Gemini, false},
} {
rec := httptest.NewRecorder()
streamError(rec, c.proto, asked, http.StatusBadGateway, `Post "https://chatgpt.com/backend-api/codex/responses": EOF`)
body := rec.Body.String()
models := streamModels(t, body)
if c.named && len(models) == 0 {
t.Errorf("%s: no model named: %s", c.proto, body)
}
if !c.named && len(models) > 0 {
t.Errorf("%s: names %q, want none: %s", c.proto, models, body)
}
for _, m := range models {
if m != asked {
t.Errorf("%s: model %q, want %q: %s", c.proto, m, asked, body)
}
}
if !strings.Contains(body, "EOF") {
t.Errorf("%s: the error isn't in the stream: %s", c.proto, body)
}
}
}
// #3728's case: a Chat stream kept alive while its vendor said nothing,
// then the vendor gone with no reply. The error goes in the stream, and
// the chunk ahead of it names the model the agent asked for; the same
// for each way the vendor can fail after the stream's headers went out:
// an error status, told as it is (holdWriter.release), a 413, told with
// the byte cap's words (failTo), a 200 that isn't a stream, and a JSON
// 200 that is no reply, which release tells as the failure it is. A model
// asked for at an effort (#536) is named with it, as the agent asked.
func TestKeptAliveChatErrorNamesTheModel(t *testing.T) {
for _, c := range []struct {
name string
model string
x reply
}{
{"gone", "a/m", reply{}},
{"gone, at an effort", "a/m:high", reply{}},
{"502", "a/m", reply{http.StatusBadGateway, "application/json", `{"error":{"message":"upstream connect error","type":"upstream_error"}}`}},
{"413", "a/m", reply{http.StatusRequestEntityTooLarge, "application/json", `{"error":{"message":"request entity too large","type":"invalid_request_error"}}`}},
{"a 200 that isn't a stream", "a/m", reply{http.StatusOK, "text/html", "<html><body>down for maintenance</body></html>"}},
{"a 200 JSON that isn't a reply", "a/m", reply{http.StatusOK, "application/json", `{"status":"ok"}`}},
} {
t.Run(c.name, func(t *testing.T) {
quietFast(t)
fresh(t)
pause := retryPause
retryPause = time.Millisecond
t.Cleanup(func() { retryPause = pause })
heard := make(chan struct{})
up := lateUpstream(t, heard, c.x)
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
code, body, _ := askChat(t, New(), c.model, heard)
keptThenFailed(t, code, body, c.model)
if c.x.code == http.StatusRequestEntityTooLarge && !strings.Contains(body, "request_too_large") {
t.Fatalf("the byte cap's words aren't in the error: %q", body)
}
})
}
}
// keptThenFailed checks a Chat stream kept alive and then failed: its
// headers went out ahead of the failure, its first chunk names model, and
// the error follows.
func keptThenFailed(t *testing.T, code int, body, model string) {
t.Helper()
if code != http.StatusOK || !strings.Contains(body, ": keepalive") {
t.Fatalf("the stream's headers didn't go out ahead of the failure: %d %q", code, body)
}
var first string
for _, line := range strings.Split(body, "\n") {
if d, ok := strings.CutPrefix(line, "data: "); ok {
first = d
break
}
}
if got := gjson.Get(first, "model"); got.String() != model {
t.Fatalf("the stream's first chunk names %s, want %s: %q", got.Raw, model, body)
}
if !strings.Contains(body, `{"error":`) {
t.Fatalf("no error in the stream: %q", body)
}
}
// #3728's own route: fx on magpie's codex provider (Codex's sign-in), its
// Chat turn asked on the ChatGPT backend, which hangs up once fx was kept
// alive, each time it is asked. The error is the report's EOF.
func TestKeptAliveChatOnCodexErrorNamesTheModel(t *testing.T) {
quietFast(t)
codexSignedIn(t)
pause := retryPause
retryPause = time.Millisecond
t.Cleanup(func() { retryPause = pause })
heard := make(chan struct{})
up := lateUpstream(t, heard, reply{})
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
code, body, _ := askChat(t, New(), "codex/gpt-5.5", heard)
keptThenFailed(t, code, body, "codex/gpt-5.5")
if !strings.Contains(body, "EOF") {
t.Fatalf("the error isn't the backend's EOF: %q", body)
}
}
// The same on Codex's own sign-in (codexBackend): the backend overloaded,
// Codex kept alive while the turn waits to be asked again, then the
// backend gone. The response.created and response.failed Codex is sent
// name the model it asked for.
func TestKeptAliveCodexErrorNamesTheModel(t *testing.T) {
quietFast(t)
codexSignedIn(t)
var mu sync.Mutex
asked := 0
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
asked++
n := asked
mu.Unlock()
if n == 1 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(529)
io.WriteString(w, overloadedStatus)
return
}
if c, _, err := w.(http.Hijacker).Hijack(); err == nil {
c.Close()
}
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
// asked again after 500ms, Codex kept alive past keepHeldAfter's 40ms
pause := retryPause
retryPause = 500 * time.Millisecond
t.Cleanup(func() { retryPause = pause })
code, body := codexPost(t, oneAccountTurn)
if code != http.StatusOK || !strings.Contains(body, ": keepalive") || !strings.Contains(body, "event: response.failed") {
t.Fatalf("not kept alive, then failed in the stream: %d %q", code, body)
}
models := streamModels(t, body)
if len(models) == 0 {
t.Fatalf("no model named: %q", body)
}
for _, m := range models {
if m != "gpt-5.5" {
t.Fatalf("model %q, want gpt-5.5: %q", m, body)
}
}
}
@@ -157,7 +157,7 @@ func TestStreamErrorByteCapInEveryShape(t *testing.T) {
{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)
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)