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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ trace-engine-cli/
- The `scan` command does not invoke DevTools Trace Engine models or calculate relative trace bounds.
- Use substring pre-filtering on decompressed trace buffers before `JSON.parse` to avoid parsing non-matching files.
- `firstEventTsMs` in scan results reports raw absolute trace timestamps normalized to milliseconds, not offsets relative to trace start.
- Report files that cannot be read, decompressed or parsed in `skippedFiles`. Never drop them silently.

---

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ trace-engine-cli scan "fixtures/**/*.json.gz" --grep "LayerTreeHostImpl"
# Filter by category and phase across multiple files
trace-engine-cli scan fixtures/traces/ --cat devtools.timeline --phase X
```
Check `skippedFiles` in the result. Scan did not search the files in that list, so a match can be missing from them.

---

Expand Down Expand Up @@ -545,6 +546,8 @@ trace-engine-cli scan "traces/*.json.gz" --cat devtools.timeline --top 10
trace-engine-cli scan fixtures/ --name TracingStartedInBrowser --fields args.data.frames
```

Files that scan cannot read, decompress or parse are listed in `skippedFiles` with the reason. Scan continues with the other files. A file with invalid JSON is only reported when its text contains the query, because a file without the query text cannot match.

---

### 14. `threads`
Expand Down
21 changes: 17 additions & 4 deletions src/engine/extractors/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import path from 'node:path';
import { microToMilli } from '../../utils/units.js';
import { getPropertyByPath } from '../helpers.js';
import { decompressTraceBuffer, parseTraceJson } from '../loader.js';
import type { RawTraceEvent, ScanMatchedFile, ScanResult } from '../types.js';
import type { RawTraceEvent, ScanMatchedFile, ScanResult, ScanSkippedFile } from '../types.js';

/**
* Options for scanning multiple trace files or directories.
Expand Down Expand Up @@ -98,6 +98,10 @@ export function resolveScanTargets(targets: string[]): string[] {
return sorted;
}

function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}

/**
* Scans multiple trace files or directories for events matching query criteria.
*
Expand All @@ -123,20 +127,27 @@ export function scanTraces(options: ScanOptions): ScanResult {
fields && fields.length > 0 ? fields.map((f) => f.split('.').pop() ?? f) : null;

const matchedFiles: ScanMatchedFile[] = [];
const skippedFiles: ScanSkippedFile[] = [];
let totalEventsMatched = 0;

for (const filePath of files) {
const skip = (reason: string) => {
skippedFiles.push({ file: path.relative(process.cwd(), filePath), reason });
};

let rawBuffer: Buffer;
try {
rawBuffer = fs.readFileSync(filePath);
} catch {
} catch (err) {
skip(`Could not read file: ${(err as NodeJS.ErrnoException).code ?? errorMessage(err)}`);
continue;
}

let jsonContent: string;
try {
jsonContent = decompressTraceBuffer(rawBuffer, filePath);
} catch {
} catch (err) {
skip(`Could not decompress file: ${errorMessage(err)}`);
continue;
}

Expand Down Expand Up @@ -166,7 +177,8 @@ export function scanTraces(options: ScanOptions): ScanResult {
let rawEvents: unknown[];
try {
rawEvents = parseTraceJson(jsonContent);
} catch {
} catch (err) {
skip(errorMessage(err));
continue;
}

Expand Down Expand Up @@ -267,5 +279,6 @@ export function scanTraces(options: ScanOptions): ScanResult {
totalFilesMatched: matchedFiles.length,
totalEventsMatched,
matchedFiles: matchedFiles.slice(0, limit),
skippedFiles,
};
}
12 changes: 12 additions & 0 deletions src/engine/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,16 @@ export interface ScanMatchedFile {
firstEventTsMs?: number;
}

/**
* A trace file that scan could not read, decompress or parse.
*/
export interface ScanSkippedFile {
/** Relative or normalized path to the trace file. */
file: string;
/** Why the file could not be scanned. */
reason: string;
}

/**
* Result of scanning multiple trace files or directories.
*/
Expand All @@ -501,4 +511,6 @@ export interface ScanResult {
totalEventsMatched: number;
/** Ordered list of matched files, sorted by match count descending. */
matchedFiles: ScanMatchedFile[];
/** Files that could not be read, decompressed or parsed, so they were not searched. */
skippedFiles: ScanSkippedFile[];
}
39 changes: 27 additions & 12 deletions src/formatters/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,24 +567,39 @@ export function formatScanMarkdown(result: ScanResult): string {
lines.push(`- **Files Matched**: ${result.totalFilesMatched}`);
}
lines.push(`- **Total Events Matched**: ${result.totalEventsMatched}`);
if (result.skippedFiles.length > 0) {
lines.push(`- **Files Skipped**: ${result.skippedFiles.length}`);
}
lines.push('');

if (result.matchedFiles.length === 0) {
lines.push('No matching trace files found.');
return lines.join('\n');
} else {
lines.push('| File | Matches | Categories | First Event | First Event Timestamp |');
lines.push('|---|---|---|---|---|');
for (const item of result.matchedFiles) {
const safeFile = item.file.replace(/\|/g, '\\|');
const cats =
item.categories.length > 0 ? item.categories.join(', ').replace(/\|/g, '\\|') : '-';
const firstEvent = item.firstEventName
? `\`${item.firstEventName.replace(/\|/g, '\\|')}\``
: '-';
const firstTs = item.firstEventTsMs !== undefined ? formatMs(item.firstEventTsMs) : '-';
lines.push(`| \`${safeFile}\` | ${item.matchCount} | ${cats} | ${firstEvent} | ${firstTs} |`);
}
}

