python / python/cpython

asyncio.as_completed() raises "no running event loop" when created outside a running loop (3.14 regression)

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

还没有人认领这个 Issue。

主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

Since 3.14, asyncio.as_completed() raises RuntimeError: no running event loop when the iterator is created outside of a running event loop, even though the futures are then driven with loop.run_until_complete(). This pattern works on 3.13 and is the same pattern that asyncio.gather() still supports.

import asyncio

async def work(i):
    await asyncio.sleep(0.01 * i)
    return i

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
tasks = [loop.create_task(work(i)) for i in (2, 1)]
for f in asyncio.as_completed(tasks):
    print(loop.run_until_complete(f))
loop.close()

3.13:

1
2

main (and 3.14):

Traceback (most recent call last):
  File "repro.py", line 10, in <module>
    for f in asyncio.as_completed(tasks):
             ~~~~~~~~~~~~~~~~~~~~^^^^^^^
  File ".../Lib/asyncio/tasks.py", line 581, in __init__
    self._cur_task = current_task()
RuntimeError: no running event loop

The cause is the awaited-by tracking added in gh-91048: _AsCompletedIterator.__init__ calls current_task() unconditionally. gather() got the same tracking but guards it with events._get_running_loop() and falls back to cur_task = None (which future_add_to_awaited_by() already treats as a no-op). as_completed() should do the same.

I have a fix with a regression test ready.

CPython versions tested on:

CPython main branch, 3.14

Operating systems tested on:

macOS

Linked PRs
  • gh-157857

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 Lib/asyncio/tasks.py 中的 _AsCompletedIterator.init 开始,然后对比 asyncio.gather() 中相关的处理方式。检查 issue 中提到的回归测试,并运行相关的 asyncio 测试套件。当报告的 loop.run_until_complete() 模式能够在 3.14 上正常工作且不破坏现有的 asyncio 测试时,即视为完成。

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

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

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