fix: Fix Duplicate Trace Calls for Async Functions and Optimize Tracer Implementation #473
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: Eliminate Duplicate Trace Calls in Async Functions and Optimize Tracer Implementation
Problem Statement
The Openlayer Python SDK was experiencing duplicate trace calls when using the
@trace()
decorator on async functions. Instead of generating a single unified trace, async functions created multiple duplicate traces with different data, causing test failures and incorrect tracing behavior.Root Cause Analysis
The issue was traced to the
@trace_async()
decorator's incompatibility with async generator functions:with create_step()
) that interfered withyield
statementscoroutine
objects instead ofasync_generator
objectsSolution Implementation
1. Async Generator Detection and Handling
inspect.isasyncgenfunction(func)
at decoration time to identify async generatorsyield
statements remain at the top level of wrapper functions2. Code Optimization (80% Duplication Reduction)
Identified and eliminated massive code duplication across three wrapper functions:
Before: ~150 lines with 80% duplication
After: ~40 lines with extracted helper functions
New Helper Functions:
_extract_function_inputs()
- Centralized input extraction and cleaning_finalize_step_logging()
- Unified step timing and logging_handle_trace_completion()
- Consistent trace completion logic_create_step_for_async_generator()
- Specialized context manager for async generators3. Client Authentication Fix
_client
was initialized at import time before environment variables were set_get_client()
function4. Test Refactoring
Created comprehensive nested test scenario with single orchestrator method:
intelligent_assistant_main()
method with 7 nested operations