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    /// `workspaces.changedSince` in the config: scope the findings of each
73    /// mapped workspace package to the files that changed since its own ref.
74    /// Not applied means a key named no workspace or a mapped ref did not
75    /// resolve, so the report covers every package in full scope. A global changed-since ref overrides the
76    /// map, and the run then publishes no entry for it.
77    PackageBaselines,
78    /// `--sarif-file <path>`: also write the findings as a SARIF document at
79    /// `path`. Not applied means the file was never written, so a consumer
80    /// uploading it to code scanning has nothing to upload. The primary report
81    /// on stdout is unaffected, which is why the run neither fails nor says
82    /// anything else about it.
83    SarifFile,
84    /// `--group <KEY>` with `--group-by`: keep only the matching groups in the
85    /// `groups` array. `scope_size` counts the groups the run kept, so `0`
86    /// means that no group matched. The project-level sections are not
87    /// filtered.
88    GroupFilter,
89}
90
91impl RequestName {
92    /// The kebab-case wire name of the request.
93    #[must_use]
94    pub const fn as_str(self) -> &'static str {
95        match self {
96            Self::ChangedSince => "changed-since",
97            Self::DiffFilter => "diff-filter",
98            Self::PackageBaselines => "package-baselines",
99            Self::SarifFile => "sarif-file",
100            Self::GroupFilter => "group-filter",
101        }
102    }
103
104    /// What an unapplied request of this name means for the report.
105    #[must_use]
106    pub const fn affects(self) -> RequestEffect {
107        match self {
108            Self::ChangedSince | Self::DiffFilter | Self::PackageBaselines | Self::GroupFilter => {
109                RequestEffect::Scope
110            }
111            Self::SarifFile => RequestEffect::Artifact,
112        }
113    }
114}
115
116/// What a request governs, and therefore what its failure means.
117///
118/// Published on every entry so a consumer selects on the class rather than on
119/// a name list. Without it the one sentence a consumer can write for the whole
120/// object ("the report is wider than requested") is false for any request that
121/// does not narrow, which is how a failed `--sarif-file` write came to be
122/// reported as an unscoped run. A request name added later carries its own
123/// class, so a consumer written today keeps saying the right thing about it.
124///
125/// The value set is open, like the names and the statuses: read a class this
126/// build does not recognise as "some request", not as an error, and do not read
127/// it as `scope`.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
129#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
130#[serde(rename_all = "kebab-case")]
131pub enum RequestEffect {
132    /// The request narrows what the report covers. Not applied means the
133    /// report that follows is complete, valid, and wider than what was asked
134    /// for, which is a reviewing problem rather than a build failure.
135    Scope,
136    /// The request produces a secondary file beside the report. Not applied
137    /// means that file was not written, so anything consuming it has nothing to
138    /// read. The report on stdout and the exit code are unaffected, and nothing
139    /// about the run's scope changed.
140    Artifact,
141}
142
143/// What became of one request on this run.
144///
145/// Two-valued today. The value set is open so a later `partial` needs no bump,
146/// and it is deliberately not added now: nothing emits it, and a permanently
147/// unused value reads as a measurement nobody takes.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
149#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
150#[serde(rename_all = "kebab-case")]
151pub enum RequestStatus {
152    /// The run did what it was asked. The report is scoped or shaped as
153    /// requested.
154    Applied,
155    /// The run could not do what it was asked and continued anyway. The report
156    /// that follows is valid and complete; what the failure cost is read off
157    /// `affects`, which says whether the report widened or a requested file was
158    /// never written.
159    NotApplied,
160}
161
162/// One request's fate on one run.
163///
164/// `reason` and `message` are present exactly when `status` is not `applied`,
165/// and absent otherwise, so a consumer that only wants to know whether a
166/// report is scoped reads `status` alone.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
168#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
169pub struct RequestOutcome {
170    /// What became of the request.
171    pub status: RequestStatus,
172    /// What this request governs, and therefore what an unapplied one means.
173    /// Derived from the name, so the two can never disagree.
174    pub affects: RequestEffect,
175    /// What was asked, as the user spelled it: the git ref for
176    /// `changed-since`, the diff source label (`--diff-file pr.diff`,
177    /// `--diff-stdin`, `$FALLOW_DIFF_FILE build/pr.diff`, or
178    /// `diffFile pr.diff` for the programmatic option) for `diff-filter`,
179    /// `workspaces.changedSince` for `package-baselines`, the target path for
180    /// `sarif-file`, the comma-joined selector patterns for `group-filter`.
181    /// Echoed rather than normalised, so a
182    /// consumer must not join it to the project root the way it joins every
183    /// other path-shaped field.
184    pub requested: String,
185    /// How much this request left in scope, in the request's own unit, when the
186    /// run applied it AND measured that scope. Absent otherwise, including on
187    /// every unapplied entry: a request that stood down narrowed nothing, so a
188    /// number there would describe a scope nobody applied.
189    ///
190    /// The unit belongs to the name. `diff-filter` counts added lines, plus one
191    /// for each touched file that adds no line (a pure rename), because its
192    /// filter keeps a finding on an added line or on a whole touched file.
193    /// `changed-since` counts changed files that the run analyzed: a changed
194    /// file that discovery or an ignore rule dropped does not count, so a
195    /// change to a README only gives `0`. A combined run counts a file that
196    /// any of its analyses kept, because a per-analysis `production` setting
197    /// can give its analyses different files. `group-filter` counts the groups
198    /// that the run kept.
199    /// Read the unit off the name the entry is keyed under, never across names,
200    /// and read an absent member as "not measured" rather than as zero.
201    ///
202    /// The count is what the run indexed rather than the true total:
203    /// `diff-filter` indexes at most one million added lines and reports that
204    /// cap for a larger diff, so read any non-zero value as a lower bound.
205    ///
206    /// `0` is the case this member exists for: a request that applied over an
207    /// empty scope. Every source-anchored finding then filters out and the
208    /// report reads clean, so a consumer that sees no findings beside
209    /// `scope_size: 0` learns that nothing was analyzable rather than that
210    /// the code is clean.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub scope_size: Option<u64>,
213    /// Why the request was not applied, as a kebab-case token. Present exactly
214    /// when `status` is not `applied`. The set is open per request name; the
215    /// names this build can emit are listed on [`RequestOutcomes`].
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub reason: Option<String>,
218    /// One sentence naming what was asked, what happened instead, and the next
219    /// step. Byte-identical to the stderr line for the same case, so a
220    /// consumer that renders this never contradicts a log a human read.
221    /// Present exactly when `status` is not `applied`.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub message: Option<String>,
224}
225
226impl RequestOutcome {
227    /// A request the run honoured.
228    ///
229    /// Takes the name rather than the class so no caller can file a request
230    /// under the wrong one.
231    #[must_use]
232    pub fn applied(name: RequestName, requested: impl Into<String>) -> Self {
233        Self {
234            status: RequestStatus::Applied,
235            affects: name.affects(),
236            requested: requested.into(),
237            scope_size: None,
238            reason: None,
239            message: None,
240        }
241    }
242
243    /// A request the run honoured, whose remaining scope it also measured.
244    ///
245    /// `size` is in the unit [`RequestOutcome::scope_size`] documents for this
246    /// name. Use [`Self::applied`] where the run applies a request without
247    /// measuring what it left, so the member stays absent rather than claiming
248    /// a zero nobody counted.
249    #[must_use]
250    pub fn applied_with_scope_size(
251        name: RequestName,
252        requested: impl Into<String>,
253        size: u64,
254    ) -> Self {
255        Self {
256            scope_size: Some(size),
257            ..Self::applied(name, requested)
258        }
259    }
260
261    /// A request the run could not honour, with the reason token and the
262    /// sentence the CLI also wrote to stderr.
263    #[must_use]
264    pub fn not_applied(
265        name: RequestName,
266        requested: impl Into<String>,
267        reason: impl Into<String>,
268        message: impl Into<String>,
269    ) -> Self {
270        Self {
271            status: RequestStatus::NotApplied,
272            affects: name.affects(),
273            requested: requested.into(),
274            scope_size: None,
275            reason: Some(reason.into()),
276            message: Some(message.into()),
277        }
278    }
279}
280
281/// Every narrowing or shaping request a run received, keyed by name.
282///
283/// Received, not failed: a request the run honoured is published with
284/// `status: "applied"`, so a consumer can say "scoped to the change"
285/// positively. Read an absent object as "nothing was asked for", never as
286/// "nothing failed".
287///
288/// Absent from an envelope whenever it is empty, so a run that was asked for
289/// nothing is byte-identical to one produced before this object existed. An
290/// empty object is never emitted: it would assert that something was asked and
291/// all of it applied, which is a different and false claim.
292///
293/// The names this build can emit are `changed-since`, `diff-filter`,
294/// `package-baselines`, `sarif-file` and `group-filter`. The reasons are `git-missing`,
295/// `not-a-repository`, `git-failed` and `invalid-ref` for `changed-since`,
296/// `unknown-workspace`, `git-missing`, `not-a-repository` and `git-failed`
297/// for `package-baselines`, `oversize`,
298/// `unreadable`, `not-utf8`, `foreign-namespace` and `ambiguous-base` for
299/// `diff-filter`, and `directory-create-failed`, `write-failed` and
300/// `serialize-failed` for `sarif-file`. Every set is open: a name a consumer
301/// does not recognise means "some request", not an error.
302///
303/// `sarif-file` reports a secondary artifact rather than the scope of the
304/// report it travels in, and it is in the same object for the same reason the
305/// others are: the run was asked to do something and did something else, and
306/// nothing in the primary report says so. Which of the two an entry is, every
307/// entry says for itself: `affects` is `scope` for the narrowing requests and
308/// `artifact` for this one. Select on it. A consumer that instead assumes the
309/// whole object narrows the report tells its reader an unwritten SARIF file
310/// widened the analysis, which is what `affects` exists to prevent.
311///
312/// `scope_size` is emitted for `diff-filter`, in added lines plus touched
313/// files that add no line, for `changed-since`, in changed files that the run
314/// analyzed, and for `group-filter`, in groups that the run kept.
315/// `package-baselines` and `sarif-file` measure no scope; the applied package refs travel in
316/// `package_baselines`. A consumer reads the unit off the name, so a name that
317/// starts to measure its own scope in a later release needs no change here.
318///
319/// `invalid-ref` is reachable only through the programmatic API. The
320/// `--changed-since` flag validates its value before a run starts and fails
321/// with exit 2 and an error document, which is the right side to err on: a
322/// malformed ref is invalid input rather than a report of the wrong scope.
323#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
324#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
325#[serde(transparent)]
326pub struct RequestOutcomes(BTreeMap<RequestName, RequestOutcome>);
327
328impl RequestOutcomes {
329    /// An empty set, which serializes to nothing once [`Self::into_option`]
330    /// has been applied.
331    #[must_use]
332    pub fn new() -> Self {
333        Self(BTreeMap::new())
334    }
335
336    /// Record one request's outcome, replacing any previous entry for that
337    /// name.
338    pub fn insert(&mut self, name: RequestName, outcome: RequestOutcome) {
339        self.0.insert(name, outcome);
340    }
341
342    /// Record one request's outcome when the run received it at all.
343    pub fn insert_if(&mut self, name: RequestName, outcome: Option<RequestOutcome>) {
344        if let Some(outcome) = outcome {
345            self.0.insert(name, outcome);
346        }
347    }
348
349    /// Collapse an empty set to `None`, which is how the field stays absent on
350    /// a run that was asked for nothing.
351    #[must_use]
352    pub fn into_option(self) -> Option<Self> {
353        if self.0.is_empty() { None } else { Some(self) }
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn empty_set_collapses_to_absent() {
363        assert!(RequestOutcomes::new().into_option().is_none());
364    }
365
366    #[test]
367    fn populated_set_survives_collapse() {
368        let mut requests = RequestOutcomes::new();
369        requests.insert(
370            RequestName::ChangedSince,
371            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
372        );
373        assert!(requests.into_option().is_some());
374    }
375
376    /// An honoured request carries neither a reason nor a sentence, so a
377    /// consumer reading `message` never renders prose about a run that did
378    /// exactly what it was told.
379    #[test]
380    fn an_applied_request_carries_no_reason_and_no_message() {
381        let mut requests = RequestOutcomes::new();
382        requests.insert(
383            RequestName::DiffFilter,
384            RequestOutcome::applied(RequestName::DiffFilter, "--diff-file pr.diff"),
385        );
386        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
387        assert_eq!(
388            value,
389            serde_json::json!({
390                "diff-filter": {
391                    "status": "applied",
392                    "affects": "scope",
393                    "requested": "--diff-file pr.diff"
394                }
395            })
396        );
397    }
398
399    #[test]
400    fn names_and_statuses_serialize_as_kebab_case() {
401        let mut requests = RequestOutcomes::new();
402        requests.insert(
403            RequestName::ChangedSince,
404            RequestOutcome::not_applied(
405                RequestName::ChangedSince,
406                "origin/main",
407                "invalid-ref",
408                "Ignored.",
409            ),
410        );
411        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
412        assert_eq!(
413            value,
414            serde_json::json!({
415                "changed-since": {
416                    "status": "not-applied",
417                    "affects": "scope",
418                    "requested": "origin/main",
419                    "reason": "invalid-ref",
420                    "message": "Ignored."
421                }
422            })
423        );
424    }
425
426    /// Two requests with different fates travel in one object, so a consumer
427    /// reads the scope of each channel rather than one verdict for the run.
428    #[test]
429    fn two_channels_keep_their_own_status_in_one_object() {
430        let mut requests = RequestOutcomes::new();
431        requests.insert(
432            RequestName::ChangedSince,
433            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
434        );
435        requests.insert(
436            RequestName::DiffFilter,
437            RequestOutcome::not_applied(
438                RequestName::DiffFilter,
439                "--diff-stdin",
440                "not-utf8",
441                "Ignored.",
442            ),
443        );
444        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
445        assert_eq!(value["changed-since"]["status"], "applied");
446        assert_eq!(value["diff-filter"]["status"], "not-applied");
447        assert_eq!(value["diff-filter"]["reason"], "not-utf8");
448    }
449
450    /// The class travels with the entry, so a consumer never has to keep a
451    /// name list to know whether an unapplied request widened the report.
452    #[test]
453    fn a_secondary_artifact_request_is_not_classed_as_scope() {
454        let mut requests = RequestOutcomes::new();
455        requests.insert(
456            RequestName::SarifFile,
457            RequestOutcome::not_applied(
458                RequestName::SarifFile,
459                "out.sarif",
460                "write-failed",
461                "Not written.",
462            ),
463        );
464        requests.insert(
465            RequestName::ChangedSince,
466            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
467        );
468        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
469        assert_eq!(value["sarif-file"]["affects"], "artifact");
470        assert_eq!(value["changed-since"]["affects"], "scope");
471    }
472
473    /// The class is derived from the name at construction, so an entry filed
474    /// under one name cannot carry another's class.
475    #[test]
476    fn every_name_carries_its_own_class() {
477        assert_eq!(RequestName::ChangedSince.affects(), RequestEffect::Scope);
478        assert_eq!(RequestName::DiffFilter.affects(), RequestEffect::Scope);
479        assert_eq!(RequestName::SarifFile.affects(), RequestEffect::Artifact);
480    }
481
482    /// An applied request that measured an empty scope is the case the member
483    /// exists for: `status` stays `applied`, because the filter DID apply, and
484    /// the zero is what tells a consumer the clean report covered nothing.
485    #[test]
486    fn an_empty_measured_scope_stays_applied_and_publishes_its_zero() {
487        let mut requests = RequestOutcomes::new();
488        requests.insert(
489            RequestName::DiffFilter,
490            RequestOutcome::applied_with_scope_size(
491                RequestName::DiffFilter,
492                "--diff-file pr.diff",
493                0,
494            ),
495        );
496        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
497        assert_eq!(
498            value,
499            serde_json::json!({
500                "diff-filter": {
501                    "status": "applied",
502                    "affects": "scope",
503                    "requested": "--diff-file pr.diff",
504                    "scope_size": 0
505                }
506            })
507        );
508    }
509
510    /// Absent is not zero. A request the run applied without counting what it
511    /// left carries no member, so a consumer cannot read "not measured" as "the
512    /// scope was empty".
513    #[test]
514    fn a_request_that_measured_nothing_carries_no_scope_size() {
515        let mut requests = RequestOutcomes::new();
516        requests.insert(
517            RequestName::ChangedSince,
518            RequestOutcome::applied(RequestName::ChangedSince, "origin/main"),
519        );
520        requests.insert(
521            RequestName::DiffFilter,
522            RequestOutcome::not_applied(
523                RequestName::DiffFilter,
524                "--diff-stdin",
525                "oversize",
526                "Ignored.",
527            ),
528        );
529        let value = serde_json::to_value(&requests).expect("request outcomes serialize");
530        assert!(
531            value["changed-since"].get("scope_size").is_none(),
532            "an unmeasured applied request carries no member: {value}"
533        );
534        assert!(
535            value["diff-filter"].get("scope_size").is_none(),
536            "a request that stood down narrowed nothing: {value}"
537        );
538    }
539
540    #[test]
541    fn insert_if_skips_a_request_the_run_never_received() {
542        let mut requests = RequestOutcomes::new();
543        requests.insert_if(RequestName::ChangedSince, None);
544        assert!(requests.into_option().is_none());
545    }
546}