Repository navigation
fix(gateway): balance review fixes before 0.70.0 - #323
Merged
Merged
Conversation
OpenRouter reads only GET /api/v1/key. The account endpoint (/api/v1/credits) answers only management keys, so every upstream whose key had no limit showed "the upstream rejected the key". A key with a limit is a quota as before; every key also reports what it spent (usage_monthly, or usage when that is missing) and its expires_at. No wallet is reported for OpenRouter any more. A read no longer leaves an upstream "running" forever. Tracker::claim now returns a Claim guard: Claim::settle records the result, and dropping it unsettled (a cancelled task, a panic) gives the upstream back to the timer, restoring the "a request ended" mark it took. The refresh endpoint runs the read in its own task, so a client that goes away no longer cancels it; the read still lands and emits balance_updated. Sub2API's "spent today" is usage.today.actual_cost (what the key was charged after the group rate), falling back to cost. New API converts its billing endpoints by the site's quota display type, not always to dollars. The reader now asks the public GET /api/status (no key sent): quota_display_type USD/CUSTOM -> USD, CNY -> CNY, TOKENS -> tokens; older New API and One API only have display_in_currency (true -> USD, false -> tokens). A site that answers without saying is labelled "unknown" rather than USD; a status request that fails outright fails the read and keeps the previous reading. The unlimited marker (exactly 100000000, written in every display mode) is taken as ">= 1e8" for money but only "== 1e8" for tokens or unknown, so a real token limit above it stays a quota. Background reads take the provider config and its client from one runtime snapshot; a reload in between could pair the key with the default client and skip its proxy. A provider without a client in that snapshot is skipped. Detection counts a 3xx as an answer (the outbound client does not follow redirects, so a login-page redirect means the endpoint is not there). When detection is undecided because a probe failed, the refresh endpoint answers 502 with that gw.balance.* reason instead of 404 control.balance_none. Check connection waits at most 5 s for the balance and otherwise returns the test result without one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes from the pre-release review of upstream balances (#321, #322; unreleased, protocol 46). Each finding was checked against the code, and for the third-party shapes against the providers' public API docs or source, before it was changed.
What changes
1. OpenRouter keys without a limit no longer fail.
/api/v1/creditsanswers only management keys (an ordinary key gets 403), so most OpenRouter upstreams showed "the upstream rejected the key". The reader now calls onlyGET /api/v1/key:limit/limit_remaining→ quota when a limit is set (used = limit − remaining, as before);usage_monthly→ spent this month (usage→ spent in total when the monthly figure is missing);expires_at→ expires.OpenRouter no longer reports a wallet. Tests use recorded shapes for a limited and an unlimited key and assert
/api/v1/creditsis never requested.2. An aborted read no longer stops background reads for that upstream.
Tracker::claimreturns aClaimguard.Claim::settlerecords the result. Dropping aClaimwithout settling it (the task was cancelled or panicked) releases the upstream and puts back the "a request ended" mark the claim cleared.refresh_balanceruns the read in a spawned task and awaits it, so a client that disconnects no longer cancels the read: it still lands and emitsbalance_updated. Tests: a dropped claim gives the upstream back (unit); a refresh whose caller is aborted mid-read still finishes; a background read aborted mid-read leaves the upstream to the timer, which reads it again. Both integration tests fail on the old code.3. Sub2API "spent today" is what the key was charged. The reader prefers
usage.today.actual_cost(after the group rate) and falls back tocost.4. New API amounts carry the site's real unit. New API's billing endpoints convert by the site's quota display type, so the amounts are not always dollars. The reader asks the public
GET /api/status, without sending the key:data.quota_display_type:USD→ USD,CNY→ CNY,TOKENS→ tokens.CUSTOM→ USD, because the billing endpoints convert custom display to dollars (the custom rate is applied only in the web UI).data.display_in_currency:true→ USD,false→ tokens.unknown(an honest plain number, not dollars). If/api/statusfails outright (connect, timeout, 5xx, 429), the read fails and the previous reading is kept.100000000for an unlimited key in every display mode. It is taken as>= 1e8for money, but only as== 1e8for tokens or an unknown unit, so a real token limit above it stays a quota.5. A reload can no longer send the key without its proxy. Background reads and refreshes take the provider config and its HTTP client from one runtime snapshot. A provider with no client in that snapshot is skipped instead of falling back to the default client.
6. A 3xx is an answer, and refresh reports why detection is undecided.
POST /providers/{name}/balance/refreshanswers 502 with that failure's existinggw.balance.*message instead of404 control.balance_none.Detection::Undecidednow carries the reason.7. Check connection waits at most 5 s for the balance. If the balance is not read by then, the test result is returned without one. A saved upstream is read in the background as usual.
Protocol
CONTROL_API_VERSIONstays 46: all of this is inside the unreleased 46.POST /providers/{name}/balance/refreshcan now answer 502 with agw.balance.*message (detection undecided).BalanceQuota.unitandSpent.currencycan beunknown(New API site that does not say) andtokens(New API site in token mode). Documented on the types.wallet; they carryquota(if limited) andspent(periodmonth, ortotal).New messages
None. The refresh 502 reuses the existing
gw.balance.*codes.Verification
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warningsenv -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy cargo test --workspacecargo test -p twcore --test msg_codes(no code changes)./scripts/smoke.sh: 82 passed, 0 failedNo real third-party service was called. All reads in the tests go to local fake servers.
🤖 Generated with Claude Code