Skip to main content

uv_python_interpreter/
interpreter.rs

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