Skip to main content

uv_python_discovery/
discovery.rs

1use itertools::{Either, Itertools};
2use rayon::iter::{IntoParallelIterator, ParallelIterator};
3use regex::Regex;
4use rustc_hash::{FxBuildHasher, FxHashSet};
5use std::cmp::Reverse;
6use std::env::consts::EXE_SUFFIX;
7use std::fmt::{self, Debug, Formatter};
8use std::{env, io, iter};
9use std::{path::Path, path::PathBuf};
10use thiserror::Error;
11use tracing::{debug, instrument, trace};
12use uv_cache::Cache;
13use uv_client::BaseClientBuilder;
14use uv_fs::Simplified;
15use uv_fs::which::is_executable;
16use uv_macros::DebugNoInline;
17use uv_platform::Platform;
18use uv_python_types::{
19    EnvironmentPreference, PythonPreference, PythonRequest, PythonRequestError, PythonSource,
20    VersionRequest,
21};
22use uv_static::EnvVars;
23use uv_warnings::{warn_user_once, warn_user_with_chain};
24use which::which_all;
25
26use crate::installation::PythonInstallation;
27#[cfg(windows)]
28use crate::microsoft_store::find_microsoft_store_pythons;
29use crate::virtualenv_discovery::CondaEnvironmentKind;
30use crate::virtualenv_discovery::conda_environment_from_env;
31use crate::virtualenv_discovery::virtualenv_from_env;
32use crate::virtualenv_discovery::virtualenv_from_working_dir;
33#[cfg(windows)]
34use crate::windows_registry::{WindowsPython, registry_pythons};
35use uv_python_interpreter::{
36    BrokenLink, Interpreter, InterpreterError, StatusCodeError, UnexpectedResponseError,
37    VirtualEnvError, virtualenv_python_executable,
38};
39use uv_python_managed::ManagedPythonInstallations;
40use uv_python_managed::PythonMinorVersionLink;
41use uv_python_managed::downloads::ManagedPythonDownloadList;
42use uv_python_types::{
43    ArchRequest, ImplementationName, PlatformRequest, PythonArchitecture, PythonDownloadMirrors,
44    PythonDownloadRequest, python_build_versions_from_env,
45};
46
47#[derive(Debug, Clone, PartialEq, Eq, Default)]
48pub(crate) struct DiscoveryPreferences {
49    python_preference: PythonPreference,
50    environment_preference: EnvironmentPreference,
51}
52
53/// The result of a Python installation search.
54///
55/// Returned by [`find_python_installation`].
56type FindPythonResult = Result<PythonInstallation, PythonNotFound>;
57
58/// The result of failed Python installation discovery.
59#[derive(Clone, Debug, Error)]
60pub struct PythonNotFound {
61    pub(super) request: PythonRequest,
62    pub(super) python_preference: PythonPreference,
63    pub(super) environment_preference: EnvironmentPreference,
64}
65
66/// A non-empty group of equally preferred Python executables.
67///
68/// Minor-version fallback candidates from one `PATH` directory share a group. Preferred executable
69/// names and interpreters from other sources form singleton groups.
70struct PythonExecutableGroup(Vec<(PythonSource, PathBuf)>);
71
72impl PythonExecutableGroup {
73    fn new(executables: Vec<(PythonSource, PathBuf)>) -> Option<Self> {
74        (!executables.is_empty()).then_some(Self(executables))
75    }
76
77    fn filter(mut self, mut predicate: impl FnMut(PythonSource, &Path) -> bool) -> Option<Self> {
78        self.0.retain(|(source, path)| predicate(*source, path));
79        (!self.0.is_empty()).then_some(self)
80    }
81}
82
83#[derive(Error, DebugNoInline)]
84pub enum Error {
85    #[error(transparent)]
86    Io(#[from] io::Error),
87
88    /// An error was encountering when retrieving interpreter information.
89    #[error("Failed to inspect Python interpreter from {} at `{}` ", _2, _1.user_display())]
90    Query(
91        #[source] Box<uv_python_interpreter::InterpreterError>,
92        PathBuf,
93        PythonSource,
94    ),
95
96    /// An error was encountered while trying to find a managed Python installation matching the
97    /// current platform.
98    #[error("Failed to discover managed Python installations")]
99    ManagedPython(#[from] uv_python_managed::Error),
100
101    /// An error was encountered when inspecting a virtual environment.
102    #[error(transparent)]
103    VirtualEnv(#[from] uv_python_interpreter::VirtualEnvError),
104
105    #[cfg(windows)]
106    #[error("Failed to query installed Python versions from the Windows registry")]
107    RegistryError(#[from] windows::core::Error),
108
109    #[error(transparent)]
110    InvalidEnvironmentVariable(#[from] uv_static::InvalidEnvironmentVariable),
111
112    /// An invalid version request was given
113    #[error("Invalid version request: {0}")]
114    InvalidVersionRequest(String),
115
116    /// The @latest version request was given
117    #[error("Requesting the 'latest' Python version is not yet supported")]
118    LatestVersionRequest,
119
120    // TODO(zanieb): Is this error case necessary still? We should probably drop it.
121    #[error("Interpreter discovery for `{0}` requires `{1}` but only `{2}` is allowed")]
122    SourceNotAllowed(PythonRequest, PythonSource, PythonPreference),
123
124    #[error(transparent)]
125    BuildVersion(#[from] uv_python_types::BuildVersionError),
126}
127
128impl From<PythonRequestError> for Error {
129    fn from(error: PythonRequestError) -> Self {
130        match error {
131            PythonRequestError::InvalidVersionRequest(value) => Self::InvalidVersionRequest(value),
132            PythonRequestError::LatestVersionRequest => Self::LatestVersionRequest,
133        }
134    }
135}
136
137impl uv_errors::Hinted for Error {
138    fn hints(&self) -> uv_errors::Hints<'_> {
139        match self {
140            Self::Query(err, _, _) => err.hints(),
141            _ => uv_errors::Hints::none(),
142        }
143    }
144}
145
146/// Lazily iterate over Python executables in mutable virtual environments.
147///
148/// The following sources are supported:
149///
150/// - Active virtual environment (via `VIRTUAL_ENV`)
151/// - Discovered virtual environment (e.g. `.venv` in a parent directory)
152///
153/// Notably, "system" environments are excluded. See [`python_executables_from_installed`].
154fn python_executables_from_virtual_environments<'a>()
155-> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a {
156    let from_active_environment = iter::once_with(|| {
157        virtualenv_from_env()
158            .into_iter()
159            .map(virtualenv_python_executable)
160            .map(|path| Ok((PythonSource::ActiveEnvironment, path)))
161    })
162    .flatten();
163
164    // N.B. we prefer the conda environment over discovered virtual environments
165    let from_conda_environment = iter::once_with(move || {
166        conda_environment_from_env(CondaEnvironmentKind::Child)
167            .into_iter()
168            .map(virtualenv_python_executable)
169            .map(|path| Ok((PythonSource::CondaPrefix, path)))
170    })
171    .flatten();
172
173    let from_discovered_environment = iter::once_with(|| {
174        virtualenv_from_working_dir()
175            .map(|path| {
176                path.map(virtualenv_python_executable)
177                    .map(|path| (PythonSource::DiscoveredEnvironment, path))
178                    .into_iter()
179            })
180            .map_err(Error::from)
181    })
182    .flatten_ok();
183
184    from_active_environment
185        .chain(from_conda_environment)
186        .chain(from_discovered_environment)
187}
188
189/// Lazily iterate over Python executables installed on the system.
190///
191/// The following sources are supported:
192///
193/// - Managed Python installations (e.g. `uv python install`)
194/// - The search path (i.e. `PATH`)
195/// - The registry (Windows only)
196///
197/// The ordering and presence of each source is determined by the [`PythonPreference`].
198///
199/// If a [`VersionRequest`] is provided, we will skip executables that we know do not satisfy the request
200/// and (as discussed in [`python_executables_from_search_path`]) additional version-specific executables may
201/// be included. However, the caller MUST query the returned executables to ensure they satisfy the request;
202/// this function does not guarantee that the executables provide any particular version. See
203/// [`find_python_installation`] instead.
204///
205/// This function does not guarantee that the executables are valid Python interpreters.
206/// See [`python_interpreters_from_executables`].
207fn python_executables_from_installed<'a>(
208    version: &'a VersionRequest,
209    implementation: Option<&'a ImplementationName>,
210    platform: PlatformRequest,
211    preference: PythonPreference,
212) -> Box<dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a> {
213    let from_managed_installations = iter::once_with(move || {
214        ManagedPythonInstallations::from_settings(None)
215            .map_err(Error::from)
216            .and_then(|installed_installations| {
217                debug!(
218                    "Searching for managed installations at `{}`",
219                    installed_installations.root().user_display()
220                );
221                let installations = ManagedPythonInstallations::find_matching_current_platform()?;
222
223                let build_versions = python_build_versions_from_env()?;
224
225                // Check that the Python version and platform satisfy the request to avoid
226                // unnecessary interpreter queries later
227                Ok(installations
228                    .into_iter()
229                    .filter(move |installation| {
230                        if !version.matches_version(&installation.version()) {
231                            debug!("Skipping managed installation `{installation}`: does not satisfy `{version}`");
232                            return false;
233                        }
234                        if !platform.matches(installation.platform()) {
235                            debug!("Skipping managed installation `{installation}`: does not satisfy requested platform `{platform}`");
236                            return false;
237                        }
238
239                        if let Some(requested_build) = build_versions.get(&installation.implementation()) {
240                            let Some(installation_build) = installation.build() else {
241                                debug!(
242                                    "Skipping managed installation `{installation}`: a build version was requested but is not recorded for this installation"
243                                );
244                                return false;
245                            };
246                            if installation_build != requested_build {
247                                debug!(
248                                    "Skipping managed installation `{installation}`: requested build version `{requested_build}` does not match installation build version `{installation_build}`"
249                                );
250                                return false;
251                            }
252                        }
253
254                        true
255                    })
256                    .inspect(|installation| debug!("Found managed installation `{installation}`"))
257                    .map(move |installation| {
258                        // If it's not a patch version request, then attempt to read the stable
259                        // minor version link.
260                        let executable = version
261                                .patch()
262                                .is_none()
263                                .then(|| {
264                                    PythonMinorVersionLink::from_installation(&installation)
265                                    .filter(PythonMinorVersionLink::exists)
266                                    .map(
267                                        |minor_version_link| {
268                                            minor_version_link.symlink_executable.clone()
269                                        },
270                                    )
271                                })
272                                .flatten()
273                                .unwrap_or_else(|| installation.executable(false));
274                        (PythonSource::Managed, executable)
275                    })
276                )
277            })
278    })
279    .flatten_ok()
280    .map_ok(|executable| PythonExecutableGroup(vec![executable]));
281
282    let from_search_path = iter::once_with(move || {
283        let mut first = true;
284        python_executables_from_search_path(version, implementation).filter_map(move |paths| {
285            let executables = paths
286                .into_iter()
287                .map(|path| {
288                    let source = if first {
289                        first = false;
290                        PythonSource::SearchPathFirst
291                    } else {
292                        PythonSource::SearchPath
293                    };
294                    (source, path)
295                })
296                .collect();
297            PythonExecutableGroup::new(executables).map(Ok)
298        })
299    })
300    .flatten();
301
302    #[cfg(windows)]
303    let from_windows_registry: Box<
304        dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a,
305    > = match uv_static::parse_boolish_environment_variable(EnvVars::UV_PYTHON_NO_REGISTRY) {
306        Ok(Some(true)) => Box::new(iter::empty()),
307        Ok(Some(false) | None) => Box::new(
308            iter::once_with(move || {
309                // Skip interpreter probing if we already know the version doesn't match.
310                let version_filter = move |entry: &WindowsPython| {
311                    if let Some(found) = &entry.version {
312                        // Some distributions emit the patch version (example: `SysVersion: 3.9`)
313                        if found.string.chars().filter(|c| *c == '.').count() == 1 {
314                            version.matches_major_minor(found.major(), found.minor())
315                        } else {
316                            version.matches_version(found)
317                        }
318                    } else {
319                        true
320                    }
321                };
322
323                registry_pythons()
324                    .map(|entries| {
325                        entries
326                            .into_iter()
327                            .filter(version_filter)
328                            .map(|entry| (PythonSource::Registry, entry.path))
329                            .chain(
330                                find_microsoft_store_pythons()
331                                    .filter(version_filter)
332                                    .map(|entry| (PythonSource::MicrosoftStore, entry.path)),
333                            )
334                    })
335                    .map_err(Error::from)
336            })
337            .flatten_ok()
338            .map_ok(|executable| PythonExecutableGroup(vec![executable])),
339        ),
340        Err(err) => Box::new(iter::once(Err(Error::from(err)))),
341    };
342
343    #[cfg(not(windows))]
344    let from_windows_registry: Box<
345        dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a,
346    > = Box::new(iter::empty());
347
348    match preference {
349        PythonPreference::OnlyManaged => {
350            // TODO(zanieb): Ideally, we'd create "fake" managed installation directories for tests,
351            // but for now... we'll just include the test interpreters which are always on the
352            // search path.
353            if std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED).is_ok() {
354                Box::new(from_managed_installations.chain(from_search_path))
355            } else {
356                Box::new(from_managed_installations)
357            }
358        }
359        PythonPreference::Managed => Box::new(
360            from_managed_installations
361                .chain(from_search_path)
362                .chain(from_windows_registry),
363        ),
364        PythonPreference::System => Box::new(
365            from_search_path
366                .chain(from_windows_registry)
367                .chain(from_managed_installations),
368        ),
369        PythonPreference::OnlySystem => Box::new(from_search_path.chain(from_windows_registry)),
370    }
371}
372
373/// Lazily iterate over all discoverable Python executables.
374///
375/// Note that Python executables may be excluded by the given [`EnvironmentPreference`],
376/// [`PythonPreference`], and [`PlatformRequest`]. However, these filters are only applied for
377/// performance. We cannot guarantee that the all requests or preferences are satisfied until we
378/// query the interpreter.
379///
380/// See [`python_executables_from_installed`] and [`python_executables_from_virtual_environments`]
381/// for more information on discovery.
382fn python_executables<'a>(
383    version: &'a VersionRequest,
384    implementation: Option<&'a ImplementationName>,
385    platform: PlatformRequest,
386    environments: EnvironmentPreference,
387    preference: PythonPreference,
388) -> Box<dyn Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a> {
389    // Always read from `UV_INTERNAL__PARENT_INTERPRETER` — it could be a system interpreter
390    let from_parent_interpreter = iter::once_with(|| {
391        env::var_os(EnvVars::UV_INTERNAL__PARENT_INTERPRETER)
392            .into_iter()
393            .map(|path| {
394                Ok(PythonExecutableGroup(vec![(
395                    PythonSource::ParentInterpreter,
396                    PathBuf::from(path),
397                )]))
398            })
399    })
400    .flatten();
401
402    // Check if the base conda environment is active
403    let from_base_conda_environment = iter::once_with(move || {
404        conda_environment_from_env(CondaEnvironmentKind::Base)
405            .into_iter()
406            .map(virtualenv_python_executable)
407            .map(|path| {
408                Ok(PythonExecutableGroup(vec![(
409                    PythonSource::BaseCondaPrefix,
410                    path,
411                )]))
412            })
413    })
414    .flatten();
415
416    let from_virtual_environments = python_executables_from_virtual_environments()
417        .map_ok(|executable| PythonExecutableGroup(vec![executable]));
418    let from_installed =
419        python_executables_from_installed(version, implementation, platform, preference);
420
421    // Limit the search to the relevant environment preference; this avoids unnecessary work like
422    // traversal of the file system. Subsequent filtering should be done by the caller with
423    // `source_satisfies_environment_preference` and `EnvironmentPreference::allows_installation`.
424    match environments {
425        EnvironmentPreference::OnlyVirtual => {
426            Box::new(from_parent_interpreter.chain(from_virtual_environments))
427        }
428        EnvironmentPreference::ExplicitSystem | EnvironmentPreference::Any => Box::new(
429            from_parent_interpreter
430                .chain(from_virtual_environments)
431                .chain(from_base_conda_environment)
432                .chain(from_installed),
433        ),
434        EnvironmentPreference::OnlySystem => Box::new(
435            from_parent_interpreter
436                .chain(from_base_conda_environment)
437                .chain(from_installed),
438        ),
439    }
440}
441
442/// Lazily iterate over Python executables in the `PATH`.
443///
444/// The [`VersionRequest`] and [`ImplementationName`] are used to determine the possible
445/// Python interpreter names, e.g. if looking for Python 3.9 we will look for `python3.9`
446/// or if looking for `PyPy` we will look for `pypy` in addition to the default names.
447///
448/// Executables are returned in the search path order, then by specificity of the name, e.g.
449/// `python3.9` is preferred over `python3` and `pypy3.9` is preferred over `python3.9`.
450///
451/// For a `PATH` directory containing `python`, `python3`, `python3.14`, `python3.15`, and
452/// `python3.15t`, an exact `3.15` request produces the following groups:
453///
454/// ```text
455/// [python3.15], [python3], [python]
456/// ```
457///
458/// A `>=3.14,<3.16` request instead produces:
459///
460/// ```text
461/// [python3], [python], [python3.14, python3.15, python3.15t]
462/// ```
463///
464/// Grouping minor-version fallback candidates from the same directory allows their queried
465/// installation keys to determine their relative order without overriding search-path precedence.
466///
467/// If a `version` is not provided, we will only look for default executable names e.g.
468/// `python3` and `python` — `python3.9` and similar will not be included.
469fn python_executables_from_search_path<'a>(
470    version: &'a VersionRequest,
471    implementation: Option<&'a ImplementationName>,
472) -> impl Iterator<Item = Vec<PathBuf>> + 'a {
473    // `UV_PYTHON_SEARCH_PATH` can be used to override `PATH` for Python executable discovery
474    let search_path = env::var_os(EnvVars::UV_PYTHON_SEARCH_PATH)
475        .unwrap_or(env::var_os(EnvVars::PATH).unwrap_or_default());
476
477    let possible_names: Vec<_> = version
478        .executable_names(implementation)
479        .into_iter()
480        .map(|name| name.to_string())
481        .collect();
482
483    trace!(
484        "Searching PATH for executables: {}",
485        possible_names.join(", ")
486    );
487
488    // Split and iterate over the paths instead of using `which_all` so we can
489    // check multiple names per directory while respecting the search path order and python names
490    // precedence.
491    let search_dirs: Vec<_> = env::split_paths(&search_path).collect();
492    let mut seen_dirs = FxHashSet::with_capacity_and_hasher(search_dirs.len(), FxBuildHasher);
493    search_dirs
494        .into_iter()
495        .filter(|dir| dir.is_dir())
496        .flat_map(move |dir| {
497            // Clone the directory for second closure
498            let dir_clone = dir.clone();
499            trace!(
500                "Checking `PATH` directory for interpreters: {}",
501                dir.display()
502            );
503            same_file::Handle::from_path(&dir)
504                // Skip directories we've already seen, to avoid inspecting interpreters multiple
505                // times when directories are repeated or symlinked in the `PATH`
506                .map(|handle| seen_dirs.insert(handle))
507                .inspect(|fresh_dir| {
508                    if !fresh_dir {
509                        trace!("Skipping already seen directory: {}", dir.display());
510                    }
511                })
512                // If we cannot determine if the directory is unique, we'll assume it is
513                .unwrap_or(true)
514                .then(|| {
515                    let minor_version_directory = dir_clone.clone();
516
517                    possible_names
518                        .clone()
519                        .into_iter()
520                        .flat_map(move |name| {
521                            // Since we're just working with a single directory at a time, we collect to simplify ownership
522                            which::which_in_global(&*name, Some(&dir))
523                                .into_iter()
524                                .flatten()
525                                .filter(|path| !is_windows_store_shim(path))
526                                .map(|path| vec![path])
527                                // We have to collect since `which` requires that the regex outlives its
528                                // parameters, and the dir is local while we return the iterator.
529                                .collect::<Vec<_>>()
530                        })
531                        .chain(
532                            iter::once_with(move || {
533                                find_all_minor(implementation, version, &minor_version_directory)
534                                    .filter(|path| !is_windows_store_shim(path))
535                                    .collect::<Vec<_>>()
536                            })
537                            .filter(|paths| !paths.is_empty()),
538                        )
539                        .inspect(|paths| {
540                            for path in paths {
541                                trace!("Found possible Python executable: {}", path.display());
542                            }
543                        })
544                        .chain(
545                            // TODO(zanieb): Consider moving `python.bat` into `possible_names` to avoid a chain
546                            cfg!(windows)
547                                .then(move || {
548                                    which::which_in_global("python.bat", Some(&dir_clone))
549                                        .into_iter()
550                                        .flatten()
551                                        .map(|path| vec![path])
552                                        .collect::<Vec<_>>()
553                                })
554                                .into_iter()
555                                .flatten(),
556                        )
557                })
558                .into_iter()
559                .flatten()
560        })
561}
562
563/// Find all acceptable `python3.x` minor versions.
564///
565/// For example, let's say `python` and `python3` are Python 3.10. When a user requests `>= 3.11`,
566/// we still need to find a `python3.12` in PATH.
567fn find_all_minor(
568    implementation: Option<&ImplementationName>,
569    version_request: &VersionRequest,
570    dir: &Path,
571) -> impl Iterator<Item = PathBuf> + use<> {
572    match version_request {
573        &VersionRequest::Any
574        | VersionRequest::Default
575        | VersionRequest::Major(_, _)
576        | VersionRequest::Range(_, _) => {
577            let regex = if let Some(implementation) = implementation {
578                Regex::new(&format!(
579                    r"^({}|python3)\.(?<minor>\d\d?)t?{}$",
580                    regex::escape(&implementation.to_string()),
581                    regex::escape(EXE_SUFFIX)
582                ))
583                .unwrap()
584            } else {
585                Regex::new(&format!(
586                    r"^python3\.(?<minor>\d\d?)t?{}$",
587                    regex::escape(EXE_SUFFIX)
588                ))
589                .unwrap()
590            };
591            let all_minors = fs_err::read_dir(dir)
592                .into_iter()
593                .flatten()
594                .flatten()
595                .map(|entry| entry.path())
596                .filter(move |path| {
597                    let Some(filename) = path.file_name() else {
598                        return false;
599                    };
600                    let Some(filename) = filename.to_str() else {
601                        return false;
602                    };
603                    let Some(captures) = regex.captures(filename) else {
604                        return false;
605                    };
606
607                    // Filter out interpreter we already know have a too low minor version.
608                    let minor = captures["minor"].parse().ok();
609                    if let Some(minor) = minor {
610                        // Optimization: Skip generally unsupported Python versions without querying.
611                        if minor < 6 {
612                            return false;
613                        }
614                        // Optimization 2: Skip excluded Python (minor) versions without querying.
615                        if !version_request.matches_major_minor(3, minor) {
616                            return false;
617                        }
618                    }
619                    true
620                })
621                .filter(|path| is_executable(path))
622                .collect::<Vec<_>>();
623            Either::Left(all_minors.into_iter())
624        }
625        VersionRequest::MajorMinor(_, _, _)
626        | VersionRequest::MajorMinorPatch(_, _, _, _)
627        | VersionRequest::MajorMinorPrerelease(_, _, _, _)
628        | VersionRequest::MajorMinorPatchPrerelease(_, _, _, _, _) => Either::Right(iter::empty()),
629    }
630}
631
632/// How to query discovered Python executables.
633#[derive(Debug, Clone, Copy)]
634enum QueryStrategy {
635    /// Lazily query one executable group at a time.
636    Sequential,
637    /// Query groups and their executables concurrently before yielding results.
638    Parallel,
639}
640
641/// Iterate over all discoverable Python interpreters.
642///
643/// Note interpreters may be excluded by the given [`EnvironmentPreference`], [`PythonPreference`],
644/// [`VersionRequest`], or [`PlatformRequest`].
645///
646/// The [`PlatformRequest`] is currently only applied to managed Python installations before querying
647/// the interpreter. The caller is responsible for ensuring it is applied otherwise.
648///
649/// See [`python_executables`] for more information on discovery.
650fn python_installations<'a>(
651    version: &'a VersionRequest,
652    implementation: Option<&'a ImplementationName>,
653    platform: PlatformRequest,
654    environments: EnvironmentPreference,
655    preference: PythonPreference,
656    cache: &'a Cache,
657    strategy: QueryStrategy,
658) -> Box<dyn Iterator<Item = Result<PythonInstallation, Error>> + 'a> {
659    Box::new(
660        python_installations_from_executables(
661            // Perform filtering on the discovered executables based on their source. This avoids
662            // unnecessary interpreter queries, which are generally expensive. We'll filter again
663            // with `PythonInstallation::satisfies_preferences` after querying.
664            python_executables(version, implementation, platform, environments, preference)
665                .filter_map(move |result| match result {
666                    Ok(group) => group
667                        .filter(|source, path| {
668                            source_satisfies_environment_preference(source, path, environments)
669                        })
670                        .map(Ok),
671                    Err(error) => Some(Err(error)),
672                }),
673            cache,
674            strategy,
675        )
676        .filter_ok(move |installation| {
677            installation.satisfies_preferences(version, environments, preference)
678                && platform.matches(&Platform::from(installation.interpreter.platform()))
679        })
680        .map_ok(PythonInstallation::maybe_with_test_source),
681    )
682}
683
684/// Query a single Python executable, returning a [`PythonInstallation`] on success.
685fn python_installation_from_executable(
686    source: PythonSource,
687    path: PathBuf,
688    cache: &Cache,
689) -> Result<PythonInstallation, Error> {
690    Interpreter::query(&path, cache)
691        .map(|interpreter| PythonInstallation {
692            source,
693            interpreter,
694        })
695        .inspect(|installation| {
696            debug!(
697                "Found `{}` at `{}` ({source})",
698                installation.key(),
699                path.display()
700            );
701        })
702        .map_err(|err| Error::Query(Box::new(err), path, source))
703        .inspect_err(|err| debug!("{err}"))
704}
705
706/// Convert Python executables into installations using the given query strategy.
707fn python_installations_from_executables<'a>(
708    executables: impl Iterator<Item = Result<PythonExecutableGroup, Error>> + 'a,
709    cache: &'a Cache,
710    strategy: QueryStrategy,
711) -> Box<dyn Iterator<Item = Result<PythonInstallation, Error>> + 'a> {
712    match strategy {
713        QueryStrategy::Sequential => Box::new(executables.flat_map(move |group| {
714            python_installations_from_executable_group(group, cache, strategy)
715        })),
716        QueryStrategy::Parallel => {
717            let items: Vec<Result<PythonExecutableGroup, Error>> = executables.collect();
718            let results: Vec<Vec<Result<PythonInstallation, Error>>> = items
719                .into_par_iter()
720                .map(|group| {
721                    python_installations_from_executable_group(group, cache, strategy)
722                        .collect::<Vec<_>>()
723                })
724                .collect();
725            Box::new(results.into_iter().flatten())
726        }
727    }
728}
729
730/// Query an executable group, ordering equally preferred installations by their installation keys.
731fn python_installations_from_executable_group(
732    group: Result<PythonExecutableGroup, Error>,
733    cache: &Cache,
734    strategy: QueryStrategy,
735) -> impl Iterator<Item = Result<PythonInstallation, Error>> + use<> {
736    match group {
737        Err(error) => Either::Left(iter::once(Err(error))),
738        Ok(PythonExecutableGroup(executables)) => {
739            let mut installations = match strategy {
740                QueryStrategy::Sequential => executables
741                    .into_iter()
742                    .map(|(source, path)| python_installation_from_executable(source, path, cache))
743                    .collect::<Vec<_>>(),
744                QueryStrategy::Parallel => executables
745                    .into_par_iter()
746                    .map(|(source, path)| python_installation_from_executable(source, path, cache))
747                    .collect::<Vec<_>>(),
748            };
749
750            sort_installations_by_key(&mut installations, PythonInstallation::key);
751
752            Either::Right(installations.into_iter())
753        }
754    }
755}
756
757/// Sort successful installations without moving them across critical query errors.
758fn sort_installations_by_key<T, K: Ord>(
759    installations: &mut [Result<T, Error>],
760    key: impl Fn(&T) -> K,
761) {
762    // Critical errors preserve discovery order; non-critical errors must not interrupt
763    // installation-key ordering and can follow successful queries.
764    for candidates in
765        installations.split_mut(|result| result.as_ref().is_err_and(Error::is_critical))
766    {
767        candidates.sort_by_key(|result| Reverse(result.as_ref().ok().map(&key)));
768    }
769}
770
771/// Returns true if a [`PythonSource`] could satisfy the [`EnvironmentPreference`].
772///
773/// This is useful as a pre-filtering step. Use of [`PythonInstallation::satisfies_environment_preference`]
774/// is required to determine if an [`Interpreter`] satisfies the preference.
775///
776/// The interpreter path is only used for debug messages.
777fn source_satisfies_environment_preference(
778    source: PythonSource,
779    interpreter_path: &Path,
780    preference: EnvironmentPreference,
781) -> bool {
782    match preference {
783        EnvironmentPreference::Any => true,
784        EnvironmentPreference::OnlyVirtual => {
785            if source.is_maybe_virtualenv() {
786                true
787            } else {
788                debug!(
789                    "Ignoring Python interpreter at `{}`: only virtual environments allowed",
790                    interpreter_path.display()
791                );
792                false
793            }
794        }
795        EnvironmentPreference::ExplicitSystem => {
796            if source.is_maybe_virtualenv() {
797                true
798            } else {
799                debug!(
800                    "Ignoring Python interpreter at `{}`: system interpreter not explicitly requested",
801                    interpreter_path.display()
802                );
803                false
804            }
805        }
806        EnvironmentPreference::OnlySystem => {
807            if source.is_maybe_system() {
808                true
809            } else {
810                debug!(
811                    "Ignoring Python interpreter at `{}`: system interpreter required",
812                    interpreter_path.display()
813                );
814                false
815            }
816        }
817    }
818}
819
820/// Check if an encountered error is critical and should stop discovery.
821///
822/// Returns false when an error could be due to a faulty Python installation and we should continue searching for a working one.
823impl Error {
824    pub(crate) fn is_critical(&self) -> bool {
825        match self {
826            // When querying the Python interpreter fails, we will only raise errors that demonstrate that something is broken
827            // If the Python interpreter returned a bad response, we'll continue searching for one that works
828            Self::Query(err, _, source) => match &**err {
829                InterpreterError::Encode(_)
830                | InterpreterError::Io(_)
831                | InterpreterError::CpuDetection(_)
832                | InterpreterError::SpawnFailed { .. } => true,
833                InterpreterError::UnexpectedResponse(UnexpectedResponseError { path, .. })
834                | InterpreterError::StatusCode(StatusCodeError { path, .. }) => {
835                    debug!(
836                        "Skipping bad interpreter at `{}` from {source}: {err}",
837                        path.display()
838                    );
839                    false
840                }
841                InterpreterError::QueryScript { path, err } => {
842                    debug!(
843                        "Skipping bad interpreter at `{}` from {source}: {err}",
844                        path.display()
845                    );
846                    false
847                }
848                #[cfg(windows)]
849                InterpreterError::CorruptWindowsPackage { path, err } => {
850                    debug!(
851                        "Skipping bad interpreter at `{}` from {source}: {err}",
852                        path.display()
853                    );
854                    false
855                }
856                InterpreterError::PermissionDenied { path, err } => {
857                    debug!(
858                        "Skipping unexecutable interpreter at `{}` from {source}: {err}",
859                        path.display()
860                    );
861                    false
862                }
863                InterpreterError::NotFound(path)
864                | InterpreterError::BrokenLink(BrokenLink { path, .. }) => {
865                    // If the interpreter is from an active, valid virtual environment, we should
866                    // fail because it's broken
867                    if matches!(source, PythonSource::ActiveEnvironment)
868                        && uv_fs::is_virtualenv_executable(path)
869                    {
870                        true
871                    } else {
872                        trace!("Skipping missing interpreter at `{}`", path.display());
873                        false
874                    }
875                }
876            },
877            Self::VirtualEnv(VirtualEnvError::MissingPyVenvCfg(path)) => {
878                trace!("Skipping broken virtualenv at `{}`", path.display());
879                false
880            }
881            _ => true,
882        }
883    }
884}
885
886/// Create a [`PythonInstallation`] from a Python installation root directory.
887fn python_installation_from_directory(
888    path: &PathBuf,
889    cache: &Cache,
890) -> Result<PythonInstallation, uv_python_interpreter::InterpreterError> {
891    let executable = virtualenv_python_executable(path);
892    Ok(PythonInstallation {
893        source: PythonSource::ProvidedPath,
894        interpreter: Interpreter::query(&executable, cache)?,
895    })
896}
897
898/// Lazily iterate over all Python executable paths on the path with the given executable name.
899fn python_executables_with_name(
900    name: &str,
901) -> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + '_ {
902    which_all(name)
903        .into_iter()
904        .flat_map(|inner| inner.map(|path| Ok((PythonSource::SearchPath, path))))
905}
906
907/// Lazily iterate over all Python installations on the path with the given executable name.
908fn python_installations_with_name<'a>(
909    name: &'a str,
910    cache: &'a Cache,
911    strategy: QueryStrategy,
912) -> Box<dyn Iterator<Item = Result<PythonInstallation, Error>> + 'a> {
913    python_installations_from_executables(
914        python_executables_with_name(name)
915            .map_ok(|executable| PythonExecutableGroup(vec![executable])),
916        cache,
917        strategy,
918    )
919}
920
921/// Iterate over all Python installations that satisfy the given request.
922pub(crate) fn find_python_installations<'a>(
923    request: &'a PythonRequest,
924    environments: EnvironmentPreference,
925    preference: PythonPreference,
926    arch: Option<PythonArchitecture>,
927    cache: &'a Cache,
928) -> Box<dyn Iterator<Item = Result<FindPythonResult, Error>> + 'a> {
929    find_python_installations_with_strategy(
930        request,
931        environments,
932        preference,
933        arch,
934        cache,
935        QueryStrategy::Sequential,
936    )
937}
938
939/// Iterate over all Python installations that satisfy the given request using the given query
940/// strategy.
941fn find_python_installations_with_strategy<'a>(
942    request: &'a PythonRequest,
943    environments: EnvironmentPreference,
944    preference: PythonPreference,
945    arch: Option<PythonArchitecture>,
946    cache: &'a Cache,
947    strategy: QueryStrategy,
948) -> Box<dyn Iterator<Item = Result<FindPythonResult, Error>> + 'a> {
949    let arch = arch.map(|arch| {
950        PythonDownloadRequest::from_request(request)
951            .and_then(|request| request.arch().map(ArchRequest::inner))
952            .unwrap_or_else(|| arch.into_inner())
953    });
954    let platform = PlatformRequest::default().with_default_arch(arch);
955    let sources = DiscoveryPreferences {
956        python_preference: preference,
957        environment_preference: environments,
958    }
959    .sources(request);
960
961    match request {
962        PythonRequest::File(path) => Box::new(iter::once({
963            if preference.allows_source(PythonSource::ProvidedPath) {
964                debug!("Checking for Python interpreter at {request}");
965                match Interpreter::query(path, cache) {
966                    Ok(interpreter) => Ok(Ok(PythonInstallation {
967                        source: PythonSource::ProvidedPath,
968                        interpreter,
969                    })),
970                    Err(InterpreterError::NotFound(_) | InterpreterError::BrokenLink(_)) => {
971                        Ok(Err(PythonNotFound {
972                            request: request.clone(),
973                            python_preference: preference,
974                            environment_preference: environments,
975                        }))
976                    }
977                    Err(err) => Err(Error::Query(
978                        Box::new(err),
979                        path.clone(),
980                        PythonSource::ProvidedPath,
981                    )),
982                }
983            } else {
984                Err(Error::SourceNotAllowed(
985                    request.clone(),
986                    PythonSource::ProvidedPath,
987                    preference,
988                ))
989            }
990        })),
991        PythonRequest::Directory(path) => Box::new(iter::once({
992            if preference.allows_source(PythonSource::ProvidedPath) {
993                debug!("Checking for Python interpreter in {request}");
994                match python_installation_from_directory(path, cache) {
995                    Ok(installation) => Ok(Ok(installation)),
996                    Err(InterpreterError::NotFound(_) | InterpreterError::BrokenLink(_)) => {
997                        Ok(Err(PythonNotFound {
998                            request: request.clone(),
999                            python_preference: preference,
1000                            environment_preference: environments,
1001                        }))
1002                    }
1003                    Err(err) => Err(Error::Query(
1004                        Box::new(err),
1005                        path.clone(),
1006                        PythonSource::ProvidedPath,
1007                    )),
1008                }
1009            } else {
1010                Err(Error::SourceNotAllowed(
1011                    request.clone(),
1012                    PythonSource::ProvidedPath,
1013                    preference,
1014                ))
1015            }
1016        })),
1017        PythonRequest::ExecutableName(name) => {
1018            if preference.allows_source(PythonSource::SearchPath) {
1019                debug!("Searching for Python interpreter with {request}");
1020                Box::new(
1021                    python_installations_with_name(name, cache, strategy)
1022                        .filter_ok(move |installation| {
1023                            installation.satisfies_environment_preference(environments)
1024                        })
1025                        .map_ok(Ok),
1026                )
1027            } else {
1028                Box::new(iter::once(Err(Error::SourceNotAllowed(
1029                    request.clone(),
1030                    PythonSource::SearchPath,
1031                    preference,
1032                ))))
1033            }
1034        }
1035        PythonRequest::Any => Box::new({
1036            debug!("Searching for any Python interpreter in {sources}");
1037            python_installations(
1038                &VersionRequest::Any,
1039                None,
1040                platform,
1041                environments,
1042                preference,
1043                cache,
1044                strategy,
1045            )
1046            .map_ok(Ok)
1047        }),
1048        PythonRequest::Default => Box::new({
1049            debug!("Searching for default Python interpreter in {sources}");
1050            python_installations(
1051                &VersionRequest::Default,
1052                None,
1053                platform,
1054                environments,
1055                preference,
1056                cache,
1057                strategy,
1058            )
1059            .map_ok(Ok)
1060        }),
1061        PythonRequest::Version(version) => {
1062            if let Err(err) = version.check_supported() {
1063                return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1064            }
1065            Box::new({
1066                debug!("Searching for {request} in {sources}");
1067                python_installations(
1068                    version,
1069                    None,
1070                    platform,
1071                    environments,
1072                    preference,
1073                    cache,
1074                    strategy,
1075                )
1076                .map_ok(Ok)
1077            })
1078        }
1079        PythonRequest::Implementation(implementation) => Box::new({
1080            debug!("Searching for a {request} interpreter in {sources}");
1081            python_installations(
1082                &VersionRequest::Default,
1083                Some(implementation),
1084                platform,
1085                environments,
1086                preference,
1087                cache,
1088                strategy,
1089            )
1090            .filter_ok(move |installation| {
1091                installation
1092                    .interpreter
1093                    .matches_implementation(*implementation)
1094            })
1095            .map_ok(Ok)
1096        }),
1097        PythonRequest::ImplementationVersion(implementation, version) => {
1098            if let Err(err) = version.check_supported() {
1099                return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1100            }
1101            Box::new({
1102                debug!("Searching for {request} in {sources}");
1103                python_installations(
1104                    version,
1105                    Some(implementation),
1106                    platform,
1107                    environments,
1108                    preference,
1109                    cache,
1110                    strategy,
1111                )
1112                .filter_ok(move |installation| {
1113                    installation
1114                        .interpreter
1115                        .matches_implementation(*implementation)
1116                })
1117                .map_ok(Ok)
1118            })
1119        }
1120        PythonRequest::Key(request) => {
1121            if let Some(version) = request.version()
1122                && let Err(err) = version.check_supported()
1123            {
1124                return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1125            }
1126
1127            Box::new({
1128                debug!("Searching for {request} in {sources}");
1129                python_installations(
1130                    request.version().unwrap_or(&VersionRequest::Default),
1131                    request.implementation(),
1132                    request.platform().with_default_arch(arch),
1133                    environments,
1134                    preference,
1135                    cache,
1136                    strategy,
1137                )
1138                .filter_ok(move |installation| {
1139                    installation.interpreter.matches_download_request(request)
1140                })
1141                .map_ok(Ok)
1142            })
1143        }
1144    }
1145}
1146
1147/// Find all Python installations that satisfy the given request, querying interpreters
1148/// concurrently.
1149///
1150/// Eagerly collects matching installations. Interpreter query failures produce warnings and are
1151/// skipped. Other non-critical discovery errors are dropped, while critical errors are propagated in
1152/// discovery order.
1153pub fn find_all_python_installations(
1154    request: &PythonRequest,
1155    environments: EnvironmentPreference,
1156    preference: PythonPreference,
1157    arch: Option<PythonArchitecture>,
1158    cache: &Cache,
1159) -> Result<Vec<PythonInstallation>, Error> {
1160    let results = find_python_installations_with_strategy(
1161        request,
1162        environments,
1163        preference,
1164        arch,
1165        cache,
1166        QueryStrategy::Parallel,
1167    );
1168    let mut installations = Vec::new();
1169    for result in results {
1170        match result {
1171            Ok(Ok(installation)) => installations.push(installation),
1172            Ok(Err(_)) => {}
1173            Err(err @ Error::Query(..)) => {
1174                warn_user_with_chain!(&err);
1175            }
1176            Err(err) if err.is_critical() => return Err(err),
1177            Err(_) => {}
1178        }
1179    }
1180    Ok(installations)
1181}
1182
1183/// Find a Python installation that satisfies the given request.
1184///
1185/// If an error is encountered while locating or inspecting a candidate installation,
1186/// the error will raised instead of attempting further candidates.
1187pub(crate) fn find_python_installation(
1188    request: &PythonRequest,
1189    environments: EnvironmentPreference,
1190    preference: PythonPreference,
1191    arch: Option<PythonArchitecture>,
1192    cache: &Cache,
1193) -> Result<FindPythonResult, Error> {
1194    let installations = find_python_installations(request, environments, preference, arch, cache);
1195    let mut first_prerelease = None;
1196    let mut first_debug = None;
1197    let mut first_managed = None;
1198    let mut first_error = None;
1199    for result in installations {
1200        // Iterate until the first critical error or happy result
1201        if !result.as_ref().err().is_none_or(Error::is_critical) {
1202            // Track the first non-critical error
1203            if first_error.is_none()
1204                && let Err(err) = result
1205            {
1206                first_error = Some(err);
1207            }
1208            continue;
1209        }
1210
1211        // If it's an error, we're done.
1212        let Ok(Ok(installation)) = result else {
1213            return result;
1214        };
1215
1216        // Check if we need to skip the interpreter because it is "not allowed", e.g., if it is a
1217        // pre-release version or an alternative implementation, using it requires opt-in.
1218
1219        // If the interpreter has a default executable name, e.g. `python`, and was found on the
1220        // search path, we consider this opt-in to use it.
1221        let has_default_executable_name = installation.interpreter.has_default_executable_name()
1222            && matches!(
1223                installation.source,
1224                PythonSource::SearchPath | PythonSource::SearchPathFirst
1225            );
1226
1227        // If it's a pre-release and pre-releases aren't allowed, skip it — but store it for later
1228        // since we'll use a pre-release if no other versions are available.
1229        if installation.python_version().pre().is_some()
1230            && !request.allows_prereleases()
1231            && !installation.source.allows_prereleases()
1232            && !has_default_executable_name
1233        {
1234            debug!("Skipping pre-release installation {}", installation.key());
1235            if first_prerelease.is_none() {
1236                first_prerelease = Some(installation);
1237            }
1238            continue;
1239        }
1240
1241        // If it's a debug build and debug builds aren't allowed, skip it — but store it for later
1242        // since we'll use a debug build if no other versions are available.
1243        if installation.key().variant().is_debug()
1244            && !request.allows_debug()
1245            && !installation.source.allows_debug()
1246            && !has_default_executable_name
1247        {
1248            debug!("Skipping debug installation {}", installation.key());
1249            if first_debug.is_none() {
1250                first_debug = Some(installation);
1251            }
1252            continue;
1253        }
1254
1255        // If it's an alternative implementation and alternative implementations aren't allowed,
1256        // skip it. Note we avoid querying these interpreters at all if they're on the search path
1257        // and are not requested, but other sources such as the managed installations can include
1258        // them.
1259        if installation.is_alternative_implementation()
1260            && !request.allows_alternative_implementations()
1261            && !installation.source.allows_alternative_implementations()
1262            && !has_default_executable_name
1263        {
1264            debug!("Skipping alternative implementation {}", installation.key());
1265            continue;
1266        }
1267
1268        // If it's a managed Python installation, and system interpreters are preferred, skip it
1269        // for now.
1270        if matches!(preference, PythonPreference::System) && installation.is_managed() {
1271            debug!(
1272                "Skipping managed installation {}: system installation preferred",
1273                installation.key()
1274            );
1275            if first_managed.is_none() {
1276                first_managed = Some(installation);
1277            }
1278            continue;
1279        }
1280
1281        // If we didn't skip it, this is the installation to use
1282        return Ok(Ok(installation));
1283    }
1284
1285    // If we only found managed installations, and the preference allows them, we should return
1286    // the first one.
1287    if let Some(installation) = first_managed {
1288        debug!(
1289            "Allowing managed installation {}: no system installations",
1290            installation.key()
1291        );
1292        return Ok(Ok(installation));
1293    }
1294
1295    // If we only found debug installations, they're implicitly allowed and we should return the
1296    // first one.
1297    if let Some(installation) = first_debug {
1298        debug!(
1299            "Allowing debug installation {}: no non-debug installations",
1300            installation.key()
1301        );
1302        return Ok(Ok(installation));
1303    }
1304
1305    // If we only found pre-releases, they're implicitly allowed and we should return the first one.
1306    if let Some(installation) = first_prerelease {
1307        debug!(
1308            "Allowing pre-release installation {}: no stable installations",
1309            installation.key()
1310        );
1311        return Ok(Ok(installation));
1312    }
1313
1314    // If we found a Python, but it was unusable for some reason, report that instead of saying we
1315    // couldn't find any Python interpreters.
1316    if let Some(err) = first_error {
1317        return Err(err);
1318    }
1319
1320    Ok(Err(PythonNotFound {
1321        request: request
1322            .with_default_arch(arch.map(PythonArchitecture::into_inner))
1323            .into_owned(),
1324        environment_preference: environments,
1325        python_preference: preference,
1326    }))
1327}
1328
1329/// Find the best-matching Python installation.
1330///
1331/// If no Python version is provided, we will use the first available installation.
1332///
1333/// If a Python version is provided, we will first try to find an exact match. If
1334/// that cannot be found and a patch version was requested, we will look for a match
1335/// without comparing the patch version number. If that cannot be found, we fall back to
1336/// the first available version.
1337///
1338/// At all points, if the specified version cannot be found, we will attempt to
1339/// download it if downloads are enabled.
1340///
1341/// See [`find_python_installation`] for more details on installation discovery.
1342#[instrument(skip_all, fields(request))]
1343pub(crate) async fn find_best_python_installation(
1344    request: &PythonRequest,
1345    environments: EnvironmentPreference,
1346    preference: PythonPreference,
1347    arch: Option<PythonArchitecture>,
1348    downloads_enabled: bool,
1349    client_builder: &BaseClientBuilder<'_>,
1350    cache: &Cache,
1351    reporter: Option<&dyn uv_python_managed::downloads::Reporter>,
1352    mirrors: PythonDownloadMirrors<'_>,
1353    python_downloads_json_url: Option<&str>,
1354) -> Result<PythonInstallation, crate::Error> {
1355    debug!("Starting Python discovery for {request}");
1356    let original_request = request;
1357
1358    let mut previous_fetch_failed = false;
1359    let mut download_state = None;
1360
1361    let request_without_patch = match request {
1362        PythonRequest::Version(version) => {
1363            if version.has_patch() {
1364                Some(PythonRequest::Version(version.clone().without_patch()))
1365            } else {
1366                None
1367            }
1368        }
1369        PythonRequest::ImplementationVersion(implementation, version) => Some(
1370            PythonRequest::ImplementationVersion(*implementation, version.clone().without_patch()),
1371        ),
1372        _ => None,
1373    };
1374
1375    for (attempt, request) in iter::once(original_request)
1376        .chain(request_without_patch.iter())
1377        .chain(iter::once(&PythonRequest::Default))
1378        .enumerate()
1379    {
1380        debug!(
1381            "Looking for {request}{}",
1382            if request != original_request {
1383                format!(" attempt {attempt} (fallback after failing to find: {original_request})")
1384            } else {
1385                String::new()
1386            }
1387        );
1388        let result = find_python_installation(request, environments, preference, arch, cache);
1389        let error = match result {
1390            Ok(Ok(installation)) => {
1391                warn_on_unsupported_python(installation.interpreter());
1392                return Ok(installation);
1393            }
1394            // Continue if we can't find a matching Python and ignore non-critical discovery errors
1395            Ok(Err(error)) => error.into(),
1396            Err(error) if !error.is_critical() => error.into(),
1397            Err(error) => return Err(error.into()),
1398        };
1399
1400        // Attempt to download the version if downloads are enabled
1401        if downloads_enabled
1402            && !previous_fetch_failed
1403            && let Some(download_request) = PythonDownloadRequest::from_request(request)
1404        {
1405            let (client, retry_policy, download_list) =
1406                if let Some(download_state) = &mut download_state {
1407                    download_state
1408                } else {
1409                    let download_list = ManagedPythonDownloadList::new(
1410                        client_builder,
1411                        cache,
1412                        python_downloads_json_url,
1413                    )
1414                    .await?;
1415                    let retry_policy = client_builder.retry_policy();
1416
1417                    // Python downloads are performing their own retries to catch stream errors, disable
1418                    // the default retries to avoid the middleware performing uncontrolled retries.
1419                    let client = client_builder.clone().retries(0).build()?;
1420                    download_state.insert((client, retry_policy, download_list))
1421                };
1422
1423            let download = download_request
1424                .clone()
1425                .with_default_arch(arch.map(PythonArchitecture::into_inner))
1426                .fill()
1427                .map(|request| download_list.find(&request));
1428
1429            let result = match download {
1430                Ok(Ok(download)) => PythonInstallation::fetch(
1431                    download,
1432                    client,
1433                    retry_policy,
1434                    cache,
1435                    reporter,
1436                    mirrors,
1437                )
1438                .await
1439                .map(Some),
1440                Ok(Err(uv_python_managed::downloads::Error::NoDownloadFound(_))) => Ok(None),
1441                Ok(Err(error)) => Err(error.into()),
1442                Err(error) => Err(error.into()),
1443            };
1444            if let Ok(Some(installation)) = result {
1445                return Ok(installation);
1446            }
1447            // Emit a warning instead of failing since we may find a suitable
1448            // interpreter on the system after relaxing the request further.
1449            // Additionally, uv did not previously attempt downloads in this
1450            // code path and we want to minimize the fatal cases for
1451            // backwards compatibility.
1452            // Errors encountered here are either network errors or quirky
1453            // configuration problems.
1454            if let Err(error) = result {
1455                // If the request was for the default or any version, propagate
1456                // the error as nothing else we are about to do will help the
1457                // situation.
1458                if matches!(request, PythonRequest::Default | PythonRequest::Any) {
1459                    return Err(error);
1460                }
1461
1462                warn_user_with_chain!(
1463                    anyhow::Error::from(error)
1464                        .context(format!(
1465                            "A managed Python download is available for {request}, but an error occurred when attempting to download it."
1466                        ))
1467                        .as_ref()
1468                );
1469                previous_fetch_failed = true;
1470            }
1471        }
1472
1473        // If this was a request for the Default or Any version, this means that
1474        // either that's what we were called with, or we're on the last
1475        // iteration.
1476        //
1477        // The most recent find error therefore becomes a fatal one.
1478        if matches!(request, PythonRequest::Default | PythonRequest::Any) {
1479            return Err(match error {
1480                crate::Error::MissingPython(err, _) => PythonNotFound {
1481                    // Use a more general error in this case since we looked for multiple versions
1482                    request: original_request
1483                        .with_default_arch(arch.map(PythonArchitecture::into_inner))
1484                        .into_owned(),
1485                    python_preference: err.python_preference,
1486                    environment_preference: err.environment_preference,
1487                }
1488                .into(),
1489                other => other,
1490            });
1491        }
1492    }
1493
1494    unreachable!("The loop should have terminated when it reached PythonRequest::Default");
1495}
1496
1497/// Display a warning if the Python version of the [`Interpreter`] is unsupported by uv.
1498fn warn_on_unsupported_python(interpreter: &Interpreter) {
1499    // Warn on usage with an unsupported Python version
1500    if interpreter.python_tuple() < (3, 8) {
1501        warn_user_once!(
1502            "uv is only compatible with Python >=3.8, found Python {}",
1503            interpreter.python_version()
1504        );
1505    }
1506}
1507
1508/// On Windows we might encounter the Windows Store proxy shim (enabled in:
1509/// Settings/Apps/Advanced app settings/App execution aliases). When Python is _not_ installed
1510/// via the Windows Store, but the proxy shim is enabled, then executing `python.exe` or
1511/// `python3.exe` will redirect to the Windows Store installer.
1512///
1513/// We need to detect that these `python.exe` and `python3.exe` files are _not_ Python
1514/// executables.
1515///
1516/// This method is taken from Rye:
1517///
1518/// > This is a pretty dumb way.  We know how to parse this reparse point, but Microsoft
1519/// > does not want us to do this as the format is unstable.  So this is a best effort way.
1520/// > we just hope that the reparse point has the python redirector in it, when it's not
1521/// > pointing to a valid Python.
1522///
1523/// See: <https://github.com/astral-sh/rye/blob/b0e9eccf05fe4ff0ae7b0250a248c54f2d780b4d/rye/src/cli/shim.rs#L108>
1524#[cfg(windows)]
1525fn is_windows_store_shim(path: &Path) -> bool {
1526    use std::os::windows::fs::MetadataExt;
1527    use std::os::windows::prelude::OsStrExt;
1528    use windows::Win32::Foundation::CloseHandle;
1529    use windows::Win32::Storage::FileSystem::{
1530        CreateFileW, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
1531        FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_MODE, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
1532        OPEN_EXISTING,
1533    };
1534    use windows::Win32::System::IO::DeviceIoControl;
1535    use windows::Win32::System::Ioctl::FSCTL_GET_REPARSE_POINT;
1536    use windows::core::PCWSTR;
1537
1538    // The path must be absolute.
1539    if !path.is_absolute() {
1540        return false;
1541    }
1542
1543    // The path must point to something like:
1544    //   `C:\Users\crmar\AppData\Local\Microsoft\WindowsApps\python3.exe`
1545    let mut components = path.components().rev();
1546
1547    // Ex) `python.exe`, `python3.exe`, `python3.12.exe`, etc.
1548    if !components
1549        .next()
1550        .and_then(|component| component.as_os_str().to_str())
1551        .is_some_and(|component| {
1552            component.starts_with("python")
1553                && std::path::Path::new(component)
1554                    .extension()
1555                    .is_some_and(|ext| ext.eq_ignore_ascii_case("exe"))
1556        })
1557    {
1558        return false;
1559    }
1560
1561    // Ex) `WindowsApps`
1562    if components
1563        .next()
1564        .is_none_or(|component| component.as_os_str() != "WindowsApps")
1565    {
1566        return false;
1567    }
1568
1569    // Ex) `Microsoft`
1570    if components
1571        .next()
1572        .is_none_or(|component| component.as_os_str() != "Microsoft")
1573    {
1574        return false;
1575    }
1576
1577    // The file is only relevant if it's a reparse point.
1578    let Ok(md) = fs_err::symlink_metadata(path) else {
1579        return false;
1580    };
1581    if md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 == 0 {
1582        return false;
1583    }
1584
1585    let mut path_encoded = path
1586        .as_os_str()
1587        .encode_wide()
1588        .chain(std::iter::once(0))
1589        .collect::<Vec<_>>();
1590
1591    // SAFETY: The path is null-terminated.
1592    #[allow(unsafe_code)]
1593    let reparse_handle = unsafe {
1594        CreateFileW(
1595            PCWSTR(path_encoded.as_mut_ptr()),
1596            0,
1597            FILE_SHARE_MODE(0),
1598            None,
1599            OPEN_EXISTING,
1600            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1601            None,
1602        )
1603    };
1604
1605    let Ok(reparse_handle) = reparse_handle else {
1606        return false;
1607    };
1608
1609    let mut buf = [0u16; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
1610    let mut bytes_returned = 0;
1611
1612    // SAFETY: The buffer is large enough to hold the reparse point.
1613    #[allow(unsafe_code, clippy::cast_possible_truncation)]
1614    let success = unsafe {
1615        DeviceIoControl(
1616            reparse_handle,
1617            FSCTL_GET_REPARSE_POINT,
1618            None,
1619            0,
1620            Some(buf.as_mut_ptr().cast()),
1621            buf.len() as u32 * 2,
1622            Some(&raw mut bytes_returned),
1623            None,
1624        )
1625        .is_ok()
1626    };
1627
1628    // SAFETY: The handle is valid.
1629    #[allow(unsafe_code)]
1630    unsafe {
1631        let _ = CloseHandle(reparse_handle);
1632    }
1633
1634    // If the operation failed, assume it's not a reparse point.
1635    if !success {
1636        return false;
1637    }
1638
1639    let reparse_point = String::from_utf16_lossy(&buf[..bytes_returned as usize]);
1640    reparse_point.contains("\\AppInstallerPythonRedirector.exe")
1641}
1642
1643/// On Unix, we do not need to deal with Windows store shims.
1644///
1645/// See the Windows implementation for details.
1646#[cfg(not(windows))]
1647fn is_windows_store_shim(_path: &Path) -> bool {
1648    false
1649}
1650
1651impl DiscoveryPreferences {
1652    /// Return a string describing the sources that are considered when searching for Python with
1653    /// the given preferences.
1654    fn sources(&self, request: &PythonRequest) -> String {
1655        let python_sources = self
1656            .python_preference
1657            .sources()
1658            .iter()
1659            .map(ToString::to_string)
1660            .collect::<Vec<_>>();
1661        match self.environment_preference {
1662            EnvironmentPreference::Any => disjunction(
1663                &["virtual environments"]
1664                    .into_iter()
1665                    .chain(python_sources.iter().map(String::as_str))
1666                    .collect::<Vec<_>>(),
1667            ),
1668            EnvironmentPreference::ExplicitSystem => {
1669                if request.is_explicit_system() {
1670                    disjunction(
1671                        &["virtual environments"]
1672                            .into_iter()
1673                            .chain(python_sources.iter().map(String::as_str))
1674                            .collect::<Vec<_>>(),
1675                    )
1676                } else {
1677                    disjunction(&["virtual environments"])
1678                }
1679            }
1680            EnvironmentPreference::OnlySystem => disjunction(
1681                &python_sources
1682                    .iter()
1683                    .map(String::as_str)
1684                    .collect::<Vec<_>>(),
1685            ),
1686            EnvironmentPreference::OnlyVirtual => disjunction(&["virtual environments"]),
1687        }
1688    }
1689}
1690
1691impl fmt::Display for PythonNotFound {
1692    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1693        let sources = DiscoveryPreferences {
1694            python_preference: self.python_preference,
1695            environment_preference: self.environment_preference,
1696        }
1697        .sources(&self.request);
1698
1699        match self.request {
1700            PythonRequest::Default | PythonRequest::Any => {
1701                write!(f, "No interpreter found in {sources}")
1702            }
1703            PythonRequest::File(_) => {
1704                write!(f, "No interpreter found at {}", self.request)
1705            }
1706            PythonRequest::Directory(_) => {
1707                write!(f, "No interpreter found in {}", self.request)
1708            }
1709            _ => {
1710                write!(f, "No interpreter found for {} in {sources}", self.request)
1711            }
1712        }
1713    }
1714}
1715
1716/// Join a series of items with `or` separators, making use of commas when necessary.
1717fn disjunction(items: &[&str]) -> String {
1718    match items.len() {
1719        0 => String::new(),
1720        1 => items[0].to_string(),
1721        2 => format!("{} or {}", items[0], items[1]),
1722        _ => {
1723            let last = items.last().unwrap();
1724            format!(
1725                "{}, or {}",
1726                items.iter().take(items.len() - 1).join(", "),
1727                last
1728            )
1729        }
1730    }
1731}
1732
1733#[cfg(test)]
1734mod tests {
1735    use std::assert_matches;
1736    use std::{cell::Cell, io, path::PathBuf};
1737
1738    use test_log::test;
1739    use uv_cache::Cache;
1740
1741    use uv_python_types::PythonRequest;
1742
1743    use super::{
1744        DiscoveryPreferences, EnvironmentPreference, Error, InterpreterError,
1745        PythonExecutableGroup, PythonPreference, PythonSource, QueryStrategy,
1746        python_installations_from_executables, sort_installations_by_key,
1747    };
1748
1749    // Testing this at a higher level would necessitate relying on filesystem ordering.
1750    #[test]
1751    fn installation_key_order_only_partitions_critical_errors() {
1752        let query_error = |error| {
1753            Error::Query(
1754                Box::new(error),
1755                PathBuf::from("python"),
1756                PythonSource::SearchPath,
1757            )
1758        };
1759
1760        let mut installations = [
1761            Ok(1_u8),
1762            Err(query_error(InterpreterError::NotFound(PathBuf::from(
1763                "missing",
1764            )))),
1765            Ok(2),
1766            Err(query_error(InterpreterError::Io(io::Error::other(
1767                "critical",
1768            )))),
1769            Ok(3),
1770        ];
1771
1772        sort_installations_by_key(&mut installations, |key| *key);
1773
1774        assert_matches!(
1775            &installations[..],
1776            [Ok(2), Ok(1), Err(noncritical), Err(critical), Ok(3)]
1777                if !noncritical.is_critical() && critical.is_critical()
1778        );
1779    }
1780
1781    #[test]
1782    fn sequential_query_strategy_does_not_prefetch_executable_groups() -> anyhow::Result<()> {
1783        let cache = Cache::temp()?;
1784        let pulls = Cell::new(0);
1785        let executables = (0..2).map(|_| {
1786            pulls.set(pulls.get() + 1);
1787            Err::<PythonExecutableGroup, _>(Error::SourceNotAllowed(
1788                PythonRequest::Default,
1789                PythonSource::SearchPath,
1790                PythonPreference::OnlyManaged,
1791            ))
1792        });
1793
1794        let mut installations =
1795            python_installations_from_executables(executables, &cache, QueryStrategy::Sequential);
1796
1797        assert_eq!(pulls.get(), 0);
1798        assert!(installations.next().is_some_and(|result| result.is_err()));
1799        assert_eq!(pulls.get(), 1);
1800
1801        Ok(())
1802    }
1803
1804    #[test]
1805    fn discovery_sources_prefer_system_orders_search_path_first() {
1806        let preferences = DiscoveryPreferences {
1807            python_preference: PythonPreference::System,
1808            environment_preference: EnvironmentPreference::OnlySystem,
1809        };
1810        let sources = preferences.sources(&PythonRequest::Default);
1811
1812        if cfg!(windows) {
1813            assert_eq!(sources, "search path, registry, or managed installations");
1814        } else {
1815            assert_eq!(sources, "search path or managed installations");
1816        }
1817    }
1818
1819    #[test]
1820    fn discovery_sources_only_system_matches_platform_order() {
1821        let preferences = DiscoveryPreferences {
1822            python_preference: PythonPreference::OnlySystem,
1823            environment_preference: EnvironmentPreference::OnlySystem,
1824        };
1825        let sources = preferences.sources(&PythonRequest::Default);
1826
1827        if cfg!(windows) {
1828            assert_eq!(sources, "search path or registry");
1829        } else {
1830            assert_eq!(sources, "search path");
1831        }
1832    }
1833}