Title: asyncio: TaskObj_dealloc leaves a refcount-0 Task GC-tracked, hanging or crashing the free-threaded build · Issue #153809 · python/cpython · GitHub
Open Graph Title: asyncio: TaskObj_dealloc leaves a refcount-0 Task GC-tracked, hanging or crashing the free-threaded build · Issue #153809 · python/cpython
X Title: asyncio: TaskObj_dealloc leaves a refcount-0 Task GC-tracked, hanging or crashing the free-threaded build · Issue #153809 · python/cpython
Description: Crash report What happened? On the free-threaded build, TaskObj_dealloc leaves an _asyncio.Task at refcount 0 while it is still GC-tracked, across a _PyEval_StopTheWorld(). A gc.collect() on another thread walks the tracked set during th...
Open Graph Description: Crash report What happened? On the free-threaded build, TaskObj_dealloc leaves an _asyncio.Task at refcount 0 while it is still GC-tracked, across a _PyEval_StopTheWorld(). A gc.collect() on anothe...
X Description: Crash report What happened? On the free-threaded build, TaskObj_dealloc leaves an _asyncio.Task at refcount 0 while it is still GC-tracked, across a _PyEval_StopTheWorld(). A gc.collect() on anothe...
Opengraph URL: https://github.com/python/cpython/issues/153809
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"asyncio: TaskObj_dealloc leaves a refcount-0 Task GC-tracked, hanging or crashing the free-threaded build","articleBody":"# Crash report\n\n### What happened?\n\nOn the free-threaded build, `TaskObj_dealloc` leaves an `_asyncio.Task` at **refcount 0 while it is still GC-tracked**, across a `_PyEval_StopTheWorld()`. A `gc.collect()` on another thread walks the tracked set during that window and finds the refcount-0 object: the interpreter aborts on a debug build, and **hangs or segfaults on a release build**.\n\n## Root cause\n\n`Modules/_asynciomodule.c`, `TaskObj_dealloc`:\n\n```c\nstatic void\nTaskObj_dealloc(PyObject *self)\n{\n if (PyObject_CallFinalizerFromDealloc(self) \u003c 0) {\n return; // resurrected\n }\n // unregister the task after finalization so that\n // if the task gets resurrected, it remains registered\n unregister_task((TaskObj *)self); // \u003c-- may _PyEval_StopTheWorld()\n\n PyTypeObject *tp = Py_TYPE(self);\n PyObject_GC_UnTrack(self); // \u003c-- untrack happens only here\n ...\n}\n```\n\nThe refcount is already 0 on entry, but the Task stays on the GC tracked list across both the finalizer and `unregister_task()`. For a Task deallocated on a thread other than its creator, `unregister_task()` takes a stop-the-world branch:\n\n```c\nstatic void\nunregister_task(TaskObj *task)\n{\n#ifdef Py_GIL_DISABLED\n if (task->task_tid == _Py_ThreadId()) {\n unregister_task_safe(task);\n } else {\n PyThreadState *tstate = _PyThreadState_GET();\n _PyEval_StopTheWorld(tstate->interp); // \u003c-- the window\n unregister_task_safe(task);\n _PyEval_StartTheWorld(tstate->interp);\n }\n#else\n unregister_task_safe(task);\n#endif\n}\n```\n\n`FutureObj_dealloc` has the same finalizer-before-untrack shape but untracks immediately afterwards, and does not reproduce — the stop-the-world inside `unregister_task()` is what widens the window enough to be hit reliably.\n\n## Reproducer\n\n```python\nimport sys, gc, threading, _asyncio\nassert not sys._is_gil_enabled()\n\nN, ITERS = 4, 6000\nbarrier = threading.Barrier(N)\n\ndef worker():\n barrier.wait()\n for i in range(ITERS):\n try:\n _asyncio.Task([1, 2, 3]) # fails the coro check before task_tid is set\n except Exception:\n pass\n if i % 16 == 0:\n gc.collect()\n\nts = [threading.Thread(target=worker) for _ in range(N)]\nfor t in ts: t.start()\nfor t in ts: t.join()\n```\n\n`Task([1, 2, 3])` fails `__init__`'s coroutine check *before* `task_tid` is assigned, so `task_tid` keeps its zero value and every transient Task takes the stop-the-world branch on teardown. A **well-formed** Task deallocated on a thread other than its creator takes the identical branch.\n\n## Observed\n\nFree-threaded CPython **3.16.0a0** (`main`, `bcf98ddbc40`):\n\n| build | result |\n|-------|--------|\n| `--disable-gil` debug | `validate_refcounts` abort, exit 134 (10/10) |\n| `--disable-gil` release | **interpreter wedges (5/5)**; segfault also observed |\n\nDebug:\n\n```\nPython/gc_free_threading.c:1083: validate_refcounts: Assertion\n \"_Py_REFCNT(((PyObject*)((op)))) > 0\" failed:\n tracked objects must have a reference count > 0\nobject type name: _asyncio.Task\nobject refcount : 0\nFatal Python error: _PyObject_AssertFailed\n```\n\nRelease (no `Py_DEBUG`, no sanitizer) — `gc.collect()` spins forever while every other thread parks behind it:\n\n```\nt1 (spinning, 100% CPU):\n _mi_page_free_collect Objects/mimalloc/page.c:245\n \u003c- mi_heap_visit_blocks(visitor=update_refs)\n \u003c- gc_visit_heaps_lock_held Python/gc_free_threading.c:395\n \u003c- deduce_unreachable_heap Python/gc_free_threading.c:1447\n \u003c- gc_collect_main Python/gc_free_threading.c:2257\n\nt0 / t2 / t3 (parked):\n _PyMutex_Lock(&_PyRuntime+169592) \u003c- _PyParkingLot_Park \u003c- _PySemaphore_Wait\n```\n\nStill wedged after 150 s for work that an identical-shape control (a plain class whose `__init__` raises — same threads, same `gc.collect()` cadence, no stop-the-world in the dealloc) completes in 0.11 s. It reproduces with as few as **10** transient Tasks, and with only 2 threads.\n\n## Suggested fix\n\nMove `PyObject_GC_UnTrack(self)` to the top of `TaskObj_dealloc`, before the finalizer and `unregister_task()` — the standard dealloc discipline (`subtype_dealloc` untracks first). Resurrection re-tracks the object, so this remains compatible with gh-142556, whose fix introduced the current finalize → unregister → untrack ordering. An object at refcount 0 should not stay on the GC tracked list across a `_PyEval_StopTheWorld()`.\n\n## Related\n\n- **gh-142556** (fixed by #142565) — same function. Its fix established the current ordering and left `PyObject_GC_UnTrack` last, which is precisely the window exploited here. Distinct bug (single-threaded re-registration UAF).\n- **gh-128656** — a different assertion in the same area (`PyObject_CallFinalizerFromDealloc` called with a non-zero refcount).\n\nFull report, reproducer and complete release-build backtraces: https://gist.github.com/devdanzin/df90699fe37599d5502ce39f718f6657\n\n_AI Disclaimer: this report was drafted by Claude Code, which also created and ran the reproducer; the maintainer reviewed and edited it._\n\n\n\n### CPython versions tested on:\n\nCPython main branch\n\n### Operating systems tested on:\n\nLinux\n\n### Output from running 'python -VV' on the command line:\n\nPython 3.16.0a0 free-threading build (heads/main:bcf98ddbc40, Jul 4 2026, 15:37:00) [Clang 21.1.8 (6ubuntu1)]\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-154563\n* gh-154665\n* gh-154666\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/devdanzin","@type":"Person","name":"devdanzin"},"datePublished":"2026-07-16T10:25:51Z","url":"https://github.com/python/cpython/issues/153809"}
| react-profiling | 0 |
| react-import-map | react,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-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:bef906c8-c7e5-151c-2ab8-0a4d12b98704 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | AA14:CE438:12E4966:19357A6:6B0201EF |
| html-safe-nonce | c218b579aaffc0c7325385aae6f0ec503474290641ab0ade738b671b421cab09 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBQTE0OkNFNDM4OjEyRTQ5NjY6MTkzNTdBNjo2QjAyMDFFRiIsInZpc2l0b3JfaWQiOiI4MTk2MjU3NTA5MTkxODQ0MzM1IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 24f57033b9b3397429f9acdb3f8dcb2f8ccca70db8c979363e3e61c64cf7d761 |
| hovercard-subject-tag | issue:4901067121 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/153809/issue_layout |
| twitter:image | https://opengraph.githubassets.com/72214ee5d8e6dec3a2e8625dd4645fb73e87260cc53e1dcf47d0e8935606e356/python/cpython/issues/153809 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/72214ee5d8e6dec3a2e8625dd4645fb73e87260cc53e1dcf47d0e8935606e356/python/cpython/issues/153809 |
| og:image:alt | Crash report What happened? On the free-threaded build, TaskObj_dealloc leaves an _asyncio.Task at refcount 0 while it is still GC-tracked, across a _PyEval_StopTheWorld(). A gc.collect() on anothe... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | devdanzin |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width