python / python/cpython

LOAD_ATTR specialization for ModuleType subclasses bypasses data descriptors on the subclass (3.14 regression)

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

还没有人认领这个 Issue。

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

描述

Bug report

Bug description:

Since 3.14, attribute loads on an instance of a types.ModuleType
subclass are specialized to LOAD_ATTR_MODULE, which reads the module
dictionary directly. The specialization does not check whether the
subclass defines a data descriptor for the name, so after the first
access a data descriptor on the subclass is silently bypassed and the
dictionary value is returned instead. Before 3.14 the guard was
PyModule_CheckExact, so subclasses never took this path and the
descriptor was honoured on every access.

The following runs the reproducer on 3.13, 3.14, 3.14t, 3.15 and
3.15t using uv:

for v in 3.13 3.14 3.14t 3.15 3.15t; do uv run --no-project --python $v python - <<'EOF'
import sys
import sysconfig
import types


class Desc:
    def __get__(self, instance, owner=None):
        return "from descriptor"

    def __set__(self, instance, value):
        instance.__dict__["x"] = value


class Module(types.ModuleType):
    pass


Module.x = Desc()

m = Module("m")
m.__dict__["x"] = "from dict"

build = "free-threaded" if sysconfig.get_config_var("Py_GIL_DISABLED") else "default"
print(sys.version.split()[0], build, [m.x for _ in range(4)])
EOF
done

Output:

3.13.15 default ['from descriptor', 'from descriptor', 'from descriptor', 'from descriptor']
3.14.7 default ['from descriptor', 'from dict', 'from dict', 'from dict']
3.14.7 free-threaded ['from descriptor', 'from dict', 'from dict', 'from dict']
3.15.0rc1 default ['from descriptor', 'from dict', 'from dict', 'from dict']
3.15.0rc1 free-threaded ['from descriptor', 'from dict', 'from dict', 'from dict']

Expected output is four "from descriptor" values on every version, as
on 3.13.

The first access runs through the general path and honours the
descriptor; the instruction is then specialized and subsequent
executions read m.__dict__["x"]. getattr(m, "x") returns
"from descriptor" every time, since it does not go through the
specialized instruction, so the same expression gives different
answers depending on how it is spelled and how many times it has run.

Expected: a data descriptor on the type takes precedence over the
instance dictionary for a module subclass exactly as it does for any
other class, and as it did on 3.13 and earlier.

Observed on 3.14.7 and 3.15.0rc1, both default and free-threaded
builds; the same code is on main.

Cause

In Python/specialize.c, _Py_Specialize_LoadAttr selects the module
path with

else if (Py_TYPE(owner)->tp_getattro == PyModule_Type.tp_getattro) {
    fail = specialize_module_load_attr(owner, instr, name);
}

which any ModuleType subclass that does not override
__getattribute__ or __getattr__ satisfies.
specialize_module_load_attr_lock_held then only inspects the module
dictionary (unicode keys, no __getattr__ entry, the name present,
a keys version); it never looks the name up on the type. The guard of
the emitted LOAD_ATTR_MODULE is likewise only the dict keys version,
so a descriptor added to the type later is not noticed either.

This came in with gh-103951 ("Fast attribute access for module
subclasses", PR #126264, merged 2024-11-15), which relaxed the guard
from PyModule_CheckExact for speed. The discussion there was about
keeping the guard cheap: PyModule_Check was rejected because it
walks the MRO, and the tp_getattro comparison was chosen as a single
pointer compare that admits only types with module attribute
semantics. The stated motivation was the "Customizing module attribute
access" pattern from the data model docs, that is, assigning a
ModuleType subclass to a module's __class__. Neither the issue
comments nor the PR body, review threads or comments mention
descriptors, property, or type version tags, so this looks like an
unintended consequence rather than a decision. A search of the
tracker (LOAD_ATTR_MODULE, module subclass descriptor, ModuleType
subclass property, and similar) found no prior report.

Impact

Any library that assigns a ModuleType subclass to a module's
__class__ in order to intercept attribute access with descriptors
(the documented route for module-level properties and lazy
attributes, per the "Customizing module attribute access" section of
the data model docs) sees the interception disappear after the first
access on 3.14+. The workaround is to define a __getattribute__ on
the subclass that delegates to the base, which gives the type its own
tp_getattro and so avoids the specialization, at the cost of a
Python-level call on every attribute access to that module.

Encountered in wrapture (https://github.com/GrahamDumpleton/wrapture),
which uses exactly this technique to intercept module attribute access;
repro above is reduced from that.

AI Disclaimer

This was a real problem I encountered, but have had AI generate the report for me so more clearly explained. The AI did generate a suggested fix as well, but I am not in a position to evaluate whether it is correct so have not included it. If want AI generated suggested fix then let me know.

CPython versions tested on:

3.14

Operating systems tested on:

macOS

Linked PRs
  • gh-156474

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 Python/specialize.c 中的 _Py_Specialize_LoadAttr 和 specialize_module_load_attr_lock_held 开始,然后检查报告中描述的 LOAD_ATTR_MODULE guard。在受影响的版本中运行提供的 ModuleType 子类复现程序,并检查现有的 specialization 测试。当重复的属性加载始终遵循该子类的数据描述符,并且有回归覆盖时,即表示完成。

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

评估

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

把新 issue 发到你的邮箱

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