gateway: an account near its usage cap takes one turn at a time (dyzdyz010)
dyzdyz010 on Discord: two Claude Code accounts, each capped at 90% of its five hours, Stop at the caps and Check usage near the cap on, and both read 100%. Routing holds a capped account by its last reading. Turns sent together (an agent's subagents, several agents) were each planned on the same reading, so an account a point under its cap took every one of them, and went as far past it as they used between them. Check usage near the cap reads the usage again before planning, but every turn read the same figure: each saw 89%. - gateway (cap_near.go): within 5 points of a usage cap (carefulNear), an account takes one turn at a time. A turn that finds it busy goes to the next candidate first, the account moved behind them once; the last candidate waits for it. Once its turn comes capHeld judges it again, by what the reply before it said (codex.rate_limits, rate_limit_event), or by the usage read again when that reply said nothing (at most carefulWait). Held, it is passed over, or the agent gets the cap's 429 when nobody is left. The cap is passed by one turn at most. - A conversation kept on its account by Stays: Strict takes no turn there and goes on past the cap, as before. Neither does an account already held when its try begins, let in past its cap on purpose (a Codex reset spent for it, its credits). - docs: gateway-routing.md's capHeld step, providers-accounts.md's cap sentence. Run (wsl-run, magpie-desktop, Go 1.26.8): - go test -tags nogui -run 'NearCap|FarFromCap' -v ./internal/gateway: the five new tests pass. - go test -tags nogui -race -count=20 -run 'NearCap|FarFromCap' ./internal/gateway: ok. - GOOS=linux go vet -tags nogui ./internal/gateway, GOOS=windows go vet ./internal/gateway: ok. gofmt -l: nothing. - go test -tags nogui -timeout 30m -run 'NearCap|FarFromCap|CodexNoCredits|Reset|Strict|Cap|Credits' ./internal/gateway: ok. - go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider, at this tree rebased on248853225: ok (gateway 604.9s, provider 90.9s). - at the pushed head, rebased on5db1b07ed: the vets ok, and -run 'NearCap|FarFromCap|CodexNoCredits|Reset|Strict|Cap|Credits|Group' ./internal/gateway ok. Broken by hand (each restored after): - the whole near-cap block off (`&& false`): TestNearCapTakesOneTurnAtATime red (acct-1 took all 4 turns), the two wait tests never saw a turn waiting, and TestNearCapClaudeAccountsTakeOneTurnEach red (both turns on the account near its cap, the spare never run). - nearCapAgain a no-op: TestNearCapReadsAgainAfterASilentReply red (200, 200). - capHeld's second look off: TestNearCapWaitsThenHolds and TestNearCapReadsAgainAfterASilentReply red. - the first full run, before the strict exception, had TestStrictAffinityGoesPastTheCap red: the strict conversation got the cap's 429. The second, without the held-on-entry exception, had TestCodexNoCreditsSpendsAReset and TestCodexNoCreditsResetAfterTheLastRefusal red: the account a reset was just spent for was held again. Both fixed in this commit. - An unrelated red in the first run, TestZCodeTrialRefusalRestsTheTrialAlone/trial_edge_block ("no plugin signs in to zcode"), passes alone and was green in the last run; filed as #5335. Not tried: a real Claude or Codex account near its cap; plugin accounts (their caps go through the same candidate loop, untested here). One turn alone can still pass a cap by what it spends: an Opus turn on a Pro plan can take several points of the five hours.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -342,7 +342,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- `GOOGLE_APPLICATION_CREDENTIALS` and `CLOUDSDK_CONFIG` are in `agentenv.Vars`. The desktop app takes them from the login shell when it wasn't started with them (`proc.UserPath`, macOS and Linux), and `testenv` clears both. Vertex AI reads them as set (`vertexEnvPath`), not through `appdir.Getenv`, which takes a relative value as unset: a `~/` that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key).
|
||||
- The Vertex AI preset's `HeaderHints` are Google's Priority PayGo and Flex PayGo headers, `X-Vertex-AI-LLM-Request-Type` and `X-Vertex-AI-LLM-Shared-Request-Type`: the editor offers to add them, the values are the user's, and they go as `Headers` do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with `trafficType` `ON_DEMAND`.
|
||||
- An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight <id> [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`).
|
||||
- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap <id> <account> --window <name>`) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool <id> [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap.
|
||||
- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap <id> <account> --window <name>`) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool <id> [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap.
|
||||
- A key's spend cap (`KeySpendCaps`, by the key's fingerprint, [`key_spend.go`](../../internal/provider/key_spend.go); sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (`Since`, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (`usage.KeySpent`: records whose `ProviderKeyID` is the key, not turned away, not reported by an app; the log is read once and each new call added by `Append`, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over ([gateway routing](gateway-routing.md)). Only a key has one: `SetKeySpendCap` refuses a subscription, an amount not above 0 or over `MaxSpendCap` (1,000,000) and a period it doesn't know. `ReplaceKey` carries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn by `keyspend.js`, which app.js imports when it draws a key's row; GUI `provider/keyspendcap`, `key-spend-cap.test.cjs`) or `magpie provider spend-cap <id> [key [usd [day|month|total]|off]]`, which also lists each key's spend. `TestKeySpendCapSet`, `TestSpendCapWindow`, `TestParseSpendCap`, `TestKeySpentCountsTheKeysCalls`, `TestSpendCapCmd`.
|
||||
- A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here.
|
||||
- A restart to update can run two magpies for up to the old one's drain
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package gateway
|
||||
|
||||
// Near its cap, one turn at a time (dyzdyz010 on Discord: capped at 90%,
|
||||
// used to 100%). Routing holds a capped account by its last reading, and
|
||||
// turns sent together were each planned on the same one: an account a
|
||||
// point under its cap took every one of them, and went as far past it as
|
||||
// they used between them. Within nearCapPoints of a usage cap set on it,
|
||||
// an account takes one turn at a time. A turn that finds it busy goes to
|
||||
// the next account or member when there is one, the account kept behind
|
||||
// them; else it waits for the turn before it. Once its turn comes it is
|
||||
// held by what is known then: the reading the reply before it left
|
||||
// (Codex's codex.rate_limits, Claude's rate_limit_event), or, when that
|
||||
// reply told nothing, the usage read again now (at most carefulWait). The
|
||||
// cap is then passed by one turn at most, not by every turn at once.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// nearCapPoints is how many points under a cap an account takes one turn at a
|
||||
// time: as careful caps read again (carefulNear), a turn of a big model
|
||||
// on a small plan spending a few points.
|
||||
const nearCapPoints = carefulNear
|
||||
|
||||
// nearCaps is each account's one turn near its cap, by candidate.who().
|
||||
type nearCaps struct {
|
||||
mu sync.Mutex
|
||||
slots map[string]chan struct{}
|
||||
wait int // turns waiting for a slot, for tests
|
||||
}
|
||||
|
||||
func (n *nearCaps) slot(who string) chan struct{} {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
if n.slots == nil {
|
||||
n.slots = map[string]chan struct{}{}
|
||||
}
|
||||
s, ok := n.slots[who]
|
||||
if !ok {
|
||||
s = make(chan struct{}, 1)
|
||||
n.slots[who] = s
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// waiting is how many turns wait for an account's turn near its cap.
|
||||
func (n *nearCaps) waiting() int {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return n.wait
|
||||
}
|
||||
|
||||
// tryTake takes who's turn when it is free, and gives back its release.
|
||||
func (n *nearCaps) tryTake(who string) (func(), bool) {
|
||||
s := n.slot(who)
|
||||
select {
|
||||
case s <- struct{}{}:
|
||||
return releaseOnce(s), true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// take waits for who's turn till ctx ends.
|
||||
func (n *nearCaps) take(ctx context.Context, who string) (func(), error) {
|
||||
s := n.slot(who)
|
||||
n.mu.Lock()
|
||||
n.wait++
|
||||
n.mu.Unlock()
|
||||
defer func() {
|
||||
n.mu.Lock()
|
||||
n.wait--
|
||||
n.mu.Unlock()
|
||||
}()
|
||||
select {
|
||||
case s <- struct{}{}:
|
||||
return releaseOnce(s), nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func releaseOnce(s chan struct{}) func() {
|
||||
var once sync.Once
|
||||
return func() { once.Do(func() { <-s }) }
|
||||
}
|
||||
|
||||
// nearCapOf says whether c's account is within nearCapPoints of a usage
|
||||
// cap set on it, by what is known of its usage at now, and the share it
|
||||
// is at for the model.
|
||||
func nearCapOf(c candidate, now time.Time) (float64, bool) {
|
||||
a := c.p.Account
|
||||
if a == nil {
|
||||
return 0, false
|
||||
}
|
||||
caps := provider.HoldCaps(c.p, a.Agent, a.User)
|
||||
if a.Agent == "codex" && freeOnChatGPT(c.model, a.Plan) {
|
||||
return 0, false // spends nothing a cap keeps (capHeld)
|
||||
}
|
||||
if !caps.Holds() {
|
||||
return 0, false
|
||||
}
|
||||
al, ok := allowances(a.UsageAgent())[a.User]
|
||||
if !ok || !al.NearCap(c.model, caps, nearCapPoints, now) {
|
||||
return 0, false
|
||||
}
|
||||
used, _ := al.For(c.model, now)
|
||||
return used, true
|
||||
}
|
||||
|
||||
// nearCapAgain, once a turn has waited for the one before it on an
|
||||
// account near its cap that was at used then, reads the account's usage
|
||||
// again when nothing has told it since (the reply before it said nothing
|
||||
// of it), waiting at most carefulWait.
|
||||
func nearCapAgain(ctx context.Context, c candidate, used float64) {
|
||||
if now, ok := nearCapOf(c, time.Now()); !ok || now != used {
|
||||
return // heard from the reply before it, or renewed
|
||||
}
|
||||
a := c.p.Account
|
||||
ctx, cancel := context.WithTimeout(ctx, carefulWait)
|
||||
defer cancel()
|
||||
readUsageNow(ctx, a.UsageAgent(), a.User)
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// nearCapBackend is a ChatGPT backend for the near-cap tests: each
|
||||
// account's five hours read at used[acct] by /wham/usage, every turn held
|
||||
// until open is closed. A turn's reply says the account is at heard[acct]
|
||||
// (its codex.rate_limits event), or nothing of it when heard has none; once
|
||||
// a turn has ended, /wham/usage says after[acct] when it has one.
|
||||
type nearCapBackend struct {
|
||||
mu sync.Mutex
|
||||
used, after map[string]float64
|
||||
heard map[string]float64
|
||||
tried []string
|
||||
ended int
|
||||
open chan struct{}
|
||||
five, week int64
|
||||
}
|
||||
|
||||
func newNearCapBackend(t *testing.T, used, heard, after map[string]float64) *nearCapBackend {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
b := &nearCapBackend{used: used, heard: heard, after: after, open: make(chan struct{}),
|
||||
five: now.Add(2 * time.Hour).Unix(), week: now.Add(4 * 24 * time.Hour).Unix()}
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
acct := r.Header.Get("chatgpt-account-id")
|
||||
switch r.URL.Path {
|
||||
case "/backend-api/codex/responses":
|
||||
io.ReadAll(r.Body)
|
||||
b.mu.Lock()
|
||||
b.tried = append(b.tried, acct)
|
||||
b.mu.Unlock()
|
||||
select {
|
||||
case <-b.open:
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
var lines []string
|
||||
if n, ok := b.heard[acct]; ok {
|
||||
lines = append(lines, `event: codex.rate_limits`+"\n"+`data: {"type":"codex.rate_limits","plan_type":"plus","rate_limits":{"allowed":true,"limit_reached":false,"primary":{"used_percent":`+jsonFloat(n)+`,"window_minutes":300,"reset_at":`+jsonInt(b.five)+`},"secondary":{"used_percent":10,"window_minutes":10080,"reset_at":`+jsonInt(b.week)+`}},"credits":null,"metered_limit_name":null,"limit_name":null}`)
|
||||
}
|
||||
lines = append(lines,
|
||||
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"pong"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`)
|
||||
io.WriteString(w, sse(lines...))
|
||||
b.mu.Lock()
|
||||
b.ended++
|
||||
b.mu.Unlock()
|
||||
case "/backend-api/wham/usage":
|
||||
b.mu.Lock()
|
||||
used := b.used[acct]
|
||||
if n, ok := b.after[acct]; ok && b.ended > 0 {
|
||||
used = n
|
||||
}
|
||||
b.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus",
|
||||
"rate_limit": map[string]any{"allowed": true,
|
||||
"primary_window": map[string]any{"used_percent": used, "limit_window_seconds": 18000, "reset_at": b.five},
|
||||
"secondary_window": map[string]any{"used_percent": 10, "limit_window_seconds": 604800, "reset_at": b.week}}})
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
t.Cleanup(func() {
|
||||
select {
|
||||
case <-b.open:
|
||||
default:
|
||||
close(b.open)
|
||||
}
|
||||
})
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
return b
|
||||
}
|
||||
|
||||
func jsonFloat(n float64) string {
|
||||
bs, _ := json.Marshal(n)
|
||||
return string(bs)
|
||||
}
|
||||
|
||||
func (b *nearCapBackend) sent() []string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return append([]string(nil), b.tried...)
|
||||
}
|
||||
|
||||
// nearCapAccounts, Codex's accounts signed in (me@example.com, and the
|
||||
// spares) and the fake backend up, routes them in order, caps me at capAt
|
||||
// and reads every one from the backend, waiting for me's reading to be
|
||||
// want.
|
||||
func nearCapAccounts(t *testing.T, capAt int, want float64, spares ...string) {
|
||||
t.Helper()
|
||||
old := allowances
|
||||
allowances = provider.Allowances
|
||||
t.Cleanup(func() { allowances = old })
|
||||
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SetAccountCap("codex", "me@example.com", capAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
users := append([]string{"me@example.com"}, spares...)
|
||||
for _, u := range users {
|
||||
provider.StaleAllowance("codex", u)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
for _, u := range users {
|
||||
provider.StaleAllowance("codex", u)
|
||||
}
|
||||
})
|
||||
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) {
|
||||
n, _ := provider.Allowances("codex")["me@example.com"].For("gpt-5.5", time.Now())
|
||||
if n == want {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("never read: %v%%", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type nearReply struct {
|
||||
code int
|
||||
body string
|
||||
}
|
||||
|
||||
// postAtOnce sends n turns at once, each in its own goroutine.
|
||||
func postAtOnce(t *testing.T, srv *Server, n int) chan nearReply {
|
||||
out := make(chan nearReply, n)
|
||||
for range n {
|
||||
go func() {
|
||||
code, body := resetPost(t, srv)
|
||||
out <- nearReply{code, body}
|
||||
}()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, what string, ok func() bool) {
|
||||
t.Helper()
|
||||
for deadline := time.Now().Add(10 * time.Second); !ok(); time.Sleep(5 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("never: %s", what)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dyzdyz010 on Discord: an account capped at 90% was used to 100%. Every
|
||||
// turn sent at once to an account a point under its cap was planned on the
|
||||
// same reading, so each went to it, and the account went as far past its
|
||||
// cap as they took between them. Within nearCapPoints of a cap an
|
||||
// account takes one turn at a time: the others go to the next account.
|
||||
func TestNearCapTakesOneTurnAtATime(t *testing.T) {
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
b := newNearCapBackend(t, map[string]float64{"acct-1": 89, "acct-2": 20},
|
||||
map[string]float64{"acct-1": 92, "acct-2": 21}, nil)
|
||||
nearCapAccounts(t, 90, 89, "spare@example.com")
|
||||
srv := New()
|
||||
const n = 4
|
||||
replies := postAtOnce(t, srv, n)
|
||||
// every turn is at the vendor, before any is answered: each was
|
||||
// routed on the reading of 89%
|
||||
waitFor(t, "every turn sent", func() bool { return len(b.sent()) == n })
|
||||
close(b.open)
|
||||
for range n {
|
||||
if r := <-replies; r.code != 200 || !strings.Contains(r.body, "pong") {
|
||||
t.Fatalf("%d %s", r.code, r.body)
|
||||
}
|
||||
}
|
||||
got := map[string]int{}
|
||||
for _, a := range b.sent() {
|
||||
got[a]++
|
||||
}
|
||||
if got["acct-1"] != 1 || got["acct-2"] != n-1 {
|
||||
t.Fatalf("sent %v; want one turn to the account near its cap, the rest to the other", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The account near its cap the only one: a turn waits for the one before
|
||||
// it, and is then held by what that one's reply said (92%), not sent past
|
||||
// the cap on the old reading.
|
||||
func TestNearCapWaitsThenHolds(t *testing.T) {
|
||||
codexSignedIn(t)
|
||||
b := newNearCapBackend(t, map[string]float64{"acct-1": 89}, map[string]float64{"acct-1": 92}, nil)
|
||||
nearCapAccounts(t, 90, 89)
|
||||
srv := New()
|
||||
replies := postAtOnce(t, srv, 2)
|
||||
waitFor(t, "one turn sent, one waiting", func() bool { return len(b.sent()) == 1 && srv.nearCap.waiting() == 1 })
|
||||
close(b.open)
|
||||
codes := map[int]int{}
|
||||
var held string
|
||||
for range 2 {
|
||||
r := <-replies
|
||||
codes[r.code]++
|
||||
if r.code == 429 {
|
||||
held = r.body
|
||||
}
|
||||
}
|
||||
if codes[200] != 1 || codes[429] != 1 || len(b.sent()) != 1 {
|
||||
t.Fatalf("codes %v, sent %v; want one answered, one held at the cap", codes, b.sent())
|
||||
}
|
||||
if !strings.Contains(held, "usage cap") {
|
||||
t.Fatalf("held as %s", held)
|
||||
}
|
||||
}
|
||||
|
||||
// A reply that tells nothing of the account's usage: the turn that waited
|
||||
// for it reads the usage again before it goes, and is held at the cap the
|
||||
// reading says it has reached.
|
||||
func TestNearCapReadsAgainAfterASilentReply(t *testing.T) {
|
||||
codexSignedIn(t)
|
||||
b := newNearCapBackend(t, map[string]float64{"acct-1": 89}, nil, map[string]float64{"acct-1": 93})
|
||||
nearCapAccounts(t, 90, 89)
|
||||
srv := New()
|
||||
replies := postAtOnce(t, srv, 2)
|
||||
waitFor(t, "one turn sent, one waiting", func() bool { return len(b.sent()) == 1 && srv.nearCap.waiting() == 1 })
|
||||
close(b.open)
|
||||
codes := map[int]int{}
|
||||
for range 2 {
|
||||
codes[(<-replies).code]++
|
||||
}
|
||||
if codes[200] != 1 || codes[429] != 1 || len(b.sent()) != 1 {
|
||||
t.Fatalf("codes %v, sent %v; want the second read again and held", codes, b.sent())
|
||||
}
|
||||
}
|
||||
|
||||
// Under its cap by more than nearCapPoints, turns go at once, together.
|
||||
func TestFarFromCapTurnsGoTogether(t *testing.T) {
|
||||
codexSignedIn(t)
|
||||
b := newNearCapBackend(t, map[string]float64{"acct-1": 50}, map[string]float64{"acct-1": 51}, nil)
|
||||
nearCapAccounts(t, 90, 50)
|
||||
srv := New()
|
||||
replies := postAtOnce(t, srv, 3)
|
||||
waitFor(t, "every turn sent", func() bool { return len(b.sent()) == 3 })
|
||||
close(b.open)
|
||||
for range 3 {
|
||||
if r := <-replies; r.code != 200 {
|
||||
t.Fatalf("%d %s", r.code, r.body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dyzdyz010's own case: Claude Code accounts, each capped at 90% of its
|
||||
// five hours, Stop at the caps on. Turns sent together while the first
|
||||
// account is a point under its cap: one goes to it, the other to the
|
||||
// second account, not both past the first's cap on one reading.
|
||||
func TestNearCapClaudeAccountsTakeOneTurnEach(t *testing.T) {
|
||||
gate := filepath.Join(t.TempDir(), "gate")
|
||||
log := claudeSubscriptionFirstSays(t, ` while [ ! -f `+gate+` ]; do sleep 0.05; done
|
||||
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pong"}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"pong"}'
|
||||
`)
|
||||
t.Cleanup(func() { os.WriteFile(gate, nil, 0o600) })
|
||||
old := allowances
|
||||
allowances = provider.Allowances
|
||||
t.Cleanup(func() { allowances = old })
|
||||
if err := provider.SetRouting("claude", provider.Ordered); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, u := range []string{"me@example.com", "spare@example.com"} {
|
||||
if err := provider.SetAccountCap("claude", u, 90); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
five, week := time.Now().Add(2*time.Hour).Unix(), time.Now().Add(4*24*time.Hour).Unix()
|
||||
provider.NoteClaudeLimits("me@example.com", []provider.ClaudeLimit{{Kind: "five_hour", Used: 0.89, ResetsAt: five}, {Kind: "seven_day", Used: 0.1, ResetsAt: week}})
|
||||
provider.NoteClaudeLimits("spare@example.com", []provider.ClaudeLimit{{Kind: "five_hour", Used: 0.2, ResetsAt: five}, {Kind: "seven_day", Used: 0.1, ResetsAt: week}})
|
||||
t.Cleanup(func() {
|
||||
provider.StaleAllowance("claude", "me@example.com")
|
||||
provider.StaleAllowance("claude", "spare@example.com")
|
||||
})
|
||||
if n, _ := provider.Allowances("claude")["me@example.com"].For("claude-sonnet-5", time.Now()); n != 89 {
|
||||
t.Fatalf("read at %v%%", n)
|
||||
}
|
||||
s := New()
|
||||
t.Cleanup(s.subscription.abortAll)
|
||||
out := make(chan nearReply, 2)
|
||||
for i := range 2 {
|
||||
go func() {
|
||||
code, body := sendTo(s, "/v1/messages", `{"model":"claude/claude-sonnet-5","max_tokens":50,"stream":true,"messages":[{"role":"user","content":"ping `+strconv.Itoa(i)+`"}]}`)
|
||||
out <- nearReply{code, body}
|
||||
}()
|
||||
}
|
||||
// a Claude Code run on each account the turns went to: the account
|
||||
// near its cap may have a run started ahead for its next turn too
|
||||
waitFor(t, "a run on each account", func() bool {
|
||||
b, _ := os.ReadFile(log)
|
||||
return strings.Contains(string(b), "own") && strings.Contains(string(b), "tok-spare")
|
||||
})
|
||||
os.WriteFile(gate, nil, 0o600)
|
||||
for range 2 {
|
||||
if r := <-out; r.code != 200 || !strings.Contains(r.body, "pong") {
|
||||
t.Fatalf("%d %s", r.code, r.body)
|
||||
}
|
||||
}
|
||||
var got []string
|
||||
s.trace.mu.Lock()
|
||||
for _, r := range s.trace.routes {
|
||||
for _, try := range r.Tries {
|
||||
got = append(got, try.ID)
|
||||
}
|
||||
}
|
||||
s.trace.mu.Unlock()
|
||||
slices.Sort(got)
|
||||
if strings.Join(got, ",") != "claude,claude@spare@example.com" {
|
||||
t.Fatalf("tried %v; want one turn on the account near its cap, one on the spare", got)
|
||||
}
|
||||
}
|
||||
@@ -550,6 +550,8 @@ type Server struct {
|
||||
// the requests out at each key or account with a MaxConcurrency, and
|
||||
// those waiting their turn (concurrency.go)
|
||||
lanes lanes
|
||||
// each account's one turn at a time near its usage cap (cap_near.go)
|
||||
nearCap nearCaps
|
||||
// the requests each key or account with a MaxRPM sent in the last
|
||||
// minute, and those about to go (rpm.go)
|
||||
rpms rpms
|
||||
@@ -3162,11 +3164,24 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// handed the request on, written once the next try begins
|
||||
var failedRow func()
|
||||
walkBegan := time.Now() // the serial walk's start, for groupBudget (#5113)
|
||||
// the turn near its cap the try before took, given back as the next
|
||||
// begins or the request ends (cap_near.go)
|
||||
var nearDone func()
|
||||
defer func() {
|
||||
if nearDone != nil {
|
||||
nearDone()
|
||||
}
|
||||
}()
|
||||
nearBehind := map[string]bool{} // accounts near their cap moved behind the rest once
|
||||
for i := 0; i < len(cands); i++ {
|
||||
if failedRow != nil {
|
||||
failedRow()
|
||||
failedRow = nil
|
||||
}
|
||||
if nearDone != nil {
|
||||
nearDone()
|
||||
nearDone = nil
|
||||
}
|
||||
c := cands[i]
|
||||
if handed.release != nil && handed.who != c.who() {
|
||||
handed.release()
|
||||
@@ -3216,6 +3231,58 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
failTo(w, kept, from, call.Status, cmp.Or(msg, call.Error))
|
||||
break
|
||||
}
|
||||
if used, near := nearCapOf(c, time.Now()); near && aff.Why != "strict" && capHeld(c.p, c.p, c.model, time.Now()) == nil {
|
||||
// within nearCapPoints of its usage cap, the account takes one
|
||||
// turn at a time (dyzdyz010 on Discord): busy, the turn goes to
|
||||
// the next one first, this one kept behind them, else waits for
|
||||
// the turn before it and is held by what that one left. A
|
||||
// conversation kept strictly on it goes on past its cap, as
|
||||
// strictKeep keeps it, and an account already held when its try
|
||||
// begins was let in past its cap on purpose (a reset spent for
|
||||
// it, its credits), so is not held again here.
|
||||
done, ok := s.nearCap.tryTake(c.who())
|
||||
if !ok && i < len(cands)-1 && !nearBehind[c.who()] {
|
||||
nearBehind[c.who()] = true
|
||||
cands = append(slices.Delete(slices.Clone(cands), i, i+1), c)
|
||||
i--
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
var err error
|
||||
if done, err = s.nearCap.take(r.Context(), c.who()); err != nil {
|
||||
// the agent went away while it waited: nothing was sent
|
||||
call.Status, call.Error = canceled(r.Context())
|
||||
break
|
||||
}
|
||||
nearCapAgain(r.Context(), c, used)
|
||||
}
|
||||
nearDone = done
|
||||
if h := capHeld(c.p, c.p, c.model, time.Now()); h != nil {
|
||||
nearDone()
|
||||
nearDone = nil
|
||||
c.capped = h
|
||||
ws := barredOf([]candidate{c}, c.p, false, from, nil)
|
||||
msg, back := cappedError(call.Model, ws, time.Now())
|
||||
skipped = append(skipped, c.label()+": "+msg)
|
||||
if i < len(cands)-1 {
|
||||
continue
|
||||
}
|
||||
// held at its cap by the turn before it: the agent is told
|
||||
// the failure of one asked before, else the cap
|
||||
if other != nil {
|
||||
call.Status, call.Error, call.Usage.ErrType = other.Status, other.Error, other.errType
|
||||
s.trace.update(tr, func(t *Route) { t.Fail = toldFail(other) })
|
||||
failTo(w, kept, from, call.Status, call.Error)
|
||||
break
|
||||
}
|
||||
if d := time.Until(back); d > 0 && !kept.sent {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(d.Seconds())+1))
|
||||
}
|
||||
call.Status, call.Error = 429, cappedRecord(ws)
|
||||
failTo(w, kept, from, 429, msg)
|
||||
break
|
||||
}
|
||||
}
|
||||
if !autoReset && c.onCredits() {
|
||||
// going to the account on its credits, its week used up: a
|
||||
// reset it spends by itself when the week runs out goes
|
||||
|
||||
Reference in New Issue
Block a user