File: fixed_size_reservoir_test.go

package info (click to toggle)
golang-opentelemetry-otel 1.31.0-5
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid
  • size: 11,844 kB
  • sloc: makefile: 237; sh: 51
file content (55 lines) | stat: -rw-r--r-- 1,307 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package exemplar

import (
	"context"
	"math"
	"math/rand"
	"slices"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestNewFixedSizeReservoir(t *testing.T) {
	t.Run("Int64", ReservoirTest[int64](func(n int) (Reservoir, int) {
		return NewFixedSizeReservoir(n), n
	}))

	t.Run("Float64", ReservoirTest[float64](func(n int) (Reservoir, int) {
		return NewFixedSizeReservoir(n), n
	}))
}

func TestNewFixedSizeReservoirSamplingCorrectness(t *testing.T) {
	intensity := 0.1
	sampleSize := 1000

	rng := rand.New(rand.NewSource(time.Now().UnixNano()))

	data := make([]float64, sampleSize*1000)
	for i := range data {
		// Generate exponentially distributed data.
		data[i] = (-1.0 / intensity) * math.Log(rng.Float64())
	}
	// Sort to test position bias.
	slices.Sort(data)

	r := NewFixedSizeReservoir(sampleSize)
	for _, value := range data {
		r.Offer(context.Background(), staticTime, NewValue(value), nil)
	}

	var sum float64
	for _, m := range r.store {
		sum += m.Value.Float64()
	}
	mean := sum / float64(sampleSize)

	// Check the intensity/rate of the sampled distribution is preserved
	// ensuring no bias in our random sampling algorithm.
	assert.InDelta(t, 1/mean, intensity, 0.02) // Within 5σ.
}