Skip to main content

cargo/compiler/job_queue/
mod.rs

1//! Management of the interaction between the main `cargo` and all spawned jobs.
2//!
3//! ## Overview
4//!
5//! This module implements a job queue. A job here represents a unit of work,
6//! which is roughly a rustc invocation, a build script run, or just a no-op.
7//! The job queue primarily handles the following things:
8//!
9//! * Spawns concurrent jobs. Depending on its [`Freshness`], a job could be
10//!     either executed on a spawned thread or ran on the same thread to avoid
11//!     the threading overhead.
12//! * Controls the number of concurrency. It allocates and manages [`jobserver`]
13//!     tokens to each spawned off rustc and build scripts.
14//! * Manages the communication between the main `cargo` process and its
15//!     spawned jobs. Those [`Message`]s are sent over a [`Queue`] shared
16//!     across threads.
17//! * Schedules the execution order of each [`Job`]. Priorities are determined
18//!     when calling [`JobQueue::enqueue`] to enqueue a job. The scheduling is
19//!     relatively rudimentary and could likely be improved.
20//!
21//! A rough outline of building a queue and executing jobs is:
22//!
23//! 1. [`JobQueue::new`] to simply create one queue.
24//! 2. [`JobQueue::enqueue`] to add new jobs onto the queue.
25//! 3. Consumes the queue and executes all jobs via [`JobQueue::execute`].
26//!
27//! The primary loop happens insides [`JobQueue::execute`], which is effectively
28//! [`DrainState::drain_the_queue`]. [`DrainState`] is, as its name tells,
29//! the running state of the job queue getting drained.
30//!
31//! ## Jobserver
32//!
33//! As of Feb. 2023, Cargo and rustc have a relatively simple jobserver
34//! relationship with each other. They share a single jobserver amongst what
35//! is potentially hundreds of threads of work on many-cored systems.
36//! The jobserver could come from either the environment (e.g., from a `make`
37//! invocation), or from Cargo creating its own jobserver server if there is no
38//! jobserver to inherit from.
39//!
40//! Cargo wants to complete the build as quickly as possible, fully saturating
41//! all cores (as constrained by the `-j=N`) parameter. Cargo also must not spawn
42//! more than N threads of work: the total amount of tokens we have floating
43//! around must always be limited to N.
44//!
45//! It is not really possible to optimally choose which crate should build
46//! first or last; nor is it possible to decide whether to give an additional
47//! token to rustc first or rather spawn a new crate of work. The algorithm in
48//! Cargo prioritizes spawning as many crates (i.e., rustc processes) as
49//! possible. In short, the jobserver relationship among Cargo and rustc
50//! processes is **1 `cargo` to N `rustc`**. Cargo knows nothing beyond rustc
51//! processes in terms of parallelism[^parallel-rustc].
52//!
53//! We integrate with the [jobserver] crate, originating from GNU make
54//! [POSIX jobserver], to make sure that build scripts which use make to
55//! build C code can cooperate with us on the number of used tokens and
56//! avoid overfilling the system we're on.
57//!
58//! ## Scheduling
59//!
60//! The current scheduling algorithm is not really polished. It is simply based
61//! on a dependency graph [`DependencyQueue`]. We continue adding nodes onto
62//! the graph until we finalize it. When the graph gets finalized, it finds the
63//! sum of the cost of each dependencies of each node, including transitively.
64//! The sum of dependency cost turns out to be the cost of each given node.
65//!
66//! At the time being, the cost is just passed as a fixed placeholder in
67//! [`JobQueue::enqueue`]. In the future, we could explore more possibilities
68//! around it. For instance, we start persisting timing information for each
69//! build somewhere. For a subsequent build, we can look into the historical
70//! data and perform a PGO-like optimization to prioritize jobs, making a build
71//! fully pipelined.
72//!
73//! ## Message queue
74//!
75//! Each spawned thread running a process uses the message queue [`Queue`] to
76//! send messages back to the main thread (the one running `cargo`).
77//! The main thread coordinates everything, and handles printing output.
78//!
79//! It is important to be careful which messages use [`push`] vs [`push_bounded`].
80//! `push` is for priority messages (like tokens, or "finished") where the
81//! sender shouldn't block. We want to handle those so real work can proceed
82//! ASAP.
83//!
84//! `push_bounded` is only for messages being printed to stdout/stderr. Being
85//! bounded prevents a flood of messages causing a large amount of memory
86//! being used.
87//!
88//! `push` also avoids blocking which helps avoid deadlocks. For example, when
89//! the diagnostic server thread is dropped, it waits for the thread to exit.
90//! But if the thread is blocked on a full queue, and there is a critical
91//! error, the drop will deadlock. This should be fixed at some point in the
92//! future. The jobserver thread has a similar problem, though it will time
93//! out after 1 second.
94//!
95//! To access the message queue, each running `Job` is given its own [`JobState`],
96//! containing everything it needs to communicate with the main thread.
97//!
98//! See [`Message`] for all available message kinds.
99//!
100//! [^parallel-rustc]: In fact, `jobserver` that Cargo uses also manages the
101//!     allocation of tokens to rustc beyond the implicit token each rustc owns
102//!     (i.e., the ones used for parallel LLVM work and parallel rustc threads).
103//!     See also ["Rust Compiler Development Guide: Parallel Compilation"]
104//!     and [this comment][rustc-codegen] in rust-lang/rust.
105//!
106//! ["Rust Compiler Development Guide: Parallel Compilation"]: https://rustc-dev-guide.rust-lang.org/parallel-rustc.html
107//! [rustc-codegen]: https://github.com/rust-lang/rust/blob/5423745db8b434fcde54888b35f518f00cce00e4/compiler/rustc_codegen_ssa/src/back/write.rs#L1204-L1217
108//! [jobserver]: https://docs.rs/jobserver
109//! [POSIX jobserver]: https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html
110//! [`push`]: Queue::push
111//! [`push_bounded`]: Queue::push_bounded
112
113mod job;
114mod job_state;
115
116use crate::util::data_structures::{HashMap, HashSet};
117use std::cell::RefCell;
118use std::fmt::Write as _;
119use std::path::{Path, PathBuf};
120use std::sync::Arc;
121use std::thread::{self, Scope};
122use std::time::Duration;
123use std::{env, io};
124
125use anyhow::{Context as _, format_err};
126use jobserver::{Acquired, HelperThread};
127use semver::Version;
128use tracing::{debug, trace};
129
130pub use self::job::Freshness::{self, Dirty, Fresh};
131pub use self::job::{Job, Work};
132pub use self::job_state::JobState;
133use super::BuildContext;
134use super::BuildRunner;
135use super::CompileMode;
136use super::Unit;
137use super::UnitIndex;
138use super::custom_build::Severity;
139use super::timings::SectionTiming;
140use super::timings::Timings;
141use crate::compiler::descriptive_pkg_name;
142use crate::compiler::future_incompat::{self, FutureBreakageItem, FutureIncompatReportPackage};
143use crate::context::WarningHandling;
144use crate::diagnostics::GlobalDiagnosticStats;
145use crate::diagnostics::rules::unused_dependencies;
146use crate::resolver::ResolveBehavior;
147use crate::util::CargoResult;
148use crate::util::diagnostic_server::{self, DiagnosticPrinter};
149use crate::util::errors::AlreadyPrintedError;
150use crate::util::interning::InternedString;
151use crate::util::machine_message::{self, Message as _};
152use crate::util::{self, internal};
153use crate::util::{DependencyQueue, GlobalContext, Progress, ProgressStyle, Queue};
154use crate::workspace::{PackageId, TargetKind};
155use cargo_util_terminal::Shell;
156
157/// This structure is backed by the `DependencyQueue` type and manages the
158/// queueing of compilation steps for each package. Packages enqueue units of
159/// work and then later on the entire graph is converted to `DrainState` and
160/// executed.
161pub struct JobQueue<'gctx> {
162    queue: DependencyQueue<Unit, Artifact, Job>,
163    counts: HashMap<PackageId, usize>,
164    timings: Timings<'gctx>,
165}
166
167/// This structure is backed by the `DependencyQueue` type and manages the
168/// actual compilation step of each package. Packages enqueue units of work and
169/// then later on the entire graph is processed and compiled.
170///
171/// It is created from `JobQueue` when we have fully assembled the crate graph
172/// (i.e., all package dependencies are known).
173struct DrainState<'gctx> {
174    // This is the length of the DependencyQueue when starting out
175    total_units: usize,
176
177    queue: DependencyQueue<Unit, Artifact, Job>,
178    messages: Arc<Queue<Message>>,
179    /// Diagnostic deduplication support.
180    diag_dedupe: DiagDedupe<'gctx>,
181    /// Count of warnings, used to print a summary after the job succeeds
182    warning_count: HashMap<JobId, WarningCount>,
183    active: HashMap<JobId, Unit>,
184    compiled: HashSet<PackageId>,
185    documented: HashSet<PackageId>,
186    scraped: HashSet<PackageId>,
187    counts: HashMap<PackageId, usize>,
188    progress: Progress<'gctx>,
189    next_id: u32,
190    timings: Timings<'gctx>,
191
192    /// Map from unit index to unit, for looking up dependency information.
193    index_to_unit: HashMap<UnitIndex, Unit>,
194
195    /// Tokens that are currently owned by this Cargo, and may be "associated"
196    /// with a rustc process. They may also be unused, though if so will be
197    /// dropped on the next loop iteration.
198    ///
199    /// Note that the length of this may be zero, but we will still spawn work,
200    /// as we share the implicit token given to this Cargo process with a
201    /// single rustc process.
202    tokens: Vec<Acquired>,
203
204    /// The list of jobs that we have not yet started executing, but have
205    /// retrieved from the `queue`. We eagerly pull jobs off the main queue to
206    /// allow us to request jobserver tokens pretty early.
207    pending_queue: Vec<(Unit, Job, usize)>,
208    print: DiagnosticPrinter<'gctx>,
209
210    /// How many jobs we've finished
211    finished: usize,
212    per_package_future_incompat_reports: Vec<FutureIncompatReportPackage>,
213}
214
215/// Count of warnings, used to print a summary after the job succeeds
216#[derive(Default, Clone)]
217pub struct WarningCount {
218    /// total number of warnings
219    pub total: usize,
220    /// number of lint warnings
221    pub lints: usize,
222    /// number of warnings that were suppressed because they
223    /// were duplicates of a previous warning
224    pub duplicates: usize,
225    /// number of fixable warnings set to `NotAllowed`
226    /// if any errors have been seen for the current
227    /// target
228    pub fixable: FixableWarnings,
229    /// if any errors have been seen for the current
230    /// target
231    pub supplanted_by_errors: bool,
232}
233
234impl WarningCount {
235    /// If an error is seen this should be called
236    /// to set `fixable` to `NotAllowed`
237    fn disallow_fixable(&mut self) {
238        self.fixable = FixableWarnings::NotAllowed;
239    }
240
241    /// Checks fixable if warnings are allowed
242    /// fixable warnings are allowed if no
243    /// errors have been seen for the current
244    /// target. If an error was seen `fixable`
245    /// will be `NotAllowed`.
246    fn fixable_allowed(&self) -> bool {
247        match &self.fixable {
248            FixableWarnings::NotAllowed => false,
249            _ => true,
250        }
251    }
252}
253
254/// Used to keep track of how many fixable warnings there are
255/// and if fixable warnings are allowed
256#[derive(Default, Copy, Clone)]
257pub enum FixableWarnings {
258    NotAllowed,
259    #[default]
260    Zero,
261    Positive(usize),
262}
263
264pub struct ErrorsDuringDrain {
265    pub count: usize,
266}
267
268struct ErrorToHandle {
269    error: anyhow::Error,
270
271    /// This field is true for "interesting" errors and false for "mundane"
272    /// errors. If false, we print the above error only if it's the first one
273    /// encountered so far while draining the job queue.
274    ///
275    /// At most places that an error is propagated, we set this to false to
276    /// avoid scenarios where Cargo might end up spewing tons of redundant error
277    /// messages. For example if an i/o stream got closed somewhere, we don't
278    /// care about individually reporting every thread that it broke; just the
279    /// first is enough.
280    ///
281    /// The exception where `print_always` is true is that we do report every
282    /// instance of a rustc invocation that failed with diagnostics. This
283    /// corresponds to errors from `Message::Finish`.
284    print_always: bool,
285}
286
287impl<E> From<E> for ErrorToHandle
288where
289    anyhow::Error: From<E>,
290{
291    fn from(error: E) -> Self {
292        ErrorToHandle {
293            error: anyhow::Error::from(error),
294            print_always: false,
295        }
296    }
297}
298
299#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
300pub struct JobId(pub u32);
301
302impl std::fmt::Display for JobId {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        write!(f, "{}", self.0)
305    }
306}
307
308/// Handler for deduplicating diagnostics.
309struct DiagDedupe<'gctx> {
310    seen: RefCell<HashSet<u64>>,
311    gctx: &'gctx GlobalContext,
312}
313
314impl<'gctx> DiagDedupe<'gctx> {
315    fn new(gctx: &'gctx GlobalContext) -> Self {
316        DiagDedupe {
317            seen: RefCell::new(HashSet::default()),
318            gctx,
319        }
320    }
321
322    /// Emits a diagnostic message.
323    ///
324    /// Returns `true` if the message was emitted, or `false` if it was
325    /// suppressed for being a duplicate.
326    fn emit_diag(&self, diag: &str) -> CargoResult<bool> {
327        let h = util::hash_u64(diag);
328        if !self.seen.borrow_mut().insert(h) {
329            return Ok(false);
330        }
331        let mut shell = self.gctx.shell();
332        shell.print_ansi_stderr(diag.as_bytes())?;
333        shell.err().write_all(b"\n")?;
334        Ok(true)
335    }
336}
337
338/// Possible artifacts that can be produced by compilations, used as edge values
339/// in the dependency graph.
340///
341/// As edge values we can have multiple kinds of edges depending on one node,
342/// for example some units may only depend on the metadata for an rlib while
343/// others depend on the full rlib. This `Artifact` enum is used to distinguish
344/// this case and track the progress of compilations as they proceed.
345#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
346enum Artifact {
347    /// A generic placeholder for "depends on everything run by a step" and
348    /// means that we can't start the next compilation until the previous has
349    /// finished entirely.
350    All,
351
352    /// A node indicating that we only depend on the metadata of a compilation,
353    /// but the compilation is typically also producing an rlib. We can start
354    /// our step, however, before the full rlib is available.
355    Metadata,
356}
357
358enum Message {
359    Run(JobId, String),
360    Stdout(String),
361    Stderr(String),
362
363    // This is for general stderr output from subprocesses
364    Diagnostic {
365        id: JobId,
366        level: String,
367        diag: String,
368        lint: bool,
369        fixable: bool,
370    },
371    // This handles duplicate output that is suppressed, for showing
372    // only a count of duplicate messages instead
373    WarningCount {
374        id: JobId,
375        lint: bool,
376        emitted: bool,
377        fixable: bool,
378    },
379    // This is for warnings generated by Cargo's interpretation of the
380    // subprocess output, e.g. scrape-examples prints a warning if a
381    // unit fails to be scraped
382    Warning {
383        id: JobId,
384        warning: String,
385    },
386
387    FixDiagnostic(diagnostic_server::Message),
388    Token(io::Result<Acquired>),
389    Finish(JobId, Artifact, CargoResult<()>),
390    FutureIncompatReport(JobId, Vec<FutureBreakageItem>),
391    SectionTiming(JobId, SectionTiming),
392    /// Peak resident set size (in bytes) of a unit's process, for `--timings`.
393    PeakMemory(JobId, u64),
394    UnusedExterns(JobId, std::collections::BTreeSet<InternedString>),
395}
396
397impl<'gctx> JobQueue<'gctx> {
398    pub fn new(bcx: &BuildContext<'_, 'gctx>) -> JobQueue<'gctx> {
399        JobQueue {
400            queue: DependencyQueue::new(),
401            counts: HashMap::default(),
402            timings: Timings::new(bcx),
403        }
404    }
405
406    pub fn enqueue(
407        &mut self,
408        build_runner: &BuildRunner<'_, 'gctx>,
409        unit: &Unit,
410        job: Job,
411    ) -> CargoResult<()> {
412        let dependencies = build_runner.unit_deps(unit);
413        let mut queue_deps = dependencies
414            .iter()
415            .filter(|dep| {
416                // Binaries aren't actually needed to *compile* tests, just to run
417                // them, so we don't include this dependency edge in the job graph.
418                // But we shouldn't filter out dependencies being scraped for Rustdoc.
419                (!dep.unit.target.is_test() && !dep.unit.target.is_bin())
420                    || dep.unit.artifact.is_true()
421                    || dep.unit.mode.is_doc_scrape()
422            })
423            .map(|dep| {
424                // Handle the case here where our `unit -> dep` dependency may
425                // only require the metadata, not the full compilation to
426                // finish. Use the tables in `build_runner` to figure out what
427                // kind of artifact is associated with this dependency.
428                let artifact = if build_runner.only_requires_rmeta(unit, &dep.unit) {
429                    Artifact::Metadata
430                } else {
431                    Artifact::All
432                };
433                (dep.unit.clone(), artifact)
434            })
435            .collect::<HashMap<_, _>>();
436
437        // This is somewhat tricky, but we may need to synthesize some
438        // dependencies for this target if it requires full upstream
439        // compilations to have completed. Because of pipelining, some
440        // dependency edges may be `Metadata` due to the above clause (as
441        // opposed to everything being `All`). For example consider:
442        //
443        //    a (binary)
444        //    └ b (lib)
445        //        └ c (lib)
446        //
447        // Here the dependency edge from B to C will be `Metadata`, and the
448        // dependency edge from A to B will be `All`. For A to be compiled,
449        // however, it currently actually needs the full rlib of C. This means
450        // that we need to synthesize a dependency edge for the dependency graph
451        // from A to C. That's done here.
452        //
453        // This will walk all dependencies of the current target, and if any of
454        // *their* dependencies are `Metadata` then we depend on the `All` of
455        // the target as well. This should ensure that edges changed to
456        // `Metadata` propagate upwards `All` dependencies to anything that
457        // transitively contains the `Metadata` edge.
458        if unit.requires_upstream_objects() {
459            for dep in dependencies {
460                depend_on_deps_of_deps(build_runner, &mut queue_deps, dep.unit.clone());
461            }
462
463            fn depend_on_deps_of_deps(
464                build_runner: &BuildRunner<'_, '_>,
465                deps: &mut HashMap<Unit, Artifact>,
466                unit: Unit,
467            ) {
468                for dep in build_runner.unit_deps(&unit) {
469                    if deps.insert(dep.unit.clone(), Artifact::All).is_none() {
470                        depend_on_deps_of_deps(build_runner, deps, dep.unit.clone());
471                    }
472                }
473            }
474        }
475
476        // For now we use a fixed placeholder value for the cost of each unit, but
477        // in the future this could be used to allow users to provide hints about
478        // relative expected costs of units, or this could be automatically set in
479        // a smarter way using timing data from a previous compilation.
480        self.queue.queue(unit.clone(), job, queue_deps, 100);
481        *self.counts.entry(unit.pkg.package_id()).or_insert(0) += 1;
482        Ok(())
483    }
484
485    /// Executes all jobs necessary to build the dependency graph.
486    ///
487    /// This function will spawn off `config.jobs()` workers to build all of the
488    /// necessary dependencies, in order. Freshness is propagated as far as
489    /// possible along each dependency chain.
490    #[tracing::instrument(skip_all)]
491    pub fn execute(mut self, build_runner: &mut BuildRunner<'_, '_>) -> CargoResult<()> {
492        self.queue.queue_finished();
493
494        let progress =
495            Progress::with_style("Building", ProgressStyle::Ratio, build_runner.bcx.gctx);
496        let state = DrainState {
497            total_units: self.queue.len(),
498            queue: self.queue,
499            // 100 here is somewhat arbitrary. It is a few screenfulls of
500            // output, and hopefully at most a few megabytes of memory for
501            // typical messages. If you change this, please update the test
502            // caching_large_output, too.
503            messages: Arc::new(Queue::new(100)),
504            diag_dedupe: DiagDedupe::new(build_runner.bcx.gctx),
505            warning_count: HashMap::default(),
506            active: HashMap::default(),
507            compiled: HashSet::default(),
508            documented: HashSet::default(),
509            scraped: HashSet::default(),
510            counts: self.counts,
511            progress,
512            next_id: 0,
513            timings: self.timings,
514            index_to_unit: build_runner
515                .bcx
516                .unit_to_index
517                .iter()
518                .map(|(unit, &index)| (index, unit.clone()))
519                .collect(),
520            tokens: Vec::new(),
521            pending_queue: Vec::new(),
522            print: DiagnosticPrinter::new(
523                build_runner.bcx.gctx,
524                &build_runner.bcx.rustc().workspace_wrapper,
525            ),
526            finished: 0,
527            per_package_future_incompat_reports: Vec::new(),
528        };
529
530        // Create a helper thread for acquiring jobserver tokens
531        let messages = state.messages.clone();
532        let helper = build_runner
533            .jobserver
534            .clone()
535            .into_helper_thread(move |token| {
536                messages.push(Message::Token(token));
537            })
538            .context("failed to create helper thread for jobserver management")?;
539
540        // Create a helper thread to manage the diagnostics for rustfix if
541        // necessary.
542        let messages = state.messages.clone();
543        // It is important that this uses `push` instead of `push_bounded` for
544        // now. If someone wants to fix this to be bounded, the `drop`
545        // implementation needs to be changed to avoid possible deadlocks.
546        let _diagnostic_server = build_runner
547            .bcx
548            .build_config
549            .rustfix_diagnostic_server
550            .borrow_mut()
551            .take()
552            .map(move |srv| srv.start(move |msg| messages.push(Message::FixDiagnostic(msg))));
553
554        thread::scope(move |scope| {
555            let (result,) = state.drain_the_queue(build_runner, scope, &helper);
556            result
557        })
558    }
559}
560
561impl<'gctx> DrainState<'gctx> {
562    fn spawn_work_if_possible<'s>(
563        &mut self,
564        build_runner: &mut BuildRunner<'_, '_>,
565        jobserver_helper: &HelperThread,
566        scope: &'s Scope<'s, '_>,
567    ) -> CargoResult<()> {
568        // Dequeue as much work as we can, learning about everything
569        // possible that can run. Note that this is also the point where we
570        // start requesting job tokens. Each job after the first needs to
571        // request a token.
572        while let Some((unit, job, priority)) = self.queue.dequeue() {
573            // We want to keep the pieces of work in the `pending_queue` sorted
574            // by their priorities, and insert the current job at its correctly
575            // sorted position: following the lower priority jobs, and the ones
576            // with the same priority (since they were dequeued before the
577            // current one, we also keep that relation).
578            let idx = self
579                .pending_queue
580                .partition_point(|&(_, _, p)| p <= priority);
581            self.pending_queue.insert(idx, (unit, job, priority));
582            if self.active.len() + self.pending_queue.len() > 1 {
583                jobserver_helper.request_token();
584            }
585        }
586
587        // Now that we've learned of all possible work that we can execute
588        // try to spawn it so long as we've got a jobserver token which says
589        // we're able to perform some parallel work.
590        // The `pending_queue` is sorted in ascending priority order, and we
591        // remove items from its end to schedule the highest priority items
592        // sooner.
593        while self.has_extra_tokens() && !self.pending_queue.is_empty() {
594            let (unit, job, _) = self.pending_queue.pop().unwrap();
595            *self.counts.get_mut(&unit.pkg.package_id()).unwrap() -= 1;
596            // Print out some nice progress information.
597            // NOTE: An error here will drop the job without starting it.
598            // That should be OK, since we want to exit as soon as
599            // possible during an error.
600            self.note_working_on(
601                build_runner.bcx.gctx,
602                build_runner.bcx.ws.root(),
603                &unit,
604                job.freshness(),
605            )?;
606            self.run(&unit, job, build_runner, scope);
607        }
608
609        Ok(())
610    }
611
612    fn has_extra_tokens(&self) -> bool {
613        self.active.len() < self.tokens.len() + 1
614    }
615
616    fn handle_event(
617        &mut self,
618        build_runner: &mut BuildRunner<'_, '_>,
619        event: Message,
620    ) -> Result<(), ErrorToHandle> {
621        let warning_handling = build_runner.bcx.gctx.warning_handling()?;
622        match event {
623            Message::Run(id, cmd) => {
624                build_runner
625                    .bcx
626                    .gctx
627                    .shell()
628                    .verbose(|c| c.status("Running", &cmd))?;
629                self.timings
630                    .unit_start(build_runner, id, self.active[&id].clone());
631            }
632            Message::Stdout(out) => {
633                writeln!(build_runner.bcx.gctx.shell().out(), "{}", out)?;
634            }
635            Message::Stderr(err) => {
636                let mut shell = build_runner.bcx.gctx.shell();
637                shell.print_ansi_stderr(err.as_bytes())?;
638                shell.err().write_all(b"\n")?;
639            }
640            Message::Diagnostic {
641                id,
642                level,
643                diag,
644                lint,
645                fixable,
646            } => {
647                let emitted = self.diag_dedupe.emit_diag(&diag)?;
648                if level == "warning" {
649                    self.bump_warning_count(id, lint, emitted, fixable);
650                }
651                if level == "error" {
652                    let count = self.warning_count.entry(id).or_default();
653                    // If there is an error, the `cargo fix` message should not show
654                    count.disallow_fixable();
655                    // If there is an error, the default summary should be shown
656                    count.supplanted_by_errors = true;
657                }
658            }
659            Message::Warning { id, warning } => {
660                build_runner.bcx.gctx.shell().warn(warning)?;
661                let lint = false;
662                let emitted = true;
663                let fixable = false;
664                self.bump_warning_count(id, lint, emitted, fixable);
665            }
666            Message::WarningCount {
667                id,
668                lint,
669                emitted,
670                fixable,
671            } => {
672                self.bump_warning_count(id, lint, emitted, fixable);
673            }
674            Message::FixDiagnostic(msg) => {
675                self.print.print(&msg)?;
676            }
677            Message::Finish(id, artifact, mut result) => {
678                let unit = match artifact {
679                    // If `id` has completely finished we remove it
680                    // from the `active` map ...
681                    Artifact::All => {
682                        trace!("end: {:?}", id);
683                        self.finished += 1;
684                        let unit = self.active.remove(&id).unwrap();
685                        // An error could add an entry for a `Unit`
686                        // with 0 warnings but having fixable
687                        // warnings be disallowed
688                        let count = self
689                            .warning_count
690                            .get(&id)
691                            .filter(|count| 0 < count.total)
692                            .cloned();
693                        if let Some(count) = count {
694                            let denied_warnings =
695                                warning_handling == WarningHandling::Deny && 0 < count.lints;
696                            self.report_warning_count(
697                                build_runner,
698                                &unit,
699                                &count,
700                                &build_runner.bcx.rustc().workspace_wrapper,
701                                denied_warnings,
702                            );
703                            let stop_on_warnings = denied_warnings
704                                && !build_runner.bcx.build_config.keep_going
705                                && !count.supplanted_by_errors;
706                            if stop_on_warnings {
707                                result = Err(anyhow::format_err!(
708                                    "warnings are denied by `build.warnings` configuration"
709                                ))
710                            }
711                        }
712                        unit
713                    }
714                    // ... otherwise if it hasn't finished we leave it
715                    // in there as we'll get another `Finish` later on.
716                    Artifact::Metadata => {
717                        trace!("end (meta): {:?}", id);
718                        self.active[&id].clone()
719                    }
720                };
721                debug!("end ({:?}): {:?}", unit, result);
722                match result {
723                    Ok(()) => self.finish(id, &unit, artifact, build_runner)?,
724                    Err(_) if build_runner.bcx.unit_can_fail_for_docscraping(&unit) => {
725                        build_runner
726                            .failed_scrape_units
727                            .lock()
728                            .unwrap()
729                            .insert(build_runner.files().metadata(&unit).unit_id());
730                        self.queue.finish(&unit, &artifact);
731                    }
732                    Err(error) => {
733                        let show_warnings = true;
734                        self.emit_log_messages(&unit, build_runner, show_warnings)?;
735                        self.back_compat_notice(build_runner, &unit)?;
736                        return Err(ErrorToHandle {
737                            error,
738                            print_always: true,
739                        });
740                    }
741                }
742            }
743            Message::FutureIncompatReport(id, items) => {
744                let unit = &self.active[&id];
745                let package_id = unit.pkg.package_id();
746                let is_local = unit.is_local();
747                self.per_package_future_incompat_reports
748                    .push(FutureIncompatReportPackage {
749                        package_id,
750                        is_local,
751                        items,
752                    });
753            }
754            Message::UnusedExterns(id, unused_externs) => {
755                let unit = &self.active[&id];
756                build_runner
757                    .unused_dep_state
758                    .record_unused_externs_for_unit(unit, unused_externs);
759            }
760            Message::Token(acquired_token) => {
761                let token = acquired_token.context("failed to acquire jobserver token")?;
762                self.tokens.push(token);
763            }
764            Message::SectionTiming(id, section) => {
765                self.timings.unit_section_timing(build_runner, id, &section);
766            }
767            Message::PeakMemory(id, bytes) => {
768                self.timings.unit_peak_memory(build_runner, id, bytes);
769            }
770        }
771
772        Ok(())
773    }
774
775    // This will also tick the progress bar as appropriate
776    fn wait_for_events(&mut self) -> Vec<Message> {
777        // Drain all events at once to avoid displaying the progress bar
778        // unnecessarily. If there's no events we actually block waiting for
779        // an event, but we keep a "heartbeat" going to allow `record_cpu`
780        // to run above to calculate CPU usage over time. To do this we
781        // listen for a message with a timeout, and on timeout we run the
782        // previous parts of the loop again.
783        let mut events = self.messages.try_pop_all();
784        if events.is_empty() {
785            loop {
786                self.tick_progress();
787                self.tokens.truncate(self.active.len() - 1);
788                match self.messages.pop(Duration::from_millis(500)) {
789                    Some(message) => {
790                        events.push(message);
791                        break;
792                    }
793                    None => continue,
794                }
795            }
796        }
797        events
798    }
799
800    /// This is the "main" loop, where Cargo does all work to run the
801    /// compiler.
802    ///
803    /// This returns a tuple of `Result` to prevent the use of `?` on
804    /// `Result` types because it is important for the loop to
805    /// carefully handle errors.
806    fn drain_the_queue<'s>(
807        mut self,
808        build_runner: &mut BuildRunner<'_, '_>,
809        scope: &'s Scope<'s, '_>,
810        jobserver_helper: &HelperThread,
811    ) -> (Result<(), anyhow::Error>,) {
812        trace!("queue: {:#?}", self.queue);
813
814        // Iteratively execute the entire dependency graph. Each turn of the
815        // loop starts out by scheduling as much work as possible (up to the
816        // maximum number of parallel jobs we have tokens for). A local queue
817        // is maintained separately from the main dependency queue as one
818        // dequeue may actually dequeue quite a bit of work (e.g., 10 binaries
819        // in one package).
820        //
821        // After a job has finished we update our internal state if it was
822        // successful and otherwise wait for pending work to finish if it failed
823        // and then immediately return (or keep going, if requested by the build
824        // config).
825        let mut errors = ErrorsDuringDrain { count: 0 };
826        // CAUTION! Do not use `?` or break out of the loop early. Every error
827        // must be handled in such a way that the loop is still allowed to
828        // drain event messages.
829        loop {
830            if errors.count == 0 || build_runner.bcx.build_config.keep_going {
831                if let Err(e) = self.spawn_work_if_possible(build_runner, jobserver_helper, scope) {
832                    self.handle_error(&mut build_runner.bcx.gctx.shell(), &mut errors, e);
833                }
834            }
835
836            // If after all that we're not actually running anything then we're
837            // done!
838            if self.active.is_empty() {
839                break;
840            }
841
842            // And finally, before we block waiting for the next event, drop any
843            // excess tokens we may have accidentally acquired. Due to how our
844            // jobserver interface is architected we may acquire a token that we
845            // don't actually use, and if this happens just relinquish it back
846            // to the jobserver itself.
847            for event in self.wait_for_events() {
848                if let Err(event_err) = self.handle_event(build_runner, event) {
849                    self.handle_error(&mut build_runner.bcx.gctx.shell(), &mut errors, event_err);
850                }
851            }
852        }
853        self.progress.clear();
854
855        let mut global_stats = GlobalDiagnosticStats::new();
856        drop(unused_dependencies::lint_build_results(
857            build_runner,
858            &mut global_stats,
859        ));
860        errors.count += global_stats.error_count();
861        build_runner.compilation.lint_warning_count += global_stats.lint_warning_count();
862
863        let profile_name = build_runner.bcx.build_config.requested_profile;
864        // NOTE: this may be a bit inaccurate, since this may not display the
865        // profile for what was actually built. Profile overrides can change
866        // these settings, and in some cases different targets are built with
867        // different profiles. To be accurate, it would need to collect a
868        // list of Units built, and maybe display a list of the different
869        // profiles used. However, to keep it simple and compatible with old
870        // behavior, we just display what the base profile is.
871        let profile = build_runner.bcx.profiles.base_profile();
872        let mut opt_type = String::from(if profile.opt_level.as_str() == "0" {
873            "unoptimized"
874        } else {
875            "optimized"
876        });
877        if profile.debuginfo.is_turned_on() {
878            opt_type += " + debuginfo";
879        }
880
881        let time_elapsed = util::elapsed(build_runner.bcx.gctx.invocation_instant().elapsed());
882        if let Err(e) = self
883            .timings
884            .finished(build_runner, &errors.to_error())
885            .context("failed to render timing report")
886        {
887            self.handle_error(&mut build_runner.bcx.gctx.shell(), &mut errors, e);
888        }
889        if build_runner.bcx.build_config.emit_json() {
890            let mut shell = build_runner.bcx.gctx.shell();
891            let msg = machine_message::BuildFinished {
892                success: errors.count == 0,
893            }
894            .to_json_string();
895            if let Err(e) = writeln!(shell.out(), "{}", msg) {
896                self.handle_error(&mut shell, &mut errors, e);
897            }
898        }
899
900        if let Some(error) = errors.to_error() {
901            // Any errors up to this point have already been printed via the
902            // `display_error` inside `handle_error`.
903            (Err(anyhow::Error::new(AlreadyPrintedError::new(error))),)
904        } else if self.queue.is_empty() && self.pending_queue.is_empty() {
905            let profile_link = build_runner.bcx.gctx.shell().err_hyperlink(
906                "https://doc.rust-lang.org/cargo/reference/profiles.html#default-profiles",
907            );
908            let message = format!(
909                "{profile_link}`{profile_name}` profile [{opt_type}]{profile_link:#} target(s) in {time_elapsed}",
910            );
911            // It doesn't really matter if this fails.
912            let _ = build_runner.bcx.gctx.shell().status("Finished", message);
913            future_incompat::save_and_display_report(
914                build_runner.bcx,
915                &self.per_package_future_incompat_reports,
916            );
917
918            (Ok(()),)
919        } else {
920            debug!("queue: {:#?}", self.queue);
921            (Err(internal("finished with jobs still left in the queue")),)
922        }
923    }
924
925    fn handle_error(
926        &mut self,
927        shell: &mut Shell,
928        err_state: &mut ErrorsDuringDrain,
929        new_err: impl Into<ErrorToHandle>,
930    ) {
931        let new_err = new_err.into();
932        if new_err.print_always || err_state.count == 0 {
933            crate::display_error(&new_err.error, shell);
934            if err_state.count == 0 && !self.active.is_empty() {
935                self.progress.indicate_error();
936                let _ = shell.warn("build failed, waiting for other jobs to finish...");
937            }
938            err_state.count += 1;
939        } else {
940            tracing::warn!("{:?}", new_err.error);
941        }
942    }
943
944    // This also records CPU usage and marks concurrency; we roughly want to do
945    // this as often as we spin on the events receiver (at least every 500ms or
946    // so).
947    fn tick_progress(&mut self) {
948        // Record some timing information if `--timings` is enabled, and
949        // this'll end up being a noop if we're not recording this
950        // information.
951        self.timings.record_cpu();
952
953        let active_names = self
954            .active
955            .values()
956            .map(|u| self.name_for_progress(u))
957            .collect::<Vec<_>>();
958        let _ = self.progress.tick_now(
959            self.finished,
960            self.total_units,
961            &format!(": {}", active_names.join(", ")),
962        );
963    }
964
965    fn name_for_progress(&self, unit: &Unit) -> String {
966        let pkg_name = unit.pkg.name();
967        let target_name = unit.target.name();
968        match unit.mode {
969            CompileMode::Doc { .. } => format!("{}(doc)", pkg_name),
970            CompileMode::RunCustomBuild => format!("{}(build)", pkg_name),
971            CompileMode::Test | CompileMode::Check { test: true } => match unit.target.kind() {
972                TargetKind::Lib(_) => format!("{}(test)", target_name),
973                TargetKind::CustomBuild => panic!("cannot test build script"),
974                TargetKind::Bin => format!("{}(bin test)", target_name),
975                TargetKind::Test => format!("{}(test)", target_name),
976                TargetKind::Bench => format!("{}(bench)", target_name),
977                TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
978                    format!("{}(example test)", target_name)
979                }
980            },
981            _ => match unit.target.kind() {
982                TargetKind::Lib(_) => pkg_name.to_string(),
983                TargetKind::CustomBuild => format!("{}(build.rs)", pkg_name),
984                TargetKind::Bin => format!("{}(bin)", target_name),
985                TargetKind::Test => format!("{}(test)", target_name),
986                TargetKind::Bench => format!("{}(bench)", target_name),
987                TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
988                    format!("{}(example)", target_name)
989                }
990            },
991        }
992    }
993
994    /// Executes a job.
995    ///
996    /// Fresh jobs block until finished (which should be very fast!), Dirty
997    /// jobs will spawn a thread in the background and return immediately.
998    fn run<'s>(
999        &mut self,
1000        unit: &Unit,
1001        job: Job,
1002        build_runner: &BuildRunner<'_, '_>,
1003        scope: &'s Scope<'s, '_>,
1004    ) {
1005        let id = JobId(self.next_id);
1006        self.next_id = self.next_id.checked_add(1).unwrap();
1007
1008        debug!("start {}: {:?}", id, unit);
1009
1010        assert!(self.active.insert(id, unit.clone()).is_none());
1011
1012        let messages = self.messages.clone();
1013        let is_fresh = job.freshness().is_fresh();
1014        let rmeta_required = build_runner.rmeta_required(unit);
1015        let lock_manager = build_runner.lock_manager.clone();
1016        let warning_handling = build_runner.bcx.gctx.warning_handling().unwrap_or_default();
1017
1018        let doit = move |diag_dedupe| {
1019            let state = JobState::new(
1020                id,
1021                messages,
1022                diag_dedupe,
1023                rmeta_required,
1024                lock_manager,
1025                warning_handling,
1026            );
1027            state.run_to_finish(job);
1028        };
1029
1030        match is_fresh {
1031            true => {
1032                // Running a fresh job on the same thread is often much faster than spawning a new
1033                // thread to run the job.
1034                doit(Some(&self.diag_dedupe));
1035            }
1036            false => {
1037                scope.spawn(move || doit(None));
1038            }
1039        }
1040    }
1041
1042    fn emit_log_messages(
1043        &self,
1044        unit: &Unit,
1045        build_runner: &mut BuildRunner<'_, '_>,
1046        show_warnings: bool,
1047    ) -> CargoResult<()> {
1048        let outputs = build_runner.build_script_outputs.lock().unwrap();
1049        let Some(metadata_vec) = build_runner.find_build_script_metadatas(unit) else {
1050            return Ok(());
1051        };
1052        let bcx = &mut build_runner.bcx;
1053        for metadata in metadata_vec {
1054            if let Some(output) = outputs.get(metadata) {
1055                if !output.log_messages.is_empty()
1056                    && (show_warnings
1057                        || output
1058                            .log_messages
1059                            .iter()
1060                            .any(|(severity, _)| *severity == Severity::Error))
1061                {
1062                    let msg_with_package =
1063                        |msg: &str| format!("{}@{}: {}", unit.pkg.name(), unit.pkg.version(), msg);
1064
1065                    for (severity, message) in output.log_messages.iter() {
1066                        match severity {
1067                            Severity::Error => {
1068                                bcx.gctx.shell().error(msg_with_package(message))?;
1069                            }
1070                            Severity::Warning => {
1071                                bcx.gctx.shell().warn(msg_with_package(message))?;
1072                            }
1073                        }
1074                    }
1075                }
1076            }
1077        }
1078
1079        Ok(())
1080    }
1081
1082    fn bump_warning_count(&mut self, id: JobId, lint: bool, emitted: bool, fixable: bool) {
1083        let count = self.warning_count.entry(id).or_default();
1084        count.total += 1;
1085        if lint {
1086            let unit = self.active.get(&id).unwrap();
1087            // If this is an upstream dep but we *do* want warnings, make sure that they
1088            // don't fail compilation.
1089            if unit.is_local() {
1090                count.lints += 1;
1091            }
1092        }
1093        if !emitted {
1094            count.duplicates += 1;
1095        // Don't add to fixable if it's already been emitted
1096        } else if fixable {
1097            // Do not add anything to the fixable warning count if
1098            // is `NotAllowed` since that indicates there was an
1099            // error while building this `Unit`
1100            if count.fixable_allowed() {
1101                count.fixable = match count.fixable {
1102                    FixableWarnings::NotAllowed => FixableWarnings::NotAllowed,
1103                    FixableWarnings::Zero => FixableWarnings::Positive(1),
1104                    FixableWarnings::Positive(fixable) => FixableWarnings::Positive(fixable + 1),
1105                };
1106            }
1107        }
1108    }
1109
1110    /// Displays a final report of the warnings emitted by a particular job.
1111    fn report_warning_count(
1112        &mut self,
1113        runner: &mut BuildRunner<'_, '_>,
1114        unit: &Unit,
1115        count: &WarningCount,
1116        rustc_workspace_wrapper: &Option<PathBuf>,
1117        denied_warnings: bool,
1118    ) {
1119        let gctx = runner.bcx.gctx;
1120        runner.compilation.lint_warning_count += count.lints;
1121        let mut message = descriptive_pkg_name(&unit.pkg.name(), &unit.target, &unit.mode);
1122        message.push_str(" generated ");
1123        match count.total {
1124            1 => message.push_str("1 warning"),
1125            n => {
1126                let _ = write!(message, "{} warnings", n);
1127            }
1128        };
1129        match count.duplicates {
1130            0 => {}
1131            1 => message.push_str(" (1 duplicate)"),
1132            n => {
1133                let _ = write!(message, " ({} duplicates)", n);
1134            }
1135        }
1136        // Only show the `cargo fix` message if its a local `Unit`
1137        if unit.is_local() {
1138            // Do not show this if there are any errors or no fixable warnings
1139            if let FixableWarnings::Positive(fixable) = count.fixable {
1140                // `cargo fix` doesn't have an option for custom builds
1141                if !unit.target.is_custom_build() {
1142                    // To make sure the correct command is shown for `clippy` we
1143                    // check if `RUSTC_WORKSPACE_WRAPPER` is set and pointing towards
1144                    // `clippy-driver`.
1145                    let clippy = std::ffi::OsStr::new("clippy-driver");
1146                    let is_clippy = rustc_workspace_wrapper.as_ref().and_then(|x| x.file_stem())
1147                        == Some(clippy);
1148
1149                    let command = if is_clippy {
1150                        "cargo clippy --fix"
1151                    } else {
1152                        "cargo fix"
1153                    };
1154
1155                    let mut args =
1156                        format!("{} -p {}", unit.target.description_named(), unit.pkg.name());
1157                    if unit.mode.is_rustc_test()
1158                        && !(unit.target.is_test() || unit.target.is_bench())
1159                    {
1160                        args.push_str(" --tests");
1161                    }
1162                    let mut suggestions = format!("{} suggestion", fixable);
1163                    if fixable > 1 {
1164                        suggestions.push_str("s")
1165                    }
1166
1167                    #[expect(clippy::disallowed_methods, reason = "consistency with clippy")]
1168                    let _ = write!(
1169                        message,
1170                        " (run `{command} --{args}{}` to apply {suggestions})",
1171                        if let Some(cli_lints_os) = env::var_os("CLIPPY_ARGS")
1172                            && let Ok(cli_lints) = cli_lints_os.into_string()
1173                            && is_clippy
1174                        {
1175                            // Clippy can take lints through the CLI, each lint flag is separated by "__CLIPPY_HACKERY__".
1176                            let cli_lints = cli_lints.replace("__CLIPPY_HACKERY__", " ");
1177                            let cli_lints = cli_lints.trim_ascii_end(); // Remove that last space left by __CLIPPY_HACKERY__
1178                            format!(" -- {cli_lints}")
1179                        } else {
1180                            "".to_owned()
1181                        }
1182                    );
1183                }
1184            }
1185        }
1186        // Errors are ignored here because it is tricky to handle them
1187        // correctly, and they aren't important.
1188        let _ = if denied_warnings {
1189            gctx.shell().error(message)
1190        } else {
1191            gctx.shell().warn(message)
1192        };
1193    }
1194
1195    fn finish(
1196        &mut self,
1197        id: JobId,
1198        unit: &Unit,
1199        artifact: Artifact,
1200        build_runner: &mut BuildRunner<'_, '_>,
1201    ) -> CargoResult<()> {
1202        if unit.mode.is_run_custom_build() {
1203            self.emit_log_messages(
1204                unit,
1205                build_runner,
1206                unit.show_warnings(build_runner.bcx.gctx),
1207            )?;
1208        }
1209        let unblocked = self.queue.finish(unit, &artifact);
1210        match artifact {
1211            Artifact::All => self.timings.unit_finished(build_runner, id, unblocked),
1212            Artifact::Metadata => self
1213                .timings
1214                .unit_rmeta_finished(build_runner, id, unblocked),
1215        }
1216        Ok(())
1217    }
1218
1219    // This isn't super trivial because we don't want to print loads and
1220    // loads of information to the console, but we also want to produce a
1221    // faithful representation of what's happening. This is somewhat nuanced
1222    // as a package can start compiling *very* early on because of custom
1223    // build commands and such.
1224    //
1225    // In general, we try to print "Compiling" for the first nontrivial task
1226    // run for a package, regardless of when that is. We then don't print
1227    // out any more information for a package after we've printed it once.
1228    fn note_working_on(
1229        &mut self,
1230        gctx: &GlobalContext,
1231        ws_root: &Path,
1232        unit: &Unit,
1233        fresh: &Freshness,
1234    ) -> CargoResult<()> {
1235        if (self.compiled.contains(&unit.pkg.package_id())
1236            && !unit.mode.is_doc()
1237            && !unit.mode.is_doc_scrape())
1238            || (self.documented.contains(&unit.pkg.package_id()) && unit.mode.is_doc())
1239            || (self.scraped.contains(&unit.pkg.package_id()) && unit.mode.is_doc_scrape())
1240        {
1241            return Ok(());
1242        }
1243
1244        match fresh {
1245            // Any dirty stage which runs at least one command gets printed as
1246            // being a compiled package.
1247            Dirty(dirty_reason) => {
1248                if !dirty_reason.is_fresh_build() {
1249                    gctx.shell().verbose(|shell| {
1250                        dirty_reason.present_to(shell, unit, ws_root, &self.index_to_unit)
1251                    })?;
1252                }
1253
1254                if unit.mode.is_doc() {
1255                    self.documented.insert(unit.pkg.package_id());
1256                    gctx.shell().status("Documenting", &unit.pkg)?;
1257                } else if unit.mode.is_doc_test() {
1258                    // Skip doc test.
1259                } else if unit.mode.is_doc_scrape() {
1260                    self.scraped.insert(unit.pkg.package_id());
1261                    gctx.shell().status("Scraping", &unit.pkg)?;
1262                } else {
1263                    self.compiled.insert(unit.pkg.package_id());
1264                    if unit.mode.is_check() {
1265                        gctx.shell().status("Checking", &unit.pkg)?;
1266                    } else {
1267                        gctx.shell().status("Compiling", &unit.pkg)?;
1268                    }
1269                }
1270            }
1271            Fresh => {
1272                // If doc test are last, only print "Fresh" if nothing has been printed.
1273                if self.counts[&unit.pkg.package_id()] == 0
1274                    && !(unit.mode.is_doc_test() && self.compiled.contains(&unit.pkg.package_id()))
1275                {
1276                    self.compiled.insert(unit.pkg.package_id());
1277                    gctx.shell().verbose(|c| c.status("Fresh", &unit.pkg))?;
1278                }
1279            }
1280        }
1281        Ok(())
1282    }
1283
1284    fn back_compat_notice(
1285        &self,
1286        build_runner: &BuildRunner<'_, '_>,
1287        unit: &Unit,
1288    ) -> CargoResult<()> {
1289        if unit.pkg.name() != "diesel"
1290            || unit.pkg.version() >= &Version::new(1, 4, 8)
1291            || build_runner.bcx.ws.resolve_behavior() == ResolveBehavior::V1
1292            || !unit.pkg.package_id().source_id().is_registry()
1293            || !unit.features.is_empty()
1294        {
1295            return Ok(());
1296        }
1297        if !build_runner
1298            .bcx
1299            .unit_graph
1300            .keys()
1301            .any(|unit| unit.pkg.name() == "diesel" && !unit.features.is_empty())
1302        {
1303            return Ok(());
1304        }
1305        build_runner.bcx.gctx.shell().note(
1306            "\
1307This error may be due to an interaction between diesel and Cargo's new
1308feature resolver. Try updating to diesel 1.4.8 to fix this error.
1309",
1310        )?;
1311        Ok(())
1312    }
1313}
1314
1315impl ErrorsDuringDrain {
1316    fn to_error(&self) -> Option<anyhow::Error> {
1317        match self.count {
1318            0 => None,
1319            1 => Some(format_err!("1 job failed")),
1320            n => Some(format_err!("{} jobs failed", n)),
1321        }
1322    }
1323}