Skip to main content

fallow_output/
request_outcomes.rs

1//! What happened to every narrowing or shaping request a run received.
2//!
3//! One shape for every command that can be asked to scope or shape its report,
4//! so a consumer reads the same members whether the envelope came from
5//! `dead-code`, `dupes`, `health` or `security`. Carried as `request_outcomes`
6//! at the envelope root, absent whenever the run was asked for nothing.
7//!
8//! This is the mirror image of [`crate::GateOutcomes`]. That object answers
9//! "what did the run conclude"; this one answers "did the run do what it was
10//! asked". Both are keyed maps at the root with an open key set, so a consumer
11//! learns one reading rule for both, and a request added in a later release
12//! reaches an unchanged consumer.
13//!
14//! # Why the honoured case is published too
15//!
16//! An entry appears for every request the run RECEIVED, including the ones it
17//! honoured, exactly as `gate_outcomes` publishes gates that passed. A report
18//! that says "scoped to the change" positively is the reviewer question this
19//! object is actually about, and a reader who only ever sees failures cannot
20//! tell "the filter applied" from "nothing was asked for".
21//!
22//! # Why this is not a `workspace_diagnostics` entry
23//!
24//! `WorkspaceDiagnostic` requires a `path` naming the file or directory that
25//! triggered it, and an unresolvable git ref or an oversize diff has no such
26//! path. More decisively, `degrades_analysis` means "less reached the analysis
27//! than the user expected", and the shipped consumer sentence built from it
28//! says findings were computed over less than the whole project. These facts
29//! mean the opposite: MORE was reported than was asked for. Routing them
30//! through that array would make an existing warning state something false.
31//!
32//! # Why it carries prose when `gate_outcomes` deliberately does not
33//!
34//! A gate verdict is rendered from `status`, `observed` and `threshold`, so it
35//! needs no sentence. Here every reason carries a different remedy (fetch the
36//! ref, regenerate the diff from the repository root, check out with full
37//! history), the CLI already writes those sentences to stderr, and a rendered
38//! pull-request comment needs one of them in its body. Reproducing nine
39//! remedies in bash and in jq, twice, is how they drift.
40//! `WorkspaceDiagnostic::message` is the precedent.
41//!
42//! # Wire compatibility
43//!
44//! The key set and the `status` value set are both OPEN. A name or a status
45//! this build does not recognise means "some request" and "some outcome", not
46//! an error, the same tolerate-unknown-values contract
47//! `workspace_diagnostics[].kind` documents. The Rust types are closed enums so
48//! the emitter cannot drift, and a request added later is an additive optional
49//! key that bumps no `schema_version`.
50
51use std::collections::BTreeMap;
52
53use serde::Serialize;
54
55/// Which request an outcome describes.
56///
57/// Taken from the flags and environment channels a run can be narrowed or
58/// shaped by, rather than from any integration's input list, because a request
59/// a consumer cannot name is exactly the one whose fate goes missing.
60/// Serialized as kebab-case and published as an open set.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
62#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
63#[serde(rename_all = "kebab-case")]
64pub enum RequestName {
65    /// `--changed-since <ref>`: scope the analysis to the files that changed
66    /// since a git ref. Not applied means the report covers the whole project.
67    ChangedSince,
68    /// `--diff-file`, `--diff-stdin` or `$FALLOW_DIFF_FILE`: keep only the
69    /// findings a supplied unified diff touches. Not applied means every
70    /// finding is reported.
71    DiffFilter,
72    /// `--sarif-file <path>`: also write the findings as a SARIF document at
73    /// `path`. Not applied means the file was never written, so a consumer
74    /// uploading it to code scanning has nothing to upload. The primary report
75    /// on stdout is unaffected, which is why the run neither fails nor says
76    /// anything else about it.
77    SarifFile,
78}
79
80impl RequestName {
81    /// What an unapplied request of this name means for the report.
82    #[must_use]
83    pub const fn affects(self) -> RequestEffect {
84        match self {
85            Self::ChangedSince | Self::DiffFilter => RequestEffect::Scope,
86            Self::SarifFile => RequestEffect::Artifact,
87        }
88    }
89}
90
91/// What a request governs, and therefore what its failure means.
92///
93/// Published on every entry so a consumer selects on the class rather than on
94/// a name list. Without it the one sentence a consumer can write for the whole
95/// object ("the report is wider than requested") is false for any request that
96/// does not narrow, which is how a failed `--sarif-file` write came to be
97/// reported as an unscoped run. A request name added later carries its own
98/// class, so a consumer written today keeps saying the right thing about it.
99///
100/// The value set is OPEN, like the names and the statuses: read a class this
101/// build does not recognise as "some request", not as an error, and do not read
102/// it as `scope`.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
104#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
105#[serde(rename_all = "kebab-case")]
106pub enum RequestEffect {
107    /// The request narrows what the report covers. Not applied means the
108    /// report that follows is complete, valid, and WIDER than what was asked
109    /// for, which is a reviewing problem rather than a build failure.
110    Scope,
111    /// The request produces a secondary file beside the report. Not applied
112    /// means that file was not written, so anything consuming it has nothing to
113    /// read. The report on stdout and the exit code are unaffected, and nothing
114    /// about the run's scope changed.
115    Artifact,
116}
117
118/// What became of one request on this run.
119///
120/// Two-valued today. The value set is OPEN so a later `partial` needs no bump,
121/// and it is deliberately not added now: nothing emits it, and a permanently
122/// unused value reads as a measurement nobody takes.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
124#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
125#[serde(rename_all = "kebab-case")]
126pub enum RequestStatus {
127    /// The run did what it was asked. The report is scoped or shaped as
128    /// requested.
129    Applied,
130    /// The run could not do what it was asked and continued anyway. The report
131    /// that follows is valid and complete; what the failure cost is read off
132    /// `affects`, which says whether the report widened or a requested file was
133    /// never written.
134    NotApplied,
135}
136
137/// One request's fate on one run.
138///
139/// `reason` and `message` are present exactly when `status` is not `applied`,
140/// and absent otherwise, so a consumer that only wants to know whether a
141/// report is scoped reads `status` alone.
142#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
143#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
144pub struct RequestOutcome {
145    /// What became of the request.
146    pub status: RequestStatus,
147    /// What this request governs, and therefore what an unapplied one means.
148    /// Derived from the name, so the two can never disagree.
149    pub affects: RequestEffect,
150    /// What was asked, as the user spelled it: the git ref for
151    /// `changed-since`, the diff source label (`--diff-file pr.diff`,
152    /// `--diff-stdin`, `$FALLOW_DIFF_FILE build/pr.diff`, or
153    /// `diffFile pr.diff` for the programmatic option) for `diff-filter`,
154    /// the target path for `sarif-file`. Echoed rather than normalised, so a
155    /// consumer must not join it to the project root the way it joins every
156    /// other path-shaped field.
157    pub requested: String,
158    /// How much this request left in scope, in the request's own unit, when the
159    /// run applied it AND measured that scope. Absent otherwise, including on
160    /// every unapplied entry: a request that stood down narrowed nothing, so a
161    /// number there would describe a scope nobody applied.
162    ///
163    /// The unit belongs to the name. `diff-filter` counts added lines, which is
164    /// what its filter keeps a finding for. `changed-since` counts changed
165    /// files that the run analyzed: a changed file that discovery or an ignore
166    /// rule dropped does not count, so a change to a README only gives `0`. A
167    /// combined run counts a file that any of its analyses kept, because a
168    /// per-analysis `production` setting can give its analyses different
169    /// files.
170    /// Read the unit off the name the entry is keyed under, never across names,
171    /// and read an absent member as "not measured" rather than as zero.
172    ///
173    /// The count is what the run INDEXED rather than the true total:
174    /// `diff-filter` indexes at most one million added lines and reports that
175    /// cap for a larger diff, so read any non-zero value as a lower bound.
176    ///
177    /// `0` is the case this member exists for: a request that applied over an
178    /// EMPTY scope. Every finding then filters out and the report reads clean,
179    /// so a consumer that sees no findings beside `scope_size: 0` learns that
180    /// nothing was analyzable rather than that the code is clean.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub scope_size: Option<u64>,
183    /// Why the request was not applied, as a kebab-case token. Present exactly
184    /// when `status` is not `applied`. The set is open per request name; the
185    /// names this build can emit are listed on [`RequestOutcomes`].
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub reason: Option<String>,
188    /// One sentence naming what was asked, what happened instead, and the next
189    /// step. Byte-identical to the stderr line for the same case, so a
190    /// consumer that renders this never contradicts a log a human read.
191    /// Present exactly when `status` is not `applied`.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub message: Option<String>,
194}
195
196impl RequestOutcome {
197    /// A request the run honoured.
198    ///
199    /// Takes the name rather than the class so no caller can file a request
200    /// under the wrong one.
201    #[must_use]
202    pub fn applied(name: RequestName, requested: impl Into<String>) -> Self {
203        Self {
204            status: RequestStatus::Applied,
205            affects: name.affects(),
206            requested: requested.into(),
207            scope_size: None,
208            reason: None,
209            message: None,
210        }
211    }
212
213    /// A request the run honoured, whose remaining scope it also measured.
214    ///
215    /// `size` is in the unit [`RequestOutcome::scope_size`] documents for this
216    /// name. Use [`Self::applied`] where the run applies a request without
217    /// measuring what it left, so the member stays absent rather than claiming
218    /// a zero nobody counted.
219    #[must_use]
220    pub fn applied_with_scope_size(
221        name: RequestName,
222        requested: impl Into<String>,
223        size: u64,
224    ) -> Self {
225        Self {
226            scope_size: Some(size),
227            ..Self::applied(name, requested)
228        }
229    }
230
231    /// A request the run could not honour, with the reason token and the
232    /// sentence the CLI also wrote to stderr.
233    #[must_use]
234    pub fn not_applied(
235        name: RequestName,
236        requested: impl Into<String>,
237        reason: impl Into<String>,
238        message: impl Into<String>,
239    ) -> Self {
240        Self {
241            status: RequestStatus::NotApplied,
242            affects: name.affects(),
243            requested: requested.into(),
244            scope_size: None,
245            reason: Some(reason.into()),
246            message: Some(message.into()),
247        }
248    }
249}
250
251/// Every narrowing or shaping request a run RECEIVED, keyed by name.
252///
253/// Received, not failed: a request the run honoured is published with
254/// `status: "applied"`, so a consumer can say "scoped to the change"
255/// positively. Read an absent object as "nothing was asked for", never as
256/// "nothing failed".
257///
258/// Absent from an envelope whenever it is empty, so a run that was asked for
259/// nothing is byte-identical to one produced before this object existed. An
260/// empty object is never emitted: it would assert that something was asked and
261/// all of it applied, which is a different and false claim.
262///
263/// The names this build can emit are `changed-since`, `diff-filter` and
264/// `sarif-file`. The reasons are `git-missing`, `not-a-repository`,
265/// `git-failed` and `invalid-ref` for `changed-since`, `oversize`,
266/// `unreadable`, `not-utf8`, `foreign-namespace` and `ambiguous-base` for
267/// `diff-filter`, and `directory-create-failed`, `write-failed` and
268/// `serialize-failed` for `sarif-file`. Every set is OPEN: a name a consumer
269/// does not recognise means "some request", not an error.
270///
271/// `sarif-file` reports a SECONDARY artifact rather than the scope of the
272/// report it travels in, and it is in the same object for the same reason the
273/// others are: the run was asked to do something and did something else, and
274/// nothing in the primary report says so. Which of the two an entry is, every
275/// entry says for itself: `affects` is `scope` for the narrowing requests and
276/// `artifact` for this one. Select on it. A consumer that instead assumes the
277/// whole object narrows the report tells its reader an unwritten SARIF file
278/// widened the analysis, which is what `affects` exists to prevent.
279///
280/// `scope_size` is emitted for `diff-filter`, in added lines, and for
281/// `changed-since`, in changed files that the run analyzed. `sarif-file`
282/// measures no scope. A consumer reads the unit off the name, so a name that
283/// starts to measure its own scope in a later release needs no change here.
284///
285/// `invalid-ref` is reachable only through the programmatic API. The
286/// `--changed-since` flag validates its value before a run starts and fails
287/// with exit 2 and an error document, which is the right side to err on: a
288/// malformed ref is invalid input rather than a report of the wrong scope.
289#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
290#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
291#[serde(transparent)]
292pub struct RequestOutcomes(BTreeMap<RequestName, RequestOutcome>);
293
294impl RequestOutcomes {
295    /// An empty set, which serializes to nothing once [`Self::into_option`]
296    /// has been applied.
297    #[must_use]
298    pub fn new() -> Self {
299        Self(BTreeMap::new())
300    }
301
302    /// Record one request's outcome, replacing any previous entry for that
303    /// name.
304    pub fn insert(&mut self, name: RequestName, outcome: RequestOutcome) {
305        self.0.insert(name, outcome);
306    }
307
308    /// Record one request's outcome when the run received it at all.
309    pub fn insert_if(&mut self, name: RequestName, outcome: Option<RequestOutcome>) {
310        if let Some(outcome) = outcome {
311            self.0.insert(name, outcome);
312        }
313    }
314
315    /// Collapse an empty set to `None`, which is how the field stays absent on
316    /// a run that was asked for nothing.
317    #[must_use]
318    pub fn into_option(self) -> Option<Self> {
319        if self.0.is_empty() { None } else { Some(self) }
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn empty_set_collapses_to_absent() {
329        assert!(RequestOutcomes::new().into_option().is_none());
330    }
331
332    #[test]
333    fn populated_set_survives_collapse() {
334        let mut requests = RequestOutcomes::new();
335        requests.insert(
336            RequestName::ChangedSince,
337            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
338        );
339        assert!(requests.into_option().is_some());
340    }
341
342    /// An honoured request carries neither a reason nor a sentence, so a
343    /// consumer reading `message` never renders prose about a run that did
344    /// exactly what it was told.
345    #[test]
346    fn an_applied_request_carries_no_reason_and_no_message() {
347        let mut requests = RequestOutcomes::new();
348        requests.insert(
349            RequestName::DiffFilter,
350            RequestOutcome::applied(RequestName::DiffFilter, "--diff-file pr.diff"),
351        );
352        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
353        assert_eq!(
354            value,
355            serde_json::json!({
356                "diff-filter": {
357                    "status": "applied",
358                    "affects": "scope",
359                    "requested": "--diff-file pr.diff"
360                }
361            })
362        );
363    }
364
365    #[test]
366    fn names_and_statuses_serialize_as_kebab_case() {
367        let mut requests = RequestOutcomes::new();
368        requests.insert(
369            RequestName::ChangedSince,
370            RequestOutcome::not_applied(
371                RequestName::ChangedSince,
372                "origin/main",
373                "invalid-ref",
374                "Ignored.",
375            ),
376        );
377        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
378        assert_eq!(
379            value,
380            serde_json::json!({
381                "changed-since": {
382                    "status": "not-applied",
383                    "affects": "scope",
384                    "requested": "origin/main",
385                    "reason": "invalid-ref",
386                    "message": "Ignored."
387                }
388            })
389        );
390    }
391
392    /// Two requests with different fates travel in one object, so a consumer
393    /// reads the scope of each channel rather than one verdict for the run.
394    #[test]
395    fn two_channels_keep_their_own_status_in_one_object() {
396        let mut requests = RequestOutcomes::new();
397        requests.insert(
398            RequestName::ChangedSince,
399            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
400        );
401        requests.insert(
402            RequestName::DiffFilter,
403            RequestOutcome::not_applied(
404                RequestName::DiffFilter,
405                "--diff-stdin",
406                "not-utf8",
407                "Ignored.",
408            ),
409        );
410        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
411        assert_eq!(value["changed-since"]["status"], "applied");
412        assert_eq!(value["diff-filter"]["status"], "not-applied");
413        assert_eq!(value["diff-filter"]["reason"], "not-utf8");
414    }
415
416    /// The class travels with the entry, so a consumer never has to keep a
417    /// name list to know whether an unapplied request widened the report.
418    #[test]
419    fn a_secondary_artifact_request_is_not_classed_as_scope() {
420        let mut requests = RequestOutcomes::new();
421        requests.insert(
422            RequestName::SarifFile,
423            RequestOutcome::not_applied(
424                RequestName::SarifFile,
425                "out.sarif",
426                "write-failed",
427                "Not written.",
428            ),
429        );
430        requests.insert(
431            RequestName::ChangedSince,
432            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
433        );
434        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
435        assert_eq!(value["sarif-file"]["affects"], "artifact");
436        assert_eq!(value["changed-since"]["affects"], "scope");
437    }
438
439    /// The class is derived from the name at construction, so an entry filed
440    /// under one name cannot carry another's class.
441    #[test]
442    fn every_name_carries_its_own_class() {
443        assert_eq!(RequestName::ChangedSince.affects(), RequestEffect::Scope);
444        assert_eq!(RequestName::DiffFilter.affects(), RequestEffect::Scope);
445        assert_eq!(RequestName::SarifFile.affects(), RequestEffect::Artifact);
446    }
447
448    /// An applied request that measured an empty scope is the case the member
449    /// exists for: `status` stays `applied`, because the filter DID apply, and
450    /// the zero is what tells a consumer the clean report covered nothing.
451    #[test]
452    fn an_empty_measured_scope_stays_applied_and_publishes_its_zero() {
453        let mut requests = RequestOutcomes::new();
454        requests.insert(
455            RequestName::DiffFilter,
456            RequestOutcome::applied_with_scope_size(
457                RequestName::DiffFilter,
458                "--diff-file pr.diff",
459                0,
460            ),
461        );
462        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
463        assert_eq!(
464            value,
465            serde_json::json!({
466                "diff-filter": {
467                    "status": "applied",
468                    "affects": "scope",
469                    "requested": "--diff-file pr.diff",
470                    "scope_size": 0
471                }
472            })
473        );
474    }
475
476    /// Absent is not zero. A request the run applied without counting what it
477    /// left carries no member, so a consumer cannot read "not measured" as "the
478    /// scope was empty".
479    #[test]
480    fn a_request_that_measured_nothing_carries_no_scope_size() {
481        let mut requests = RequestOutcomes::new();
482        requests.insert(
483            RequestName::ChangedSince,
484            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
485        );
486        requests.insert(
487            RequestName::DiffFilter,
488            RequestOutcome::not_applied(
489                RequestName::DiffFilter,
490                "--diff-stdin",
491                "oversize",
492                "Ignored.",
493            ),
494        );
495        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
496        assert!(
497            value["changed-since"].get("scope_size").is_none(),
498            "an unmeasured applied request carries no member: {value}"
499        );
500        assert!(
501            value["diff-filter"].get("scope_size").is_none(),
502            "a request that stood down narrowed nothing: {value}"
503        );
504    }
505
506    #[test]
507    fn insert_if_skips_a_request_the_run_never_received() {
508        let mut requests = RequestOutcomes::new();
509        requests.insert_if(RequestName::ChangedSince, None);
510        assert!(requests.into_option().is_none());
511    }
512}