Skip to content

Conversation

@aanshu-ss
Copy link
Collaborator

Fix OpenTelemetry Context Propagation in Async Generator Functions
Problem Statement
The existing @pulse_agent decorator was not properly propagating OpenTelemetry trace context to async generator functions, resulting in different trace IDs being generated within the wrapped function compared to the wrapper span. This broke distributed tracing continuity and made it difficult to correlate logs and spans across the application.
Root Cause
Async generators (async def functions with yield) have unique execution characteristics:

They return an async generator object immediately upon invocation
Actual execution occurs during iteration over the generator
Each yield statement creates suspension points where execution context can be lost
The previous implementation's context attachment/detachment mechanism didn't account for these suspension points

Solution
Updated the @pulse_agent decorator to use Python's contextvars.copy_context() for proper context propagation in async generators.
Key Changes

Context Capture: Use copy_context() to capture the current execution context before entering the async wrapper
Context Preservation: Run the entire async generator within the captured context using ctx.run()
Span Lifecycle Management: Ensure the OpenTelemetry span remains active throughout the generator's execution lifecycle

@aanshu-ss aanshu-ss force-pushed the aanshu/tmp-response-traceID branch from 1bf88dc to b187239 Compare June 9, 2025 20:41
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.

2 participants