python / python/cpython

Structseq objects created with PyStructSequence_New() are not tracked by the GC

Open
#157,443 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

3.13 3.14 3.15 3.16 interpreter-core type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

PyStructSequence_New() allocates the object with PyObject_GC_NewVar() but never calls PyObject_GC_Track(). Only structseq_new_impl() (calling the type from Python) and __replace__() track the result (bpo-37126, gh-145376). All 45 C callers of PyStructSequence_New() in the tree, including make_unraisable_hook_args() in Python/errors.c, produce objects which the GC never sees, so a reference cycle through them is never collected.

Most structseq objects hold only ints and strings, but sys.UnraisableHookArgs holds the exception and its traceback, which keeps the frames alive (the current frame, when the exception has no traceback, format_unraisable_v() synthesizes one from it). Storing the hook argument in something reachable from those frames creates an uncollectable cycle:

import gc
import sys
import weakref

class Holder:
    pass

def f():
    holder = Holder()
    def hook(unraisable):
        holder.unraisable = unraisable
    sys.unraisablehook = hook
    class C:
        def __del__(self):
            raise ValueError
    C()
    print(gc.is_tracked(holder.unraisable))
    return weakref.ref(holder)

wr = f()
sys.unraisablehook = sys.__unraisablehook__
gc.collect()
print(wr())

Output (3.13 and main):

False
<__main__.Holder object at 0x7a7fda9d22c0>

Expected: True and None.

test.support.catch_unraisable_exception() works around this by deleting its unraisable attribute on exit (bpo-37261). I hit it in test_class.test_detach_materialized_dict_no_memory(), which leaks about 140 references per run as soon as it keeps ex.unraisable in a local variable.

The simplest fix is to call _PyObject_GC_TRACK() in PyStructSequence_New(), as PyTuple_New() does, and drop the explicit calls in structseq_new_impl() and structseq_replace(). Py_VISIT() handles the NULL items of a partially filled object.

Linked PRs
  • gh-157447

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in Python/errors.c at make_unraisable_hook_args(), then inspect PyStructSequence_New() and the structseq_new_impl() and structseq_replace() callers described in the report. Run test_class.test_detach_materialized_dict_no_memory() and reproduce the gc.is_tracked() example. Done means structseq objects created through the C API are tracked and the demonstrated reference cycle is collected.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.