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::SpawnFailed { .. } => true,
832                InterpreterError::UnexpectedResponse(UnexpectedResponseError { path, .. })
833                | InterpreterError::StatusCode(StatusCodeError { path, .. }) => {
834                    debug!(
835                        "Skipping bad interpreter at `{}` from {source}: {err}",
836                        path.display()
837                    );
838                    false
839                }
840                InterpreterError::QueryScript { path, err } => {
841                    debug!(
842                        "Skipping bad interpreter at `{}` from {source}: {err}",
843                        path.display()
844                    );
845                    false
846                }
847                #[cfg(windows)]
848                InterpreterError::CorruptWindowsPackage { path, err } => {
849                    debug!(
850                        "Skipping bad interpreter at `{}` from {source}: {err}",
851                        path.display()
852                    );
853                    false
854                }
855                InterpreterError::PermissionDenied { path, err } => {
856                    debug!(
857                        "Skipping unexecutable interpreter at `{}` from {source}: {err}",
858                        path.display()
859                    );
860                    false
861                }
862                InterpreterError::NotFound(path)
863                | InterpreterError::BrokenLink(BrokenLink { path, .. }) => {
864                    // If the interpreter is from an active, valid virtual environment, we should
865                    // fail because it's broken
866                    if matches!(source, PythonSource::ActiveEnvironment)
867                        && uv_fs::is_virtualenv_executable(path)
868                    {
869                        true
870                    } else {
871                        trace!("Skipping missing interpreter at `{}`", path.display());
872                        false
873                    }
874                }
875            },
876            Self::VirtualEnv(VirtualEnvError::MissingPyVenvCfg(path)) => {
877                trace!("Skipping broken virtualenv at `{}`", path.display());
878                false
879            }
880            _ => true,
881        }
882    }
883}
884
885/// Create a [`PythonInstallation`] from a Python installation root directory.
886fn python_installation_from_directory(
887    path: &PathBuf,
888    cache: &Cache,
889) -> Result<PythonInstallation, uv_python_interpreter::InterpreterError> {
890    let executable = virtualenv_python_executable(path);
891    Ok(PythonInstallation {
892        source: PythonSource::ProvidedPath,
893        interpreter: Interpreter::query(&executable, cache)?,
894    })
895}
896
897/// Lazily iterate over all Python executable paths on the path with the given executable name.
898fn python_executables_with_name(
899    name: &str,
900) -> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + '_ {
901    which_all(name)
902        .into_iter()
903        .flat_map(|inner| inner.map(|path| Ok((PythonSource::SearchPath, path))))
904}
905
906/// Lazily iterate over all Python installations on the path with the given executable name.
907fn python_installations_with_name<'a>(
908    name: &'a str,
909    cache: &'a Cache,
910    strategy: QueryStrategy,
911) -> Box<dyn Iterator<Item = Result<PythonInstallation, Error>> + 'a> {
912    python_installations_from_executables(
913        python_executables_with_name(name)
914            .map_ok(|executable| PythonExecutableGroup(vec![executable])),
915        cache,
916        strategy,
917    )
918}
919
920/// Iterate over all Python installations that satisfy the given request.
921pub(crate) fn find_python_installations<'a>(
922    request: &'a PythonRequest,
923    environments: EnvironmentPreference,
924    preference: PythonPreference,
925    arch: Option<PythonArchitecture>,
926    cache: &'a Cache,
927) -> Box<dyn Iterator<Item = Result<FindPythonResult, Error>> + 'a> {
928    find_python_installations_with_strategy(
929        request,
930        environments,
931        preference,
932        arch,
933        cache,
934        QueryStrategy::Sequential,
935    )
936}
937
938/// Iterate over all Python installations that satisfy the given request using the given query
939/// strategy.
940fn find_python_installations_with_strategy<'a>(
941    request: &'a PythonRequest,
942    environments: EnvironmentPreference,
943    preference: PythonPreference,
944    arch: Option<PythonArchitecture>,
945    cache: &'a Cache,
946    strategy: QueryStrategy,
947) -> Box<dyn Iterator<Item = Result<FindPythonResult, Error>> + 'a> {
948    let arch = arch.map(|arch| {
949        PythonDownloadRequest::from_request(request)
950            .and_then(|request| request.arch().map(ArchRequest::inner))
951            .unwrap_or_else(|| arch.into_inner())
952    });
953    let platform = PlatformRequest::default().with_default_arch(arch);
954    let sources = DiscoveryPreferences {
955        python_preference: preference,
956        environment_preference: environments,
957    }
958    .sources(request);
959
960    match request {
961        PythonRequest::File(path) => Box::new(iter::once({
962            if preference.allows_source(PythonSource::ProvidedPath) {
963                debug!("Checking for Python interpreter at {request}");
964                match Interpreter::query(path, cache) {
965                    Ok(interpreter) => Ok(Ok(PythonInstallation {
966                        source: PythonSource::ProvidedPath,
967                        interpreter,
968                    })),
969                    Err(InterpreterError::NotFound(_) | InterpreterError::BrokenLink(_)) => {
970                        Ok(Err(PythonNotFound {
971                            request: request.clone(),
972                            python_preference: preference,
973                            environment_preference: environments,
974                        }))
975                    }
976                    Err(err) => Err(Error::Query(
977                        Box::new(err),
978                        path.clone(),
979                        PythonSource::ProvidedPath,
980                    )),
981                }
982            } else {
983                Err(Error::SourceNotAllowed(
984                    request.clone(),
985                    PythonSource::ProvidedPath,
986                    preference,
987                ))
988            }
989        })),
990        PythonRequest::Directory(path) => Box::new(iter::once({
991            if preference.allows_source(PythonSource::ProvidedPath) {
992                debug!("Checking for Python interpreter in {request}");
993                match python_installation_from_directory(path, cache) {
994                    Ok(installation) => Ok(Ok(installation)),
995                    Err(InterpreterError::NotFound(_) | InterpreterError::BrokenLink(_)) => {
996                        Ok(Err(PythonNotFound {
997                            request: request.clone(),
998                            python_preference: preference,
999                            environment_preference: environments,
1000                        }))
1001                    }
1002                    Err(err) => Err(Error::Query(
1003                        Box::new(err),
1004                        path.clone(),
1005                        PythonSource::ProvidedPath,
1006                    )),
1007                }
1008            } else {
1009                Err(Error::SourceNotAllowed(
1010                    request.clone(),
1011                    PythonSource::ProvidedPath,
1012                    preference,
1013                ))
1014            }
1015        })),
1016        PythonRequest::ExecutableName(name) => {
1017            if preference.allows_source(PythonSource::SearchPath) {
1018                debug!("Searching for Python interpreter with {request}");
1019                Box::new(
1020                    python_installations_with_name(name, cache, strategy)
1021                        .filter_ok(move |installation| {
1022                            installation.satisfies_environment_preference(environments)
1023                        })
1024                        .map_ok(Ok),
1025                )
1026            } else {
1027                Box::new(iter::once(Err(Error::SourceNotAllowed(
1028                    request.clone(),
1029                    PythonSource::SearchPath,
1030                    preference,
1031                ))))
1032            }
1033        }
1034        PythonRequest::Any => Box::new({
1035            debug!("Searching for any Python interpreter in {sources}");
1036            python_installations(
1037                &VersionRequest::Any,
1038                None,
1039                platform,
1040                environments,
1041                preference,
1042                cache,
1043                strategy,
1044            )
1045            .map_ok(Ok)
1046        }),
1047        PythonRequest::Default => Box::new({
1048            debug!("Searching for default Python interpreter in {sources}");
1049            python_installations(
1050                &VersionRequest::Default,
1051                None,
1052                platform,
1053                environments,
1054                preference,
1055                cache,
1056                strategy,
1057            )
1058            .map_ok(Ok)
1059        }),
1060        PythonRequest::Version(version) => {
1061            if let Err(err) = version.check_supported() {
1062                return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1063            }
1064            Box::new({
1065                debug!("Searching for {request} in {sources}");
1066                python_installations(
1067                    version,
1068                    None,
1069                    platform,
1070                    environments,
1071                    preference,
1072                    cache,
1073                    strategy,
1074                )
1075                .map_ok(Ok)
1076            })
1077        }
1078        PythonRequest::Implementation(implementation) => Box::new({
1079            debug!("Searching for a {request} interpreter in {sources}");
1080            python_installations(
1081                &VersionRequest::Default,
1082                Some(implementation),
1083                platform,
1084                environments,
1085                preference,
1086                cache,
1087                strategy,
1088            )
1089            .filter_ok(move |installation| {
1090                installation
1091                    .interpreter
1092                    .matches_implementation(*implementation)
1093            })
1094            .map_ok(Ok)
1095        }),
1096        PythonRequest::ImplementationVersion(implementation, version) => {
1097            if let Err(err) = version.check_supported() {
1098                return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1099            }
1100            Box::new({
1101                debug!("Searching for {request} in {sources}");
1102                python_installations(
1103                    version,
1104                    Some(implementation),
1105                    platform,
1106                    environments,
1107                    preference,
1108                    cache,
1109                    strategy,
1110                )
1111                .filter_ok(move |installation| {
1112                    installation
1113                        .interpreter
1114                        .matches_implementation(*implementation)
1115                })
1116                .map_ok(Ok)
1117            })
1118        }
1119        PythonRequest::Key(request) => {
1120            if let Some(version) = request.version()
1121                && let Err(err) = version.check_supported()
1122            {
1123                return Box::new(iter::once(Err(Error::InvalidVersionRequest(err))));
1124            }
1125
1126            Box::new({
1127                debug!("Searching for {request} in {sources}");
1128                python_installations(
1129                    request.version().unwrap_or(&VersionRequest::Default),
1130                    request.implementation(),
1131                    request.platform().with_default_arch(arch),
1132                    environments,
1133                    preference,
1134                    cache,
1135                    strategy,
1136                )
1137                .filter_ok(move |installation| {
1138                    installation.interpreter.matches_download_request(request)
1139                })
1140                .map_ok(Ok)
1141            })
1142        }
1143    }
1144}
1145
1146/// Find all Python installations that satisfy the given request, querying interpreters
1147/// concurrently.
1148///
1149/// Eagerly collects matching installations. Interpreter query failures produce warnings and are
1150/// skipped. Other non-critical discovery errors are dropped, while critical errors are propagated in
1151/// discovery order.
1152pub fn find_all_python_installations(
1153    request: &PythonRequest,
1154    environments: EnvironmentPreference,
1155    preference: PythonPreference,
1156    arch: Option<PythonArchitecture>,
1157    cache: &Cache,
1158) -> Result<Vec<PythonInstallation>, Error> {
1159    let results = find_python_installations_with_strategy(
1160        request,
1161        environments,
1162        preference,
1163        arch,
1164        cache,
1165        QueryStrategy::Parallel,
1166    );
1167    let mut installations = Vec::new();
1168    for result in results {
1169        match result {
1170            Ok(Ok(installation)) => installations.push(installation),
1171            Ok(Err(_)) => {}
1172            Err(err @ Error::Query(..)) => {
1173                warn_user_with_chain!(&err);
1174            }
1175            Err(err) if err.is_critical() => return Err(err),
1176            Err(_) => {}
1177        }
1178    }
1179    Ok(installations)
1180}
1181
1182/// Find a Python installation that satisfies the given request.
1183///
1184/// If an error is encountered while locating or inspecting a candidate installation,
1185/// the error will raised instead of attempting further candidates.
1186pub(crate) fn find_python_installation(
1187    request: &PythonRequest,
1188    environments: EnvironmentPreference,
1189    preference: PythonPreference,
1190    arch: Option<PythonArchitecture>,
1191    cache: &Cache,
1192) -> Result<FindPythonResult, Error> {
1193    let installations = find_python_installations(request, environments, preference, arch, cache);
1194    let mut first_prerelease = None;
1195    let mut first_debug = None;
1196    let mut first_managed = None;
1197    let mut first_error = None;
1198    for result in installations {
1199        // Iterate until the first critical error or happy result
1200        if !result.as_ref().err().is_none_or(Error::is_critical) {
1201            // Track the first non-critical error
1202            if first_error.is_none()
1203                && let Err(err) = result
1204            {
1205                first_error = Some(err);
1206            }
1207            continue;
1208        }
1209
1210        // If it's an error, we're done.
1211        let Ok(Ok(installation)) = result else {
1212            return result;
1213        };
1214
1215        // Check if we need to skip the interpreter because it is "not allowed", e.g., if it is a
1216        // pre-release version or an alternative implementation, using it requires opt-in.
1217
1218        // If the interpreter has a default executable name, e.g. `python`, and was found on the
1219        // search path, we consider this opt-in to use it.
1220        let has_default_executable_name = installation.interpreter.has_default_executable_name()
1221            && matches!(
1222                installation.source,
1223                PythonSource::SearchPath | PythonSource::SearchPathFirst
1224            );
1225
1226        // If it's a pre-release and pre-releases aren't allowed, skip it — but store it for later
1227        // since we'll use a pre-release if no other versions are available.
1228        if installation.python_version().pre().is_some()
1229            && !request.allows_prereleases()
1230            && !installation.source.allows_prereleases()
1231            && !has_default_executable_name
1232        {
1233            debug!("Skipping pre-release installation {}", installation.key());
1234            if first_prerelease.is_none() {
1235                first_prerelease = Some(installation);
1236            }
1237            continue;
1238        }
1239
1240        // If it's a debug build and debug builds aren't allowed, skip it — but store it for later
1241        // since we'll use a debug build if no other versions are available.
1242        if installation.key().variant().is_debug()
1243            && !request.allows_debug()
1244            && !installation.source.allows_debug()
1245            && !has_default_executable_name
1246        {
1247            debug!("Skipping debug installation {}", installation.key());
1248            if first_debug.is_none() {
1249                first_debug = Some(installation);
1250            }
1251            continue;
1252        }
1253
1254        // If it's an alternative implementation and alternative implementations aren't allowed,
1255        // skip it. Note we avoid querying these interpreters at all if they're on the search path
1256        // and are not requested, but other sources such as the managed installations can include
1257        // them.
1258        if installation.is_alternative_implementation()
1259            && !request.allows_alternative_implementations()
1260            && !installation.source.allows_alternative_implementations()
1261            && !has_default_executable_name
1262        {
1263            debug!("Skipping alternative implementation {}", installation.key());
1264            continue;
1265        }
1266
1267        // If it's a managed Python installation, and system interpreters are preferred, skip it
1268        // for now.
1269        if matches!(preference, PythonPreference::System) && installation.is_managed() {
1270            debug!(
1271                "Skipping managed installation {}: system installation preferred",
1272                installation.key()
1273            );
1274            if first_managed.is_none() {
1275                first_managed = Some(installation);
1276            }
1277            continue;
1278        }
1279
1280        // If we didn't skip it, this is the installation to use
1281        return Ok(Ok(installation));
1282    }
1283
1284    // If we only found managed installations, and the preference allows them, we should return
1285    // the first one.
1286    if let Some(installation) = first_managed {
1287        debug!(
1288            "Allowing managed installation {}: no system installations",
1289            installation.key()
1290        );
1291        return Ok(Ok(installation));
1292    }
1293
1294    // If we only found debug installations, they're implicitly allowed and we should return the
1295    // first one.
1296    if let Some(installation) = first_debug {
1297        debug!(
1298            "Allowing debug installation {}: no non-debug installations",
1299            installation.key()
1300        );
1301        return Ok(Ok(installation));
1302    }
1303
1304    // If we only found pre-releases, they're implicitly allowed and we should return the first one.
1305    if let Some(installation) = first_prerelease {
1306        debug!(
1307            "Allowing pre-release installation {}: no stable installations",
1308            installation.key()
1309        );
1310        return Ok(Ok(installation));
1311    }
1312
1313    // If we found a Python, but it was unusable for some reason, report that instead of saying we
1314    // couldn't find any Python interpreters.
1315    if let Some(err) = first_error {
1316        return Err(err);
1317    }
1318
1319    Ok(Err(PythonNotFound {
1320        request: request
1321            .with_default_arch(arch.map(PythonArchitecture::into_inner))
1322            .into_owned(),
1323        environment_preference: environments,
1324        python_preference: preference,
1325    }))
1326}
1327
1328/// Find the best-matching Python installation.
1329///
1330/// If no Python version is provided, we will use the first available installation.
1331///
1332/// If a Python version is provided, we will first try to find an exact match. If
1333/// that cannot be found and a patch version was requested, we will look for a match
1334/// without comparing the patch version number. If that cannot be found, we fall back to
1335/// the first available version.
1336///
1337/// At all points, if the specified version cannot be found, we will attempt to
1338/// download it if downloads are enabled.
1339///
1340/// See [`find_python_installation`] for more details on installation discovery.
1341#[instrument(skip_all, fields(request))]
1342pub(crate) async fn find_best_python_installation(
1343    request: &PythonRequest,
1344    environments: EnvironmentPreference,
1345    preference: PythonPreference,
1346    arch: Option<PythonArchitecture>,
1347    downloads_enabled: bool,
1348    client_builder: &BaseClientBuilder<'_>,
1349    cache: &Cache,
1350    reporter: Option<&dyn uv_python_managed::downloads::Reporter>,
1351    mirrors: PythonDownloadMirrors<'_>,
1352    python_downloads_json_url: Option<&str>,
1353) -> Result<PythonInstallation, crate::Error> {
1354    debug!("Starting Python discovery for {request}");
1355    let original_request = request;
1356
1357    let mut previous_fetch_failed = false;
1358    let mut download_state = None;
1359
1360    let request_without_patch = match request {
1361        PythonRequest::Version(version) => {
1362            if version.has_patch() {
1363                Some(PythonRequest::Version(version.clone().without_patch()))
1364            } else {
1365                None
1366            }
1367        }
1368        PythonRequest::ImplementationVersion(implementation, version) => Some(
1369            PythonRequest::ImplementationVersion(*implementation, version.clone().without_patch()),
1370        ),
1371        _ => None,
1372    };
1373
1374    for (attempt, request) in iter::once(original_request)
1375        .chain(request_without_patch.iter())
1376        .chain(iter::once(&PythonRequest::Default))
1377        .enumerate()
1378    {
1379        debug!(
1380            "Looking for {request}{}",
1381            if request != original_request {
1382                format!(" attempt {attempt} (fallback after failing to find: {original_request})")
1383            } else {
1384                String::new()
1385            }
1386        );
1387        let result = find_python_installation(request, environments, preference, arch, cache);
1388        let error = match result {
1389            Ok(Ok(installation)) => {
1390                warn_on_unsupported_python(installation.interpreter());
1391                return Ok(installation);
1392            }
1393            // Continue if we can't find a matching Python and ignore non-critical discovery errors
1394            Ok(Err(error)) => error.into(),
1395            Err(error) if !error.is_critical() => error.into(),
1396            Err(error) => return Err(error.into()),
1397        };
1398
1399        // Attempt to download the version if downloads are enabled
1400        if downloads_enabled
1401            && !previous_fetch_failed
1402            && let Some(download_request) = PythonDownloadRequest::from_request(request)
1403        {
1404            let (client, retry_policy, download_list) =
1405                if let Some(download_state) = &mut download_state {
1406                    download_state
1407                } else {
1408                    let download_list = ManagedPythonDownloadList::new(
1409                        client_builder,
1410                        cache,
1411                        python_downloads_json_url,
1412                    )
1413                    .await?;
1414                    let retry_policy = client_builder.retry_policy();
1415
1416                    // Python downloads are performing their own retries to catch stream errors, disable
1417                    // the default retries to avoid the middleware performing uncontrolled retries.
1418                    let client = client_builder.clone().retries(0).build()?;
1419                    download_state.insert((client, retry_policy, download_list))
1420                };
1421
1422            let download = download_request
1423                .clone()
1424                .with_default_arch(arch.map(PythonArchitecture::into_inner))
1425                .fill()
1426                .map(|request| download_list.find(&request));
1427
1428            let result = match download {
1429                Ok(Ok(download)) => PythonInstallation::fetch(
1430                    download,
1431                    client,
1432                    retry_policy,
1433                    cache,
1434                    reporter,
1435                    mirrors,
1436                )
1437                .await
1438                .map(Some),
1439                Ok(Err(uv_python_managed::downloads::Error::NoDownloadFound(_))) => Ok(None),
1440                Ok(Err(error)) => Err(error.into()),
1441                Err(error) => Err(error.into()),
1442            };
1443            if let Ok(Some(installation)) = result {
1444                return Ok(installation);
1445            }
1446            // Emit a warning instead of failing since we may find a suitable
1447            // interpreter on the system after relaxing the request further.
1448            // Additionally, uv did not previously attempt downloads in this
1449            // code path and we want to minimize the fatal cases for
1450            // backwards compatibility.
1451            // Errors encountered here are either network errors or quirky
1452            // configuration problems.
1453            if let Err(error) = result {
1454                // If the request was for the default or any version, propagate
1455                // the error as nothing else we are about to do will help the
1456                // situation.
1457                if matches!(request, PythonRequest::Default | PythonRequest::Any) {
1458                    return Err(error);
1459                }
1460
1461                warn_user_with_chain!(
1462                    anyhow::Error::from(error)
1463                        .context(format!(
1464                            "A managed Python download is available for {request}, but an error occurred when attempting to download it."
1465                        ))
1466                        .as_ref()
1467                );
1468                previous_fetch_failed = true;
1469            }
1470        }
1471
1472        // If this was a request for the Default or Any version, this means that
1473        // either that's what we were called with, or we're on the last
1474        // iteration.
1475        //
1476        // The most recent find error therefore becomes a fatal one.
1477        if matches!(request, PythonRequest::Default | PythonRequest::Any) {
1478            return Err(match error {
1479                crate::Error::MissingPython(err, _) => PythonNotFound {
1480                    // Use a more general error in this case since we looked for multiple versions
1481                    request: original_request
1482                        .with_default_arch(arch.map(PythonArchitecture::into_inner))
1483                        .into_owned(),
1484                    python_preference: err.python_preference,
1485                    environment_preference: err.environment_preference,
1486                }
1487                .into(),
1488                other => other,
1489            });
1490        }
1491    }
1492
1493    unreachable!("The loop should have terminated when it reached PythonRequest::Default");
1494}
1495
1496/// Display a warning if the Python version of the [`Interpreter`] is unsupported by uv.
1497fn warn_on_unsupported_python(interpreter: &Interpreter) {
1498    // Warn on usage with an unsupported Python version
1499    if interpreter.python_tuple() < (3, 8) {
1500        warn_user_once!(
1501            "uv is only compatible with Python >=3.8, found Python {}",
1502            interpreter.python_version()
1503        );
1504    }
1505}
1506
1507/// On Windows we might encounter the Windows Store proxy shim (enabled in:
1508/// Settings/Apps/Advanced app settings/App execution aliases). When Python is _not_ installed
1509/// via the Windows Store, but the proxy shim is enabled, then executing `python.exe` or
1510/// `python3.exe` will redirect to the Windows Store installer.
1511///
1512/// We need to detect that these `python.exe` and `python3.exe` files are _not_ Python
1513/// executables.
1514///
1515/// This method is taken from Rye:
1516///
1517/// > This is a pretty dumb way.  We know how to parse this reparse point, but Microsoft
1518/// > does not want us to do this as the format is unstable.  So this is a best effort way.
1519/// > we just hope that the reparse point has the python redirector in it, when it's not
1520/// > pointing to a valid Python.
1521///
1522/// See: <https://github.com/astral-sh/rye/blob/b0e9eccf05fe4ff0ae7b0250a248c54f2d780b4d/rye/src/cli/shim.rs#L108>
1523#[cfg(windows)]
1524fn is_windows_store_shim(path: &Path) -> bool {
1525    use std::os::windows::fs::MetadataExt;
1526    use std::os::windows::prelude::OsStrExt;
1527    use windows::Win32::Foundation::CloseHandle;
1528    use windows::Win32::Storage::FileSystem::{
1529        CreateFileW, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
1530        FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_MODE, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
1531        OPEN_EXISTING,
1532    };
1533    use windows::Win32::System::IO::DeviceIoControl;
1534    use windows::Win32::System::Ioctl::FSCTL_GET_REPARSE_POINT;
1535    use windows::core::PCWSTR;
1536
1537    // The path must be absolute.
1538    if !path.is_absolute() {
1539        return false;
1540    }
1541
1542    // The path must point to something like:
1543    //   `C:\Users\crmar\AppData\Local\Microsoft\WindowsApps\python3.exe`
1544    let mut components = path.components().rev();
1545
1546    // Ex) `python.exe`, `python3.exe`, `python3.12.exe`, etc.
1547    if !components
1548        .next()
1549        .and_then(|component| component.as_os_str().to_str())
1550        .is_some_and(|component| {
1551            component.starts_with("python")
1552                && std::path::Path::new(component)
1553                    .extension()
1554                    .is_some_and(|ext| ext.eq_ignore_ascii_case("exe"))
1555        })
1556    {
1557        return false;
1558    }
1559
1560    // Ex) `WindowsApps`
1561    if components
1562        .next()
1563        .is_none_or(|component| component.as_os_str() != "WindowsApps")
1564    {
1565        return false;
1566    }
1567
1568    // Ex) `Microsoft`
1569    if components
1570        .next()
1571        .is_none_or(|component| component.as_os_str() != "Microsoft")
1572    {
1573        return false;
1574    }
1575
1576    // The file is only relevant if it's a reparse point.
1577    let Ok(md) = fs_err::symlink_metadata(path) else {
1578        return false;
1579    };
1580    if md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 == 0 {
1581        return false;
1582    }
1583
1584    let mut path_encoded = path
1585        .as_os_str()
1586        .encode_wide()
1587        .chain(std::iter::once(0))
1588        .collect::<Vec<_>>();
1589
1590    // SAFETY: The path is null-terminated.
1591    #[allow(unsafe_code)]
1592    let reparse_handle = unsafe {
1593        CreateFileW(
1594            PCWSTR(path_encoded.as_mut_ptr()),
1595            0,
1596            FILE_SHARE_MODE(0),
1597            None,
1598            OPEN_EXISTING,
1599            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1600            None,
1601        )
1602    };
1603
1604    let Ok(reparse_handle) = reparse_handle else {
1605        return false;
1606    };
1607
1608    let mut buf = [0u16; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
1609    let mut bytes_returned = 0;
1610
1611    // SAFETY: The buffer is large enough to hold the reparse point.
1612    #[allow(unsafe_code, clippy::cast_possible_truncation)]
1613    let success = unsafe {
1614        DeviceIoControl(
1615            reparse_handle,
1616            FSCTL_GET_REPARSE_POINT,
1617            None,
1618            0,
1619            Some(buf.as_mut_ptr().cast()),
1620            buf.len() as u32 * 2,
1621            Some(&raw mut bytes_returned),
1622            None,
1623        )
1624        .is_ok()
1625    };
1626
1627    // SAFETY: The handle is valid.
1628    #[allow(unsafe_code)]
1629    unsafe {
1630        let _ = CloseHandle(reparse_handle);
1631    }
1632
1633    // If the operation failed, assume it's not a reparse point.
1634    if !success {
1635        return false;
1636    }
1637
1638    let reparse_point = String::from_utf16_lossy(&buf[..bytes_returned as usize]);
1639    reparse_point.contains("\\AppInstallerPythonRedirector.exe")
1640}
1641
1642/// On Unix, we do not need to deal with Windows store shims.
1643///
1644/// See the Windows implementation for details.
1645#[cfg(not(windows))]
1646fn is_windows_store_shim(_path: &Path) -> bool {
1647    false
1648}
1649
1650impl DiscoveryPreferences {
1651    /// Return a string describing the sources that are considered when searching for Python with
1652    /// the given preferences.
1653    fn sources(&self, request: &PythonRequest) -> String {
1654        let python_sources = self
1655            .python_preference
1656            .sources()
1657            .iter()
1658            .map(ToString::to_string)
1659            .collect::<Vec<_>>();
1660        match self.environment_preference {
1661            EnvironmentPreference::Any => disjunction(
1662                &["virtual environments"]
1663                    .into_iter()
1664                    .chain(python_sources.iter().map(String::as_str))
1665                    .collect::<Vec<_>>(),
1666            ),
1667            EnvironmentPreference::ExplicitSystem => {
1668                if request.is_explicit_system() {
1669                    disjunction(
1670                        &["virtual environments"]
1671                            .into_iter()
1672                            .chain(python_sources.iter().map(String::as_str))
1673                            .collect::<Vec<_>>(),
1674                    )
1675                } else {
1676                    disjunction(&["virtual environments"])
1677                }
1678            }
1679            EnvironmentPreference::OnlySystem => disjunction(
1680                &python_sources
1681                    .iter()
1682                    .map(String::as_str)
1683                    .collect::<Vec<_>>(),
1684            ),
1685            EnvironmentPreference::OnlyVirtual => disjunction(&["virtual environments"]),
1686        }
1687    }
1688}
1689
1690impl fmt::Display for PythonNotFound {
1691    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1692        let sources = DiscoveryPreferences {
1693            python_preference: self.python_preference,
1694            environment_preference: self.environment_preference,
1695        }
1696        .sources(&self.request);
1697
1698        match self.request {
1699            PythonRequest::Default | PythonRequest::Any => {
1700                write!(f, "No interpreter found in {sources}")
1701            }
1702            PythonRequest::File(_) => {
1703                write!(f, "No interpreter found at {}", self.request)
1704            }
1705            PythonRequest::Directory(_) => {
1706                write!(f, "No interpreter found in {}", self.request)
1707            }
1708            _ => {
1709                write!(f, "No interpreter found for {} in {sources}", self.request)
1710            }
1711        }
1712    }
1713}
1714
1715/// Join a series of items with `or` separators, making use of commas when necessary.
1716fn disjunction(items: &[&str]) -> String {
1717    match items.len() {
1718        0 => String::new(),
1719        1 => items[0].to_string(),
1720        2 => format!("{} or {}", items[0], items[1]),
1721        _ => {
1722            let last = items.last().unwrap();
1723            format!(
1724                "{}, or {}",
1725                items.iter().take(items.len() - 1).join(", "),
1726                last
1727            )
1728        }
1729    }
1730}
1731
1732#[cfg(test)]
1733mod tests {
1734    use std::assert_matches;
1735    use std::{cell::Cell, io, path::PathBuf};
1736
1737    use test_log::test;
1738    use uv_cache::Cache;
1739
1740    use uv_python_types::PythonRequest;
1741
1742    use super::{
1743        DiscoveryPreferences, EnvironmentPreference, Error, InterpreterError,
1744        PythonExecutableGroup, PythonPreference, PythonSource, QueryStrategy,
1745        python_installations_from_executables, sort_installations_by_key,
1746    };
1747
1748    // Testing this at a higher level would necessitate relying on filesystem ordering.
1749    #[test]
1750    fn installation_key_order_only_partitions_critical_errors() {
1751        let query_error = |error| {
1752            Error::Query(
1753                Box::new(error),
1754                PathBuf::from("python"),
1755                PythonSource::SearchPath,
1756            )
1757        };
1758
1759        let mut installations = [
1760            Ok(1_u8),
1761            Err(query_error(InterpreterError::NotFound(PathBuf::from(
1762                "missing",
1763            )))),
1764            Ok(2),
1765            Err(query_error(InterpreterError::Io(io::Error::other(
1766                "critical",
1767            )))),
1768            Ok(3),
1769        ];
1770
1771        sort_installations_by_key(&mut installations, |key| *key);
1772
1773        assert_matches!(
1774            &installations[..],
1775            [Ok(2), Ok(1), Err(noncritical), Err(critical), Ok(3)]
1776                if !noncritical.is_critical() && critical.is_critical()
1777        );
1778    }
1779
1780    #[test]
1781    fn sequential_query_strategy_does_not_prefetch_executable_groups() -> anyhow::Result<()> {
1782        let cache = Cache::temp()?;
1783        let pulls = Cell::new(0);
1784        let executables = (0..2).map(|_| {
1785            pulls.set(pulls.get() + 1);
1786            Err::<PythonExecutableGroup, _>(Error::SourceNotAllowed(
1787                PythonRequest::Default,
1788                PythonSource::SearchPath,
1789                PythonPreference::OnlyManaged,
1790            ))
1791        });
1792
1793        let mut installations =
1794            python_installations_from_executables(executables, &cache, QueryStrategy::Sequential);
1795
1796        assert_eq!(pulls.get(), 0);
1797        assert!(installations.next().is_some_and(|result| result.is_err()));
1798        assert_eq!(pulls.get(), 1);
1799
1800        Ok(())
1801    }
1802
1803    #[test]
1804    fn discovery_sources_prefer_system_orders_search_path_first() {
1805        let preferences = DiscoveryPreferences {
1806            python_preference: PythonPreference::System,
1807            environment_preference: EnvironmentPreference::OnlySystem,
1808        };
1809        let sources = preferences.sources(&PythonRequest::Default);
1810
1811        if cfg!(windows) {
1812            assert_eq!(sources, "search path, registry, or managed installations");
1813        } else {
1814            assert_eq!(sources, "search path or managed installations");
1815        }
1816    }
1817
1818    #[test]
1819    fn discovery_sources_only_system_matches_platform_order() {
1820        let preferences = DiscoveryPreferences {
1821            python_preference: PythonPreference::OnlySystem,
1822            environment_preference: EnvironmentPreference::OnlySystem,
1823        };
1824        let sources = preferences.sources(&PythonRequest::Default);
1825
1826        if cfg!(windows) {
1827            assert_eq!(sources, "search path or registry");
1828        } else {
1829            assert_eq!(sources, "search path");
1830        }
1831    }
1832}