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#[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 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 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 #[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 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 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 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 pub fn find_base_python(&self) -> Result<PathBuf, io::Error> {
186 let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable());
187 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 #[inline]
213 pub fn platform(&self) -> &Platform {
214 &self.platform
215 }
216
217 #[inline]
219 pub const fn markers(&self) -> &MarkerEnvironment {
220 &self.markers
221 }
222
223 pub fn to_resolver_marker_environment(&self) -> ResolverMarkerEnvironment {
225 ResolverMarkerEnvironment::from(self.markers().clone())
226 }
227
228 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 pub fn arch(&self) -> Arch {
257 Arch::from(&self.platform().arch())
258 }
259
260 pub fn libc(&self) -> Libc {
262 Libc::from(self.platform().os())
263 }
264
265 pub fn os(&self) -> Os {
267 Os::from(self.platform().os())
268 }
269
270 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 pub fn is_virtualenv(&self) -> bool {
294 self.sys_prefix != self.sys_base_prefix
296 }
297
298 fn is_target(&self) -> bool {
300 self.target.is_some()
301 }
302
303 fn is_prefix(&self) -> bool {
305 self.prefix.is_some()
306 }
307
308 pub fn is_externally_managed(&self) -> Option<ExternallyManaged> {
313 if self.is_virtualenv() {
315 return None;
316 }
317
318 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 return Some(ExternallyManaged::default());
331 };
332
333 Some(ExternallyManaged {
334 error: ini.get("externally-managed", "Error").map(str::to_owned),
335 })
336 }
337
338 #[inline]
340 pub fn python_full_version(&self) -> &StringVersion {
341 self.markers.python_full_version()
342 }
343
344 #[inline]
346 pub fn python_version(&self) -> &Version {
347 &self.markers.python_full_version().version
348 }
349
350 #[inline]
352 pub fn python_minor_version(&self) -> Version {
353 Version::new(self.python_version().release().iter().take(2).copied())
354 }
355
356 #[inline]
358 pub(crate) fn python_patch_version(&self) -> Version {
359 Version::new(self.python_version().release().iter().take(3).copied())
360 }
361
362 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 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 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 pub fn python_tuple(&self) -> (u8, u8) {
382 (self.python_major(), self.python_minor())
383 }
384
385 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 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 pub fn implementation_tuple(&self) -> (u8, u8) {
399 (self.implementation_major(), self.implementation_minor())
400 }
401
402 pub fn implementation_name(&self) -> &str {
404 self.markers.implementation_name()
405 }
406
407 pub fn sys_base_prefix(&self) -> &Path {
409 &self.sys_base_prefix
410 }
411
412 pub fn sys_prefix(&self) -> &Path {
414 &self.sys_prefix
415 }
416
417 fn sys_base_executable(&self) -> Option<&Path> {
420 self.sys_base_executable.as_deref()
421 }
422
423 pub fn sys_executable(&self) -> &Path {
425 &self.sys_executable
426 }
427
428 pub fn extension_suffixes(&self) -> &[Box<str>] {
430 &self.extension_suffixes
431 }
432
433 pub fn real_executable(&self) -> &Path {
435 &self.real_executable
436 }
437
438 pub fn runtime_site_packages(&self) -> &[PathBuf] {
446 &self.site_packages
447 }
448
449 pub fn stdlib(&self) -> &Path {
451 &self.stdlib
452 }
453
454 fn purelib(&self) -> &Path {
456 &self.scheme.purelib
457 }
458
459 fn platlib(&self) -> &Path {
461 &self.scheme.platlib
462 }
463
464 pub fn scripts(&self) -> &Path {
466 &self.scheme.scripts
467 }
468
469 fn data(&self) -> &Path {
471 &self.scheme.data
472 }
473
474 fn include(&self) -> &Path {
476 &self.scheme.include
477 }
478
479 pub fn virtualenv(&self) -> &Scheme {
481 &self.virtualenv
482 }
483
484 pub fn manylinux_compatible(&self) -> bool {
486 self.manylinux_compatible
487 }
488
489 pub fn pointer_size(&self) -> PointerSize {
491 self.pointer_size
492 }
493
494 pub fn gil_disabled(&self) -> bool {
500 self.gil_disabled
501 }
502
503 pub fn debug_enabled(&self) -> bool {
506 self.debug_enabled
507 }
508
509 fn target(&self) -> Option<&Target> {
511 self.target.as_ref()
512 }
513
514 fn prefix(&self) -> Option<&Prefix> {
516 self.prefix.as_ref()
517 }
518
519 #[cfg(unix)]
528 pub fn is_standalone(&self) -> bool {
529 self.standalone
530 }
531
532 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 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 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 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 pub async fn lock(&self) -> Result<LockedFile, LockedFileError> {
631 if let Some(target) = self.target() {
632 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 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 LockedFile::acquire(
650 self.sys_prefix.join(".lock"),
651 LockedFileMode::Exclusive,
652 self.sys_prefix.user_display(),
653 )
654 .await
655 } else {
656 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 fn matches_variant(&self, variant: PythonVariant) -> bool {
668 match variant {
669 PythonVariant::Default => {
670 if (self.python_major(), self.python_minor()) >= (3, 14) {
673 true
676 } else {
677 !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 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 pub fn matches_version_request(&self, request: &VersionRequest) -> bool {
702 match request {
703 VersionRequest::Any => true,
704 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 && self.python_version().pre().is_none()
722 && self.matches_variant(*variant)
723 }
724 VersionRequest::Range(specifiers, variant) => {
725 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 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 pub fn matches_request(&self, request: &PythonRequest, cache: &Cache) -> bool {
799 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 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 if is_same_executable(self.sys_executable(), file) {
820 return true;
821 }
822 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 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 if self
852 .sys_executable()
853 .file_name()
854 .is_some_and(|filename| filename == name.as_str())
855 {
856 return true;
857 }
858 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 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
890pub 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#[derive(Debug, Default, Clone)]
917pub struct ExternallyManaged {
918 error: Option<String>,
919}
920
921impl ExternallyManaged {
922 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 pub unix: bool,
1061 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#[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 Detected(CpuInfo),
1118 UnsupportedArchitecture(Box<str>),
1120 Unavailable(Box<str>),
1122 Error(CpuDetectionError),
1126}
1127
1128#[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 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 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") .arg("-B") .arg("-c")
1209 .arg(script);
1210
1211 #[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 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 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 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 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 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 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 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 format!(
1376 "{}.msgpack",
1377 cache_digest(&(absolute, canonical, &python_executable, &pyvenv_launcher))
1378 ),
1379 )
1380 }
1381
1382 fn query_cached(executable: &Path, cache: &Cache) -> Result<Self, Error> {
1388 let absolute = std::path::absolute(executable)?;
1389
1390 let handle_io_error = |err: io::Error| -> Error {
1394 if err.kind() == io::ErrorKind::NotFound {
1395 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 let modified = Timestamp::from_path(canonical).map_err(handle_io_error)?;
1420
1421 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 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 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 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
1514fn find_base_python(
1540 executable: &Path,
1541 major: u8,
1542 minor: u8,
1543 suffix: &str,
1544) -> Result<PathBuf, io::Error> {
1545 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 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 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 let resolved = fs_err::read_link(&executable)?;
1582
1583 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 let resolved = uv_fs::normalize_absolute_path(&resolved)?;
1596
1597 executable = Cow::Owned(resolved);
1598 }
1599}
1600
1601fn 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 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}