Skip to content

gh-135909: Assert incoming refcnt != 0 for the free threaded GC. #136009

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions Python/gc_free_threading.c
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,14 @@ validate_refcounts(const mi_heap_t *heap, const mi_heap_area_t *area,
return true;
}

// This assert mirrors the one in Python/gc.c:update_refs(). There must be
// no tracked objects with a reference count of 0 when the cyclic
// collector starts. If there is, then the collector will double dealloc
// the object. The likely cause for hitting this is a faulty .tp_dealloc.
// Also see the comment in `update_refs()`.
_PyObject_ASSERT_WITH_MSG(op, Py_REFCNT(op) > 0,
"tracked objects must have a reference count > 0");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're trying to mimick the default GC, let's use the same error message:

Suggested change
"tracked objects must have a reference count > 0");
"refcount is too small");


_PyObject_ASSERT_WITH_MSG(op, !gc_is_unreachable(op),
"object should not be marked as unreachable yet");

Expand Down Expand Up @@ -1422,13 +1430,6 @@ static int
deduce_unreachable_heap(PyInterpreterState *interp,
struct collection_state *state)
{

#ifdef GC_DEBUG
// Check that all objects are marked as unreachable and that the computed
// reference count difference (stored in `ob_tid`) is non-negative.
gc_visit_heaps(interp, &validate_refcounts, &state->base);
#endif

// Identify objects that are directly reachable from outside the GC heap
// by computing the difference between the refcount and the number of
// incoming references.
Expand Down Expand Up @@ -2154,6 +2155,13 @@ gc_collect_internal(PyInterpreterState *interp, struct collection_state *state,
state->gcstate->old[i-1].count = 0;
}

#ifdef GC_DEBUG
// Before we start, check that the heap is in a good condition. There must
// be no objects with a zero reference count. And `ob_tid` must only have a
// thread if the refcount is unmerged.
gc_visit_heaps(interp, &validate_refcounts, &state->base);
#endif

_Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
_PyThreadStateImpl *tstate = (_PyThreadStateImpl *)p;

Expand Down
Loading