gateway: Codex's compaction back on its own model goes without another vendor's reasoning text, so the turn after DeepSeek isn't refused over input[n].content (jue on Discord)

jue (Codex app, GPT-6.1 Sol) set a DeepSeek model for Codex on the
Agents page, went back to GPT, and the next turn sometimes failed with
"[ArrayParam] [input[8].content] [array_above_max_length] Invalid
'input[8].content': array too long. Expected an array with maximum
length 0, but got an array with length 1 instead."

Cause: when the model changes (or the thread passes its auto-compact
limit) Codex compacts the thread before the turn, and shows a failed
compaction as the turn's error. Codex's /responses/compact for one of
its own models went to the ChatGPT backend (Codex's sign-in, its sk-
key, or a magpie Codex account through compactOn) with its input as
sent. A reasoning item from DeepSeek's Responses API carries its
reasoning_text in content, which OpenAI accepts only empty, so the
whole compaction was refused. A turn on the same routes already went
through codexInput(body, false), which drops such items; the
compaction didn't. "Sometimes" is when Codex compacts first.

Fix: codexBackend's own-model branch runs codexInput(body, false) on
/responses/compact too, before any of the three routes. OpenAI's own
sealed reasoning (encrypted_content, no text) stays; a summary magpie
made goes as its text, as from a turn. DeepSeek still gets its
reasoning text (withReasoningText). Siblings read: the translated
Responses path sends back only sealed reasoning (sealedReasoning);
passthrough strips reasoning text for openai.com, Azure and Codex
accounts and retries on the refusal elsewhere (#1411). Not covered: a
full restore that drops openai_base_url leaves magpie off Codex's path.
Codex's base_instructions and prompts are untouched.

Test: TestForeignReasoningNeverReachesOpenAI sends the reported thread
(input[8] a DeepSeek reasoning item with one reasoning_text, input[3]
OpenAI's sealed reasoning) on seven routes: turn and compaction on
Codex's sign-in, its API key and a magpie account, and /v1/responses
with codex/gpt-6.1-sol. The fake OpenAI refuses a reasoning item with
text with the reported 400 byte for byte. On the old code the three
compaction routes are red with that 400 and the four turns green;
with the fix all seven are green. Broken by hand a second way
(codexInput(body, true) on the compact branch): the same three red.

Run at 592899467 + this change, GOMODCACHE=/Users/yetone/go/pkg/mod,
sandbox HOME and GOCACHE in the worktree:
- gofmt -l on the changed Go files: empty.
- go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...: all clean.
- set -o pipefail; go test -timeout 45m ./...: exit 1 at load from
  other sessions' suites. 61 packages ok. internal/agent, gateway and
  library hit the 45m timeout (#2869's kind).
  TestSetAnswersWhileDevinAndProvidersHang (internal/gui, 10.6s set,
  #1375) and TestTaggedReposSlowRead (internal/plugin, #1889) failed
  their timing bars.
- Rerun alone, go test -timeout 45m -p 2 ./internal/gateway
  ./internal/agent ./internal/library ./internal/gui ./internal/plugin:
  all five ok (gateway 1011s, agent 1235s, library 632s, gui 184s,
  plugin 452s).
- Rebased on c922225f1 (5 commits, gateway.go among them): go vet
  ./internal/gateway for darwin, linux -tags nogui and windows clean;
  go test -timeout 45m ./internal/gateway ok (1253s).
This commit is contained in:
yetone
2026-10-21 05:57:34 +08:00
parent c922225f13
commit a3ebed202e
3 changed files with 157 additions and 0 deletions
File diff suppressed because one or more lines are too long
+7
View File
@@ -162,6 +162,13 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
// the ChatGPT backend checks every item id as OpenAI does
body = plainItemIDs(boundCallIDs(callItemIDs(body)))
if rest == "/responses/compact" {
// Codex compacts a thread before its first turn back on one of
// its own models; the thread's reasoning from another vendor
// goes, as it does from a turn: with its text in it, the
// backend refuses the whole compaction over "input[n].content:
// array too long", and Codex shows it as the turn's error
// (jue on Discord). A summary magpie made goes as its text.
body, _ = codexInput(body, false)
// a key held to some accounts (#905) may not spend the sign-in
// compaction still relays on: refused as its turns are (#967),
// with nothing asked of OpenAI — and refused when the sign-in
+149
View File
@@ -188,3 +188,152 @@ func TestReasoningTextNotSentToCodexAccount(t *testing.T) {
t.Fatalf("the ChatGPT backend was asked %d times: %v", len(got), got)
}
}
// openaiItems stands in for the ChatGPT backend and OpenAI's API as they
// check a reasoning item (jue on Discord): one with its text in it is
// turned away with the 400 the backend answers, naming the item; one
// with nothing sealed in it is looked up and not found, store being
// false (#1008). Each request's path and input are kept.
type openaiItems struct {
mu sync.Mutex
paths []string
inputs [][]map[string]any
}
func (u *openaiItems) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
if strings.HasSuffix(r.URL.Path, "/models") {
io.WriteString(w, `{"models":[{"slug":"gpt-6.1-sol","visibility":"list"}]}`)
return
}
var q struct {
Input []map[string]any `json:"input"`
}
json.Unmarshal(b, &q)
u.mu.Lock()
u.paths = append(u.paths, r.URL.Path)
u.inputs = append(u.inputs, q.Input)
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
for i, it := range q.Input {
if it["type"] != "reasoning" {
continue
}
if c, _ := it["content"].([]any); len(c) > 0 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"error":{"message":"[ArrayParam] [input[%d].content] [array_above_max_length] Invalid 'input[%d].content': array too long. Expected an array with maximum length 0, but got an array with length %d instead.","type":"invalid_request_error","param":"input[%d].content","code":"array_above_max_length"}}`, i, i, len(c), i)
return
}
if enc, _ := it["encrypted_content"].(string); enc == "" {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, `{"error":{"message":"Item with id '%v' not found. Items are not persisted when `+"`store`"+` is set to false.","type":"invalid_request_error","param":"input","code":null}}`, it["id"])
return
}
}
if strings.HasSuffix(r.URL.Path, "/compact") {
io.WriteString(w, `{"id":"resp_c","object":"response.compaction","output":[{"type":"compaction","encrypted_content":"gAAAAAcompacted"}],"usage":{"input_tokens":9,"output_tokens":3}}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`,
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"DONE"}]}}`,
`data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`))
}
func (u *openaiItems) asked() ([]string, [][]map[string]any) {
u.mu.Lock()
defer u.mu.Unlock()
return append([]string(nil), u.paths...), append([][]map[string]any(nil), u.inputs...)
}
// switchedBackFromDeepSeek is jue's Codex thread (Discord, #feedback): a
// turn on GPT, whose reasoning OpenAI sealed (content null, as Codex
// writes a reasoning item without text), then a turn on DeepSeek set for
// Codex on magpie's Agents page, whose reasoning DeepSeek's Responses API
// gave with its text and nothing sealed (encrypted_content null), then
// back on GPT. input[8] is DeepSeek's reasoning, with one content entry.
func switchedBackFromDeepSeek(model string) string {
return `{"model":"` + model + `","instructions":"You are Codex.","stream":true,"store":false,"include":["reasoning.encrypted_content"],"input":[` +
`{"type":"message","role":"developer","content":[{"type":"input_text","text":"<permissions instructions>workspace-write</permissions instructions>"}]},` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"<environment_context><cwd>/Users/jue/app</cwd></environment_context>"}]},` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"看看这个仓库"}]},` +
`{"type":"reasoning","summary":[{"type":"summary_text","text":"**Listing files**"}],"content":null,"encrypted_content":"gAAAAABo-sealed-by-openai"},` +
`{"type":"function_call","name":"exec_command","arguments":"{\"cmd\":\"ls\"}","call_id":"call_gpt1"},` +
`{"type":"function_call_output","call_id":"call_gpt1","output":"main.go\nREADME.md"},` +
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"两个文件。"}]},` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"README 写了什么"}]},` +
`{"type":"reasoning","id":"rs_ds_3b1f","summary":[],"content":[{"type":"reasoning_text","text":"用户想知道 README 的内容。"}],"encrypted_content":null},` +
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"README 是项目说明。"}]},` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"继续"}]}]}`
}
// jue on Discord: Codex on DeepSeek, then back on its own GPT, failed its
// next turn with OpenAI's 400 over input[8].content, the reasoning
// DeepSeek wrote. Every way a request for one of OpenAI's models reaches
// OpenAI's Responses endpoint through magpie — Codex's turn and its
// compaction, on its own sign-in, its API key or a magpie account, and a
// client of the gateway's own /v1/responses — goes without that item,
// asked once, OpenAI's own sealed reasoning and the rest kept.
func TestForeignReasoningNeverReachesOpenAI(t *testing.T) {
for _, tc := range []struct {
name, path, model, auth string
spare, pauseOwn bool
}{
{name: "turn on Codex's sign-in", path: CodexPath + "/responses", model: "gpt-6.1-sol", auth: "Bearer chatgpt-token"},
{name: "compaction on Codex's sign-in", path: CodexPath + "/responses/compact", model: "gpt-6.1-sol", auth: "Bearer chatgpt-token"},
{name: "turn on Codex's API key", path: CodexPath + "/responses", model: "gpt-6.1-sol", auth: "Bearer sk-test"},
{name: "compaction on Codex's API key", path: CodexPath + "/responses/compact", model: "gpt-6.1-sol", auth: "Bearer sk-test"},
{name: "turn on a magpie account", path: CodexPath + "/responses", model: "gpt-6.1-sol", auth: "Bearer chatgpt-token", spare: true, pauseOwn: true},
{name: "compaction on a magpie account", path: CodexPath + "/responses/compact", model: "gpt-6.1-sol", auth: "Bearer chatgpt-token", spare: true, pauseOwn: true},
{name: "the gateway's own Responses API", path: "/v1/responses", model: "codex/gpt-6.1-sol", auth: ""},
} {
t.Run(tc.name, func(t *testing.T) {
if tc.spare {
codexSignedIn(t, "spare@example.com")
} else {
codexSignedIn(t)
}
if tc.pauseOwn {
if err := provider.SetLoginOn("codex", "me@example.com", false); err != nil {
t.Fatal(err)
}
}
u := &openaiItems{}
srv := httptest.NewServer(u)
t.Cleanup(srv.Close)
was, wasAPI := provider.CodexBase, codexAPIBase
provider.CodexBase, codexAPIBase = srv.URL+"/backend-api/codex", srv.URL+"/v1"
t.Cleanup(func() { provider.CodexBase, codexAPIBase = was, wasAPI })
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", tc.path, strings.NewReader(switchedBackFromDeepSeek(tc.model)))
if tc.auth != "" {
req.Header.Set("Authorization", tc.auth)
req.Header.Set("chatgpt-account-id", "acct-1")
}
req.Header.Set("session_id", "thread-jue")
New().Handler().ServeHTTP(rec, req)
if rec.Code != 200 || strings.Contains(rec.Body.String(), "array too long") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
paths, got := u.asked()
if len(got) != 1 {
t.Fatalf("OpenAI was asked %d times (%v), want once", len(got), paths)
}
if reasoningTexts(got[0]) != 0 {
t.Errorf("DeepSeek's reasoning text reached OpenAI: %v", got[0])
}
sealed := 0
for _, it := range got[0] {
if it["type"] == "reasoning" && it["encrypted_content"] == "gAAAAABo-sealed-by-openai" {
sealed++
}
}
k := kinds(got[0])
if sealed != 1 || k["reasoning"] != 1 || k["function_call"] != 1 || k["function_call_output"] != 1 || k["message"] < 7 {
t.Errorf("OpenAI's own items not all kept: %v", k)
}
})
}
}