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`) for `diff-filter`,
153    /// the target path for `sarif-file`. Echoed rather than normalised, so a
154    /// consumer must not join it to the project root the way it joins every
155    /// other path-shaped field.
156    pub requested: String,
157    /// How much this request left in scope, in the request's own unit, when the
158    /// run applied it AND measured that scope. Absent otherwise, including on
159    /// every unapplied entry: a request that stood down narrowed nothing, so a
160    /// number there would describe a scope nobody applied.
161    ///
162    /// The unit belongs to the name. `diff-filter` counts added lines, which is
163    /// what its filter keeps a finding for. Read the unit off the name the entry
164    /// is keyed under, never across names, and read an absent member as "not
165    /// measured" rather than as zero.
166    ///
167    /// The count is what the run INDEXED rather than the true total:
168    /// `diff-filter` indexes at most one million added lines and reports that
169    /// cap for a larger diff, so read any non-zero value as a lower bound.
170    ///
171    /// `0` is the case this member exists for: a request that applied over an
172    /// EMPTY scope. Every finding then filters out and the report reads clean,
173    /// so a consumer that sees no findings beside `scope_size: 0` learns that
174    /// nothing was analyzable rather than that the code is clean.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub scope_size: Option<u64>,
177    /// Why the request was not applied, as a kebab-case token. Present exactly
178    /// when `status` is not `applied`. The set is open per request name; the
179    /// names this build can emit are listed on [`RequestOutcomes`].
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub reason: Option<String>,
182    /// One sentence naming what was asked, what happened instead, and the next
183    /// step. Byte-identical to the stderr line for the same case, so a
184    /// consumer that renders this never contradicts a log a human read.
185    /// Present exactly when `status` is not `applied`.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub message: Option<String>,
188}
189
190impl RequestOutcome {
191    /// A request the run honoured.
192    ///
193    /// Takes the name rather than the class so no caller can file a request
194    /// under the wrong one.
195    #[must_use]
196    pub fn applied(name: RequestName, requested: impl Into<String>) -> Self {
197        Self {
198            status: RequestStatus::Applied,
199            affects: name.affects(),
200            requested: requested.into(),
201            scope_size: None,
202            reason: None,
203            message: None,
204        }
205    }
206
207    /// A request the run honoured, whose remaining scope it also measured.
208    ///
209    /// `size` is in the unit [`RequestOutcome::scope_size`] documents for this
210    /// name. Use [`Self::applied`] where the run applies a request without
211    /// measuring what it left, so the member stays absent rather than claiming
212    /// a zero nobody counted.
213    #[must_use]
214    pub fn applied_with_scope_size(
215        name: RequestName,
216        requested: impl Into<String>,
217        size: u64,
218    ) -> Self {
219        Self {
220            scope_size: Some(size),
221            ..Self::applied(name, requested)
222        }
223    }
224
225    /// A request the run could not honour, with the reason token and the
226    /// sentence the CLI also wrote to stderr.
227    #[must_use]
228    pub fn not_applied(
229        name: RequestName,
230        requested: impl Into<String>,
231        reason: impl Into<String>,
232        message: impl Into<String>,
233    ) -> Self {
234        Self {
235            status: RequestStatus::NotApplied,
236            affects: name.affects(),
237            requested: requested.into(),
238            scope_size: None,
239            reason: Some(reason.into()),
240            message: Some(message.into()),
241        }
242    }
243}
244
245/// Every narrowing or shaping request a run RECEIVED, keyed by name.
246///
247/// Received, not failed: a request the run honoured is published with
248/// `status: "applied"`, so a consumer can say "scoped to the change"
249/// positively. Read an absent object as "nothing was asked for", never as
250/// "nothing failed".
251///
252/// Absent from an envelope whenever it is empty, so a run that was asked for
253/// nothing is byte-identical to one produced before this object existed. An
254/// empty object is never emitted: it would assert that something was asked and
255/// all of it applied, which is a different and false claim.
256///
257/// The names this build can emit are `changed-since`, `diff-filter` and
258/// `sarif-file`. The reasons are `git-missing`, `not-a-repository`,
259/// `git-failed` and `invalid-ref` for `changed-since`, `oversize`,
260/// `unreadable`, `not-utf8`, `foreign-namespace` and `ambiguous-base` for
261/// `diff-filter`, and `directory-create-failed`, `write-failed` and
262/// `serialize-failed` for `sarif-file`. Every set is OPEN: a name a consumer
263/// does not recognise means "some request", not an error.
264///
265/// `sarif-file` reports a SECONDARY artifact rather than the scope of the
266/// report it travels in, and it is in the same object for the same reason the
267/// others are: the run was asked to do something and did something else, and
268/// nothing in the primary report says so. Which of the two an entry is, every
269/// entry says for itself: `affects` is `scope` for the narrowing requests and
270/// `artifact` for this one. Select on it. A consumer that instead assumes the
271/// whole object narrows the report tells its reader an unwritten SARIF file
272/// widened the analysis, which is what `affects` exists to prevent.
273///
274/// `scope_size` is emitted for `diff-filter` only today, in added lines. A
275/// consumer reads the unit off the name, so a name that starts measuring its
276/// own scope in a later release needs no change here.
277///
278/// `invalid-ref` is reachable only through the programmatic API. The
279/// `--changed-since` flag validates its value before a run starts and fails
280/// with exit 2 and an error document, which is the right side to err on: a
281/// malformed ref is invalid input rather than a report of the wrong scope.
282#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
283#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
284#[serde(transparent)]
285pub struct RequestOutcomes(BTreeMap<RequestName, RequestOutcome>);
286
287impl RequestOutcomes {
288    /// An empty set, which serializes to nothing once [`Self::into_option`]
289    /// has been applied.
290    #[must_use]
291    pub fn new() -> Self {
292        Self(BTreeMap::new())
293    }
294
295    /// Record one request's outcome, replacing any previous entry for that
296    /// name.
297    pub fn insert(&mut self, name: RequestName, outcome: RequestOutcome) {
298        self.0.insert(name, outcome);
299    }
300
301    /// Record one request's outcome when the run received it at all.
302    pub fn insert_if(&mut self, name: RequestName, outcome: Option<RequestOutcome>) {
303        if let Some(outcome) = outcome {
304            self.0.insert(name, outcome);
305        }
306    }
307
308    /// Collapse an empty set to `None`, which is how the field stays absent on
309    /// a run that was asked for nothing.
310    #[must_use]
311    pub fn into_option(self) -> Option<Self> {
312        if self.0.is_empty() { None } else { Some(self) }
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    #[test]
321    fn empty_set_collapses_to_absent() {
322        assert!(RequestOutcomes::new().into_option().is_none());
323    }
324
325    #[test]
326    fn populated_set_survives_collapse() {
327        let mut requests = RequestOutcomes::new();
328        requests.insert(
329            RequestName::ChangedSince,
330            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
331        );
332        assert!(requests.into_option().is_some());
333    }
334
335    /// An honoured request carries neither a reason nor a sentence, so a
336    /// consumer reading `message` never renders prose about a run that did
337    /// exactly what it was told.
338    #[test]
339    fn an_applied_request_carries_no_reason_and_no_message() {
340        let mut requests = RequestOutcomes::new();
341        requests.insert(
342            RequestName::DiffFilter,
343            RequestOutcome::applied(RequestName::DiffFilter, "--diff-file pr.diff"),
344        );
345        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
346        assert_eq!(
347            value,
348            serde_json::json!({
349                "diff-filter": {
350                    "status": "applied",
351                    "affects": "scope",
352                    "requested": "--diff-file pr.diff"
353                }
354            })
355        );
356    }
357
358    #[test]
359    fn names_and_statuses_serialize_as_kebab_case() {
360        let mut requests = RequestOutcomes::new();
361        requests.insert(
362            RequestName::ChangedSince,
363            RequestOutcome::not_applied(
364                RequestName::ChangedSince,
365                "origin/main",
366                "invalid-ref",
367                "Ignored.",
368            ),
369        );
370        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
371        assert_eq!(
372            value,
373            serde_json::json!({
374                "changed-since": {
375                    "status": "not-applied",
376                    "affects": "scope",
377                    "requested": "origin/main",
378                    "reason": "invalid-ref",
379                    "message": "Ignored."
380                }
381            })
382        );
383    }
384
385    /// Two requests with different fates travel in one object, so a consumer
386    /// reads the scope of each channel rather than one verdict for the run.
387    #[test]
388    fn two_channels_keep_their_own_status_in_one_object() {
389        let mut requests = RequestOutcomes::new();
390        requests.insert(
391            RequestName::ChangedSince,
392            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
393        );
394        requests.insert(
395            RequestName::DiffFilter,
396            RequestOutcome::not_applied(
397                RequestName::DiffFilter,
398                "--diff-stdin",
399                "not-utf8",
400                "Ignored.",
401            ),
402        );
403        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
404        assert_eq!(value["changed-since"]["status"], "applied");
405        assert_eq!(value["diff-filter"]["status"], "not-applied");
406        assert_eq!(value["diff-filter"]["reason"], "not-utf8");
407    }
408
409    /// The class travels with the entry, so a consumer never has to keep a
410    /// name list to know whether an unapplied request widened the report.
411    #[test]
412    fn a_secondary_artifact_request_is_not_classed_as_scope() {
413        let mut requests = RequestOutcomes::new();
414        requests.insert(
415            RequestName::SarifFile,
416            RequestOutcome::not_applied(
417                RequestName::SarifFile,
418                "out.sarif",
419                "write-failed",
420                "Not written.",
421            ),
422        );
423        requests.insert(
424            RequestName::ChangedSince,
425            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
426        );
427        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
428        assert_eq!(value["sarif-file"]["affects"], "artifact");
429        assert_eq!(value["changed-since"]["affects"], "scope");
430    }
431
432    /// The class is derived from the name at construction, so an entry filed
433    /// under one name cannot carry another's class.
434    #[test]
435    fn every_name_carries_its_own_class() {
436        assert_eq!(RequestName::ChangedSince.affects(), RequestEffect::Scope);
437        assert_eq!(RequestName::DiffFilter.affects(), RequestEffect::Scope);
438        assert_eq!(RequestName::SarifFile.affects(), RequestEffect::Artifact);
439    }
440
441    /// An applied request that measured an empty scope is the case the member
442    /// exists for: `status` stays `applied`, because the filter DID apply, and
443    /// the zero is what tells a consumer the clean report covered nothing.
444    #[test]
445    fn an_empty_measured_scope_stays_applied_and_publishes_its_zero() {
446        let mut requests = RequestOutcomes::new();
447        requests.insert(
448            RequestName::DiffFilter,
449            RequestOutcome::applied_with_scope_size(
450                RequestName::DiffFilter,
451                "--diff-file pr.diff",
452                0,
453            ),
454        );
455        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
456        assert_eq!(
457            value,
458            serde_json::json!({
459                "diff-filter": {
460                    "status": "applied",
461                    "affects": "scope",
462                    "requested": "--diff-file pr.diff",
463                    "scope_size": 0
464                }
465            })
466        );
467    }
468
469    /// Absent is not zero. A request the run applied without counting what it
470    /// left carries no member, so a consumer cannot read "not measured" as "the
471    /// scope was empty".
472    #[test]
473    fn a_request_that_measured_nothing_carries_no_scope_size() {
474        let mut requests = RequestOutcomes::new();
475        requests.insert(
476            RequestName::ChangedSince,
477            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
478        );
479        requests.insert(
480            RequestName::DiffFilter,
481            RequestOutcome::not_applied(
482                RequestName::DiffFilter,
483                "--diff-stdin",
484                "oversize",
485                "Ignored.",
486            ),
487        );
488        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
489        assert!(
490            value["changed-since"].get("scope_size").is_none(),
491            "an unmeasured applied request carries no member: {value}"
492        );
493        assert!(
494            value["diff-filter"].get("scope_size").is_none(),
495            "a request that stood down narrowed nothing: {value}"
496        );
497    }
498
499    #[test]
500    fn insert_if_skips_a_request_the_run_never_received() {
501        let mut requests = RequestOutcomes::new();
502        requests.insert_if(RequestName::ChangedSince, None);
503        assert!(requests.into_option().is_none());
504    }
505}