From ddf272ade92fc82e372733b1374fb4c15b772913 Mon Sep 17 00:00:00 2001 From: m4air Date: Fri, 11 Sep 2026 21:40:23 -0700 Subject: [PATCH 1/3] perf(tooling): reuse directory entry types in source scans --- config/scripts/source-tree-walk-benchmark.mjs | 63 +++++++++++ src/shared/source-scan/source-tree-scan.ts | 12 ++- .../source-scan/source-tree-walk.test.ts | 101 ++++++++++++++++++ 3 files changed, 171 insertions(+), 5 deletions(-) create mode 100644 config/scripts/source-tree-walk-benchmark.mjs create mode 100644 src/shared/source-scan/source-tree-walk.test.ts diff --git a/config/scripts/source-tree-walk-benchmark.mjs b/config/scripts/source-tree-walk-benchmark.mjs new file mode 100644 index 000000000000..462f9fb8cce4 --- /dev/null +++ b/config/scripts/source-tree-walk-benchmark.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { stripTypeScriptTypes } from 'node:module' +import { resolve } from 'node:path' +import { performance } from 'node:perf_hooks' +import { buildCounterbalancedSchedule } from './counterbalanced-benchmark-schedule.mjs' +import { summarizeBenchmarkSamples } from './benchmark-sample-summary.mjs' + +// git show :src/shared/source-scan/source-tree-scan.ts | node config/scripts/source-tree-walk-benchmark.mjs +async function load(source) { + const code = stripTypeScriptTypes(source) + return (await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`)) + .scanSourceTree +} +const baseline = readFileSync(0, 'utf8') +assert.ok(baseline.includes('function scanSourceTree'), 'Pipe the baseline source into stdin') +const implementations = { + before: await load(baseline), + after: await load(readFileSync('src/shared/source-scan/source-tree-scan.ts', 'utf8')) +} +function fingerprint(files) { + const hash = createHash('sha256') + for (const file of files) { + for (const value of [file.path, file.relativePath, file.source]) { + hash + .update(String(Buffer.byteLength(value))) + .update(':') + .update(value) + } + } + return hash.digest('hex') +} +const results = [] +for (const directory of ['src', 'mobile/src', 'cloud/apps']) { + const root = resolve(directory) + const original = implementations.before(root) + const expected = fingerprint(original) + assert.deepEqual(implementations.after(root), original) + const samples = { before: [], after: [] } + for (let warmup = 0; warmup < 2; warmup += 1) { + for (const run of Object.values(implementations)) { + run(root) + } + } + for (const pair of buildCounterbalancedSchedule(8, 'before', 'after')) { + for (const arm of pair) { + const started = performance.now() + const files = implementations[arm](root) + samples[arm].push(performance.now() - started) + assert.equal(fingerprint(files), expected, `${directory} ${arm} inventory changed`) + } + } + results.push({ + directory, + files: original.length, + sourceBytes: original.reduce((bytes, file) => bytes + Buffer.byteLength(file.source), 0), + fingerprint: expected, + before: summarizeBenchmarkSamples(samples.before), + after: summarizeBenchmarkSamples(samples.after) + }) +} +console.log(JSON.stringify({ node: process.version, platform: process.platform, results }, null, 2)) diff --git a/src/shared/source-scan/source-tree-scan.ts b/src/shared/source-scan/source-tree-scan.ts index 937a2fc39dbd..2678c1851d0a 100644 --- a/src/shared/source-scan/source-tree-scan.ts +++ b/src/shared/source-scan/source-tree-scan.ts @@ -46,16 +46,18 @@ export function scanSourceTree( const extensions = options.extensions ?? /\.tsx?$/ const found: ScannedFile[] = [] const visit = (directory: string): void => { - for (const entry of readdirSync(directory)) { - if (IGNORED_DIRECTORIES.has(entry) || entry.startsWith('.') || entry === '__fixtures__') { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const name = entry.name + if (IGNORED_DIRECTORIES.has(name) || name.startsWith('.') || name === '__fixtures__') { continue } - const path = join(directory, entry) - if (statSync(path).isDirectory()) { + const path = join(directory, name) + // Preserve link traversal; ordinary entries already carry their type from readdir. + if (entry.isSymbolicLink() ? statSync(path).isDirectory() : entry.isDirectory()) { visit(path) continue } - if (!extensions.test(entry)) { + if (!extensions.test(name)) { continue } const relativePath = relative(root, path).replace(/\\/g, '/') diff --git a/src/shared/source-scan/source-tree-walk.test.ts b/src/shared/source-scan/source-tree-walk.test.ts new file mode 100644 index 000000000000..65e68f149eb8 --- /dev/null +++ b/src/shared/source-scan/source-tree-walk.test.ts @@ -0,0 +1,101 @@ +import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs' +import type * as Fs from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { scanSourceTree } from './source-tree-scan' + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, statSync: vi.fn(actual.statSync) } +}) + +let root: string + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-source-tree-walk-')) + vi.mocked(statSync).mockClear() +}) + +afterEach(() => { + rmSync(root, { recursive: true, force: true }) +}) + +function file(relativePath: string, contents = relativePath): void { + writeFileSync(join(root, relativePath), contents) +} + +describe('scanSourceTree filesystem traversal', () => { + it('reads nested source files without stat calls for ordinary directory entries', () => { + mkdirSync(join(root, 'nested')) + file('first.ts') + file(join('nested', 'second.tsx'), 'nested/second.tsx') + file('ignored.txt') + file('first.test.ts') + + const files = scanSourceTree(root) + + expect(files).toEqual([ + { path: join(root, 'first.ts'), relativePath: 'first.ts', source: 'first.ts' }, + { + path: join(root, 'nested', 'second.tsx'), + relativePath: 'nested/second.tsx', + source: 'nested/second.tsx' + } + ]) + expect(statSync).not.toHaveBeenCalled() + }) + + it('keeps ignored directories, dotfiles, and test exclusions out of the inventory', () => { + for (const directory of ['node_modules', 'dist', 'out', 'build', '.cache', '__fixtures__']) { + mkdirSync(join(root, directory)) + file(join(directory, 'hidden.ts')) + } + file('.hidden.ts') + file('sample.test.ts') + file('sample.spec.tsx') + file('test-harness.ts') + file('production.ts') + + expect(scanSourceTree(root).map((entry) => entry.relativePath)).toEqual(['production.ts']) + }) + + it('keeps extension and test-inclusion options', () => { + file('module.mjs') + file('module.ts') + file('module.test.ts') + + expect(scanSourceTree(root, { includeTests: true }).map((entry) => entry.relativePath)).toEqual( + ['module.test.ts', 'module.ts'] + ) + expect( + scanSourceTree(root, { extensions: /\.mjs$/ }).map((entry) => entry.relativePath) + ).toEqual(['module.mjs']) + }) + + it('follows directory links with stat while preserving the lexical path', () => { + const target = join(root, '.target') + mkdirSync(target) + writeFileSync(join(target, 'linked.ts'), 'linked source') + symlinkSync(target, join(root, 'alias'), 'junction') + + expect(scanSourceTree(root)).toEqual([ + { + path: join(root, 'alias', 'linked.ts'), + relativePath: 'alias/linked.ts', + source: 'linked source' + } + ]) + expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'alias')) + }) + + it('still reports a broken link instead of silently dropping it', () => { + const target = join(root, '.target') + mkdirSync(target) + symlinkSync(target, join(root, 'alias'), 'junction') + rmSync(target, { recursive: true }) + + expect(() => scanSourceTree(root)).toThrow(/ENOENT/) + expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'alias')) + }) +}) From 7a16059adc22d88c84471cb6a9255af3bd8e785b Mon Sep 17 00:00:00 2001 From: Neil Date: Sat, 12 Sep 2026 20:43:51 -0700 Subject: [PATCH 2/3] fix(source-scan): stat DT_UNKNOWN dirents so untyped directories are still walked `readdirSync(..., { withFileTypes: true })` can hand back a Dirent whose type the filesystem did not report. For that entry every predicate is false, so the readdir-type fast path treated a real directory as a file and silently dropped its subtree from every ratchet guard. Fall back to `statSync` whenever the entry is neither conclusively a file nor a directory, keeping the no-stat fast path for ordinary entries. Also make the two readdir-order assertions in the walk test order-independent; `scanSourceTree` returns raw readdir order, which differs on tmpfs. --- src/shared/source-scan/source-tree-scan.ts | 7 +- .../source-scan/source-tree-walk.test.ts | 72 +++++++++++++++---- 2 files changed, 64 insertions(+), 15 deletions(-) diff --git a/src/shared/source-scan/source-tree-scan.ts b/src/shared/source-scan/source-tree-scan.ts index 2678c1851d0a..64ef28be77da 100644 --- a/src/shared/source-scan/source-tree-scan.ts +++ b/src/shared/source-scan/source-tree-scan.ts @@ -52,8 +52,11 @@ export function scanSourceTree( continue } const path = join(directory, name) - // Preserve link traversal; ordinary entries already carry their type from readdir. - if (entry.isSymbolicLink() ? statSync(path).isDirectory() : entry.isDirectory()) { + // Ordinary entries carry their type from readdir. Links need a stat to follow + // them, and so does DT_UNKNOWN (every predicate false), or a real directory + // would be silently dropped from the scan. + const needsStat = entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory()) + if (needsStat ? statSync(path).isDirectory() : entry.isDirectory()) { visit(path) continue } diff --git a/src/shared/source-scan/source-tree-walk.test.ts b/src/shared/source-scan/source-tree-walk.test.ts index 65e68f149eb8..6807ffa847d8 100644 --- a/src/shared/source-scan/source-tree-walk.test.ts +++ b/src/shared/source-scan/source-tree-walk.test.ts @@ -1,4 +1,12 @@ -import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs' +import { + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + statSync, + symlinkSync, + writeFileSync +} from 'node:fs' import type * as Fs from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -7,13 +15,20 @@ import { scanSourceTree } from './source-tree-scan' vi.mock('node:fs', async (importOriginal) => { const actual = await importOriginal() - return { ...actual, statSync: vi.fn(actual.statSync) } + return { + ...actual, + readdirSync: vi.fn(actual.readdirSync), + statSync: vi.fn(actual.statSync) + } }) +const actualFs = await vi.importActual('node:fs') + let root: string beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'orca-source-tree-walk-')) + vi.mocked(readdirSync).mockReset() vi.mocked(statSync).mockClear() }) @@ -35,14 +50,18 @@ describe('scanSourceTree filesystem traversal', () => { const files = scanSourceTree(root) - expect(files).toEqual([ - { path: join(root, 'first.ts'), relativePath: 'first.ts', source: 'first.ts' }, - { - path: join(root, 'nested', 'second.tsx'), - relativePath: 'nested/second.tsx', - source: 'nested/second.tsx' - } - ]) + // readdir order is filesystem-dependent (tmpfs differs from APFS/ext4). + expect(files).toHaveLength(2) + expect(files).toEqual( + expect.arrayContaining([ + { path: join(root, 'first.ts'), relativePath: 'first.ts', source: 'first.ts' }, + { + path: join(root, 'nested', 'second.tsx'), + relativePath: 'nested/second.tsx', + source: 'nested/second.tsx' + } + ]) + ) expect(statSync).not.toHaveBeenCalled() }) @@ -65,9 +84,11 @@ describe('scanSourceTree filesystem traversal', () => { file('module.ts') file('module.test.ts') - expect(scanSourceTree(root, { includeTests: true }).map((entry) => entry.relativePath)).toEqual( - ['module.test.ts', 'module.ts'] - ) + expect( + scanSourceTree(root, { includeTests: true }) + .map((entry) => entry.relativePath) + .sort() + ).toEqual(['module.test.ts', 'module.ts']) expect( scanSourceTree(root, { extensions: /\.mjs$/ }).map((entry) => entry.relativePath) ).toEqual(['module.mjs']) @@ -89,6 +110,31 @@ describe('scanSourceTree filesystem traversal', () => { expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'alias')) }) + it('stats an entry whose type readdir could not report instead of dropping its subtree', () => { + mkdirSync(join(root, 'nested')) + file(join('nested', 'inner.ts'), 'inner source') + // Filesystems without d_type yield a Dirent where every predicate is false. + vi.mocked(readdirSync).mockImplementationOnce(((directory: Fs.PathLike) => + actualFs.readdirSync(directory, { withFileTypes: true }).map((entry) => + entry.name === 'nested' + ? Object.assign(Object.create(Object.getPrototypeOf(entry)), entry, { + isFile: () => false, + isDirectory: () => false, + isSymbolicLink: () => false + }) + : entry + )) as typeof readdirSync) + + expect(scanSourceTree(root)).toEqual([ + { + path: join(root, 'nested', 'inner.ts'), + relativePath: 'nested/inner.ts', + source: 'inner source' + } + ]) + expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'nested')) + }) + it('still reports a broken link instead of silently dropping it', () => { const target = join(root, '.target') mkdirSync(target) From 7e7af82af42f73cabdf598a48ffb56b15edbfdf2 Mon Sep 17 00:00:00 2001 From: Neil Date: Sat, 12 Sep 2026 22:29:36 -0700 Subject: [PATCH 3/3] test(source-scan): unit-test the stat fallback via an extracted helper The fabricated-Dirent readdir mock could not satisfy both gates at once: vi.mocked(readdirSync) resolves to Node's Dirent overload, so the mock needed a type assertion, and #19462's casting gate rejects new ones on changed lines. Removing the cast then failed tsc. Extract directoryEntryNeedsStat and test it directly with a structural probe. No mock, no cast, no top-level await, and the DT_UNKNOWN case is pinned: removing the fallback fails 'stats an entry whose type readdir could not report'. --- src/shared/source-scan/source-tree-scan.ts | 23 +++++++-- .../source-scan/source-tree-walk.test.ts | 51 +++++++++---------- 2 files changed, 42 insertions(+), 32 deletions(-) diff --git a/src/shared/source-scan/source-tree-scan.ts b/src/shared/source-scan/source-tree-scan.ts index 64ef28be77da..dcd6050799bf 100644 --- a/src/shared/source-scan/source-tree-scan.ts +++ b/src/shared/source-scan/source-tree-scan.ts @@ -29,6 +29,22 @@ export function isTestFile(relativePath: string): boolean { export type ScannedFile = { path: string; relativePath: string; source: string } +/** The three readdir type predicates the walk consults. */ +type DirentTypeProbe = { + isSymbolicLink(): boolean + isFile(): boolean + isDirectory(): boolean +} + +/** + * Links need a stat to follow them, and so does DT_UNKNOWN (every predicate + * false) -- filesystems that do not report d_type would otherwise have a real + * directory silently dropped from the scan. + */ +export function directoryEntryNeedsStat(entry: DirentTypeProbe): boolean { + return entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory()) +} + /** * Every `.ts`/`.tsx` file under `root`, with its text. * @@ -52,11 +68,8 @@ export function scanSourceTree( continue } const path = join(directory, name) - // Ordinary entries carry their type from readdir. Links need a stat to follow - // them, and so does DT_UNKNOWN (every predicate false), or a real directory - // would be silently dropped from the scan. - const needsStat = entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory()) - if (needsStat ? statSync(path).isDirectory() : entry.isDirectory()) { + // Ordinary entries carry their type from readdir. + if (directoryEntryNeedsStat(entry) ? statSync(path).isDirectory() : entry.isDirectory()) { visit(path) continue } diff --git a/src/shared/source-scan/source-tree-walk.test.ts b/src/shared/source-scan/source-tree-walk.test.ts index 6807ffa847d8..afc7c8dba88c 100644 --- a/src/shared/source-scan/source-tree-walk.test.ts +++ b/src/shared/source-scan/source-tree-walk.test.ts @@ -11,7 +11,7 @@ import type * as Fs from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { scanSourceTree } from './source-tree-scan' +import { directoryEntryNeedsStat, scanSourceTree } from './source-tree-scan' vi.mock('node:fs', async (importOriginal) => { const actual = await importOriginal() @@ -22,8 +22,6 @@ vi.mock('node:fs', async (importOriginal) => { } }) -const actualFs = await vi.importActual('node:fs') - let root: string beforeEach(() => { @@ -110,30 +108,6 @@ describe('scanSourceTree filesystem traversal', () => { expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'alias')) }) - it('stats an entry whose type readdir could not report instead of dropping its subtree', () => { - mkdirSync(join(root, 'nested')) - file(join('nested', 'inner.ts'), 'inner source') - // Filesystems without d_type yield a Dirent where every predicate is false. - vi.mocked(readdirSync).mockImplementationOnce(((directory: Fs.PathLike) => - actualFs.readdirSync(directory, { withFileTypes: true }).map((entry) => - entry.name === 'nested' - ? Object.assign(Object.create(Object.getPrototypeOf(entry)), entry, { - isFile: () => false, - isDirectory: () => false, - isSymbolicLink: () => false - }) - : entry - )) as typeof readdirSync) - - expect(scanSourceTree(root)).toEqual([ - { - path: join(root, 'nested', 'inner.ts'), - relativePath: 'nested/inner.ts', - source: 'inner source' - } - ]) - expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'nested')) - }) it('still reports a broken link instead of silently dropping it', () => { const target = join(root, '.target') @@ -145,3 +119,26 @@ describe('scanSourceTree filesystem traversal', () => { expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'alias')) }) }) + +describe('directoryEntryNeedsStat', () => { + const probe = (kind: 'file' | 'dir' | 'link' | 'unknown') => ({ + isFile: () => kind === 'file', + isDirectory: () => kind === 'dir', + isSymbolicLink: () => kind === 'link' + }) + + it('skips the stat for entries readdir already typed', () => { + expect(directoryEntryNeedsStat(probe('file'))).toBe(false) + expect(directoryEntryNeedsStat(probe('dir'))).toBe(false) + }) + + it('stats links so they are followed', () => { + expect(directoryEntryNeedsStat(probe('link'))).toBe(true) + }) + + // Filesystems without d_type report DT_UNKNOWN: every predicate is false, and + // without the stat a real directory's whole subtree is silently dropped. + it('stats an entry whose type readdir could not report', () => { + expect(directoryEntryNeedsStat(probe('unknown'))).toBe(true) + }) +})