Skip to content

Commit 1c72747

Browse files
authored
Only add to trace state if key does not exist (#3645)
`trace_state.add` will never overwrite existing entries -- this is good. However, everytime it bails, it logs a warning, which then shows up in breadcrumbs in tests. With this commit we explicitly check before adding.
1 parent a67125a commit 1c72747

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

sentry_sdk/integrations/opentelemetry/sampler.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,13 @@ def get_parent_sampled(parent_context, trace_id):
4848

4949
def dropped_result(span_context, attributes, sample_rate=None):
5050
# type: (SpanContext, Attributes, Optional[float]) -> SamplingResult
51-
# note that trace_state.add will NOT overwrite existing entries
52-
# so these will only be added the first time in a root span sampling decision
53-
trace_state = span_context.trace_state.add(TRACESTATE_SAMPLED_KEY, "false")
54-
if sample_rate:
51+
# these will only be added the first time in a root span sampling decision
52+
trace_state = span_context.trace_state
53+
54+
if TRACESTATE_SAMPLED_KEY not in trace_state:
55+
trace_state = trace_state.add(TRACESTATE_SAMPLED_KEY, "false")
56+
57+
if sample_rate and TRACESTATE_SAMPLE_RATE_KEY not in trace_state:
5558
trace_state = trace_state.add(TRACESTATE_SAMPLE_RATE_KEY, str(sample_rate))
5659

5760
return SamplingResult(
@@ -63,11 +66,13 @@ def dropped_result(span_context, attributes, sample_rate=None):
6366

6467
def sampled_result(span_context, attributes, sample_rate):
6568
# type: (SpanContext, Attributes, float) -> SamplingResult
66-
# note that trace_state.add will NOT overwrite existing entries
67-
# so these will only be added the first time in a root span sampling decision
68-
trace_state = span_context.trace_state.add(TRACESTATE_SAMPLED_KEY, "true").add(
69-
TRACESTATE_SAMPLE_RATE_KEY, str(sample_rate)
70-
)
69+
# these will only be added the first time in a root span sampling decision
70+
trace_state = span_context.trace_state
71+
72+
if TRACESTATE_SAMPLED_KEY not in trace_state:
73+
trace_state = trace_state.add(TRACESTATE_SAMPLED_KEY, "true")
74+
if TRACESTATE_SAMPLE_RATE_KEY not in trace_state:
75+
trace_state = trace_state.add(TRACESTATE_SAMPLE_RATE_KEY, str(sample_rate))
7176

7277
return SamplingResult(
7378
Decision.RECORD_AND_SAMPLE,

0 commit comments

Comments
 (0)