fix(tracing): improve error handling in sync generator finalization #506
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.
Fix Context Variable Error in Sync Generator Tracing for Multi-threaded Environments
Problem Description
The
@trace
decorator for synchronous generators crashes in multi-threaded web frameworks like FastAPI and OpenWebUI with the following error:Root Cause
This error occurs when:
starlette.concurrency.iterate_in_threadpool
)_current_step.reset(token)
call in_finalize_sync_generator_step()
attempts to reset a context variable token that was created in the original contextExample Scenario
The crash happens because Python's
contextvars
are thread-local, and tokens cannot be reset across thread boundaries.Impact
Proposed Solution
Add graceful error handling for context variable operations in multi-threaded scenarios:
Changes Made
Protected Context Variable Reset:
Protected Finalization Calls:
Behavior Changes
Why This Solution is Safe
1. Preserves Normal Operation
2. Automatic Memory Management
3. Limited Impact Scope
get_current_step()
directly4. Comprehensive Error Handling
Alternative Solutions Considered
1. Store Original Context Reference
Rejected because:
2. Disable Generator Tracing in Multi-threaded Environments
Rejected because:
3. Require Manual Context Management
Rejected because:
4. Use Weak References for Memory Safety
Rejected because:
Testing
Test Coverage
Validation Script
Backward Compatibility
Risk Assessment
Low Risk
Medium Risk
Mitigation
Conclusion
This change enables Openlayer tracing to work correctly in modern async web frameworks while maintaining full backward compatibility. The solution is conservative, focusing on graceful error handling rather than complex architectural changes.
The fix addresses a critical blocker for adoption in FastAPI, OpenWebUI, and similar frameworks without compromising the reliability or performance of existing use cases.