Skip to main content

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