From e4384fc3cd5c7be35a11ab3085dab6519f8caf1c Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 1 Nov 2026 05:24:43 +0800 Subject: [PATCH] gateway: a Codex stream cut inside a line still has its failure read (#3377) #3377's patch writes response.failed when the upstream cuts a Codex stream mid-reply. When the cut lands inside a line, the half line was still open, so the events streamError writes were read as more of that line's data and the client never parsed the failure. A blank line now goes first, ending the half event (as #2446 and #2580 do on the other relays). TestCodexStreamCutMidLineFailureParses cuts the stream inside a delta's data and checks every event the client reads parses, apart from the half line itself, and that response.failed is among them. Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061), go1.26.8: - go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway, internal/redact, internal/provider and internal/plugin (this batch's packages and those main changed since the full run): all ok. gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags nogui ./... clean. internal/gui on macOS (mote-run): TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners (#3949), both red at main too. - The full go test ./... -timeout 45m -count=1 ran one rebase earlier, at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux (wsl-run): 82 packages ok. internal/agent has 4 reds, all red at origin/main on that box as well: TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir and TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root package and internal/cli need gtk4 to build, so they ran on macOS (mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An earlier full run at base d307aa648 was red once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both the head and main. - Each landed patch's diff matches the head ggbdpq posted last on its issue (patch-id). - No GUI file is touched, so no GUI test file was run. Broken by hand: the blank line removed: TestCodexStreamCutMidLineFailureParses goes red; restored, green. Not tried: a real cut inside a line from chatgpt.com. #3377's patch writes response.failed when the upstream cuts a Codex stream mid-reply. When the cut lands inside a line, the half line was still open, so the events streamError writes were read as more of that line's data and the client never parsed the failure. A blank line now goes first, ending the half event (as #2446 and #2580 do on the other relays). TestCodexStreamCutMidLineFailureParses cuts the stream inside a delta's data and checks every event the client reads parses, apart from the half line itself, and that response.failed is among them. Landing record (yetone): Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8: - go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway, internal/redact, internal/provider, internal/agent and internal/usage (this batch's packages, plus those main changed since the full run): all ok except internal/agent's TestInstalledVersion, TestGrokInstalled and TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033, #3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the root package and internal/cli ok; internal/gui red in TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners (#3949) and TestColdTurnsTaken (#4510), the first two red at main too. - The full go test ./... -timeout 45m -count=1 ran two rebases earlier, at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82 packages ok, internal/agent's 4 reds as above, plus TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The root package, internal/cli and internal/gui need gtk4 to build, so they ran on macOS as above. An earlier full run at base d307aa648 was red once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both the head and main. - Each landed patch's diff matches the head ggbdpq posted last on its issue (patch-id). - No GUI file is touched, so no GUI test file was run. - Rebased after these runs onto origin/main c1457f2ee. Its two commits since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither internal/gateway nor internal/redact, nor any file this batch changes, and were not run again here. Broken by hand: the blank line removed: TestCodexStreamCutMidLineFailureParses goes red; restored, green. Not tried: a real cut inside a line from chatgpt.com. --- internal/gateway/codex_backend.go | 3 ++ internal/gateway/codex_stream_cut_test.go | 61 +++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index cf015f067..5e3a1f261 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1493,6 +1493,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st // 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 + // after a blank line, so a line the cut left half written can't + // take the events streamError writes into its data (#2446, #2580) + w.Write([]byte("\n\n")) streamError(w, provider.Responses, call.Model, call.Status, said) } end(call.Status, call.Error, uu.Input+uu.Output+uu.CacheRead+uu.CacheWrite, uu.Output) diff --git a/internal/gateway/codex_stream_cut_test.go b/internal/gateway/codex_stream_cut_test.go index d3064f195..6438eabe7 100644 --- a/internal/gateway/codex_stream_cut_test.go +++ b/internal/gateway/codex_stream_cut_test.go @@ -1,6 +1,7 @@ package gateway import ( + "encoding/json" "io" "net/http" "net/http/httptest" @@ -72,3 +73,63 @@ func TestCodexStreamCutToldTheClient(t *testing.T) { t.Fatalf("the ledger kept %d rows for the turn", seen) } } + +// A stream the backend cut inside a line still has its failure read: what +// magpie appends begins after a blank line, so the half line can't take +// its first event into its data, which no client parses (#3377, as #2446 +// and #2580 for a relayed stream). +func TestCodexStreamCutMidLineFailureParses(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"}`)) + io.WriteString(w, `data: {"type":"response.output_text.delta","del`) + w.(http.Flusher).Flush() + })) + 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) + } + // every event magpie appended parses; the half line the cut left is + // an event of its own, which a client skips + const half = `{"type":"response.output_text.delta","del` + failed := false + for _, ev := range strings.Split(string(body), "\n\n") { + var data []string + for _, l := range strings.Split(ev, "\n") { + if d, ok := strings.CutPrefix(l, "data:"); ok { + data = append(data, strings.TrimSpace(d)) + } + } + d := strings.Join(data, "\n") + if d == "" || d == half { + continue + } + if !json.Valid([]byte(d)) { + t.Fatalf("an event no client parses, the half line run into what magpie appended: %q\n%s", ev, body) + } + failed = failed || strings.Contains(d, `"response.failed"`) + } + if !failed { + t.Fatalf("no response.failed after the cut:\n%s", body) + } +}