Repository navigation
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. The second reachability pass used to rescue the referent, because the holder is outside unreachable.
The 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()).
Real world triggers
It 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).
Grounding that in reality
The 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?]
Suggestions
Always 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]
Reproducers (extension + python, and a torch example)
// box.c: cc -shared -fPIC -I<build> -I<src>/Include box.c -o box.so
#include <Python.h>
#include <pthread.h>
#include <unistd.h>
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
typedef struct { PyObject_HEAD PyObject *item; } Box;
static int traverse(PyObject *op, visitproc visit, void *arg) {
if (pthread_mutex_trylock(&mu) != 0) return 0; /* busy: skip */
int err = visit(((Box *)op)->item, arg);
pthread_mutex_unlock(&mu);
return err;
}
static void dealloc(PyObject *op) {
PyObject_GC_UnTrack(op);
Py_DECREF(((Box *)op)->item);
PyObject_GC_Del(op);
}
static PyObject *get(PyObject *op, void *c) { return Py_NewRef(((Box *)op)->item); }
static PyGetSetDef getset[] = {{"item", get}, {0}};
static PyTypeObject BoxType = {
PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "box.Box", .tp_basicsize = sizeof(Box),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = traverse, .tp_dealloc = dealloc, .tp_getset = getset};
static PyObject *box(PyObject *m, PyObject *item) {
Box *b = PyObject_GC_New(Box, &BoxType);
if (b == NULL) return NULL;
b->item = Py_NewRef(item);
PyObject_GC_Track(b);
return (PyObject *)b;
}
static void *worker(void *arg) { /* never touches Python */
for (;;) { pthread_mutex_lock(&mu); usleep(50); pthread_mutex_unlock(&mu); usleep(50); }
}
static PyMethodDef methods[] = {{"box", box, METH_O}, {0}};
static struct PyModuleDef def = {PyModuleDef_HEAD_INIT, "box", NULL, -1, methods};
PyMODINIT_FUNC PyInit_box(void) {
pthread_t t;
if (PyType_Ready(&BoxType) < 0 || pthread_create(&t, NULL, worker, NULL)) return NULL;
PyObject *m = PyModule_Create(&def);
#ifdef Py_GIL_DISABLED
PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
#endif
return m;
}import gc, box
lost = 0
for _ in range(2000):
b = box.box([1, 2, 3])
gc.collect()
lost += b.item != [1, 2, 3]
print("emptied while alive:", lost, "of 2000")
# 8bf6305b (parent): 0. fbbf4f48 and main: tens to hundreds.
# Free-threaded: call gc.freeze() first.PyTorch 2.15.0, 3.15 + fbbf4f4 (timing dependent, ~2 GiB):
import gc, threading, time, torch
torch.set_num_threads(1)
class F(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.scale = [2.0]
return x * 2
@staticmethod
def backward(ctx, g):
return g * ctx.scale[0]
x = torch.ones(36_000_000, requires_grad=True)
y = F.apply(x)
ballast = [[i] for i in range(1_000_000)] # makes a collection take a while
done = False
def work():
while not done:
y.allclose(x) # releases the GIL
t = threading.Thread(target=work); t.start()
for _ in range(200):
gc.collect()
done = True; t.join()
y.sum().backward()
print("ok")
# AttributeError: 'FBackward' object has no attribute 'scale'Versions tested
main - this gc work is new for 3.16 alphas.
Activity
pablogsal commentedon Nov 22, 2026
I think #159138 was correct under the
tp_traversecontract we had at the time.Boxhad to visit the list it owned. If nothing ran that could resurrect an object, there was no reason to check for resurrection again. We added the advice about skipping traversal on a busy lock later, in #160455.If
tp_traversegives two different answers in the same collection, the old collector only got this case right by accident. Insubtract_refs()the box tells us it owns the list, so we subtract that reference. Inmove_unreachable()we trace the live box and it skips the list. Both versions of the collector now think the list is garbage.The second pass happened to save the list because the live box was outside the set we checked again. Its reference counted as external on that pass. But we can already call a weakref callback or a finalizer before we get there, so the first wrong answer matters even with the old code.
My change explains why the list now ends up empty. I think the advice in #160455 needs a correction either way.
cc @encukou
pablogsal commentedon Nov 22, 2026
CC @brandtbucher, as Brandt and his team are also working to merge passes.