feat(tracer): add support for generators #13377
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Description
Fix support for wrapping generator functions with
tracer.wrap()
and ensure they generate traces in DatadogRelated issue: #5403
Summary of the problem
Currently, when a generator function is wrapped with
tracer.wrap()
, two major issues arise:Accessing the current span fails:
Inside the wrapped generator,
tracer.current_span()
returnsNone
.As a result, any attempt to set tags or interact with the span raises:
Example:
Calling
list(foobar())
→ crashes withAttributeError
.No traces are reported to Datadog:
Even if the generator runs without explicit span interaction, no traces are emitted to Datadog.
This is because the
tracer.wrap()
decorator does not maintain the span context during generator iteration (next()
orasync for
), so the span never gets properly activated or closed.Root cause
wrap()
logic does not correctly handle Python generators (def ... yield
) or async generators (async def ... yield
).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:
tracer.current_span()
is available.Add dedicated support for async generators:
async for
wrapper.With this change:
current_span()
is valid).How to reproduce + verify the fix
Minimal reproducible example:
Expected result:
hello: world
.Added test cases:
Checklist
Reviewer Checklist