Skip to content

[API Proposal]: Api handle Activity.Current value changes #67276

Closed

Description

@pjanotti

Background and motivation

[Edit 04/07/2022: Use the event as proposed by @noahfalk]
[Edit 04/07/2022: Updates per conversation with @tarekgh ]

A typical implementation of distributed tracing uses an AsyncLocal<T> to track the "span context" of managed threads. When changes to the span context needs to be tracked this is done by using the AsyncLocal<T> constructor that takes the valueChangedHandler parameter. However, with Activity becoming the standard to represent spans, as used by OpenTelemetry, it is impossible to set the value changed handler since the context is tracked via Activity.Current.

cc @tarekgh @open-telemetry/dotnet-instrumentation-approvers

API Proposal

namespace System.Diagnostics
{
    public readonly struct ActivityNotification
    {
        public Activity? Previous { get; }
        public Activity? Current { get; }
    }

    public partial class Activity : IDisposable
    {
        // Add an event to track updates to the current Activity
        public static event EventHandler<ActivityNotification>? CurrentChanged;
    }
}

API Usage

AsyncLocal<Activity> t_currentActvity = new AsyncLocal<Activity>(ValueChanged);

void Init()
{
    Activity.CurrentChanged += OnCurrentActivityChange;
}

void OnCurrentActivityChange(object sender, ActivityNotification notification)
{
    t_currentActvity = notification.Current;
}

void ValueChanged(AsyncLocalValueChangedArgs<Activity> args)
{
    // Profiler can do whatever it wants with the Activity here. This callback is invoked every time the Activity.Current is set. 
}

Alternative Designs

Using registration methods instead of an Event:

namespace System.Diagnostics
{
    public delegate void ActivityCurrentChangeHandler(Activity? previous, Activity? current);

    public partial class Activity : IDisposable
    {
        public static void RegisterActivityCurrentChangeNotification(ActivityCurrentChangeHandler handler) { }
        public static void CancelActivityCurrentChangeNotification(ActivityCurrentChangeHandler handler) { }
    }
}

Using an Event but using an action that receives only the new current Activity:

namespace System.Diagnostics
{
    public partial class Activity
    {
        public static event Action<Activity?, Activity?>? ActivityChanged;
    }
}
  • Considered the AsyncLocal<Activity> backing Activity.Current to always be created with a valueChangedHandler and exposing a static method on Activity that would allow users to add their own handlers if desired.

  • Implement the support to add value changed handlers directly in AsyncLocal<T> this way any other type of context that needs to be shared can leverage the same implementation and expose similar APIs if desired. However, any implementation still needs to expose an API to add handlers.

Risks

Potentially Activity.Current can change very frequently, especially in a server application, so the implementation should be "pay-for-play" as much as possible.

Activity

  1. added
    api-suggestion
    on Mar 29, 2022
  2. ghost added
    untriaged
    on Mar 29, 2022
  3. added this to the 7.0.0 milestone on Mar 29, 2022
  4. ghost removed
    untriaged
    on Mar 29, 2022
  5. tarekgh commented on Apr 1, 2022

    @tarekgh
    Member

    @pjanotti thanks for the proposal and nice to hear from you :-)

    I have some questions here I hope you can help clarify as this will affect the design of such API. I am seeing you designed the API around the fact of internally using asynclocal. This will be a concern as we'll need to enable the asynclocal value change notification when instantiating it which may have some perf concern. I didn't measure that, but I'll do it in the first chance. So, my questions are:

    • Does your scenario need the notification when the thread context changes with asynclocal or you need the notification only when the Activity.Current explicitly set?
    • I assume we allow multiple registration for such notification, right?

    CC @noahfalk @reyang @cijothomas

  6. pjanotti commented on Apr 4, 2022

    @pjanotti
    ContributorAuthor

    Hi @tarekgh 👋

    Does your scenario need the notification when the thread context changes with asynclocal or you need the notification only when the Activity.Current explicitly set?

    We used it to track thread context changes. In our specific usage we used that to do a P/Invoke back to a CLR profiler so we could know to which span/Activity associate a given managed Thread. That said I think there would be also situations that would be useful to do it even from managed code for tracking purposes.

    I assume we allow multiple registration for such notification, right?

    Right, I think that is desirable and avoids having one implementation and then having to add composition support later.

    I am seeing you designed the API around the fact of internally using asynclocal.

    Correct, of course this does not need to be the implementation. I wanted to started with something more concrete to capture what capability needs to be satisfied. Having that capability and completely hiding whatever is backing it will be ideal.

  7. tarekgh commented on Apr 5, 2022

    @tarekgh
    Member

    I have done an experiment to calculate the cost if we enable asynclocal context change notification. I just enabled the notification even without doing any real action inside the callback:

    -        private static readonly AsyncLocal<Activity?> s_current = new AsyncLocal<Activity?>();
    +       private const bool s_isRegistered = false;
    +       private static readonly AsyncLocal<Activity?> s_current = new AsyncLocal<Activity?>((valueChangedArgs) => {
    +           if (s_isRegistered)
    +           {
    +           }
    +       });

    Then I ran the following measurement tests:

            [Benchmark]
            public int SettingActivityCurrentInAsyncChain0()
            {
                using var a = new Activity("a1");
                a.Start();
    
                return 0;
            }
    
            [Benchmark]
            public async Task<int> SettingActivityCurrentInAsyncChain1()
            {
                using var a = new Activity("a1");
                using var b = new Activity("a2");
    
                a.Start();
    
                await Task.Run(() =>
                    {
                        b.Start();
                    });
                return 0;
            }
    
            [Benchmark]
            public async Task<int> SettingActivityCurrentInAsyncChain2()
            {
                using var a = new Activity("a1");
                using var b = new Activity("a2");
                using var c = new Activity("a3");
    
                a.Start();
    
                await Task.Run(async () =>
                {
                    b.Start();
                    await Task.Run(() =>
                    {
                        c.Start();
                    });
                });
    
                return 0;
            }
    
            [Benchmark]
            public async Task<int> SettingActivityCurrentInAsyncChain3()
            {
                using var a = new Activity("a1");
                using var b = new Activity("a2");
                using var c = new Activity("a3");
                using var d = new Activity("a4");
    
                a.Start();
    
                await Task.Run(async () =>
                {
                    b.Start();
                    await Task.Run(async () =>
                    {
                        c.Start();
    
                        await Task.Run(() =>
                        {
                            d.Start();
                        });
                    });
                });
    
                return 0;
            }

    and I have gotten the following result:

    Before the change

    |                              Method |       Mean |    Error |   StdDev |  Gen 0 | Allocated |
    |------------------------------------ |-----------:|---------:|---------:|-------:|----------:|
    | SettingActivityCurrentInAsyncChain0 |   191.8 ns |  1.38 ns |  1.29 ns | 0.0496 |     416 B |
    | SettingActivityCurrentInAsyncChain1 | 1,243.2 ns | 12.03 ns | 10.66 ns | 0.1316 |   1,104 B |
    | SettingActivityCurrentInAsyncChain2 | 2,110.0 ns | 25.74 ns | 22.82 ns | 0.2403 |   2,000 B |
    | SettingActivityCurrentInAsyncChain3 | 2,903.3 ns | 18.77 ns | 16.64 ns | 0.3395 |   2,824 B |
    

    After the change

    |                              Method |       Mean |    Error |   StdDev |  Gen 0 | Allocated |
    |------------------------------------ |-----------:|---------:|---------:|-------:|----------:|
    | SettingActivityCurrentInAsyncChain0 |   184.7 ns |  1.09 ns |  1.02 ns | 0.0582 |     488 B |	
    | SettingActivityCurrentInAsyncChain1 | 1,345.6 ns | 25.97 ns | 29.91 ns | 0.1431 |   1,208 B |
    | SettingActivityCurrentInAsyncChain2 | 2,242.9 ns | 21.95 ns | 19.46 ns | 0.2518 |   2,104 B |
    | SettingActivityCurrentInAsyncChain3 | 3,249.8 ns | 37.52 ns | 31.33 ns | 0.3510 |   2,928 B |
    

    The allocation cost is constant and doesn't grow so there is no allocation concern. It is clear there is some perf cost though between 6% to 11% depending on the scenario. This is the part we need to be careful with.

  8. noahfalk commented on Apr 6, 2022

    @noahfalk
    Member

    Tarek do you want to check what the perf overhead is if .NET only provides notification when the Activity.Current setter is called? I think that is sufficient for others to bootstrap themselves to the full set of notifications by using a 2nd AsyncLocal. I'd expect overhead when no event is attached to be very low though the overhead to achieve @pjanotti's scenario could be a little higher. I'm thinking something like this:

    .NET Code:

    class Activity
    {
        public static Activity Current
        {
           get { ... }
           set 
           {
               CurrentActivityChanged?.Invoke(value);
               ...       
           }
        }
    
        public static event Action<Activity> CurrentActivityChanged;
    }

    Your benchmark above would be the same where CurrentActivityChanged = null. I expect the CPU will have no problem predicting that the conditional branch for Invoke() won't be taken so I'm hoping we are going to see overhead <= 1ns per Activity.

    @pjanotti could then write something like this to generate the full set of notifications he is looking for:

    AsyncLocal<Activity> t_currentActvity = new AsyncLocal<Activity>(ValueChanged);
    
    void Init()
    {
        Activity.CurrentActivityChanged += OnCurrentChanged;
    }
    
    void OnCurrentChanged(Activity newValue)
    {
        t_currentActivity = newValue;
    }
    
    void ValueChanged(AsyncLocalValueChangedArgs<Activity> args)
    {
        // profiler can do whatever it wants with the Activity here. This callback is invoked for all Activity changes
        // both ExecutionContext changes and Activity.Current setter invocations
    }
  9. tarekgh commented on Apr 6, 2022

    @tarekgh
    Member

    @noahfalk I think your idea will work and I don't think there will be much overhead if we just have:

        public static Activity Current
        {
           get { ... }
           set 
           {
               CurrentActivityChanged?.Invoke(value);
               ...       
           }
        }

    But I'll measure it anyway to ensure no issue with it.

    I like the idea of having the asynclocal in the app side to track the context change. honestly I didn't think of this option before :-)

  10. 14 remaining items

  11. tarekgh commented on Apr 8, 2022

    @tarekgh
    Member

    @noahfalk let's know if you are ok with the final proposal.

  12. noahfalk commented on Apr 8, 2022

    @noahfalk
    Member

    [EDIT] Spoke too soon.
    The API looks great but the comment in the API usage is misleading. The comment says the callback will be invoked for both setter invocations and ExecutionContext changes but that isn't the intended behavior. The callback would only be invoked for setter invocations, not ExecutionContext changes. To get EC changes the caller needs to set up a 2nd async local and sync it using the usage that I had showed. I'm guessing that was just a copy-paste error but it might mislead the reviewers.

  13. tarekgh commented on Apr 8, 2022

    @tarekgh
    Member

    I updated the text telling the callback will be called only when Activity.Current is set.

  14. pjanotti commented on Apr 8, 2022

    @pjanotti
    ContributorAuthor

    Forgot to mention that I had updated the usage per Noah's comment.

    Not sure if useful but I wrote a quick test to validate the proposal, anyway here it goes:

    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using FluentAssertions;
    using Xunit;
    
    namespace ApiProposalValidation
    {
        public class ApiProposalValidation
        {
            [Fact(Timeout = 500_000)]
            public void PushAsyncContextToNative()
            {
                // Have the whole test running in a dedicated thread so Tasks get to
                // run in the thread pool, causing an async thread change. This is
                // not required on dev boxes but makes the test more robust for machines
                // with a smaller number of cores.
                // Running the test in a dedicated thread requires any exception throw
                // in the test, eg.: an assert, to be flowed to the original test thread.
                Exception testException = null;
                var testThread = new Thread(() =>
                {
                    try
                    {
                        // The actual code of the test will execute in different threads
                        // because of that the thread must wait for its completion.
                        TestThread().GetAwaiter().GetResult();
                    }
                    catch (Exception ex)
                    {
                        testException = ex;
                    }
                });
    
                testThread.Start();
                testThread.Join();
    
                // Check if there wasn't any assertion/exception on the test thread.
                testException.Should().BeNull();
    
                async Task TestThread()
                {
                    // For the tests use a delegate that keeps track of current context
                    // in the test thread.
                    var tid2ProfilingCtx = new Dictionary<int, Guid>();
    
                    var mockSetProfilingContext = (Guid id, int managedThreadId) =>
                    {
                        if (id == Guid.Empty)
                        {
                            tid2ProfilingCtx.Remove(managedThreadId);
                            return;
                        }
    
                        tid2ProfilingCtx[managedThreadId] = id;
                    };
    
                    var manager = new ContextManager()
                    {
                        SetProfilingContext = mockSetProfilingContext
                    };
    
                    var id = Guid.NewGuid();
                    Context.Current = id;
    
                    var currentManagedThreadId = Thread.CurrentThread.ManagedThreadId;
                    var initialManagedThreadId = currentManagedThreadId;
    
                    tid2ProfilingCtx[currentManagedThreadId].Should().Be(id);
    
                    while (currentManagedThreadId == initialManagedThreadId)
                    {
                        var blockingThreadTask = Task.Run(() => Thread.Sleep(200));
                        await Task.Delay(100);
                        await blockingThreadTask;
                        currentManagedThreadId = Thread.CurrentThread.ManagedThreadId;
                    }
    
                    // Context must have migrated to the new thread.
                    tid2ProfilingCtx[currentManagedThreadId].Should().Be(id);
    
                    // Context must have been cleaned up from old thread.
                    tid2ProfilingCtx.Should().NotContainKey(initialManagedThreadId);
    
                    Context.Current = Guid.Empty;
    
                    tid2ProfilingCtx.Should().NotContainKey(currentManagedThreadId);
                }
            }
    
            // Represents an implementation like the proposed API
            private static class Context
            {
                private static AsyncLocal<Guid> _localGuid = new();
    
                public static event EventHandler<Guid> CurrentChanged;
    
                public static Guid Current
                {
                    get
                    {
                        return _localGuid.Value;
                    }
    
                    set
                    {
                        CurrentChanged?.Invoke(null, value);
                        _localGuid.Value = value;
                    }
                }
            }
    
            // Represents the API usage
            private class ContextManager
            {
                private readonly AsyncLocal<Guid> _localGuid;
    
                public ContextManager()
                {
                    // TODO: need to think about possible races here.
                    _localGuid = new(ValueChanged);
                    Context.CurrentChanged += OnCurrentChanged;
                }
    
                public Action<Guid, int> SetProfilingContext { get; set; }
    
                public Guid Current { get => _localGuid.Value; }
    
                private void OnCurrentChanged(object sender, Guid e)
                {
                    _localGuid.Value = e;
                }
    
                private void ValueChanged(AsyncLocalValueChangedArgs<Guid> args)
                {
                    SetProfilingContext(args.CurrentValue, Thread.CurrentThread.ManagedThreadId);
                }
            }
        }
    }
  15. added
    api-ready-for-review
    blocking
    and removed
    api-suggestion
    on Apr 9, 2022
  16. terrajobst commented on Apr 12, 2022

    @terrajobst
    Contributor

    Video

    • Makes sense, but we should rename the struct and make the properties init
    namespace System.Diagnostics
    {
        public readonly struct ActivityChangedEventArgs
        {
            public Activity? Previous { get; init; }
            public Activity? Current { get; init; }
        }
    
        public partial class Activity : IDisposable
        {
            public static event EventHandler<ActivityChangedEventArgs>? CurrentChanged;
        }
    }
  17. added
    api-approved
    and removed
    api-ready-for-review
    on Apr 12, 2022
  18. removed
    blocking
    on Apr 12, 2022
  19. ghost added
    in-pr
    on Apr 13, 2022
  20. ghost removed
    in-pr
    on Apr 13, 2022
  21. ghost locked as resolved and limited conversation to collaborators on May 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Diagnostics.Activity

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions