Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions coordinator/api/billing_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1123,6 +1123,132 @@ func TestIntegration_MultiNodeSameAccount(t *testing.T) {
}
}

// TestOverageChargeBeforeClamp verifies that when a provider's actual cost
// exceeds the pre-flight reservation, the coordinator attempts to charge the
// consumer the overage before falling back to the hard clamp.
func TestOverageChargeBeforeClamp(t *testing.T) {
srv, st, ledger := billingTestServer(t)

model := "overage-test-model"
accountID := "overage-provider-account"
// Set a provider custom price well above the platform default so that
// the actual cost computed by handleComplete exceeds ReservedMicroUSD.
const customInputPrice int64 = 500_000 // 10x platform default
const customOutputPrice int64 = 50_000_000 // 10x platform default
if err := st.SetModelPrice(accountID, model, customInputPrice, customOutputPrice); err != nil {
t.Fatalf("set provider custom price: %v", err)
}

provider := srv.registry.Register("overage-provider", nil, &protocol.RegisterMessage{
Models: []protocol.ModelInfo{{ID: model, ModelType: "chat", Quantization: "4bit"}},
})
provider.Mu().Lock()
provider.AccountID = accountID
provider.Mu().Unlock()

usage := protocol.UsageInfo{PromptTokens: 1000, CompletionTokens: 500}
actualCost := payments.CalculateCostWithOverrides(model, usage.PromptTokens, usage.CompletionTokens, customInputPrice, customOutputPrice, true)
// Reservation is deliberately lower than actual cost to trigger overage.
reservedAmount := actualCost / 2

consumerID := "test-key"
initialBalance := ledger.Balance(consumerID)
if err := ledger.Charge(consumerID, reservedAmount, "reserve:"+consumerID); err != nil {
t.Fatalf("reserve balance: %v", err)
}

pr := &registry.PendingRequest{
RequestID: "overage-charge-test",
Model: model,
ConsumerKey: consumerID,
ReservedMicroUSD: reservedAmount,
ChunkCh: make(chan string, 1),
CompleteCh: make(chan protocol.UsageInfo, 1),
ErrorCh: make(chan protocol.InferenceErrorMessage, 1),
}
provider.AddPending(pr)

srv.handleComplete(provider.ID, provider, &protocol.InferenceCompleteMessage{
Type: protocol.TypeInferenceComplete,
RequestID: pr.RequestID,
Usage: usage,
})

// The overage should have been charged successfully, so the consumer
// pays the full actual cost (reservation + overage), not the clamped
// reservation amount.
expectedPayout := payments.ProviderPayout(actualCost)
if got := st.GetWithdrawableBalance(accountID); got != expectedPayout {
t.Errorf("provider payout = %d, want %d (full actual cost payout)", got, expectedPayout)
}
if got := ledger.Balance(consumerID); got != initialBalance-actualCost {
t.Errorf("consumer balance = %d, want %d (charged full actual cost)", got, initialBalance-actualCost)
}
}

// TestOverageChargeClampOnInsufficientBalance verifies that when the overage
// charge fails (consumer balance drained mid-flight), the coordinator falls
// back to the hard clamp at the reservation amount.
func TestOverageChargeClampOnInsufficientBalance(t *testing.T) {
srv, st, _ := billingTestServer(t)

model := "overage-clamp-model"
accountID := "overage-clamp-account"
const customInputPrice int64 = 500_000
const customOutputPrice int64 = 50_000_000
if err := st.SetModelPrice(accountID, model, customInputPrice, customOutputPrice); err != nil {
t.Fatalf("set provider custom price: %v", err)
}

provider := srv.registry.Register("overage-clamp-provider", nil, &protocol.RegisterMessage{
Models: []protocol.ModelInfo{{ID: model, ModelType: "chat", Quantization: "4bit"}},
})
provider.Mu().Lock()
provider.AccountID = accountID
provider.Mu().Unlock()

usage := protocol.UsageInfo{PromptTokens: 1000, CompletionTokens: 500}
actualCost := payments.CalculateCostWithOverrides(model, usage.PromptTokens, usage.CompletionTokens, customInputPrice, customOutputPrice, true)
reservedAmount := actualCost / 2

// Use a consumer with exactly the reserved amount so the overage charge
// will fail due to insufficient balance.
consumerID := "low-balance-consumer"
_ = st.Credit(consumerID, reservedAmount, store.LedgerDeposit, "test-setup")
if err := srv.ledger.Charge(consumerID, reservedAmount, "reserve:"+consumerID); err != nil {
t.Fatalf("reserve balance: %v", err)
}

pr := &registry.PendingRequest{
RequestID: "overage-clamp-test",
Model: model,
ConsumerKey: consumerID,
ReservedMicroUSD: reservedAmount,
ChunkCh: make(chan string, 1),
CompleteCh: make(chan protocol.UsageInfo, 1),
ErrorCh: make(chan protocol.InferenceErrorMessage, 1),
}
provider.AddPending(pr)

srv.handleComplete(provider.ID, provider, &protocol.InferenceCompleteMessage{
Type: protocol.TypeInferenceComplete,
RequestID: pr.RequestID,
Usage: usage,
})

// Overage charge should have failed, so the provider gets paid based on
// the clamped reservation amount, not the full actual cost.
expectedPayout := payments.ProviderPayout(reservedAmount)
if got := st.GetWithdrawableBalance(accountID); got != expectedPayout {
t.Errorf("provider payout = %d, want %d (clamped to reservation)", got, expectedPayout)
}
// Consumer balance should be zero: entire deposit was reserved, overage
// failed, no refund since totalCost was clamped to exactly the reservation.
if got := srv.ledger.Balance(consumerID); got != 0 {
t.Errorf("consumer balance = %d, want 0", got)
}
}

