python / python/cpython

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

Abierto
#157,443 0 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

3.13 3.14 3.15 3.16 interpreter-core type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza en Python/errors.c, en make_unraisable_hook_args(), y examina después PyStructSequence_New() y los llamadores de structseq_new_impl() y structseq_replace() descritos en el informe. Ejecuta test_class.test_detach_materialized_dict_no_memory() y reproduce el ejemplo de gc.is_tracked(). Se considera terminado cuando los objetos structseq creados mediante la C API están rastreados y se recolecta el ciclo de referencias demostrado.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
c, python
Área
backend
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.