diff --git a/shared_state.go b/shared_state.go index 6ee3131..5d9905d 100644 --- a/shared_state.go +++ b/shared_state.go @@ -1,6 +1,7 @@ package traefikllmgateway import ( + "fmt" "sort" "strconv" "sync" @@ -412,6 +413,13 @@ func (b *sharedBreaker) sharedOpen(id string) bool { return b.openUntil[id] > b.nowFn().UnixMilli() } +// viewOpen is sharedOpen without the loop touch, for the loop's own goroutine. +func (b *sharedBreaker) viewOpen(id string, now time.Time) bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.openUntil[id] > now.UnixMilli() +} + // recordFailure updates local state and queues the failure for the loop to flush. func (b *sharedBreaker) recordFailure(id string) { b.mu.Lock() @@ -454,8 +462,8 @@ func (b *sharedBreaker) pending() bool { return len(b.failAcc) > 0 } -// flush adds the queued failures to the fleet counts. The instance whose flush takes a count from below the -// threshold to at or above it is the single opener. +// flush adds the queued failures to the fleet counts. An instance whose flush leaves the count at or above the +// threshold opens the breaker unless its last refresh already shows it open. func (b *sharedBreaker) flush(l *sharedStateLoop, _ time.Time) error { b.mu.Lock() ids := make([]string, 0, len(b.failAcc)) @@ -477,7 +485,7 @@ func (b *sharedBreaker) flush(l *sharedStateLoop, _ time.Time) error { return err } if len(post) != len(ids) { - return nil + return fmt.Errorf("shared breaker: %d counts for %d keys", len(post), len(ids)) } b.mu.Lock() for i, id := range ids { @@ -489,7 +497,9 @@ func (b *sharedBreaker) flush(l *sharedStateLoop, _ time.Time) error { } b.mu.Unlock() for i, id := range ids { - if post[i]-deltas[i] < int64(b.threshold) && post[i] >= int64(b.threshold) { + // A crossing test (post-delta below, post at or above) would miss an incr that Redis applied while its reply was lost. + // The last refreshed view says whether a trip already happened; a rare double trip only adds one to opens. + if post[i] >= int64(b.threshold) && !b.viewOpen(id, l.nowFn()) { b.trip(l, id) } } diff --git a/shared_state_review_test.go b/shared_state_review_test.go index d804780..c8fce5c 100644 --- a/shared_state_review_test.go +++ b/shared_state_review_test.go @@ -1,6 +1,9 @@ package traefikllmgateway import ( + "errors" + "strings" + "sync" "testing" "time" ) @@ -33,3 +36,126 @@ func TestSharedBreakerSuccessResetsBackoff(t *testing.T) { t.Fatalf("trip after a success open for %v, want %v (backoff must reset)", got, testBrkOpenBase) } } + +// fussyStore applies a write and still fails it, short-changes the reply, or fails writes to one key suffix. +type fussyStore struct { + counterStore + failSuffix string + applyThenFail int + mu sync.Mutex + shortReply bool +} + +func (f *fussyStore) incrAndGetMulti(e []counterIncr, reads []string) ([]int64, []int64, error) { + f.mu.Lock() + apply, short, suffix := f.applyThenFail > 0, f.shortReply, f.failSuffix + if apply { + f.applyThenFail-- + } + f.mu.Unlock() + if suffix != "" && strings.HasSuffix(e[0].key, suffix) { + return nil, nil, errors.New("opens write failed") + } + post, got, err := f.counterStore.incrAndGetMulti(e, reads) + if err != nil { + return nil, nil, err + } + if apply { + return nil, nil, errors.New("reply lost") + } + if short { + return post[:len(post)-1], got, nil + } + return post, got, nil +} + +func fussyEnv() (*fussyStore, *sharedClock, *sharedStateLoop, *sharedBreaker) { + clk := &sharedClock{t: time.Unix(1_800_000_000, 0)} + mem := newMemoryStore() + mem.nowFn = clk.now + st := &fussyStore{counterStore: mem} + l := sharedTestLoop(st, clk) + return st, clk, l, testBreaker(l) +} + +func openUntilOf(t *testing.T, st counterStore, id string) int64 { + t.Helper() + got, err := st.getMulti([]string{sharedBreakerKey("req", id, "open")}) + if err != nil { + t.Fatal(err) + } + return got[0] +} + +func TestSharedBreakerTripsAfterAppliedButFailedIncr(t *testing.T) { + st, _, l, b := fussyEnv() + b.recordFailure("p") + b.recordFailure("p") + l.refresh() + b.recordFailure("p") + st.mu.Lock() + st.applyThenFail = 1 + st.mu.Unlock() + l.refresh() // INCR applied (count 3), reply lost: delta retained + if openUntilOf(t, st, "p") != 0 { + t.Fatal("tripped before any flush saw the reply") + } + l.refresh() // resend: count 4, post-delta is already past the threshold + if openUntilOf(t, st, "p") == 0 { + t.Fatal("fleet never tripped after an applied-but-failed incr") + } +} + +func TestSharedBreakerRetriesTripAfterOpensIncrFailure(t *testing.T) { + st, _, l, b := fussyEnv() + st.mu.Lock() + st.failSuffix = ":opens" + st.mu.Unlock() + for i := 0; i < 3; i++ { + b.recordFailure("p") + } + l.refresh() + if openUntilOf(t, st, "p") != 0 { + t.Fatal("tripped although the opens incr failed") + } + st.mu.Lock() + st.failSuffix = "" + st.mu.Unlock() + b.recordFailure("p") + l.refresh() + if openUntilOf(t, st, "p") == 0 { + t.Fatal("fleet never tripped after the opens incr failed once") + } +} + +func TestSharedBreakerNoRetripWhileOpen(t *testing.T) { + st, _, l, b := fussyEnv() + for i := 0; i < 3; i++ { + b.recordFailure("p") + } + l.refresh() + l.refresh() // the loop now sees the open mark + for i := 0; i < 5; i++ { + b.recordFailure("p") + l.refresh() + } + got, _ := st.getMulti([]string{sharedBreakerKey("req", "p", "opens")}) + if got[0] != 1 { + t.Errorf("opens = %d after failures during the open window, want 1", got[0]) + } +} + +func TestSharedBreakerShortReplyKeepsDeltas(t *testing.T) { + st, _, l, b := fussyEnv() + st.mu.Lock() + st.shortReply = true + st.mu.Unlock() + b.recordFailure("p") + err := b.flush(l, l.nowFn()) + if err == nil { + t.Fatal("flush with a short reply returned nil, want an error") + } + if !b.pending() { + t.Fatal("deltas dropped after a short reply") + } +}