Skip to content

perf(compile): cache file walk and fix placement for narrow patterns#871

Open
Roozi489 wants to merge 3 commits intomicrosoft:mainfrom
Roozi489:perf/compile-cache-and-placement
Open

perf(compile): cache file walk and fix placement for narrow patterns#871
Roozi489 wants to merge 3 commits intomicrosoft:mainfrom
Roozi489:perf/compile-cache-and-placement

Conversation

@Roozi489
Copy link
Copy Markdown

Depends on #870.

Build a single _directory_files_cache during project analysis and use it for all subsequent glob matching, eliminating repeated os.walk/iterdir() calls. Also fixes instruction files with narrow applyTo globs (e.g. Engine/Plugins/PCG*/**/*) incorrectly landing at ./ instead of their target subtree -- _optimize_low_distribution_placement now uses _find_minimal_coverage_placement (lowest common ancestor) instead of a pollution-scored search that biased toward root. Stats loop rewritten from O(N^2) to O(N).

Martin Matouš and others added 2 commits April 23, 2026 11:26
Replace glob.glob(recursive=True) in find_primitive_files() with an
os.walk loop that prunes directories before descending into them.

This allows compilation.exclude patterns (and the new DEFAULT_SKIP_DIRS
constant) to short-circuit traversal into large subtrees -- e.g. a UE5
game repo with 265 K files no longer hangs because node_modules / build
/ apm_modules are skipped at the first encountered node.

Changes:
- constants.py: add DEFAULT_SKIP_DIRS frozenset (replaces duplicate
  inline sets in discovery.py and context_optimizer.py)
- discovery.py: os.walk + early prune; thread exclude_patterns into
  traversal so callers no longer need a post-filter pass; add
  _glob_match() helper for ** zero-segment matching
- test_discovery_walk.py: new unit tests covering prune behaviour,
  exclude_patterns, symlink rejection, and ** pattern matching

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Build a _directory_files_cache during _analyze_project_structure() so
that _cached_glob(), _find_matching_directories(), and
_directory_matches_pattern() all work from the same in-memory file list
instead of issuing repeated os.walk / iterdir() calls against disk.

Key changes in context_optimizer.py:

- _analyze_project_structure: move dirs[:] pruning BEFORE the depth /
  exclusion checks so os.walk never descends into excluded subtrees;
  populate _directory_files_cache[dir] = [file, ...] for later use

- _cached_glob: replaces glob.glob(cwd=base_dir) with a scan of
  _directory_files_cache using _glob_match() from discovery.py

- _find_matching_directories: fast path for ** patterns derives
  directory hits from the cached glob set (no iterdir()); slow path
  for non-recursive patterns iterates cached files

- _calculate_optimization_stats: rewrite O(N^2) efficiency loop to O(N)
  using pre-computed pattern_dir_sets from _pattern_cache

- _optimize_low_distribution_placement: go straight to
  _find_minimal_coverage_placement (lowest common ancestor) instead of
  the pollution-scored candidate search that biased toward root;
  fixes instruction files for narrow applyTo globs landing at ./ when
  all matching files live under a specific subtree

- Drop local DEFAULT_EXCLUDED_DIRNAMES; use DEFAULT_SKIP_DIRS from
  constants (introduced in perf/discovery-prune)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings April 23, 2026 09:31
@microsoft-github-policy-service
Copy link
Copy Markdown

@Roozi489 please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR improves apm compile performance and correctness by caching filesystem traversal results and adjusting low-distribution instruction placement to use lowest-common-ancestor coverage, reducing repeated os.walk/iterdir() work and avoiding incorrect root placements for narrow applyTo patterns.

Changes:

  • Switch primitive discovery find_primitive_files() from glob.glob(recursive=True) to os.walk with early directory pruning and shared skip dirs.
  • Add DEFAULT_SKIP_DIRS constant and use it to prune traversal in both primitives discovery and compilation analysis.
  • Update ContextOptimizer to cache per-directory file lists and use them for glob matching, directory matching, and stats computation; adjust low-distribution placement to use minimal-coverage (LCA) placement.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tests/unit/primitives/test_discovery_walk.py Adds unit tests for the new walk-based discovery helpers and verifies ContextOptimizer’s cached glob behavior.
src/apm_cli/primitives/discovery.py Implements _glob_match and updates find_primitive_files() to walk/prune instead of glob.glob().
src/apm_cli/constants.py Introduces DEFAULT_SKIP_DIRS to centralize unconditional traversal skips.
src/apm_cli/compilation/context_optimizer.py Adds _directory_files_cache and rewires _cached_glob / matching / stats; changes single-point placement to use LCA.
CHANGELOG.md Documents the behavior/perf changes under Unreleased.

