python / python/cpython

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

オープン
#157,443 コメント 0 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

3.13 3.14 3.15 3.16 interpreter-core type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Python/errors.c の make_unraisable_hook_args() から始め、次に PyStructSequence_New() と、報告書で説明されている structseq_new_impl() および structseq_replace() の呼び出し元を調べます。test_class.test_detach_materialized_dict_no_memory() を実行し、gc.is_tracked() の例を再現します。C API を通じて作成された structseq オブジェクトが追跡され、示された参照サイクルが回収されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
c, python
領域
backend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。