python / python/cpython

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

Aperta
#157,856 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
Python
Stelle
77.2k
Fork
36k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia in Lib/asyncio/tasks.py, in _AsCompletedIterator.init, quindi confronta la gestione correlata in asyncio.gather(). Esamina il test di regressione menzionato nell’issue ed esegui la suite di test asyncio pertinente. Il lavoro è completato quando il pattern segnalato di loop.run_until_complete() funziona su 3.14 senza rompere i test asyncio esistenti.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
backend
Tipo di issue
Bug
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.