Repository navigation
Description
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>backingActivity.Currentto always be created with avalueChangedHandlerand exposing a static method onActivitythat 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
tarekgh commentedon Apr 1, 2022
@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 theasynclocalvalue 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:Activity.Currentexplicitly set?CC @noahfalk @reyang @cijothomas
pjanotti commentedon Apr 4, 2022
Hi @tarekgh 👋
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.
Right, I think that is desirable and avoids having one implementation and then having to add composition support later.
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.
tarekgh commentedon Apr 5, 2022
I have done an experiment to calculate the cost if we enable
asynclocalcontext change notification. I just enabled the notification even without doing any real action inside the callback:Then I ran the following measurement tests:
and I have gotten the following result:
Before the change
After the change
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.
noahfalk commentedon Apr 6, 2022
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:
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:
tarekgh commentedon Apr 6, 2022
@noahfalk I think your idea will work and I don't think there will be much overhead if we just have:
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 :-)
14 remaining items
tarekgh commentedon Apr 8, 2022
@noahfalk let's know if you are ok with the final proposal.
noahfalk commentedon Apr 8, 2022
[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.
tarekgh commentedon Apr 8, 2022
I updated the text telling the callback will be called only when Activity.Current is set.
pjanotti commentedon Apr 8, 2022
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:
terrajobst commentedon Apr 12, 2022
Video
init