Structseq objects created with PyStructSequence_New() are not tracked by the GC
還沒有人認領這個 Issue。
- 主要語言
- 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
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 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