Skip to content

fix(python-sdk): trace awaited coroutine execution - #2018

Open
Twiink wants to merge 2 commits into
openlit:mainfrom
Twiink:fix/trace-awaited-coroutines-20261125
Open

Twiink wants to merge 2 commits into
openlit:mainfrom
Twiink:fix/trace-awaited-coroutines-20261125

Conversation

@Twiink

@Twiink Twiink commented Nov 25, 2026 •

Copy link
Copy Markdown

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

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines.
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented

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:

  • Support tracing the awaited execution of asynchronous coroutines, including decorated coroutines, with nested spans retaining their parent context.

Bug Fixes:

  • Ensure coroutine spans capture execution results, exceptions, cancellation, metadata, and configured content-capture behavior instead of ending before the coroutine is awaited.

Enhancements:

  • Share manual tracing behavior between synchronous and asynchronous wrappers while preserving existing synchronous tracing semantics.

Documentation:

  • Document synchronous and asynchronous manual tracing usage, including coroutine lifecycle and content-capture settings.

Tests:

  • Add coverage for coroutine execution, nested and overlapping spans, exceptions, cancellation, decorated coroutines, result serialization, content capture, and truncation.

@Twiink
Twiink requested review from a team and ishanjainn as code owners November 25, 2026 09:34
@Twiink
Twiink deployed to release-notes November 25, 2026 09:34 — with GitHub Actions Active
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

API

Extend the public trace decorator to recognize wrapped coroutine functions and keep their awaited execution inside the manual span while preserving synchronous behavior.

  • sdk/python/src/openlit/__init__.py L9-13, L964-1003 (+5 small edits)

Documentation

Document coroutine tracing behavior and provide an async manual-tracing example alongside the content-capture guidance.

  • docs/latest/sdk/features/tracing.mdx L106-134

Point Python SDK readers to the manual-tracing documentation for sync and async examples and content-capture settings.

  • sdk/python/README.md L296-300

Tests

Add regression tests for awaited coroutine span lifecycle, nesting, errors, cancellation, concurrency, output capture, and unchanged synchronous tracing.

  • sdk/python/tests/test_manual_trace_coroutines.py L1-263

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix manual tracing of awaited Python coroutines

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Keep manual spans active while decorated coroutines execute, preserving child-span parentage and
 final results.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed decorator is the single public integration that creates manual spans for both synchronous functions and coroutines.
  • Its propagation path ends at the telemetry behavior produced for the decorating caller; no separate storage or consumer capability is changed.
Sources

sdk/python/src/openlit/init.py[982-995]

    if iscoroutinefunction(unwrap(wrapped)):

        @wraps(wrapped)
        async def async_wrapper(*args, **kwargs):
            with traced_operation(args, kwargs) as span:
                response = await wrapped(*args, **kwargs)
                if getattr(OpenlitConfig, "capture_message_content", True):
                    span.set_attribute(
                        SemanticConvention.GEN_AI_OUTPUT_MESSAGES,
                        truncate_content(response),
                    )
                return response

        return async_wrapper

sdk/python/src/openlit/init.py[997-1005]

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        with traced_operation(args, kwargs) as span:
            response = wrapped(*args, **kwargs)
            if getattr(OpenlitConfig, "capture_message_content", True):
                span.set_attribute(
                    SemanticConvention.GEN_AI_OUTPUT_MESSAGES, truncate_content(response)
                )
            return response
Behavioral complexity 🔴 High 🧩 Interacting branches, Concurrent ordering

  • Before: tracing synchronously executed the wrapped function inside a span.
  • After: wrapper selection distinguishes unwrapped coroutine functions, and the span remains current across await, cancellation, nested spans, and overlapping tasks while sync behavior remains supported.
  • New correctness conditions are that span lifetime must cover the awaited execution, cancellation must record and close the span, concurrent coroutine contexts must not cross, and capture settings must consistently govern arguments and results in both paths.
  • These are changed lifecycle and async-context interactions, not complexity inherited merely from using existing OpenTelemetry APIs.
Sources

sdk/python/src/openlit/init.py[982-995]

    if iscoroutinefunction(unwrap(wrapped)):

        @wraps(wrapped)
        async def async_wrapper(*args, **kwargs):
            with traced_operation(args, kwargs) as span:
                response = await wrapped(*args, **kwargs)
                if getattr(OpenlitConfig, "capture_message_content", True):
                    span.set_attribute(
                        SemanticConvention.GEN_AI_OUTPUT_MESSAGES,
                        truncate_content(response),
                    )
                return response

        return async_wrapper

sdk/python/src/openlit/init.py[997-1005]

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        with traced_operation(args, kwargs) as span:
            response = wrapped(*args, **kwargs)
            if getattr(OpenlitConfig, "capture_message_content", True):
                span.set_attribute(
                    SemanticConvention.GEN_AI_OUTPUT_MESSAGES, truncate_content(response)
                )
            return response
Potential damage 🟡 Medium 🩹 Recoverable

  • If the changed behavior regresses, decorated calls may emit missing, incomplete, incorrectly parented, or incorrectly captured telemetry.
  • The wrapped application result is conditionally preserved when tracing continues normally; reverting restores subsequent telemetry behavior, and no persistent application state or external business effect requires repair.
  • Code rollback restores future manual-trace emission.
  • Spans already exported with incorrect fields or parentage are not automatically repaired, but the affected consequence is limited to observability data.
Sources

sdk/python/src/openlit/init.py[982-995]

    if iscoroutinefunction(unwrap(wrapped)):

        @wraps(wrapped)
        async def async_wrapper(*args, **kwargs):
            with traced_operation(args, kwargs) as span:
                response = await wrapped(*args, **kwargs)
                if getattr(OpenlitConfig, "capture_message_content", True):
                    span.set_attribute(
                        SemanticConvention.GEN_AI_OUTPUT_MESSAGES,
                        truncate_content(response),
                    )
                return response

        return async_wrapper

sdk/python/src/openlit/init.py[997-1005]

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        with traced_operation(args, kwargs) as span:
            response = wrapped(*args, **kwargs)
            if getattr(OpenlitConfig, "capture_message_content", True):
                span.set_attribute(
                    SemanticConvention.GEN_AI_OUTPUT_MESSAGES, truncate_content(response)
                )
            return response
Assessed commit d006711
Diagram

graph TD
  A["Decorated call"] --> B{"Coroutine function?"} -->|yes| C["Async wrapper"] --> E["Active parent span"] --> F["Execute function"] --> G["Nested child spans"] --> H["Exported telemetry"]
  B -->|no| D["Sync wrapper"] --> E
  F --> H
Loading
High-Level Assessment

Selecting an async wrapper and awaiting within the existing span context directly fixes the lifetime mismatch. Sharing status, exception, and metadata handling with the synchronous path avoids duplicating that behavior; separate async span handling offers no clear advantage.

Files changed (3) +187 / -8

Bug fix (1) +23 / -8
__init__.pyAwait decorated coroutines inside their manual spans +23/-8

Await decorated coroutines inside their manual spans

• Selects an async wrapper for coroutine functions so their execution and output recording occur within the active span. Extracts shared span status, exception, and metadata handling into a context manager used by both wrappers.

sdk/python/src/openlit/init.py

Tests (1) +145 / -0
test_manual_trace_coroutines.pyCover coroutine span lifetimes and synchronous behavior +145/-0

Cover coroutine span lifetimes and synchronous behavior

• Uses an isolated OpenTelemetry provider and in-memory exporter to verify awaited results, child parentage, exceptions, overlapping calls, and cancellation. Includes synchronous success and error controls.

sdk/python/tests/test_manual_trace_coroutines.py

Documentation (1) +19 / -0
README.mdDocument manual tracing of async functions +19/-0

Document manual tracing of async functions

• Adds an async decorator example and explains that the span remains active through awaited execution, retaining child-span parentage and the final result or error.

sdk/python/README.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Cancelled operations appear successful ✓ Resolved

Resolving commit: d006711

Resolution reason
traced_operation now catches asyncio.CancelledError alongside Exception, recording the exception and
setting ERROR status on the span before re-raising. The cancellation test was extended to assert
ERROR status and an exception event.
Description
traced_operation catches Exception, but the new await path can exit with
asyncio.CancelledError, which bypasses that handler. When a traced task is cancelled, its span
ends without a recorded exception or error status; the cancellation test checks only that it ended.

2. False results disappear from async traces ✓ Resolved

Resolving commit: d006711

Resolution reason
The output attribute now uses truncate_content(response) instead of response or "", so falsy
values such as False and 0 are exported as their string forms; regression tests cover False, 0,
dict, list, and None on both sync and async paths.
Description
async_wrapper uses response or "" when setting the output attribute, replacing valid results
such as False and 0 with an empty string. Any decorated coroutine returning one of those values
still gives its caller the correct result, while its exported span reports different output.

3. Structured async results lose trace output ✓ Resolved

Resolving commit: d006711

Resolution reason
The async wrapper now passes the response through truncate_content(response) (which uses the SDK's
string conversion and truncation) before setting GEN_AI_OUTPUT_MESSAGES, and only when content
capture is enabled. The sync wrapper got the same change. A new test asserts a dict result
({"booked": True}) is exported as "{'booked': True}", covering the nonempty-dictionary case the
finding raised.
Description
async_wrapper passes the awaited result directly to span.set_attribute without converting
mappings or response objects to an attribute-compatible value. When a decorated coroutine returns a
nonempty dictionary or model object, its output cannot be stored as written, unlike the stringified
structured output used by existing instrumentation.

View review recommended (1)
4. Failed async spans omit operation metadata ✓ Resolved

Resolving commit: d006711

Resolution reason
Moved the operation metadata assignments (args, kwargs, service name, environment) into a finally
block in traced_operation so they are set on exception paths too, and added test assertions that
failed async spans retain service.name and function.args.
Description
traced_operation sets arguments, service name and environment after its error handler, but that
handler re-raises before reaching those assignments. When the new async await raises an ordinary
exception, the exported error span lacks those attributes even though the error itself is recorded.

Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit d006711

#2016 Bug: @trace ends async function spans before the coroutine runs · 3 of 3 met

# Requirement Status Notes
1 Keep the manual span active until the coroutine completes ✅ Met The async wrapper opens the span when awaited and keeps it active through the awaited call.
2 Record the coroutine's resolved output and errors ✅ Met The wrapper records the resolved result and the shared span handling records and re-raises exceptions, including cancellation.
3 Retain parent/child relationships ✅ Met The coroutine executes inside the active span context; the tests cover nested and overlapping child spans.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread sdk/python/src/openlit/__init__.py Resolved
Comment thread sdk/python/src/openlit/__init__.py Resolved
Comment thread sdk/python/src/openlit/__init__.py Resolved
Comment thread sdk/python/src/openlit/__init__.py Resolved
Comment thread sdk/python/src/openlit/__init__.py Resolved
Comment thread sdk/python/src/openlit/__init__.py Resolved
Comment thread sdk/python/README.md Resolved
Comment thread sdk/python/README.md Resolved
@mintlify

mintlify Bot commented Nov 26, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit d006711.

Approve preview

This branch was successfully deployed

1 active (outdated) deployment
release-notes — d79cff30 Deployed Nov 25, 2026 by Twiink via Normalize / Conventional title #907
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: @trace ends async function spans before the coroutine runs

1 participant