perf(shared-state): batch calibrator counters with the usage write

Each served request spawned a second async write for the calibrator
counters. They now ride the batch accountWith already sends, and only
when shared state is on and a store is configured.
This commit is contained in:
2026-11-26 04:12:38 +00:00
parent 383d477778
commit 367f3b60ff
6 changed files with 98 additions and 21 deletions
+6
View File
@@ -1995,6 +1995,8 @@ type accountExtras struct {
// with a store, accountWith mirrors it, and provenanceTokens, into the
// shared month counters.
provenance string
// calibration is the shared token-calibrator counters of this call; accountWith adds them only with a store.
calibration []counterIncr
// promptCacheSaved is the micro-USD the provider prompt cache saved this call.
promptCacheSaved int64
provenanceTokens int64
@@ -2229,6 +2231,10 @@ func (l *limiter) accountWith(scopes []limitScope, u usage, costMicros int64, x
entries = append(entries, provenanceEntries(x.provider, x.provenance, x.provenanceTokens, wb.month)...)
}
if l.store != nil && len(x.calibration) > 0 {
entries = append(entries, x.calibration...)
}
if x.hasLat && l.statsLatency {
if x.provider != "" {
entries = append(entries, latencyCounterEntries(kindProvider, x.provider, x.lat, wb, et)...)
+5 -1
View File
@@ -801,6 +801,10 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
extras.provenance = provenance
extras.provenanceTokens = result.total()
}
calibrate := plan != nil && callErr == nil && !plan.hasImage && !result.estimated
if calibrate {
extras.calibration = g.tokenCalib.fleetEntries(providerName, cand.upstreamModel, plan.promptBytes, result.prompt)
}
extras.promptCacheSaved = unifiedPromptCacheSaved(cand.canonical, cand.upstreamModel, result, g.cfg.Pricing, g.cfg.ModelMeta)
g.recordPromptCache(providerName, cand.upstreamModel, result)
g.limiter.accountWith(acctScopes, result, unifiedCostMicros(cand.canonical, cand.upstreamModel, result, g.cfg.Pricing, g.cfg.ModelMeta, g.pricingWarn), extras)
@@ -808,7 +812,7 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
g.logf("%s: usage for model %q logged as estimated (%d prompt tokens derived from request body size, not the provider's reported usage)", logPrefix, cand.canonical, result.prompt)
}
if plan != nil && callErr == nil && !plan.hasImage && !result.estimated {
if calibrate {
g.tokenCalib.observe(providerName, cand.upstreamModel, plan.promptBytes, result.prompt)
}
if plan != nil && plan.bandit != nil {
+10 -4
View File
@@ -10,6 +10,12 @@ func shareLimiterStore(g *Gateway, store counterStore) {
g.limiter.spawn = func(f func()) { f() }
}
// observeShared records one sample the way a served request does: the shared counters ride accountWith's batch.
func observeShared(g *Gateway, provider, model string, bytes, tokens int64) {
g.limiter.accountWith(nil, usage{}, 0, accountExtras{calibration: g.tokenCalib.fleetEntries(provider, model, bytes, tokens)})
g.tokenCalib.observe(provider, model, bytes, tokens)
}
func TestSharedCalibratorAcrossGateways(t *testing.T) {
a, b, store, _, _ := sharedGatewayPair(t, nil)
shareLimiterStore(a, store)
@@ -20,13 +26,13 @@ func TestSharedCalibratorAcrossGateways(t *testing.T) {
t.Fatalf("uncalibrated estimate = %d, want 250", got)
}
for i := 0; i < smartCalibMinSamples-1; i++ {
a.tokenCalib.observe("alpha", "a1", bytes, tokens)
observeShared(a, "alpha", "a1", bytes, tokens)
}
b.refreshRouterLearning(b.limiter.now())
if got := b.tokenCalib.promptTokens("alpha", "a1", bytes); got != 250 {
t.Fatalf("estimate below the minimum sample count = %d, want 250", got)
}
a.tokenCalib.observe("alpha", "a1", bytes, tokens)
observeShared(a, "alpha", "a1", bytes, tokens)
if got := b.tokenCalib.promptTokens("alpha", "a1", bytes); got != 250 {
t.Fatalf("estimate changed before the learn refresh = %d, want 250", got)
}
@@ -42,8 +48,8 @@ func TestSharedCalibratorAcrossGateways(t *testing.T) {
func TestSharedCalibratorSkipsUnusableSamples(t *testing.T) {
a, _, store, _, _ := sharedGatewayPair(t, nil)
shareLimiterStore(a, store)
a.tokenCalib.observe("alpha", "a1", smartCalibMinBytes-1, 10)
a.tokenCalib.observe("alpha", "a1", 1000, 0)
observeShared(a, "alpha", "a1", smartCalibMinBytes-1, 10)
observeShared(a, "alpha", "a1", 1000, 0)
if len(store.writes) != 0 {
t.Fatalf("unusable samples wrote %d counters, want 0", len(store.writes))
}
+59
View File
@@ -360,3 +360,62 @@ func TestSharedStateErrorLogsAreRateLimited(t *testing.T) {
t.Errorf("%d error lines after the interval, want 2", got)
}
}
// batchStore records each incrMulti call as one batch of keys.
type batchStore struct {
counterStore
batches [][]string
mu sync.Mutex
}
func (s *batchStore) incrMulti(e []counterIncr) ([]int64, error) {
keys := make([]string, len(e))
for i, x := range e {
keys[i] = x.key
}
s.mu.Lock()
s.batches = append(s.batches, keys)
s.mu.Unlock()
return s.counterStore.incrMulti(e)
}
func TestSharedCalibratorCountersRideTheAccountBatch(t *testing.T) {
body := `{"id":"x","object":"chat.completion","model":"a1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1000,"completion_tokens":2}}`
a := newRouterBackend(200, body)
b := newRouterBackend(200, successRespBody)
c := newRouterBackend(200, successRespBody)
defer closeBackends(a, b, c)
cfg := routerTestConfig(a, b, c, threeTiers())
h, gw := buildRouterGateway(t, cfg)
rec, clk := sharedTestEnv()
bs := &batchStore{counterStore: rec}
gw.sharedState = sharedTestLoop(bs, clk)
gw.wireSharedState(cfg)
shareLimiterStore(gw, bs)
if r := routerChat(t, h, routerName, strings.Repeat("plain words ", 400), nil); r.Code != 200 {
t.Fatalf("status = %d", r.Code)
}
var calBatches, mixed int
bs.mu.Lock()
defer bs.mu.Unlock()
for _, keys := range bs.batches {
cal, other := false, false
for _, k := range keys {
if strings.Contains(k, ":"+calibKind+":") {
cal = true
} else {
other = true
}
}
if cal {
calBatches++
if other {
mixed++
}
}
}
if calBatches != 1 || mixed != 1 {
t.Errorf("calibrator counters in %d batches (%d shared with usage counters), want 1 batch shared with them", calBatches, mixed)
}
}
+1 -3
View File
@@ -25,9 +25,7 @@ func (g *Gateway) wireSharedState(cfg *Config) {
}
g.shareDecisionBreakers(ids)
if g.tokenCalib != nil && g.limiter != nil {
g.tokenCalib.share(
func(entries []counterIncr) { g.limiter.countAsync(entries) },
func() time.Time { return g.limiter.now() })
g.tokenCalib.share(func() time.Time { return g.limiter.now() })
}
}
+17 -13
View File
@@ -44,19 +44,18 @@ type smartTokenCalibrator struct {
stats map[smartCalibKey]*smartCalibStat
// fleet holds the ratios the router-learning loop read from the shared counters; nil without sharedState.
fleet map[smartCalibKey]smartCalibStat
count func([]counterIncr)
now func() time.Time
mu sync.Mutex
}
// share makes observe also add to the fleet counters through count. Call it before the calibrator serves requests.
func (c *smartTokenCalibrator) share(count func([]counterIncr), now func() time.Time) {
c.count, c.now = count, now
// share makes fleetEntries return the shared counters to add. Call it before the calibrator serves requests.
func (c *smartTokenCalibrator) share(now func() time.Time) {
c.now = now
c.fleet = make(map[smartCalibKey]smartCalibStat)
}
func (c *smartTokenCalibrator) sharing() bool {
return c != nil && c.count != nil
return c != nil && c.now != nil
}
// setFleet replaces the shared ratios with those of the latest learn refresh.
@@ -70,17 +69,23 @@ func calibFleetKey(k smartCalibKey, metric, bucket string) string {
return windowKeyForBucket(calibKind, k.provider+"/"+k.model, metric, windowDay, bucket)
}
// countFleet adds one usable sample to the day's shared counters. Dropped writes only blur an estimate.
func (c *smartTokenCalibrator) countFleet(key smartCalibKey, promptBytes, promptTokens int64) {
if c.count == nil {
return
// fleetEntries returns the day's shared counters for one usable sample, for the caller to add to its own batch.
// It returns nil when not sharing or the sample is unusable.
func (c *smartTokenCalibrator) fleetEntries(provider, model string, promptBytes, promptTokens int64) []counterIncr {
if !c.sharing() || !calibUsable(promptBytes, promptTokens) {
return nil
}
key := smartCalibKey{provider: provider, model: model}
bucket := bucketFor(c.now(), windowDay)
c.count([]counterIncr{
return []counterIncr{
{key: calibFleetKey(key, calibMetricBytes, bucket), delta: promptBytes, ttl: dayWindowTTL, enforceTTL: enforceTTLDayWindow},
{key: calibFleetKey(key, calibMetricToken, bucket), delta: promptTokens, ttl: dayWindowTTL, enforceTTL: enforceTTLDayWindow},
{key: calibFleetKey(key, calibMetricCount, bucket), delta: 1, ttl: dayWindowTTL, enforceTTL: enforceTTLDayWindow},
})
}
}
func calibUsable(promptBytes, promptTokens int64) bool {
return promptTokens > 0 && promptBytes >= smartCalibMinBytes
}
func newSmartTokenCalibrator() *smartTokenCalibrator {
@@ -89,12 +94,11 @@ func newSmartTokenCalibrator() *smartTokenCalibrator {
// observe records one request's estimated prompt bytes against the upstream's reported prompt tokens.
func (c *smartTokenCalibrator) observe(provider, model string, promptBytes, promptTokens int64) {
if c == nil || promptTokens <= 0 || promptBytes < smartCalibMinBytes {
if c == nil || !calibUsable(promptBytes, promptTokens) {
return
}
sample := float64(promptBytes) / float64(promptTokens)
key := smartCalibKey{provider: provider, model: model}
c.countFleet(key, promptBytes, promptTokens)
c.mu.Lock()
defer c.mu.Unlock()
st := c.stats[key]