Repository navigation
fix(payments): use len(prompt) as universal token upper bound, add overage charge before clamp - #215
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8b6d98dc31
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| s.ddIncr("billing.cost_clamped", []string{"model:" + pr.Model}) | ||
| totalCost = pr.ReservedMicroUSD | ||
| overage := totalCost - pr.ReservedMicroUSD | ||
| if err := s.ledger.Charge(pr.ConsumerKey, overage, "overage:"+msg.RequestID); err != nil { |
There was a problem hiding this comment.
Finalize reservation before charging overage
Move the overage debit behind reservation finalization (or into FinalizeReservation) because handleComplete now calls s.ledger.Charge(...) before pr.MarkReservationFinalized(). In late-completion races where the consumer path has already called refundReservedBalance (timeout/provider error paths), the reservation is finalized/refunded first, but this line can still charge an overage; then MarkReservationFinalized() returns false and settlement/payout is skipped, leaving the consumer incorrectly debited for a request that already took the refund path.
Useful? React with 👍 / 👎.
| s.ddIncr("billing.cost_clamped", []string{"model:" + pr.Model}) | ||
| totalCost = pr.ReservedMicroUSD | ||
| overage := totalCost - pr.ReservedMicroUSD | ||
| if err := s.ledger.Charge(pr.ConsumerKey, overage, "overage:"+msg.RequestID); err != nil { |
There was a problem hiding this comment.
Keep hard cap against provider-reported overbilling
Charging overage unconditionally removes the prior safety cap that bounded billing to the pre-flight reservation when providers reported usage above expected limits. Since totalCost is derived from provider-reported token counts, a misbehaving or compromised provider can now bill consumers above the reserved maximum whenever the account has balance, whereas the previous clamp prevented this class of overcharge.
Useful? React with 👍 / 👎.
…dd overage charge before clamp Three changes to eliminate the silent provider shortfall from Issue #115. 1. Decouple billing estimate from routing estimate approximateTokenCount (len/4) is kept for routing and queue admission where a tighter heuristic produces better capacity decisions. A new approximateTokenCountUpperBound (len) is used exclusively for billing reservation. Every BPE tokenizer starts with one token per byte and can only merge, so len(prompt) is mathematically >= tokens for any model family, any language, forever. The ~3-4x over- reservation for English prose is refunded immediately after inference. 2. Overage charge before hard clamp When totalCost > ReservedMicroUSD (e.g. provider custom pricing above platform rate), the coordinator now attempts to charge the consumer the difference first — but only after MarkReservationFinalized() succeeds, preventing a race with timeout/error refund paths. The overage is capped at the reservation amount (total cannot exceed 2x reservation) as a fraud circuit-breaker against provider over- reporting. The hard clamp is retained as a last resort if the overage charge fails (balance drained mid-flight). 3. Tests - TestApproximateTokenCount: routing heuristic (len/4) - TestApproximateTokenCountUpperBound: billing upper bound (len) - TestBillingEstimateAlwaysGERoutingEstimate: invariant check - TestEstimatePromptTokens: routing + billing for messages/prompt/input - TestOverageChargeBeforeClamp: overage succeeds, provider gets full payout - TestOverageChargeClampOnInsufficientBalance: overage fails, falls back Closes #115
8b6d98d to
c01263a
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c01263a883
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } else if totalCost > pr.ReservedMicroUSD { | ||
| // Actual cost exceeds reservation (e.g. provider custom | ||
| // pricing above platform rate). Attempt to charge the | ||
| // consumer the difference. Cap overage at the reservation |
There was a problem hiding this comment.
Restrict overage debits to trusted overage cases
Fresh evidence in this revision: even after adding the 2x clamp, the new totalCost > pr.ReservedMicroUSD branch still attempts ledger.Charge for any overage without requiring a custom-price scenario or validating usage against the request’s bounded token budget. In practice, a buggy/malicious provider can report inflated usage and now debit consumers above their pre-flight reservation (up to the new cap), whereas the previous behavior hard-clamped at reservation. Gate overage charging to verifiable/expected cases (e.g., known custom pricing deltas) before debiting.
Useful? React with 👍 / 👎.
| if s.billing != nil { | ||
| consumerKey := consumerKeyFromContext(r.Context()) | ||
| reservedMicroUSD = s.reservationCost(model, estimatedPromptTokens, requestedMaxTokens) | ||
| reservedMicroUSD = s.reservationCost(model, billingPromptTokens, requestedMaxTokens) |
There was a problem hiding this comment.
Carry billing token estimate into provider top-up logic
This patch reserves base cost with billingPromptTokens, but provider-specific reservation top-ups still derive from PendingRequest.EstimatedPromptTokens (the routing len/4 heuristic). That mismatch means dense-token prompts can still be under-reserved for custom-priced providers, pushing settlement into the overage/clamp path and reintroducing provider shortfall the change is trying to eliminate. Propagate the billing upper-bound estimate to the provider top-up path instead of reusing the routing heuristic.
Useful? React with 👍 / 👎.
|
|
||
| stream, _ := parsed["stream"].(bool) | ||
| estimatedPromptTokens := estimatePromptTokens(parsed) | ||
| billingPromptTokens := estimateBillingPromptTokens(parsed) |
There was a problem hiding this comment.
Compute reservation after Responses input normalization
For /v1/responses requests, billing reservation is computed from the raw parsed payload before conversion, but the conversion path strips binary parts (input_image/input_file) down to short placeholders before sending to providers. That means large image/file URLs or blobs can inflate billingPromptTokens far beyond the actual prompt tokens consumed, triggering avoidable insufficient_funds rejections despite low real inference cost. Derive billing prompt tokens from the normalized provider payload for Responses requests to avoid this false over-reservation.
Useful? React with 👍 / 👎.
What
Two changes to eliminate the silent provider shortfall from Issue #115.
Why
Issue #115: The
len(x)/4heuristic inapproximateTokenCountunderestimates token count for code, non-English text, and chat template expansions. When the estimate is low, the pre-flight reservation is lower than the actual cost, and the post-inference clamp atReservedMicroUSDsilently shorts the provider — they do the work but get paid less than actual usage.A second cause:
reservationCostuses platform pricing, buthandleCompleteuses provider pricing. A provider with a custom price above the platform rate triggers the clamp even with a perfect token estimate.Changes
1.
approximateTokenCount:len(x)/4→len(x)Every BPE tokenizer starts with one token per byte and can only merge, so
len(prompt)is mathematically ≥ tokens for any model family, any language, forever. The reservation now always covers the actual token workload.The ~3-4x over-reservation for English prose is refunded immediately after inference completes, so consumers are never overcharged — they only need sufficient balance to cover the reservation hold.
2. Try overage charge before clamping
When
totalCost > ReservedMicroUSD(e.g. provider custom pricing above platform rate), the coordinator now attempts to charge the consumer the difference first. The consumer already proved sufficient balance at reservation time, so the overage is typically small and succeeds. The hard clamp is retained as a circuit breaker — it only fires if the overage charge fails (balance drained mid-flight).coordinator/api/consumer.golen(x)/4→len(x)inapproximateTokenCount; updated commentscoordinator/api/provider.gocoordinator/api/consumer_test.goapproximateTokenCount,estimatePromptTokenscoordinator/api/billing_integration_test.goTests added
TestApproximateTokenCount— verifieslen(text)upper bound for nil, empty, ASCII, code, UTF-8, emoji, chat template tags, and JSON objectsTestApproximateTokenCountIsUpperBound— confirms the invariant across representative inputsTestEstimatePromptTokens— verifies messages/prompt/input field estimationTestOverageChargeBeforeClamp— provider custom price exceeds reservation; overage charged successfully; provider gets full payoutTestOverageChargeClampOnInsufficientBalance— consumer balance drained; overage fails; falls back to hard clampAll existing coordinator tests pass (
go test ./... -count=1).Closes #115
Need help on this PR? Tag
@codesmithwith what you need. Autofix is disabled.