Files
magpie/internal/provider/sub2api_usage_test.go
T
forever b0a96cbbd7 gateway, provider, gui: a Sub2API key given 5h/1d/7d limits is weighed and rested by its own windows, like an account (#1004)
* gateway: a Sub2API key out of its 5h/1d/7d limit ("…限额已用完") rests as out of quota, not a 1-minute rate limit

Sub2API refuses a key that has spent the 5-hour, day or 7-day limit its
owner gave it with 429 "api key 7天限额已用完" (or 日限额, 5小时限额),
typed rate_limit_exceeded. It matched rateWords and not plannedWords
("限额" is not "额度"), so failure() said rate: the key rested a minute,
was tried again, refused again, and sank, for the days its 7-day window
had left. plannedWords now has 限额已用完, so it is failQuota.

The relay's other refusals keep their classes, fixed by the test: the
pool out of accounts (v0.1.149's 503 "No available accounts": other;
later versions' 429 "All available accounts are currently
rate-limited": rate), its upstream's rate limit (rate), the key's own
total quota API_KEY_QUOTA_EXHAUSTED (quota) and the wallet's 403
INSUFFICIENT_BALANCE (credit).

Verified: TestSub2APIKeyLimitIsQuota, with Sub2API v0.1.149's message
bodies. Without the change it fails: "429 {…api key 7天限额已用完…}:
rate, want quota", and the same for 日限额 and 5小时限额.

* provider: a Sub2API key's /v1/usage shows its 5 hours / 1 day / 7 days windows instead of nothing at "remaining"

A Sub2API key its owner gave a 5-hour, day or 7-day spending limit
answers /v1/usage in quota_limited mode with rate_limits — each
window's limit, used and reset_at in dollars — and, without a total
quota of its own, no "remaining". With the Balance URL set to it, the
key's card said `nothing at "remaining" in the reply`.

readSub2APIKeyLimits reads rate_limits into the windows the cards
already name 5 hours, 1 day and 7 days, in USD. A window not started
(used 0, no reset_at) is taken to renew a span from now; a window with
a limit of 0 is none. The card shows them, beside a balance field the
user wrote; with none, Check balance and `magpie provider show` give
what the fullest window has left. A wallet key's reply is unchanged.

KeyAllowance gives routing the same windows, per provider and key: read
behind the request, never waited for, at most once a minute (once for
any number of asks at a time); a failed read keeps the last; after a
restart it is seeded from the card's last reading in quotas.json;
StaleKeyAllowance has it read again at the next ask. ForgetBalances (a
key or Balance URL changed) has every key read again, a read begun
before dropped, the last reading standing until then. Only keys whose
Balance URL is a Sub2API /v1/usage are asked: any other key, and every
account, costs nothing here.

Verified with real bytes of a limited key's reply, its key removed
(testdata/sub2api_usage_key_limits*.json): TestReadSub2APIKeyLimits,
TestSub2APIKeyLimitsOnItsCard, TestKeyAllowance*. Each fails without
its part, e.g. the card without the windows: `Error:nothing at
"remaining" in the reply`; KeyAllowance waiting for the read: "waited
30.0s"; asking every time: "asked 11 times"; a failed read asked again
at once: "asked 22 times after failing"; not seeded: "seeded = [],
false"; any key asked: "asked /api/usage/token"; ForgetBalances
dropping what was read: "after ForgetBalances, and a read begun before
it: []"; leaving a read under way loading: "the key's windows were
never read"; a stale-generation read landing: it replaced 95%; a limit
of 0 taken: "a day's limit of 0 = [{… Used:100 …}]"; Balance from the
first window only: "$300.00" for $80 left.

* gateway, gui: keys whose windows magpie reads are weighed and rested by them, like accounts

Smart, least-used and pace routing weighed only subscriptions by their
windows: weighRouted skipped every key (c.p.Account == nil), so a
Sub2API key beside Codex accounts in a group went by its place in the
order, and, refused for its 7-day limit, rested a quarter of an hour at
a time while the window had days to run.

A key whose own windows magpie reads (KeyAllowance: a Sub2API key given
a 5h/1d/7d limit, its Balance URL /v1/usage) is now weighed as an
account is: fine, low (90%) or spent (98%), the one renewing soonest
first, in a provider and in a group alike, and its trace row carries
them. Out of quota it rests till the window it filled renews, by
candidate.full; when its windows as last read aren't full it rests
quotaRest, and either way they are read again (staleKeyAllowance).
Every other failure of a key backs off as before, never to the window:
the relay out of accounts for everyone (503/429) says nothing of the
key's own spend. capHeld and pooled stay accounts' only. Keys magpie
reads no windows of are ordered exactly as before.

The Routing page tells such a key as it does an account: its row's bar,
used share and renewal, why it went first by its allowance, "Every key
and account here is at 90% or more", and the Smart header. A key not
read yet beside one read is told as weighed with it, not "keys go in
their order" or by its tokens. New strings in en, zh, ja and de.

Other users of the relay draining its accounts don't show in a key's
windows, which count only its spend: they show as the pool's 503/429,
which back off and fall over to the next key, account or fallback.

Verified: TestKeysWeighedByTheirWindows, TestGroupWeighsKeyWindows,
TestKeyOutOfItsWindowRestsUntilReset, TestKeyPoolErrorDoesNotRestForWindow;
and routing-key-windows.test.cjs in Chromium and WebKit (en/zh/ja/de).
Without the change they fail: "smart: kw#a kw#b kw#c"; "the key renewing
first: codex sub2api"; "full: rests 14m59.99s by quota"; "read again:
[]"; backing off to the window: "pool empty: rests 71h59m59.99s by
window (other)"; and on the page "relay-a goes first: keys go in their
order, those that suit the request first." where all are at 90% or
more, or a key not read yet beside one read.

* gateway, provider: a Sub2API key out of its limit is back once its windows read short of full, not only when the window renews

A key refused for its 5h/1d/7d limit rests till the window it filled
renews: days, for the week. Its windows are read again behind the next
requests (a minute apart) and by its card, but nothing lifted the rest
when they came back short of full, so the owner raising the key's limit
in the relay's panel, or resetting its usage, left the key out till the
week turned, though the relay would take it at once. Accounts have this
already: a Codex reset spent tells OnRenewed, and the gateway lifts the
account's rests (renewed).

A key's reading, routing's or its card's, now tells OnRenewed the same
way, as agent "" and the key's KeyAllowanceID, when a window it was full
in (Allowance.Full at SpentShareOf its routing, as candidate.full counts
it) is full no more, or full till sooner. Its first reading, a failed
read, or one that finds it fuller tells nothing. The gateway notes the
key's KeyAllowanceID on its rest out of quota only, so renewed lifts
that rest and no other: the relay out of accounts for everyone (503)
still backs off, and another key still out of its week stays out.

Where nothing weighs the key by its windows, nothing read them again
either: an ordered group weighs each member's keys alone, so a member
with one key, like a provider with one key, never asks for them. After
the one read its 429 starts, the key sat out its week on that reading.
restingOf, which plans a resting key behind the rest, now asks for the
windows of a key resting out of them (agent "" and a user on its rest),
so the next request planned past a minute reads them, behind it, and a
reading short of full brings the key back there too. No card is read
for it, and a key resting for any other reason asks nothing.

Verified: TestKeyAllowanceRenewed (provider) and
TestKeyBackOnceItsWindowIsNotFull (gateway, end to end through the key
cards' reads and restAfter), each failing with a piece of the change
undone: never telling, "its week's limit raised to $1,000: told []" and
"a, its limit raised: still rests by window till …"; telling on any
change, "its first reading, out of its week: told [/sub2api#…]"; a
failed read telling, "a read that failed: told [… …]"; the card not
telling, "its usage reset, read on its card: told [/sub2api#…]"; the
rest not noted, "a, its limit raised: still rests by window"; every
rest of a key noted, "c, the relay out of accounts: …, false"; renewed
not matching the key, "b, still out of its week: …, false". And
TestRestingKeyReadAgainInAnOrderedGroup (gateway: an ordered group, its
first member one key on a fake /v1/usage, no card read after the 429),
failing without restingOf's ask: "its limit raised: still rests by
window till …, its windows read 1 times".

Tried on a real Sub2API v0.1.149 relay, in a sandbox HOME, its key's 7d
limit lowered under its spend for the test and then restored, with
magpie serve on a group ordered: the key, then a local stand-in. The
key answered 429 "api key 7天限额已用完"; it rested by window till its
7d reset, 2026-10-13 00:00 +08:00, and the stand-in served. Planned
again a minute later, still over, it still rested. With the limit back
at $800, the next request was planned with it resting, the stand-in
serving, and read its windows; the one after went to the key, 200.
2026-10-06 18:57:47 +08:00

534 lines
17 KiB
Go

package provider
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/agentenv"
)
// sub2apiUsage is a sub2api key's /v1/usage as sub2api v0.1.149 answered
// it, the key given a $300 day and an $800 week in its panel: before its
// next request (not started) and after one.
func sub2apiUsage(t *testing.T, started bool) []byte {
t.Helper()
name := "testdata/sub2api_usage_key_limits_not_started.json"
if started {
name = "testdata/sub2api_usage_key_limits.json"
}
b, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
return b
}
// weekUsed is the started reply with $used of the week spent, its day and
// week resetting a day and three days from now, as a test run on any day
// sees them.
func weekUsed(t *testing.T, used string, week time.Time) []byte {
t.Helper()
b := sub2apiUsage(t, true)
b = bytes.Replace(b, []byte(`"used":0.0000958,"window":"7d"`), []byte(`"used":`+used+`,"window":"7d"`), 1)
b = bytes.Replace(b, []byte("2026-10-07T00:00:00+08:00"), []byte(time.Now().Add(24*time.Hour).Format(time.RFC3339)), 1)
return bytes.Replace(b, []byte("2026-10-13T00:00:00+08:00"), []byte(week.Format(time.RFC3339)), 1)
}
// A key given limits answers with its windows' spend in dollars; a
// window not started (or run out since) says used 0 and no reset_at.
func TestReadSub2APIKeyLimits(t *testing.T) {
ws, ok := readSub2APIKeyLimits(sub2apiUsage(t, true))
if !ok || len(ws) != 2 {
t.Fatalf("windows = %+v, %v", ws, ok)
}
day, week := ws[0], ws[1]
reset := func(s string) time.Time {
v, err := time.Parse(time.RFC3339, s)
if err != nil {
t.Fatal(err)
}
return v
}
if day.Name != "1 day" || day.Span != 24*time.Hour || day.Limit != 300 || day.Unit != "USD" ||
day.ResetsAt == nil || !day.ResetsAt.Equal(reset("2026-10-07T00:00:00+08:00")) ||
day.Amount != 0.0000958 || day.Used <= 0 || day.Used > 0.0001 {
t.Fatalf("day = %+v", day)
}
if week.Name != "7 days" || week.Span != 7*24*time.Hour || week.Limit != 800 ||
week.ResetsAt == nil || !week.ResetsAt.Equal(reset("2026-10-13T00:00:00+08:00")) {
t.Fatalf("week = %+v", week)
}
ws, ok = readSub2APIKeyLimits(sub2apiUsage(t, false))
if !ok || len(ws) != 2 || ws[0].ResetsAt != nil || ws[1].ResetsAt != nil || ws[1].Used != 0 || ws[1].Span != 7*24*time.Hour {
t.Fatalf("not started = %+v, %v", ws, ok)
}
// $720 of the week's $800 is 90%, over it no more than 100
b := bytes.Replace(sub2apiUsage(t, true), []byte(`"used":0.0000958,"window":"7d"`), []byte(`"used":720,"window":"7d"`), 1)
if ws, _ = readSub2APIKeyLimits(b); len(ws) != 2 || ws[1].Used != 90 || ws[1].Amount != 720 {
t.Fatalf("$720 of $800 = %+v", ws)
}
b = bytes.Replace(sub2apiUsage(t, true), []byte(`"used":0.0000958,"window":"7d"`), []byte(`"used":812.5,"window":"7d"`), 1)
if ws, _ = readSub2APIKeyLimits(b); len(ws) != 2 || ws[1].Used != 100 {
t.Fatalf("$812.50 of $800 = %+v", ws)
}
// a window without a limit is none
b = bytes.Replace(sub2apiUsage(t, true), []byte(`"limit":300`), []byte(`"limit":0`), 1)
if ws, _ = readSub2APIKeyLimits(b); len(ws) != 1 || ws[0].Name != "7 days" {
t.Fatalf("a day's limit of 0 = %+v", ws)
}
// a key on the wallet has none
if ws, ok := readSub2APIKeyLimits([]byte(`{"mode":"unrestricted","isValid":true,"planName":"钱包余额","remaining":7.25,"unit":"USD","balance":7.25}`)); ok || ws != nil {
t.Fatalf("wallet = %+v, %v", ws, ok)
}
}
// keyLimitsHome gives a test a magpie of its own, without any key or
// window another test read.
func keyLimitsHome(t *testing.T) {
t.Helper()
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("PATH", h)
for _, v := range agentenv.Vars {
t.Setenv(v, "")
}
restart := func() {
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
ForgetBalances()
keyAllowances.Lock()
keyAllowances.m = nil
keyAllowances.Unlock()
}
restart()
t.Cleanup(func() {
// the reads behind the test, and the sign-ins they look up, end
// before the next test's isolate changes what they call
deadline := time.Now().Add(10 * time.Second)
for busy := true; busy && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
busy = false
keyAllowances.Lock()
for _, e := range keyAllowances.m {
busy = busy || e.loading
}
keyAllowances.Unlock()
devinStatus.Lock()
busy = busy || devinStatus.refreshing
devinStatus.Unlock()
}
restart()
})
}
// sub2apiServer answers /v1/usage for sk-limited with body(), counting
// the asks; any other key is refused as sub2api refuses it.
func sub2apiServer(t *testing.T, body func() ([]byte, int)) (*httptest.Server, *atomic.Int32) {
t.Helper()
var asked atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/usage" {
t.Errorf("asked %s", r.URL.Path)
}
if r.Header.Get("Authorization") != "Bearer sk-limited" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":{"type":"authentication_error","message":"Invalid API key"}}`))
return
}
asked.Add(1)
b, status := body()
w.WriteHeader(status)
w.Write(b)
}))
t.Cleanup(srv.Close)
return srv, &asked
}
func sub2apiKey(srv *httptest.Server) Provider {
return Provider{ID: "sub2api", Name: "Sub2API", Chat: srv.URL + "/v1", Responses: srv.URL + "/v1",
Key: "sk-limited", BalanceURL: srv.URL + "/v1/usage"}
}
// A key its owner gave limits has no "remaining" of its own: its card
// shows the windows it has spent of, not "nothing at remaining"; a field
// the user wrote is still read, beside them.
func TestSub2APIKeyLimitsOnItsCard(t *testing.T) {
keyLimitsHome(t)
var body atomic.Pointer[[]byte]
b := sub2apiUsage(t, true)
body.Store(&b)
srv, _ := sub2apiServer(t, func() ([]byte, int) { return *body.Load(), 200 })
p := sub2apiKey(srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
card := func() SubscriptionQuota {
ForgetBalances()
for _, q := range KeyBalances(context.Background()) {
if q.Provider == "sub2api" {
return q
}
}
t.Fatal("no card for the key")
return SubscriptionQuota{}
}
q := card()
if q.Error != "" || q.Balance != "" || len(q.Windows) != 2 || q.Windows[0].Name != "1 day" || q.Windows[1].Name != "7 days" || q.ReadAt == nil {
t.Fatalf("card = %+v", q)
}
// checked from its editor, or magpie provider show: what it can
// spend now, the least its windows have left
if amount, ok, err := Balance(context.Background(), p); err != nil || !ok || amount != "$300.00" {
t.Fatalf("Balance = %q %v %v", amount, ok, err)
}
week := weekUsed(t, "720", time.Now().Add(72*time.Hour))
body.Store(&week)
if amount, _, err := Balance(context.Background(), p); err != nil || amount != "$80.00" {
t.Fatalf("Balance with $720 of the week's $800 spent = %q %v", amount, err)
}
body.Store(&b)
p.BalancePath = "usage.total.actual_cost"
if err := Save(p); err != nil {
t.Fatal(err)
}
if q = card(); q.Error != "" || q.Balance != "192.33" || len(q.Windows) != 2 {
t.Fatalf("with a field: %+v", q)
}
// a field the user wrote that isn't there still says so
p.BalancePath = "remaining"
if err := Save(p); err != nil {
t.Fatal(err)
}
if q = card(); q.Error == "" || len(q.Windows) != 0 {
t.Fatalf("a field not there: %+v", q)
}
}
// waitAllowance waits for p's key's windows to be read.
func waitAllowance(t *testing.T, p Provider, until func(Allowance) bool) Allowance {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for {
if a, ok := KeyAllowance(p); ok && until(a) {
return a
}
if time.Now().After(deadline) {
t.Fatal("the key's windows were never read")
}
time.Sleep(5 * time.Millisecond)
}
}
// Routing asks for a key's windows on every request: it must never wait
// for sub2api, nor ask it more than once at a time.
func TestKeyAllowanceNeverWaits(t *testing.T) {
keyLimitsHome(t)
week := time.Now().Add(72 * time.Hour).Truncate(time.Second)
release := make(chan struct{})
srv, asked := sub2apiServer(t, func() ([]byte, int) {
<-release
return weekUsed(t, "720", week), 200
})
p := sub2apiKey(srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
start := time.Now()
if a, ok := KeyAllowance(p); ok || a != nil {
t.Errorf("known before it was read: %+v", a)
}
if d := time.Since(start); d > time.Second {
t.Errorf("waited %v", d)
}
}()
}
wg.Wait()
close(release)
a := waitAllowance(t, p, func(Allowance) bool { return true })
if used, _ := a.For("gpt-6-astra", time.Now()); used != 90 {
t.Fatalf("used = %v of %+v", used, a)
}
if n := asked.Load(); n != 1 {
t.Fatalf("asked %d times", n)
}
// read within the minute: not asked again
KeyAllowance(p)
time.Sleep(20 * time.Millisecond)
if n := asked.Load(); n != 1 {
t.Fatalf("asked %d times within the minute", n)
}
}
// A read that fails says nothing of the key: what was known stands, and
// is asked for again a minute on rather than on every request.
func TestKeyAllowanceFailedReadKeepsLast(t *testing.T) {
keyLimitsHome(t)
week := time.Now().Add(72 * time.Hour).Truncate(time.Second)
var down atomic.Bool
srv, asked := sub2apiServer(t, func() ([]byte, int) {
if down.Load() {
return []byte(`{"error":{"type":"api_error","message":"internal error"}}`), 502
}
return weekUsed(t, "720", week), 200
})
p := sub2apiKey(srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
waitAllowance(t, p, func(Allowance) bool { return true })
down.Store(true)
StaleKeyAllowance(p)
KeyAllowance(p) // asks again, and is told nothing
deadline := time.Now().Add(5 * time.Second)
for asked.Load() < 2 {
if time.Now().After(deadline) {
t.Fatal("not asked again once stale")
}
time.Sleep(5 * time.Millisecond)
}
for range 20 {
a, ok := KeyAllowance(p)
if used, _ := a.For("gpt-6-astra", time.Now()); !ok || used != 90 {
t.Fatalf("after a failed read: %+v, %v", a, ok)
}
time.Sleep(5 * time.Millisecond)
}
if n := asked.Load(); n != 2 {
t.Fatalf("asked %d times after failing", n)
}
}
// A read under way as the keys are forgotten is dropped, and the key is
// read again at its next ask — not left waiting on the read dropped.
func TestKeyAllowanceForgottenMidRead(t *testing.T) {
keyLimitsHome(t)
release := make(chan struct{})
var first atomic.Bool
srv, asked := sub2apiServer(t, func() ([]byte, int) {
if first.CompareAndSwap(false, true) {
<-release
}
return sub2apiUsage(t, true), 200
})
var once sync.Once
t.Cleanup(func() { once.Do(func() { close(release) }) })
p := sub2apiKey(srv)
KeyAllowance(p)
for asked.Load() < 1 {
time.Sleep(5 * time.Millisecond)
}
ForgetBalances()
once.Do(func() { close(release) })
waitAllowance(t, p, func(a Allowance) bool { return len(a) == 2 })
if n := asked.Load(); n != 2 {
t.Fatalf("asked %d times", n)
}
}
// Until the key is first read (magpie just started), its windows are the
// ones its card last showed, kept on disk; a window whose reset passed
// since is empty again.
func TestKeyAllowanceSeededFromItsCard(t *testing.T) {
keyLimitsHome(t)
week := time.Now().Add(72 * time.Hour).Truncate(time.Second)
var down atomic.Bool
srv, _ := sub2apiServer(t, func() ([]byte, int) {
if down.Load() {
return nil, 503
}
return weekUsed(t, "720", week), 200
})
p := sub2apiKey(srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
KeyBalances(context.Background())
down.Store(true)
// as after a restart: nothing in memory
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
keyAllowances.Lock()
keyAllowances.m = nil
keyAllowances.Unlock()
a, ok := KeyAllowance(p)
now := time.Now()
if used, _ := a.For("gpt-6-astra", now); !ok || used != 90 {
t.Fatalf("seeded = %+v, %v", a, ok)
}
// the week renews on the reset sub2api told, not a week from now
if r := a.Renewal("gpt-6-astra", now); len(r) != 2 || !r[0].Equal(week) {
t.Fatalf("renewal = %v", r)
}
}
// Only a key whose Balance URL is sub2api's /v1/usage is asked: any other
// key, or an account, costs nothing.
func TestKeyAllowanceOnlyForSub2APIKeys(t *testing.T) {
keyLimitsHome(t)
srv, asked := sub2apiServer(t, func() ([]byte, int) { return sub2apiUsage(t, true), 200 })
for _, p := range []Provider{
{ID: "relay", Chat: srv.URL + "/v1", Key: "sk-limited", BalanceURL: srv.URL + "/api/usage/token"},
{ID: "plain", Chat: srv.URL + "/v1", Key: "sk-limited"},
{ID: "sub2api", Chat: srv.URL + "/v1", BalanceURL: srv.URL + "/v1/usage"},
{ID: "codex", Chat: srv.URL + "/v1", Key: "sk-limited", BalanceURL: srv.URL + "/v1/usage", Account: &Account{Agent: "codex", User: "a@example.com"}},
} {
if a, ok := KeyAllowance(p); ok || a != nil {
t.Errorf("%s: %+v", p.ID, a)
}
}
time.Sleep(20 * time.Millisecond)
if n := asked.Load(); n != 0 {
t.Fatalf("asked %d times", n)
}
}
// Each key of a provider has windows of its own; a key or Balance URL
// changed (ForgetBalances) has them all read again.
func TestKeyAllowancePerKeyAndForgotten(t *testing.T) {
keyLimitsHome(t)
srv, asked := sub2apiServer(t, func() ([]byte, int) { return sub2apiUsage(t, true), 200 })
p := sub2apiKey(srv)
now := time.Now()
week := now.Add(72 * time.Hour)
noteKeyAllowance(p, []QuotaWindow{{Name: "7 days", Span: 7 * 24 * time.Hour, Used: 95, ResetsAt: &week}}, now)
other := p
other.Key = "sk-other"
if a, ok := KeyAllowance(other); ok || a != nil {
t.Fatalf("another key's: %+v", a)
}
if _, ok := KeyAllowance(p); !ok {
t.Fatal("the key's own not known")
}
// a read begun before ForgetBalances doesn't land after it
keyAllowances.Lock()
gen := keyAllowances.gen
keyAllowances.Unlock()
ForgetBalances()
readKeyAllowance(p, keyAllowanceID(p), gen)
keyAllowances.Lock()
e := keyAllowances.m[keyAllowanceID(p)]
var kept Allowance
if e != nil {
kept = e.a
}
keyAllowances.Unlock()
if len(kept) != 1 || kept[0].Used != 95 {
t.Fatalf("after ForgetBalances, and a read begun before it: %+v", kept)
}
// what was read stands, not the card's older reading, until the key
// is read again at its next ask
if a, ok := KeyAllowance(p); !ok || len(a) != 1 || a[0].Used != 95 {
t.Fatalf("after ForgetBalances: %+v, %v", a, ok)
}
waitAllowance(t, p, func(a Allowance) bool { return len(a) == 2 })
if n := asked.Load(); n != 2 { // the read dropped, and the one after
t.Fatalf("asked %d times after ForgetBalances", n)
}
if strings.Contains(keyAllowanceID(p), "sk-limited") {
t.Fatal("the key itself names its windows")
}
}
// A key out of a window is told renewed (OnRenewed, as agent "" and its
// KeyAllowanceID) once a reading finds that window full no more — its
// limit raised in the panel, or its usage reset — whether routing read it
// or its card did; not on its first reading, while it stays full, as it
// fills, or when a read fails.
func TestKeyAllowanceRenewed(t *testing.T) {
keyLimitsHome(t)
week := time.Now().Add(72 * time.Hour).Truncate(time.Second)
var body atomic.Pointer[[]byte]
srv, _ := sub2apiServer(t, func() ([]byte, int) {
if b := *body.Load(); b != nil {
return b, 200
}
return []byte(`{"error":{"type":"api_error","message":"internal error"}}`), 502
})
p := sub2apiKey(srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
renewedHooks.Lock()
hooks := renewedHooks.fs
renewedHooks.Unlock()
t.Cleanup(func() {
renewedHooks.Lock()
renewedHooks.fs = hooks
renewedHooks.Unlock()
})
var mu sync.Mutex
var told []string
OnRenewed(func(agent, user string) {
mu.Lock()
told = append(told, agent+"/"+user)
mu.Unlock()
})
id := KeyAllowanceID(p)
if id != keyAllowanceID(p) {
t.Fatalf("KeyAllowanceID = %q", id)
}
reply := func(b []byte) { body.Store(&b) }
// read is a reading as routing's, done here rather than behind it
read := func(b []byte) {
reply(b)
keyAllowances.Lock()
gen := keyAllowances.gen
keyAllowances.Unlock()
readKeyAllowance(p, id, gen)
}
tellsSo := func(what string, n int) {
t.Helper()
mu.Lock()
defer mu.Unlock()
if len(told) != n {
t.Fatalf("%s: told %v", what, told)
}
for _, s := range told {
if s != "/"+id {
t.Fatalf("%s: told %v", what, told)
}
}
}
full := weekUsed(t, "800", week)
reply(full)
waitAllowance(t, p, func(a Allowance) bool { u, _ := a.For("gpt-6-astra", time.Now()); return u == 100 })
tellsSo("its first reading, out of its week", 0)
read(full)
tellsSo("its week still used up", 0)
read(bytes.Replace(full, []byte(`"limit":800`), []byte(`"limit":1000`), 1))
tellsSo("its week's limit raised to $1,000", 1)
read(full)
tellsSo("its week used up again", 1)
read(nil)
tellsSo("a read that failed", 1)
// its usage reset in the panel, as its card reads it
reply(sub2apiUsage(t, false))
ForgetBalances()
KeyBalances(context.Background())
tellsSo("its usage reset, read on its card", 2)
}