Skip to content

Optimise venv identification for mid/large-sized directory trees#4242

Open
alexander-beedie wants to merge 1 commit into
facebook:mainfrom
alexander-beedie:perf-venv-discovery
Open

Optimise venv identification for mid/large-sized directory trees#4242
alexander-beedie wants to merge 1 commit into
facebook:mainfrom
alexander-beedie:perf-venv-discovery

Conversation

@alexander-beedie

@alexander-beedie alexander-beedie commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Summary

Overview

  • When pyrefly check runs over a package without a configured interpreter, it auto-discovers a project's venv.

  • If "pyvenv.cfg" isn't immediately found in the project root or ".venv" / "venv", it falls back to an unfiltered WalkDir (to depth 3) over the entire project, testing every filename against the interpreter regex.

  • For large projects, this can be a significant fixed cost. For example, profiling showed it taking up ~20% of the total runtime for checking homeassistant, as that package has ~2,700 directories (!!). For small projects there is no change.

Solution

  • walk_interpreter gains a simple "should_descend" predicate that prunes a directory's subtree when the predicate rejects it; a venv-aware pruning rule is supplied in find_in_dir.

  • The prune is a strict superset of the reachable interpreters, so which interpreter the find resolves is unchanged, but the non-venv source fan-out is skipped.

  • In the extreme homeassistant case, this reduces ~2,700 opendir calls down to only ~15, making the check essentially free (instead of ~20% of the runtime) 🚀

Test Plan

All existing tests pass, and two new venv discovery tests were added (which actually represent the majority of this PR as the code change itself is small).

Benchmarks1

Timed across a sample of the mypy_primer projects. Speedup is proportional to directory-tree size; significant on large trees, negligible on small flat projects.

dirs ≤ 3 = how many directories (with depth ≤ 3) in the project.
modules = how many modules in the project.
before = pyrefly on main branch.
after = main + this PR.

project dirs ≤ 3 modules before after Δ%
homeassistant 2,736 9,811 2.010 1.611 -19.8%
poetry 124 191 0.172 0.151 -12.6%
sphinx 360 243 0.253 0.229 -9.4%
pylint 129 51 0.178 0.162 -9.0%
hypothesis 66 103 0.172 0.157 -8.7%
sympy 153 1,560 0.358 0.334 -6.6%
pydantic 60 104 0.170 0.164 -3.4%
pandas 129 1,459 0.407 0.396 -2.6%
mypy 61 1,098 0.394 0.384 -2.5%
scipy 137 925 0.429 0.425 -1.0%

Footnotes

  1. Test machine: Apple Silicon M3 Max.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants