Skip to content

Commit cc6be88

Browse files
[3.15] gh-162698: Fix awaited-by edges in asyncio.as_completed() (GH-162700) (#162984)
gh-162698: Fix awaited-by edges in asyncio.as_completed() (GH-162700) (cherry picked from commit 37ecbb7) Co-authored-by: Timofei Ivankov <128279579+deadlovelll@users.noreply.github.com>
1 parent d37626b commit cc6be88

3 files changed

Lines changed: 97 additions & 20 deletions

File tree

‎Lib/asyncio/tasks.py‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -576,17 +576,11 @@ def __init__(self, aws, timeout):
576576
self._timeout_handle = None
577577

578578
loop = events.get_event_loop()
579-
# The iterator may be created outside of a running event loop and
580-
# then driven with loop.run_until_complete(), in which case there
581-
# is no current task to record as the waiter.
582-
if events._get_running_loop() is loop:
583-
self._cur_task = current_task(loop)
584-
else:
585-
self._cur_task = None
586579
todo = {ensure_future(aw, loop=loop) for aw in set(aws)}
580+
self._waiter = loop.create_future()
587581
for f in todo:
588582
f.add_done_callback(self._handle_completion)
589-
futures.future_add_to_awaited_by(f, self._cur_task)
583+
futures.future_add_to_awaited_by(f, self._waiter)
590584
if todo and timeout is not None:
591585
self._timeout_handle = (
592586
loop.call_later(timeout, self._handle_timeout)
@@ -617,15 +611,15 @@ def __next__(self):
617611
def _handle_timeout(self):
618612
for f in self._todo:
619613
f.remove_done_callback(self._handle_completion)
620-
futures.future_discard_from_awaited_by(f, self._cur_task)
614+
futures.future_discard_from_awaited_by(f, self._waiter)
621615
self._done.put_nowait(None) # Sentinel for _wait_for_one().
622616
self._todo.clear() # Can't do todo.remove(f) in the loop.
623617

624618
def _handle_completion(self, f):
625619
if not self._todo:
626620
return # _handle_timeout() was here first.
627621
self._todo.remove(f)
628-
futures.future_discard_from_awaited_by(f, self._cur_task)
622+
futures.future_discard_from_awaited_by(f, self._waiter)
629623
self._done.put_nowait(f)
630624
if not self._todo and self._timeout_handle is not None:
631625
self._timeout_handle.cancel()
@@ -634,11 +628,18 @@ async def _wait_for_one(self, resolve=False):
634628
# Wait for the next future to be done and return it unless resolve is
635629
# set, in which case return either the result of the future or raise
636630
# an exception.
631+
edge_added = False
637632
try:
633+
cur_task = current_task() if self._done.empty() else None
634+
futures.future_add_to_awaited_by(self._waiter, cur_task)
635+
edge_added = True
638636
f = await self._done.get()
639637
except:
640638
self._todo_left += 1
641639
raise
640+
finally:
641+
if edge_added:
642+
futures.future_discard_from_awaited_by(self._waiter, cur_task)
642643
if f is None:
643644
# Dummy value from _handle_timeout().
644645
raise exceptions.TimeoutError

‎Lib/test/test_asyncio/test_graph.py‎

Lines changed: 84 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -436,11 +436,12 @@ async def main(t):
436436
'T<inner>',
437437
['s capture_test_stack', 'a inner'],
438438
[
439-
['T<anon>',
440-
['a get', 'a _wait_for_one', 'a main',
441-
'a test_stack_as_completed'],
442-
[]
443-
]
439+
['F', [], [
440+
['T<anon>',
441+
['a get', 'a _wait_for_one', 'a main',
442+
'a test_stack_as_completed'],
443+
[]],
444+
]],
444445
]
445446
])
446447

@@ -469,14 +470,87 @@ async def main(t):
469470
'T<inner>',
470471
['s capture_test_stack', 'a inner'],
471472
[
472-
['T<anon>',
473-
['a get', 'a _wait_for_one', 'a main',
474-
'a test_stack_as_completed_timeout'],
475-
[]
476-
]
473+
['F', [], [
474+
['T<anon>',
475+
['a get', 'a _wait_for_one', 'a main',
476+
'a test_stack_as_completed_timeout'],
477+
[]],
478+
]],
477479
]
478480
])
479481

482+
async def test_as_completed_awaited_by_different_task(self):
483+
for get_next in (anext, next):
484+
with self.subTest(iterator=get_next.__name__):
485+
child = asyncio.get_running_loop().create_future()
486+
iterator = asyncio.as_completed([child])
487+
consumer = asyncio.create_task(
488+
get_next(iterator), eager_start=True)
489+
graph = asyncio.capture_call_graph(child, limit=0)
490+
child.set_result(None)
491+
await consumer
492+
493+
waiter, = graph.awaited_by
494+
self.assertEqual([node.future for node in waiter.awaited_by],
495+
[consumer])
496+
graph = asyncio.capture_call_graph(waiter.future, limit=0)
497+
self.assertFalse(graph.awaited_by)
498+
499+
async def test_as_completed_discards_awaited_by_on_cancel(self):
500+
for get_next in (anext, next):
501+
with self.subTest(iterator=get_next.__name__):
502+
loop = asyncio.get_running_loop()
503+
first, second = loop.create_future(), loop.create_future()
504+
iterator = asyncio.as_completed([first, second])
505+
cancelled = asyncio.create_task(
506+
get_next(iterator), eager_start=True)
507+
remaining = asyncio.create_task(
508+
get_next(iterator), eager_start=True)
509+
510+
before = asyncio.capture_call_graph(second, limit=0)
511+
cancelled.cancel()
512+
with self.assertRaises(asyncio.CancelledError):
513+
await cancelled
514+
after = asyncio.capture_call_graph(second, limit=0)
515+
516+
first.set_result(None)
517+
second.set_result(None)
518+
await remaining
519+
await get_next(iterator)
520+
521+
before_waiter, = before.awaited_by
522+
after_waiter, = after.awaited_by
523+
self.assertCountEqual(
524+
[node.future for node in before_waiter.awaited_by],
525+
[cancelled, remaining])
526+
self.assertEqual(
527+
[node.future for node in after_waiter.awaited_by],
528+
[remaining])
529+
530+
async def test_as_completed_discards_awaited_by_on_timeout(self):
531+
for get_next in (anext, next):
532+
with self.subTest(iterator=get_next.__name__):
533+
loop = asyncio.get_running_loop()
534+
first, second = loop.create_future(), loop.create_future()
535+
iterator = asyncio.as_completed([first, second], timeout=0)
536+
537+
graph = asyncio.capture_call_graph(first, limit=0)
538+
self.assertEqual(len(graph.awaited_by), 1)
539+
waiter = graph.awaited_by[0].future
540+
graph = asyncio.capture_call_graph(second, limit=0)
541+
self.assertEqual([node.future for node in graph.awaited_by],
542+
[waiter])
543+
544+
with self.assertRaises(TimeoutError):
545+
await get_next(iterator)
546+
547+
for child in (first, second):
548+
self.assertFalse(child.done())
549+
graph = asyncio.capture_call_graph(child, limit=0)
550+
self.assertFalse(graph.awaited_by)
551+
self.assertFalse(
552+
asyncio.capture_call_graph(waiter, limit=0).awaited_by)
553+
480554
async def test_stack_task(self):
481555

482556
stack_for_inner = None
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix the asyncio call graph to show the task waiting for the next result from
2+
asyncio.as_completed(). Patch by Timofei Ivankov.

0 commit comments

Comments
 (0)