diff --git a/failover.go b/failover.go index 70d65e7..662473a 100644 --- a/failover.go +++ b/failover.go @@ -622,9 +622,16 @@ type requestHealthState struct { type requestHealthTracker struct { states map[string]*requestHealthState nowFn func() time.Time + // shared layers the fleet view over the local breaker; nil means local only. + shared *sharedBreaker mu sync.Mutex } +// share attaches the fleet breaker. Call it before the tracker serves requests. +func (t *requestHealthTracker) share(b *sharedBreaker) { + t.shared = b +} + // newRequestHealthTracker returns an empty tracker — every provider name // reads healthy until its first recorded failure. func newRequestHealthTracker() *requestHealthTracker { @@ -712,11 +719,15 @@ func (t *requestHealthTracker) record(provider string, success bool) { defer st.mu.Unlock() now := t.nowFn() + sb := t.shared if success { st.open = false st.consecutiveFailures = 0 st.backoff = 0 st.openUntil = time.Time{} + if sb != nil { + sb.recordSuccess(provider) + } return } @@ -725,6 +736,9 @@ func (t *requestHealthTracker) record(provider string, success bool) { if st.open && now.Before(st.openUntil) { return } + if sb != nil { + sb.recordFailure(provider) + } if st.open { // Cooldown elapsed: this failure IS the probe outcome. Escalate. @@ -762,11 +776,13 @@ func (t *requestHealthTracker) healthy(provider string) bool { } st := t.stateFor(provider) st.mu.Lock() - defer st.mu.Unlock() - if !st.open { - return true + local := !st.open || !t.nowFn().Before(st.openUntil) + st.mu.Unlock() + if !local { + return false } - return !t.nowFn().Before(st.openUntil) + sb := t.shared + return sb == nil || !sb.sharedOpen(provider) } // contextOverflowScanBytes bounds how much of an upstream 400 body is scanned. diff --git a/llmgateway.go b/llmgateway.go index ad9ff5f..f095609 100644 --- a/llmgateway.go +++ b/llmgateway.go @@ -1303,6 +1303,7 @@ func newGateway(ctx context.Context, next http.Handler, config *Config, name str // is accepted. registry.warmFill(ctx) g.registry = registry + g.wireSharedState(config) g.warnRouterSessions() g.warnRouterLearning() diff --git a/shared_state.go b/shared_state.go index d3ef5b3..de988e8 100644 --- a/shared_state.go +++ b/shared_state.go @@ -16,6 +16,11 @@ const ( // sharedStateChunk bounds the keys of one getMulti. sharedStateChunk = 500 + // Breaker kinds, the {kind} part of a breaker key. + sharedKindRequest = "req" + sharedKindDiscovery = "disc" + sharedKindDecision = "dec" + sharedBreakerPrefix = "llmgw:brk:" sharedInflightPrefix = "llmgw:inf:" @@ -393,6 +398,15 @@ func (b *sharedBreaker) isOpen(id string) bool { return b.openUntil[id] > now.UnixMilli() } +// sharedOpen reports whether the last-refreshed fleet state says id is open, ignoring this breaker's local arm. +// Callers with their own local breaker use it to layer the fleet view on top. It never calls the store. +func (b *sharedBreaker) sharedOpen(id string) bool { + b.loop.touch() + b.mu.Lock() + defer b.mu.Unlock() + return b.openUntil[id] > b.nowFn().UnixMilli() +} + // recordFailure updates local state and queues the failure for the loop to flush. func (b *sharedBreaker) recordFailure(id string) { b.mu.Lock() @@ -507,26 +521,35 @@ func (b *sharedBreaker) openDuration(opens int64) time.Duration { return d } -// recordSuccess resets local state and, when a failure count may exist in the store, clears it. +// recordSuccess resets local state and clears the fleet failure count and open mark when either may exist. func (b *sharedBreaker) recordSuccess(id string) { b.mu.Lock() st := b.localFor(id) dirty := st.consecutiveFailures > 0 || b.failsSeen[id] > 0 + // A success closes the fleet breaker too, as it closes the local one. + wasOpen := b.openUntil[id] > b.nowFn().UnixMilli() delete(b.failAcc, id) st.open = false st.consecutiveFailures = 0 st.backoff = 0 st.openUntil = time.Time{} b.mu.Unlock() - if b.loop == nil || !dirty { + if b.loop == nil || (!dirty && !wasOpen) { 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}}) + entries := []counterIncr{{key: sharedBreakerKey(b.kind, id, "fails"), delta: 0, ttl: b.failWindow, enforceTTL: b.failWindow, absolute: true}} + if wasOpen { + entries = append(entries, counterIncr{key: sharedBreakerKey(b.kind, id, "open"), delta: 0, ttl: b.openBase, enforceTTL: b.openBase, absolute: true}) + } + b.loop.write(entries) }) b.mu.Lock() b.failsSeen[id] = 0 + if wasOpen { + delete(b.openUntil, id) + } b.mu.Unlock() } diff --git a/shared_state_failover_test.go b/shared_state_failover_test.go new file mode 100644 index 0000000..73ca6c9 --- /dev/null +++ b/shared_state_failover_test.go @@ -0,0 +1,105 @@ +package traefikllmgateway + +import ( + "testing" + "time" +) + +// sharedGatewayPair builds two gateways from one config over one shared store and fake clock, as two pods of a fleet. +func sharedGatewayPair(t *testing.T, mut func(*Config)) (a, b *Gateway, store *sharedRecStore, clk *sharedClock, cfg *Config) { + t.Helper() + ba := newRouterBackend(200, successRespBody) + bb := newRouterBackend(200, successRespBody) + bc := newRouterBackend(200, successRespBody) + t.Cleanup(func() { closeBackends(ba, bb, bc) }) + cfg = routerTestConfig(ba, bb, bc, threeTiers()) + if mut != nil { + mut(cfg) + } + store, clk = sharedTestEnv() + pod := func() *Gateway { + _, gw := buildRouterGateway(t, cfg) + gw.sharedState = sharedTestLoop(store, clk) + gw.wireSharedState(cfg) + return gw + } + return pod(), pod(), store, clk, cfg +} + +// sharedOffGateway is a gateway with redis.sharedState off: no loop, so wireSharedState must change nothing. +func sharedOffGateway(t *testing.T) (*Gateway, *Config) { + t.Helper() + ba := newRouterBackend(200, successRespBody) + bb := newRouterBackend(200, successRespBody) + bc := newRouterBackend(200, successRespBody) + t.Cleanup(func() { closeBackends(ba, bb, bc) }) + cfg := routerTestConfig(ba, bb, bc, threeTiers()) + _, gw := buildRouterGateway(t, cfg) + if gw.sharedState != nil { + t.Fatal("sharedState loop built with the switch off") + } + gw.wireSharedState(cfg) + return gw, cfg +} + +func TestSharedRequestBreakerAcrossGateways(t *testing.T) { + a, b, _, _, _ := sharedGatewayPair(t, nil) + for i := 0; i < requestBreakerFailureThreshold; i++ { + a.failoverHealth.record("alpha", false) + } + if b.failoverHealth.healthy("alpha") != true { + t.Fatal("B unhealthy before any refresh, healthy must not read the store") + } + a.sharedState.refresh() + b.sharedState.refresh() + if b.failoverHealth.healthy("alpha") { + t.Fatal("B healthy after A tripped the breaker and one refresh, want unhealthy") + } + if !b.failoverHealth.healthy("beta") { + t.Fatal("B beta unhealthy, a trip on alpha must not leak to other providers") + } + b.failoverHealth.record("alpha", true) + b.sharedState.refresh() + if !b.failoverHealth.healthy("alpha") { + t.Fatal("B still unhealthy after a success, want closed") + } +} + +func TestSharedRequestBreakerClosesAfterWindow(t *testing.T) { + a, b, _, clk, _ := sharedGatewayPair(t, nil) + for i := 0; i < requestBreakerFailureThreshold; i++ { + a.failoverHealth.record("alpha", false) + } + a.sharedState.refresh() + b.sharedState.refresh() + clk.advance(requestBreakerOpenDuration + time.Second) + if !b.failoverHealth.healthy("alpha") { + t.Fatal("B unhealthy after the open window elapsed") + } +} + +func TestSharedStateOffIdenticalRequestBreaker(t *testing.T) { + gw, _ := sharedOffGateway(t) + rec, _ := sharedTestEnv() + gw.limiter.store = rec + off := gw.failoverHealth + ref := newRequestHealthTracker() + now := time.Unix(1_800_000_000, 0) + off.nowFn = func() time.Time { return now } + ref.nowFn = off.nowFn + steps := []struct { + ok bool + advance time.Duration + }{{false, 0}, {false, 0}, {false, 0}, {false, time.Second}, {false, 40 * time.Second}, {false, 0}, {true, 0}, {false, 0}} + for i, s := range steps { + now = now.Add(s.advance) + off.record("alpha", s.ok) + ref.record("alpha", s.ok) + if got, want := off.healthy("alpha"), ref.healthy("alpha"); got != want { + t.Fatalf("step %d: healthy = %v, want %v", i, got, want) + } + } + 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)) + } +} diff --git a/shared_state_test.go b/shared_state_test.go index 1ea63b8..805f8fe 100644 --- a/shared_state_test.go +++ b/shared_state_test.go @@ -737,3 +737,25 @@ func TestSharedStateNoIdleStopWithPendingDeltas(t *testing.T) { } l.close() } + +func TestSharedBreakerSuccessClosesOpen(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) + for i := 0; i < 3; i++ { + a.recordFailure("p") + } + la.refresh() + lb.refresh() + if !b.sharedOpen("p") { + t.Fatal("B shared view closed after the trip") + } + b.recordSuccess("p") + lc.refresh() + if c.sharedOpen("p") { + t.Fatal("C still sees open after B's success") + } + if b.sharedOpen("p") { + t.Fatal("B still sees open right after its own success") + } +} diff --git a/shared_state_wire.go b/shared_state_wire.go new file mode 100644 index 0000000..1e40479 --- /dev/null +++ b/shared_state_wire.go @@ -0,0 +1,13 @@ +package traefikllmgateway + +// wireSharedState layers fleet-wide state over the local trackers. It is a no-op without a shared-state loop. +func (g *Gateway) wireSharedState(cfg *Config) { + if g.sharedState == nil { + return + } + ids := sharedStateIDs(cfg) + if g.failoverHealth != nil { + g.failoverHealth.share(newSharedBreaker(g.sharedState, sharedKindRequest, ids, + requestBreakerFailureThreshold, requestBreakerOpenDuration, requestBreakerMaxOpenDuration, 2*requestBreakerMaxOpenDuration)) + } +}