buildl-core 0.2.0

Domain data, ports, and pure pipeline logic for the buildl build system — no I/O, no Lua.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! The verify assembly: from a plan, through the ports, to one check per cached target.
//!
//! Its own file because it is where the steps of a verify meet and where their order is fixed.
//! Everything that can refuse a verify is checked before anything is touched, as a build does.
//! Then the outputs of every cached target are put back in place, a sample of those targets is
//! chosen, and only then do the chosen actions run, independent of one another, each compared
//! with what was cached.
//!
//! Responsibilities: [`verify`]; which targets are cached and have their outputs put back; the
//! direct dependency that keeps a target from re-running; running the chosen actions; and the
//! comparison of a re-run's outputs with the cached ones.
//!
//! Non-responsibilities: which targets a sample takes and where two manifests differ, which each
//! have a sibling file; and running one action, which is [`perform`](crate::execute::perform)'s.
//! Nothing here records a row, forgets one, logs an event or reports to a person.

use core::sync::atomic::AtomicBool;
use std::collections::BTreeSet;

use super::{Chosen, chosen, first_difference};
use crate::error::{Error, Result};
use crate::execute::assembly::{Prepared, made_from, prepared};
use crate::execute::perform::{
    Ended, Kept, Performed, RemoteRun, Shared, Task, Told, Worked, perform,
};
use crate::execute::record::{restore, shown};
use crate::execute::settle::restorable;
use crate::placement::layout::Layout;
use crate::ports::{
    ActionCache, Clock, ContentStore, Dispatcher, ExecStrategy, Manifest, NoRemote, PortSet, Ports,
};
use crate::types::{
    ActionKey, CacheRow, Check, Diagnostic, Digest, InfraKind, Label, NodeId, OutcomeClass,
    OutputManifest, OutputName, Plan, Sample, TargetGraph, Turn, Verdict, Verification,
};

