Skip to content

Commit a754316

Browse files
authored
fix(ingester): skip in-flight entries when evicting from the postings cache (#7993)
* fix(ingester): skip in-flight entries when evicting from the postings cache Since #7944 an entry is linked into the LRU list when its fetch starts. evictLocked only looked at the list front, so: - under byte pressure it evicted an in-flight front, which frees no bytes and lets the next caller for that key start a duplicate fetch; - during expiry it stopped at an in-flight front, so expired entries behind it survived PurgeExpiredItems. Walk the list from the front and skip in-flight entries in both cases. Signed-off-by: Alan Protasio <alanprot@gmail.com> * test(ingester): cover a failed postings fetch with waiters Signed-off-by: Alan Protasio <alanprot@gmail.com> --------- Signed-off-by: Alan Protasio <alanprot@gmail.com>
1 parent 32756c7 commit a754316

2 files changed

Lines changed: 148 additions & 4 deletions

File tree

‎pkg/storage/tsdb/expanded_postings_cache.go‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -644,21 +644,28 @@ func (c *lruCache[V]) isExpiredLocked(e *cacheEntryPromise[V], now time.Time) bo
644644
}
645645

646646
// evictLocked drops least recently used entries while over budget, then expired ones.
647-
// Entries whose fetch is still running are never expired.
647+
// Entries whose fetch is still running hold no counted bytes and are skipped, so
648+
// eviction never breaks fetch sharing and they do not hide entries behind them.
648649
func (c *lruCache[V]) evictLocked() {
649650
now := c.timeNow()
650-
for c.front != nil {
651+
for e := c.front; e != nil; {
652+
next := e.next
653+
if e.call.Load() != nil {
654+
e = next
655+
continue
656+
}
651657
reason := ""
652658
switch {
653659
case c.cachedBytes > c.cfg.MaxBytes:
654660
reason = "full"
655-
case c.front.call.Load() == nil && c.isExpiredLocked(c.front, now):
661+
case c.isExpiredLocked(e, now):
656662
reason = "expired"
657663
default:
658664
return
659665
}
660666
c.metrics.CacheEvicts.WithLabelValues(c.name, reason).Inc()
661-
c.removeLocked(c.front)
667+
c.removeLocked(e)
668+
e = next
662669
}
663670
}
664671

‎pkg/storage/tsdb/expanded_postings_lru_test.go‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"time"
1313

1414
"github.com/prometheus/client_golang/prometheus"
15+
prom_testutil "github.com/prometheus/client_golang/prometheus/testutil"
1516
"github.com/prometheus/prometheus/storage"
1617
"github.com/stretchr/testify/require"
1718
"go.uber.org/atomic"
@@ -219,6 +220,142 @@ func TestLruCache_FetchPanicDoesNotPoisonKey(t *testing.T) {
219220
checkLruInvariants(t, cache)
220221
}
221222

223+
// startBlockedFetch starts a fetch for k that runs until the returned release is called.
224+
func startBlockedFetch(t *testing.T, cache *lruCache[int], k string, fetches *atomic.Int64) (release func()) {
225+
t.Helper()
226+
unblock := make(chan struct{})
227+
done := make(chan struct{})
228+
go func() {
229+
defer close(done)
230+
cache.getPromiseForKey(k, func() (int, int64, error) {
231+
fetches.Inc()
232+
<-unblock
233+
return 1, 8, nil
234+
})
235+
}()
236+
require.Eventually(t, func() bool { return fetches.Load() == 1 }, time.Second, time.Millisecond)
237+
var once sync.Once
238+
release = func() {
239+
once.Do(func() { close(unblock) })
240+
<-done
241+
}
242+
t.Cleanup(release)
243+
return release
244+
}
245+
246+
// An in-flight entry holds no counted bytes, so the byte budget must evict completed
247+
// entries behind it instead; evicting it would let a later caller start a second fetch.
248+
func TestLruCache_FullEvictionSkipsInflightEntries(t *testing.T) {
249+
cfg := PostingsCacheConfig{Enabled: true, MaxBytes: 15, Ttl: time.Hour}
250+
m := NewPostingCacheMetrics(prometheus.NewPedanticRegistry())
251+
cache := newLruCache[int](cfg, "test", m, time.Now)
252+
253+
var fetches atomic.Int64
254+
release := startBlockedFetch(t, cache, "kA", &fetches)
255+
256+
// kB and kC are 10 bytes each, so completing kC puts the cache over budget.
257+
cache.getPromiseForKey("kB", func() (int, int64, error) { return 2, 8, nil })
258+
cache.getPromiseForKey("kC", func() (int, int64, error) { return 3, 8, nil })
259+
260+
require.True(t, cache.contains("kA"), "in-flight entry evicted for space")
261+
require.False(t, cache.contains("kB"), "the least recently used completed entry must be evicted")
262+
require.True(t, cache.contains("kC"))
263+
require.Equal(t, 1.0, prom_testutil.ToFloat64(m.CacheEvicts.WithLabelValues("test", "full")))
264+
265+
_, loaded := cache.getPromiseForKey("kA", func() (int, int64, error) {
266+
fetches.Inc()
267+
return 1, 8, nil
268+
})
269+
require.True(t, loaded, "a later caller must join the running fetch")
270+
require.Equal(t, int64(1), fetches.Load())
271+
272+
release()
273+
checkLruInvariants(t, cache)
274+
require.LessOrEqual(t, cache.cachedBytes, cfg.MaxBytes)
275+
}
276+
277+
// An in-flight entry at the front of the list must not stop the sweep of expired
278+
// entries behind it.
279+
func TestLruCache_ExpireSkipsInflightEntries(t *testing.T) {
280+
const ttl = time.Minute
281+
var nowNs atomic.Int64
282+
nowNs.Store(time.Hour.Nanoseconds())
283+
cfg := PostingsCacheConfig{Enabled: true, MaxBytes: 10 << 20, Ttl: ttl}
284+
cache := newLruCache[int](cfg, "test", NewPostingCacheMetrics(prometheus.NewPedanticRegistry()),
285+
func() time.Time { return time.Unix(0, nowNs.Load()) })
286+
287+
var fetches atomic.Int64
288+
release := startBlockedFetch(t, cache, "kA", &fetches)
289+
cache.getPromiseForKey("kB", func() (int, int64, error) { return 2, 8, nil })
290+
291+
nowNs.Add((2 * ttl).Nanoseconds())
292+
cache.expire()
293+
294+
require.True(t, cache.contains("kA"), "in-flight entries are never expired")
295+
require.False(t, cache.contains("kB"), "expired entry behind an in-flight front survived expire()")
296+
release()
297+
checkLruInvariants(t, cache)
298+
}
299+
300+
// A fetch that fails while other callers wait on it must return the error to them,
301+
// leave no entry or bytes behind, and let the next caller fetch again.
302+
func TestLruCache_FailedFetchWithWaitersIsNotCached(t *testing.T) {
303+
cfg := PostingsCacheConfig{Enabled: true, MaxBytes: 10 << 20, Ttl: time.Hour}
304+
c := &blocksPostingsForMatchersCache{}
305+
cache := newLruCache[[]storage.SeriesRef](cfg, "test", NewPostingCacheMetrics(prometheus.NewPedanticRegistry()), time.Now)
306+
fetchErr := errors.New("fetch failed")
307+
308+
cache.getPromiseForKey("other", func() ([]storage.SeriesRef, int64, error) { return []storage.SeriesRef{1}, 8, nil })
309+
cache.mu.Lock()
310+
bytesBefore := cache.cachedBytes
311+
cache.mu.Unlock()
312+
313+
release := make(chan struct{})
314+
leaderDone := make(chan struct{})
315+
go func() {
316+
defer close(leaderDone)
317+
cache.getPromiseForKey("key", func() ([]storage.SeriesRef, int64, error) {
318+
<-release
319+
return nil, 0, fetchErr
320+
})
321+
}()
322+
require.Eventually(t, func() bool { return cache.contains("key") }, time.Second, time.Millisecond)
323+
324+
waiter, loaded := cache.getPromiseForKey("key", func() ([]storage.SeriesRef, int64, error) {
325+
t.Fatal("concurrent caller must not fetch")
326+
return nil, 0, nil
327+
})
328+
require.True(t, loaded)
329+
330+
close(release)
331+
<-leaderDone
332+
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
333+
defer cancel()
334+
_, err := c.result(waiter)(ctx)
335+
require.ErrorIs(t, err, fetchErr, "a waiter on a failed fetch gets its error")
336+
337+
require.False(t, cache.contains("key"), "a failed fetch must not stay in the cache")
338+
require.True(t, cache.contains("other"))
339+
require.Equal(t, 1, cache.size())
340+
cache.mu.Lock()
341+
require.Equal(t, bytesBefore, cache.cachedBytes, "a failed fetch must not change cachedBytes")
342+
cache.mu.Unlock()
343+
checkLruInvariants(t, cache)
344+
345+
var fetched atomic.Bool
346+
p, loaded := cache.getPromiseForKey("key", func() ([]storage.SeriesRef, int64, error) {
347+
fetched.Store(true)
348+
return []storage.SeriesRef{7}, 8, nil
349+
})
350+
require.False(t, loaded)
351+
require.True(t, fetched.Load(), "the next caller must fetch again")
352+
postings, err := c.result(p)(ctx)
353+
require.NoError(t, err)
354+
require.True(t, postings.Next())
355+
require.Equal(t, storage.SeriesRef(7), postings.At())
356+
checkLruInvariants(t, cache)
357+
}
358+
222359
// BenchmarkLruCache_BytesPerEntry reports real heap bytes per cached entry for keys of
223360
// about 190 bytes, alongside the bytes the cache accounts for.
224361
func BenchmarkLruCache_BytesPerEntry(b *testing.B) {

0 commit comments

Comments
 (0)