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 std::cell::RefCell;
117use std::collections::{HashMap, HashSet};
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::new()),
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::new(),
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::new(),
503            active: HashMap::new(),
504            compiled: HashSet::new(),
505            documented: HashSet::new(),
506            scraped: HashSet::new(),
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        }
854
855        let profile_name = build_runner.bcx.build_config.requested_profile;
856        // NOTE: this may be a bit inaccurate, since this may not display the
857        // profile for what was actually built. Profile overrides can change
858        // these settings, and in some cases different targets are built with
859        // different profiles. To be accurate, it would need to collect a
860        // list of Units built, and maybe display a list of the different
861        // profiles used. However, to keep it simple and compatible with old
862        // behavior, we just display what the base profile is.
863        let profile = build_runner.bcx.profiles.base_profile();
864        let mut opt_type = String::from(if profile.opt_level.as_str() == "0" {
865            "unoptimized"
866        } else {
867            "optimized"
868        });
869        if profile.debuginfo.is_turned_on() {
870            opt_type += " + debuginfo";
871        }
872
873        let time_elapsed = util::elapsed(build_runner.bcx.gctx.creation_time().elapsed());
874        if let Err(e) = self
875            .timings
876            .finished(build_runner, &errors.to_error())
877            .context("failed to render timing report")
878        {
879            self.handle_error(&mut build_runner.bcx.gctx.shell(), &mut errors, e);
880        }
881        if build_runner.bcx.build_config.emit_json() {
882            let mut shell = build_runner.bcx.gctx.shell();
883            let msg = machine_message::BuildFinished {
884                success: errors.count == 0,
885            }
886            .to_json_string();
887            if let Err(e) = writeln!(shell.out(), "{}", msg) {
888                self.handle_error(&mut shell, &mut errors, e);
889            }
890        }
891
892        if let Some(error) = errors.to_error() {
893            // Any errors up to this point have already been printed via the
894            // `display_error` inside `handle_error`.
895            (Err(anyhow::Error::new(AlreadyPrintedError::new(error))),)
896        } else if self.queue.is_empty() && self.pending_queue.is_empty() {
897            let profile_link = build_runner.bcx.gctx.shell().err_hyperlink(
898                "https://doc.rust-lang.org/cargo/reference/profiles.html#default-profiles",
899            );
900            let message = format!(
901                "{profile_link}`{profile_name}` profile [{opt_type}]{profile_link:#} target(s) in {time_elapsed}",
902            );
903            // It doesn't really matter if this fails.
904            let _ = build_runner.bcx.gctx.shell().status("Finished", message);
905            future_incompat::save_and_display_report(
906                build_runner.bcx,
907                &self.per_package_future_incompat_reports,
908            );
909
910            (Ok(()),)
911        } else {
912            debug!("queue: {:#?}", self.queue);
913            (Err(internal("finished with jobs still left in the queue")),)
914        }
915    }
916
917    fn handle_error(
918        &mut self,
919        shell: &mut Shell,
920        err_state: &mut ErrorsDuringDrain,
921        new_err: impl Into<ErrorToHandle>,
922    ) {
923        let new_err = new_err.into();
924        if new_err.print_always || err_state.count == 0 {
925            crate::display_error(&new_err.error, shell);
926            if err_state.count == 0 && !self.active.is_empty() {
927                self.progress.indicate_error();
928                let _ = shell.warn("build failed, waiting for other jobs to finish...");
929            }
930            err_state.count += 1;
931        } else {
932            tracing::warn!("{:?}", new_err.error);
933        }
934    }
935
936    // This also records CPU usage and marks concurrency; we roughly want to do
937    // this as often as we spin on the events receiver (at least every 500ms or
938    // so).
939    fn tick_progress(&mut self) {
940        // Record some timing information if `--timings` is enabled, and
941        // this'll end up being a noop if we're not recording this
942        // information.
943        self.timings.record_cpu();
944
945        let active_names = self
946            .active
947            .values()
948            .map(|u| self.name_for_progress(u))
949            .collect::<Vec<_>>();
950        let _ = self.progress.tick_now(
951            self.finished,
952            self.total_units,
953            &format!(": {}", active_names.join(", ")),
954        );
955    }
956
957    fn name_for_progress(&self, unit: &Unit) -> String {
958        let pkg_name = unit.pkg.name();
959        let target_name = unit.target.name();
960        match unit.mode {
961            CompileMode::Doc { .. } => format!("{}(doc)", pkg_name),
962            CompileMode::RunCustomBuild => format!("{}(build)", pkg_name),
963            CompileMode::Test | CompileMode::Check { test: true } => match unit.target.kind() {
964                TargetKind::Lib(_) => format!("{}(test)", target_name),
965                TargetKind::CustomBuild => panic!("cannot test build script"),
966                TargetKind::Bin => format!("{}(bin test)", target_name),
967                TargetKind::Test => format!("{}(test)", target_name),
968                TargetKind::Bench => format!("{}(bench)", target_name),
969                TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
970                    format!("{}(example test)", target_name)
971                }
972            },
973            _ => match unit.target.kind() {
974                TargetKind::Lib(_) => pkg_name.to_string(),
975                TargetKind::CustomBuild => format!("{}(build.rs)", pkg_name),
976                TargetKind::Bin => format!("{}(bin)", target_name),
977                TargetKind::Test => format!("{}(test)", target_name),
978                TargetKind::Bench => format!("{}(bench)", target_name),
979                TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
980                    format!("{}(example)", target_name)
981                }
982            },
983        }
984    }
985
986    /// Executes a job.
987    ///
988    /// Fresh jobs block until finished (which should be very fast!), Dirty
989    /// jobs will spawn a thread in the background and return immediately.
990    fn run<'s>(
991        &mut self,
992        unit: &Unit,
993        job: Job,
994        build_runner: &BuildRunner<'_, '_>,
995        scope: &'s Scope<'s, '_>,
996    ) {
997        let id = JobId(self.next_id);
998        self.next_id = self.next_id.checked_add(1).unwrap();
999
1000        debug!("start {}: {:?}", id, unit);
1001
1002        assert!(self.active.insert(id, unit.clone()).is_none());
1003
1004        let messages = self.messages.clone();
1005        let is_fresh = job.freshness().is_fresh();
1006        let rmeta_required = build_runner.rmeta_required(unit);
1007        let lock_manager = build_runner.lock_manager.clone();
1008        let warning_handling = build_runner.bcx.gctx.warning_handling().unwrap_or_default();
1009
1010        let doit = move |diag_dedupe| {
1011            let state = JobState::new(
1012                id,
1013                messages,
1014                diag_dedupe,
1015                rmeta_required,
1016                lock_manager,
1017                warning_handling,
1018            );
1019            state.run_to_finish(job);
1020        };
1021
1022        match is_fresh {
1023            true => {
1024                // Running a fresh job on the same thread is often much faster than spawning a new
1025                // thread to run the job.
1026                doit(Some(&self.diag_dedupe));
1027            }
1028            false => {
1029                scope.spawn(move || doit(None));
1030            }
1031        }
1032    }
1033
1034    fn emit_log_messages(
1035        &self,
1036        unit: &Unit,
1037        build_runner: &mut BuildRunner<'_, '_>,
1038        show_warnings: bool,
1039    ) -> CargoResult<()> {
1040        let outputs = build_runner.build_script_outputs.lock().unwrap();
1041        let Some(metadata_vec) = build_runner.find_build_script_metadatas(unit) else {
1042            return Ok(());
1043        };
1044        let bcx = &mut build_runner.bcx;
1045        for metadata in metadata_vec {
1046            if let Some(output) = outputs.get(metadata) {
1047                if !output.log_messages.is_empty()
1048                    && (show_warnings
1049                        || output
1050                            .log_messages
1051                            .iter()
1052                            .any(|(severity, _)| *severity == Severity::Error))
1053                {
1054                    let msg_with_package =
1055                        |msg: &str| format!("{}@{}: {}", unit.pkg.name(), unit.pkg.version(), msg);
1056
1057                    for (severity, message) in output.log_messages.iter() {
1058                        match severity {
1059                            Severity::Error => {
1060                                bcx.gctx.shell().error(msg_with_package(message))?;
1061                            }
1062                            Severity::Warning => {
1063                                bcx.gctx.shell().warn(msg_with_package(message))?;
1064                            }
1065                        }
1066                    }
1067                }
1068            }
1069        }
1070
1071        Ok(())
1072    }
1073
1074    fn bump_warning_count(&mut self, id: JobId, lint: bool, emitted: bool, fixable: bool) {
1075        let count = self.warning_count.entry(id).or_default();
1076        count.total += 1;
1077        if lint {
1078            let unit = self.active.get(&id).unwrap();
1079            // If this is an upstream dep but we *do* want warnings, make sure that they
1080            // don't fail compilation.
1081            if unit.is_local() {
1082                count.lints += 1;
1083            }
1084        }
1085        if !emitted {
1086            count.duplicates += 1;
1087        // Don't add to fixable if it's already been emitted
1088        } else if fixable {
1089            // Do not add anything to the fixable warning count if
1090            // is `NotAllowed` since that indicates there was an
1091            // error while building this `Unit`
1092            if count.fixable_allowed() {
1093                count.fixable = match count.fixable {
1094                    FixableWarnings::NotAllowed => FixableWarnings::NotAllowed,
1095                    FixableWarnings::Zero => FixableWarnings::Positive(1),
1096                    FixableWarnings::Positive(fixable) => FixableWarnings::Positive(fixable + 1),
1097                };
1098            }
1099        }
1100    }
1101
1102    /// Displays a final report of the warnings emitted by a particular job.
1103    fn report_warning_count(
1104        &mut self,
1105        runner: &mut BuildRunner<'_, '_>,
1106        unit: &Unit,
1107        count: &WarningCount,
1108        rustc_workspace_wrapper: &Option<PathBuf>,
1109        denied_warnings: bool,
1110    ) {
1111        let gctx = runner.bcx.gctx;
1112        runner.compilation.lint_warning_count += count.lints;
1113        let mut message = descriptive_pkg_name(&unit.pkg.name(), &unit.target, &unit.mode);
1114        message.push_str(" generated ");
1115        match count.total {
1116            1 => message.push_str("1 warning"),
1117            n => {
1118                let _ = write!(message, "{} warnings", n);
1119            }
1120        };
1121        match count.duplicates {
1122            0 => {}
1123            1 => message.push_str(" (1 duplicate)"),
1124            n => {
1125                let _ = write!(message, " ({} duplicates)", n);
1126            }
1127        }
1128        // Only show the `cargo fix` message if its a local `Unit`
1129        if unit.is_local() {
1130            // Do not show this if there are any errors or no fixable warnings
1131            if let FixableWarnings::Positive(fixable) = count.fixable {
1132                // `cargo fix` doesn't have an option for custom builds
1133                if !unit.target.is_custom_build() {
1134                    // To make sure the correct command is shown for `clippy` we
1135                    // check if `RUSTC_WORKSPACE_WRAPPER` is set and pointing towards
1136                    // `clippy-driver`.
1137                    let clippy = std::ffi::OsStr::new("clippy-driver");
1138                    let is_clippy = rustc_workspace_wrapper.as_ref().and_then(|x| x.file_stem())
1139                        == Some(clippy);
1140
1141                    let command = if is_clippy {
1142                        "cargo clippy --fix"
1143                    } else {
1144                        "cargo fix"
1145                    };
1146
1147                    let mut args =
1148                        format!("{} -p {}", unit.target.description_named(), unit.pkg.name());
1149                    if unit.mode.is_rustc_test()
1150                        && !(unit.target.is_test() || unit.target.is_bench())
1151                    {
1152                        args.push_str(" --tests");
1153                    }
1154                    let mut suggestions = format!("{} suggestion", fixable);
1155                    if fixable > 1 {
1156                        suggestions.push_str("s")
1157                    }
1158
1159                    #[expect(clippy::disallowed_methods, reason = "consistency with clippy")]
1160                    let _ = write!(
1161                        message,
1162                        " (run `{command} --{args}{}` to apply {suggestions})",
1163                        if let Some(cli_lints_os) = env::var_os("CLIPPY_ARGS")
1164                            && let Ok(cli_lints) = cli_lints_os.into_string()
1165                            && is_clippy
1166                        {
1167                            // Clippy can take lints through the CLI, each lint flag is separated by "__CLIPPY_HACKERY__".
1168                            let cli_lints = cli_lints.replace("__CLIPPY_HACKERY__", " ");
1169                            let cli_lints = cli_lints.trim_ascii_end(); // Remove that last space left by __CLIPPY_HACKERY__
1170                            format!(" -- {cli_lints}")
1171                        } else {
1172                            "".to_owned()
1173                        }
1174                    );
1175                }
1176            }
1177        }
1178        // Errors are ignored here because it is tricky to handle them
1179        // correctly, and they aren't important.
1180        let _ = if denied_warnings {
1181            gctx.shell().error(message)
1182        } else {
1183            gctx.shell().warn(message)
1184        };
1185    }
1186
1187    fn finish(
1188        &mut self,
1189        id: JobId,
1190        unit: &Unit,
1191        artifact: Artifact,
1192        build_runner: &mut BuildRunner<'_, '_>,
1193    ) -> CargoResult<()> {
1194        if unit.mode.is_run_custom_build() {
1195            self.emit_log_messages(
1196                unit,
1197                build_runner,
1198                unit.show_warnings(build_runner.bcx.gctx),
1199            )?;
1200        }
1201        let unblocked = self.queue.finish(unit, &artifact);
1202        match artifact {
1203            Artifact::All => self.timings.unit_finished(build_runner, id, unblocked),
1204            Artifact::Metadata => self
1205                .timings
1206                .unit_rmeta_finished(build_runner, id, unblocked),
1207        }
1208        Ok(())
1209    }
1210
1211    // This isn't super trivial because we don't want to print loads and
1212    // loads of information to the console, but we also want to produce a
1213    // faithful representation of what's happening. This is somewhat nuanced
1214    // as a package can start compiling *very* early on because of custom
1215    // build commands and such.
1216    //
1217    // In general, we try to print "Compiling" for the first nontrivial task
1218    // run for a package, regardless of when that is. We then don't print
1219    // out any more information for a package after we've printed it once.
1220    fn note_working_on(
1221        &mut self,
1222        gctx: &GlobalContext,
1223        ws_root: &Path,
1224        unit: &Unit,
1225        fresh: &Freshness,
1226    ) -> CargoResult<()> {
1227        if (self.compiled.contains(&unit.pkg.package_id())
1228            && !unit.mode.is_doc()
1229            && !unit.mode.is_doc_scrape())
1230            || (self.documented.contains(&unit.pkg.package_id()) && unit.mode.is_doc())
1231            || (self.scraped.contains(&unit.pkg.package_id()) && unit.mode.is_doc_scrape())
1232        {
1233            return Ok(());
1234        }
1235
1236        match fresh {
1237            // Any dirty stage which runs at least one command gets printed as
1238            // being a compiled package.
1239            Dirty(dirty_reason) => {
1240                if !dirty_reason.is_fresh_build() {
1241                    gctx.shell().verbose(|shell| {
1242                        dirty_reason.present_to(shell, unit, ws_root, &self.index_to_unit)
1243                    })?;
1244                }
1245
1246                if unit.mode.is_doc() {
1247                    self.documented.insert(unit.pkg.package_id());
1248                    gctx.shell().status("Documenting", &unit.pkg)?;
1249                } else if unit.mode.is_doc_test() {
1250                    // Skip doc test.
1251                } else if unit.mode.is_doc_scrape() {
1252                    self.scraped.insert(unit.pkg.package_id());
1253                    gctx.shell().status("Scraping", &unit.pkg)?;
1254                } else {
1255                    self.compiled.insert(unit.pkg.package_id());
1256                    if unit.mode.is_check() {
1257                        gctx.shell().status("Checking", &unit.pkg)?;
1258                    } else {
1259                        gctx.shell().status("Compiling", &unit.pkg)?;
1260                    }
1261                }
1262            }
1263            Fresh => {
1264                // If doc test are last, only print "Fresh" if nothing has been printed.
1265                if self.counts[&unit.pkg.package_id()] == 0
1266                    && !(unit.mode.is_doc_test() && self.compiled.contains(&unit.pkg.package_id()))
1267                {
1268                    self.compiled.insert(unit.pkg.package_id());
1269                    gctx.shell().verbose(|c| c.status("Fresh", &unit.pkg))?;
1270                }
1271            }
1272        }
1273        Ok(())
1274    }
1275
1276    fn back_compat_notice(
1277        &self,
1278        build_runner: &BuildRunner<'_, '_>,
1279        unit: &Unit,
1280    ) -> CargoResult<()> {
1281        if unit.pkg.name() != "diesel"
1282            || unit.pkg.version() >= &Version::new(1, 4, 8)
1283            || build_runner.bcx.ws.resolve_behavior() == ResolveBehavior::V1
1284            || !unit.pkg.package_id().source_id().is_registry()
1285            || !unit.features.is_empty()
1286        {
1287            return Ok(());
1288        }
1289        if !build_runner
1290            .bcx
1291            .unit_graph
1292            .keys()
1293            .any(|unit| unit.pkg.name() == "diesel" && !unit.features.is_empty())
1294        {
1295            return Ok(());
1296        }
1297        build_runner.bcx.gctx.shell().note(
1298            "\
1299This error may be due to an interaction between diesel and Cargo's new
1300feature resolver. Try updating to diesel 1.4.8 to fix this error.
1301",
1302        )?;
1303        Ok(())
1304    }
1305}
1306
1307impl ErrorsDuringDrain {
1308    fn to_error(&self) -> Option<anyhow::Error> {
1309        match self.count {
1310            0 => None,
1311            1 => Some(format_err!("1 job failed")),
1312            n => Some(format_err!("{} jobs failed", n)),
1313        }
1314    }
1315}