-
Notifications
You must be signed in to change notification settings - Fork 880
[bug] Race condition in Tracer.StartSpan() can throw System.InvalidOperation #6257
Copy link
Copy link
Closed
Labels
bugSomething isn't workingSomething isn't workinghelp wantedGood for taking. Extra help will be provided by maintainersGood for taking. Extra help will be provided by maintainerspkg:OpenTelemetry.ApiIssues related to OpenTelemetry.Api NuGet packageIssues related to OpenTelemetry.Api NuGet package
Description
Package
OpenTelemetry.Api
Package Version
| Package Name | Version |
|---|---|
| OpenTelemetry.Api | 1.11.2 |
| OpenTelemetry | 1.11.2 |
Runtime Version
net9.0
Description
If calling Tracer.StartSpan() when Activity.Current has an item it is possible to hit the exception:
System.InvalidOperationException: 'Trying to set an Activity that is not running'
Currently, the Tracer.StartSpan() method does the following:
- Captures the current
Activitythat is inActivity.CurrentaspreviousActivty. - Creates the new
TelemetrySpanto be returned. - Puts
previousActivityback into place asActivity.Current.
When trying to put previousActivity back into Activity.Current, if previousActivity has stopped whilst we were creating the new TelemetrySpan it will throw an error.
A simple way to avoid this seems to be by changing the following:
if (startSpanBehavior.HasFlag(StartSpanBehaviors.DeactivateNewSpan)
&& Activity.Current != previousActivity)
{
Activity.Current = previousActivity;
}
to
if (startSpanBehavior.HasFlag(StartSpanBehaviors.DeactivateNewSpan)
&& Activity.Current != previousActivity)
{
Activity.Current = previousActivity?.IsStopped == true ? null : previousActivity;
}
Steps to Reproduce
I've had difficulty recreating this race condition in a simple sample project.
Expected Result
No exceptions are thrown.
Actual Result
The following exception can sometimes be thrown.
System.InvalidOperationException: 'Trying to set an Activity that is not running'
Additional Context
No response
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't workinghelp wantedGood for taking. Extra help will be provided by maintainersGood for taking. Extra help will be provided by maintainerspkg:OpenTelemetry.ApiIssues related to OpenTelemetry.Api NuGet packageIssues related to OpenTelemetry.Api NuGet package