Files
magpie/internal/gateway/cap_group_member_test.go
T
yetone f1996e7e5d gateway: a provider named past its usage cap is not sent on to a group (Anotiaww on X)
Anotiaww on X: magpie on server B asked magpie on server A for
claude/claude-opus-5-5. A's Claude account was past its usage cap (the
trace: "a usage window at 98%, over the account's 98% cap"), and the
Claude provider had no fallback set. The request was answered by a
WorkBuddy member of the user's routing group claude-opus-5.5 (the trace
row marked Fallback), with nothing said. They expect the cap's refusal.

Cause: 44d6dd75d (adorable_piglet, v0.1.3354) made serve plan a capped
provider again with every user-built routing group that has the model
in it (provider.GroupsAfter, groupsAfter) whenever no candidate was
left, so the Codex app, which asks its own model bare and never the
group, reaches the group's APIs. That rule did not look at what the
client asked for: a request naming the provider itself got the same
implicit fallback. Not the cause: the remote/shared path, auto groups
(GroupsAfter leaves them out), or a peer magpie's model mapping; the
peer sent claude/claude-opus-5-5 as written.

Fix: namedProvider(r, call.Model) in serve's groupsAfter arm. A model
asked with its provider in it (call.Model after unprefixed, so a flat
or aliased spelling of one too) is that provider's alone: past the cap
it goes to the provider's own Fallback list (planned before, untouched)
and else gets cappedError's 429 "usage cap reached". A bare model, and
Codex's own model that codexAccounts rewrote to codex/<model> on the
backend path (marked with providerPicked), still go on to the groups as
adorable_piglet asked; so does a turn codexFallBack hands on. CapStop is
unchanged. GroupsAfter's only other caller, codexFallsBack, is the
backend path, where Codex asks bare. Images and embeddings never read
GroupsAfter.

Tests:
- TestNamedProviderCappedRefuses: codex/gpt-5.5 past its 98% cap, a
  group [codex/gpt-5.5, a/m], on /v1/chat/completions, /v1/responses
  and /v1/messages, stream and not: 429 "usage cap reached" and the
  group's API not asked; with a fallback f/m set on the provider, the
  fallback answers (the user's fallback still holds).
- TestPluginCarefulPool: the plugin's model asked bare ("fake-1") still
  goes to the group; named "factory/fake-1" it is the 429.
- TestCappedCodexOwnModelGoesToItsGroup keeps the backend path's bare
  gpt-5.5; its /v1/responses "codex/gpt-5.5" subtest is now the named
  case above, the reverse answer.

Broken by hand (mote-run): the namedProvider guard out of serve:
TestNamedProviderCappedRefuses 6 subtests red (200 "from the group")
and TestPluginCarefulPool red ("named, group, stop off: 200 ... from
kf"). Restored: green.

Run (mote-run, mote at load ~130-165):
- gofmt -l internal empty.
- At the pushed tree, rebased on origin/main 208b89422: go test -count=1 ./internal/gateway -run 'TestNamedProviderCappedRefuses|
  TestCappedCodexOwnModelGoesToItsGroup|TestCappedSubscriptionGivesWayInGroup|
  TestSubscriptionCappedMidConversationGivesWay|TestCodexOneAccount|
  TestPluginCarefulPool|Fallback|Cap|Group': ok (144.6s; 138.9s before the rebase).
- go vet ./internal/gateway ./internal/provider: darwin, GOOS=linux -tags nogui, GOOS=windows: ok.

Rebased again onto 6b92824ff before the push (26 files of usage,
sessions and provider window-hold changes, none of the files here); the
runs above were at 208b89422, the tests run again at the pushed head
after the tag.

Not tried: a real Claude account past a real cap, and a real second
magpie (fakes only). The full suite runs after the tag. No GUI change.
2026-11-10 18:04:25 +08:00

144 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 rather than answering "usage cap reached". A model named with its provider ("codex/gpt-5.5")
// is that provider's alone: TestNamedProviderCappedRefuses.
func TestCappedCodexOwnModelGoesToItsGroup(t *testing.T) {
for _, c := range []struct{ path, model string }{
{CodexPath + "/responses", "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)
}
})
}
}
}