gateway: Codex's compaction trigger is summarised, not refused, when no key that lists the model can carry it (#2725)

nativeCompactionFor kept Codex's compaction_trigger whenever the
provider asked had native compaction on and could be asked it on
Responses. When the vendor's lists held the model to a key that speaks
no Responses there (a key set to Chat), compactionCarriers then cleared
every candidate and Codex got 400 carrierError, with no upstream asked:
the dead end #2725 reports. The trigger is now kept only when a key or
account the request would go over (the provider's and its fallbacks',
or a group's members', held and capped ones too, not one whose own
list lacks the model) carries it (plannedCarrier). Otherwise
codexCompact gives magpie's summary through the listed key, as with
native compaction off.

Patch by ggbdpq (#2725): route (a) and both tests are theirs. Changed
from it: their planCarries ran s.plan / s.planGroup, which weighs the
keys, and a provider routed in turn moves its turn along there
(routes.Rotate). nativeCompactionFor runs on every Codex turn (handle,
codexBackend), so each decision would have skipped a key. plannedCarrier
reads perKeyBarred without weighing. Doc sentence in
docs/subsystems/gateway-routing.md.

Run (worktree at e54a7d50b):
- TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt: red
  on the old native_compaction.go ("400, the relay asked 0 times ...
  none of the keys or accounts that serve fake/m1 now can be asked it
  on the Responses"), green now.
  TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt green.
- TestNativeCompactionDecisionLeavesTheTurnsAlone (new, three keys,
  Rotate): red with the patch's planCarries ("a turn began at k2, the
  next at k1"), green with plannedCarrier.
- -race -count=3 on those three; NativeCompaction|Compact|Checkpoint|
  CodexBackend ok; the whole internal/gateway package
  (-tags nogui -count=1 -timeout 45m) ok in 609s.
- gofmt -l clean; go vet ./internal/gateway for darwin, GOOS=windows,
  GOOS=linux -tags nogui clean.
Not tried: a real relay whose vendor lists a model to a Chat-only key.
This commit is contained in:
yetone
2026-10-28 00:16:48 +08:00
parent 8586b1cda5
commit fff05e55d8
3 changed files with 181 additions and 5 deletions
File diff suppressed because one or more lines are too long
+42 -4
View File
@@ -91,8 +91,11 @@ func (s *Server) compactsNatively(p provider.Provider, model string) bool {
// nativeCompactionFor is whether Codex's compaction_trigger for the model
// it asked (a provider's model, or a routing group) goes on as Codex sent
// it: every member of a group compacting natively, as any of them may
// answer it. A group with one that doesn't keeps magpie's summary, which
// any member can read.
// answer it, and a key or account the request would go over able to be
// asked it (plannedCarrier, #2725). A group with one that doesn't keeps
// magpie's summary, which any member can read; so does a provider whose
// vendor lists the model only to keys that speak no Responses there, as
// with native compaction off, where the trigger was refused before.
func (s *Server) nativeCompactionFor(asked string) bool {
if _, ms, ok := provider.FindGroup(asked); ok {
if len(ms) == 0 {
@@ -103,10 +106,45 @@ func (s *Server) nativeCompactionFor(asked string) bool {
return false
}
}
return true
return slices.ContainsFunc(ms, func(m provider.Member) bool { return s.plannedCarrier(m.Provider, m.Model) })
}
p, model, ok := provider.Resolve(asked)
return ok && s.compactsNatively(p, model)
if !ok || !s.compactsNatively(p, model) {
return false
}
// the request goes over the provider's keys, then its fallbacks' (plan)
if s.plannedCarrier(p, model) {
return true
}
seen := map[string]bool{p.ID + "/" + model: true}
for _, id := range p.Fallback {
fp, fm, ok := provider.Resolve(id)
if !ok || seen[fp.ID+"/"+fm] {
continue
}
seen[fp.ID+"/"+fm] = true
if s.plannedCarrier(fp, fm) {
return true
}
}
return false
}
// plannedCarrier is whether one of the keys or accounts plan would put in
// a Responses request's candidates for model at p — those it goes over,
// those made for another protocol, and the held and capped ones, not those
// whose own list lacks the model — can be asked Codex's compaction, as
// compactionCarriers keeps them. It reads perKeyBarred alone, not plan:
// a plan weighs the keys, and a provider routed in turn would move its
// turn along for a request that never went (every Codex turn is decided).
func (s *Server) plannedCarrier(p provider.Provider, model string) bool {
cs, aside, _, barred := perKeyBarred(p, model, provider.Responses)
for _, l := range [][]candidate{cs, aside, creditsHeld(barred), capHeldOnly(barred)} {
if slices.ContainsFunc(l, func(c candidate) bool { return s.carriesCompaction(c.p, c.model) }) {
return true
}
}
return false
}
// keepsCompaction is whether body goes to p as it is for its compaction:
+138
View File
@@ -802,3 +802,141 @@ func TestNativeCompactionCompactKeepsTheKeysAccounts(t *testing.T) {
})
}
}
// A trigger Codex asks of a provider set to compact natively is kept only
// when a key that lists the model can be asked it on the Responses API.
// When the vendor's lists hold the model to a key that speaks no
// Responses there (its key is set to Chat, so WithKey leaves it no
// Responses URL), the trigger is not kept: magpie summarises instead,
// which the listed key reads, as it does when native compaction is off.
// Before, the trigger was kept because the provider (whose setting is
// what kept it) carries it, and then refused saying none of the keys that
// serve the model can be asked it on Responses — a dead end, when
// magpie's summary was one turn away.
func TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt(t *testing.T) {
noRests()
t.Cleanup(noRests)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
// the summary comes back through the chat key, the one whose list
// holds the model
f := &fake{t: t, reply: sse(
`data: {"id":"c1","model":"m1","choices":[{"delta":{"content":"SUMM"}}]}`,
`data: {"id":"c1","choices":[{"delta":{"content":"ARY"},"finish_reason":"stop"}]}`,
`data: [DONE]`)}
up := httptest.NewServer(f)
t.Cleanup(up.Close)
// the first key is set to chat: it serves the model, but not on
// Responses; the second speaks nothing in particular and would carry
// the compaction, but the vendor's list doesn't hold the model to it
p := provider.Provider{ID: "fake", Name: "Fake", Key: "kchat", KeyProtocol: provider.Chat, Models: []string{"m1"}}
p.Chat = up.URL + "/v1"
p.Responses = up.URL + "/v1"
p.Keys = []provider.KeyAccount{{Key: "kresp"}}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("fake", up.URL+"/v1", []catalog.Model{
{ID: "m1", Keys: []string{provider.KeyID("kchat")}},
{ID: "m2", Keys: []string{provider.KeyID("kresp")}},
}); err != nil {
t.Fatal(err)
}
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400) })
nativeOn(t, "fake")
code, body := nativeAsk(t, "fake/m1", compactTurn)
if code != 200 || f.calls != 1 || !strings.Contains(string(f.got), "CONTEXT CHECKPOINT COMPACTION") || strings.Contains(string(f.got), "compaction_trigger") {
t.Fatalf("%d, the relay asked %d times: %s", code, f.calls, body)
}
// the summary went by the chat key, the only one that lists the model;
// the responses key, whose own list lacks it, was never asked
if f.path != "/v1/chat/completions" || f.head.Get("Authorization") != "Bearer kchat" {
t.Errorf("the summary didn't go by the listed key: %s %q", f.path, f.head.Get("Authorization"))
}
if !strings.Contains(body, magpieCompaction) || strings.Contains(body, "gAAAAB") {
t.Errorf("Codex got %s", body)
}
}
// A trigger Codex asks of a provider whose listed key can be asked the
// compaction on Responses still goes to it as Codex sent it — the gate
// that summarises when no listed key carries it changes nothing here —
// and the key whose own list lacks the model stays unasked, as an
// ordinary request leaves it.
func TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt(t *testing.T) {
noRests()
t.Cleanup(noRests)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
f := &fake{t: t, reply: nativeSealedReply("gAAAAB-sealed-by-listed")}
up := httptest.NewServer(f)
t.Cleanup(up.Close)
// neither key is set to a protocol, so the first can be asked the
// compaction on Responses; the vendor's list holds the model to it
// alone, and another model to the second
p := provider.Provider{ID: "fake", Name: "Fake", Key: "kcarries", Models: []string{"m1"}}
p.Chat = up.URL + "/v1"
p.Responses = up.URL + "/v1"
p.Keys = []provider.KeyAccount{{Key: "kother"}}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("fake", up.URL+"/v1", []catalog.Model{
{ID: "m1", Keys: []string{provider.KeyID("kcarries")}},
{ID: "m2", Keys: []string{provider.KeyID("kother")}},
}); err != nil {
t.Fatal(err)
}
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400) })
nativeOn(t, "fake")
code, body := nativeAsk(t, "fake/m1", compactTurn)
if code != 200 || f.calls != 1 {
t.Fatalf("%d, the relay asked %d times: %s", code, f.calls, body)
}
if !strings.Contains(string(f.got), `{"type":"compaction_trigger"}`) || strings.Contains(string(f.got), "CONTEXT CHECKPOINT COMPACTION") {
t.Errorf("the relay wasn't asked Codex's own compaction: %s", f.got)
}
if f.path != "/v1/responses" || f.head.Get("Authorization") != "Bearer kcarries" {
t.Errorf("the trigger didn't go by the listed key: %s %q", f.path, f.head.Get("Authorization"))
}
if !strings.Contains(body, `"encrypted_content":"gAAAAB-sealed-by-listed"`) || strings.Contains(body, magpieCompaction) {
t.Errorf("Codex got %s", body)
}
}
// Deciding whether a provider set to compact natively keeps Codex's
// trigger asks nothing of its routing. The decision is made on every one
// of Codex's turns, compacting or not, before the turn is planned; a plan
// weighs the keys, and a provider routed in turn would move its turn along
// for a request that never went (a plan in the decision did: each turn
// began two keys along, not one).
func TestNativeCompactionDecisionLeavesTheTurnsAlone(t *testing.T) {
noRests()
t.Cleanup(noRests)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
setHome(t, t.TempDir())
p := provider.Provider{ID: "fake", Name: "Fake", Key: "k1", Models: []string{"m1"}, Routing: provider.Rotate,
Responses: "http://127.0.0.1:1/v1", Keys: []provider.KeyAccount{{Key: "k2"}, {Key: "k3"}}}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
nativeOn(t, "fake")
s := New()
first := func() string {
q, _, _ := provider.Resolve("fake/m1")
cs, _ := s.plan(q, "m1", provider.Responses)
return cs[0].p.Key
}
if !s.nativeCompactionFor("fake/m1") {
t.Fatal("a provider set to compact natively, whose keys carry it, doesn't keep the trigger")
}
next := map[string]string{"k1": "k2", "k2": "k3", "k3": "k1"}
for range 3 {
was := first()
s.nativeCompactionFor("fake/m1")
if now := first(); now != next[was] {
t.Fatalf("a turn began at %s, the next at %s: the decision moved the turn along", was, now)
}
}
}