Commit Graph
4 Commits
Author SHA1 Message Date
wei 043e0cfc7b provider tests: the allowance tests end only once their own reading and renewal tell are done, and each sub2api key test reads its key under an id of its own (#1058)
TestKeyAllowanceStaleMidRead waits until its own OnRenewed hook has been
told, and puts back the hooks it found. TestAllowancesBeforeFirstReading's
cleanup waits for the reading it held before the reset. sub2apiKey takes the
test and names the key sub2api-<test>, so a renewal told late by one test
is not counted by the next, and TestKeyAllowanceRenewed counts only its own
key's renewals. Only test code changes.

Squashed from #1058 (waitingsnow, head 42fe2c7b). The reviewer changed one
thing: quota_asked_test.go's TestKeyReadsOnlyWhenAsked, added on main by
e9221e96 after the PR's last rebase, still called sub2apiKey(srv), so the
PR's head merged onto main didn't build. It now calls sub2apiKey(t, srv).

What was run (macOS arm64, Go 1.26.8, -tags nogui, sandbox HOME, private
GOCACHE), on the merge with origin/main 5b14ebf4:
- 100 ms before key_allowance.go's tellRenewed:
  -count=5 -run '^(TestKeyAllowanceStaleMidRead|TestKeyAllowanceRenewed)$'
  fails on main's tests ("its week's limit raised to $1,000: told
  [/sub2api#703eb1a04b /sub2api#703eb1a04b]") and passes with this change.
- With 250 ms before Allowances stores a reading, plus 500 ms before each
  codex Allowances ask, TestAllowancesBeforeFirstReading followed by
  TestResetRunsOutForRouting passes on current main as well as with this
  change. That failure reproduced 5/5 at 443f1cbc, but not on current main.
  The cleanup's wait is kept anyway: it is right regardless.
- -race -count=20 of TestKeyAllowance|TestSub2API|TestAllowancesBeforeFirstReading|
  TestResetRunsOutForRouting|TestKeyReadsOnlyWhenAsked|TestCachedCardsTellKeyReadings: ok
- go test ./internal/provider: ok (728s on a heavily loaded machine; a
  first run under the default 10m timeout timed out from the load)
- go vet on darwin, GOOS=linux -tags nogui and GOOS=windows for the
  package; gofmt -l clean.
Not run: go test ./... on an idle machine.
2026-10-13 09:09:37 +08:00
yetone 49caff3caf provider tests: a no-wait return is asserted by holding the slow thing, not a wall-clock bound (#1617)
The siblings of #1586 that 7b151cf54 left alone. Each said "comes back
without waiting" by measuring time.Since(start) against a bound (50ms,
500ms, 1s, 2s, 3s) that a loaded runner can pass and so make red without
the guarantee breaking. Each now holds the slow thing until it has its
answer, so a call that comes back at all came back without waiting for it.
A deadline is kept only so a call that did wait fails as a FAIL rather
than a hang, and each is short of the slow thing's own timeout, so a call
that waited cannot come back in time by having it time out:

- cli_identity_test TestCLIIdentityFirstAskBounded: both looks run while
  the ask is held (it was already). The second look is run with firstAsk
  set to an hour, so a second look that waited again (not only waited the
  whole ask) is caught; 10s guard.
- claude_status_test TestClaudeIdentityServedWhileAsked: the stand-in CLI
  now waits for a file instead of `sleep 1`, and writes another when
  reached. The stale look must come back while it is held, with the ask
  still in flight (claudeStatusBusy), and the CLI must have been asked
  again. The guard is 4s, short of askClaudeStatus' own 5s kill. Its
  cleanup lets the CLI go and waits for the ask to end.
- partners_test TestPartnersDoesNotWait: the five Partners() calls run
  while the site is held; 10s guard (the fetch's own is 20s).
- partners_test TestPartnersNow and plugin_icon_test
  TestRepoIconsWaitForFirstFetch had a floor and a ceiling. The floor is
  the guarantee that the call waited for its bound, and a busy machine only
  lengthens it, so it stays (100ms, and 250ms for a 300ms wait as before).
  The ceiling was the "doesn't wait past its bound" half: it is now that
  the call comes back while the site/fetch is held; 10s guard (the fetch's
  own are 20s and 30s).
- sub2api_usage_test TestKeyAllowanceNeverWaits: the ten looks run while
  sub2api is held and report back over a channel, not t.Errorf from a
  goroutine that could outlive a failed test; 10s guard (the read's own is
  30s).

What was run (temp HOME, caches pinned):
  go test -tags nogui -race -count=10 -run '<the six tests>' ./internal/provider  ok
  go test -tags nogui -count=1 ./internal/provider                                ok 395.6s
  gofmt -l; go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/provider  clean

Broken by hand, each red at the new assertion:
  cli_identity.go, drop c.waited = true (every look waits):
    :124 a second look waited
  cli_identity.go, drop the firstAsk case (the first look waits the ask):
    :116 the first look waited for the held ask
  account.go, askClaudeStatus() in the stale case under the lock:
    claude_status_test.go:111 a stale look waited for the held CLI
  partners.go, Partners runs refreshPartners in line:
    :246 Partners waited for the held site
  partners.go, PartnersNow without its time.After(wait):
    :316 PartnersNow waited past its bound for the held site
  key_allowance.go, KeyAllowance reads in line (lock let go around it):
    sub2api_usage_test.go:279 a look waited for the held read
  plugin_icon.go, RepoIcons without its timer case:
    :168 RepoIcons waited past its 300ms for the held fetch
2026-10-11 22:02:50 +08:00
yetone ee2588c268 provider: a key that says it is out of its windows while they are being read has them read again once that reading is back (TestRestingKeyReadAgainInAnOrderedGroup red on macOS CI, runs 37467016755 and on main since 555f5706) — since 555f5706 the first planning of a lone key reads its windows behind the request. When that reading was still out as the key refused for quota, StaleKeyAllowance only zeroed the time it was read, and the reading, asked before the refusal, came back, set it to now and was trusted for a minute: the rest out of the key's windows wasn't lifted by the reading planned after it, though its limit had been raised. StaleKeyAllowance now marks a reading that is out (stale), and once it is back the key's windows are read again at once; forgetting every key's windows clears the mark. TestKeyAllowanceStaleMidRead (the first reading held until after StaleKeyAllowance, then answered; the second answered with the week half used) fails without the change (asked once) and passes -race -count=20 with the other TestKeyAllowance tests. The gateway test fails every time with its first reading delayed 300 ms ("still rests by window …, its windows read 2 times", as CI said) and passes with the change. go test -race ./internal/provider (8 of 9 runs pass; the first run's failure wasn't kept and didn't come back), go test -race -count=10 -run 'TestResting|Key|Lone|Allowance' ./internal/gateway, go vet, gofmt -l pass. 2026-10-06 21:29:55 +08:00
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