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