From 590a23750b03a6d7167e60c452917884367a3f59 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 03:15:12 +0000 Subject: [PATCH] feat(redis): shared breaker and in-flight primitives Add sharedStateLoop, sharedBreaker and sharedInflight. One loop per gateway refreshes every primitive from the store once per second, so request paths read local copies only. A store error keeps the last values, and three failed refreshes make shared values absent. Add the redis.sharedState switch. It defaults off, and it needs redis.address. With it off, no shared keys are read or written. --- admin_config_guard_test.go | 2 +- llmgateway.go | 24 +- shared_state.go | 577 ++++++++++++++++++++++++++++++++++++ shared_state_test.go | 583 +++++++++++++++++++++++++++++++++++++ 4 files changed, 1181 insertions(+), 5 deletions(-) create mode 100644 shared_state.go create mode 100644 shared_state_test.go diff --git a/admin_config_guard_test.go b/admin_config_guard_test.go index 06a69a9..b3b40d1 100644 --- a/admin_config_guard_test.go +++ b/admin_config_guard_test.go @@ -16,7 +16,7 @@ var nonSecretConfigKeys = map[string]bool{ "openDuration": true, "passthroughPaths": true, "path": true, "pathBaseUrls": true, "probeInterval": true, "providers": true, "requestTimeout": true, "ttl": true, "type": true, - "cachedInputPerM": true, "cacheWritePerM": true, "defaultTier": true, "toolsMinTier": true, "classifier": true, "shadowClassifier": true, "intentTiers": true, "keywords": true, "selection": true, "tier": true, "header": true, "mode": true, "firstByteTimeout": true, "provider": true, "timeout": true, + "cachedInputPerM": true, "cacheWritePerM": true, "defaultTier": true, "toolsMinTier": true, "classifier": true, "shadowClassifier": true, "intentTiers": true, "keywords": true, "selection": true, "tier": true, "header": true, "mode": true, "firstByteTimeout": true, "provider": true, "timeout": true, "sharedState": true, } func collectStringKeys(t reflect.Type, seen map[reflect.Type]bool, out map[string]bool) { diff --git a/llmgateway.go b/llmgateway.go index e690344..ad9ff5f 100644 --- a/llmgateway.go +++ b/llmgateway.go @@ -447,10 +447,13 @@ type UserConfig struct { // RedisConfig configures the distributed limit-state backend. type RedisConfig struct { - FailOpen *bool `json:"failOpen,omitempty"` - Address string `json:"address"` - Password string `json:"password,omitempty"` - DB int `json:"db,omitempty"` + FailOpen *bool `json:"failOpen,omitempty"` + // SharedState shares circuit-breaker and in-flight state across gateway + // instances through Redis. nil and false both mean off. + SharedState *bool `json:"sharedState,omitempty"` + Address string `json:"address"` + Password string `json:"password,omitempty"` + DB int `json:"db,omitempty"` // PoolSize overrides respClient's self-tuned connection pool size // (defaultRespPoolSize, resp.go: GOMAXPROCS clamped to [4, 8]) — perf // finding 1, 2026-08-2x audit. Left at 0 (the default), the pool @@ -870,6 +873,7 @@ type Gateway struct { promptCacheStats promptCacheStats routerSessions *routerSessions routerLearn *routerLearner + sharedState *sharedStateLoop tokenCalib *smartTokenCalibrator name string replica string @@ -996,6 +1000,7 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h // plugin a way to do better. func (g *Gateway) Close() error { g.closeRouterLearning() + g.sharedState.close() if g.redisClient == nil { return nil } @@ -1184,6 +1189,9 @@ func newGateway(ctx context.Context, next http.Handler, config *Config, name str // limiter's redisStore (one connection, one config)". Building it // separately per consumer would dial (and AUTH/SELECT) a second TCP // connection to the exact same server for no benefit. + if config.Redis != nil && config.Redis.SharedState != nil && *config.Redis.SharedState && config.Redis.Address == "" { + return nil, errors.New("llmgateway: redis: sharedState requires redis.address") + } redisClient, err := buildRedisClient(config.Redis) if err != nil { return nil, err @@ -1192,6 +1200,9 @@ func newGateway(ctx context.Context, next http.Handler, config *Config, name str lim := newConfiguredLimiter(config, redisClient) lim.logf = g.errorf g.limiter = lim + if sharedStateEnabled(config.Redis) { + g.sharedState = newSharedStateLoop(lim.store, lim.spawn, g.errorf) + } // events (F3, v0.3 dashboard task): built here, after redisClient/ // limiter both exist — shares the SAME respClient (spec §2, above) // and reuses the limiter's own bounded spawn (limits.go's @@ -1343,6 +1354,11 @@ func reservedRoutePrefix(path string) bool { // one respClient — one dialled connection, one AUTH/SELECT handshake — // between the limiter's redisStore and the response cache (cache.go), // instead of each dialing its own connection to the identical server. +// sharedStateEnabled reports whether redis.sharedState is on. +func sharedStateEnabled(rc *RedisConfig) bool { + return rc != nil && rc.SharedState != nil && *rc.SharedState && rc.Address != "" +} + func buildRedisClient(rc *RedisConfig) (*respClient, error) { if rc == nil { return nil, nil diff --git a/shared_state.go b/shared_state.go new file mode 100644 index 0000000..8ccdbb3 --- /dev/null +++ b/shared_state.go @@ -0,0 +1,577 @@ +package traefikllmgateway + +import ( + "sort" + "strconv" + "sync" + "time" +) + +const ( + sharedStateRefreshInterval = time.Second + // sharedStateIdleStop ends the ticker of a gateway that uses no shared state, such as one a config reload replaced. + sharedStateIdleStop = 10 * time.Minute + // sharedStateMaxFailures is the count of consecutive failed refreshes after which shared values count as absent. + sharedStateMaxFailures = 3 + // sharedStateChunk bounds the keys of one getMulti. + sharedStateChunk = 500 + + sharedBreakerPrefix = "llmgw:brk:" + sharedInflightPrefix = "llmgw:inf:" + + sharedBreakerOpensTTLFactor = 4 + sharedBreakerMaxDoublings = 30 + + sharedInflightEpochSecs = 300 + sharedInflightEpoch = 5 * time.Minute + sharedInflightLimitTTL = 10 * time.Minute +) + +// sharedPrimitive is a state that reads a fixed key set from the store on every refresh. +type sharedPrimitive interface { + keys(now time.Time) []string + // apply hands over the values of keys in order; nil means shared values are absent. + apply(vals []int64) +} + +// sharedStateLoop refreshes every registered primitive from the store in the background, so request paths read local copies only. +type sharedStateLoop struct { + store counterStore + nowFn func() time.Time + logf func(string, ...any) + // lossy runs best-effort writes and may drop them under pressure. + lossy func(func()) + // sure runs writes that must not be dropped. + sure func(func()) + lastUse time.Time + stop chan struct{} + done chan struct{} + prims []sharedPrimitive + every time.Duration + failures int + mu sync.Mutex + running bool + closed bool +} + +// newSharedStateLoop returns a loop over store; lossy is the droppable write spawn (the limiter's). +func newSharedStateLoop(store counterStore, lossy func(func()), logf func(string, ...any)) *sharedStateLoop { + if logf == nil { + logf = func(string, ...any) {} + } + l := &sharedStateLoop{store: store, nowFn: time.Now, logf: logf, lossy: lossy, every: sharedStateRefreshInterval} + l.sure = func(f func()) { + go func() { //nolint:gosec // G118: in-flight writes must never drop; bounded by request concurrency + defer func() { + if rec := recover(); rec != nil { + logf("shared state write panicked: %v", rec) + } + }() + f() + }() + } + if l.lossy == nil { + l.lossy = l.sure + } + return l +} + +// log forwards to logf; calling the func field directly with two or more variadic args panics under yaegi v0.16.1. +func (l *sharedStateLoop) log(format string, args ...any) { + l.logf(format, args...) +} + +func (l *sharedStateLoop) register(p sharedPrimitive) { + l.mu.Lock() + l.prims = append(l.prims, p) + l.mu.Unlock() +} + +// stale reports whether the last refresh failed and shared values are last-known or absent. +func (l *sharedStateLoop) stale() bool { + l.mu.Lock() + defer l.mu.Unlock() + return l.failures > 0 +} + +// touch notes a use and starts the refresh goroutine if it is not running. A nil loop is a no-op. +func (l *sharedStateLoop) touch() { + if l == nil { + return + } + l.mu.Lock() + l.lastUse = l.nowFn() + start := !l.running && !l.closed + if start { + l.running = true + l.stop = make(chan struct{}) + l.done = make(chan struct{}) + } + stop, done := l.stop, l.done + l.mu.Unlock() + if start { + go l.run(stop, done) //nolint:gosec // G118: bounded by close and sharedStateIdleStop, one goroutine per gateway + } +} + +func (l *sharedStateLoop) run(stop, done chan struct{}) { + // No request goroutine can catch a panic here, and it would end the whole Traefik process. + defer func() { + if rec := recover(); rec != nil { + l.log("shared state refresh panicked: %v", rec) + l.mu.Lock() + l.running = false + l.mu.Unlock() + } + close(done) + }() + l.refresh() + t := time.NewTicker(l.every) + defer t.Stop() + for { + select { + case <-stop: + return + case <-t.C: + l.mu.Lock() + idle := l.nowFn().Sub(l.lastUse) > sharedStateIdleStop + if idle { + l.running = false + } + l.mu.Unlock() + if idle { + l.clearAll() + return + } + l.refresh() + } + } +} + +// close stops the refresh goroutine for good. A nil loop is a no-op. +func (l *sharedStateLoop) close() { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + l.closed = true + if l.running { + l.running = false + close(l.stop) + } +} + +func (l *sharedStateLoop) snapshot() []sharedPrimitive { + l.mu.Lock() + defer l.mu.Unlock() + out := make([]sharedPrimitive, len(l.prims)) + copy(out, l.prims) + return out +} + +func (l *sharedStateLoop) clearAll() { + var none []int64 + for _, p := range l.snapshot() { + p.apply(none) + } +} + +// refresh reads every primitive's keys in chunked getMulti calls and hands each its values. +func (l *sharedStateLoop) refresh() { + prims := l.snapshot() + now := l.nowFn() + var all []string + sizes := make([]int, len(prims)) + for i, p := range prims { + k := p.keys(now) + sizes[i] = len(k) + all = append(all, k...) + } + vals := make([]int64, 0, len(all)) + for off := 0; off < len(all); off += sharedStateChunk { + end := off + sharedStateChunk + if end > len(all) { + end = len(all) + } + got, err := l.store.getMulti(all[off:end]) + if err != nil || len(got) != end-off { + l.refreshFailed(prims, err) + return + } + vals = append(vals, got...) + } + l.mu.Lock() + l.failures = 0 + l.mu.Unlock() + pos := 0 + for i, p := range prims { + p.apply(vals[pos : pos+sizes[i]]) + pos += sizes[i] + } +} + +func (l *sharedStateLoop) refreshFailed(prims []sharedPrimitive, err error) { + l.mu.Lock() + l.failures++ + absent := l.failures >= sharedStateMaxFailures + n := l.failures + l.mu.Unlock() + l.log("shared state refresh failed (%d consecutive): %v", n, err) + if absent { + var none []int64 + for _, p := range prims { + p.apply(none) + } + } +} + +func (l *sharedStateLoop) incrAndGet(e counterIncr) (int64, bool) { + got, _, err := l.store.incrAndGetMulti([]counterIncr{e}, nil) + if err != nil || len(got) != 1 { + l.log("shared state write %q failed: %v", e.key, err) + return 0, false + } + return got[0], true +} + +func (l *sharedStateLoop) write(entries []counterIncr) { + if _, err := l.store.incrMulti(entries); err != nil { + l.log("shared state write of %d keys failed: %v", len(entries), err) + } +} + +func sharedBreakerKey(kind, id, field string) string { + return sharedBreakerPrefix + kind + ":" + id + ":" + field +} + +func sharedInflightKey(provider, suffix string) string { + return sharedInflightPrefix + provider + ":" + suffix +} + +// sharedStateIDs returns the sorted provider ids shared primitives track: configured providers plus each router's decision provider. +func sharedStateIDs(cfg *Config) []string { + seen := make(map[string]bool) + for name := range cfg.Providers { + seen[name] = true + } + for _, r := range cfg.SmartRouters { + if r != nil && r.Decision != nil && r.Decision.Provider != "" { + seen[r.Decision.Provider] = true + } + } + ids := make([]string, 0, len(seen)) + for id := range seen { + ids = append(ids, id) + } + sort.Strings(ids) + return ids +} + +// breakerLocal is one id's local breaker state, mirroring requestHealthState. +type breakerLocal struct { + openUntil time.Time + backoff time.Duration + consecutiveFailures int + open bool +} + +// sharedBreaker is a per-id circuit breaker whose trips are shared fleet-wide through the store. With a nil loop it is purely local. +type sharedBreaker struct { + loop *sharedStateLoop + nowFn func() time.Time + local map[string]*breakerLocal + openUntil map[string]int64 + failsSeen map[string]int64 + kind string + ids []string + openBase time.Duration + openMax time.Duration + failWindow time.Duration + threshold int + mu sync.Mutex +} + +// newSharedBreaker returns a breaker over ids; loop may be nil for a local-only breaker. +func newSharedBreaker(loop *sharedStateLoop, kind string, ids []string, threshold int, openBase, openMax, failWindow time.Duration) *sharedBreaker { + b := &sharedBreaker{ + loop: loop, nowFn: time.Now, kind: kind, ids: ids, + threshold: threshold, openBase: openBase, openMax: openMax, failWindow: failWindow, + local: make(map[string]*breakerLocal), openUntil: make(map[string]int64), failsSeen: make(map[string]int64), + } + if loop != nil { + b.nowFn = loop.nowFn + loop.register(b) + } + return b +} + +// keys lists, per id, the open-until and fail-count keys. +func (b *sharedBreaker) keys(_ time.Time) []string { + out := make([]string, 0, 2*len(b.ids)) + for _, id := range b.ids { + out = append(out, sharedBreakerKey(b.kind, id, "open"), sharedBreakerKey(b.kind, id, "fails")) + } + return out +} + +func (b *sharedBreaker) apply(vals []int64) { + b.mu.Lock() + defer b.mu.Unlock() + for i, id := range b.ids { + if vals == nil { + delete(b.openUntil, id) + delete(b.failsSeen, id) + } else { + b.openUntil[id] = vals[2*i] + b.failsSeen[id] = vals[2*i+1] + } + } +} + +func (b *sharedBreaker) localFor(id string) *breakerLocal { + st, ok := b.local[id] + if !ok { + st = &breakerLocal{} + b.local[id] = st + } + return st +} + +// isOpen reports whether the local or the last-refreshed shared breaker is open. It never calls the store. +func (b *sharedBreaker) isOpen(id string) bool { + b.loop.touch() + b.mu.Lock() + defer b.mu.Unlock() + now := b.nowFn() + if st, ok := b.local[id]; ok && st.open && now.Before(st.openUntil) { + return true + } + return b.openUntil[id] > now.UnixMilli() +} + +// recordFailure updates local state and, in the background, the shared failure count. +func (b *sharedBreaker) recordFailure(id string) { + b.mu.Lock() + b.recordFailureLocal(b.localFor(id), b.nowFn()) + b.mu.Unlock() + if b.loop == nil { + return + } + b.loop.touch() + b.loop.lossy(func() { b.shareFailure(id) }) +} + +// recordFailureLocal is requestHealthTracker.record's failure arm with this breaker's tunables. +func (b *sharedBreaker) recordFailureLocal(st *breakerLocal, now time.Time) { + if st.open && now.Before(st.openUntil) { + return + } + if st.open { + if st.backoff <= 0 { + st.backoff = b.openBase + } else { + st.backoff *= 2 + } + if st.backoff > b.openMax { + st.backoff = b.openMax + } + st.openUntil = now.Add(st.backoff) + return + } + st.consecutiveFailures++ + if st.consecutiveFailures >= b.threshold { + st.open = true + st.backoff = b.openBase + st.openUntil = now.Add(st.backoff) + } +} + +// shareFailure counts one failure fleet-wide; only the instance that reaches the threshold opens the breaker. +func (b *sharedBreaker) shareFailure(id string) { + l := b.loop + fails, ok := l.incrAndGet(counterIncr{key: sharedBreakerKey(b.kind, id, "fails"), delta: 1, ttl: b.failWindow, enforceTTL: b.failWindow}) + if !ok || fails != int64(b.threshold) { + return + } + opensTTL := b.openMax * sharedBreakerOpensTTLFactor + opens, ok := l.incrAndGet(counterIncr{key: sharedBreakerKey(b.kind, id, "opens"), delta: 1, ttl: opensTTL, enforceTTL: opensTTL}) + if !ok { + return + } + dur := b.openDuration(opens) + until := l.nowFn().Add(dur).UnixMilli() + // Resetting fails lets the next threshold failures trip again after the open window. + l.write([]counterIncr{ + {key: sharedBreakerKey(b.kind, id, "open"), delta: until, ttl: dur, enforceTTL: dur, absolute: true}, + {key: sharedBreakerKey(b.kind, id, "fails"), delta: 0, ttl: b.failWindow, enforceTTL: b.failWindow, absolute: true}, + }) +} + +// openDuration is min(openBase << (opens-1), openMax). +func (b *sharedBreaker) openDuration(opens int64) time.Duration { + d := b.openBase + for i := int64(1); i < opens && i <= sharedBreakerMaxDoublings; i++ { + d *= 2 + if d >= b.openMax { + break + } + } + if d > b.openMax { + d = b.openMax + } + return d +} + +// recordSuccess resets local state and, when a failure count may exist in the store, clears it. +func (b *sharedBreaker) recordSuccess(id string) { + b.mu.Lock() + st := b.localFor(id) + dirty := st.consecutiveFailures > 0 || b.failsSeen[id] > 0 + st.open = false + st.consecutiveFailures = 0 + st.backoff = 0 + st.openUntil = time.Time{} + b.mu.Unlock() + if b.loop == nil || !dirty { + return + } + b.loop.touch() + b.loop.lossy(func() { + b.loop.write([]counterIncr{{key: sharedBreakerKey(b.kind, id, "fails"), delta: 0, ttl: b.failWindow, enforceTTL: b.failWindow, absolute: true}}) + }) + b.mu.Lock() + b.failsSeen[id] = 0 + b.mu.Unlock() +} + +// sharedInflight counts in-flight requests per provider fleet-wide with epoch-bucketed started/finished counters, so a crashed pod's leak ages out. +type sharedInflight struct { + loop *sharedStateLoop + nowFn func() time.Time + counts map[string]int + limits map[string]int + ids []string + epochs int + mu sync.Mutex +} + +// newSharedInflight returns the tracker over ids; loop may be nil for a no-op tracker. +func newSharedInflight(loop *sharedStateLoop, ids []string, maxRequestTimeout time.Duration) *sharedInflight { + m := int((maxRequestTimeout+sharedInflightEpoch-1)/sharedInflightEpoch) + 1 + if m < 1 { + m = 1 + } + s := &sharedInflight{loop: loop, nowFn: time.Now, ids: ids, epochs: m, counts: make(map[string]int), limits: make(map[string]int)} + if loop != nil { + s.nowFn = loop.nowFn + loop.register(s) + } + return s +} + +func (s *sharedInflight) epochOf(t time.Time) int64 { + return t.Unix() / sharedInflightEpochSecs +} + +func (s *sharedInflight) ttl() time.Duration { + return time.Duration(s.epochs+1) * sharedInflightEpoch +} + +func (s *sharedInflight) epochKey(provider string, epoch int64, kind string) string { + return sharedInflightKey(provider, strconv.FormatInt(epoch, 10)+":"+kind) +} + +// keys lists, per provider, the started and finished keys of the last M epochs, then the learned limit. +func (s *sharedInflight) keys(now time.Time) []string { + e := s.epochOf(now) + out := make([]string, 0, len(s.ids)*(2*s.epochs+1)) + for _, id := range s.ids { + for i := 0; i < s.epochs; i++ { + out = append(out, s.epochKey(id, e-int64(i), "s"), s.epochKey(id, e-int64(i), "f")) + } + out = append(out, sharedInflightKey(id, "limit")) + } + return out +} + +func (s *sharedInflight) apply(vals []int64) { + s.mu.Lock() + defer s.mu.Unlock() + per := 2*s.epochs + 1 + for i, id := range s.ids { + if vals == nil { + delete(s.counts, id) + delete(s.limits, id) + } else { + base := i * per + total := 0 + for j := 0; j < s.epochs; j++ { + if d := vals[base+2*j] - vals[base+2*j+1]; d > 0 { + total += int(d) + } + } + s.counts[id] = total + s.limits[id] = int(vals[base+2*s.epochs]) + } + } +} + +// begin records a started request and returns the func that records its end, once. Writes are never dropped. +func (s *sharedInflight) begin(provider string) func() { + if s.loop == nil { + return func() {} + } + s.loop.touch() + epoch := s.epochOf(s.nowFn()) + ttl := s.ttl() + s.loop.sure(func() { + s.loop.write([]counterIncr{{key: s.epochKey(provider, epoch, "s"), delta: 1, ttl: ttl, enforceTTL: ttl}}) + }) + var once sync.Once + return func() { + once.Do(func() { + s.loop.sure(func() { + s.loop.write([]counterIncr{{key: s.epochKey(provider, epoch, "f"), delta: 1, ttl: ttl, enforceTTL: ttl}}) + }) + }) + } +} + +// shared returns the fleet-wide in-flight count from the last refresh. +func (s *sharedInflight) shared(provider string) int { + s.loop.touch() + s.mu.Lock() + defer s.mu.Unlock() + return s.counts[provider] +} + +// merged returns max(local, shared) in-flight for provider. +func (s *sharedInflight) merged(provider string, local int) int { + if sh := s.shared(provider); sh > local { + return sh + } + return local +} + +// setLearnedLimit shares a 429-learned limit; the last writer wins. +func (s *sharedInflight) setLearnedLimit(provider string, limit int) { + if s.loop == nil || limit <= 0 { + return + } + s.loop.touch() + s.loop.lossy(func() { + s.loop.write([]counterIncr{{key: sharedInflightKey(provider, "limit"), delta: int64(limit), ttl: sharedInflightLimitTTL, enforceTTL: sharedInflightLimitTTL, absolute: true}}) + }) +} + +// learnedLimit returns the shared learned limit when present, else local. +func (s *sharedInflight) learnedLimit(provider string, local int) int { + s.loop.touch() + s.mu.Lock() + defer s.mu.Unlock() + if v := s.limits[provider]; v > 0 { + return v + } + return local +} diff --git a/shared_state_test.go b/shared_state_test.go new file mode 100644 index 0000000..f457969 --- /dev/null +++ b/shared_state_test.go @@ -0,0 +1,583 @@ +package traefikllmgateway + +import ( + "context" + "errors" + "net/http" + "strings" + "sync" + "testing" + "time" +) + +type sharedClock struct { + t time.Time + mu sync.Mutex +} + +func (c *sharedClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *sharedClock) advance(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +// sharedRecStore wraps a counterStore, logging every key touched and optionally failing reads. +type sharedRecStore struct { + counterStore + failGet error + reads []string + writes []counterIncr + mu sync.Mutex +} + +func (r *sharedRecStore) getMulti(keys []string) ([]int64, error) { + r.mu.Lock() + r.reads = append(r.reads, keys...) + fail := r.failGet + r.mu.Unlock() + if fail != nil { + return nil, fail + } + return r.counterStore.getMulti(keys) +} + +func (r *sharedRecStore) incrMulti(e []counterIncr) ([]int64, error) { + r.mu.Lock() + r.writes = append(r.writes, e...) + r.mu.Unlock() + return r.counterStore.incrMulti(e) +} + +func (r *sharedRecStore) incrAndGetMulti(e []counterIncr, reads []string) ([]int64, []int64, error) { + r.mu.Lock() + r.writes = append(r.writes, e...) + r.mu.Unlock() + return r.counterStore.incrAndGetMulti(e, reads) +} + +func (r *sharedRecStore) writesTo(suffix string) int { + r.mu.Lock() + defer r.mu.Unlock() + n := 0 + for _, w := range r.writes { + if strings.HasSuffix(w.key, suffix) { + n++ + } + } + return n +} + +func (r *sharedRecStore) setFail(err error) { + r.mu.Lock() + r.failGet = err + r.mu.Unlock() +} + +func sharedTestEnv() (*sharedRecStore, *sharedClock) { + clk := &sharedClock{t: time.Unix(1_800_000_000, 0)} + mem := newMemoryStore() + mem.nowFn = clk.now + return &sharedRecStore{counterStore: mem}, clk +} + +// sharedTestLoop is one "pod": its own loop, writes run synchronously, no goroutine until touch. +func sharedTestLoop(store counterStore, clk *sharedClock) *sharedStateLoop { + l := newSharedStateLoop(store, nil, nil) + l.nowFn = clk.now + sync := func(f func()) { f() } + l.lossy, l.sure = sync, sync + // Tests drive refresh by hand; closed keeps touch from starting the goroutine. + l.closed = true + return l +} + +const ( + testBrkOpenBase = 30 * time.Second + testBrkOpenMax = 5 * time.Minute + testBrkWindow = time.Minute +) + +func testBreaker(l *sharedStateLoop) *sharedBreaker { + return newSharedBreaker(l, "req", []string{"p"}, 3, testBrkOpenBase, testBrkOpenMax, testBrkWindow) +} + +func TestSharedBreakerTripsFleetWide(t *testing.T) { + store, clk := sharedTestEnv() + la, lb, lc := sharedTestLoop(store, clk), sharedTestLoop(store, clk), sharedTestLoop(store, clk) + a, b, c := testBreaker(la), testBreaker(lb), testBreaker(lc) + + a.recordFailure("p") + a.recordFailure("p") + lc.refresh() + if c.isOpen("p") { + t.Fatal("C open after 2 fleet failures, want closed") + } + b.recordFailure("p") + if c.isOpen("p") { + t.Fatal("C open before refresh, isOpen must not read the store") + } + lc.refresh() + if !c.isOpen("p") { + t.Fatal("C closed after threshold failures and a refresh, want open") + } + clk.advance(testBrkOpenBase + time.Second) + if c.isOpen("p") { + t.Fatal("C still open after the open window") + } +} + +func TestSharedBreakerOnlyOneOpener(t *testing.T) { + store, clk := sharedTestEnv() + loops := []*sharedStateLoop{sharedTestLoop(store, clk), sharedTestLoop(store, clk)} + brks := []*sharedBreaker{testBreaker(loops[0]), testBreaker(loops[1])} + for i := 0; i < 5; i++ { + brks[i%2].recordFailure("p") + } + if got := store.writesTo(":open"); got != 1 { + t.Errorf("writes to open = %d, want 1", got) + } + if got := store.writesTo(":opens"); got != 1 { + t.Errorf("increments of opens = %d, want 1", got) + } +} + +func TestSharedBreakerSuccessResets(t *testing.T) { + store, clk := sharedTestEnv() + la, lb, lc := sharedTestLoop(store, clk), sharedTestLoop(store, clk), sharedTestLoop(store, clk) + a, b, c := testBreaker(la), testBreaker(lb), testBreaker(lc) + + a.recordFailure("p") + a.recordFailure("p") + lb.refresh() + b.recordSuccess("p") + // A's own local count stays; the fleet count is what C reads. + lc.refresh() + a2 := testBreaker(sharedTestLoop(store, clk)) + a2.recordFailure("p") + a2.recordFailure("p") + lc.refresh() + if c.isOpen("p") { + t.Fatal("C open after success reset then 2 failures, want closed") + } + a2.recordFailure("p") + lc.refresh() + if !c.isOpen("p") { + t.Fatal("C closed after 3 failures since the reset, want open") + } +} + +func TestSharedBreakerSuccessWithoutFailuresWritesNothing(t *testing.T) { + store, clk := sharedTestEnv() + l := sharedTestLoop(store, clk) + b := testBreaker(l) + l.refresh() + for i := 0; i < 5; i++ { + b.recordSuccess("p") + } + if len(store.writes) != 0 { + t.Errorf("healthy successes wrote %d entries, want 0", len(store.writes)) + } +} + +func TestSharedBreakerBackoffDoubles(t *testing.T) { + store, clk := sharedTestEnv() + l := sharedTestLoop(store, clk) + b := testBreaker(l) + openKey := sharedBreakerKey("req", "p", "open") + read := func() time.Duration { + got, _ := store.getMulti([]string{openKey}) + return time.UnixMilli(got[0]).Sub(clk.now()) + } + trip := func() { + for i := 0; i < 3; i++ { + b.recordFailure("p") + } + } + want := []time.Duration{testBrkOpenBase, 2 * testBrkOpenBase, 4 * testBrkOpenBase, 8 * testBrkOpenBase, testBrkOpenMax, testBrkOpenMax} + for i, w := range want { + trip() + if got := read(); got != w { + t.Fatalf("trip %d open for %v, want %v", i+1, got, w) + } + clk.advance(w + time.Second) + } +} + +func TestSharedBreakerOpenDurationTable(t *testing.T) { + b := testBreaker(nil) + for _, tc := range []struct { + opens int64 + want time.Duration + }{ + {1, 30 * time.Second}, {2, time.Minute}, {3, 2 * time.Minute}, {4, 4 * time.Minute}, + {5, 5 * time.Minute}, {100, 5 * time.Minute}, + } { + if got := b.openDuration(tc.opens); got != tc.want { + t.Errorf("openDuration(%d) = %v, want %v", tc.opens, got, tc.want) + } + } +} + +func TestSharedBreakerLocalOnlyMatchesRequestHealth(t *testing.T) { + clk := &sharedClock{t: time.Unix(1_800_000_000, 0)} + b := newSharedBreaker(nil, "req", []string{"p"}, requestBreakerFailureThreshold, requestBreakerOpenDuration, requestBreakerMaxOpenDuration, time.Minute) + b.nowFn = clk.now + ref := newRequestHealthTracker() + ref.nowFn = clk.now + steps := []struct { + success bool + advance time.Duration + }{ + {false, 0}, {false, 0}, {false, 0}, {false, time.Second}, {false, 31 * time.Second}, + {false, 0}, {false, 61 * time.Second}, {true, 0}, {false, 0}, {false, 0}, {false, 0}, + } + for i, s := range steps { + clk.advance(s.advance) + if s.success { + b.recordSuccess("p") + } else { + b.recordFailure("p") + } + ref.record("p", s.success) + if got, want := !b.isOpen("p"), ref.healthy("p"); got != want { + t.Fatalf("step %d: healthy = %v, want %v", i, got, want) + } + } +} + +func inflightEnv(maxReq time.Duration) (*sharedRecStore, *sharedClock, func() (*sharedStateLoop, *sharedInflight)) { + store, clk := sharedTestEnv() + return store, clk, func() (*sharedStateLoop, *sharedInflight) { + l := sharedTestLoop(store, clk) + return l, newSharedInflight(l, []string{"p"}, maxReq) + } +} + +func TestSharedInflightSums(t *testing.T) { + _, _, mk := inflightEnv(10 * time.Minute) + _, a := mk() + _, b := mk() + lc, c := mk() + end1 := a.begin("p") + a.begin("p") + b.begin("p") + lc.refresh() + if got := c.shared("p"); got != 3 { + t.Fatalf("shared = %d, want 3", got) + } + end1() + end1() // a second end must not double-count + lc.refresh() + if got := c.shared("p"); got != 2 { + t.Fatalf("shared after one end = %d, want 2", got) + } + if got := c.merged("p", 5); got != 5 { + t.Errorf("merged(local 5) = %d, want 5", got) + } + if got := c.merged("p", 1); got != 2 { + t.Errorf("merged(local 1) = %d, want 2", got) + } +} + +func TestSharedInflightCrashLeakExpires(t *testing.T) { + _, clk, mk := inflightEnv(10 * time.Minute) + _, a := mk() + lc, c := mk() + a.begin("p") // never ended: the pod crashed + lc.refresh() + if got := c.shared("p"); got != 1 { + t.Fatalf("shared = %d, want 1", got) + } + clk.advance(time.Duration(c.epochs) * sharedInflightEpoch) + lc.refresh() + if got := c.shared("p"); got != 0 { + t.Fatalf("shared after %d epochs = %d, want 0", c.epochs, got) + } +} + +func TestSharedInflightEndInLaterEpochCreditsStartEpoch(t *testing.T) { + _, clk, mk := inflightEnv(10 * time.Minute) + _, a := mk() + lc, c := mk() + end := a.begin("p") + clk.advance(sharedInflightEpoch + time.Second) + end() + lc.refresh() + if got := c.shared("p"); got != 0 { + t.Fatalf("shared = %d, want 0 (end credited to the start epoch)", got) + } +} + +func TestSharedInflightNegativeEpochClamped(t *testing.T) { + store, clk, mk := inflightEnv(10 * time.Minute) + lc, c := mk() + e := c.epochOf(clk.now()) + // Epoch e-1 saw more finishes than starts; epoch e has 2 open. + if _, err := store.incrMulti([]counterIncr{ + {key: c.epochKey("p", e-1, "s"), delta: 1, ttl: time.Hour}, + {key: c.epochKey("p", e-1, "f"), delta: 3, ttl: time.Hour}, + {key: c.epochKey("p", e, "s"), delta: 2, ttl: time.Hour}, + }); err != nil { + t.Fatal(err) + } + lc.refresh() + if got := c.shared("p"); got != 2 { + t.Fatalf("shared = %d, want 2", got) + } +} + +func TestSharedInflightLearnedLimit(t *testing.T) { + _, clk, mk := inflightEnv(time.Minute) + _, a := mk() + lc, c := mk() + if got := c.learnedLimit("p", 7); got != 7 { + t.Fatalf("before any shared limit = %d, want local 7", got) + } + a.setLearnedLimit("p", 4) + a.setLearnedLimit("p", 6) // last writer wins + lc.refresh() + if got := c.learnedLimit("p", 7); got != 6 { + t.Fatalf("learnedLimit = %d, want shared 6", got) + } + clk.advance(sharedInflightLimitTTL + time.Second) + lc.refresh() + if got := c.learnedLimit("p", 7); got != 7 { + t.Fatalf("after TTL = %d, want local 7", got) + } +} + +func TestSharedStateStoreErrorFallsBackLocal(t *testing.T) { + store, clk := sharedTestEnv() + la, lc := sharedTestLoop(store, clk), sharedTestLoop(store, clk) + a, c := testBreaker(la), testBreaker(lc) + for i := 0; i < 3; i++ { + a.recordFailure("p") + } + lc.refresh() + if !c.isOpen("p") { + t.Fatal("setup: C should see the shared open") + } + + store.setFail(errors.New("redis down")) + lc.refresh() + lc.refresh() + if !lc.stale() { + t.Error("loop not marked stale after failed refreshes") + } + if !c.isOpen("p") { + t.Error("last-known shared open dropped before 3 failed refreshes") + } + lc.refresh() + if c.isOpen("p") { + t.Error("shared open still used after 3 failed refreshes, want absent") + } + + // Local breaker keeps working while the store is down. + for i := 0; i < 3; i++ { + c.recordFailure("p") + } + if !c.isOpen("p") { + t.Error("local breaker did not open while store is down") + } + + store.setFail(nil) + lc.refresh() + if lc.stale() { + t.Error("loop still stale after a good refresh") + } +} + +func TestSharedStateChunkedRefresh(t *testing.T) { + store, clk := sharedTestEnv() + l := sharedTestLoop(store, clk) + ids := make([]string, 0, 700) + for i := 0; i < 700; i++ { + ids = append(ids, "prov"+string(rune('a'+i%26))+strings.Repeat("x", i/26)) + } + b := newSharedBreaker(l, "req", ids, 3, testBrkOpenBase, testBrkOpenMax, testBrkWindow) + b.recordFailure(ids[699]) + l.refresh() + if len(store.reads) != 1400 { + t.Fatalf("keys read = %d, want 1400", len(store.reads)) + } + if l.stale() { + t.Error("stale after a chunked successful refresh") + } +} + +func TestSharedStateOffNoKeys(t *testing.T) { + store, _ := sharedTestEnv() + b := newSharedBreaker(nil, "req", []string{"p"}, 3, testBrkOpenBase, testBrkOpenMax, testBrkWindow) + in := newSharedInflight(nil, []string{"p"}, time.Minute) + for i := 0; i < 4; i++ { + b.recordFailure("p") + b.recordSuccess("p") + b.isOpen("p") + } + in.begin("p")() + in.shared("p") + in.merged("p", 1) + in.setLearnedLimit("p", 3) + in.learnedLimit("p", 1) + if len(store.reads) != 0 || len(store.writes) != 0 { + t.Fatalf("nil loop touched the store: %d reads, %d writes", len(store.reads), len(store.writes)) + } +} + +func TestSharedStateConfigValidation(t *testing.T) { + on, off := true, false + next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) + for _, tc := range []struct { + redis *RedisConfig + name string + wantErr bool + wantLp bool + }{ + {&RedisConfig{SharedState: &on}, "on without address", true, false}, + {&RedisConfig{SharedState: &off}, "off without address", true, false}, // pre-existing address error + {&RedisConfig{Address: "127.0.0.1:0", SharedState: &on}, "on with address", false, true}, + {&RedisConfig{Address: "127.0.0.1:0", SharedState: &off}, "off with address", false, false}, + {&RedisConfig{Address: "127.0.0.1:0"}, "nil with address", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := CreateConfig() + cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}} + cfg.Redis = tc.redis + h, err := New(context.Background(), next, cfg, "llmgw") + if tc.wantErr { + if err == nil { + t.Fatal("want error") + } + if tc.redis.SharedState != nil && *tc.redis.SharedState && !strings.Contains(err.Error(), "sharedState") { + t.Errorf("error %q does not name sharedState", err) + } + return + } + if err != nil { + t.Fatalf("New: %v", err) + } + gw := h.(*Gateway) + defer gw.Close() + if got := gw.sharedState != nil; got != tc.wantLp { + t.Errorf("sharedState loop present = %v, want %v", got, tc.wantLp) + } + }) + } +} + +func TestSharedStateNoRedisNoLoop(t *testing.T) { + cfg := CreateConfig() + cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}} + h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw") + if err != nil { + t.Fatal(err) + } + if h.(*Gateway).sharedState != nil { + t.Error("loop built with no Redis") + } +} + +func TestSharedStateLoopLifecycle(t *testing.T) { + store, clk := sharedTestEnv() + l := newSharedStateLoop(store, nil, nil) + l.nowFn = clk.now + l.every = 5 * time.Millisecond + b := testBreaker(l) + b.recordFailure("p") // touch starts the goroutine + deadline := time.Now().Add(2 * time.Second) + for { + l.mu.Lock() + running := l.running + l.mu.Unlock() + if running || time.Now().After(deadline) { + break + } + time.Sleep(time.Millisecond) + } + // Idle past the stop interval: the next tick ends the goroutine. + clk.advance(sharedStateIdleStop + time.Second) + l.mu.Lock() + done := l.done + l.mu.Unlock() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("loop did not stop on idle") + } + l.mu.Lock() + if l.running { + t.Error("running still set after idle stop") + } + l.mu.Unlock() + + // A new use restarts it; close stops it for good and blocks restarts. + b.isOpen("p") + l.mu.Lock() + stop, done := l.stop, l.done + l.mu.Unlock() + l.close() + select { + case <-stop: + default: + t.Fatal("close did not signal stop") + } + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("loop did not stop on close") + } + b.isOpen("p") + l.mu.Lock() + if l.running { + t.Error("closed loop restarted") + } + l.mu.Unlock() +} + +func TestSharedStateLoopRecoversFromPanic(t *testing.T) { + store, clk := sharedTestEnv() + l := newSharedStateLoop(store, nil, nil) + l.nowFn = clk.now + l.every = 5 * time.Millisecond + l.register(panicPrimitive{}) + l.touch() + l.mu.Lock() + done := l.done + l.mu.Unlock() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("panicking refresh did not end the goroutine cleanly") + } + l.mu.Lock() + defer l.mu.Unlock() + if l.running { + t.Error("running still set after panic") + } +} + +type panicPrimitive struct{} + +func (panicPrimitive) keys(time.Time) []string { return []string{"k"} } +func (panicPrimitive) apply([]int64) { panic("boom") } + +func TestSharedStateIDs(t *testing.T) { + cfg := &Config{ + Providers: map[string]*ProviderConfig{"b": {}, "a": {}}, + SmartRouters: map[string]*SmartRouterConfig{ + "r": {Decision: &SmartRouterDecisionConfig{Provider: "c"}}, + "s": {}, + "t": nil, + }, + } + got := strings.Join(sharedStateIDs(cfg), ",") + if got != "a,b,c" { + t.Errorf("ids = %q, want a,b,c", got) + } +}