C API/GC: datetime.datetime doesn't have `Py_TPFLAGS_HAVE_GC`, potentially causing leaks in `tzinfo` cycles
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 77.2k
- フォーク
- 35.9k
- PR マージ指標
- PR 指標を取得中
説明
Bug report
Bug description:
The GC docs say (emphasis mine)
Python’s support for detecting and collecting garbage which involves circular references requires support from object types which are “containers” for other objects which may also be containers. Types which do not store references to other objects, or which only store references to atomic types (such as numbers or strings), do not need to provide any explicit support for garbage collection.
However in datetime, PyDateTime_DateTimeType is a container (of tzinfo), but doesn’t have the GC flags set.
With help on Python's discuss forums, I was able to get to this minimal example that appears to show a possible leak.
from datetime import datetime, tzinfo
import gc, sys
class MyTzinfo(tzinfo): pass
tz = MyTzinfo()
dt = datetime(2000, 1, 1, tzinfo=tz)
tz.foo = dt # circular ref introduced here
assert sys.getrefcount(tz) == 3 # 1 from dt, 1 variable, 1extra from passing it in
assert sys.getrefcount(tz) == 3 # 1 from tz, 1 variable, 1extra from passing it in
assert len([obj for obj in gc.get_objects() if isinstance(obj, MyTzinfo)]) == 1
del tz
assert len([obj for obj in gc.get_objects() if isinstance(obj, MyTzinfo)]) == 1
del dt
gc.collect()
# At this point, dt and tz should be gone
assert len([obj for obj in gc.get_objects() if isinstance(obj, MyTzinfo)]) == 0
If datetime is replaced with a dummy class, the above program works:
class datetime:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
I'm happy to submit a PR if needed.
CPython versions tested on:
3.12
Operating systems tested on:
macOS
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
Modules/_datetimemodule.c で PyDateTime_DateTimeType を調べることから始め、その tzinfo 参照がガベージコレクションのサポートとどのように相互作用するかを確認します。最小限の datetime/tzinfo サイクル再現プログラムを実行し、既存の datetime テストを調べます。gc.collect() の後にサイクルが回収され、この動作をカバーするリグレッションテストがあれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- c, python
- 領域
- backend
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100