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/main208b89422: 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 onto6b92824ffbefore the push (26 files of usage, sessions and provider window-hold changes, none of the files here); the runs above were at208b89422, 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.
266 lines
8.8 KiB
Go
266 lines
8.8 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/plugin"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/testenv"
|
|
)
|
|
|
|
// plugins#349 through a real plugin host: the fake plugin as Factory, two
|
|
// accounts in order, each capped at 90%, their usage read from the
|
|
// plugin's usage call as it says it now (FAKE_WINDOWS). With Check usage
|
|
// near a cap on, a usage call that fails holds both accounts: the agent is
|
|
// 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, for the
|
|
// model asked bare; named "factory/fake-1" it is the cap's 429.
|
|
func TestPluginCarefulPool(t *testing.T) {
|
|
bun := testenv.Bun(t)
|
|
fresh(t)
|
|
t.Setenv("MAGPIE_BUN", bun)
|
|
t.Setenv("FAKE_ID", "factory")
|
|
windows := filepath.Join(t.TempDir(), "windows.json")
|
|
t.Setenv("FAKE_WINDOWS", windows)
|
|
t.Cleanup(plugin.Settle)
|
|
old := allowances
|
|
allowances = provider.Allowances
|
|
t.Cleanup(func() { allowances = old })
|
|
carefulTried.Lock()
|
|
carefulTried.at = nil
|
|
carefulTried.Unlock()
|
|
|
|
var mu sync.Mutex
|
|
var tried []string
|
|
up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
io.ReadAll(r.Body)
|
|
who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer fresh-r-")
|
|
mu.Lock()
|
|
tried = append(tried, who)
|
|
mu.Unlock()
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"from `+who+`"},"finish_reason":"stop"}]}`+"\n\n")
|
|
fmt.Fprint(w, "data: [DONE]\n\n")
|
|
}))
|
|
defer up.Close()
|
|
|
|
dir := filepath.Dir(provider.Path())
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mig, _ := json.Marshal(map[string]any{"factory": map[string]any{"state": provider.MovePlugin}})
|
|
if err := os.WriteFile(filepath.Join(dir, "migrations.json"), mig, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
resets := time.Now().Add(2 * time.Hour)
|
|
five := func(used float64) []map[string]any {
|
|
return []map[string]any{{"name": "5 hours", "used": used, "span": 18000, "resetsAt": resets.UTC().Format(time.RFC3339)}}
|
|
}
|
|
write := func(t *testing.T, raw []byte) {
|
|
t.Helper()
|
|
if err := os.WriteFile(windows+".tmp", raw, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Rename(windows+".tmp", windows); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
// says writes what the plugin says of each account, and waits for
|
|
// routing to have read it: a's share, or with broken, a failed read
|
|
says := func(t *testing.T, a, b float64, broken bool) {
|
|
t.Helper()
|
|
if broken {
|
|
write(t, []byte("{not json"))
|
|
} else {
|
|
raw, _ := json.Marshal(map[string]any{"a@fake": five(a), "b@fake": five(b)})
|
|
write(t, raw)
|
|
}
|
|
for _, u := range []string{"a@fake", "b@fake"} {
|
|
provider.StaleAllowance("plugin:factory", u)
|
|
}
|
|
deadline := time.Now().Add(time.Minute)
|
|
for {
|
|
got := provider.Allowances("plugin:factory")
|
|
_, failed, ok := provider.UsageRead("plugin:factory", "a@fake")
|
|
if broken && ok && failed || !broken && ok && !failed && len(got["a@fake"]) > 0 && got["a@fake"][0].Used == a && len(got["b@fake"]) > 0 && got["b@fake"][0].Used == b {
|
|
return
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("routing never read the windows (broken %v): %+v", broken, got)
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
}
|
|
raw, _ := json.Marshal(map[string]any{"a@fake": five(40), "b@fake": five(10)})
|
|
write(t, raw)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
|
|
if _, err := plugin.Add(ctx, abs); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := plugin.Providers(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, team := range []string{"a", "b"} {
|
|
st, err := provider.StartPluginSignIn("factory", 1, map[string]string{"where": "work", "team": team})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if _, err := plugin.Providers(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if ls := provider.Logins("factory"); len(ls) != 2 {
|
|
t.Fatalf("accounts %+v", ls)
|
|
}
|
|
if err := provider.SwitchLogin("factory", "a@fake"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := provider.SetLoginOn("factory", "b@fake", true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := provider.SetRouting("factory", provider.Ordered); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, u := range []string{"a@fake", "b@fake"} {
|
|
if err := provider.SetAccountCap("factory", u, 90); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if p, _ := provider.Find("factory"); p.CapCareful || p.CapStop {
|
|
t.Fatalf("on by default: careful %v stop %v", p.CapCareful, p.CapStop)
|
|
}
|
|
|
|
s := New()
|
|
ask := func(t *testing.T, model ...string) (int, string, []string) {
|
|
t.Helper()
|
|
m := "factory/fake-1"
|
|
if len(model) > 0 {
|
|
m = model[0]
|
|
}
|
|
mu.Lock()
|
|
tried = nil
|
|
mu.Unlock()
|
|
sticks.Lock()
|
|
sticks.m = map[string]stick{}
|
|
sticks.Unlock()
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+m+`","stream":true,"messages":[{"role":"user","content":"hello"}]}`))
|
|
s.Handler().ServeHTTP(rec, req)
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
return rec.Code, rec.Body.String(), append([]string(nil), tried...)
|
|
}
|
|
served := func(t *testing.T, want string) {
|
|
t.Helper()
|
|
code, body, seen := ask(t)
|
|
if code != 200 || !strings.Contains(body, "from "+want) || strings.Join(seen, " ") != want {
|
|
t.Fatalf("%d %s (tried %v), want %s alone", code, body, seen, want)
|
|
}
|
|
}
|
|
careful := func(t *testing.T, on bool) {
|
|
t.Helper()
|
|
if err := provider.SetCapCareful("factory", on); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
carefulTried.Lock()
|
|
carefulTried.at = nil
|
|
carefulTried.Unlock()
|
|
}
|
|
|
|
says(t, 40, 10, false)
|
|
served(t, "a")
|
|
|
|
// usage can't be read: careful holds both, nothing reaches Factory
|
|
says(t, 0, 0, true)
|
|
careful(t, true)
|
|
code, body, seen := ask(t)
|
|
if code != 429 || len(seen) != 0 {
|
|
t.Fatalf("careful, unread: %d %s (tried %v)", code, body, seen)
|
|
}
|
|
for _, want := range []string{"rate_limit", "couldn't be read", "a@fake", "b@fake", "--careful off"} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("no %q in %s", want, body)
|
|
}
|
|
}
|
|
// off: the last reading (A at 40%) is used, as before
|
|
careful(t, false)
|
|
served(t, "a")
|
|
|
|
// read again: careful sends to A
|
|
careful(t, true)
|
|
raw, _ = json.Marshal(map[string]any{"a@fake": five(40), "b@fake": five(10)})
|
|
write(t, raw)
|
|
served(t, "a")
|
|
|
|
// both at their caps with a fallback: it takes the request, unless
|
|
// Stop at the caps is on
|
|
careful(t, false)
|
|
fb := &keyed{}
|
|
serveOn(t, "spare", "kf", []string{"m2"}, fb)
|
|
p, _ := provider.Find("factory")
|
|
p.Fallback = []string{"spare/m2"}
|
|
if err := provider.Save(*p); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
says(t, 95, 92, false)
|
|
if code, body, seen := ask(t); code != 200 || !strings.Contains(body, "from kf") || len(seen) != 0 {
|
|
t.Fatalf("stop off: %d %s (tried %v)", code, body, seen)
|
|
}
|
|
if err := provider.SetCapStop("factory", true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
fb.tried = nil
|
|
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, "fake-1"); code != 200 || !strings.Contains(body, "from kf") || len(seen) != 0 {
|
|
t.Fatalf("group, stop off: %d %s (tried %v)", code, body, seen)
|
|
}
|
|
// named with its provider, the plugin's model is the provider's
|
|
// alone: the cap's 429, the group not asked (Anotiaww on X)
|
|
fb.tried = nil
|
|
if code, body, seen := ask(t); code != 429 || len(seen) != 0 || len(fb.tried) != 0 || !strings.Contains(body, "usage cap reached") {
|
|
t.Fatalf("named, group, stop off: %d %s (tried %v, group's API %v)", code, body, seen, fb.tried)
|
|
}
|
|
}
|