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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ trace-engine-cli/

### 2.3. Main Thread Category Calculation
- **No Flat Duration Summation**: Chromium traces contain deeply nested event slices (e.g. `RunTask` -> `EvaluateScript` -> `FunctionCall` -> `Layout`). Summing raw `entry.dur` across all entries results in severe double/triple counting (>100% trace time).
- **TraceTree Self-Times**: Main thread categories (Scripting, Layout, Rendering, GC, System, Idle) in [`src/engine/extractors/overview.ts`](src/engine/extractors/overview.ts) MUST be derived from non-overlapping `TraceTree.BottomUpRootNode` self-times so that `scripting + layout + rendering + gc + system + idle === totalDurationMs`.
- **TraceTree Self-Times**: Main thread categories (Scripting, Style, Layout, Paint, Composite, GC, Interrupts, System, Idle) in [`src/engine/extractors/overview.ts`](src/engine/extractors/overview.ts) MUST be derived from non-overlapping `TraceTree.BottomUpRootNode` self-times so that `scripting + style + layout + paint + composite + gc + interrupt + system + idle === totalDurationMs`.

### 2.4. Safe File Reading & No TOCTOU
- Do **not** use `fs.existsSync` immediately before `fs.readFileSync`.
Expand Down
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ Use `trace-engine-cli` to inspect, profile, and diagnose performance recordings
## 3. Command Reference

### `trace-engine-cli <file>` / `trace-engine-cli overview <file>`
High-level trace metadata, duration, Core Web Vitals (LCP, INP, CLS), and main-thread category breakdown (Scripting, Layout, Rendering, GC, System, Idle). Calling `trace-engine-cli <file>` without `overview` also prints the `# Drill-down commands:` reference footer.
High-level trace metadata, duration, Core Web Vitals (LCP, INP, CLS), and a breakdown of main-thread time by category. Calling `trace-engine-cli <file>` without `overview` also prints the `# Drill-down commands:` reference footer.
```bash
trace-engine-cli trace.json.gz
```
Expand Down Expand Up @@ -314,11 +314,12 @@ All time-range inputs (`--time-range`, `--window-a`, `--window-b`, `--bucket`) s
## Subcommands

### 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.
High-level trace metadata, Core Web Vitals (FCP, LCP, CLS, INP), a non-overlapping breakdown of main-thread time, 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.
Style recalculation appears in `styleMs`, and `interruptMs` tracks V8 API interrupt callbacks used by the tracer and CPU throttling.

```bash
# Default invocation (includes the drill-down commands footer)
Expand Down Expand Up @@ -351,11 +352,14 @@ coreWebVitals:
inp: null
mainThreadBreakdown:
scriptingMs: 1.69
layoutMs: 80.13
renderingMs: 17.9
styleMs: 30
layoutMs: 50.13
paintMs: 14.9
compositeMs: 3
gcMs: 0.07
systemMs: 233.52
idleMs: 5057.64
interruptMs: 100
systemMs: 133.52
idleMs: 5057.65
totalMs: 5390.96
warnings[1]: 1 render-blocking resource(s) detected.

Expand Down
98 changes: 58 additions & 40 deletions src/engine/extractors/overview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,14 +172,15 @@ export function extractOverview(
}

// 4. Main Thread Breakdown (Derived from TraceTree self-times to eliminate double-counting)
const breakdown = {
const work = {
scriptingMs: 0,
styleMs: 0,
layoutMs: 0,
renderingMs: 0,
paintMs: 0,
compositeMs: 0,
gcMs: 0,
interruptMs: 0,
systemMs: 0,
idleMs: 0,
totalMs: 0,
};

const mainThread = getRendererThread(data, options?.threadId);
Expand All @@ -200,62 +201,79 @@ export function extractOverview(
endTime: engine.Types.Timing.Micro(milliToMicro(maxMs)),
});

const { Name } = engine.Types.Events;
const children = bottomUp.children();
for (const node of children.values()) {
if (node.selfTime <= 0) continue;
const selfTimeMs = microToMilli(node.selfTime);
const name = node.event?.name || String(node.id) || '';

if (
name === 'MajorGC' ||
name === 'MinorGC' ||
name === 'GCEvent' ||
name === Name.MAJOR_GC ||
name === Name.MINOR_GC ||
name === Name.GC ||
name.toLowerCase().startsWith('v8.gc')
) {
breakdown.gcMs += selfTimeMs;
} else if (name === 'Layout' || name === 'UpdateLayoutTree' || name === 'InvalidateLayout') {
breakdown.layoutMs += selfTimeMs;
work.gcMs += selfTimeMs;
} else if (name === Name.RECALC_STYLE) {
work.styleMs += selfTimeMs;
} else if (name === Name.LAYOUT || name === Name.INVALIDATE_LAYOUT) {
work.layoutMs += selfTimeMs;
} else if (
name === Name.PRE_PAINT ||
name === Name.PAINT ||
name === Name.PAINT_IMAGE ||
name === Name.RASTER_TASK ||
name === Name.DECODE_IMAGE ||
name === Name.UPDATE_LAYER
) {
work.paintMs += selfTimeMs;
} else if (
name === 'UpdateLayerTree' ||
name === 'Layerize' ||
name === 'Paint' ||
name === 'CompositeLayers' ||
name === 'RasterTask' ||
name === 'DecodeImage'
name === Name.UPDATE_LAYER_TREE ||
name === Name.LAYERIZE ||
name === Name.COMPOSITE_LAYERS ||
name === Name.COMMIT
) {
breakdown.renderingMs += selfTimeMs;
work.compositeMs += selfTimeMs;
} else if (name === 'V8.InvokeApiInterruptCallbacks') {
work.interruptMs += selfTimeMs;
} else if (
name === 'EvaluateScript' ||
name === 'FunctionCall' ||
name.startsWith('v8.compile') ||
name === Name.EVALUATE_SCRIPT ||
name === Name.FUNCTION_CALL ||
name.startsWith(Name.COMPILE) ||
name === 'v8.callFunction' ||
name === 'RunMicrotasks' ||
name === Name.RUN_MICROTASKS ||
name === 'v8.run' ||
name === 'TimerFire' ||
name === 'FireAnimationFrame' ||
name === 'EventDispatch'
name === Name.TIMER_FIRE ||
name === Name.FIRE_ANIMATION_FRAME ||
name === Name.EVENT_DISPATCH
) {
breakdown.scriptingMs += selfTimeMs;
work.scriptingMs += selfTimeMs;
} else {
breakdown.systemMs += selfTimeMs;
work.systemMs += selfTimeMs;
}
}
}

const activeWork =
breakdown.scriptingMs +
breakdown.layoutMs +
breakdown.renderingMs +
breakdown.gcMs +
breakdown.systemMs;

breakdown.idleMs = round(Math.max(0, durationMs - activeWork));
breakdown.scriptingMs = round(breakdown.scriptingMs);
breakdown.layoutMs = round(breakdown.layoutMs);
breakdown.renderingMs = round(breakdown.renderingMs);
breakdown.gcMs = round(breakdown.gcMs);
breakdown.systemMs = round(breakdown.systemMs);
breakdown.totalMs = durationMs;
let activeWork = 0;
// Round cumulative time so category rounding cannot add or remove time from the total.
function roundKind(ms: number): number {
const previous = round(activeWork);
activeWork += ms;
return round(round(activeWork) - previous);
}
const breakdown = {
scriptingMs: roundKind(work.scriptingMs),
styleMs: roundKind(work.styleMs),
layoutMs: roundKind(work.layoutMs),
paintMs: roundKind(work.paintMs),
compositeMs: roundKind(work.compositeMs),
gcMs: roundKind(work.gcMs),
interruptMs: roundKind(work.interruptMs),
systemMs: roundKind(work.systemMs),
idleMs: round(Math.max(0, durationMs - round(activeWork))),
totalMs: durationMs,
};

// 5. Warnings
const warnings: string[] = [];
Expand Down
5 changes: 4 additions & 1 deletion src/engine/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,12 @@ export interface OverviewResult {
};
mainThreadBreakdown: {
scriptingMs: number;
styleMs: number;
layoutMs: number;
renderingMs: number;
paintMs: number;
compositeMs: number;
gcMs: number;
interruptMs: number;
systemMs: number;
idleMs: number;
totalMs: number;
Expand Down
5 changes: 4 additions & 1 deletion src/formatters/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,12 @@ export function formatOverviewMarkdown(overview: OverviewResult): string {
const total = b.totalMs > 0 ? b.totalMs : 1;
const rows = [
{ name: 'Scripting', ms: b.scriptingMs },
{ name: 'Style', ms: b.styleMs },
{ name: 'Layout', ms: b.layoutMs },
{ name: 'Rendering', ms: b.renderingMs },
{ name: 'Paint', ms: b.paintMs },
{ name: 'Composite', ms: b.compositeMs },
{ name: 'Garbage Collection', ms: b.gcMs },
{ name: 'Interrupts (tracer, throttling)', ms: b.interruptMs },
{ name: 'System', ms: b.systemMs },
{ name: 'Idle', ms: b.idleMs },
];
Expand Down
59 changes: 54 additions & 5 deletions test/extractors/overview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,15 @@ describe('Overview Extractor', () => {
assert.equal(overview.mainUrl, 'https://example.com/test');
assert.equal(overview.navigationStartMs, 1050);
assert.deepEqual(overview.mainThreadBreakdown, {
systemMs: 60,
idleMs: 100,
scriptingMs: 0,
styleMs: 0,
layoutMs: 0,
renderingMs: 0,
paintMs: 0,
compositeMs: 0,
gcMs: 0,
interruptMs: 0,
systemMs: 60,
idleMs: 100,
totalMs: 160,
});
});
Expand All @@ -67,23 +70,69 @@ describe('Overview Extractor', () => {
assert.ok(overview.warnings.includes('1 render-blocking resource(s) detected.'));
assert.deepEqual(overview.mainThreadBreakdown, {
scriptingMs: 70,
styleMs: 0,
layoutMs: 20,
renderingMs: 10,
paintMs: 10,
compositeMs: 0,
gcMs: 25,
interruptMs: 0,
systemMs: 65,
idleMs: 4010,
totalMs: 4200,
});
const activeAndIdleSum =
overview.mainThreadBreakdown.scriptingMs +
overview.mainThreadBreakdown.styleMs +
overview.mainThreadBreakdown.layoutMs +
overview.mainThreadBreakdown.renderingMs +
overview.mainThreadBreakdown.paintMs +
overview.mainThreadBreakdown.compositeMs +
overview.mainThreadBreakdown.gcMs +
overview.mainThreadBreakdown.interruptMs +
overview.mainThreadBreakdown.systemMs +
overview.mainThreadBreakdown.idleMs;
assert.equal(activeAndIdleSum, overview.mainThreadBreakdown.totalMs);
});

test('splits render work and V8 API interrupts into exclusive categories', async () => {
const fixture = path.resolve(import.meta.dirname, '../fixtures/render-kinds-trace.json');
const loaded = await loadTraceFromFile(fixture);
const b = extractOverview(loaded, { threadId: '100:1' }).mainThreadBreakdown;

assert.equal(b.scriptingMs, 6);
assert.equal(b.styleMs, 4);
assert.equal(b.layoutMs, 3);
assert.equal(b.paintMs, 4);
assert.equal(b.compositeMs, 2);
assert.equal(b.gcMs, 0);
assert.equal(b.interruptMs, 5);
assert.equal(b.systemMs, 6);
assert.equal(b.idleMs, 10);
assert.equal(
b.scriptingMs +
b.styleMs +
b.layoutMs +
b.paintMs +
b.compositeMs +
b.gcMs +
b.interruptMs +
b.systemMs +
b.idleMs,
b.totalMs,
);
});

test('keeps a fractional window fully accounted for after rounding', async () => {
const fixture = path.resolve(import.meta.dirname, '../fixtures/render-kinds-trace.json');
const loaded = await loadTraceFromFile(fixture);
const b = extractOverview(loaded, {
timeRange: { startMs: 1017.994, endMs: 1018.006 },
}).mainThreadBreakdown;

assert.equal(b.idleMs, 0);
assert.equal(b.totalMs, 0.01);
assert.equal(b.layoutMs + b.paintMs, b.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'));
Expand Down
Loading