From 07066c984aeada1040e9272edb465d374c3bb9ea Mon Sep 17 00:00:00 2001 From: Joan Leon Date: Tue, 24 Nov 2026 19:30:23 +0100 Subject: [PATCH] Report trace files that scan cannot read, decompress or parse `scan` lists these files in `skippedFiles` with the reason and continues with the other files. Before, it dropped them silently, so a broken trace looked the same as a trace without matches. A file with invalid JSON is only reported when its text contains the query, because the text pre-filter runs before parsing and a file without the query text cannot match. --- AGENTS.md | 1 + README.md | 3 ++ src/engine/extractors/scan.ts | 21 +++++++-- src/engine/types.ts | 12 +++++ src/formatters/markdown.ts | 39 ++++++++++----- test/extractors/scan.test.ts | 81 ++++++++++++++++++++++++++++++++ test/formatters/markdown.test.ts | 30 ++++++++++++ 7 files changed, 171 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b5bb523..c6fb915 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. --- diff --git a/README.md b/README.md index 4802c86..c558498 100644 --- a/README.md +++ b/README.md @@ -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. --- @@ -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` diff --git a/src/engine/extractors/scan.ts b/src/engine/extractors/scan.ts index fe357a5..5dd5c41 100644 --- a/src/engine/extractors/scan.ts +++ b/src/engine/extractors/scan.ts @@ -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. @@ -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. * @@ -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; } @@ -166,7 +177,8 @@ export function scanTraces(options: ScanOptions): ScanResult { let rawEvents: unknown[]; try { rawEvents = parseTraceJson(jsonContent); - } catch { + } catch (err) { + skip(errorMessage(err)); continue; } @@ -267,5 +279,6 @@ export function scanTraces(options: ScanOptions): ScanResult { totalFilesMatched: matchedFiles.length, totalEventsMatched, matchedFiles: matchedFiles.slice(0, limit), + skippedFiles, }; } diff --git a/src/engine/types.ts b/src/engine/types.ts index 5d36706..0621ea4 100644 --- a/src/engine/types.ts +++ b/src/engine/types.ts @@ -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. */ @@ -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[]; } diff --git a/src/formatters/markdown.ts b/src/formatters/markdown.ts index 3c73edd..76e7000 100644 --- a/src/formatters/markdown.ts +++ b/src/formatters/markdown.ts @@ -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'); diff --git a/test/extractors/scan.test.ts b/test/extractors/scan.test.ts index d9fbbfe..774823b 100644 --- a/test/extractors/scan.test.ts +++ b/test/extractors/scan.test.ts @@ -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 }); + } + }); }); diff --git a/test/formatters/markdown.test.ts b/test/formatters/markdown.test.ts index 2697c16..72c2be8 100644 --- a/test/formatters/markdown.test.ts +++ b/test/formatters/markdown.test.ts @@ -455,6 +455,7 @@ describe('Markdown Formatter', () => { totalFilesScanned: 10, totalFilesMatched: 1, totalEventsMatched: 3, + skippedFiles: [], matchedFiles: [ { file: 'fixtures/shifts-trace.json', @@ -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', () => { @@ -492,6 +520,7 @@ describe('Markdown Formatter', () => { totalFilesScanned: 20, totalFilesMatched: 10, totalEventsMatched: 25, + skippedFiles: [], matchedFiles: [ { file: 'path/to|file.json', @@ -546,6 +575,7 @@ describe('Markdown Formatter', () => { totalFilesMatched: 0, totalEventsMatched: 0, matchedFiles: [], + skippedFiles: [], }, 'scan', );