From 7d8cda18aa282828bf17ebbd5e4259e221ff595d Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 8 Oct 2026 16:47:18 +0800 Subject: [PATCH] gateway: a magpie-model compaction the ChatGPT backend breaks off after the reply began, HTTP 200 and an error event "response protection is unavailable", is asked again as text and else compacted locally, as the 502 is; the error nested in an error event is read, not "the model failed" (#1270) Ran: go test -tags nogui ./internal/gateway (green; an earlier full run had TestOTelExportsWholeBodiesWhenOn panic once under load, passes alone -count=3 and in the rerun); GOOS=linux/windows go vet ./internal/gateway. The new tests failed before the fix with the reporter's "502 compaction: the model failed". Not tried with the real backend or Lody. --- internal/gateway/codex_backend.go | 60 ++++++++++++++------- internal/gateway/protection_test.go | 84 +++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 19 deletions(-) diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 9d310dde2..9d1e870c8 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1262,22 +1262,39 @@ func userMessage(text string) map[string]any { // so the compaction still completes and Codex goes on. So is one the // ChatGPT backend answers 502 "response protection is unavailable" (vs on // Discord): the same long history failed so on every account and model, -// and as plain text was summarised. Any other failure -// (401, 429, 500) goes back to Codex as it came. +// and as plain text was summarised — and one it breaks off with that +// refusal after the reply began, HTTP 200 and an error event (#1270). Any +// other failure (401, 429, 500) goes back to Codex as it came. func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byte) { - rec := &recorder{header: http.Header{}, status: 200} - s.serve(rec, r, provider.Responses, body) - local := "" - if first := rec.status; first == http.StatusNotFound || itemNotFound(rec) || protectionRefused(first, rec.body.Bytes()) { - who, msg := compactFailure(body, rec) - log.Printf("codex compaction: %s answered %d (%s); asking again with the conversation as text", who, first, msg) - rec = &recorder{header: http.Header{}, status: 200} - s.serve(rec, r, provider.Responses, plainCompact(body)) + ask := func(b []byte) (*recorder, compactResult, error) { + rec := &recorder{header: http.Header{}, status: 200} + s.serve(rec, r, provider.Responses, b) if rec.status >= 400 { - _, again := compactFailure(body, rec) + return rec, compactResult{}, nil + } + res, err := compactReply(rec.body.Bytes()) + return rec, res, err + } + rec, res, err := ask(body) + local := "" + if first := rec.status; first == http.StatusNotFound || itemNotFound(rec) || protectionRefused(first, rec.body.Bytes()) || + err != nil && protectionWords.MatchString(err.Error()) { + who, msg := compactFailure(body, rec) + if err != nil { + msg = "broken off: " + err.Error() + } + log.Printf("codex compaction: %s answered %d (%s); asking again with the conversation as text", who, first, msg) + rec, res, err = ask(plainCompact(body)) + if rec.status >= 400 || err != nil { + again := "" + if err != nil { + again = "broken off: " + err.Error() + } else { + _, again = compactFailure(body, rec) + } log.Printf("codex compaction: %s answered %d again (%s); compacting locally", who, rec.status, again) local = localSummary(body, fmt.Sprintf("%s answered %d to the summary request: %s", who, first, msg)) - rec = &recorder{header: http.Header{}, status: 200} + rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil } } if rec.status >= 400 { @@ -1288,16 +1305,14 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt w.Write(rec.body.Bytes()) return } - var res compactResult + if err != nil { + writeError(w, provider.Responses, 502, "compaction: "+err.Error()) + return + } var sum strings.Builder if local != "" { sum.WriteString(local) } else { - var err error - if res, err = compactReply(rec.body.Bytes()); err != nil { - writeError(w, provider.Responses, 502, "compaction: "+err.Error()) - return - } for _, o := range res.Output { if o.Type != "message" { continue @@ -1520,6 +1535,9 @@ func compactReply(b []byte) (compactResult, error) { Item compactOutput `json:"item"` Response *compactResult `json:"response"` Message string `json:"message"` // an error event's + Error *struct { + Message string `json:"message"` + } `json:"error"` // or nested in its error, as the ChatGPT backend's (#1270) } if json.Unmarshal([]byte(data), &ev) != nil { return nil @@ -1535,7 +1553,11 @@ func compactReply(b []byte) (compactResult, error) { res.Output, res.Usage = ev.Response.Output, ev.Response.Usage } case "response.failed", "error": - failed = cmp.Or(ev.Message, "the model failed") + failed = ev.Message + if failed == "" && ev.Error != nil { + failed = ev.Error.Message + } + failed = cmp.Or(failed, "the model failed") if ev.Response != nil && ev.Response.Error != nil && ev.Response.Error.Message != "" { failed = ev.Response.Error.Message } diff --git a/internal/gateway/protection_test.go b/internal/gateway/protection_test.go index 2e939fa10..38291120f 100644 --- a/internal/gateway/protection_test.go +++ b/internal/gateway/protection_test.go @@ -1,6 +1,7 @@ package gateway import ( + "encoding/base64" "io" "net/http" "net/http/httptest" @@ -115,3 +116,86 @@ func TestProtectionBreakOffDoesNotRest(t *testing.T) { t.Error("a vendor failing mid-reply no longer rests") } } + +// brokenOff is the ChatGPT backend's refusal as #1270 (bulai0408, Codex +// 0.159.2 in Lody) met it on a long history: HTTP 200, the reply begun, +// then an error event whose error is nested — the object Codex was shown, +// {"message":"response protection is unavailable","type":"internal_error", +// "param":null,"code":null}, when it came before the reply. +var brokenOff = sse( + `data: {"type":"response.created","response":{"id":"resp_1","model":"gpt-6.1-sol"}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","role":"assistant","content":[]}}`, + `data: {"type":"response.output_text.delta","output_index":0,"delta":"## Progress so far"}`, + `event: error`+"\n"+`data: {"type":"error","error":{"message":"response protection is unavailable","type":"internal_error","param":null,"code":null}}`) + +// brokenOffUp answers the structured history with brokenOff, and the +// history as text with brokenOff too when textFails, else with a summary. +func brokenOffUp(t *testing.T, textFails bool) *[]string { + t.Helper() + var mu sync.Mutex + tried := &[]string{} + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + *tried = append(*tried, r.Header.Get("chatgpt-account-id")) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + if textFails || !strings.Contains(string(b), "This is the conversation so far") { + io.WriteString(w, brokenOff) + return + } + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"resp_2","model":"gpt-6.1-sol"}}`, + `data: {"type":"response.output_item.done","item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"the summary"}]}}`, + `data: {"type":"response.completed","response":{"id":"resp_2","usage":{"input_tokens":7,"output_tokens":2}}}`)) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + return tried +} + +// #1270: the refusal came after the reply began, so the compaction got a +// 200 and Codex "502 compaction: the model failed" — the error's nested +// message unread and the history never asked as text. It is asked as text +// as the 502 is, and Codex gets its compaction. +func TestProtectionBrokenOffCompactionAsText(t *testing.T) { + codexSignedIn(t, "two@example.com") + tried := brokenOffUp(t, false) + code, body := codexPost(t, strings.Replace(protectedCompaction, "%q", `"codex/gpt-6.1-sol"`, 1)) + if code != 200 || !strings.Contains(body, `"type":"compaction"`) || !strings.Contains(body, magpieCompaction) { + t.Fatalf("status %d: %s", code, body) + } + if len(*tried) != 2 { + t.Errorf("asked %d times (%v), not once as it came and once as text", len(*tried), *tried) + } + if r := restingNow(t); len(r) > 0 { + t.Errorf("resting: %v", r) + } +} + +// Broken off as text too, the summary is magpie's own, and Codex goes on. +func TestProtectionBrokenOffTwiceCompactsLocally(t *testing.T) { + codexSignedIn(t, "two@example.com") + brokenOffUp(t, true) + code, body := codexPost(t, strings.Replace(protectedCompaction, "%q", `"codex/gpt-6.1-sol"`, 1)) + if code != 200 || !strings.Contains(body, `"type":"compaction"`) { + t.Fatalf("status %d: %s", code, body) + } + _, enc, _ := strings.Cut(body, magpieCompaction) + enc, _, _ = strings.Cut(enc, `"`) + sum, _ := base64.StdEncoding.DecodeString(enc) + if !strings.Contains(string(sum), "refactor the parser") || !strings.Contains(string(sum), "response protection is unavailable") { + t.Errorf("local summary: %s", sum) + } +} + +// An error event's message nested in its error is the one read, not "the +// model failed". +func TestCompactReplyReadsNestedError(t *testing.T) { + _, err := compactReply([]byte(brokenOff)) + if err == nil || err.Error() != "response protection is unavailable" { + t.Errorf("err = %v", err) + } +}