Files
magpie/internal/gateway/cap_group_member_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

145 lines
5.9 KiB
Go

package gateway
import (
"fmt"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// Discord (v0.1.3354): a subscription account at its usage cap in a
// routing group with two APIs; the group's next member takes the request.
func TestCappedSubscriptionGivesWayInGroup(t *testing.T) {
for _, routing := range []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed, provider.Pace, provider.Weighted, provider.FreeFirst, provider.Fastest, provider.Cheapest, provider.Drain, provider.FreeExpiring} {
for _, path := range []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", CodexPath + "/responses"} {
t.Run(routing+path, func(t *testing.T) {
codexSignedIn(t)
b := newResetBackend(t)
capUsage(t, map[string]float64{"me@example.com": 75})
if err := provider.SetAccountCap("codex", "me@example.com", 70); err != nil {
t.Fatal(err)
}
a := &scripted{replies: []reply{{200, "", chatSSEReply("OK")}}}
c := &scripted{replies: []reply{{200, "", chatSSEReply("OK")}}}
scriptedOn(t, "a", provider.Chat, a)
scriptedOn(t, "c", provider.Chat, c)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5", "a/m", "c/m"}, Routing: routing}); err != nil {
t.Fatal(err)
}
s := New()
var code int
var body string
switch {
case strings.HasPrefix(path, CodexPath):
rec := codexOn(s, path, `{"model":"group/g","input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`)
code, body = rec.Code, rec.Body.String()
case path == "/v1/responses":
code, body = postTo(t, s, path, `{"model":"group/g","input":"hi"}`)
case path == "/v1/messages":
code, body = postTo(t, s, path, `{"model":"group/g","max_tokens":20,"messages":[{"role":"user","content":"hi"}]}`)
default:
code, body = postTo(t, s, path, `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`)
}
tried, _ := b.seen()
if code != 200 || tried != "" || a.n+c.n != 1 {
t.Fatalf("%d %s (codex %q, a %d, c %d)", code, body, tried, a.n, c.n)
}
})
}
}
}
// The same, with the account crossing its cap during a conversation: the
// turn after the reading says it is past the cap goes to the group's next
// member, as the conversation's own account is used up.
func TestSubscriptionCappedMidConversationGivesWay(t *testing.T) {
for _, routing := range []string{"", provider.Ordered} {
for _, used := range []float64{50, 68} {
t.Run(fmt.Sprintf("%s-%v", routing, used), func(t *testing.T) {
codexSignedIn(t)
b := newResetBackend(t)
now := map[string]float64{"me@example.com": used}
old := allowances
t.Cleanup(func() { allowances = old })
reset := time.Now().Add(3 * time.Hour)
var mu sync.Mutex
allowances = func(string) map[string]provider.Allowance {
mu.Lock()
defer mu.Unlock()
out := map[string]provider.Allowance{}
for u, n := range now {
out[u] = provider.Allowance{{Used: n, Resets: reset, Span: 5 * time.Hour}}
}
return out
}
if err := provider.SetAccountCap("codex", "me@example.com", 70); err != nil {
t.Fatal(err)
}
a := &scripted{replies: []reply{{200, "", chatSSEReply("OK")}}}
c := &scripted{replies: []reply{{200, "", chatSSEReply("OK")}}}
scriptedOn(t, "a", provider.Chat, a)
scriptedOn(t, "c", provider.Chat, c)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5", "a/m", "c/m"}, Routing: routing}); err != nil {
t.Fatal(err)
}
s := New()
code, body := postTo(t, s, "/v1/chat/completions", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`)
if tried, _ := b.seen(); code != 200 || tried == "" {
t.Fatalf("first turn: %d %s (codex %q)", code, body, tried)
}
mu.Lock()
now["me@example.com"] = 75
mu.Unlock()
code, body = postTo(t, s, "/v1/chat/completions", `{"model":"group/g","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"OK"},{"role":"user","content":"again"}]}`)
if code != 200 || a.n+c.n != 1 {
tried, _ := b.seen()
t.Fatalf("second turn: %d %s (codex %q, a %d, c %d)", code, body, tried, a.n, c.n)
}
})
}
}
}
// The reporter's case: the Codex app, signed in to ChatGPT, sends Codex's
// own model names, never the group's. With the account past its cap, a
// routing group the user built with that account first goes on to its
// next member, on both of magpie's Codex paths, rather than answering
// "usage cap reached".
func TestCappedCodexOwnModelGoesToItsGroup(t *testing.T) {
for _, c := range []struct{ path, model string }{
{CodexPath + "/responses", "gpt-5.5"},
{"/v1/responses", "codex/gpt-5.5"},
} {
for _, stream := range []bool{true, false} {
t.Run(fmt.Sprintf("%s-%s-%v", c.path, c.model, stream), func(t *testing.T) {
codexSignedIn(t)
b := newResetBackend(t)
capUsage(t, map[string]float64{"me@example.com": 75})
if err := provider.SetAccountCap("codex", "me@example.com", 70); err != nil {
t.Fatal(err)
}
a := &scripted{replies: []reply{{200, "", chatSSEReply("OK")}}}
c2 := &scripted{replies: []reply{{200, "", chatSSEReply("OK")}}}
scriptedOn(t, "a", provider.Chat, a)
scriptedOn(t, "c", provider.Chat, c2)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5", "a/m", "c/m"}}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", c.path, strings.NewReader(fmt.Sprintf(`{"model":%q,"stream":%v,"input":"hi"}`, c.model, stream)))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
New().Handler().ServeHTTP(rec, req)
tried, _ := b.seen()
if rec.Code != 200 || tried != "" || a.n != 1 || c2.n != 0 {
t.Fatalf("%d %s (codex %q, a %d, c %d)", rec.Code, rec.Body.String(), tried, a.n, c2.n)
}
})
}
}
}