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
分支
36k
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 摘要。