| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import math |
| 5 |
import typing |
| 6 |
import uuid |
| 7 |
from typing import Callable, Sequence |
| 8 |
|
| 9 |
from pyinstrument.frame_info import ( |
| 10 |
ATTRIBUTE_MARKER_CLASS_NAME, |
| 11 |
ATTRIBUTE_MARKER_TRACEBACKHIDE, |
| 12 |
frame_info_get_identifier, |
| 13 |
parse_frame_info, |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
AWAIT_FRAME_IDENTIFIER = "[await]" |
| 22 |
SELF_TIME_FRAME_IDENTIFIER = "[self]" |
| 23 |
OUT_OF_CONTEXT_FRAME_IDENTIFIER = "[out-of-context]" |
| 24 |
DUMMY_ROOT_FRAME_IDENTIFIER = "[root]" |
| 25 |
|
| 26 |
SYNTHETIC_FRAME_IDENTIFIERS = frozenset( |
| 27 |
[ |
| 28 |
AWAIT_FRAME_IDENTIFIER, |
| 29 |
SELF_TIME_FRAME_IDENTIFIER, |
| 30 |
OUT_OF_CONTEXT_FRAME_IDENTIFIER, |
| 31 |
DUMMY_ROOT_FRAME_IDENTIFIER, |
| 32 |
] |
| 33 |
) |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
SYNTHETIC_LEAF_IDENTIFIERS = frozenset( |
| 38 |
[ |
| 39 |
AWAIT_FRAME_IDENTIFIER, |
| 40 |
SELF_TIME_FRAME_IDENTIFIER, |
| 41 |
OUT_OF_CONTEXT_FRAME_IDENTIFIER, |
| 42 |
] |
| 43 |
) |
| 44 |
|
| 45 |
|
| 46 |
class FrameContext(typing.Protocol): |
| 47 |
def shorten_path(self, path: str) -> str: ... |
| 48 |
@property |
| 49 |
def sys_prefixes(self) -> Sequence[str]: ... |
| 50 |
|
| 51 |
|
| 52 |
class Frame: |
| 53 |
""" |
| 54 |
Object that represents a stack frame in the parsed tree |
| 55 |
""" |
| 56 |
|
| 57 |
parent: Frame | None |
| 58 |
group: FrameGroup | None |
| 59 |
time: float |
| 60 |
|
| 61 |
|
| 62 |
_context: FrameContext | None |
| 63 |
|
| 64 |
|
| 65 |
absorbed_time: float |
| 66 |
|
| 67 |
attributes: dict[str, float] |
| 68 |
|
| 69 |
def __init__( |
| 70 |
self, |
| 71 |
identifier_or_frame_info: str = "", |
| 72 |
children: Sequence[Frame] | None = None, |
| 73 |
time: float = 0, |
| 74 |
context: FrameContext | None = None, |
| 75 |
): |
| 76 |
identifier = frame_info_get_identifier(identifier_or_frame_info) |
| 77 |
self.identifier = identifier |
| 78 |
self.parent = None |
| 79 |
self.time = 0.0 |
| 80 |
self.group = None |
| 81 |
self.absorbed_time = 0.0 |
| 82 |
self._context = context |
| 83 |
|
| 84 |
self._identifier_parts = identifier.split("\x00") |
| 85 |
self.attributes = {} |
| 86 |
self._children = [] |
| 87 |
|
| 88 |
self.record_time_from_frame_info(frame_info=identifier_or_frame_info, time=time) |
| 89 |
|
| 90 |
if children: |
| 91 |
for child in children: |
| 92 |
self.add_child(child) |
| 93 |
|
| 94 |
def record_time_from_frame_info(self, frame_info: str, time: float): |
| 95 |
self.time += time |
| 96 |
|
| 97 |
_, attributes_list = parse_frame_info(frame_info) |
| 98 |
|
| 99 |
for attribute in attributes_list: |
| 100 |
try: |
| 101 |
self.attributes[attribute] += time |
| 102 |
except KeyError: |
| 103 |
self.attributes[attribute] = time |
| 104 |
|
| 105 |
def remove_from_parent(self): |
| 106 |
""" |
| 107 |
Removes this frame from its parent, and nulls the parent link |
| 108 |
""" |
| 109 |
if self.parent: |
| 110 |
self.parent._children.remove(self) |
| 111 |
self.parent = None |
| 112 |
|
| 113 |
@property |
| 114 |
def context(self): |
| 115 |
if not self._context: |
| 116 |
raise RuntimeError("Frame has no context") |
| 117 |
return self._context |
| 118 |
|
| 119 |
def set_context(self, context: FrameContext | None): |
| 120 |
self._context = context |
| 121 |
for child in self._children: |
| 122 |
child.set_context(context) |
| 123 |
|
| 124 |
@staticmethod |
| 125 |
def new_subclass_with_frame_info(frame_info: str) -> Frame: |
| 126 |
|
| 127 |
return Frame(identifier_or_frame_info=frame_info) |
| 128 |
|
| 129 |
@property |
| 130 |
def proportion_of_parent(self) -> float: |
| 131 |
if self.parent: |
| 132 |
try: |
| 133 |
return self.time / self.parent.time |
| 134 |
except ZeroDivisionError: |
| 135 |
return float("nan") |
| 136 |
else: |
| 137 |
return 1.0 |
| 138 |
|
| 139 |
@property |
| 140 |
def total_self_time(self) -> float: |
| 141 |
""" |
| 142 |
The total amount of self time in this frame (including self time recorded by SelfTimeFrame |
| 143 |
children, and await time from AwaitTimeFrame children) |
| 144 |
""" |
| 145 |
|
| 146 |
|
| 147 |
self_time = self.time |
| 148 |
real_children = [c for c in self.children if not c.is_synthetic] |
| 149 |
|
| 150 |
for child in real_children: |
| 151 |
self_time -= child.time |
| 152 |
|
| 153 |
return self_time |
| 154 |
|
| 155 |
@property |
| 156 |
def function(self) -> str: |
| 157 |
return self._identifier_parts[0] |
| 158 |
|
| 159 |
@property |
| 160 |
def file_path(self) -> str | None: |
| 161 |
if len(self._identifier_parts) > 1: |
| 162 |
return self._identifier_parts[1] |
| 163 |
|
| 164 |
@property |
| 165 |
def line_no(self) -> int | None: |
| 166 |
if len(self._identifier_parts) > 2: |
| 167 |
return int(self._identifier_parts[2]) |
| 168 |
|
| 169 |
@property |
| 170 |
def file_path_short(self) -> str | None: |
| 171 |
"""Return the path resolved against the closest entry in sys.path""" |
| 172 |
if self.is_synthetic and self.parent: |
| 173 |
return self.parent.file_path_short |
| 174 |
|
| 175 |
if not self.file_path: |
| 176 |
return None |
| 177 |
|
| 178 |
return self.context.shorten_path(self.file_path) |
| 179 |
|
| 180 |
@property |
| 181 |
def is_application_code(self) -> bool: |
| 182 |
if self.is_synthetic: |
| 183 |
return False |
| 184 |
|
| 185 |
file_path = self.file_path |
| 186 |
|
| 187 |
if not file_path: |
| 188 |
return False |
| 189 |
|
| 190 |
if any(file_path.startswith(p) for p in self.context.sys_prefixes): |
| 191 |
|
| 192 |
return False |
| 193 |
|
| 194 |
if file_path.startswith("<"): |
| 195 |
if file_path.startswith("<ipython-input-"): |
| 196 |
|
| 197 |
return True |
| 198 |
elif file_path == "<string>" or file_path == "<stdin>": |
| 199 |
|
| 200 |
|
| 201 |
if self.parent: |
| 202 |
return self.parent.is_application_code |
| 203 |
else: |
| 204 |
|
| 205 |
|
| 206 |
return True |
| 207 |
else: |
| 208 |
|
| 209 |
return False |
| 210 |
|
| 211 |
return True |
| 212 |
|
| 213 |
def code_position_short(self) -> str | None: |
| 214 |
file_path_short = self.file_path_short |
| 215 |
if file_path_short and self.line_no: |
| 216 |
return "%s:%i" % (file_path_short, self.line_no) |
| 217 |
return file_path_short |
| 218 |
|
| 219 |
_children: list[Frame] |
| 220 |
attributes: dict[str, float] |
| 221 |
|
| 222 |
def add_child(self, frame: Frame, after: Frame | None = None): |
| 223 |
""" |
| 224 |
Adds a child frame, updating the parent link. |
| 225 |
Optionally, insert the frame in a specific position by passing the frame to insert |
| 226 |
this one after. |
| 227 |
""" |
| 228 |
|
| 229 |
if self.identifier in SYNTHETIC_LEAF_IDENTIFIERS: |
| 230 |
raise ValueError("Cannot add children to a leaf-only frame") |
| 231 |
|
| 232 |
frame.remove_from_parent() |
| 233 |
frame.parent = self |
| 234 |
frame.set_context(self._context) |
| 235 |
if after is None: |
| 236 |
self._children.append(frame) |
| 237 |
else: |
| 238 |
index = self._children.index(after) + 1 |
| 239 |
self._children.insert(index, frame) |
| 240 |
|
| 241 |
def add_children(self, frames: Sequence[Frame], after: Frame | None = None): |
| 242 |
""" |
| 243 |
Convenience method to add multiple frames at once. |
| 244 |
""" |
| 245 |
if after is not None: |
| 246 |
|
| 247 |
|
| 248 |
for frame in reversed(frames): |
| 249 |
self.add_child(frame, after=after) |
| 250 |
else: |
| 251 |
for frame in frames: |
| 252 |
self.add_child(frame) |
| 253 |
|
| 254 |
@property |
| 255 |
def is_synthetic(self) -> bool: |
| 256 |
return self.identifier in SYNTHETIC_FRAME_IDENTIFIERS |
| 257 |
|
| 258 |
@property |
| 259 |
def is_synthetic_leaf(self) -> bool: |
| 260 |
return self.identifier in SYNTHETIC_LEAF_IDENTIFIERS |
| 261 |
|
| 262 |
@property |
| 263 |
def children(self) -> Sequence[Frame]: |
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
return tuple(self._children) |
| 268 |
|
| 269 |
def await_time(self) -> float: |
| 270 |
|
| 271 |
await_time = 0 |
| 272 |
|
| 273 |
if self.identifier == AWAIT_FRAME_IDENTIFIER: |
| 274 |
await_time += self.time |
| 275 |
|
| 276 |
for child in self.children: |
| 277 |
await_time += child.await_time() |
| 278 |
|
| 279 |
return await_time |
| 280 |
|
| 281 |
def get_attribute_value(self, attribute_marker: str) -> str | None: |
| 282 |
""" |
| 283 |
Returns the value of the attribute. If multiple values are present, |
| 284 |
the most commonly observed one is returned. |
| 285 |
""" |
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
matching_attributes = [ |
| 291 |
a_tuple |
| 292 |
for a_tuple in self.attributes.items() |
| 293 |
if a_tuple[0].startswith(attribute_marker) |
| 294 |
] |
| 295 |
|
| 296 |
if len(matching_attributes) == 0: |
| 297 |
return None |
| 298 |
|
| 299 |
top_attribute, _ = max(matching_attributes, key=lambda a: a[1]) |
| 300 |
|
| 301 |
|
| 302 |
return top_attribute[1:] |
| 303 |
|
| 304 |
@property |
| 305 |
def class_name(self) -> str | None: |
| 306 |
return self.get_attribute_value(ATTRIBUTE_MARKER_CLASS_NAME) |
| 307 |
|
| 308 |
@property |
| 309 |
def has_tracebackhide(self) -> bool: |
| 310 |
""" |
| 311 |
Returns whether this frame has a `__tracebackhide__` variable. |
| 312 |
""" |
| 313 |
return self.get_attribute_value(ATTRIBUTE_MARKER_TRACEBACKHIDE) == "1" |
| 314 |
|
| 315 |
def self_check(self, recursive: bool = True) -> None: |
| 316 |
""" |
| 317 |
Checks that the frame is valid. |
| 318 |
""" |
| 319 |
if self.identifier in SYNTHETIC_LEAF_IDENTIFIERS: |
| 320 |
assert len(self._children) == 0 |
| 321 |
|
| 322 |
|
| 323 |
return |
| 324 |
|
| 325 |
calculated_time = sum(child.time for child in self.children) + self.absorbed_time |
| 326 |
assert math.isclose( |
| 327 |
calculated_time, self.time |
| 328 |
), f"Frame time mismatch, should be {calculated_time}, was {self.time}, {self.children}" |
| 329 |
|
| 330 |
if recursive: |
| 331 |
for child in self.children: |
| 332 |
child.self_check(recursive=True) |
| 333 |
|
| 334 |
def __repr__(self): |
| 335 |
return "Frame(identifier=%s, time=%f, len(children)=%d), group=%r" % ( |
| 336 |
self.identifier, |
| 337 |
self.time, |
| 338 |
len(self.children), |
| 339 |
self.group, |
| 340 |
) |
| 341 |
|
| 342 |
def to_json_str(self): |
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
encode_str = typing.cast(Callable[[str], str], json.encoder.encode_basestring) |
| 347 |
|
| 348 |
property_decls: list[str] = [] |
| 349 |
property_decls.append('"identifier": %s' % encode_str(self.identifier)) |
| 350 |
property_decls.append('"time": %f' % self.time) |
| 351 |
property_decls.append('"attributes": %s' % json.dumps(self.attributes)) |
| 352 |
child_jsons: list[str] = [] |
| 353 |
for child in self.children: |
| 354 |
child_jsons.append(child.to_json_str()) |
| 355 |
property_decls.append('"children": [%s]' % ",".join(child_jsons)) |
| 356 |
|
| 357 |
return "{%s}" % ",".join(property_decls) |
| 358 |
|
| 359 |
|
| 360 |
class FrameGroup: |
| 361 |
_frames: list[Frame] |
| 362 |
_exit_frames: list[Frame] | None |
| 363 |
|
| 364 |
def __init__(self, root: Frame): |
| 365 |
self.root = root |
| 366 |
self.id = str(uuid.uuid4()) |
| 367 |
self._frames = [] |
| 368 |
self._exit_frames = None |
| 369 |
|
| 370 |
self.add_frame(root) |
| 371 |
|
| 372 |
@property |
| 373 |
def frames(self) -> Sequence[Frame]: |
| 374 |
return tuple(self._frames) |
| 375 |
|
| 376 |
def add_frame(self, frame: Frame): |
| 377 |
if frame.group: |
| 378 |
frame.group.remove_frame(frame) |
| 379 |
|
| 380 |
self._frames.append(frame) |
| 381 |
frame.group = self |
| 382 |
|
| 383 |
def remove_frame(self, frame: Frame): |
| 384 |
assert frame.group is self |
| 385 |
self._frames.remove(frame) |
| 386 |
frame.group = None |
| 387 |
|
| 388 |
@property |
| 389 |
def exit_frames(self): |
| 390 |
""" |
| 391 |
Returns a list of frames whose children include a frame outside of the group |
| 392 |
""" |
| 393 |
if self._exit_frames is None: |
| 394 |
exit_frames: list[Frame] = [] |
| 395 |
for frame in self.frames: |
| 396 |
if any(c.group != self for c in frame.children): |
| 397 |
exit_frames.append(frame) |
| 398 |
self._exit_frames = exit_frames |
| 399 |
|
| 400 |
return self._exit_frames |
| 401 |
|
| 402 |
def __repr__(self): |
| 403 |
return "FrameGroup(len(frames)=%d)" % len(self.frames) |