ABC causing massive memory swell

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

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

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
25/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
python
領域
compilers

調査の方向性

まず、提供された再現コードを影響を受ける Python バージョンで実行し、issubclass ループ中のメモリを測定します。関係する ABCMeta と issubclass の動作を読み、その後、結果を issue #92810 および pydantic #3829 と比較します。キャッシュの増大とサブクラスツリーの走査に対処し、ABC の登録動作を後退させない、合意済みでテスト済みのアプローチが得られれば完了です。

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

説明

3.12 performance stdlib type-bug

Bug report

from abc import ABC, ABCMeta
from datetime import datetime


abcclasses = set()

normalclasses = set()

for i in range(10000):
    abcclasses.add(ABCMeta("abc_"+str(i), (ABC, ), {}))
    normalclasses.add(type("normal_"+str(i), (object,), {}))


if __name__ == '__main__':

    starttime = datetime.now()
    import os, psutil
    process = psutil.Process(os.getpid())
    mb = 1024 * 1024
    mem = last = process.memory_info().rss
    print(f'{i + 1:>4d} {mem / mb:8.2f}MB {(mem - last) / mb:+8.2f}MB | {"━" * int(mem / 8_000_000)}')
    for item in normalclasses:
        issubclass(item, ABC)

    mem = process.memory_info().rss
    print(f'{i + 1:>4d} {mem / mb:8.2f}MB {(mem - last) / mb:+8.2f}MB | {"━" * int(mem / 8_000_000)}')
    print(f"This took {datetime.now()-starttime}")

Your environment

Running this takes several minutes and consumes over 20 gbs of memory.

I've checked it against python 3.8-3.10. The issue is just that ABC caches every single issubclass evaluation combined with it searching its entire subclass tree recursively causes it to grind to a halt if you have any significant number of subclass 10k sub classes of ABC and 10k normal classes being compared to the base ABC climbs to over 20 GBs. I am not really sure it is necessary to check the entire subclass tree. I presume it is because of concerns about register calls happening low in the class tree.

It would likely be far more efficient to chase upward the calls to register and place those in the parent classes then to search the entire class hierarchy. This can get really aggressive performance issues if you have any multiple inheritance structures going on as well as those will get checked multiple times.

See these issues.
https://github.com/python/cpython/issues/92810
https://github.com/samuelcolvin/pydantic/issues/3829

主要言語
Python
スター
77.2k
フォーク
36k
平均マージ
1日 9時間
マージ済み PR(30日)
558

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

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

はじめの一歩

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

python/cpython のほかの issue

python/cpython の issue をすべて見る

似ている issue

Python の issue をもっと見る

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

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