Skip to content

feat(tracer): add support for generators #13377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

chasleslr
Copy link

@chasleslr chasleslr commented May 9, 2025

PR Description

Fix support for wrapping generator functions with tracer.wrap() and ensure they generate traces in Datadog
Related issue: #5403


Summary of the problem

Currently, when a generator function is wrapped with tracer.wrap(), two major issues arise:

  1. Accessing the current span fails:
    Inside the wrapped generator, tracer.current_span() returns None.
    As a result, any attempt to set tags or interact with the span raises:

    AttributeError: 'NoneType' object has no attribute 'set_tag'
    

    Example:

    @tracer.wrap()
    def foobar():
        current_span = tracer.current_span()
        current_span.set_tag("hello", "world")
        yield 1

    Calling list(foobar()) → crashes with AttributeError.

  2. Traces are reported to Datadog with incorrect duration:
    Even if the generator runs without explicit span interaction, traces emitted to Datadog do not correctly report the execution time of the function.
    This is because the tracer.wrap() decorator does not maintain the span context during generator iteration (next() or async for), so the span gets opened and closed at the same time.


Root cause

  • The wrap() logic does not correctly handle Python generators (def ... yield) or async generators (async def ... yield).
  • Without this, both local span interactions (current_span()) and backend reporting (sending traces to Datadog) break.

Proposed fix

This PR updates the tracer.wrap() decorator to:

  • Add proper handling for sync generators:

    • Ensure tracer.current_span() is available.
    • Finalize the span after the generator is exhausted or on error.
    • Report traces to Datadog as expected.
  • Add dedicated support for async generators:

    • Use an async for wrapper.
    • Maintain the tracing context.

With this change:

  • Spans inside generators work (current_span() is valid).
  • Traces from generator functions are correctly sent to Datadog.

How to reproduce + verify the fix

Minimal reproducible example:

@tracer.wrap()
def foobar():
    current_span = tracer.current_span()
    current_span.set_tag("hello", "world")
    yield 1

assert list(foobar()) == [1]

Expected result:

  • No errors.
  • Span is created and tagged.
  • Trace is visible in Datadog with the tag hello: world.

Added test cases:

  • Sync generator with span tags.
  • Async generator with span tags.
  • Backward compatibility for sync/async functions.

Checklist

  • PR author has checked that all the criteria below are met
  • The PR description includes an overview of the change
  • The PR description articulates the motivation for the change
  • The change includes tests OR the PR description describes a testing strategy
  • The PR description notes risks associated with the change, if any
  • Newly-added code is easy to change
  • The change follows the library release note guidelines
  • The change includes or references documentation updates if necessary
  • Backport labels are set (if applicable)

Reviewer Checklist

  • Reviewer has checked that all the criteria below are met
  • Title is accurate
  • All changes are related to the pull request's stated goal
  • Avoids breaking API changes
  • Testing strategy adequately addresses listed risks
  • Newly-added code is easy to change
  • Release note makes sense to a user of the library
  • If necessary, author has acknowledged and discussed the performance implications of this PR as reported in the benchmarks PR comment
  • Backport labels are set in a manner that is consistent with the release branch maintenance policy

Copy link

cit-pr-commenter bot commented May 12, 2025

PR Security Update

All commits in this PR up to and including 056d361 have been reviewed and marked safe by SDLC security. For any questions, please reach out to #ci-for-external-contributors-collab on Slack.

Copy link
Collaborator

@emmettbutler emmettbutler left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new feature needs a release note. Aside from that, the change looks great.

@@ -284,6 +284,29 @@ def wrapped_function(param, kw_param=None):
(dict(name="wrap.overwrite", service="webserver", meta=dict(args="(42,)", kwargs="{'kw_param': 42}")),),
)

def test_tracer_wrap_generator(self):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you considered adding a test that validates the duration of these spans?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point -- updated in c6029f5.

@chasleslr chasleslr requested a review from a team as a code owner May 13, 2025 14:09
@chasleslr
Copy link
Author

This new feature needs a release note. Aside from that, the change looks great.

Oops -- I just added a release note in 056d361. ✅

@chasleslr chasleslr requested a review from emmettbutler May 13, 2025 14:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants