fix(billing): hold inflight reservation until billing lands; price estimate like billing; wire remaining endpoints

Address gaps found in adversarial verification of the in-flight balance
reservation:

- Early release: the reservation is now a ref-counted handle carried on the
  request context. Billing tasks submitted via submit*UsageRecordTask take a
  ref and return it only after RecordUsage has run; with reservation enabled
  the balance cache is deducted synchronously inside the billing task, so the
  reservation is released only after admission can see the deduction. Dropped
  tasks return their ref immediately. The reservation is renewed every ttl/3
  while the handler runs; after the handler returns it is no longer renewed,
  so the post-handler hold is bounded by one TTL.
- Estimate: use the same billing model (channel mapping + BillingModelSource,
  max over requested/mapped when ambiguous) and ModelPricingResolver (group
  ModelPricing incl. wildcards, channel per_request/image/video/token
  overrides), default/group/user rate + peak multiplier, plus image, video,
  audio and search surcharge kinds. Unpriced requests fail open with a
  throttled log; new billing.inflight_reservation.fail_closed_on_unpriced
  (default false) rejects them instead.
- Wire images, embeddings, web/x search, alpha search, grok media generation,
  grok realtime/voice, OpenAI-platform /v1/messages and ResponsesWebSocket
  (session-level reservation with renewal).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
William DrakeandClaude Opus 5.5 committed 2026-09-28 16:14:43 -04:00
1 parent 43f88c99aa
commit 52c123e6f4
21 files changed
+1250 -102

No files matched your search

@@ -56,6 +56,23 @@ var (
return {1, tostring(sum), count}
`)
// KEYS: [1]=zset [2]=hash ARGV: [1]=member [2]=expire_at_ms [3]=key_ttl_ms
// 仅当成员仍存在时续期(XX),并把两个 key 的 TTL 至少延长到 key_ttl_ms。
renewInflightBalanceScript = redis.NewScript(`
if not redis.call('ZSCORE', KEYS[1], ARGV[1]) then
return 0
end
redis.call('ZADD', KEYS[1], 'XX', tonumber(ARGV[2]), ARGV[1])
local ttl = tonumber(ARGV[3])
if redis.call('PTTL', KEYS[1]) < ttl then
redis.call('PEXPIRE', KEYS[1], ttl)
end
if redis.call('PTTL', KEYS[2]) < ttl then
redis.call('PEXPIRE', KEYS[2], ttl)
end
return 1
`)
releaseInflightBalanceScript = redis.NewScript(`
redis.call('ZREM', KEYS[1], ARGV[1])
redis.call('HDEL', KEYS[2], ARGV[1])
@@ -99,4 +116,21 @@ func (c *billingCache) ReleaseInflightBalance(ctx context.Context, userID int64,
return releaseInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID).Err()
}
var _ service.InflightBalanceReservationCache = (*billingCache)(nil)
// RenewInflightBalance 实现 service.InflightBalanceReservationRenewer。
func (c *billingCache) RenewInflightBalance(ctx context.Context, userID int64, requestID string, ttl time.Duration) (bool, error) {
zkey, hkey := billingInflightKeys(userID)
ttlMs := ttl.Milliseconds()
if ttlMs <= 0 {
ttlMs = 1
}
n, err := renewInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID, time.Now().UnixMilli()+ttlMs, ttlMs).Int64()
if err != nil {
return false, err
}
return n == 1, nil
}
var (
_ service.InflightBalanceReservationCache = (*billingCache)(nil)
_ service.InflightBalanceReservationRenewer = (*billingCache)(nil)
)