From 11e7f2186cd4dc814a433ba9931af34e7fb2c357 Mon Sep 17 00:00:00 2001 From: Joan Leon Date: Tue, 24 Nov 2026 18:30:51 +0100 Subject: [PATCH] Scope time range options per command and bound profile bucket count `--time-range` and `--absolute-timestamps` are declared only on the commands that use them, so `threads` and `scan` reject both and `diff` rejects `--time-range` instead of ignoring them. `diff` keeps `--absolute-timestamps` for `--window-a` and `--window-b`, and command help only lists the options each command supports. `tasks --min-duration` rejects negative and non-numeric values. `extractProfile()` enforces a 0.01ms minimum and a maximum of 1000 buckets, and rounds the bucket size before the check so it matches the loop step. Before, `--bucket 0.01ms` created 16,000 buckets on a 160ms trace. --- README.md | 13 +++- src/cli.ts | 108 +++++++++++++++++++++---------- src/engine/extractors/profile.ts | 19 +++++- test/cli.test.ts | 77 ++++++++++++++++++++++ test/extractors/profile.test.ts | 54 ++++++++++++++++ 5 files changed, 234 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 4802c86..c3647c6 100644 --- a/README.md +++ b/README.md @@ -274,11 +274,18 @@ trace-engine-cli --help | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `-f, --format` | `'toon' \| 'md' \| 'json'` | `'toon'` | Output serialization format | -| `--time-range` | `string` | — | Filter window relative to trace start (e.g. `"3500,4200"`, `"3.5s,4.2s"`, `"100ms-500ms"`) | -| `--absolute-timestamps` | `boolean` | `false` | Treat time ranges as raw absolute trace timestamps rather than relative to trace start | | `--trace-engine`| `string` | — | Path to a custom DevTools trace engine bundle | | `--help` | `boolean` | — | Show help and synopsis | +### Time Range Options + +All commands except `threads`, `diff` and `scan` accept these options. `diff` accepts `--absolute-timestamps` for its `--window-a` and `--window-b` values. `threads` and `scan` reject both options. + +| Option | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `--time-range` | `string` | — | Filter window relative to trace start (e.g. `"3500,4200"`, `"3.5s,4.2s"`, `"100ms-500ms"`) | +| `--absolute-timestamps` | `boolean` | `false` | Treat time ranges as raw absolute trace timestamps rather than relative to trace start | + --- ## Relative vs. Absolute Timestamps & Units @@ -434,6 +441,8 @@ trace-engine-cli profile trace.json.gz --time-range "3.5s,4.1s" trace-engine-cli profile trace.json.gz --time-range "3500ms,4100ms" --bucket 50ms --top 5 ``` +`--bucket` must be at least `0.01ms`. A profile can have a maximum of 1000 buckets. If the time range divided by the bucket size is more than 1000, the command fails and shows the smallest valid bucket size. + --- ### 6. `diff` diff --git a/src/cli.ts b/src/cli.ts index c9238da..4533206 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -22,7 +22,7 @@ import { extractInteractions } from './engine/extractors/interactions.js'; import { extractNavigations } from './engine/extractors/navigations.js'; import { extractNetwork } from './engine/extractors/network.js'; import { extractOverview } from './engine/extractors/overview.js'; -import { extractProfile } from './engine/extractors/profile.js'; +import { extractProfile, MIN_BUCKET_MS } from './engine/extractors/profile.js'; import { DEFAULT_REPORT_SECTIONS, extractReport, @@ -60,6 +60,19 @@ const THREAD_OPTION = { describe: 'Renderer thread as PID:TID. Use threads to look up a frame URL.', } satisfies import('yargs').Options; +const TIME_RANGE_OPTION = { + type: 'string', + describe: + 'Time window (relative to trace start by default, e.g. "3500,4200", "3.5s,4.2s", "100ms-500ms")', +} satisfies import('yargs').Options; + +const ABSOLUTE_TIMESTAMPS_OPTION = { + type: 'boolean', + default: false, + describe: + 'Treat time ranges as raw absolute trace timestamps rather than relative to trace start (default: false)', +} satisfies import('yargs').Options; + function positiveInteger(value: number): number { if (!Number.isSafeInteger(value) || value < 1) { throw new Error('Result limits must be positive integers.'); @@ -67,6 +80,13 @@ function positiveInteger(value: number): number { return value; } +function nonNegativeMinDuration(value: number): number { + if (!Number.isFinite(value) || value < 0) { + throw new Error(`--min-duration must be a number >= 0. Received: ${value}`); + } + return value; +} + function parseReportSections(value?: string): ReportSection[] { if (value === undefined) return DEFAULT_REPORT_SECTIONS; @@ -98,26 +118,19 @@ export async function runCli(argv: string[]): Promise { type: 'string', describe: 'Path to custom trace engine bundle', }) - .option('time-range', { - type: 'string', - describe: - 'Time window (relative to trace start by default, e.g. "3500,4200", "3.5s,4.2s", "100ms-500ms")', - }) - .option('absolute-timestamps', { - type: 'boolean', - default: false, - describe: - 'Treat time ranges as raw absolute trace timestamps rather than relative to trace start (default: false)', - }) .command( ['overview ', '$0 '], 'High-level trace metadata, Core Web Vitals, and main thread category breakdown (default command)', (y) => - y.option('thread', THREAD_OPTION).positional('file', { - describe: 'Path to trace file (.json or .json.gz)', - type: 'string', - demandOption: true, - }), + y + .option('thread', THREAD_OPTION) + .positional('file', { + describe: 'Path to trace file (.json or .json.gz)', + type: 'string', + demandOption: true, + }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION), async (args) => { const loaded = await loadTraceFromFile( args.file as string, @@ -150,6 +163,8 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('sections', { type: 'string', describe: `Comma-separated analyses: ${REPORT_SECTIONS.join(', ')} (default: ${DEFAULT_REPORT_SECTIONS.join(',')})`, @@ -207,6 +222,8 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('category', { type: 'string', choices: ['lcp', 'inp', 'cls', 'render-blocking', 'third-parties'] as const, @@ -257,8 +274,11 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('min-duration', { type: 'number', + coerce: nonNegativeMinDuration, default: 50, describe: 'Minimum task duration threshold in milliseconds (default: 50ms)', }) @@ -317,6 +337,8 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('function', { alias: ['fn', 'name'], type: 'string', @@ -370,6 +392,8 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('bucket', { type: 'string', describe: @@ -394,8 +418,8 @@ export async function runCli(argv: string[]): Promise { args.absoluteTimestamps as boolean, ); 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.'); + if (bucketMs !== undefined && (!Number.isFinite(bucketMs) || bucketMs < MIN_BUCKET_MS)) { + throw new Error(`--bucket must be at least ${MIN_BUCKET_MS}ms.`); } const result = extractProfile(loaded, { timeRange, @@ -422,6 +446,7 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('window-a', { type: 'string', demandOption: true, @@ -476,11 +501,14 @@ export async function runCli(argv: string[]): Promise { 'scheduling ', 'Async task and animation frame scheduling, cancellation, and churn metrics', (y) => - y.positional('file', { - describe: 'Path to trace file (.json or .json.gz)', - type: 'string', - demandOption: true, - }), + y + .positional('file', { + describe: 'Path to trace file (.json or .json.gz)', + type: 'string', + demandOption: true, + }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION), async (args) => { const loaded = await loadTraceFromFile( args.file as string, @@ -511,6 +539,8 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('strip-query', { type: 'boolean', describe: 'Remove query strings from request and initiator URLs in the output', @@ -562,11 +592,14 @@ export async function runCli(argv: string[]): Promise { 'interactions ', 'User interaction latencies and target DOM elements', (y) => - y.positional('file', { - describe: 'Path to trace file (.json or .json.gz)', - type: 'string', - demandOption: true, - }), + y + .positional('file', { + describe: 'Path to trace file (.json or .json.gz)', + type: 'string', + demandOption: true, + }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION), async (args) => { const loaded = await loadTraceFromFile( args.file as string, @@ -597,6 +630,8 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('events', { type: 'boolean', default: false, @@ -635,6 +670,8 @@ export async function runCli(argv: string[]): Promise { type: 'string', demandOption: true, }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION) .option('name', { alias: ['event'], type: 'string', @@ -696,11 +733,14 @@ export async function runCli(argv: string[]): Promise { ['navigations ', 'navs '], 'List all navigations in the trace and their InsightSet mappings', (y) => - y.positional('file', { - describe: 'Path to trace file (.json or .json.gz)', - type: 'string', - demandOption: true, - }), + y + .positional('file', { + describe: 'Path to trace file (.json or .json.gz)', + type: 'string', + demandOption: true, + }) + .option('time-range', TIME_RANGE_OPTION) + .option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION), async (args) => { const loaded = await loadTraceFromFile( args.file as string, diff --git a/src/engine/extractors/profile.ts b/src/engine/extractors/profile.ts index 4a1ab65..8235220 100644 --- a/src/engine/extractors/profile.ts +++ b/src/engine/extractors/profile.ts @@ -18,6 +18,9 @@ import { getRendererThread, MISSING_CPU_SAMPLES, rendererCpuFilter } from '../he import type { LoadedTrace } from '../loader.js'; import type { ProfileResult } from '../types.js'; +export const MIN_BUCKET_MS = 0.01; +export const MAX_BUCKETS = 1000; + export interface ExtractProfileOptions { threadId?: string; timeRange?: TimeRange; @@ -40,9 +43,23 @@ export function extractProfile( const endMs = options?.timeRange ? options.timeRange.endMs : round(microToMilli(traceBounds.max)); const totalRangeMs = Math.max(1, endMs - startMs); - const bucketSizeMs = options?.bucketMs ?? Math.max(10, round(totalRangeMs / 20)); + if (options?.bucketMs !== undefined && options.bucketMs < MIN_BUCKET_MS) { + throw new Error( + `Bucket size ${options.bucketMs}ms is below the minimum of ${MIN_BUCKET_MS}ms.`, + ); + } + const bucketSizeMs = round(options?.bucketMs ?? Math.max(10, totalRangeMs / 20)); const topCount = options?.top ?? 3; + const rangeMs = endMs - startMs; + if (bucketSizeMs < rangeMs / MAX_BUCKETS) { + const bucketCount = Math.ceil(rangeMs / bucketSizeMs); + const minBucketMs = Math.ceil((rangeMs / MAX_BUCKETS) * 100) / 100; + throw new Error( + `Bucket size ${bucketSizeMs}ms creates ${bucketCount} buckets over ${round(rangeMs)}ms. The maximum is ${MAX_BUCKETS}. Use a bucket size of at least ${minBucketMs}ms.`, + ); + } + const result: ProfileResult = { threadId: options?.threadId, timeRange: { startMs, endMs }, diff --git a/test/cli.test.ts b/test/cli.test.ts index 142515c..f56be41 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -442,3 +442,80 @@ describe('CLI Dispatcher', () => { ); }); }); + +describe('CLI option validation', () => { + const tracePath = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json'); + const fixturesDir = path.resolve(import.meta.dirname, 'fixtures'); + const cli = ['node', 'trace-engine-cli']; + + test('rejects negative --min-duration on tasks', async () => { + await assert.rejects( + captureCliOutput([...cli, 'tasks', tracePath, '--min-duration', '-5']), + /--min-duration must be a number >= 0\./, + ); + }); + + test('rejects non-numeric --min-duration on tasks', async () => { + await assert.rejects( + captureCliOutput([...cli, 'tasks', tracePath, '--min-duration', 'abc']), + /--min-duration must be a number >= 0\./, + ); + }); + + test('accepts --min-duration 0 on tasks', async () => { + const output = await captureCliOutput([...cli, 'tasks', tracePath, '--min-duration', '0']); + assert.match(output, /^mode: list$/m); + }); + + test('rejects --time-range on diff', async () => { + await assert.rejects( + captureCliOutput([ + ...cli, + 'diff', + tracePath, + '--window-a', + '0,50', + '--window-b', + '50,100', + '--time-range', + '0,10', + ]), + /Unknown arguments: time-range/, + ); + }); + + test('rejects --time-range on threads', async () => { + await assert.rejects( + captureCliOutput([...cli, 'threads', tracePath, '--time-range', '0,10']), + /Unknown arguments: time-range/, + ); + }); + + test('rejects --absolute-timestamps on threads', async () => { + await assert.rejects( + captureCliOutput([...cli, 'threads', tracePath, '--absolute-timestamps']), + /Unknown arguments: absolute-timestamps/, + ); + }); + + test('rejects --time-range on scan', async () => { + await assert.rejects( + captureCliOutput([...cli, 'scan', fixturesDir, '--name', 'RunTask', '--time-range', '0,10']), + /Unknown arguments: time-range/, + ); + }); + + test('rejects --absolute-timestamps on scan', async () => { + await assert.rejects( + captureCliOutput([...cli, 'scan', fixturesDir, '--name', 'RunTask', '--absolute-timestamps']), + /Unknown arguments: absolute-timestamps/, + ); + }); + + test('rejects --bucket that creates more than 1000 buckets on profile', async () => { + await assert.rejects( + captureCliOutput([...cli, 'profile', tracePath, '--bucket', '10us']), + /Bucket size 0\.01ms creates 16000 buckets over 160ms\. The maximum is 1000\./, + ); + }); +}); diff --git a/test/extractors/profile.test.ts b/test/extractors/profile.test.ts index 3f941e5..2557e61 100644 --- a/test/extractors/profile.test.ts +++ b/test/extractors/profile.test.ts @@ -80,4 +80,58 @@ describe('Profile Extractor', () => { assert.ok(functionNames.includes('Paint')); assert.ok(functionNames.includes('RunTask')); }); + + test('rejects bucket sizes below 0.01ms', async () => { + const fixturePath = path.resolve(import.meta.dirname, '../fixtures/basic-trace.json'); + const loaded = await loadTraceFromFile(fixturePath); + + assert.throws( + () => + extractProfile(loaded, { + timeRange: { startMs: 1000, endMs: 1001 }, + bucketMs: 0.004, + }), + /Bucket size 0\.004ms is below the minimum of 0\.01ms\./, + ); + }); + + test('rejects bucket sizes that create more than 1000 buckets', async () => { + const fixturePath = path.resolve(import.meta.dirname, '../fixtures/basic-trace.json'); + const loaded = await loadTraceFromFile(fixturePath); + + assert.throws( + () => + extractProfile(loaded, { + timeRange: { startMs: 1000, endMs: 1300 }, + bucketMs: 0.29, + }), + /Bucket size 0\.29ms creates 1035 buckets over 300ms\. The maximum is 1000\. Use a bucket size of at least 0\.3ms\./, + ); + }); + + test('checks the bucket limit against the rounded bucket size', async () => { + const fixturePath = path.resolve(import.meta.dirname, '../fixtures/basic-trace.json'); + const loaded = await loadTraceFromFile(fixturePath); + + assert.throws( + () => + extractProfile(loaded, { + timeRange: { startMs: 1000, endMs: 1014 }, + bucketMs: 0.014, + }), + /Bucket size 0\.01ms creates 1400 buckets over 14ms\. The maximum is 1000\./, + ); + }); + + test('accepts a bucket size that creates exactly 1000 buckets', async () => { + const fixturePath = path.resolve(import.meta.dirname, '../fixtures/basic-trace.json'); + const loaded = await loadTraceFromFile(fixturePath); + + const result = extractProfile(loaded, { + timeRange: { startMs: 1000, endMs: 1300 }, + bucketMs: 0.3, + }); + + assert.equal(result.buckets.length, 1000); + }); });