Files
magpie/internal/gateway/codex_one_account_spent_test.go
T
yetone 44d6dd75d1 gateway: a subscription's capped or spent turn goes on to the user's group with it in
adorable_piglet on Discord (v0.1.3354): a Codex subscription with a usage
cap set in magpie, first in a routing group with two APIs after it. Past
the cap the Codex app's turns were answered 429 "usage cap reached" and
never reached the APIs; only switching the subscription off in Providers
moved them.

Cause: the Codex app signed in to ChatGPT asks Codex's own model
("gpt-5.5"), never "group/<id>". With a cap on the account,
codexAccounts routes the turn as codex/gpt-5.5, and serve plans the
codex provider and its own Fallback list only. A group that merely has
codex/gpt-5.5 in it was never planned, so with every account held the
answer was cappedError's 429. A request for the group itself was already
routed on past the cap (TestCappedSubscriptionGivesWayInGroup, green on
the old code too). The same gap was on Codex's own sign-in out of its
allowance at OpenAI: codexFallsBack counted the subscription's Fallback
only, so the backend's usage_limit_reached reached Codex.

Fix:
- provider.GroupsAfter(id): the routing groups the user built that have
  the model in them and another member to go on to, in the user's order;
  auto groups, hidden or switched-off ones are none.
- serve: when every account is held at its cap (pl.capped, no candidate
  left, CapStop off), or for a turn codexFallBack handed on, the provider
  is planned again with those groups after its own fallbacks
  (groupsAfter), each group routed as a request to it is. One place, so
  it holds on every protocol (chat, responses, messages, Codex's backend
  path), streaming or not, and for plugin-served subscriptions.
- codexFallsBack counts those groups as fallbacks too.
- Stop at the caps (CapStop) still answers 429 (planPaused returns
  before any fallback, the groups included).

Tests:
- TestCappedCodexOwnModelGoesToItsGroup: backend path with "gpt-5.5" and
  /v1/responses with "codex/gpt-5.5", stream and not; red on origin/main
  3cabaab54 (4 of 4, 429 usage cap reached).
- TestCodexOneAccountSpentGoesToItsGroup: one ChatGPT account, the
  backend's usage_limit_reached, group [codex/gpt-5.5, a/m].
- TestPluginCarefulPool: the fake plugin as Factory through a real
  plugin host, both accounts past their caps, no fallback, group
  [factory/fake-1, spare/m2]: 429 with Stop at the caps on, the API with
  it off.
- TestCappedSubscriptionGivesWayInGroup (11 routings x 4 paths) and
  TestSubscriptionCappedMidConversationGivesWay pin the group/<id> case.

Broken by hand (each through mote-run):
- the serve block off: TestCappedCodexOwnModelGoesToItsGroup 4 of 4 red
  and TestPluginCarefulPool red ("group, stop off: 429").
- GroupsAfter out of codexFallsBack: TestCodexOneAccountSpentGoesToItsGroup
  red (429 usage_limit_reached).
- the handedOnOf arm out of serve: the same test red.
- the !p.CapStop guard out: still green, since planPaused itself returns
  before fallbacks with CapStop; the guard only saves a second plan.

Run at this tree (mote-run, mote under load from other sessions):
- gofmt -l . empty; go vet (darwin, GOOS=windows, GOOS=linux) of
  internal/gateway and internal/provider ok.
- go test -timeout 45m -count=1 ./internal/gateway ./internal/provider:
  provider ok (673s); gateway FAIL (2545s) on TestBurstTellsNoSpeed/
  responses_from_chat_burst alone (5000 tokens in 1091ms read as a
  speed), a timing red under load, ttft untouched here; 3 of 3 green
  alone at this tree, noted on #2719 (the same test's chat_burst).
  That run was at base 3cabaab54.
- Rebased onto origin/main 8a7f77cb7 (9 gateway/provider files changed
  there): gofmt empty, go vet ok, and go test ./internal/gateway -run
  "Cap|Capped|Fallback|TestCodexOneAccount|TestPluginCarefulPool|
  TestSubscriptionCapped" ok (199s) at the pushed tree.

Not tried: a real Codex app and ChatGPT account past a real cap (fakes
only). Not covered: an account that crosses its cap in serve's near-cap
walk (planned with room, held at its turn) still gets the 429 for that
turn; the next turn is planned with it held and goes to the group.
Drawing (images) and embeddings keep their own planning and are
unchanged. No GUI change.
2026-11-09 12:31:00 +08:00