/// Re-runs the cached targets of `graph` and returns one check for each target that was looked at.
///
/// `plan` must be the plan made from `graph`, and `whole` the graph of the whole workspace, the
/// one `graph` was narrowed from, or `graph` itself. A target is cached when its verdict is clean
/// and everything its row names is still held, in a form that hashes to the digest the row
/// records. The outputs of every cached target are put back in place first, in graph order, as a
/// build does for a target that need not run; a target they cannot be put back for is
/// [`Check::Unplaced`].
///
/// A cached target with a direct dependency that was not put back, because that dependency is
/// not cached or is unplaced, is [`Check::Skipped`], naming the lowest such dependency: its
/// action would not find what it reads. A skipped target's own outputs are in place, so a target
/// above it is not skipped for it.
///
/// `sample` then chooses which of the remaining targets re-run, by their key digests; the others
/// are counted in [`Verification::not_sampled`]. The chosen actions run through the dispatcher
/// port, with no live output. Each is [`Check::Verified`] when every output it produced equals
/// the cached one, [`Check::Mismatched`] naming the first output that does not, and
/// [`Check::Failed`] when it did not end in outputs. A failed re-run does not stop the others.
///
/// Every other target of `graph` is counted in [`Verification::not_cached`].
///
/// No row is recorded or forgotten, no event is logged, nothing is reported, and what a re-run
/// produced is never put in place: only the restores place content. Content a re-run stores is
/// named by no row and no log line. A re-run never asks the remote cache for a result: the point
/// is to run the action here.
///
/// # Errors
///
/// Before anything is touched, returns the first failure met, in this order:
///
/// 1. [`Error::ForeignPlan`] when `plan` was not made from `graph`;
/// 2. whatever the manifest port returns;
/// 3. [`Error::OutputConflict`] when two outputs of `whole` would be written to one place;
/// 4. for the first target, in id order, whose expanded command cannot run or whose environment
///    cannot be read: [`Error::NoProgram`] when it names no program, [`Error::Refused`] when the
///    program is outside the workspace's ceiling, and whatever the host port returns when it
///    cannot report the value of a variable the target marks `unkeyed`.
///
/// After that, returns whatever the content store returns when the manifest of a recorded output
/// cannot be read or what a re-run printed cannot be read back, [`Error::CanonicalJson`] for a
/// manifest that cannot be serialized, and whatever the dispatcher itself returns. When the
/// dispatcher returns success and a chosen action has no result, returns
/// [`Error::DispatcherFault`] naming those targets.
pub fn verify<P: Ports>(
    whole: &TargetGraph,
    graph: &TargetGraph,
    plan: &Plan,
    sample: Sample,
    ports: &mut PortSet<P>,
) -> Result<Verification> {
    if !made_from(plan, graph) {
        return Err(Error::ForeignPlan);
    }
    let workspace = ports.manifest.workspace()?;
    Layout::of(whole, &workspace.out)?;
    let layout = Layout::of(graph, &workspace.out)?;
    let targets = prepared(graph, plan, &layout, &workspace.ceiling, &ports.host)?;

    let PortSet {
        cache,
        cas,
        strategy,
        dispatcher,
        clock,
        ..
    } = ports;
    let (cache, cas, strategy, clock) = (&*cache, &*cas, &*strategy, &*clock);

    let PutBack {
        restored,
        mut unplaced,
        not_cached,
    } = restore_cached(&targets, plan, &layout, cache, cas)?;

    let in_place: BTreeSet<&Label> = targets
        .iter()
        .zip(&restored)
        .filter(|(_, restored)| restored.is_some())
        .map(|(target, _)| &target.node.label)
        .collect();
    let mut checked = Vec::new();
    let mut candidates = Vec::new();
    for (target, restored) in targets.iter().zip(&restored) {
        let Some(restored) = restored else {
            continue;
        };
        match unmet(&target.deps, &in_place) {
            Some(because) => checked.push((
                target.node.label.clone(),
                Check::Skipped {
                    because: because.clone(),
                },
            )),
            None => candidates.push((target.node.label.clone(), restored.key.clone())),
        }
    }

    let Chosen { rerun, left_out } = chosen(candidates, sample);
    let mut tasks = Vec::new();
    for ((node, target), restored) in (0_u32..).map(NodeId::new).zip(&targets).zip(&restored) {
        if let Some(restored) = restored
            && rerun.binary_search(&target.node.label).is_ok()
        {
            tasks.push(Task {
                node,
                role: target.node.role,
                key: restored.key.clone(),
                action: target.action.clone(),
            });
        }
    }
    let asked: Vec<NodeId> = tasks.iter().map(|task| task.node).collect();
    let performed = run(tasks, strategy, cas, clock, dispatcher)?;
    let lost: Vec<Label> = asked
        .iter()
        .filter(|node| !performed.iter().any(|done| done.node == **node))
        .filter_map(|node| graph.node(*node))
        .map(|node| node.label.clone())
        .collect();
    if !lost.is_empty() {
        return Err(Error::DispatcherFault { targets: lost });
    }

    for done in performed {
        let (Some(target), Some(Some(cached))) = (
            targets.get(done.node.index()),
            restored.get(done.node.index()),
        ) else {
            continue;
        };
        let label = &target.node.label;
        let check = rechecked(
            done.ended,
            &target.node.outputs,
            &cached.manifests,
            cas,
            label,
        )?;
        checked.push((label.clone(), check));
    }
    checked.append(&mut unplaced);
    Ok(Verification::new(checked, not_cached, left_out))
}

/// How a re-run that `ended` compares with what was cached: `names` are the outputs the target
/// declares and `cached` what each was when it was cached.
///
/// A re-run never asks the remote cache, so one that ended by fetching, by the remote running the
/// action or by a failed remote call is the builder's own failure.
///
/// # Errors
///
/// Returns whatever the content store returns when what a failed re-run printed cannot be read.
fn rechecked<C: ContentStore>(
    ended: Ended,
    names: &[OutputName],
    cached: &[OutputManifest],
    cas: &C,
    label: &Label,
) -> Result<Check> {
    Ok(match ended {
        Ended::Produced { outputs, .. } => compared(names, cached, &outputs),
        Ended::Failed {
            class,
            diagnostic,
            printed,
        } => Check::Failed {
            class,
            diagnostic,
            stdout: shown(cas, label, printed.map(|printed| printed.stdout))?,
            stderr: shown(cas, label, printed.map(|printed| printed.stderr))?,
        },
        Ended::Fetched { .. } | Ended::Executed { .. } | Ended::RemoteFailed(_) => Check::Failed {
            class: OutcomeClass::InfraFailure {
                kind: InfraKind::Run,
            },
            diagnostic: Some(Diagnostic::new(
                "the re-run consulted the remote cache, which a verify never does",
            )),
            stdout: Vec::new(),
            stderr: Vec::new(),
        },
    })
}

/// A cached target whose outputs are in place: what it needs to be re-run and compared.
struct Restored {
    /// The key its action re-runs under: the one its row was recorded under.
    key: ActionKey,
    /// What each of its outputs was when it was cached, in declared order.
    manifests: Vec<OutputManifest>,
}

/// What putting the cached targets back in place came to.
struct PutBack {
    /// One slot per target, in id order: filled for a target whose outputs are in place.
    restored: Vec<Option<Restored>>,
    /// The targets whose outputs could not be put back, as checks.
    unplaced: Vec<(Label, Check)>,
    /// How many targets have nothing cached to check against.
    not_cached: usize,
}

/// Puts the outputs of every cached target of `targets` back in place, in id order.
///
/// A target is cached when its verdict is clean and its row is [`cached_manifests`]. Every other
/// target is not cached. Nothing is written to `cache`.
///
/// # Errors
///
/// Returns whatever [`cached_manifests`] returns.
fn restore_cached<A: ActionCache, C: ContentStore>(
    targets: &[Prepared<'_>],
    plan: &Plan,
    layout: &Layout,
    cache: &A,
    cas: &C,
) -> Result<PutBack> {
    let mut put_back = PutBack {
        restored: Vec::with_capacity(targets.len()),
        unplaced: Vec::new(),
        not_cached: 0,
    };
    for ((node, target), verdict) in (0_u32..).map(NodeId::new).zip(targets).zip(plan.verdicts()) {
        let label = &target.node.label;
        let cached = match (verdict, cache.row(label)) {
            (Verdict::Clean { key }, Some(row)) => {
                cached_manifests(row, cas)?.map(|manifests| (key, row, manifests))
            }
            _ => None,
        };
        let Some((key, row, manifests)) = cached else {
            put_back.not_cached += 1;
            put_back.restored.push(None);
            continue;
        };
        let outcome = restore(
            label.clone(),
            target.node.role,
            row,
            &manifests,
            layout.outputs(node),
            cas,
        );
        if outcome.class.succeeded() {
            put_back.restored.push(Some(Restored {
                key: key.clone(),
                manifests,
            }));
        } else {
            let diagnostic = outcome
                .diagnostic
                .unwrap_or_else(|| Diagnostic::new("the cached outputs could not be put back"));
            put_back
                .unplaced
                .push((label.clone(), Check::Unplaced { diagnostic }));
            put_back.restored.push(None);
        }
    }
    Ok(put_back)
}

/// What each output of `row` was, in declared order, when `cas` still holds everything the row
/// names and each manifest hashes to the digest the row records for it; `None` otherwise.
///
/// A manifest that does not hash to its digest cannot be trusted to be what the row recorded.
/// Rejecting it here is what lets the walk that compares it with a re-run's manifest stand for
/// comparing their digests.
///
/// # Errors
///
/// Returns whatever `cas` returns when a manifest cannot be read, and [`Error::CanonicalJson`]
/// for a manifest that cannot be serialized.
fn cached_manifests<C: ContentStore>(
    row: &CacheRow,
    cas: &C,
) -> Result<Option<Vec<OutputManifest>>> {
    let Some(manifests) = restorable(row, |digest| cas.contains(digest), |digest| cas.get(digest))?
    else {
        return Ok(None);
    };
    for (manifest, digest) in manifests.iter().zip(row.outputs()) {
        if Digest::of(&manifest.to_bytes()?) != *digest {
            return Ok(None);
        }
    }
    Ok(Some(manifests))
}

/// The lowest of `deps` that is not in `in_place`, if any: the dependency that keeps a target
/// from re-running.
fn unmet<'a>(deps: &[&'a Label], in_place: &BTreeSet<&Label>) -> Option<&'a Label> {
    deps.iter()
        .copied()
        .filter(|dep| !in_place.contains(dep))
        .min()
}

