Fix deadlock in atexit cleanup handlers#3031
Open
rob0tics wants to merge 1 commit intomicrosoft:mainfrom
Open
Conversation
Author
@microsoft-github-policy-service agree |
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.
Fix deadlock in atexit cleanup handlers
Fixes #3004
Problem
When using
asyncio_atexitor similar libraries to register async cleanup handlers, Playwright hangs indefinitely during shutdown. The program never exits cleanly.Root Cause
When atexit handlers are registered, Python's atexit mechanism creates a new execution context at program termination. The
_stopped_futurein the Transport class is tied to the original event loop, but when atexit handlers run, they attempt to use this future in a different (or already-closed) event loop context. This causes a deadlock - the code tries toawaita future from a dead loop that cannot be resolved.Solution
The fix involves detecting when the event loop is closed or unavailable and handling shutdown gracefully:
wait_until_stopped()method: Check if the event loop is closed before awaiting the stopped future. If closed, return immediately since the OS will clean up the process.run()task: Catchasyncio.CancelledErrorwhen the event loop shuts down, allowing the message-reading loop to exit gracefully instead of crashing.Shutdown logic: Before attempting any async operations, verify that a running event loop exists. If not, send SIGTERM to the driver process and trust the OS to clean up child processes.
Instead of adding defensive timeouts or force-killing processes, the fix follows the Unix philosophy: trust the OS to clean up child processes. A graceful SIGTERM signal is sent, and the kernel handles process reaping.