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