/// Runs every task of `tasks` through `dispatcher`, none of them shown live, and returns the
/// ones that ended, in the order they came back.
///
/// Every task is handed out when the dispatcher begins, and nothing is handed out after. The
/// stop flag is never set, so a task is always begun; one that comes back as not begun is left
/// out of the result, like one the dispatcher lost.
///
/// # Errors
///
/// Returns whatever the dispatcher returns.
fn run<S, C, K, D>(
    tasks: Vec<Task>,
    strategy: &S,
    cas: &C,
    clock: &K,
    dispatcher: &mut D,
) -> Result<Vec<Performed>>
where
    S: ExecStrategy,
    C: ContentStore,
    K: Clock + Sync,
    D: Dispatcher,
{
    let stop = AtomicBool::new(false);
    let shared = Shared {
        stop: &stop,
        live: None,
    };
    let mut waiting = tasks;
    let mut performed = Vec::new();
    dispatcher.dispatch(
        |task, tell| {
            perform(
                task,
                strategy,
                cas,
                clock,
                None::<&RemoteRun<'_, NoRemote>>,
                shared,
                tell,
            )
        },
        |turn: Turn<Told, Worked>| match turn {
            Turn::Begin => core::mem::take(&mut waiting),
            Turn::Told(_) | Turn::Done(Worked::NotBegun(_)) => Vec::new(),
            Turn::Done(Worked::Performed(done)) => {
                performed.push(*done);
                Vec::new()
            }
        },
    )?;
    Ok(performed)
}

/// How a re-run's outputs compare with the cached ones: verified when every output is equal, and
/// otherwise mismatched at the first output, in declared order, that differs.
///
/// `names` are the outputs the target declares, `cached` what each was when it was cached and
/// `kept` what each is now, all in declared order.
fn compared(names: &[OutputName], cached: &[OutputManifest], kept: &[Kept]) -> Check {
    names
        .iter()
        .zip(cached)
        .zip(kept)
        .find_map(|((name, cached), kept)| {
            first_difference(cached, &kept.manifest).map(|difference| Check::Mismatched {
                output: name.clone(),
                difference,
            })
        })
        .unwrap_or(Check::Verified)
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::unwrap_used,
        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
    )]

    use std::collections::BTreeSet;

    use super::{compared, unmet};
    use crate::execute::fixtures::{file, kept, label, outputs, tree};
    use crate::types::{Check, EntryChange, FileChange, OutputDifference, TreePath};

    #[test]
    fn the_lowest_dependency_not_in_place_is_the_one_that_is_unmet() {
        let (a, b, c) = (label("//:a"), label("//:b"), label("//:c"));
        let in_place = BTreeSet::from([&a]);
        assert_eq!(unmet(&[&c, &b, &a], &in_place), Some(&b));
        assert_eq!(unmet(&[&a], &in_place), None);
        assert_eq!(unmet(&[], &in_place), None);
    }

    #[test]
    fn equal_outputs_are_verified() {
        let check = compared(
            &outputs(&["x", "y"]),
            &[file("one"), tree(&[("a", "1")])],
            &[kept(file("one")), kept(tree(&[("a", "1")]))],
        );
        assert_eq!(check, Check::Verified);
    }

    #[test]
    fn the_first_output_in_declared_order_that_differs_is_named() {
        let names = outputs(&["x", "y", "z"]);
        let check = compared(
            &names,
            &[file("one"), tree(&[("a", "1")]), file("three")],
            &[
                kept(file("one")),
                kept(tree(&[("a", "2")])),
                kept(file("3")),
            ],
        );
        assert_eq!(
            check,
            Check::Mismatched {
                output: names[1].clone(),
                difference: OutputDifference::Entry {
                    path: TreePath::parse("a").unwrap(),
                    change: EntryChange::Bytes,
                },
            }
        );
    }

    #[test]
    fn a_file_with_other_bytes_is_mismatched_in_bytes() {
        let names = outputs(&["x"]);
        let check = compared(&names, &[file("one")], &[kept(file("two"))]);
        assert_eq!(
            check,
            Check::Mismatched {
                output: names[0].clone(),
                difference: OutputDifference::File(FileChange::Bytes),
            }
        );
    }
}