`groupby_next` data race on free-threaded builds
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
Two threads calling next on the same groupby object concurrently in a free-threaded build race on the currgrouper field, corrupting the iterator's internal state and producing AttributeError on slot accesses of live objects.
groupby_next has no Py_BEGIN_CRITICAL_SECTION guard. The first thing it does is write gbo->currgrouper = NULL:
Later, after the loop exits, it calls _grouper_create, which writes parent->currgrouper = igo:
If Thread A is past line 633 (just stored the new grouper pointer) while Thread B is at line 537 (about to store NULL), Thread B overwrites the pointer Thread A just wrote. Both are plain pointer stores with no synchronisation.
The following script reproduces the condition under which this happens.
import itertools, threading
class K:
__slots__ = ("v",)
def __init__(self, v): self.v = v
def __eq__(self, o): return isinstance(o, K) and self.v == o.v
def __hash__(self): return hash(self.v)
def consume(g):
try:
while True:
_, _ = next(g)
except StopIteration:
pass
keys = [K(i) for i in range(500_000)]
g = itertools.groupby(keys)
threads = [threading.Thread(target=consume, args=(g,)) for _ in range(8)]
for t in threads: t.start()
for t in threads: t.join()
On a free-threaded build, this results in the following Python logs...
Exception in Thread-15 (consume):
File "<python-input-2>", line 6, in __eq__
def __eq__(self, o): return isinstance(o, K) and self.v == o.v
^^^^^^
AttributeError: 'K' object has no attribute 'v'
... and the following TSan logs.
WARNING: ThreadSanitizer: data race (pid=20464)
Write of size 8 at 0x0003026e4a88 by thread T2:
#0 groupby_next itertoolsmodule.c:537 (python.exe:arm64+0x10042a8b8)
#1 builtin_next bltinmodule.c:1770
Previous write of size 8 at 0x0003026e4a88 by thread T1:
#0 _grouper_create itertoolsmodule.c:633 (python.exe:arm64+0x10042ac5c)
#1 groupby_next itertoolsmodule.c:570 (python.exe:arm64+0x10042ac5c)
#2 builtin_next bltinmodule.c:1770
CPython versions tested on:
CPython main branch
Operating systems tested on:
macOS
Linked PRs
- gh-150792
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Modules/itertoolsmodule.c 中的 groupby_next 和 _grouper_create 开始,然后在带有 ThreadSanitizer 的 free-threaded 构建上运行提供的并发 reproducer。完成的标准是 reproducer 不再报告 currgrouper race,也不再产生所描述的 AttributeError。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, python
- 领域
- backend, testing-qa
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100