Skip to main content

kizz_core/
why.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The report of `kizz why`: the reasons stored by the most recent build for the
6//! tasks under a path, with each step's untracked `/proc` and `/sys` accesses, its
7//! connections to the network and to Unix sockets, the system calls it made that
8//! the tracer does not know, the recorded machine state of the parts it names, or
9//! of every part with `--verbose`, and how many accesses it ignored.
10//!
11//! The tasks under a directory are the task records whose `kizz.md` is under it; a
12//! path that names a file selects the tasks of that file. Among those, the most
13//! recent build is the one with the largest build identity, and the report holds
14//! the tasks that build ran, each with the step positions of that run. The caller
15//! holds the cache lock while it reads, so no build changes the records meanwhile.
16
17use std::{
18    os::unix::ffi::OsStrExt as _,
19    path::{Path, PathBuf},
20};
21
22use kizz_store::{
23    AccessBits, BuildId, Connection, MachinePart, MachineStateRecord, PathState, StepKey,
24    StepPosition, StepRecord, Store, StoreError, TaskId, TaskLabel, TaskRecord, Verdict,
25    path_prefix,
26};
27
28use crate::{explain::RepeatedWarning, render::Render};
29
30/// One step of a task in the report.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct WhyStep {
33    /// The position of the step in the task's run, counting from zero.
34    pub position: u32,
35    /// The step key.
36    pub key: StepKey,
37    /// What the build decided about the step.
38    pub verdict: Verdict,
39    /// The argument vector, or `None` when the step record is gone.
40    pub argv: Option<Vec<String>>,
41    /// Every untracked access under `/proc` and `/sys`, sorted by path, with its
42    /// kinds.
43    pub untracked: Vec<(PathBuf, AccessBits)>,
44    /// The number of accesses that ignore patterns left out.
45    pub ignored: u64,
46    /// The numbers of the system calls that the step's command made and that the
47    /// tracer does not know, sorted, as its record lists them.
48    pub unknown_system_calls: Vec<u32>,
49    /// The connections that the step's command made to IPv4 or IPv6 addresses or to
50    /// Unix sockets, sorted, as its record lists them.
51    pub connections: Vec<Connection>,
52    /// The names of the parts of the machine state that the step names, sorted, as
53    /// its specification lists them.
54    pub machine_names: Vec<String>,
55    /// The machine state that the step's command started with, as its record keeps
56    /// it; every part is unknown when the step record is gone.
57    pub machine: MachineStateRecord,
58}
59
60impl WhyStep {
61    /// The command, the argument vector joined with spaces, or a note that the
62    /// step record is gone.
63    #[must_use]
64    pub fn command(&self) -> String {
65        self.argv.as_ref().map_or_else(
66            || "(the step record is no longer in the cache)".to_owned(),
67            |argv| argv.join(" "),
68        )
69    }
70}
71
72/// One task of the report.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct WhyTask {
75    /// The task.
76    pub id: TaskId,
77    /// Its task record.
78    pub record: TaskRecord,
79    /// The steps of its run in the build, in order.
80    pub steps: Vec<WhyStep>,
81}
82
83impl WhyTask {
84    /// The task as explanations name it.
85    #[must_use]
86    pub fn label(&self) -> TaskLabel {
87        TaskLabel {
88            task: self.id.clone(),
89            line: self.record.line,
90            heading: self.record.heading.clone(),
91        }
92    }
93}
94
95/// The report of `kizz why` for one path.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct WhyReport {
98    /// The absolute path the report is for.
99    pub path: PathBuf,
100    /// The most recent build that ran a task under the path, or `None` when no
101    /// build did.
102    pub build: Option<BuildId>,
103    /// The tasks that build ran under the path, in key order: by `kizz.md` path, then
104    /// by index.
105    pub tasks: Vec<WhyTask>,
106}
107
108impl WhyReport {
109    /// The loud warning of every step that re-ran in consecutive builds for the same
110    /// self-inflicted reason.
111    #[must_use]
112    pub fn warnings(&self) -> Vec<RepeatedWarning> {
113        self.tasks
114            .iter()
115            .flat_map(|task| {
116                task.steps.iter().filter_map(|step| {
117                    match &step.verdict {
118                        Verdict::Ran(explanation) if !explanation.repeated.is_empty() => {
119                            Some(RepeatedWarning {
120                                task: Some(task.label()),
121                                position: step.position,
122                                command: step.command(),
123                                paths: explanation.repeated.clone(),
124                            })
125                        },
126                        Verdict::Ran(_) | Verdict::Cached => None,
127                    }
128                })
129            })
130            .collect()
131    }
132}
133
134/// The report of the most recent build for the tasks under `path`, an absolute
135/// path, read from `store`.
136///
137/// # Errors
138///
139/// A [`StoreError`] when a record cannot be read.
140pub fn why(
141    store: &Store,
142    path: &Path,
143) -> Result<WhyReport, StoreError> {
144    let txn = store.read()?;
145    let prefix = if path.is_file() {
146        // The tasks of one `kizz.md`: its path, then the zero byte of task keys.
147        let mut prefix = path.as_os_str().as_bytes().to_vec();
148        prefix.push(0);
149        prefix
150    } else {
151        path_prefix(path)
152    };
153    let records = txn.scan::<TaskRecord>(&prefix)?;
154    let build = records.iter().map(|(_, record)| record.build).max();
155    let mut tasks = Vec::new();
156    for (id, record) in records {
157        if Some(record.build) != build {
158            continue;
159        }
160        let mut steps = Vec::new();
161        for (key, position) in txn.scan::<StepPosition>(&id.key_prefix())? {
162            if key.task != id || key.position >= record.steps {
163                continue;
164            }
165            steps.push(step(
166                txn.get::<StepRecord>(&position.step)?,
167                key.position,
168                position,
169            ));
170        }
171        tasks.push(WhyTask { id, record, steps });
172    }
173    Ok(WhyReport {
174        path: path.to_path_buf(),
175        build,
176        tasks,
177    })
178}
179
180/// The report of the step at `position`, whose step-position record is `stored`
181/// and whose step record is `record`, if it is still there.
182fn step(
183    record: Option<StepRecord>,
184    position: u32,
185    stored: StepPosition,
186) -> WhyStep {
187    let (argv, untracked, ignored, unknown_system_calls, connections, machine_names, machine) =
188        record.map_or_else(
189            || {
190                (
191                    None,
192                    Vec::new(),
193                    0,
194                    Vec::new(),
195                    Vec::new(),
196                    Vec::new(),
197                    MachineStateRecord::default(),
198                )
199            },
200            |record| {
201                let untracked = record
202                    .observations
203                    .iter()
204                    .filter(|observation| observation.state == PathState::Untracked)
205                    .map(|observation| (observation.path.clone(), observation.access))
206                    .collect();
207                (
208                    Some(record.spec.argv),
209                    untracked,
210                    record.ignored,
211                    record.unknown_system_calls,
212                    record.connections,
213                    record.spec.machine,
214                    record.machine,
215                )
216            },
217        );
218    WhyStep {
219        position,
220        key: stored.step,
221        verdict: stored.verdict,
222        argv,
223        untracked,
224        ignored,
225        unknown_system_calls,
226        connections,
227        machine_names,
228        machine,
229    }
230}
231
232impl Render {
233    /// The report of `kizz why` as text: each task with its targets, and each step
234    /// with its command, its full reasons, its untracked `/proc` and `/sys` accesses,
235    /// on a line of their own its connections, or that it made none, and the system
236    /// calls it made that the tracer does not know, when there are any, the recorded
237    /// machine state of each part it names, or with `--verbose` of every part, one
238    /// line for each, and how many accesses it ignored.
239    #[must_use]
240    pub fn why(
241        &self,
242        report: &WhyReport,
243    ) -> String {
244        let path = format!("`{}`", self.path(&report.path));
245        if report.tasks.is_empty() {
246            if report.build.is_some() {
247                return format!(
248                    "No tasks matched the filter in the most recent build under {path}.\n"
249                );
250            }
251            return format!("No build has recorded a task under {path}.\n");
252        }
253        let tasks = if report.tasks.len() == 1 {
254            "1 task".to_owned()
255        } else {
256            format!("{} tasks", report.tasks.len())
257        };
258        let mut lines = vec![format!("The most recent build ran {tasks} under {path}.")];
259        for task in &report.tasks {
260            let failed = if task.record.succeeded {
261                ""
262            } else {
263                " (failed)"
264            };
265            lines.push(String::new());
266            lines.push(format!(
267                "{} [{}]{failed}",
268                self.task(&task.label()),
269                task.record.targets.join(", ")
270            ));
271            if task.steps.is_empty() {
272                lines.push("  no commands ran".to_owned());
273            }
274            for step in &task.steps {
275                lines.push(format!(
276                    "  step {}: `{}`",
277                    step.position.saturating_add(1),
278                    step.command()
279                ));
280                lines.extend(
281                    self.full(&step.verdict)
282                        .into_iter()
283                        .map(|line| format!("    {line}")),
284                );
285                lines.push(format!("    {}", self.untracked(&step.untracked)));
286                lines.push(format!("    {}", self.connections(&step.connections)));
287                if !step.unknown_system_calls.is_empty() {
288                    let numbers: Vec<String> = step
289                        .unknown_system_calls
290                        .iter()
291                        .map(ToString::to_string)
292                        .collect();
293                    lines.push(format!(
294                        "    system calls that the tracer does not know: {}",
295                        numbers.join(", ")
296                    ));
297                }
298                if step.argv.is_some() {
299                    lines.extend(
300                        self.machine(step)
301                            .into_iter()
302                            .map(|line| format!("    {line}")),
303                    );
304                }
305                lines.push(format!("    ignored accesses: {}", step.ignored));
306            }
307        }
308        lines.push(String::new());
309        lines.join("\n")
310    }
311
312    /// The recorded machine state of a step, one line for each part, in the order
313    /// of the spec's list: the parts that the step names, or with `--verbose` every
314    /// part, those that the step names marked `checked`.
315    fn machine(
316        &self,
317        step: &WhyStep,
318    ) -> Vec<String> {
319        MachinePart::ALL
320            .into_iter()
321            .filter_map(|part| {
322                let named = step.machine_names.iter().any(|name| name == part.name());
323                let text = step.machine.text(part);
324                match (named, self.verbose) {
325                    (true, true) => Some(format!("machine {part} (checked): {text}")),
326                    (true, false) | (false, true) => Some(format!("machine {part}: {text}")),
327                    (false, false) => None,
328                }
329            })
330            .collect()
331    }
332
333    /// The connections of a step on one line, each Unix socket path relative to the
334    /// base and in backticks, or `none`.
335    fn connections(
336        &self,
337        connections: &[Connection],
338    ) -> String {
339        if connections.is_empty() {
340            return "connections: none".to_owned();
341        }
342        let shown: Vec<String> = connections
343            .iter()
344            .map(|connection| connection.text(|path| format!("`{}`", self.path(path))))
345            .collect();
346        format!("connections: {}", shown.join(", "))
347    }
348
349    /// The untracked `/proc` and `/sys` accesses of a step on one line.
350    fn untracked(
351        &self,
352        untracked: &[(PathBuf, AccessBits)],
353    ) -> String {
354        if untracked.is_empty() {
355            return "untracked /proc and /sys accesses: none".to_owned();
356        }
357        let shown: Vec<String> = untracked
358            .iter()
359            .map(|(path, access)| {
360                format!(
361                    "`{}` ({})",
362                    self.path(path),
363                    crate::render::access_kinds(*access)
364                )
365            })
366            .collect();
367        format!("untracked /proc and /sys accesses: {}", shown.join(", "))
368    }
369}