Skip to content

Commit 0e8f9a1

Browse files
committed
Fix: PostingCache promise should fetch data only once
1 parent 2e5488a commit 0e8f9a1

File tree

1 file changed

+37
-13
lines changed

1 file changed

+37
-13
lines changed

pkg/storage/tsdb/expanded_postings_cache_test.go

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,48 @@
11
package tsdb
22

33
import (
4-
"context"
54
"fmt"
65
"strings"
6+
"sync"
77
"testing"
88
"time"
99

1010
"github.com/prometheus/client_golang/prometheus"
1111
"github.com/stretchr/testify/require"
12+
"go.uber.org/atomic"
1213
)
1314

15+
func Test_ShouldFetchPromiseOnlyOnce(t *testing.T) {
16+
cfg := PostingsCacheConfig{
17+
Enabled: true,
18+
Ttl: time.Hour,
19+
MaxBytes: 10 << 20,
20+
}
21+
m := NewPostingCacheMetrics(prometheus.DefaultRegisterer)
22+
cache := newFifoCache[int](cfg, "test", m, time.Now)
23+
calls := atomic.Int64{}
24+
concurrency := 100
25+
wg := sync.WaitGroup{}
26+
wg.Add(concurrency)
27+
28+
fetchFunc := func() (int, int64, error) {
29+
calls.Inc()
30+
time.Sleep(100 * time.Millisecond)
31+
return 0, 0, nil
32+
}
33+
34+
for i := 0; i < 100; i++ {
35+
go func() {
36+
defer wg.Done()
37+
cache.getPromiseForKey("key1", fetchFunc)
38+
}()
39+
}
40+
41+
wg.Wait()
42+
require.Equal(t, int64(1), calls.Load())
43+
44+
}
45+
1446
func TestFifoCacheDisabled(t *testing.T) {
1547
cfg := PostingsCacheConfig{}
1648
cfg.Enabled = false
@@ -21,9 +53,7 @@ func TestFifoCacheDisabled(t *testing.T) {
2153
return 1, 0, nil
2254
})
2355
require.False(t, loaded)
24-
v, err := old.result(context.Background())
25-
require.NoError(t, err)
26-
require.Equal(t, 1, v)
56+
require.Equal(t, 1, old.v)
2757
require.False(t, cache.contains("key1"))
2858
}
2959

@@ -68,17 +98,13 @@ func TestFifoCacheExpire(t *testing.T) {
6898
return 1, 8, nil
6999
})
70100
require.False(t, loaded)
71-
v, err := p.result(context.Background())
72-
require.NoError(t, err)
73-
require.Equal(t, 1, v)
101+
require.Equal(t, 1, p.v)
74102
require.True(t, cache.contains(key))
75103
p, loaded = cache.getPromiseForKey(key, func() (int, int64, error) {
76104
return 1, 0, nil
77105
})
78106
require.True(t, loaded)
79-
v, err = p.result(context.Background())
80-
require.NoError(t, err)
81-
require.Equal(t, 1, v)
107+
require.Equal(t, 1, p.v)
82108
}
83109

84110
totalCacheSize := 0
@@ -104,10 +130,8 @@ func TestFifoCacheExpire(t *testing.T) {
104130
return 2, 18, nil
105131
})
106132
require.False(t, loaded)
107-
v, err := p.result(context.Background())
108-
require.NoError(t, err)
109133
// New value
110-
require.Equal(t, 2, v)
134+
require.Equal(t, 2, p.v)
111135
// Total Size Updated
112136
require.Equal(t, originalSize+10, cache.cachedBytes)
113137
}

0 commit comments

Comments
 (0)