// sha256HexStr computes SHA-256 of a string and returns hex encoding.
func sha256HexStr(s string) string {
h := sha256.Sum256([]byte(s))
Expand Down
75 changes: 66 additions & 9 deletions coordinator/api/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,14 @@ func intFromRequestValue(v any) (int, bool) {
}
}

// approximateTokenCount returns a rough token estimate for routing and queue
// admission. The len/4 heuristic is a reasonable average for English text
// with GPT-style BPE tokenizers. This value feeds into the scheduler's
// capacity checks (pendingTokenBudget, freeMemoryAdmits) where a tighter
// estimate produces better routing decisions.
//
// For billing reservation (where underestimation causes provider shortfall),
// use approximateTokenCountUpperBound instead.
func approximateTokenCount(v any) int {
if v == nil {
return 0
Expand Down Expand Up @@ -320,6 +328,32 @@ func approximateTokenCount(v any) int {
}
}

// approximateTokenCountUpperBound returns a guaranteed upper bound on the
// number of tokens a BPE tokenizer would produce for v. Every BPE vocabulary
// starts with one token per byte and can only merge, so len(text) >= tokens
// for any model family, any language, forever. This is used only for billing
// reservation to ensure the pre-flight debit always covers the actual cost.
//
// Using len(text) over-reserves by ~3-4x on average for English prose, but
// the difference is refunded immediately after inference completes, so
// consumers are never overcharged — they only need sufficient balance to
// cover the reservation hold.
func approximateTokenCountUpperBound(v any) int {
if v == nil {
return 0
}
switch x := v.(type) {
case string:
return len(x)
Comment thread
Gajesh2007 marked this conversation as resolved.
Resolved
default:
b, err := json.Marshal(v)
if err != nil {
return 0
}
return len(b)
}
}

func estimatePromptTokens(parsed map[string]any) int {
total := 0
if v, ok := parsed["messages"]; ok {
Expand All @@ -337,6 +371,27 @@ func estimatePromptTokens(parsed map[string]any) int {
return total
}

// estimateBillingPromptTokens returns a guaranteed upper bound on prompt
// tokens for billing reservation. Uses byte-length (not len/4) so the
// pre-flight reservation always covers actual cost. This value must NOT
// be used for routing — see estimatePromptTokens for that.
func estimateBillingPromptTokens(parsed map[string]any) int {
total := 0
if v, ok := parsed["messages"]; ok {
total += approximateTokenCountUpperBound(v)
}
if v, ok := parsed["input"]; ok {
total += approximateTokenCountUpperBound(v)
}
if v, ok := parsed["prompt"]; ok {
total += approximateTokenCountUpperBound(v)
}
if total == 0 {
total = approximateTokenCountUpperBound(parsed)
}
return total
}

func estimateRequestedMaxTokens(parsed map[string]any) int {
for _, key := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens"} {
if n, ok := intFromRequestValue(parsed[key]); ok && n > 0 {
Expand Down Expand Up @@ -852,6 +907,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {

stream, _ := parsed["stream"].(bool)
estimatedPromptTokens := estimatePromptTokens(parsed)
billingPromptTokens := estimateBillingPromptTokens(parsed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

requestedMaxTokens := estimateRequestedMaxTokens(parsed)
timing.ParsedAt = time.Now()

Expand All @@ -865,14 +921,15 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
}

// Pre-flight balance reservation — atomically debit the worst-case cost
// (prompt tokens already consumed + max_tokens we just bounded the
// generation to) before routing to a provider. The post-inference charge
// refunds any unused portion. Reserving only the minimum charge let
// consumers receive streamed output far exceeding their actual balance.
// using the byte-length upper bound for prompt tokens (guaranteed >=
// actual tokens for any BPE tokenizer) plus max_tokens we just bounded
// the generation to. The post-inference charge refunds any unused
// portion. The routing estimate (estimatedPromptTokens, len/4) is kept
// separate so scheduler capacity checks aren't over-inflated.
var reservedMicroUSD int64
if s.billing != nil {
consumerKey := consumerKeyFromContext(r.Context())
reservedMicroUSD = s.reservationCost(model, estimatedPromptTokens, requestedMaxTokens)
reservedMicroUSD = s.reservationCost(model, billingPromptTokens, requestedMaxTokens)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

start := time.Now()
if err := s.ledger.Charge(consumerKey, reservedMicroUSD, "reserve:"+consumerKey); err != nil {
writeJSON(w, http.StatusPaymentRequired, errorResponse("insufficient_funds",
Expand Down Expand Up @@ -3256,20 +3313,20 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request,

stream, _ := parsed["stream"].(bool)
estimatedPromptTokens := estimatePromptTokens(parsed)
billingPromptTokens := estimateBillingPromptTokens(parsed)
requestedMaxTokens := estimateRequestedMaxTokens(parsed)

// Inject the endpoint so the provider knows which local path to forward to.
parsed["endpoint"] = endpoint

// Pre-flight balance reservation — same worst-case-cost reservation as
// handleChatCompletions. Before this fix the completions and Anthropic
// paths routed without ANY reservation; the silent post-inference charge
// meant a consumer could receive full responses with a zero balance.
// handleChatCompletions, using the byte-length upper bound for prompt
// tokens so the reservation always covers actual cost.
consumerKey := consumerKeyFromContext(r.Context())
consumerLocation := s.requestLocation(r)
var reservedMicroUSD int64
if s.billing != nil {
reservedMicroUSD = s.reservationCost(model, estimatedPromptTokens, requestedMaxTokens)
reservedMicroUSD = s.reservationCost(model, billingPromptTokens, requestedMaxTokens)
start := time.Now()
if err := s.ledger.Charge(consumerKey, reservedMicroUSD, "reserve:"+consumerKey); err != nil {
writeJSON(w, http.StatusPaymentRequired, errorResponse("insufficient_funds",
Expand Down
106 changes: 106 additions & 0 deletions coordinator/api/consumer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1294,3 +1294,109 @@ func TestProviderEarningsEmptyWallet(t *testing.T) {
t.Errorf("total_jobs = %v, want 0", resp["total_jobs"])
}
}

// TestApproximateTokenCount verifies the len/4 routing heuristic.
func TestApproximateTokenCount(t *testing.T) {
tests := []struct {
name string
input any
want int
}{
{"nil", nil, 0},
{"empty string", "", 0},
{"single char", "a", 1},
{"short ASCII", "hello", 1}, // 5/4 = 1
{"english prose", "The quick brown fox jumps.", 6}, // 26/4 = 6
{"16 bytes", "0123456789abcdef", 4}, // 16/4 = 4
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := approximateTokenCount(tt.input)
if got != tt.want {
t.Errorf("approximateTokenCount(%v) = %d, want %d", tt.input, got, tt.want)
}
})
}
}

// TestApproximateTokenCountUpperBound verifies that the billing upper bound
// returns len(text) — guaranteed >= actual BPE tokens for any tokenizer.
func TestApproximateTokenCountUpperBound(t *testing.T) {
tests := []struct {
name string
input any
want int
}{
{"nil", nil, 0},
{"empty string", "", 0},
{"single char", "a", 1},
{"short ASCII", "hello", 5},
{"english prose", "The quick brown fox jumps over the lazy dog.", 44},
{"code snippet", "func main() { fmt.Println(\"hello\") }", 36},
{"multibyte UTF-8", "こんにちは世界", 21}, // 7 chars × 3 bytes each
{"emoji", "👋🌍", 8}, // 2 emoji × 4 bytes each
{"chat template tags", "<|im_start|>system\nYou are helpful.<|im_end|>", 45},
{"json object", map[string]string{"role": "user", "content": "hi"}, len(`{"content":"hi","role":"user"}`)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := approximateTokenCountUpperBound(tt.input)
if got != tt.want {
t.Errorf("approximateTokenCountUpperBound(%v) = %d, want %d", tt.input, got, tt.want)
}
})
}
}

// TestBillingEstimateAlwaysGERoutingEstimate confirms that the billing
// upper bound is always >= the routing heuristic for the same input.
func TestBillingEstimateAlwaysGERoutingEstimate(t *testing.T) {
inputs := []string{
"Hello, world!",
"def fibonacci(n):\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)",
"SELECT u.id, u.name FROM users u WHERE u.active = true ORDER BY u.created_at DESC LIMIT 10;",
"これはテストです。日本語のテキストはトークン数が多くなります。",
strings.Repeat("a", 1000),
}
for _, input := range inputs {
routing := approximateTokenCount(input)
billing := approximateTokenCountUpperBound(input)
if billing < routing {
t.Errorf("billing(%d) < routing(%d) for %q", billing, routing, input[:min(20, len(input))])
}
}
}

// TestEstimatePromptTokens verifies the routing estimate for different
// request field layouts.
func TestEstimatePromptTokens(t *testing.T) {
tests := []struct {
name string
input map[string]any
}{
{
name: "messages field",
input: map[string]any{"messages": []any{map[string]any{"role": "user", "content": "hello"}}},
},
{
name: "prompt field",
input: map[string]any{"prompt": "Tell me a story"},
},
{
name: "input field",
input: map[string]any{"input": "Translate this"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
routing := estimatePromptTokens(tt.input)
billing := estimateBillingPromptTokens(tt.input)
if routing < 1 {
t.Errorf("estimatePromptTokens() = %d, want >= 1", routing)
}
if billing < routing {
t.Errorf("billing(%d) < routing(%d)", billing, routing)
}
})
}
}
Loading
Loading