diff --git a/shared_state.go b/shared_state.go index 5d9905d..26bb2e7 100644 --- a/shared_state.go +++ b/shared_state.go @@ -579,6 +579,8 @@ type infDelta struct { key string epoch int64 n int64 + // tried is the oldest part of n that an earlier flush sent and may have landed. + tried int64 } // sharedInflight counts in-flight requests per provider fleet-wide with epoch-bucketed started/finished counters, so a crashed pod's leak ages out. @@ -689,7 +691,8 @@ func (s *sharedInflight) pending() bool { } // flush writes every non-zero delta in one incrMulti. Epochs outside the read window are discarded. -// On error the deltas stay and later begin/end calls add on top of them. +// A failure that never wrote keeps every delta. A failure that may have landed (written, reply lost or timed out) +// resends each batch once and then drops it, which equals the leak a crashed pod leaves and the epoch scheme bounds. func (s *sharedInflight) flush(l *sharedStateLoop, now time.Time) error { oldest := s.epochOf(now) - int64(s.epochs) s.mu.Lock() @@ -706,12 +709,19 @@ func (s *sharedInflight) flush(l *sharedStateLoop, now time.Time) error { return nil } if _, err := l.store.incrMulti(entries); err != nil { + if !respNotApplied(err) { + s.markAmbiguous(entries) + } return err } s.mu.Lock() for _, e := range entries { if d, ok := s.acc[e.key]; ok { d.n -= e.delta + d.tried -= e.delta + if d.tried < 0 { + d.tried = 0 + } if d.n <= 0 { delete(s.acc, e.key) } @@ -721,6 +731,27 @@ func (s *sharedInflight) flush(l *sharedStateLoop, now time.Time) error { return nil } +// markAmbiguous drops the part of each sent batch that an earlier flush already sent, and marks the rest as sent once. +func (s *sharedInflight) markAmbiguous(sent []counterIncr) { + s.mu.Lock() + defer s.mu.Unlock() + for _, e := range sent { + d, ok := s.acc[e.key] + if !ok { + continue + } + old := d.tried + if old > e.delta { + old = e.delta + } + d.n -= old + d.tried = e.delta - old + if d.n <= 0 { + delete(s.acc, e.key) + } + } +} + // shared returns the fleet-wide in-flight count from the last refresh. func (s *sharedInflight) shared(provider string) int { s.loop.touch() diff --git a/shared_state_review_test.go b/shared_state_review_test.go index c8fce5c..c8bb712 100644 --- a/shared_state_review_test.go +++ b/shared_state_review_test.go @@ -40,9 +40,11 @@ func TestSharedBreakerSuccessResetsBackoff(t *testing.T) { // fussyStore applies a write and still fails it, short-changes the reply, or fails writes to one key suffix. type fussyStore struct { counterStore + incrErr error failSuffix string applyThenFail int mu sync.Mutex + incrApply bool shortReply bool } @@ -159,3 +161,99 @@ func TestSharedBreakerShortReplyKeepsDeltas(t *testing.T) { t.Fatal("deltas dropped after a short reply") } } + +func (f *fussyStore) incrMulti(e []counterIncr) ([]int64, error) { + f.mu.Lock() + err, apply := f.incrErr, f.incrApply + f.mu.Unlock() + if err == nil { + return f.counterStore.incrMulti(e) + } + if apply { + _, _ = f.counterStore.incrMulti(e) + } + return nil, err +} + +func (f *fussyStore) failIncr(err error, applied bool) { + f.mu.Lock() + f.incrErr, f.incrApply = err, applied + f.mu.Unlock() +} + +func startedTotal(t *testing.T, st counterStore, clk *sharedClock, epochs int) int64 { + t.Helper() + in := newSharedInflight(nil, []string{"p"}, time.Minute) + var keys []string + for i := 0; i < epochs; i++ { + keys = append(keys, in.epochKey("p", in.epochOf(clk.now())-int64(i), "s")) + } + got, err := st.getMulti(keys) + if err != nil { + t.Fatal(err) + } + var sum int64 + for _, v := range got { + sum += v + } + return sum +} + +func TestSharedInflightAmbiguousFailureResendsOnce(t *testing.T) { + st, clk, _, _ := fussyEnv() + l := sharedTestLoop(st, clk) + in := newSharedInflight(l, []string{"p"}, time.Minute) + for i := 0; i < 3; i++ { + in.begin("p") + } + st.failIncr(errors.New("reply lost"), true) + l.refresh() // applied, reply lost + l.refresh() // resent once, applied again, reply lost: dropped now + st.failIncr(nil, false) + l.refresh() + l.refresh() + if in.pending() { + t.Error("deltas still queued after two ambiguous failures") + } + if got := startedTotal(t, st, clk, in.epochs); got > 6 { + t.Errorf("started total = %d for 3 begins, want at most 2x one batch (6)", got) + } +} + +func TestSharedInflightNotWrittenFailureKeepsExactTotal(t *testing.T) { + st, clk, _, _ := fussyEnv() + l := sharedTestLoop(st, clk) + in := newSharedInflight(l, []string{"p"}, time.Minute) + st.failIncr(¬AppliedError{err: errors.New("dial refused")}, false) + for i := 0; i < 4; i++ { + in.begin("p") + l.refresh() + } + if !in.pending() { + t.Fatal("deltas dropped after failures that never wrote") + } + st.failIncr(nil, false) + l.refresh() + if got := startedTotal(t, st, clk, in.epochs); got != 4 { + t.Errorf("started total = %d, want exactly 4", got) + } + if in.pending() { + t.Error("deltas queued after the successful flush") + } +} + +func TestSharedInflightNewDeltasSurviveAfterAmbiguousDrop(t *testing.T) { + st, clk, _, _ := fussyEnv() + l := sharedTestLoop(st, clk) + in := newSharedInflight(l, []string{"p"}, time.Minute) + in.begin("p") + st.failIncr(errors.New("reply lost"), false) + l.refresh() + in.begin("p") // new delta lands on the once-sent batch + l.refresh() // batch of 1 dropped, new delta kept + st.failIncr(nil, false) + l.refresh() + if got := startedTotal(t, st, clk, in.epochs); got != 1 { + t.Errorf("started total = %d, want 1 (the dropped batch is gone, the new delta lands once)", got) + } +} diff --git a/shared_state_test.go b/shared_state_test.go index fa8a04a..eaa5c3e 100644 --- a/shared_state_test.go +++ b/shared_state_test.go @@ -630,7 +630,7 @@ func TestSharedInflightFlushErrorRetains(t *testing.T) { a.begin("p") a.begin("p") end() - store.setFailIncr(errors.New("redis down")) + store.setFailIncr(¬AppliedError{err: errors.New("redis down")}) la.refresh() a.begin("p") // lands on top of the retained deltas la.refresh() @@ -717,7 +717,7 @@ func TestSharedStateNoIdleStopWithPendingDeltas(t *testing.T) { l.nowFn = clk.now l.every = 5 * time.Millisecond in := newSharedInflight(l, []string{"p"}, 20*time.Minute) - store.setFailIncr(errors.New("redis down")) + store.setFailIncr(¬AppliedError{err: errors.New("redis down")}) in.begin("p") clk.advance(sharedStateIdleStop + time.Second) time.Sleep(50 * time.Millisecond)