Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions pkg/storage/tsdb/expanded_postings_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -639,21 +639,28 @@ func (c *lruCache[V]) isExpiredLocked(e *cacheEntryPromise[V], now time.Time) bo
}

// evictLocked drops least recently used entries while over budget, then expired ones.
// Entries whose fetch is still running are never expired.
// Entries whose fetch is still running hold no counted bytes and are skipped, so
// eviction never breaks fetch sharing and they do not hide entries behind them.
func (c *lruCache[V]) evictLocked() {
now := c.timeNow()
for c.front != nil {
for e := c.front; e != nil; {
next := e.next
if e.call.Load() != nil {
e = next
continue
}
reason := ""
switch {
case c.cachedBytes > c.cfg.MaxBytes:
reason = "full"
case c.front.call.Load() == nil && c.isExpiredLocked(c.front, now):
case c.isExpiredLocked(e, now):
reason = "expired"
default:
return
}
c.metrics.CacheEvicts.WithLabelValues(c.name, reason).Inc()
c.removeLocked(c.front)
c.removeLocked(e)
e = next
}
}

Expand Down
137 changes: 137 additions & 0 deletions pkg/storage/tsdb/expanded_postings_lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"time"

"github.com/prometheus/client_golang/prometheus"
prom_testutil "github.com/prometheus/client_golang/prometheus/testutil"
"github.com/prometheus/prometheus/storage"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
Expand Down Expand Up @@ -219,6 +220,142 @@ func TestLruCache_FetchPanicDoesNotPoisonKey(t *testing.T) {
checkLruInvariants(t, cache)
}

// startBlockedFetch starts a fetch for k that runs until the returned release is called.
func startBlockedFetch(t *testing.T, cache *lruCache[int], k string, fetches *atomic.Int64) (release func()) {
t.Helper()
unblock := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
cache.getPromiseForKey(k, func() (int, int64, error) {
fetches.Inc()
<-unblock
return 1, 8, nil
})
}()
require.Eventually(t, func() bool { return fetches.Load() == 1 }, time.Second, time.Millisecond)
var once sync.Once
release = func() {
once.Do(func() { close(unblock) })
<-done
}
t.Cleanup(release)
return release
}

// An in-flight entry holds no counted bytes, so the byte budget must evict completed
// entries behind it instead; evicting it would let a later caller start a second fetch.
func TestLruCache_FullEvictionSkipsInflightEntries(t *testing.T) {
cfg := PostingsCacheConfig{Enabled: true, MaxBytes: 15, Ttl: time.Hour}
m := NewPostingCacheMetrics(prometheus.NewPedanticRegistry())
cache := newLruCache[int](cfg, "test", m, time.Now)

var fetches atomic.Int64
release := startBlockedFetch(t, cache, "kA", &fetches)

// kB and kC are 10 bytes each, so completing kC puts the cache over budget.
cache.getPromiseForKey("kB", func() (int, int64, error) { return 2, 8, nil })
cache.getPromiseForKey("kC", func() (int, int64, error) { return 3, 8, nil })

require.True(t, cache.contains("kA"), "in-flight entry evicted for space")
require.False(t, cache.contains("kB"), "the least recently used completed entry must be evicted")
require.True(t, cache.contains("kC"))
require.Equal(t, 1.0, prom_testutil.ToFloat64(m.CacheEvicts.WithLabelValues("test", "full")))

_, loaded := cache.getPromiseForKey("kA", func() (int, int64, error) {
fetches.Inc()
return 1, 8, nil
})
require.True(t, loaded, "a later caller must join the running fetch")
require.Equal(t, int64(1), fetches.Load())

release()
checkLruInvariants(t, cache)
require.LessOrEqual(t, cache.cachedBytes, cfg.MaxBytes)
}

// An in-flight entry at the front of the list must not stop the sweep of expired
// entries behind it.
func TestLruCache_ExpireSkipsInflightEntries(t *testing.T) {
const ttl = time.Minute
var nowNs atomic.Int64
nowNs.Store(time.Hour.Nanoseconds())
cfg := PostingsCacheConfig{Enabled: true, MaxBytes: 10 << 20, Ttl: ttl}
cache := newLruCache[int](cfg, "test", NewPostingCacheMetrics(prometheus.NewPedanticRegistry()),
func() time.Time { return time.Unix(0, nowNs.Load()) })

var fetches atomic.Int64
release := startBlockedFetch(t, cache, "kA", &fetches)
cache.getPromiseForKey("kB", func() (int, int64, error) { return 2, 8, nil })

nowNs.Add((2 * ttl).Nanoseconds())
cache.expire()

require.True(t, cache.contains("kA"), "in-flight entries are never expired")
require.False(t, cache.contains("kB"), "expired entry behind an in-flight front survived expire()")
release()
checkLruInvariants(t, cache)
}

// A fetch that fails while other callers wait on it must return the error to them,
// leave no entry or bytes behind, and let the next caller fetch again.
func TestLruCache_FailedFetchWithWaitersIsNotCached(t *testing.T) {
cfg := PostingsCacheConfig{Enabled: true, MaxBytes: 10 << 20, Ttl: time.Hour}
c := &blocksPostingsForMatchersCache{}
cache := newLruCache[[]storage.SeriesRef](cfg, "test", NewPostingCacheMetrics(prometheus.NewPedanticRegistry()), time.Now)
fetchErr := errors.New("fetch failed")

cache.getPromiseForKey("other", func() ([]storage.SeriesRef, int64, error) { return []storage.SeriesRef{1}, 8, nil })
cache.mu.Lock()
bytesBefore := cache.cachedBytes
cache.mu.Unlock()

release := make(chan struct{})
leaderDone := make(chan struct{})
go func() {
defer close(leaderDone)
cache.getPromiseForKey("key", func() ([]storage.SeriesRef, int64, error) {
<-release
return nil, 0, fetchErr
})
}()
require.Eventually(t, func() bool { return cache.contains("key") }, time.Second, time.Millisecond)

waiter, loaded := cache.getPromiseForKey("key", func() ([]storage.SeriesRef, int64, error) {
t.Fatal("concurrent caller must not fetch")
return nil, 0, nil
})
require.True(t, loaded)

close(release)
<-leaderDone
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err := c.result(waiter)(ctx)
require.ErrorIs(t, err, fetchErr, "a waiter on a failed fetch gets its error")

require.False(t, cache.contains("key"), "a failed fetch must not stay in the cache")
require.True(t, cache.contains("other"))
require.Equal(t, 1, cache.size())
cache.mu.Lock()
require.Equal(t, bytesBefore, cache.cachedBytes, "a failed fetch must not change cachedBytes")
cache.mu.Unlock()
checkLruInvariants(t, cache)

var fetched atomic.Bool
p, loaded := cache.getPromiseForKey("key", func() ([]storage.SeriesRef, int64, error) {
fetched.Store(true)
return []storage.SeriesRef{7}, 8, nil
})
require.False(t, loaded)
require.True(t, fetched.Load(), "the next caller must fetch again")
postings, err := c.result(p)(ctx)
require.NoError(t, err)
require.True(t, postings.Next())
require.Equal(t, storage.SeriesRef(7), postings.At())
checkLruInvariants(t, cache)
}

// BenchmarkLruCache_BytesPerEntry reports real heap bytes per cached entry for keys of
// about 190 bytes, alongside the bytes the cache accounts for.
func BenchmarkLruCache_BytesPerEntry(b *testing.B) {
Expand Down