diff --git a/README.md b/README.md index 251655c..695f129 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,10 @@ trace-engine-cli scan fixtures/traces/ --cat devtools.timeline --phase X 3. Inspect relevant subsystem: `trace-engine-cli shifts --events`, `trace-engine-cli network `, or `trace-engine-cli insights --category ` 4. Inspect raw event payloads: `trace-engine-cli events --name --fields ` +### Recipe D: Analyzing CPU Activity in a Subframe +1. Run `trace-engine-cli threads ` and find the renderer thread by frame URL. +2. Pass its `PID:TID` as `--thread` to a CPU command, for example `trace-engine-cli tasks --thread 123:1`. Frames that share a renderer thread share its CPU results. + --- ## 5. Capture Caveats @@ -285,6 +289,10 @@ All time-range inputs (`--time-range`, `--window-a`, `--window-b`, `--bucket`) s ### 1. `overview` (default) High-level trace metadata, Core Web Vitals (FCP, LCP, CLS, INP), non-overlapping main-thread category breakdown (Scripting, Layout, Rendering, GC, System, Idle), and diagnostic warnings. +The breakdown uses the same instrumented timeline events with and without CPU +samples. With `--thread PID:TID`, the breakdown describes that +renderer thread and Web Vitals still describe the page. + ```bash # Default invocation (includes the drill-down commands footer) trace-engine-cli trace.json.gz @@ -326,8 +334,9 @@ warnings[1]: 1 render-blocking resource(s) detected. # Drill-down commands: # - trace-engine-cli insights [--category ] [--navigation ] -# - trace-engine-cli tasks [--min-duration ] [--tree ] [--top ] -# - trace-engine-cli find --function [--time-range ] +# - trace-engine-cli tasks [--min-duration ] [--tree ] [--url-only] [--top ] +# - trace-engine-cli find [--function ] [--url ] [--time-range ] +# - trace-engine-cli threads # - trace-engine-cli profile [--time-range ] [--bucket ] # - trace-engine-cli diff --window-a --window-b # - trace-engine-cli scheduling [--time-range ] @@ -365,7 +374,9 @@ trace-engine-cli insights trace.json.gz --navigation 9E74B39B7C378297071F6E3618C --- ### 3. `tasks` -Main thread task execution, long tasks, and aggregated call trees. +Long tasks and aggregated call trees for a renderer thread. Aggregated rows +show their first event timestamp. Top-down rows include the call path, and +`--url-only` limits output to rows with source URLs. ```bash # List long tasks above 50ms (default) @@ -374,8 +385,8 @@ trace-engine-cli tasks trace.json.gz # Custom duration threshold and limit within relative window trace-engine-cli tasks trace.json.gz --min-duration 20 --time-range "1s,4s" --top 10 -# Bottom-up call tree (aggregated and sorted by self-time) -trace-engine-cli tasks trace.json.gz --tree bottom-up --top 20 +# Bottom-up call tree with source URLs, sorted by self-time +trace-engine-cli tasks trace.json.gz --tree bottom-up --url-only --top 20 # Top-down call tree (aggregated and sorted by total duration) trace-engine-cli tasks trace.json.gz --tree top-down --top 20 @@ -384,14 +395,15 @@ trace-engine-cli tasks trace.json.gz --tree top-down --top 20 --- ### 4. `find` -Search for executions of a specific function name or pattern to verify call frequency, duration, or confirm starvation (0 calls in window). +Search executions by function name or script URL substring to inspect call +frequency and duration. Pass both `--function` and `--url` to require both matches. ```bash # Search for invocations of a function across the whole trace trace-engine-cli find trace.json.gz --function "drawEventTiles" -# Query within a specific relative time window -trace-engine-cli find trace.json.gz --function "drawEventTiles" --time-range "3.5s,4.2s" +# Search calls in one script within a relative time window +trace-engine-cli find trace.json.gz --url "/app.js" --time-range "3.5s,4.2s" ``` --- @@ -513,6 +525,18 @@ trace-engine-cli scan fixtures/ --name TracingStartedInBrowser --fields args.dat --- +### 14. `threads` + +List renderer threads, their frame URLs, and CPU sample availability. Use +`--thread PID:TID` with `overview`, `tasks`, `profile`, `find`, or `diff` to +select a renderer, including one for an out-of-process iframe. + +```bash +trace-engine-cli threads trace.json.gz +``` + +--- + ## Output Formats ### TOON (Default) diff --git a/src/cli.ts b/src/cli.ts index f088144..8088b0e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -27,7 +27,9 @@ import { scanTraces } from './engine/extractors/scan.js'; import { extractScheduling } from './engine/extractors/scheduling.js'; import { extractShifts } from './engine/extractors/shifts.js'; import { extractTasks } from './engine/extractors/tasks.js'; +import { listRendererThreads } from './engine/helpers.js'; import { loadTraceFromFile } from './engine/loader.js'; +import type { ThreadsResult } from './engine/types.js'; import { type FormatOptions, formatResult } from './formatters/index.js'; import { parseTimeRange, parseTimeValue, resolveTimeRange } from './utils/filter.js'; @@ -47,6 +49,18 @@ function parseCommaList(val?: unknown): string[] | undefined { return items.length > 0 ? items : undefined; } +const THREAD_OPTION = { + type: 'string', + describe: 'Renderer thread as PID:TID. Use threads to look up a frame URL.', +} satisfies import('yargs').Options; + +function positiveInteger(value: number): number { + if (!Number.isSafeInteger(value) || value < 1) { + throw new Error('Result limits must be positive integers.'); + } + return value; +} + export async function runCli(argv: string[]): Promise { const cli = yargs(hideBin(argv)) .scriptName('trace-engine-cli') @@ -77,7 +91,7 @@ export async function runCli(argv: string[]): Promise { ['overview ', '$0 '], 'High-level trace metadata, Core Web Vitals, and main thread category breakdown (default command)', (y) => - y.positional('file', { + y.option('thread', THREAD_OPTION).positional('file', { describe: 'Path to trace file (.json or .json.gz)', type: 'string', demandOption: true, @@ -93,7 +107,7 @@ export async function runCli(argv: string[]): Promise { loaded.parsedTrace.data.Meta.traceBounds, args.absoluteTimestamps as boolean, ); - const result = extractOverview(loaded, { timeRange }); + const result = extractOverview(loaded, { timeRange, threadId: args.thread }); const isDefaultCmd = !args._.includes('overview'); console.log( formatResult(result, { @@ -104,6 +118,21 @@ export async function runCli(argv: string[]): Promise { ); }, ) + .command( + 'threads ', + 'List renderer threads, their frame URLs, and CPU sample availability', + (y) => + y.positional('file', { + describe: 'Path to trace file (.json or .json.gz)', + type: 'string', + demandOption: true, + }), + async (args) => { + const loaded = await loadTraceFromFile(args.file, args.traceEngine); + const result: ThreadsResult = { threads: listRendererThreads(loaded.parsedTrace.data) }; + console.log(formatResult(result, { format: args.format, type: 'threads' })); + }, + ) .command( 'insights ', 'Diagnostic insight cards (LCP, INP, CLS, render-blocking, third-parties)', @@ -152,6 +181,7 @@ export async function runCli(argv: string[]): Promise { 'Long tasks, bottom-up and top-down TraceTree call aggregations', (y) => y + .option('thread', THREAD_OPTION) .positional('file', { describe: 'Path to trace file (.json or .json.gz)', type: 'string', @@ -168,9 +198,14 @@ export async function runCli(argv: string[]): Promise { describe: "Generate aggregated call tree ('bottom-up' sorted by self-time, 'top-down' sorted by total duration)", }) + .option('url-only', { + type: 'boolean', + describe: 'Only show rows with a source URL', + }) .option('top', { alias: ['limit'], type: 'number', + coerce: positiveInteger, default: 20, describe: 'Limit output to top N tasks (default: 20)', }), @@ -186,10 +221,12 @@ export async function runCli(argv: string[]): Promise { args.absoluteTimestamps as boolean, ); const result = extractTasks(loaded, { + urlOnly: args.urlOnly, minDurationMs: args.minDuration as number, tree: args.tree as 'bottom-up' | 'top-down' | undefined, top: args.top as number, timeRange, + threadId: args.thread, }); console.log( formatResult(result, { @@ -204,6 +241,7 @@ export async function runCli(argv: string[]): Promise { 'Search for function execution instances, call frequency, and starvation intervals', (y) => y + .option('thread', THREAD_OPTION) .positional('file', { describe: 'Path to trace file (.json or .json.gz)', type: 'string', @@ -212,12 +250,16 @@ export async function runCli(argv: string[]): Promise { .option('function', { alias: ['fn', 'name'], type: 'string', - demandOption: true, - describe: 'Function name or pattern to search for', + describe: 'Function name substring to search for', + }) + .option('url', { + type: 'string', + describe: 'Script URL substring to search for, optionally combined with --function', }) .option('top', { alias: ['limit'], type: 'number', + coerce: positiveInteger, default: 50, describe: 'Maximum number of invocation entries to list (default: 50)', }), @@ -233,8 +275,10 @@ export async function runCli(argv: string[]): Promise { args.absoluteTimestamps as boolean, ); const result = extractFind(loaded, { - functionName: args.function as string, + functionName: args.function, + url: args.url, timeRange, + threadId: args.thread, limit: args.top as number, }); console.log( @@ -250,6 +294,7 @@ export async function runCli(argv: string[]): Promise { 'Time-bucketed CPU profiling progression across discrete intervals', (y) => y + .option('thread', THREAD_OPTION) .positional('file', { describe: 'Path to trace file (.json or .json.gz)', type: 'string', @@ -263,6 +308,7 @@ export async function runCli(argv: string[]): Promise { .option('top', { alias: ['limit'], type: 'number', + coerce: positiveInteger, default: 3, describe: 'Top N functions to include per time bucket (default: 3)', }), @@ -277,9 +323,13 @@ export async function runCli(argv: string[]): Promise { loaded.parsedTrace.data.Meta.traceBounds, args.absoluteTimestamps as boolean, ); - const bucketMs = args.bucket ? parseTimeValue(String(args.bucket)) : undefined; + const bucketMs = args.bucket === undefined ? undefined : parseTimeValue(args.bucket); + if (bucketMs !== undefined && (!Number.isFinite(bucketMs) || bucketMs < 0.01)) { + throw new Error('--bucket must be at least 0.01ms.'); + } const result = extractProfile(loaded, { timeRange, + threadId: args.thread, bucketMs, top: args.top as number, }); @@ -296,6 +346,7 @@ export async function runCli(argv: string[]): Promise { 'Differential CPU profiling comparing two time windows in the trace', (y) => y + .option('thread', THREAD_OPTION) .positional('file', { describe: 'Path to trace file (.json or .json.gz)', type: 'string', @@ -316,6 +367,7 @@ export async function runCli(argv: string[]): Promise { .option('top', { alias: ['limit'], type: 'number', + coerce: positiveInteger, default: 20, describe: 'Maximum differential entries to return (default: 20)', }), @@ -338,6 +390,7 @@ export async function runCli(argv: string[]): Promise { const result = extractDiff(loaded, { windowA, + threadId: args.thread, windowB, top: args.top as number, }); @@ -396,6 +449,7 @@ export async function runCli(argv: string[]): Promise { .option('slowest', { alias: ['top', 'limit'], type: 'number', + coerce: positiveInteger, default: 20, describe: 'Limit output to N slowest requests (default: 20)', }) @@ -530,6 +584,7 @@ export async function runCli(argv: string[]): Promise { .option('top', { alias: ['limit'], type: 'number', + coerce: positiveInteger, default: 50, describe: 'Maximum number of matching events to return (default: 50)', }), @@ -624,6 +679,7 @@ export async function runCli(argv: string[]): Promise { .option('top', { alias: ['limit'], type: 'number', + coerce: positiveInteger, default: 50, describe: 'Maximum number of matched files to return (default: 50)', }), diff --git a/src/engine/extractors/diff.ts b/src/engine/extractors/diff.ts index 02fa0c0..c98bb8d 100644 --- a/src/engine/extractors/diff.ts +++ b/src/engine/extractors/diff.ts @@ -14,11 +14,12 @@ import type { TimeRange } from '../../utils/filter.js'; import { round } from '../../utils/units.js'; -import { getMainRendererThread } from '../helpers.js'; +import { getRendererThread, rendererCpuFilter } from '../helpers.js'; import type { LoadedTrace } from '../loader.js'; import type { DiffEntryItem, DiffResult } from '../types.js'; export interface ExtractDiffOptions { + threadId?: string; windowA: TimeRange; windowB: TimeRange; top?: number; @@ -39,6 +40,7 @@ export function extractDiff(loadedTrace: LoadedTrace, options: ExtractDiffOption const topCount = options.top ?? 20; const result: DiffResult = { + threadId: options.threadId, windowA: { startMs: windowA.startMs, endMs: windowA.endMs, @@ -52,7 +54,7 @@ export function extractDiff(loadedTrace: LoadedTrace, options: ExtractDiffOption entries: [], }; - const mainThread = getMainRendererThread(parsedTrace.data); + const mainThread = getRendererThread(parsedTrace.data, options?.threadId); if (!mainThread?.entries?.length) { return result; } @@ -64,7 +66,7 @@ export function extractDiff(loadedTrace: LoadedTrace, options: ExtractDiffOption } { const bottomUp = new engine.Extras.TraceTree.BottomUpRootNode(mainThreadEntries, { textFilter: { accept: () => true }, - filters: [], + filters: [rendererCpuFilter(loadedTrace)], startTime: engine.Types.Timing.Milli(range.startMs), endTime: engine.Types.Timing.Milli(range.endMs), }); diff --git a/src/engine/extractors/find.ts b/src/engine/extractors/find.ts index 6ce688f..a2aaad9 100644 --- a/src/engine/extractors/find.ts +++ b/src/engine/extractors/find.ts @@ -14,12 +14,14 @@ import { isEventInBounds, type TimeRange } from '../../utils/filter.js'; import { microToMilli, round } from '../../utils/units.js'; -import { getMainRendererThread } from '../helpers.js'; +import { getRendererThread } from '../helpers.js'; import type { LoadedTrace } from '../loader.js'; import type { FindCallInstance, FindIntervalItem, FindResult } from '../types.js'; export interface ExtractFindOptions { - functionName: string; + threadId?: string; + functionName?: string; + url?: string; timeRange?: TimeRange; limit?: number; } @@ -29,12 +31,18 @@ export interface ExtractFindOptions { */ export function extractFind(loadedTrace: LoadedTrace, options: ExtractFindOptions): FindResult { const { engine, parsedTrace } = loadedTrace; - const functionQuery = options.functionName.trim(); + const functionQuery = options.functionName?.trim(); + const urlQuery = options.url?.trim(); + if (!functionQuery && !urlQuery) throw new Error('Specify --function or --url to search for.'); + const functionNeedle = functionQuery?.toLowerCase(); + const urlNeedle = urlQuery?.toLowerCase(); const timeRange = options.timeRange; const limit = options.limit ?? 50; const result: FindResult = { + threadId: options.threadId, functionQuery, + urlQuery, timeRange, totalCalls: 0, totalDurationMs: 0, @@ -42,12 +50,11 @@ export function extractFind(loadedTrace: LoadedTrace, options: ExtractFindOption calls: [], }; - const mainThread = getMainRendererThread(parsedTrace.data); - if (!mainThread || !functionQuery) { + const mainThread = getRendererThread(parsedTrace.data, options?.threadId); + if (!mainThread) { return result; } - const queryLower = functionQuery.toLowerCase(); const matchedCalls: FindCallInstance[] = []; for (const entry of mainThread.entries) { @@ -61,8 +68,12 @@ export function extractFind(loadedTrace: LoadedTrace, options: ExtractFindOption const frame = engine.Extras.TraceTree.eventStackFrame(entry); const fnName = frame?.functionName || entry.name || ''; - if (fnName.toLowerCase().includes(queryLower)) { + if ( + (!functionNeedle || fnName.toLowerCase().includes(functionNeedle)) && + (!urlNeedle || frame?.url.toLowerCase().includes(urlNeedle)) + ) { matchedCalls.push({ + functionName: fnName, timestampMs: round(startMs), durationMs: round(durMs), url: frame?.url, diff --git a/src/engine/extractors/overview.ts b/src/engine/extractors/overview.ts index 6928192..bab950d 100644 --- a/src/engine/extractors/overview.ts +++ b/src/engine/extractors/overview.ts @@ -15,8 +15,8 @@ import type { TimeRange } from '../../utils/filter.js'; import { microToMilli, round } from '../../utils/units.js'; import { - getMainRendererThread, getPrimaryInsightSet, + getRendererThread, MISSING_CPU_SAMPLES, PAGE_TRACE_CAPTURE_HINT, shouldWarnAboutLayoutShiftCapture, @@ -50,6 +50,7 @@ function rateInp(inpMs: number): CwvRating { } export interface ExtractOverviewOptions { + threadId?: string; timeRange?: TimeRange; } @@ -178,12 +179,20 @@ export function extractOverview( totalMs: 0, }; - const mainThread = getMainRendererThread(data); + const mainThread = getRendererThread(data, options?.threadId); if (mainThread?.entries && mainThread.entries.length > 0) { const bottomUp = new engine.Extras.TraceTree.BottomUpRootNode(mainThread.entries, { textFilter: { accept: () => true }, - filters: [], + // Renderer.entryToNode is built with CPU samples, which can displace overlapping timeline + // events. Keep timeline attribution independent of whether samples were captured. + filters: [ + { + accept: (event) => + !engine.Types.Events.isProfileCall(event) && + !engine.Types.Events.isPhaseAsync(event.ph), + }, + ], startTime: engine.Types.Timing.Milli(minMs), endTime: engine.Types.Timing.Milli(maxMs), }); @@ -197,13 +206,14 @@ export function extractOverview( name === 'MajorGC' || name === 'MinorGC' || name === 'GCEvent' || - name.startsWith('v8.gc') + name.toLowerCase().startsWith('v8.gc') ) { breakdown.gcMs += node.selfTime; } else if (name === 'Layout' || name === 'UpdateLayoutTree' || name === 'InvalidateLayout') { breakdown.layoutMs += node.selfTime; } else if ( name === 'UpdateLayerTree' || + name === 'Layerize' || name === 'Paint' || name === 'CompositeLayers' || name === 'RasterTask' || @@ -211,10 +221,11 @@ export function extractOverview( ) { breakdown.renderingMs += node.selfTime; } else if ( - name.startsWith('f:') || name === 'EvaluateScript' || name === 'FunctionCall' || - name === 'v8.compile' || + name.startsWith('v8.compile') || + name === 'v8.callFunction' || + name === 'RunMicrotasks' || name === 'v8.run' || name === 'TimerFire' || name === 'FireAnimationFrame' || @@ -266,6 +277,7 @@ export function extractOverview( } return { + threadId: options?.threadId, bounds: { minMs, maxMs, durationMs }, mainUrl, navigationStartMs, diff --git a/src/engine/extractors/profile.ts b/src/engine/extractors/profile.ts index 03180a8..0f11b8c 100644 --- a/src/engine/extractors/profile.ts +++ b/src/engine/extractors/profile.ts @@ -14,11 +14,12 @@ import type { TimeRange } from '../../utils/filter.js'; import { microToMilli, round } from '../../utils/units.js'; -import { getMainRendererThread } from '../helpers.js'; +import { getRendererThread, MISSING_CPU_SAMPLES, rendererCpuFilter } from '../helpers.js'; import type { LoadedTrace } from '../loader.js'; import type { ProfileResult } from '../types.js'; export interface ExtractProfileOptions { + threadId?: string; timeRange?: TimeRange; bucketMs?: number; top?: number; @@ -43,16 +44,20 @@ export function extractProfile( const topCount = options?.top ?? 3; const result: ProfileResult = { + threadId: options?.threadId, timeRange: { startMs, endMs }, bucketSizeMs, buckets: [], }; - const mainThread = getMainRendererThread(parsedTrace.data); + const mainThread = getRendererThread(parsedTrace.data, options?.threadId); if (!mainThread?.entries?.length) { return result; } + if (!mainThread.profileCalls.length) result.warnings = [MISSING_CPU_SAMPLES]; + + const cpuFilter = rendererCpuFilter(loadedTrace); let currentStart = startMs; while (currentStart < endMs) { const currentEnd = Math.min(endMs, round(currentStart + bucketSizeMs)); @@ -60,12 +65,12 @@ export function extractProfile( const bottomUp = new engine.Extras.TraceTree.BottomUpRootNode(mainThread.entries, { textFilter: { accept: () => true }, - filters: [], + filters: [cpuFilter], startTime: engine.Types.Timing.Milli(currentStart), endTime: engine.Types.Timing.Milli(currentEnd), }); - const funcList: Array<{ name: string; selfTimeMs: number }> = []; + const funcList: Array<{ name: string; url?: string; selfTimeMs: number }> = []; let totalActiveMs = 0; const children = bottomUp.children(); @@ -80,6 +85,7 @@ export function extractProfile( totalActiveMs += node.selfTime; funcList.push({ name: fnName, + url: frame?.url || undefined, selfTimeMs: round(node.selfTime), }); } @@ -88,6 +94,7 @@ export function extractProfile( const topFunctions = funcList.slice(0, topCount).map((f) => ({ name: f.name, + url: f.url, selfTimeMs: f.selfTimeMs, selfTimePct: totalActiveMs > 0 ? round((f.selfTimeMs / totalActiveMs) * 100, 1) : 0, })); diff --git a/src/engine/extractors/tasks.ts b/src/engine/extractors/tasks.ts index f6b05cb..cc0f603 100644 --- a/src/engine/extractors/tasks.ts +++ b/src/engine/extractors/tasks.ts @@ -14,164 +14,175 @@ import { isEventInBounds, type TimeRange } from '../../utils/filter.js'; import { microToMilli, round } from '../../utils/units.js'; -import { getMainRendererThread } from '../helpers.js'; +import { getRendererThread, MISSING_CPU_SAMPLES, rendererCpuFilter } from '../helpers.js'; import type { LoadedTrace } from '../loader.js'; import type { TaskItem, TasksResult } from '../types.js'; export interface ExtractTasksOptions { + threadId?: string; minDurationMs?: number; tree?: 'bottom-up' | 'top-down'; top?: number; + urlOnly?: boolean; timeRange?: TimeRange; } +function rankAndLimit(candidates: T[], limit: number): void { + candidates.sort((a, b) => b.score - a.score); + if (candidates.length > limit) candidates.length = limit; +} + /** * Extracts long main thread tasks and aggregated top-down / bottom-up call trees. */ export function extractTasks(loadedTrace: LoadedTrace, options?: ExtractTasksOptions): TasksResult { const { engine, parsedTrace } = loadedTrace; const minDurationMs = options?.minDurationMs ?? 50; - const top = options?.top ?? 20; + const top = Math.trunc(options?.top ?? 20); + const urlOnly = options?.urlOnly; const treeMode = options?.tree; const timeRange = options?.timeRange; - const mainThread = getMainRendererThread(parsedTrace.data); + const mainThread = getRendererThread(parsedTrace.data, options?.threadId); + + const result: TasksResult = { mode: treeMode ?? 'list', threadId: options?.threadId, tasks: [] }; + if (!mainThread) return result; + if (!mainThread.profileCalls.length) result.warnings = [MISSING_CPU_SAMPLES]; + if (!(top > 0)) return result; - if (!mainThread) { + const traceBounds = parsedTrace.data.Meta.traceBounds; + const treeOptions = { + startTime: engine.Types.Timing.Milli(timeRange?.startMs ?? microToMilli(traceBounds.min)), + endTime: engine.Types.Timing.Milli(timeRange?.endMs ?? microToMilli(traceBounds.max)), + }; + const traceTree = engine.Extras.TraceTree; + const cpuFilter = rendererCpuFilter(loadedTrace); + type TreeNode = InstanceType; + + function treeItem(node: TreeNode): TaskItem { + const frame = traceTree.eventStackFrame(node.event); + // Bottom-up nodes are created in event end order. A recursive call can end before its caller. + const firstTs = node.events.reduce( + (min, event) => Math.min(min, event.ts), + node.event.ts, + ); return { - mode: treeMode || 'list', - tasks: [], + startTimeMs: round(microToMilli(firstTs)), + durationMs: round(node.totalTime), + selfTimeMs: round(node.selfTime), + functionName: frame?.functionName || node.event.name, + url: frame?.url || undefined, + lineNumber: frame?.lineNumber, + columnNumber: frame?.columnNumber, }; } - const traceBounds = parsedTrace.data.Meta.traceBounds; - const startMs = timeRange ? timeRange.startMs : microToMilli(traceBounds.min); - const endMs = timeRange ? timeRange.endMs : microToMilli(traceBounds.max); - if (treeMode === 'bottom-up') { - const bottomUp = new engine.Extras.TraceTree.BottomUpRootNode(mainThread.entries, { + const bottomUp = new traceTree.BottomUpRootNode(mainThread.entries, { + ...treeOptions, textFilter: { accept: () => true }, - filters: [], - startTime: engine.Types.Timing.Milli(startMs), - endTime: engine.Types.Timing.Milli(endMs), + filters: [cpuFilter], }); - const tasks: TaskItem[] = []; - const children = bottomUp.children(); - for (const node of children.values()) { - if (node.selfTime <= 0) continue; - const frame = node.event ? engine.Extras.TraceTree.eventStackFrame(node.event) : null; - tasks.push({ - startTimeMs: round(startMs), - durationMs: round(node.totalTime), - selfTimeMs: round(node.selfTime), - functionName: frame?.functionName || node.event?.name || String(node.id) || 'Unknown', - url: frame?.url || undefined, - lineNumber: frame?.lineNumber, - columnNumber: frame?.columnNumber, - }); + const candidates: Array<{ node: TreeNode; score: number }> = []; + for (const node of bottomUp.children().values()) { + if (node.selfTime > 0 && (!urlOnly || traceTree.eventStackFrame(node.event)?.url)) { + candidates.push({ node, score: round(node.selfTime) }); + // Trim in batches to bound memory and sort work for a small --top. + if (candidates.length === top * 2) rankAndLimit(candidates, top); + } } + rankAndLimit(candidates, top); - tasks.sort((a, b) => b.selfTimeMs - a.selfTimeMs); - return { - mode: 'bottom-up', - tasks: tasks.slice(0, top), - }; + for (const { node } of candidates) result.tasks.push(treeItem(node)); + return result; } if (treeMode === 'top-down') { - const topDown = new engine.Extras.TraceTree.TopDownRootNode(mainThread.entries, { - filters: [], - startTime: engine.Types.Timing.Milli(startMs), - endTime: engine.Types.Timing.Milli(endMs), + const topDown = new traceTree.TopDownRootNode(mainThread.entries, { + ...treeOptions, + filters: options?.urlOnly + ? [cpuFilter, { accept: (event) => Boolean(traceTree.eventStackFrame(event)?.url) }] + : [cpuFilter], }); - const tasks: TaskItem[] = []; - const children = topDown.children(); - for (const node of children.values()) { - const frame = node.event ? engine.Extras.TraceTree.eventStackFrame(node.event) : null; - tasks.push({ - startTimeMs: round(startMs), - durationMs: round(node.totalTime), - selfTimeMs: round(node.selfTime), - functionName: frame?.functionName || node.event?.name || String(node.id) || 'Unknown', - url: frame?.url || undefined, - lineNumber: frame?.lineNumber, - columnNumber: frame?.columnNumber, - }); + // TraceTree computes descendants on demand. Expand only the most expensive paths. + const pending: Array<{ node: TreeNode; parents: string[] }> = [ + ...topDown.children().values(), + ].map((node) => ({ node, parents: [] })); + while (pending.length && result.tasks.length < top) { + pending.sort((a, b) => b.node.totalTime - a.node.totalTime); + const next = pending.shift(); + if (!next) break; + const item = treeItem(next.node); + const callPath = [...next.parents, item.functionName]; + result.tasks.push({ ...item, callPath }); + if (result.tasks.length === top || !next.node.hasChildren()) continue; + for (const node of next.node.children().values()) pending.push({ node, parents: callPath }); } - - tasks.sort((a, b) => b.durationMs - a.durationMs); - return { - mode: 'top-down', - tasks: tasks.slice(0, top), - }; + return result; } - // Default List Mode - const tasks: TaskItem[] = []; - const entryToNode = parsedTrace.data.Renderer?.entryToNode; + const candidates: Array<{ entry: (typeof mainThread.entries)[number]; score: number }> = []; + // URL eligibility is only known after inspecting a task's descendants. + const candidateLimit = urlOnly ? Infinity : top; for (const entry of mainThread.entries) { - if (!entry.dur) continue; - const durMs = microToMilli(entry.dur); - const startEntryMs = microToMilli(entry.ts); - - if (durMs < minDurationMs) continue; - if (!isEventInBounds(startEntryMs, durMs, timeRange)) continue; - - const isTop = entry.name === 'RunTask' || engine.Helpers.Trace.isTopLevelEvent(entry); - - if (isTop) { - let functionName = entry.name; - let url: string | undefined; - let lineNumber: number | undefined; - let columnNumber: number | undefined; - let selfTimeMs = durMs; - - const frame = engine.Extras.TraceTree.eventStackFrame(entry); - if (frame?.functionName) { - functionName = frame.functionName; - url = frame.url; - lineNumber = frame.lineNumber; - columnNumber = frame.columnNumber; - } + if (!entry.dur || (entry.name !== 'RunTask' && !engine.Helpers.Trace.isTopLevelEvent(entry))) { + continue; + } + const durationMs = microToMilli(entry.dur); + const startTimeMs = microToMilli(entry.ts); + if (durationMs < minDurationMs || !isEventInBounds(startTimeMs, durationMs, timeRange)) { + continue; + } + + candidates.push({ entry, score: round(durationMs) }); + if (candidates.length === candidateLimit * 2) rankAndLimit(candidates, candidateLimit); + } + rankAndLimit(candidates, candidateLimit); - if (entryToNode) { - const node = entryToNode.get(entry); - if (node?.children && node.children.length > 0) { - let childDurationSum = 0; - for (const c of node.children) { - childDurationSum += microToMilli(c.entry.dur ?? 0); - } - selfTimeMs = Math.max(0, durMs - childDurationSum); - - if (!frame?.functionName) { - const mainChild = node.children[0].entry; - const childFrame = engine.Extras.TraceTree.eventStackFrame(mainChild); - functionName = `${entry.name} > ${childFrame?.functionName || mainChild.name}`; - url = childFrame?.url; - lineNumber = childFrame?.lineNumber; - columnNumber = childFrame?.columnNumber; - } + const entryToNode = parsedTrace.data.Renderer?.entryToNode; + for (const { entry, score: durationMs } of candidates) { + if (result.tasks.length === top) break; + + const node = entryToNode?.get(entry); + let source = entry; + let frame = traceTree.eventStackFrame(entry); + if (node && !frame?.url) { + let bestTime = -1; + const pending = [...node.children]; + while (pending.length > 0) { + const child = pending.pop(); + if (!child) break; + const childFrame = traceTree.eventStackFrame(child.entry); + const time = child.selfTime ?? child.entry.dur ?? 0; + if (childFrame?.url && childFrame.functionName && time > bestTime) { + source = child.entry; + frame = childFrame; + bestTime = time; } + for (const descendant of child.children) pending.push(descendant); } - tasks.push({ - startTimeMs: round(startEntryMs), - durationMs: round(durMs), - selfTimeMs: round(selfTimeMs), - functionName, - url, - lineNumber, - columnNumber, - }); + if (source === entry && !frame?.functionName && node.children[0]) { + source = node.children[0].entry; + frame = traceTree.eventStackFrame(source); + } } + + if (urlOnly && !frame?.url) continue; + const name = frame?.functionName || source.name; + result.tasks.push({ + startTimeMs: round(microToMilli(entry.ts)), + durationMs, + selfTimeMs: round(microToMilli(node?.selfTime ?? entry.dur ?? 0)), + functionName: source === entry ? name : `${entry.name} > ${name}`, + url: frame?.url || undefined, + lineNumber: frame?.lineNumber, + columnNumber: frame?.columnNumber, + }); } - tasks.sort((a, b) => b.durationMs - a.durationMs); - return { - mode: 'list', - tasks: tasks.slice(0, top), - }; + return result; } diff --git a/src/engine/helpers.ts b/src/engine/helpers.ts index 2c0b810..b0b411c 100644 --- a/src/engine/helpers.ts +++ b/src/engine/helpers.ts @@ -13,6 +13,7 @@ // limitations under the License. import type { LoadedTrace, ParsedTrace } from './loader.js'; +import type { ThreadItem } from './types.js'; type MapValue = T extends Map ? V : never; type RendererProcess = MapValue['processes']>; @@ -53,6 +54,51 @@ export function getMainRendererThread(data: ParsedTrace['data']): RendererThread return null; } +export function getRendererThread( + data: ParsedTrace['data'], + threadId?: string, +): RendererThread | null { + if (threadId === undefined) return getMainRendererThread(data); + + for (const [pid, process] of data.Renderer?.processes ?? []) { + for (const [tid, thread] of process.threads) { + if (threadId === `${pid}:${tid}` && thread.entries.length > 0) return thread; + } + } + throw new Error( + `Unknown renderer thread "${threadId}". Use trace-engine-cli threads to list PID:TID values.`, + ); +} + +export function listRendererThreads(data: ParsedTrace['data']): ThreadItem[] { + const threads: ThreadItem[] = []; + const defaultThread = getMainRendererThread(data); + for (const [pid, process] of data.Renderer?.processes ?? []) { + const frames = [...(data.Meta.frameByProcessId.get(pid)?.values() ?? [])]; + const frameUrls = [...new Set(frames.map((frame) => frame.url).filter(Boolean))]; + for (const [tid, thread] of process.threads) { + if (!thread.entries.length) continue; + threads.push({ + id: `${pid}:${tid}`, + name: thread.name, + frameUrls, + isDefault: thread === defaultThread, + hasCpuSamples: thread.profileCalls.length > 0, + }); + } + } + return threads; +} + +export function rendererCpuFilter({ engine, parsedTrace }: LoadedTrace) { + const entryToNode = parsedTrace.data.Renderer?.entryToNode; + return { + // The renderer tree discards overlapping entries that cannot represent nested CPU work. + accept: (event: RendererThread['entries'][number]) => + entryToNode?.has(event) === true && !engine.Types.Events.isPhaseAsync(event.ph), + }; +} + export interface InsightEntryResult { insightSetId: string; model: InsightModels; diff --git a/src/engine/types.ts b/src/engine/types.ts index 7525266..12e6e1f 100644 --- a/src/engine/types.ts +++ b/src/engine/types.ts @@ -22,6 +22,7 @@ export type CwvRating = 'good' | 'needs-improvement' | 'poor'; * All duration and timestamp properties are normalized to milliseconds (ms). */ export interface OverviewResult { + threadId?: string; bounds: { minMs: number; maxMs: number; @@ -130,6 +131,7 @@ export interface InsightsResult { */ export interface TaskItem { startTimeMs: number; + callPath?: string[]; durationMs: number; selfTimeMs: number; functionName: string; @@ -142,10 +144,24 @@ export interface TaskItem { * Aggregated main thread task execution details. */ export interface TasksResult { + threadId?: string; + warnings?: string[]; mode: 'list' | 'top-down' | 'bottom-up'; tasks: TaskItem[]; } +export interface ThreadItem { + id: string; + name: string | null; + frameUrls: string[]; + isDefault: boolean; + hasCpuSamples: boolean; +} + +export interface ThreadsResult { + threads: ThreadItem[]; +} + /** * Individual network request details and timing waterfall. */ @@ -263,6 +279,7 @@ export interface ShiftsResult { * Individual invocation instance of a searched function. */ export interface FindCallInstance { + functionName?: string; timestampMs: number; durationMs: number; url?: string; @@ -284,7 +301,9 @@ export interface FindIntervalItem { * Result of searching for a specific function's executions across a trace. */ export interface FindResult { - functionQuery: string; + threadId?: string; + functionQuery?: string; + urlQuery?: string; timeRange?: { startMs: number; endMs: number }; totalCalls: number; totalDurationMs: number; @@ -304,6 +323,7 @@ export interface ProfileBucketItem { totalActiveMs: number; topFunctions: Array<{ name: string; + url?: string; selfTimeMs: number; selfTimePct: number; }>; @@ -313,6 +333,8 @@ export interface ProfileBucketItem { * Time-bucketed CPU profiling result. */ export interface ProfileResult { + threadId?: string; + warnings?: string[]; timeRange: { startMs: number; endMs: number }; bucketSizeMs: number; buckets: ProfileBucketItem[]; @@ -335,6 +357,7 @@ export interface DiffEntryItem { * Differential profile result comparing two trace intervals. */ export interface DiffResult { + threadId?: string; windowA: { startMs: number; endMs: number; durationMs: number }; windowB: { startMs: number; endMs: number; durationMs: number }; entries: DiffEntryItem[]; diff --git a/src/formatters/index.ts b/src/formatters/index.ts index ed739f8..866d815 100644 --- a/src/formatters/index.ts +++ b/src/formatters/index.ts @@ -21,6 +21,7 @@ export interface FormatOptions { | 'overview' | 'insights' | 'tasks' + | 'threads' | 'network' | 'interactions' | 'shifts' @@ -37,8 +38,9 @@ export interface FormatOptions { const NEXT_STEPS_HINT_TOON = ` # Drill-down commands: # - trace-engine-cli insights [--category ] [--navigation ] -# - trace-engine-cli tasks [--min-duration ] [--tree ] [--top ] -# - trace-engine-cli find --function [--time-range ] +# - trace-engine-cli tasks [--min-duration ] [--tree ] [--url-only] [--top ] +# - trace-engine-cli find [--function ] [--url ] [--time-range ] +# - trace-engine-cli threads # - trace-engine-cli profile [--time-range ] [--bucket ] # - trace-engine-cli diff --window-a --window-b # - trace-engine-cli scheduling [--time-range ] @@ -56,8 +58,9 @@ const NEXT_STEPS_HINT_MD = ` --- ### Drill-down Commands - \`trace-engine-cli insights [--category ] [--navigation ]\` -- \`trace-engine-cli tasks [--min-duration ] [--tree ] [--top ]\` -- \`trace-engine-cli find --function [--time-range ]\` +- \`trace-engine-cli tasks [--min-duration ] [--tree ] [--url-only] [--top ]\` +- \`trace-engine-cli find [--function ] [--url ] [--time-range ]\` +- \`trace-engine-cli threads \` - \`trace-engine-cli profile [--time-range ] [--bucket ]\` - \`trace-engine-cli diff --window-a --window-b \` - \`trace-engine-cli scheduling [--time-range ]\` diff --git a/src/formatters/markdown.ts b/src/formatters/markdown.ts index b9af784..4fa8313 100644 --- a/src/formatters/markdown.ts +++ b/src/formatters/markdown.ts @@ -26,6 +26,7 @@ import type { SchedulingResult, ShiftsResult, TasksResult, + ThreadsResult, } from '../engine/types.js'; import { formatBytes, formatMs, formatScore } from '../utils/units.js'; @@ -60,7 +61,11 @@ export function formatOverviewMarkdown(overview: OverviewResult): string { ); lines.push(''); - lines.push('## Main Thread Time Breakdown'); + lines.push( + overview.threadId + ? `## Thread ${overview.threadId} Time Breakdown` + : '## Main Thread Time Breakdown', + ); lines.push(''); lines.push('| Category | Duration (ms) | Share |'); lines.push('|---|---|---|'); @@ -181,6 +186,8 @@ export function formatInsightsMarkdown(insights: InsightsResult): string { export function formatTasksMarkdown(tasksResult: TasksResult): string { const lines: string[] = [`# Tasks (${tasksResult.mode})`, '']; + if (tasksResult.threadId) lines.push(`Renderer thread \`${tasksResult.threadId}\``, ''); + if (tasksResult.warnings?.length) lines.push(...tasksResult.warnings, ''); if (tasksResult.tasks.length === 0) { lines.push('No tasks found matching criteria.'); return lines.join('\n'); @@ -191,7 +198,7 @@ export function formatTasksMarkdown(tasksResult: TasksResult): string { for (const t of tasksResult.tasks) { const loc = t.url ? `${t.url}${t.lineNumber !== undefined ? `:${t.lineNumber}` : ''}` : '-'; lines.push( - `| ${formatMs(t.startTimeMs)} | ${formatMs(t.durationMs)} | ${formatMs(t.selfTimeMs)} | \`${t.functionName}\` | \`${loc}\` |`, + `| ${formatMs(t.startTimeMs)} | ${formatMs(t.durationMs)} | ${formatMs(t.selfTimeMs)} | \`${t.callPath?.join(' > ') ?? t.functionName}\` | \`${loc}\` |`, ); } return lines.join('\n'); @@ -314,7 +321,12 @@ export function formatShiftsMarkdown(shifts: ShiftsResult): string { } export function formatFindMarkdown(findResult: FindResult): string { - const lines: string[] = [`# Function Execution: \`${findResult.functionQuery}\``, '']; + const heading = findResult.functionQuery + ? `# Function Execution: \`${findResult.functionQuery}\`` + : '# Function Execution'; + const lines: string[] = [heading, '']; + if (findResult.urlQuery) lines.push(`- **URL**: \`${findResult.urlQuery}\``); + if (findResult.threadId) lines.push(`- **Renderer thread**: \`${findResult.threadId}\``); lines.push(`- **Total Calls**: \`${findResult.totalCalls}\``); lines.push(`- **Total Duration**: \`${formatMs(findResult.totalDurationMs)}\``); lines.push(`- **Average Duration**: \`${formatMs(findResult.avgDurationMs)}\``); @@ -342,11 +354,13 @@ export function formatFindMarkdown(findResult: FindResult): string { if (findResult.calls.length > 0) { lines.push('## Call Invocations'); lines.push(''); - lines.push('| Timestamp (ms) | Duration (ms) | Location |'); - lines.push('|---|---|---|'); + lines.push('| Timestamp (ms) | Duration (ms) | Function | Location |'); + lines.push('|---|---|---|---|'); for (const c of findResult.calls) { const loc = c.url ? `${c.url}${c.lineNumber !== undefined ? `:${c.lineNumber}` : ''}` : '-'; - lines.push(`| ${formatMs(c.timestampMs)} | ${formatMs(c.durationMs)} | \`${loc}\` |`); + lines.push( + `| ${formatMs(c.timestampMs)} | ${formatMs(c.durationMs)} | ${c.functionName ?? '-'} | \`${loc}\` |`, + ); } lines.push(''); } @@ -360,6 +374,9 @@ export function formatProfileMarkdown(profileResult: ProfileResult): string { '', ]; + if (profileResult.threadId) lines.push(`Renderer thread \`${profileResult.threadId}\``, ''); + if (profileResult.warnings?.length) lines.push(...profileResult.warnings, ''); + if (profileResult.buckets.length === 0) { lines.push('No CPU activity found in the specified range.'); return lines.join('\n'); @@ -368,7 +385,9 @@ export function formatProfileMarkdown(profileResult: ProfileResult): string { lines.push('| Time Bucket | Active CPU (ms) | Top Functions (% of slice) |'); lines.push('|---|---|---|'); for (const b of profileResult.buckets) { - const topSummary = b.topFunctions.map((f) => `${f.name} (${f.selfTimePct}%)`).join(', '); + const topSummary = b.topFunctions + .map((f) => `${f.name} (${f.selfTimePct}%)${f.url ? ` \`${f.url}\`` : ''}`) + .join(', '); lines.push( `| ${formatMs(b.startMs)} - ${formatMs(b.endMs)} | ${formatMs(b.totalActiveMs)} | ${topSummary || 'None (Idle)'} |`, ); @@ -378,6 +397,7 @@ export function formatProfileMarkdown(profileResult: ProfileResult): string { export function formatDiffMarkdown(diffResult: DiffResult): string { const lines: string[] = ['# Differential Profile', '']; + if (diffResult.threadId) lines.push(`Renderer thread \`${diffResult.threadId}\``, ''); lines.push( `- **Window A**: \`${formatMs(diffResult.windowA.startMs)} - ${formatMs(diffResult.windowA.endMs)}\` (${formatMs(diffResult.windowA.durationMs)})`, ); @@ -562,6 +582,21 @@ export function formatScanMarkdown(result: ScanResult): string { return lines.join('\n'); } +function formatThreadsMarkdown({ threads }: ThreadsResult): string { + const lines = [ + '# Renderer Threads', + '', + '| PID:TID | Thread | Frame URLs | Default | CPU samples |', + '|---|---|---|---|---|', + ]; + for (const thread of threads) { + lines.push( + `| ${thread.id} | ${thread.name ?? '-'} | ${thread.frameUrls.join(', ') || '-'} | ${thread.isDefault ? 'Yes' : 'No'} | ${thread.hasCpuSamples ? 'Yes' : 'No'} |`, + ); + } + return lines.join('\n'); +} + export function formatMarkdown(data: unknown, type?: string): string { switch (type) { case 'overview': @@ -570,6 +605,8 @@ export function formatMarkdown(data: unknown, type?: string): string { return formatInsightsMarkdown(data as InsightsResult); case 'tasks': return formatTasksMarkdown(data as TasksResult); + case 'threads': + return formatThreadsMarkdown(data as ThreadsResult); case 'network': return formatNetworkMarkdown(data as NetworkResult); case 'interactions': diff --git a/test/cli.test.ts b/test/cli.test.ts index 2cc0daa..945483e 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -100,6 +100,49 @@ describe('CLI Dispatcher', () => { assert.ok(output.includes('totalCalls: 1')); }); + test('lists renderer threads in Markdown and JSON', async () => { + const fixture = path.resolve(import.meta.dirname, 'fixtures/navigation-cwv-trace.json'); + const args = ['node', 'trace-engine-cli', 'threads', fixture]; + const threads = await captureCliOutput([...args, '--format', 'md']); + assert.match(threads, /100:1.*CrRendererMain/); + const json = JSON.parse(await captureCliOutput([...args, '--format', 'json'])); + assert.equal(json.threads[0].id, '100:1'); + assert.equal(json.threads[0].name, 'CrRendererMain'); + }); + + test('finds named calls by URL on the chosen renderer thread', async () => { + const fixture = path.resolve(import.meta.dirname, 'fixtures/navigation-cwv-trace.json'); + const cli = ['node', 'trace-engine-cli']; + const args = [...cli, 'find', fixture, '--thread', '100:1', '--url', 'app.js']; + assert.match(await captureCliOutput(args), /bootApp/); + assert.match(await captureCliOutput([...args, '--function', 'missing']), /totalCalls: 0/); + await assert.rejects( + () => captureCliOutput([...args.slice(0, 4), '--thread', '999:1', '--url', 'app.js']), + /Unknown renderer thread.*threads /, + ); + }); + + test('rejects non-positive result limits and bucket sizes', async () => { + const fixture = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json'); + const args = ['node', 'trace-engine-cli']; + await assert.rejects( + () => captureCliOutput([...args, 'tasks', fixture, '--top', '-5']), + /positive integers/, + ); + await assert.rejects( + () => captureCliOutput([...args, 'profile', fixture, '--bucket', '0']), + /--bucket must be at least/, + ); + }); + + test('requires a function or URL for find', async () => { + const fixture = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json'); + await assert.rejects( + () => captureCliOutput(['node', 'trace-engine-cli', 'find', fixture]), + /Specify --function or --url/, + ); + }); + test('runs profile subcommand with relative range and bucket units', async () => { const fixturePath = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json'); const output = await captureCliOutput([ diff --git a/test/extractors/overview.test.ts b/test/extractors/overview.test.ts index 1dce1ca..24d8ff3 100644 --- a/test/extractors/overview.test.ts +++ b/test/extractors/overview.test.ts @@ -13,11 +13,13 @@ // limitations under the License. import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; import path from 'node:path'; import test, { describe } from 'node:test'; import { extractOverview } from '../../src/engine/extractors/overview.js'; import { extractShifts } from '../../src/engine/extractors/shifts.js'; -import { loadTraceFromFile } from '../../src/engine/loader.js'; +import { loadTraceFromFile, parseTraceJson } from '../../src/engine/loader.js'; describe('Overview Extractor', () => { test('extractOverview parses metadata and main thread stats for basic-trace', async () => { @@ -82,6 +84,61 @@ describe('Overview Extractor', () => { assert.equal(activeAndIdleSum, overview.mainThreadBreakdown.totalMs); }); + test('keeps timeline categories stable when CPU samples add nested calls', async (t) => { + const fixture = path.resolve(import.meta.dirname, '../fixtures/navigation-cwv-trace.json'); + const events = parseTraceJson(await readFile(fixture, 'utf8')); + const dir = await mkdtemp(path.join(os.tmpdir(), 'trace-cli-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const sampled = path.join(dir, 'sampled.json'); + const profile = { + cat: 'disabled-by-default-v8.cpu_profiler', + ph: 'P', + pid: 100, + tid: 1, + id: '0x1', + }; + const profileStart = { + ...profile, + name: 'Profile', + ts: 1405000, + args: { data: { startTime: 1405000 } }, + }; + const profileChunk = { + ...profile, + name: 'ProfileChunk', + ts: 1465000, + args: { + data: { + cpuProfile: { + nodes: [ + { id: 1, callFrame: { functionName: '(root)', scriptId: '0' } }, + { + id: 2, + parent: 1, + callFrame: { + functionName: 'sampledFunction', + scriptId: '1', + url: 'https://example.com/app.js', + lineNumber: 43, + columnNumber: 1, + }, + }, + ], + samples: [2, 2, 2], + }, + timeDeltas: [10000, 20000, 30000], + }, + }, + }; + await writeFile(sampled, JSON.stringify([...events, profileStart, profileChunk])); + + const original = extractOverview(await loadTraceFromFile(fixture)); + const withSamples = extractOverview(await loadTraceFromFile(sampled)); + assert.ok(original.warnings.some((warning) => warning.includes('cpu_profiler'))); + assert.ok(!withSamples.warnings.some((warning) => warning.includes('cpu_profiler'))); + assert.deepEqual(withSamples.mainThreadBreakdown, original.mainThreadBreakdown); + }); + test('extractOverview parses interaction-to-next-paint for interaction-trace', async () => { const fixturePath = path.resolve(import.meta.dirname, '../fixtures/interaction-trace.json'); const loaded = await loadTraceFromFile(fixturePath); diff --git a/test/extractors/tasks.test.ts b/test/extractors/tasks.test.ts index bf44e5e..48deda4 100644 --- a/test/extractors/tasks.test.ts +++ b/test/extractors/tasks.test.ts @@ -13,10 +13,12 @@ // limitations under the License. import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; import path from 'node:path'; import test, { describe } from 'node:test'; import { extractTasks } from '../../src/engine/extractors/tasks.js'; -import { loadTraceFromFile } from '../../src/engine/loader.js'; +import { loadTraceFromFile, parseTraceJson } from '../../src/engine/loader.js'; describe('Tasks Extractor', () => { test('extractTasks extracts top-level tasks above threshold', async () => { @@ -89,10 +91,56 @@ describe('Tasks Extractor', () => { assert.equal(bottomUpResult.mode, 'bottom-up'); assert.ok(bottomUpResult.tasks.length > 0); assert.equal(bottomUpResult.tasks[0].functionName, 'bootApp'); + assert.equal(bottomUpResult.tasks[0].startTimeMs, 1405); assert.equal(bottomUpResult.tasks[0].selfTimeMs, 70); assert.equal(bottomUpResult.tasks[0].durationMs, 70); assert.equal(bottomUpResult.tasks[0].url, 'https://example.com/app.js'); assert.equal(bottomUpResult.tasks[0].lineNumber, 42); assert.equal(bottomUpResult.tasks[0].columnNumber, 8); }); + + test('shows nested calls in the top-down tree and applies URL filtering before the limit', async () => { + const fixture = path.resolve(import.meta.dirname, '../fixtures/navigation-cwv-trace.json'); + const loaded = await loadTraceFromFile(fixture); + const topDown = extractTasks(loaded, { tree: 'top-down' }); + const call = topDown.tasks.find((task) => task.functionName === 'bootApp'); + assert.deepEqual(call?.callPath, ['RunTask', 'bootApp']); + + const filtered = extractTasks(loaded, { tree: 'top-down', top: 1, urlOnly: true }); + assert.equal(filtered.tasks[0]?.url, 'https://example.com/app.js'); + assert.equal(filtered.tasks[0]?.functionName, 'bootApp'); + }); + + test('preserves ranking ties and applies URL eligibility before the limit', async (t) => { + const fixture = path.resolve(import.meta.dirname, '../fixtures/navigation-cwv-trace.json'); + const events = parseTraceJson(await readFile(fixture, 'utf8')); + const dir = await mkdtemp(path.join(os.tmpdir(), 'trace-cli-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const file = path.join(dir, 'ranked-tasks.json'); + const runTask = { + name: 'RunTask', + cat: 'disabled-by-default-devtools.timeline', + ph: 'X', + pid: 100, + tid: 1, + }; + const taskEvents = [ + { ...runTask, ts: 5500000, dur: 180000 }, + { ...runTask, ts: 5800000, dur: 180001 }, + { ...runTask, ts: 6100000, dur: 180002 }, + { ...runTask, ts: 6400000, dur: 180003 }, + ]; + await writeFile(file, JSON.stringify([...events, ...taskEvents])); + + const loaded = await loadTraceFromFile(file); + const longest = extractTasks(loaded, { top: 2 }); + const startTimes = longest.tasks.map((task) => task.startTimeMs); + assert.deepEqual(startTimes, [5500, 5800]); + + const withUrl = extractTasks(loaded, { top: 1, urlOnly: true }); + assert.equal(withUrl.tasks[0]?.functionName, 'RunTask > bootApp'); + + const bottomUp = extractTasks(loaded, { tree: 'bottom-up', top: 1, urlOnly: true }); + assert.equal(bottomUp.tasks[0]?.functionName, 'bootApp'); + }); });