Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
c354d31
test: normalize ContinueTrace tests
Flash0ver Jul 21, 2025
37908a3
test: use Assertion over type-cast
Flash0ver Jul 21, 2025
23a45c2
fix: DSC contains actual SampleRate
Flash0ver Jul 21, 2025
5cace1f
test: fix catch and handle failed Assertions
Flash0ver Jul 21, 2025
4401a98
style: reformat HubTests
Flash0ver Jul 21, 2025
3197ab6
test: fix HubTests
Flash0ver Jul 21, 2025
bc91dd3
docs: update CHANGELOG.md
Flash0ver Jul 21, 2025
755bbef
test: skip failing test on Android & iOS (device tests)
Flash0ver Jul 23, 2025
6259233
fix: DSC sample_rate when sampling forced
Flash0ver Jul 24, 2025
fd39406
test: fix PushAndLockScope when GlobalMode
Flash0ver Jul 24, 2025
3be7eee
Merge branch 'main' into fix/update-dsc-sample-rate
Flash0ver Jul 24, 2025
cd5355b
fix: forced sampling is only considered when TracesSampler has not de…
Flash0ver Jul 24, 2025
8dbe5e3
fix: no longer overwrite DSC sample_rate when upstream sampling decis…
Flash0ver Jul 25, 2025
2dc8666
Merge branch 'main' into fix/update-dsc-sample-rate
Flash0ver Jul 25, 2025
fa43554
fix: overwrite DSC sample_rate only when TracesSampler or TracesSampl…
Flash0ver Jul 28, 2025
2382943
ref: remove Debug.Assert
Flash0ver Jul 28, 2025
8c5588f
docs: add comment to test
Flash0ver Jul 28, 2025
50edc11
Merge branch 'main' into fix/update-dsc-sample-rate
Flash0ver Jul 30, 2025
758028c
docs: update CHANGELOG
Flash0ver Jul 30, 2025
a13b7e0
fix: TransactionTracer was assumed to be considered even when TracesS…
Flash0ver Jul 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Fixes

- Update `sample_rate` of _Dynamic Sampling Context (DSC)_ when making sampling decisions ([#4374](https://github.com/getsentry/sentry-dotnet/pull/4374))

## 5.13.0

### Features
Expand Down Expand Up @@ -1252,7 +1258,7 @@ There are some functional differences when publishing Native AOT:

### Fixes

- Resolved an isse where the SDK would throw an exception while attempting to set the DynamicSamplingContext but the context exists already. ([#2592](https://github.com/getsentry/sentry-dotnet/pull/2592))
- Resolved an issue where the SDK would throw an exception while attempting to set the DynamicSamplingContext but the context exists already. ([#2592](https://github.com/getsentry/sentry-dotnet/pull/2592))

### Dependencies

Expand Down
18 changes: 18 additions & 0 deletions src/Sentry/DynamicSamplingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,24 @@ private DynamicSamplingContext(SentryId traceId,

public BaggageHeader ToBaggageHeader() => BaggageHeader.Create(Items, useSentryPrefix: true);

public DynamicSamplingContext WithSampleRate(double sampleRate)
{
if (Items.TryGetValue("sample_rate", out var dscSampleRate))
{
if (double.TryParse(dscSampleRate, NumberStyles.Float, CultureInfo.InvariantCulture, out var rate))
{
if (Math.Abs(rate - sampleRate) > double.Epsilon)
{
var items = Items.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
items["sample_rate"] = sampleRate.ToString(CultureInfo.InvariantCulture);
return new DynamicSamplingContext(items);
}
}
}

return this;
}

public DynamicSamplingContext WithReplayId(IReplaySession? replaySession)
{
if (replaySession?.ActiveReplayId is not { } replayId || replayId == SentryId.Empty)
Expand Down
22 changes: 17 additions & 5 deletions src/Sentry/Internal/Hub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,8 @@ internal ITransactionTracer StartTransaction(

bool? isSampled = null;
double? sampleRate = null;
var sampleRand = dynamicSamplingContext?.Items.TryGetValue("sample_rand", out var dscsampleRand) ?? false
? double.Parse(dscsampleRand, NumberStyles.Float, CultureInfo.InvariantCulture)
var sampleRand = dynamicSamplingContext?.Items.TryGetValue("sample_rand", out var dscSampleRand) ?? false
? double.Parse(dscSampleRand, NumberStyles.Float, CultureInfo.InvariantCulture)
: SampleRandHelper.GenerateSampleRand(context.TraceId.ToString());

// TracesSampler runs regardless of whether a decision has already been made, as it can be used to override it.
Expand All @@ -188,14 +188,26 @@ internal ITransactionTracer StartTransaction(
{
// The TracesSampler trumps all other sampling decisions (even the trace header)
sampleRate = samplerSampleRate;
isSampled = SampleRandHelper.IsSampled(sampleRand, sampleRate.Value);
isSampled = SampleRandHelper.IsSampled(sampleRand, samplerSampleRate);

// Ensure the actual sampleRate is set on the provided DSC (if any) when the TracesSampler reached a sampling decision
dynamicSamplingContext = dynamicSamplingContext?.WithSampleRate(samplerSampleRate);
}
}

// If the sampling decision isn't made by a trace sampler we check the trace header first (from the context) or
// finally fallback to Random sampling if the decision has been made by no other means
sampleRate ??= _options.TracesSampleRate ?? 0.0;
isSampled ??= context.IsSampled ?? SampleRandHelper.IsSampled(sampleRand, sampleRate.Value);
if (isSampled == null)
{
sampleRate = _options.TracesSampleRate ?? 0.0;
isSampled = context.IsSampled ?? SampleRandHelper.IsSampled(sampleRand, sampleRate.Value);

if (context.IsSampled is null && _options.TracesSampleRate is not null)
Copy link
Collaborator

@jamescrosswell jamescrosswell Jul 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TLDR; I think we can remove the if block here.

Long version

Apologies, I think I got us confused on Slack:

  • context is of type ITransactionContext... I think when an upstream span is sampled, context.IsParentSampled will be true (not context.IsSampled).
  • Whether or not the parent span was sampled is probably not relevant. It's possible that our process has a different sample-rate configured to the upstream node... as long as we use the same sample rand, we maximise (not guarantee) the chance of having a complete trace. If we have a sample-rand of 0.5 and the upstream node has a sample rate of 0.75 but we have a sample rate of 0.25 (and assuming I've understood the requirements) I think we need to sample out in this case and put our own sample-rate (0.25) on the header... so we just overwrite in this scenario.
    • I'm not 100% sure whether that's how sampling is implemented at Sentry though... maybe we only support different sample rates on different nodes via the TracesSampler function. @cleptric do you know?
  • If context.IsSampled == true I think that means the SDK user has forced sampling to true (passing it explicitly via the call to StartTransaction).
    • Note that we do sometimes set this to false ourselves internally (e.g. here and here)
    • This is what I think I got us confused about. I suggested this field might be true when the upstream span was sampled in... with fresh eyes, I think I was mistaken and that's what the IsParentSampled field is for.

On the bright side, if all of the above is correct, it means it should be trivial to implement the logic to force sampling (per the other SDKs)... basically we can force a sample-rate of 0.0 or 1.0 if context.IsSampled is set.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

followed-up via #4386

{
// Ensure the actual sampleRate is set on the provided DSC (if any) when not IsSampled upstream but the TracesSampleRate reached a sampling decision
dynamicSamplingContext = dynamicSamplingContext?.WithSampleRate(_options.TracesSampleRate.Value);
}
}

// Make sure there is a replayId (if available) on the provided DSC (if any).
dynamicSamplingContext = dynamicSamplingContext?.WithReplayId(_replaySession);
Expand Down
1 change: 0 additions & 1 deletion src/Sentry/TransactionTracer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,6 @@ internal TransactionTracer(IHub hub, string name, string operation, TransactionN
/// </summary>
internal TransactionTracer(IHub hub, ITransactionContext context, TimeSpan? idleTimeout = null)
{
Debug.Assert(context.IsSampled ?? true, "context.IsSampled should always be true when creating a TransactionTracer");
_hub = hub;
_options = _hub.GetSentryOptions();
Name = context.Name;
Expand Down
15 changes: 10 additions & 5 deletions test/Sentry.AspNetCore.Tests/SentryTracingMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ public async Task Baggage_header_propagates_to_outbound_requests(bool shouldProp
"sentry-trace_id=75302ac48a024bde9a3b3734a82e36c8, " +
"sentry-public_key=d4d82fc1c2c4032a83f3a29aa3a3aff, " +
"sentry-sample_rand=0.1234, " +
"sentry-sample_rate=0.5";
"sentry-sample_rate=1";
}
else
{
Expand Down Expand Up @@ -395,13 +395,18 @@ public async Task Baggage_header_propagates_to_outbound_requests(bool shouldProp
[Fact]
public async Task Baggage_header_sets_dynamic_sampling_context()
{
// incoming baggage header
const string baggage =
const string incomingBaggageHeader =
"sentry-trace_id=75302ac48a024bde9a3b3734a82e36c8, " +
"sentry-public_key=d4d82fc1c2c4032a83f3a29aa3a3aff, " +
"sentry-sample_rand=0.1234, " +
"sentry-sample_rate=0.5";

const string expectedBaggageHeader =
"sentry-trace_id=75302ac48a024bde9a3b3734a82e36c8, " +
"sentry-public_key=d4d82fc1c2c4032a83f3a29aa3a3aff, " +
"sentry-sample_rand=0.1234, " +
"sentry-sample_rate=1";

// Arrange
TransactionTracer transaction = null;

Expand Down Expand Up @@ -440,7 +445,7 @@ public async Task Baggage_header_sets_dynamic_sampling_context()
{
Headers =
{
{"baggage", baggage}
{"baggage", incomingBaggageHeader}
}
};

Expand All @@ -449,7 +454,7 @@ public async Task Baggage_header_sets_dynamic_sampling_context()
// Assert
var dsc = transaction?.DynamicSamplingContext;
Assert.NotNull(dsc);
Assert.Equal(baggage, dsc.ToBaggageHeader().ToString());
Assert.Equal(expectedBaggageHeader, dsc.ToBaggageHeader().ToString());
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,8 @@ public void OnStart_Transaction_With_DynamicSamplingContext()
{
actual.Items["trace_id"].Should().Be(expected["trace_id"]);
actual.Items["public_key"].Should().Be(expected["public_key"]);
actual.Items["sample_rate"].Should().Be(expected["sample_rate"]);
actual.Items["sample_rate"].Should().NotBe(expected["sample_rate"]);
actual.Items["sample_rate"].Should().Be(_fixture.Options.TracesSampleRate.ToString());
}
}

Expand Down
Loading
Loading