Skip to content

Even faster stack traces for _connection.py #2836

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 47 additions & 11 deletions playwright/_impl/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@
import inspect
import sys
import traceback
from inspect import FrameInfo
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Expand Down Expand Up @@ -362,7 +364,7 @@ def _send_message_to_server(
"params": self._replace_channels_with_guids(params),
"metadata": metadata,
}
if self._tracing_count > 0 and frames and object._guid != "localUtils":
if self.needs_full_stack_trace() and frames and object._guid != "localUtils":
self.local_utils.add_stack_to_tracing_no_reply(id, frames)

self._transport.send(message)
Expand Down Expand Up @@ -508,17 +510,44 @@ def _replace_guids_with_channels(self, payload: Any) -> Any:
return result
return payload

def needs_full_stack_trace(self) -> bool:
return self._tracing_count > 0

def get_frame_info(self) -> Iterator[FrameInfo]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just thinking out loud - why does it need to be an Iterator in order to get the faster stacktraces? I assume that we call it only when we actually need it in line 546 and 566?

Also should we maybe use this similar function in playwright/_impl/_sync_base.pyplaywright/_impl/_sync_base.py:108` ? Then sync users - what the majority is - would benefit as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As to your question: In the original code, when we were calling inspect.stack(0), it would immediately walk the entire stack (essentially, it would call frame.f_back in a loop until there were no more frames). This is pretty expensive. By using an iterator, we delay walking the stack until we need it, and then we can only walk part of the stack (because frame.f_back is only called when we need another frame)

Basically: Calling frame.f_back is more expensive than one might think.

Thanks for the heads up about playwright/_impl/_sync_base.pyplaywright/_impl/_sync_base.py:108! :) No wonder I couldn't find any information about __pw_stack__... I thought it was being set by asyncio, but it's actually being set by this package! XD

Let me take a look.

Copy link
Contributor Author

@neoncube2 neoncube2 May 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mxschmitt Now that I'm working on this again, I see what you mean about the iterator. I think that once I merge the logic in _sync_base.py and _connection.py, this PR should be a lot cleaner (and faster!) :)

current_frame = inspect.currentframe()

if current_frame is None:
return

# Don't include the current method ("get_frame_info()") in the callstack
current_frame = current_frame.f_back

while current_frame:
traceback_info = inspect.getframeinfo(current_frame, 0)

yield FrameInfo(
current_frame,
traceback_info.filename,
traceback_info.lineno,
traceback_info.function,
traceback_info.code_context,
traceback_info.index,
)

current_frame = current_frame.f_back

async def wrap_api_call(
self, cb: Callable[[], Any], is_internal: bool = False
) -> Any:
if self._api_zone.get():
return await cb()
task = asyncio.current_task(self._loop)
st: List[inspect.FrameInfo] = getattr(
task, "__pw_stack__", None
) or inspect.stack(0)

parsed_st = _extract_stack_trace_information_from_stack(st, is_internal)
st: Union[List[FrameInfo], Iterator[FrameInfo]] = (
getattr(task, "__pw_stack__", None) or self.get_frame_info()
)
parsed_st = _extract_stack_trace_information_from_stack(
st, is_internal, self.needs_full_stack_trace()
)
self._api_zone.set(parsed_st)
try:
return await cb()
Expand All @@ -533,10 +562,12 @@ def wrap_api_call_sync(
if self._api_zone.get():
return cb()
task = asyncio.current_task(self._loop)
st: List[inspect.FrameInfo] = getattr(
task, "__pw_stack__", None
) or inspect.stack(0)
parsed_st = _extract_stack_trace_information_from_stack(st, is_internal)
st: Union[List[FrameInfo], Iterator[FrameInfo]] = (
getattr(task, "__pw_stack__", None) or self.get_frame_info()
)
parsed_st = _extract_stack_trace_information_from_stack(
st, is_internal, self.needs_full_stack_trace()
)
self._api_zone.set(parsed_st)
try:
return cb()
Expand Down Expand Up @@ -567,7 +598,9 @@ class ParsedStackTrace(TypedDict):


def _extract_stack_trace_information_from_stack(
st: List[inspect.FrameInfo], is_internal: bool
st: Union[List[FrameInfo], Iterator[FrameInfo]],
is_internal: bool,
needs_full_stack: bool,
) -> ParsedStackTrace:
playwright_module_path = str(Path(playwright.__file__).parents[0])
last_internal_api_name = ""
Expand Down Expand Up @@ -596,6 +629,9 @@ def _extract_stack_trace_information_from_stack(
"function": method_name,
}
)

if not needs_full_stack:
break
if is_playwright_internal:
last_internal_api_name = method_name
elif last_internal_api_name:
Expand Down
Loading