diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 7cb7cda39..704fe49e5 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1487,6 +1487,13 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st // (codex.out) and the Codex app is told without a restart codexMayBeUsedUp(relayedAcct) } + } else if said := codexStreamCut(res, sniff, began, r.Context()); said != "" { + // the stream's bytes stopped mid-reply, no failure said and no + // last event reached: the client still there hears it as the + // stream's failure, not a bare EOF to puzzle over, and the row + // says why instead of a clean 200 with no usage (#3377) + call.Status, call.Error = http.StatusBadGateway, said + streamError(w, provider.Responses, call.Model, call.Status, said) } end(call.Status, call.Error, uu.Input+uu.Output+uu.CacheRead+uu.CacheWrite, uu.Output) call.Route = tr.ID @@ -1789,6 +1796,23 @@ func codexSaidNothing(rest, model, who string, res *http.Response, msg []byte) ( "or pick one of magpie's models in Codex (provider/model, or set it in magpie's Agents view)", true } +// codexStreamCut says when a relayed stream was cut mid-reply: an SSE reply +// whose bytes stopped with no failure said and no last event reached, its +// client still there to hear of it. Left alone the reply just ends: Codex +// read a bare EOF, "stream disconnected before completion", and the row +// recorded a clean 200 with nothing of why — every reply the ChatGPT +// backend cut about two minutes in said nothing else for days (#3377). +// The text carries how long the stream had gone, so a cut's fixed shape +// shows in the log. +func codexStreamCut(res *http.Response, sniff *usageSniffer, began time.Time, ctx context.Context) string { + if res.StatusCode >= 400 || !sniff.sse || sniff.failed != "" || sniff.whole() || ctx.Err() != nil { + return "" + } + return "OpenAI closed the stream " + time.Since(began).Round(time.Second).String() + " into the reply, " + + "before its last event: response.completed never came, and the usage with it. " + + "The reply is lost, and asking again sends the turn whole" +} + // routeOf is the id of the route a Codex relay opened, so the call it // records is the one the Routing page's "Request and response" opens (#2481); // 0 for a compaction, which opens none. diff --git a/internal/gateway/codex_stream_cut_test.go b/internal/gateway/codex_stream_cut_test.go new file mode 100644 index 000000000..d3064f195 --- /dev/null +++ b/internal/gateway/codex_stream_cut_test.go @@ -0,0 +1,74 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// TestCodexStreamCutToldTheClient (#3377): the ChatGPT backend closed every +// relayed stream about two minutes into the reply, its deltas flowing to the +// end — no response.completed, no error event, no usage. Codex read a bare +// EOF, "stream disconnected before completion", and the row recorded a clean +// 200 that said nothing of why. A stream the upstream breaks mid-reply is +// told to the client still there as its failure, and the row says why. +func TestCodexStreamCutToldTheClient(t *testing.T) { + codexSignedIn(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-astra"}}`, + `data: {"type":"response.output_text.delta","delta":"half a report"}`)) + w.(http.Flusher).Flush() + // the handler returns with no terminal event: the stream ends the + // way the backend's cut streams did, mid-reply + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-6-astra"}}); err != nil { + t.Fatal(err) + } + server := httptest.NewServer(New().Handler()) + defer server.Close() + req, _ := http.NewRequest("POST", server.URL+CodexPath+"/responses", + strings.NewReader(`{"model":"gpt-6-astra","stream":true,"input":"write a long report"}`)) + req.Header.Set("Content-Type", "application/json") + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if err != nil { + t.Fatal(err) + } + said := string(body) + delta, failed := strings.Index(said, "half a report"), strings.Index(said, "response.failed") + if delta < 0 { + t.Fatalf("the reply's deltas never reached the client:\n%s", said) + } + if failed < 0 || failed < delta || !strings.Contains(said, "before its last event") { + t.Fatalf("a stream cut mid-reply ended without its failure said after the deltas:\n%s", said) + } + seen := 0 + usage.Visit(time.Time{}, func(r usage.Record) { + if r.Endpoint != CodexPath+"/responses" { + return + } + seen++ + if r.Status != http.StatusBadGateway || !strings.Contains(r.Error, "before its last event") { + t.Fatalf("the row said %d %q, not why the reply was lost", r.Status, r.Error) + } + }) + if seen != 1 { + t.Fatalf("the ledger kept %d rows for the turn", seen) + } +}