Skip to content

Commit a7a8fab

Browse files
authored
Update asyncio task lifecycle and frame handling to Python 3.15.2 (#9910)
* Update asyncio cancellation and incomplete-frame handling from CPython 3.15.2 Use update_lib while preserving the existing gather and shield adaptations and native thread-state test scope. Assisted-by: OpenAI Codex:GPT-6.1 * 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 933b014 commit a7a8fab

4 files changed

Lines changed: 194 additions & 36 deletions

File tree

‎Lib/asyncio/tasks.py‎

Lines changed: 9 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,11 @@ async def _wait_for_one(self, resolve=False):
628628
# Wait for the next future to be done and return it unless resolve is
629629
# set, in which case return either the result of the future or raise
630630
# an exception.
631-
f = await self._done.get()
631+
try:
632+
f = await self._done.get()
633+
except:
634+
self._todo_left += 1
635+
raise
632636
if f is None:
633637
# Dummy value from _handle_timeout().
634638
raise exceptions.TimeoutError
@@ -784,7 +788,7 @@ def cancel(self, msg=None):
784788
return ret
785789

786790

787-
def _discard_awaited_by(children, waiter, outer):
791+
def _discard_awaited_by(children, waiter):
788792
for fut in children:
789793
futures.future_discard_from_awaited_by(fut, waiter)
790794

@@ -850,11 +854,14 @@ def _done_callback(fut, cur_task=cur_task):
850854
# 'fut.exception()' will *raise* a CancelledError
851855
# instead of returning it.
852856
exc = fut._make_cancelled_error()
857+
# gh-157213: children outliving gather() must lose the edge
858+
_discard_awaited_by(children, cur_task)
853859
outer.set_exception(exc)
854860
return
855861
else:
856862
exc = fut.exception()
857863
if exc is not None:
864+
_discard_awaited_by(children, cur_task)
858865
outer.set_exception(exc)
859866
return
860867

@@ -922,10 +929,6 @@ def _done_callback(fut, cur_task=cur_task):
922929
children.append(fut)
923930

924931
outer = _GatheringFuture(children, loop=loop)
925-
if cur_task is not None:
926-
# gh-157213: a child outliving gather() must lose the awaited-by edge
927-
outer.add_done_callback(
928-
functools.partial(_discard_awaited_by, children, cur_task))
929932
# Run done callbacks after GatheringFuture created so any post-processing
930933
# can be performed at this point
931934
# optimization: in the special case that *all* futures finished eagerly,
@@ -936,25 +939,6 @@ def _done_callback(fut, cur_task=cur_task):
936939
return outer
937940

938941

939-
def _log_on_exception(fut):
940-
if fut.cancelled():
941-
return
942-
943-
exc = fut.exception()
944-
if exc is None:
945-
return
946-
947-
context = {
948-
'message':
949-
f'{exc.__class__.__name__} exception in shielded future',
950-
'exception': exc,
951-
'future': fut,
952-
}
953-
if fut._source_traceback:
954-
context['source_traceback'] = fut._source_traceback
955-
fut._loop.call_exception_handler(context)
956-
957-
958942
def shield(arg):
959943
"""Wait for a future, shielding it from cancellation.
960944
@@ -1019,9 +1003,6 @@ def _inner_done_callback(inner):
10191003
def _outer_done_callback(outer):
10201004
if not inner.done():
10211005
inner.remove_done_callback(_inner_done_callback)
1022-
# Keep only one callback to log on cancel
1023-
inner.remove_done_callback(_log_on_exception)
1024-
inner.add_done_callback(_log_on_exception)
10251006
if cur_task is not None:
10261007
inner.remove_done_callback(_clear_awaited_by_callback)
10271008
futures.future_discard_from_awaited_by(inner, cur_task)

‎Lib/asyncio/tools.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ def __init__(
2727
# ─── indexing helpers ───────────────────────────────────────────
2828
def _format_stack_entry(elem: str|FrameInfo) -> str:
2929
if not isinstance(elem, str):
30+
if elem.location is None:
31+
if elem.filename in ("", "~"):
32+
return f"{elem.funcname}"
33+
return f"{elem.funcname} {elem.filename}"
3034
if elem.location.lineno == 0 and elem.filename == "":
3135
return f"{elem.funcname}"
3236
else:
@@ -190,8 +194,7 @@ def build_task_table(result):
190194
# Build coroutine stack string
191195
frames = [frame for coro in task_info.coroutine_stack
192196
for frame in coro.call_stack]
193-
coro_stack = " -> ".join(_format_stack_entry(x).split(" ")[0]
194-
for x in frames)
197+
coro_stack = " -> ".join(x.funcname for x in frames)
195198

196199
# Handle tasks with no awaiters
197200
if not task_info.awaited_by:
@@ -202,8 +205,7 @@ def build_task_table(result):
202205
# Handle tasks with awaiters
203206
for coro_info in task_info.awaited_by:
204207
parent_id = coro_info.task_name
205-
awaiter_frames = [_format_stack_entry(x).split(" ")[0]
206-
for x in coro_info.call_stack]
208+
awaiter_frames = [x.funcname for x in coro_info.call_stack]
207209
awaiter_chain = " -> ".join(awaiter_frames)
208210
awaiter_name = id2name.get(parent_id, "Unknown")
209211
parent_id_str = (hex(parent_id) if isinstance(parent_id, int)

‎Lib/test/test_asyncio/test_tasks.py‎

Lines changed: 103 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
@@ -1669,6 +1702,46 @@ async def coro(i):
16691702
)
16701703
self.assertCountEqual(results, (0, 1, 2, 3))
16711704

1705+
def test_as_completed_async_iterator_cancelled_anext(self):
1706+
async def main():
1707+
loop = asyncio.get_running_loop()
1708+
a = loop.create_future()
1709+
b = loop.create_future()
1710+
iterator = asyncio.as_completed([a, b])
1711+
1712+
waiter = asyncio.create_task(anext(iterator))
1713+
await asyncio.sleep(0)
1714+
waiter.cancel()
1715+
with self.assertRaises(asyncio.CancelledError):
1716+
await waiter
1717+
1718+
a.set_result('a')
1719+
b.set_result('b')
1720+
return [await f async for f in iterator]
1721+
1722+
results = self.loop.run_until_complete(main())
1723+
self.assertCountEqual(results, ['a', 'b'])
1724+
1725+
def test_as_completed_plain_iterator_cancelled_wait(self):
1726+
async def main():
1727+
loop = asyncio.get_running_loop()
1728+
a = loop.create_future()
1729+
b = loop.create_future()
1730+
iterator = asyncio.as_completed([a, b])
1731+
1732+
waiter = asyncio.create_task(next(iterator))
1733+
await asyncio.sleep(0)
1734+
waiter.cancel()
1735+
with self.assertRaises(asyncio.CancelledError):
1736+
await waiter
1737+
1738+
a.set_result('a')
1739+
b.set_result('b')
1740+
return [await c for c in iterator]
1741+
1742+
results = self.loop.run_until_complete(main())
1743+
self.assertCountEqual(results, ['a', 'b'])
1744+
16721745
def test_as_completed_reverse_wait(self):
16731746
# Tests the plain iterator style of as_completed iteration to
16741747
# ensure that the first future awaited resolves to the first
@@ -2148,7 +2221,7 @@ def test_shield_cancel_outer(self):
21482221
self.assertTrue(outer.cancelled())
21492222
self.assertEqual(0, 0 if outer._callbacks is None else len(outer._callbacks))
21502223
self.assertFalse(inner._asyncio_awaited_by)
2151-
self.assertTrue({f for f, _ctx in inner._callbacks or []} <= {asyncio.tasks._log_on_exception})
2224+
self.assertFalse(inner._callbacks)
21522225

21532226
def test_shield_cancel_outer_result(self):
21542227
mock_handler = mock.Mock()
@@ -2163,6 +2236,8 @@ def test_shield_cancel_outer_result(self):
21632236
mock_handler.assert_not_called()
21642237

21652238
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.
21662241
mock_handler = mock.Mock()
21672242
self.loop.set_exception_handler(mock_handler)
21682243
inner = self.new_future(self.loop)
@@ -2172,7 +2247,29 @@ def test_shield_cancel_outer_exception(self):
21722247
test_utils.run_briefly(self.loop)
21732248
inner.set_exception(Exception('foo'))
21742249
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()
21752269
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)
21762273

21772274
def test_shield_cancel_outer_in_task(self):
21782275
inner = self.new_future(self.loop)
@@ -2187,9 +2284,9 @@ async def coro():
21872284
task = self.new_task(self.loop, coro())
21882285
self.loop.run_until_complete(task)
21892286
self.assertFalse(inner._asyncio_awaited_by)
2190-
self.assertTrue({f for f, _ctx in inner._callbacks or []} <= {asyncio.tasks._log_on_exception})
2287+
self.assertFalse(inner._callbacks)
21912288

2192-
def test_shield_duplicate_log_once(self):
2289+
def test_shield_cancel_outer_twice_exception(self):
21932290
mock_handler = mock.Mock()
21942291
self.loop.set_exception_handler(mock_handler)
21952292
inner = self.new_future(self.loop)
@@ -2201,9 +2298,11 @@ def test_shield_duplicate_log_once(self):
22012298
test_utils.run_briefly(self.loop)
22022299
outer.cancel()
22032300
test_utils.run_briefly(self.loop)
2301+
self.assertFalse(inner._callbacks)
22042302
inner.set_exception(Exception('foo'))
22052303
test_utils.run_briefly(self.loop)
2206-
mock_handler.assert_called_once()
2304+
mock_handler.assert_not_called()
2305+
self.assertIsInstance(inner.exception(), Exception)
22072306

22082307
def test_shield_shortcut(self):
22092308
fut = self.new_future(self.loop)

‎Lib/test/test_asyncio/test_tools.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1558,6 +1558,82 @@ def test_table_output_format(self):
15581558

15591559
class TestAsyncioToolsEdgeCases(unittest.TestCase):
15601560

1561+
def test_frames_without_location_tree(self):
1562+
"""Frames the unwinder could not fully read - should not crash."""
1563+
input_ = [
1564+
AwaitedInfo(
1565+
thread_id=1,
1566+
awaited_by=[
1567+
TaskInfo(
1568+
task_id=1,
1569+
task_name="Task-A",
1570+
coroutine_stack=[
1571+
CoroInfo(
1572+
call_stack=[
1573+
FrameInfo("<unreadable frame>", "~", None),
1574+
FrameInfo("<unknown function>", "app.py", None),
1575+
FrameInfo("big", "big.py", None),
1576+
],
1577+
task_name=1
1578+
)
1579+
],
1580+
awaited_by=[]
1581+
)
1582+
]
1583+
)
1584+
]
1585+
self.assertEqual(
1586+
tools.build_async_tree(input_),
1587+
[[
1588+
"└── (T) Task-A",
1589+
" └── big big.py",
1590+
" └── <unknown function> app.py",
1591+
" └── <unreadable frame>",
1592+
]],
1593+
)
1594+
1595+
def test_frames_without_location_table(self):
1596+
"""Frame names are not truncated at the first space."""
1597+
input_ = [
1598+
AwaitedInfo(
1599+
thread_id=1,
1600+
awaited_by=[
1601+
TaskInfo(
1602+
task_id=1,
1603+
task_name="Task-A",
1604+
coroutine_stack=[
1605+
CoroInfo(
1606+
call_stack=[
1607+
FrameInfo("<unreadable frame>", "~", None)
1608+
],
1609+
task_name=1
1610+
)
1611+
],
1612+
awaited_by=[
1613+
CoroInfo(
1614+
call_stack=[
1615+
FrameInfo("<unknown function>", "app.py", None)
1616+
],
1617+
task_name=2
1618+
)
1619+
]
1620+
)
1621+
]
1622+
)
1623+
]
1624+
self.assertEqual(
1625+
tools.build_task_table(input_),
1626+
[[
1627+
1,
1628+
"0x1",
1629+
"Task-A",
1630+
"<unreadable frame>",
1631+
"<unknown function>",
1632+
"Unknown",
1633+
"0x2",
1634+
]],
1635+
)
1636+
15611637
def test_task_awaits_self(self):
15621638
"""A task directly awaits itself - should raise a cycle."""
15631639
input_ = [

0 commit comments

Comments
 (0)