Files
magpie/internal/gateway/plugin_cap_pool_test.go
T
yetone 08b02cf18c providers: a pool stops at its caps and reads usage again near them (plugins#349)
What was adopted on magpie-community/plugins#349 (1939869736luosi): one
place, in the GUI and the CLI, for a subscription's account pool, and an
opt-in conservative mode.

- Stop at the caps (Provider.CapStop, off by default): once every account
  in use is held at its cap, the request is answered 429 rather than going
  on to the provider's fallbacks (plan returns restLast). Off, as before.
- Check usage again near a cap (Provider.CapCareful, off by default,
  internal/gateway/cap_careful.go): before planning, a capped account's
  usage is read again when its reading is over 15s old within 5 points of
  a cap, or over 5m old at all; the request waits at most 10s, and a
  failed account is asked again at most every 15s. An account whose usage
  was never read, whose last read failed, or whose reading is still that
  old is then held as one at its cap is (capHold "unread", traced as
  Weighed.Unread, named in the 429 with "--careful off"). Generic: it
  goes by provider.UsageRead/ReadUsageNow, so every subscription that
  reports usage windows (Codex, Claude, plugins) gets it.
- provider: usedCache records each account's read state; a failed read
  keeps the last good reading's time. ReadUsageNow no longer reports
  false when the read had already finished on the first ask.
- GUI: under the provider's account list, once an account has a cap (or
  either is on), two ticks for the above, and a note naming the accounts
  in use with no cap ("used to 100% of each window"). Accounts, order and
  caps stay where they were in that list. zh, zh-TW, ja, de added.
  app.js 1,309,658 within its 1,310,460 budget, unraised: addRow and a
  per-row forgetOf replace 3 add-button and 5 Remove-button builds.
- CLI: magpie provider pool <id> [--accounts a,b,…] [--cap percent|off]
  [--stop on|off] [--careful on|off] shows and sets the whole pool.
- docs: gateway-routing.md and providers-accounts.md.

Run (mote, before the rebase at 8bade6c5e + this change):
- go test -tags nogui -timeout 45m ./...: exit 0, 76 packages ok, no
  FAIL (log grepped).
- GOOS=linux and GOOS=windows go vet of cli, gateway, provider, gui: ok.
- pool-ends.test.cjs: 32/32, Chromium and WebKit, en zh ja de, 1100 and
  420 wide.
- The 81 GUI files whose fixtures have accounts or caps, plus i18n*,
  6 at a time at load ~130: 76 pass. i18n-keys is red on the base too
  (#3897). account-mask (#3951), account-alias (#2984),
  signin-closes-sheet and signin-again timed out under load and pass
  run again, as on the base; signin-again filed as #3960.
- Real plugin host: TestPluginCarefulPool runs the fake plugin under Bun
  as Factory with two accounts capped at 90%: a failing usage call gives
  429 with nothing sent upstream while careful is on, the last reading
  is used with it off, a good read sends to A again, and with both at
  their caps the fallback serves unless Stop is on.
- CLI binary in a sandbox HOME on mote: unknown provider, a bad --stop
  value and no id each refuse and change nothing.
At the rebased head (0a7633136 + this): gofmt -l
clean, go build ./..., the new Go tests and the budget tests, and
pool-ends.test.cjs 32/32.

Broken by hand, each seen red, then restored:
- the CapStop line in plan: TestCapStopSkipsTheFallbacks and
  TestPluginCarefulPool red;
- the careful hold in capHeld: the three careful tests and
  TestPluginCarefulPool red;
- careful always on: TestCarefulOffByDefault red;
- readCareful not called: the failed, never-read, stale and re-read
  subtests red;
- a failed read not keeping the good time, or not counted as failed,
  and ReadUsageNow's early return forced false: TestUsageReadAndReadAgain
  red;
- the ticks' onchange emptied: pool-ends.test.cjs 16 of 16 red.

Not tried: a real Factory or any real account (fake plugin only); the
whole GUI suite (932 files, ~5h at this load), only the 81 files that
reach the account list; Linux WebKitGTK and Windows; the 15s/5m/5-point
figures against a real vendor's usage endpoint latency.
2026-10-28 09:29:44 +08:00

230 lines
7.3 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.
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) (int, string, []string) {
t.Helper()
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":"factory/fake-1","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)
}
}