Skip to content

Commit 921e943

Browse files
authored
bpo-31970: Reduce performance overhead of asyncio debug mode. (#4314)
* bpo-31970: Reduce performance overhead of asyncio debug mode.
1 parent 1e5d54c commit 921e943

File tree

7 files changed

+38
-6
lines changed

7 files changed

+38
-6
lines changed

Lib/asyncio/base_events.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1223,6 +1223,11 @@ def default_exception_handler(self, context):
12231223
handler is set, and can be called by a custom exception
12241224
handler that wants to defer to the default behavior.
12251225
1226+
This default handler logs the error message and other
1227+
context-dependent information. In debug mode, a truncated
1228+
stack trace is also appended showing where the given object
1229+
(e.g. a handle or future or task) was created, if any.
1230+
12261231
The context parameter has the same meaning as in
12271232
`call_exception_handler()`.
12281233
"""

Lib/asyncio/constants.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,8 @@
55

66
# Seconds to wait before retrying accept().
77
ACCEPT_RETRY_DELAY = 1
8+
9+
# Number of stack entries to capture in debug mode.
10+
# The large the number, the slower the operation in debug mode
11+
# (see extract_stack() in events.py)
12+
DEBUG_STACK_DEPTH = 10

Lib/asyncio/coroutines.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import types
1111

1212
from . import compat
13+
from . import constants
1314
from . import events
1415
from . import base_futures
1516
from .log import logger
@@ -91,7 +92,7 @@ def __init__(self, gen, func=None):
9192
assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
9293
self.gen = gen
9394
self.func = func # Used to unwrap @coroutine decorator
94-
self._source_traceback = traceback.extract_stack(sys._getframe(1))
95+
self._source_traceback = events.extract_stack(sys._getframe(1))
9596
self.__name__ = getattr(gen, '__name__', None)
9697
self.__qualname__ = getattr(gen, '__qualname__', None)
9798

@@ -183,8 +184,9 @@ def __del__(self):
183184
tb = getattr(self, '_source_traceback', ())
184185
if tb:
185186
tb = ''.join(traceback.format_list(tb))
186-
msg += ('\nCoroutine object created at '
187-
'(most recent call last):\n')
187+
msg += (f'\nCoroutine object created at '
188+
f'(most recent call last, truncated to '
189+
f'{constants.DEBUG_STACK_DEPTH} last lines):\n')
188190
msg += tb.rstrip()
189191
logger.error(msg)
190192

Lib/asyncio/events.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
import threading
2020
import traceback
2121

22+
from . import constants
23+
2224

2325
def _get_function_source(func):
2426
func = inspect.unwrap(func)
@@ -72,6 +74,23 @@ def _format_callback_source(func, args):
7274
return func_repr
7375

7476

77+
def extract_stack(f=None, limit=None):
78+
"""Replacement for traceback.extract_stack() that only does the
79+
necessary work for asyncio debug mode.
80+
"""
81+
if f is None:
82+
f = sys._getframe().f_back
83+
if limit is None:
84+
# Limit the amount of work to a reasonable amount, as extract_stack()
85+
# can be called for each coroutine and future in debug mode.
86+
limit = constants.DEBUG_STACK_DEPTH
87+
stack = traceback.StackSummary.extract(traceback.walk_stack(f),
88+
limit=limit,
89+
lookup_lines=False)
90+
stack.reverse()
91+
return stack
92+
93+
7594
class Handle:
7695
"""Object returned by callback registration methods."""
7796

@@ -85,7 +104,7 @@ def __init__(self, callback, args, loop):
85104
self._cancelled = False
86105
self._repr = None
87106
if self._loop.get_debug():
88-
self._source_traceback = traceback.extract_stack(sys._getframe(1))
107+
self._source_traceback = extract_stack(sys._getframe(1))
89108
else:
90109
self._source_traceback = None
91110

Lib/asyncio/futures.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def __init__(self, *, loop=None):
7979
self._loop = loop
8080
self._callbacks = []
8181
if self._loop.get_debug():
82-
self._source_traceback = traceback.extract_stack(sys._getframe(1))
82+
self._source_traceback = events.extract_stack(sys._getframe(1))
8383

8484
_repr_info = base_futures._future_repr_info
8585

Lib/test/test_asyncio/test_tasks.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1981,7 +1981,7 @@ def coro_noop():
19811981

19821982
regex = (r'^<CoroWrapper %s\(?\)? .* at %s:%s, .*> '
19831983
r'was never yielded from\n'
1984-
r'Coroutine object created at \(most recent call last\):\n'
1984+
r'Coroutine object created at \(most recent call last, truncated to \d+ last lines\):\n'
19851985
r'.*\n'
19861986
r' File "%s", line %s, in test_coroutine_never_yielded\n'
19871987
r' coro_noop\(\)$'
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Reduce performance overhead of asyncio debug mode.

0 commit comments

Comments
 (0)