Skip to content

refactor(code-intelligence): one file-discovery and exclusion implementation for all analyzers (#21004) - #21110

Closed
mrveiss wants to merge 5 commits into
mainfrom
issue-21004-analyzer-discovery
Closed

mrveiss wants to merge 5 commits into
mainfrom
issue-21004-analyzer-discovery

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Thinking Path

The analyzers each walked the tree and excluded directories by their own rules (15 bare walk sites, 11 exclusion definitions). #21002 landed the root-relative is_excluded in code_intelligence/python_files.py. This PR makes that module the single home: one discover_files() walk and one ANALYSIS_EXCLUDE_DIRS set (derived from SKIP_DIRS plus the analysis-only extras the copies used to add individually), and migrates every analyzer to them.

What Changed

  • python_files.py: add ANALYSIS_EXCLUDE_DIRS and discover_files(root, patterns, exclude_dirs); collect_python_files delegates to it.
  • Migrated walk sites to discover_files: testing_pattern_analyzer, shared/analysis_base, redis_optimizer, llm_pattern_analyzer, bug_predictor (sync and async), merge_conflict_resolver, cross_language_patterns/detector, pattern_analysis (analyzer, complexity, regex), shared/file_cache, base_analyzer.
  • Removed exclusion copies (EXCLUDE_DIRS x3, _SKIP_DIRS x3, _COCHANGE_SKIP_DIRS, per-class default lists in fingerprinting/testing_pattern/redis/llm/base_analyzer); DEFAULT_IGNORE_PATTERNS and DEFAULT_EXCLUDE_PATTERNS now derive from the canonical set. File-name patterns (tests, bytecode, migrations) stay with their analyzers.
  • Behaviour change: bug_predictor and merge_conflict_resolver now apply the exclusions (they applied none); archive/backup/third_party are now skipped by every analyzer, not only some.
  • Guard + tests: code_intelligence/analyzer_discovery_one_home_21004_test.py (AST guard for bare rglob/os.walk and local exclusion-set copies, planted-violation control, root-under-skipped-name regression).
  • conftest.py: real-load python_files before merge_conflict_resolver (it now imports it). Size ceilings lowered in scripts/python_file_size_known_large.py.

Verification

  • pytest on the touched analyzers' tests plus the new test: 100 + 219 + 117 passed; repo_tests/file_type_sets_one_home_19339_test.py 34 passed.
  • flake8 clean on touched files; scripts/check_python_file_size.py clean.
  • Not run locally: full suite (CI).

Refs #21004

Model Used

Claude Sonnet 5.5

@mrveiss mrveiss added the phase:M4.9 One definition per concept label Nov 8, 2026
@coderabbitai

coderabbitai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 18 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 250ddc4 and 926da88.

Files ignored due to path filters: 1

  • scripts/python_file_size_known_large.py is excluded by !scripts/python_file_size_known_large.py
Files selected for processing: 19

  • autobot-backend/code_intelligence/analyzer_discovery_one_home_21004_test.py
  • autobot-backend/code_intelligence/anti_pattern_detection/types.py
  • autobot-backend/code_intelligence/base_analyzer.py
  • autobot-backend/code_intelligence/bug_predictor.py
  • autobot-backend/code_intelligence/code_evolution_miner.py
  • autobot-backend/code_intelligence/cross_language_patterns/detector.py
  • autobot-backend/code_intelligence/cross_language_patterns/extractors.py
  • autobot-backend/code_intelligence/fingerprinting/detector.py
  • autobot-backend/code_intelligence/llm_pattern_analyzer.py
  • autobot-backend/code_intelligence/merge_conflict_resolver.py
  • autobot-backend/code_intelligence/pattern_analysis/analyzer.py
  • autobot-backend/code_intelligence/pattern_analysis/complexity_analyzer.py
  • autobot-backend/code_intelligence/pattern_analysis/regex_detector.py
  • autobot-backend/code_intelligence/python_files.py
  • autobot-backend/code_intelligence/redis_optimizer.py
  • autobot-backend/code_intelligence/shared/analysis_base.py
  • autobot-backend/code_intelligence/shared/file_cache.py
  • autobot-backend/code_intelligence/testing_pattern_analyzer.py
  • autobot-backend/conftest.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at 8f65271

Verdict: CHANGES. The consolidation is sound and the three items I could verify as safe are listed below, but there is one behaviour regression (F1) and one symlink-handling regression (F2) to fix in this PR.

# Severity file:line Finding Fix
F1 HIGH code_intelligence/llm_pattern_analyzer.py:~320 file_path.relative_to(directory).match(pattern) changes what **/test* excludes. PurePath.match right-aligns and needs at least as many parts as the pattern, so a top-level test_x.py (relative path of 1 part) no longer matches the 2-part **/test*. Checked: PurePath('test_x.py').match('**/test*') is False, the absolute form is True. Files directly under a scanned directory are now analysed where they were excluded before. Keep matching the absolute path as before (the dir exclusion is already done by discover_files), or match on file_path.name for the test* rule. Add a regression test with a top-level test_*.py.
F2 MEDIUM shared/file_cache.py:~184 Switched from is_skipped_path (lexical, then is_symlink(), then resolve() for symlinked leaves) to lexical is_excluded. A symlinked leaf x.py pointing outside the root, or into a skipped dir, is now returned (is_file() follows it) and read by the analyzers. The old function's tier 2/3 existed for exactly this. Make discover_files symlink-aware (resolve symlinked leaves and require them to stay under the root and out of excluded names), or have it call is_skipped_path-equivalent logic once for everyone. Add a symlink-escape test.
F3 MEDIUM python_files.py:45-60 discover_files runs root.rglob over the whole tree and filters afterwards; it does not prune. is_skipped_path's own comment records 214k globbed paths against ~7k kept. This is the one home now, so the cost is paid by every analyzer, and multi-pattern callers walk once per pattern (file_cache N extensions, cross_language_patterns/detector.py 4 patterns, plus set + sorted over all of them). Not a regression versus before, but this is the place to fix it. Single os.walk with dirnames[:] = [d for d in dirnames if d not in excluded], matching all patterns with fnmatch per file; keep the symlink handling from F2 (followlinks=False).
F4 LOW file_cache.py:~184 Passes SKIP_DIRS while every other caller uses ANALYSIS_EXCLUDE_DIRS, so archive/backup/third_party are still scanned there. The PR body says they are now skipped "by every analyzer". Either intended (then say so in the body) or an inconsistency. Use the default (ANALYSIS_EXCLUDE_DIRS), or document why the cache keeps the narrower set.
F5 LOW analyzer_discovery_one_home_21004_test.py:36-50 Guard only flags <x>.rglob(...) and os.walk. It misses Path.glob("**/..."), glob.glob(..., recursive=True), os.scandir/iterdir recursion, from os import walk. The planted-violation control does fail correctly for what it covers (3 findings: rglob, walk, EXCLUDE_DIRS), and base_analyzer.py:441 still has a non-recursive directory.glob("*") that is legitimately fine. Also flag glob with a ** literal first arg, glob.glob/iglob, os.scandir, os.walk via alias import; extend the planted fixture to cover each.
F6 LOW code_evolution_miner.py:45, cross_language_patterns/detector.py:53, pattern_analysis/analyzer.py:90, complexity_analyzer.py:258, regex_detector.py:205 Comment lines ("Canonical skip dirs plus extras ...", "Default directories to skip") left behind after their constants were deleted; they now describe nothing and mislead. Delete the orphaned comments.
F7 INFO scripts/python_file_size_known_large.py Ceilings lowered correctly; all touched files remain over 600 lines only via the known-large list (pre-existing). New functions are all under 30 lines. None.

Checked and fine:

  • FileListCache._should_skip_path: no callers at the PR head. The remaining _should_skip_path hits are api/codebase_analytics/duplicate_detector.py (its own method, own test) and an unrelated profiler script; no getattr/string references.
  • Async path: bug_predictor.analyze_directory_async uses asyncio.to_thread(discover_files, root, (pattern,)), so the walk stays off the event loop.
  • Root under a skipped name: is_excluded is root-relative, so venv/project roots still yield files; the parametrized regression test covers venv, node_modules, .worktrees. Hidden dirs are only excluded by name if in the set, as before.
  • conftest.py: real-loading python_files first is not hiding an import cycle. python_files imports only stdlib and utils.file_categorization; conftest stubs the code_intelligence package, and the existing pattern for self-contained leaves (diff, scoring) is exactly to real-load them by path. Acceptable and consistent.
  • bug_predictor / merge_conflict_resolver now excluding vendored/archived dirs is the stated, intended behaviour change per the issue (rows 6-8).

Issue ACs: AC1 ("one discovery function and one exclusion predicate") is only partly met, since analysis_base and redis_optimizer still apply their own file-name/glob predicates, and ANALYSIS_EXCLUDE_DIRS adds extras beyond SKIP_DIRS (AC2 says "derive from SKIP_DIRS only"; it does derive from it, with extras in the canonical module, which I read as acceptable). AC3-AC5 are met. Given AC1 is partial, Refs #21004 is the correct keyword; do not use Closes.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Review fixes pushed at 441853c.

# Fix
F1 llm_pattern_analyzer._collect_files matches the full path again, so a top-level test_*.py is excluded by **/test*. Regression test test_llm_pattern_exclude_still_drops_a_top_level_test_file.
F2 discover_files drops any symlinked leaf that resolves outside the root or into an excluded dir. Test test_symlinked_leaf_escaping_the_root_or_into_a_skipped_dir_is_dropped (escape, into-skipped and inside-root links).
F3 discover_files is now one os.walk (followlinks=False) that prunes dirnames[:] and matches every pattern per file with fnmatch. Test test_discover_files_prunes_excluded_dirs_and_matches_every_pattern.
F4 file_cache uses the default ANALYSIS_EXCLUDE_DIRS; cache_covers_exclusions now compares against that set, so the PR body statement holds.
F5 Guard also flags glob("**/..."), glob.glob/iglob(recursive=), os.scandir/fwalk, from os import walk and a bare walk(). Each rule has its own planted fixture (parametrized control) plus a negative test for non-recursive glob("*").
F6 Orphaned comments removed in code_evolution_miner.py, cross_language_patterns/detector.py, pattern_analysis/analyzer.py, complexity_analyzer.py, regex_detector.py.

CI: the failures on 8f65271 were cancellations by the one-PR-CI queue gate ("not admitted" / parked), not code failures. The jobs ran no steps and have no runner.

Local checks: touched tests 279 passed plus the new guard tests, flake8 and the file-size check clean.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at 441853c

Delta review of 8f65271..441853c. Verdict: APPROVE. F1 to F6 are all fixed in the code; the remaining items are low and non-blocking. I read the code and tests; I did not run them.

Previous findings:

# Status Evidence
F1 Fixed llm_pattern_analyzer.py matches file_path.match(pattern) on the full path again. Regression test test_llm_pattern_exclude_still_drops_a_top_level_test_file calls _collect_files([tmp_path], ["**/test*"]) with a top-level test_top.py.
F2 Fixed python_files.py _walk_matches: a symlinked leaf is resolved and dropped if is_excluded(resolved, real_root, excluded) (outside the root or into an excluded name); loops and OS errors are dropped. Test covers escape, into-skipped and inside-root links.
F3 Fixed One os.walk(root, followlinks=False), dirnames[:] pruned in place, patterns matched per file name with fnmatchcase. Excluded trees are no longer traversed.
F4 Fixed file_cache calls discover_files with the default set; cache_covers_exclusions now compares against ANALYSIS_EXCLUDE_DIRS.
F5 Fixed Guard extended and each rule has its own planted fixture (parametrized control) plus a negative glob("*") test.
F6 Fixed Orphaned comments removed in the five files.

New-code checks on discover_files:

  • Pruning is correct: the root is never pruned, only names below it, so a root under venv/node_modules still works.
  • followlinks=False: directory symlinks are listed in dirnames but not descended into, same as the old rglob. A directory symlink that matches a file pattern fails is_file().
  • Symlink cost: is_symlink() (one lstat) runs only on name-matched files, and resolve() only on symlinked leaves, so the cost is small. real_root is resolved once.
  • Ordering: sorted(Path) over the generator keeps the result deterministic and identical in form to before; it does not depend on os.walk order.
  • Broken symlinks resolve inside the root and are then rejected by is_file().

Remaining non-blocking items:

# Severity file Finding Fix
N1 LOW python_files.py _walk_matches Patterns are matched against the file name only. The old rglob(pattern) also accepted a pattern containing a separator (for example src/*.py). bug_predictor.analyze_directory(pattern=...) is a public parameter, so such a pattern now silently matches nothing. The in-repo callers pass *.py. Document "name globs only" in the discover_files docstring, or reject a pattern containing /.
N2 LOW analyzer_discovery_one_home_21004_test.py _call_violation A bare walk(...)/scandir(...)/fwalk(...) is flagged by name, so from ast import walk; walk(tree) or a local helper named walk would be a false positive; glob.glob(p, recursive=False) is flagged too. The tree is clean today, so nothing fails now. Flag a bare walk() only if the file has from os import walk (the import is already flagged on its own), and read the recursive= value instead of its presence.
N3 INFO autobot-backend/api/analytics_bug_prediction.py:690 Out of this PR's scope (outside code_intelligence, so the guard does not see it): list(root.rglob(include_pattern))[:limit] is another unpruned walk with no exclusions, on a user-supplied pattern. Follow-up under #21004's umbrella; route through discover_files once N1 is settled.

The PR body's CI note (failures were queue-gate cancellations, no steps ran) is the coordinator's statement; I did not verify it on this head. Keep Refs #21004, not Closes, because AC1 is still partial.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Delta findings fixed at 053bc0a.

# Fix
N1 discover_files raises ValueError for any pattern containing / or \, and its docstring says "file-name globs only". Test test_discover_files_rejects_a_path_pattern covers src/*.py, **/*.py and a backslash pattern.
N2 The guard flags a bare walk(...) only when the file binds it with from os import walk/fwalk/scandir (alias-aware), and flags glob.glob/iglob only when recursive is not a literal falsy value. Negative fixtures in test_guard_does_not_flag_look_alikes: from ast import walk, glob.glob(recursive=False), glob.iglob(p).

N3: api/analytics_bug_prediction.py:690 is already in the #21111 checklist, so the issue body was not changed.

Local checks: 98 tests passed (new guard test, bug_predictor, shared_caches, anti_pattern scope); flake8 clean.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at 053bc0a

Verdict: APPROVE. I read the diff and the code; I did not run the tests. Scope: 20 changed files, 17 commits behind main (merge main before the train, no conflict check done). Author self-approval not counted.

# Area Finding Severity
1 One home discover_files in code_intelligence/python_files.py is the only os.walk in code_intelligence production code; 15 analyzers/call sites delegate to it (cross_language, fingerprinting, pattern_analysis x3, redis_optimizer, bug_predictor, file_cache, testing_pattern, llm_pattern, merge_conflict, analysis_base). Remaining ast.walk hits are AST traversal, not file walks. ok
2 Remaining walkers rglob/os.walk outside the package are tracked as the #21111 checklist (blocked_by #21004), e.g. agents, api/analytics_, api/codebase_analytics/. Not in scope here. ok
3 Separator rejection discover_files raises ValueError on / or \ in a pattern; test covers src/*.py, **/*.py, backslash. ok
4 Exclusions One pruned os.walk, excluded names matched below the root only (root under venv/node_modules still scans), symlink leaf escaping the root or into an excluded dir dropped, ANALYSIS_EXCLUDE_DIRS is a superset of SKIP_DIRS; each pinned by a test. .gitignore is not consulted, same as the replaced walkers. ok
5 Guard Flags walk only when bound by from os import, glob only when recursive (** or recursive= non-falsy). Eight planted controls are parametrized and assert the guard fires; three look-alike negatives assert it does not. It scans the whole package, so no extra reach floor is needed. ok
6 Performance One walk per call; file_cache keeps its shared cached list and falls back to a walk only when the caller's exclusions are narrower than the cache's. No per-analyzer repeat scan introduced. ok
7 Behavior risk bug_predictor now passes its pattern argument to discover_files; a caller supplying a pattern with a path separator now gets ValueError instead of a match. Current callers use name globs. Non-blocking: note in #21111 alongside api/analytics_bug_prediction.py:690. low
8 Hygiene No sleeps and no line-number comments in the added lines. Touched files that were over 600 lines only shrank, and their ceilings in python_file_size_known_large.py were lowered. New module and test are under 250 lines. Functions in the new code are within 30 lines. ok
9 CI At this head 27 check runs have no conclusion yet, 1 success, 1 neutral, 1 skipped. Merge only once they are green. gate

Threads: no inline review threads exist. The only conversation is a rate-limited bot notice and the author's own earlier review comments, whose findings F1 to F6 and N1 to N3 are fixed in the code at this head.

@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

✅ SSOT Configuration Compliance: Passing

🎉 No new hardcoded values of either class — ssot and other both block.

Known backlog in pipeline-scripts/hardcoded_values_baseline.txt is suppressed and tracked in #14371.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Landed on main in merge train T98c (#21182), merge commit e28fed6. Closing as landed; the owning session handles the linked-issue closure (with AC evidence) and the branch/worktree disposal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

phase:M4.9 One definition per concept

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant