Skip to content

Commit d887ed3

Browse files
committed
Account for nil sample_rate when sampling
1 parent 3fd1304 commit d887ed3

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

lib/sentry/opentelemetry/sampler.ex

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -81,23 +81,25 @@ if Code.ensure_loaded?(:otel_sampler) do
8181
end
8282

8383
defp make_sampling_decision(sample_rate) do
84-
{sampled, random_value} =
85-
cond do
86-
sample_rate == 0.0 ->
87-
{false, 1.0}
88-
89-
sample_rate == 1.0 ->
90-
{true, 0.0}
84+
cond do
85+
is_nil(sample_rate) ->
86+
{:drop, [], []}
9187

92-
true ->
93-
random_value = :rand.uniform()
94-
{random_value < sample_rate, random_value}
95-
end
88+
sample_rate == 0.0 ->
89+
tracestate = build_tracestate(sample_rate, 1.0, false)
90+
{:drop, [], tracestate}
9691

97-
tracestate = build_tracestate(sample_rate, random_value, sampled)
98-
decision = if sampled, do: :record_and_sample, else: :drop
92+
sample_rate == 1.0 ->
93+
tracestate = build_tracestate(sample_rate, 0.0, true)
94+
{:record_and_sample, [], tracestate}
9995

100-
{decision, [], tracestate}
96+
true ->
97+
random_value = :rand.uniform()
98+
sampled = random_value < sample_rate
99+
tracestate = build_tracestate(sample_rate, random_value, sampled)
100+
decision = if sampled, do: :record_and_sample, else: :drop
101+
{decision, [], tracestate}
102+
end
101103
end
102104

103105
defp build_tracestate(sample_rate, random_value, sampled) do

test/sentry/opentelemetry/sampler_test.exs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,20 @@ defmodule Sentry.Opentelemetry.SamplerTest do
123123
discarded_count = Map.get(state, {:sample_rate, "transaction"}, 0)
124124
assert discarded_count > 0, "Expected some spans to be dropped and recorded"
125125
end
126+
127+
test "always drops when sample rate is nil (tracing disabled) and records discarded event" do
128+
:sys.replace_state(ClientReport.Sender, fn _ -> %{} end)
129+
130+
Sentry.Config.put_config(:traces_sample_rate, nil)
131+
132+
test_ctx = create_test_span_context()
133+
134+
assert {:drop, [], []} =
135+
Sampler.should_sample(test_ctx, 123, nil, "test span", nil, nil, drop: [])
136+
137+
state = :sys.get_state(ClientReport.Sender)
138+
assert state == %{{:sample_rate, "transaction"} => 1}
139+
end
126140
end
127141

128142
describe "trace-level sampling consistency" do

0 commit comments

Comments
 (0)