Files
magpie/internal/provider/key_spend_test.go
T
yetone e41ef6288c providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted
credits that other docker services spend from too, and they want magpie
to stop at a share of it. Their workaround was two magpies behind a
gateway-key limit.

What changed
- provider: KeySpendCaps on a provider, keyed by the key's fingerprint
  (key_spend.go): USD over a local calendar day, a local calendar month,
  or in all since it was set. Since is kept while the cap stays one in
  all. SetKeySpendCap and ParseSpendCap refuse an amount outside
  0 < usd <= 1,000,000 and an unknown period, and leave the saved cap
  as it was. Subscriptions are refused, since an account has its own
  usage-window cap.
- usage: KeySpent(keyID, start) is what magpie's own calls on the key
  cost at the Usage page's prices. Turned-away calls and app-reported
  ones are left out. It reads usage.jsonl once per key and start, keeps
  the sum for 5 minutes, and Append counts each new call into it
  (spentNew). A read that a write races is read again.
- gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap
  holds an account. The next key serves, then the fallbacks. With none,
  the reply is 429 "spend cap reached: ..." naming each key, what it
  spent of which cap, and how to go on. Retry-After is when the soonest
  period renews; a cap in all gives none. A spend hold is not a usage
  cap: Stop at the caps and strictKeep don't end at it (capHeldOnly).
  The trace's barred row carries the cap, the spend and the period.
- GUI: a pill on each key's row in the provider editor, for example
  "$7.50 of $20.00 today". It opens the app's menu (No spend cap,
  Per day..., Per month..., In all...) and then takes the amount in
  place, as the lane-limit pill does. A key at its cap gets a line
  under its row: "At its spend cap · back in ...". Every string is in
  all five languages. The pill and the line are in keyspend.js, which
  app.js imports when it draws a key's row, so the core's script
  budget is not raised. /api/providers' keyList carries spend, and
  POST provider/keyspendcap sets it.
- CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]]
  lists each key's spend and sets or removes a cap.
- docs: providers-accounts.md and gateway-routing.md.

Caveats, also in the tooltips:
- What counts is magpie's priced usage, not OpenAI's bill.
- A model with no known price counts $0.
- Requests already under way when the cap is reached still finish, so
  a key can go a little past it.

Run on mote at the pre-rebase head (3e3196222 + this change):
- go test -count=1 -timeout 45m for internal/provider, usage, cli, gui
  and gateway: provider, usage and gateway ok. Three reds, none from
  this change:
  - cli TestEveryRouteHasACommandOrIsNamed: GET /api/context/reply,
    red on main, #5026.
  - gui TestMainWindowCorners/macOS_26_SDK: macOS 27, #3949.
  - gui TestCoreScriptBudget: from this change. Fixed by moving the
    pill into keyspend.js, then ok on a rerun.
- go vet: plain, GOOS=linux -tags nogui and GOOS=windows -tags nogui,
  all clean. gofmt -l is clean.
- GUI, both engines: key-spend-cap.test.cjs passed 20 of 20 before
  the keyspend.js move, and all of its tests passed again after it.
  It covers en, zh, zh-TW, ja and de at 900 and 400px, a refused
  amount, the set, change and remove posts, and checks for no native
  select, no border stripe and no sideways scroll.
