@@ -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.
224361func BenchmarkLruCache_BytesPerEntry (b * testing.B ) {
0 commit comments