Skip to content
Merged
Show file tree
Hide file tree
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
40 changes: 32 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ trace-engine-cli scan fixtures/traces/ --cat devtools.timeline --phase X
3. Inspect relevant subsystem: `trace-engine-cli shifts <fixture> --events`, `trace-engine-cli network <fixture>`, or `trace-engine-cli insights <fixture> --category <category>`
4. Inspect raw event payloads: `trace-engine-cli events <fixture> --name <EventName> --fields <fieldPaths>`

### Recipe D: Analyzing CPU Activity in a Subframe
1. Run `trace-engine-cli threads <file>` 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 <file> --thread 123:1`. Frames that share a renderer thread share its CPU results.

---

## 5. Capture Caveats
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -326,8 +334,9 @@ warnings[1]: 1 render-blocking resource(s) detected.

# Drill-down commands:
# - trace-engine-cli insights <file> [--category <lcp|inp|cls|render-blocking|third-parties>] [--navigation <id>]
# - trace-engine-cli tasks <file> [--min-duration <ms>] [--tree <bottom-up|top-down>] [--top <n>]
# - trace-engine-cli find <file> --function <name> [--time-range <start,end>]
# - trace-engine-cli tasks <file> [--min-duration <ms>] [--tree <bottom-up|top-down>] [--url-only] [--top <n>]
# - trace-engine-cli find <file> [--function <name>] [--url <pattern>] [--time-range <start,end>]
# - trace-engine-cli threads <file>
# - trace-engine-cli profile <file> [--time-range <start,end>] [--bucket <ms>]
# - trace-engine-cli diff <file> --window-a <start,end> --window-b <start,end>
# - trace-engine-cli scheduling <file> [--time-range <start,end>]
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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"
```

---
Expand Down Expand Up @@ -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)
Expand Down
68 changes: 62 additions & 6 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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 <file> 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<void> {
const cli = yargs(hideBin(argv))
.scriptName('trace-engine-cli')
Expand Down Expand Up @@ -77,7 +91,7 @@ export async function runCli(argv: string[]): Promise<void> {
['overview <file>', '$0 <file>'],
'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,
Expand All @@ -93,7 +107,7 @@ export async function runCli(argv: string[]): Promise<void> {
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, {
Expand All @@ -104,6 +118,21 @@ export async function runCli(argv: string[]): Promise<void> {
);
},
)
.command(
'threads <file>',
'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 <file>',
'Diagnostic insight cards (LCP, INP, CLS, render-blocking, third-parties)',
Expand Down Expand Up @@ -152,6 +181,7 @@ export async function runCli(argv: string[]): Promise<void> {
'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',
Expand All @@ -168,9 +198,14 @@ export async function runCli(argv: string[]): Promise<void> {
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)',
}),
Expand All @@ -186,10 +221,12 @@ export async function runCli(argv: string[]): Promise<void> {
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, {
Expand All @@ -204,6 +241,7 @@ export async function runCli(argv: string[]): Promise<void> {
'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',
Expand All @@ -212,12 +250,16 @@ export async function runCli(argv: string[]): Promise<void> {
.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)',
}),
Expand All @@ -233,8 +275,10 @@ export async function runCli(argv: string[]): Promise<void> {
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(
Expand All @@ -250,6 +294,7 @@ export async function runCli(argv: string[]): Promise<void> {
'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',
Expand All @@ -263,6 +308,7 @@ export async function runCli(argv: string[]): Promise<void> {
.option('top', {
alias: ['limit'],
type: 'number',
coerce: positiveInteger,
default: 3,
describe: 'Top N functions to include per time bucket (default: 3)',
}),
Expand All @@ -277,9 +323,13 @@ export async function runCli(argv: string[]): Promise<void> {
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,
});
Expand All @@ -296,6 +346,7 @@ export async function runCli(argv: string[]): Promise<void> {
'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',
Expand All @@ -316,6 +367,7 @@ export async function runCli(argv: string[]): Promise<void> {
.option('top', {
alias: ['limit'],
type: 'number',
coerce: positiveInteger,
default: 20,
describe: 'Maximum differential entries to return (default: 20)',
}),
Expand All @@ -338,6 +390,7 @@ export async function runCli(argv: string[]): Promise<void> {

const result = extractDiff(loaded, {
windowA,
threadId: args.thread,
windowB,
top: args.top as number,
});
Expand Down Expand Up @@ -396,6 +449,7 @@ export async function runCli(argv: string[]): Promise<void> {
.option('slowest', {
alias: ['top', 'limit'],
type: 'number',
coerce: positiveInteger,
default: 20,
describe: 'Limit output to N slowest requests (default: 20)',
})
Expand Down Expand Up @@ -530,6 +584,7 @@ export async function runCli(argv: string[]): Promise<void> {
.option('top', {
alias: ['limit'],
type: 'number',
coerce: positiveInteger,
default: 50,
describe: 'Maximum number of matching events to return (default: 50)',
}),
Expand Down Expand Up @@ -624,6 +679,7 @@ export async function runCli(argv: string[]): Promise<void> {
.option('top', {
alias: ['limit'],
type: 'number',
coerce: positiveInteger,
default: 50,
describe: 'Maximum number of matched files to return (default: 50)',
}),
Expand Down
8 changes: 5 additions & 3 deletions src/engine/extractors/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand All @@ -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;
}
Expand All @@ -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),
});
Expand Down
Loading