feat(router): share the token-size estimate through Redis

With redis.sharedState on, each observed sample also adds to day counters of prompt bytes, prompt tokens and sample count per model. The router-learning loop reads the counters of the routers' target models and keeps one fleet ratio per model. The estimate prefers that ratio once the fleet has the same minimum sample count as the local calibrator. Dropped counter writes only blur the estimate. With the switch off, the calibrator runs its local code only and makes no store call.
This commit is contained in:
2026-11-26 03:32:03 +00:00
parent fe5e9afdc9
commit e70eb32336
4 changed files with 236 additions and 3 deletions
+88
View File
@@ -0,0 +1,88 @@
package traefikllmgateway
import (
"testing"
)
// shareLimiterStore points a pod's limiter at the shared store and makes its async writes synchronous.
func shareLimiterStore(g *Gateway, store counterStore) {
g.limiter.store = store
g.limiter.spawn = func(f func()) { f() }
}
func TestSharedCalibratorAcrossGateways(t *testing.T) {
a, b, store, _, _ := sharedGatewayPair(t, nil)
shareLimiterStore(a, store)
shareLimiterStore(b, store)
const bytes, tokens = 1000, 400 // 2.5 bytes per token
if got := b.tokenCalib.promptTokens("alpha", "a1", bytes); got != 250 {
t.Fatalf("uncalibrated estimate = %d, want 250", got)
}
for i := 0; i < smartCalibMinSamples-1; i++ {
a.tokenCalib.observe("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)
if got := b.tokenCalib.promptTokens("alpha", "a1", bytes); got != 250 {
t.Fatalf("estimate changed before the learn refresh = %d, want 250", got)
}
b.refreshRouterLearning(b.limiter.now())
if got := b.tokenCalib.promptTokens("alpha", "a1", bytes); got != 400 {
t.Fatalf("shared estimate = %d, want 400", got)
}
if got := b.tokenCalib.promptTokens("beta", "b1", bytes); got != 250 {
t.Fatalf("an unobserved model changed to %d, want 250", got)
}
}
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)
if len(store.writes) != 0 {
t.Fatalf("unusable samples wrote %d counters, want 0", len(store.writes))
}
}
func TestSharedCalibratorStartsRouterLearning(t *testing.T) {
a, _, _, _, _ := sharedGatewayPair(t, nil)
off, _ := sharedOffGateway(t)
for name, gw := range map[string]*Gateway{"shared": a, "off": off} {
rt := gw.registry.routers[routerName]
if rt.learns() {
t.Fatalf("%s: router learns without calibration or bandit, fixture is wrong", name)
}
gw.touchRouterLearning(rt)
t.Cleanup(gw.closeRouterLearning)
}
if !a.routerLearn.running {
t.Error("shared: router learning loop did not start for a calibrator-only router")
}
if off.routerLearn.running {
t.Error("off: router learning loop started with sharedState off")
}
}
func TestSharedStateOffIdenticalCalibrator(t *testing.T) {
gw, _ := sharedOffGateway(t)
rec, _ := sharedTestEnv()
gw.limiter.store = rec
gw.limiter.spawn = func(f func()) { f() }
ref := newSmartTokenCalibrator()
for i := 0; i < 80; i++ {
gw.tokenCalib.observe("alpha", "a1", 1000+int64(i), 400)
ref.observe("alpha", "a1", 1000+int64(i), 400)
if got, want := gw.tokenCalib.promptTokens("alpha", "a1", 5000), ref.promptTokens("alpha", "a1", 5000); got != want {
t.Fatalf("observation %d: estimate %d, want %d", i, got, want)
}
}
gw.refreshRouterLearning(gw.limiter.now())
if len(rec.reads) != 0 || len(rec.writes) != 0 {
t.Fatalf("store touched with sharedState off: %d reads, %d writes", len(rec.reads), len(rec.writes))
}
}
+5
View File
@@ -24,6 +24,11 @@ func (g *Gateway) wireSharedState(cfg *Config) {
brk.failureThreshold, brk.openBase, brk.openMax, 2*brk.openMax))
}
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() })
}
}
// maxProviderTimeout is the longest request timeout any provider can run, which bounds how long an in-flight count stays live.
+57 -2
View File
@@ -1,6 +1,9 @@
package traefikllmgateway
import "sync"
import (
"sync"
"time"
)
const (
// smartDefaultBytesPerToken is the uncalibrated estimate.
@@ -16,6 +19,14 @@ const (
smartCalibAlpha = 0.1
// smartCalibMaxModels bounds the map; models come from config and discovery, so it is a safety cap.
smartCalibMaxModels = 1024
// Fleet counters per model and day: prompt bytes, prompt tokens and sample count.
calibKind = "cal"
calibMetricBytes = "b"
calibMetricToken = "t"
calibMetricCount = "n"
// calibFleetDays is how many day buckets the fleet ratio spans, so it does not reset at midnight.
calibFleetDays = 2
)
type smartCalibKey struct {
@@ -31,9 +42,47 @@ type smartCalibStat struct {
// from reported usage. It keeps two numbers per model and no request data.
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
c.fleet = make(map[smartCalibKey]smartCalibStat)
}
func (c *smartTokenCalibrator) sharing() bool {
return c != nil && c.count != nil
}
// setFleet replaces the shared ratios with those of the latest learn refresh.
func (c *smartTokenCalibrator) setFleet(m map[smartCalibKey]smartCalibStat) {
c.mu.Lock()
c.fleet = m
c.mu.Unlock()
}
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
}
bucket := bucketFor(c.now(), windowDay)
c.count([]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 newSmartTokenCalibrator() *smartTokenCalibrator {
return &smartTokenCalibrator{stats: make(map[smartCalibKey]*smartCalibStat)}
}
@@ -45,6 +94,7 @@ func (c *smartTokenCalibrator) observe(provider, model string, promptBytes, prom
}
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]
@@ -65,12 +115,17 @@ func (c *smartTokenCalibrator) observe(provider, model string, promptBytes, prom
// clamped learned ratio once enough samples exist, else one token per four bytes.
func (c *smartTokenCalibrator) promptTokens(provider, model string, promptBytes int64) int64 {
if c != nil {
key := smartCalibKey{provider: provider, model: model}
c.mu.Lock()
st := c.stats[smartCalibKey{provider: provider, model: model}]
st := c.stats[key]
ratio, ready := 0.0, false
if st != nil && st.samples >= smartCalibMinSamples {
ratio, ready = st.ratio, true
}
// The fleet ratio covers every pod's samples, so it wins when it has enough of them.
if fs, ok := c.fleet[key]; ok && fs.samples >= smartCalibMinSamples {
ratio, ready = fs.ratio, true
}
c.mu.Unlock()
if ready {
if ratio < smartCalibMinRatio {
+86 -1
View File
@@ -316,7 +316,7 @@ func (rt *smartRouter) learns() bool {
// touchRouterLearning notes a routed request and starts the refresh goroutine if it is not running.
func (g *Gateway) touchRouterLearning(rt *smartRouter) {
l := g.routerLearn
if l == nil || !rt.learns() {
if l == nil || (!rt.learns() && !g.sharesCalibration(rt)) {
return
}
l.mu.Lock()
@@ -397,6 +397,91 @@ func (g *Gateway) refreshRouterLearning(now time.Time) {
g.refreshBandit(rt, now)
}
}
g.refreshSharedCalibration(now)
}
// sharesCalibration reports whether rt's token estimate reads the fleet counters.
func (g *Gateway) sharesCalibration(rt *smartRouter) bool {
return rt.contextEscalation && g.tokenCalib.sharing()
}
// calibrationTargets lists the upstream (provider, model) pairs the calibrating routers can send to.
func (g *Gateway) calibrationTargets() []smartCalibKey {
seen := make(map[smartCalibKey]bool)
var out []smartCalibKey
grp := &group{}
for _, rt := range g.registry.routers {
if !g.sharesCalibration(rt) {
continue
}
for _, tier := range rt.tiers {
for _, target := range tier.models {
var cands []resolveCandidate
if g.failover.enabled {
primary, extra, err := g.registry.resolveWithCandidates(target, grp)
if err != nil {
continue
}
cands = append([]resolveCandidate{primary}, extra...)
} else {
primary, err := g.registry.resolvePrimaryOnly(target, grp)
if err != nil {
continue
}
cands = []resolveCandidate{primary}
}
for _, cand := range cands {
k := smartCalibKey{provider: cand.providerName, model: cand.upstreamModel}
if !seen[k] {
seen[k] = true
out = append(out, k)
}
}
}
}
}
return out
}
// refreshSharedCalibration reads the fleet counters of every calibrating router's targets and keeps one bytes-per-token ratio per model.
// A failed read keeps the previous ratios.
func (g *Gateway) refreshSharedCalibration(now time.Time) {
if !g.tokenCalib.sharing() || g.limiter == nil {
return
}
targets := g.calibrationTargets()
if len(targets) == 0 {
return
}
buckets := make([]string, calibFleetDays)
for i := range buckets {
buckets[i] = bucketFor(now.Add(-time.Duration(i)*24*time.Hour), windowDay)
}
names := make([]string, 0, len(targets)*len(buckets)*3)
for _, k := range targets {
for _, bucket := range buckets {
names = append(names, calibFleetKey(k, calibMetricBytes, bucket), calibFleetKey(k, calibMetricToken, bucket), calibFleetKey(k, calibMetricCount, bucket))
}
}
vals, ok := g.limiter.chunkedGetMulti(names, usageModelsChunkKeys)
if !ok {
return
}
fleet := make(map[smartCalibKey]smartCalibStat, len(targets))
pos := 0
for _, k := range targets {
var bytes, tokens, n int64
for range buckets {
bytes += vals[pos]
tokens += vals[pos+1]
n += vals[pos+2]
pos += 3
}
if bytes > 0 && tokens > 0 {
fleet[k] = smartCalibStat{ratio: float64(bytes) / float64(tokens), samples: int(n)}
}
}
g.tokenCalib.setFleet(fleet)
}
// warnRouterLearning notes learning settings that stay per instance.