python / python/cpython

C call specialization misses with `METH_CLASS`, `METH_STATIC` or `METH_COEXIST`

未关闭
#157,833 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

The specializer ignores METH_CLASS, METH_STATIC and METH_COEXIST when selecting a specialized C-call instruction, but the corresponding flag guards compare all flags. Affected calls fail these guards and fall back to generic CALL, even after repeated specialization. Return values are correct.

Save this as repro.py and run PYTHON_JIT=0 python repro.py with CPython 3.13 or newer:

import dis
import math


def counter(f):
    call = [i for i in dis.get_instructions(f, adaptive=True)
            if i.baseopname == "CALL"][-1]
    cache = {name: data for name, _, data in call.cache_info}
    return call.opname, cache["counter"]


def control():
    math.gcd(4, 6)


def affected():
    dict.fromkeys((), None)


for f in control, affected:
    for _ in range(100):
        f()
    before = counter(f)
    for _ in range(10):
        f()
    print(f.__name__, before[0], "hit" if counter(f) == before else "miss")

Output from an unpatched Linux build of 5539c2a5437 (3.16.0a0):

control CALL_BUILTIN_FAST hit
affected CALL_BUILTIN_FAST miss

Both call sites should report hit. The example detects misses by comparing the adaptive counter before and after ten calls.

For dict.fromkeys, the specializer masks out METH_CLASS and selects CALL_BUILTIN_FAST, but its guard requires exactly METH_FASTCALL. The actual flags are METH_FASTCALL | METH_CLASS. The method-descriptor guards and corresponding Tier 2 optimizer checks have the same mismatch.

I also reproduced the issue on Linux with CPython 3.13.14, 3.14.7, 3.14.7 free-threaded and 3.15.0rc2.

More cases, pystats results, timing measurements and source analysis.

I have a patch with Tier 1 and Tier 2 regression tests and will open a PR.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-157834

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

将提供的示例保存为 repro.py,并在 CPython 3.13 或更高版本上使用 PYTHON_JIT=0 运行,以复现 adaptive-counter misses。阅读 Python/specialize.c 中引用的 specialization,以及 Python/bytecodes.c 中的 guard 和 Tier 2 检查。完成标准是两个 call site 都报告 hit,并且 Tier 1 和 Tier 2 regression tests 覆盖受影响的 flags。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
活跃
描述清晰度
描述清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。