feat(router): decision model client with breaker and cache

This commit is contained in:
2026-11-25 13:39:45 +00:00
parent 266ce22e72
commit 73fc53a29b
2 changed files with 585 additions and 0 deletions
+273
View File
@@ -1,9 +1,17 @@
package traefikllmgateway
import (
"container/list"
"context"
"encoding/json"
"fmt"
"hash/fnv"
"io"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
)
@@ -19,8 +27,26 @@ const (
defaultDecisionMinProb = 700
defaultDecisionBand = 100
maxDecisionPerMille = 1000
decisionSystemCap = 1024
decisionAskCap = 8192
decisionBodyLimit = 64 << 10
decisionCacheSize = 1024
decisionCacheTTL = 10 * time.Minute
decisionBreakerFails = 3
decisionBreakerOpen = 30 * time.Second
decisionAgree = "agree"
decisionOverride = "override"
decisionLowConf = "lowconf"
decisionTimeout = "timeout"
decisionError = "error"
decisionBreaker = "breaker"
decisionCache = "cache"
)
var routerDecisionOutcomes = [...]string{decisionAgree, decisionOverride, decisionLowConf, decisionTimeout, decisionError, decisionBreaker, decisionCache}
// SmartRouterDecisionConfig asks a THX-02 decision model to settle requests whose
// classifier score sits near a tier boundary. It needs classifier v2 and is off when absent.
type SmartRouterDecisionConfig struct {
@@ -40,6 +66,7 @@ type SmartRouterDecisionConfig struct {
// smartDecisionCfg is a validated SmartRouterDecisionConfig with defaults applied.
type smartDecisionCfg struct {
dec *smartDecider
provider string
path string
timeout time.Duration
@@ -57,6 +84,7 @@ func compileSmartDecision(router string, cfg *SmartRouterDecisionConfig, classif
timeout: defaultDecisionTimeout,
minProb: defaultDecisionMinProb,
band: defaultDecisionBand,
dec: newSmartDecider(time.Now),
}
switch cfg.Mode {
case "", smartDecisionShadow:
@@ -126,3 +154,248 @@ func validateRouterDecisions(routers map[string]*smartRouter, cfg *Config) error
}
return nil
}
type decisionCacheEntry struct {
expires time.Time
key uint64
rank int
prob int
}
// smartDecider holds the breaker and answer cache shared by every request of one router.
type smartDecider struct {
now func() time.Time
items map[uint64]*list.Element
order *list.List
openUntil time.Time
mu sync.Mutex
fails int
}
func newSmartDecider(nowFn func() time.Time) *smartDecider {
return &smartDecider{now: nowFn, items: make(map[uint64]*list.Element), order: list.New()}
}
func (d *smartDecider) cacheLen() int {
d.mu.Lock()
defer d.mu.Unlock()
return d.order.Len()
}
func (d *smartDecider) cacheGet(key uint64) (int, int, bool) {
d.mu.Lock()
defer d.mu.Unlock()
el, ok := d.items[key]
if !ok {
return 0, 0, false
}
entry, _ := el.Value.(*decisionCacheEntry)
if !d.now().Before(entry.expires) {
delete(d.items, key)
d.order.Remove(el)
return 0, 0, false
}
d.order.MoveToFront(el)
return entry.rank, entry.prob, true
}
func (d *smartDecider) cachePut(key uint64, rank, prob int) {
d.mu.Lock()
defer d.mu.Unlock()
exp := d.now().Add(decisionCacheTTL)
if el, ok := d.items[key]; ok {
entry, _ := el.Value.(*decisionCacheEntry)
entry.rank, entry.prob, entry.expires = rank, prob, exp
d.order.MoveToFront(el)
return
}
d.items[key] = d.order.PushFront(&decisionCacheEntry{key: key, rank: rank, prob: prob, expires: exp})
for d.order.Len() > decisionCacheSize {
oldest := d.order.Back()
entry, _ := oldest.Value.(*decisionCacheEntry)
delete(d.items, entry.key)
d.order.Remove(oldest)
}
}
func (d *smartDecider) breakerOpen() bool {
d.mu.Lock()
defer d.mu.Unlock()
return d.now().Before(d.openUntil)
}
// record counts one call result; a failure at the threshold opens the breaker.
func (d *smartDecider) record(success bool) {
d.mu.Lock()
defer d.mu.Unlock()
if success {
d.fails = 0
return
}
d.fails++
if d.fails >= decisionBreakerFails {
d.openUntil = d.now().Add(decisionBreakerOpen)
}
}
// decisionAnswer is one decision-model result; outcome is empty for a fresh answer.
type decisionAnswer struct {
outcome string
rank int
prob int
}
type decisionQuestion struct {
Type string `json:"type"`
Instructions string `json:"instructions"`
Criteria []string `json:"criteria"`
}
type decisionRequest struct {
Questions map[string]decisionQuestion `json:"questions"`
State string `json:"state"`
}
type decisionTierAnswer struct {
Probabilities map[string]float64 `json:"probabilities"`
}
type decisionResponse struct {
Answers map[string]decisionTierAnswer `json:"answers"`
}
// decisionState is the text the decision model sees and the cache key source.
func decisionState(system, ask string) string {
if len(ask) > decisionAskCap {
ask = ask[:decisionAskCap]
}
if system == "" {
return ask
}
if len(system) > decisionSystemCap {
system = system[:decisionSystemCap]
}
return system + "\n\n" + ask
}
func decisionRequestBody(rt *smartRouter, state string) []byte {
names := make([]string, len(rt.tiers))
for i, t := range rt.tiers {
names[i] = t.name
}
req := decisionRequest{
State: state,
Questions: map[string]decisionQuestion{"tier": {
Type: "score",
Instructions: "Pick the cheapest tier whose model can answer this request well. Tiers run from cheapest and weakest to strongest: " + strings.Join(names, ", ") + ".",
Criteria: names,
}},
}
b, err := json.Marshal(req)
if err != nil {
return nil
}
return b
}
// decodeDecisionAnswer returns the argmax tier and its per-mille probability.
func decodeDecisionAnswer(body []byte, tiers int) (int, int, bool) {
var resp decisionResponse
if err := json.Unmarshal(body, &resp); err != nil {
return 0, 0, false
}
probs := resp.Answers["tier"].Probabilities
if len(probs) == 0 {
return 0, 0, false
}
for k := range probs {
i, err := strconv.Atoi(k)
if err != nil || i < 0 || i >= tiers {
return 0, 0, false
}
}
best, bestP := -1, -1.0
for i := 0; i < tiers; i++ {
p, present := probs[strconv.Itoa(i)]
if !present {
continue
}
if p < 0 || p > 1 {
return 0, 0, false
}
if p > bestP {
best, bestP = i, p
}
}
if best < 0 {
return 0, 0, false
}
return best, int(bestP*1000 + 0.5), true
}
// askDecisionModel returns the cached answer, else calls the decision model unless the breaker is open.
func (g *Gateway) askDecisionModel(ctx context.Context, rt *smartRouter, state string) decisionAnswer {
cfg := rt.decision
h := fnv.New64a()
_, _ = h.Write([]byte(state))
key := h.Sum64()
if rank, prob, ok := cfg.dec.cacheGet(key); ok {
return decisionAnswer{outcome: decisionCache, rank: rank, prob: prob}
}
if cfg.dec.breakerOpen() {
return decisionAnswer{outcome: decisionBreaker}
}
rank, prob, outcome := g.callDecisionModel(ctx, rt, state)
if outcome != "" {
cfg.dec.record(false)
return decisionAnswer{outcome: outcome}
}
cfg.dec.record(true)
cfg.dec.cachePut(key, rank, prob)
return decisionAnswer{rank: rank, prob: prob}
}
// callDecisionModel returns the decoded answer, or an outcome of timeout or error.
func (g *Gateway) callDecisionModel(ctx context.Context, rt *smartRouter, state string) (int, int, string) {
cfg := rt.decision
oa, isOpenAI := g.adapters[cfg.provider].(*openaiAdapter)
if !isOpenAI {
return 0, 0, decisionError
}
body := decisionRequestBody(rt, state)
if body == nil {
return 0, 0, decisionError
}
callCtx, cancel := context.WithTimeout(ctx, cfg.timeout)
defer cancel()
probe := &http.Request{Header: http.Header{}}
oa.injectAuth(probe)
probe.Header.Set("Content-Type", "application/json")
url := oa.passthroughBase("", cfg.path) + cfg.path
// The watchdog gets a longer budget so callCtx's deadline decides the timeout outcome.
resp, err := upstreamBytes(callCtx, oa.httpClient(), http.MethodPost, url, probe.Header, body, nil, 2*cfg.timeout, cfg.provider)
if err != nil {
return 0, 0, decisionFailure(ctx, callCtx)
}
defer func() { _ = resp.Body.Close() }()
data, err := io.ReadAll(io.LimitReader(resp.Body, decisionBodyLimit))
if err != nil {
return 0, 0, decisionFailure(ctx, callCtx)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return 0, 0, decisionError
}
rank, prob, ok := decodeDecisionAnswer(data, len(rt.tiers))
if !ok {
return 0, 0, decisionError
}
return rank, prob, ""
}
// decisionFailure maps a failed call to timeout when only the derived deadline expired.
func decisionFailure(parent, call context.Context) string {
if parent.Err() == nil && call.Err() == context.DeadlineExceeded {
return decisionTimeout
}
return decisionError
}
+312
View File
@@ -1,7 +1,16 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
@@ -134,3 +143,306 @@ func TestCompileSmartRouterDecisionWiring(t *testing.T) {
t.Fatalf("absent decision must stay off: %v", err)
}
}
type decisionFixture struct {
g *Gateway
rt *smartRouter
clk *decisionClock
hits *int64
}
type decisionClock struct {
t time.Time
mu sync.Mutex
}
func (c *decisionClock) now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.t
}
func (c *decisionClock) advance(d time.Duration) {
c.mu.Lock()
c.t = c.t.Add(d)
c.mu.Unlock()
}
const decisionOKBody = `{"model":"THX-02","answers":{"tier":{"type":"score","probabilities":{"0":0.1,"1":0.15,"2":0.75}}},"latency_ms":5}`
// newDecisionFixture builds a gateway whose "gx10" provider serves /v1/decide from handler.
func newDecisionFixture(t *testing.T, tierCount int, timeout string, handler http.HandlerFunc) *decisionFixture {
t.Helper()
var hits int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&hits, 1)
handler(w, r)
}))
t.Cleanup(srv.Close)
tiers := make([]SmartRouterTier, tierCount)
models := make([]string, tierCount)
for i := range tiers {
models[i] = "m" + string(rune('0'+i))
tiers[i] = SmartRouterTier{Name: "t" + string(rune('a'+i)), MinScore: i * 250, Models: []string{models[i]}}
}
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{
"gx10": {Type: "openai", BaseURL: srv.URL, APIKey: "k", Models: models, PathBaseURLs: map[string]string{"/v1/decide": srv.URL}},
}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
cfg.SmartRouters = map[string]*SmartRouterConfig{"auto": {
Tiers: tiers,
Classifier: smartClassifierV2,
Decision: &SmartRouterDecisionConfig{Provider: "gx10", Timeout: timeout},
}}
_, g := buildRouterGateway(t, cfg)
rt := g.registry.routers["auto"]
if rt == nil || rt.decision == nil {
t.Fatal("router or decision missing")
}
clk := &decisionClock{t: time.Unix(1_700_000_000, 0)}
rt.decision.dec = newSmartDecider(clk.now)
return &decisionFixture{g: g, rt: rt, clk: clk, hits: &hits}
}
func (f *decisionFixture) hitCount() int64 { return atomic.LoadInt64(f.hits) }
func okHandler(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, decisionOKBody)
}
func TestRouterDecisionRequestBody(t *testing.T) {
for _, n := range []int{2, 4} {
f := newDecisionFixture(t, n, "", okHandler)
var got decisionRequest
if err := json.Unmarshal(decisionRequestBody(f.rt, "hello"), &got); err != nil {
t.Fatal(err)
}
names := make([]string, n)
for i, tr := range f.rt.tiers {
names[i] = tr.name
}
q := got.Questions["tier"]
if q.Type != "score" || got.State != "hello" || !reflect.DeepEqual(q.Criteria, names) {
t.Fatalf("n=%d body wrong: %+v", n, got)
}
want := "Pick the cheapest tier whose model can answer this request well. Tiers run from cheapest and weakest to strongest: " + strings.Join(names, ", ") + "."
if q.Instructions != want {
t.Fatalf("instructions %q", q.Instructions)
}
}
}
func TestRouterDecisionDecode(t *testing.T) {
tests := []struct {
name string
body string
tiers int
rank int
prob int
wantOK bool
}{
{"argmax", `{"answers":{"tier":{"probabilities":{"0":0.1,"1":0.15,"2":0.75}}}}`, 3, 2, 750, true},
{"rounds per mille", `{"answers":{"tier":{"probabilities":{"0":0.9235,"1":0.0765}}}}`, 2, 0, 924, true},
{"missing answers", `{"model":"THX-02"}`, 3, 0, 0, false},
{"key out of range", `{"answers":{"tier":{"probabilities":{"0":0.1,"3":0.9}}}}`, 3, 0, 0, false},
{"non json", `not json`, 3, 0, 0, false},
{"empty map", `{"answers":{"tier":{"probabilities":{}}}}`, 3, 0, 0, false},
{"error envelope", `{"error":"bad"}`, 3, 0, 0, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rank, prob, ok := decodeDecisionAnswer([]byte(tt.body), tt.tiers)
if ok != tt.wantOK || (ok && (rank != tt.rank || prob != tt.prob)) {
t.Fatalf("got (%d,%d,%v)", rank, prob, ok)
}
})
}
}
func TestRouterDecisionState(t *testing.T) {
sys := strings.Repeat("s", 2000)
ask := strings.Repeat("a", 10000)
if got := decisionState(sys, ask); len(got) != 1024+2+8192 {
t.Fatalf("len %d", len(got))
}
if got := decisionState("", ask); got != ask[:8192] {
t.Fatalf("empty system len %d", len(got))
}
}
func TestRouterDecisionStatusErrors(t *testing.T) {
for _, status := range []int{http.StatusBadRequest, http.StatusUnauthorized} {
f := newDecisionFixture(t, 3, "", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(status)
_, _ = io.WriteString(w, `{"error":"nope"}`)
})
if a := f.g.askDecisionModel(context.Background(), f.rt, "s"); a.outcome != decisionError {
t.Fatalf("status %d: outcome %q", status, a.outcome)
}
}
}
func TestRouterDecisionBadBodyIsError(t *testing.T) {
f := newDecisionFixture(t, 3, "", func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, `{}`) })
if a := f.g.askDecisionModel(context.Background(), f.rt, "s"); a.outcome != decisionError {
t.Fatalf("outcome %q", a.outcome)
}
}
func TestRouterDecisionSendsAuthAndPath(t *testing.T) {
var auth, path string
f := newDecisionFixture(t, 3, "", func(w http.ResponseWriter, r *http.Request) {
auth, path = r.Header.Get("Authorization"), r.URL.Path
okHandler(w, r)
})
a := f.g.askDecisionModel(context.Background(), f.rt, "s")
if a.outcome != "" || a.rank != 2 || a.prob != 750 {
t.Fatalf("answer %+v", a)
}
if auth != "Bearer k" || path != "/v1/decide" {
t.Fatalf("auth %q path %q", auth, path)
}
}
func TestRouterDecisionTimeout(t *testing.T) {
f := newDecisionFixture(t, 3, "50ms", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(200 * time.Millisecond):
case <-r.Context().Done():
}
okHandler(w, r)
})
start := time.Now()
a := f.g.askDecisionModel(context.Background(), f.rt, "s")
if a.outcome != decisionTimeout {
t.Fatalf("outcome %q", a.outcome)
}
if el := time.Since(start); el > 150*time.Millisecond {
t.Fatalf("took %s", el)
}
}
func TestRouterDecisionBreaker(t *testing.T) {
var fail atomic.Bool
fail.Store(true)
f := newDecisionFixture(t, 3, "", func(w http.ResponseWriter, r *http.Request) {
if fail.Load() {
w.WriteHeader(http.StatusInternalServerError)
return
}
okHandler(w, r)
})
ctx := context.Background()
ask := func(i int) decisionAnswer { return f.g.askDecisionModel(ctx, f.rt, "s"+strconv.Itoa(i)) }
for i := 0; i < 3; i++ {
if a := ask(i); a.outcome != decisionError {
t.Fatalf("call %d outcome %q", i, a.outcome)
}
}
if a := ask(3); a.outcome != decisionBreaker || f.hitCount() != 3 {
t.Fatalf("outcome %q hits %d", a.outcome, f.hitCount())
}
f.clk.advance(30 * time.Second)
fail.Store(false)
if a := ask(4); a.outcome != "" || f.hitCount() != 4 {
t.Fatalf("after reopen: outcome %q hits %d", a.outcome, f.hitCount())
}
// A success resets the count: two failures then no trip.
fail.Store(true)
ask(5)
ask(6)
fail.Store(false)
ask(7)
fail.Store(true)
ask(8)
ask(9)
if a := ask(10); a.outcome == decisionBreaker {
t.Fatal("breaker tripped although a success reset the count")
}
}
func TestRouterDecisionCache(t *testing.T) {
f := newDecisionFixture(t, 3, "", okHandler)
ctx := context.Background()
first := f.g.askDecisionModel(ctx, f.rt, "same")
second := f.g.askDecisionModel(ctx, f.rt, "same")
if first.outcome != "" || second.outcome != decisionCache || second.rank != first.rank || second.prob != first.prob || f.hitCount() != 1 {
t.Fatalf("first %+v second %+v hits %d", first, second, f.hitCount())
}
f.clk.advance(10*time.Minute + time.Second)
if a := f.g.askDecisionModel(ctx, f.rt, "same"); a.outcome != "" || f.hitCount() != 2 {
t.Fatalf("after ttl: %+v hits %d", a, f.hitCount())
}
for i := 0; i < 1100; i++ {
f.g.askDecisionModel(ctx, f.rt, "state-"+strconv.Itoa(i))
}
if n := f.rt.decision.dec.cacheLen(); n > 1024 {
t.Fatalf("cache size %d", n)
}
}
func TestRouterDecisionCacheServedWhileBreakerOpen(t *testing.T) {
var fail atomic.Bool
f := newDecisionFixture(t, 3, "", func(w http.ResponseWriter, r *http.Request) {
if fail.Load() {
w.WriteHeader(http.StatusInternalServerError)
return
}
okHandler(w, r)
})
ctx := context.Background()
f.g.askDecisionModel(ctx, f.rt, "warm")
fail.Store(true)
for i := 0; i < 3; i++ {
f.g.askDecisionModel(ctx, f.rt, "cold"+strconv.Itoa(i))
}
if a := f.g.askDecisionModel(ctx, f.rt, "warm"); a.outcome != decisionCache {
t.Fatalf("outcome %q", a.outcome)
}
}
func TestRouterDecisionContextCancel(t *testing.T) {
f := newDecisionFixture(t, 3, "", func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
})
ctx, cancel := context.WithCancel(context.Background())
cancel()
done := make(chan decisionAnswer, 1)
go func() { done <- f.g.askDecisionModel(ctx, f.rt, "s") }()
select {
case a := <-done:
if a.outcome != decisionTimeout && a.outcome != decisionError {
t.Fatalf("outcome %q", a.outcome)
}
case <-time.After(time.Second):
t.Fatal("hung")
}
}
func TestRouterDecisionConcurrent(t *testing.T) {
f := newDecisionFixture(t, 3, "", okHandler)
var wg sync.WaitGroup
for i := 0; i < 16; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
f.g.askDecisionModel(context.Background(), f.rt, "s"+strconv.Itoa(i%4))
}(i)
}
wg.Wait()
}
func TestRouterDecisionOutcomeNames(t *testing.T) {
seen := map[string]bool{}
for _, o := range routerDecisionOutcomes {
if o == "" || seen[o] {
t.Fatalf("bad outcome %q", o)
}
seen[o] = true
}
if len(seen) != 7 {
t.Fatalf("got %d outcomes", len(seen))
}
}