Skip to content

Allow setting the Activity properties after Activity creation and before starting it when using ActivitySource #42784

Closed

Description

@macrogreg

The description and the Proposal edited by @tarekgh. The original description is moved down in the comment #42784 (comment)

ActivitySource provides the method StartActivity which will try to create and start the Activity object. There is a scenario that needs to add some more properties to the Activity object after it is created and before it gets started.
The reason is the caller wants to avoid creating the objects need to set to the Activity before ensuring the Activity object is created. It is important to have these properties set before starting the Activity so the listeners of the Start event will get the full set of the data.

Proposal

namespace System.Diagnostics
{
    public sealed class ActivitySource : IDisposable
    {
        // Alternative proposed name is CreateUnstartedActivity
        public Activity? CreateActivity(
                             string name,
                             ActivityKind kind, 
                             ActivityContext parentContext,
                             IEnumerable<KeyValuePair<string, object?>>? tags = null, 
                             IEnumerable<ActivityLink>? links = null);

        public Activity? CreateActivity(
                             string name, 
                             ActivityKind kind,
                             string parentContext,
                             IEnumerable<KeyValuePair<string, object?>>? tags = null, 
                             IEnumerable<ActivityLink>? links = null);
    }
}

Example

    using (Activity activity = activitySource.CreateActivity("SomeName", ActivityKind.Server, context))
    {
        activity?.AddBaggage("db.type", "mongo");
        activity?.Start();

        // Do any necessary work      
    }

Activity

  1. added
    untriaged
    on Sep 26, 2020
  2. macrogreg commented on Sep 26, 2020

    @macrogreg
    Author

    Some tags to raise awareness for folks involved into relevant work streams:
    @cijothomas @noahfalk

    Thanks! :)

  3. added
    api-suggestion
    and removed
    untriaged
    on Sep 27, 2020
  4. added this to the Future milestone on Sep 27, 2020
  5. tarekgh commented on Sep 27, 2020

    @tarekgh
    Member

    I don't think it is intended to support all possible scenario in ActivitySource in first version. Your scenario can be considered in the future releases. You still have the option to use old way of creating the Activity and using DiagnosticSource. This still work.

    For tags allocation, you can still avoid the allocation before creating the activity by setting ActivityCreationOptions.SamplingTags in the listener callbacks. This will still allocate at that time but for sure it will be determined the Activity is going to be allocated anyway.

    It is too late to change any APIs in the 5.0 release.

  6. macrogreg commented on Sep 28, 2020

    @macrogreg
    Author

    You still have the option to use old way of creating the Activity and using DiagnosticSource. This still work.

    From the perspective of a telemetry producer - yes. But a producer does not know whether this scenario is important for any actual consumer. And if a producer who followed the existing guidance wants to transition to the "new way" while enabling all previous scenarios, they cannot. I completely realize the current spot in the release cycle, but if this item was to be tracked for prioritization in the next cycles, then, for the record, I think that the workaround you mention does not apply. :)

    For tags allocation, you can still avoid the allocation before creating the activity by setting ActivityCreationOptions.SamplingTags in the listener callbacks.

    Thanks for pointing it out. I had missed the existence of that property. However, having had a look at it, I do not fully understand its use. Is there a doc or an example? What I mean above is that when invoking ActivitySource.StartActivity(..) you need to pass an IEnumerable object on the heap. So the allocation will occur when creating that object while the sampling decision is taken within the scope of the ActivitySource.StartActivity(..) method. So regardless of whether or not you decided to allocate the activity, you will have to allocate the tags collection object.

    Please let me know if you guys consider these Activity-related submissions as a valuable input for forward-looking planning / for the next cycle. I do not want to create a distraction if it is not productive. :)

    Thanks!

  7. tarekgh commented on Sep 28, 2020

    @tarekgh
    Member

    if a producer who followed the existing guidance wants to transition to the "new way" while enabling all previous scenarios, they cannot.

    Agree. What i was trying to say is, this is not supported scenario yet with ActivitySource. I was pointing if someone blocked for now can consider use the old way.

    For ActivityCreationOptions.SamplingTags, the idea is when you are calling ActivitySource.StartActivity you'll not pass any tags at that time but in the listener you'll have a chance to add the tags during then. I am not sure if this will fully satisfy your scenario. you may look at our test

    activityOptions.SamplingTags.Add("tag1", "value1");
    which show how it is used.

    If the allocation is very critical to your scenario, you may consider having IEnumerable thread local object (e.g. List<>) which you can use for all subsequent calls on same thread. The allocation would be once per thread instead to be ones per ActivityStart call.

  8. modified the milestones: Future, 6.0.0 on Sep 28, 2020
  9. macrogreg commented on Sep 28, 2020

    @macrogreg
    Author

    Agree. What i was trying to say is, this is not supported scenario yet with ActivitySource. I was pointing if someone blocked for now can consider use the old way.

    Gotcha, thanks!

    For ActivityCreationOptions.SamplingTags, the idea is when you are calling ActivitySource.StartActivity you'll not pass any tags at that time but in the listener you'll have a chance to add the tags during then.

    Ah, understood. This is a different scenario. I was talking about saving the allocation that is only required only to pass parameters to StartActivity(..)

    If the allocation is very critical to your scenario, you may consider having IEnumerable thread local object (e.g. List<>) which you can use for all subsequent calls on same thread.

    That might work, but the complexity of implementing such cache and the perf overhead required for cleaning it before each use make this feel concerning. Of course, .NET5 is done. I would love a performance-focused overload similar to what I mentioned above to be considered for the next release.

    If the team decides that such an overload is beneficial, I'd be happy to contribute when the time comes. :)

    Thanks!

  10. cijothomas commented on Sep 28, 2020

    @cijothomas
    Contributor

    StartActivity(..) overloads that have parameters like string tag1Key, string tag1Value, ... for the first few tags.

    This sounds like a good improvement. In most cases the number of initial tags/attributes is very low (or none). More tags are added after actually creating the activity and knowing the sampling decision.

    (if activity != null && activity.IsAllDataRequested == true) 
    {
      add tags.
    }
    
  11. noahfalk commented on Sep 28, 2020

    @noahfalk
    Member

    Thanks @macrogreg!

    System.Diagnostics.ActivitySource.StartActivity(..) is missing an overload that takes Baggage items

    StartActivity() was intended to take the minimum amount of data necessary for sampling. Adding more types of data trades off performance for more flexibility in sampling and richer data available on the start callback. Another direction is to create an API that returns an unstarted Activity allowing Start() to be decoupled from sampling. That option is trading off more complicated API usage for richer data available on the start callback. I'm not opposed to this in principle, but they first hurdle to clear would be to understand why do we need specific data attached to a Start callback if that same data will be available later in the Stop callback?

    However, this will require that an enumerable is allocated before StartActivity(..) is called

    We added the overload which took tags because OpenTelemetry defined that it must be possible to give tags to the sampling algorithm. My hope is that in practice it is a rare case that the sampling algorithm needs to consider tags because doing so implies you are paying perf costs to generate them and analyze them even for sampled-out activities. The higher performing route would be to determine in advance that the tags aren't relevant for sampling and provide them only after an Activity has been sampled in using Activity.SetTag(). If there is a need for higher performance scenarios where certain tags are available to the sampler or available in the Start() callback I'm not opposed to optimizations you suggested, but I'd like to be able to tie to some specific customer or use-case that the work is improving.

  12. 27 remaining items

  13. tarekgh commented on Feb 10, 2021

    @tarekgh
    Member

    I have added the proposal in the top. We should discuss the naming in the design meeting. Thanks allot for your feedback.

  14. added
    api-ready-for-review
    and removed
    api-suggestion
    on Feb 10, 2021
  15. cijothomas commented on Feb 10, 2021

    @cijothomas
    Contributor

    minor: The title of this issue can be confusing as the new API is about slightly different things. Could you create a new issue with the proposal, and link it from there for easy read by anyone new. :)

  16. tarekgh commented on Feb 10, 2021

    @tarekgh
    Member

    minor: The title of this issue can be confusing as the new API is about slightly different things. Could you create a new issue with the proposal, and link it from there for easy read by anyone new. :)

    We can rename the title and possibly the description if @macrogreg not mind. I am not sure creating a new issue and link it to this one would help much as all discussions are listed here.

  17. tarekgh commented on Feb 11, 2021

    @tarekgh
    Member

    Moving the original description added by @macrogreg here for the record as we need to modify the description up to match what have discussed and decided on.

    @macrogreg original description

    I think there is a scenario supported by the pre-.NET-5 Activity APIs based on DiagnosticSource that is not supported in the new ActivitySource based APIs:

    System.Diagnostics.ActivitySource.StartActivity(..) is missing an overload that takes Baggage items.

    Consider .NET's own guidance on using Activity with DiagnosticSource:
    https://github.com/dotnet/runtime/blob/master/src/libraries/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#starting-and-stopping-activity

    In this scenario, a telemetry consumer who chooses to listen to "Http_In"-evens will receive Start and Stop events such that the Start events already contain information from the "Correlation-Context"-headers in the Baggage bag attached to the activity. (In addition, the whole HttpContext context object is also passed, but this is not the focus here.)

    On contrary, in the new ActivitySource-based APIs, the listeners are notified within the scope of the ActivitySource.StartActivity(..) method. The creator of the activity only receives a reference to the new activity after the potentially registered listeners have been notified and finished processing the Start event. Only information that can be passed as arguments to the StartActivity(..) method can reach the listeners.

    So the scenario that is used as the "model" scenario in .NET's own docs is not supported.

    If we consider this to indeed be a problem worth addressing, we should not stop at Baggage and consider that it applies to all Activity properties that existed pre-.NET-5 and were settable on an Activity instance before is is passed to DiagnosticSource.StartActivity(..).

    I realized how late to the final release the product is. There are several possible approaches:

    • I am missing something, and there is a workaround already (I hope for this to be the case :) ). Perhaps we can include it into some doc.

    • We decide that this is indeed a problem, but we are too late in the cycle to fix it. The we should still acknowledge and document it, and track for a future release.

    • We consider it fixing for .NET 5. If so, please let me know, I'd be happy to prepare a PR.

    Thanks for considering this!


    (Update an hour later) Just discovered an additional (related) issue, adding relevant info here:

    For convenience, here is the current ActivitySource public surface.

    The Tags of an Activity are not exactly affected by the above problem as ActivitySource.StartActivity(..) has overloads that take an IEnumerable<KeyValuePair<string, object>> tags parameter. However, this will require that an enumerable is allocated before StartActivity(..) is called. This is problematic in two ways. One of them is easier to address than the other:

    1. If the activity would not be created due to sampling (i.e. StartActivity(..) returns null), then the allocation of the enumerable and all its members was for nothing. This is hard to address in the current model. At this stage all we can do is to document it and recommend a best way to minimize overhead.

    2. Even if the Activity object is created, there is still an allocation if the IEnumerable just to pass parameters. The object will likely not survive beyond Gen0, but still: so much work was done to avoid allocations, that it seems weird. This could be addressed by providing StartActivity(..) overloads that have parameters like string tag1Key, string tag1Value, ... for the first few tags. This could help skipping that allocation for the common case where there is just a few tags. Notably, having tags and/or baggage is likely much more frequent than having links, events etc. So yes, the number of overloads would grow, but would not explode uncontrollably. :)

  18. changed the title [-]ActivitySource.StartActivity(..) is missing an overload that takes Baggage Items[/-] [+]Allow setting the Activity properties after Activity creation and before starting it when using ActivitySource[/+] on Feb 11, 2021
  19. added
    api-approved
    and removed
    api-ready-for-review
    on Feb 16, 2021
  20. terrajobst commented on Feb 16, 2021

    @terrajobst
    Contributor

    Video

    • We should add a simplified overload that only requires name and kind
    • The proposed name is sufficiently clear
    namespace System.Diagnostics
    {
        public sealed class ActivitySource : IDisposable
        {
            public Activity? CreateActivity(string name, 
                                            ActivityKind kind);
    
            public Activity? CreateActivity(string name,
                                            ActivityKind kind, 
                                            ActivityContext parentContext,
                                            IEnumerable<KeyValuePair<string, object?>>? tags = null, 
                                            IEnumerable<ActivityLink>? links = null);
    
            public Activity? CreateActivity(string name, 
                                            ActivityKind kind,
                                            string parentContext,
                                            IEnumerable<KeyValuePair<string, object?>>? tags = null, 
                                            IEnumerable<ActivityLink>? links = null);
        }
    }
  21. ghost added
    in-pr
    on Feb 17, 2021
  22. tarekgh commented on Feb 18, 2021

    @tarekgh
    Member

    Discussed offline more the proposal with @dotnet/fxdc to ensure we are addressing the request in #43853 and decided we'll add the extra parameter ActivityIdFormat idFormat = ActivityIdFormat.Unknown to the last 2 overloads. the final approved proposal now is:

    namespace System.Diagnostics
    {
        public sealed class ActivitySource : IDisposable
        {
            public Activity? CreateActivity(string name, 
                                            ActivityKind kind);
    
            public Activity? CreateActivity(string name,
                                            ActivityKind kind, 
                                            ActivityContext parentContext,
                                            IEnumerable<KeyValuePair<string, object?>>? tags = null, 
                                            IEnumerable<ActivityLink>? links = null,
                                            ActivityIdFormat idFormat = ActivityIdFormat.Unknown);
    
            public Activity? CreateActivity(string name, 
                                            ActivityKind kind,
                                            string parentContext,
                                            IEnumerable<KeyValuePair<string, object?>>? tags = null, 
                                            IEnumerable<ActivityLink>? links = null,
                                            ActivityIdFormat idFormat = ActivityIdFormat.Unknown);
        }
    }
  23. ghost removed
    in-pr
    on Feb 23, 2021
  24. ghost locked as resolved and limited conversation to collaborators on Mar 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Diagnostics.Activityfeature-request

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions