Repository navigation
Conversation
Reviewer's GuideAPIExtend the public
DocumentationDocument coroutine tracing behavior and provide an async manual-tracing example alongside the content-capture guidance.
Point Python SDK readers to the manual-tracing documentation for sync and async examples and content-capture settings.
TestsAdd regression tests for awaited coroutine span lifecycle, nesting, errors, cancellation, concurrency, output capture, and unchanged synchronous tracing.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
PR Summary by QodoFix manual tracing of awaited Python coroutines
AI Description
Merge Risk
|
Code Review by Qodo
1.
|
Linked issuesChecked at commit d006711 #2016 Bug: @trace ends async function spans before the coroutine runs · 3 of 3 met
|
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="sdk/python/src/openlit/__init__.py" line_range="984-986" />
<code_context>
- response = None
try:
- response = wrapped(*args, **kwargs)
- span.set_attribute(
- SemanticConvention.GEN_AI_OUTPUT_MESSAGES, response or ""
- )
+ yield span
span.set_status(Status(StatusCode.OK))
</code_context>
<issue_to_address>
**Disabled content still reaches telemetry**
When `capture_message_content` is disabled and an async function decorated with `@openlit.trace` handles sensitive inputs or returns sensitive content, the async wrapper writes the raw return value to `gen_ai.output.messages`, while `traced_operation` also records raw arguments and keyword arguments. The exporter therefore receives sensitive content despite the caller's content-capture opt-out.
Honor `OpenlitConfig.capture_message_content` in manual tracing and avoid recording raw arguments or results when content capture is disabled.
</issue_to_address>
### Comment 2
<location path="sdk/python/src/openlit/__init__.py" line_range="978" />
<code_context>
exc_info=True,
)
+ if iscoroutinefunction(wrapped):
+
+ @wraps(wrapped)
</code_context>
<issue_to_address>
**Async work escapes its trace span**
When a synchronous decorator wraps an async function and returns its coroutine before @openlit.trace is applied, iscoroutinefunction(wrapped) returns false, so trace selects the synchronous wrapper, which ends the span before the coroutine runs; awaited work and nested spans lose their parent, and the final result is not recorded.
Detect the wrapped coroutine and keep the span open until its returned coroutine has been awaited.
</issue_to_address>
### Comment 3
<location path="sdk/python/src/openlit/__init__.py" line_range="956" />
<code_context>
- )
+ yield span
span.set_status(Status(StatusCode.OK))
except Exception as e:
span.record_exception(e)
</code_context>
<issue_to_address>
**Cancelled spans lose metadata**
When a decorated coroutine is cancelled while suspended or running, the except Exception handler does not catch asyncio.CancelledError, so exception recording and status handling are skipped, as is the metadata block after the try; the exported span lacks function arguments and cancellation details.
Handle cancellation explicitly so the span records the cancellation and metadata before re-raising it.
</issue_to_address>
### Comment 4
<location path="sdk/python/src/openlit/__init__.py" line_range="985" />
<code_context>
try:
- response = wrapped(*args, **kwargs)
- span.set_attribute(
- SemanticConvention.GEN_AI_OUTPUT_MESSAGES, response or ""
- )
+ yield span
</code_context>
<issue_to_address>
**Structured results are omitted**
When a decorated coroutine returns a mapping or another non-OTel-attribute object, async_wrapper passes the response directly to Span.set_attribute, which rejects unsupported values, so the exported span lacks gen_ai.output.messages.
Convert non-attribute results to a supported serialized value before setting gen_ai.output.messages.
Also at `sdk/python/src/openlit/__init__.py:986`.
</issue_to_address>
### Comment 5
<location path="sdk/python/src/openlit/__init__.py" line_range="984-986" />
<code_context>
- response = None
try:
- response = wrapped(*args, **kwargs)
- span.set_attribute(
- SemanticConvention.GEN_AI_OUTPUT_MESSAGES, response or ""
- )
+ yield span
span.set_status(Status(StatusCode.OK))
</code_context>
<issue_to_address>
**Configured content limit is bypassed**
When `max_content_length` is set and a decorated coroutine returns content longer than that limit, the async wrapper stores the full result in the span without applying `max_content_length`, so an oversized result exceeds the configured telemetry-size limit and can send more content than intended to the exporter.
Apply the configured content truncation to coroutine results before setting the span attribute, and to any other captured content that exceeds the limit.
</issue_to_address>
### Comment 6
<location path="sdk/python/src/openlit/__init__.py" line_range="985" />
<code_context>
try:
- response = wrapped(*args, **kwargs)
- span.set_attribute(
- SemanticConvention.GEN_AI_OUTPUT_MESSAGES, response or ""
- )
+ yield span
</code_context>
<issue_to_address>
**Falsey coroutine results are erased**
When the decorated coroutine returns a falsey value other than `None`, `response or ""` replaces legitimate results such as `False` or `0` with an empty string, so the exported output does not match the coroutine's result.
Use an explicit `None` check and encode the result without collapsing falsey values.
</issue_to_address>
### Comment 7
<location path="sdk/python/README.md" line_range="308-312" />
<code_context>
+openlit.init()
+
[email protected]
+async def reserve_room(calendar, minutes):
+ return await calendar.reserve(minutes)
+
+# In an async application:
+# confirmation = await reserve_room(calendar, 45)
+```
+
</code_context>
<issue_to_address>
**Example cannot run as shown**
When a reader runs the added manual-tracing example as shown, the example leaves `calendar` undefined and comments out the only call to `reserve_room`, so it neither runs the operation nor demonstrates the awaited tracing behavior it describes.
Include a working calendar implementation or mock and an awaited invocation so the example can be run as documented.
</issue_to_address>
### Comment 8
<location path="sdk/python/README.md" line_range="296-314" />
<code_context>
openlit.log_score("category", "accurate")
```
+## Manual tracing
+
+Use `@openlit.trace` on synchronous functions or `async def` functions. For a
+coroutine, its span stays active through the awaited execution, so nested LLM
</code_context>
<issue_to_address>
**Manual-tracing docs use wrong format**
When the manual-tracing documentation is added to the SDK README, the new manual-tracing guidance is placed in `sdk/python/README.md`, not in an `.mdx` page under `/docs/latest/`, so it does not follow the repository’s required documentation format and location.
Move the guidance to an appropriately located `.mdx` page under `/docs/latest/sdk/` and update navigation if needed.
</issue_to_address>
### Comment 9
<location path="sdk/python/tests/test_manual_trace_coroutines.py" line_range="143-145" />
<code_context>
+ with pytest.raises(ValueError, match="calendar unavailable"):
+ reserve()
+ else:
+ assert reserve() == "booked"
+ (span,) = exporter.get_finished_spans()
+ assert span.status.status_code == (StatusCode.ERROR if fails else StatusCode.OK)
</code_context>
<issue_to_address>
**Sync output attribute goes unchecked**
When the synchronous wrapper omits the output-message attribute, when the synchronous wrapper returns the right value and status but omits the output-message attribute, `test_synchronous_trace_still_records_results_and_errors` passes: lines `fm` and `fo` check only the return value and status.
Assert that the exported synchronous span’s output-message attribute equals `"booked"`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 7 findings to address first, and the awaited return value is now attached to the span and may be exported to a telemetry backend, exposing sensitive data if a traced coroutine returns it. Reverting stops future exports but cannot retract data already sent.
Blocking findings: sdk/python/src/openlit/__init__.py:986, sdk/python/src/openlit/__init__.py:978, sdk/python/src/openlit/__init__.py:956, sdk/python/src/openlit/__init__.py:985, sdk/python/src/openlit/__init__.py:986, and 2 more
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Issue number: Fixes #2016
Change description:
Await decorated coroutines inside their manual span so child LLM/tool spans retain their parent and exported output/error reflects execution. Share the existing span/error/metadata handling between the sync and async wrappers; document the supported usage.
Validation (Python 3.12, Linux): Four coroutine regressions fail on main; two synchronous controls pass. With the fix, 153 related offline tests pass. Full SDK Pylint and the new tests rate 10.00/10; poetry check and sdist/wheel builds pass. Tested the real OpenTelemetry SDK/exporter, including suspension, exceptions, cancellation and overlapping calls. Live provider tests require credentials and were not run.
Checklist
Acknowledgment
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.
Prepared and verified with OpenAI Codex assistance. The linked issue was opened with the executed reproduction before implementation.
Summary by Sourcery
Trace asynchronous functions through their awaited execution so exported spans accurately represent coroutine results, errors, cancellation, and child operations.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: