René's URL Explorer Experiment


Title: AsyncIO thread-safety issue in Python 3.14's free-threading · Issue #159449 · python/cpython · GitHub

Open Graph Title: AsyncIO thread-safety issue in Python 3.14's free-threading · Issue #159449 · python/cpython

X Title: AsyncIO thread-safety issue in Python 3.14's free-threading · Issue #159449 · python/cpython

Description: Bug report When a short-lived thread exits while some of its async tasks are still unfinished, Python moves those leftover tasks onto a shared global list; however, because Linux reuses the OS thread IDs of exited threads for newly creat...

Open Graph Description: Bug report When a short-lived thread exits while some of its async tasks are still unfinished, Python moves those leftover tasks onto a shared global list; however, because Linux reuses the OS thre...

X Description: Bug report When a short-lived thread exits while some of its async tasks are still unfinished, Python moves those leftover tasks onto a shared global list; however, because Linux reuses the OS thre...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"AsyncIO thread-safety issue in Python 3.14's free-threading","articleBody":"### Bug report\n\n When a short-lived thread exits while some of its async tasks are still unfinished, Python moves those leftover tasks onto a shared global list; however, because Linux reuses the OS thread IDs of exited threads for newly created threads, a later thread can be mistaken for the original creator of those tasks and remove them from the shared list without locking, which corrupts the list and causes the next thread cleaning up after an async run to segfault.\n\nFound and fixed by a colleague.\n\nReproducer:\n\n```\n\"\"\"Reproduces a free-threaded CPython 3.14 SIGSEGV in `_asyncio_all_tasks`.\n\nSpawner threads repeatedly start a short-lived worker thread that cancels the\nasyncio Tasks left behind by its predecessor, creates a new batch of pending\nTasks, and exits. When a thread exits with pending Tasks, PyThreadState_Clear()\nmoves them onto the interpreter-wide `interp->asyncio_tasks_head` list. glibc\nhands the exited thread's pthread_t to the next thread, so the successor has the\nsame `_Py_ThreadId()` as the creator of those Tasks. unregister_task() then\ntakes\nits lock-free fast path and unlinks them from the shared list without stopping\nthe world, and concurrent unlinks corrupt the list.\n\nRunner threads call asyncio.run(). Its shutdown calls asyncio.all_tasks() after\nthe loop stopped running, which takes the stop-the-world slow path in\n_asyncio_all_tasks() and walks the corrupted list until it dereferences NULL.\n\nIf the runtime is not affected, the binary runs for --duration_secs and exits 0.\n\"\"\"\n\nimport asyncio\nimport collections\nfrom collections.abc import Sequence\nimport sys\nimport sysconfig\nimport threading\nfrom typing import Any\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\n_DURATION_SECS = flags.DEFINE_float(\n    \"duration_secs\", 30.0, \"How long to run before declaring a pass.\"\n)\n_SPAWNER_THREADS = flags.DEFINE_integer(\n    \"spawner_threads\", 6, \"Threads that churn short-lived Task-owning threads.\"\n)\n_RUNNER_THREADS = flags.DEFINE_integer(\n    \"runner_threads\", 2, \"Threads that call asyncio.run() in a loop.\"\n)\n_TASKS_PER_THREAD = flags.DEFINE_integer(\n    \"tasks_per_thread\", 32, \"Pending Tasks each short-lived thread leaves.\"\n)\n\n_TaskBatch = list[asyncio.Task[Any]]\n\n\nclass _InertLoop:\n  \"\"\"Minimal event loop stand-in for constructing `asyncio.Task` objects.\n\n  `call_soon` drops the Task's first step, so a Task stays pending without a\n  real event loop holding a reference to it or opening file descriptors.\n  \"\"\"\n\n  def get_debug(self) -> bool:\n    return False\n\n  def call_soon(self, *args: object, **kwargs: object) -> None:\n    del args, kwargs  # Unused.\n\n\n_INERT_LOOP = _InertLoop()\n\n# Keeps recently cancelled Tasks alive so their memory is not reused while a\n# corrupted list may still point at them. This turns a nondeterministic\n# use-after-free into the deterministic NULL dereference seen in production.\n_RECENTLY_CANCELLED: collections.deque[_TaskBatch] = collections.deque(\n    maxlen=4096\n)\n\n\nasync def _noop() -> None:\n  pass\n\n\ndef _create_pending_tasks(count: int) -> _TaskBatch:\n  \"\"\"Creates `count` Tasks that stay pending until they are cancelled.\"\"\"\n  tasks = []\n  for _ in range(count):\n    coro = _noop()\n    task = asyncio.Task(coro, loop=_INERT_LOOP)  # type: ignore[arg-type]\n    # The Task never runs: close its coroutine to avoid \"never awaited\", and do\n    # not warn about Tasks that are still pending when the process exits.\n    coro.close()\n    setattr(task, \"_log_destroy_pending\", False)\n    tasks.append(task)\n  return tasks\n\n\ndef _short_lived_worker(\n    handoff: list[_TaskBatch], tasks_per_thread: int\n) -> None:\n  \"\"\"Cancels the predecessor's Tasks, then exits leaving new pending Tasks.\"\"\"\n  while handoff:\n    tasks = handoff.pop()\n    for task in tasks:\n      # Future.cancel() completes the Task immediately, which unregisters it\n      # from the asyncio task list (Task.cancel() would only request it).\n      asyncio.Future.cancel(task)\n    _RECENTLY_CANCELLED.append(tasks)\n  handoff.append(_create_pending_tasks(tasks_per_thread))\n\n\ndef _spawner_loop(stop: threading.Event, tasks_per_thread: int) -> None:\n  \"\"\"Starts and joins short-lived worker threads until `stop` is set.\"\"\"\n  handoff: list[_TaskBatch] = []\n  while not stop.is_set():\n    worker = threading.Thread(\n        target=_short_lived_worker, args=(handoff, tasks_per_thread)\n    )\n    worker.start()\n    worker.join()\n\n\ndef _runner_loop(stop: threading.Event) -> None:\n  \"\"\"Runs short asyncio.run() calls until `stop` is set.\"\"\"\n  while not stop.is_set():\n    asyncio.run(_noop())\n\n\ndef main(argv: Sequence[str]) -> None:\n  if len(argv) > 1:\n    raise app.UsageError(\"Too many command-line arguments.\")\n  if not sysconfig.get_config_var(\"Py_GIL_DISABLED\"):\n    raise app.UsageError(\"Needs a free-threaded Python build; see README.md.\")\n  if sys._is_gil_enabled():  # pylint: disable=protected-access\n    raise app.UsageError(\"The GIL is enabled; run with PYTHON_GIL=0.\")\n  logging.info(\"Running on Python %s with the GIL disabled.\", sys.version)\n\n  stop = threading.Event()\n  threads = [\n      threading.Thread(\n          target=_spawner_loop, args=(stop, _TASKS_PER_THREAD.value)\n      )\n      for _ in range(_SPAWNER_THREADS.value)\n  ]\n  threads.extend(\n      threading.Thread(target=_runner_loop, args=(stop,))\n      for _ in range(_RUNNER_THREADS.value)\n  )\n  for thread in threads:\n    thread.start()\n  stop.wait(_DURATION_SECS.value)\n  stop.set()\n  for thread in threads:\n    thread.join()\n  logging.info(\"PASS: no crash after %.1f seconds.\", _DURATION_SECS.value)\n\n\nif __name__ == \"__main__\":\n  app.run(main)\n```\n\nI am sending a PR separately.\n\n### CPython versions tested on:\n\n3.14\n\n### Operating systems tested on:\n\nLinux\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-159450\n* gh-159451\n* gh-159483\n* gh-161379\n* gh-161380\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/jblespiau","@type":"Person","name":"jblespiau"},"datePublished":"2026-10-15T08:30:54Z","url":"https://github.com/python/cpython/issues/159449"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:b05f5e19-5180-9f5d-3e28-f328532db690
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idC8F2:2F9718:2E983C7:3E80C9D:6B01EC1A
html-safe-noncebafcacc1c12eafcbf5ba04ae6a33eb42ef1d88170435dc8fcd04cad1dc18fe0e
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDOEYyOjJGOTcxODoyRTk4M0M3OjNFODBDOUQ6NkIwMUVDMUEiLCJ2aXNpdG9yX2lkIjoiMzI1MDMxOTAwNjczMjc3NDQyNiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac868c41b905d5a7adbd97a3f2822fb7164c9dcd4ccbe056aacc5a6c8daf991796
hovercard-subject-tagissue:5862800532
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/159449/issue_layout
twitter:imagehttps://opengraph.githubassets.com/1c7c0b9b1b3d06259f965953795213346fe3e4fe47e1cd397dbe00f06edce54c/python/cpython/issues/159449
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/1c7c0b9b1b3d06259f965953795213346fe3e4fe47e1cd397dbe00f06edce54c/python/cpython/issues/159449
og:image:altBug report When a short-lived thread exits while some of its async tasks are still unfinished, Python moves those leftover tasks onto a shared global list; however, because Linux reuses the OS thre...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamejblespiau
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
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
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/159449#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F159449
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
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
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://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/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F159449
Sign uphttps://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/159449
Reloadhttps://github.com/python/cpython/issues/159449
Reloadhttps://github.com/python/cpython/issues/159449
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/159449
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/159449
AsyncIO thread-safety issue in Python 3.14's free-threadinghttps://github.com/python/cpython/issues/159449#top
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
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/jblespiau
jblespiauhttps://github.com/jblespiau
on Oct 15, 2026https://github.com/python/cpython/issues/159449#issue-5862800532
gh-159449 - Fix asyncio task unregister race 3.14 #159450https://github.com/python/cpython/pull/159450
gh-159449 - Fix a free-threaded asyncio race that corrupts the task lists #159451https://github.com/python/cpython/pull/159451
gh-159449: Fix a free-threaded asyncio race that corrupts the task lists #159483https://github.com/python/cpython/pull/159483
[3.15] gh-159449: Fix free-threaded asyncio race that corrupts the task lists (GH-159483) #161379https://github.com/python/cpython/pull/161379
[3.14] gh-159449: Fix free-threaded asyncio race that corrupts the task lists (GH-159483) #161380https://github.com/python/cpython/pull/161380
jblespiauhttps://github.com/jblespiau
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
on Oct 15, 2026https://github.com/python/cpython/issues/159449#event-33313193398
aiskhttps://github.com/aisk
topic-asynciohttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-asyncio%22
stdlibStandard Library Python modules in the Lib/ directoryhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
on Oct 15, 2026https://github.com/python/cpython/issues/159449#event-33316611713
github-project-automationhttps://github.com/apps/github-project-automation
asynciohttps://github.com/orgs/python/projects/29
on Oct 15, 2026https://github.com/python/cpython/issues/159449#event-33422070425
github-project-automationhttps://github.com/apps/github-project-automation
asynciohttps://github.com/orgs/python/projects/29
on Oct 15, 2026https://github.com/python/cpython/issues/159449
aiskhttps://github.com/aisk
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%22
on Oct 15, 2026https://github.com/python/cpython/issues/159449#event-33316628599
https://github.com/AnnaAr321
AnnaAr321https://github.com/AnnaAr321
on Oct 15, 2026https://github.com/python/cpython/issues/159449#issuecomment-6190622874
https://github.com/AnnaAr321
AnnaAr321https://github.com/AnnaAr321
on Oct 15, 2026https://github.com/python/cpython/issues/159449#issuecomment-6191087904
kevinprimeraquecreo-stackhttps://github.com/kevinprimeraquecreo-stack
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/159449#event-33592166436
github-project-automationhttps://github.com/apps/github-project-automation
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/159449
kevinprimeraquecreo-stackhttps://github.com/kevinprimeraquecreo-stack
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/159449#event-33592182344
jblespiauhttps://github.com/jblespiau
on Nov 4, 2026https://github.com/python/cpython/issues/159449#event-35119449889
pythongh-159449: Fix a free-threaded asyncio race that corrupts the t…https://github.com/jblespiau/cpython/commit/60d8cacb56ee1542c1d3d03400304493d9413ec6
pythongh-159449https://github.com/python/cpython/issues/159449
60d8cachttps://github.com/jblespiau/cpython/commit/60d8cacb56ee1542c1d3d03400304493d9413ec6
https://github.com/nascheme
naschemehttps://github.com/nascheme
on Nov 4, 2026https://github.com/python/cpython/issues/159449#issuecomment-6640203435
@kumaraditya303https://github.com/kumaraditya303
kumaraditya303https://github.com/kumaraditya303
on Nov 5, 2026https://github.com/python/cpython/issues/159449#event-35204841309
pythongh-159449: Fix a free-threaded asyncio race that corrupts the t…https://github.com/jblespiau/cpython/commit/8e75accaa1757b117eedfbee8f688fc2258b4268
pythongh-159449https://github.com/python/cpython/issues/159449
8e75acchttps://github.com/jblespiau/cpython/commit/8e75accaa1757b117eedfbee8f688fc2258b4268
gh-159449: Fix free-threaded asyncio race that corrupts the task lists (https://github.com/python/cpython/commit/aaaf61ca62f0924d7b5134c2d237313d8be2215c
gh-159449https://github.com/python/cpython/issues/159449
aaaf61chttps://github.com/python/cpython/commit/aaaf61ca62f0924d7b5134c2d237313d8be2215c
[3.14] pythongh-159449: Fix free-threaded asyncio race that corrupts …https://github.com/kumaraditya303/cpython/commit/abee7e4fe18ab6d99bd48717fab88990f5cbdb29
pythongh-159449https://github.com/python/cpython/issues/159449
abee7e4https://github.com/kumaraditya303/cpython/commit/abee7e4fe18ab6d99bd48717fab88990f5cbdb29
kumaraditya303https://github.com/kumaraditya303
completedhttps://github.com/python/cpython/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Nov 5, 2026https://github.com/python/cpython/issues/159449#event-35209540151
github-project-automationhttps://github.com/apps/github-project-automation
asynciohttps://github.com/orgs/python/projects/29
on Nov 5, 2026https://github.com/python/cpython/issues/159449
kumaraditya303https://github.com/kumaraditya303
on Nov 5, 2026https://github.com/python/cpython/issues/159449#event-35211540901
[3.15] gh-159449: Fix free-threaded asyncio race that corrupts the ta…https://github.com/python/cpython/commit/3619efa3df9e88d1197b89c43c55ed3e3fb13f67
gh-159449https://github.com/python/cpython/issues/159449
3619efahttps://github.com/python/cpython/commit/3619efa3df9e88d1197b89c43c55ed3e3fb13f67
[3.14] gh-159449: Fix free-threaded asyncio race that corrupts the ta…https://github.com/python/cpython/commit/6e8892710f3e6a48b702b645ac208183ee81769c
gh-159449https://github.com/python/cpython/issues/159449
6e88927https://github.com/python/cpython/commit/6e8892710f3e6a48b702b645ac208183ee81769c
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/159449
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/159449
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
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%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.