Skip to content

fix(python-sdk): preserve using_attributes context in async decorators - #2010

Merged
AmanAgarwal041 merged 2 commits into
openlit:mainfrom
tomwangcn:fix/async-custom-attributes
Nov 29, 2026
Merged

AmanAgarwal041 merged 2 commits into
openlit:mainfrom
tomwangcn:fix/async-custom-attributes

Conversation

@tomwangcn

@tomwangcn tomwangcn commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2009

Problem

ContextDecorator enters and exits the attribute context while creating a coroutine, before the coroutine body runs. As a result, @using_attributes(...) on an async function loses the configured attributes, including those read by evaluation score events.

Change

  • Detect coroutine functions and await them inside the attribute context.
  • Recreate the context manager for each decorated call so overlapping tasks do not overwrite a shared reset token.
  • Keep the existing synchronous decorator path and preserve wrapped-function metadata.

Tests

Added five regression tests covering attributes across an await, return values and coroutine metadata, exception cleanup, overlapping calls with different caller contexts, synchronous behavior, and cancellation cleanup.

Before the fix: three async regressions failed and the synchronous test passed. After the fix: all five new tests and the 13 existing score tests pass (18 total), using Python 3.10 and the real local SDK imports. git diff --check passes. The full Python SDK suite was not run.

Summary by Sourcery

Preserve using_attributes context across asynchronous decorator execution and isolate concurrent calls.

Bug Fixes:

  • Preserve configured custom attributes throughout decorated asynchronous function execution, including across awaits, errors, and cancellation.
  • Prevent overlapping asynchronous decorated calls from interfering with one another’s attribute contexts.

Enhancements:

  • Retain coroutine metadata and support attribute-context subclasses with required constructor state while preserving existing synchronous decorator behavior.

Tests:

  • Add regression coverage for asynchronous attribute preservation, cleanup, overlapping calls, cancellation, metadata, subclass state, and synchronous compatibility.

@tomwangcn
tomwangcn requested review from a team and ishanjainn as code owners November 25, 2026 02:58
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Detect coroutine functions and run each async invocation inside a shallow-copied attribute context, while preserving the synchronous decorator path and subclass state.

  • sdk/python/src/openlit/__init__.py L8, L13, L903-919

Tests

Add regression coverage for async attribute propagation, metadata, cleanup, overlapping calls, subclass state, and synchronous behavior.

  • sdk/python/tests/test_using_attributes.py L1-125

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

Preserve custom attributes in async using_attributes decorators

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Keep custom attributes active while decorated async functions run, including across awaits.
• Isolate context tokens for overlapping calls and restore caller attributes after completion,
 errors, or cancellation.
• Add regressions for async behavior, concurrency, metadata, and unchanged synchronous behavior.
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 wrapper, ContextVar state, and span enrichment form one bounded SDK integration: a caller decorates a function, attributes are active during the invocation, and auto-instrumented spans consume the same context.
  • Synchronous and asynchronous entry points are distinct execution modes of this same user-visible capability, not independent functional scopes.
  • The propagation path is directly from the changed decorator to this end-to-end behavior.
Sources

sdk/python/src/openlit/init.py[903-912]

    def __call__(self, func):
        if iscoroutinefunction(func):

            @wraps(func)
            async def async_wrapper(*args, **kwargs):
                with self._recreate_cm():
                    return await func(*args, **kwargs)

            return async_wrapper
        return super().__call__(func)

sdk/python/src/openlit/init.py[914-918]

    def _recreate_cm(self):
        # Keep subclass state without assuming its constructor signature.
        context = copy(self)
        context._token = None
        return context
Behavioral complexity 🔴 High 🧩 Interacting branches, Concurrent ordering

  • Before: ContextDecorator used one decorator/context-manager object and its mutable token state, and the added async path did not exist.
  • After: asynchronous functions take a separate copied context-manager instance per invocation, while synchronous functions also resolve recreation through the updated _recreate_cm method; subclass attributes must survive copying and each invocation must reset its own ContextVar token.
  • New correctness condition for interacting branches/states: both synchronous and asynchronous decorator paths must preserve the intended attributes and restore the caller's prior context across normal return, exceptions, and cancellation.
  • New correctness condition for concurrency/ordering: overlapping asynchronous invocations must not overwrite one another's token or restore contexts in the wrong order.
  • The implementation relies on the established ContextVar set/reset mechanism, but the per-call copy and async wrapper introduce the new invocation-isolation and lifecycle interaction.
Sources

sdk/python/src/openlit/init.py[903-912]

    def __call__(self, func):
        if iscoroutinefunction(func):

            @wraps(func)
            async def async_wrapper(*args, **kwargs):
                with self._recreate_cm():
                    return await func(*args, **kwargs)

            return async_wrapper
        return super().__call__(func)

sdk/python/src/openlit/init.py[914-918]

    def _recreate_cm(self):
        # Keep subclass state without assuming its constructor signature.
        context = copy(self)
        context._token = None
        return context
Potential damage 🟡 Medium 🩹 Recoverable

  • If the changed behavior regresses, decorated calls can emit spans with missing, stale, or incorrectly scoped custom attributes, reducing telemetry correctness for the affected calls.
  • The consequence is limited to observability enrichment; no source evidence indicates that these attributes control the user's underlying LLM, agent, or application operation.
  • Future behavior can be restored by reverting or correcting the SDK code.
  • Already-emitted telemetry cannot generally be repaired by code rollback, although the underlying application operation remains available.
  • Code rollback or SDK upgrade restores behavior for future invocations.
  • Previously emitted spans with incorrect or missing attributes remain incorrect unless the telemetry backend supports a separate manual correction; no automatic state repair or external-effect compensation path is evidenced.
Sources

sdk/python/src/openlit/init.py[903-912]

    def __call__(self, func):
        if iscoroutinefunction(func):

            @wraps(func)
            async def async_wrapper(*args, **kwargs):
                with self._recreate_cm():
                    return await func(*args, **kwargs)

            return async_wrapper
        return super().__call__(func)
Assessed commit 7278e5d
Diagram

graph TD
  A["Decorated call"] --> B{"Coroutine function?"}
  B -->|async| C["Fresh context"] --> D["Await body"] --> E["Reset token"] --> G["Caller attributes"]
  B -->|sync| F["Base decorator"] --> E
Loading
High-Level Assessment

Keep the targeted async wrapper and per-call context manager. They address coroutine timing and overlapping-token safety while retaining the established synchronous path; replacing the decorator abstraction would add scope without a clear benefit.

Files changed (2) +113 / -0

Bug fix (1) +16 / -0
__init__.pyKeep attribute context active throughout async decorated calls +16/-0

Keep attribute context active throughout async decorated calls

• Adds a coroutine-aware wrapper that awaits the function inside a fresh attribute context, so each call has its own reset token. Synchronous functions continue through ContextDecorator, and the async wrapper preserves function metadata.

sdk/python/src/openlit/init.py

Tests (1) +97 / -0
test_using_attributes.pyCover async attribute lifetime and context restoration +97/-0

Cover async attribute lifetime and context restoration

• Adds five regression tests for attributes across awaits, return values and metadata, error and cancellation cleanup, overlapping calls, and synchronous behavior.

sdk/python/tests/test_using_attributes.py

@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. Subclassed decorators fail on calls ✓ Resolved
Description
_recreate_cm() reconstructs a using_attributes subclass with only self._attributes, discarding
any additional constructor arguments it requires. A subclass that previously worked as a synchronous
decorator now raises TypeError when its decorated function is called, and the new async path has
the same failure.

Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

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 7278e5d

#2009 Bug: using_attributes loses span attributes in async functions · 2 of 2 met

# Requirement Status Notes
1 Keep configured attributes available throughout a decorated async function, including after an await and on score events. ✅ Met The async wrapper awaits the function inside the recreated attribute context; score events read the active context attributes.
2 Restore the caller's previous attributes when the async function exits. ✅ Met Exiting the context resets its ContextVar token, including when the function raises or is cancelled.

