Skip to content

perf: bound wildcard segment work in nested repository scans - #23149

Merged
nwparker merged 2 commits into
mainfrom
nwparker/perf-09-25-nested-glob-work
Sep 27, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/perf-09-25-nested-glob-work

Conversation

@nwparker

@nwparker nwparker commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​193 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​193
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​95 $\color{#cf222e}{\Huge{\mathbf{−}}}$​25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​70

ELI5

A short ignore rule containing many stars can make nested repository discovery spend tens of milliseconds rejecting one directory. The matcher now avoids repeatedly trying the same combinations of stars.

What Changed

Replace the wildcard segment's regular expression with a loop that retries only the latest star. Literal matching, ignore-rule order, negation, directory traversal and provider routing stay unchanged.

Synthetic matching workload, median of 7 runs Before After
One adverse 25-character nonmatch 25.09 ms 0.0045 ms
10,000 ordinary prefix matches 0.85 ms 1.25 ms
10,000 ordinary suffix matches 0.56 ms 1.78 ms
10,000 question-mark matches 0.44 ms 0.96 ms

These timings use the actual exported predicate with injected ignore-file text; parsing is outside the timer. They do not measure a whole scan or application latency.

Why

A latest-star retry loop bounds each segment to O(pattern length × name length) with a fixed number of indices. The existing glob converter elsewhere also uses backtracking and has different semantics. Extending this private matcher keeps the change small without adding a dependency or cache. The outer recursive ** path matcher remains outside this bound.

Separate trade-off PR: ordinary wildcard matches can take longer, as shown above. Native regular expressions are faster for those simple cases. The unchanged literal path showed only small measurement noise. No measured heap or whole-app speed claim.

Linked Issue

Fixes #23147

Visual Proof

N/A

This changes synchronous matching work without a layout or interaction change. No rendered scan timing is claimed.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

83 tests pass across seven project-group suites. The new 14-case suite passes; its original version fails the adverse-work guard (50 names used 1.31 seconds of process CPU against a broad 500 ms ceiling). This is a machine-dependent CPU guard, not a deterministic instruction count. 41,140 small pattern/name comparisons and Unicode, slash, newline and regex-metacharacter probes preserve original semantics. Node typecheck, focused lint, formatting and changed-code quality pass.

Existing suites exercise owned temporary directories, symlinks and read-only Git probes; remote graph providers are mocked. All commands use background-launch mode. No user filesystem scan, external provider, native Electron window, live SSH/WSL or native Windows/Linux execution. Full build and platform application checks remain gaps.

Review

Independent review approved the exact two file hashes. Seventeen independent cases pass on original and candidate, including 30,000 comparisons against a separate dynamic-programming oracle and two in-memory Windows/POSIX scanner fixtures; a candidate-only loop instrumentation case also passes. Independent timings confirm both the adverse gain and ordinary suffix slowdown. Thirty-four focused permanent cases pass independently, with the same original CPU-guard failure.

Merge risk: low to moderate. Matching semantics have broad comparison coverage, but this replaces a core ignore-rule primitive and ordinary wildcard work is slower.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Shared by local and SSH scan adapters; no new process, Git command, filesystem operation, wire field, host selection, status ownership or permission change. Folder workspace imports remain supported. Total scan input size, pending I/O and outer ** recursion remain existing limits; this PR bounds only an individual wildcard segment. Mobile and Git-provider behavior are unaffected.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

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: 39a4ff01-58be-4207-b34b-bd7c7ccf143f

📥 Commits

Reviewing files that changed from the base of the PR and between 135eb7a and f3db53f.

📒 Files selected for processing (2)
  • src/main/project-groups/nested-repo-glob-budget.test.ts
  • src/main/project-groups/nested-repo-scan-rules.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

Nested-repository ignore rules now compile path patterns into glob segments and collapse consecutive ** segments. Wildcard segments use iterative matching, and path matching memoizes visited pattern and candidate pairs when a rule contains multiple ** segments. Tests compare results with a reference matcher and check matcher-step budgets and character handling.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to f3db5

The nested-repository matcher change has no identified issue requiring resolution before merge. The remaining platform and application validation gaps do not establish a defect.

Security Architecture Review

Security architecture risk: 🔵 Low · up to f3db5

The change appears to reduce costly wildcard matching while preserving the checks that control repository scanning. No new security issue was established, but the authority to choose scan roots and the behavior of alternative filesystem adapters remain unconfirmed.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The observed effect is confined to ignore decisions within a selected nested-repository scan. The authority governing the initial scan root and any alternative filesystem adapter is not established by the reviewed source.

Security Findings and Attack Paths

  • inferred — Controlled ignore text or directory names could affect matching work and whether a child reaches marker inspection. The examined base-to-head behavior and differential tests did not establish a newly bypassed ignore gate or newly reachable filesystem sink.

Trust Boundaries and Controls

  • observed — The scanner retains depth, repository-count, timeout, and cancellation checks around traversal; it excludes symlink directory entries before applying ignore rules.

Resilience and Maintainability Implications

  • observed — The new step counter is process-wide and read as a before-and-after difference by tests; the reviewed scanner does not use it to authorize or terminate a scan.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 2 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 and concisely describes the primary performance change: bounding wildcard-segment work in nested repository scans.
Description check ✅ Passed The description is complete and focused. It covers the user impact, implementation, rationale, trade-offs, linked issue, testing, review findings, platform considerations, and known validation gaps.
Linked Issues check ✅ Passed Issue #23147 is closed and provides historical context only. No active directly linked issue supplies coding requirements for this pull request.
Out of Scope Changes check ✅ Passed The reported changes remain within the performance scope described for this pull request. They replace wildcard matching work, bound repeated ** traversal with collapsing and memoization, add a matc…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@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

  • Manual wildcard matcher replaces per-segment RegExp — compileGlobSegment now returns GlobSegment = string | { pattern: string } and globSegmentMatches walks * → [^/]* / ? → [^/] with a latest-star backtracking loop, so an adverse .gitignore glob can no longer drive catastrophic regex backtracking.
  • Adverse-work and semantics tests added — a cpuUsage guard (50 adverse matches under 500 ms), an exhaustive short pattern/name comparison against a regex oracle, and a literal/code-unit edge-case table.

I verified the new matcher preserves the old semantics beyond the added tests: 3.6M exhaustive pattern/value pairs against the removed regex and 5M random pairs against an independent DP oracle (including /, ., [, \n, and surrogate code units) produced zero mismatches. Worst-case work is genuinely bounded at O(pattern length × name length) — measured ~0.5·n² growth up to n=3200 with no exponential blowup, which is the regression the PR targets. Ignore-rule ordering, negation, basenameOnly, anchored base-segment scoping, and the ** recursion are unchanged, and the module's matcher helpers are private, so no external caller is affected. The disclosed ordinary-wildcard slowdown (a few× on a 10k-match microbenchmark) is negligible in absolute terms for this synchronous path.

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

@nwparker nwparker added the perf:high-impact-review Large measured gain in a specific workload; review trade-offs before merging. label Sep 27, 2026
… segment

The wildcard-segment fix left the larger blowup in place. A short .gitignore line
made only of `**` segments still costs exponential work in the outer path walk:
`**/**/.../z` at 24 segments and 73 characters, against an eight-segment
candidate, takes about 49 million recursive calls and ~150 ms here — larger than
the 25 ms single-segment case this branch removes. Rules are inherited down the
tree and re-checked for every directory, so that price is per directory, the
runtime's 15s scan timeout fires, and the user silently gets a short repo list.

Two independent bounds, both kept:

- `**` spans zero or more segments, so `**/**` accepts exactly what `**` accepts.
  Parsing now collapses a run of them to one segment, taking the reported shape
  from 49M recursive calls to 26 matcher steps.
- The walk memoizes on (pattern index, candidate index), so no other arrangement
  of `**` can reintroduce the blowup. A rule holding at most one `**` is already
  linear and skips the table, because allocating it costs more than the walk it
  would save on the shapes real ignore files contain.

The budget suite's process-CPU ceiling is replaced by a matcher step counter read
through `readNestedRepoGlobMatchSteps`, so an algorithmic regression fails the
suite rather than passing on a fast machine. Each bound has its own budget case,
and each fails when only the other is applied.

The equivalence oracle now also covers multi-segment and anchored patterns
including `**`, checked against the pre-change per-segment expression walking
uncollapsed segments. Code-unit and metacharacter cases are unchanged.

Co-Authored-By: Claude <[email protected]>

@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

Reviewed the delta since the prior pullfrog review (135eb7a → f3db53f), which extends the work bound from a single wildcard segment to the outer ** path walk.

  • Collapsed consecutive ** at parse time — compilePathSegments merges adjacent ** runs, so **/**/**/x compiles to the same two-segment pattern as **/x; a differential case confirms a collapsed and an expanded run accept identical paths.
  • Memoized the path walk when it can revisit a pair — pathSegmentsMatch now takes a memoize flag and caches (patternIndex, candidateIndex) results in a Map, enabled only when a rule has more than one ** run (memoizePathWalk). A single ** already visits each pair once, so the allocation is skipped on the common shapes.
  • Replaced the CPU-time adverse-work guard with a deterministic step budget — globMatchSteps / readNestedRepoGlobMatchSteps count matcher steps, and the budget tests assert on a delta, so an algorithmic regression fails independently of machine speed.
  • Added oracle-based coverage — multi-segment patterns up to three segments are compared against an uncollapsed/regex reference, with new budget cases pinning the collapse and memoization shapes.

I verified the semantics hold: the collapse is safe (** matches zero or more segments, so **/** ≡ **), the memo key is unique (candidateIndex < memoStride), and memoizing a (patternIndex, candidateIndex) state is sound because the walk is a pure DAG. The focused suites pass locally (nested-repo-glob-budget.test.ts, nested-repo-scan-rules.test.ts — 32 tests). The disclosed ordinary-wildcard slowdown versus the native regex remains and is unchanged by this commit.

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

@nwparker
nwparker merged commit 375c027 into main Sep 27, 2026
40 checks passed
@nwparker
nwparker deleted the nwparker/perf-09-25-nested-glob-work branch September 27, 2026 03:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf:high-impact-review Large measured gain in a specific workload; review trade-offs before merging.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Nested repository ignore rules can cause combinatorial matching work

1 participant