Debian Codegraph @

html_renderer/src/lib/model/processors.ts

raw symbols SCIP
1 import { maxBy } from "../utils";
2 import type Frame from "./Frame";
3 import { SELF_TIME_FRAME_IDENTIFIER } from "./Frame";
4 import FrameGroup from "./FrameGroup";
5 import { combineFrames, deleteFrameFromTree } from './frameOps'
6
7 export interface ProcessorOptions {
8 filterThreshold?: number // used by remove_irrelevant_nodes
9 hideRegex?: string // used by group_library_frames_processor
10 showRegex?: string // used by group_library_frames_processor
11 }
12 export type ProcessorFunction = (frame: Frame | null, options: ProcessorOptions) => Frame | null
13
14 export interface Processor {
15 name: string
16 description: string
17 function: ProcessorFunction
18 optionsSpec: {
19 key: string,
20 name: string,
21 value: {
22 type: 'string',
23 default: string
24 } | {
25 type: 'number',
26 default: number
27 min?: number
28 max?: number
29 sliderMin?: number
30 sliderMax?: number
31 sliderLogarithmic?: boolean
32 } | {
33 type: 'boolean',
34 default: boolean
35 }
36 }[],
37 category: 'normal' | 'advanced'
38 }
39
40 export const allProcessors: Processor[] = []
41
42 /**
43 * Removes ``<frozen importlib._bootstrap`` frames that clutter the output.
44 */
45 export function remove_importlib(frame: Frame | null, options: ProcessorOptions): Frame | null {
46 if (!frame) {
47 return null
48 }
49
50 for (const child of frame.children) {
51 remove_importlib(child, options)
52
53 if (child.filePath && child.filePath.includes("<frozen importlib._bootstrap")) {
54 deleteFrameFromTree(child, { replaceWith: "children" })
55 }
56 }
57
58 return frame
59 }
60 allProcessors.push({
61 name: "remove_importlib",
62 description: "Removes <frozen importlib._bootstrap frames that clutter the output.",
63 function: remove_importlib,
64 optionsSpec: [],
65 category: 'normal',
66 })
67
68 /**
69 * Removes frames that have set a local `__traceback_hide__` (e.g.
70 * `__traceback_hide__ = True`), to remove them from the output.
71 */
72 export function remove_tracebackhide(frame: Frame | null, options: ProcessorOptions): Frame | null {
73 if (!frame) {
74 return null
75 }
76
77 for (const child of frame.children) {
78 remove_tracebackhide(child, options)
79
80 if (child.hasTracebackHide) {
81 deleteFrameFromTree(child, { replaceWith: "children" })
82 }
83 }
84
85 return frame
86 }
87 allProcessors.push({
88 name: "remove_tracebackhide",
89 description: "Removes frames that have set a local __traceback_hide__ (e.g. __traceback_hide__ = True), to remove them from the output.",
90 function: remove_tracebackhide,
91 optionsSpec: [],
92 category: 'advanced',
93 })
94
95 /**
96 * Converts a timeline into a time-aggregate summary.
97 *
98 * Adds together calls along the same call stack, so that repeated calls
99 * appear as the same frame. Removes time-linearity - frames are sorted
100 * according to total time spent.
101 *
102 * Useful for outputs that display a summary of execution (e.g., text and HTML
103 * outputs).
104 */
105 export function aggregate_repeated_calls(frame: Frame | null, options: ProcessorOptions): Frame | null {
106 if (!frame) {
107 return null;
108 }
109
110 const childrenByIdentifier: Record<string, Frame> = {};
111
112 for (const child of frame.children.slice()) {
113 if (childrenByIdentifier[child.identifier]) {
114 const aggregateFrame = childrenByIdentifier[child.identifier];
115 combineFrames(child, aggregateFrame);
116 } else {
117 childrenByIdentifier[child.identifier] = child;
118 }
119 }
120
121 frame.children.forEach(child => aggregate_repeated_calls(child, options));
122 frame._children.sort((a, b) => b.time - a.time);
123
124 return frame;
125 }
126 allProcessors.push({
127 name: "aggregate_repeated_calls",
128 description: "Converts a timeline into a time-aggregate summary. Adds together calls along the same call stack, so that repeated calls appear as the same frame. Removes time-linearity - frames are sorted according to total time spent.",
129 function: aggregate_repeated_calls,
130 optionsSpec: [],
131 category: 'normal',
132 })
133
134 /**
135 * Groups frames that should be hidden into FrameGroup objects,
136 * according to `remove_regex` and `show_regex` in the options dictionary.
137 */
138 export function group_library_frames_processor(frame: Frame | null, options: ProcessorOptions): Frame | null {
139 if (!frame) {
140 return null;
141 }
142
143 const hideRegex = options.hideRegex;
144 const showRegex = options.showRegex;
145
146 function shouldHide(frame: Frame): boolean {
147 const filePath = frame.filePath || "";
148 const show = showRegex && new RegExp(showRegex).test(filePath);
149 const hide = hideRegex && new RegExp(hideRegex).test(filePath);
150
151 if (show) {
152 return false;
153 }
154 if (hide) {
155 return true;
156 }
157 return !frame.isApplicationCode
158 }
159
160 function addFramesToGroup(frame: Frame, group: FrameGroup): void {
161 group.addFrame(frame);
162 frame.children.forEach(child => {
163 if (shouldHide(child)) {
164 addFramesToGroup(child, group);
165 }
166 });
167 }
168
169 frame.children.forEach(child => {
170 if (!child.group && shouldHide(child) && child.children.some(shouldHide)) {
171 const group = new FrameGroup(child);
172 addFramesToGroup(child, group);
173 }
174
175 group_library_frames_processor(child, options);
176 });
177
178 return frame;
179 }
180 allProcessors.push({
181 name: "Group library frames",
182 description: "Groups frames that should be hidden.",
183 function: group_library_frames_processor,
184 optionsSpec: [
185 {
186 key: "hideRegex",
187 name: "Hide regex",
188 value: {
189 type: "string",
190 default: ""
191 }
192 },
193 {
194 key: "showRegex",
195 name: "Show regex",
196 value: {
197 type: "string",
198 default: ""
199 }
200 }
201 ],
202 category: 'normal',
203 })
204
205 /**
206 * Combines consecutive 'self time' frames.
207 */
208 export function merge_consecutive_self_time(frame: Frame | null, options: ProcessorOptions, recursive: boolean = true): Frame | null {
209 if (!frame) {
210 return null;
211 }
212
213 let previousSelfTimeFrame: Frame | null = null;
214
215 for (const child of frame.children) {
216 if (child.identifier === SELF_TIME_FRAME_IDENTIFIER) {
217 if (previousSelfTimeFrame) {
218 previousSelfTimeFrame.time += child.time;
219 child.removeFromParent();
220 } else {
221 previousSelfTimeFrame = child;
222 }
223 } else {
224 previousSelfTimeFrame = null;
225 }
226 }
227
228 if (recursive) {
229 frame.children.forEach(child => merge_consecutive_self_time(child, options, true));
230 }
231
232 return frame;
233 }
234 allProcessors.push({
235 name: "Merge consecutive self time",
236 description: "Combines consecutive 'self time' frames.",
237 function: merge_consecutive_self_time,
238 optionsSpec: [],
239 category: 'advanced',
240 })
241
242 /**
243 * Removes unnecessary self-time nodes.
244 */
245 export function remove_unnecessary_self_time_nodes(frame: Frame | null, options: ProcessorOptions): Frame | null {
246 if (!frame) {
247 return null;
248 }
249
250 if (frame.children.length === 1 && frame.children[0].identifier === SELF_TIME_FRAME_IDENTIFIER) {
251 deleteFrameFromTree(frame.children[0], { replaceWith: "nothing" });
252 }
253
254 frame.children.forEach(child => remove_unnecessary_self_time_nodes(child, options));
255
256 return frame;
257 }
258 allProcessors.push({
259 name: "Remove unnecessary self time nodes",
260 description: "Removes unnecessary self-time nodes.",
261 function: remove_unnecessary_self_time_nodes,
262 optionsSpec: [],
263 category: 'advanced',
264 })
265
266 /**
267 * Removes nodes that represent less than a certain percentage of the output.
268 */
269 export function remove_irrelevant_nodes(frame: Frame | null, options: ProcessorOptions, totalTime: number | null = null): Frame | null {
270 if (!frame) {
271 return null;
272 }
273
274 if (totalTime === null) {
275 totalTime = frame.time;
276 if (totalTime <= 0) {
277 totalTime = 1e-44; // Prevent divide by zero
278 }
279 }
280
281 const filterThreshold = options.filterThreshold ?? 0.01;
282
283 for (const child of frame.children.slice()) {
284 const proportionOfTotal = child.time / totalTime;
285 if (proportionOfTotal < filterThreshold) {
286 deleteFrameFromTree(child, { replaceWith: "nothing" });
287 }
288 }
289
290 frame.children.forEach(child => remove_irrelevant_nodes(child, options, totalTime));
291
292 return frame;
293 }
294 allProcessors.push({
295 name: "Remove irrelevant nodes",
296 description: "Removes nodes that represent less than a certain percentage of the output.",
297 function: remove_irrelevant_nodes,
298 optionsSpec: [
299 {
300 key: "filterThreshold",
301 name: "Filter threshold",
302 value: {
303 type: "number",
304 default: 0.01,
305 min: 0,
306 max: 1,
307 sliderMin: 0.0001,
308 sliderMax: 1
309 }
310 }
311 ],
312 category: 'normal',
313 })
314
315 /**
316 * Removes the initial frames specific to the command line use of pyinstrument.
317 */
318 export function remove_first_pyinstrument_frames_processor(frame: Frame | null, options: ProcessorOptions): Frame | null {
319 if (!frame) {
320 return null;
321 }
322
323 const longestFrame = (frames: readonly Frame[]) => maxBy(frames, f => f.time)
324
325 const isInitialPyinstrumentFrame = (f: Frame) =>
326 f.filePath?.includes("pyinstrument/__main__.py") && f.children.length > 0;
327
328 const isExecFrame = (f: Frame) =>
329 f.proportionOfParent > 0.8 && f.filePath?.includes("<string>") && f.children.length > 0;
330
331 const isRunpyFrame = (f: Frame) =>
332 f.proportionOfParent > 0.8 && (new RegExp(".*runpy.py").test(f.filePath ?? '') || f.filePath?.includes("<frozen runpy>")) && f.children.length > 0;
333
334 let result = frame;
335
336 if (!isInitialPyinstrumentFrame(result)) return frame;
337
338 result = longestFrame(result.children)!
339
340 if (!isExecFrame(result)) return frame;
341
342 result = longestFrame(result.children)!
343
344 if (!isRunpyFrame(result)) return frame;
345
346 while (isRunpyFrame(result)) {
347 result = longestFrame(result.children)!
348 }
349
350 result.removeFromParent();
351
352 return result;
353 }
354
355 export function remove_useless_groups_processor(frame: Frame | null, options: ProcessorOptions): Frame | null {
356 if (!frame) {
357 return null;
358 }
359
360 frame.children.forEach(child => remove_useless_groups_processor(child, options));
361
362 // a group with only two frames is meaningless, you still print the root
363 // frame, so you're just collapsing the single child frame with a group,
364 // which is better printed as just a single frame
365 if (frame.group && frame.group.frames.length < 3) {
366 frame.group.removeFrame(frame);
367 }
368
369 return frame;
370 }
371
372 allProcessors.push({
373 name: "Remove first pyinstrument frames",
374 description: "Removes the initial frames specific to the command line use of pyinstrument.",
375 function: remove_first_pyinstrument_frames_processor,
376 optionsSpec: [],
377 category: 'advanced',
378 })