Debian Codegraph @

prometheus/histogram_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2015 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 "reflect"
20 "runtime"
21 "sort"
22 "sync"
23 "sync/atomic"
24 "testing"
25 "testing/quick"
26 "time"
27
28 dto "github.com/prometheus/client_model/go"
29 "google.golang.org/protobuf/proto"
30 "google.golang.org/protobuf/types/known/timestamppb"
31
32 "github.com/prometheus/client_golang/prometheus/internal"
33 )
34
35 func benchmarkHistogramObserve(w int, b *testing.B) {
36 b.StopTimer()
37
38 wg := new(sync.WaitGroup)
39 wg.Add(w)
40
41 g := new(sync.WaitGroup)
42 g.Add(1)
43
44 s := NewHistogram(HistogramOpts{})
45
46 for i := 0; i < w; i++ {
47 go func() {
48 g.Wait()
49
50 for i := 0; i < b.N; i++ {
51 s.Observe(float64(i))
52 }
53
54 wg.Done()
55 }()
56 }
57
58 b.StartTimer()
59 g.Done()
60 wg.Wait()
61 }
62
63 func BenchmarkHistogramObserve1(b *testing.B) {
64 benchmarkHistogramObserve(1, b)
65 }
66
67 func BenchmarkHistogramObserve2(b *testing.B) {
68 benchmarkHistogramObserve(2, b)
69 }
70
71 func BenchmarkHistogramObserve4(b *testing.B) {
72 benchmarkHistogramObserve(4, b)
73 }
74
75 func BenchmarkHistogramObserve8(b *testing.B) {
76 benchmarkHistogramObserve(8, b)
77 }
78
79 func benchmarkHistogramWrite(w int, b *testing.B) {
80 b.StopTimer()
81
82 wg := new(sync.WaitGroup)
83 wg.Add(w)
84
85 g := new(sync.WaitGroup)
86 g.Add(1)
87
88 s := NewHistogram(HistogramOpts{})
89
90 for i := 0; i < 1000000; i++ {
91 s.Observe(float64(i))
92 }
93
94 for j := 0; j < w; j++ {
95 outs := make([]dto.Metric, b.N)
96
97 go func(o []dto.Metric) {
98 g.Wait()
99
100 for i := 0; i < b.N; i++ {
101 s.Write(&o[i])
102 }
103
104 wg.Done()
105 }(outs)
106 }
107
108 b.StartTimer()
109 g.Done()
110 wg.Wait()
111 }
112
113 func BenchmarkHistogramWrite1(b *testing.B) {
114 benchmarkHistogramWrite(1, b)
115 }
116
117 func BenchmarkHistogramWrite2(b *testing.B) {
118 benchmarkHistogramWrite(2, b)
119 }
120
121 func BenchmarkHistogramWrite4(b *testing.B) {
122 benchmarkHistogramWrite(4, b)
123 }
124
125 func BenchmarkHistogramWrite8(b *testing.B) {
126 benchmarkHistogramWrite(8, b)
127 }
128
129 func TestHistogramNonMonotonicBuckets(t *testing.T) {
130 testCases := map[string][]float64{
131 "not strictly monotonic": {1, 2, 2, 3},
132 "not monotonic at all": {1, 2, 4, 3, 5},
133 "have +Inf in the middle": {1, 2, math.Inf(+1), 3},
134 }
135 for name, buckets := range testCases {
136 func() {
137 defer func() {
138 if r := recover(); r == nil {
139 t.Errorf("Buckets %v are %s but NewHistogram did not panic.", buckets, name)
140 }
141 }()
142 _ = NewHistogram(HistogramOpts{
143 Name: "test_histogram",
144 Help: "helpless",
145 Buckets: buckets,
146 })
147 }()
148 }
149 }
150
151 // Intentionally adding +Inf here to test if that case is handled correctly.
152 // Also, getCumulativeCounts depends on it.
153 var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}
154
155 func TestHistogramConcurrency(t *testing.T) {
156 if testing.Short() {
157 t.Skip("Skipping test in short mode.")
158 }
159
160 rand.New(rand.NewSource(42))
161
162 it := func(n uint32) bool {
163 mutations := int(n%1e4 + 1e4)
164 concLevel := int(n%5 + 1)
165 total := mutations * concLevel
166
167 var start, end sync.WaitGroup
168 start.Add(1)
169 end.Add(concLevel)
170
171 his := NewHistogram(HistogramOpts{
172 Name: "test_histogram",
173 Help: "helpless",
174 Buckets: testBuckets,
175 })
176
177 allVars := make([]float64, total)
178 var sampleSum float64
179 for i := 0; i < concLevel; i++ {
180 vals := make([]float64, mutations)
181 for j := 0; j < mutations; j++ {
182 v := rand.NormFloat64()
183 vals[j] = v
184 allVars[i*mutations+j] = v
185 sampleSum += v
186 }
187
188 go func(vals []float64) {
189 start.Wait()
190 for _, v := range vals {
191 if n%2 == 0 {
192 his.Observe(v)
193 } else {
194 his.(ExemplarObserver).ObserveWithExemplar(v, Labels{"foo": "bar"})
195 }
196 }
197 end.Done()
198 }(vals)
199 }
200 sort.Float64s(allVars)
201 start.Done()
202 end.Wait()
203
204 m := &dto.Metric{}
205 his.Write(m)
206 if got, want := int(*m.Histogram.SampleCount), total; got != want {
207 t.Errorf("got sample count %d, want %d", got, want)
208 }
209 if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 {
210 t.Errorf("got sample sum %f, want %f", got, want)
211 }
212
213 wantCounts := getCumulativeCounts(allVars)
214 wantBuckets := len(testBuckets)
215 if !math.IsInf(m.Histogram.Bucket[len(m.Histogram.Bucket)-1].GetUpperBound(), +1) {
216 wantBuckets--
217 }
218
219 if got := len(m.Histogram.Bucket); got != wantBuckets {
220 t.Errorf("got %d buckets in protobuf, want %d", got, wantBuckets)
221 }
222 for i, wantBound := range testBuckets {
223 if i == len(testBuckets)-1 {
224 break // No +Inf bucket in protobuf.
225 }
226 if gotBound := *m.Histogram.Bucket[i].UpperBound; gotBound != wantBound {
227 t.Errorf("got bound %f, want %f", gotBound, wantBound)
228 }
229 if gotCount, wantCount := *m.Histogram.Bucket[i].CumulativeCount, wantCounts[i]; gotCount != wantCount {
230 t.Errorf("got count %d, want %d", gotCount, wantCount)
231 }
232 }
233 return true
234 }
235
236 if err := quick.Check(it, nil); err != nil {
237 t.Error(err)
238 }
239 }
240
241 func TestHistogramVecConcurrency(t *testing.T) {
242 if testing.Short() {
243 t.Skip("Skipping test in short mode.")
244 }
245
246 rand.New(rand.NewSource(42))
247
248 it := func(n uint32) bool {
249 mutations := int(n%1e4 + 1e4)
250 concLevel := int(n%7 + 1)
251 vecLength := int(n%3 + 1)
252
253 var start, end sync.WaitGroup
254 start.Add(1)
255 end.Add(concLevel)
256
257 his := NewHistogramVec(
258 HistogramOpts{
259 Name: "test_histogram",
260 Help: "helpless",
261 Buckets: []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)},
262 },
263 []string{"label"},
264 )
265
266 allVars := make([][]float64, vecLength)
267 sampleSums := make([]float64, vecLength)
268 for i := 0; i < concLevel; i++ {
269 vals := make([]float64, mutations)
270 picks := make([]int, mutations)
271 for j := 0; j < mutations; j++ {
272 v := rand.NormFloat64()
273 vals[j] = v
274 pick := rand.Intn(vecLength)
275 picks[j] = pick
276 allVars[pick] = append(allVars[pick], v)
277 sampleSums[pick] += v
278 }
279
280 go func(vals []float64) {
281 start.Wait()
282 for i, v := range vals {
283 his.WithLabelValues(string('A' + rune(picks[i]))).Observe(v)
284 }
285 end.Done()
286 }(vals)
287 }
288 for _, vars := range allVars {
289 sort.Float64s(vars)
290 }
291 start.Done()
292 end.Wait()
293
294 for i := 0; i < vecLength; i++ {
295 m := &dto.Metric{}
296 s := his.WithLabelValues(string('A' + rune(i)))
297 s.(Histogram).Write(m)
298
299 if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want {
300 t.Errorf("got %d buckets in protobuf, want %d", got, want)
301 }
302 if got, want := int(*m.Histogram.SampleCount), len(allVars[i]); got != want {
303 t.Errorf("got sample count %d, want %d", got, want)
304 }
305 if got, want := *m.Histogram.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 {
306 t.Errorf("got sample sum %f, want %f", got, want)
307 }
308
309 wantCounts := getCumulativeCounts(allVars[i])
310
311 for j, wantBound := range testBuckets {
312 if j == len(testBuckets)-1 {
313 break // No +Inf bucket in protobuf.
314 }
315 if gotBound := *m.Histogram.Bucket[j].UpperBound; gotBound != wantBound {
316 t.Errorf("got bound %f, want %f", gotBound, wantBound)
317 }
318 if gotCount, wantCount := *m.Histogram.Bucket[j].CumulativeCount, wantCounts[j]; gotCount != wantCount {
319 t.Errorf("got count %d, want %d", gotCount, wantCount)
320 }
321 }
322 }
323 return true
324 }
325
326 if err := quick.Check(it, nil); err != nil {
327 t.Error(err)
328 }
329 }
330
331 func getCumulativeCounts(vars []float64) []uint64 {
332 counts := make([]uint64, len(testBuckets))
333 for _, v := range vars {
334 for i := len(testBuckets) - 1; i >= 0; i-- {
335 if v > testBuckets[i] {
336 break
337 }
338 counts[i]++
339 }
340 }
341 return counts
342 }
343
344 func TestBuckets(t *testing.T) {
345 got := LinearBuckets(-15, 5, 6)
346 want := []float64{-15, -10, -5, 0, 5, 10}
347 if !reflect.DeepEqual(got, want) {
348 t.Errorf("linear buckets: got %v, want %v", got, want)
349 }
350
351 got = ExponentialBuckets(100, 1.2, 3)
352 want = []float64{100, 120, 144}
353 if !reflect.DeepEqual(got, want) {
354 t.Errorf("exponential buckets: got %v, want %v", got, want)
355 }
356
357 got = ExponentialBucketsRange(1, 100, 10)
358 want = []float64{
359 1.0, 1.6681, 2.7825, 4.6415, 7.7426, 12.9154, 21.5443,
360 35.9381, 59.9484, 100.0000,
361 }
362 const epsilon = 0.0001
363 if !internal.AlmostEqualFloat64s(got, want, epsilon) {
364 t.Errorf("exponential buckets range: got %v, want %v (epsilon %f)", got, want, epsilon)
365 }
366 }
367
368 func TestHistogramAtomicObserve(t *testing.T) {
369 var (
370 quit = make(chan struct{})
371 his = NewHistogram(HistogramOpts{
372 Buckets: []float64{0.5, 10, 20},
373 })
374 )
375
376 defer func() { close(quit) }()
377
378 observe := func() {
379 for {
380 select {
381 case <-quit:
382 return
383 default:
384 his.Observe(1)
385 time.Sleep(time.Nanosecond)
386 }
387 }
388 }
389
390 go observe()
391 go observe()
392 go observe()
393
394 for i := 0; i < 100; i++ {
395 m := &dto.Metric{}
396 if err := his.Write(m); err != nil {
397 t.Fatal("unexpected error writing histogram:", err)
398 }
399 h := m.GetHistogram()
400 if h.GetSampleCount() != uint64(h.GetSampleSum()) ||
401 h.GetSampleCount() != h.GetBucket()[1].GetCumulativeCount() ||
402 h.GetSampleCount() != h.GetBucket()[2].GetCumulativeCount() {
403 t.Fatalf(
404 "inconsistent counts in histogram: count=%d sum=%f buckets=[%d, %d]",
405 h.GetSampleCount(), h.GetSampleSum(),
406 h.GetBucket()[1].GetCumulativeCount(), h.GetBucket()[2].GetCumulativeCount(),
407 )
408 }
409 runtime.Gosched()
410 }
411 }
412
413 func TestHistogramExemplar(t *testing.T) {
414 now := time.Now()
415
416 histogram := NewHistogram(HistogramOpts{
417 Name: "test",
418 Help: "test help",
419 Buckets: []float64{1, 2, 3, 4},
420 now: func() time.Time { return now },
421 }).(*histogram)
422
423 ts := timestamppb.New(now)
424 if err := ts.CheckValid(); err != nil {
425 t.Fatal(err)
426 }
427 expectedExemplars := []*dto.Exemplar{
428 nil,
429 {
430 Label: []*dto.LabelPair{
431 {Name: proto.String("id"), Value: proto.String("2")},
432 },
433 Value: proto.Float64(1.6),
434 Timestamp: ts,
435 },
436 nil,
437 {
438 Label: []*dto.LabelPair{
439 {Name: proto.String("id"), Value: proto.String("3")},
440 },
441 Value: proto.Float64(4),
442 Timestamp: ts,
443 },
444 {
445 Label: []*dto.LabelPair{
446 {Name: proto.String("id"), Value: proto.String("4")},
447 },
448 Value: proto.Float64(4.5),
449 Timestamp: ts,
450 },
451 }
452
453 histogram.ObserveWithExemplar(1.5, Labels{"id": "1"})
454 histogram.ObserveWithExemplar(1.6, Labels{"id": "2"}) // To replace exemplar in bucket 0.
455 histogram.ObserveWithExemplar(4, Labels{"id": "3"})
456 histogram.ObserveWithExemplar(4.5, Labels{"id": "4"}) // Should go to +Inf bucket.
457
458 for i, ex := range histogram.exemplars {
459 var got, expected string
460 if val := ex.Load(); val != nil {
461 got = val.(*dto.Exemplar).String()
462 }
463 if expectedExemplars[i] != nil {
464 expected = expectedExemplars[i].String()
465 }
466 if got != expected {
467 t.Errorf("expected exemplar %s, got %s.", expected, got)
468 }
469 }
470 }
471
472 func TestNativeHistogram(t *testing.T) {
473 now := time.Now()
474
475 scenarios := []struct {
476 name string
477 observations []float64 // With simulated interval of 1m.
478 factor float64
479 zeroThreshold float64
480 maxBuckets uint32
481 minResetDuration time.Duration
482 maxZeroThreshold float64
483 want *dto.Histogram
484 }{
485 {
486 name: "no sparse buckets",
487 observations: []float64{1, 2, 3},
488 factor: 1,
489 want: &dto.Histogram{
490 SampleCount: proto.Uint64(3),
491 SampleSum: proto.Float64(6),
492 Bucket: []*dto.Bucket{
493 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.005)},
494 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.01)},
495 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.025)},
496 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.05)},
497 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.1)},
498 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.25)},
499 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.5)},
500 {CumulativeCount: proto.Uint64(1), UpperBound: proto.Float64(1)},
501 {CumulativeCount: proto.Uint64(2), UpperBound: proto.Float64(2.5)},
502 {CumulativeCount: proto.Uint64(3), UpperBound: proto.Float64(5)},
503 {CumulativeCount: proto.Uint64(3), UpperBound: proto.Float64(10)},
504 },
505 CreatedTimestamp: timestamppb.New(now),
506 },
507 },
508 {
509 name: "no observations",
510 factor: 1.1,
511 want: &dto.Histogram{
512 SampleCount: proto.Uint64(0),
513 SampleSum: proto.Float64(0),
514 Schema: proto.Int32(3),
515 ZeroThreshold: proto.Float64(2.938735877055719e-39),
516 ZeroCount: proto.Uint64(0),
517 CreatedTimestamp: timestamppb.New(now),
518 },
519 },
520 {
521 name: "no observations and zero threshold of zero resulting in no-op span",
522 factor: 1.1,
523 zeroThreshold: NativeHistogramZeroThresholdZero,
524 want: &dto.Histogram{
525 SampleCount: proto.Uint64(0),
526 SampleSum: proto.Float64(0),
527 Schema: proto.Int32(3),
528 ZeroThreshold: proto.Float64(0),
529 ZeroCount: proto.Uint64(0),
530 PositiveSpan: []*dto.BucketSpan{
531 {Offset: proto.Int32(0), Length: proto.Uint32(0)},
532 },
533 CreatedTimestamp: timestamppb.New(now),
534 },
535 },
536 {
537 name: "factor 1.1 results in schema 3",
538 observations: []float64{0, 1, 2, 3},
539 factor: 1.1,
540 want: &dto.Histogram{
541 SampleCount: proto.Uint64(4),
542 SampleSum: proto.Float64(6),
543 Schema: proto.Int32(3),
544 ZeroThreshold: proto.Float64(2.938735877055719e-39),
545 ZeroCount: proto.Uint64(1),
546 PositiveSpan: []*dto.BucketSpan{
547 {Offset: proto.Int32(0), Length: proto.Uint32(1)},
548 {Offset: proto.Int32(7), Length: proto.Uint32(1)},
549 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
550 },
551 PositiveDelta: []int64{1, 0, 0},
552 CreatedTimestamp: timestamppb.New(now),
553 },
554 },
555 {
556 name: "factor 1.2 results in schema 2",
557 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
558 factor: 1.2,
559 want: &dto.Histogram{
560 SampleCount: proto.Uint64(6),
561 SampleSum: proto.Float64(7.4),
562 Schema: proto.Int32(2),
563 ZeroThreshold: proto.Float64(2.938735877055719e-39),
564 ZeroCount: proto.Uint64(1),
565 PositiveSpan: []*dto.BucketSpan{
566 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
567 },
568 PositiveDelta: []int64{1, -1, 2, -2, 2},
569 CreatedTimestamp: timestamppb.New(now),
570 },
571 },
572 {
573 name: "factor 4 results in schema -1",
574 observations: []float64{
575 0.0156251, 0.0625, // Bucket -2: (0.015625, 0.0625)
576 0.1, 0.25, // Bucket -1: (0.0625, 0.25]
577 0.5, 1, // Bucket 0: (0.25, 1]
578 1.5, 2, 3, 3.5, // Bucket 1: (1, 4]
579 5, 6, 7, // Bucket 2: (4, 16]
580 33.33, // Bucket 3: (16, 64]
581 },
582 factor: 4,
583 want: &dto.Histogram{
584 SampleCount: proto.Uint64(14),
585 SampleSum: proto.Float64(63.2581251),
586 Schema: proto.Int32(-1),
587 ZeroThreshold: proto.Float64(2.938735877055719e-39),
588 ZeroCount: proto.Uint64(0),
589 PositiveSpan: []*dto.BucketSpan{
590 {Offset: proto.Int32(-2), Length: proto.Uint32(6)},
591 },
592 PositiveDelta: []int64{2, 0, 0, 2, -1, -2},
593 CreatedTimestamp: timestamppb.New(now),
594 },
595 },
596 {
597 name: "factor 17 results in schema -2",
598 observations: []float64{
599 0.0156251, 0.0625, // Bucket -1: (0.015625, 0.0625]
600 0.1, 0.25, 0.5, 1, // Bucket 0: (0.0625, 1]
601 1.5, 2, 3, 3.5, 5, 6, 7, // Bucket 1: (1, 16]
602 33.33, // Bucket 2: (16, 256]
603 },
604 factor: 17,
605 want: &dto.Histogram{
606 SampleCount: proto.Uint64(14),
607 SampleSum: proto.Float64(63.2581251),
608 Schema: proto.Int32(-2),
609 ZeroThreshold: proto.Float64(2.938735877055719e-39),
610 ZeroCount: proto.Uint64(0),
611 PositiveSpan: []*dto.BucketSpan{
612 {Offset: proto.Int32(-1), Length: proto.Uint32(4)},
613 },
614 PositiveDelta: []int64{2, 2, 3, -6},
615 CreatedTimestamp: timestamppb.New(now),
616 },
617 },
618 {
619 name: "negative buckets",
620 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
621 factor: 1.2,
622 want: &dto.Histogram{
623 SampleCount: proto.Uint64(6),
624 SampleSum: proto.Float64(-7.4),
625 Schema: proto.Int32(2),
626 ZeroThreshold: proto.Float64(2.938735877055719e-39),
627 ZeroCount: proto.Uint64(1),
628 NegativeSpan: []*dto.BucketSpan{
629 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
630 },
631 NegativeDelta: []int64{1, -1, 2, -2, 2},
632 CreatedTimestamp: timestamppb.New(now),
633 },
634 },
635 {
636 name: "negative and positive buckets",
637 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
638 factor: 1.2,
639 want: &dto.Histogram{
640 SampleCount: proto.Uint64(11),
641 SampleSum: proto.Float64(0),
642 Schema: proto.Int32(2),
643 ZeroThreshold: proto.Float64(2.938735877055719e-39),
644 ZeroCount: proto.Uint64(1),
645 NegativeSpan: []*dto.BucketSpan{
646 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
647 },
648 NegativeDelta: []int64{1, -1, 2, -2, 2},
649 PositiveSpan: []*dto.BucketSpan{
650 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
651 },
652 PositiveDelta: []int64{1, -1, 2, -2, 2},
653 CreatedTimestamp: timestamppb.New(now),
654 },
655 },
656 {
657 name: "wide zero bucket",
658 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
659 factor: 1.2,
660 zeroThreshold: 1.4,
661 want: &dto.Histogram{
662 SampleCount: proto.Uint64(11),
663 SampleSum: proto.Float64(0),
664 Schema: proto.Int32(2),
665 ZeroThreshold: proto.Float64(1.4),
666 ZeroCount: proto.Uint64(7),
667 NegativeSpan: []*dto.BucketSpan{
668 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
669 },
670 NegativeDelta: []int64{2},
671 PositiveSpan: []*dto.BucketSpan{
672 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
673 },
674 PositiveDelta: []int64{2},
675 CreatedTimestamp: timestamppb.New(now),
676 },
677 },
678 {
679 name: "NaN observation",
680 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.NaN()},
681 factor: 1.2,
682 want: &dto.Histogram{
683 SampleCount: proto.Uint64(7),
684 SampleSum: proto.Float64(math.NaN()),
685 Schema: proto.Int32(2),
686 ZeroThreshold: proto.Float64(2.938735877055719e-39),
687 ZeroCount: proto.Uint64(1),
688 PositiveSpan: []*dto.BucketSpan{
689 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
690 },
691 PositiveDelta: []int64{1, -1, 2, -2, 2},
692 CreatedTimestamp: timestamppb.New(now),
693 },
694 },
695 {
696 name: "+Inf observation",
697 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(+1)},
698 factor: 1.2,
699 want: &dto.Histogram{
700 SampleCount: proto.Uint64(7),
701 SampleSum: proto.Float64(math.Inf(+1)),
702 Schema: proto.Int32(2),
703 ZeroThreshold: proto.Float64(2.938735877055719e-39),
704 ZeroCount: proto.Uint64(1),
705 PositiveSpan: []*dto.BucketSpan{
706 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
707 {Offset: proto.Int32(4092), Length: proto.Uint32(1)},
708 },
709 PositiveDelta: []int64{1, -1, 2, -2, 2, -1},
710 CreatedTimestamp: timestamppb.New(now),
711 },
712 },
713 {
714 name: "-Inf observation",
715 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(-1)},
716 factor: 1.2,
717 want: &dto.Histogram{
718 SampleCount: proto.Uint64(7),
719 SampleSum: proto.Float64(math.Inf(-1)),
720 Schema: proto.Int32(2),
721 ZeroThreshold: proto.Float64(2.938735877055719e-39),
722 ZeroCount: proto.Uint64(1),
723 NegativeSpan: []*dto.BucketSpan{
724 {Offset: proto.Int32(4097), Length: proto.Uint32(1)},
725 },
726 NegativeDelta: []int64{1},
727 PositiveSpan: []*dto.BucketSpan{
728 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
729 },
730 PositiveDelta: []int64{1, -1, 2, -2, 2},
731 CreatedTimestamp: timestamppb.New(now),
732 },
733 },
734 {
735 name: "limited buckets but nothing triggered",
736 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
737 factor: 1.2,
738 maxBuckets: 4,
739 want: &dto.Histogram{
740 SampleCount: proto.Uint64(6),
741 SampleSum: proto.Float64(7.4),
742 Schema: proto.Int32(2),
743 ZeroThreshold: proto.Float64(2.938735877055719e-39),
744 ZeroCount: proto.Uint64(1),
745 PositiveSpan: []*dto.BucketSpan{
746 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
747 },
748 PositiveDelta: []int64{1, -1, 2, -2, 2},
749 CreatedTimestamp: timestamppb.New(now),
750 },
751 },
752 {
753 name: "buckets limited by halving resolution",
754 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
755 factor: 1.2,
756 maxBuckets: 4,
757 want: &dto.Histogram{
758 SampleCount: proto.Uint64(8),
759 SampleSum: proto.Float64(11.5),
760 Schema: proto.Int32(1),
761 ZeroThreshold: proto.Float64(2.938735877055719e-39),
762 ZeroCount: proto.Uint64(1),
763 PositiveSpan: []*dto.BucketSpan{
764 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
765 },
766 PositiveDelta: []int64{1, 2, -1, -2, 1},
767 CreatedTimestamp: timestamppb.New(now),
768 },
769 },
770 {
771 name: "buckets limited by widening the zero bucket",
772 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
773 factor: 1.2,
774 maxBuckets: 4,
775 maxZeroThreshold: 1.2,
776 want: &dto.Histogram{
777 SampleCount: proto.Uint64(8),
778 SampleSum: proto.Float64(11.5),
779 Schema: proto.Int32(2),
780 ZeroThreshold: proto.Float64(1),
781 ZeroCount: proto.Uint64(2),
782 PositiveSpan: []*dto.BucketSpan{
783 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
784 },
785 PositiveDelta: []int64{1, 1, -2, 2, -2, 0, 1},
786 CreatedTimestamp: timestamppb.New(now),
787 },
788 },
789 {
790 name: "buckets limited by widening the zero bucket twice",
791 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
792 factor: 1.2,
793 maxBuckets: 4,
794 maxZeroThreshold: 1.2,
795 want: &dto.Histogram{
796 SampleCount: proto.Uint64(9),
797 SampleSum: proto.Float64(15.5),
798 Schema: proto.Int32(2),
799 ZeroThreshold: proto.Float64(1.189207115002721),
800 ZeroCount: proto.Uint64(3),
801 PositiveSpan: []*dto.BucketSpan{
802 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
803 },
804 PositiveDelta: []int64{2, -2, 2, -2, 0, 1, 0},
805 CreatedTimestamp: timestamppb.New(now),
806 },
807 },
808 {
809 name: "buckets limited by reset",
810 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
811 factor: 1.2,
812 maxBuckets: 4,
813 maxZeroThreshold: 1.2,
814 minResetDuration: 5 * time.Minute,
815 want: &dto.Histogram{
816 SampleCount: proto.Uint64(2),
817 SampleSum: proto.Float64(7),
818 Schema: proto.Int32(2),
819 ZeroThreshold: proto.Float64(2.938735877055719e-39),
820 ZeroCount: proto.Uint64(0),
821 PositiveSpan: []*dto.BucketSpan{
822 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
823 },
824 PositiveDelta: []int64{1, 0},
825 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
826 },
827 },
828 {
829 name: "limited buckets but nothing triggered, negative observations",
830 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
831 factor: 1.2,
832 maxBuckets: 4,
833 want: &dto.Histogram{
834 SampleCount: proto.Uint64(6),
835 SampleSum: proto.Float64(-7.4),
836 Schema: proto.Int32(2),
837 ZeroThreshold: proto.Float64(2.938735877055719e-39),
838 ZeroCount: proto.Uint64(1),
839 NegativeSpan: []*dto.BucketSpan{
840 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
841 },
842 NegativeDelta: []int64{1, -1, 2, -2, 2},
843 CreatedTimestamp: timestamppb.New(now),
844 },
845 },
846 {
847 name: "buckets limited by halving resolution, negative observations",
848 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
849 factor: 1.2,
850 maxBuckets: 4,
851 want: &dto.Histogram{
852 SampleCount: proto.Uint64(8),
853 SampleSum: proto.Float64(-11.5),
854 Schema: proto.Int32(1),
855 ZeroThreshold: proto.Float64(2.938735877055719e-39),
856 ZeroCount: proto.Uint64(1),
857 NegativeSpan: []*dto.BucketSpan{
858 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
859 },
860 NegativeDelta: []int64{1, 2, -1, -2, 1},
861 CreatedTimestamp: timestamppb.New(now),
862 },
863 },
864 {
865 name: "buckets limited by widening the zero bucket, negative observations",
866 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
867 factor: 1.2,
868 maxBuckets: 4,
869 maxZeroThreshold: 1.2,
870 want: &dto.Histogram{
871 SampleCount: proto.Uint64(8),
872 SampleSum: proto.Float64(-11.5),
873 Schema: proto.Int32(2),
874 ZeroThreshold: proto.Float64(1),
875 ZeroCount: proto.Uint64(2),
876 NegativeSpan: []*dto.BucketSpan{
877 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
878 },
879 NegativeDelta: []int64{1, 1, -2, 2, -2, 0, 1},
880 CreatedTimestamp: timestamppb.New(now),
881 },
882 },
883 {
884 name: "buckets limited by widening the zero bucket twice, negative observations",
885 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
886 factor: 1.2,
887 maxBuckets: 4,
888 maxZeroThreshold: 1.2,
889 want: &dto.Histogram{
890 SampleCount: proto.Uint64(9),
891 SampleSum: proto.Float64(-15.5),
892 Schema: proto.Int32(2),
893 ZeroThreshold: proto.Float64(1.189207115002721),
894 ZeroCount: proto.Uint64(3),
895 NegativeSpan: []*dto.BucketSpan{
896 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
897 },
898 NegativeDelta: []int64{2, -2, 2, -2, 0, 1, 0},
899 CreatedTimestamp: timestamppb.New(now),
900 },
901 },
902 {
903 name: "buckets limited by reset, negative observations",
904 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
905 factor: 1.2,
906 maxBuckets: 4,
907 maxZeroThreshold: 1.2,
908 minResetDuration: 5 * time.Minute,
909 want: &dto.Histogram{
910 SampleCount: proto.Uint64(2),
911 SampleSum: proto.Float64(-7),
912 Schema: proto.Int32(2),
913 ZeroThreshold: proto.Float64(2.938735877055719e-39),
914 ZeroCount: proto.Uint64(0),
915 NegativeSpan: []*dto.BucketSpan{
916 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
917 },
918 NegativeDelta: []int64{1, 0},
919 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
920 },
921 },
922 {
923 name: "buckets limited by halving resolution, then reset",
924 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
925 factor: 1.2,
926 maxBuckets: 4,
927 minResetDuration: 9 * time.Minute,
928 want: &dto.Histogram{
929 SampleCount: proto.Uint64(3),
930 SampleSum: proto.Float64(12.1),
931 Schema: proto.Int32(2),
932 ZeroThreshold: proto.Float64(2.938735877055719e-39),
933 ZeroCount: proto.Uint64(0),
934 PositiveSpan: []*dto.BucketSpan{
935 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
936 },
937 PositiveDelta: []int64{1, 0, -1, 1},
938 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
939 },
940 },
941 {
942 name: "buckets limited by widening the zero bucket, then reset",
943 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
944 factor: 1.2,
945 maxBuckets: 4,
946 maxZeroThreshold: 1.2,
947 minResetDuration: 9 * time.Minute,
948 want: &dto.Histogram{
949 SampleCount: proto.Uint64(3),
950 SampleSum: proto.Float64(12.1),
951 Schema: proto.Int32(2),
952 ZeroThreshold: proto.Float64(2.938735877055719e-39),
953 ZeroCount: proto.Uint64(0),
954 PositiveSpan: []*dto.BucketSpan{
955 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
956 },
957 PositiveDelta: []int64{1, 0, -1, 1},
958 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
959 },
960 },
961 }
962
963 for _, s := range scenarios {
964 t.Run(s.name, func(t *testing.T) {
965 var (
966 ts = now
967 funcToCall func()
968 whenToCall time.Duration
969 )
970
971 his := NewHistogram(HistogramOpts{
972 Name: "name",
973 Help: "help",
974 NativeHistogramBucketFactor: s.factor,
975 NativeHistogramZeroThreshold: s.zeroThreshold,
976 NativeHistogramMaxBucketNumber: s.maxBuckets,
977 NativeHistogramMinResetDuration: s.minResetDuration,
978 NativeHistogramMaxZeroThreshold: s.maxZeroThreshold,
979 now: func() time.Time { return ts },
980 afterFunc: func(d time.Duration, f func()) *time.Timer {
981 funcToCall = f
982 whenToCall = d
983 return nil
984 },
985 })
986
987 ts = ts.Add(time.Minute)
988 for _, o := range s.observations {
989 his.Observe(o)
990 ts = ts.Add(time.Minute)
991 whenToCall -= time.Minute
992 if funcToCall != nil && whenToCall <= 0 {
993 funcToCall()
994 funcToCall = nil
995 }
996 }
997 m := &dto.Metric{}
998 if err := his.Write(m); err != nil {
999 t.Fatal("unexpected error writing metric", err)
1000 }
1001 got := m.Histogram
1002 if !proto.Equal(s.want, got) {
1003 t.Errorf("want histogram %q, got %q", s.want, got)
1004 }
1005 })
1006 }
1007 }
1008
1009 func TestNativeHistogramConcurrency(t *testing.T) {
1010 if testing.Short() {
1011 t.Skip("Skipping test in short mode.")
1012 }
1013
1014 rand.New(rand.NewSource(42))
1015
1016 it := func(n uint32) bool {
1017 ts := time.Now().Add(30 * time.Second).Unix()
1018
1019 mutations := int(n%1e4 + 1e4)
1020 concLevel := int(n%5 + 1)
1021 total := mutations * concLevel
1022
1023 var start, end sync.WaitGroup
1024 start.Add(1)
1025 end.Add(concLevel)
1026
1027 his := NewHistogram(HistogramOpts{
1028 Name: "test_native_histogram",
1029 Help: "This help is sparse.",
1030 NativeHistogramBucketFactor: 1.05,
1031 NativeHistogramZeroThreshold: 0.0000001,
1032 NativeHistogramMaxBucketNumber: 50,
1033 NativeHistogramMinResetDuration: time.Hour, // Comment out to test for totals below.
1034 NativeHistogramMaxZeroThreshold: 0.001,
1035 now: func() time.Time {
1036 return time.Unix(atomic.LoadInt64(&ts), 0)
1037 },
1038 })
1039
1040 allVars := make([]float64, total)
1041 var sampleSum float64
1042 for i := 0; i < concLevel; i++ {
1043 vals := make([]float64, mutations)
1044 for j := 0; j < mutations; j++ {
1045 v := rand.NormFloat64()
1046 vals[j] = v
1047 allVars[i*mutations+j] = v
1048 sampleSum += v
1049 }
1050
1051 go func(vals []float64) {
1052 start.Wait()
1053 for i, v := range vals {
1054 // An observation every 1 to 10 seconds.
1055 atomic.AddInt64(&ts, rand.Int63n(10)+1)
1056 if i%2 == 0 {
1057 his.Observe(v)
1058 } else {
1059 his.(ExemplarObserver).ObserveWithExemplar(v, Labels{"foo": "bar"})
1060 }
1061 }
1062 end.Done()
1063 }(vals)
1064 }
1065 sort.Float64s(allVars)
1066 start.Done()
1067 end.Wait()
1068
1069 m := &dto.Metric{}
1070 his.Write(m)
1071
1072 // Uncomment these tests for totals only if you have disabled histogram resets above.
1073 //
1074 // if got, want := int(*m.Histogram.SampleCount), total; got != want {
1075 // t.Errorf("got sample count %d, want %d", got, want)
1076 // }
1077 // if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 {
1078 // t.Errorf("got sample sum %f, want %f", got, want)
1079 // }
1080
1081 sumBuckets := int(m.Histogram.GetZeroCount())
1082 current := 0
1083 for _, delta := range m.Histogram.GetNegativeDelta() {
1084 current += int(delta)
1085 if current < 0 {
1086 t.Fatalf("negative bucket population negative: %d", current)
1087 }
1088 sumBuckets += current
1089 }
1090 current = 0
1091 for _, delta := range m.Histogram.GetPositiveDelta() {
1092 current += int(delta)
1093 if current < 0 {
1094 t.Fatalf("positive bucket population negative: %d", current)
1095 }
1096 sumBuckets += current
1097 }
1098 if got, want := sumBuckets, int(*m.Histogram.SampleCount); got != want {
1099 t.Errorf("got bucket population sum %d, want %d", got, want)
1100 }
1101
1102 return true
1103 }
1104
1105 if err := quick.Check(it, nil); err != nil {
1106 t.Error(err)
1107 }
1108 }
1109
1110 func TestGetLe(t *testing.T) {
1111 scenarios := []struct {
1112 key int
1113 schema int32
1114 want float64
1115 }{
1116 {
1117 key: -1,
1118 schema: -1,
1119 want: 0.25,
1120 },
1121 {
1122 key: 0,
1123 schema: -1,
1124 want: 1,
1125 },
1126 {
1127 key: 1,
1128 schema: -1,
1129 want: 4,
1130 },
1131 {
1132 key: 512,
1133 schema: -1,
1134 want: math.MaxFloat64,
1135 },
1136 {
1137 key: 513,
1138 schema: -1,
1139 want: math.Inf(+1),
1140 },
1141 {
1142 key: -1,
1143 schema: 0,
1144 want: 0.5,
1145 },
1146 {
1147 key: 0,
1148 schema: 0,
1149 want: 1,
1150 },
1151 {
1152 key: 1,
1153 schema: 0,
1154 want: 2,
1155 },
1156 {
1157 key: 1024,
1158 schema: 0,
1159 want: math.MaxFloat64,
1160 },
1161 {
1162 key: 1025,
1163 schema: 0,
1164 want: math.Inf(+1),
1165 },
1166 {
1167 key: -1,
1168 schema: 2,
1169 want: 0.8408964152537144,
1170 },
1171 {
1172 key: 0,
1173 schema: 2,
1174 want: 1,
1175 },
1176 {
1177 key: 1,
1178 schema: 2,
1179 want: 1.189207115002721,
1180 },
1181 {
1182 key: 4096,
1183 schema: 2,
1184 want: math.MaxFloat64,
1185 },
1186 {
1187 key: 4097,
1188 schema: 2,
1189 want: math.Inf(+1),
1190 },
1191 }
1192
1193 for i, s := range scenarios {
1194 got := getLe(s.key, s.schema)
1195 if s.want != got {
1196 t.Errorf("%d. key %d, schema %d, want upper bound of %g, got %g", i, s.key, s.schema, s.want, got)
1197 }
1198 }
1199 }
1200
1201 func TestHistogramCreatedTimestamp(t *testing.T) {
1202 now := time.Now()
1203
1204 histogram := NewHistogram(HistogramOpts{
1205 Name: "test",
1206 Help: "test help",
1207 Buckets: []float64{1, 2, 3, 4},
1208 now: func() time.Time { return now },
1209 })
1210
1211 var metric dto.Metric
1212 if err := histogram.Write(&metric); err != nil {
1213 t.Fatal(err)
1214 }
1215
1216 if metric.Histogram.CreatedTimestamp.AsTime().Unix() != now.Unix() {
1217 t.Errorf("expected created timestamp %d, got %d", now.Unix(), metric.Histogram.CreatedTimestamp.AsTime().Unix())
1218 }
1219 }
1220
1221 func TestHistogramVecCreatedTimestamp(t *testing.T) {
1222 now := time.Now()
1223
1224 histogramVec := NewHistogramVec(HistogramOpts{
1225 Name: "test",
1226 Help: "test help",
1227 Buckets: []float64{1, 2, 3, 4},
1228 now: func() time.Time { return now },
1229 }, []string{"label"})
1230 histogram := histogramVec.WithLabelValues("value").(Histogram)
1231
1232 var metric dto.Metric
1233 if err := histogram.Write(&metric); err != nil {
1234 t.Fatal(err)
1235 }
1236
1237 if metric.Histogram.CreatedTimestamp.AsTime().Unix() != now.Unix() {
1238 t.Errorf("expected created timestamp %d, got %d", now.Unix(), metric.Histogram.CreatedTimestamp.AsTime().Unix())
1239 }
1240 }
1241
1242 func TestHistogramVecCreatedTimestampWithDeletes(t *testing.T) {
1243 now := time.Now()
1244
1245 histogramVec := NewHistogramVec(HistogramOpts{
1246 Name: "test",
1247 Help: "test help",
1248 Buckets: []float64{1, 2, 3, 4},
1249 now: func() time.Time { return now },
1250 }, []string{"label"})
1251
1252 // First use of "With" should populate CT.
1253 histogramVec.WithLabelValues("1")
1254 expected := map[string]time.Time{"1": now}
1255
1256 now = now.Add(1 * time.Hour)
1257 expectCTsForMetricVecValues(t, histogramVec.MetricVec, dto.MetricType_HISTOGRAM, expected)
1258
1259 // Two more labels at different times.
1260 histogramVec.WithLabelValues("2")
1261 expected["2"] = now
1262
1263 now = now.Add(1 * time.Hour)
1264
1265 histogramVec.WithLabelValues("3")
1266 expected["3"] = now
1267
1268 now = now.Add(1 * time.Hour)
1269 expectCTsForMetricVecValues(t, histogramVec.MetricVec, dto.MetricType_HISTOGRAM, expected)
1270
1271 // Recreate metric instance should reset created timestamp to now.
1272 histogramVec.DeleteLabelValues("1")
1273 histogramVec.WithLabelValues("1")
1274 expected["1"] = now
1275
1276 now = now.Add(1 * time.Hour)
1277 expectCTsForMetricVecValues(t, histogramVec.MetricVec, dto.MetricType_HISTOGRAM, expected)
1278 }
1279
1280 func TestNewConstHistogramWithCreatedTimestamp(t *testing.T) {
1281 metricDesc := NewDesc(
1282 "sample_value",
1283 "sample value",
1284 nil,
1285 nil,
1286 )
1287 buckets := map[float64]uint64{25: 100, 50: 200}
1288 createdTs := time.Unix(1719670764, 123)
1289
1290 h, err := NewConstHistogramWithCreatedTimestamp(metricDesc, 100, 200, buckets, createdTs)
1291 if err != nil {
1292 t.Fatal(err)
1293 }
1294
1295 var metric dto.Metric
1296 if err := h.Write(&metric); err != nil {
1297 t.Fatal(err)
1298 }
1299
1300 if metric.Histogram.CreatedTimestamp.AsTime().UnixMicro() != createdTs.UnixMicro() {
1301 t.Errorf("Expected created timestamp %v, got %v", createdTs, &metric.Histogram.CreatedTimestamp)
1302 }
1303 }
1304
1305 func TestNativeHistogramExemplar(t *testing.T) {
1306 // Test the histogram with positive NativeHistogramExemplarTTL and NativeHistogramMaxExemplars
1307 h := NewHistogram(HistogramOpts{
1308 Name: "test",
1309 Help: "test help",
1310 Buckets: []float64{1, 2, 3, 4},
1311 NativeHistogramBucketFactor: 1.1,
1312 NativeHistogramMaxExemplars: 3,
1313 NativeHistogramExemplarTTL: 10 * time.Second,
1314 }).(*histogram)
1315
1316 tcs := []struct {
1317 name string
1318 addFunc func(*histogram)
1319 expectedValues []float64
1320 }{
1321 {
1322 name: "add exemplars to the limit",
1323 addFunc: func(h *histogram) {
1324 h.ObserveWithExemplar(1, Labels{"id": "1"})
1325 h.ObserveWithExemplar(3, Labels{"id": "1"})
1326 h.ObserveWithExemplar(5, Labels{"id": "1"})
1327 },
1328 expectedValues: []float64{1, 3, 5},
1329 },
1330 {
1331 name: "remove exemplar in closest pair, the removed index equals to inserted index",
1332 addFunc: func(h *histogram) {
1333 h.ObserveWithExemplar(4, Labels{"id": "1"})
1334 },
1335 expectedValues: []float64{1, 3, 4},
1336 },
1337 {
1338 name: "remove exemplar in closest pair, the removed index is bigger than inserted index",
1339 addFunc: func(h *histogram) {
1340 h.ObserveWithExemplar(0, Labels{"id": "1"})
1341 },
1342 expectedValues: []float64{0, 1, 4},
1343 },
1344 {
1345 name: "remove exemplar with oldest timestamp, the removed index is smaller than inserted index",
1346 addFunc: func(h *histogram) {
1347 h.now = func() time.Time { return time.Now().Add(time.Second * 11) }
1348 h.ObserveWithExemplar(6, Labels{"id": "1"})
1349 },
1350 expectedValues: []float64{0, 4, 6},
1351 },
1352 }
1353
1354 for _, tc := range tcs {
1355 t.Run(tc.name, func(t *testing.T) {
1356 tc.addFunc(h)
1357 compareNativeExemplarValues(t, h.nativeExemplars.exemplars, tc.expectedValues)
1358 })
1359 }
1360
1361 // Test the histogram with negative NativeHistogramExemplarTTL
1362 h = NewHistogram(HistogramOpts{
1363 Name: "test",
1364 Help: "test help",
1365 Buckets: []float64{1, 2, 3, 4},
1366 NativeHistogramBucketFactor: 1.1,
1367 NativeHistogramMaxExemplars: 3,
1368 NativeHistogramExemplarTTL: -1 * time.Second,
1369 }).(*histogram)
1370
1371 tcs = []struct {
1372 name string
1373 addFunc func(*histogram)
1374 expectedValues []float64
1375 }{
1376 {
1377 name: "add exemplars to the limit",
1378 addFunc: func(h *histogram) {
1379 h.ObserveWithExemplar(1, Labels{"id": "1"})
1380 h.ObserveWithExemplar(3, Labels{"id": "1"})
1381 h.ObserveWithExemplar(5, Labels{"id": "1"})
1382 },
1383 expectedValues: []float64{1, 3, 5},
1384 },
1385 {
1386 name: "remove exemplar with oldest timestamp, the removed index is smaller than inserted index",
1387 addFunc: func(h *histogram) {
1388 h.ObserveWithExemplar(4, Labels{"id": "1"})
1389 },
1390 expectedValues: []float64{3, 4, 5},
1391 },
1392 {
1393 name: "remove exemplar with oldest timestamp, the removed index equals to inserted index",
1394 addFunc: func(h *histogram) {
1395 h.ObserveWithExemplar(0, Labels{"id": "1"})
1396 },
1397 expectedValues: []float64{0, 4, 5},
1398 },
1399 {
1400 name: "remove exemplar with oldest timestamp, the removed index is bigger than inserted index",
1401 addFunc: func(h *histogram) {
1402 h.ObserveWithExemplar(3, Labels{"id": "1"})
1403 },
1404 expectedValues: []float64{0, 3, 4},
1405 },
1406 }
1407
1408 for _, tc := range tcs {
1409 t.Run(tc.name, func(t *testing.T) {
1410 tc.addFunc(h)
1411 compareNativeExemplarValues(t, h.nativeExemplars.exemplars, tc.expectedValues)
1412 })
1413 }
1414
1415 // Test the histogram with negative NativeHistogramMaxExemplars
1416 h = NewHistogram(HistogramOpts{
1417 Name: "test",
1418 Help: "test help",
1419 Buckets: []float64{1, 2, 3, 4},
1420 NativeHistogramBucketFactor: 1.1,
1421 NativeHistogramMaxExemplars: -1,
1422 NativeHistogramExemplarTTL: -1 * time.Second,
1423 }).(*histogram)
1424
1425 tcs = []struct {
1426 name string
1427 addFunc func(*histogram)
1428 expectedValues []float64
1429 }{
1430 {
1431 name: "add exemplars to the limit, but no effect",
1432 addFunc: func(h *histogram) {
1433 h.ObserveWithExemplar(1, Labels{"id": "1"})
1434 h.ObserveWithExemplar(3, Labels{"id": "1"})
1435 h.ObserveWithExemplar(5, Labels{"id": "1"})
1436 },
1437 expectedValues: []float64{},
1438 },
1439 }
1440
1441 for _, tc := range tcs {
1442 t.Run(tc.name, func(t *testing.T) {
1443 tc.addFunc(h)
1444 compareNativeExemplarValues(t, h.nativeExemplars.exemplars, tc.expectedValues)
1445 })
1446 }
1447 }
1448
1449 func compareNativeExemplarValues(t *testing.T, exps []*dto.Exemplar, values []float64) {
1450 if len(exps) != len(values) {
1451 t.Errorf("the count of exemplars is not %d", len(values))
1452 }
1453 for i, e := range exps {
1454 if e.GetValue() != values[i] {
1455 t.Errorf("the %dth exemplar value %v is not as expected: %v", i, e.GetValue(), values[i])
1456 }
1457 }
1458 }
1459
1460 var resultFindBucket int
1461
1462 func benchmarkFindBucket(b *testing.B, l int) {
1463 h := &histogram{upperBounds: make([]float64, l)}
1464 for i := range h.upperBounds {
1465 h.upperBounds[i] = float64(i)
1466 }
1467 v := float64(l / 2)
1468
1469 b.ResetTimer()
1470 for i := 0; i < b.N; i++ {
1471 resultFindBucket = h.findBucket(v)
1472 }
1473 }
1474
1475 func BenchmarkFindBucketShort(b *testing.B) {
1476 benchmarkFindBucket(b, 20)
1477 }
1478
1479 func BenchmarkFindBucketMid(b *testing.B) {
1480 benchmarkFindBucket(b, 40)
1481 }
1482
1483 func BenchmarkFindBucketLarge(b *testing.B) {
1484 benchmarkFindBucket(b, 100)
1485 }
1486
1487 func BenchmarkFindBucketHuge(b *testing.B) {
1488 benchmarkFindBucket(b, 500)
1489 }
1490
1491 func BenchmarkFindBucketInf(b *testing.B) {
1492 h := &histogram{upperBounds: make([]float64, 500)}
1493 for i := range h.upperBounds {
1494 h.upperBounds[i] = float64(i)
1495 }
1496 v := 1000.5
1497
1498 b.ResetTimer()
1499 for i := 0; i < b.N; i++ {
1500 resultFindBucket = h.findBucket(v)
1501 }
1502 }
1503
1504 func BenchmarkFindBucketLow(b *testing.B) {
1505 h := &histogram{upperBounds: make([]float64, 500)}
1506 for i := range h.upperBounds {
1507 h.upperBounds[i] = float64(i)
1508 }
1509 v := -1.1
1510
1511 b.ResetTimer()
1512 for i := 0; i < b.N; i++ {
1513 resultFindBucket = h.findBucket(v)
1514 }
1515 }
1516
1517 func TestFindBucket(t *testing.T) {
1518 smallHistogram := &histogram{upperBounds: []float64{1, 2, 3, 4, 5}}
1519 largeHistogram := &histogram{upperBounds: make([]float64, 50)}
1520 for i := range largeHistogram.upperBounds {
1521 largeHistogram.upperBounds[i] = float64(i)
1522 }
1523
1524 tests := []struct {
1525 h *histogram
1526 v float64
1527 expected int
1528 }{
1529 {smallHistogram, -1, 0},
1530 {smallHistogram, 0.5, 0},
1531 {smallHistogram, 2.5, 2},
1532 {smallHistogram, 5.5, 5},
1533 {largeHistogram, -1, 0},
1534 {largeHistogram, 25.5, 26},
1535 {largeHistogram, 49.5, 50},
1536 {largeHistogram, 50.5, 50},
1537 {largeHistogram, 5000.5, 50},
1538 }
1539
1540 for _, tt := range tests {
1541 result := tt.h.findBucket(tt.v)
1542 if result != tt.expected {
1543 t.Errorf("findBucket(%v) = %d; expected %d", tt.v, result, tt.expected)
1544 }
1545 }
1546 }
1547
1548 func syncMapToMap(syncmap *sync.Map) (m map[int]int64) {
1549 m = map[int]int64{}
1550 syncmap.Range(func(key, value any) bool {
1551 m[key.(int)] = *value.(*int64)
1552 return true
1553 })
1554 return m
1555 }
1556
1557 func TestConstNativeHistogram(t *testing.T) {
1558 now := time.Now()
1559
1560 scenarios := []struct {
1561 name string
1562 observations []float64 // With simulated interval of 1m.
1563 factor float64
1564 zeroThreshold float64
1565 maxBuckets uint32
1566 minResetDuration time.Duration
1567 maxZeroThreshold float64
1568 want *dto.Histogram
1569 }{
1570 {
1571 name: "no observations",
1572 factor: 1.1,
1573 want: &dto.Histogram{
1574 SampleCount: proto.Uint64(0),
1575 SampleSum: proto.Float64(0),
1576 Schema: proto.Int32(3),
1577 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1578 ZeroCount: proto.Uint64(0),
1579 CreatedTimestamp: timestamppb.New(now),
1580 },
1581 },
1582 {
1583 name: "no observations and zero threshold of zero resulting in no-op span",
1584 factor: 1.1,
1585 zeroThreshold: NativeHistogramZeroThresholdZero,
1586 want: &dto.Histogram{
1587 SampleCount: proto.Uint64(0),
1588 SampleSum: proto.Float64(0),
1589 Schema: proto.Int32(3),
1590 ZeroThreshold: proto.Float64(0),
1591 ZeroCount: proto.Uint64(0),
1592 PositiveSpan: []*dto.BucketSpan{
1593 {Offset: proto.Int32(0), Length: proto.Uint32(0)},
1594 },
1595 CreatedTimestamp: timestamppb.New(now),
1596 },
1597 },
1598 {
1599 name: "factor 1.1 results in schema 3",
1600 observations: []float64{0, 1, 2, 3},
1601 factor: 1.1,
1602 want: &dto.Histogram{
1603 SampleCount: proto.Uint64(4),
1604 SampleSum: proto.Float64(6),
1605 Schema: proto.Int32(3),
1606 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1607 ZeroCount: proto.Uint64(1),
1608 PositiveSpan: []*dto.BucketSpan{
1609 {Offset: proto.Int32(0), Length: proto.Uint32(1)},
1610 {Offset: proto.Int32(7), Length: proto.Uint32(1)},
1611 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
1612 },
1613 PositiveDelta: []int64{1, 0, 0},
1614 CreatedTimestamp: timestamppb.New(now),
1615 },
1616 },
1617 {
1618 name: "factor 1.2 results in schema 2",
1619 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
1620 factor: 1.2,
1621 want: &dto.Histogram{
1622 SampleCount: proto.Uint64(6),
1623 SampleSum: proto.Float64(7.4),
1624 Schema: proto.Int32(2),
1625 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1626 ZeroCount: proto.Uint64(1),
1627 PositiveSpan: []*dto.BucketSpan{
1628 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1629 },
1630 PositiveDelta: []int64{1, -1, 2, -2, 2},
1631 CreatedTimestamp: timestamppb.New(now),
1632 },
1633 },
1634 {
1635 name: "factor 4 results in schema -1",
1636 observations: []float64{
1637 0.0156251, 0.0625, // Bucket -2: (0.015625, 0.0625)
1638 0.1, 0.25, // Bucket -1: (0.0625, 0.25]
1639 0.5, 1, // Bucket 0: (0.25, 1]
1640 1.5, 2, 3, 3.5, // Bucket 1: (1, 4]
1641 5, 6, 7, // Bucket 2: (4, 16]
1642 33.33, // Bucket 3: (16, 64]
1643 },
1644 factor: 4,
1645 want: &dto.Histogram{
1646 SampleCount: proto.Uint64(14),
1647 SampleSum: proto.Float64(63.2581251),
1648 Schema: proto.Int32(-1),
1649 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1650 ZeroCount: proto.Uint64(0),
1651 PositiveSpan: []*dto.BucketSpan{
1652 {Offset: proto.Int32(-2), Length: proto.Uint32(6)},
1653 },
1654 PositiveDelta: []int64{2, 0, 0, 2, -1, -2},
1655 CreatedTimestamp: timestamppb.New(now),
1656 },
1657 },
1658 {
1659 name: "factor 17 results in schema -2",
1660 observations: []float64{
1661 0.0156251, 0.0625, // Bucket -1: (0.015625, 0.0625]
1662 0.1, 0.25, 0.5, 1, // Bucket 0: (0.0625, 1]
1663 1.5, 2, 3, 3.5, 5, 6, 7, // Bucket 1: (1, 16]
1664 33.33, // Bucket 2: (16, 256]
1665 },
1666 factor: 17,
1667 want: &dto.Histogram{
1668 SampleCount: proto.Uint64(14),
1669 SampleSum: proto.Float64(63.2581251),
1670 Schema: proto.Int32(-2),
1671 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1672 ZeroCount: proto.Uint64(0),
1673 PositiveSpan: []*dto.BucketSpan{
1674 {Offset: proto.Int32(-1), Length: proto.Uint32(4)},
1675 },
1676 PositiveDelta: []int64{2, 2, 3, -6},
1677 CreatedTimestamp: timestamppb.New(now),
1678 },
1679 },
1680 {
1681 name: "negative buckets",
1682 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
1683 factor: 1.2,
1684 want: &dto.Histogram{
1685 SampleCount: proto.Uint64(6),
1686 SampleSum: proto.Float64(-7.4),
1687 Schema: proto.Int32(2),
1688 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1689 ZeroCount: proto.Uint64(1),
1690 NegativeSpan: []*dto.BucketSpan{
1691 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1692 },
1693 NegativeDelta: []int64{1, -1, 2, -2, 2},
1694 CreatedTimestamp: timestamppb.New(now),
1695 },
1696 },
1697 {
1698 name: "negative and positive buckets",
1699 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
1700 factor: 1.2,
1701 want: &dto.Histogram{
1702 SampleCount: proto.Uint64(11),
1703 SampleSum: proto.Float64(0),
1704 Schema: proto.Int32(2),
1705 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1706 ZeroCount: proto.Uint64(1),
1707 NegativeSpan: []*dto.BucketSpan{
1708 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1709 },
1710 NegativeDelta: []int64{1, -1, 2, -2, 2},
1711 PositiveSpan: []*dto.BucketSpan{
1712 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1713 },
1714 PositiveDelta: []int64{1, -1, 2, -2, 2},
1715 CreatedTimestamp: timestamppb.New(now),
1716 },
1717 },
1718 {
1719 name: "wide zero bucket",
1720 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
1721 factor: 1.2,
1722 zeroThreshold: 1.4,
1723 want: &dto.Histogram{
1724 SampleCount: proto.Uint64(11),
1725 SampleSum: proto.Float64(0),
1726 Schema: proto.Int32(2),
1727 ZeroThreshold: proto.Float64(1.4),
1728 ZeroCount: proto.Uint64(7),
1729 NegativeSpan: []*dto.BucketSpan{
1730 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
1731 },
1732 NegativeDelta: []int64{2},
1733 PositiveSpan: []*dto.BucketSpan{
1734 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
1735 },
1736 PositiveDelta: []int64{2},
1737 CreatedTimestamp: timestamppb.New(now),
1738 },
1739 },
1740 {
1741 name: "NaN observation",
1742 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.NaN()},
1743 factor: 1.2,
1744 want: &dto.Histogram{
1745 SampleCount: proto.Uint64(7),
1746 SampleSum: proto.Float64(math.NaN()),
1747 Schema: proto.Int32(2),
1748 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1749 ZeroCount: proto.Uint64(1),
1750 PositiveSpan: []*dto.BucketSpan{
1751 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1752 },
1753 PositiveDelta: []int64{1, -1, 2, -2, 2},
1754 CreatedTimestamp: timestamppb.New(now),
1755 },
1756 },
1757 {
1758 name: "+Inf observation",
1759 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(+1)},
1760 factor: 1.2,
1761 want: &dto.Histogram{
1762 SampleCount: proto.Uint64(7),
1763 SampleSum: proto.Float64(math.Inf(+1)),
1764 Schema: proto.Int32(2),
1765 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1766 ZeroCount: proto.Uint64(1),
1767 PositiveSpan: []*dto.BucketSpan{
1768 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1769 {Offset: proto.Int32(4092), Length: proto.Uint32(1)},
1770 },
1771 PositiveDelta: []int64{1, -1, 2, -2, 2, -1},
1772 CreatedTimestamp: timestamppb.New(now),
1773 },
1774 },
1775 {
1776 name: "-Inf observation",
1777 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(-1)},
1778 factor: 1.2,
1779 want: &dto.Histogram{
1780 SampleCount: proto.Uint64(7),
1781 SampleSum: proto.Float64(math.Inf(-1)),
1782 Schema: proto.Int32(2),
1783 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1784 ZeroCount: proto.Uint64(1),
1785 NegativeSpan: []*dto.BucketSpan{
1786 {Offset: proto.Int32(4097), Length: proto.Uint32(1)},
1787 },
1788 NegativeDelta: []int64{1},
1789 PositiveSpan: []*dto.BucketSpan{
1790 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1791 },
1792 PositiveDelta: []int64{1, -1, 2, -2, 2},
1793 CreatedTimestamp: timestamppb.New(now),
1794 },
1795 },
1796 {
1797 name: "limited buckets but nothing triggered",
1798 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
1799 factor: 1.2,
1800 maxBuckets: 4,
1801 want: &dto.Histogram{
1802 SampleCount: proto.Uint64(6),
1803 SampleSum: proto.Float64(7.4),
1804 Schema: proto.Int32(2),
1805 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1806 ZeroCount: proto.Uint64(1),
1807 PositiveSpan: []*dto.BucketSpan{
1808 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1809 },
1810 PositiveDelta: []int64{1, -1, 2, -2, 2},
1811 CreatedTimestamp: timestamppb.New(now),
1812 },
1813 },
1814 {
1815 name: "buckets limited by halving resolution",
1816 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
1817 factor: 1.2,
1818 maxBuckets: 4,
1819 want: &dto.Histogram{
1820 SampleCount: proto.Uint64(8),
1821 SampleSum: proto.Float64(11.5),
1822 Schema: proto.Int32(1),
1823 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1824 ZeroCount: proto.Uint64(1),
1825 PositiveSpan: []*dto.BucketSpan{
1826 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1827 },
1828 PositiveDelta: []int64{1, 2, -1, -2, 1},
1829 CreatedTimestamp: timestamppb.New(now),
1830 },
1831 },
1832 {
1833 name: "buckets limited by widening the zero bucket",
1834 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
1835 factor: 1.2,
1836 maxBuckets: 4,
1837 maxZeroThreshold: 1.2,
1838 want: &dto.Histogram{
1839 SampleCount: proto.Uint64(8),
1840 SampleSum: proto.Float64(11.5),
1841 Schema: proto.Int32(2),
1842 ZeroThreshold: proto.Float64(1),
1843 ZeroCount: proto.Uint64(2),
1844 PositiveSpan: []*dto.BucketSpan{
1845 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
1846 },
1847 PositiveDelta: []int64{1, 1, -2, 2, -2, 0, 1},
1848 CreatedTimestamp: timestamppb.New(now),
1849 },
1850 },
1851 {
1852 name: "buckets limited by widening the zero bucket twice",
1853 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
1854 factor: 1.2,
1855 maxBuckets: 4,
1856 maxZeroThreshold: 1.2,
1857 want: &dto.Histogram{
1858 SampleCount: proto.Uint64(9),
1859 SampleSum: proto.Float64(15.5),
1860 Schema: proto.Int32(2),
1861 ZeroThreshold: proto.Float64(1.189207115002721),
1862 ZeroCount: proto.Uint64(3),
1863 PositiveSpan: []*dto.BucketSpan{
1864 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
1865 },
1866 PositiveDelta: []int64{2, -2, 2, -2, 0, 1, 0},
1867 CreatedTimestamp: timestamppb.New(now),
1868 },
1869 },
1870 {
1871 name: "buckets limited by reset",
1872 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
1873 factor: 1.2,
1874 maxBuckets: 4,
1875 maxZeroThreshold: 1.2,
1876 minResetDuration: 5 * time.Minute,
1877 want: &dto.Histogram{
1878 SampleCount: proto.Uint64(2),
1879 SampleSum: proto.Float64(7),
1880 Schema: proto.Int32(2),
1881 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1882 ZeroCount: proto.Uint64(0),
1883 PositiveSpan: []*dto.BucketSpan{
1884 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
1885 },
1886 PositiveDelta: []int64{1, 0},
1887 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
1888 },
1889 },
1890 {
1891 name: "limited buckets but nothing triggered, negative observations",
1892 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
1893 factor: 1.2,
1894 maxBuckets: 4,
1895 want: &dto.Histogram{
1896 SampleCount: proto.Uint64(6),
1897 SampleSum: proto.Float64(-7.4),
1898 Schema: proto.Int32(2),
1899 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1900 ZeroCount: proto.Uint64(1),
1901 NegativeSpan: []*dto.BucketSpan{
1902 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1903 },
1904 NegativeDelta: []int64{1, -1, 2, -2, 2},
1905 CreatedTimestamp: timestamppb.New(now),
1906 },
1907 },
1908 {
1909 name: "buckets limited by halving resolution, negative observations",
1910 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
1911 factor: 1.2,
1912 maxBuckets: 4,
1913 want: &dto.Histogram{
1914 SampleCount: proto.Uint64(8),
1915 SampleSum: proto.Float64(-11.5),
1916 Schema: proto.Int32(1),
1917 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1918 ZeroCount: proto.Uint64(1),
1919 NegativeSpan: []*dto.BucketSpan{
1920 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1921 },
1922 NegativeDelta: []int64{1, 2, -1, -2, 1},
1923 CreatedTimestamp: timestamppb.New(now),
1924 },
1925 },
1926 {
1927 name: "buckets limited by widening the zero bucket, negative observations",
1928 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
1929 factor: 1.2,
1930 maxBuckets: 4,
1931 maxZeroThreshold: 1.2,
1932 want: &dto.Histogram{
1933 SampleCount: proto.Uint64(8),
1934 SampleSum: proto.Float64(-11.5),
1935 Schema: proto.Int32(2),
1936 ZeroThreshold: proto.Float64(1),
1937 ZeroCount: proto.Uint64(2),
1938 NegativeSpan: []*dto.BucketSpan{
1939 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
1940 },
1941 NegativeDelta: []int64{1, 1, -2, 2, -2, 0, 1},
1942 CreatedTimestamp: timestamppb.New(now),
1943 },
1944 },
1945 {
1946 name: "buckets limited by widening the zero bucket twice, negative observations",
1947 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
1948 factor: 1.2,
1949 maxBuckets: 4,
1950 maxZeroThreshold: 1.2,
1951 want: &dto.Histogram{
1952 SampleCount: proto.Uint64(9),
1953 SampleSum: proto.Float64(-15.5),
1954 Schema: proto.Int32(2),
1955 ZeroThreshold: proto.Float64(1.189207115002721),
1956 ZeroCount: proto.Uint64(3),
1957 NegativeSpan: []*dto.BucketSpan{
1958 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
1959 },
1960 NegativeDelta: []int64{2, -2, 2, -2, 0, 1, 0},
1961 CreatedTimestamp: timestamppb.New(now),
1962 },
1963 },
1964 {
1965 name: "buckets limited by reset, negative observations",
1966 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
1967 factor: 1.2,
1968 maxBuckets: 4,
1969 maxZeroThreshold: 1.2,
1970 minResetDuration: 5 * time.Minute,
1971 want: &dto.Histogram{
1972 SampleCount: proto.Uint64(2),
1973 SampleSum: proto.Float64(-7),
1974 Schema: proto.Int32(2),
1975 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1976 ZeroCount: proto.Uint64(0),
1977 NegativeSpan: []*dto.BucketSpan{
1978 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
1979 },
1980 NegativeDelta: []int64{1, 0},
1981 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
1982 },
1983 },
1984 {
1985 name: "buckets limited by halving resolution, then reset",
1986 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
1987 factor: 1.2,
1988 maxBuckets: 4,
1989 minResetDuration: 9 * time.Minute,
1990 want: &dto.Histogram{
1991 SampleCount: proto.Uint64(3),
1992 SampleSum: proto.Float64(12.1),
1993 Schema: proto.Int32(2),
1994 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1995 ZeroCount: proto.Uint64(0),
1996 PositiveSpan: []*dto.BucketSpan{
1997 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
1998 },
1999 PositiveDelta: []int64{1, 0, -1, 1},
2000 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
2001 },
2002 },
2003 {
2004 name: "buckets limited by widening the zero bucket, then reset",
2005 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
2006 factor: 1.2,
2007 maxBuckets: 4,
2008 maxZeroThreshold: 1.2,
2009 minResetDuration: 9 * time.Minute,
2010 want: &dto.Histogram{
2011 SampleCount: proto.Uint64(3),
2012 SampleSum: proto.Float64(12.1),
2013 Schema: proto.Int32(2),
2014 ZeroThreshold: proto.Float64(2.938735877055719e-39),
2015 ZeroCount: proto.Uint64(0),
2016 PositiveSpan: []*dto.BucketSpan{
2017 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
2018 },
2019 PositiveDelta: []int64{1, 0, -1, 1},
2020 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
2021 },
2022 },
2023 }
2024
2025 for _, s := range scenarios {
2026 t.Run(s.name, func(t *testing.T) {
2027 var (
2028 ts = now
2029 funcToCall func()
2030 whenToCall time.Duration
2031 )
2032
2033 his := NewHistogram(HistogramOpts{
2034 Name: "name",
2035 Help: "help",
2036 NativeHistogramBucketFactor: s.factor,
2037 NativeHistogramZeroThreshold: s.zeroThreshold,
2038 NativeHistogramMaxBucketNumber: s.maxBuckets,
2039 NativeHistogramMinResetDuration: s.minResetDuration,
2040 NativeHistogramMaxZeroThreshold: s.maxZeroThreshold,
2041 now: func() time.Time { return ts },
2042 afterFunc: func(d time.Duration, f func()) *time.Timer {
2043 funcToCall = f
2044 whenToCall = d
2045 return nil
2046 },
2047 })
2048
2049 ts = ts.Add(time.Minute)
2050 for _, o := range s.observations {
2051 his.Observe(o)
2052 ts = ts.Add(time.Minute)
2053 whenToCall -= time.Minute
2054 if funcToCall != nil && whenToCall <= 0 {
2055 funcToCall()
2056 funcToCall = nil
2057 }
2058 }
2059 _his := his.(*histogram)
2060 n := atomic.LoadUint64(&_his.countAndHotIdx)
2061 hotIdx := n >> 63
2062 cold := _his.counts[hotIdx]
2063 consthist, err := NewConstNativeHistogram(_his.Desc(),
2064 cold.count,
2065 math.Float64frombits(cold.sumBits),
2066 syncMapToMap(&cold.nativeHistogramBucketsPositive),
2067 syncMapToMap(&cold.nativeHistogramBucketsNegative),
2068 cold.nativeHistogramZeroBucket,
2069 cold.nativeHistogramSchema,
2070 math.Float64frombits(cold.nativeHistogramZeroThresholdBits),
2071 _his.lastResetTime,
2072 )
2073 if err != nil {
2074 t.Fatal("unexpected error writing metric", err)
2075 }
2076 m2 := &dto.Metric{}
2077
2078 if err := consthist.Write(m2); err != nil {
2079 t.Fatal("unexpected error writing metric", err)
2080 }
2081 got := m2.Histogram
2082 if !proto.Equal(s.want, got) {
2083 t.Errorf("want histogram %q, got %q", s.want, got)
2084 }
2085 })
2086 }
2087 }