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