Skip to main content

uv_resolver/
version_map.rs

1use std::collections::BTreeMap;
2use std::collections::Bound;
3use std::ops::RangeBounds;
4use std::sync::OnceLock;
5
6use jiff::Timestamp;
7use pubgrub::Ranges;
8use tracing::{instrument, trace};
9
10use uv_client::{FlatIndexEntry, OwnedArchive, SimpleDetailMetadata, VersionFiles};
11use uv_configuration::BuildOptions;
12use uv_distribution_filename::{DistFilename, SourceDistFilename, WheelFilename};
13use uv_distribution_types::{
14    IndexEntryFilename, IndexUrl, MinimumLibcVersion, RegistryBuiltWheel, RegistrySourceDist,
15    RequiresPython,
16};
17use uv_normalize::PackageName;
18use uv_pep440::Version;
19use uv_platform_tags::{IncompatibleTag, TagCompatibility, Tags};
20use uv_preview::PreviewFeature;
21use uv_pypi_types::{HashDigest, ResolutionMetadata, Yanked};
22use uv_types::HashStrategy;
23use uv_warnings::warn_user_once;
24
25use crate::flat_index::FlatDistributions;
26use crate::prioritized_distribution::{
27    HashComparison, IncompatibleSource, IncompatibleWheel, PrioritizedDist, RegistryVariantsJson,
28    SourceDistCompatibility, WheelCompatibility,
29};
30use crate::yanks::AllowedYanks;
31
32/// A map from versions to distributions.
33#[derive(Debug)]
34pub struct VersionMap {
35    /// The inner representation of the version map.
36    inner: VersionMapInner,
37}
38
39impl VersionMap {
40    /// Initialize a [`VersionMap`] from the given metadata.
41    ///
42    /// Note it is possible for files to have a different yank status per PEP 592 but in the official
43    /// PyPI warehouse this cannot happen.
44    ///
45    /// Here, we track if each file is yanked separately. If a release is partially yanked, the
46    /// unyanked distributions _can_ be used.
47    ///
48    /// PEP 592: <https://peps.python.org/pep-0592/#warehouse-pypi-implementation-notes>
49    #[instrument(skip_all, fields(package_name))]
50    pub(crate) fn from_simple_metadata(
51        simple_metadata: OwnedArchive<SimpleDetailMetadata>,
52        package_name: &PackageName,
53        index: IndexUrl,
54        tags: Option<Tags>,
55        requires_python: RequiresPython,
56        allowed_yanks: AllowedYanks,
57        hasher: HashStrategy,
58        included_version_cutoff: Option<Timestamp>,
59        available_version_cutoff: Option<Timestamp>,
60        flat_index: Option<FlatDistributions>,
61        build_options: &BuildOptions,
62        minimum_libc_version: Option<MinimumLibcVersion>,
63    ) -> Self {
64        let mut local = false;
65        let mut entries = Vec::with_capacity(simple_metadata.iter().size_hint().0);
66        // Create stubs for each entry in simple metadata. The full conversion
67        // from a `VersionFiles` to a PrioritizedDist for each version
68        // isn't done until that specific version is requested.
69        for (datum_index, datum) in simple_metadata.iter().enumerate() {
70            // Index metadata alone does not provide an installable distribution.
71            if datum.files.wheels.is_empty() && datum.files.source_dists.is_empty() {
72                continue;
73            }
74            let version = rkyv::deserialize::<Version, rkyv::rancor::Error>(&datum.version)
75                .expect("archived version always deserializes");
76
77            local |= version.is_local();
78            debug_assert!(
79                entries
80                    .last()
81                    .is_none_or(|entry: &VersionMapLazyEntry| entry.version < version),
82                "simple metadata versions must be sorted and unique"
83            );
84            entries.push(VersionMapLazyEntry {
85                version,
86                dist: LazyPrioritizedDist {
87                    flat: None,
88                    simple: Some(SimplePrioritizedDist {
89                        datum_index,
90                        dist: OnceLock::new(),
91                    }),
92                },
93            });
94        }
95        let mut map = VersionMapLazyIndex { entries };
96        // If a set of flat distributions have been given, linearly merge the
97        // already sorted flat entries with the archive-ordered simple vector.
98        if let Some(flat_index) = flat_index {
99            map = map.merge_flat(flat_index);
100        }
101        Self {
102            inner: VersionMapInner::Lazy(VersionMapLazy {
103                package_name: package_name.clone(),
104                map,
105                local,
106                simple_metadata,
107                no_binary: build_options.no_binary_package(package_name),
108                no_build: build_options.no_build_package(package_name),
109                index,
110                tags,
111                allowed_yanks,
112                hasher,
113                requires_python,
114                included_version_cutoff,
115                available_version_cutoff,
116                minimum_libc_version,
117            }),
118        }
119    }
120
121    #[instrument(skip_all, fields(package_name))]
122    pub(crate) fn from_flat_metadata(
123        flat_metadata: Vec<FlatIndexEntry>,
124        tags: Option<&Tags>,
125        hasher: &HashStrategy,
126        build_options: &BuildOptions,
127        minimum_libc_version: Option<MinimumLibcVersion>,
128    ) -> Self {
129        FlatDistributions::from_entries(
130            flat_metadata,
131            tags,
132            hasher,
133            build_options,
134            minimum_libc_version,
135        )
136        .into()
137    }
138
139    /// Return the [`ResolutionMetadata`] for the given version, if any.
140    pub(crate) fn get_metadata(&self, version: &Version) -> Option<ResolutionMetadata> {
141        match self.inner {
142            VersionMapInner::Eager(_) => None,
143            VersionMapInner::Lazy(ref lazy) => lazy.get_metadata(version),
144        }
145    }
146
147    /// Return the [`DistFile`] for the given version, if any.
148    pub(crate) fn get(&self, version: &Version) -> Option<&PrioritizedDist> {
149        match self.inner {
150            VersionMapInner::Eager(ref eager) => eager.map.get(version),
151            VersionMapInner::Lazy(ref lazy) => lazy.get(version),
152        }
153    }
154
155    /// Return an iterator over the versions in this map.
156    pub(crate) fn versions(&self) -> impl DoubleEndedIterator<Item = &Version> {
157        match &self.inner {
158            VersionMapInner::Eager(eager) => either::Either::Left(eager.map.keys()),
159            VersionMapInner::Lazy(lazy) => either::Either::Right(lazy.map.keys()),
160        }
161    }
162
163    /// Returns versions with at least one file not excluded by an upload-time cutoff, in ascending
164    /// order.
165    ///
166    /// Versions unavailable for other reasons remain present so callers receive a conservative
167    /// superset of selectable versions. These reasons include yanks, hashes, `requires-python`,
168    /// and `--no-binary` or `--no-build` policies. Flat-index versions bypass upload-time cutoffs
169    /// because their files do not carry upload times.
170    pub(crate) fn included_versions(&self) -> impl DoubleEndedIterator<Item = &Version> {
171        match &self.inner {
172            VersionMapInner::Eager(eager) => either::Either::Left(eager.map.keys()),
173            VersionMapInner::Lazy(lazy) => either::Either::Right(lazy.included_versions()),
174        }
175    }
176
177    /// Return the index URL where this package came from.
178    pub(crate) fn index(&self) -> Option<&IndexUrl> {
179        match &self.inner {
180            VersionMapInner::Eager(_) => None,
181            VersionMapInner::Lazy(lazy) => Some(&lazy.index),
182        }
183    }
184
185    /// Return an example of a wheel name rejected by this index.
186    pub(crate) fn mismatched_wheel_name(&self) -> Option<PackageName> {
187        match &self.inner {
188            VersionMapInner::Eager(_) => None,
189            VersionMapInner::Lazy(lazy) => lazy.simple_metadata.mismatched_wheel_name(),
190        }
191    }
192
193    /// Return the included-version cutoff for this version map, if any.
194    pub(crate) fn included_version_cutoff(&self) -> Option<&Timestamp> {
195        match &self.inner {
196            VersionMapInner::Eager(_) => None,
197            VersionMapInner::Lazy(lazy) => lazy.included_version_cutoff.as_ref(),
198        }
199    }
200
201    /// Return an iterator over the versions and distributions.
202    ///
203    /// Note that the value returned in this iterator is a [`VersionMapDist`],
204    /// which can be used to lazily request a [`CompatibleDist`]. This is
205    /// useful in cases where one can skip materializing a full distribution
206    /// for each version.
207    pub(crate) fn iter(
208        &self,
209        range: &Ranges<Version>,
210    ) -> impl DoubleEndedIterator<Item = (&Version, VersionMapDistHandle<'_>)> {
211        // Performance optimization: If we only have a single version, return that version directly.
212        if let Some(version) = range.as_singleton() {
213            either::Either::Left(match self.inner {
214                VersionMapInner::Eager(ref eager) => {
215                    either::Either::Left(eager.map.get_key_value(version).into_iter().map(
216                        move |(version, dist)| {
217                            let version_map_dist = VersionMapDistHandle {
218                                inner: VersionMapDistHandleInner::Eager(dist),
219                            };
220                            (version, version_map_dist)
221                        },
222                    ))
223                }
224                VersionMapInner::Lazy(ref lazy) => {
225                    either::Either::Right(lazy.map.get(version).into_iter().map(move |entry| {
226                        let version_map_dist = VersionMapDistHandle {
227                            inner: VersionMapDistHandleInner::Lazy {
228                                lazy,
229                                dist: &entry.dist,
230                            },
231                        };
232                        (&entry.version, version_map_dist)
233                    }))
234                }
235            })
236        } else {
237            either::Either::Right(match self.inner {
238                VersionMapInner::Eager(ref eager) => {
239                    either::Either::Left(eager.map.range(BoundingRange::from(range)).map(
240                        |(version, dist)| {
241                            let version_map_dist = VersionMapDistHandle {
242                                inner: VersionMapDistHandleInner::Eager(dist),
243                            };
244                            (version, version_map_dist)
245                        },
246                    ))
247                }
248                VersionMapInner::Lazy(ref lazy) => {
249                    either::Either::Right(lazy.map.range(BoundingRange::from(range)).iter().map(
250                        |entry| {
251                            let version_map_dist = VersionMapDistHandle {
252                                inner: VersionMapDistHandleInner::Lazy {
253                                    lazy,
254                                    dist: &entry.dist,
255                                },
256                            };
257                            (&entry.version, version_map_dist)
258                        },
259                    ))
260                }
261            })
262        }
263    }
264
265    /// Return an iterator over the versions that can be considered for selection.
266    ///
267    /// Unlike [`Self::iter`], this skips lazy registry versions whose files are all excluded by
268    /// an upload-time cutoff without materializing their distributions. Files without an upload
269    /// time remain included so that materialization can emit the appropriate warning.
270    pub(crate) fn iter_included(
271        &self,
272        range: &Ranges<Version>,
273    ) -> impl DoubleEndedIterator<Item = (&Version, VersionMapDistHandle<'_>)> {
274        self.iter(range).filter(|(_, dist)| dist.is_included())
275    }
276
277    /// Return the [`Hashes`] for the given version, if any.
278    pub(crate) fn hashes(&self, version: &Version) -> Option<&[HashDigest]> {
279        match self.inner {
280            VersionMapInner::Eager(ref eager) => {
281                eager.map.get(version).map(PrioritizedDist::hashes)
282            }
283            VersionMapInner::Lazy(ref lazy) => lazy.get(version).map(PrioritizedDist::hashes),
284        }
285    }
286
287    /// Returns the total number of distinct versions in this map.
288    ///
289    /// Note that this may include versions of distributions that are not
290    /// usable in the current environment.
291    pub(crate) fn len(&self) -> usize {
292        match self.inner {
293            VersionMapInner::Eager(VersionMapEager { ref map, .. }) => map.len(),
294            VersionMapInner::Lazy(VersionMapLazy { ref map, .. }) => map.len(),
295        }
296    }
297
298    /// Returns `true` if the map contains at least one local version (e.g., `2.6.0+cpu`).
299    pub(crate) fn local(&self) -> bool {
300        match self.inner {
301            VersionMapInner::Eager(ref map) => map.local,
302            VersionMapInner::Lazy(ref map) => map.local,
303        }
304    }
305}
306
307impl From<FlatDistributions> for VersionMap {
308    fn from(flat_index: FlatDistributions) -> Self {
309        let local = flat_index.iter().any(|(version, _)| version.is_local());
310        let map = flat_index.into();
311        Self {
312            inner: VersionMapInner::Eager(VersionMapEager { map, local }),
313        }
314    }
315}
316
317/// A lazily initialized distribution.
318///
319/// This permits access to a handle that can be turned into a resolvable
320/// distribution when desired. This is coupled with a `Version` in
321/// [`VersionMap::iter`] to permit iteration over all items in a map without
322/// necessarily constructing a distribution for every version if it isn't
323/// needed.
324///
325/// Note that because of laziness, not all such items can be turned into
326/// a valid distribution. For example, if in the process of building a
327/// distribution no compatible wheel or source distribution could be found,
328/// then building a `CompatibleDist` will fail.
329pub(crate) struct VersionMapDistHandle<'a> {
330    inner: VersionMapDistHandleInner<'a>,
331}
332
333enum VersionMapDistHandleInner<'a> {
334    Eager(&'a PrioritizedDist),
335    Lazy {
336        lazy: &'a VersionMapLazy,
337        dist: &'a LazyPrioritizedDist,
338    },
339}
340
341impl<'a> VersionMapDistHandle<'a> {
342    /// Returns whether this distribution can be considered for selection.
343    fn is_included(&self) -> bool {
344        match self.inner {
345            VersionMapDistHandleInner::Eager(_) => true,
346            VersionMapDistHandleInner::Lazy { lazy, dist } => match (&dist.flat, &dist.simple) {
347                (Some(_), _) => true,
348                (None, Some(simple)) => lazy.any_file_materializable(simple),
349                (None, None) => false,
350            },
351        }
352    }
353
354    /// Returns a prioritized distribution from this handle.
355    pub(crate) fn prioritized_dist(&self) -> Option<&'a PrioritizedDist> {
356        match self.inner {
357            VersionMapDistHandleInner::Eager(dist) => Some(dist),
358            VersionMapDistHandleInner::Lazy { lazy, dist } => Some(lazy.get_lazy(dist)?),
359        }
360    }
361}
362
363/// The kind of internal version map we have.
364#[derive(Debug)]
365#[expect(clippy::large_enum_variant)]
366enum VersionMapInner {
367    /// All distributions are fully materialized in memory.
368    ///
369    /// This usually happens when one needs a `VersionMap` from a
370    /// `FlatDistributions`.
371    Eager(VersionMapEager),
372    /// Some distributions might be fully materialized (i.e., by initializing
373    /// a `VersionMap` with a `FlatDistributions`), but some distributions
374    /// might still be in their "raw" `SimpleDetailMetadata` format. In this case, a
375    /// `PrioritizedDist` isn't actually created in memory until the
376    /// specific version has been requested.
377    Lazy(VersionMapLazy),
378}
379
380/// A map from versions to distributions that are fully materialized in memory.
381#[derive(Debug)]
382struct VersionMapEager {
383    /// A map from version to distribution.
384    map: BTreeMap<Version, PrioritizedDist>,
385    /// Whether the version map contains at least one local version.
386    local: bool,
387}
388
389/// An entry in the immutable lazy version index.
390#[derive(Debug)]
391struct VersionMapLazyEntry {
392    version: Version,
393    dist: LazyPrioritizedDist,
394}
395
396/// A compact immutable version index, ordered by native PEP 440 versions.
397#[derive(Debug)]
398struct VersionMapLazyIndex {
399    entries: Vec<VersionMapLazyEntry>,
400}
401
402impl VersionMapLazyIndex {
403    /// Merge the sorted flat index into the sorted simple entries in one pass.
404    fn merge_flat(self, flat_index: FlatDistributions) -> Self {
405        let flat_count = flat_index.iter().size_hint().0;
406        let mut merged = Vec::with_capacity(self.entries.len() + flat_count);
407        let mut simple = self.entries.into_iter().peekable();
408        let mut flat = flat_index.into_iter().peekable();
409        let flat_entry = |(version, dist)| VersionMapLazyEntry {
410            version,
411            dist: LazyPrioritizedDist {
412                flat: Some(dist),
413                simple: None,
414            },
415        };
416        while let (Some(simple_entry), Some((flat_version, _))) = (simple.peek(), flat.peek()) {
417            match simple_entry.version.cmp(flat_version) {
418                std::cmp::Ordering::Less => {
419                    if let Some(entry) = simple.next() {
420                        merged.push(entry);
421                    }
422                }
423                std::cmp::Ordering::Greater => {
424                    if let Some(entry) = flat.next() {
425                        merged.push(flat_entry(entry));
426                    }
427                }
428                std::cmp::Ordering::Equal => {
429                    if let (Some(mut entry), Some((_, dist))) = (simple.next(), flat.next()) {
430                        entry.dist.flat = Some(dist);
431                        merged.push(entry);
432                    }
433                }
434            }
435        }
436        merged.extend(simple);
437        merged.extend(flat.map(flat_entry));
438
439        Self { entries: merged }
440    }
441
442    fn get(&self, version: &Version) -> Option<&VersionMapLazyEntry> {
443        let index = self
444            .entries
445            .binary_search_by(|entry| entry.version.cmp(version))
446            .ok()?;
447        self.entries.get(index)
448    }
449
450    fn keys(&self) -> impl DoubleEndedIterator<Item = &Version> {
451        self.entries.iter().map(|entry| &entry.version)
452    }
453
454    fn range(&self, range: BoundingRange<'_>) -> &[VersionMapLazyEntry] {
455        let start = match range.min {
456            Bound::Included(version) => self
457                .entries
458                .partition_point(|entry| entry.version < *version),
459            Bound::Excluded(version) => self
460                .entries
461                .partition_point(|entry| entry.version <= *version),
462            Bound::Unbounded => 0,
463        };
464        let end = match range.max {
465            Bound::Included(version) => self
466                .entries
467                .partition_point(|entry| entry.version <= *version),
468            Bound::Excluded(version) => self
469                .entries
470                .partition_point(|entry| entry.version < *version),
471            Bound::Unbounded => self.entries.len(),
472        };
473        self.entries.get(start..end).unwrap_or_default()
474    }
475
476    fn len(&self) -> usize {
477        self.entries.len()
478    }
479}
480
481/// A map that lazily materializes some prioritized distributions upon access.
482///
483/// The idea here is that some packages have a lot of versions published, and
484/// needing to materialize a full `VersionMap` with all corresponding metadata
485/// for every version in memory is expensive. Since a `SimpleDetailMetadata` can be
486/// materialized with very little cost (via `rkyv` in the warm cached case),
487/// avoiding another conversion step into a fully filled out `VersionMap` can
488/// provide substantial savings in some cases.
489#[derive(Debug)]
490struct VersionMapLazy {
491    /// The normalized package name used to reconstruct cached wheel filenames.
492    package_name: PackageName,
493    /// An immutable archive-order index from version to possibly-initialized distribution.
494    map: VersionMapLazyIndex,
495    /// Whether the version map contains at least one local version.
496    local: bool,
497    /// The raw simple metadata from which `PrioritizedDist`s should
498    /// be constructed.
499    simple_metadata: OwnedArchive<SimpleDetailMetadata>,
500    /// When true, wheels aren't allowed.
501    no_binary: bool,
502    /// When true, source dists aren't allowed.
503    no_build: bool,
504    /// The URL of the index where this package came from.
505    index: IndexUrl,
506    /// The set of compatibility tags that determines whether a wheel is usable
507    /// in the current environment.
508    tags: Option<Tags>,
509    /// Files newer than this timestamp are considered excluded, i.e., that they cannot be selected by the
510    /// resolver.
511    included_version_cutoff: Option<Timestamp>,
512    /// Files newer than this timestamp are considered unavailable, i.e., that they do not exist.
513    available_version_cutoff: Option<Timestamp>,
514    /// Which yanked versions are allowed
515    allowed_yanks: AllowedYanks,
516    /// The hashes of allowed distributions.
517    hasher: HashStrategy,
518    /// The `requires-python` constraint for the resolution.
519    requires_python: RequiresPython,
520    /// The libc baselines required during universal resolution.
521    minimum_libc_version: Option<MinimumLibcVersion>,
522}
523
524impl VersionMapLazy {
525    /// Returns the registry-provided metadata for the given version, if it exists.
526    fn get_metadata(&self, version: &Version) -> Option<ResolutionMetadata> {
527        let archived = self
528            .map
529            .get(version)
530            .and_then(|entry| entry.dist.simple.as_ref())
531            .and_then(|simple| self.simple_metadata.datum(simple.datum_index))
532            .and_then(|datum| datum.metadata.as_deref())?;
533        Some(
534            rkyv::deserialize::<ResolutionMetadata, rkyv::rancor::Error>(archived)
535                .expect("archived metadata always deserializes"),
536        )
537    }
538
539    /// Returns the distribution for the given version, if it exists.
540    fn get(&self, version: &Version) -> Option<&PrioritizedDist> {
541        self.get_lazy(&self.map.get(version)?.dist)
542    }
543
544    /// Returns an iterator over the versions with at least one file within the exclude-newer
545    /// cutoffs, without materializing the distributions.
546    fn included_versions(&self) -> impl DoubleEndedIterator<Item = &Version> {
547        self.map.entries.iter().filter_map(move |entry| {
548            let included = match (&entry.dist.flat, &entry.dist.simple) {
549                // Flat index files have no upload times and bypass the cutoffs.
550                (Some(_), _) => true,
551                (None, Some(simple)) => self.any_file_included(simple),
552                (None, None) => false,
553            };
554            included.then_some(&entry.version)
555        })
556    }
557
558    /// Returns whether at least one file keeps this version inside the candidate universe.
559    ///
560    /// This mirrors the per-file cutoff handling in [`Self::get_simple`] without materializing the
561    /// distribution, including the two cutoff modes' distinct handling of missing upload times.
562    fn any_file_included(&self, simple: &SimplePrioritizedDist) -> bool {
563        if self.included_version_cutoff.is_none() && self.available_version_cutoff.is_none() {
564            return true;
565        }
566        let Some(datum) = self.simple_metadata.datum(simple.datum_index) else {
567            return false;
568        };
569        let files = &datum.files;
570        files
571            .wheels
572            .iter()
573            .chain(files.source_dists.iter())
574            .any(|file| {
575                let upload_time = file.upload_time_utc_ms();
576                let excluded = if let Some(cutoff) = &self.included_version_cutoff {
577                    upload_time.is_none_or(|t| t >= cutoff.as_millisecond())
578                } else if let Some(cutoff) = &self.available_version_cutoff {
579                    upload_time.is_some_and(|t| t >= cutoff.as_millisecond())
580                } else {
581                    false
582                };
583                !excluded
584            })
585    }
586
587    /// Returns whether a version should be materialized during candidate selection.
588    ///
589    /// Missing upload times are retained here, even for `included_version_cutoff`, since
590    /// materializing them is what emits the corresponding `exclude-newer` warning.
591    fn any_file_materializable(&self, simple: &SimplePrioritizedDist) -> bool {
592        let Some(cutoff) = self
593            .included_version_cutoff
594            .as_ref()
595            .or(self.available_version_cutoff.as_ref())
596        else {
597            return true;
598        };
599        let Some(datum) = self.simple_metadata.datum(simple.datum_index) else {
600            return false;
601        };
602        datum
603            .files
604            .wheels
605            .iter()
606            .chain(datum.files.source_dists.iter())
607            .any(|file| {
608                file.upload_time_utc_ms()
609                    .is_none_or(|upload_time| upload_time < cutoff.as_millisecond())
610            })
611    }
612
613    /// Given a reference to a possibly-initialized distribution that is in
614    /// this lazy map, return the corresponding distribution.
615    ///
616    /// When both a flat and simple distribution are present internally, they
617    /// are merged automatically.
618    fn get_lazy<'p>(&'p self, lazy_dist: &'p LazyPrioritizedDist) -> Option<&'p PrioritizedDist> {
619        match (&lazy_dist.flat, &lazy_dist.simple) {
620            (Some(flat), Some(simple)) => self.get_simple(Some(flat), simple),
621            (Some(flat), None) => Some(flat),
622            (None, Some(simple)) => self.get_simple(None, simple),
623            (None, None) => None,
624        }
625    }
626
627    /// Given an optional starting point, return the final form of the
628    /// given simple distribution. If it wasn't initialized yet, then this
629    /// initializes it. If the distribution would otherwise be empty, this
630    /// returns `None`.
631    fn get_simple<'p>(
632        &'p self,
633        init: Option<&'p PrioritizedDist>,
634        simple: &'p SimplePrioritizedDist,
635    ) -> Option<&'p PrioritizedDist> {
636        let get_or_init = || {
637            let files = rkyv::deserialize::<VersionFiles, rkyv::rancor::Error>(
638                &self
639                    .simple_metadata
640                    .datum(simple.datum_index)
641                    .expect("index to lazy dist is correct")
642                    .files,
643            )
644            .expect("archived version files always deserializes");
645            let mut priority_dist = init.cloned().unwrap_or_default();
646            for (filename, file) in files.all_entries(&self.package_name) {
647                let filename = match filename {
648                    IndexEntryFilename::DistFilename(filename) => filename,
649                    IndexEntryFilename::VariantJson(filename) => {
650                        if !priority_dist
651                            .variants_json()
652                            .iter()
653                            .any(|variants_json| variants_json.index == self.index)
654                        {
655                            priority_dist.insert_variants_json(RegistryVariantsJson {
656                                filename,
657                                file,
658                                index: self.index.clone(),
659                            });
660                        }
661                        continue;
662                    }
663                };
664                // Support resolving as if it were an earlier timestamp, at least as long files have
665                // upload time information.
666                let (excluded, upload_time) = if let Some(included_version_cutoff) =
667                    &self.included_version_cutoff
668                {
669                    match file.upload_time_utc_ms.as_ref() {
670                        Some(&upload_time)
671                            if upload_time >= included_version_cutoff.as_millisecond() =>
672                        {
673                            trace!(
674                                "Excluding `{}` (uploaded {upload_time}) due to exclude-newer ({included_version_cutoff})",
675                                file.filename
676                            );
677                            (true, Some(upload_time))
678                        }
679                        None => {
680                            warn_user_once!(
681                                "`{}` is missing an upload date, but user provided: {included_version_cutoff}",
682                                file.filename,
683                            );
684                            (true, None)
685                        }
686                        _ => (false, None),
687                    }
688                } else if let Some(available_version_cutoff) = &self.available_version_cutoff {
689                    match file.upload_time_utc_ms.as_ref() {
690                        Some(&upload_time)
691                            if upload_time >= available_version_cutoff.as_millisecond() =>
692                        {
693                            trace!(
694                                "Excluding `{}` (uploaded {upload_time}) due to available version cutoff ({available_version_cutoff})",
695                                file.filename
696                            );
697                            (true, Some(upload_time))
698                        }
699                        _ => (false, None),
700                    }
701                } else {
702                    (false, None)
703                };
704
705                let file = file.assume_canonical();
706
707                // Prioritize amongst all available files.
708                let yanked = file.yanked.as_deref();
709                let hashes = file.hashes.clone();
710                match filename {
711                    DistFilename::WheelFilename(filename) => {
712                        let compatibility = self.wheel_compatibility(
713                            &filename,
714                            &filename.name,
715                            &filename.version,
716                            hashes.as_slice(),
717                            yanked,
718                            excluded,
719                            upload_time,
720                        );
721                        let dist = RegistryBuiltWheel {
722                            filename,
723                            file: Box::new(file),
724                            index: self.index.clone(),
725                            size_is_authoritative: false,
726                        };
727                        priority_dist.insert_built(
728                            dist,
729                            hashes,
730                            compatibility,
731                            self.minimum_libc_version,
732                        );
733                    }
734                    DistFilename::SourceDistFilename(filename) => {
735                        let compatibility = self.source_dist_compatibility(
736                            &filename,
737                            hashes.as_slice(),
738                            yanked,
739                            excluded,
740                            upload_time,
741                        );
742                        let dist = RegistrySourceDist {
743                            name: filename.name.clone(),
744                            version: filename.version.clone(),
745                            ext: filename.extension,
746                            file: Box::new(file),
747                            index: self.index.clone(),
748                            wheels: vec![],
749                            size_is_authoritative: false,
750                        };
751                        priority_dist.insert_source(dist, hashes, compatibility);
752                    }
753                }
754            }
755            if priority_dist.is_empty() {
756                None
757            } else {
758                Some(priority_dist)
759            }
760        };
761        simple.dist.get_or_init(get_or_init).as_ref()
762    }
763
764    fn source_dist_compatibility(
765        &self,
766        filename: &SourceDistFilename,
767        hashes: &[HashDigest],
768        yanked: Option<&Yanked>,
769        excluded: bool,
770        upload_time: Option<i64>,
771    ) -> SourceDistCompatibility {
772        // Check if after upload time cutoff
773        if excluded {
774            return SourceDistCompatibility::Incompatible(IncompatibleSource::ExcludeNewer(
775                upload_time,
776            ));
777        }
778
779        // Check if builds are disabled
780        if self.no_build {
781            return SourceDistCompatibility::Incompatible(IncompatibleSource::NoBuild);
782        }
783
784        // Check if yanked
785        if let Some(yanked) = yanked {
786            if yanked.is_yanked()
787                && !self
788                    .allowed_yanks
789                    .contains(&filename.name, &filename.version)
790            {
791                return SourceDistCompatibility::Incompatible(IncompatibleSource::Yanked(
792                    yanked.clone(),
793                ));
794            }
795        }
796
797        // Check if the filename is PEP 625-compliant.
798        // TODO: Strengthen this check more; right now we allow `.zip`
799        // (which is not compliant) and we don't strictly
800        // enforce the formatting rules for the name or version.
801        if !filename.extension.is_pep625_compliant() {
802            return SourceDistCompatibility::Incompatible(IncompatibleSource::NotPep625Filename);
803        }
804
805        // Check if hashes line up. If hashes aren't required, they're considered matching.
806        let hash_policy = self
807            .hasher
808            .archive_policy_for_package(&filename.name, &filename.version);
809        let required_hashes = hash_policy.digests();
810        let hash = if required_hashes.is_empty() {
811            HashComparison::Matched
812        } else {
813            if hashes.is_empty() {
814                HashComparison::Missing
815            } else if hash_policy.matches(hashes) {
816                HashComparison::Matched
817            } else {
818                HashComparison::Mismatched
819            }
820        };
821
822        SourceDistCompatibility::Compatible(hash)
823    }
824
825    fn wheel_compatibility(
826        &self,
827        filename: &WheelFilename,
828        name: &PackageName,
829        version: &Version,
830        hashes: &[HashDigest],
831        yanked: Option<&Yanked>,
832        excluded: bool,
833        upload_time: Option<i64>,
834    ) -> WheelCompatibility {
835        // Check if after upload time cutoff
836        if excluded {
837            return WheelCompatibility::Incompatible(IncompatibleWheel::ExcludeNewer(upload_time));
838        }
839
840        // Check if binaries are disabled
841        if self.no_binary {
842            return WheelCompatibility::Incompatible(IncompatibleWheel::NoBinary);
843        }
844
845        // Check if yanked
846        if let Some(yanked) = yanked {
847            if yanked.is_yanked() && !self.allowed_yanks.contains(name, version) {
848                return WheelCompatibility::Incompatible(IncompatibleWheel::Yanked(yanked.clone()));
849            }
850        }
851
852        if filename.variant().is_some() && !uv_preview::is_enabled(PreviewFeature::WheelVariants) {
853            return WheelCompatibility::Incompatible(IncompatibleWheel::Tag(
854                IncompatibleTag::Variant,
855            ));
856        }
857
858        // Determine a compatibility for the wheel based on tags.
859        let priority = if let Some(tags) = &self.tags {
860            match filename.tag_compatibility(tags) {
861                TagCompatibility::Incompatible(tag) => {
862                    return WheelCompatibility::Incompatible(IncompatibleWheel::Tag(tag));
863                }
864                TagCompatibility::Compatible(priority) => Some(priority),
865            }
866        } else {
867            // Check if the wheel is compatible with the `requires-python` (i.e., the Python
868            // ABI tag is not less than the `requires-python` minimum version).
869            if !self.requires_python.matches_wheel_tag(filename) {
870                return WheelCompatibility::Incompatible(IncompatibleWheel::Tag(
871                    IncompatibleTag::AbiPythonVersion,
872                ));
873            }
874            None
875        };
876
877        // Check if hashes line up. If hashes aren't required, they're considered matching.
878        let hash_policy = self.hasher.archive_policy_for_package(name, version);
879        let required_hashes = hash_policy.digests();
880        let hash = if required_hashes.is_empty() {
881            HashComparison::Matched
882        } else {
883            if hashes.is_empty() {
884                HashComparison::Missing
885            } else if hash_policy.matches(hashes) {
886                HashComparison::Matched
887            } else {
888                HashComparison::Mismatched
889            }
890        };
891
892        WheelCompatibility::from_tag_priority(filename, hash, priority)
893    }
894}
895
896/// Represents a possibly initialized [`PrioritizedDist`] for a package version.
897#[derive(Debug)]
898struct LazyPrioritizedDist {
899    /// An eagerly constructed distribution from [`FlatDistributions`], if present.
900    flat: Option<PrioritizedDist>,
901    /// A lazy index into [`SimpleDetailMetadata`], if present.
902    simple: Option<SimplePrioritizedDist>,
903}
904
905/// Represents a lazily initialized `PrioritizedDist`.
906#[derive(Debug)]
907struct SimplePrioritizedDist {
908    /// An offset into `SimpleDetailMetadata` corresponding to a `SimpleMetadatum`.
909    /// This provides access to a `VersionFiles` that is used to construct a
910    /// `PrioritizedDist`.
911    datum_index: usize,
912    /// A lazily initialized distribution.
913    ///
914    /// Note that the `Option` does not represent the initialization state.
915    /// The `Option` can be `None` even after initialization, for example,
916    /// if initialization could not find any usable files from which to
917    /// construct a distribution. (One easy way to effect this, at the time
918    /// of writing, is to use `--exclude-newer 1900-01-01`.)
919    dist: OnceLock<Option<PrioritizedDist>>,
920}
921
922/// A range that can be used to iterate over a subset of a [`BTreeMap`].
923#[derive(Debug)]
924struct BoundingRange<'a> {
925    min: Bound<&'a Version>,
926    max: Bound<&'a Version>,
927}
928
929impl<'a> From<&'a Ranges<Version>> for BoundingRange<'a> {
930    fn from(value: &'a Ranges<Version>) -> Self {
931        let (min, max) = value
932            .bounding_range()
933            .unwrap_or((Bound::Unbounded, Bound::Unbounded));
934        Self { min, max }
935    }
936}
937
938impl<'a> RangeBounds<Version> for BoundingRange<'a> {
939    fn start_bound(&self) -> Bound<&'a Version> {
940        self.min
941    }
942
943    fn end_bound(&self) -> Bound<&'a Version> {
944        self.max
945    }
946}