@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 2 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="903" />
<code_context>
         self._token = None

+    def __call__(self, func):
+        if iscoroutinefunction(func):
+
+            @wraps(func)
</code_context>
<issue_to_address>
**Async work loses attributes**

When the decorated target is an async generator, an async callable, or a synchronous callable returning an awaitable, `iscoroutinefunction` sends only recognized coroutine functions through `async_wrapper`; otherwise, `super().__call__` exits the attribute context before the returned generator or awaitable executes, so instrumentation misses the configured attributes.

Keep the attribute context active while returned generators and awaitables execute, including those from callable instances and synchronous wrappers.

Also at `sdk/python/src/openlit/__init__.py:911`.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/__init__.py" line_range="915" />
<code_context>
+
+    def _recreate_cm(self):
+        # Each decorated call needs its own context token, including overlapping tasks.
+        return type(self)(self._attributes)
+
     def __enter__(self):
</code_context>
<issue_to_address>
**Subclass decorators fail before calls**

When a `using_attributes` subclass requires constructor arguments or state beyond `_attributes` and inherits `_recreate_cm`, `_recreate_cm` calls `type(self)(self._attributes)`, so construction raises `TypeError` or recreated instances lose subclass state, and decorated calls fail or run without that state.

Provide an overridable recreation path that preserves each subclass’s required constructor arguments and state.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: sdk/python/src/openlit/__init__.py:903, sdk/python/src/openlit/__init__.py:915


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

self._token = None

def __call__(self, func):
if iscoroutinefunction(func):

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.

🟡 Medium · Async work loses attributes

When the decorated target is an async generator, an async callable, or a synchronous callable returning an awaitable, iscoroutinefunction sends only recognized coroutine functions through async_wrapper; otherwise, super().__call__ exits the attribute context before the returned generator or awaitable executes, so instrumentation misses the configured attributes.

Keep the attribute context active while returned generators and awaitables execute, including those from callable instances and synchronous wrappers.

Also at sdk/python/src/openlit/__init__.py:911.

Prompt for AI agents
In `sdk/python/src/openlit/__init__.py` at line 903:

**Async work loses attributes**

When the decorated target is an async generator, an async callable, or a synchronous callable returning an awaitable, `iscoroutinefunction` sends only recognized coroutine functions through `async_wrapper`; otherwise, `super().__call__` exits the attribute context before the returned generator or awaitable executes, so instrumentation misses the configured attributes.

Keep the attribute context active while returned generators and awaitables execute, including those from callable instances and synchronous wrappers.

Also at `sdk/python/src/openlit/__init__.py:911`.

Comment thread sdk/python/src/openlit/__init__.py Resolved
@tomwangcn

Copy link
Copy Markdown
Contributor Author

The subclass regression is valid. Added sync and async tests with a required extra constructor argument; both failed on the first commit. Context recreation now shallow-copies the instance and clears its reset token instead of calling the subclass constructor. All seven decorator tests plus 13 existing score tests pass (20 total).

The other finding concerns async generators, callable instances, and synchronous functions returning awaitables. Those were not supported by the original ContextDecorator path either. This PR is scoped to the reported async-def regression in #2009 and preserves the synchronous path. Supporting all lazy return types would need separate lifecycle and generator-close tests, so I have left that broader change out of this fix.

@AmanAgarwal041
AmanAgarwal041 merged commit 3fc2242 into openlit:main Nov 29, 2026
4 of 5 checks passed
@github-actions

Copy link
Copy Markdown

Merged PR summary

  • Python SDK · Fixes — Preserves using_attributes context across async decorator execution, including awaits, errors, and cancellation, and isolates overlapping calls.

Generated from the merged PR description and bounded, component-scoped file evidence. Release preparation reuses this validated summary.

This branch was successfully deployed

1 active deployment
release-notes — 7278e5d0 Deployed Nov 29, 2026 by AmanAgarwal041 via Summarize / Merged pull request #359
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: using_attributes loses span attributes in async functions

2 participants