Skip to content

fix memory leak of cancelled timeout tasks#3077

Merged
dpkp merged 2 commits into
dpkp:masterfrom
azdobylak:fix-memory-leak
Jun 18, 2026
Merged

fix memory leak of cancelled timeout tasks#3077
dpkp merged 2 commits into
dpkp:masterfrom
azdobylak:fix-memory-leak

Conversation

@azdobylak

Copy link
Copy Markdown
Contributor

Issue

The issue is already described in #3076. Cancelled/unscheduled tasks were not garbage collected due to strong reference kept in _pending_tasks. Tasks were only removed from _pending_tasks on completion in _poll_once, so unschedule() left them pinned by that strong reference (with their underlying coroutines left unclosed).
To confirm that issue exists and is resolved by this PR I am attaching memray screenshots. Leaking version is kafka-python==3.0.0.
leak
fixed

Fix Approach:

This PR introduces _retire_task to drop the strong reference from _pending_tasks and explicitly closes the coroutine stack on cancellation/shutdown to release the frame's local variables.

@dpkp

dpkp commented Jun 18, 2026

Copy link
Copy Markdown
Owner

Thanks!

@dpkp dpkp merged commit a4a344d into dpkp:master Jun 18, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants