René's URL Explorer Experiment


Title: gc regression on main; live objects can be cleared due to tp_traverse races · Issue #162407 · python/cpython · GitHub

Open Graph Title: gc regression on main; live objects can be cleared due to tp_traverse races · Issue #162407 · python/cpython

X Title: gc regression on main; live objects can be cleared due to tp_traverse races · Issue #162407 · python/cpython

Description: Bug GH-159138 (fbbf4f4) can tp_clear live objects when a tp_traverse visits a reference in subtract_refs() but skips it in move_unreachable(). No Python code has to run: a native thread changing the state that tp_traverse reads is enough...

Open Graph Description: Bug GH-159138 (fbbf4f4) can tp_clear live objects when a tp_traverse visits a reference in subtract_refs() but skips it in move_unreachable(). No Python code has to run: a native thread changing th...

X Description: Bug GH-159138 (fbbf4f4) can tp_clear live objects when a tp_traverse visits a reference in subtract_refs() but skips it in move_unreachable(). No Python code has to run: a native thread changing th...

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

X: @github

direct link

Domain: github.com

IPv4 address: 140.82.113.3


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"gc regression on main; live objects can be cleared due to tp_traverse races","articleBody":"### Bug\n\nGH-159138 (fbbf4f48) can `tp_clear` live objects when a `tp_traverse` visits a reference in `subtract_refs()` but skips it in `move_unreachable()`. No Python code has to run: a native thread changing the state that `tp_traverse` reads is enough. The second reachability pass used to rescue the referent, because the holder is outside `unreachable`.\n\nThe docs now allow this pattern (GH-160455: skip the traversal if a lock is busy, \"correctness won't be affected\"). An extension doing exactly that loses data in 3-48% of collections on main (timing dependent) and never at the parent commit _[edit: not quite never... see the grounding below]_ . The free-threaded collector is affected too, for objects that mark-alive does not reach first (e.g. after `gc.freeze()`).\n\n### Real world triggers\n\nIt also happens with PyTorch 2.15.0, whose `THPVariable_traverse` visits `grad_fn` only while `use_count() == 1`. There are no 3.16 wheels, so my Claude applied the commit's `gc.c` change to 3.15: a live autograd `ctx` loses its `__dict__`. PyGObject _(a GTK wrapper?)_ has a similar `ref_count == 1` check (not tested).\n\n#### Grounding that in reality\n\nThe old behavior was not fully safe _either_: such objects can already get an early `__del__` or weakref callback, and nested holders can occasionally be cleared. So the docs sentence needs a caveat regardless. But the common case went from harmless to silent data loss.  _[edit: maybe not harmless... contents survive yet the weakref callback happened?]_\n\n### Suggestions\n\nAlways take the second pass again (gives back the ~20-25% saved on all-garbage collections) 😦 _[edit: but there's still a lot of benefit]_ , or always run a cheaper check for outside references first.  _[edit: i'm not sure that \"cheaper\" one is possible to make correct, especially for free-threading]_\n\n\u003cdetails>\u003csummary>Reproducers (extension + python, and a torch example)\u003c/summary>\n\n```c\n// box.c: cc -shared -fPIC -I\u003cbuild> -I\u003csrc>/Include box.c -o box.so\n#include \u003cPython.h>\n#include \u003cpthread.h>\n#include \u003cunistd.h>\nstatic pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;\ntypedef struct { PyObject_HEAD PyObject *item; } Box;\n\nstatic int traverse(PyObject *op, visitproc visit, void *arg) {\n    if (pthread_mutex_trylock(&mu) != 0) return 0;   /* busy: skip */\n    int err = visit(((Box *)op)->item, arg);\n    pthread_mutex_unlock(&mu);\n    return err;\n}\nstatic void dealloc(PyObject *op) {\n    PyObject_GC_UnTrack(op);\n    Py_DECREF(((Box *)op)->item);\n    PyObject_GC_Del(op);\n}\nstatic PyObject *get(PyObject *op, void *c) { return Py_NewRef(((Box *)op)->item); }\nstatic PyGetSetDef getset[] = {{\"item\", get}, {0}};\nstatic PyTypeObject BoxType = {\n    PyVarObject_HEAD_INIT(NULL, 0) .tp_name = \"box.Box\", .tp_basicsize = sizeof(Box),\n    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,\n    .tp_traverse = traverse, .tp_dealloc = dealloc, .tp_getset = getset};\n\nstatic PyObject *box(PyObject *m, PyObject *item) {\n    Box *b = PyObject_GC_New(Box, &BoxType);\n    if (b == NULL) return NULL;\n    b->item = Py_NewRef(item);\n    PyObject_GC_Track(b);\n    return (PyObject *)b;\n}\nstatic void *worker(void *arg) {   /* never touches Python */\n    for (;;) { pthread_mutex_lock(&mu); usleep(50); pthread_mutex_unlock(&mu); usleep(50); }\n}\nstatic PyMethodDef methods[] = {{\"box\", box, METH_O}, {0}};\nstatic struct PyModuleDef def = {PyModuleDef_HEAD_INIT, \"box\", NULL, -1, methods};\nPyMODINIT_FUNC PyInit_box(void) {\n    pthread_t t;\n    if (PyType_Ready(&BoxType) \u003c 0 || pthread_create(&t, NULL, worker, NULL)) return NULL;\n    PyObject *m = PyModule_Create(&def);\n#ifdef Py_GIL_DISABLED\n    PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);\n#endif\n    return m;\n}\n```\n\n```python\nimport gc, box\nlost = 0\nfor _ in range(2000):\n    b = box.box([1, 2, 3])\n    gc.collect()\n    lost += b.item != [1, 2, 3]\nprint(\"emptied while alive:\", lost, \"of 2000\")\n# 8bf6305b (parent): 0.  fbbf4f48 and main: tens to hundreds.\n# Free-threaded: call gc.freeze() first.\n```\n\nPyTorch 2.15.0, 3.15 + fbbf4f48 (timing dependent, ~2 GiB):\n\n```python\nimport gc, threading, time, torch\ntorch.set_num_threads(1)\n\nclass F(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, x):\n        ctx.scale = [2.0]\n        return x * 2\n    @staticmethod\n    def backward(ctx, g):\n        return g * ctx.scale[0]\n\nx = torch.ones(36_000_000, requires_grad=True)\ny = F.apply(x)\nballast = [[i] for i in range(1_000_000)]   # makes a collection take a while\ndone = False\ndef work():\n    while not done:\n        y.allclose(x)                       # releases the GIL\nt = threading.Thread(target=work); t.start()\nfor _ in range(200):\n    gc.collect()\ndone = True; t.join()\ny.sum().backward()\nprint(\"ok\")\n# AttributeError: 'FBackward' object has no attribute 'scale'\n```\n\u003c/details>\n\n### Versions tested\n\nmain - this gc work is new for 3.16 alphas.\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-162541\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/gpshead","@type":"Person","name":"gpshead"},"datePublished":"2026-11-21T21:57:30Z","url":"https://github.com/python/cpython/issues/162407"}

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:883a8f5c-4570-bad7-44b1-0b2a9670622b
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idCEC2:D7B8A:F9F2FA:14B7C06:6B064BBA
html-safe-noncefc01b927879223b841a07e5c16c69c46559bc22c2fadfa5a7eb4b41bebb427a8
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDRUMyOkQ3QjhBOkY5RjJGQToxNEI3QzA2OjZCMDY0QkJBIiwidmlzaXRvcl9pZCI6IjY3MTEwODk1MTkzODg5MzcxNDYiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac171bd685518e6f1b83dbdbb5f2928f59313c1c1ac086670aa2e79478d3999301
hovercard-subject-tagissue:6534916703
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/162407/issue_layout
twitter:imagehttps://opengraph.githubassets.com/1a8f470a3ce9f05537934b4daee0fe1ccb796643ef55396abe45b8ba28b72bce/python/cpython/issues/162407
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/1a8f470a3ce9f05537934b4daee0fe1ccb796643ef55396abe45b8ba28b72bce/python/cpython/issues/162407
og:image:altBug GH-159138 (fbbf4f4) can tp_clear live objects when a tp_traverse visits a reference in subtract_refs() but skips it in move_unreachable(). No Python code has to run: a native thread changing th...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamegpshead
hostnamegithub.com
expected-hostnamegithub.com
None772b6997ca4daa0428dd49a25d76052e765555ae560fe9c88517eb828bbd861e
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
releasef1f9a08f7c769a37f1dfc18ad43d463c222a7eea
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/162407#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F162407
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%2F162407
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/162407
Reloadhttps://github.com/python/cpython/issues/162407
Reloadhttps://github.com/python/cpython/issues/162407
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/162407
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/162407
gc regression on main; live objects can be cleared due to tp_traverse raceshttps://github.com/python/cpython/issues/162407#top
https://github.com/encukou
https://github.com/pablogsal
3.16https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.16%22
interpreter-corehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-bughttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/gpshead
gpsheadhttps://github.com/gpshead
on Nov 21, 2026https://github.com/python/cpython/issues/162407#issue-6534916703
GH-159138https://github.com/python/cpython/pull/159138
fbbf4f4https://github.com/python/cpython/commit/fbbf4f48c48cd9de2373494b2408c1424fe7ef3f
GH-160455https://github.com/python/cpython/pull/160455
fbbf4f4https://github.com/python/cpython/commit/fbbf4f48c48cd9de2373494b2408c1424fe7ef3f
gh-162407: Clarify the consistency requirement for tp_traverse #162541https://github.com/python/cpython/pull/162541
gpsheadhttps://github.com/gpshead
pablogsalhttps://github.com/pablogsal
on Nov 21, 2026https://github.com/python/cpython/issues/162407#event-36887433272
gpsheadhttps://github.com/gpshead
type-bughttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
interpreter-corehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
3.16https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.16%22
on Nov 21, 2026https://github.com/python/cpython/issues/162407#event-36887434103
gpsheadhttps://github.com/gpshead
encukouhttps://github.com/encukou
on Nov 21, 2026https://github.com/python/cpython/issues/162407#event-36887515840
https://github.com/pablogsal
pablogsalhttps://github.com/pablogsal
on Nov 22, 2026https://github.com/python/cpython/issues/162407#issuecomment-7078447130
ChatGPT Codex Connectorhttps://www.chatgpt.com
#159138https://github.com/python/cpython/pull/159138
#160455https://github.com/python/cpython/pull/160455
#160455https://github.com/python/cpython/pull/160455
@encukouhttps://github.com/encukou
https://github.com/pablogsal
pablogsalhttps://github.com/pablogsal
on Nov 22, 2026https://github.com/python/cpython/issues/162407#issuecomment-7078478510
ChatGPT Codex Connectorhttps://www.chatgpt.com
@brandtbucherhttps://github.com/brandtbucher
https://github.com/encukou
encukouhttps://github.com/encukou
on Nov 23, 2026https://github.com/python/cpython/issues/162407#issuecomment-7098076543
https://github.com/pablogsal
pablogsalhttps://github.com/pablogsal
on Nov 23, 2026https://github.com/python/cpython/issues/162407#issuecomment-7105368579
#159138https://github.com/python/cpython/pull/159138
https://github.com/nascheme
naschemehttps://github.com/nascheme
on Nov 23, 2026https://github.com/python/cpython/issues/162407#issuecomment-7113087266
GH-160455https://github.com/python/cpython/pull/160455
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/162407
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/162407
encukouhttps://github.com/encukou
pablogsalhttps://github.com/pablogsal
3.16https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.16%22
interpreter-corehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-bughttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
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

Response headers:
Servergithub.com
Content-Typetext/html; charset=utf-8
Cache-Controlmax-age=0, private, must-revalidate

Viewport: width=device-width


URLs of crawlers that visited me.