Debian Codegraph @

prometheus/summary_test.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2014 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package prometheus
15
16 import (
17 "math"
18 "math/rand"
19 "sort"
20 "sync"
21 "testing"
22 "testing/quick"
23 "time"
24
25 dto "github.com/prometheus/client_model/go"
26 )
27
28 func TestSummaryWithDefaultObjectives(t *testing.T) {
29 now := time.Now()
30
31 reg := NewRegistry()
32 summaryWithDefaultObjectives := NewSummary(SummaryOpts{
33 Name: "default_objectives",
34 Help: "Test help.",
35 now: func() time.Time { return now },
36 })
37 if err := reg.Register(summaryWithDefaultObjectives); err != nil {
38 t.Error(err)
39 }
40
41 m := &dto.Metric{}
42 if err := summaryWithDefaultObjectives.Write(m); err != nil {
43 t.Error(err)
44 }
45 if len(m.GetSummary().Quantile) != 0 {
46 t.Error("expected no objectives in summary")
47 }
48
49 if !m.Summary.CreatedTimestamp.AsTime().Equal(now) {
50 t.Errorf("expected created timestamp %s, got %s", now, m.Summary.CreatedTimestamp.AsTime())
51 }
52 }
53
54 func TestSummaryWithoutObjectives(t *testing.T) {
55 reg := NewRegistry()
56 summaryWithEmptyObjectives := NewSummary(SummaryOpts{
57 Name: "empty_objectives",
58 Help: "Test help.",
59 Objectives: map[float64]float64{},
60 })
61 if err := reg.Register(summaryWithEmptyObjectives); err != nil {
62 t.Error(err)
63 }
64 summaryWithEmptyObjectives.Observe(3)
65 summaryWithEmptyObjectives.Observe(0.14)
66
67 m := &dto.Metric{}
68 if err := summaryWithEmptyObjectives.Write(m); err != nil {
69 t.Error(err)
70 }
71 if got, want := m.GetSummary().GetSampleSum(), 3.14; got != want {
72 t.Errorf("got sample sum %f, want %f", got, want)
73 }
74 if got, want := m.GetSummary().GetSampleCount(), uint64(2); got != want {
75 t.Errorf("got sample sum %d, want %d", got, want)
76 }
77 if len(m.GetSummary().Quantile) != 0 {
78 t.Error("expected no objectives in summary")
79 }
80 }
81
82 func TestSummaryWithQuantileLabel(t *testing.T) {
83 defer func() {
84 if r := recover(); r == nil {
85 t.Error("Attempt to create Summary with 'quantile' label did not panic.")
86 }
87 }()
88 _ = NewSummary(SummaryOpts{
89 Name: "test_summary",
90 Help: "less",
91 ConstLabels: Labels{"quantile": "test"},
92 })
93 }
94
95 func TestSummaryVecWithQuantileLabel(t *testing.T) {
96 defer func() {
97 if r := recover(); r == nil {
98 t.Error("Attempt to create SummaryVec with 'quantile' label did not panic.")
99 }
100 }()
101 _ = NewSummaryVec(SummaryOpts{
102 Name: "test_summary",
103 Help: "less",
104 }, []string{"quantile"})
105 }
106
107 func benchmarkSummaryObserve(w int, b *testing.B) {
108 b.StopTimer()
109
110 wg := new(sync.WaitGroup)
111 wg.Add(w)
112
113 g := new(sync.WaitGroup)
114 g.Add(1)
115
116 s := NewSummary(SummaryOpts{})
117
118 for i := 0; i < w; i++ {
119 go func() {
120 g.Wait()
121
122 for i := 0; i < b.N; i++ {
123 s.Observe(float64(i))
124 }
125
126 wg.Done()
127 }()
128 }
129
130 b.StartTimer()
131 g.Done()
132 wg.Wait()
133 }
134
135 func BenchmarkSummaryObserve1(b *testing.B) {
136 benchmarkSummaryObserve(1, b)
137 }
138
139 func BenchmarkSummaryObserve2(b *testing.B) {
140 benchmarkSummaryObserve(2, b)
141 }
142
143 func BenchmarkSummaryObserve4(b *testing.B) {
144 benchmarkSummaryObserve(4, b)
145 }
146
147 func BenchmarkSummaryObserve8(b *testing.B) {
148 benchmarkSummaryObserve(8, b)
149 }
150
151 func benchmarkSummaryWrite(w int, b *testing.B) {
152 b.StopTimer()
153
154 wg := new(sync.WaitGroup)
155 wg.Add(w)
156
157 g := new(sync.WaitGroup)
158 g.Add(1)
159
160 s := NewSummary(SummaryOpts{})
161
162 for i := 0; i < 1000000; i++ {
163 s.Observe(float64(i))
164 }
165
166 for j := 0; j < w; j++ {
167 outs := make([]dto.Metric, b.N)
168
169 go func(o []dto.Metric) {
170 g.Wait()
171
172 for i := 0; i < b.N; i++ {
173 s.Write(&o[i])
174 }
175
176 wg.Done()
177 }(outs)
178 }
179
180 b.StartTimer()
181 g.Done()
182 wg.Wait()
183 }
184
185 func BenchmarkSummaryWrite1(b *testing.B) {
186 benchmarkSummaryWrite(1, b)
187 }
188
189 func BenchmarkSummaryWrite2(b *testing.B) {
190 benchmarkSummaryWrite(2, b)
191 }
192
193 func BenchmarkSummaryWrite4(b *testing.B) {
194 benchmarkSummaryWrite(4, b)
195 }
196
197 func BenchmarkSummaryWrite8(b *testing.B) {
198 benchmarkSummaryWrite(8, b)
199 }
200
201 func TestSummaryConcurrency(t *testing.T) {
202 if testing.Short() {
203 t.Skip("Skipping test in short mode.")
204 }
205
206 rand.New(rand.NewSource(42))
207 objMap := map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
208
209 it := func(n uint32) bool {
210 mutations := int(n%1e4 + 1e4)
211 concLevel := int(n%5 + 1)
212 total := mutations * concLevel
213
214 var start, end sync.WaitGroup
215 start.Add(1)
216 end.Add(concLevel)
217
218 sum := NewSummary(SummaryOpts{
219 Name: "test_summary",
220 Help: "helpless",
221 Objectives: objMap,
222 })
223
224 allVars := make([]float64, total)
225 var sampleSum float64
226 for i := 0; i < concLevel; i++ {
227 vals := make([]float64, mutations)
228 for j := 0; j < mutations; j++ {
229 v := rand.NormFloat64()
230 vals[j] = v
231 allVars[i*mutations+j] = v
232 sampleSum += v
233 }
234
235 go func(vals []float64) {
236 start.Wait()
237 for _, v := range vals {
238 sum.Observe(v)
239 }
240 end.Done()
241 }(vals)
242 }
243 sort.Float64s(allVars)
244 start.Done()
245 end.Wait()
246
247 m := &dto.Metric{}
248 sum.Write(m)
249 if got, want := int(*m.Summary.SampleCount), total; got != want {
250 t.Errorf("got sample count %d, want %d", got, want)
251 }
252 if got, want := *m.Summary.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 {
253 t.Errorf("got sample sum %f, want %f", got, want)
254 }
255
256 objSlice := make([]float64, 0, len(objMap))
257 for qu := range objMap {
258 objSlice = append(objSlice, qu)
259 }
260 sort.Float64s(objSlice)
261
262 for i, wantQ := range objSlice {
263 ε := objMap[wantQ]
264 gotQ := *m.Summary.Quantile[i].Quantile
265 gotV := *m.Summary.Quantile[i].Value
266 minBound, maxBound := getBounds(allVars, wantQ, ε)
267 if gotQ != wantQ {
268 t.Errorf("got quantile %f, want %f", gotQ, wantQ)
269 }
270 if gotV < minBound || gotV > maxBound {
271 t.Errorf("got %f for quantile %f, want [%f,%f]", gotV, gotQ, minBound, maxBound)
272 }
273 }
274 return true
275 }
276
277 if err := quick.Check(it, nil); err != nil {
278 t.Error(err)
279 }
280 }
281
282 func TestSummaryVecConcurrency(t *testing.T) {
283 if testing.Short() {
284 t.Skip("Skipping test in short mode.")
285 }
286
287 rand.New(rand.NewSource(42))
288 objMap := map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
289
290 objSlice := make([]float64, 0, len(objMap))
291 for qu := range objMap {
292 objSlice = append(objSlice, qu)
293 }
294 sort.Float64s(objSlice)
295
296 it := func(n uint32) bool {
297 mutations := int(n%1e4 + 1e4)
298 concLevel := int(n%7 + 1)
299 vecLength := int(n%3 + 1)
300
301 var start, end sync.WaitGroup
302 start.Add(1)
303 end.Add(concLevel)
304
305 sum := NewSummaryVec(
306 SummaryOpts{
307 Name: "test_summary",
308 Help: "helpless",
309 Objectives: objMap,
310 },
311 []string{"label"},
312 )
313
314 allVars := make([][]float64, vecLength)
315 sampleSums := make([]float64, vecLength)
316 for i := 0; i < concLevel; i++ {
317 vals := make([]float64, mutations)
318 picks := make([]int, mutations)
319 for j := 0; j < mutations; j++ {
320 v := rand.NormFloat64()
321 vals[j] = v
322 pick := rand.Intn(vecLength)
323 picks[j] = pick
324 allVars[pick] = append(allVars[pick], v)
325 sampleSums[pick] += v
326 }
327
328 go func(vals []float64) {
329 start.Wait()
330 for i, v := range vals {
331 sum.WithLabelValues(string('A' + rune(picks[i]))).Observe(v)
332 }
333 end.Done()
334 }(vals)
335 }
336 for _, vars := range allVars {
337 sort.Float64s(vars)
338 }
339 start.Done()
340 end.Wait()
341
342 for i := 0; i < vecLength; i++ {
343 m := &dto.Metric{}
344 s := sum.WithLabelValues(string('A' + rune(i)))
345 s.(Summary).Write(m)
346 if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want {
347 t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want)
348 }
349 if got, want := *m.Summary.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 {
350 t.Errorf("got sample sum %f for label %c, want %f", got, 'A'+i, want)
351 }
352 for j, wantQ := range objSlice {
353 ε := objMap[wantQ]
354 gotQ := *m.Summary.Quantile[j].Quantile
355 gotV := *m.Summary.Quantile[j].Value
356 minBound, maxBound := getBounds(allVars[i], wantQ, ε)
357 if gotQ != wantQ {
358 t.Errorf("got quantile %f for label %c, want %f", gotQ, 'A'+i, wantQ)
359 }
360 if gotV < minBound || gotV > maxBound {
361 t.Errorf("got %f for quantile %f for label %c, want [%f,%f]", gotV, gotQ, 'A'+i, minBound, maxBound)
362 }
363 }
364 }
365 return true
366 }
367
368 if err := quick.Check(it, nil); err != nil {
369 t.Error(err)
370 }
371 }
372
373 func TestSummaryDecay(t *testing.T) {
•374 t.Skip("Skipping flaky test.")
375 now := time.Now()
376
377 sum := NewSummary(SummaryOpts{
378 Name: "test_summary",
379 Help: "helpless",
380 MaxAge: 100 * time.Millisecond,
381 Objectives: map[float64]float64{0.1: 0.001},
382 AgeBuckets: 10,
383 now: func() time.Time {
384 return now
385 },
386 })
387
388 m := &dto.Metric{}
389 for i := 1; i <= 1000; i++ {
390 now = now.Add(time.Millisecond)
391 sum.Observe(float64(i))
392 if i%10 == 0 {
393 sum.Write(m)
394 got := *m.Summary.Quantile[0].Value
395 want := math.Max(float64(i)/10, float64(i-90))
396 if math.Abs(got-want) > 20 {
397 t.Errorf("%d. got %f, want %f", i, got, want)
398 }
399 m.Reset()
400 }
401 }
402
403 // Simulate waiting for MaxAge without observations
404 now = now.Add(100 * time.Millisecond)
405 sum.Write(m)
406 if got := *m.Summary.Quantile[0].Value; !math.IsNaN(got) {
407 t.Errorf("got %f, want NaN after expiration", got)
408 }
409 }
410
411 func getBounds(vars []float64, q, ε float64) (minBound, maxBound float64) {
412 // TODO(beorn7): This currently tolerates an error of up to 2*ε. The
413 // error must be at most ε, but for some reason, it's sometimes slightly
414 // higher. That's a bug.
415 n := float64(len(vars))
416 lower := int((q - 2*ε) * n)
417 upper := int(math.Ceil((q + 2*ε) * n))
418 minBound = vars[0]
419 if lower > 1 {
420 minBound = vars[lower-1]
421 }
422 maxBound = vars[len(vars)-1]
423 if upper < len(vars) {
424 maxBound = vars[upper-1]
425 }
426 return
427 }
428
429 func TestSummaryVecCreatedTimestampWithDeletes(t *testing.T) {
430 for _, tcase := range []struct {
431 desc string
432 objectives map[float64]float64
433 }{
434 {desc: "summary with objectives", objectives: map[float64]float64{1.0: 1.0}},
435 {desc: "no objectives summary", objectives: nil},
436 } {
437 now := time.Now()
438 t.Run(tcase.desc, func(t *testing.T) {
439 summaryVec := NewSummaryVec(SummaryOpts{
440 Name: "test",
441 Help: "test help",
442 Objectives: tcase.objectives,
443 now: func() time.Time { return now },
444 }, []string{"label"})
445
446 // First use of "With" should populate CT.
447 summaryVec.WithLabelValues("1")
448 expected := map[string]time.Time{"1": now}
449
450 now = now.Add(1 * time.Hour)
451 expectCTsForMetricVecValues(t, summaryVec.MetricVec, dto.MetricType_SUMMARY, expected)
452
453 // Two more labels at different times.
454 summaryVec.WithLabelValues("2")
455 expected["2"] = now
456
457 now = now.Add(1 * time.Hour)
458
459 summaryVec.WithLabelValues("3")
460 expected["3"] = now
461
462 now = now.Add(1 * time.Hour)
463 expectCTsForMetricVecValues(t, summaryVec.MetricVec, dto.MetricType_SUMMARY, expected)
464
465 // Recreate metric instance should reset created timestamp to now.
466 summaryVec.DeleteLabelValues("1")
467 summaryVec.WithLabelValues("1")
468 expected["1"] = now
469
470 now = now.Add(1 * time.Hour)
471 expectCTsForMetricVecValues(t, summaryVec.MetricVec, dto.MetricType_SUMMARY, expected)
472 })
473 }
474 }
475
476 func TestNewConstSummaryWithCreatedTimestamp(t *testing.T) {
477 metricDesc := NewDesc(
478 "sample_value",
479 "sample value",
480 nil,
481 nil,
482 )
483 quantiles := map[float64]float64{50: 200.12, 99: 500.342}
484 createdTs := time.Unix(1719670764, 123)
485
486 s, err := NewConstSummaryWithCreatedTimestamp(metricDesc, 100, 200, quantiles, createdTs)
487 if err != nil {
488 t.Fatal(err)
489 }
490
491 var metric dto.Metric
492 if err := s.Write(&metric); err != nil {
493 t.Fatal(err)
494 }
495
496 if metric.Summary.CreatedTimestamp.AsTime().UnixMicro() != createdTs.UnixMicro() {
497 t.Errorf("Expected created timestamp %v, got %v", createdTs, &metric.Summary.CreatedTimestamp)
498 }
499 }