Files
magpie/internal/gateway/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

119 lines
5.1 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
)
// sparkling_lemur_62868 on Discord: a team's OpenAI key with credits that
// other services spend from too, and magpie to stop at a share of them. A
// key that has spent its spend cap, as the Usage page prices magpie's calls
// on it, is passed over: the provider's next key serves the request, then
// its fallback; with neither, the request is answered 429 with which key is
// at which cap and how to go on. The key never reaches the upstream. A
// spend cap is no usage cap: Stop at the caps doesn't hold the fallbacks
// back from it.
func TestKeySpendCapPassesTheKeyOver(t *testing.T) {
fresh(t)
s := settings.Load()
s.ModelPrices = map[string]settings.ModelPrice{
"plan/m1": {Input: new(1.0), Output: new(1.0), CacheRead: new(0.0), CacheWrite: new(0.0)},
}
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var keys []string
serve := func(name string) *httptest.Server {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
keys = append(keys, name+" "+strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
}))
t.Cleanup(up.Close)
return up
}
planUp, spareUp := serve("plan"), serve("spare")
since := time.Now().Add(-time.Hour).UTC().Truncate(time.Second)
plan := provider.Provider{ID: "plan", Name: "Plan", Key: "sk-team", KeyName: "Team", Keys: []provider.KeyAccount{{Name: "Spare", Key: "sk-spare"}},
Chat: planUp.URL + "/v1", Models: []string{"m1"}, Routing: provider.Ordered,
KeySpendCaps: map[string]provider.SpendCap{provider.KeyID("sk-team"): {USD: 5, Period: provider.SpendTotal, Since: since}}}
if err := provider.Save(plan); err != nil {
t.Fatal(err)
}
// $6 spent on Team since its cap was set, $1 before it
usage.Append(usage.Record{Time: time.Now().Add(-30 * time.Minute), Agent: "codex", Provider: "plan", Model: "m1", ProviderKeyID: provider.KeyID("sk-team"), Input: 6e6, Status: 200})
usage.Append(usage.Record{Time: since.Add(-time.Hour), Agent: "codex", Provider: "plan", Model: "m1", ProviderKeyID: provider.KeyID("sk-spare"), Input: 1e6, Status: 200})
h := New().Handler()
post := func() (int, string, []string) {
t.Helper()
mu.Lock()
keys = nil
mu.Unlock()
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq)))
mu.Lock()
defer mu.Unlock()
return w.Code, w.Body.String(), keys
}
// Team, first, is at its cap: Spare serves
if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "plan sk-spare" {
t.Fatalf("Team at its cap: %d %s, upstream got %v", code, body, got)
}
// raised past what it spent, Team serves again
if err := provider.SetKeySpendCap("plan", "Team", &provider.SpendCap{USD: 50, Period: provider.SpendTotal}); err != nil {
t.Fatal(err)
}
if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "plan sk-team" {
t.Fatalf("Team under its raised cap: %d %s, upstream got %v", code, body, got)
}
// both at their caps, with no fallback: a 429 says which and why
if err := provider.SetKeySpendCap("plan", "Team", &provider.SpendCap{USD: 5, Period: provider.SpendTotal}); err != nil {
t.Fatal(err)
}
if err := provider.SetKeySpendCap("plan", "Spare", &provider.SpendCap{USD: 0.000001, Period: provider.SpendDay}); err != nil {
t.Fatal(err)
}
code, body, got := post()
var e struct {
Error struct{ Message, Type string }
}
json.Unmarshal([]byte(body), &e)
if code != 429 || len(got) != 0 || !strings.Contains(e.Error.Message, "spend cap reached") ||
!strings.Contains(e.Error.Message, "Team") || !strings.Contains(e.Error.Message, "$6.00 of the $5.00 spend cap") ||
!strings.Contains(e.Error.Message, "Spare") || !strings.Contains(e.Error.Message, "for today") || !strings.Contains(e.Error.Message, "spend-cap") {
t.Fatalf("both at their caps: %d %s, upstream got %v", code, body, got)
}
// with a fallback, it serves
p, _ := provider.Find("plan")
p.Fallback = []string{"spare/m2"}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "spare", Name: "Spare plan", Key: "sk-other", Chat: spareUp.URL + "/v1", Models: []string{"m2"}}); err != nil {
t.Fatal(err)
}
if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "spare sk-other" {
t.Fatalf("both at their caps, with a fallback: %d %s, upstream got %v", code, body, got)
}
// a spend cap is not a usage cap: Stop at the caps doesn't end there
if err := provider.SetCapStop("plan", true); err != nil {
t.Fatal(err)
}
if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "spare sk-other" {
t.Fatalf("both at their caps, Stop at the caps on: %d %s, upstream got %v", code, body, got)
}
}