fix(openai-agents): use synchronous spans to fix OTel context detachment #1312
+19
−26
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.
Problem
PR #1197 attempts to fix OpenAI Agents tracing but fails with OTel providers (Langfuse, Logfire) due to context detachment errors:
The issue: OTel validates token detachment happens in the exact same
contextvars.Contextinstance where the token was created. Evencopy_context()creates a new instance with equivalent values, causing the check to fail.Root Cause
Activities and child workflows complete in:
Callbacks registered with copied context still execute in a new context instance, breaking OTel's validation.
Solution
Follow the pattern used in
temporalio/contrib/opentelemetry.py- complete spans synchronously at the orchestration point:Benefits
add_done_callbackmachinery, cleaner code (-26 lines, +19 lines)Span Hierarchy
The zero-duration span is correct - it represents when the orchestration decision was made, not when the distributed work completed.
Testing
temporalio/contrib/opentelemetry.pyReferences
temporalio/contrib/opentelemetry.pycc @cretz - This implements the synchronous span approach you suggested in the PR #1197 review. Let me know if you'd like any changes!
🤖 Generated with Claude Code