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 /// The file on disk exceeded the read guard, so drep never read it.
72 ///
73 /// Distinct from [`Self::PayloadTooLarge`] because the two measure
74 /// different things: this is the file's own size, checked before any I/O,
75 /// and that one is the size of the text the model would have been sent.
76 /// They were one variant sharing one limit, which meant `bytes` held the
77 /// file size on one code path and the rendered-payload size on another -
78 /// so "file is too large (330102 bytes)" could name a file that `ls`
79 /// reports as 261900 bytes.
80 FileTooLarge { bytes: u64, limit: u64 },
81 /// The rendered LLM payload exceeded the ceiling. See [`Self::FileTooLarge`].
82 PayloadTooLarge { bytes: u64, limit: u64 },
83 /// The file could not be read from disk.
84 Unreadable(String),
85 /// The user named a file that the running command has no analyzer for.
86 ///
87 /// Only ever produced for an **explicitly named** path. A walk that turns
88 /// up nothing analyzable is legitimately empty - `drep check .` in a
89 /// documentation repository has correctly found no code. A path the user
90 /// typed is different: reporting "No issues found." for a file drep
91 /// declined to look at is the single failure this codebase is built to
92 /// prevent, and it is the same distinction `resolve_paths` already draws
93 /// for an argument that does not exist at all.
94 ///
95 /// `hint` names the command that *does* handle the type, when there is
96 /// one. Markdown has `drep lint-docs`, so the error is a redirection
97 /// rather than a dead end.
98 Unsupported {
99 /// The extension as written, with its dot. `None` when the file has
100 /// none, which reads differently in the message.
101 extension: Option<String>,
102 /// What to run instead, phrased as an imperative.
103 hint: Option<String>,
104 },
105 /// A failover chain produced no answer, with what each provider
106 /// contributed.
107 ///
108 /// Only produced for a chain of **two or more** providers. A one-provider
109 /// config - what `drep init` writes, and what almost every run uses -
110 /// collapses to that provider's own reason, so it reports exactly what it
111 /// did before failover existed, JSON `kind` included. The trigger is the
112 /// chain's length, not the number of providers that failed: a two-provider
113 /// chain stopped dead at the head by a 401 has one failure and is exactly
114 /// the case where "which provider, and why did my fallback not run" is the
115 /// user's live question.
116 ///
117 /// Keeping only the last reason would hide a dead local endpoint behind
118 /// the cloud fallback's 401; keeping only the first would hide the broken
119 /// fallback. A user fixing the run needs both.
120 ///
121 /// The list can be shorter than the chain - a 401 at the head stops it, and
122 /// the providers below were never consulted.
123 ChainFailed(Vec<ProviderFailure>),
124}
125
126/// One provider's contribution to a file that no provider could analyze.
127///
128/// `reason` is always a non-chain LLM-layer variant. That is a property of the
129/// only thing that builds these: the conversion runs over one provider's
130/// `LlmError`, so a nested `ChainFailed` is not merely absent but unreachable.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct ProviderFailure {
133 /// Zero-based position in the chain. Rendered one-based, matching how
134 /// `doctor` numbers the same list.
135 pub provider: usize,
136 /// The model that provider asks for.
137 pub model: String,
138 /// Why it did not produce an answer.
139 pub reason: FailureReason,
140 /// True when the provider was already demoted and was not contacted for
141 /// this file. Worth reporting: a user needs to know the local endpoint has
142 /// been dead since the third file, not just that the fallback then failed.
143 pub skipped: bool,
144}
145
146impl FailureReason {
147 /// Build an [`Self::Unsupported`] for `path`.
148 ///
149 /// The extension convention (leading dot, `None` when there is none) is
150 /// stated here, beside the variant whose `one_line` renders it, rather than
151 /// at each command that raises one. It was written out twice, which is one
152 /// copy per command pointing at the other.
153 pub fn unsupported(path: &std::path::Path, hint: Option<String>) -> Self {
154 FailureReason::Unsupported {
155 extension: path
156 .extension()
157 .map(|ext| format!(".{}", ext.to_string_lossy())),
158 hint,
159 }
160 }
161
162 /// A single line suitable for a terminal, derived from the variant.
163 ///
164 /// The HTTP status is rendered next to the message so a 429 is visible
165 /// without the user having to match the message against a status code
166 /// list. This is the load-bearing reason the `Transport` variant carries
167 /// the status as a number rather than only inside the string.
168 pub fn one_line(&self) -> String {
169 match self {
170 FailureReason::Transport {
171 status: Some(code),
172 message,
173 } => {
174 format!("LLM transport failed (HTTP {code}): {message}")
175 }
176 FailureReason::Transport {
177 status: None,
178 message,
179 } => {
180 format!("LLM transport failed: {message}")
181 }
182 FailureReason::Unparseable(message) => {
183 format!("LLM response was unparseable: {message}")
184 }
185 FailureReason::CacheMiss => {
186 "LLM review is not cached; run a normal check to warm it".to_owned()
187 }
188 FailureReason::ReviewLimit { completed, limit } if completed < limit => format!(
189 "fresh LLM review capacity is currently reserved ({completed} completed of \
190 {limit}); wait for the in-flight review, pass `--max-review-rounds N`, or pass \
191 `--unlimited-reviews` to authorize another round"
192 ),
193 FailureReason::ReviewLimit { completed, limit } => format!(
194 "fresh LLM review limit reached ({completed} of {limit}); raise \
195 `max_review_rounds`, pass `--max-review-rounds N`, or pass \
196 `--unlimited-reviews` to authorize another round"
197 ),
198 FailureReason::Backend { kind, message } => {
199 format!("LLM backend {kind}: {message}")
200 }
201 // Deliberately says nothing about *which* command is running: both
202 // `check` and `lint-docs` produce this, pointing at each other.
203 FailureReason::Unsupported { extension, hint } => {
204 let what = match extension {
205 Some(ext) => format!("`{ext}` files"),
206 None => "files with no extension".to_owned(),
207 };
208 match hint {
209 Some(hint) => format!("no analyzer for {what}: {hint}"),
210 None => format!("no analyzer for {what}"),
211 }
212 }
213 // The message is already a sentence a user can act on; prefixing it
214 // with a category would bury the actionable half.
215 FailureReason::ModelStopped { message, .. } => message.clone(),
216 FailureReason::Truncated => "response was truncated".to_owned(),
217 FailureReason::MalformedFinding(detail) => format!("malformed finding: {detail}"),
218 FailureReason::ToolUnavailable { tool, detail } => {
219 format!("{tool} could not run: {detail}")
220 }
221 FailureReason::FileTooLarge { bytes, limit } => {
222 format!("file is too large to read ({bytes} bytes; limit is {limit})")
223 }
224 FailureReason::PayloadTooLarge { bytes, limit } => {
225 format!("the code sent for review is too large ({bytes} bytes; limit is {limit})")
226 }
227 FailureReason::Unreadable(detail) => format!("file could not be read: {detail}"),
228 FailureReason::ChainFailed(failures) => {
229 let each: Vec<String> = failures.iter().map(ProviderFailure::one_line).collect();
230 // Phrased by what happened, not by a count. "All N providers
231 // failed" is wrong for the case that matters most - a chain
232 // stopped at the head by a 401 has one entry and more
233 // providers behind it that were deliberately not asked.
234 if each.is_empty() {
235 "no LLM provider analyzed this file".to_owned()
236 } else {
237 format!("no LLM provider analyzed this file: {}", each.join("; "))
238 }
239 }
240 }
241 }
242
243 /// The HTTP status, when the failure had one.
244 ///
245 /// Only `Transport` ever carries one. Exposed as a number rather than
246 /// left inside the message because a caller has to distinguish a 429 from
247 /// a 401 - the message is prose and prose gets reworded.
248 pub fn status(&self) -> Option<u16> {
249 match self {
250 FailureReason::Transport { status, .. } => *status,
251 // Deliberately not "the first attempt's status". A chain failure
252 // has one status *per provider*, and flattening them to one number
253 // would tell a consumer a 401 was the whole story when a 500 came
254 // first. The JSON renderer exposes the per-provider list instead.
255 _ => None,
256 }
257 }
258}
259
260impl ProviderFailure {
261 /// One line naming the provider, its model, and what it said.
262 pub fn one_line(&self) -> String {
263 let skipped = if self.skipped {
264 " (already down earlier in this run)"
265 } else {
266 ""
267 };
268 format!(
269 "[{}] {}: {}{}",
270 self.provider + 1,
271 self.model,
272 self.reason.one_line(),
273 skipped
274 )
275 }
276}
277
278impl fmt::Display for FailureReason {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.pad(&self.one_line())
281 }
282}
283
284/// What one analysis pass produced.
285///
286/// `findings` and `failed_files` are independent axes: a file can contribute
287/// findings AND be unanalyzed (a truncated response gives a partial list).
288/// Reporting the findings while forgetting the failure is the exact bug this
289/// type exists to prevent.
290#[derive(Debug, Default, Clone, PartialEq, Eq)]
291pub struct AnalysisResult {
292 /// Findings the analyzer could attribute to a real line of code.
293 pub findings: Vec<Finding>,
294 /// Files that could not be fully analyzed, with the reason. A `BTreeMap`
295 /// because two passes over the same file set must UNION, never sum —
296 /// summing counts one unreachable endpoint twice.
297 pub failed_files: BTreeMap<PathBuf, FailureReason>,
298 /// Findings discarded because their line was not in the payload's
299 /// `valid_lines`. Counted rather than silently dropped, so the drop is
300 /// observable.
301 pub dropped_out_of_range: usize,
302}
303
304/// Fold `src` into `dst`, keeping the reason already present on a collision.
305///
306/// The one statement of the failure-union rule. It was written out longhand as
307/// `entry().or_insert()` at four sites - `merge` here plus three in the CLI -
308/// each with its own comment re-explaining it. The two analysis layers cover
309/// the same files, so the sets union rather than sum: one unreachable endpoint
310/// is one failure, not two. First-wins because the reasons cannot be
311/// meaningfully combined and the earlier layer saw the file first.
312pub fn union_failures(
313 dst: &mut BTreeMap<PathBuf, FailureReason>,
314 src: BTreeMap<PathBuf, FailureReason>,
315) {
316 for (path, reason) in src {
317 dst.entry(path).or_insert(reason);
318 }
319}
320
321impl AnalysisResult {
322 /// One file, one failure, no findings.
323 ///
324 /// The shape was hand-assembled at four call sites - `default()`, insert,
325 /// return - each of which independently had to know that `findings` and
326 /// `dropped_out_of_range` stay at their defaults. Forgetting the insert at
327 /// any one of them reports an unanalyzed file as clean, which is the single
328 /// failure this whole type exists to prevent, so it gets a constructor.
329 pub fn failed(path: PathBuf, reason: FailureReason) -> Self {
330 let mut result = Self::default();
331 result.failed_files.insert(path, reason);
332 result
333 }
334
335 /// Fold `other` into `self`: findings concatenate, `failed_files`
336 /// unions, `dropped_out_of_range` sums.
337 ///
338 /// The merge semantics let a caller combine per-file and per-layer results
339 /// without losing the failure signal.
340 ///
341 /// On a key collision in `failed_files`, the **first** reason wins. A
342 /// file failing twice is still one failure, and the two reasons are not
343 /// meaningfully combinable - the first one is at least specific to the
344 /// file, while a hypothetical last-wins policy would let a later
345 /// analyzer overwrite a more informative first reason with a generic
346 /// one.
347 pub fn merge(&mut self, other: AnalysisResult) {
348 self.findings.extend(other.findings);
349 // `union_failures` rather than the loop written out again: the
350 // first-writer-wins rule is one decision, and two copies of it are two
351 // places for it to change independently.
352 union_failures(&mut self.failed_files, other.failed_files);
353 self.dropped_out_of_range = self
354 .dropped_out_of_range
355 .saturating_add(other.dropped_out_of_range);
356 }
357
358 /// True when any file went unanalyzed.
359 ///
360 /// The caller maps this to process exit 2: "could not analyze" is
361 /// distinct from both "clean" (exit 0) and "found issues" (exit 1),
362 /// because a gate that cannot distinguish them rubber-stamps the day
363 /// the LLM endpoint goes down.
364 pub fn has_failures(&self) -> bool {
365 !self.failed_files.is_empty()
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 /// `merge` keeps the first reason on a key collision - the documented
374 /// first-writer-wins rule. A last-wins policy would silently overwrite
375 /// the more informative first reason with a generic later one.
376 #[test]
377 fn merge_keeps_first_reason_on_key_collision() {
378 let mut a = AnalysisResult::default();
379 a.failed_files.insert(
380 PathBuf::from("src/lib.rs"),
381 FailureReason::Transport {
382 status: Some(429),
383 message: "rate limited".to_owned(),
384 },
385 );
386
387 let mut b = AnalysisResult::default();
388 b.failed_files.insert(
389 PathBuf::from("src/lib.rs"),
390 FailureReason::Transport {
391 status: Some(500),
392 message: "internal".to_owned(),
393 },
394 );
395
396 a.merge(b);
397
398 assert_eq!(a.failed_files.len(), 1);
399 let reason = a.failed_files.get(&PathBuf::from("src/lib.rs")).unwrap();
400 assert_eq!(
401 reason,
402 &FailureReason::Transport {
403 status: Some(429),
404 message: "rate limited".to_owned(),
405 },
406 "first reason wins on collision"
407 );
408 }
409
410 /// A `Transport` failure with a status surfaces the code in the rendered
411 /// line. The whole point of keeping the status as a number is that it
412 /// reaches the user; this pins that the rendering preserves it.
413 #[test]
414 fn transport_render_includes_the_http_status() {
415 let reason = FailureReason::Transport {
416 status: Some(429),
417 message: "rate limited".to_owned(),
418 };
419 let rendered = reason.one_line();
420 assert!(
421 rendered.contains("429"),
422 "rendered line must contain 429, got {rendered:?}"
423 );
424 }
425
426 #[test]
427 fn display_honours_formatter_width_and_alignment() {
428 let reason = FailureReason::Truncated;
429 assert_eq!(
430 format!("{reason:>30}"),
431 format!("{:>30}", reason.one_line())
432 );
433 }
434}