125 lines
4.9 KiB
Go

package gateway
import (
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// spentBackend is the ChatGPT backend turning every turn away as refuse
// does, counting what it was asked.
type spentBackend struct {
refuse func(w http.ResponseWriter)
n atomic.Int32
}
func (b *spentBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b.n.Add(1)
// no Content-Type unless refuse says one, as the backend streams
w.Header()["Content-Type"] = nil
b.refuse(w)
}
// spentAccount is Codex signed in to ChatGPT with its one account, the
// ChatGPT backend b, and the Codex subscription falling back to fb/m
// when fallback is set.
func spentAccount(t *testing.T, b *spentBackend, fallback bool) *scripted {
t.Helper()
codexSignedIn(t)
up := httptest.NewServer(b)
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
pause := retryPause
retryPause = time.Millisecond
t.Cleanup(func() { retryPause = pause })
fb := &scripted{replies: []reply{{200, "text/event-stream", sse(
`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from the fallback"}`,
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"f1","status":"completed","output":[]}}`)}}}
if fallback {
responsesOn(t, "fb", fb)
if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil {
t.Fatal(err)
}
}
if id, routed := codexAccounts(httptest.NewRequest("POST", CodexPath+"/responses", nil), "gpt-5.5"); routed {
t.Fatalf("one account goes through routing as %s", id)
}
return fb
}
// Codex's one ChatGPT account out of its allowance, the Codex subscription
// with a fallback set in magpie (the user's own API key, another
// provider): the turn Codex relays on its sign-in goes on to the fallback,
// in every shape the backend says the account is out, as a turn through
// magpie's accounts does (adorable_piglet on Discord: the Plus account's
// quota ran out and Codex was handed the refusal, never the fallback).
// The account is asked once; the refusal never reaches Codex.
func TestCodexOneAccountSpentFallsBack(t *testing.T) {
for _, x := range codexSpent {
t.Run(x.name, func(t *testing.T) {
b := &spentBackend{refuse: x.refuse}
fb := spentAccount(t, b, true)
code, body := codexPost(t, oneAccountTurn)
if code != 200 || !strings.Contains(body, "from the fallback") || strings.Contains(body, "usage_limit_reached") ||
strings.Contains(body, "rate_limit_exceeded") || strings.Contains(body, "usage_not_included") {
t.Fatalf("%d %q", code, body)
}
if b.n.Load() != 1 || fb.n != 1 {
t.Fatalf("ChatGPT asked %d times, the fallback %d", b.n.Load(), fb.n)
}
})
}
}
// With no fallback set, Codex still has the backend's own refusal, as it
// had (TestCodexOwnModelOneAccountRelayed): nowhere else to go.
func TestCodexOneAccountSpentNoFallbackRelayed(t *testing.T) {
b := &spentBackend{refuse: codexSpent[0].refuse}
spentAccount(t, b, false)
code, body := codexPost(t, oneAccountTurn)
if code != 429 || !strings.Contains(body, "usage_limit_reached") || b.n.Load() != 1 {
t.Fatalf("%d %q, asked %d", code, body, b.n.Load())
}
}
// With no fallback set but a routing group of the user's with the Codex
// subscription's model first and an API after it, the spent turn goes on
// to the group's API (adorable_piglet on Discord, v0.1.3354: the Codex app
// asks its own model, never the group).
func TestCodexOneAccountSpentGoesToItsGroup(t *testing.T) {
b := &spentBackend{refuse: codexSpent[0].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)
}
code, body := codexPost(t, oneAccountTurn)
if code != 200 || !strings.Contains(body, "from the group") || b.n.Load() != 1 || a.n != 1 {
t.Fatalf("%d %q, ChatGPT asked %d, the group's API %d", code, body, b.n.Load(), a.n)
}
}
// A sign-in the backend refuses (401) goes to Codex as it came, fallback
// or not: Codex renews its own token on it, which a fallback's answer
// would keep it from doing.
func TestCodexOneAccountSignInRefusedNotFallenBack(t *testing.T) {
b := &spentBackend{refuse: func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(401)
w.Write([]byte(`{"error":{"message":"Provided authentication token is expired. Please try signing in again.","code":"token_expired"}}`))
}}
fb := spentAccount(t, b, true)
code, body := codexPost(t, oneAccountTurn)
if code != 401 || !strings.Contains(body, "token_expired") || fb.n != 0 {
t.Fatalf("%d %q, fallback asked %d", code, body, fb.n)
}
}