uv-dispatch 0.0.92

This is an internal component crate of uv
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Avoid cyclic crate dependencies between [resolver][`uv_resolver`],
//! [installer][`uv_installer`] and [build frontend][`uv_build_frontend`] through [`BuildDispatch`]
//! implementing [`BuildContext`].

use std::ffi::{OsStr, OsString};
use std::future::{self, Future};
use std::path::Path;

use anyhow::Result;
use futures::FutureExt;
use itertools::Itertools;
use rustc_hash::FxHashMap;
use thiserror::Error;
use tracing::{debug, instrument, trace};

use uv_build_backend::{Error as BuildBackendError, check_direct_build};
use uv_build_frontend::{SourceBuild, SourceBuildContext};
use uv_cache::Cache;
use uv_client::RegistryClient;
use uv_configuration::{
    BuildKind, BuildOptions, Constraints, DependencyModifiers, HashCheckingMode, IndexStrategy,
    NoSources, Reinstall,
};
use uv_configuration::{BuildOutput, Concurrency};
use uv_distribution::DistributionDatabase;
use uv_distribution_filename::DistFilename;
use uv_distribution_types::{
    CachedDist, ConfigSettings, DependencyMetadata, ExtraBuildRequires, ExtraBuildVariables,
    Identifier, IndexCapabilities, IndexLocations, IsBuildBackendError, Name,
    PackageConfigSettings, Requirement, Resolution, SourceDist, VersionOrUrlRef,
};
use uv_git::GitResolver;
use uv_installer::{InstallationStrategy, Installer, Plan, Planner, Preparer, SitePackages};
use uv_preview::Preview;
use uv_pypi_types::Conflicts;
use uv_python_interpreter::{Interpreter, PythonEnvironment};
use uv_requirements::LookaheadResolver;
use uv_resolver::{
    ExcludeNewer, FlatIndex, Flexibility, InMemoryIndex, Manifest, OptionsBuilder,
    PythonRequirement, Resolver, ResolverEnvironment,
};
use uv_static::TarBackend;
use uv_types::{
    AnyErrorBuild, BuildArena, BuildContext, BuildIsolation, BuildStack, EmptyInstalledPackages,
    HashStrategy, HashVerification, InFlight, ResolvedRequirements, SourceTreeEditablePolicy,
};
use uv_workspace::WorkspaceCache;

#[derive(Debug, Error)]
pub enum BuildDispatchError {
    #[error(transparent)]
    BuildFrontend(#[from] AnyErrorBuild),

    #[error(transparent)]
    BuildBackend(#[from] BuildBackendError),

    #[error(transparent)]
    Tags(#[from] uv_platform_tags::TagsError),

    #[error(transparent)]
    Resolve(#[from] uv_resolver::ResolveError),

    #[error(
        "No solution found when resolving: {}",
        requirements.iter().format_with(", ", |requirement, f| f(&format_args!("`{requirement}`")))
    )]
    ResolveRequirements {
        requirements: Vec<Requirement>,
        #[source]
        source: uv_resolver::ResolveError,
    },

    #[error(transparent)]
    Join(#[from] tokio::task::JoinError),

    #[error(transparent)]
    Anyhow(#[from] anyhow::Error),

    #[error(transparent)]
    Prepare(#[from] uv_installer::PrepareError),

    #[error("Failed to uninstall build dependencies")]
    UninstallBuildDependencies(#[source] uv_installer::UninstallError),

    #[error("Failed to install build dependencies")]
    InstallBuildDependencies(#[source] uv_installer::InstallError),

    #[error(transparent)]
    Plan(#[from] uv_installer::PlanError),

    #[error(transparent)]
    Lookahead(#[from] uv_requirements::Error),
}

impl uv_errors::Hinted for BuildDispatchError {
    fn hints(&self) -> uv_errors::Hints<'_> {
        match self {
            Self::BuildFrontend(err) => err.hints(),
            Self::Plan(error) => error.hints(),
            Self::Resolve(err) | Self::ResolveRequirements { source: err, .. } => err.hints(),
            Self::BuildBackend(_)
            | Self::Tags(_)
            | Self::Join(_)
            | Self::Anyhow(_)
            | Self::Prepare(_)
            | Self::UninstallBuildDependencies(_)
            | Self::InstallBuildDependencies(_)
            | Self::Lookahead(_) => uv_errors::Hints::none(),
        }
    }
}

impl IsBuildBackendError for BuildDispatchError {
    fn is_user_failure(&self) -> bool {
        match self {
            Self::BuildFrontend(error) => error.is_user_failure(),
            Self::Resolve(error) | Self::ResolveRequirements { source: error, .. } => {
                error.is_user_failure()
            }
            Self::Prepare(error) => error.is_user_failure(),
            Self::Lookahead(error) => error.is_user_failure(),
            Self::BuildBackend(_)
            | Self::Tags(_)
            | Self::Join(_)
            | Self::Anyhow(_)
            | Self::UninstallBuildDependencies(_)
            | Self::InstallBuildDependencies(_)
            | Self::Plan(_) => false,
        }
    }

    fn is_build_backend_error(&self) -> bool {
        match self {
            Self::BuildBackend(_)
            | Self::Tags(_)
            | Self::Resolve(_)
            | Self::ResolveRequirements { .. }
            | Self::Join(_)
            | Self::Anyhow(_)
            | Self::Prepare(_)
            | Self::UninstallBuildDependencies(_)
            | Self::InstallBuildDependencies(_)
            | Self::Plan(_)
            | Self::Lookahead(_) => false,
            Self::BuildFrontend(err) => err.is_build_backend_error(),
        }
    }
}

/// The main implementation of [`BuildContext`], used by the CLI, see [`BuildContext`]
/// documentation.
#[derive(Clone)]
pub struct BuildDispatch<'a> {
    client: &'a RegistryClient,
    cache: &'a Cache,
    constraints: &'a Constraints,
    interpreter: &'a Interpreter,
    index_locations: &'a IndexLocations,
    index_strategy: IndexStrategy,
    flat_index: &'a FlatIndex,
    shared_state: SharedState,
    dependency_metadata: &'a DependencyMetadata,
    build_isolation: BuildIsolation<'a>,
    extra_build_requires: &'a ExtraBuildRequires,
    extra_build_variables: &'a ExtraBuildVariables,
    link_mode: uv_install_wheel::LinkMode,
    build_options: &'a BuildOptions,
    config_settings: &'a ConfigSettings,
    config_settings_package: &'a PackageConfigSettings,
    base_hasher: &'a HashStrategy,
    build_hash_checking: HashCheckingMode,
    exclude_newer: ExcludeNewer,
    source_build_context: SourceBuildContext,
    build_extra_env_vars: FxHashMap<OsString, OsString>,
    sources: NoSources,
    source_tree_editable_policy: SourceTreeEditablePolicy,
    workspace_cache: WorkspaceCache,
    concurrency: Concurrency,
    preview: Preview,
    tar_backend: TarBackend,
}

impl<'a> BuildDispatch<'a> {
    pub fn new(
        client: &'a RegistryClient,
        cache: &'a Cache,
        constraints: &'a Constraints,
        interpreter: &'a Interpreter,
        index_locations: &'a IndexLocations,
        flat_index: &'a FlatIndex,
        dependency_metadata: &'a DependencyMetadata,
        shared_state: SharedState,
        index_strategy: IndexStrategy,
        config_settings: &'a ConfigSettings,
        config_settings_package: &'a PackageConfigSettings,
        build_isolation: BuildIsolation<'a>,
        extra_build_requires: &'a ExtraBuildRequires,
        extra_build_variables: &'a ExtraBuildVariables,
        link_mode: uv_install_wheel::LinkMode,
        build_options: &'a BuildOptions,
        hasher: &'a HashStrategy,
        exclude_newer: ExcludeNewer,
        sources: NoSources,
        source_tree_editable_policy: SourceTreeEditablePolicy,
        workspace_cache: WorkspaceCache,
        concurrency: Concurrency,
        preview: Preview,
    ) -> Self {
        Self {
            client,
            cache,
            constraints,
            interpreter,
            index_locations,
            flat_index,
            shared_state,
            dependency_metadata,
            index_strategy,
            config_settings,
            config_settings_package,
            build_isolation,
            extra_build_requires,
            extra_build_variables,
            link_mode,
            build_options,
            base_hasher: hasher,
            build_hash_checking: match hasher.verification() {
                HashVerification::Required(_) => HashCheckingMode::Require,
                HashVerification::None | HashVerification::IfPresent(_) => HashCheckingMode::Verify,
            },
            exclude_newer,
            source_build_context: SourceBuildContext::new(concurrency.builds_semaphore.clone()),
            build_extra_env_vars: FxHashMap::default(),
            sources,
            source_tree_editable_policy,
            workspace_cache,
            concurrency,
            preview,
            tar_backend: TarBackend::from_env(),
        }
    }

    /// Fork the dispatch with a different hash strategy.
    ///
    /// In-memory resolution, download, and build caches are reset, since they may depend on the
    /// previous policy.
    #[must_use]
    pub fn fork<'fork>(&'fork self, hasher: &'fork HashStrategy) -> BuildDispatch<'fork> {
        BuildDispatch {
            base_hasher: hasher,
            shared_state: SharedState {
                build_arena: BuildArena::default(),
                ..self.shared_state.fork()
            },
            source_build_context: SourceBuildContext::new(
                self.concurrency.builds_semaphore.clone(),
            ),
            ..self.clone()
        }
    }

    /// Set the environment variables to be used when building a source distribution.
    #[must_use]
    pub fn with_build_extra_env_vars<I, K, V>(mut self, sdist_build_env_variables: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.build_extra_env_vars = sdist_build_env_variables
            .into_iter()
            .map(|(key, value)| (key.as_ref().to_owned(), value.as_ref().to_owned()))
            .collect();
        self
    }

    /// Set the hash-checking mode for build dependencies.
    ///
    /// When hashes are required, hashes from backend-generated requirements are not trusted.
    #[must_use]
    pub fn with_build_hash_checking(mut self, mode: HashCheckingMode) -> Self {
        self.build_hash_checking = mode;
        self
    }

    fn require_build_hashes(&self) -> bool {
        self.build_hash_checking.is_require()
    }
}

#[allow(refining_impl_trait)]
impl BuildContext for BuildDispatch<'_> {
    type SourceDistBuilder = SourceBuild;

    fn tar_backend(&self) -> TarBackend {
        self.tar_backend
    }

    fn interpreter(&self) -> impl Future<Output = &Interpreter> + '_ {
        future::ready(self.interpreter)
    }

    fn cache(&self) -> &Cache {
        self.cache
    }

    fn git(&self) -> &GitResolver {
        &self.shared_state.git
    }

    fn build_arena(&self) -> &BuildArena<SourceBuild> {
        &self.shared_state.build_arena
    }

    fn capabilities(&self) -> &IndexCapabilities {
        &self.shared_state.capabilities
    }

    fn dependency_metadata(&self) -> &DependencyMetadata {
        self.dependency_metadata
    }

    fn build_options(&self) -> &BuildOptions {
        self.build_options
    }

    fn build_isolation(&self) -> BuildIsolation<'_> {
        self.build_isolation
    }

    fn config_settings(&self) -> &ConfigSettings {
        self.config_settings
    }

    fn config_settings_package(&self) -> &PackageConfigSettings {
        self.config_settings_package
    }

    fn sources(&self) -> &NoSources {
        &self.sources
    }

    fn source_tree_editable_policy(&self) -> SourceTreeEditablePolicy {
        self.source_tree_editable_policy
    }

    fn locations(&self) -> &IndexLocations {
        self.index_locations
    }

    fn workspace_cache(&self) -> &WorkspaceCache {
        &self.workspace_cache
    }

    fn extra_build_requires(&self) -> &ExtraBuildRequires {
        self.extra_build_requires
    }

    fn extra_build_variables(&self) -> &ExtraBuildVariables {
        self.extra_build_variables
    }

    async fn resolve<'data>(
        &'data self,
        requirements: &'data [Requirement],
        hash_override: Option<&'data HashStrategy>,
        build_stack: &'data BuildStack,
    ) -> Result<ResolvedRequirements, BuildDispatchError> {
        let python_requirement = PythonRequirement::from_interpreter(self.interpreter);
        let marker_env = self.interpreter.to_resolver_marker_environment();
        let resolver_env = ResolverEnvironment::specific(marker_env);
        let tags = self.interpreter.tags()?;

        let active_requirements = requirements.iter().filter(|requirement| {
            requirement.evaluate_markers(Some(self.interpreter.markers()), &[])
        });
        let previous_hasher = hash_override;
        let hasher = match previous_hasher {
            Some(hasher) if self.require_build_hashes() => hasher
                .clone()
                .augment_with_metadata_requirements(active_requirements),
            previous_hasher => previous_hasher
                .unwrap_or(self.base_hasher)
                .clone()
                .augment_with_requirements(active_requirements),
        }
        .map_err(uv_requirements::Error::from)?;

        // Walk any URL requirements transitively so their sub-URLs (for example, a workspace
        // member that depends on another workspace member) are known before the resolver runs
        // its URL allow-list check. This mirrors what the project resolver does in
        // `uv_requirements::LookaheadResolver` and prevents a `DisallowedUrl` error when one
        // `build-system.requires` entry pulls in another URL dependency.
        let modifiers = DependencyModifiers::default();
        let (lookaheads, hasher) = LookaheadResolver::new(
            requirements,
            self.constraints,
            &modifiers,
            &hasher,
            &self.shared_state.index,
            DistributionDatabase::new(
                self.client,
                self,
                self.concurrency.downloads_semaphore.clone(),
            )
            .with_build_stack(build_stack),
        )
        .resolve(&resolver_env)
        .await?;

        let manifest = Manifest::simple(requirements.to_vec())
            .with_constraints(self.constraints.clone())
            .with_lookaheads(lookaheads);

        let resolver = Resolver::new(
            manifest,
            OptionsBuilder::new()
                .exclude_newer(self.exclude_newer.clone())
                .index_strategy(self.index_strategy)
                .build_options(self.build_options.clone())
                .flexibility(Flexibility::Fixed)
                .build(),
            &python_requirement,
            resolver_env,
            self.interpreter.markers(),
            // Conflicting groups only make sense when doing universal resolution.
            Conflicts::empty(),
            Some(tags),
            self.flat_index,
            &self.shared_state.index,
            &hasher,
            self,
            EmptyInstalledPackages,
            DistributionDatabase::new(
                self.client,
                self,
                self.concurrency.downloads_semaphore.clone(),
            )
            .with_build_stack(build_stack),
        )?;
        let resolution = Resolution::from(resolver.resolve().await.map_err(|source| {
            BuildDispatchError::ResolveRequirements {
                requirements: requirements.to_vec(),
                source,
            }
        })?);
        Ok(ResolvedRequirements::new(resolution, hasher))
    }

    #[instrument(
        skip(self, requirements, venv),
        fields(
            resolution = requirements.resolution().distributions().map(ToString::to_string).join(", "),
            venv = ?venv.root()
        )
    )]
    async fn install<'data>(
        &'data self,
        requirements: &'data ResolvedRequirements,
        venv: &'data PythonEnvironment,
        build_stack: &'data BuildStack,
    ) -> Result<Vec<CachedDist>, BuildDispatchError> {
        let resolution = requirements.resolution();
        let hasher = requirements.hasher();

        debug!(
            "Installing `{}` in `{}`",
            resolution
                .distributions()
                .map(ToString::to_string)
                .join("`, `"),
            venv.root().display(),
        );

        // Determine the current environment markers.
        let tags = self.interpreter.tags()?;

        // Determine the set of installed packages.
        let site_packages = SitePackages::from_environment(venv)?;

        let Plan {
            cached,
            remote,
            reinstalls,
            extraneous: _,
        } = Planner::new(resolution).build(
            site_packages,
            InstallationStrategy::Permissive,
            &Reinstall::default(),
            self.build_options,
            hasher,
            self.index_locations,
            self.config_settings,
            self.config_settings_package,
            self.extra_build_requires(),
            self.extra_build_variables,
            self.cache(),
            venv,
            tags,
        )?;

        // Nothing to do.
        if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() {
            debug!("No build requirements to install for build");
            return Ok(vec![]);
        }

        // Verify that none of the missing distributions are already in the build stack.
        for dist in &remote {
            let id = dist.distribution_id();
            if build_stack.contains(&id) {
                return Err(BuildDispatchError::BuildFrontend(
                    uv_build_frontend::Error::CyclicBuildDependency(dist.name().clone()).into(),
                ));
            }
        }

        // Download any missing distributions.
        let wheels = if remote.is_empty() {
            vec![]
        } else {
            let preparer = Preparer::new(
                self.cache,
                tags,
                hasher,
                self.build_options,
                DistributionDatabase::new(
                    self.client,
                    self,
                    self.concurrency.downloads_semaphore.clone(),
                )
                .with_build_stack(build_stack),
            );

            debug!(
                "Downloading and building requirement{} for build: {}",
                if remote.len() == 1 { "" } else { "s" },
                remote.iter().map(ToString::to_string).join(", ")
            );

            preparer
                .prepare(remote, &self.shared_state.in_flight, resolution)
                .await?
        };

        // Remove any unnecessary packages.
        if !reinstalls.is_empty() {
            let layout = venv.interpreter().layout();
            for dist_info in &reinstalls {
                let summary = uv_installer::uninstall(dist_info, &layout)
                    .await
                    .map_err(BuildDispatchError::UninstallBuildDependencies)?;
                debug!(
                    "Uninstalled {} ({} file{}, {} director{})",
                    dist_info.name(),
                    summary.file_count,
                    if summary.file_count == 1 { "" } else { "s" },
                    summary.dir_count,
                    if summary.dir_count == 1 { "y" } else { "ies" },
                );
            }
        }

        // Install the resolved distributions.
        let mut wheels = wheels.into_iter().chain(cached).collect::<Vec<_>>();
        if !wheels.is_empty() {
            debug!(
                "Installing build requirement{}: {}",
                if wheels.len() == 1 { "" } else { "s" },
                wheels.iter().map(ToString::to_string).join(", ")
            );
            wheels = Installer::new(venv, self.preview)
                .with_link_mode(self.link_mode)
                .with_cache(self.cache)
                .install(wheels)
                .await
                .map_err(BuildDispatchError::InstallBuildDependencies)?;
        }

        Ok(wheels)
    }

    #[instrument(skip_all, fields(version_id = version_id, subdirectory = ?subdirectory))]
    async fn setup_build<'data>(
        &'data self,
        source: &'data Path,
        subdirectory: Option<&'data Path>,
        install_path: &'data Path,
        stop_discovery_at: Option<&'data Path>,
        version_id: Option<&'data str>,
        dist: Option<&'data SourceDist>,
        sources: &'data NoSources,
        build_kind: BuildKind,
        build_output: BuildOutput,
        mut build_stack: BuildStack,
    ) -> Result<SourceBuild, uv_build_frontend::Error> {
        let dist_name = dist.map(uv_distribution_types::Name::name);
        let dist_version = dist
            .map(uv_distribution_types::DistributionMetadata::version_or_url)
            .and_then(|version| match version {
                VersionOrUrlRef::Version(version) => Some(version),
                VersionOrUrlRef::Url(_) => None,
            });

        // Push the current distribution onto the build stack, to prevent cyclic dependencies.
        if let Some(dist) = dist {
            build_stack.insert(dist.distribution_id());
        }

        // Get package-specific config settings if available; otherwise, use global settings.
        let config_settings = if let Some(name) = dist_name {
            if let Some(package_settings) = self.config_settings_package.get(name) {
                package_settings.clone().merge(self.config_settings.clone())
            } else {
                self.config_settings.clone()
            }
        } else {
            self.config_settings.clone()
        };

        // Get package-specific environment variables if available.
        let mut environment_variables = self.build_extra_env_vars.clone();
        if let Some(name) = dist_name {
            if let Some(package_vars) = self.extra_build_variables.get(name) {
                environment_variables.extend(
                    package_vars
                        .iter()
                        .map(|(key, value)| (OsString::from(key), OsString::from(value))),
                );
            }
        }

        let builder = SourceBuild::setup(
            source,
            subdirectory,
            install_path,
            stop_discovery_at,
            dist_name,
            dist_version,
            self.interpreter,
            self,
            self.source_build_context.clone(),
            version_id,
            self.index_locations,
            sources.clone(),
            self.workspace_cache(),
            config_settings,
            self.build_isolation,
            self.extra_build_requires,
            &build_stack,
            build_kind,
            environment_variables,
            build_output,
            self.client.credentials_cache(),
        )
        .boxed_local()
        .await?;
        Ok(builder)
    }

    async fn direct_build<'data>(
        &'data self,
        source: &'data Path,
        subdirectory: Option<&'data Path>,
        output_dir: &'data Path,
        sources: NoSources,
        build_kind: BuildKind,
        version_id: Option<&'data str>,
    ) -> Result<Option<DistFilename>, BuildDispatchError> {
        let source_tree = if let Some(subdir) = subdirectory {
            source.join(subdir)
        } else {
            source.to_path_buf()
        };

        // Only perform the direct build if the backend is uv in a compatible version.
        let source_tree_str = source_tree.display().to_string();
        let identifier = version_id.unwrap_or_else(|| &source_tree_str);
        if let Err(reason) = check_direct_build(
            &source_tree,
            uv_version::version(),
            &self.interpreter.to_resolver_marker_environment(),
            self.constraints.requirements().cloned().map(Into::into),
        ) {
            trace!("Requirements for direct build not matched because {reason}");
            return Ok(None);
        }

        debug!("Performing direct build for {identifier}");

        let output_dir = output_dir.to_path_buf();
        let tar_backend = self.tar_backend;
        let filename = tokio::task::spawn_blocking(move || -> Result<_, BuildBackendError> {
            let filename = match build_kind {
                BuildKind::Wheel => {
                    let wheel = uv_build_backend::build_wheel(
                        &source_tree,
                        &output_dir,
                        None,
                        uv_version::version(),
                        sources.is_none(),
                    )?;
                    DistFilename::WheelFilename(wheel)
                }
                BuildKind::Sdist => {
                    let source_dist = uv_build_backend::build_source_dist(
                        &source_tree,
                        &output_dir,
                        uv_version::version(),
                        sources.is_none(),
                        tar_backend,
                    )?;
                    DistFilename::SourceDistFilename(source_dist)
                }
                BuildKind::Editable => {
                    let wheel = uv_build_backend::build_editable(
                        &source_tree,
                        &output_dir,
                        None,
                        uv_version::version(),
                        sources.is_none(),
                    )?;
                    DistFilename::WheelFilename(wheel)
                }
            };
            Ok(filename)
        })
        .await??;

        Ok(Some(filename))
    }
}

/// Shared state used during resolution and installation.
///
/// All elements are `Arc`s, so we can clone freely.
#[derive(Default, Clone)]
pub struct SharedState {
    /// The resolved Git references.
    git: GitResolver,
    /// The discovered capabilities for each registry index.
    capabilities: IndexCapabilities,
    /// The fetched package versions and metadata.
    index: InMemoryIndex,
    /// The downloaded distributions.
    in_flight: InFlight,
    /// Build directories for any PEP 517 builds executed during resolution or installation.
    build_arena: BuildArena<SourceBuild>,
}

impl SharedState {
    /// Fork the [`SharedState`], creating a new in-memory index and in-flight cache.
    ///
    /// State that is universally applicable (like the Git resolver and index capabilities)
    /// are retained.
    #[must_use]
    fn fork(&self) -> Self {
        Self {
            git: self.git.clone(),
            capabilities: self.capabilities.clone(),
            build_arena: self.build_arena.clone(),
            ..Default::default()
        }
    }

    /// Return the [`GitResolver`] used by the [`SharedState`].
    pub fn git(&self) -> &GitResolver {
        &self.git
    }

    /// Return the [`InMemoryIndex`] used by the [`SharedState`].
    pub fn index(&self) -> &InMemoryIndex {
        &self.index
    }

