-
Notifications
You must be signed in to change notification settings - Fork 20.1k
fix(core): prevent async task garbage collection (RUF006) #34238
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(core): prevent async task garbage collection (RUF006) #34238
Conversation
CodSpeed Performance ReportMerging #34238 will not alter performanceComparing
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR fixes a potential async task garbage collection issue (flagged by Ruff rule RUF006) in the retry decorator's callback handling. The fix introduces a module-level set to maintain strong references to fire-and-forget tasks, preventing them from being prematurely garbage collected during execution.
Key Changes:
- Introduced
_background_tasksset to hold strong references to running async tasks - Modified task creation in
_before_sleepto register tasks with the tracking set - Added cleanup callback using
add_done_callbackto prevent memory leaks
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _background_tasks: set[asyncio.Task] = set() |
Copilot
AI
Dec 8, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The type annotation for _background_tasks is incomplete. Since asyncio.Task is a generic type, it should include a type parameter. Consider using set[asyncio.Task[Any]] to properly type-hint the set of tasks with their return types.
Co-authored-by: Copilot <[email protected]>
PR Title: fix(core): prevent async task garbage collection (RUF006)
Description
This PR addresses a cryptic issue (flagged by Ruff rule RUF006) where
asynciotasks created vialoop.create_taskcould be garbage collected mid-execution because no strong reference was maintained.In
libs/core/langchain_core/language_models/llms.py, the retry decorator's_before_sleephook creates a fire-and-forget task for logging/callbacks. If the garbage collector runs before this task completes, the task may be destroyed, leading to silent failures.Changes
_background_tasksto hold strong references to running tasks._before_sleepto add new tasks to this set.done_callbackto remove the task from the set upon completion, preventing memory leaks.Verification
asynciodocumentation.Checklist