Skip to content

Ending an activity will not restore the previously active one for explicit parents  #46721

Closed
@cijothomas

Description

@cijothomas

Copied from open-telemetry/opentelemetry-dotnet#1677

Symptom

Activity.Current becomes null whenever any Activity with explicit parent is ended. I would instead have expected that the previously active activity would be restored, independent of whether it was the parent or not.

Following shows how to repro this with OpenTelemetry, but this can be reproed by setting up any Activitylistener.

Reproduce

using System;
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;

public class Program
{
    private static readonly ActivitySource MyActivitySource = new ActivitySource(
        "MyCompany.MyProduct.MyLibrary");

    public static void Main()
    {
        using var tracerProvider = Sdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource("MyCompany.MyProduct.MyLibrary")
            .Build();

        using (var activity = MyActivitySource.StartActivity("SayHello"))
        {
            Console.WriteLine("Current before: {0}", Activity.Current?.DisplayName);
            using (var child = MyActivitySource.StartActivity("SayWorld", ActivityKind.Internal, activity.Context))
            {
                Console.WriteLine("Current child: {0}", Activity.Current?.DisplayName);
            }

            Console.WriteLine("Current after: {0}", Activity.Current?.DisplayName ?? "(null)");
        }
    }
}

Actual Output:

Current before: SayHello
Current child: SayWorld
Current after: (null)

Expected output would be that the last line is Current after: SayHello.

Additional context

Responsible line in Activity.Stop:

https://github.com/dotnet/runtime/blob/v5.0.1/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs#L629

I think the Activity should capture a "previous" Activity independently of the Parent Activity and then always set that as active when stopping it.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions