-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathtest_sampling.py
178 lines (143 loc) · 7.04 KB
/
test_sampling.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any
import pytest
from inline_snapshot import snapshot
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
import logfire
from logfire.testing import SeededRandomIdGenerator, TestExporter
@dataclass
class SpanNode:
name: str | None = None
children: list[SpanNode] = field(default_factory=list) # type: ignore[reportUnknownVariableType]
# TODO(Marcelo): Remove pragma when this file is covered by tests.
def build_tree(exported_spans: list[dict[str, Any]]) -> list[SpanNode]: # pragma: no cover
traces: dict[int, list[dict[str, Any]]] = defaultdict(list)
for span in exported_spans:
trace_id: int = span['context']['trace_id']
traces[trace_id].append(span)
roots: list[SpanNode] = []
tree: dict[int, dict[int, SpanNode]] = {}
for trace_id, trace in traces.items():
spans: dict[int, SpanNode] = {}
tree[trace_id] = spans
for span in trace:
span_id: int = span['context']['span_id']
spans[span_id] = SpanNode(name=span['name'])
if span['parent'] is None:
roots.append(spans[span_id])
for trace_id, trace in traces.items():
spans = tree[trace_id]
for span in trace:
span_id: int = span['context']['span_id']
parent_id: int | None = span['parent']['span_id'] if span['parent'] is not None else None
if parent_id is not None:
spans[parent_id].children.append(spans[span_id])
return roots
@pytest.mark.skipif(
not hasattr(logfire, 'with_trace_sample_rate'), reason='with_trace_sample_rate is hidden from public API'
)
@pytest.mark.parametrize('sample_rate', [-1, 1.5])
def test_invalid_sample_rate(sample_rate: float) -> None: # pragma: no cover
with pytest.raises(ValueError, match='sample_rate must be between 0 and 1'):
logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(sample_rate)
def test_sample_rate_config(exporter: TestExporter, config_kwargs: dict[str, Any]) -> None:
config_kwargs.update(
sampling=logfire.SamplingOptions(head=0.3),
advanced=logfire.AdvancedOptions(id_generator=SeededRandomIdGenerator()),
)
logfire.configure(**config_kwargs)
for _ in range(1000):
with logfire.span('outer'):
with logfire.span('inner'):
pass
# 1000 iterations of 2 spans -> 2000 spans
# 30% sampling -> 600 spans (approximately)
assert len(exporter.exported_spans_as_dict()) == 588, len(exporter.exported_spans_as_dict())
@pytest.mark.skipif(
not hasattr(logfire, 'with_trace_sample_rate'), reason='with_trace_sample_rate is hidden from public API'
)
def test_sample_rate_runtime() -> None: # pragma: no cover
exporter = TestExporter()
logfire.configure(
send_to_logfire=False,
additional_span_processors=[SimpleSpanProcessor(exporter)],
advanced=logfire.AdvancedOptions(id_generator=SeededRandomIdGenerator()),
metrics=logfire.MetricsOptions(additional_readers=[InMemoryMetricReader()]),
)
for _ in range(100):
with logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(0.5).span('outer'):
with logfire.span('inner'):
pass
# 100 iterations of 2 spans -> 200 spans
# 50% sampling -> 100 spans (approximately)
assert len(exporter.exported_spans_as_dict()) == 102
@pytest.mark.skipif(
not hasattr(logfire, 'with_trace_sample_rate'), reason='with_trace_sample_rate is hidden from public API'
)
def test_outer_sampled_inner_not() -> None: # pragma: no cover
exporter = TestExporter()
logfire.configure(
send_to_logfire=False,
advanced=logfire.AdvancedOptions(id_generator=SeededRandomIdGenerator()),
additional_span_processors=[SimpleSpanProcessor(exporter)],
metrics=logfire.MetricsOptions(additional_readers=[InMemoryMetricReader()]),
)
for _ in range(10):
with logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(0.1).span('1'):
with logfire.span('2'):
with logfire.span('3'):
pass
assert build_tree(exporter.exported_spans_as_dict()) == snapshot(
[
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
]
)
@pytest.mark.skipif(
not hasattr(logfire, 'with_trace_sample_rate'), reason='with_trace_sample_rate is hidden from public API'
)
def test_outer_and_inner_sampled() -> None: # pragma: no cover
exporter = TestExporter()
logfire.configure(
send_to_logfire=False,
advanced=logfire.AdvancedOptions(id_generator=SeededRandomIdGenerator()),
additional_span_processors=[SimpleSpanProcessor(exporter)],
metrics=logfire.MetricsOptions(additional_readers=[InMemoryMetricReader()]),
)
for _ in range(10):
with logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(0.75).span('1'):
with logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(0.75).span('2'):
with logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(0.75).span('3'):
pass
assert build_tree(exporter.exported_spans_as_dict()) == snapshot(
[
SpanNode(name='1', children=[SpanNode(name='2', children=[])]),
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
SpanNode(name='1', children=[]),
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
SpanNode(name='1', children=[SpanNode(name='2', children=[SpanNode(name='3', children=[])])]),
]
)
@pytest.mark.skipif(
not hasattr(logfire, 'with_trace_sample_rate'), reason='with_trace_sample_rate is hidden from public API'
)
def test_sampling_rate_does_not_get_overwritten() -> None: # pragma: no cover
exporter = TestExporter()
logfire.configure(
send_to_logfire=False,
advanced=logfire.AdvancedOptions(id_generator=SeededRandomIdGenerator()),
additional_span_processors=[SimpleSpanProcessor(exporter)],
metrics=logfire.MetricsOptions(additional_readers=[InMemoryMetricReader()]),
)
for _ in range(10):
with logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(0).span('1'):
for _ in range(100):
with logfire.DEFAULT_LOGFIRE_INSTANCE.with_trace_sample_rate(1).span('2'):
pass
assert build_tree(exporter.exported_spans_as_dict()) == snapshot([])