Skip to main content

buildl_core/execute/
assembly.rs

1//! The assembly: from a plan, through the ports, to one outcome per target.
2//!
3//! Its own file because it is where this phase's steps meet and where their order is fixed.
4//! Everything that can refuse a build is checked before any of it runs: the plan belongs to the
5//! graph, no two outputs collide, and every command, once expanded, names a program the
6//! workspace allows. Only then are targets handed out to be built, each one settled when it may
7//! start and recorded when it is done.
8//!
9//! Responsibilities: [`execute`]; the flag that keeps workers from beginning anything once the
10//! build has stopped, and the place of the one action shown as it prints; the bookkeeping
11//! between two results — which targets wait to be settled, which have their outcome, and the
12//! one error that fails the whole build, which includes a failed call to the remote cache in a
13//! build that fails on one; having the build reported as it goes, an outcome only once its
14//! event is logged; and refusing to report a build whose dispatcher returned with a
15//! target left without an outcome.
16//!
17//! Non-responsibilities: what each step decides. Each has its own sibling file.
18
19use core::sync::atomic::{AtomicBool, Ordering};
20use std::collections::{BTreeMap, VecDeque};
21
22use crate::error::{Error, Result, UnsandboxedRemote};
23use crate::execute::admission::admit;
24use crate::execute::perform::{Gates, Performed, RemoteRun, Shared, Task, Told, Worked, perform};
25use crate::execute::record::{
26    Progress, append, forget_contradicted, recorded, restore, shown, skipped,
27};
28use crate::execute::schedule::{Finish, Schedule};
29use crate::execute::settle::{Settled, settle};
30use crate::placement::expand::{Lists, expand, expand_description};
31use crate::placement::layout::Layout;
32use crate::ports::{Dispatcher, Host, Manifest, PortSet, Ports, Reporter};
33use crate::types::{
34    ActionOutcome, Captured, Ceiling, Command, EnvName, EnvValue, ExpandedDescription, Forcing,
35    Isolation, Label, LiveOutput, Node, NodeId, OutcomeEvent, OutputPath, OwnComponents, Plan,
36    PlannedKey, PlatformProperties, ReadyAction, RemoteExecution, RemotePolicy, RemoteSettings,
37    RemoteSwitch, RemoteUse, Rerun, RunChoices, Summary, TargetGraph, Turn, Verdict,
38};
39
40/// Refuses a run that would upload to the remote cache, or have the remote run actions, while
41/// actions run `strategy`.
42///
43/// A bare action can read files it did not declare, so what it produced is not known to depend
44/// only on its declared inputs, and no one else could trust it; a worker receives only declared
45/// files, so an action that ran there could differ from one that ran here. Reading from the
46/// remote is not refused.
47///
48/// # Errors
49///
50/// Returns [`Error::UploadUnsandboxed`] when `remote` writes or executes and `strategy` is
51/// [`Isolation::Bare`]; execution is the one it names when both are asked for.
52pub fn ensure_sandboxed_remote(remote: RemotePolicy, strategy: Isolation) -> Result<()> {
53    if strategy != Isolation::Bare {
54        return Ok(());
55    }
56    let which = match (remote.execution, remote.use_) {
57        (RemoteExecution::On { .. }, _) => UnsandboxedRemote::Execute,
58        (RemoteExecution::Off, RemoteUse::ReadWrite) => UnsandboxedRemote::Upload,
59        (RemoteExecution::Off, _) => return Ok(()),
60    };
61    Err(Error::UploadUnsandboxed { which })
62}
63
64/// Builds every target of `graph` as `plan` says, and returns one outcome per target, in id
65/// order.
66///
67/// `plan` must be the plan made from `graph`; the value of every build setting is the one
68/// `plan` holds. `choices` are the choices of the command that makes the run. A target starts
69/// once everything it depends on has succeeded. Its key is then finished from what those
70/// dependencies produced: when its last build recorded that key and everything it produced is
71/// still stored, the target is not run and its outputs are put back in place; otherwise its
72/// action runs. What an action produced is stored first, its row
73/// recorded after, and its outcome logged whatever it is, so a row never names content that is
74/// not held and a failure is never recorded as a result.
75///
76/// An action may leave a regular file or a directory of regular files at each output path. A
77/// directory is stored file by file with a manifest of its paths, is put back whole or not at
78/// all, and is one digest in the key of every target that depends on it. An output that is
79/// anything else, or a directory holding anything else, is refused for one of the reasons of
80/// [`OutputRefusal`](crate::types::OutputRefusal), and the target fails.
81///
82/// An action that fails is an outcome, not an error. What a failure does to the rest of the
83/// build is `choices.on_failure`'s to say: under
84/// [`OnFailure::Stop`](crate::types::OnFailure::Stop) nothing more is begun, and under
85/// [`OnFailure::KeepGoing`](crate::types::OnFailure::KeepGoing) only the targets that depend
86/// on the failed one are skipped.
87///
88/// A target's description is expanded with its command, from the same paths and with the
89/// settings `plan` holds, and handed to the strategy with it; expanding one cannot fail, and it
90/// is no part of the key.
91///
92/// `whole` is the graph of the whole workspace, the one `graph` was narrowed from, or `graph`
93/// itself. A target of `whole` that `graph` leaves out is no part of the build: it has no
94/// outcome, no event and no row, and whatever it left in the workspace stays.
95///
96/// Under `choices.rerun` of [`Rerun::Tests`] a test runs whatever its recorded result says, and
97/// its new result is recorded; any other target settles as before.
98///
99/// `choices.remote` says how the remote cache is used. When it reads, a worker asks the remote
100/// for a target that must run before it runs it: a usable result the remote holds is stored as
101/// a run would store its own and the target ends
102/// [`OutcomeClass::Fetched`](crate::types::OutcomeClass::Fetched), without its action running
103/// and without being reported as started. A miss runs the action. A call that fails under
104/// [`RemoteFailure::Lenient`](crate::types::RemoteFailure::Lenient) is reported once through
105/// the reporter's `remote` call, turns the remote off through `remote_off` and runs the
106/// action; under [`RemoteFailure::Strict`](crate::types::RemoteFailure::Strict) it fails the
107/// build. A target whose row stands is restored without asking the remote. With
108/// [`RemotePolicy::OFF`](crate::types::RemotePolicy::OFF) the remote is never called.
109///
110/// When it also writes, a worker sends what an action it ran produced to the remote once that is
111/// in the content store, and before the target's row is recorded. A failed action, a target
112/// restored from its row and a target fetched from the remote send nothing. A failed upload is
113/// handled as a failed lookup is; an input file that changed after its digest was taken is
114/// reported through the reporter's `remote` call, sends nothing for that target, and leaves the
115/// remote on.
116///
117/// `remote_off` is the caller's, so that a remote turned off stays off, and is reported once,
118/// across every run of one command: a caller that runs twice for one command passes the same
119/// switch to both.
120///
121/// The build is shown through the reporter port, always from the calling thread: that it begins,
122/// once nothing can refuse it any more; each action as a worker begins it; each target's outcome,
123/// once its event is logged; and the count of the outcomes last, unless the build ends in an
124/// error. An outcome is reported with what its action printed, read back from the content store,
125/// for a target that ran as for one that is cached.
126///
127/// Under `choices.live` of [`LiveOutput::OneAction`] one running action at a time is shown as it
128/// prints: what it writes is reported while it runs, and its outcome is then reported with
129/// nothing left to show.
130/// The outcome of a target that ends meanwhile is logged at once and reported after that
131/// action's. What is stored and what is returned are the same under either choice.
132///
133/// # Errors
134///
135/// Before anything runs, returns the first failure met, in this order:
136///
137/// 1. [`Error::ForeignPlan`] when `plan` was not made from `graph`;
138/// 2. whatever the manifest port returns;
139/// 3. [`Error::UploadUnsandboxed`] when `choices.remote` writes to the remote or has it run
140///    actions, and the workspace's actions run bare;
141/// 4. [`Error::OutputConflict`] when two outputs of `whole` would be written to one place;
142/// 5. for the first target, in id order, whose expanded command cannot run or whose
143///    environment cannot be read: [`Error::NoProgram`] when it names no program,
144///    [`Error::Refused`] when the program is outside the workspace's ceiling, and whatever the
145///    host port returns when it cannot report the value of a variable the target marks
146///    `unkeyed`.
147///
148/// Once the build is under way, returns the first of: [`Error::Adapter`], naming the remote
149/// cache and the call, for a failed call under
150/// [`RemoteFailure::Strict`](crate::types::RemoteFailure::Strict); the log port's failure to
151/// append an event; [`Error::CanonicalJson`] for a key that cannot be serialized;
152/// [`Error::Adapter`], naming the action cache, for a dependency that succeeded and has no row;
153/// the content store's failure to read the manifest of a recorded output; and its failure to
154/// read what a target printed, which is [`Error::Adapter`] naming the content store when that
155/// content is no longer held. After such an error no port is asked anything more, and no count is
156/// reported. Otherwise returns whatever the dispatcher port itself returns.
157///
158/// When the dispatcher returns success and a target has no outcome, returns
159/// [`Error::DispatcherFault`] naming those targets: the port's contract is that every task is
160/// run and every result reaches the build, so a build never reports success, or a summary,
161/// with a target missing. What ended before is recorded and logged already, and stays.
162pub fn execute<P: Ports>(
163    whole: &TargetGraph,
164    graph: &TargetGraph,
165    plan: &Plan,
166    choices: RunChoices,
167    remote_off: &RemoteSwitch,
168    ports: &mut PortSet<P>,
169) -> Result<Vec<ActionOutcome>> {
170    let RunChoices {
171        on_failure,
172        live,
173        rerun,
174        remote,
175    } = choices;
176    if !made_from(plan, graph) {
177        return Err(Error::ForeignPlan);
178    }
179    let workspace = ports.manifest.workspace()?;
180    ensure_sandboxed_remote(remote, workspace.execution.strategy)?;
181    Layout::of(whole, &workspace.out)?;
182    let layout = Layout::of(graph, &workspace.out)?;
183    let targets = prepared(graph, plan, &layout, &workspace.ceiling, &ports.host)?;
184
185    let PortSet {
186        cache,
187        cas,
188        log,
189        strategy,
190        dispatcher,
191        clock,
192        reporter,
193        remote: remote_cache,
194        ..
195    } = ports;
196    let (cas, strategy, clock) = (&*cas, &*strategy, &*clock);
197    let no_properties = PlatformProperties::default();
198    let remote = RemoteRun {
199        port: &*remote_cache,
200        policy: remote,
201        execution: &workspace.execution,
202        properties: workspace
203            .remote
204            .as_ref()
205            .map_or(&no_properties, RemoteSettings::properties),
206        down: remote_off,
207        gates: Gates::of(remote.execution),
208    };
209    let stop = AtomicBool::new(false);
210    let place = AtomicBool::new(false);
211    let shared = Shared {
212        stop: &stop,
213        live: match live {
214            LiveOutput::Off => None,
215            LiveOutput::OneAction => Some(&place),
216        },
217    };
218    let mut build = Build::<P> {
219        graph,
220        targets,
221        layout: &layout,
222        schedule: Schedule::new(graph, on_failure),
223        rerun,
224        outcomes: vec![None; graph.len()],
225        queue: VecDeque::new(),
226        fatal: None,
227        cache,
228        cas,
229        log,
230        clock,
231        reporter,
232        shared,
233        live: None,
234        held: Vec::new(),
235    };
236    build.reporter.begun(graph.len());
237    let dispatched = dispatcher.dispatch(
238        |task, tell| perform(task, strategy, cas, clock, Some(&remote), shared, tell),
239        |turn| build.step(turn),
240    );
241    build.outcomes(dispatched)
242}
243
244/// Whether `plan` holds exactly the targets of `graph`, under the same ids, and a value for
245/// exactly the settings `graph` declares.
246pub(crate) fn made_from(plan: &Plan, graph: &TargetGraph) -> bool {
247    plan.len() == graph.len()
248        && graph
249            .nodes()
250            .iter()
251            .zip((0_u32..).map(NodeId::new))
252            .all(|(node, id)| plan.label(id) == Some(&node.label))
253        && plan.settings().keys().eq(graph.settings().keys())
254}
255
256/// The components a verdict holds for its target, whatever the verdict says.
257const fn own_of(verdict: &Verdict) -> &OwnComponents {
258    match verdict {
259        Verdict::Clean { key }
260        | Verdict::Dirty {
261            key: PlannedKey::Finished(key),
262            ..
263        } => &key.components().own,
264        Verdict::Dirty {
265            key: PlannedKey::Unfinished(unfinished),
266            ..
267        }
268        | Verdict::Conditional(unfinished) => &unfinished.own,
269    }
270}
271
272/// The action of `node` as a strategy is handed it: `command` is its expanded command,
273/// `description` its description expanded the same way, `outputs` where its own outputs live
274/// and `deps` where its dependencies' do.
275///
276/// The environment holds each variable the target reads that has a value; one that is not set
277/// is left out, as it is absent where the action runs. A `key` variable's value is the one the
278/// key holds; an `unkeyed` variable's is what `host` reports now, since no key holds it, and
279/// `unkeyed` names those variables.
280///
281/// # Errors
282///
283/// Returns whatever `host` returns for the first `unkeyed` variable it cannot report.
284pub(crate) fn ready<H: Host>(
285    node: &Node,
286    own: &OwnComponents,
287    host: &H,
288    command: Command,
289    description: Option<ExpandedDescription>,
290    outputs: &[OutputPath],
291    deps: Vec<OutputPath>,
292) -> Result<ReadyAction> {
293    let mut env: BTreeMap<EnvName, EnvValue> = own
294        .env
295        .iter()
296        .filter_map(|(name, value)| Some((name.clone(), value.clone()?)))
297        .collect();
298    for name in &own.unkeyed {
299        if let Some(value) = host.env(name)? {
300            env.insert(name.clone(), value);
301        }
302    }
303    Ok(ReadyAction {
304        label: node.label.clone(),
305        command,
306        description,
307        env,
308        unkeyed: own.unkeyed.clone(),
309        inputs: node.inputs.clone(),
310        deps,
311        outputs: outputs.to_vec(),
312        network: node.network,
313        output_source: node.output_source,
314    })
315}
316
317/// One target, with everything about it that is settled before anything runs.
318pub(crate) struct Prepared<'a> {
319    /// The target as the graph holds it.
320    pub(crate) node: &'a Node,
321    /// Its own key components, from its verdict.
322    own: &'a OwnComponents,
323    /// The labels of the targets it depends on, in the order they were written.
324    pub(crate) deps: Vec<&'a Label>,
325    /// Its action, ready to hand to a strategy.
326    pub(crate) action: ReadyAction,
327}
328
329/// Every target of `graph` prepared, in id order: its command expanded and admitted, and its
330/// description expanded.
331///
332/// A command is expanded with the settings its key holds. A description may name a setting its
333/// command does not, which its key does not hold, so it is expanded with the settings `plan`
334/// holds: the value of every setting.
335///
336/// The value of each `unkeyed` variable a target reads is asked of `host` as its action is made
337/// ready: no plan holds it.
338///
339/// # Errors
340///
341/// Returns [`Error::NoProgram`] or [`Error::Refused`] for the first target, in id order, whose
342/// expanded command cannot run under `ceiling`, and whatever `host` returns for an `unkeyed`
343/// variable it cannot report.
344pub(crate) fn prepared<'a, H: Host>(
345    graph: &'a TargetGraph,
346    plan: &'a Plan,
347    layout: &Layout,
348    ceiling: &Ceiling,
349    host: &H,
350) -> Result<Vec<Prepared<'a>>> {
351    graph
352        .nodes()
353        .iter()
354        .zip(plan.verdicts())
355        .zip((0_u32..).map(NodeId::new))
356        .map(|((node, verdict), id)| {
357            let own = own_of(verdict);
358            let outputs = layout.outputs(id);
359            let dep_paths = layout.deps(graph, id);
360            let lists = Lists {
361                inputs: &node.inputs,
362                outputs,
363                deps: &dep_paths,
364            };
365            let command = admit(
366                expand(&node.run, &own.settings, &lists),
367                node,
368                ceiling,
369                &dep_paths,
370            )?;
371            let description = node
372                .description
373                .as_ref()
374                .map(|description| expand_description(description, plan.settings(), &lists));
375            let deps = graph
376                .deps(id)
377                .unwrap_or_default()
378                .iter()
379                .filter_map(|dep| graph.node(*dep))
380                .map(|dep| &dep.label)
381                .collect();
382            Ok(Prepared {
383                node,
384                own,
385                deps,
386                action: ready(node, own, host, command, description, outputs, dep_paths)?,
387            })
388        })
389        .collect()
390}
391
392/// The labels of the targets of `graph` whose slot in `slots` is empty, in label order.
393///
394/// A build that ran to its end gave every target an outcome: one that succeeded, one that
395/// failed, or one that was skipped. A target left without is one whose task, or whose result,
396/// the dispatcher lost, or one that waited on such a target. Targets are numbered in label
397/// order, so walking the slots in order yields the labels sorted.
398fn without_outcome<T>(graph: &TargetGraph, slots: &[Option<T>]) -> Vec<Label> {
399    graph
400        .nodes()
401        .iter()
402        .zip(slots)
403        .filter(|(_, slot)| slot.is_none())
404        .map(|(node, _)| node.label.clone())
405        .collect()
406}
407
408/// One build under way: everything the calling thread keeps between two results.
409struct Build<'a, P: Ports> {
410    /// The graph being built.
411    graph: &'a TargetGraph,
412    /// Every target, in id order.
413    targets: Vec<Prepared<'a>>,
414    /// Where every output lives.
415    layout: &'a Layout,
416    /// Which targets may start, and which never will.
417    schedule: Schedule,
418    /// Whether the run's tests run again whatever their rows say.
419    rerun: Rerun,
420    /// One slot per target, in id order, filled when the target has its outcome.
421    outcomes: Vec<Option<ActionOutcome>>,
422    /// The started targets waiting to be settled, oldest first.
423    queue: VecDeque<NodeId>,
424    /// The error that fails the build, once there is one.
425    fatal: Option<Error>,
426    /// The rows of the last build and of this one.
427    cache: &'a mut P::Cache,
428    /// The content store, shared with the workers.
429    cas: &'a P::Cas,
430    /// The build log.
431    log: &'a mut P::Log,
432    /// The clock, shared with the workers.
433    clock: &'a P::Clock,
434    /// What shows the build. Only this thread calls it.
435    reporter: &'a mut P::Reporter,
436    /// What the workers read: whether anything more may begin, and the place of the action
437    /// shown live.
438    shared: Shared<'a>,
439    /// The target whose action is being shown live: set when the first of what it printed is
440    /// reported, cleared when its outcome is.
441    live: Option<NodeId>,
442    /// The events of targets that ended while another was being shown live, oldest first:
443    /// logged already, and reported once that one has ended.
444    held: Vec<OutcomeEvent>,
445}
446
447impl<P: Ports> Build<'_, P> {
448    /// Takes one turn: the beginning of the build, then each thing a worker says and the result
449    /// of each task. Returns the tasks that became ready.
450    ///
451    /// Once an error has failed the build, a turn does nothing: no port is asked anything, a
452    /// message or a result is dropped, and no task is returned.
453    fn step(&mut self, turn: Turn<Told, Worked>) -> Vec<Task> {
454        if self.fatal.is_some() {
455            return Vec::new();
456        }
457        let mut tasks = Vec::new();
458        let stepped = match turn {
459            Turn::Begin => {
460                let started = self.schedule.start();
461                self.queue.extend(started);
462                self.drain(&mut tasks)
463            }
464            Turn::Told(told) => {
465                self.told(told);
466                Ok(())
467            }
468            Turn::Done(Worked::NotBegun(node)) => self.abandon(node),
469            Turn::Done(Worked::Performed(performed)) => self
470                .record(*performed)
471                .and_then(|()| self.drain(&mut tasks)),
472        };
473        match stepped {
474            Ok(()) => tasks,
475            Err(error) => {
476                self.fatal = Some(error);
477                self.shared.stop.store(true, Ordering::SeqCst);
478                Vec::new()
479            }
480        }
481    }
482
483    /// Reports what a worker said: that it began an action, what the action shown live just
484    /// wrote, or that a call to the remote cache failed.
485    fn told(&mut self, told: Told) {
486        match told {
487            Told::Began(node) => {
488                if let Some(target) = self.targets.get(node.index()) {
489                    self.reporter.started(&target.action);
490                }
491            }
492            Told::Printed {
493                node,
494                channel,
495                bytes,
496            } => {
497                if let Some(target) = self.targets.get(node.index()) {
498                    self.live = Some(node);
499                    self.reporter.printed(&target.node.label, channel, &bytes);
500                }
501            }
502            Told::Remote(notice) => self.reporter.remote(&notice),
503        }
504    }
505
506    /// Settles every started target waiting in the queue, oldest first: one whose recorded
507    /// result still stands is finished at once, which may start others that join the queue;
508    /// one that must run becomes a task. Once the build has stopped, what waits is abandoned.
509    fn drain(&mut self, tasks: &mut Vec<Task>) -> Result<()> {
510        while let Some(node) = self.queue.pop_front() {
511            if self.schedule.stopped().is_some() {
512                self.abandon(node)?;
513                continue;
514            }
515            let Some(target) = self.targets.get(node.index()) else {
516                continue;
517            };
518            let settled = settle(
519                &target.node.label,
520                Forcing::of(target.node.freshness, target.node.role, self.rerun),
521                target.own,
522                &target.deps,
523                &*self.cache,
524                self.cas,
525            )?;
526            match settled {
527                Settled::Runs(key) => {
528                    tasks.push(Task {
529                        node,
530                        role: target.node.role,
531                        key,
532                        action: target.action.clone(),
533                    });
534                }
535                Settled::Cached { row, manifests } => {
536                    let outcome = restore(
537                        target.node.label.clone(),
538                        target.node.role,
539                        &row,
540                        &manifests,
541                        self.layout.outputs(node),
542                        self.cas,
543                    );
544                    let progress = Progress::Keyed {
545                        key: row.key().digest(),
546                    };
547                    self.finish(node, progress, outcome)?;
548                }
549            }
550        }
551        Ok(())
552    }
553
554    /// Records what a worker did for one target, and finishes the target. A failure under the
555    /// key the target's row was recorded under removes that row first.
556    ///
557    /// # Errors
558    ///
559    /// Returns the error of a failed remote call in a build that fails when one does, and
560    /// whatever finishing the target returns.
561    fn record(&mut self, performed: Performed) -> Result<()> {
562        let node = performed.node;
563        let Some(target) = self.targets.get(node.index()) else {
564            return Ok(());
565        };
566        let was_live = performed.live;
567        let progress = Progress::Began {
568            key: performed.key.digest(),
569            span: performed.span,
570        };
571        let key = performed.key.clone();
572        let outcome = recorded(
573            target.node,
574            performed.key,
575            performed.ended,
576            self.layout.outputs(node),
577            self.cas,
578            self.cache,
579        )?;
580        // Before the outcome is finished, so the row is gone before the log line is written.
581        let outcome = forget_contradicted(outcome, &key, self.cache);
582        self.finish(node, progress, outcome)?;
583        if was_live && let Some(place) = self.shared.live {
584            // Given back only now, with the outcome reported: the next action to take the
585            // place cannot have anything it prints shown before this one has ended.
586            place.store(false, Ordering::SeqCst);
587        }
588        Ok(())
589    }
590
591    /// Gives `node` its outcome, and tells the schedule how it finished: every target that
592    /// can no longer be built is given its outcome too, and every target that may start now
593    /// joins the queue. When the build has stopped, the workers are told to begin nothing.
594    fn finish(&mut self, node: NodeId, progress: Progress, outcome: ActionOutcome) -> Result<()> {
595        let finish = if outcome.class.succeeded() {
596            Finish::Succeeded
597        } else {
598            Finish::Failed
599        };
600        self.conclude(node, progress, outcome)?;
601        let effects = self.schedule.complete(self.graph, node, finish);
602        for skipped_node in effects.skipped {
603            self.skip(skipped_node, node)?;
604        }
605        if self.schedule.stopped().is_some() {
606            self.shared.stop.store(true, Ordering::SeqCst);
607        }
608        self.queue.extend(effects.started);
609        Ok(())
610    }
611
612    /// Gives up on the started target `node` because the build has stopped: it is skipped,
613    /// naming the failure that stopped the build. A build that has not stopped abandons
614    /// nothing.
615    fn abandon(&mut self, node: NodeId) -> Result<()> {
616        let Some(failed) = self.schedule.stopped() else {
617            return Ok(());
618        };
619        self.schedule.abandon(node);
620        self.skip(node, failed)
621    }
622
623    /// Gives `node` the outcome of a target never begun because the target `because` failed.
624    fn skip(&mut self, node: NodeId, because: NodeId) -> Result<()> {
625        let (Some(target), Some(cause)) = (
626            self.targets.get(node.index()),
627            self.targets.get(because.index()),
628        ) else {
629            return Ok(());
630        };
631        let outcome = skipped(
632            target.node.label.clone(),
633            target.node.role,
634            cause.node.label.clone(),
635        );
636        self.conclude(node, Progress::Skipped, outcome)
637    }
638
639    /// Keeps `outcome` as the outcome of `node`, appends its event to the log, and only then
640    /// has it reported.
641    fn conclude(&mut self, node: NodeId, progress: Progress, outcome: ActionOutcome) -> Result<()> {
642        let (Some(target), Some(slot)) = (
643            self.targets.get(node.index()),
644            self.outcomes.get_mut(node.index()),
645        ) else {
646            return Ok(());
647        };
648        *slot = Some(outcome.clone());
649        let event = append(
650            self.log,
651            self.clock,
652            &target.node.provenance,
653            &target.action.command,
654            progress,
655            outcome,
656        )?;
657        self.show(node, event)
658    }
659
660    /// Reports the event of `node`, at once unless another target is being shown live.
661    ///
662    /// While one is, the event is held, so that nothing is shown in the middle of what that
663    /// action prints. When `node` is the one shown live, its event is reported with nothing
664    /// left to show, since all of it was shown as it was written, and then every held event is
665    /// reported, oldest first.
666    fn show(&mut self, node: NodeId, event: OutcomeEvent) -> Result<()> {
667        match self.live {
668            Some(live) if live != node => {
669                self.held.push(event);
670                Ok(())
671            }
672            Some(_) => {
673                self.reporter.finished(&event, Captured::default());
674                self.live = None;
675                let held = core::mem::take(&mut self.held);
676                held.iter().try_for_each(|event| self.report(event))
677            }
678            None => self.report(&event),
679        }
680    }
681
682    /// Reports `event` with what its action printed, read back from the content store: for a
683    /// target that ran as for one that is cached.
684    fn report(&mut self, event: &OutcomeEvent) -> Result<()> {
685        let label = &event.outcome.label;
686        let stdout = shown(self.cas, label, event.outcome.stdout)?;
687        let stderr = shown(self.cas, label, event.outcome.stderr)?;
688        self.reporter.finished(
689            event,
690            Captured {
691                stdout: &stdout,
692                stderr: &stderr,
693            },
694        );
695        Ok(())
696    }
697
698    /// What the build comes to, once the dispatcher has returned with `dispatched`: the error
699    /// that failed it, or the dispatcher's own, or else every target's outcome in id order.
700    ///
701    /// # Errors
702    ///
703    /// Returns [`Error::DispatcherFault`] when the dispatcher returned success and a target has
704    /// no outcome. Whatever ended before that was recorded and logged as it ended, and stays.
705    fn outcomes(self, dispatched: Result<()>) -> Result<Vec<ActionOutcome>> {
706        if let Some(error) = self.fatal {
707            return Err(error);
708        }
709        dispatched?;
710        let targets = without_outcome(self.graph, &self.outcomes);
711        if !targets.is_empty() {
712            return Err(Error::DispatcherFault { targets });
713        }
714        let outcomes: Vec<ActionOutcome> = self.outcomes.into_iter().flatten().collect();
715        self.reporter.summary(Summary::of(&outcomes));
716        Ok(outcomes)
717    }
718}
719
720#[cfg(test)]
721mod tests {
722    #![expect(
723        clippy::unwrap_used,
724        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
725    )]
726
727    use std::collections::{BTreeMap, BTreeSet};
728
729    use super::{made_from, own_of, ready, without_outcome};
730    use crate::execute::fixtures::{
731        command, graph, key, label, node, output_path, own, path, settings,
732    };
733    use crate::ports::two_machines::TwoMachines;
734    use crate::types::{
735        Attribution, DirtyReason, EnvName, EnvValue, ExpandedDescription, NetworkAccess, NodeId,
736        Plan, PlannedKey, TargetGraph, Unfinished, Verdict, WantedSet,
737    };
738
739    /// A plan holding one clean verdict per label, in the order given, and the settings
740    /// `values`.
741    fn plan_with(labels: &[&str], values: &[(&str, &str)]) -> Plan {
742        let verdicts = labels
743            .iter()
744            .map(|_| Verdict::Clean { key: key(&["o"]) })
745            .collect();
746        let wanted = WantedSet {
747            programs: BTreeSet::new(),
748            env: BTreeSet::new(),
749            unkeyed: BTreeSet::new(),
750            write: BTreeSet::new(),
751            network: BTreeSet::new(),
752        };
753        Plan::new(
754            labels.iter().map(|raw| label(raw)).collect(),
755            verdicts,
756            wanted,
757            Attribution::default(),
758            settings(values),
759        )
760    }
761
762    /// A plan holding one clean verdict per label, in the order given, and no setting.
763    fn plan(labels: &[&str]) -> Plan {
764        plan_with(labels, &[])
765    }
766
767    #[test]
768    fn a_plan_is_made_from_a_graph_when_it_holds_its_targets_under_the_same_ids() {
769        let graph = graph(
770            vec![node("//:a", |_| {}), node("//:b", |_| {})],
771            &[&[], &[]],
772        );
773        assert!(made_from(&plan(&["//:a", "//:b"]), &graph));
774        assert!(!made_from(&plan(&["//:a"]), &graph), "a target short");
775        assert!(
776            !made_from(&plan(&["//:a", "//:b", "//:c"]), &graph),
777            "a target more"
778        );
779        assert!(
780            !made_from(&plan(&["//:a", "//:c"]), &graph),
781            "another target"
782        );
783        assert!(
784            !made_from(&plan(&["//:b", "//:a"]), &graph),
785            "the same targets under other ids"
786        );
787    }
788
789    #[test]
790    fn the_targets_without_an_outcome_are_named_in_label_order() {
791        let graph = graph(
792            vec![
793                node("//:a", |_| {}),
794                node("//:b", |_| {}),
795                node("//:c", |_| {}),
796            ],
797            &[&[], &[], &[]],
798        );
799        assert_eq!(
800            without_outcome(&graph, &[Some(()), None, None]),
801            [label("//:b"), label("//:c")]
802        );
803        assert_eq!(
804            without_outcome(&graph, &[None, Some(()), Some(())]),
805            [label("//:a")]
806        );
807        assert_eq!(without_outcome(&graph, &[Some(()); 3]), []);
808        assert_eq!(without_outcome::<()>(&graph, &[]), [], "no slot, no target");
809    }
810
811    #[test]
812    fn a_plan_is_made_from_a_graph_when_it_holds_a_value_for_exactly_its_settings() {
813        let graph = TargetGraph::new(
814            Vec::new(),
815            Vec::new(),
816            BTreeMap::new(),
817            settings(&[("level", "1"), ("mode", "debug")]),
818        );
819        assert!(
820            made_from(
821                &plan_with(&[], &[("level", "1"), ("mode", "debug")]),
822                &graph
823            ),
824            "the defaults"
825        );
826        assert!(
827            made_from(&plan_with(&[], &[("level", "1"), ("mode", "fast")]), &graph),
828            "an overridden value"
829        );
830        assert!(
831            !made_from(&plan_with(&[], &[("mode", "debug")]), &graph),
832            "a setting short"
833        );
834        assert!(
835            !made_from(
836                &plan_with(&[], &[("arch", "arm"), ("level", "1"), ("mode", "debug")]),
837                &graph
838            ),
839            "a setting more"
840        );
841        assert!(
842            !made_from(&plan_with(&[], &[("level", "1"), ("tool", "cc")]), &graph),
843            "another setting"
844        );
845    }
846
847    #[test]
848    fn every_verdict_yields_the_components_of_its_target() {
849        let finished = key(&["app"]);
850        let unfinished = Unfinished {
851            own: own(&["lib"]),
852            awaiting: vec![NodeId::new(0)],
853        };
854        let clean = Verdict::Clean {
855            key: finished.clone(),
856        };
857        let dirty = Verdict::Dirty {
858            reason: DirtyReason::NeverBuilt,
859            key: PlannedKey::Finished(finished),
860        };
861        let waiting = Verdict::Dirty {
862            reason: DirtyReason::NeverBuilt,
863            key: PlannedKey::Unfinished(unfinished.clone()),
864        };
865        let conditional = Verdict::Conditional(unfinished);
866
867        assert_eq!(own_of(&clean), &own(&["app"]));
868        assert_eq!(own_of(&dirty), &own(&["app"]));
869        assert_eq!(own_of(&waiting), &own(&["lib"]));
870        assert_eq!(own_of(&conditional), &own(&["lib"]));
871    }
872
873    #[test]
874    fn an_action_is_handed_its_paths_in_written_order_and_only_the_variables_that_are_set() {
875        let node = node("//:app", |node| {
876            node.inputs = vec![path("z.c"), path("a.c")];
877            node.network = NetworkAccess::Declared;
878        });
879        let cc = EnvName::parse("CC").unwrap();
880        let unset = EnvName::parse("CFLAGS").unwrap();
881        let mut own = own(&["app"]);
882        own.env = BTreeMap::from([
883            (cc.clone(), Some(EnvValue::parse("clang").unwrap())),
884            (unset, None),
885        ]);
886        let outputs = [output_path("//:app", "app")];
887        let deps = vec![output_path("//:z", "z"), output_path("//:a", "a")];
888
889        let action = ready(
890            &node,
891            &own,
892            &TwoMachines::first(),
893            command(&["cc", "-o", "out/app"]),
894            Some(ExpandedDescription::new("compile z.c a.c")),
895            &outputs,
896            deps.clone(),
897        )
898        .unwrap();
899
900        assert_eq!(action.label, label("//:app"));
901        assert_eq!(action.command, command(&["cc", "-o", "out/app"]));
902        assert_eq!(
903            action.description,
904            Some(ExpandedDescription::new("compile z.c a.c"))
905        );
906        assert_eq!(
907            action.env,
908            BTreeMap::from([(cc, EnvValue::parse("clang").unwrap())])
909        );
910        assert_eq!(action.inputs, [path("z.c"), path("a.c")]);
911        assert_eq!(action.deps, deps);
912        assert_eq!(action.outputs, outputs);
913        assert_eq!(action.network, NetworkAccess::Declared);
914        assert!(action.unkeyed.is_empty());
915    }
916
917    #[test]
918    fn ready_action_holds_unkeyed_values() {
919        let node = node("//:app", |_| {});
920        let mut own = own(&["app"]);
921        own.env = BTreeMap::from([(
922            EnvName::parse("RUSTFLAGS").unwrap(),
923            Some(EnvValue::parse("-Cdebuginfo=0").unwrap()),
924        )]);
925        own.unkeyed = BTreeSet::from([
926            EnvName::parse("HOME").unwrap(),
927            EnvName::parse("PATH").unwrap(),
928            EnvName::parse("LANG").unwrap(),
929        ]);
930        let outputs = [output_path("//:app", "app")];
931
932        let action = ready(
933            &node,
934            &own,
935            &TwoMachines::first(),
936            command(&["cc"]),
937            None,
938            &outputs,
939            Vec::new(),
940        )
941        .unwrap();
942
943        let value = |text: &str| EnvValue::parse(text).unwrap();
944        assert_eq!(
945            action.env,
946            BTreeMap::from([
947                (EnvName::parse("HOME").unwrap(), value("/home/alice")),
948                (EnvName::parse("PATH").unwrap(), value("/usr/bin")),
949                (EnvName::parse("RUSTFLAGS").unwrap(), value("-Cdebuginfo=0")),
950            ]),
951            "an unset unkeyed variable (LANG) is left out as an unset key one is"
952        );
953        assert_eq!(action.unkeyed, own.unkeyed);
954    }
955}