lines.push('| File | Matches | Categories | First Event | First Event Timestamp |');
lines.push('|---|---|---|---|---|');
for (const item of result.matchedFiles) {
const safeFile = item.file.replace(/\|/g, '\\|');
const cats =
item.categories.length > 0 ? item.categories.join(', ').replace(/\|/g, '\\|') : '-';
const firstEvent = item.firstEventName
? `\`${item.firstEventName.replace(/\|/g, '\\|')}\``
: '-';
const firstTs = item.firstEventTsMs !== undefined ? formatMs(item.firstEventTsMs) : '-';
lines.push(`| \`${safeFile}\` | ${item.matchCount} | ${cats} | ${firstEvent} | ${firstTs} |`);
if (result.skippedFiles.length > 0) {
lines.push('');
lines.push('## Skipped Files');
lines.push('');
lines.push('| File | Reason |');
lines.push('|---|---|');
for (const item of result.skippedFiles) {
const safeFile = item.file.replace(/\|/g, '\\|');
const safeReason = item.reason.replace(/\|/g, '\\|');
lines.push(`| \`${safeFile}\` | ${safeReason} |`);
}
}

return lines.join('\n');
Expand Down
81 changes: 81 additions & 0 deletions test/extractors/scan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,85 @@ describe('Scan Extractor', () => {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});

test('reports no skipped files when every file can be read', () => {
const result = scanTraces({
targets: [fixturesDir],
names: ['LayoutShift'],
});

assert.deepEqual(result.skippedFiles, []);
});

test('reports a file that cannot be decompressed and keeps scanning', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trace-scan-test-'));
try {
fs.writeFileSync(path.join(tempDir, 'broken.json.gz'), 'not gzip data');
fs.writeFileSync(
path.join(tempDir, 'valid.json'),
JSON.stringify([{ name: 'RunTask', cat: 'toplevel', ph: 'X', ts: 1000 }]),
);

const result = scanTraces({ targets: [tempDir], names: ['RunTask'] });

assert.equal(result.totalFilesScanned, 2);
assert.equal(result.totalFilesMatched, 1);
assert.ok(result.matchedFiles[0].file.endsWith('valid.json'));
assert.equal(result.skippedFiles.length, 1);
assert.ok(result.skippedFiles[0].file.endsWith('broken.json.gz'));
assert.match(result.skippedFiles[0].reason, /^Could not decompress file: /);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});

test('reports a file with invalid JSON that passes the text pre-filter', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trace-scan-test-'));
try {
fs.writeFileSync(path.join(tempDir, 'truncated.json'), '[{"name":"RunTask","ph":"X"');

const result = scanTraces({ targets: [tempDir], names: ['RunTask'] });

assert.equal(result.totalFilesMatched, 0);
assert.equal(result.skippedFiles.length, 1);
assert.ok(result.skippedFiles[0].file.endsWith('truncated.json'));
assert.match(result.skippedFiles[0].reason, /^Failed to parse trace JSON: /);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});

test('does not report invalid JSON that cannot contain the query text', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trace-scan-test-'));
try {
fs.writeFileSync(path.join(tempDir, 'truncated.json'), '[{"name":"Paint","ph":"X"');

const result = scanTraces({ targets: [tempDir], names: ['RunTask'] });

assert.equal(result.totalFilesMatched, 0);
assert.deepEqual(result.skippedFiles, []);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});

test('reports a file that cannot be read', {
skip: process.getuid?.() === 0 && 'root can read files without read permission',
}, () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trace-scan-test-'));
const unreadable = path.join(tempDir, 'unreadable.json');
try {
fs.writeFileSync(unreadable, '[]');
fs.chmodSync(unreadable, 0o000);

const result = scanTraces({ targets: [tempDir], names: ['RunTask'] });

assert.equal(result.skippedFiles.length, 1);
assert.ok(result.skippedFiles[0].file.endsWith('unreadable.json'));
assert.equal(result.skippedFiles[0].reason, 'Could not read file: EACCES');
} finally {
fs.chmodSync(unreadable, 0o644);
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
});
30 changes: 30 additions & 0 deletions test/formatters/markdown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,7 @@ describe('Markdown Formatter', () => {
totalFilesScanned: 10,
totalFilesMatched: 1,
totalEventsMatched: 3,
skippedFiles: [],
matchedFiles: [
{
file: 'fixtures/shifts-trace.json',
Expand All @@ -480,10 +481,37 @@ describe('Markdown Formatter', () => {
totalFilesMatched: 0,
totalEventsMatched: 0,
matchedFiles: [],
skippedFiles: [],
};
const output = formatScanMarkdown(scan);
assert.ok(output.includes('# Trace Scan Results'));
assert.ok(output.includes('No matching trace files found.'));
assert.ok(!output.includes('Files Skipped'));
});

test('formatScanMarkdown lists skipped files with their reason', () => {
const scan: ScanResult = {
query: { names: ['RunTask'] },
totalFilesScanned: 3,
totalFilesMatched: 0,
totalEventsMatched: 0,
matchedFiles: [],
skippedFiles: [
{
file: 'traces/broken|1.json.gz',
reason: 'Could not decompress file: incorrect header check',
},
],
};
const output = formatScanMarkdown(scan);
assert.ok(output.includes('- **Files Skipped**: 1'));
assert.ok(output.includes('## Skipped Files'));
assert.ok(
output.includes(
'| `traces/broken\\|1.json.gz` | Could not decompress file: incorrect header check |',
),
);
assert.ok(output.includes('No matching trace files found.'));
});

test('formatScanMarkdown indicates truncation and escapes pipe characters', () => {
Expand All @@ -492,6 +520,7 @@ describe('Markdown Formatter', () => {
totalFilesScanned: 20,
totalFilesMatched: 10,
totalEventsMatched: 25,
skippedFiles: [],
matchedFiles: [
{
file: 'path/to|file.json',
Expand Down Expand Up @@ -546,6 +575,7 @@ describe('Markdown Formatter', () => {
totalFilesMatched: 0,
totalEventsMatched: 0,
matchedFiles: [],
skippedFiles: [],
},
'scan',
);
Expand Down