feat(router): decision model stats and admin view

This commit is contained in:
2026-11-25 13:56:39 +00:00
parent 0d1f71b392
commit f8a38e10da
4 changed files with 361 additions and 9 deletions
+63 -1
View File
@@ -34,6 +34,23 @@ type adminRouterShadowView struct {
Count int64 `json:"count"`
}
// adminRouterDecisionTierView is one cell of the heuristic-tier by model-tier matrix.
type adminRouterDecisionTierView struct {
Heuristic string `json:"heuristic"`
Model string `json:"model"`
Count int64 `json:"count"`
}
// adminRouterDecisionView shows the decision-model settings of a router.
type adminRouterDecisionView struct {
Provider string `json:"provider"`
Path string `json:"path"`
Mode string `json:"mode"`
Timeout string `json:"timeout"`
MinProb int `json:"minProb"`
Band int `json:"band"`
}
// adminRouterOutcomeView counts finished requests by first attempted tier, reason and outcome.
type adminRouterOutcomeView struct {
Tier string `json:"tier"`
@@ -67,7 +84,10 @@ type adminRouterStatsView struct {
Escalations []adminRouterEscalationView `json:"escalations"`
Shadow []adminRouterShadowView `json:"shadow"`
Outcomes []adminRouterOutcomeView `json:"outcomes"`
Requests int64 `json:"requests"`
// Decision is the heuristic-vs-model tier matrix; DecisionOutcomes has one row per outcome when the router has a decision block.
Decision []adminRouterDecisionTierView `json:"decision"`
DecisionOutcomes []adminRouterCountView `json:"decisionOutcomes"`
Requests int64 `json:"requests"`
}
// adminRouterAdaptiveView shows the settings of adaptive selection.
@@ -81,6 +101,7 @@ type adminRouterAdaptiveView struct {
// hints, not secrets.
type adminRouterView struct {
Adaptive *adminRouterAdaptiveView `json:"adaptive,omitempty"`
Decision *adminRouterDecisionView `json:"decision,omitempty"`
Name string `json:"name"`
DefaultTier string `json:"defaultTier"`
ToolsMinTier string `json:"toolsMinTier,omitempty"`
@@ -132,6 +153,9 @@ func (g *Gateway) buildAdminRouterViews() []adminRouterView {
if rt.shadowV2 {
v.ShadowClassifier = smartClassifierV2
}
if rt.decision != nil {
v.Decision = buildAdminRouterDecision(rt.decision)
}
if rt.bandit != nil {
v.Adaptive = &adminRouterAdaptiveView{ExplorePct: rt.bandit.cfg.explorePct, WindowHours: rt.bandit.cfg.windowHours, LatencyWeightPct: rt.bandit.cfg.latencyPct}
}
@@ -190,6 +214,9 @@ func buildAdminRouterStats(rt *smartRouter, c routerCounters) adminRouterStatsVi
Escalations: []adminRouterEscalationView{},
Shadow: []adminRouterShadowView{},
Outcomes: []adminRouterOutcomeView{},
Decision: []adminRouterDecisionTierView{},
DecisionOutcomes: []adminRouterCountView{},
}
tierIdx := make(map[string]int, len(rt.tiers))
for i, t := range rt.tiers {
@@ -225,6 +252,8 @@ func buildAdminRouterStats(rt *smartRouter, c routerCounters) adminRouterStatsVi
})
st.Shadow = buildAdminRouterShadow(rt, c.shadow)
st.Outcomes = buildAdminRouterOutcomes(rt, c.outcomes)
st.Decision = buildAdminRouterDecisionTiers(rt, c.decMx)
st.DecisionOutcomes = buildAdminRouterDecisionOutcomes(rt, c.decs)
return st
}
@@ -241,6 +270,39 @@ func buildAdminRouterShadow(rt *smartRouter, counts map[routerShadowKey]int64) [
return out
}
func buildAdminRouterDecision(d *smartDecisionCfg) *adminRouterDecisionView {
mode := smartDecisionShadow
if d.live {
mode = smartDecisionLive
}
return &adminRouterDecisionView{Provider: d.provider, Path: d.path, Mode: mode, Timeout: d.timeout.String(), MinProb: d.minProb, Band: d.band}
}
// buildAdminRouterDecisionTiers lists the non-zero heuristic-by-model cells in tier order.
func buildAdminRouterDecisionTiers(rt *smartRouter, counts map[routerDecisionTierKey]int64) []adminRouterDecisionTierView {
out := []adminRouterDecisionTierView{}
for _, h := range rt.tiers {
for _, m := range rt.tiers {
if n := counts[routerDecisionTierKey{router: rt.name, heuristic: h.name, model: m.name}]; n > 0 {
out = append(out, adminRouterDecisionTierView{Heuristic: h.name, Model: m.name, Count: n})
}
}
}
return out
}
// buildAdminRouterDecisionOutcomes returns one row per outcome, zeros included, only for routers with a decision block.
func buildAdminRouterDecisionOutcomes(rt *smartRouter, counts map[routerDecisionKey]int64) []adminRouterCountView {
out := []adminRouterCountView{}
if rt.decision == nil {
return out
}
for _, name := range routerDecisionOutcomes {
out = append(out, adminRouterCountView{Name: name, Count: counts[routerDecisionKey{router: rt.name, outcome: name}]})
}
return out
}
// buildAdminRouterOutcomes lists the non-zero outcome counts in tier, reason, outcome order.
func buildAdminRouterOutcomes(rt *smartRouter, counts map[routerOutcomeKey]int64) []adminRouterOutcomeView {
out := []adminRouterOutcomeView{}
+126
View File
@@ -0,0 +1,126 @@
package traefikllmgateway
import (
"context"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func decisionStatsPlan(outcome, heuristic, model string) *routerPlan {
return &routerPlan{
router: "r", reason: "score", startTier: "mid",
entries: []routerPlanEntry{{tier: "mid"}},
decisionOutcome: outcome, heuristicTier: heuristic, decisionTier: model,
}
}
func TestRecordRouterDecisionStats(t *testing.T) {
tests := []struct {
plan *routerPlan
name string
wantTiers int
wantOut int
}{
{decisionStatsPlan(decisionOverride, "mid", "top"), "override", 1, 1},
{decisionStatsPlan(decisionCache, "mid", "top"), "cache", 1, 1},
{decisionStatsPlan(decisionTimeout, "", ""), "timeout", 0, 1},
{decisionStatsPlan(decisionOverride, "mid", ""), "tier missing", 0, 1},
{decisionStatsPlan("", "", ""), "no call", 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := &Gateway{cfg: &Config{Metrics: &MetricsConfig{Enabled: true}}, routerStats: newRouterStats()}
g.recordRouterAttempt(tt.plan, 0, cacheEndpointChat, nil)
dec, tiers := g.routerStats.decisionSnapshot()
assert.Len(t, dec, tt.wantOut)
assert.Len(t, tiers, tt.wantTiers)
if tt.wantOut == 1 {
assert.EqualValues(t, 1, dec[routerDecisionKey{router: "r", outcome: tt.plan.decisionOutcome}])
}
if tt.wantTiers == 1 {
assert.EqualValues(t, 1, tiers[routerDecisionTierKey{router: "r", heuristic: "mid", model: "top"}])
}
})
}
}
func TestRouterDecisionMetricsExposition(t *testing.T) {
g := newDecisionFixture(t, 3, "", okHandler).g
g.cfg.Metrics = &MetricsConfig{Enabled: true}
g.recordRouterAttempt(decisionStatsPlan(decisionOverride, "mid", "top"), 0, cacheEndpointChat, nil)
out := scrape(g)
assert.Contains(t, out, `llmgateway_router_decision_total{router="r",outcome="override"} 1`)
assert.Contains(t, out, `llmgateway_router_decision_tiers_total{router="r",heuristic="mid",model="top"} 1`)
}
func TestAdminRouterDecisionView(t *testing.T) {
f := newDecisionFixture(t, 3, "", okHandler)
f.rt.decision.live = true
f.g.cfg.Metrics = &MetricsConfig{Enabled: true}
for _, p := range []*routerPlan{decisionStatsPlan(decisionOverride, "ta", "tc"), decisionStatsPlan(decisionTimeout, "", "")} {
p.router = "auto"
f.g.recordRouterAttempt(p, 0, cacheEndpointChat, nil)
}
views := f.g.buildAdminRouterViews()
require.Len(t, views, 1)
v := views[0]
require.NotNil(t, v.Decision)
assert.Equal(t, "live", v.Decision.Mode)
assert.Equal(t, "500ms", v.Decision.Timeout)
assert.Equal(t, "gx10", v.Decision.Provider)
assert.Equal(t, "/v1/decide", v.Decision.Path)
require.Len(t, v.Stats.DecisionOutcomes, len(routerDecisionOutcomes))
for i, name := range routerDecisionOutcomes {
assert.Equal(t, name, v.Stats.DecisionOutcomes[i].Name)
}
counts := map[string]int64{}
for _, row := range v.Stats.DecisionOutcomes {
counts[row.Name] = row.Count
}
assert.EqualValues(t, 1, counts[decisionOverride])
assert.EqualValues(t, 1, counts[decisionTimeout])
assert.EqualValues(t, 0, counts[decisionAgree])
assert.Equal(t, []adminRouterDecisionTierView{{Heuristic: "ta", Model: "tc", Count: 1}}, v.Stats.Decision)
f.rt.decision.live = false
assert.Equal(t, "shadow", f.g.buildAdminRouterViews()[0].Decision.Mode)
}
func TestAdminRouterWithoutDecisionOmitsView(t *testing.T) {
gw, _ := planTestGateway(t, nil)
v := gw.buildAdminRouterViews()[0]
assert.Nil(t, v.Decision)
assert.Empty(t, v.Stats.DecisionOutcomes)
assert.NotNil(t, v.Stats.DecisionOutcomes)
assert.NotNil(t, v.Stats.Decision)
}
func TestRouterDecisionKeysNoText(t *testing.T) {
k := routerDecisionKeyFor(routerDecisionKey{router: "r", outcome: decisionOverride}, "b")
assert.Contains(t, k, metricRouterDec+routerKeySep+decisionOverride)
m := routerDecisionTierKeyFor(routerDecisionTierKey{router: "r", heuristic: "mid", model: "top"}, "b")
assert.Contains(t, m, metricRouterDmx+routerKeySep+"mid"+routerKeySep+"top")
assert.False(t, strings.Contains(k+m, "hello"))
}
func TestPlanSmartRouterDecisionLiveOverride(t *testing.T) {
f := newDecisionFixture(t, 3, "", okHandler)
f.rt.decision.live = true
f.rt.decision.band = 1000
f.g.cfg.Metrics = &MetricsConfig{Enabled: true}
plan, err := f.g.planSmartRouter(context.Background(), f.rt, userReq("hello"), cacheEndpointChat, nil, &group{}, nil)
require.NoError(t, err)
assert.Equal(t, smartReasonModel, plan.reason)
assert.Equal(t, decisionOverride, plan.decisionOutcome)
assert.Equal(t, "ta", plan.heuristicTier)
assert.Equal(t, "tc", plan.decisionTier)
assert.Equal(t, "tb", plan.startTier)
f.g.recordRouterAttempt(plan, 0, cacheEndpointChat, nil)
dec, tiers := f.g.routerStats.decisionSnapshot()
assert.EqualValues(t, 1, dec[routerDecisionKey{router: "auto", outcome: decisionOverride}])
assert.EqualValues(t, 1, tiers[routerDecisionTierKey{router: "auto", heuristic: "ta", model: "tc"}])
}
+121
View File
@@ -32,6 +32,16 @@ type routerShadowKey struct {
router, live, shadow string
}
// routerDecisionKey counts decision-model calls by outcome.
type routerDecisionKey struct {
router, outcome string
}
// routerDecisionTierKey counts model answers by the heuristic tier and the tier the model ranked.
type routerDecisionTierKey struct {
router, heuristic, model string
}
// routerOutcomeKey counts finished requests by first attempted tier, routing reason and outcome.
type routerOutcomeKey struct {
router, tier, reason, outcome string
@@ -56,6 +66,8 @@ type routerStats struct {
escalations map[routerEscalationKey]int64
shadow map[routerShadowKey]int64
outcomes map[routerOutcomeKey]int64
decisions map[routerDecisionKey]int64
decisionMx map[routerDecisionTierKey]int64
mu sync.Mutex
}
@@ -65,9 +77,47 @@ func newRouterStats() *routerStats {
escalations: make(map[routerEscalationKey]int64),
shadow: make(map[routerShadowKey]int64),
outcomes: make(map[routerOutcomeKey]int64),
decisions: make(map[routerDecisionKey]int64),
decisionMx: make(map[routerDecisionTierKey]int64),
}
}
func (s *routerStats) addDecision(k routerDecisionKey) {
if s == nil {
return
}
s.mu.Lock()
s.decisions[k]++
s.mu.Unlock()
}
func (s *routerStats) addDecisionTier(k routerDecisionTierKey) {
if s == nil {
return
}
s.mu.Lock()
s.decisionMx[k]++
s.mu.Unlock()
}
// decisionSnapshot copies the decision outcome and tier-matrix counters.
func (s *routerStats) decisionSnapshot() (map[routerDecisionKey]int64, map[routerDecisionTierKey]int64) {
dec := make(map[routerDecisionKey]int64)
mx := make(map[routerDecisionTierKey]int64)
if s == nil {
return dec, mx
}
s.mu.Lock()
defer s.mu.Unlock()
for k, v := range s.decisions {
dec[k] = v
}
for k, v := range s.decisionMx {
mx[k] = v
}
return dec, mx
}
func (s *routerStats) addShadow(k routerShadowKey) {
if s == nil {
return
@@ -168,6 +218,7 @@ func (g *Gateway) recordRouterAttempt(plan *routerPlan, i int, endpoint string,
}
g.countRouterShared(func(bucket string) string { return routerShadowKeyFor(sk, bucket) })
}
g.recordRouterDecision(plan)
return
}
if i == plan.fallbackAt {
@@ -242,6 +293,31 @@ func (g *Gateway) recordRouterEventKind(plan *routerPlan, i int, endpoint string
g.recordEvent(ev)
}
// recordRouterDecision counts the decision-model outcome and, for answered calls, the heuristic-vs-model tier pair.
func (g *Gateway) recordRouterDecision(plan *routerPlan) {
if plan.decisionOutcome == "" {
return
}
dk := routerDecisionKey{router: plan.router, outcome: plan.decisionOutcome}
if metricsEnabled(g.cfg) {
g.routerStats.addDecision(dk)
}
g.countRouterShared(func(bucket string) string { return routerDecisionKeyFor(dk, bucket) })
if !decisionAnswered(plan.decisionOutcome) || plan.heuristicTier == "" || plan.decisionTier == "" {
return
}
mk := routerDecisionTierKey{router: plan.router, heuristic: plan.heuristicTier, model: plan.decisionTier}
if metricsEnabled(g.cfg) {
g.routerStats.addDecisionTier(mk)
}
g.countRouterShared(func(bucket string) string { return routerDecisionTierKeyFor(mk, bucket) })
}
// decisionAnswered reports whether the outcome carries a model rank.
func decisionAnswered(outcome string) bool {
return outcome == decisionAgree || outcome == decisionOverride || outcome == decisionLowConf || outcome == decisionCache
}
// writeRouterMetrics emits the router counter families; absent until the first observation.
func (g *Gateway) writeRouterMetrics(m *metricWriter) {
g.writeRouterCalibrationMetrics(m)
@@ -268,6 +344,7 @@ func (g *Gateway) writeRouterMetrics(m *metricWriter) {
[]metricLabel{{"router", k.router}, {"tier", k.tier}, {"reason", k.reason}}, reqs[k])
}
}
g.writeRouterDecisionMetrics(m)
if len(escs) > 0 {
keys := make([]routerEscalationKey, 0, len(escs))
for k := range escs {
@@ -291,3 +368,47 @@ func (g *Gateway) writeRouterMetrics(m *metricWriter) {
}
}
}
func (g *Gateway) writeRouterDecisionMetrics(m *metricWriter) {
dec, mx := g.routerStats.decisionSnapshot()
if len(dec) > 0 {
keys := make([]routerDecisionKey, 0, len(dec))
for k := range dec {
keys = append(keys, k)
}
sort.Slice(keys, func(a, b int) bool {
if keys[a].router != keys[b].router {
return keys[a].router < keys[b].router
}
return keys[a].outcome < keys[b].outcome
})
m.family("llmgateway_router_decision_total", "counter",
"Smart router decision-model calls by router and outcome (agree, override, lowconf, timeout, error, breaker, cache)."+aggregationNotePerProcess)
for _, k := range keys {
m.sampleInt("llmgateway_router_decision_total",
[]metricLabel{{"router", k.router}, {"outcome", k.outcome}}, dec[k])
}
}
if len(mx) > 0 {
keys := make([]routerDecisionTierKey, 0, len(mx))
for k := range mx {
keys = append(keys, k)
}
sort.Slice(keys, func(a, b int) bool {
x, y := keys[a], keys[b]
if x.router != y.router {
return x.router < y.router
}
if x.heuristic != y.heuristic {
return x.heuristic < y.heuristic
}
return x.model < y.model
})
m.family("llmgateway_router_decision_tiers_total", "counter",
"Smart router answers from the decision model or its cache by router, heuristic tier and model-ranked tier."+aggregationNotePerProcess)
for _, k := range keys {
m.sampleInt("llmgateway_router_decision_tiers_total",
[]metricLabel{{"router", k.router}, {"heuristic", k.heuristic}, {"model", k.model}}, mx[k])
}
}
}
+51 -8
View File
@@ -11,6 +11,8 @@ const (
metricRouterEsc = "resc"
metricRouterShd = "rshd"
metricRouterOut = "rout"
metricRouterDec = "rdec"
metricRouterDmx = "rdmx"
routerKeySep = "/"
routerReasonsMax = 11
)
@@ -29,6 +31,14 @@ func routerShadowKeyFor(k routerShadowKey, bucket string) string {
return windowKeyForBucket(kindRouter, k.router, metricRouterShd+routerKeySep+k.live+routerKeySep+k.shadow, windowMonth, bucket)
}
func routerDecisionKeyFor(k routerDecisionKey, bucket string) string {
return windowKeyForBucket(kindRouter, k.router, metricRouterDec+routerKeySep+k.outcome, windowMonth, bucket)
}
func routerDecisionTierKeyFor(k routerDecisionTierKey, bucket string) string {
return windowKeyForBucket(kindRouter, k.router, metricRouterDmx+routerKeySep+k.heuristic+routerKeySep+k.model, windowMonth, bucket)
}
func routerOutcomeKeyFor(k routerOutcomeKey, bucket string) string {
return windowKeyForBucket(kindRouter, k.router, metricRouterOut+routerKeySep+k.tier+routerKeySep+k.reason+routerKeySep+k.outcome, windowMonth, bucket)
}
@@ -53,6 +63,8 @@ type routerCounters struct {
escs map[routerEscalationKey]int64
shadow map[routerShadowKey]int64
outcomes map[routerOutcomeKey]int64
decs map[routerDecisionKey]int64
decMx map[routerDecisionTierKey]int64
scope string
}
@@ -66,7 +78,8 @@ func (g *Gateway) routerStatsSnapshot(now time.Time) routerCounters {
}
reqs, escs := g.routerStats.snapshot()
shadow, outcomes := g.routerStats.extraSnapshot()
return routerCounters{reqs: reqs, escs: escs, shadow: shadow, outcomes: outcomes, scope: statsScopeInstance}
decs, decMx := g.routerStats.decisionSnapshot()
return routerCounters{reqs: reqs, escs: escs, shadow: shadow, outcomes: outcomes, decs: decs, decMx: decMx, scope: statsScopeInstance}
}
// readRouterShared reads every config-derived key in one chunked round trip; ok is false on any store failure.
@@ -76,7 +89,9 @@ func (g *Gateway) readRouterShared(now time.Time) (routerCounters, bool) {
var escKeys []routerEscalationKey
var shdKeys []routerShadowKey
var outKeys []routerOutcomeKey
var reqNames, escNames, outNames, shdNames []string
var decKeys []routerDecisionKey
var dmxKeys []routerDecisionTierKey
var reqNames, escNames, outNames, shdNames, decNames, dmxNames []string
for _, rt := range g.registry.routers {
for _, t := range rt.tiers {
for _, reason := range routerReasonNames {
@@ -99,22 +114,38 @@ func (g *Gateway) readRouterShared(now time.Time) (routerCounters, bool) {
outNames = append(outNames, routerOutcomeKeyFor(k, bucket))
}
}
if !rt.shadowEnabled() {
continue
if rt.shadowEnabled() {
for _, to := range rt.tiers {
k := routerShadowKey{router: rt.name, live: t.name, shadow: to.name}
shdKeys = append(shdKeys, k)
shdNames = append(shdNames, routerShadowKeyFor(k, bucket))
}
}
for _, to := range rt.tiers {
k := routerShadowKey{router: rt.name, live: t.name, shadow: to.name}
shdKeys = append(shdKeys, k)
shdNames = append(shdNames, routerShadowKeyFor(k, bucket))
if rt.decision != nil {
for _, to := range rt.tiers {
k := routerDecisionTierKey{router: rt.name, heuristic: t.name, model: to.name}
dmxKeys = append(dmxKeys, k)
dmxNames = append(dmxNames, routerDecisionTierKeyFor(k, bucket))
}
}
}
if rt.decision != nil {
for _, outcome := range routerDecisionOutcomes {
k := routerDecisionKey{router: rt.name, outcome: outcome}
decKeys = append(decKeys, k)
decNames = append(decNames, routerDecisionKeyFor(k, bucket))
}
}
}
names := append(append(append(reqNames, escNames...), outNames...), shdNames...)
names = append(append(names, decNames...), dmxNames...)
c := routerCounters{
reqs: make(map[routerRequestKey]int64),
escs: make(map[routerEscalationKey]int64),
shadow: make(map[routerShadowKey]int64),
outcomes: make(map[routerOutcomeKey]int64),
decs: make(map[routerDecisionKey]int64),
decMx: make(map[routerDecisionTierKey]int64),
}
if len(names) == 0 {
return c, true
@@ -148,5 +179,17 @@ func (g *Gateway) readRouterShared(now time.Time) (routerCounters, bool) {
}
pos++
}
for _, k := range decKeys {
if vals[pos] > 0 {
c.decs[k] = vals[pos]
}
pos++
}
for _, k := range dmxKeys {
if vals[pos] > 0 {
c.decMx[k] = vals[pos]
}
pos++
}
return c, true
}