Skip to main content

vitrify_cli/incremental/
recheck.rs

1//! Re-check batches: rows of dirty units, then the §5 Test command.
2//!
3//! A batch runs in a lane checkout made pristine at one commit — `reset
4//! --hard` and `clean -ffdx`, so no file a previous command left behind can
5//! decide a result — through an injected [`Runner`]: the §5 Bootstrap and
6//! Build (a fresh tree has nothing built), the Verification rows of the
7//! given units that are Verified at that commit (each distinct command once,
8//! [`rows::for_recheck`]), then the §5 Test command. A unit passes when every
9//! row of its table passed; the suite is judged on its own.
10//!
11//! Successes are recorded as they happen ([`Report::edits`], [`apply`]): for
12//! each unit that passed, a `verified` journal event with actor
13//! [`journal::RECHECK_ACTOR`] and the checked commit — the unit's new
14//! anchor — and a fresh `verified:` stamp, a volatile field masked from
15//! traces, so no trace moves; and, when the Test command passed,
16//! `suite: "pass"` on the `audit` event the edits end with. A failing row
17//! records nothing for its unit: failures are recomputed, never trusted. An
18//! interrupted batch records nothing at all.
19
20use std::path::Path;
21
22use vitrify_core::audit::{self, Finding};
23use vitrify_core::journal::{self, Event};
24use vitrify_core::model::{self, Instance, UtcTime};
25use vitrify_core::{CoreError, ledger, yamlish};
26
27use super::rows::{self, Commands};
28use crate::cmd;
29use crate::gate;
30use crate::git::Git;
31
32/// One command's result.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct CommandResult {
35    pub passed: bool,
36    /// Stopped because the run was interrupted, not because it failed.
37    pub interrupted: bool,
38    pub output: String,
39}
40
41/// Runs a batch's commands: one in a directory, or a list of rows. The rows
42/// are handed over at once, so a runner with a pool of its own can run them
43/// side by side; by default they run one after another.
44pub trait Runner {
45    fn run(&self, cmd: &str, cwd: &Path) -> CommandResult;
46
47    /// Every row in `cwd`, results index-aligned with `rows`.
48    fn run_rows(&self, rows: &[String], cwd: &Path) -> Vec<CommandResult> {
49        rows.iter().map(|r| self.run(r, cwd)).collect()
50    }
51}
52
53impl<F: Fn(&str, &Path) -> CommandResult> Runner for F {
54    fn run(&self, cmd: &str, cwd: &Path) -> CommandResult {
55        self(cmd, cwd)
56    }
57}
58
59/// The plain runner: each command through `sh -c`, one at a time.
60pub struct ShRunner;
61
62impl Runner for ShRunner {
63    fn run(&self, cmd: &str, cwd: &Path) -> CommandResult {
64        let ran = gate::run_command(cmd, cwd);
65        CommandResult {
66            passed: ran.ok(),
67            interrupted: ran.interrupted,
68            output: ran.output,
69        }
70    }
71}
72
73/// A command that failed, with its output.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct Failure {
76    pub command: String,
77    pub output: String,
78}
79
80/// One unit of the batch.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct UnitResult {
83    pub unit: String,
84    /// Every row of its table passed.
85    pub passed: bool,
86    /// Its rows that failed, in table order.
87    pub failures: Vec<Failure>,
88}
89
90/// The §5 Test command's result.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct SuiteResult {
93    pub command: String,
94    pub passed: bool,
95    pub output: String,
96}
97
98/// What a batch found.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct Report {
101    /// The commit checked, in full.
102    pub commit: String,
103    /// The units checked, in the order given.
104    pub units: Vec<UnitResult>,
105    /// Units given that are not Verified at the commit: nothing to re-check.
106    pub skipped: Vec<String>,
107    /// The §5 Test command; `None` when the SDD has none, or it did not run.
108    pub suite: Option<SuiteResult>,
109    /// A §5 Bootstrap or Build that failed: no row ran.
110    pub broken: Option<Failure>,
111    /// The run was interrupted: nothing is recorded.
112    pub interrupted: bool,
113}
114
115/// The protocol edits a batch earns ([`apply`]).
116#[derive(Debug, Clone, Default, PartialEq, Eq)]
117pub struct Edits {
118    /// The checked commit, short, as the journal records commits.
119    pub commit: String,
120    /// The units that passed, in batch order.
121    pub verified: Vec<String>,
122    /// The §5 Test command passed.
123    pub suite_pass: bool,
124}
125
126impl Edits {
127    /// Whether there is nothing to record.
128    pub fn is_empty(&self) -> bool {
129        self.verified.is_empty() && !self.suite_pass
130    }
131}
132
133impl Report {
134    /// What to record: every unit that passed, and the suite if it passed.
135    /// Nothing when the batch was interrupted.
136    pub fn edits(&self) -> Edits {
137        if self.interrupted {
138            return Edits {
139                commit: short(&self.commit).to_string(),
140                ..Default::default()
141            };
142        }
143        Edits {
144            commit: short(&self.commit).to_string(),
145            verified: self
146                .units
147                .iter()
148                .filter(|u| u.passed)
149                .map(|u| u.unit.clone())
150                .collect(),
151            suite_pass: self.suite.as_ref().is_some_and(|s| s.passed),
152        }
153    }
154}
155
156fn short(sha: &str) -> &str {
157    &sha[..7.min(sha.len())]
158}
159
160/// Re-check `units` of the SDD at `sdd_rel` (relative to the checkout) at
161/// `commit`, in the lane checkout `lane`: reset it to `commit` and clean
162/// it, run the §5 Bootstrap and Build, the units' rows, then the §5 Test
163/// command, each through `runner`. Leaves the checkout holding whatever the
164/// commands left; reset it before using it for anything else.
165pub fn run(
166    lane: &Git,
167    commit: &str,
168    sdd_rel: &Path,
169    units: &[String],
170    runner: &dyn Runner,
171) -> Result<Report, CoreError> {
172    let full = lane
173        .resolve_commit(commit)
174        .map_err(CoreError::from)?
175        .ok_or_else(|| CoreError::refusal(1, format!("error: {commit} names no commit")))?;
176    lane.reset_hard(&full).map_err(CoreError::from)?;
177    lane.clean_all().map_err(CoreError::from)?;
178    let inst = Instance::load(cmd::resolve_sdd_in(&lane.dir, sdd_rel)?)?;
179    let tables = rows::tables(&inst)?;
180    let commands = Commands::of(&inst)?;
181    let selection = rows::for_recheck(&tables, units, commands.test.as_deref());
182
183    let mut report = Report {
184        commit: full,
185        units: Vec::new(),
186        skipped: units
187            .iter()
188            .filter(|u| !selection.units.contains(u))
189            .cloned()
190            .collect(),
191        suite: None,
192        broken: None,
193        interrupted: false,
194    };
195    let failed_all = |report: &mut Report| {
196        report.units = selection
197            .units
198            .iter()
199            .map(|u| UnitResult {
200                unit: u.clone(),
201                passed: false,
202                failures: Vec::new(),
203            })
204            .collect();
205    };
206    if selection.units.is_empty() && selection.test.is_none() {
207        return Ok(report);
208    }
209
210    // a pristine tree has nothing built
211    for cmd in [&commands.bootstrap, &commands.build].into_iter().flatten() {
212        let ran = runner.run(cmd, &lane.dir);
213        if ran.interrupted {
214            report.interrupted = true;
215            failed_all(&mut report);
216            return Ok(report);
217        }
218        if !ran.passed {
219            report.broken = Some(Failure {
220                command: cmd.clone(),
221                output: ran.output,
222            });
223            failed_all(&mut report);
224            return Ok(report);
225        }
226    }
227
228    let results = runner.run_rows(&selection.rows, &lane.dir);
229    let result_of = |row: &str| -> Option<&CommandResult> {
230        let i = selection.rows.iter().position(|r| r == row)?;
231        results.get(i)
232    };
233    report.interrupted = results.iter().any(|r| r.interrupted);
234    for unit in &selection.units {
235        let table = tables
236            .iter()
237            .find(|t| &t.unit == unit)
238            .map(|t| t.rows.as_slice())
239            .unwrap_or_default();
240        let mut failures = Vec::new();
241        let mut passed = true;
242        for row in table {
243            match result_of(row) {
244                Some(r) if r.passed => {}
245                Some(r) => {
246                    passed = false;
247                    failures.push(Failure {
248                        command: row.clone(),
249                        output: r.output.clone(),
250                    });
251                }
252                // a row the runner gave no result for is no pass
253                None => passed = false,
254            }
255        }
256        report.units.push(UnitResult {
257            unit: unit.clone(),
258            passed,
259            failures,
260        });
261    }
262    if report.interrupted {
263        return Ok(report);
264    }
265
266    if let Some(test) = &selection.test {
267        let ran = runner.run(test, &lane.dir);
268        if ran.interrupted {
269            report.interrupted = true;
270            return Ok(report);
271        }
272        report.suite = Some(SuiteResult {
273            command: test.clone(),
274            passed: ran.passed,
275            output: ran.output,
276        });
277    }
278    Ok(report)
279}
280
281/// Append one event to `inst`'s journal, numbered after the last.
282fn append_event(inst: &Instance, mut event: Event) -> Result<(), CoreError> {
283    let handle = inst.handle();
284    let (events, _) = journal::read(&handle)?;
285    event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
286    if event.at.is_empty() {
287        event.at = UtcTime::now().format();
288    }
289    if event.sdd.is_empty() {
290        event.sdd = inst.meta.get_str_or("version", "0.0.0").to_string();
291    }
292    journal::append_line(&handle, &journal::render_line(&event))?;
293    Ok(())
294}
295
296/// Record `edits` in the SDD `inst`, loaded from the checkout at `root`
297/// (one holding the checked commit's spec files, or a descendant whose
298/// changes since are protocol state only): for each unit that passed and is
299/// still Verified, a fresh `verified:` stamp and a `verified` event with
300/// actor `recheck` and the checked commit; then the ledger, regenerated;
301/// then the audit (check 4 skipped), which must be clean; then an `audit`
302/// event carrying `suite: "pass"` when the Test command passed. Returns the
303/// audit's findings: when there are any, the closing `audit` event is not
304/// written, and the checkout should be reset rather than committed. Nothing
305/// is written when `edits` is empty. Committing and publishing are the
306/// caller's.
307pub fn apply(inst: &Instance, root: &Path, edits: &Edits) -> Result<Vec<Finding>, CoreError> {
308    if edits.is_empty() {
309        return Ok(Vec::new());
310    }
311    let stamp = model::render_stamp(
312        &UtcTime::now().format_date(),
313        inst.meta.get_str_or("version", "0.0.0"),
314        &edits.commit,
315    );
316    let handle = inst.handle();
317    for uid in &edits.verified {
318        let Some(unit) = inst.unit(uid) else {
319            continue;
320        };
321        if unit.meta.get_str_or("status", "Draft") != "Verified" {
322            continue;
323        }
324        model::rewrite_unit_meta(&handle, unit, |inner| {
325            yamlish::set_scalar_in_place(inner, "verified", &stamp)
326        })?;
327        append_event(
328            inst,
329            Event {
330                event: "verified".to_string(),
331                unit: Some(uid.clone()),
332                actor: Some(journal::RECHECK_ACTOR.to_string()),
333                commit: Some(edits.commit.clone()),
334                ..Default::default()
335            },
336        )?;
337    }
338    let stamped = Instance::load(handle)?;
339    ledger::regen(&stamped, &UtcTime::now().format_date())?;
340    let (findings, _) = audit::run(
341        &stamped,
342        root,
343        &cmd::audit_options(
344            audit::Options {
345                skip_rotten: true,
346                ..Default::default()
347            },
348            root,
349            &stamped,
350        ),
351        &gate::ShRunner,
352        UtcTime::now(),
353    )?;
354    if !findings.is_empty() {
355        return Ok(findings);
356    }
357    append_event(
358        &stamped,
359        Event {
360            event: "audit".to_string(),
361            actor: Some("audit".to_string()),
362            findings: Some(0),
363            suite: edits.suite_pass.then(|| journal::SUITE_PASS.to_string()),
364            commit: Some(edits.commit.clone()),
365            ..Default::default()
366        },
367    )?;
368    Ok(Vec::new())
369}