python / python/cpython

GC - Possible to indefinitely prevent collection of generation-1 objects by calling gc.collect(0) often

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

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

performance type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

The example below will die from memory exhaustion, despite nearly all objects being eligible for collection and despite garbage collection not being disabled. See inline comments for an explanation of what I think is happening:

import gc
from typing import Any

class Temp:
  def __init__(self):
    # Cyclic reference to prevent deletion by ref count dropping to 0.
    self._x = self
    # Allocate a bunch of memory so that the process will die if
    # collection doesn't happen.
    self.memory = bytearray(1024*1024*512)

# Set some low thresholds so that collection should occur often.
gc.set_threshold(100, 3, 3)

while True:
  ref = Temp()
  # Promote the new Temp() object to generation-1. I think this is also resetting
  # the GCs view of how many objects were allocated at the "last collection". If
  # that's true, it will effectively stop the GC from ever being invoked
  # automatically, even though we're accumulating more and more objects,
  # because `threshold0` will never be exceeded.
  gc.collect(0)
  del ref
  # Temp() is now in generation-1 and eligible for collection, but gc.collect(1)
  # is never triggered, because there are no automatically invoked GCs at all.
  # Here we log the number of generation-1 objects, which continues to increase
  # until the process dies.
  print("Number of generation 1 objects: ", len(gc.get_objects(generation=1)))

Commenting out only the gc.collect(0) allows the Temp objects to be collected, and the process to run indefinitely. The fact that removing an explicit GC actually enables more GC to happen seems broken.

If what I think is happening is what's happening, then perhaps manually invoked GCs should not reset the GC's view on how many objects were allocated at the "last collection", since that would be what's effectively disabling the automatically triggered GCs (and hence the GCs at higher generations) from running.

CPython versions tested on:

3.11

Operating systems tested on:

macOS

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

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

はじめの一歩

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

調査の方向性

ソースファイルもテストも指定されていません。まず、提供された再現プログラムを CPython 3.11 で実行し、gc.collect(0) の挙動、自動コレクションのしきい値、generation-1 の増加を追跡してください。報告された相互作用を確認し、挙動が検証された場合は適切な回帰テストと修正を追加できれば完了です。

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

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

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

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