gateway: Codex's auto-review goes on where its conversation does when the sign-in is out (riverleaf88 on X)

riverleaf88 on X: with Codex's ChatGPT allowance spent and magpie routing
Codex on to another model, Codex's automatic review still failed.

Codex's guardian (codex-rs guardian-v2 sync_reviewer) asks the same
provider, so magpie's /backend-api/codex/responses, on codex-auto-review
(approval_review_preferred_model) with x-openai-subagent: guardian. On a
spent sign-in codexFallsBack and serve's groupsAfter looked for fallbacks
and routing groups of codex/codex-auto-review, a model no group names, so
the review was handed ChatGPT's 429 while the conversation's turns went
on to the group.

- codexReviewAfter: an auto-review on the codex sign-in takes the model
  its conversation's own turns go on (codexLeads). A codex model brings
  that model's fallbacks and groups (fallbacksOnly on the lead too); a
  magpie model the caller may use (servedSession) is tried itself.
  codexFallsBack and groupsAfter add them.
- codexHolds: once a 429 naming a reset held the account, later turns
  (main turns too) were answered with the held refusal before any
  fallback. The held branch now hands a /responses turn with fallbacks to
  codexFallBack as the first spent turn was.
- docs/subsystems/gateway-routing.md says both.

Run (mote): go test -count=1 -run 'TestCodexReviewSpent|TestCodexHeld|
TestCodexOneAccount|TestCodexSpent|Hold|Held' ./internal/gateway/ ok
71.2s; gofmt -l clean.
New tests red on the old code: TestCodexReviewSpentFollowsTheGroup and
...FollowsMagpieModel (review got 429 usage_limit_reached); the held case
in TestCodexHeldTurnFollowsTheGroup.
Broken by hand: codexReviewAfter returning nil turns
TestCodexReviewSpentFollowsTheGroup, ...FollowsMagpieModel and
TestCodexHeldTurnFollowsTheGroup red; dropping the held-branch fallback
turns TestCodexHeldTurnFollowsTheGroup and ...FollowsTheGroup red.
Not tried: a real exhausted ChatGPT account; guardian-v2's async scorer;
the multi-account pool path past serve's candidate loop is covered only
through the one-account tests.
Also run (mote, at this tree): go vet ./internal/gateway/ for darwin,
GOOS=linux -tags nogui and GOOS=windows: clean. go test -count=1
-timeout 45m ./internal/gateway/: ok 1037.9s (base 2219fdd49).
Rebased on 662546e78 (agentpath change only): go vet ./internal/gateway/
and -run 'TestCodex|Hold|Held|Fallback|Group': ok 289.7s.
This commit is contained in:
yetone
2026-11-10 16:43:25 +08:00
parent 286e3b6d5f
commit f2b9ec354a
5 changed files with 215 additions and 15 deletions
File diff suppressed because one or more lines are too long
+70 -7
View File
@@ -994,6 +994,15 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
if r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact") {
holdKey = codexHoldKey(base, on)
if h, ok := codexHeld(holdKey, start); ok {
if rest == "/responses" && base == provider.CodexBase && on == nil && s.codexFallsBack(r, body0) {
// Codex's own sign-in held, and somewhere for the turn to
// go on to: the fallbacks answer, as they did the refusal
// that held it, not Codex handed that refusal again while
// it lasts (riverleaf88 on X: the turn after went on to
// the group no more, nor did the auto-review)
s.codexFallBack(w0, r, body0, &keptAlive{proto: provider.Responses, told: start, streams: streamOf(body0)})
return
}
s.writeCodexHeld(w, r, h, base, on, modelOf(body), start)
return
}
@@ -1423,7 +1432,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
// its credits and resets looked at above, a 429 that names
// when the account is back holds it till then (codexHolds)
noteCodexHold(holdKey, res.StatusCode, res.Header, msg)
if overload && codexBusy(res.StatusCode, msg) && s.codexFallsBack(modelOf(body), body) {
if overload && codexBusy(res.StatusCode, msg) && s.codexFallsBack(r, body) {
// still too busy once asked again: the fallbacks answer
said := provider.APIError(msg, res.Status)
handOn(res.StatusCode, said, 0)
@@ -1431,7 +1440,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
s.codexFallBack(w0, r, body0, kept)
return
}
if overload && codexAccountOut(res.StatusCode, msg) && s.codexFallsBack(modelOf(body), body) {
if overload && codexAccountOut(res.StatusCode, msg) && s.codexFallsBack(r, body) {
// the account out of its allowance (its credits and resets
// looked at above): the fallbacks answer, as they do for a
// turn through magpie's accounts, rather than Codex handed
@@ -1461,7 +1470,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
// come, an error before them held for the turn to be asked again
out := w
var hw *holdWriter
if overload && streams && (busyAgain < lastRetries || kept.sent || s.codexFallsBack(modelOf(body), body)) {
if overload && streams && (busyAgain < lastRetries || kept.sent || s.codexFallsBack(r, body)) {
hw = newHoldWriter(w, true)
hw.alive, hw.streams, hw.ctx, hw.stop = kept, true, r.Context(), cancel
// reasoning goes to Codex at once, as it always went
@@ -1542,7 +1551,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
}
continue
}
if s.codexFallsBack(modelOf(body), body) {
if s.codexFallsBack(r, body) {
res.Body.Close()
handOn(hw.failure, said, 0)
end(hw.failure, said, 0, 0)
@@ -1550,7 +1559,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
return
}
}
if hw.mayAskAgain() && hw.failure != 0 && !hw.refused && codexAccountOut(hw.failure, hw.errBody()) && r.Context().Err() == nil && s.codexFallsBack(modelOf(body), body) {
if hw.mayAskAgain() && hw.failure != 0 && !hw.refused && codexAccountOut(hw.failure, hw.errBody()) && r.Context().Err() == nil && s.codexFallsBack(r, body) {
// the account out of its allowance, said on its stream before
// any of the reply: the fallbacks answer
said := "OpenAI: " + string(hw.errBody())
@@ -1689,7 +1698,14 @@ func codexAccountOut(status int, body []byte) bool {
// least one of them found, or a routing group the user built with the
// model in it (provider.GroupsAfter). A turn compacting natively is the backend's to
// answer, and goes nowhere else.
func (s *Server) codexFallsBack(model string, body []byte) bool {
//
// Codex's auto-review on codex-auto-review falls back too where its
// conversation's turns would (codexReviewAfter): no group has that model,
// so with the account out and Codex routed on through a group, every
// review was handed the refusal and failed while the turns went on
// (riverleaf88 on X).
func (s *Server) codexFallsBack(r *http.Request, body []byte) bool {
model := modelOf(body)
if model == "" || strings.Contains(model, "/") || compactionTriggerIn(body) {
return false
}
@@ -1697,7 +1713,54 @@ func (s *Server) codexFallsBack(model string, body []byte) bool {
if !ok || p.Account == nil || p.Account.Agent != "codex" {
return false
}
return len(provider.FallbackModels(p)) > 0 || len(provider.GroupsAfter(p.ID+"/"+model)) > 0
return len(provider.FallbackModels(p)) > 0 || len(provider.GroupsAfter(p.ID+"/"+model)) > 0 ||
len(s.codexReviewAfter(r, p, model, body)) > 0
}
// codexReviewAfter is where Codex's auto-review on codex-auto-review goes
// on to when the Codex subscription can't take it (the account out of its
// allowance, every account held at its cap), after the subscription's own
// fallbacks: where the turns of the conversation it reviews go on to.
// That conversation on one of magpie's models, the model itself, when
// magpie serves it to this caller (servedSession); on one of Codex's own,
// the routing groups the user built with that model in them
// (provider.GroupsAfter), which a turn on it goes on to. Codex asks its
// reviewer by OpenAI's name whatever the conversation is on (codex-rs
// guardian reviewer_config.rs, approval_review_preferred_model), and only
// the ChatGPT backend serves it. nil for any other request.
func (s *Server) codexReviewAfter(r *http.Request, p provider.Provider, model string, body []byte) []string {
lead := s.codexReviewLead(r, p, model, body)
if lead == "" {
return nil
}
if strings.Contains(lead, "/") {
to := s.servedSession(r, lead)
if to == "" {
return nil
}
if q, _, ok := provider.Resolve(to); ok && q.ID == p.ID && !provider.IsGroupRef(to) {
// the subscription itself, under another name: out too
return nil
}
return []string{to}
}
return provider.GroupsAfter(p.ID + "/" + lead)
}
// codexReviewLead is the model the conversation Codex's auto-review on
// codex-auto-review through p, the Codex subscription, reviews is on: one
// of Codex's own by its bare name, or one of magpie's ids; "" for any
// other request, or a conversation magpie has seen no turn of.
func (s *Server) codexReviewLead(r *http.Request, p provider.Provider, model string, body []byte) string {
if p.ID != "codex" || p.Account == nil || p.Account.Agent != "codex" || !strings.EqualFold(strings.TrimSpace(model), provider.CodexAutoReview) {
return ""
}
lead, _, _ := s.codexLeads.lookup(r, body)
lead = strings.TrimPrefix(lead, "codex/")
if strings.EqualFold(lead, model) {
return ""
}
return lead
}
// codexFallBack serves Codex's turn on its own sign-in, which the backend
+129
View File
@@ -0,0 +1,129 @@
package gateway
import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Codex's auto-review of an approval, as codex-rs's guardian sends it: on
// its reviewer model, codex-auto-review, whatever the conversation is on,
// under x-openai-subagent: guardian and x-codex-guardian: reviewer.
const reviewTurn = `{"model":"codex-auto-review","stream":true,"input":"review this approval"}`
// reviewOn posts body to s's Codex route as Codex's guardian does (guardian
// true) or as one of the conversation's own turns.
func reviewOn(s *Server, body string, guardian bool) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
if guardian {
req.Header.Set("x-openai-subagent", "guardian")
req.Header.Set("x-codex-guardian", "reviewer")
}
s.Handler().ServeHTTP(rec, req)
return rec
}
// Codex's one ChatGPT account out of its allowance, and Codex routed on
// through a routing group of the user's with Codex's model first and an
// API after it: the conversation's turns go on to the API, and so does
// its auto-review, which asks codex-auto-review, a model no group has
// (riverleaf88 on X: "在codex耗尽额度时,即使路由到别的模型,在codex中自动审查会失败").
// Before, the review was handed the backend's refusal, and Codex failed it.
func TestCodexReviewSpentFollowsTheGroup(t *testing.T) {
for _, x := range codexSpent {
t.Run(x.name, func(t *testing.T) {
b := &spentBackend{refuse: x.refuse}
spentAccount(t, b, false)
a := &scripted{replies: []reply{{200, "", chatSSEReply("from the group")}}}
scriptedOn(t, "a", provider.Chat, a)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5", "a/m"}}); err != nil {
t.Fatal(err)
}
s := New()
if rec := reviewOn(s, oneAccountTurn, false); rec.Code != 200 || !strings.Contains(rec.Body.String(), "from the group") {
t.Fatalf("turn: %d %q", rec.Code, rec.Body.String())
}
rec := reviewOn(s, reviewTurn, true)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from the group") || strings.Contains(rec.Body.String(), "usage_limit_reached") {
t.Fatalf("review: %d %q", rec.Code, rec.Body.String())
}
if a.n != 2 {
t.Fatalf("the group's API asked %d times, ChatGPT %d", a.n, b.n.Load())
}
if b.n.Load() > 2 {
// the spent account isn't asked again for the review on
// the conversation's model, the group's first member
t.Fatalf("ChatGPT asked %d times", b.n.Load())
}
})
}
}
// The conversation on one of magpie's models, picked in the Codex app
// beside the spent ChatGPT sign-in: its auto-review, on codex-auto-review
// through the sign-in, goes on to that model when the account is out.
func TestCodexReviewSpentFollowsMagpieModel(t *testing.T) {
for _, x := range codexSpent {
t.Run(x.name, func(t *testing.T) {
b := &spentBackend{refuse: x.refuse}
spentAccount(t, b, false)
a := &scripted{replies: []reply{{200, "", chatSSEReply("from magpie's model")}}}
scriptedOn(t, "a", provider.Chat, a)
s := New()
if rec := reviewOn(s, `{"model":"a/m","stream":true,"input":"ping"}`, false); rec.Code != 200 || b.n.Load() != 0 {
t.Fatalf("turn: %d %q, ChatGPT asked %d", rec.Code, rec.Body.String(), b.n.Load())
}
rec := reviewOn(s, reviewTurn, true)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from magpie's model") || b.n.Load() != 1 || a.n != 2 {
t.Fatalf("review: %d %q, ChatGPT asked %d, a %d", rec.Code, rec.Body.String(), b.n.Load(), a.n)
}
})
}
}
// With nowhere else for the conversation to go (no fallback, no group, no
// turn of magpie's to follow), the review still has the backend's own
// refusal, as it had.
func TestCodexReviewSpentNowhereElseRelayed(t *testing.T) {
b := &spentBackend{refuse: codexSpent[0].refuse}
spentAccount(t, b, false)
a := &scripted{replies: []reply{{200, "", chatSSEReply("never")}}}
scriptedOn(t, "a", provider.Chat, a)
rec := reviewOn(New(), reviewTurn, true)
if rec.Code != 429 || !strings.Contains(rec.Body.String(), "usage_limit_reached") || b.n.Load() != 1 || a.n != 0 {
t.Fatalf("%d %q, ChatGPT asked %d, a %d", rec.Code, rec.Body.String(), b.n.Load(), a.n)
}
}
// The account held after ChatGPT's 429 named when it is back
// (codexHolds): the next turn, and the review after it, go on to the
// group as the turn that held it did, never handed the refusal again from
// the hold while it lasts.
func TestCodexHeldTurnFollowsTheGroup(t *testing.T) {
for _, x := range codexSpent[:2] {
t.Run(x.name, func(t *testing.T) {
b := &spentBackend{refuse: x.refuse}
spentAccount(t, b, false)
a := &scripted{replies: []reply{{200, "", chatSSEReply("from the group")}}}
scriptedOn(t, "a", provider.Chat, a)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5", "a/m"}}); err != nil {
t.Fatal(err)
}
s := New()
for i, body := range []string{oneAccountTurn, oneAccountTurn, reviewTurn} {
rec := reviewOn(s, body, body == reviewTurn)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from the group") {
t.Fatalf("request %d: %d %q", i, rec.Code, rec.Body.String())
}
}
if b.n.Load() != 1 || a.n != 3 {
t.Fatalf("ChatGPT asked %d times, the group's API %d", b.n.Load(), a.n)
}
})
}
}
+6 -5
View File
@@ -583,12 +583,13 @@ func (s *Server) planPaused(p provider.Provider, model string, from provider.Pro
}
// groupsAfter is p with the routing groups the user built that have p's
// model in them (provider.GroupsAfter) added after its own fallbacks,
// those it has already left out; ok is false when there are none to add.
func groupsAfter(p provider.Provider, model string) (provider.Provider, bool) {
// model in them (provider.GroupsAfter), then also, added after its own
// fallbacks, those it has already left out; ok is false when there are
// none to add.
func groupsAfter(p provider.Provider, model string, also ...string) (provider.Provider, bool) {
var add []string
for _, id := range provider.GroupsAfter(p.ID + "/" + model) {
if !slices.Contains(p.Fallback, id) {
for _, id := range append(provider.GroupsAfter(p.ID+"/"+model), also...) {
if !slices.Contains(p.Fallback, id) && !slices.Contains(add, id) {
add = append(add, id)
}
}
+8 -1
View File
@@ -2931,7 +2931,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// the groups the user built with this model in them go on from
// it, as a request to the group would (the Codex app asks
// Codex's own model, never the group)
if q, ok := groupsAfter(p, model); ok {
// Codex's auto-review on codex-auto-review, which no group has,
// goes on where its conversation's turns go (codexReviewAfter)
if q, ok := groupsAfter(p, model, s.codexReviewAfter(r, p, model, body)...); ok {
cands, pl = s.planPaused(q, model, from, pausedIn)
}
}
@@ -2939,6 +2941,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// Codex's own sign-in, asked as often as it is asked: only
// the fallbacks are left (codexFallBack)
cands, pl = fallbacksOnly(cands, pl, p.ID, model)
if lead := s.codexReviewLead(r, p, model, body); lead != "" && !strings.Contains(lead, "/") {
// and an auto-review's, on the conversation's model through
// that same sign-in, in a group it goes on to
cands, pl = fallbacksOnly(cands, pl, p.ID, lead)
}
}
if provider.IsFastPick(agent, p.ID+"/"+model) {
// the agent's pick of it is sent in its vendor's fast mode