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