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/main2beed3b0, 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 at2beed3b0and 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 at2beed3b0, 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 on1cbdda25b, 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 ontoab546a4ee(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.
247 lines
8.0 KiB
Go
247 lines
8.0 KiB
Go
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)
|
|
}
|
|
}
|
|
}
|