René's URL Explorer Experiment


Title: asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task running · Issue #105836 · python/cpython · GitHub

Open Graph Title: asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task running · Issue #105836 · python/cpython

X Title: asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task running · Issue #105836 · python/cpython

Description: Bug report When an asyncio task is created from another thread via asyncio.run_coroutine_threadsafe, a concurrent.futures.Future is returned, which wraps an underlying asyncio.Task. In a typical use future.result() or future.exception() ...

Open Graph Description: Bug report When an asyncio task is created from another thread via asyncio.run_coroutine_threadsafe, a concurrent.futures.Future is returned, which wraps an underlying asyncio.Task. In a typical us...

X Description: Bug report When an asyncio task is created from another thread via asyncio.run_coroutine_threadsafe, a concurrent.futures.Future is returned, which wraps an underlying asyncio.Task. In a typical us...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task running","articleBody":"# Bug report\r\n\r\nWhen an `asyncio` task is created from another thread via `asyncio.run_coroutine_threadsafe`, a `concurrent.futures.Future` is returned, which wraps an underlying `asyncio.Task`. \r\n\r\nIn a typical use `future.result()` or `future.exception()` can be used to wait for completion. However, when the returned future is cancelled, no built-in mechanism is provided to wait for the underlying `asyncio` task to complete, leaving it running when application is terminated, possibly accessing dangling data.\r\n\r\nThis is an example that reproduces what is described above. There's no way to make it smaller without losing some aspect of what's going on.\r\n\r\nThe output of this code is as follows:\r\n```\r\nAbout to create an asyncio task\r\nasyncio task is set up\r\nasyncio task is running\r\nTask cancelled (callback)\r\nCancelled?: True\r\nDone?: True\r\nCannot access task.result()\r\nCannot access task.exception()\r\nAll done. No app code should run after this.\r\nasyncio task is cancelled; rethrowing...   \u003c-- runs after the app is shut down\r\nSetting the asyncio task event             \u003c-- same\r\n```\r\nPerhaps `concurrent.futures.Future.cancelled()` should have a timeout to wait for the underlying `asyncio` task to complete or some additional method provided for that.\r\n\r\nHere's the sample code.\r\n```python\r\nimport asyncio\r\nimport concurrent.futures\r\nimport threading\r\n\r\nclass MyApp:\r\n    def __init__(self) -\u003e None:\r\n        self.task: concurrent.futures.Future[int]|None = None\r\n\r\n        self.task_event = asyncio.Event()\r\n        self.task_event.clear()\r\n\r\n    # An asyncio task that runs in the specified event loop\r\n    async def process_task(self) -\u003e int:\r\n        try:\r\n            self.task_event.clear()\r\n            print(\"asyncio task is running\")\r\n            await asyncio.sleep(10)\r\n            print(\"asyncio task is finished\")\r\n            return 123\r\n        except asyncio.CancelledError:\r\n            print(\"asyncio task is cancelled; rethrowing...\")\r\n            raise\r\n        finally:\r\n            print(\"Setting the asyncio task event\")\r\n            self.task_event.set()\r\n\r\n    # Called immediately from task.cancel(), before the underlying\r\n    # asyncio task completes.\r\n    def task_done(self, future: concurrent.futures.Future[int]) -\u003e None:\r\n        if future.cancelled():\r\n            print(\"Task cancelled (callback)\")\r\n        elif future.exception() is not None:\r\n            print(\"Task error %s (callback)\" % future.exception())\r\n        else:\r\n            print(\"Task is done with result %d (callback)\" % future.result())\r\n\r\n    def start_async_task(self, thread_event: threading.Event) -\u003e None:\r\n\r\n        print(\"About to create an asyncio task\")\r\n\r\n        self.task = asyncio.run_coroutine_threadsafe(self.process_task(), asyncio.get_running_loop())\r\n        self.task.add_done_callback(self.task_done)\r\n\r\n        print(\"asyncio task is set up\")\r\n        thread_event.set()\r\n\r\n    # This method is supposed to be the last call to the application,\r\n    # which shuts down all services and cancels all outstanding work.\r\n    async def shutdown(self) -\u003e None:\r\n\r\n        # Calls the done callback immediately and returns before the\r\n        # future cancels the underlying asyncio task, rendering the\r\n        # future unusable via standard methods.\r\n        self.task.cancel()\r\n\r\n        # This event compensates for lack of ability to wait for the\r\n        # underlying asyncio task. Without this wait, asyncio task\r\n        # runs after the code that manages all this is gone.\r\n        #\r\n        # Perhaps Future.cancel() should provide this functionality?\r\n        #\r\n        #print(\"Waiting for a task to complete\")\r\n        #await self.task_event.wait()\r\n\r\n        # returns True, while underlying asyncio task is still running\r\n        print(\"Cancelled?: %s\" % self.task.cancelled())\r\n        print(\"Done?: %s\" % self.task.done())\r\n\r\n        # supposed to wait for result, but because it's cancelled, will throw\r\n        try:\r\n            print(\"Result?: %d\" % self.task.result())\r\n        except concurrent.futures.CancelledError:\r\n            print(\"Cannot access task.result()\")\r\n\r\n        # or wait for exception, but because it's cancelled, will throw as well\r\n        try:\r\n            print(\"Exception?: %s\" % str(self.task.exception()))\r\n        except concurrent.futures.CancelledError:\r\n            print(\"Cannot access task.exception()\")\r\n\r\nasync def main() -\u003e None:\r\n    myapp = MyApp()\r\n\r\n    thread_event = threading.Event()\r\n    thread_event.clear()\r\n\r\n    # emulates some worker thread (e.g. APScheduler)\r\n    runner = threading.Thread(target=myapp.start_async_task, args=[thread_event])\r\n    runner.run()\r\n\r\n    thread_event.wait()\r\n\r\n    await asyncio.sleep(1)\r\n\r\n    await myapp.shutdown()\r\n\r\n    await asyncio.sleep(0)\r\n\r\n    print(\"All done. No app code should run after this.\")\r\n\r\nasyncio.run(main())\r\n```\r\nIf the `wait` call under _Waiting for a task to complete_ is uncommented, which would simulate having waiting implemented in `Future.cancelled()`, it would work as expected.\r\n\r\n# Your environment\r\n\r\n- CPython versions tested on: 3.10.10\r\n- Operating system and architecture: Microsoft Windows \\[Version 10.0.19045.3086\\]\r\n\r\n\n\n\u003c!-- gh-linked-prs --\u003e\n### Linked PRs\n* gh-141696\n* gh-142358\n* gh-142359\n\u003c!-- /gh-linked-prs --\u003e\n","author":{"url":"https://github.com/gh-andre","@type":"Person","name":"gh-andre"},"datePublished":"2023-06-15T19:53:27.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":14},"url":"https://github.com/105836/cpython/issues/105836"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:fb24a906-2076-c2d3-bb67-1783774bbfc3
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id8DE8:31608E:8946CA2:B722B25:696E1683
html-safe-nonced8ca1312d20c58a2b99fb4147dad6c92d18bf35ef5b5c8a7c476d8ba6e0cb5e9
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4REU4OjMxNjA4RTo4OTQ2Q0EyOkI3MjJCMjU6Njk2RTE2ODMiLCJ2aXNpdG9yX2lkIjoiODUxOTE3NjgzNzIyMzI5MDQ5OSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac1d40f48d0c86eee7fad62d68c53d64b4061747602ef58f25c6481cd699102315
hovercard-subject-tagissue:1759461818
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/105836/issue_layout
twitter:imagehttps://opengraph.githubassets.com/a4d7ac18fd6077318b48b22c509dec992b4955007cb1b5f93b933bc35dfdff0f/python/cpython/issues/105836
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/a4d7ac18fd6077318b48b22c509dec992b4955007cb1b5f93b933bc35dfdff0f/python/cpython/issues/105836
og:image:altBug report When an asyncio task is created from another thread via asyncio.run_coroutine_threadsafe, a concurrent.futures.Future is returned, which wraps an underlying asyncio.Task. In a typical us...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamegh-andre
hostnamegithub.com
expected-hostnamegithub.com
None1a7d6d739bf034e67486b9f97a31887ca30302b72a0acac49b6bcddff34356d7
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
release87d7872ec7094ed247923539669aabda9230966f
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/issues/105836#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F105836
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%2F105836
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/105836
Reloadhttps://github.com/python/cpython/issues/105836
Reloadhttps://github.com/python/cpython/issues/105836
python https://github.com/python
cpythonhttps://github.com/python/cpython
Please reload this pagehttps://github.com/python/cpython/issues/105836
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/105836
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/105836
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/105836
asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task runninghttps://github.com/python/cpython/issues/105836#top
https://github.com/gvanrossum
stdlibStandard Library Python modules in the Lib/ directoryhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
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/gh-andre
https://github.com/gh-andre
gh-andrehttps://github.com/gh-andre
on Jun 15, 2023https://github.com/python/cpython/issues/105836#issue-1759461818
gh-105836: Fix asyncio.run_coroutine_threadsafe leaving underlying cancelled asyncio task running #141696https://github.com/python/cpython/pull/141696
[3.14] gh-105836: Fix asyncio.run_coroutine_threadsafe leaving underlying cancelled asyncio task running (GH-141696) #142358https://github.com/python/cpython/pull/142358
[3.13] gh-105836: Fix asyncio.run_coroutine_threadsafe leaving underlying cancelled asyncio task running (GH-141696) #142359https://github.com/python/cpython/pull/142359
gvanrossumhttps://github.com/gvanrossum
stdlibStandard Library Python modules in the Lib/ directoryhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
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.