Skip to content

perf(tooling): reuse directory entry types in source scans - #20212

Merged
nwparker merged 4 commits into
mainfrom
OrcaWin/codex-perf-09-11-source-walk
Sep 13, 2026
Merged

nwparker merged 4 commits into
mainfrom
OrcaWin/codex-perf-09-11-source-walk

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​144 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​144
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​86 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​81

ELI5

Repository checks were asking the filesystem for each file's type separately. Directory listings already supply that information, so use it and keep the extra lookup only for symbolic links.

What Changed

Use readdirSync(..., { withFileTypes: true }) in the existing scanSourceTree walker. Preserve directory traversal, ignored names, test/extension filtering, lexical paths, and symlink handling. Symbolic links still go through statSync, including its error for broken links.

Why

Several repository-wide safety checks share this walker. Each walk previously called statSync for every nonignored entry, including files it subsequently excluded.

Measured the actual baseline and candidate functions over the current checkout, with eight counterbalanced pairs after warmup (macOS arm64, Node 26.6.0):

Tree Scanned files Before median After median
src 12,789 264.5 ms 236.5 ms
mobile/src 998 18.8 ms 16.2 ms
cloud/apps 100 2.0 ms 1.7 ms

The main tree walk is about 11% faster. This improves development/CI scanning; it is not a claim about application latency. The benchmark compares complete results up front and verifies ordered path/content fingerprints after every measured walk. OS-specific directory-type fallback costs can differ.

Linked Issue

Refs #20206. Performance audit PR 2, independent of PR #20208.

Visual Proof

N/A — no application UI or interactions change.

Testing

  • 85 tests pass across the walker, source parsing, and every direct scanner-dependent test suite found in the checkout.
  • Real filesystem fixtures cover nested files, ignored paths, options, directory links/junctions, and broken links. Operation-count tests fail on the baseline and pass after the change: ordinary directory entries require no explicit stat calls; link traversal retains its stat call.
  • ORCA_BACKGROUND_LAUNCH=1 pnpm tc passes; pnpm tc:node passes after the test type-import cleanup.
  • Changed-code quality gate passes.
  • Locally verified on macOS. Windows/Linux execution remains CI coverage; the directory-link fixtures use junctions on Windows without requiring file-symlink privileges.

Reproduce from the repository root:

git show 20ab99506541:src/shared/source-scan/source-tree-scan.ts | node config/scripts/source-tree-walk-benchmark.mjs

Review

No Git subprocess, remote execution, RPC, agent status, or workspace assumptions change. The walker continues to use Node path utilities and preserve normalized relative paths. Existing symlink traversal is retained rather than silently excluding linked source.

Agent skill upstream boundary

  • Not applicable.

Checklist

  • Small, focused change with measured benefit.
  • Self-reviewed and compatible behavior covered by tests.
  • Targeted tests, full typecheck and changed-file lint pass.
  • Full lint, full test suite and build: CI coverage pending.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 4958907a-1e87-46eb-8dfc-840710c8f7b9

📥 Commits

Reviewing files that changed from the base of the PR and between 7a16059 and 7e7af82.

📒 Files selected for processing (2)
  • src/shared/source-scan/source-tree-scan.ts
  • src/shared/source-scan/source-tree-walk.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/shared/source-scan/source-tree-walk.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The source tree walker now uses Dirent metadata and limits statSync calls to symbolic links and unknown entry types. Tests directly cover the new predicate. A benchmark script compares baseline and current inventories, measures counterbalanced runs, and prints JSON results.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 7e7af

The traversal optimization preserves existing scan behavior, and no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the performance change: reusing directory entry types during source scans.
Description check ✅ Passed The description is complete and focused. It covers the change, rationale, linked issue, testing, visual proof, compatibility considerations, and pending CI checks. The AI Disclosure section is omitted…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 58c1d4d0-3820-41a7-9632-e4b59a685c19

📥 Commits

Reviewing files that changed from the base of the PR and between 20ab995 and ddf272a.

📒 Files selected for processing (3)
  • config/scripts/source-tree-walk-benchmark.mjs
  • src/shared/source-scan/source-tree-scan.ts
  • src/shared/source-scan/source-tree-walk.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Directory entry types reused in the shared walker — scanSourceTree now iterates readdirSync(..., { withFileTypes: true }) and takes the type from the Dirent, keeping statSync only for symbolic links (including the broken-link ENOENT). Filters, extension/test exclusions, relative-path normalization, and link traversal are unchanged. src/shared/source-scan/source-tree-scan.ts:49
  • Traversal operation-count tests — real-filesystem fixtures assert ordinary entries incur no statSync, exclusions/options are preserved, directory links still stat exactly once, and broken links still throw. src/shared/source-scan/source-tree-walk.test.ts
  • Benchmark harness — counterbalanced before/after walker benchmark that compares full results and re-verifies an ordered path/content fingerprint on every sampled walk. config/scripts/source-tree-walk-benchmark.mjs