    /// Return mutable access to the index owner. Removing cached entries additionally requires
    /// exclusive access to the index's shared storage.
    fn index_mut(&mut self) -> &mut InMemoryIndex {
        &mut self.index
    }

    /// Return the [`InFlight`] used by the [`SharedState`].
    pub fn in_flight(&self) -> &InFlight {
        &self.in_flight
    }
}

/// A [`SharedState`] instance to use for universal resolution.
#[derive(Default, Clone)]
pub struct UniversalState(SharedState);

impl std::ops::Deref for UniversalState {
    type Target = SharedState;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl UniversalState {
    /// Return mutable access to the index owner between lock operations.
    pub fn index_mut(&mut self) -> &mut InMemoryIndex {
        self.0.index_mut()
    }

    /// Fork the [`UniversalState`] to create a [`PlatformState`].
    pub fn fork(&self) -> PlatformState {
        PlatformState(self.0.fork())
    }
}

/// A [`SharedState`] instance to use for platform-specific resolution.
#[derive(Default, Clone)]
pub struct PlatformState(SharedState);

impl std::ops::Deref for PlatformState {
    type Target = SharedState;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl PlatformState {
    /// Fork the [`PlatformState`] to create a [`UniversalState`].
    pub fn fork(&self) -> UniversalState {
        UniversalState(self.0.fork())
    }

    /// Create a [`SharedState`] from the [`PlatformState`].
    pub fn into_inner(self) -> SharedState {
        self.0
    }
}