- Also run in both engines: i18n-keys, old-webkit, lane-limit,
  account-cap, key-row-chips-fit, key-weight-fit, key-nourl,
  provider-many-keys, key-switch, key-plan and key-rest-date.
  - key-replace's webkit 420px is red at base 3e3196222 too
    (#4126; base failed 2 of 3 en runs, this change 3 of 3).
  - key-rest-date's webkit zh-TW, ja and de tests time out at
    --test-concurrency=4 with three other files beside it, at base
    too (base 5 reds, this change 7). Run alone at concurrency 2, it
    passes 10 of 10 at base and with this change (#4691).

After the rebase onto 9c51f7fdb, at the pushed head:
- go build ./... and go vet on the five packages: clean.
- go test of the spend tests, TestCoreScriptBudget and the gui
  package's word tests: ok.
- i18n-keys and key-spend-cap in both engines: 24 of 24.

Broken by hand, each red and then restored:
- spentNew taken out of Append: TestKeySpentCountsTheKeysCalls red
  ("after a new call key a spent 3, want 7").
- spendHeld never barring: TestKeySpendCapPassesTheKeyOver red (the
  capped key reached the upstream).
- capHeldOnly keeping spend holds: TestKeySpendCapPassesTheKeyOver red
  (Stop at the caps answered 429 instead of using the fallback).

Not tried:
- a real OpenAI key or real spend;
- the real app window;
- Windows and Linux test runs (vet only);
- the whole GUI suite: mote was running two other sessions' full GUI
  suites at load 250 to 400.
2026-11-03 15:30:44 +08:00

135 lines
5.1 KiB
Go

package provider
import (
"strings"
"testing"
"time"
)
// A key's spend cap (sparkling_lemur_62868 on Discord) is set by the key's
// id or name, kept by its fingerprint in lower case, and taken off with
// nil. A cap in all counts from when it was set, and keeps that start
// while it stays one in all, its amount changed; a cap a day or a month
// keeps none. A key the provider hasn't and a cap out of range are
// refused, and a key's value replaced keeps its cap.
func TestKeySpendCapSet(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Key: "sk-first", KeyName: "Team",
Keys: []KeyAccount{{Name: "Spare", Key: "sk-spare"}}}); err != nil {
t.Fatal(err)
}
first, spare := keyID("sk-first"), keyID("sk-spare")
capOf := func(ref string) (SpendCap, bool) {
t.Helper()
p, err := Find("relay")
if err != nil {
t.Fatal(err)
}
return p.KeySpendCap(ref)
}
if err := SetKeySpendCap("relay", "Team", &SpendCap{USD: 20, Period: SpendDay}); err != nil {
t.Fatal(err)
}
if c, ok := capOf(strings.ToUpper(first)); !ok || c.USD != 20 || c.Period != SpendDay || !c.Since.IsZero() {
t.Fatalf("Team's cap %+v %v", c, ok)
}
if _, ok := capOf(spare); ok {
t.Fatal("Spare got a cap it wasn't given")
}
before := time.Now().UTC().Truncate(time.Second)
if err := SetKeySpendCap("relay", spare, &SpendCap{USD: 100, Period: SpendTotal}); err != nil {
t.Fatal(err)
}
c, ok := capOf(spare)
if !ok || c.Period != SpendTotal || c.Since.Before(before) || c.Since.After(time.Now()) {
t.Fatalf("Spare's cap in all %+v %v", c, ok)
}
// set in all a while back, raised: it still counts from then
p, _ := Find("relay")
since := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
p.KeySpendCaps[spare] = SpendCap{USD: 100, Period: SpendTotal, Since: since}
if err := Save(*p); err != nil {
t.Fatal(err)
}
if err := SetKeySpendCap("relay", "Spare", &SpendCap{USD: 150, Period: SpendTotal}); err != nil {
t.Fatal(err)
}
if c, _ := capOf(spare); c.USD != 150 || !c.Since.Equal(since) {
t.Fatalf("raised in all, it counts from %v, not %v: %+v", c.Since, since, c)
}
// a month: no start of its own; in all again counts from now
if err := SetKeySpendCap("relay", spare, &SpendCap{USD: 150, Period: SpendMonth}); err != nil {
t.Fatal(err)
}
if c, _ := capOf(spare); c.Period != SpendMonth || !c.Since.IsZero() {
t.Fatalf("a month's cap %+v", c)
}
for _, bad := range []SpendCap{{USD: 0, Period: SpendDay}, {USD: -1, Period: SpendDay}, {USD: MaxSpendCap + 1, Period: SpendDay}, {USD: 5, Period: "week"}} {
if err := SetKeySpendCap("relay", spare, &bad); err == nil {
t.Fatalf("%+v was taken", bad)
}
}
if err := SetKeySpendCap("relay", "nobody", &SpendCap{USD: 1, Period: SpendDay}); err == nil {
t.Fatal("a key the provider hasn't got a cap")
}
// the value replaced, the cap goes with the key
if _, _, err := ReplaceKey("relay", first, "sk-first-2"); err != nil {
t.Fatal(err)
}
if c, ok := capOf(keyID("sk-first-2")); !ok || c.USD != 20 {
t.Fatalf("replaced, Team's cap %+v %v", c, ok)
}
if err := SetKeySpendCap("relay", "Team", nil); err != nil {
t.Fatal(err)
}
if _, ok := capOf(keyID("sk-first-2")); ok {
t.Fatal("the cap taken off is still there")
}
}
// A day's cap counts from local midnight to the next, a month's from the
// 1st to the next month's, and one in all from its Since, never renewing.
func TestSpendCapWindow(t *testing.T) {
loc := time.FixedZone("far", 13*3600)
now := time.Date(2026, 12, 31, 23, 30, 0, 0, loc)
s, r := SpendCap{USD: 1, Period: SpendDay}.Window(now)
if !s.Equal(time.Date(2026, 12, 31, 0, 0, 0, 0, loc)) || !r.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, loc)) {
t.Fatalf("day %v %v", s, r)
}
s, r = SpendCap{USD: 1, Period: SpendMonth}.Window(now)
if !s.Equal(time.Date(2026, 12, 1, 0, 0, 0, 0, loc)) || !r.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, loc)) {
t.Fatalf("month %v %v", s, r)
}
since := time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC)
s, r = SpendCap{USD: 1, Period: SpendTotal, Since: since}.Window(now)
if !s.Equal(since) || !r.IsZero() {
t.Fatalf("in all %v %v", s, r)
}
}
// The CLI's words for a cap: an amount, $ or not, a period by any of its
// names, a day when none; off for none; anything else refused.
func TestParseSpendCap(t *testing.T) {
for _, c := range []struct {
amount, period string
want *SpendCap
}{
{"20", "", &SpendCap{USD: 20, Period: SpendDay}},
{"$12.5", "monthly", &SpendCap{USD: 12.5, Period: SpendMonth}},
{"100", "total", &SpendCap{USD: 100, Period: SpendTotal}},
{"100", "all", &SpendCap{USD: 100, Period: SpendTotal}},
{"off", "", nil},
} {
got, err := ParseSpendCap(c.amount, c.period)
if err != nil || (got == nil) != (c.want == nil) || got != nil && *got != *c.want {
t.Fatalf("%q %q: %+v %v", c.amount, c.period, got, err)
}
}
for _, bad := range [][2]string{{"--help", ""}, {"twenty", ""}, {"0", ""}, {"-5", ""}, {"5", "week"}, {"NaN", ""}, {"2000000", ""}} {
if _, err := ParseSpendCap(bad[0], bad[1]); err == nil {
t.Fatalf("%q %q was taken", bad[0], bad[1])
}
}
}