Skip to content

Commit 850f486

Browse files
committed
Include canonical gather and shield lifecycle fixes in asyncio update
Preserve existing native thread-state scope while migrating the related task lifecycle tests. Both production modules now match CPython 3.15.2 exactly. Assisted-by: OpenAI Codex:GPT-6.1
1 parent d96a854 commit 850f486

2 files changed

Lines changed: 67 additions & 31 deletions

File tree

‎Lib/asyncio/tasks.py‎

Lines changed: 4 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ def cancel(self, msg=None):
788788
return ret
789789

790790

791-
def _discard_awaited_by(children, waiter, outer):
791+
def _discard_awaited_by(children, waiter):
792792
for fut in children:
793793
futures.future_discard_from_awaited_by(fut, waiter)
794794

@@ -854,11 +854,14 @@ def _done_callback(fut, cur_task=cur_task):
854854
# 'fut.exception()' will *raise* a CancelledError
855855
# instead of returning it.
856856
exc = fut._make_cancelled_error()
857+
# gh-157213: children outliving gather() must lose the edge
858+
_discard_awaited_by(children, cur_task)
857859
outer.set_exception(exc)
858860
return
859861
else:
860862
exc = fut.exception()
861863
if exc is not None:
864+
_discard_awaited_by(children, cur_task)
862865
outer.set_exception(exc)
863866
return
864867

@@ -926,10 +929,6 @@ def _done_callback(fut, cur_task=cur_task):
926929
children.append(fut)
927930

928931
outer = _GatheringFuture(children, loop=loop)
929-
if cur_task is not None:
930-
# gh-157213: a child outliving gather() must lose the awaited-by edge
931-
outer.add_done_callback(
932-
functools.partial(_discard_awaited_by, children, cur_task))
933932
# Run done callbacks after GatheringFuture created so any post-processing
934933
# can be performed at this point
935934
# optimization: in the special case that *all* futures finished eagerly,
@@ -940,25 +939,6 @@ def _done_callback(fut, cur_task=cur_task):
940939
return outer
941940

942941

943-
def _log_on_exception(fut):
944-
if fut.cancelled():
945-
return
946-
947-
exc = fut.exception()
948-
if exc is None:
949-
return
950-
951-
context = {
952-
'message':
953-
f'{exc.__class__.__name__} exception in shielded future',
954-
'exception': exc,
955-
'future': fut,
956-
}
957-
if fut._source_traceback:
958-
context['source_traceback'] = fut._source_traceback
959-
fut._loop.call_exception_handler(context)
960-
961-
962942
def shield(arg):
963943
"""Wait for a future, shielding it from cancellation.
964944
@@ -1023,9 +1003,6 @@ def _inner_done_callback(inner):
10231003
def _outer_done_callback(outer):
10241004
if not inner.done():
10251005
inner.remove_done_callback(_inner_done_callback)
1026-
# Keep only one callback to log on cancel
1027-
inner.remove_done_callback(_log_on_exception)
1028-
inner.add_done_callback(_log_on_exception)
10291006
if cur_task is not None:
10301007
inner.remove_done_callback(_clear_awaited_by_callback)
10311008
futures.future_discard_from_awaited_by(inner, cur_task)

‎Lib/test/test_asyncio/test_tasks.py‎

Lines changed: 63 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Tests for tasks.py."""
22

3+
import _thread
34
import collections
45
import contextlib
56
import contextvars
@@ -19,6 +20,7 @@
1920
from asyncio import tasks
2021
from test.test_asyncio import utils as test_utils
2122
from test import support
23+
from test.support import threading_helper
2224
from test.support.script_helper import assert_python_ok
2325
from test.support.warnings_helper import ignore_warnings
2426

@@ -1250,6 +1252,37 @@ async def coro():
12501252

12511253
self.loop.run_until_complete(self.new_task(self.loop, coro()))
12521254

1255+
def test_gather_discards_awaited_by_for_cancelled_sibling(self):
1256+
# gh-157213: same, when gather() is ended by a cancelled child
1257+
async def survivor():
1258+
await asyncio.Future()
1259+
1260+
async def coro():
1261+
t = self.new_task(self.loop, survivor())
1262+
victim = self.new_task(self.loop, asyncio.sleep(10))
1263+
victim.cancel()
1264+
with self.assertRaises(asyncio.CancelledError):
1265+
await asyncio.gather(t, victim)
1266+
self.assertFalse(t._asyncio_awaited_by)
1267+
t.cancel()
1268+
with self.assertRaises(asyncio.CancelledError):
1269+
await t
1270+
1271+
self.loop.run_until_complete(self.new_task(self.loop, coro()))
1272+
1273+
def test_gather_does_not_add_callback_to_outer(self):
1274+
# gh-158239: gather() must not add an internal done callback to
1275+
# the outer future just to maintain the await graph.
1276+
async def child():
1277+
await asyncio.sleep(0)
1278+
1279+
async def coro():
1280+
outer = asyncio.gather(child(), child())
1281+
self.assertFalse(outer._callbacks)
1282+
await outer
1283+
1284+
self.loop.run_until_complete(self.new_task(self.loop, coro()))
1285+
12531286
def test_wait_really_done(self):
12541287
# there is possibility that some tasks in the pending list
12551288
# became done but their callbacks haven't all been called yet
@@ -2188,7 +2221,7 @@ def test_shield_cancel_outer(self):
21882221
self.assertTrue(outer.cancelled())
21892222
self.assertEqual(0, 0 if outer._callbacks is None else len(outer._callbacks))
21902223
self.assertFalse(inner._asyncio_awaited_by)
2191-
self.assertTrue({f for f, _ctx in inner._callbacks or []} <= {asyncio.tasks._log_on_exception})
2224+
self.assertFalse(inner._callbacks)
21922225

21932226
def test_shield_cancel_outer_result(self):
21942227
mock_handler = mock.Mock()
@@ -2203,6 +2236,8 @@ def test_shield_cancel_outer_result(self):
22032236
mock_handler.assert_not_called()
22042237

22052238
def test_shield_cancel_outer_exception(self):
2239+
# gh-156321: an exception in the inner future must not be reported
2240+
# eagerly, as it may still be retrieved later.
22062241
mock_handler = mock.Mock()
22072242
self.loop.set_exception_handler(mock_handler)
22082243
inner = self.new_future(self.loop)
@@ -2212,7 +2247,29 @@ def test_shield_cancel_outer_exception(self):
22122247
test_utils.run_briefly(self.loop)
22132248
inner.set_exception(Exception('foo'))
22142249
test_utils.run_briefly(self.loop)
2250+
mock_handler.assert_not_called()
2251+
self.assertIsInstance(inner.exception(), Exception)
2252+
2253+
def test_shield_cancel_outer_exception_never_retrieved(self):
2254+
# gh-156321: an exception nobody retrieves is reported by the inner
2255+
# future itself when it is garbage collected, like any other future.
2256+
mock_handler = mock.Mock()
2257+
self.loop.set_exception_handler(mock_handler)
2258+
inner = self.new_future(self.loop)
2259+
outer = asyncio.shield(inner)
2260+
test_utils.run_briefly(self.loop)
2261+
outer.cancel()
2262+
test_utils.run_briefly(self.loop)
2263+
inner.set_exception(Exception('foo'))
2264+
test_utils.run_briefly(self.loop)
2265+
mock_handler.assert_not_called()
2266+
inner = None
2267+
outer = None
2268+
support.gc_collect()
22152269
mock_handler.assert_called_once()
2270+
context = mock_handler.call_args[0][1]
2271+
self.assertEndsWith(context['message'], 'exception was never retrieved')
2272+
self.assertIsInstance(context['exception'], Exception)
22162273

22172274
def test_shield_cancel_outer_in_task(self):
22182275
inner = self.new_future(self.loop)
@@ -2227,9 +2284,9 @@ async def coro():
22272284
task = self.new_task(self.loop, coro())
22282285
self.loop.run_until_complete(task)
22292286
self.assertFalse(inner._asyncio_awaited_by)
2230-
self.assertTrue({f for f, _ctx in inner._callbacks or []} <= {asyncio.tasks._log_on_exception})
2287+
self.assertFalse(inner._callbacks)
22312288

2232-
def test_shield_duplicate_log_once(self):
2289+
def test_shield_cancel_outer_twice_exception(self):
22332290
mock_handler = mock.Mock()
22342291
self.loop.set_exception_handler(mock_handler)
22352292
inner = self.new_future(self.loop)
@@ -2241,9 +2298,11 @@ def test_shield_duplicate_log_once(self):
22412298
test_utils.run_briefly(self.loop)
22422299
outer.cancel()
22432300
test_utils.run_briefly(self.loop)
2301+
self.assertFalse(inner._callbacks)
22442302
inner.set_exception(Exception('foo'))
22452303
test_utils.run_briefly(self.loop)
2246-
mock_handler.assert_called_once()
2304+
mock_handler.assert_not_called()
2305+
self.assertIsInstance(inner.exception(), Exception)
22472306

22482307
def test_shield_shortcut(self):
22492308
fut = self.new_future(self.loop)

0 commit comments

Comments
 (0)