Skip to main content

drep/analysis/
result.rs

1//! What one analysis pass produced.
2//!
3//! A single pass over a file can produce findings AND fail to fully analyze
4//! the file (a truncated response gives a partial list, an unknown severity
5//! in one record fails the file, a transport error produces zero findings but
6//! still surfaces as a failure). Reporting the findings while forgetting the
7//! failure is the exact bug this type exists to prevent — the gate would
8//! green-light a commit whenever the LLM endpoint was unreachable, which is
9//! worse than having no gate at all.
10//!
11//! `failed_files` is a [`BTreeMap`] rather than a `Vec` because two passes
12//! over the same file set must UNION, never sum. Summing counts one
13//! unreachable endpoint twice, drifting the failure count up without any
14//! matching file to investigate. The map's value carries the reason so the
15//! caller can render something a user can act on, not just a path.
16//!
17//! `dropped_out_of_range` counts rather than silently drops out-of-range
18//! findings so that a model which consistently reports wrong lines is
19//! observable to the caller — not invisible.
20
21use std::collections::BTreeMap;
22use std::fmt;
23use std::path::PathBuf;
24
25use crate::analysis::findings::Finding;
26use crate::llm::error::BackendErrorKind;
27
28/// Why one file went unanalyzed.
29///
30/// A bare set of paths cannot tell a dead endpoint from a rate limit from a
31/// truncated response, and the caller needs that to print something a user can
32/// act on. `LlmError` already carries the detail; it used to be discarded at
33/// the analyzer boundary.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum FailureReason {
36    /// The endpoint was unreachable, or returned a retryable status too many
37    /// times. `status` is the HTTP code when there was one.
38    Transport {
39        status: Option<u16>,
40        message: String,
41    },
42    /// A non-HTTP backend failed with a structured routing class.
43    Backend {
44        kind: BackendErrorKind,
45        message: String,
46    },
47    /// A response arrived and no JSON could be extracted from it.
48    Unparseable(String),
49    /// Cache-only review found no response for this exact prompt and provider.
50    CacheMiss,
51    /// A fresh semantic review was required after the configured remediation
52    /// budget had already been consumed. This is fail-closed: cached reviews
53    /// remain usable, but uncached code is never waved through unseen.
54    ReviewLimit { completed: u32, limit: u32 },
55    /// The model stopped before producing JSON, and the server said why.
56    ///
57    /// Distinct from [`Self::Unparseable`] because the cause is known and
58    /// deterministic - an output-token cap or a content filter - so the answer
59    /// is not "ask again" but "this request cannot be served as sent". `finish`
60    /// is the server's own word for it, kept as a machine tag beside the human
61    /// message exactly as [`Self::Transport`] keeps its status.
62    ModelStopped { finish: String, message: String },
63    /// The response parsed only after closing unbalanced delimiters, so it is
64    /// a prefix of what the model meant to say.
65    Truncated,
66    /// A record in the response could not be understood - unknown severity,
67    /// missing field, unusable line number.
68    MalformedFinding(String),
69    /// A deterministic tool that should have run could not.
70    ToolUnavailable { tool: String, detail: String },
71    /// Machine site policy refuses to have this repository's source reviewed by
72    /// a model, because a marker file is present at its root.
73    ///
74    /// A `FailureReason` rather than a run-level field because this is the type
75    /// the whole exit-2 contract already rests on: putting the refusal in
76    /// `failed_files` makes `gate`, the text failure block, the JSON `unanalyzed`
77    /// array and the clean-cycle reset guard treat it correctly with no second
78    /// mechanism to keep in agreement. A consumer asking "did semantic review
79    /// happen" is then told no, rather than handed an empty `unanalyzed` beside
80    /// exit 2.
81    ///
82    /// Both paths are carried because a developer meeting this for the first time
83    /// reads it as a broken install unless it names the file that caused it and
84    /// the policy that asked for it.
85    SitePolicyRefused { marker: PathBuf, policy: PathBuf },
86    /// The file on disk exceeded the read guard, so drep never read it.
87    ///
88    /// Distinct from [`Self::PayloadTooLarge`] because the two measure
89    /// different things: this is the file's own size, checked before any I/O,
90    /// and that one is the size of the text the model would have been sent.
91    /// They were one variant sharing one limit, which meant `bytes` held the
92    /// file size on one code path and the rendered-payload size on another -
93    /// so "file is too large (330102 bytes)" could name a file that `ls`
94    /// reports as 261900 bytes.
95    FileTooLarge { bytes: u64, limit: u64 },
96    /// The rendered LLM payload exceeded the ceiling. See [`Self::FileTooLarge`].
97    PayloadTooLarge { bytes: u64, limit: u64 },
98    /// The file could not be read from disk.
99    Unreadable(String),
100    /// The user named a file that the running command has no analyzer for.
101    ///
102    /// Only ever produced for an **explicitly named** path. A walk that turns
103    /// up nothing analyzable is legitimately empty - `drep check .` in a
104    /// documentation repository has correctly found no code. A path the user
105    /// typed is different: reporting "No issues found." for a file drep
106    /// declined to look at is the single failure this codebase is built to
107    /// prevent, and it is the same distinction `resolve_paths` already draws
108    /// for an argument that does not exist at all.
109    ///
110    /// `hint` names the command that *does* handle the type, when there is
111    /// one. Markdown has `drep lint-docs`, so the error is a redirection
112    /// rather than a dead end.
113    Unsupported {
114        /// The extension as written, with its dot. `None` when the file has
115        /// none, which reads differently in the message.
116        extension: Option<String>,
117        /// What to run instead, phrased as an imperative.
118        hint: Option<String>,
119    },
120    /// A failover chain produced no answer, with what each provider
121    /// contributed.
122    ///
123    /// Only produced for a chain of **two or more** providers. A one-provider
124    /// config - what `drep init` writes, and what almost every run uses -
125    /// collapses to that provider's own reason, so it reports exactly what it
126    /// did before failover existed, JSON `kind` included. The trigger is the
127    /// chain's length, not the number of providers that failed: a two-provider
128    /// chain stopped dead at the head by a 401 has one failure and is exactly
129    /// the case where "which provider, and why did my fallback not run" is the
130    /// user's live question.
131    ///
132    /// Keeping only the last reason would hide a dead local endpoint behind
133    /// the cloud fallback's 401; keeping only the first would hide the broken
134    /// fallback. A user fixing the run needs both.
135    ///
136    /// The list can be shorter than the chain - a 401 at the head stops it, and
137    /// the providers below were never consulted.
138    ChainFailed(Vec<ProviderFailure>),
139}
140
141/// One provider's contribution to a file that no provider could analyze.
142///
143/// `reason` is always a non-chain LLM-layer variant. That is a property of the
144/// only thing that builds these: the conversion runs over one provider's
145/// `LlmError`, so a nested `ChainFailed` is not merely absent but unreachable.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct ProviderFailure {
148    /// Zero-based position in the chain. Rendered one-based, matching how
149    /// `doctor` numbers the same list.
150    pub provider: usize,
151    /// The model that provider asks for.
152    pub model: String,
153    /// Why it did not produce an answer.
154    pub reason: FailureReason,
155    /// True when the provider was already demoted and was not contacted for
156    /// this file. Worth reporting: a user needs to know the local endpoint has
157    /// been dead since the third file, not just that the fallback then failed.
158    pub skipped: bool,
159}
160
161impl FailureReason {
162    /// Build an [`Self::Unsupported`] for `path`.
163    ///
164    /// The extension convention (leading dot, `None` when there is none) is
165    /// stated here, beside the variant whose `one_line` renders it, rather than
166    /// at each command that raises one. It was written out twice, which is one
167    /// copy per command pointing at the other.
168    pub fn unsupported(path: &std::path::Path, hint: Option<String>) -> Self {
169        FailureReason::Unsupported {
170            extension: path
171                .extension()
172                .map(|ext| format!(".{}", ext.to_string_lossy())),
173            hint,
174        }
175    }
176
177    /// A single line suitable for a terminal, derived from the variant.
178    ///
179    /// The HTTP status is rendered next to the message so a 429 is visible
180    /// without the user having to match the message against a status code
181    /// list. This is the load-bearing reason the `Transport` variant carries
182    /// the status as a number rather than only inside the string.
183    pub fn one_line(&self) -> String {
184        match self {
185            FailureReason::Transport {
186                status: Some(code),
187                message,
188            } => {
189                format!("LLM transport failed (HTTP {code}): {message}")
190            }
191            FailureReason::Transport {
192                status: None,
193                message,
194            } => {
195                format!("LLM transport failed: {message}")
196            }
197            FailureReason::Unparseable(message) => {
198                format!("LLM response was unparseable: {message}")
199            }
200            FailureReason::CacheMiss => {
201                "LLM review is not cached; run a normal check to warm it".to_owned()
202            }
203            FailureReason::ReviewLimit { completed, limit } if completed < limit => format!(
204                "fresh LLM review capacity is currently reserved ({completed} completed of \
205                 {limit}); wait for the in-flight review, pass `--max-review-rounds N`, or pass \
206                 `--unlimited-reviews` to authorize another round"
207            ),
208            FailureReason::ReviewLimit { completed, limit } => format!(
209                "fresh LLM review limit reached ({completed} of {limit}); raise \
210                 `max_review_rounds`, pass `--max-review-rounds N`, or pass \
211                 `--unlimited-reviews` to authorize another round"
212            ),
213            FailureReason::Backend { kind, message } => {
214                format!("LLM backend {kind}: {message}")
215            }
216            // Deliberately says nothing about *which* command is running: both
217            // `check` and `lint-docs` produce this, pointing at each other.
218            FailureReason::Unsupported { extension, hint } => {
219                let what = match extension {
220                    Some(ext) => format!("`{ext}` files"),
221                    None => "files with no extension".to_owned(),
222                };
223                match hint {
224                    Some(hint) => format!("no analyzer for {what}: {hint}"),
225                    None => format!("no analyzer for {what}"),
226                }
227            }
228            // The message is already a sentence a user can act on; prefixing it
229            // with a category would bury the actionable half.
230            FailureReason::ModelStopped { message, .. } => message.clone(),
231            FailureReason::Truncated => "response was truncated".to_owned(),
232            FailureReason::MalformedFinding(detail) => format!("malformed finding: {detail}"),
233            FailureReason::ToolUnavailable { tool, detail } => {
234                format!("{tool} could not run: {detail}")
235            }
236            FailureReason::SitePolicyRefused { marker, policy } => format!(
237                "semantic review is refused by site policy: {} is present (policy: {})",
238                marker.display(),
239                policy.display()
240            ),
241            FailureReason::FileTooLarge { bytes, limit } => {
242                format!("file is too large to read ({bytes} bytes; limit is {limit})")
243            }
244            FailureReason::PayloadTooLarge { bytes, limit } => {
245                format!("the code sent for review is too large ({bytes} bytes; limit is {limit})")
246            }
247            FailureReason::Unreadable(detail) => format!("file could not be read: {detail}"),
248            FailureReason::ChainFailed(failures) => {
249                let each: Vec<String> = failures.iter().map(ProviderFailure::one_line).collect();
250                // Phrased by what happened, not by a count. "All N providers
251                // failed" is wrong for the case that matters most - a chain
252                // stopped at the head by a 401 has one entry and more
253                // providers behind it that were deliberately not asked.
254                if each.is_empty() {
255                    "no LLM provider analyzed this file".to_owned()
256                } else {
257                    format!("no LLM provider analyzed this file: {}", each.join("; "))
258                }
259            }
260        }
261    }
262
263    /// The HTTP status, when the failure had one.
264    ///
265    /// Only `Transport` ever carries one. Exposed as a number rather than
266    /// left inside the message because a caller has to distinguish a 429 from
267    /// a 401 - the message is prose and prose gets reworded.
268    pub fn status(&self) -> Option<u16> {
269        match self {
270            FailureReason::Transport { status, .. } => *status,
271            // Deliberately not "the first attempt's status". A chain failure
272            // has one status *per provider*, and flattening them to one number
273            // would tell a consumer a 401 was the whole story when a 500 came
274            // first. The JSON renderer exposes the per-provider list instead.
275            _ => None,
276        }
277    }
278}
279
280impl ProviderFailure {
281    /// One line naming the provider, its model, and what it said.
282    pub fn one_line(&self) -> String {
283        let skipped = if self.skipped {
284            " (already down earlier in this run)"
285        } else {
286            ""
287        };
288        format!(
289            "[{}] {}: {}{}",
290            self.provider + 1,
291            self.model,
292            self.reason.one_line(),
293            skipped
294        )
295    }
296}
297
298impl fmt::Display for FailureReason {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        f.pad(&self.one_line())
301    }
302}
303
304/// What one analysis pass produced.
305///
306/// `findings` and `failed_files` are independent axes: a file can contribute
307/// findings AND be unanalyzed (a truncated response gives a partial list).
308/// Reporting the findings while forgetting the failure is the exact bug this
309/// type exists to prevent.
310#[derive(Debug, Default, Clone, PartialEq, Eq)]
311pub struct AnalysisResult {
312    /// Findings the analyzer could attribute to a real line of code.
313    pub findings: Vec<Finding>,
314    /// Files that could not be fully analyzed, with the reason. A `BTreeMap`
315    /// because two passes over the same file set must UNION, never sum —
316    /// summing counts one unreachable endpoint twice.
317    pub failed_files: BTreeMap<PathBuf, FailureReason>,
318    /// Findings discarded because their line was not in the payload's
319    /// `valid_lines`. Counted rather than silently dropped, so the drop is
320    /// observable.
321    pub dropped_out_of_range: usize,
322}
323
324/// Fold `src` into `dst`, keeping the reason already present on a collision.
325///
326/// The one statement of the failure-union rule. It was written out longhand as
327/// `entry().or_insert()` at four sites - `merge` here plus three in the CLI -
328/// each with its own comment re-explaining it. The two analysis layers cover
329/// the same files, so the sets union rather than sum: one unreachable endpoint
330/// is one failure, not two. First-wins because the reasons cannot be
331/// meaningfully combined and the earlier layer saw the file first.
332pub fn union_failures(
333    dst: &mut BTreeMap<PathBuf, FailureReason>,
334    src: BTreeMap<PathBuf, FailureReason>,
335) {
336    for (path, reason) in src {
337        dst.entry(path).or_insert(reason);
338    }
339}
340
341impl AnalysisResult {
342    /// One file, one failure, no findings.
343    ///
344    /// The shape was hand-assembled at four call sites - `default()`, insert,
345    /// return - each of which independently had to know that `findings` and
346    /// `dropped_out_of_range` stay at their defaults. Forgetting the insert at
347    /// any one of them reports an unanalyzed file as clean, which is the single
348    /// failure this whole type exists to prevent, so it gets a constructor.
349    pub fn failed(path: PathBuf, reason: FailureReason) -> Self {
350        let mut result = Self::default();
351        result.failed_files.insert(path, reason);
352        result
353    }
354
355    /// Fold `other` into `self`: findings concatenate, `failed_files`
356    /// unions, `dropped_out_of_range` sums.
357    ///
358    /// The merge semantics let a caller combine per-file and per-layer results
359    /// without losing the failure signal.
360    ///
361    /// On a key collision in `failed_files`, the **first** reason wins. A
362    /// file failing twice is still one failure, and the two reasons are not
363    /// meaningfully combinable - the first one is at least specific to the
364    /// file, while a hypothetical last-wins policy would let a later
365    /// analyzer overwrite a more informative first reason with a generic
366    /// one.
367    pub fn merge(&mut self, other: AnalysisResult) {
368        self.findings.extend(other.findings);
369        // `union_failures` rather than the loop written out again: the
370        // first-writer-wins rule is one decision, and two copies of it are two
371        // places for it to change independently.
372        union_failures(&mut self.failed_files, other.failed_files);
373        self.dropped_out_of_range = self
374            .dropped_out_of_range
375            .saturating_add(other.dropped_out_of_range);
376    }
377
378    /// True when any file went unanalyzed.
379    ///
380    /// The caller maps this to process exit 2: "could not analyze" is
381    /// distinct from both "clean" (exit 0) and "found issues" (exit 1),
382    /// because a gate that cannot distinguish them rubber-stamps the day
383    /// the LLM endpoint goes down.
384    pub fn has_failures(&self) -> bool {
385        !self.failed_files.is_empty()
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    /// `merge` keeps the first reason on a key collision - the documented
394    /// first-writer-wins rule. A last-wins policy would silently overwrite
395    /// the more informative first reason with a generic later one.
396    #[test]
397    fn merge_keeps_first_reason_on_key_collision() {
398        let mut a = AnalysisResult::default();
399        a.failed_files.insert(
400            PathBuf::from("src/lib.rs"),
401            FailureReason::Transport {
402                status: Some(429),
403                message: "rate limited".to_owned(),
404            },
405        );
406
407        let mut b = AnalysisResult::default();
408        b.failed_files.insert(
409            PathBuf::from("src/lib.rs"),
410            FailureReason::Transport {
411                status: Some(500),
412                message: "internal".to_owned(),
413            },
414        );
415
416        a.merge(b);
417
418        assert_eq!(a.failed_files.len(), 1);
419        let reason = a.failed_files.get(&PathBuf::from("src/lib.rs")).unwrap();
420        assert_eq!(
421            reason,
422            &FailureReason::Transport {
423                status: Some(429),
424                message: "rate limited".to_owned(),
425            },
426            "first reason wins on collision"
427        );
428    }
429
430    /// A `Transport` failure with a status surfaces the code in the rendered
431    /// line. The whole point of keeping the status as a number is that it
432    /// reaches the user; this pins that the rendering preserves it.
433    #[test]
434    fn transport_render_includes_the_http_status() {
435        let reason = FailureReason::Transport {
436            status: Some(429),
437            message: "rate limited".to_owned(),
438        };
439        let rendered = reason.one_line();
440        assert!(
441            rendered.contains("429"),
442            "rendered line must contain 429, got {rendered:?}"
443        );
444    }
445
446    /// A refusal names both the marker and the policy that asked for it.
447    ///
448    /// Pinned at the type that owns the wording, beside the `Transport`-status
449    /// test, and for the same reason: the paths are carried as fields precisely so
450    /// they reach the user. A developer meeting this line for the first time reads
451    /// it as a broken install unless it says which file caused it and where the
452    /// decision came from.
453    #[test]
454    fn site_policy_refusal_names_the_marker_and_the_policy_file() {
455        let reason = FailureReason::SitePolicyRefused {
456            marker: PathBuf::from("/work/repo/.drep-no-llm"),
457            policy: PathBuf::from("/etc/drep/site.toml"),
458        };
459        let rendered = reason.one_line();
460        assert!(
461            rendered.contains("/work/repo/.drep-no-llm"),
462            "must name the marker, got {rendered:?}"
463        );
464        assert!(
465            rendered.contains("/etc/drep/site.toml"),
466            "must name the policy, got {rendered:?}"
467        );
468    }
469
470    #[test]
471    fn display_honours_formatter_width_and_alignment() {
472        let reason = FailureReason::Truncated;
473        assert_eq!(
474            format!("{reason:>30}"),
475            format!("{:>30}", reason.one_line())
476        );
477    }
478}