Debian Codegraph @

prometheus/histogram_test.go

raw ◀ ▶
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 if runtime.GOARCH == "ppc64le" {
474 t.Skip("Skipping buggy test on ppc64el")
475 }
476 now := time.Now()
477
478 scenarios := []struct {
479 name string
480 observations []float64 // With simulated interval of 1m.
481 factor float64
482 zeroThreshold float64
483 maxBuckets uint32
484 minResetDuration time.Duration
485 maxZeroThreshold float64
486 want *dto.Histogram
487 }{
488 {
489 name: "no sparse buckets",
490 observations: []float64{1, 2, 3},
491 factor: 1,
492 want: &dto.Histogram{
493 SampleCount: proto.Uint64(3),
494 SampleSum: proto.Float64(6),
495 Bucket: []*dto.Bucket{
496 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.005)},
497 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.01)},
498 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.025)},
499 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.05)},
500 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.1)},
501 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.25)},
502 {CumulativeCount: proto.Uint64(0), UpperBound: proto.Float64(0.5)},
503 {CumulativeCount: proto.Uint64(1), UpperBound: proto.Float64(1)},
504 {CumulativeCount: proto.Uint64(2), UpperBound: proto.Float64(2.5)},
505 {CumulativeCount: proto.Uint64(3), UpperBound: proto.Float64(5)},
506 {CumulativeCount: proto.Uint64(3), UpperBound: proto.Float64(10)},
507 },
508 CreatedTimestamp: timestamppb.New(now),
509 },
510 },
511 {
512 name: "no observations",
513 factor: 1.1,
514 want: &dto.Histogram{
515 SampleCount: proto.Uint64(0),
516 SampleSum: proto.Float64(0),
517 Schema: proto.Int32(3),
518 ZeroThreshold: proto.Float64(2.938735877055719e-39),
519 ZeroCount: proto.Uint64(0),
520 CreatedTimestamp: timestamppb.New(now),
521 },
522 },
523 {
524 name: "no observations and zero threshold of zero resulting in no-op span",
525 factor: 1.1,
526 zeroThreshold: NativeHistogramZeroThresholdZero,
527 want: &dto.Histogram{
528 SampleCount: proto.Uint64(0),
529 SampleSum: proto.Float64(0),
530 Schema: proto.Int32(3),
531 ZeroThreshold: proto.Float64(0),
532 ZeroCount: proto.Uint64(0),
533 PositiveSpan: []*dto.BucketSpan{
534 {Offset: proto.Int32(0), Length: proto.Uint32(0)},
535 },
536 CreatedTimestamp: timestamppb.New(now),
537 },
538 },
539 {
540 name: "factor 1.1 results in schema 3",
541 observations: []float64{0, 1, 2, 3},
542 factor: 1.1,
543 want: &dto.Histogram{
544 SampleCount: proto.Uint64(4),
545 SampleSum: proto.Float64(6),
546 Schema: proto.Int32(3),
547 ZeroThreshold: proto.Float64(2.938735877055719e-39),
548 ZeroCount: proto.Uint64(1),
549 PositiveSpan: []*dto.BucketSpan{
550 {Offset: proto.Int32(0), Length: proto.Uint32(1)},
551 {Offset: proto.Int32(7), Length: proto.Uint32(1)},
552 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
553 },
554 PositiveDelta: []int64{1, 0, 0},
555 CreatedTimestamp: timestamppb.New(now),
556 },
557 },
558 {
559 name: "factor 1.2 results in schema 2",
560 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
561 factor: 1.2,
562 want: &dto.Histogram{
563 SampleCount: proto.Uint64(6),
564 SampleSum: proto.Float64(7.4),
565 Schema: proto.Int32(2),
566 ZeroThreshold: proto.Float64(2.938735877055719e-39),
567 ZeroCount: proto.Uint64(1),
568 PositiveSpan: []*dto.BucketSpan{
569 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
570 },
571 PositiveDelta: []int64{1, -1, 2, -2, 2},
572 CreatedTimestamp: timestamppb.New(now),
573 },
574 },
575 {
576 name: "factor 4 results in schema -1",
577 observations: []float64{
578 0.0156251, 0.0625, // Bucket -2: (0.015625, 0.0625)
579 0.1, 0.25, // Bucket -1: (0.0625, 0.25]
580 0.5, 1, // Bucket 0: (0.25, 1]
581 1.5, 2, 3, 3.5, // Bucket 1: (1, 4]
582 5, 6, 7, // Bucket 2: (4, 16]
583 33.33, // Bucket 3: (16, 64]
584 },
585 factor: 4,
586 want: &dto.Histogram{
587 SampleCount: proto.Uint64(14),
588 SampleSum: proto.Float64(63.2581251),
589 Schema: proto.Int32(-1),
590 ZeroThreshold: proto.Float64(2.938735877055719e-39),
591 ZeroCount: proto.Uint64(0),
592 PositiveSpan: []*dto.BucketSpan{
593 {Offset: proto.Int32(-2), Length: proto.Uint32(6)},
594 },
595 PositiveDelta: []int64{2, 0, 0, 2, -1, -2},
596 CreatedTimestamp: timestamppb.New(now),
597 },
598 },
599 {
600 name: "factor 17 results in schema -2",
601 observations: []float64{
602 0.0156251, 0.0625, // Bucket -1: (0.015625, 0.0625]
603 0.1, 0.25, 0.5, 1, // Bucket 0: (0.0625, 1]
604 1.5, 2, 3, 3.5, 5, 6, 7, // Bucket 1: (1, 16]
605 33.33, // Bucket 2: (16, 256]
606 },
607 factor: 17,
608 want: &dto.Histogram{
609 SampleCount: proto.Uint64(14),
610 SampleSum: proto.Float64(63.2581251),
611 Schema: proto.Int32(-2),
612 ZeroThreshold: proto.Float64(2.938735877055719e-39),
613 ZeroCount: proto.Uint64(0),
614 PositiveSpan: []*dto.BucketSpan{
615 {Offset: proto.Int32(-1), Length: proto.Uint32(4)},
616 },
617 PositiveDelta: []int64{2, 2, 3, -6},
618 CreatedTimestamp: timestamppb.New(now),
619 },
620 },
621 {
622 name: "negative buckets",
623 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
624 factor: 1.2,
625 want: &dto.Histogram{
626 SampleCount: proto.Uint64(6),
627 SampleSum: proto.Float64(-7.4),
628 Schema: proto.Int32(2),
629 ZeroThreshold: proto.Float64(2.938735877055719e-39),
630 ZeroCount: proto.Uint64(1),
631 NegativeSpan: []*dto.BucketSpan{
632 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
633 },
634 NegativeDelta: []int64{1, -1, 2, -2, 2},
635 CreatedTimestamp: timestamppb.New(now),
636 },
637 },
638 {
639 name: "negative and positive buckets",
640 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
641 factor: 1.2,
642 want: &dto.Histogram{
643 SampleCount: proto.Uint64(11),
644 SampleSum: proto.Float64(0),
645 Schema: proto.Int32(2),
646 ZeroThreshold: proto.Float64(2.938735877055719e-39),
647 ZeroCount: proto.Uint64(1),
648 NegativeSpan: []*dto.BucketSpan{
649 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
650 },
651 NegativeDelta: []int64{1, -1, 2, -2, 2},
652 PositiveSpan: []*dto.BucketSpan{
653 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
654 },
655 PositiveDelta: []int64{1, -1, 2, -2, 2},
656 CreatedTimestamp: timestamppb.New(now),
657 },
658 },
659 {
660 name: "wide zero bucket",
661 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
662 factor: 1.2,
663 zeroThreshold: 1.4,
664 want: &dto.Histogram{
665 SampleCount: proto.Uint64(11),
666 SampleSum: proto.Float64(0),
667 Schema: proto.Int32(2),
668 ZeroThreshold: proto.Float64(1.4),
669 ZeroCount: proto.Uint64(7),
670 NegativeSpan: []*dto.BucketSpan{
671 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
672 },
673 NegativeDelta: []int64{2},
674 PositiveSpan: []*dto.BucketSpan{
675 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
676 },
677 PositiveDelta: []int64{2},
678 CreatedTimestamp: timestamppb.New(now),
679 },
680 },
681 {
682 name: "NaN observation",
683 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.NaN()},
684 factor: 1.2,
685 want: &dto.Histogram{
686 SampleCount: proto.Uint64(7),
687 SampleSum: proto.Float64(math.NaN()),
688 Schema: proto.Int32(2),
689 ZeroThreshold: proto.Float64(2.938735877055719e-39),
690 ZeroCount: proto.Uint64(1),
691 PositiveSpan: []*dto.BucketSpan{
692 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
693 },
694 PositiveDelta: []int64{1, -1, 2, -2, 2},
695 CreatedTimestamp: timestamppb.New(now),
696 },
697 },
698 {
699 name: "+Inf observation",
700 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(+1)},
701 factor: 1.2,
702 want: &dto.Histogram{
703 SampleCount: proto.Uint64(7),
704 SampleSum: proto.Float64(math.Inf(+1)),
705 Schema: proto.Int32(2),
706 ZeroThreshold: proto.Float64(2.938735877055719e-39),
707 ZeroCount: proto.Uint64(1),
708 PositiveSpan: []*dto.BucketSpan{
709 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
710 {Offset: proto.Int32(4092), Length: proto.Uint32(1)},
711 },
712 PositiveDelta: []int64{1, -1, 2, -2, 2, -1},
713 CreatedTimestamp: timestamppb.New(now),
714 },
715 },
716 {
717 name: "-Inf observation",
718 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(-1)},
719 factor: 1.2,
720 want: &dto.Histogram{
721 SampleCount: proto.Uint64(7),
722 SampleSum: proto.Float64(math.Inf(-1)),
723 Schema: proto.Int32(2),
724 ZeroThreshold: proto.Float64(2.938735877055719e-39),
725 ZeroCount: proto.Uint64(1),
726 NegativeSpan: []*dto.BucketSpan{
727 {Offset: proto.Int32(4097), Length: proto.Uint32(1)},
728 },
729 NegativeDelta: []int64{1},
730 PositiveSpan: []*dto.BucketSpan{
731 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
732 },
733 PositiveDelta: []int64{1, -1, 2, -2, 2},
734 CreatedTimestamp: timestamppb.New(now),
735 },
736 },
737 {
738 name: "limited buckets but nothing triggered",
739 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
740 factor: 1.2,
741 maxBuckets: 4,
742 want: &dto.Histogram{
743 SampleCount: proto.Uint64(6),
744 SampleSum: proto.Float64(7.4),
745 Schema: proto.Int32(2),
746 ZeroThreshold: proto.Float64(2.938735877055719e-39),
747 ZeroCount: proto.Uint64(1),
748 PositiveSpan: []*dto.BucketSpan{
749 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
750 },
751 PositiveDelta: []int64{1, -1, 2, -2, 2},
752 CreatedTimestamp: timestamppb.New(now),
753 },
754 },
755 {
756 name: "buckets limited by halving resolution",
757 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
758 factor: 1.2,
759 maxBuckets: 4,
760 want: &dto.Histogram{
761 SampleCount: proto.Uint64(8),
762 SampleSum: proto.Float64(11.5),
763 Schema: proto.Int32(1),
764 ZeroThreshold: proto.Float64(2.938735877055719e-39),
765 ZeroCount: proto.Uint64(1),
766 PositiveSpan: []*dto.BucketSpan{
767 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
768 },
769 PositiveDelta: []int64{1, 2, -1, -2, 1},
770 CreatedTimestamp: timestamppb.New(now),
771 },
772 },
773 {
774 name: "buckets limited by widening the zero bucket",
775 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
776 factor: 1.2,
777 maxBuckets: 4,
778 maxZeroThreshold: 1.2,
779 want: &dto.Histogram{
780 SampleCount: proto.Uint64(8),
781 SampleSum: proto.Float64(11.5),
782 Schema: proto.Int32(2),
783 ZeroThreshold: proto.Float64(1),
784 ZeroCount: proto.Uint64(2),
785 PositiveSpan: []*dto.BucketSpan{
786 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
787 },
788 PositiveDelta: []int64{1, 1, -2, 2, -2, 0, 1},
789 CreatedTimestamp: timestamppb.New(now),
790 },
791 },
792 {
793 name: "buckets limited by widening the zero bucket twice",
794 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
795 factor: 1.2,
796 maxBuckets: 4,
797 maxZeroThreshold: 1.2,
798 want: &dto.Histogram{
799 SampleCount: proto.Uint64(9),
800 SampleSum: proto.Float64(15.5),
801 Schema: proto.Int32(2),
802 ZeroThreshold: proto.Float64(1.189207115002721),
803 ZeroCount: proto.Uint64(3),
804 PositiveSpan: []*dto.BucketSpan{
805 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
806 },
807 PositiveDelta: []int64{2, -2, 2, -2, 0, 1, 0},
808 CreatedTimestamp: timestamppb.New(now),
809 },
810 },
811 {
812 name: "buckets limited by reset",
813 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
814 factor: 1.2,
815 maxBuckets: 4,
816 maxZeroThreshold: 1.2,
817 minResetDuration: 5 * time.Minute,
818 want: &dto.Histogram{
819 SampleCount: proto.Uint64(2),
820 SampleSum: proto.Float64(7),
821 Schema: proto.Int32(2),
822 ZeroThreshold: proto.Float64(2.938735877055719e-39),
823 ZeroCount: proto.Uint64(0),
824 PositiveSpan: []*dto.BucketSpan{
825 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
826 },
827 PositiveDelta: []int64{1, 0},
828 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
829 },
830 },
831 {
832 name: "limited buckets but nothing triggered, negative observations",
833 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
834 factor: 1.2,
835 maxBuckets: 4,
836 want: &dto.Histogram{
837 SampleCount: proto.Uint64(6),
838 SampleSum: proto.Float64(-7.4),
839 Schema: proto.Int32(2),
840 ZeroThreshold: proto.Float64(2.938735877055719e-39),
841 ZeroCount: proto.Uint64(1),
842 NegativeSpan: []*dto.BucketSpan{
843 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
844 },
845 NegativeDelta: []int64{1, -1, 2, -2, 2},
846 CreatedTimestamp: timestamppb.New(now),
847 },
848 },
849 {
850 name: "buckets limited by halving resolution, negative observations",
851 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
852 factor: 1.2,
853 maxBuckets: 4,
854 want: &dto.Histogram{
855 SampleCount: proto.Uint64(8),
856 SampleSum: proto.Float64(-11.5),
857 Schema: proto.Int32(1),
858 ZeroThreshold: proto.Float64(2.938735877055719e-39),
859 ZeroCount: proto.Uint64(1),
860 NegativeSpan: []*dto.BucketSpan{
861 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
862 },
863 NegativeDelta: []int64{1, 2, -1, -2, 1},
864 CreatedTimestamp: timestamppb.New(now),
865 },
866 },
867 {
868 name: "buckets limited by widening the zero bucket, negative observations",
869 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
870 factor: 1.2,
871 maxBuckets: 4,
872 maxZeroThreshold: 1.2,
873 want: &dto.Histogram{
874 SampleCount: proto.Uint64(8),
875 SampleSum: proto.Float64(-11.5),
876 Schema: proto.Int32(2),
877 ZeroThreshold: proto.Float64(1),
878 ZeroCount: proto.Uint64(2),
879 NegativeSpan: []*dto.BucketSpan{
880 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
881 },
882 NegativeDelta: []int64{1, 1, -2, 2, -2, 0, 1},
883 CreatedTimestamp: timestamppb.New(now),
884 },
885 },
886 {
887 name: "buckets limited by widening the zero bucket twice, negative observations",
888 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
889 factor: 1.2,
890 maxBuckets: 4,
891 maxZeroThreshold: 1.2,
892 want: &dto.Histogram{
893 SampleCount: proto.Uint64(9),
894 SampleSum: proto.Float64(-15.5),
895 Schema: proto.Int32(2),
896 ZeroThreshold: proto.Float64(1.189207115002721),
897 ZeroCount: proto.Uint64(3),
898 NegativeSpan: []*dto.BucketSpan{
899 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
900 },
901 NegativeDelta: []int64{2, -2, 2, -2, 0, 1, 0},
902 CreatedTimestamp: timestamppb.New(now),
903 },
904 },
905 {
906 name: "buckets limited by reset, negative observations",
907 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
908 factor: 1.2,
909 maxBuckets: 4,
910 maxZeroThreshold: 1.2,
911 minResetDuration: 5 * time.Minute,
912 want: &dto.Histogram{
913 SampleCount: proto.Uint64(2),
914 SampleSum: proto.Float64(-7),
915 Schema: proto.Int32(2),
916 ZeroThreshold: proto.Float64(2.938735877055719e-39),
917 ZeroCount: proto.Uint64(0),
918 NegativeSpan: []*dto.BucketSpan{
919 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
920 },
921 NegativeDelta: []int64{1, 0},
922 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
923 },
924 },
925 {
926 name: "buckets limited by halving resolution, then reset",
927 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
928 factor: 1.2,
929 maxBuckets: 4,
930 minResetDuration: 9 * time.Minute,
931 want: &dto.Histogram{
932 SampleCount: proto.Uint64(3),
933 SampleSum: proto.Float64(12.1),
934 Schema: proto.Int32(2),
935 ZeroThreshold: proto.Float64(2.938735877055719e-39),
936 ZeroCount: proto.Uint64(0),
937 PositiveSpan: []*dto.BucketSpan{
938 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
939 },
940 PositiveDelta: []int64{1, 0, -1, 1},
941 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
942 },
943 },
944 {
945 name: "buckets limited by widening the zero bucket, then reset",
946 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
947 factor: 1.2,
948 maxBuckets: 4,
949 maxZeroThreshold: 1.2,
950 minResetDuration: 9 * time.Minute,
951 want: &dto.Histogram{
952 SampleCount: proto.Uint64(3),
953 SampleSum: proto.Float64(12.1),
954 Schema: proto.Int32(2),
955 ZeroThreshold: proto.Float64(2.938735877055719e-39),
956 ZeroCount: proto.Uint64(0),
957 PositiveSpan: []*dto.BucketSpan{
958 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
959 },
960 PositiveDelta: []int64{1, 0, -1, 1},
961 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
962 },
963 },
964 }
965
966 for _, s := range scenarios {
967 t.Run(s.name, func(t *testing.T) {
968 var (
969 ts = now
970 funcToCall func()
971 whenToCall time.Duration
972 )
973
974 his := NewHistogram(HistogramOpts{
975 Name: "name",
976 Help: "help",
977 NativeHistogramBucketFactor: s.factor,
978 NativeHistogramZeroThreshold: s.zeroThreshold,
979 NativeHistogramMaxBucketNumber: s.maxBuckets,
980 NativeHistogramMinResetDuration: s.minResetDuration,
981 NativeHistogramMaxZeroThreshold: s.maxZeroThreshold,
982 now: func() time.Time { return ts },
983 afterFunc: func(d time.Duration, f func()) *time.Timer {
984 funcToCall = f
985 whenToCall = d
986 return nil
987 },
988 })
989
990 ts = ts.Add(time.Minute)
991 for _, o := range s.observations {
992 his.Observe(o)
993 ts = ts.Add(time.Minute)
994 whenToCall -= time.Minute
995 if funcToCall != nil && whenToCall <= 0 {
996 funcToCall()
997 funcToCall = nil
998 }
999 }
1000 m := &dto.Metric{}
1001 if err := his.Write(m); err != nil {
1002 t.Fatal("unexpected error writing metric", err)
1003 }
1004 got := m.Histogram
1005 if !proto.Equal(s.want, got) {
1006 t.Errorf("want histogram %q, got %q", s.want, got)
1007 }
1008 })
1009 }
1010 }
1011
1012 func TestNativeHistogramConcurrency(t *testing.T) {
1013 if testing.Short() {
1014 t.Skip("Skipping test in short mode.")
1015 }
1016
1017 rand.New(rand.NewSource(42))
1018
1019 it := func(n uint32) bool {
1020 ts := time.Now().Add(30 * time.Second).Unix()
1021
1022 mutations := int(n%1e4 + 1e4)
1023 concLevel := int(n%5 + 1)
1024 total := mutations * concLevel
1025
1026 var start, end sync.WaitGroup
1027 start.Add(1)
1028 end.Add(concLevel)
1029
1030 his := NewHistogram(HistogramOpts{
1031 Name: "test_native_histogram",
1032 Help: "This help is sparse.",
1033 NativeHistogramBucketFactor: 1.05,
1034 NativeHistogramZeroThreshold: 0.0000001,
1035 NativeHistogramMaxBucketNumber: 50,
1036 NativeHistogramMinResetDuration: time.Hour, // Comment out to test for totals below.
1037 NativeHistogramMaxZeroThreshold: 0.001,
1038 now: func() time.Time {
1039 return time.Unix(atomic.LoadInt64(&ts), 0)
1040 },
1041 })
1042
1043 allVars := make([]float64, total)
1044 var sampleSum float64
1045 for i := 0; i < concLevel; i++ {
1046 vals := make([]float64, mutations)
1047 for j := 0; j < mutations; j++ {
1048 v := rand.NormFloat64()
1049 vals[j] = v
1050 allVars[i*mutations+j] = v
1051 sampleSum += v
1052 }
1053
1054 go func(vals []float64) {
1055 start.Wait()
1056 for i, v := range vals {
1057 // An observation every 1 to 10 seconds.
1058 atomic.AddInt64(&ts, rand.Int63n(10)+1)
1059 if i%2 == 0 {
1060 his.Observe(v)
1061 } else {
1062 his.(ExemplarObserver).ObserveWithExemplar(v, Labels{"foo": "bar"})
1063 }
1064 }
1065 end.Done()
1066 }(vals)
1067 }
1068 sort.Float64s(allVars)
1069 start.Done()
1070 end.Wait()
1071
1072 m := &dto.Metric{}
1073 his.Write(m)
1074
1075 // Uncomment these tests for totals only if you have disabled histogram resets above.
1076 //
1077 // if got, want := int(*m.Histogram.SampleCount), total; got != want {
1078 // t.Errorf("got sample count %d, want %d", got, want)
1079 // }
1080 // if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 {
1081 // t.Errorf("got sample sum %f, want %f", got, want)
1082 // }
1083
1084 sumBuckets := int(m.Histogram.GetZeroCount())
1085 current := 0
1086 for _, delta := range m.Histogram.GetNegativeDelta() {
1087 current += int(delta)
1088 if current < 0 {
1089 t.Fatalf("negative bucket population negative: %d", current)
1090 }
1091 sumBuckets += current
1092 }
1093 current = 0
1094 for _, delta := range m.Histogram.GetPositiveDelta() {
1095 current += int(delta)
1096 if current < 0 {
1097 t.Fatalf("positive bucket population negative: %d", current)
1098 }
1099 sumBuckets += current
1100 }
1101 if got, want := sumBuckets, int(*m.Histogram.SampleCount); got != want {
1102 t.Errorf("got bucket population sum %d, want %d", got, want)
1103 }
1104
1105 return true
1106 }
1107
1108 if err := quick.Check(it, nil); err != nil {
1109 t.Error(err)
1110 }
1111 }
1112
1113 func TestGetLe(t *testing.T) {
1114 scenarios := []struct {
1115 key int
1116 schema int32
1117 want float64
1118 }{
1119 {
1120 key: -1,
1121 schema: -1,
1122 want: 0.25,
1123 },
1124 {
1125 key: 0,
1126 schema: -1,
1127 want: 1,
1128 },
1129 {
1130 key: 1,
1131 schema: -1,
1132 want: 4,
1133 },
1134 {
1135 key: 512,
1136 schema: -1,
1137 want: math.MaxFloat64,
1138 },
1139 {
1140 key: 513,
1141 schema: -1,
1142 want: math.Inf(+1),
1143 },
1144 {
1145 key: -1,
1146 schema: 0,
1147 want: 0.5,
1148 },
1149 {
1150 key: 0,
1151 schema: 0,
1152 want: 1,
1153 },
1154 {
1155 key: 1,
1156 schema: 0,
1157 want: 2,
1158 },
1159 {
1160 key: 1024,
1161 schema: 0,
1162 want: math.MaxFloat64,
1163 },
1164 {
1165 key: 1025,
1166 schema: 0,
1167 want: math.Inf(+1),
1168 },
1169 {
1170 key: -1,
1171 schema: 2,
1172 want: 0.8408964152537144,
1173 },
1174 {
1175 key: 0,
1176 schema: 2,
1177 want: 1,
1178 },
1179 {
1180 key: 1,
1181 schema: 2,
1182 want: 1.189207115002721,
1183 },
1184 {
1185 key: 4096,
1186 schema: 2,
1187 want: math.MaxFloat64,
1188 },
1189 {
1190 key: 4097,
1191 schema: 2,
1192 want: math.Inf(+1),
1193 },
1194 }
1195
1196 for i, s := range scenarios {
1197 got := getLe(s.key, s.schema)
1198 if s.want != got {
1199 t.Errorf("%d. key %d, schema %d, want upper bound of %g, got %g", i, s.key, s.schema, s.want, got)
1200 }
1201 }
1202 }
1203
1204 func TestHistogramCreatedTimestamp(t *testing.T) {
1205 now := time.Now()
1206
1207 histogram := NewHistogram(HistogramOpts{
1208 Name: "test",
1209 Help: "test help",
1210 Buckets: []float64{1, 2, 3, 4},
1211 now: func() time.Time { return now },
1212 })
1213
1214 var metric dto.Metric
1215 if err := histogram.Write(&metric); err != nil {
1216 t.Fatal(err)
1217 }
1218
1219 if metric.Histogram.CreatedTimestamp.AsTime().Unix() != now.Unix() {
1220 t.Errorf("expected created timestamp %d, got %d", now.Unix(), metric.Histogram.CreatedTimestamp.AsTime().Unix())
1221 }
1222 }
1223
1224 func TestHistogramVecCreatedTimestamp(t *testing.T) {
1225 now := time.Now()
1226
1227 histogramVec := NewHistogramVec(HistogramOpts{
1228 Name: "test",
1229 Help: "test help",
1230 Buckets: []float64{1, 2, 3, 4},
1231 now: func() time.Time { return now },
1232 }, []string{"label"})
1233 histogram := histogramVec.WithLabelValues("value").(Histogram)
1234
1235 var metric dto.Metric
1236 if err := histogram.Write(&metric); err != nil {
1237 t.Fatal(err)
1238 }
1239
1240 if metric.Histogram.CreatedTimestamp.AsTime().Unix() != now.Unix() {
1241 t.Errorf("expected created timestamp %d, got %d", now.Unix(), metric.Histogram.CreatedTimestamp.AsTime().Unix())
1242 }
1243 }
1244
1245 func TestHistogramVecCreatedTimestampWithDeletes(t *testing.T) {
1246 now := time.Now()
1247
1248 histogramVec := NewHistogramVec(HistogramOpts{
1249 Name: "test",
1250 Help: "test help",
1251 Buckets: []float64{1, 2, 3, 4},
1252 now: func() time.Time { return now },
1253 }, []string{"label"})
1254
1255 // First use of "With" should populate CT.
1256 histogramVec.WithLabelValues("1")
1257 expected := map[string]time.Time{"1": now}
1258
1259 now = now.Add(1 * time.Hour)
1260 expectCTsForMetricVecValues(t, histogramVec.MetricVec, dto.MetricType_HISTOGRAM, expected)
1261
1262 // Two more labels at different times.
1263 histogramVec.WithLabelValues("2")
1264 expected["2"] = now
1265
1266 now = now.Add(1 * time.Hour)
1267
1268 histogramVec.WithLabelValues("3")
1269 expected["3"] = now
1270
1271 now = now.Add(1 * time.Hour)
1272 expectCTsForMetricVecValues(t, histogramVec.MetricVec, dto.MetricType_HISTOGRAM, expected)
1273
1274 // Recreate metric instance should reset created timestamp to now.
1275 histogramVec.DeleteLabelValues("1")
1276 histogramVec.WithLabelValues("1")
1277 expected["1"] = now
1278
1279 now = now.Add(1 * time.Hour)
1280 expectCTsForMetricVecValues(t, histogramVec.MetricVec, dto.MetricType_HISTOGRAM, expected)
1281 }
1282
1283 func TestNewConstHistogramWithCreatedTimestamp(t *testing.T) {
1284 metricDesc := NewDesc(
1285 "sample_value",
1286 "sample value",
1287 nil,
1288 nil,
1289 )
1290 buckets := map[float64]uint64{25: 100, 50: 200}
1291 createdTs := time.Unix(1719670764, 123)
1292
1293 h, err := NewConstHistogramWithCreatedTimestamp(metricDesc, 100, 200, buckets, createdTs)
1294 if err != nil {
1295 t.Fatal(err)
1296 }
1297
1298 var metric dto.Metric
1299 if err := h.Write(&metric); err != nil {
1300 t.Fatal(err)
1301 }
1302
1303 if metric.Histogram.CreatedTimestamp.AsTime().UnixMicro() != createdTs.UnixMicro() {
1304 t.Errorf("Expected created timestamp %v, got %v", createdTs, &metric.Histogram.CreatedTimestamp)
1305 }
1306 }
1307
1308 func TestNativeHistogramExemplar(t *testing.T) {
1309 // Test the histogram with positive NativeHistogramExemplarTTL and NativeHistogramMaxExemplars
1310 h := NewHistogram(HistogramOpts{
1311 Name: "test",
1312 Help: "test help",
1313 Buckets: []float64{1, 2, 3, 4},
1314 NativeHistogramBucketFactor: 1.1,
1315 NativeHistogramMaxExemplars: 3,
1316 NativeHistogramExemplarTTL: 10 * time.Second,
1317 }).(*histogram)
1318
1319 tcs := []struct {
1320 name string
1321 addFunc func(*histogram)
1322 expectedValues []float64
1323 }{
1324 {
1325 name: "add exemplars to the limit",
1326 addFunc: func(h *histogram) {
1327 h.ObserveWithExemplar(1, Labels{"id": "1"})
1328 h.ObserveWithExemplar(3, Labels{"id": "1"})
1329 h.ObserveWithExemplar(5, Labels{"id": "1"})
1330 },
1331 expectedValues: []float64{1, 3, 5},
1332 },
1333 {
1334 name: "remove exemplar in closest pair, the removed index equals to inserted index",
1335 addFunc: func(h *histogram) {
1336 h.ObserveWithExemplar(4, Labels{"id": "1"})
1337 },
1338 expectedValues: []float64{1, 3, 4},
1339 },
1340 {
1341 name: "remove exemplar in closest pair, the removed index is bigger than inserted index",
1342 addFunc: func(h *histogram) {
1343 h.ObserveWithExemplar(0, Labels{"id": "1"})
1344 },
1345 expectedValues: []float64{0, 1, 4},
1346 },
1347 {
1348 name: "remove exemplar with oldest timestamp, the removed index is smaller than inserted index",
1349 addFunc: func(h *histogram) {
1350 h.now = func() time.Time { return time.Now().Add(time.Second * 11) }
1351 h.ObserveWithExemplar(6, Labels{"id": "1"})
1352 },
1353 expectedValues: []float64{0, 4, 6},
1354 },
1355 }
1356
1357 for _, tc := range tcs {
1358 t.Run(tc.name, func(t *testing.T) {
1359 tc.addFunc(h)
1360 compareNativeExemplarValues(t, h.nativeExemplars.exemplars, tc.expectedValues)
1361 })
1362 }
1363
1364 // Test the histogram with negative NativeHistogramExemplarTTL
1365 h = NewHistogram(HistogramOpts{
1366 Name: "test",
1367 Help: "test help",
1368 Buckets: []float64{1, 2, 3, 4},
1369 NativeHistogramBucketFactor: 1.1,
1370 NativeHistogramMaxExemplars: 3,
1371 NativeHistogramExemplarTTL: -1 * time.Second,
1372 }).(*histogram)
1373
1374 tcs = []struct {
1375 name string
1376 addFunc func(*histogram)
1377 expectedValues []float64
1378 }{
1379 {
1380 name: "add exemplars to the limit",
1381 addFunc: func(h *histogram) {
1382 h.ObserveWithExemplar(1, Labels{"id": "1"})
1383 h.ObserveWithExemplar(3, Labels{"id": "1"})
1384 h.ObserveWithExemplar(5, Labels{"id": "1"})
1385 },
1386 expectedValues: []float64{1, 3, 5},
1387 },
1388 {
1389 name: "remove exemplar with oldest timestamp, the removed index is smaller than inserted index",
1390 addFunc: func(h *histogram) {
1391 h.ObserveWithExemplar(4, Labels{"id": "1"})
1392 },
1393 expectedValues: []float64{3, 4, 5},
1394 },
1395 {
1396 name: "remove exemplar with oldest timestamp, the removed index equals to inserted index",
1397 addFunc: func(h *histogram) {
1398 h.ObserveWithExemplar(0, Labels{"id": "1"})
1399 },
1400 expectedValues: []float64{0, 4, 5},
1401 },
1402 {
1403 name: "remove exemplar with oldest timestamp, the removed index is bigger than inserted index",
1404 addFunc: func(h *histogram) {
1405 h.ObserveWithExemplar(3, Labels{"id": "1"})
1406 },
1407 expectedValues: []float64{0, 3, 4},
1408 },
1409 }
1410
1411 for _, tc := range tcs {
1412 t.Run(tc.name, func(t *testing.T) {
1413 tc.addFunc(h)
1414 compareNativeExemplarValues(t, h.nativeExemplars.exemplars, tc.expectedValues)
1415 })
1416 }
1417
1418 // Test the histogram with negative NativeHistogramMaxExemplars
1419 h = NewHistogram(HistogramOpts{
1420 Name: "test",
1421 Help: "test help",
1422 Buckets: []float64{1, 2, 3, 4},
1423 NativeHistogramBucketFactor: 1.1,
1424 NativeHistogramMaxExemplars: -1,
1425 NativeHistogramExemplarTTL: -1 * time.Second,
1426 }).(*histogram)
1427
1428 tcs = []struct {
1429 name string
1430 addFunc func(*histogram)
1431 expectedValues []float64
1432 }{
1433 {
1434 name: "add exemplars to the limit, but no effect",
1435 addFunc: func(h *histogram) {
1436 h.ObserveWithExemplar(1, Labels{"id": "1"})
1437 h.ObserveWithExemplar(3, Labels{"id": "1"})
1438 h.ObserveWithExemplar(5, Labels{"id": "1"})
1439 },
1440 expectedValues: []float64{},
1441 },
1442 }
1443
1444 for _, tc := range tcs {
1445 t.Run(tc.name, func(t *testing.T) {
1446 tc.addFunc(h)
1447 compareNativeExemplarValues(t, h.nativeExemplars.exemplars, tc.expectedValues)
1448 })
1449 }
1450 }
1451
1452 func compareNativeExemplarValues(t *testing.T, exps []*dto.Exemplar, values []float64) {
1453 if len(exps) != len(values) {
1454 t.Errorf("the count of exemplars is not %d", len(values))
1455 }
1456 for i, e := range exps {
1457 if e.GetValue() != values[i] {
1458 t.Errorf("the %dth exemplar value %v is not as expected: %v", i, e.GetValue(), values[i])
1459 }
1460 }
1461 }
1462
1463 var resultFindBucket int
1464
1465 func benchmarkFindBucket(b *testing.B, l int) {
1466 h := &histogram{upperBounds: make([]float64, l)}
1467 for i := range h.upperBounds {
1468 h.upperBounds[i] = float64(i)
1469 }
1470 v := float64(l / 2)
1471
1472 b.ResetTimer()
1473 for i := 0; i < b.N; i++ {
1474 resultFindBucket = h.findBucket(v)
1475 }
1476 }
1477
1478 func BenchmarkFindBucketShort(b *testing.B) {
1479 benchmarkFindBucket(b, 20)
1480 }
1481
1482 func BenchmarkFindBucketMid(b *testing.B) {
1483 benchmarkFindBucket(b, 40)
1484 }
1485
1486 func BenchmarkFindBucketLarge(b *testing.B) {
1487 benchmarkFindBucket(b, 100)
1488 }
1489
1490 func BenchmarkFindBucketHuge(b *testing.B) {
1491 benchmarkFindBucket(b, 500)
1492 }
1493
1494 func BenchmarkFindBucketInf(b *testing.B) {
1495 h := &histogram{upperBounds: make([]float64, 500)}
1496 for i := range h.upperBounds {
1497 h.upperBounds[i] = float64(i)
1498 }
1499 v := 1000.5
1500
1501 b.ResetTimer()
1502 for i := 0; i < b.N; i++ {
1503 resultFindBucket = h.findBucket(v)
1504 }
1505 }
1506
1507 func BenchmarkFindBucketLow(b *testing.B) {
1508 h := &histogram{upperBounds: make([]float64, 500)}
1509 for i := range h.upperBounds {
1510 h.upperBounds[i] = float64(i)
1511 }
1512 v := -1.1
1513
1514 b.ResetTimer()
1515 for i := 0; i < b.N; i++ {
1516 resultFindBucket = h.findBucket(v)
1517 }
1518 }
1519
1520 func TestFindBucket(t *testing.T) {
1521 smallHistogram := &histogram{upperBounds: []float64{1, 2, 3, 4, 5}}
1522 largeHistogram := &histogram{upperBounds: make([]float64, 50)}
1523 for i := range largeHistogram.upperBounds {
1524 largeHistogram.upperBounds[i] = float64(i)
1525 }
1526
1527 tests := []struct {
1528 h *histogram
1529 v float64
1530 expected int
1531 }{
1532 {smallHistogram, -1, 0},
1533 {smallHistogram, 0.5, 0},
1534 {smallHistogram, 2.5, 2},
1535 {smallHistogram, 5.5, 5},
1536 {largeHistogram, -1, 0},
1537 {largeHistogram, 25.5, 26},
1538 {largeHistogram, 49.5, 50},
1539 {largeHistogram, 50.5, 50},
1540 {largeHistogram, 5000.5, 50},
1541 }
1542
1543 for _, tt := range tests {
1544 result := tt.h.findBucket(tt.v)
1545 if result != tt.expected {
1546 t.Errorf("findBucket(%v) = %d; expected %d", tt.v, result, tt.expected)
1547 }
1548 }
1549 }
1550
1551 func syncMapToMap(syncmap *sync.Map) (m map[int]int64) {
1552 m = map[int]int64{}
1553 syncmap.Range(func(key, value any) bool {
1554 m[key.(int)] = *value.(*int64)
1555 return true
1556 })
1557 return m
1558 }
1559
1560 func TestConstNativeHistogram(t *testing.T) {
1561 now := time.Now()
1562
1563 scenarios := []struct {
1564 name string
1565 observations []float64 // With simulated interval of 1m.
1566 factor float64
1567 zeroThreshold float64
1568 maxBuckets uint32
1569 minResetDuration time.Duration
1570 maxZeroThreshold float64
1571 want *dto.Histogram
1572 }{
1573 {
1574 name: "no observations",
1575 factor: 1.1,
1576 want: &dto.Histogram{
1577 SampleCount: proto.Uint64(0),
1578 SampleSum: proto.Float64(0),
1579 Schema: proto.Int32(3),
1580 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1581 ZeroCount: proto.Uint64(0),
1582 CreatedTimestamp: timestamppb.New(now),
1583 },
1584 },
1585 {
1586 name: "no observations and zero threshold of zero resulting in no-op span",
1587 factor: 1.1,
1588 zeroThreshold: NativeHistogramZeroThresholdZero,
1589 want: &dto.Histogram{
1590 SampleCount: proto.Uint64(0),
1591 SampleSum: proto.Float64(0),
1592 Schema: proto.Int32(3),
1593 ZeroThreshold: proto.Float64(0),
1594 ZeroCount: proto.Uint64(0),
1595 PositiveSpan: []*dto.BucketSpan{
1596 {Offset: proto.Int32(0), Length: proto.Uint32(0)},
1597 },
1598 CreatedTimestamp: timestamppb.New(now),
1599 },
1600 },
1601 {
1602 name: "factor 1.1 results in schema 3",
1603 observations: []float64{0, 1, 2, 3},
1604 factor: 1.1,
1605 want: &dto.Histogram{
1606 SampleCount: proto.Uint64(4),
1607 SampleSum: proto.Float64(6),
1608 Schema: proto.Int32(3),
1609 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1610 ZeroCount: proto.Uint64(1),
1611 PositiveSpan: []*dto.BucketSpan{
1612 {Offset: proto.Int32(0), Length: proto.Uint32(1)},
1613 {Offset: proto.Int32(7), Length: proto.Uint32(1)},
1614 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
1615 },
1616 PositiveDelta: []int64{1, 0, 0},
1617 CreatedTimestamp: timestamppb.New(now),
1618 },
1619 },
1620 {
1621 name: "factor 1.2 results in schema 2",
1622 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
1623 factor: 1.2,
1624 want: &dto.Histogram{
1625 SampleCount: proto.Uint64(6),
1626 SampleSum: proto.Float64(7.4),
1627 Schema: proto.Int32(2),
1628 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1629 ZeroCount: proto.Uint64(1),
1630 PositiveSpan: []*dto.BucketSpan{
1631 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1632 },
1633 PositiveDelta: []int64{1, -1, 2, -2, 2},
1634 CreatedTimestamp: timestamppb.New(now),
1635 },
1636 },
1637 {
1638 name: "factor 4 results in schema -1",
1639 observations: []float64{
1640 0.0156251, 0.0625, // Bucket -2: (0.015625, 0.0625)
1641 0.1, 0.25, // Bucket -1: (0.0625, 0.25]
1642 0.5, 1, // Bucket 0: (0.25, 1]
1643 1.5, 2, 3, 3.5, // Bucket 1: (1, 4]
1644 5, 6, 7, // Bucket 2: (4, 16]
1645 33.33, // Bucket 3: (16, 64]
1646 },
1647 factor: 4,
1648 want: &dto.Histogram{
1649 SampleCount: proto.Uint64(14),
1650 SampleSum: proto.Float64(63.2581251),
1651 Schema: proto.Int32(-1),
1652 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1653 ZeroCount: proto.Uint64(0),
1654 PositiveSpan: []*dto.BucketSpan{
1655 {Offset: proto.Int32(-2), Length: proto.Uint32(6)},
1656 },
1657 PositiveDelta: []int64{2, 0, 0, 2, -1, -2},
1658 CreatedTimestamp: timestamppb.New(now),
1659 },
1660 },
1661 {
1662 name: "factor 17 results in schema -2",
1663 observations: []float64{
1664 0.0156251, 0.0625, // Bucket -1: (0.015625, 0.0625]
1665 0.1, 0.25, 0.5, 1, // Bucket 0: (0.0625, 1]
1666 1.5, 2, 3, 3.5, 5, 6, 7, // Bucket 1: (1, 16]
1667 33.33, // Bucket 2: (16, 256]
1668 },
1669 factor: 17,
1670 want: &dto.Histogram{
1671 SampleCount: proto.Uint64(14),
1672 SampleSum: proto.Float64(63.2581251),
1673 Schema: proto.Int32(-2),
1674 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1675 ZeroCount: proto.Uint64(0),
1676 PositiveSpan: []*dto.BucketSpan{
1677 {Offset: proto.Int32(-1), Length: proto.Uint32(4)},
1678 },
1679 PositiveDelta: []int64{2, 2, 3, -6},
1680 CreatedTimestamp: timestamppb.New(now),
1681 },
1682 },
1683 {
1684 name: "negative buckets",
1685 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
1686 factor: 1.2,
1687 want: &dto.Histogram{
1688 SampleCount: proto.Uint64(6),
1689 SampleSum: proto.Float64(-7.4),
1690 Schema: proto.Int32(2),
1691 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1692 ZeroCount: proto.Uint64(1),
1693 NegativeSpan: []*dto.BucketSpan{
1694 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1695 },
1696 NegativeDelta: []int64{1, -1, 2, -2, 2},
1697 CreatedTimestamp: timestamppb.New(now),
1698 },
1699 },
1700 {
1701 name: "negative and positive buckets",
1702 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
1703 factor: 1.2,
1704 want: &dto.Histogram{
1705 SampleCount: proto.Uint64(11),
1706 SampleSum: proto.Float64(0),
1707 Schema: proto.Int32(2),
1708 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1709 ZeroCount: proto.Uint64(1),
1710 NegativeSpan: []*dto.BucketSpan{
1711 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1712 },
1713 NegativeDelta: []int64{1, -1, 2, -2, 2},
1714 PositiveSpan: []*dto.BucketSpan{
1715 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1716 },
1717 PositiveDelta: []int64{1, -1, 2, -2, 2},
1718 CreatedTimestamp: timestamppb.New(now),
1719 },
1720 },
1721 {
1722 name: "wide zero bucket",
1723 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2, 1, 1.2, 1.4, 1.8, 2},
1724 factor: 1.2,
1725 zeroThreshold: 1.4,
1726 want: &dto.Histogram{
1727 SampleCount: proto.Uint64(11),
1728 SampleSum: proto.Float64(0),
1729 Schema: proto.Int32(2),
1730 ZeroThreshold: proto.Float64(1.4),
1731 ZeroCount: proto.Uint64(7),
1732 NegativeSpan: []*dto.BucketSpan{
1733 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
1734 },
1735 NegativeDelta: []int64{2},
1736 PositiveSpan: []*dto.BucketSpan{
1737 {Offset: proto.Int32(4), Length: proto.Uint32(1)},
1738 },
1739 PositiveDelta: []int64{2},
1740 CreatedTimestamp: timestamppb.New(now),
1741 },
1742 },
1743 {
1744 name: "NaN observation",
1745 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.NaN()},
1746 factor: 1.2,
1747 want: &dto.Histogram{
1748 SampleCount: proto.Uint64(7),
1749 SampleSum: proto.Float64(math.NaN()),
1750 Schema: proto.Int32(2),
1751 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1752 ZeroCount: proto.Uint64(1),
1753 PositiveSpan: []*dto.BucketSpan{
1754 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1755 },
1756 PositiveDelta: []int64{1, -1, 2, -2, 2},
1757 CreatedTimestamp: timestamppb.New(now),
1758 },
1759 },
1760 {
1761 name: "+Inf observation",
1762 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(+1)},
1763 factor: 1.2,
1764 want: &dto.Histogram{
1765 SampleCount: proto.Uint64(7),
1766 SampleSum: proto.Float64(math.Inf(+1)),
1767 Schema: proto.Int32(2),
1768 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1769 ZeroCount: proto.Uint64(1),
1770 PositiveSpan: []*dto.BucketSpan{
1771 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1772 {Offset: proto.Int32(4092), Length: proto.Uint32(1)},
1773 },
1774 PositiveDelta: []int64{1, -1, 2, -2, 2, -1},
1775 CreatedTimestamp: timestamppb.New(now),
1776 },
1777 },
1778 {
1779 name: "-Inf observation",
1780 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2, math.Inf(-1)},
1781 factor: 1.2,
1782 want: &dto.Histogram{
1783 SampleCount: proto.Uint64(7),
1784 SampleSum: proto.Float64(math.Inf(-1)),
1785 Schema: proto.Int32(2),
1786 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1787 ZeroCount: proto.Uint64(1),
1788 NegativeSpan: []*dto.BucketSpan{
1789 {Offset: proto.Int32(4097), Length: proto.Uint32(1)},
1790 },
1791 NegativeDelta: []int64{1},
1792 PositiveSpan: []*dto.BucketSpan{
1793 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1794 },
1795 PositiveDelta: []int64{1, -1, 2, -2, 2},
1796 CreatedTimestamp: timestamppb.New(now),
1797 },
1798 },
1799 {
1800 name: "limited buckets but nothing triggered",
1801 observations: []float64{0, 1, 1.2, 1.4, 1.8, 2},
1802 factor: 1.2,
1803 maxBuckets: 4,
1804 want: &dto.Histogram{
1805 SampleCount: proto.Uint64(6),
1806 SampleSum: proto.Float64(7.4),
1807 Schema: proto.Int32(2),
1808 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1809 ZeroCount: proto.Uint64(1),
1810 PositiveSpan: []*dto.BucketSpan{
1811 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1812 },
1813 PositiveDelta: []int64{1, -1, 2, -2, 2},
1814 CreatedTimestamp: timestamppb.New(now),
1815 },
1816 },
1817 {
1818 name: "buckets limited by halving resolution",
1819 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
1820 factor: 1.2,
1821 maxBuckets: 4,
1822 want: &dto.Histogram{
1823 SampleCount: proto.Uint64(8),
1824 SampleSum: proto.Float64(11.5),
1825 Schema: proto.Int32(1),
1826 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1827 ZeroCount: proto.Uint64(1),
1828 PositiveSpan: []*dto.BucketSpan{
1829 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1830 },
1831 PositiveDelta: []int64{1, 2, -1, -2, 1},
1832 CreatedTimestamp: timestamppb.New(now),
1833 },
1834 },
1835 {
1836 name: "buckets limited by widening the zero bucket",
1837 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3},
1838 factor: 1.2,
1839 maxBuckets: 4,
1840 maxZeroThreshold: 1.2,
1841 want: &dto.Histogram{
1842 SampleCount: proto.Uint64(8),
1843 SampleSum: proto.Float64(11.5),
1844 Schema: proto.Int32(2),
1845 ZeroThreshold: proto.Float64(1),
1846 ZeroCount: proto.Uint64(2),
1847 PositiveSpan: []*dto.BucketSpan{
1848 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
1849 },
1850 PositiveDelta: []int64{1, 1, -2, 2, -2, 0, 1},
1851 CreatedTimestamp: timestamppb.New(now),
1852 },
1853 },
1854 {
1855 name: "buckets limited by widening the zero bucket twice",
1856 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
1857 factor: 1.2,
1858 maxBuckets: 4,
1859 maxZeroThreshold: 1.2,
1860 want: &dto.Histogram{
1861 SampleCount: proto.Uint64(9),
1862 SampleSum: proto.Float64(15.5),
1863 Schema: proto.Int32(2),
1864 ZeroThreshold: proto.Float64(1.189207115002721),
1865 ZeroCount: proto.Uint64(3),
1866 PositiveSpan: []*dto.BucketSpan{
1867 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
1868 },
1869 PositiveDelta: []int64{2, -2, 2, -2, 0, 1, 0},
1870 CreatedTimestamp: timestamppb.New(now),
1871 },
1872 },
1873 {
1874 name: "buckets limited by reset",
1875 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 3, 4},
1876 factor: 1.2,
1877 maxBuckets: 4,
1878 maxZeroThreshold: 1.2,
1879 minResetDuration: 5 * time.Minute,
1880 want: &dto.Histogram{
1881 SampleCount: proto.Uint64(2),
1882 SampleSum: proto.Float64(7),
1883 Schema: proto.Int32(2),
1884 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1885 ZeroCount: proto.Uint64(0),
1886 PositiveSpan: []*dto.BucketSpan{
1887 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
1888 },
1889 PositiveDelta: []int64{1, 0},
1890 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
1891 },
1892 },
1893 {
1894 name: "limited buckets but nothing triggered, negative observations",
1895 observations: []float64{0, -1, -1.2, -1.4, -1.8, -2},
1896 factor: 1.2,
1897 maxBuckets: 4,
1898 want: &dto.Histogram{
1899 SampleCount: proto.Uint64(6),
1900 SampleSum: proto.Float64(-7.4),
1901 Schema: proto.Int32(2),
1902 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1903 ZeroCount: proto.Uint64(1),
1904 NegativeSpan: []*dto.BucketSpan{
1905 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1906 },
1907 NegativeDelta: []int64{1, -1, 2, -2, 2},
1908 CreatedTimestamp: timestamppb.New(now),
1909 },
1910 },
1911 {
1912 name: "buckets limited by halving resolution, negative observations",
1913 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
1914 factor: 1.2,
1915 maxBuckets: 4,
1916 want: &dto.Histogram{
1917 SampleCount: proto.Uint64(8),
1918 SampleSum: proto.Float64(-11.5),
1919 Schema: proto.Int32(1),
1920 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1921 ZeroCount: proto.Uint64(1),
1922 NegativeSpan: []*dto.BucketSpan{
1923 {Offset: proto.Int32(0), Length: proto.Uint32(5)},
1924 },
1925 NegativeDelta: []int64{1, 2, -1, -2, 1},
1926 CreatedTimestamp: timestamppb.New(now),
1927 },
1928 },
1929 {
1930 name: "buckets limited by widening the zero bucket, negative observations",
1931 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3},
1932 factor: 1.2,
1933 maxBuckets: 4,
1934 maxZeroThreshold: 1.2,
1935 want: &dto.Histogram{
1936 SampleCount: proto.Uint64(8),
1937 SampleSum: proto.Float64(-11.5),
1938 Schema: proto.Int32(2),
1939 ZeroThreshold: proto.Float64(1),
1940 ZeroCount: proto.Uint64(2),
1941 NegativeSpan: []*dto.BucketSpan{
1942 {Offset: proto.Int32(1), Length: proto.Uint32(7)},
1943 },
1944 NegativeDelta: []int64{1, 1, -2, 2, -2, 0, 1},
1945 CreatedTimestamp: timestamppb.New(now),
1946 },
1947 },
1948 {
1949 name: "buckets limited by widening the zero bucket twice, negative observations",
1950 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
1951 factor: 1.2,
1952 maxBuckets: 4,
1953 maxZeroThreshold: 1.2,
1954 want: &dto.Histogram{
1955 SampleCount: proto.Uint64(9),
1956 SampleSum: proto.Float64(-15.5),
1957 Schema: proto.Int32(2),
1958 ZeroThreshold: proto.Float64(1.189207115002721),
1959 ZeroCount: proto.Uint64(3),
1960 NegativeSpan: []*dto.BucketSpan{
1961 {Offset: proto.Int32(2), Length: proto.Uint32(7)},
1962 },
1963 NegativeDelta: []int64{2, -2, 2, -2, 0, 1, 0},
1964 CreatedTimestamp: timestamppb.New(now),
1965 },
1966 },
1967 {
1968 name: "buckets limited by reset, negative observations",
1969 observations: []float64{0, -1, -1.1, -1.2, -1.4, -1.8, -2, -3, -4},
1970 factor: 1.2,
1971 maxBuckets: 4,
1972 maxZeroThreshold: 1.2,
1973 minResetDuration: 5 * time.Minute,
1974 want: &dto.Histogram{
1975 SampleCount: proto.Uint64(2),
1976 SampleSum: proto.Float64(-7),
1977 Schema: proto.Int32(2),
1978 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1979 ZeroCount: proto.Uint64(0),
1980 NegativeSpan: []*dto.BucketSpan{
1981 {Offset: proto.Int32(7), Length: proto.Uint32(2)},
1982 },
1983 NegativeDelta: []int64{1, 0},
1984 CreatedTimestamp: timestamppb.New(now.Add(8 * time.Minute)), // We expect reset to happen after 8 observations.
1985 },
1986 },
1987 {
1988 name: "buckets limited by halving resolution, then reset",
1989 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
1990 factor: 1.2,
1991 maxBuckets: 4,
1992 minResetDuration: 9 * time.Minute,
1993 want: &dto.Histogram{
1994 SampleCount: proto.Uint64(3),
1995 SampleSum: proto.Float64(12.1),
1996 Schema: proto.Int32(2),
1997 ZeroThreshold: proto.Float64(2.938735877055719e-39),
1998 ZeroCount: proto.Uint64(0),
1999 PositiveSpan: []*dto.BucketSpan{
2000 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
2001 },
2002 PositiveDelta: []int64{1, 0, -1, 1},
2003 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
2004 },
2005 },
2006 {
2007 name: "buckets limited by widening the zero bucket, then reset",
2008 observations: []float64{0, 1, 1.1, 1.2, 1.4, 1.8, 2, 5, 5.1, 3, 4},
2009 factor: 1.2,
2010 maxBuckets: 4,
2011 maxZeroThreshold: 1.2,
2012 minResetDuration: 9 * time.Minute,
2013 want: &dto.Histogram{
2014 SampleCount: proto.Uint64(3),
2015 SampleSum: proto.Float64(12.1),
2016 Schema: proto.Int32(2),
2017 ZeroThreshold: proto.Float64(2.938735877055719e-39),
2018 ZeroCount: proto.Uint64(0),
2019 PositiveSpan: []*dto.BucketSpan{
2020 {Offset: proto.Int32(7), Length: proto.Uint32(4)},
2021 },
2022 PositiveDelta: []int64{1, 0, -1, 1},
2023 CreatedTimestamp: timestamppb.New(now.Add(9 * time.Minute)), // We expect reset to happen after 8 minutes.
2024 },
2025 },
2026 }
2027
2028 for _, s := range scenarios {
2029 t.Run(s.name, func(t *testing.T) {
2030 var (
2031 ts = now
2032 funcToCall func()
2033 whenToCall time.Duration
2034 )
2035
2036 his := NewHistogram(HistogramOpts{
2037 Name: "name",
2038 Help: "help",
2039 NativeHistogramBucketFactor: s.factor,
2040 NativeHistogramZeroThreshold: s.zeroThreshold,
2041 NativeHistogramMaxBucketNumber: s.maxBuckets,
2042 NativeHistogramMinResetDuration: s.minResetDuration,
2043 NativeHistogramMaxZeroThreshold: s.maxZeroThreshold,
2044 now: func() time.Time { return ts },
2045 afterFunc: func(d time.Duration, f func()) *time.Timer {
2046 funcToCall = f
2047 whenToCall = d
2048 return nil
2049 },
2050 })
2051
2052 ts = ts.Add(time.Minute)
2053 for _, o := range s.observations {
2054 his.Observe(o)
2055 ts = ts.Add(time.Minute)
2056 whenToCall -= time.Minute
2057 if funcToCall != nil && whenToCall <= 0 {
2058 funcToCall()
2059 funcToCall = nil
2060 }
2061 }
2062 _his := his.(*histogram)
2063 n := atomic.LoadUint64(&_his.countAndHotIdx)
2064 hotIdx := n >> 63
2065 cold := _his.counts[hotIdx]
2066 consthist, err := NewConstNativeHistogram(_his.Desc(),
2067 cold.count,
2068 math.Float64frombits(cold.sumBits),
2069 syncMapToMap(&cold.nativeHistogramBucketsPositive),
2070 syncMapToMap(&cold.nativeHistogramBucketsNegative),
2071 cold.nativeHistogramZeroBucket,
2072 cold.nativeHistogramSchema,
2073 math.Float64frombits(cold.nativeHistogramZeroThresholdBits),
2074 _his.lastResetTime,
2075 )
2076 if err != nil {
2077 t.Fatal("unexpected error writing metric", err)
2078 }
2079 m2 := &dto.Metric{}
2080
2081 if err := consthist.Write(m2); err != nil {
2082 t.Fatal("unexpected error writing metric", err)
2083 }
2084 got := m2.Histogram
2085 if !proto.Equal(s.want, got) {
2086 t.Errorf("want histogram %q, got %q", s.want, got)
2087 }
2088 })
2089 }
2090 }