fix(core): context preservation in shielded async callbacks#32163
Merged
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎ |
Co-authored-by: mdrxy <61371264+mdrxy@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] core/callbacks - context is not maintained when async callbacks get shielded
core/callbacks - fix context preservation in shielded async callbacks
Jul 22, 2025
CodSpeed Performance ReportMerging #32163 will not alter performanceComparing
|
CodSpeed Instrumentation Performance ReportMerging #32163 will not alter performanceComparing Summary
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
The
@shieldeddecorator in async callback managers was not preserving context variables, breaking OpenTelemetry instrumentation and other context-dependent functionality.Problem
When using async callbacks with the
@shieldeddecorator (applied to methods likeon_llm_end,on_chain_end, etc.), context variables were not being preserved across the shield boundary. This caused issues with:The issue was reproducible with:
Root Cause
The original
shieldeddecorator implementation:Used
asyncio.shield()directly without preserving the current execution context, causing context variables to be lost.Solution
Modified the
shieldeddecorator to:copy_context()asyncio.create_task(coro, context=ctx)for Python 3.11+Testing
test_shielded_callback_context_preservation()that validates context variables are preserved across shielded callback boundariesThe fix is minimal, maintains backward compatibility, and ensures proper context preservation for both modern Python versions and older ones.
Fixes #31398.
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.