Comment thread src/apm_cli/compilation/context_optimizer.py Outdated
Comment on lines +903 to +910
Strategy: Place at the lowest common ancestor of all matching directories.
This is the most specific directory that still provides full hierarchical
coverage, avoiding pollution of unrelated subtrees.
"""
candidates = self._generate_all_candidates(matching_directories, instruction)
# Find the deepest directory that covers all matches
minimal_coverage = self._find_minimal_coverage_placement(matching_directories)
if minimal_coverage and minimal_coverage in self._directory_cache:
return [minimal_coverage]
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

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

_optimize_single_point_placement() now uses lowest-common-ancestor placement, which is the crux of the bugfix described in the PR. There are existing tests for single-point placement and for LCA-at-root sibling coverage, but there is no test that asserts a non-root LCA is chosen when multiple matching directories exist under a deep subtree (the regression you mention like Engine/Plugins/PCG*/**/*). Add a unit test that constructs such a tree and asserts the placement directory is that subtree LCA, not the project root.

Copilot generated this review using guidance from repository custom instructions.
Comment thread CHANGELOG.md
Comment on lines +11 to +14
### Changed

- `find_primitive_files()` now uses `os.walk` with early directory pruning instead of `glob.glob(recursive=True)`, so `compilation.exclude` patterns prevent traversal into expensive subtrees (e.g. large game-engine asset trees). Adds shared `DEFAULT_SKIP_DIRS` constant used by both discovery and compilation.
- `ContextOptimizer` now builds a `_directory_files_cache` during `_analyze_project_structure()` and uses it for `_cached_glob`, `_find_matching_directories`, and `_directory_matches_pattern`, eliminating repeated `os.walk` / `iterdir()` calls. Directory pruning is moved before the depth check so excluded subtrees are never descended into. Stats loop rewritten from O(N^2) per-directory inheritance walk to O(N) with pre-computed pattern sets. Low-distribution placement now uses `_find_minimal_coverage_placement` directly instead of a pollution-scored candidate search that incorrectly biased toward the project root.
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

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

The new changelog bullets under ## [Unreleased] do not follow the repo format rules: each entry should end with a PR reference like (#<number>), and be one logical change per line. Please add the appropriate PR number(s) to these entries (and consider splitting the long ContextOptimizer bullet if needed).

Copilot uses AI. Check for mistakes.
Comment on lines +453 to +460
# Match files against the requested patterns
for file_name in files:
file_path = current / file_name
rel_str = str(file_path.relative_to(base_path)).replace(os.sep, '/')
for pattern in patterns:
if _glob_match(rel_str, pattern):
all_files.append(file_path)
break
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

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

find_primitive_files() iterates files from os.walk() without sorting, which can make primitive discovery order nondeterministic across filesystems. Because local primitives with the same name are conflict-resolved by first-seen order, this can lead to different winners on different machines. Sort files (and ideally return a consistently sorted valid_files) to preserve deterministic behavior similar to the old glob.glob() path ordering.

Copilot uses AI. Check for mistakes.
Comment on lines 505 to +515
def _should_skip_directory(dir_path: str) -> bool:
"""Check if a directory should be skipped during scanning.

Args:
dir_path (str): Directory path to check.

Returns:
bool: True if directory should be skipped, False otherwise.
"""
skip_patterns = {
'.git',
'node_modules',
'__pycache__',
'.pytest_cache',
'.venv',
'venv',
'.tox',
'build',
'dist',
'.mypy_cache'
}

dir_name = os.path.basename(dir_path)
return dir_name in skip_patterns
return dir_name in DEFAULT_SKIP_DIRS
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

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

_should_skip_directory() is now unused (no references in the repo) and duplicates the DEFAULT_SKIP_DIRS check already done inline during traversal. Consider removing it to avoid dead code, or reintroduce a call site if it is meant to be the canonical skip check.

Copilot uses AI. Check for mistakes.
Comment thread src/apm_cli/constants.py
Comment on lines +36 to +39
# These never contain APM primitives or user source files and can be
# very large (e.g. node_modules, .git objects). Used by discovery,
# compilation, and content hashing to avoid expensive walks.
# NOTE: .apm is intentionally absent -- it is where primitives live.
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

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

The comment for DEFAULT_SKIP_DIRS says these directories "never contain APM primitives", but apm_modules/ can contain dependency primitives (it is just intentionally excluded from local traversal). Reword the comment to reflect that these dirs are skipped because they are not relevant for project-source analysis / local primitive discovery. Also consider updating the docs default-exclusions list (e.g. reference/cli-commands.md) since venv/ is now an unconditional skip.

Suggested change
# These never contain APM primitives or user source files and can be
# very large (e.g. node_modules, .git objects). Used by discovery,
# compilation, and content hashing to avoid expensive walks.
# NOTE: .apm is intentionally absent -- it is where primitives live.
# These directories are not relevant to project-source analysis or local
# primitive discovery and may be very large (e.g. node_modules, .git
# objects). Used by discovery, compilation, and content hashing to avoid
# expensive walks.
# NOTE: .apm is intentionally absent because local project primitives may
# live there and should still be discovered.

Copilot uses AI. Check for mistakes.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@Roozi489
Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

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