Skip to content

gh-146194: Fix nested KeyboardInterrupt handling in asyncio#146203

Open
okiemute04 wants to merge 5 commits intopython:mainfrom
okiemute04:fix-asyncio-nested-keyboardinterrupt
Open

gh-146194: Fix nested KeyboardInterrupt handling in asyncio#146203
okiemute04 wants to merge 5 commits intopython:mainfrom
okiemute04:fix-asyncio-nested-keyboardinterrupt

Conversation

@okiemute04
Copy link
Contributor

@okiemute04 okiemute04 commented Mar 20, 2026

Fixes #146194

Problem

When multiple Ctrl+C presses occurred in nested asyncio tasks, the
third press would cause a crash with "Task was destroyed but it is pending!"
instead of gracefully cancelling the nested tasks.

Solution

Modified _on_sigint in Lib/asyncio/runners.py to cancel the main task
on every SIGINT, allowing nested cancellations to propagate correctly
through multiple levels.

Testing

  • Added test_nested_keyboardinterrupt_handling to test_runners.py
  • Verified that multiple cancellations work correctly without crashes
  • All existing runner tests pass

- Modify _on_sigint to cancel main task on every SIGINT
- Allow nested cancellations to propagate correctly through multiple levels
- Add test_nested_keyboardinterrupt_handling to test_runners.py
- Add NEWS entry

Fixes issue where third Ctrl+C would crash with:
'Task was destroyed but it is pending!'
- Modify _on_sigint to cancel main task on every SIGINT
- Allow nested cancellations to propagate correctly through multiple levels
- Add test_nested_keyboardinterrupt_handling to test_runners.py
- Add NEWS entry

Fixes issue where third Ctrl+C would crash with:
'Task was destroyed but it is pending!'
@okiemute04 okiemute04 force-pushed the fix-asyncio-nested-keyboardinterrupt branch from bd97ffd to 5982498 Compare March 20, 2026 11:48
@okiemute04 okiemute04 force-pushed the fix-asyncio-nested-keyboardinterrupt branch from ce191ae to 2563ac4 Compare March 20, 2026 12:13
@aisk
Copy link
Member

aisk commented Mar 20, 2026

Hi, please don't force push, see yesterday's comment: #146179 (comment)

Comment on lines +1 to +4
.. gh-issue: 146194
.. section: Library
Copy link
Member

Choose a reason for hiding this comment

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

There are the same error as #146179

@okiemute04
Copy link
Contributor Author

okiemute04 commented Mar 20, 2026

@aisk thanks, I will not anymore. Noted, I was trying to fix the NEWS file issue. I will avoid force pushing going forward.

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.

Asyncio does not handle nested KeyboardInterrupt correctly

2 participants