Skip to content

Commit 37ecbb7

Browse files
authored
gh-162698: Fix awaited-by edges in asyncio.as_completed() (#162700)
1 parent 1f9c198 commit 37ecbb7

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
@@ -581,17 +581,11 @@ def __init__(self, aws, timeout):
581581
self._timeout_handle = None
582582

583583
loop = events.get_event_loop()
584-
# The iterator may be created outside of a running event loop and
585-
# then driven with loop.run_until_complete(), in which case there
586-
# is no current task to record as the waiter.
587-
if events._get_running_loop() is loop:
588-
self._cur_task = current_task(loop)
589-
else:
590-
self._cur_task = None
591584
todo = {ensure_future(aw, loop=loop) for aw in set(aws)}
585+
self._waiter = loop.create_future()
592586
for f in todo:
593587
f.add_done_callback(self._handle_completion)
594-
futures.future_add_to_awaited_by(f, self._cur_task)
588+
futures.future_add_to_awaited_by(f, self._waiter)
595589
if todo and timeout is not None:
596590
self._timeout_handle = (
597591
loop.call_later(timeout, self._handle_timeout)
@@ -622,15 +616,15 @@ def __next__(self):
622616
def _handle_timeout(self):
623617
for f in self._todo:
624618
f.remove_done_callback(self._handle_completion)
625-
futures.future_discard_from_awaited_by(f, self._cur_task)
619+
futures.future_discard_from_awaited_by(f, self._waiter)
626620
self._done.put_nowait(None) # Sentinel for _wait_for_one().
627621
self._todo.clear() # Can't do todo.remove(f) in the loop.
628622

629623
def _handle_completion(self, f):
630624
if not self._todo:
631625
return # _handle_timeout() was here first.
632626
self._todo.remove(f)
633-
futures.future_discard_from_awaited_by(f, self._cur_task)
627+
futures.future_discard_from_awaited_by(f, self._waiter)
634628
self._done.put_nowait(f)
635629
if not self._todo and self._timeout_handle is not None:
636630
self._timeout_handle.cancel()
@@ -639,11 +633,18 @@ async def _wait_for_one(self, resolve=False):
639633
# Wait for the next future to be done and return it unless resolve is
640634
# set, in which case return either the result of the future or raise
641635
# an exception.
636+
edge_added = False
642637
try:
638+
cur_task = current_task() if self._done.empty() else None
639+
futures.future_add_to_awaited_by(self._waiter, cur_task)
640+
edge_added = True
643641
f = await self._done.get()
644642
except:
645643
self._todo_left += 1
646644
raise
645+
finally:
646+
if edge_added:
647+
futures.future_discard_from_awaited_by(self._waiter, cur_task)
647648
if f is None:
648649
# Dummy value from _handle_timeout().
649650
raise exceptions.TimeoutError

‎Lib/test/test_asyncio/test_graph.py‎

Lines changed: 84 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -763,11 +763,12 @@ async def main(t):
763763
'T<inner>',
764764
['s capture_test_stack', 'a inner'],
765765
[
766-
['T<anon>',
767-
['a get', 'a _wait_for_one', 'a main',
768-
'a test_stack_as_completed'],
769-
[]
770-
]
766+
['F', [], [
767+
['T<anon>',
768+
['a get', 'a _wait_for_one', 'a main',
769+
'a test_stack_as_completed'],
770+
[]],
771+
]],
771772
]
772773
])
773774

@@ -796,14 +797,87 @@ async def main(t):
796797
'T<inner>',
797798
['s capture_test_stack', 'a inner'],
798799
[
799-
['T<anon>',
800-
['a get', 'a _wait_for_one', 'a main',
801-
'a test_stack_as_completed_timeout'],
802-
[]
803-
]
800+
['F', [], [
801+
['T<anon>',
802+
['a get', 'a _wait_for_one', 'a main',
803+
'a test_stack_as_completed_timeout'],
804+
[]],
805+
]],
804806
]
805807
])
806808

809+
async def test_as_completed_awaited_by_different_task(self):
810+
for get_next in (anext, next):
811+
with self.subTest(iterator=get_next.__name__):
812+
child = asyncio.get_running_loop().create_future()
813+
iterator = asyncio.as_completed([child])
814+
consumer = asyncio.create_task(
815+
get_next(iterator), eager_start=True)
816+
graph = asyncio.capture_call_graph(child, limit=0)
817+
child.set_result(None)
818+
await consumer
819+
820+
waiter, = graph.awaited_by
821+
self.assertEqual([node.future for node in waiter.awaited_by],
822+
[consumer])
823+
graph = asyncio.capture_call_graph(waiter.future, limit=0)
824+
self.assertFalse(graph.awaited_by)
825+
826+
async def test_as_completed_discards_awaited_by_on_cancel(self):
827+
for get_next in (anext, next):
828+
with self.subTest(iterator=get_next.__name__):
829+
loop = asyncio.get_running_loop()
830+
first, second = loop.create_future(), loop.create_future()
831+
iterator = asyncio.as_completed([first, second])
832+
cancelled = asyncio.create_task(
833+
get_next(iterator), eager_start=True)
834+
remaining = asyncio.create_task(
835+
get_next(iterator), eager_start=True)
836+
837+
before = asyncio.capture_call_graph(second, limit=0)
838+
cancelled.cancel()
839+
with self.assertRaises(asyncio.CancelledError):
840+
await cancelled
841+
after = asyncio.capture_call_graph(second, limit=0)
842+
843+
first.set_result(None)
844+
second.set_result(None)
845+
await remaining
846+
await get_next(iterator)
847+
848+
before_waiter, = before.awaited_by
849+
after_waiter, = after.awaited_by
850+
self.assertCountEqual(
851+
[node.future for node in before_waiter.awaited_by],
852+
[cancelled, remaining])
853+
self.assertEqual(
854+
[node.future for node in after_waiter.awaited_by],
855+
[remaining])
856+
857+
async def test_as_completed_discards_awaited_by_on_timeout(self):
858+
for get_next in (anext, next):
859+
with self.subTest(iterator=get_next.__name__):
860+
loop = asyncio.get_running_loop()
861+
first, second = loop.create_future(), loop.create_future()
862+
iterator = asyncio.as_completed([first, second], timeout=0)
863+
864+
graph = asyncio.capture_call_graph(first, limit=0)
865+
self.assertEqual(len(graph.awaited_by), 1)
866+
waiter = graph.awaited_by[0].future
867+
graph = asyncio.capture_call_graph(second, limit=0)
868+
self.assertEqual([node.future for node in graph.awaited_by],
869+
[waiter])
870+
871+
with self.assertRaises(TimeoutError):
872+
await get_next(iterator)
873+
874+
for child in (first, second):
875+
self.assertFalse(child.done())
876+
graph = asyncio.capture_call_graph(child, limit=0)
877+
self.assertFalse(graph.awaited_by)
878+
self.assertFalse(
879+
asyncio.capture_call_graph(waiter, limit=0).awaited_by)
880+
807881
async def test_stack_task(self):
808882

809883
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)