René's URL Explorer Experiment


Title: `BaseSubprocessTransport.__del__` fails if the event loop is already closed, which can leak an orphan process · Issue #114177 · python/cpython · GitHub

Open Graph Title: `BaseSubprocessTransport.__del__` fails if the event loop is already closed, which can leak an orphan process · Issue #114177 · python/cpython

X Title: `BaseSubprocessTransport.__del__` fails if the event loop is already closed, which can leak an orphan process · Issue #114177 · python/cpython

Description: Bug report Bug description: there is a race where it's possible for BaseSubprocessTransport.__del__ to try to close the transport after the event loop has been closed. this results in an unraisable exception in __del__, and it can also r...

Open Graph Description: Bug report Bug description: there is a race where it's possible for BaseSubprocessTransport.__del__ to try to close the transport after the event loop has been closed. this results in an unraisable...

X Description: Bug report Bug description: there is a race where it's possible for BaseSubprocessTransport.__del__ to try to close the transport after the event loop has been closed. this results in an unrais...

Opengraph URL: https://github.com/python/cpython/issues/114177

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`BaseSubprocessTransport.__del__` fails if the event loop is already closed, which can leak an orphan process","articleBody":"# Bug report\n\n### Bug description:\n\nthere is a race where it's possible for `BaseSubprocessTransport.__del__` to try to close the transport *after* the event loop has been closed. this results in an unraisable exception in `__del__`, and it can also result in an orphan process being leaked.\n\nthe following is a reproducer that triggers the race between `run()` exiting and [the process dying and the event loop learning about the process's death]. on my machine, with this reproducer the bug occurs (due to `run()` winning the race) maybe 90% of the time:\n\n```python\nfrom __future__ import annotations\n\nimport asyncio\nfrom subprocess import PIPE\n\n\nasync def main() -\u003e None:\n    try:\n        async with asyncio.timeout(1):\n            process = await asyncio.create_subprocess_exec(\n                \"/usr/bin/env\",\n                \"sh\",\n                \"-c\",\n                \"while true; do sleep 1; done\",\n                stdin=PIPE,\n                stdout=PIPE,\n                stderr=PIPE,\n            )\n            try:\n                await process.wait()\n            except BaseException:\n                process.kill()\n                # N.B.: even though they send it SIGKILL, the user is (very briefly)\n                # leaking an orphan process to asyncio, because they are not waiting for\n                # the event loop to learn that the process died. if we added\n                # while True:\n                #     try:\n                #         await process.wait()\n                #     except CancelledError:\n                #         pass\n                #     else:\n                #         break\n                # (i.e. if we used structured concurrency) then the race would not\n                # occur.\n                raise\n    except TimeoutError:\n        pass\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\nmost of the time, running this emits\n\n```\nException ignored in: \u003cfunction BaseSubprocessTransport.__del__ at 0x7fd25db428e0\u003e\nTraceback (most recent call last):\n    File \"/usr/lib/python3.11/asyncio/base_subprocess.py\", line 126, in __del__\n    self.close()\n    File \"/usr/lib/python3.11/asyncio/base_subprocess.py\", line 104, in close\n    proto.pipe.close()\n    File \"/usr/lib/python3.11/asyncio/unix_events.py\", line 566, in close\n    self._close(None)\n    File \"/usr/lib/python3.11/asyncio/unix_events.py\", line 590, in _close\n    self._loop.call_soon(self._call_connection_lost, exc)\n    File \"/usr/lib/python3.11/asyncio/base_events.py\", line 761, in call_soon\n    self._check_closed()\n    File \"/usr/lib/python3.11/asyncio/base_events.py\", line 519, in _check_closed\n    raise RuntimeError('Event loop is closed')\nRuntimeError: Event loop is closed\n```\n\nthis case looks similar to GH-109538. i think the following patch (analogous to GH-111983) fixes it:\n\n```diff\ndiff --git a/Lib/asyncio/base_subprocess.py b/Lib/asyncio/base_subprocess.py\nindex 6dbde2b696..ba219ba39d 100644\n--- a/Lib/asyncio/base_subprocess.py\n+++ b/Lib/asyncio/base_subprocess.py\n@@ -123,8 +123,11 @@ def close(self):\n\n     def __del__(self, _warn=warnings.warn):\n         if not self._closed:\n-            _warn(f\"unclosed transport {self!r}\", ResourceWarning, source=self)\n-            self.close()\n+            if self._loop.is_closed():\n+                _warn(\"loop is closed\", ResourceWarning, source=self)\n+            else:\n+                _warn(f\"unclosed transport {self!r}\", ResourceWarning, source=self)\n+                self.close()\n\n     def get_pid(self):\n         return self._pid\n```\n\nhowever, there is another case for which the above patch is not sufficient. in the above example the user orphaned the process after sending `SIGKILL`/`TerminateProcess` (which is not immediate, but only schedules the kill), but what if they fully orphan it?\n\n```python\nfrom __future__ import annotations\n\nimport asyncio\nfrom subprocess import PIPE\n\n\nasync def main_leak_subprocess() -\u003e None:\n    await asyncio.create_subprocess_exec(\n        \"/usr/bin/env\",\n        \"sh\",\n        \"-c\",\n        \"while true; do sleep 1; done\",\n        stdin=PIPE,\n        stdout=PIPE,\n        stderr=PIPE,\n    )\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main_leak_subprocess())\n```\n\ncurrently (on `main`), when the race condition occurs (for this example the condition is `run()` winning the race against `BaseSubprocessTransport` GC) then asyncio emits a loud complaint `Exception ignored in: \u003cfunction BaseSubprocessTransport.__del__ at 0x7f5b3b291e40\u003e` and leaks the orphan process (check `htop` after the interpreter exits!). asyncio probably also leaks the pipes.\n\nbut with the patch above, asyncio will quietly leak the orphan process (and probably pipes), but it will not yell about the leak unless the user enables `ResourceWarning`s. which is not good.\n\nso a more correct patch (fixes both cases) may be something along the lines of\n\n```diff\ndiff --git a/Lib/asyncio/base_subprocess.py b/Lib/asyncio/base_subprocess.py\nindex 6dbde2b696..9c86c8444c 100644\n--- a/Lib/asyncio/base_subprocess.py\n+++ b/Lib/asyncio/base_subprocess.py\n@@ -123,8 +123,31 @@ def close(self):\n\n     def __del__(self, _warn=warnings.warn):\n         if not self._closed:\n-            _warn(f\"unclosed transport {self!r}\", ResourceWarning, source=self)\n-            self.close()\n+            if not self._loop.is_closed():\n+                _warn(f\"unclosed transport {self!r}\", ResourceWarning, source=self)\n+                self.close()\n+            else:\n+                _warn(\"loop is closed\", ResourceWarning, source=self)\n+\n+                # self.close() requires the event loop to be open, so we need to reach\n+                # into close() and its dependencies and manually do the bare-minimum\n+                # cleanup that they'd do if the loop was open. I.e. we do the syscalls\n+                # only; we can't interact with an event loop.\n+\n+                # TODO: Probably need some more stuff here too so that we don't leak fd's...\n+\n+                if (self._proc is not None and\n+                        # has the child process finished?\n+                        self._returncode is None and\n+                        # the child process has finished, but the\n+                        # transport hasn't been notified yet?\n+                        self._proc.poll() is None):\n+\n+                    try:\n+                        self._proc.kill()\n+                    except (ProcessLookupError, PermissionError):\n+                        # the process may have already exited or may be running setuid\n+                        pass\n\n     def get_pid(self):\n         return self._pid\n```\n\nwith this patch applied, neither example leaks an orphan process out of `run()`, and both examples emit `ResourceWarning`. however this patch is rather messy. it is also perhaps still leaking pipe fd's out of `run()`. (the fd's probably get closed by the OS when the interpreter shuts down, but i suspect one end of each pipe will be an orphan from the time when `run()` exits to the time when the interpreter shuts down, which can be arbitrarily long).\n\n### CPython versions tested on:\n\n3.11, CPython main branch\n\n### Operating systems tested on:\n\nLinux\n\n\u003c!-- gh-linked-prs --\u003e\n### Linked PRs\n* gh-134508\n* gh-134561\n* gh-134562\n\u003c!-- /gh-linked-prs --\u003e\n","author":{"url":"https://github.com/gschaffner","@type":"Person","name":"gschaffner"},"datePublished":"2024-01-17T08:08:30.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":6},"url":"https://github.com/114177/cpython/issues/114177"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:10f8d6df-7ec7-8476-b622-15be3318d4e4
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idC9C8:1D772C:22B6C1F:2DD4F5E:696B156F
html-safe-nonceef10d716b0943003405acfdd39e0883a6431908ae0e3be6b2e72071fa0804a12
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDOUM4OjFENzcyQzoyMkI2QzFGOjJERDRGNUU6Njk2QjE1NkYiLCJ2aXNpdG9yX2lkIjoiNDI3NjczNjIyMjQ1NDAyNzYzMSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmacf9bb2d7dacbf98453e69e71239be86163701f1a83dd3cacef626cc124c24ee44
hovercard-subject-tagissue:2085638107
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/114177/issue_layout
twitter:imagehttps://opengraph.githubassets.com/436851f8416f2282f045839dca69c838e99b28d3f3561702b12b3f7b0a274e02/python/cpython/issues/114177
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/436851f8416f2282f045839dca69c838e99b28d3f3561702b12b3f7b0a274e02/python/cpython/issues/114177
og:image:altBug report Bug description: there is a race where it's possible for BaseSubprocessTransport.__del__ to try to close the transport after the event loop has been closed. this results in an unraisable...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamegschaffner
hostnamegithub.com
expected-hostnamegithub.com
None5f99f7c1d70f01da5b93e5ca90303359738944d8ab470e396496262c66e60b8d
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release82560a55c6b2054555076f46e683151ee28a19bc
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/issues/114177#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F114177
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub SparkBuild and deploy intelligent appshttps://github.com/features/spark
GitHub ModelsManage and compare promptshttps://github.com/features/models
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F114177
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/114177
Reloadhttps://github.com/python/cpython/issues/114177
Reloadhttps://github.com/python/cpython/issues/114177
python https://github.com/python
cpythonhttps://github.com/python/cpython
Please reload this pagehttps://github.com/python/cpython/issues/114177
Notifications https://github.com/login?return_to=%2Fpython%2Fcpython
Fork 33.9k https://github.com/login?return_to=%2Fpython%2Fcpython
Star 71.1k https://github.com/login?return_to=%2Fpython%2Fcpython
Code https://github.com/python/cpython
Issues 5k+ https://github.com/python/cpython/issues
Pull requests 2.1k https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects 31 https://github.com/python/cpython/projects
Security Uh oh! There was an error while loading. Please reload this page. https://github.com/python/cpython/security
Please reload this pagehttps://github.com/python/cpython/issues/114177
Insights https://github.com/python/cpython/pulse
Code https://github.com/python/cpython
Issues https://github.com/python/cpython/issues
Pull requests https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects https://github.com/python/cpython/projects
Security https://github.com/python/cpython/security
Insights https://github.com/python/cpython/pulse
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/114177
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/114177
BaseSubprocessTransport.__del__ fails if the event loop is already closed, which can leak an orphan processhttps://github.com/python/cpython/issues/114177#top
topic-asynciohttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-asyncio%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/gschaffner
https://github.com/gschaffner
gschaffnerhttps://github.com/gschaffner
on Jan 17, 2024https://github.com/python/cpython/issues/114177#issue-2085638107
GH-109538https://github.com/python/cpython/issues/109538
GH-111983https://github.com/python/cpython/pull/111983
gh-114177: avoid calling connection lost callbacks when loop is already closed in asyncio subprocess #134508https://github.com/python/cpython/pull/134508
[3.14] gh-114177: avoid calling connection lost callbacks when loop is already closed in asyncio subprocess (GH-134508) #134561https://github.com/python/cpython/pull/134561
[3.13] gh-114177: avoid calling connection lost callbacks when loop is already closed in asyncio subprocess (GH-134508) #134562https://github.com/python/cpython/pull/134562
topic-asynciohttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-asyncio%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
asynciohttps://github.com/orgs/python/projects/29
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.