I verified the behavior-preservation claim at the Node/libuv boundary rather than by inspection alone: Windows junctions are classified UV_DIRENT_LINK (so isSymbolicLink() is true and the ternary still calls statSync), regular directories are UV_DIRENT_DIR, and readdirSync({ withFileTypes: true }) resolves UV_DIRENT_UNKNOWN through an internal lstat (DirentFromStats), so the all-is*()-false state is unreachable through the public API. The new operation-count tests fail against the baseline walker, confirming they pin real behavior. Locally the new suite (5 tests) and the direct consumer config/scripts/win32-test-lane-registration.test.mjs (31 tests) pass, and oxlint is clean on the three changed files.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin

OrcaWin commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator Author

Checked the unknown-Dirent concern against the supported Node 24 implementation. readdirSync({ withFileTypes: true }) resolves UV_DIRENT_UNKNOWN internally using lstatSync, then returns DirentFromStats: Node v24.0.0, internal/fs/utils.js lines 309–312.

An unknown directory from the filesystem therefore does not reach this walker with all type predicates false. A manually constructed/mock unknown Dirent would bypass that public-API behavior. The explicit statSync remains necessary for symlinks/junctions because the walker follows their targets. Pullfrog independently checked the same Node/libuv boundary. No additional fallback added; all CI checks are green.

…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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • DT_UNKNOWN entries are statted instead of being silently dropped — scanSourceTree now treats a Dirent whose predicates are all false as needing statSync, so a real directory the OS did not type is still walked. Symlinks keep their stat-follow; ordinary files/directories still skip it, so the perf win is preserved. src/shared/source-scan/source-tree-scan.ts:58
  • Regression test for the untyped-entry path — a mocked all-false Dirent for a nested directory asserts the subtree is visited and exactly that entry is statted. src/shared/source-scan/source-tree-walk.test.ts:113
  • Filesystem-order-independent inventory assertions — the nested-file and test/extension expectations switched to arrayContaining / .sort(), since tmpfs readdir order differs from APFS/ext4. This keeps the same coverage (length + exact element set) without pinning an incidental order. src/shared/source-scan/source-tree-walk.test.ts:53

This addresses the DT_UNKNOWN concern CodeRabbit raised on the first revision. Verified locally on Linux/Node 24.19: the suite passes (6 tests), oxlint is clean on the three changed files, and the new test fails against the pre-fix walker (which dropped the subtree), so it genuinely pins the fix. The mocked readdirSync reset restores the real implementation, so the remaining cases still traverse the real filesystem.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

The fabricated-Dirent readdir mock could not satisfy both gates at once:
vi.mocked(readdirSync) resolves to Node's Dirent<NonSharedBuffer> 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'.
@nwparker

Copy link
Copy Markdown
Contributor

Unblocked. The blocker was never the production fix — it was that the regression test could not satisfy two CI gates at once.

The test fabricated a Dirent whose predicates are all false (the DT_UNKNOWN shape) by stubbing readdirSync. But vi.mocked(readdirSync) resolves to Node's Dirent<NonSharedBuffer> overload, so the stub needed a type assertion — and #19462's casting gate rejects new assertions on changed lines. Removing the cast then failed tsc with TS2345, and a disable directive got reported as unused by the base oxlint pass. Circular.

Fixed by extracting the decision into directoryEntryNeedsStat(entry) and testing it directly with a structural probe object. No mock, no cast, no top-level await.

  • src/shared/source-scan/: 24/24 pass; all 10 suites importing source-tree-scan: 65/65 pass
  • tc:cli and tc:node clean (the earlier TS1309 top-level-await failure is gone)
  • changed-code quality gate: 0 findings across code-quality, casting, type-aware and React Doctor
  • Mutation-checked: deleting the (!isFile() && !isDirectory()) fallback fails stats an entry whose type readdir could not report, so the DT_UNKNOWN case is genuinely pinned

The production behaviour is unchanged from the previous push — ordinary files and directories still take the no-stat fast path, so the PR's win is intact; only links and DT_UNKNOWN entries pay a statSync.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Stat predicate extracted into directoryEntryNeedsStat — the inline needsStat expression moved to an exported helper with a structural DirentTypeProbe parameter; the scanSourceTree call site is unchanged, so there is no behavioral change. src/shared/source-scan/source-tree-scan.ts:44
  • DT_UNKNOWN coverage moved to unit tests — the mocked-readdirSync integration test was replaced with three focused unit tests asserting false for typed files/dirs, true for links, and true for the all-predicates-false (DT_UNKNOWN) case. The predicate that the fix hinges on is still pinned. src/shared/source-scan/source-tree-walk.test.ts:123
  • Dead import removed — the now-unused actualFs actual-module handle is gone; Fs is still used by the importOriginal type argument.

Verified locally: the suite passes (8 tests) and oxlint is clean on the three changed files.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 6c1d95b into main Sep 13, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants