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