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
Domain: github.com
IPv4 address: 140.82.113.3
{"@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-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:883a8f5c-4570-bad7-44b1-0b2a9670622b |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | CEC2:D7B8A:F9F2FA:14B7C06:6B064BBA |
| html-safe-nonce | fc01b927879223b841a07e5c16c69c46559bc22c2fadfa5a7eb4b41bebb427a8 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDRUMyOkQ3QjhBOkY5RjJGQToxNEI3QzA2OjZCMDY0QkJBIiwidmlzaXRvcl9pZCI6IjY3MTEwODk1MTkzODg5MzcxNDYiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 171bd685518e6f1b83dbdbb5f2928f59313c1c1ac086670aa2e79478d3999301 |
| hovercard-subject-tag | issue:6534916703 |
| 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/162407/issue_layout |
| twitter:image | https://opengraph.githubassets.com/1a8f470a3ce9f05537934b4daee0fe1ccb796643ef55396abe45b8ba28b72bce/python/cpython/issues/162407 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/1a8f470a3ce9f05537934b4daee0fe1ccb796643ef55396abe45b8ba28b72bce/python/cpython/issues/162407 |
| og:image:alt | 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... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | gpshead |
| hostname | github.com |
| expected-hostname | github.com |
| None | 772b6997ca4daa0428dd49a25d76052e765555ae560fe9c88517eb828bbd861e |
| 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 | f1f9a08f7c769a37f1dfc18ad43d463c222a7eea |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width