Data race between `sys._current_exceptions()` and a concurrently attaching thread
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug description:
In the free-threaded build, sys._current_exceptions() iterates every thread state under stop-the-world + HEAD_LOCK and reads t->thread_id.
But a newly started thread sets tstate->thread_id in bind_tstate() without holding HEAD_LOCK. Its PyThreadState is already on the interpreter's thread list by this point.
A thread that is still attaching is not yet stop-the-world-stoppable. _PyEval_StopTheWorldAll() therefore does not pause it, and its unlocked write to tstate->thread_id races the stop-the-world reader in _PyThread_CurrentExceptions.
Reproducer:
import sys
import threading
stop = threading.Event()
def reader(): # keep stop-the-world almost always active
for _ in range(20000):
sys._current_exceptions()
def churn(): # continuously attach new threads (bind_tstate)
for _ in range(20000):
t = threading.Thread(target=lambda: None)
t.start()
t.join()
readers = [threading.Thread(target=reader) for _ in range(8)]
churners = [threading.Thread(target=churn) for _ in range(4)]
for t in readers + churners: t.start()
for t in readers + churners: t.join()
TSAN Report:
WARNING: ThreadSanitizer: data race (pid=94157)
Read of size 8 at 0x0001081180b0 by thread T1:
#0 _PyThread_CurrentExceptions pystate.c:2817
#1 sys__current_exceptions sysmodule.c.h:1180
#2 cfunction_vectorcall_NOARGS methodobject.c:508
#3 PyObject_Vectorcall call.c:327
#4 _Py_VectorCallInstrumentation_StackRefSteal ceval.c:768
#5 _PyEval_EvalFrameDefault generated_cases.c.h:1906
...
Previous write of size 8 by thread T9:
#0 bind_tstate pystate.c:178
#1 _PyThreadState_Bind pystate.c:2660
#2 thread_run _threadmodule.c:384
#3 pythread_wrapper thread_pthread.h:234
SUMMARY: ThreadSanitizer: data race pystate.c:2817 in _PyThread_CurrentExceptions
CPython versions tested on:
CPython main branch
Operating systems tested on:
macOS
Linked PRs
- gh-152755
- gh-156202
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
先从 Python/pystate.c 中的 bind_tstate() 和 _PyThread_CurrentExceptions 开始,然后查看链接的 PR gh-152755 和 gh-156202。在 ThreadSanitizer 下运行提供的 free-threaded 复现程序,并验证报告的 thread_id 写入与读取之间的竞态已得到解决,且没有引入新的失败。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- operating-systems
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100