Skip to content

Commit 6e56143

Browse files
feat(tracing): Propagate sample_rand to transaction's baggage
`continue_trace` now propagates incoming `sample_rand` values to the transaction's baggage. Also, in the case where `sample_rand` is missing from the incoming trace and needs to be backfilled, this change introduces a mechanism for the backfilled value from the scope's propagation context to be propagated to the transaction's baggage. The transaction still does not use the `sample_rand` for making sampling decisions; this PR only enables propagation. A future PR will add support for reading the incoming/backfilled `sample_rand` and for using this value to make sampling decisions. Ref #3998
1 parent 9863506 commit 6e56143

File tree

4 files changed

+114
-3
lines changed

4 files changed

+114
-3
lines changed

sentry_sdk/scope.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
logger,
4444
)
4545

46+
import typing
4647
from typing import TYPE_CHECKING
4748

4849
if TYPE_CHECKING:
@@ -1146,8 +1147,20 @@ def continue_trace(
11461147
"""
11471148
self.generate_propagation_context(environ_or_headers)
11481149

1150+
# When we generate the propagation context, the sample_rand value is set
1151+
# if missing or invalid (we use the original value if it's valid).
1152+
# We want the transaction to use the same sample_rand value. Due to duplicated
1153+
# propagation logic in the transaction, we pass it in to avoid recomputing it
1154+
# in the transaction.
1155+
# TYPE SAFETY: self.generate_propagation_context() ensures that self._propagation_context
1156+
# is not None.
1157+
sample_rand = typing.cast(
1158+
PropagationContext, self._propagation_context
1159+
)._sample_rand()
1160+
11491161
transaction = Transaction.continue_from_headers(
11501162
normalize_incoming_data(environ_or_headers),
1163+
_sample_rand=sample_rand,
11511164
op=op,
11521165
origin=origin,
11531166
name=name,

sentry_sdk/tracing.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,8 @@ def continue_from_environ(
477477
def continue_from_headers(
478478
cls,
479479
headers, # type: Mapping[str, str]
480+
*,
481+
_sample_rand=None, # type: Optional[str]
480482
**kwargs, # type: Any
481483
):
482484
# type: (...) -> Transaction
@@ -485,6 +487,8 @@ def continue_from_headers(
485487
the ``sentry-trace`` and ``baggage`` headers).
486488
487489
:param headers: The dictionary with the HTTP headers to pull information from.
490+
:param _sample_rand: If provided, we override the sample_rand value from the
491+
incoming headers with this value. (internal use only)
488492
"""
489493
# TODO move this to the Transaction class
490494
if cls is Span:
@@ -495,7 +499,9 @@ def continue_from_headers(
495499

496500
# TODO-neel move away from this kwargs stuff, it's confusing and opaque
497501
# make more explicit
498-
baggage = Baggage.from_incoming_header(headers.get(BAGGAGE_HEADER_NAME))
502+
baggage = Baggage.from_incoming_header(
503+
headers.get(BAGGAGE_HEADER_NAME), _sample_rand=_sample_rand
504+
)
499505
kwargs.update({BAGGAGE_HEADER_NAME: baggage})
500506

501507
sentrytrace_kwargs = extract_sentrytrace_data(

sentry_sdk/tracing_utils.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,14 @@ def _fill_sample_rand(self):
524524

525525
self.dynamic_sampling_context["sample_rand"] = str(sample_rand)
526526

527+
def _sample_rand(self):
528+
# type: () -> Optional[str]
529+
"""Convenience method to get the sample_rand value from the dynamic_sampling_context."""
530+
if self.dynamic_sampling_context is None:
531+
return None
532+
533+
return self.dynamic_sampling_context.get("sample_rand")
534+
527535

528536
class Baggage:
529537
"""
@@ -546,8 +554,13 @@ def __init__(
546554
self.mutable = mutable
547555

548556
@classmethod
549-
def from_incoming_header(cls, header):
550-
# type: (Optional[str]) -> Baggage
557+
def from_incoming_header(
558+
cls,
559+
header, # type: Optional[str]
560+
*,
561+
_sample_rand=None, # type: Optional[str]
562+
):
563+
# type: (...) -> Baggage
551564
"""
552565
freeze if incoming header already has sentry baggage
553566
"""
@@ -570,6 +583,10 @@ def from_incoming_header(cls, header):
570583
else:
571584
third_party_items += ("," if third_party_items else "") + item
572585

586+
if _sample_rand is not None:
587+
sentry_items["sample_rand"] = str(_sample_rand)
588+
mutable = False
589+
573590
return Baggage(sentry_items, third_party_items, mutable)
574591

575592
@classmethod
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""
2+
These tests exist to verify that Scope.continue_trace() correctly propagates the
3+
sample_rand value onto the transaction's baggage.
4+
5+
We check both the case where there is an incoming sample_rand, as well as the case
6+
where we need to compute it because it is missing.
7+
"""
8+
9+
import pytest
10+
11+
import sentry_sdk
12+
13+
14+
def test_continue_trace_with_sample_rand():
15+
"""
16+
Test that an incoming sample_rand is propagated onto the transaction's baggage.
17+
"""
18+
headers = {
19+
"sentry-trace": "00000000000000000000000000000000-0000000000000000-0",
20+
"baggage": "sentry-sample_rand=0.1,sentry-sample_rate=0.5",
21+
}
22+
23+
transaction = sentry_sdk.continue_trace(headers)
24+
assert transaction.get_baggage().sentry_items["sample_rand"] == "0.1"
25+
26+
27+
@pytest.mark.parametrize(
28+
("parent_sampled", "sample_rate", "expected_sample_rand"),
29+
(
30+
# Note that parent_sampled and sample_rate do not scale the
31+
# sample_rand value, only determine the range of the value.
32+
# Expected values are determined by parent_sampled, sample_rate,
33+
# and the trace_id.
34+
(None, None, "0.919221"),
35+
(None, "0.5", "0.919221"),
36+
(False, None, "0.919221"),
37+
(True, None, "0.919221"),
38+
(False, "0.0", "0.919221"),
39+
(False, "0.01", "0.929221"),
40+
(True, "0.01", "0.006073"),
41+
(False, "0.1", "0.762590"),
42+
(True, "0.1", "0.082823"),
43+
(False, "0.5", "0.959610"),
44+
(True, "0.5", "0.459610"),
45+
(True, "1.0", "0.919221"),
46+
),
47+
)
48+
def test_continue_trace_missing_sample_rand(
49+
parent_sampled, sample_rate, expected_sample_rand
50+
):
51+
"""
52+
Test that a missing sample_rand is filled in onto the transaction's baggage. The sample_rand
53+
is pseudorandomly generated based on the trace_id, so we assert the exact values that should
54+
be generated.
55+
"""
56+
headers = {
57+
"sentry-trace": f"00000000000000000000000000000000-0000000000000000{sampled_flag(parent_sampled)}",
58+
"baggage": f"sentry-sample_rate={sample_rate}",
59+
}
60+
61+
transaction = sentry_sdk.continue_trace(headers)
62+
assert transaction.get_baggage().sentry_items["sample_rand"] == expected_sample_rand
63+
64+
65+
def sampled_flag(sampled):
66+
"""
67+
convenience function to get the sampled flag on the sentry-trace header, given a parent
68+
sampling decision.
69+
"""
70+
if sampled is None:
71+
return ""
72+
elif sampled is True:
73+
return "-1"
74+
else:
75+
return "-0"

0 commit comments

Comments
 (0)