Debian Codegraph @

samplers/probability/consistent/statistical_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 //go:build !race
5
6 package consistent
7
8 import (
9 "fmt"
10 "math"
11 "math/rand"
12 "strconv"
13 "testing"
14 "time"
15
16 "github.com/stretchr/testify/require"
17 sdktrace "go.opentelemetry.io/otel/sdk/trace"
18 "go.opentelemetry.io/otel/sdk/trace/tracetest"
19 )
20
21 const (
22 oneDegree testDegrees = 1
23 twoDegrees testDegrees = 2
24
25 trials = 20
26 populationSize int64 = 1e5
27
28 // These may be computed using Gonum, e.g.,
29 // import "gonum.org/v1/gonum/stat/distuv"
30 // with significance = 1 / float64(trials) = 0.05
31 // chiSquaredDF1 = distuv.ChiSquared{K: 1}.Quantile(significance)
32 // chiSquaredDF2 = distuv.ChiSquared{K: 2}.Quantile(significance)
33 //
34 // These have been specified using significance = 0.05:
35 chiSquaredDF1 = 0.003932140000019522
36 chiSquaredDF2 = 0.1025865887751011
37 )
38
39 var chiSquaredByDF = [3]float64{
40 0,
41 chiSquaredDF1,
42 chiSquaredDF2,
43 }
44
45 func TestSamplerStatistics(t *testing.T) {
46 seedBankRng := rand.New(rand.NewSource(77777677777))
47 seedBank := make([]int64, 7) // N.B. Max=6 below.
48 for i := range seedBank {
49 seedBank[i] = seedBankRng.Int63()
50 }
51 type (
52 testCase struct {
53 // prob is the sampling probability under test.
54 prob float64
55
56 // upperP reflects the larger of the one or two
57 // distinct adjusted counts represented in the test.
58 //
59 // For power-of-two tests, there is one distinct p-value,
60 // and each span counts as 2**upperP representative spans.
61 //
62 // For non-power-of-two tests, there are two distinct
63 // p-values expected, the test is specified using the
64 // larger of these values corresponding with the
65 // smaller sampling probability. The sampling
66 // probability under test rounded down to the nearest
67 // power of two is expected to equal 2**(-upperP).
68 upperP pValue
69
70 // degrees is 1 for power-of-two tests and 2 for
71 // non-power-of-two tests.
72 degrees testDegrees
73
74 // seedIndex is the index into seedBank of the test seed.
75 // If this is -1 the code below will search for the smallest
76 // seed index that passes the test.
77 seedIndex int
78 }
79 testResult struct {
80 test testCase
81 expected []float64
82 }
83 )
84 var (
85 testSummary []testResult
86
87 allTests = []testCase{
88 // Non-powers of two
89 {0.90000, 1, twoDegrees, 3},
90 {0.60000, 1, twoDegrees, 2},
91 {0.33000, 2, twoDegrees, 2},
92 {0.13000, 3, twoDegrees, 1},
93 {0.10000, 4, twoDegrees, 0},
94 {0.05000, 5, twoDegrees, 0},
95 {0.01700, 6, twoDegrees, 2},
96 {0.01000, 7, twoDegrees, 2},
97 {0.00500, 8, twoDegrees, 2},
98 {0.00290, 9, twoDegrees, 4},
99 {0.00100, 10, twoDegrees, 6},
100 {0.00050, 11, twoDegrees, 0},
101
102 // Powers of two
103 {0x1p-1, 1, oneDegree, 0},
104 {0x1p-4, 4, oneDegree, 0},
105 {0x1p-7, 7, oneDegree, 1},
106 }
107 )
108
109 // Limit the test runtime by choosing 3 of the above
110 // non-deterministically
111 rand.New(rand.NewSource(time.Now().UnixNano())).Shuffle(len(allTests), func(i, j int) {
112 allTests[i], allTests[j] = allTests[j], allTests[i]
113 })
114 allTests = allTests[0:3]
115
116 for _, test := range allTests {
117 t.Run(fmt.Sprint(test.prob), func(t *testing.T) {
118 var expected []float64
119 trySeedIndex := 0
120
121 for {
122 var seed int64
123 seedIndex := test.seedIndex
124 if seedIndex >= 0 {
125 seed = seedBank[seedIndex]
126 } else {
127 seedIndex = trySeedIndex
128 seed = seedBank[trySeedIndex]
129 trySeedIndex++
130 }
131
132 countFailures := func(src rand.Source) int {
133 failed := 0
134
135 for range trials {
136 var x float64
137 x, expected = sampleTrials(t, test.prob, test.degrees, test.upperP, src)
138
139 if x < chiSquaredByDF[test.degrees] {
140 failed++
141 }
142 }
143 return failed
144 }
145
146 failed := countFailures(rand.NewSource(seed))
147
148 if failed == 1 {
149 if test.seedIndex < 0 {
150 t.Logf("update the test for %g to use seed index %d", test.prob, seedIndex)
151 t.Fail()
152 return
153 }
154 // Note: this can be uncommented to verify that the preceding seed failed the test,
155 // however this just doubles runtime and adds little evidence. For example:
156 // if seedIndex != 0 && countFailures(rand.NewSource(seedBank[seedIndex-1])) == 1 {
157 // t.Logf("update the test for %g to use seed index < %d", test.prob, seedIndex)
158 // t.Fail()
159 // }
160 break
161 }
162 if test.seedIndex < 0 {
163 t.Logf("%d probabilistic failures, trying a new seed for %g was 0x%x", failed, test.prob, seed)
164 continue
165 }
166 t.Errorf("wrong number of probabilistic failures for %g, should be 1 was %d for seed 0x%x", test.prob, failed, seed)
167 }
168 testSummary = append(testSummary, testResult{
169 test: test,
170 expected: expected,
171 })
172 })
173 }
174
175 // Note: This produces a table that should match what is in
176 // the specification if it's the same test.
177 for idx, res := range testSummary {
178 var probability, pvalues, expectLower, expectUpper, expectUnsampled string
179 if res.test.degrees == twoDegrees {
180 probability = fmt.Sprintf("%.6f", res.test.prob)
181 pvalues = fmt.Sprint(res.test.upperP-1, ", ", res.test.upperP)
182 expectUnsampled = fmt.Sprintf("%.10g", res.expected[0])
183 expectLower = fmt.Sprintf("%.10g", res.expected[1])
184 expectUpper = fmt.Sprintf("%.10g", res.expected[2])
185 } else {
186 probability = fmt.Sprintf("%x (%.6f)", res.test.prob, res.test.prob)
187 pvalues = fmt.Sprint(res.test.upperP)
188 expectUnsampled = fmt.Sprintf("%.10g", res.expected[0])
189 expectLower = fmt.Sprintf("%.10g", res.expected[1])
190 expectUpper = "n/a"
191 }
192 t.Logf("| %d | %s | %s | %s | %s | %s |\n", idx+1, probability, pvalues, expectLower, expectUpper, expectUnsampled)
193 }
194 }
195
196 func sampleTrials(t *testing.T, prob float64, degrees testDegrees, upperP pValue, source rand.Source) (float64, []float64) {
197 ctx := t.Context()
198
199 sampler := ProbabilityBased(
200 prob,
201 WithRandomSource(source),
202 )
203
204 recorder := &tracetest.InMemoryExporter{}
205 provider := sdktrace.NewTracerProvider(
206 sdktrace.WithSyncer(recorder),
207 sdktrace.WithSampler(sampler),
208 )
209
210 tracer := provider.Tracer("test")
211
212 for range populationSize {
213 _, span := tracer.Start(ctx, "span")
214 span.End()
215 }
216
217 var minP, maxP pValue
218
219 counts := map[pValue]int64{}
220 spans := recorder.GetSpans()
221
222 for idx := range spans {
223 r := &spans[idx]
224 ts := r.SpanContext.TraceState()
225 p, _ := parsePR(ts.Get("ot"))
226
227 pi, err := strconv.ParseUint(p, 10, 64)
228 require.NoError(t, err)
229
230 if idx == 0 {
231 maxP = pValue(pi)
232 minP = maxP
233 } else {
234 if pValue(pi) < minP {
235 minP = pValue(pi)
236 }
237 if pValue(pi) > maxP {
238 maxP = pValue(pi)
239 }
240 }
241 counts[pValue(pi)]++
242 }
243
244 require.Less(t, maxP, minP+pValue(degrees), "%v %v %v", minP, maxP, degrees)
245 require.Less(t, maxP, pValue(63))
246 require.LessOrEqual(t, len(counts), 2)
247
248 var ceilingProb, floorProb, floorChoice float64
249
250 // Note: we have to test len(counts) == 0 because this outcome
251 // is actually possible, just very unlikely. If this happens
252 // during development, a new initial seed must be used for
253 // this test.
254 //
255 // The test specification ensures the test ensures there are
256 // at least 20 expected items per category in these tests.
257 require.NotEmpty(t, counts)
258
259 if degrees == 2 {
260 // Note: because the test is probabilistic, we can't be
261 // sure that both the min and max P values happen. We
262 // can only assert that one of these is true.
263 require.GreaterOrEqual(t, maxP, upperP-1)
264 require.GreaterOrEqual(t, minP, upperP-1)
265 require.LessOrEqual(t, maxP, upperP)
266 require.LessOrEqual(t, minP, upperP)
267 require.LessOrEqual(t, maxP-minP, 1)
268
269 ceilingProb = 1 / float64(int64(1)<<(upperP-1))
270 floorProb = 1 / float64(int64(1)<<upperP)
271 floorChoice = (ceilingProb - prob) / (ceilingProb - floorProb)
272 } else {
273 require.Equal(t, minP, maxP)
274 require.Equal(t, upperP, maxP)
275 ceilingProb = 0
276 floorProb = prob
277 floorChoice = 1
278 }
279
280 expectLowerCount := floorChoice * floorProb * float64(populationSize)
281 expectUpperCount := (1 - floorChoice) * ceilingProb * float64(populationSize)
282 expectUnsampled := (1 - prob) * float64(populationSize)
283
284 upperCount := int64(0)
285 lowerCount := counts[maxP]
286 if degrees == 2 {
287 upperCount = counts[minP]
288 }
289 unsampled := populationSize - upperCount - lowerCount
290
291 expected := []float64{
292 expectUnsampled,
293 expectLowerCount,
294 expectUpperCount,
295 }
296
297 chi2 := 0.0
298 chi2 += math.Pow(float64(unsampled)-expectUnsampled, 2) / expectUnsampled
299 chi2 += math.Pow(float64(lowerCount)-expectLowerCount, 2) / expectLowerCount
300 if degrees == 2 {
301 chi2 += math.Pow(float64(upperCount)-expectUpperCount, 2) / expectUpperCount
302 }
303
304 return chi2, expected
305 }