gateway: a thread switched off a used-up Codex model compacts locally (hiwise_aigc)

hiwise_aigc on X (2115741641017565304): with Codex's allowance used up,
an existing thread switched to a magpie model failed every turn and
"还会走gpt模型", restarts or not; a new thread worked.

Cause, from codex-rs: before a turn on a model with a smaller window
(or a changed comp_hash), core/src/session/turn.rs
maybe_run_previous_model_inline_compact compacts the thread on the
PREVIOUS model (gpt-5.5) through the current provider, turn metadata
compaction.reason "model_downshift" / "comp_hash_changed", phase
pre_turn. compact_model_fallback.rs retries with the turn's model only
when the provider is_openai() (name "OpenAI"). Under the takeover
provider "magpie" there is no fallback: /v1/responses resolved bare
gpt-5.5 to the used-up codex account, codexCompact returned its 429,
and that was the turn's error, every turn. A new thread has no previous
model, so no compaction.

Fix: codexCompact, off CodexPath only, reads the compaction reason from
x-codex-turn-metadata (header, else client_metadata in the body). For
model_downshift / comp_hash_changed, a failed, errored or empty
compaction on the old model is answered with localSummary (magpie's own
magpie1 summary, no model), so the thread goes on on the model it was
switched to. The held-account check doesn't short-circuit it either.
context_limit (the thread's own model out of room) still says the
refusal, and CodexPath is left alone: Codex's "OpenAI" provider falls
back to the turn's model itself and gets a better summary there.
Prompts and base_instructions are not touched.

Run:
- TestCodexLeavingModelCompactsLocally: red on the old code (429 at
  codex_leaving_model_test.go:84), green now.
- Broken by hand: without the body client_metadata fallback the
  header-less case goes red; without the CodexPath scope the CodexPath
  case goes red (got 200).
- Sandbox repro (sandbox HOME + CODEX_HOME, fake upstream, live ~/.codex
  untouched): codex 0.162.1, takeover-like config with
  remote_compaction v2 and a model catalog (gpt-5.5 400k, magpie-x
  128k), a gpt-5.5 thread relabelled to provider magpie, resumed on
  magpie-x: POST /v1/responses model gpt-5.5 + compaction_trigger,
  reason model_downshift; a 429 failed the turn ("Error running remote
  compact task: You've hit your usage limit"); answered with a
  compaction item, as the gateway now does, the turn went on to
  magpie-x and completed. ChatGPT.app's bundled codex has the same
  model_downshift / comp_hash_changed path (strings).
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux
  -tags nogui and GOOS=windows (mote).
- go test -timeout 45m -count=1 ./internal/gateway ./internal/codexsummary
  on mote at this tree (parent 0745db932 = origin/main at push): ok
  gateway 474s, ok codexsummary.

Not tried: a real used-up ChatGPT account through a real gateway end to
end; ChatGPT.app's bundled codex 0.164-alpha run itself; Codex without
remote_compaction v2 (the memento "responses" implementation sends a
plain turn, not covered here). The local summary is lossy (the user's
messages and the last reply), the same one codexCompact already falls
back to.
This commit is contained in:
yetone
2026-10-29 19:46:39 +08:00
parent 0745db932e
commit 2768f04f9b
3 changed files with 157 additions and 2 deletions
File diff suppressed because one or more lines are too long
+54 -1
View File
@@ -2312,6 +2312,31 @@ func localCompactionTurn(meta string) (string, bool) {
return strings.Replace(meta, old, `"implementation":"responses"`, 1), true
}
// previousModelCompaction is whether a compaction is the one Codex runs
// before a turn on another model, on the model the thread was on: a
// switch to a model with a smaller window (compaction.reason
// "model_downshift") or of another compaction hash ("comp_hash_changed"),
// the only places Codex names either (codex-rs core/src/session/turn.rs,
// maybe_run_previous_model_inline_compact). When it fails Codex asks the
// turn's own model instead, but only under its provider named "OpenAI"
// (compact_model_fallback.rs); under magpie's, the provider Codex has
// while its sign-in is used up (codex.out), the failure is the turn's,
// and every turn of the thread asks the old model again.
func previousModelCompaction(r *http.Request, body []byte) bool {
meta := r.Header.Get(turnMetadataHeader)
if meta == "" {
meta = gjson.GetBytes(body, "client_metadata.x-codex-turn-metadata").Str
}
if !strings.Contains(meta, `"compaction"`) {
return false
}
switch gjson.Get(meta, "compaction.reason").Str {
case "model_downshift", "comp_hash_changed":
return true
}
return false
}
// localCompactionMeta is a request's client_metadata with its
// x-codex-turn-metadata made localCompactionTurn's.
func localCompactionMeta(raw json.RawMessage) (json.RawMessage, bool) {
@@ -2959,7 +2984,14 @@ func userMessage(text string) map[string]any { return codexsummary.UserMessage(t
// keeps failing stops being asked for a while (compactFails, #2274).
func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byte) {
key, model := compactKey(body), modelOf(body)
if msg, held := s.compactFails.held(key, model); held {
// Codex's compaction on the model a thread is leaving, under magpie's
// provider: one that fails is compacted locally, as Codex would have
// the turn's own model do it (previousModelCompaction), never the
// turn's failure. On CodexPath Codex's provider is its own "OpenAI",
// which asks the turn's model itself, a summary where magpie's local
// one is only what was asked and the last reply
prev := !strings.HasPrefix(r.URL.Path, CodexPath+"/") && previousModelCompaction(r, body)
if msg, held := s.compactFails.held(key, model); held && !prev {
log.Printf("codex compaction: %s", msg)
writeError(w, provider.Responses, http.StatusBadRequest, msg)
return
@@ -3005,6 +3037,19 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt
rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil
}
}
if prev && local == "" && (rec.status >= 400 || err != nil) {
// the thread's old model can't summarise it — Codex's sign-in used
// up, the model gone — and the turn is on another: compacted
// locally, the thread goes on on the model it was switched to,
// where the refusal failed every turn of it (hiwise_aigc on X)
who, msg := compactFailure(body, rec)
if err != nil {
msg = "broken off: " + err.Error()
}
log.Printf("codex compaction: %s answered %d (%s) on the model the thread is leaving; compacting locally", who, rec.status, msg)
local = localSummary(body, fmt.Sprintf("%s answered %d to the summary request: %s", who, rec.status, msg))
rec, res, err = &recorder{header: http.Header{}, status: 200}, compactResult{}, nil
}
if rec.status >= 400 {
// said as the compaction's failure, with who answered it: a bare
// "Fake: 502 Bad Gateway" read as Codex's own, and a body with
@@ -3031,6 +3076,11 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt
}
err = fmt.Errorf("%s (%s)", incompleteReply, why)
}
if err != nil && prev {
who, _ := compactFailure(body, rec)
log.Printf("codex compaction: %s: %v on the model the thread is leaving; compacting locally", who, err)
local, err = localSummary(body, who+": "+err.Error()), nil
}
if err != nil {
who, _ := compactFailure(body, rec)
msg := "compaction: " + who + ": " + err.Error() + ", so there is no summary"
@@ -3075,6 +3125,9 @@ func (s *Server) codexCompact(w http.ResponseWriter, r *http.Request, body []byt
} else {
sum.WriteString(res.summary())
}
if strings.TrimSpace(sum.String()) == "" && prev {
sum.WriteString(localSummary(body, "the model wrote no summary"+answeredWith(res.Output)))
}
if strings.TrimSpace(sum.String()) == "" {
why := "the model wrote no summary" + answeredWith(res.Output)
s.compactFails.failed(key, http.StatusBadGateway, why)
@@ -0,0 +1,102 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/codexsummary"
"github.com/yetone/magpie/internal/provider"
)
// hiwise_aigc on X: Codex's allowance used up, an existing thread switched
// to a magpie model failed every turn with ChatGPT's usage limit, "还会走
// gpt模型", restarts or not; a new thread worked. Before a turn on a model
// with a smaller window Codex compacts the thread on the model it was on
// (reason model_downshift). Under magpie's provider, the one Codex has
// while its sign-in is used up, that went to the used-up account, and
// Codex asks the turn's own model instead only under its provider named
// "OpenAI": the refusal was the turn's. Compacted locally, the thread goes
// on on the model it was switched to. A compaction for the thread's own
// model running out of room (context_limit) still says the refusal, and
// so does the old model's compaction on CodexPath, where Codex's "OpenAI"
// provider asks the turn's model itself.
func TestCodexLeavingModelCompactsLocally(t *testing.T) {
codexSignedIn(t)
old := codexHeldKnown
codexHeldKnown = func() bool { return true }
t.Cleanup(func() { codexHeldKnown = old })
var tried, models []string
usedUp(t, &tried, &models)
if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-5.5"}}); err != nil {
t.Fatal(err)
}
meta := func(reason string) string {
return `{"session_id":"th1","thread_id":"th1","turn_id":"tu1","request_kind":"compaction","compaction":{"trigger":"auto","reason":"` +
reason + `","implementation":"responses_compaction_v2","phase":"pre_turn","strategy":"memento"}}`
}
body := func(meta string) string {
cm, _ := json.Marshal(map[string]string{"x-codex-turn-metadata": meta})
return `{"model":"gpt-5.5","stream":true,"prompt_cache_key":"th1","client_metadata":` + string(cm) + `,"input":[` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"build the parser"}]},` +
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"the parser is built"}]},` +
`{"type":"compaction_trigger"}]}`
}
post := func(path, reason string, header bool) (int, string) {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", path, strings.NewReader(body(meta(reason))))
if path == CodexPath+"/responses" {
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
}
if header {
req.Header.Set(turnMetadataHeader, meta(reason))
}
New().Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
summary := func(sse string) string {
for _, l := range strings.Split(sse, "\n") {
d, ok := strings.CutPrefix(l, "data: ")
if !ok || gjson.Get(d, "type").Str != "response.output_item.done" {
continue
}
msg, ours := codexsummary.Message(gjson.Get(d, "item.encrypted_content").Str)
if !ours {
return ""
}
b, _ := json.Marshal(msg)
return string(b)
}
return ""
}
for _, c := range []struct {
reason string
header bool
}{{"model_downshift", true}, {"comp_hash_changed", true}, {"model_downshift", false}} {
tried = nil
code, out := post("/v1/responses", c.reason, c.header)
if code != 200 {
t.Fatalf("%s (header %v): %d %s", c.reason, c.header, code, out)
}
if strings.Join(tried, ",") != "acct-1" {
t.Fatalf("%s: the old model was asked of %v, want acct-1 once", c.reason, tried)
}
if s := summary(out); !strings.Contains(s, "build the parser") || !strings.Contains(s, "the parser is built") {
t.Fatalf("%s: no local summary of the thread: %q\n%s", c.reason, s, out)
}
}
// the thread's own model out of room: the refusal is said, as before
if code, out := post("/v1/responses", "context_limit", true); code != 429 || !strings.Contains(out, "usage limit") {
t.Fatalf("context_limit: %d %s", code, out)
}
// Codex's own provider asks the turn's model by itself
if code, out := post(CodexPath+"/responses", "model_downshift", true); code != 429 || !strings.Contains(out, "usage limit") {
t.Fatalf("CodexPath model_downshift: %d %s", code, out)
}
}