-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Fix deadlock in atexit cleanup handlers #3031
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
base: main
Are you sure you want to change the base?
Conversation
@microsoft-github-policy-service agree |
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.