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.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -0,0 +1,144 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1670,7 +1670,8 @@ func codexAccountOut(status int, body []byte) bool {
|
||||
|
||||
// codexFallsBack says Codex's turn on one of its own models has fallbacks
|
||||
// to go on to (codexFallBack): the Codex subscription's, set in magpie, at
|
||||
// least one of them found. A turn compacting natively is the backend's to
|
||||
// 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 {
|
||||
if model == "" || strings.Contains(model, "/") || compactionTriggerIn(body) {
|
||||
@@ -1680,7 +1681,7 @@ 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
|
||||
return len(provider.FallbackModels(p)) > 0 || len(provider.GroupsAfter(p.ID+"/"+model)) > 0
|
||||
}
|
||||
|
||||
// codexFallBack serves Codex's turn on its own sign-in, which the backend
|
||||
|
||||
@@ -89,6 +89,24 @@ func TestCodexOneAccountSpentNoFallbackRelayed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -578,6 +578,23 @@ func (s *Server) planPaused(p provider.Provider, model string, from provider.Pro
|
||||
return restLast(out, pl)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
var add []string
|
||||
for _, id := range provider.GroupsAfter(p.ID + "/" + model) {
|
||||
if !slices.Contains(p.Fallback, id) {
|
||||
add = append(add, id)
|
||||
}
|
||||
}
|
||||
if len(add) == 0 {
|
||||
return p, false
|
||||
}
|
||||
p.Fallback = append(slices.Clone(p.Fallback), add...)
|
||||
return p, true
|
||||
}
|
||||
|
||||
// planFallbackGroup is planGroup for a routing group a provider falls back
|
||||
// to, its rows added to pl as fallbacks reached through g: the group's
|
||||
// keys and accounts in its own order, sunk by its own Sink, those set
|
||||
|
||||
@@ -2804,14 +2804,25 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
} else {
|
||||
// a routing group among the fallbacks is routed as a request to it
|
||||
// would be, its pause rules too (pausedOut's)
|
||||
cands, pl = s.planPaused(p, model, from, func(fg provider.Group, fms []provider.Member) []provider.Member {
|
||||
pausedIn := func(fg provider.Group, fms []provider.Member) []provider.Member {
|
||||
folder := ""
|
||||
if provider.PausesByFolder(fg, fms) {
|
||||
folder = factsOf(from, body).dir
|
||||
}
|
||||
kept, _ := provider.PausedOut(fg, fms, agent, folder, ruleClock())
|
||||
return kept
|
||||
})
|
||||
}
|
||||
cands, pl = s.planPaused(p, model, from, pausedIn)
|
||||
if len(cands) == 0 && len(pl.capped) > 0 && !p.CapStop || handedOnOf(r) != nil {
|
||||
// every account held at the usage cap the user set, or Codex's
|
||||
// own sign-in handed on (codexFallBack), and no fallback left:
|
||||
// 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 {
|
||||
cands, pl = s.planPaused(q, model, from, pausedIn)
|
||||
}
|
||||
}
|
||||
if handedOnOf(r) != nil {
|
||||
// Codex's own sign-in, asked as often as it is asked: only
|
||||
// the fallbacks are left (codexFallBack)
|
||||
|
||||
@@ -26,6 +26,8 @@ import (
|
||||
// answered 429 and nothing reaches the vendor; off, the last reading is
|
||||
// used as before; once usage reads again, A serves. With Stop at the caps
|
||||
// on, both at their caps, the fallback isn't sent the request either.
|
||||
// With no fallback, a routing group of the user's that has the plugin's
|
||||
// model first goes on to its next member, Stop at the caps off.
|
||||
func TestPluginCarefulPool(t *testing.T) {
|
||||
bun := testenv.Bun(t)
|
||||
fresh(t)
|
||||
@@ -226,4 +228,27 @@ func TestPluginCarefulPool(t *testing.T) {
|
||||
if code, body, seen := ask(t); code != 429 || len(seen) != 0 || len(fb.tried) != 0 || !strings.Contains(body, "usage cap reached") {
|
||||
t.Fatalf("stop on: %d %s (tried %v, fallback %v)", code, body, seen, fb.tried)
|
||||
}
|
||||
|
||||
// no fallback, but a routing group of the user's with the plugin's
|
||||
// model first and an API after it: asked for the plugin's own model,
|
||||
// both accounts at their caps, the API takes it; Stop at the caps
|
||||
// still ends there
|
||||
p, _ = provider.Find("factory")
|
||||
p.Fallback = nil
|
||||
if err := provider.Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{Name: "Pool", Members: []string{"factory/fake-1", "spare/m2"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fb.tried = nil
|
||||
if code, body, seen := ask(t); code != 429 || len(seen) != 0 || len(fb.tried) != 0 {
|
||||
t.Fatalf("group, stop on: %d %s (tried %v, group's API %v)", code, body, seen, fb.tried)
|
||||
}
|
||||
if err := provider.SetCapStop("factory", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, body, seen := ask(t); code != 200 || !strings.Contains(body, "from kf") || len(seen) != 0 {
|
||||
t.Fatalf("group, stop off: %d %s (tried %v)", code, body, seen)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1001,6 +1001,25 @@ func FallbackModels(p Provider) []Member {
|
||||
return out
|
||||
}
|
||||
|
||||
// GroupsAfter are the routing groups the user built that have id
|
||||
// ("provider/model") in them as a member and another member to go on to,
|
||||
// as "group/<id>", in the user's order; one magpie found (Auto), hidden
|
||||
// or switched off is none. A request for the model that its own accounts
|
||||
// can't take (every one held at its usage cap, or Codex's own sign-in out
|
||||
// of its allowance) goes on to these when nothing set as its fallback
|
||||
// takes it (adorable_piglet on Discord, v0.1.3354): the Codex app asks
|
||||
// Codex's own model, never the group built around it.
|
||||
func GroupsAfter(id string) []string {
|
||||
var out []string
|
||||
for _, gid := range MemberGroups()[id] {
|
||||
g, ms, ok := FallbackGroup(gid)
|
||||
if ok && !g.Auto && slices.ContainsFunc(ms, func(m Member) bool { return m.Provider.ID+"/"+m.Model != id }) {
|
||||
out = append(out, gid)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GroupFor is the group a model's id without a provider in it names, as
|
||||
// "group/<id>": the group of that id, else the group of that model however
|
||||
// a vendor spells it ("grok-4.7" is the group grok-4-7 or auto-grok-4-7).
|
||||
|
||||
Reference in New Issue
Block a user