Skip to main content

uv_python_interpreter/
interpreter.rs

1use std::borrow::Cow;
2use std::env::consts::ARCH;
3use std::fmt::{Display, Formatter};
4use std::path::{Path, PathBuf};
5use std::process::{Command, ExitStatus};
6use std::sync::OnceLock;
7use std::{env, io};
8
9use astral_ini::Options;
10use fs_err as fs;
11use owo_colors::OwoColorize;
12use same_file::is_same_file;
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15use tracing::{debug, trace, warn};
16
17use uv_cache::{Cache, CacheBucket, CacheEntry, CachedByTimestamp, Freshness};
18use uv_cache_info::Timestamp;
19use uv_cache_key::cache_digest;
20use uv_errors::Hints;
21use uv_fs::{
22    LockedFile, LockedFileError, LockedFileMode, PythonExt, Simplified, write_atomic_sync,
23};
24use uv_install_wheel::Layout;
25use uv_pep440::Version;
26use uv_pep508::{MarkerEnvironment, StringVersion};
27use uv_platform::{Arch, Libc, Os};
28use uv_platform_tags::{CpuInfo, Platform, Tags, TagsError, TagsOptions};
29use uv_preview::PreviewFeature;
30use uv_pypi_types::{ResolverMarkerEnvironment, Scheme};
31use uv_static::EnvVars;
32use uv_warnings::warn_user_once_with_chain;
33
34use crate::PointerSize;
35use crate::PyVenvConfiguration;
36use crate::VirtualEnvironment;
37use crate::virtualenv::virtualenv_python_executable;
38use uv_python_types::{
39    ImplementationName, LenientImplementationName, Prefix, PythonDownloadRequest,
40    PythonInstallationKey, PythonRequest, PythonVariant, Target, VersionRequest,
41};
42use which::which;
43
44#[cfg(windows)]
45use windows::Win32::Foundation::{APPMODEL_ERROR_NO_PACKAGE, ERROR_CANT_ACCESS_FILE, WIN32_ERROR};
46
47/// A Python executable and its associated platform markers.
48#[cfg_attr(unix, expect(clippy::struct_excessive_bools))]
49#[derive(Debug, Clone)]
50pub struct Interpreter {
51    platform: Platform,
52    markers: Box<MarkerEnvironment>,
53    scheme: Scheme,
54    virtualenv: Scheme,
55    manylinux_compatible: bool,
56    sys_prefix: PathBuf,
57    sys_base_prefix: PathBuf,
58    sys_base_executable: Option<PathBuf>,
59    sys_executable: PathBuf,
60    site_packages: Vec<PathBuf>,
61    stdlib: PathBuf,
62    extension_suffixes: Vec<Box<str>>,
63    #[cfg(unix)]
64    standalone: bool,
65    tags: OnceLock<Tags>,
66    target: Option<Target>,
67    prefix: Option<Prefix>,
68    pointer_size: PointerSize,
69    gil_disabled: bool,
70    real_executable: PathBuf,
71    debug_enabled: bool,
72}
73
74impl Interpreter {
75    /// Detect the interpreter info for the given Python executable.
76    pub fn query(executable: impl AsRef<Path>, cache: &Cache) -> Result<Self, Error> {
77        let executable = executable.as_ref();
78        let InterpreterInfo {
79            platform,
80            metadata: info,
81        } = InterpreterInfo::query_cached(executable, cache)?;
82
83        debug_assert!(
84            info.sys_executable.is_absolute(),
85            "`sys.executable` is not an absolute Python; Python installation is broken: {}",
86            info.sys_executable.display()
87        );
88
89        Ok(Self {
90            platform,
91            markers: Box::new(info.markers),
92            scheme: info.scheme,
93            virtualenv: info.virtualenv,
94            manylinux_compatible: info.manylinux_compatible,
95            sys_prefix: info.sys_prefix,
96            pointer_size: info.pointer_size,
97            gil_disabled: info.gil_disabled,
98            debug_enabled: info.debug_enabled,
99            sys_base_prefix: info.sys_base_prefix,
100            sys_base_executable: info.sys_base_executable,
101            sys_executable: info.sys_executable,
102            site_packages: info.site_packages,
103            stdlib: info.stdlib,
104            extension_suffixes: info.extension_suffixes,
105            #[cfg(unix)]
106            standalone: info.standalone,
107            tags: OnceLock::new(),
108            target: None,
109            prefix: None,
110            real_executable: executable.to_path_buf(),
111        })
112    }
113
114    /// Remove any cached metadata for the given Python executable.
115    pub fn clear_cache(executable: impl AsRef<Path>, cache: &Cache) -> Result<(), Error> {
116        let absolute = std::path::absolute(executable.as_ref())?;
117        let canonical = canonicalize_executable(&absolute)?;
118        let cache_entry = InterpreterInfo::cache_entry(&absolute, &canonical, cache);
119
120        match fs::remove_file(cache_entry.path()) {
121            Ok(()) => Ok(()),
122            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
123            Err(err) => Err(err.into()),
124        }
125    }
126
127    /// Return a new [`Interpreter`] with the given virtual environment root.
128    #[must_use]
129    pub fn with_virtualenv(self, virtualenv: VirtualEnvironment) -> Self {
130        Self {
131            scheme: virtualenv.scheme,
132            sys_base_executable: Some(virtualenv.base_executable),
133            sys_executable: virtualenv.executable,
134            sys_prefix: virtualenv.root,
135            target: None,
136            prefix: None,
137            site_packages: vec![],
138            ..self
139        }
140    }
141
142    /// Return a new [`Interpreter`] to install into the given `--target` directory.
143    pub(crate) fn with_target(self, target: Target) -> io::Result<Self> {
144        fs::create_dir_all(target.root())?;
145        Ok(Self {
146            target: Some(target),
147            ..self
148        })
149    }
150
151    /// Return a new [`Interpreter`] to install into the given `--prefix` directory.
152    pub(crate) fn with_prefix(self, prefix: Prefix) -> io::Result<Self> {
153        fs::create_dir_all(prefix.root().join(&self.virtualenv.purelib))?;
154        Ok(Self {
155            prefix: Some(prefix),
156            ..self
157        })
158    }
159
160    /// Return the base Python executable; that is, the Python executable that should be
161    /// considered the "base" for the virtual environment. This is typically the Python executable
162    /// from the [`Interpreter`]; however, if the interpreter is a virtual environment itself, then
163    /// the base Python executable is the Python executable of the interpreter's base interpreter.
164    ///
165    /// This routine relies on `sys._base_executable`, falling back to `sys.executable` if unset.
166    /// Broadly, this routine should be used when attempting to determine the "base Python
167    /// executable" in a way that is consistent with the CPython standard library, such as when
168    /// determining the `home` key for a virtual environment.
169    pub fn to_base_python(&self) -> Result<PathBuf, io::Error> {
170        let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
171        let base_python = std::path::absolute(base_executable)?;
172        Ok(base_python)
173    }
174
175    /// Determine the base Python executable; that is, the Python executable that should be
176    /// considered the "base" for the virtual environment. This is typically the Python executable
177    /// from the [`Interpreter`]; however, if the interpreter is a virtual environment itself, then
178    /// the base Python executable is the Python executable of the interpreter's base interpreter.
179    ///
180    /// This routine mimics the CPython `getpath.py` logic in order to make a more robust assessment
181    /// of the appropriate base Python executable. Broadly, this routine should be used when
182    /// attempting to determine the "true" base executable for a Python interpreter by resolving
183    /// symlinks until a valid Python installation is found. In particular, we tend to use this
184    /// routine for our own managed (or standalone) Python installations.
185    pub fn find_base_python(&self) -> Result<PathBuf, io::Error> {
186        let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
187        // In `python-build-standalone`, a symlinked interpreter will return its own executable path
188        // as `sys._base_executable`. Using the symlinked path as the base Python executable can be
189        // incorrect, since it could cause `home` to point to something that is _not_ a Python
190        // installation. Specifically, if the interpreter _itself_ is symlinked to an arbitrary
191        // location, we need to fully resolve it to the actual Python executable; however, if the
192        // entire standalone interpreter is symlinked, then we can use the symlinked path.
193        //
194        // We emulate CPython's `getpath.py` to ensure that the base executable results in a valid
195        // Python prefix when converted into the `home` key for `pyvenv.cfg`.
196        let base_python = match find_base_python(
197            base_executable,
198            self.python_major(),
199            self.python_minor(),
200            self.variant().executable_suffix(),
201        ) {
202            Ok(path) => path,
203            Err(err) => {
204                warn!("Failed to find base Python executable: {err}");
205                canonicalize_executable(base_executable)?
206            }
207        };
208        Ok(base_python)
209    }
210
211    /// Returns the Python interpreter's platform.
212    #[inline]
213    pub fn platform(&self) -> &Platform {
214        &self.platform
215    }
216
217    /// Returns the [`MarkerEnvironment`] for this Python executable.
218    #[inline]
219    pub const fn markers(&self) -> &MarkerEnvironment {
220        &self.markers
221    }
222
223    /// Return the [`ResolverMarkerEnvironment`] for this Python executable.
224    pub fn to_resolver_marker_environment(&self) -> ResolverMarkerEnvironment {
225        ResolverMarkerEnvironment::from(self.markers().clone())
226    }
227
228    /// Returns the [`PythonInstallationKey`] for this interpreter.
229    pub fn key(&self) -> PythonInstallationKey {
230        PythonInstallationKey::new(
231            LenientImplementationName::from(self.implementation_name()),
232            self.python_major(),
233            self.python_minor(),
234            self.python_patch(),
235            self.python_version().pre(),
236            uv_platform::Platform::new(self.os(), self.arch(), self.libc()),
237            self.variant(),
238        )
239    }
240
241    pub fn variant(&self) -> PythonVariant {
242        if self.gil_disabled() {
243            if self.debug_enabled() {
244                PythonVariant::FreethreadedDebug
245            } else {
246                PythonVariant::Freethreaded
247            }
248        } else if self.debug_enabled() {
249            PythonVariant::Debug
250        } else {
251            PythonVariant::default()
252        }
253    }
254
255    /// Return the [`Arch`] reported by the interpreter platform tags.
256    pub fn arch(&self) -> Arch {
257        Arch::from(&self.platform().arch())
258    }
259
260    /// Return the [`Libc`] reported by the interpreter platform tags.
261    pub fn libc(&self) -> Libc {
262        Libc::from(self.platform().os())
263    }
264
265    /// Return the [`Os`] reported by the interpreter platform tags.
266    pub fn os(&self) -> Os {
267        Os::from(self.platform().os())
268    }
269
270    /// Returns the [`Tags`] for this Python executable.
271    pub fn tags(&self) -> Result<&Tags, TagsError> {
272        if self.tags.get().is_none() {
273            let tags = Tags::from_env(
274                self.platform().clone(),
275                self.python_tuple(),
276                self.implementation_name(),
277                self.implementation_tuple(),
278                TagsOptions {
279                    manylinux_compatible: self.manylinux_compatible,
280                    gil_disabled: self.gil_disabled,
281                    debug_enabled: self.debug_enabled,
282                    is_cross: false,
283                },
284            )?;
285            self.tags.set(tags).expect("tags should not be set");
286        }
287        Ok(self.tags.get().expect("tags should be set"))
288    }
289
290    /// Returns `true` if the environment is a PEP 405-compliant virtual environment.
291    ///
292    /// See: <https://github.com/pypa/pip/blob/0ad4c94be74cc24874c6feb5bb3c2152c398a18e/src/pip/_internal/utils/virtualenv.py#L14>
293    pub fn is_virtualenv(&self) -> bool {
294        // Maybe this should return `false` if it's a target?
295        self.sys_prefix != self.sys_base_prefix
296    }
297
298    /// Returns `true` if the environment is a `--target` environment.
299    fn is_target(&self) -> bool {
300        self.target.is_some()
301    }
302
303    /// Returns `true` if the environment is a `--prefix` environment.
304    fn is_prefix(&self) -> bool {
305        self.prefix.is_some()
306    }
307
308    /// Returns `Some` if the environment is externally managed, optionally including an error
309    /// message from the `EXTERNALLY-MANAGED` file.
310    ///
311    /// See: <https://packaging.python.org/en/latest/specifications/externally-managed-environments/>
312    pub fn is_externally_managed(&self) -> Option<ExternallyManaged> {
313        // Per the spec, a virtual environment is never externally managed.
314        if self.is_virtualenv() {
315            return None;
316        }
317
318        // If we're installing into a target or prefix directory, it's never externally managed.
319        if self.is_target() || self.is_prefix() {
320            return None;
321        }
322
323        let Ok(contents) = fs::read_to_string(self.stdlib.join("EXTERNALLY-MANAGED")) else {
324            return None;
325        };
326
327        let Ok(ini) = Options::default().case_sensitive(true).parse(&contents) else {
328            // If a file exists but is not a valid INI file, we assume the environment is
329            // externally managed.
330            return Some(ExternallyManaged::default());
331        };
332
333        Some(ExternallyManaged {
334            error: ini.get("externally-managed", "Error").map(str::to_owned),
335        })
336    }
337
338    /// Returns the `python_full_version` marker corresponding to this Python version.
339    #[inline]
340    pub fn python_full_version(&self) -> &StringVersion {
341        self.markers.python_full_version()
342    }
343
344    /// Returns the full Python version.
345    #[inline]
346    pub fn python_version(&self) -> &Version {
347        &self.markers.python_full_version().version
348    }
349
350    /// Returns the Python version up to the minor component.
351    #[inline]
352    pub fn python_minor_version(&self) -> Version {
353        Version::new(self.python_version().release().iter().take(2).copied())
354    }
355
356    /// Returns the Python version up to the patch component.
357    #[inline]
358    pub(crate) fn python_patch_version(&self) -> Version {
359        Version::new(self.python_version().release().iter().take(3).copied())
360    }
361
362    /// Return the major version component of this Python version.
363    pub fn python_major(&self) -> u8 {
364        let major = self.markers.python_full_version().version.release()[0];
365        u8::try_from(major).expect("invalid major version")
366    }
367
368    /// Return the minor version component of this Python version.
369    pub fn python_minor(&self) -> u8 {
370        let minor = self.markers.python_full_version().version.release()[1];
371        u8::try_from(minor).expect("invalid minor version")
372    }
373
374    /// Return the patch version component of this Python version.
375    fn python_patch(&self) -> u8 {
376        let minor = self.markers.python_full_version().version.release()[2];
377        u8::try_from(minor).expect("invalid patch version")
378    }
379
380    /// Returns the Python version as a simple tuple, e.g., `(3, 12)`.
381    pub fn python_tuple(&self) -> (u8, u8) {
382        (self.python_major(), self.python_minor())
383    }
384
385    /// Return the major version of the implementation (e.g., `CPython` or `PyPy`).
386    fn implementation_major(&self) -> u8 {
387        let major = self.markers.implementation_version().version.release()[0];
388        u8::try_from(major).expect("invalid major version")
389    }
390
391    /// Return the minor version of the implementation (e.g., `CPython` or `PyPy`).
392    fn implementation_minor(&self) -> u8 {
393        let minor = self.markers.implementation_version().version.release()[1];
394        u8::try_from(minor).expect("invalid minor version")
395    }
396
397    /// Returns the implementation version as a simple tuple.
398    pub fn implementation_tuple(&self) -> (u8, u8) {
399        (self.implementation_major(), self.implementation_minor())
400    }
401
402    /// Returns the implementation name (e.g., `CPython` or `PyPy`).
403    pub fn implementation_name(&self) -> &str {
404        self.markers.implementation_name()
405    }
406
407    /// Return the `sys.base_prefix` path for this Python interpreter.
408    pub fn sys_base_prefix(&self) -> &Path {
409        &self.sys_base_prefix
410    }
411
412    /// Return the `sys.prefix` path for this Python interpreter.
413    pub fn sys_prefix(&self) -> &Path {
414        &self.sys_prefix
415    }
416
417    /// Return the `sys._base_executable` path for this Python interpreter. Some platforms do not
418    /// have this attribute, so it may be `None`.
419    fn sys_base_executable(&self) -> Option<&Path> {
420        self.sys_base_executable.as_deref()
421    }
422
423    /// Return the `sys.executable` path for this Python interpreter.
424    pub fn sys_executable(&self) -> &Path {
425        &self.sys_executable
426    }
427
428    /// Return the recognized native extension module suffixes for this Python interpreter.
429    pub fn extension_suffixes(&self) -> &[Box<str>] {
430        &self.extension_suffixes
431    }
432
433    /// Return the "real" queried executable path for this Python interpreter.
434    pub fn real_executable(&self) -> &Path {
435        &self.real_executable
436    }
437
438    /// Return the `site.getsitepackages` for this Python interpreter.
439    ///
440    /// These are the paths Python will search for packages in at runtime. We use this for
441    /// environment layering, but not for checking for installed packages. We could use these paths
442    /// to check for installed packages, but it introduces a lot of complexity, so instead we use a
443    /// simplified version that does not respect customized site-packages. See
444    /// [`Interpreter::site_packages`].
445    pub fn runtime_site_packages(&self) -> &[PathBuf] {
446        &self.site_packages
447    }
448
449    /// Return the `stdlib` path for this Python interpreter, as returned by `sysconfig.get_paths()`.
450    pub fn stdlib(&self) -> &Path {
451        &self.stdlib
452    }
453
454    /// Return the `purelib` path for this Python interpreter, as returned by `sysconfig.get_paths()`.
455    fn purelib(&self) -> &Path {
456        &self.scheme.purelib
457    }
458
459    /// Return the `platlib` path for this Python interpreter, as returned by `sysconfig.get_paths()`.
460    fn platlib(&self) -> &Path {
461        &self.scheme.platlib
462    }
463
464    /// Return the `scripts` path for this Python interpreter, as returned by `sysconfig.get_paths()`.
465    pub fn scripts(&self) -> &Path {
466        &self.scheme.scripts
467    }
468
469    /// Return the `data` path for this Python interpreter, as returned by `sysconfig.get_paths()`.
470    fn data(&self) -> &Path {
471        &self.scheme.data
472    }
473
474    /// Return the `include` path for this Python interpreter, as returned by `sysconfig.get_paths()`.
475    fn include(&self) -> &Path {
476        &self.scheme.include
477    }
478
479    /// Return the [`Scheme`] for a virtual environment created by this [`Interpreter`].
480    pub fn virtualenv(&self) -> &Scheme {
481        &self.virtualenv
482    }
483
484    /// Return whether this interpreter is `manylinux` compatible.
485    pub fn manylinux_compatible(&self) -> bool {
486        self.manylinux_compatible
487    }
488
489    /// Return the [`PointerSize`] of the Python interpreter (i.e., 32- vs. 64-bit).
490    pub fn pointer_size(&self) -> PointerSize {
491        self.pointer_size
492    }
493
494    /// Return whether this is a Python 3.13+ freethreading Python, as specified by the sysconfig var
495    /// `Py_GIL_DISABLED`.
496    ///
497    /// freethreading Python is incompatible with earlier native modules, re-introducing
498    /// abiflags with a `t` flag. <https://peps.python.org/pep-0703/#build-configuration-changes>
499    pub fn gil_disabled(&self) -> bool {
500        self.gil_disabled
501    }
502
503    /// Return whether this is a debug build of Python, as specified by the sysconfig var
504    /// `Py_DEBUG`.
505    pub fn debug_enabled(&self) -> bool {
506        self.debug_enabled
507    }
508
509    /// Return the `--target` directory for this interpreter, if any.
510    fn target(&self) -> Option<&Target> {
511        self.target.as_ref()
512    }
513
514    /// Return the `--prefix` directory for this interpreter, if any.
515    fn prefix(&self) -> Option<&Prefix> {
516        self.prefix.as_ref()
517    }
518
519    /// Returns `true` if an [`Interpreter`] may be a `python-build-standalone` interpreter.
520    ///
521    /// This method may return false positives, but it should not return false negatives. In other
522    /// words, if this method returns `true`, the interpreter _may_ be from
523    /// `python-build-standalone`; if it returns `false`, the interpreter is definitely _not_ from
524    /// `python-build-standalone`.
525    ///
526    /// See: <https://github.com/astral-sh/python-build-standalone/issues/382>
527    #[cfg(unix)]
528    pub fn is_standalone(&self) -> bool {
529        self.standalone
530    }
531
532    /// Return the [`Layout`] environment used to install wheels into this interpreter.
533    pub fn layout(&self) -> Layout {
534        Layout {
535            python_version: self.python_tuple(),
536            sys_executable: self.sys_executable().to_path_buf(),
537            os_name: self.markers.os_name().to_string(),
538            scheme: if let Some(target) = self.target.as_ref() {
539                Scheme {
540                    purelib: target.root().to_path_buf(),
541                    platlib: target.root().to_path_buf(),
542                    scripts: target.root().join("bin"),
543                    data: target.root().to_path_buf(),
544                    include: target.root().join("include"),
545                }
546            } else if let Some(prefix) = self.prefix.as_ref() {
547                Scheme {
548                    purelib: prefix.root().join(&self.virtualenv.purelib),
549                    platlib: prefix.root().join(&self.virtualenv.platlib),
550                    scripts: prefix.root().join(&self.virtualenv.scripts),
551                    data: prefix.root().join(&self.virtualenv.data),
552                    include: prefix.root().join(&self.virtualenv.include),
553                }
554            } else {
555                Scheme {
556                    purelib: self.purelib().to_path_buf(),
557                    platlib: self.platlib().to_path_buf(),
558                    scripts: self.scripts().to_path_buf(),
559                    data: self.data().to_path_buf(),
560                    include: if self.is_virtualenv() {
561                        // If the interpreter is a venv, then the `include` directory has a different structure.
562                        // See: https://github.com/pypa/pip/blob/0ad4c94be74cc24874c6feb5bb3c2152c398a18e/src/pip/_internal/locations/_sysconfig.py#L172
563                        self.sys_prefix.join("include").join("site").join(format!(
564                            "python{}.{}",
565                            self.python_major(),
566                            self.python_minor()
567                        ))
568                    } else {
569                        self.include().to_path_buf()
570                    },
571                }
572            },
573        }
574    }
575
576    /// Returns an iterator over the `site-packages` directories inside the environment.
577    ///
578    /// In most cases, `purelib` and `platlib` will be the same, and so the iterator will contain
579    /// a single element; however, in some distributions, they may be different.
580    ///
581    /// Some distributions also create symbolic links from `purelib` to `platlib`; in such cases, we
582    /// still deduplicate the entries, returning a single path.
583    ///
584    /// Note this does not include all runtime site-packages directories if the interpreter has been
585    /// customized. See [`Interpreter::runtime_site_packages`].
586    pub fn site_packages(&self) -> impl Iterator<Item = Cow<'_, Path>> {
587        let target = self.target().map(Target::root);
588
589        let prefix = self
590            .prefix()
591            .map(|prefix| prefix.root().join(&self.virtualenv.purelib));
592
593        let interpreter = if target.is_none() && prefix.is_none() {
594            let purelib = self.purelib();
595            let platlib = self.platlib();
596            Some(std::iter::once(purelib).chain(
597                if purelib == platlib || is_same_file(purelib, platlib).unwrap_or(false) {
598                    None
599                } else {
600                    Some(platlib)
601                },
602            ))
603        } else {
604            None
605        };
606
607        target
608            .into_iter()
609            .map(Cow::Borrowed)
610            .chain(prefix.into_iter().map(Cow::Owned))
611            .chain(interpreter.into_iter().flatten().map(Cow::Borrowed))
612    }
613
614    /// Whether or not this Python interpreter is from a default Python executable name, like
615    /// `python`, `python3`, or `python.exe`.
616    pub fn has_default_executable_name(&self) -> bool {
617        let Some(file_name) = self.sys_executable().file_name() else {
618            return false;
619        };
620        let Some(name) = file_name.to_str() else {
621            return false;
622        };
623        VersionRequest::Default
624            .executable_names(None)
625            .into_iter()
626            .any(|default_name| name == default_name.to_string())
627    }
628
629    /// Grab a file lock for the environment to prevent concurrent writes across processes.
630    pub async fn lock(&self) -> Result<LockedFile, LockedFileError> {
631        if let Some(target) = self.target() {
632            // If we're installing into a `--target`, use a target-specific lockfile.
633            LockedFile::acquire(
634                target.root().join(".lock"),
635                LockedFileMode::Exclusive,
636                target.root().user_display(),
637            )
638            .await
639        } else if let Some(prefix) = self.prefix() {
640            // Likewise, if we're installing into a `--prefix`, use a prefix-specific lockfile.
641            LockedFile::acquire(
642                prefix.root().join(".lock"),
643                LockedFileMode::Exclusive,
644                prefix.root().user_display(),
645            )
646            .await
647        } else if self.is_virtualenv() {
648            // If the environment a virtualenv, use a virtualenv-specific lockfile.
649            LockedFile::acquire(
650                self.sys_prefix.join(".lock"),
651                LockedFileMode::Exclusive,
652                self.sys_prefix.user_display(),
653            )
654            .await
655        } else {
656            // Otherwise, use a global lockfile.
657            LockedFile::acquire(
658                env::temp_dir().join(format!("uv-{}.lock", cache_digest(&self.sys_executable))),
659                LockedFileMode::Exclusive,
660                self.sys_prefix.user_display(),
661            )
662            .await
663        }
664    }
665
666    /// Check whether this interpreter satisfies the given variant.
667    fn matches_variant(&self, variant: PythonVariant) -> bool {
668        match variant {
669            PythonVariant::Default => {
670                // TODO(zanieb): Right now, we allow debug interpreters to be selected by default for
671                // backwards compatibility, but we may want to change this in the future.
672                if (self.python_major(), self.python_minor()) >= (3, 14) {
673                    // For Python 3.14+, the free-threaded build is not considered experimental
674                    // and can satisfy the default variant without opt-in
675                    true
676                } else {
677                    // In Python 3.13 and earlier, the free-threaded build is considered
678                    // experimental and requires explicit opt-in
679                    !self.gil_disabled()
680                }
681            }
682            PythonVariant::Debug => self.debug_enabled(),
683            PythonVariant::Freethreaded => self.gil_disabled(),
684            PythonVariant::FreethreadedDebug => self.gil_disabled() && self.debug_enabled(),
685            PythonVariant::Gil => !self.gil_disabled(),
686            PythonVariant::GilDebug => !self.gil_disabled() && self.debug_enabled(),
687        }
688    }
689
690    /// Check whether this interpreter satisfies the given implementation.
691    pub fn matches_implementation(&self, implementation: ImplementationName) -> bool {
692        match implementation {
693            ImplementationName::Pyodide => self.os().is_emscripten(),
694            _ => self
695                .implementation_name()
696                .eq_ignore_ascii_case(implementation.long_name()),
697        }
698    }
699
700    /// Check whether this interpreter satisfies the given request.
701    pub fn matches_version_request(&self, request: &VersionRequest) -> bool {
702        match request {
703            VersionRequest::Any => true,
704            // Do not use free-threaded interpreters by default
705            VersionRequest::Default => self.matches_variant(PythonVariant::Default),
706            VersionRequest::Major(major, variant) => {
707                self.python_major() == *major && self.matches_variant(*variant)
708            }
709            VersionRequest::MajorMinor(major, minor, variant) => {
710                (self.python_major(), self.python_minor()) == (*major, *minor)
711                    && self.matches_variant(*variant)
712            }
713            VersionRequest::MajorMinorPatch(major, minor, patch, variant) => {
714                (
715                    self.python_major(),
716                    self.python_minor(),
717                    self.python_patch(),
718                ) == (*major, *minor, *patch)
719                    // When a patch version is included, we treat it as a request for a stable
720                    // release
721                    && self.python_version().pre().is_none()
722                    && self.matches_variant(*variant)
723            }
724            VersionRequest::Range(specifiers, variant) => {
725                // If the specifier contains pre-releases, use the full version for comparison.
726                // Otherwise, strip pre-release so that, e.g., `>=3.14` matches `3.14.0rc3`.
727                let version = if specifiers
728                    .iter()
729                    .any(uv_pep440::VersionSpecifier::any_prerelease)
730                {
731                    Cow::Borrowed(self.python_version())
732                } else {
733                    Cow::Owned(self.python_version().only_release())
734                };
735                specifiers.contains(&version) && self.matches_variant(*variant)
736            }
737            VersionRequest::MajorMinorPrerelease(major, minor, prerelease, variant) => {
738                let version = self.python_version();
739                let Some(interpreter_prerelease) = version.pre() else {
740                    return false;
741                };
742                (
743                    self.python_major(),
744                    self.python_minor(),
745                    interpreter_prerelease,
746                ) == (*major, *minor, *prerelease)
747                    && self.matches_variant(*variant)
748            }
749            VersionRequest::MajorMinorPatchPrerelease(major, minor, patch, prerelease, variant) => {
750                let version = self.python_version();
751                let Some(interpreter_prerelease) = version.pre() else {
752                    return false;
753                };
754                (
755                    self.python_major(),
756                    self.python_minor(),
757                    self.python_patch(),
758                    interpreter_prerelease,
759                ) == (*major, *minor, *patch, *prerelease)
760                    && self.matches_variant(*variant)
761            }
762        }
763    }
764
765    /// Check whether this interpreter satisfies the given request.
766    pub fn matches_download_request(&self, request: &PythonDownloadRequest) -> bool {
767        let executable = self.sys_executable().display();
768        if let Some(version) = request.version()
769            && !self.matches_version_request(version)
770        {
771            let interpreter_version = self.python_version();
772            debug!(
773                "Skipping interpreter at `{executable}`: version `{interpreter_version}` does not match request `{version}`"
774            );
775            return false;
776        }
777        let platform = request.platform();
778        let interpreter_platform = uv_platform::Platform::from(self.platform());
779        if !platform.matches(&interpreter_platform) {
780            debug!(
781                "Skipping interpreter at `{executable}`: platform `{interpreter_platform}` does not match request `{platform}`",
782            );
783            return false;
784        }
785        if let Some(implementation) = request.implementation()
786            && !self.matches_implementation(*implementation)
787        {
788            debug!(
789                "Skipping interpreter at `{executable}`: implementation `{}` does not match request `{implementation}`",
790                self.implementation_name(),
791            );
792            return false;
793        }
794        true
795    }
796
797    /// Check whether this interpreter satisfies the given request.
798    pub fn matches_request(&self, request: &PythonRequest, cache: &Cache) -> bool {
799        /// Returns `true` if the two paths refer to the same interpreter executable.
800        fn is_same_executable(path1: &Path, path2: &Path) -> bool {
801            path1 == path2 || is_same_file(path1, path2).unwrap_or(false)
802        }
803
804        match request {
805            PythonRequest::Default | PythonRequest::Any => true,
806            PythonRequest::Version(version_request) => {
807                self.matches_version_request(version_request)
808            }
809            PythonRequest::Directory(directory) => {
810                // `sys.prefix` points to the environment root or `sys.executable` is the same
811                is_same_executable(directory, self.sys_prefix())
812                    || is_same_executable(
813                        virtualenv_python_executable(directory).as_path(),
814                        self.sys_executable(),
815                    )
816            }
817            PythonRequest::File(file) => {
818                // The interpreter satisfies the request both if it is the venv...
819                if is_same_executable(self.sys_executable(), file) {
820                    return true;
821                }
822                // ...or if it is the base interpreter the venv was created from.
823                if self
824                    .sys_base_executable()
825                    .is_some_and(|sys_base_executable| {
826                        is_same_executable(sys_base_executable, file)
827                    })
828                {
829                    return true;
830                }
831                // ...or, on Windows, if both interpreters have the same base executable. On
832                // Windows, interpreters are copied rather than symlinked, so a virtual environment
833                // created from within a virtual environment will _not_ evaluate to the same
834                // `sys.executable`, but will have the same `sys._base_executable`.
835                if cfg!(windows) {
836                    if let Ok(file_interpreter) = Self::query(file, cache) {
837                        if let (Some(file_base), Some(interpreter_base)) = (
838                            file_interpreter.sys_base_executable(),
839                            self.sys_base_executable(),
840                        ) {
841                            if is_same_executable(file_base, interpreter_base) {
842                                return true;
843                            }
844                        }
845                    }
846                }
847                false
848            }
849            PythonRequest::ExecutableName(name) => {
850                // First, see if we have a match in the venv ...
851                if self
852                    .sys_executable()
853                    .file_name()
854                    .is_some_and(|filename| filename == name.as_str())
855                {
856                    return true;
857                }
858                // ... or the venv's base interpreter (without performing IO), if that fails, ...
859                if self
860                    .sys_base_executable()
861                    .and_then(|executable| executable.file_name())
862                    .is_some_and(|file_name| file_name == name.as_str())
863                {
864                    return true;
865                }
866                // ... check in `PATH`. The name we find here does not need to be the
867                // name we install, so we can find `foopython` here which got installed as `python`.
868                if which(name)
869                    .ok()
870                    .as_ref()
871                    .and_then(|executable| executable.file_name())
872                    .is_some_and(|file_name| file_name == name.as_str())
873                {
874                    return true;
875                }
876                false
877            }
878            PythonRequest::Implementation(implementation) => {
879                self.matches_implementation(*implementation)
880            }
881            PythonRequest::ImplementationVersion(implementation, version) => {
882                self.matches_version_request(version)
883                    && self.matches_implementation(*implementation)
884            }
885            PythonRequest::Key(request) => self.matches_download_request(request),
886        }
887    }
888}
889
890/// Calls `fs_err::canonicalize` on Unix. On Windows, avoids attempting to resolve symlinks
891/// but will resolve junctions if they are part of a trampoline target.
892pub fn canonicalize_executable(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
893    let path = path.as_ref();
894    debug_assert!(
895        path.is_absolute(),
896        "path must be absolute: {}",
897        path.display()
898    );
899
900    #[cfg(windows)]
901    {
902        if let Ok(Some(launcher)) = uv_trampoline_builder::Launcher::try_from_path(path) {
903            Ok(dunce::canonicalize(launcher.python_path)?)
904        } else {
905            Ok(path.to_path_buf())
906        }
907    }
908
909    #[cfg(unix)]
910    fs_err::canonicalize(path)
911}
912
913/// The `EXTERNALLY-MANAGED` file in a Python installation.
914///
915/// See: <https://packaging.python.org/en/latest/specifications/externally-managed-environments/>
916#[derive(Debug, Default, Clone)]
917pub struct ExternallyManaged {
918    error: Option<String>,
919}
920
921impl ExternallyManaged {
922    /// Return the `EXTERNALLY-MANAGED` error message, if any.
923    pub fn into_error(self) -> Option<String> {
924        self.error
925    }
926}
927
928#[derive(Debug, Error)]
929pub struct UnexpectedResponseError {
930    #[source]
931    err: serde_json::Error,
932    stdout: String,
933    stderr: String,
934    pub path: PathBuf,
935}
936
937impl Display for UnexpectedResponseError {
938    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
939        write!(
940            f,
941            "Querying Python at `{}` returned an invalid response: {}",
942            self.path.display(),
943            self.err
944        )?;
945
946        let mut non_empty = false;
947
948        if !self.stdout.trim().is_empty() {
949            write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
950            non_empty = true;
951        }
952
953        if !self.stderr.trim().is_empty() {
954            write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
955            non_empty = true;
956        }
957
958        if non_empty {
959            writeln!(f)?;
960        }
961
962        Ok(())
963    }
964}
965
966#[derive(Debug, Error)]
967pub struct StatusCodeError {
968    code: ExitStatus,
969    stdout: String,
970    stderr: String,
971    pub path: PathBuf,
972}
973
974impl Display for StatusCodeError {
975    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
976        write!(
977            f,
978            "Querying Python at `{}` failed with exit status {}",
979            self.path.display(),
980            self.code
981        )?;
982
983        let mut non_empty = false;
984
985        if !self.stdout.trim().is_empty() {
986            write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?;
987            non_empty = true;
988        }
989
990        if !self.stderr.trim().is_empty() {
991            write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?;
992            non_empty = true;
993        }
994
995        if non_empty {
996            writeln!(f)?;
997        }
998
999        Ok(())
1000    }
1001}
1002
1003#[derive(Debug, Error)]
1004pub enum Error {
1005    #[error("Failed to detect CPU capabilities")]
1006    CpuDetection(#[source] CpuDetectionError),
1007    #[error("Failed to query Python interpreter")]
1008    Io(#[from] io::Error),
1009    #[error(transparent)]
1010    BrokenLink(BrokenLink),
1011    #[error("Python interpreter not found at `{0}`")]
1012    NotFound(PathBuf),
1013    #[error("Failed to query Python interpreter at `{path}`")]
1014    SpawnFailed {
1015        path: PathBuf,
1016        #[source]
1017        err: io::Error,
1018    },
1019    #[cfg(windows)]
1020    #[error("Failed to query Python interpreter at `{path}`")]
1021    CorruptWindowsPackage {
1022        path: PathBuf,
1023        #[source]
1024        err: io::Error,
1025    },
1026    #[error("Failed to query Python interpreter at `{path}`")]
1027    PermissionDenied {
1028        path: PathBuf,
1029        #[source]
1030        err: io::Error,
1031    },
1032    #[error("{0}")]
1033    UnexpectedResponse(UnexpectedResponseError),
1034    #[error("{0}")]
1035    StatusCode(StatusCodeError),
1036    #[error("Can't use Python at `{path}`")]
1037    QueryScript {
1038        #[source]
1039        err: InterpreterInfoError,
1040        path: PathBuf,
1041    },
1042    #[error("Failed to write to cache")]
1043    Encode(#[from] rmp_serde::encode::Error),
1044}
1045
1046impl uv_errors::Hinted for Error {
1047    fn hints(&self) -> uv_errors::Hints<'_> {
1048        match self {
1049            Self::BrokenLink(err) => err.hints(),
1050            _ => uv_errors::Hints::none(),
1051        }
1052    }
1053}
1054
1055#[derive(Debug, Error)]
1056pub struct BrokenLink {
1057    pub path: PathBuf,
1058    /// Whether we have a broken symlink (Unix) or whether the shim returned that the underlying
1059    /// Python went away (Windows).
1060    pub unix: bool,
1061    /// Whether the interpreter path looks like a virtual environment.
1062    pub venv: bool,
1063}
1064
1065impl Display for BrokenLink {
1066    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1067        if self.unix {
1068            write!(
1069                f,
1070                "Broken symlink at `{}`, was the underlying Python interpreter removed?",
1071                self.path.user_display()
1072            )
1073        } else {
1074            write!(
1075                f,
1076                "Broken Python trampoline at `{}`, was the underlying Python interpreter removed?",
1077                self.path.user_display()
1078            )
1079        }
1080    }
1081}
1082
1083impl uv_errors::Hinted for BrokenLink {
1084    fn hints(&self) -> uv_errors::Hints<'_> {
1085        if self.venv {
1086            uv_errors::Hints::from(format!(
1087                "Consider recreating the environment (e.g., with `{}`)",
1088                "uv venv".green()
1089            ))
1090        } else {
1091            uv_errors::Hints::none()
1092        }
1093    }
1094}
1095
1096#[derive(Debug, Deserialize)]
1097#[serde(tag = "result", rename_all = "lowercase")]
1098enum InterpreterInfoResult {
1099    Error(InterpreterInfoError),
1100    Success(Box<InterpreterInfoWire>),
1101}
1102
1103/// A successful Python probe response, before applying the CPU detection policy.
1104#[derive(Debug, Deserialize)]
1105struct InterpreterInfoWire {
1106    os: uv_platform_tags::Os,
1107    arch: uv_platform_tags::Arch,
1108    cpu_info: CpuProbe,
1109    #[serde(flatten)]
1110    metadata: InterpreterMetadata,
1111}
1112
1113#[derive(Debug, Deserialize)]
1114#[serde(rename_all = "snake_case")]
1115enum CpuProbe {
1116    /// CPU capabilities were detected successfully.
1117    Detected(CpuInfo),
1118    /// No probe supports this interpreter architecture. Continue without CPU data.
1119    UnsupportedArchitecture(Box<str>),
1120    /// An expected limitation prevented detection. Continue with the platform defaults.
1121    Unavailable(Box<str>),
1122    /// An unexpected probe failure, fatal with wheel variants enabled and a warning otherwise.
1123    ///
1124    /// TODO(konsti): Make probe failures unconditionally fatal when wheel variants stabilize.
1125    Error(CpuDetectionError),
1126}
1127
1128/// The failure reported by the interpreter's CPU probe.
1129#[derive(Debug, Deserialize, Error)]
1130#[error("{0}")]
1131pub struct CpuDetectionError(Box<str>);
1132
1133#[derive(Debug, Error, Deserialize, Serialize)]
1134#[serde(tag = "kind", rename_all = "snake_case")]
1135pub enum InterpreterInfoError {
1136    #[error("Could not detect a glibc or a musl libc (while running on Linux)")]
1137    LibcNotFound,
1138    #[error(
1139        "Broken Python installation, `platform.mac_ver()` returned an empty value, please reinstall Python"
1140    )]
1141    BrokenMacVer,
1142    #[error("Unknown operating system: `{operating_system}`")]
1143    UnknownOperatingSystem { operating_system: String },
1144    #[error("Python {python_version} is not supported. Please use Python 3.6 or newer.")]
1145    UnsupportedPythonVersion { python_version: String },
1146    #[error("Python executable does not support `-I` flag. Please use Python 3.6 or newer.")]
1147    UnsupportedPython,
1148    #[error(
1149        "Python installation is missing `distutils`, which is required for packaging on older Python versions. Your system may package it separately, e.g., as `python{python_major}-distutils` or `python{python_major}.{python_minor}-distutils`."
1150    )]
1151    MissingRequiredDistutils {
1152        python_major: usize,
1153        python_minor: usize,
1154    },
1155    #[error("Only Pyodide is supported for Emscripten Python")]
1156    EmscriptenNotPyodide,
1157}
1158
1159#[derive(Debug, Deserialize, Serialize, Clone)]
1160struct InterpreterInfo {
1161    platform: Platform,
1162    metadata: InterpreterMetadata,
1163}
1164
1165#[expect(clippy::struct_excessive_bools)]
1166#[derive(Debug, Deserialize, Serialize, Clone)]
1167struct InterpreterMetadata {
1168    markers: MarkerEnvironment,
1169    scheme: Scheme,
1170    virtualenv: Scheme,
1171    manylinux_compatible: bool,
1172    sys_prefix: PathBuf,
1173    sys_base_exec_prefix: PathBuf,
1174    sys_base_prefix: PathBuf,
1175    sys_base_executable: Option<PathBuf>,
1176    sys_executable: PathBuf,
1177    sys_path: Vec<PathBuf>,
1178    site_packages: Vec<PathBuf>,
1179    stdlib: PathBuf,
1180    extension_suffixes: Vec<Box<str>>,
1181    standalone: bool,
1182    pointer_size: PointerSize,
1183    gil_disabled: bool,
1184    debug_enabled: bool,
1185}
1186
1187impl InterpreterInfo {
1188    /// Query the given Python executable for its interpreter information.
1189    fn query(interpreter: &Path, cache: &Cache) -> Result<InterpreterInfoWire, Error> {
1190        let tempdir = tempfile::tempdir_in(cache.root())?;
1191        Self::setup_python_query_files(tempdir.path())?;
1192
1193        // Sanitize the path by (1) running under isolated mode (`-I`) to ignore any site packages
1194        // modifications, and then (2) adding the path containing our query script to the front of
1195        // `sys.path` so that we can import it.
1196        // There are user reports that `sitecustomize.py` output breaks worker communication, but
1197        // we cannot use `-S` here because interpreter discovery needs the site-initialized
1198        // `sys.path`. We may want to fix this in the future if there are more reports. See:
1199        // https://github.com/astral-sh/uv/issues/11508.
1200        let script = format!(
1201            r"import sys; sys.path = [{}] + sys.path; from python.get_interpreter_info import main; main()",
1202            tempdir.path().escape_for_python()
1203        );
1204        let mut command = Command::new(interpreter);
1205        command
1206            .arg("-I") // Isolated mode.
1207            .arg("-B") // Don't write bytecode.
1208            .arg("-c")
1209            .arg(script);
1210
1211        // Disable Apple's SYSTEM_VERSION_COMPAT shim so that `platform.mac_ver()` reports
1212        // the real macOS version instead of "10.16" for interpreters built against older SDKs
1213        // (e.g., conda with MACOSX_DEPLOYMENT_TARGET=10.15).
1214        //
1215        // See:
1216        //
1217        // - https://github.com/astral-sh/uv/issues/14267
1218        // - https://github.com/pypa/packaging/blob/f2bbd4f578644865bc5cb2534768e46563ee7f66/src/packaging/tags.py#L436
1219        #[cfg(target_os = "macos")]
1220        command.env("SYSTEM_VERSION_COMPAT", "0");
1221
1222        let output = command.output().map_err(|err| {
1223            match err.kind() {
1224                io::ErrorKind::NotFound => return Error::NotFound(interpreter.to_path_buf()),
1225                io::ErrorKind::PermissionDenied => {
1226                    return Error::PermissionDenied {
1227                        path: interpreter.to_path_buf(),
1228                        err,
1229                    };
1230                }
1231                _ => {}
1232            }
1233            #[cfg(windows)]
1234            if let Some(APPMODEL_ERROR_NO_PACKAGE | ERROR_CANT_ACCESS_FILE) = err
1235                .raw_os_error()
1236                .and_then(|code| u32::try_from(code).ok())
1237                .map(WIN32_ERROR)
1238            {
1239                // These error codes are returned if the Python interpreter is a corrupt MSIX
1240                // package, which we want to differentiate from a typical spawn failure.
1241                return Error::CorruptWindowsPackage {
1242                    path: interpreter.to_path_buf(),
1243                    err,
1244                };
1245            }
1246            Error::SpawnFailed {
1247                path: interpreter.to_path_buf(),
1248                err,
1249            }
1250        })?;
1251
1252        if !output.status.success() {
1253            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1254
1255            // Handle uninstalled CPython interpreters on Windows.
1256            //
1257            // The IO error from the CPython trampoline is unstructured and localized, so we check
1258            // whether the `home` from `pyvenv.cfg` still exists, it's missing if the Python
1259            // interpreter was uninstalled.
1260            if python_home(interpreter).is_some_and(|home| !home.exists()) {
1261                return Err(Error::BrokenLink(BrokenLink {
1262                    path: interpreter.to_path_buf(),
1263                    unix: false,
1264                    venv: uv_fs::is_virtualenv_executable(interpreter),
1265                }));
1266            }
1267
1268            // If the Python version is too old, we may not even be able to invoke the query script
1269            if stderr.contains("Unknown option: -I") {
1270                return Err(Error::QueryScript {
1271                    err: InterpreterInfoError::UnsupportedPython,
1272                    path: interpreter.to_path_buf(),
1273                });
1274            }
1275
1276            return Err(Error::StatusCode(StatusCodeError {
1277                code: output.status,
1278                stderr,
1279                stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1280                path: interpreter.to_path_buf(),
1281            }));
1282        }
1283
1284        let result: InterpreterInfoResult =
1285            serde_json::from_slice(&output.stdout).map_err(|err| {
1286                let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1287
1288                // If the Python version is too old, we may not even be able to invoke the query script
1289                if stderr.contains("Unknown option: -I") {
1290                    Error::QueryScript {
1291                        err: InterpreterInfoError::UnsupportedPython,
1292                        path: interpreter.to_path_buf(),
1293                    }
1294                } else {
1295                    Error::UnexpectedResponse(UnexpectedResponseError {
1296                        err,
1297                        stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
1298                        stderr,
1299                        path: interpreter.to_path_buf(),
1300                    })
1301                }
1302            })?;
1303
1304        match result {
1305            InterpreterInfoResult::Error(err) => Err(Error::QueryScript {
1306                err,
1307                path: interpreter.to_path_buf(),
1308            }),
1309            InterpreterInfoResult::Success(data) => Ok(*data),
1310        }
1311    }
1312
1313    /// Duplicate the directory structure we have in `../python` into a tempdir, so we can run
1314    /// the Python probing scripts with `python -m python.get_interpreter_info` from that tempdir.
1315    fn setup_python_query_files(root: &Path) -> Result<(), Error> {
1316        let python_dir = root.join("python");
1317        fs_err::create_dir(&python_dir)?;
1318        fs_err::write(
1319            python_dir.join("get_interpreter_info.py"),
1320            include_str!("../python/get_interpreter_info.py"),
1321        )?;
1322        fs_err::write(
1323            python_dir.join("__init__.py"),
1324            include_str!("../python/__init__.py"),
1325        )?;
1326        let packaging_dir = python_dir.join("packaging");
1327        fs_err::create_dir(&packaging_dir)?;
1328        fs_err::write(
1329            packaging_dir.join("__init__.py"),
1330            include_str!("../python/packaging/__init__.py"),
1331        )?;
1332        fs_err::write(
1333            packaging_dir.join("_elffile.py"),
1334            include_str!("../python/packaging/_elffile.py"),
1335        )?;
1336        fs_err::write(
1337            packaging_dir.join("_manylinux.py"),
1338            include_str!("../python/packaging/_manylinux.py"),
1339        )?;
1340        fs_err::write(
1341            packaging_dir.join("_musllinux.py"),
1342            include_str!("../python/packaging/_musllinux.py"),
1343        )?;
1344        Ok(())
1345    }
1346
1347    /// Return the cache entry for an interpreter's absolute and canonical executable paths.
1348    fn cache_entry(absolute: &Path, canonical: &Path, cache: &Cache) -> CacheEntry {
1349        let python_executable = env::var_os(EnvVars::PYTHONEXECUTABLE).map(PathBuf::from);
1350        let pyvenv_launcher = env::var_os(EnvVars::PYVENV_LAUNCHER).map(PathBuf::from);
1351
1352        cache.entry(
1353            CacheBucket::Interpreter,
1354            // Shard interpreter metadata by host architecture, operating system, and version, to
1355            // invalidate the cache (e.g.) on OS upgrades.
1356            cache_digest(&(
1357                ARCH,
1358                uv_platform::OsType::from_env()
1359                    .map(|os_type| os_type.to_string())
1360                    .unwrap_or_default(),
1361                uv_platform::OsRelease::from_env()
1362                    .map(|os_release| os_release.to_string())
1363                    .unwrap_or_default(),
1364            )),
1365            // We use the absolute path for the cache entry to avoid cache collisions for relative
1366            // paths. But we don't want to query the executable with symbolic links resolved because
1367            // that can change reported values, e.g., `sys.executable`. We include the canonical
1368            // path in the cache entry as well, otherwise we can have cache collisions if an
1369            // absolute path refers to different interpreters with matching ctimes, e.g., if you
1370            // have a `.venv/bin/python` pointing to both Python 3.12 and Python 3.13 that were
1371            // modified at the same time.
1372            //
1373            // Launcher overrides can also change the reported executable and virtual environment
1374            // without changing either executable path.
1375            format!(
1376                "{}.msgpack",
1377                cache_digest(&(absolute, canonical, &python_executable, &pyvenv_launcher))
1378            ),
1379        )
1380    }
1381
1382    /// A wrapper around [`markers::query_interpreter_info`] to cache the computed markers.
1383    ///
1384    /// Running a Python script is (relatively) expensive, and the markers won't change
1385    /// unless the Python executable changes, so we use the executable's last modified
1386    /// time as a cache key.
1387    fn query_cached(executable: &Path, cache: &Cache) -> Result<Self, Error> {
1388        let absolute = std::path::absolute(executable)?;
1389
1390        // Provide a better error message if the link is broken or the file does not exist. Since
1391        // `canonicalize_executable` does not resolve the file on Windows, we must re-use this logic
1392        // for the subsequent metadata read as we may not have actually resolved the path.
1393        let handle_io_error = |err: io::Error| -> Error {
1394            if err.kind() == io::ErrorKind::NotFound {
1395                // Check if it looks like a venv interpreter where the underlying Python
1396                // installation was removed.
1397                if absolute
1398                    .symlink_metadata()
1399                    .is_ok_and(|metadata| metadata.is_symlink())
1400                {
1401                    Error::BrokenLink(BrokenLink {
1402                        path: executable.to_path_buf(),
1403                        unix: true,
1404                        venv: uv_fs::is_virtualenv_executable(executable),
1405                    })
1406                } else {
1407                    Error::NotFound(executable.to_path_buf())
1408                }
1409            } else {
1410                err.into()
1411            }
1412        };
1413
1414        let canonical = canonicalize_executable(&absolute).map_err(handle_io_error)?;
1415        let cache_entry = Self::cache_entry(&absolute, &canonical, cache);
1416
1417        // We check the timestamp of the canonicalized executable to check if an underlying
1418        // interpreter has been modified.
1419        let modified = Timestamp::from_path(canonical).map_err(handle_io_error)?;
1420
1421        // Read from the cache.
1422        if cache
1423            .freshness(&cache_entry, None, None)
1424            .is_ok_and(Freshness::is_fresh)
1425        {
1426            if let Ok(data) = fs::read(cache_entry.path()) {
1427                match rmp_serde::from_slice::<CachedByTimestamp<Self>>(&data) {
1428                    Ok(cached) => {
1429                        if cached.timestamp == modified {
1430                            trace!(
1431                                "Found cached interpreter info for Python {}, skipping query of: {}",
1432                                cached.data.metadata.markers.python_full_version(),
1433                                executable.user_display()
1434                            );
1435                            return Ok(cached.data);
1436                        }
1437
1438                        trace!(
1439                            "Ignoring stale interpreter markers for: {}",
1440                            executable.user_display()
1441                        );
1442                    }
1443                    Err(err) => {
1444                        warn!(
1445                            "Broken interpreter cache entry at `{}`, removing: {err}",
1446                            cache_entry.path().user_display()
1447                        );
1448                        let _ = fs_err::remove_file(cache_entry.path());
1449                    }
1450                }
1451            }
1452        }
1453
1454        // Otherwise, run the Python script.
1455        trace!(
1456            "Querying interpreter executable at `{}`",
1457            executable.display()
1458        );
1459        let wire = Self::query(executable, cache)?;
1460        let cpu_info = match wire.cpu_info {
1461            CpuProbe::Detected(info) => Some(info),
1462            CpuProbe::UnsupportedArchitecture(architecture) => {
1463                debug!("CPU detection is unsupported for architecture `{architecture}`");
1464                None
1465            }
1466            CpuProbe::Unavailable(reason) => {
1467                debug!(
1468                    "CPU information unavailable for `{}`: {reason}",
1469                    executable.display()
1470                );
1471                None
1472            }
1473            CpuProbe::Error(err) => {
1474                if uv_preview::is_enabled(PreviewFeature::WheelVariants) {
1475                    return Err(Error::CpuDetection(err));
1476                }
1477                warn_user_once_with_chain!(
1478                    anyhow::Error::from(err)
1479                        .context(format!(
1480                            "Failed to detect CPU capabilities for interpreter at `{}`",
1481                            executable.display()
1482                        ))
1483                        .as_ref(),
1484                    Hints::from("CPU detection failures will become errors in a future release.")
1485                );
1486                // Cache the interpreter so ordinary commands don't retry the failed probe on every
1487                // run. While wheel variants are in preview, we accept that enabling them later can
1488                // reuse this entry and fall back to the target architecture's defaults.
1489                None
1490            }
1491        };
1492        let info = Self {
1493            platform: Platform::from_interpreter(wire.os, wire.arch, cpu_info),
1494            metadata: wire.metadata,
1495        };
1496
1497        // If `executable` is a pyenv shim, a bash script that redirects to the activated
1498        // python executable at another path, we're not allowed to cache the interpreter info.
1499        if is_same_file(executable, &info.metadata.sys_executable).unwrap_or(false) {
1500            fs::create_dir_all(cache_entry.dir())?;
1501            write_atomic_sync(
1502                cache_entry.path(),
1503                rmp_serde::to_vec(&CachedByTimestamp {
1504                    timestamp: modified,
1505                    data: &info,
1506                })?,
1507            )?;
1508        }
1509
1510        Ok(info)
1511    }
1512}
1513
1514/// Find the Python executable that should be considered the "base" for a virtual environment.
1515///
1516/// Assumes that the provided executable is that of a standalone Python interpreter.
1517///
1518/// The strategy here mimics that of `getpath.py`: we search up the ancestor path to determine
1519/// whether a given executable will convert into a valid Python prefix; if not, we resolve the
1520/// symlink and try again.
1521///
1522/// This ensures that:
1523///
1524/// 1. We avoid using symlinks to arbitrary locations as the base Python executable. For example,
1525///    if a user symlinks a Python _executable_ to `/Users/user/foo`, we want to avoid using
1526///    `/Users/user` as `home`, since it's not a Python installation, and so the relevant libraries
1527///    and headers won't be found when it's used as the executable directory.
1528///    See: <https://github.com/python/cpython/blob/a03efb533a58fd13fb0cc7f4a5c02c8406a407bd/Modules/getpath.py#L367-L400>
1529///
1530/// 2. We use the "first" resolved symlink that _is_ a valid Python prefix, and thereby preserve
1531///    symlinks. For example, if a user symlinks a Python _installation_ to `/Users/user/foo`, such
1532///    that `/Users/user/foo/bin/python` is the resulting executable, we want to use `/Users/user/foo`
1533///    as `home`, rather than resolving to the symlink target. Concretely, this allows users to
1534///    symlink patch versions (like `cpython-3.12.6-macos-aarch64-none`) to minor version aliases
1535///    (like `cpython-3.12-macos-aarch64-none`) and preserve those aliases in the resulting virtual
1536///    environments.
1537///
1538/// See: <https://github.com/python/cpython/blob/a03efb533a58fd13fb0cc7f4a5c02c8406a407bd/Modules/getpath.py#L591-L594>
1539fn find_base_python(
1540    executable: &Path,
1541    major: u8,
1542    minor: u8,
1543    suffix: &str,
1544) -> Result<PathBuf, io::Error> {
1545    /// Returns `true` if `path` is the root directory.
1546    fn is_root(path: &Path) -> bool {
1547        let mut components = path.components();
1548        components.next() == Some(std::path::Component::RootDir) && components.next().is_none()
1549    }
1550
1551    /// Determining whether `dir` is a valid Python prefix by searching for a "landmark".
1552    ///
1553    /// See: <https://github.com/python/cpython/blob/a03efb533a58fd13fb0cc7f4a5c02c8406a407bd/Modules/getpath.py#L183>
1554    fn is_prefix(dir: &Path, major: u8, minor: u8, suffix: &str) -> bool {
1555        if cfg!(windows) {
1556            dir.join("Lib").join("os.py").is_file()
1557        } else {
1558            dir.join("lib")
1559                .join(format!("python{major}.{minor}{suffix}"))
1560                .join("os.py")
1561                .is_file()
1562        }
1563    }
1564
1565    let mut executable = Cow::Borrowed(executable);
1566
1567    loop {
1568        debug!(
1569            "Assessing Python executable as base candidate: {}",
1570            executable.display()
1571        );
1572
1573        // Determine whether this executable will produce a valid `home` for a virtual environment.
1574        for prefix in executable.ancestors().take_while(|path| !is_root(path)) {
1575            if is_prefix(prefix, major, minor, suffix) {
1576                return Ok(executable.into_owned());
1577            }
1578        }
1579
1580        // If not, resolve the symlink.
1581        let resolved = fs_err::read_link(&executable)?;
1582
1583        // If the symlink is relative, resolve it relative to the executable.
1584        let resolved = if resolved.is_relative() {
1585            if let Some(parent) = executable.parent() {
1586                parent.join(resolved)
1587            } else {
1588                return Err(io::Error::other("Symlink has no parent directory"));
1589            }
1590        } else {
1591            resolved
1592        };
1593
1594        // Normalize the resolved path.
1595        let resolved = uv_fs::normalize_absolute_path(&resolved)?;
1596
1597        executable = Cow::Owned(resolved);
1598    }
1599}
1600
1601/// Parse the `home` key from `pyvenv.cfg`, if any.
1602fn python_home(interpreter: &Path) -> Option<PathBuf> {
1603    let venv_root = interpreter.parent()?.parent()?;
1604    let pyvenv_cfg = PyVenvConfiguration::parse(venv_root.join("pyvenv.cfg")).ok()?;
1605    pyvenv_cfg.home
1606}
1607
1608#[cfg(unix)]
1609#[cfg(test)]
1610mod tests {
1611    use std::str::FromStr;
1612    use std::time::{Duration, UNIX_EPOCH};
1613
1614    use anyhow::Result;
1615    use fs_err as fs;
1616    use indoc::{formatdoc, indoc};
1617    use serde_json::Value;
1618    use tempfile::tempdir;
1619
1620    use uv_cache::{Cache, CacheBucket, CachedByTimestamp};
1621    use uv_cache_info::Timestamp;
1622    use uv_pep440::Version;
1623    use uv_platform_tags::CpuInfo;
1624
1625    use crate::Interpreter;
1626    use crate::interpreter::{InterpreterInfo, canonicalize_executable};
1627
1628    fn mocked_interpreter_response() -> &'static str {
1629        indoc! {r##"
1630        {
1631            "result": "success",
1632            "os": {
1633                "name": "manylinux",
1634                "major": 2,
1635                "minor": 38
1636            },
1637            "arch": "x86_64",
1638            "cpu_info": { "detected": { "kind": "flags", "flags": "pni ssse3" } },
1639            "manylinux_compatible": false,
1640            "standalone": false,
1641            "markers": {
1642                "implementation_name": "cpython",
1643                "implementation_version": "3.12.0",
1644                "os_name": "posix",
1645                "platform_machine": "x86_64",
1646                "platform_python_implementation": "CPython",
1647                "platform_release": "6.5.0-13-generic",
1648                "platform_system": "Linux",
1649                "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov  3 12:16:05 UTC 2023",
1650                "python_full_version": "3.12.0",
1651                "python_version": "3.12",
1652                "sys_platform": "linux"
1653            },
1654            "sys_base_exec_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1655            "sys_base_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1656            "sys_prefix": "/home/ferris/projects/uv/.venv",
1657            "sys_executable": "{sys_executable}",
1658            "sys_path": [
1659                "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/lib/python3.12",
1660                "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1661            ],
1662            "site_packages": [
1663                "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages"
1664            ],
1665            "stdlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12",
1666            "extension_suffixes": [".cpython-312-x86_64-linux-gnu.so", ".abi3.so", ".so"],
1667            "scheme": {
1668                "data": "/home/ferris/.pyenv/versions/3.12.0",
1669                "include": "/home/ferris/.pyenv/versions/3.12.0/include",
1670                "platlib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1671                "purelib": "/home/ferris/.pyenv/versions/3.12.0/lib/python3.12/site-packages",
1672                "scripts": "/home/ferris/.pyenv/versions/3.12.0/bin"
1673            },
1674            "virtualenv": {
1675                "data": "",
1676                "include": "include",
1677                "platlib": "lib/python3.12/site-packages",
1678                "purelib": "lib/python3.12/site-packages",
1679                "scripts": "bin"
1680            },
1681            "pointer_size": "64",
1682            "gil_disabled": true,
1683            "debug_enabled": false
1684        }
1685    "##}
1686    }
1687
1688    #[tokio::test]
1689    async fn test_cache_invalidation() -> Result<()> {
1690        let mock_dir = tempdir()?;
1691        let mocked_interpreter = mock_dir.path().join("python");
1692        let query_log = mock_dir.path().join("queries");
1693        let json = mocked_interpreter_response().replace(
1694            "{sys_executable}",
1695            &mocked_interpreter.display().to_string(),
1696        );
1697
1698        let cache = Cache::temp()?.init().await?;
1699
1700        fs::write(
1701            &mocked_interpreter,
1702            formatdoc! {r"
1703        #!/bin/sh
1704        echo queried >> '{}'
1705        echo '{json}'
1706        ", query_log.display()},
1707        )?;
1708
1709        fs::set_permissions(
1710            &mocked_interpreter,
1711            std::os::unix::fs::PermissionsExt::from_mode(0o770),
1712        )?;
1713        let interpreter = Interpreter::query(&mocked_interpreter, &cache)?;
1714        assert_eq!(
1715            interpreter.markers.python_version().version,
1716            Version::from_str("3.12")?
1717        );
1718        assert!(cache.bucket(CacheBucket::Interpreter).is_dir());
1719        assert_eq!(fs::read_to_string(&query_log)?, "queried\n");
1720
1721        let interpreter = Interpreter::query(&mocked_interpreter, &cache)?;
1722        let Some(CpuInfo::Flags { flags }) = interpreter.platform().cpu_info() else {
1723            anyhow::bail!("CPU flags missing from cached platform");
1724        };
1725        assert_eq!(flags.as_ref(), "pni ssse3");
1726        assert_eq!(
1727            interpreter.markers.python_version().version,
1728            Version::from_str("3.12")?
1729        );
1730        assert_eq!(fs::read_to_string(&query_log)?, "queried\n");
1731
1732        let absolute = std::path::absolute(&mocked_interpreter)?;
1733        let canonical = canonicalize_executable(&absolute)?;
1734        let cache_entry = InterpreterInfo::cache_entry(&absolute, &canonical, &cache);
1735        let mut cached: CachedByTimestamp<InterpreterInfo> =
1736            rmp_serde::from_slice(&fs::read(cache_entry.path())?)?;
1737        assert_eq!(cached.timestamp, Timestamp::from_path(&canonical)?);
1738        assert_eq!(
1739            cached.data.metadata.markers.python_version().version,
1740            Version::from_str("3.12")?
1741        );
1742
1743        fs::write(
1744            &mocked_interpreter,
1745            formatdoc! {r"
1746        #!/bin/sh
1747        echo queried >> '{}'
1748        echo '{}'
1749        ", query_log.display(), json.replace("3.12", "3.13")},
1750        )?;
1751
1752        // Back-to-back writes can share a Unix `ctime`. Store a well-formed entry with a
1753        // different timestamp to exercise stale-cache rejection deterministically.
1754        let modified = Timestamp::from_path(&canonical)?;
1755        cached.timestamp = if modified == Timestamp::from(UNIX_EPOCH) {
1756            Timestamp::from(UNIX_EPOCH + Duration::from_secs(1))
1757        } else {
1758            Timestamp::from(UNIX_EPOCH)
1759        };
1760        fs::write(cache_entry.path(), rmp_serde::to_vec(&cached)?)?;
1761        assert_ne!(cached.timestamp, Timestamp::from_path(&canonical)?);
1762
1763        let interpreter = Interpreter::query(&mocked_interpreter, &cache)?;
1764        assert_eq!(
1765            interpreter.markers.python_version().version,
1766            Version::from_str("3.13")?
1767        );
1768        assert_eq!(
1769            fs::read_to_string(&query_log)?,
1770            indoc! {"
1771                queried
1772                queried
1773            "}
1774        );
1775
1776        let refreshed: CachedByTimestamp<InterpreterInfo> =
1777            rmp_serde::from_slice(&fs::read(cache_entry.path())?)?;
1778        assert_eq!(refreshed.timestamp, Timestamp::from_path(&canonical)?);
1779        assert_eq!(
1780            refreshed.data.metadata.markers.python_version().version,
1781            Version::from_str("3.13")?
1782        );
1783
1784        let interpreter = Interpreter::query(&mocked_interpreter, &cache)?;
1785        assert_eq!(
1786            interpreter.markers.python_version().version,
1787            Version::from_str("3.13")?
1788        );
1789        assert_eq!(
1790            fs::read_to_string(&query_log)?,
1791            indoc! {"
1792                queried
1793                queried
1794            "}
1795        );
1796        Ok(())
1797    }
1798
1799    #[tokio::test]
1800    async fn test_cache_eviction_with_unchanged_executable() -> Result<()> {
1801        let mock_dir = tempdir()?;
1802        let mocked_interpreter = mock_dir.path().join("python");
1803        let response_file = mock_dir.path().join("response.json");
1804        let query_count = mock_dir.path().join("queries");
1805
1806        let mut response = serde_json::from_str::<Value>(mocked_interpreter_response())?;
1807        response["sys_executable"] = serde_json::to_value(&mocked_interpreter)?;
1808        fs::write(&response_file, serde_json::to_vec(&response)?)?;
1809        fs::write(
1810            &mocked_interpreter,
1811            formatdoc! {r#"
1812                #!/bin/sh
1813                printf '.' >> "{}"
1814                cat "{}"
1815            "#, query_count.display(), response_file.display()},
1816        )?;
1817        fs::set_permissions(
1818            &mocked_interpreter,
1819            std::os::unix::fs::PermissionsExt::from_mode(0o770),
1820        )?;
1821
1822        let cache = Cache::temp()?.init().await?;
1823        let original_version = Version::from_str("3.12.0")?;
1824        let updated_version = Version::from_str("3.12.13")?;
1825
1826        assert_eq!(
1827            Interpreter::query(&mocked_interpreter, &cache)?.python_version(),
1828            &original_version
1829        );
1830
1831        response["markers"]["implementation_version"] = "3.12.13".into();
1832        response["markers"]["python_full_version"] = "3.12.13".into();
1833        fs::write(&response_file, serde_json::to_vec(&response)?)?;
1834
1835        assert_eq!(
1836            Interpreter::query(&mocked_interpreter, &cache)?.python_version(),
1837            &original_version,
1838            "an unchanged executable should retain its cached interpreter metadata"
1839        );
1840
1841        Interpreter::clear_cache(&mocked_interpreter, &cache)?;
1842        assert_eq!(
1843            fs::read_to_string(&query_count)?,
1844            ".",
1845            "clearing cached metadata should not query the interpreter"
1846        );
1847        assert_eq!(
1848            Interpreter::query(&mocked_interpreter, &cache)?.python_version(),
1849            &updated_version,
1850            "clearing the cache should force the next query to run the interpreter"
1851        );
1852        assert_eq!(
1853            Interpreter::query(&mocked_interpreter, &cache)?.python_version(),
1854            &updated_version,
1855            "the next query should persist the updated interpreter metadata"
1856        );
1857        assert_eq!(
1858            fs::read_to_string(&query_count)?,
1859            "..",
1860            "the updated interpreter metadata should be cached again"
1861        );
1862
1863        Ok(())
1864    }
1865}