Skip to main content

drep/analysis/
code_quality.rs

1//! The code-quality analyzer: render a payload, ask the LLM, turn the
2//! response into findings — and never report an unanalyzed file as clean.
3//!
4//! The analyzer enforces these contracts:
5//!
6//! 1. No language, no analysis. drep has no opinion on a file type it does
7//!    not claim, and silently returning an empty result is the correct
8//!    behavior — *not* a failure. The CLI surfaces "no language" by simply
9//!    not including the file in the work set.
10//! 2. Empty hunks → empty result, no LLM call.
11//! 3. Build the payload with `payload::render`. `None` → empty result.
12//! 4. Cache first. A hit is parsed exactly as a `Complete` response would
13//!    be, and the duplicate is silent — the caller's view is identical. The
14//!    explicitly live pass after cache-only preflight bypasses cache, because
15//!    only a fresh provider response may consume a remediation round.
16//! 5. Concurrency. A limiter slot is acquired before the LLM call and held
17//!    for the duration. A cache hit must not acquire a slot: the slot
18//!    represents in-flight HTTP work, and a cache read is not in-flight.
19//! 6. `Ok(Extracted::Complete)` → parse, store in the cache.
20//! 7. `Ok(Extracted::Truncated)` → parse the partial result AND mark the
21//!    file failed. Never cache a truncated response — caching it makes one
22//!    truncation permanent for the whole TTL, and this layer does not know
23//!    about `--fail-on` (a caller deciding otherwise would make
24//!    `failed_files` depend on a CLI flag, which is the wrong layering).
25//! 8. `Err(LlmError::*)` → no findings, file in `failed_files` with the
26//!    specific LLM layer that failed.
27//!
28//! The five rules around out-of-range lines, missing fields, unknown
29//! severities, and `issues` itself being absent are at the boundary between
30//! "model misreported" and "we could not understand the response". The first
31//! is a *finding* we drop; the others are *file-level failures*, because a
32//! file we did not fully understand must never be reported clean.
33
34use std::path::Path;
35
36use futures::future::join_all;
37use serde_json::Value;
38
39use crate::analysis::findings::{Finding, LlmSeverity};
40use crate::analysis::payload;
41use crate::analysis::prompt::build_analysis_prompt;
42use crate::analysis::response_contract::{
43    CATEGORY, COMPILE_FAILURE, ISSUES, LINE, MESSAGE, SEVERITY, SUGGESTION,
44};
45use crate::analysis::result::{AnalysisResult, FailureReason, ProviderFailure};
46use crate::diff::hunks::Hunk;
47use crate::diff::hunks::group_by_file;
48use crate::languages;
49use crate::llm::cache::Cache;
50use crate::llm::chain::{ChainError, ProviderChain};
51use crate::llm::error::LlmError;
52use crate::llm::json_parsing::Extracted;
53
54/// The code-quality analyzer.
55///
56/// Built once per process. The `chain` and the `cache` are both passed in
57/// rather than constructed here: they are process-wide resources. The chain in
58/// particular carries the concurrency limiter for each provider *and* the
59/// record of which providers have been demoted, so a second chain would both
60/// double the in-flight requests against one endpoint and re-discover a dead
61/// provider the first one already knew about.
62///
63/// The model and temperature are **not** duplicated onto this struct. They
64/// belong to the provider that ends up answering, which is not known until the
65/// chain has run, and a second copy is exactly what lets a request go to one
66/// model while the cache key names another.
67pub struct CodeQualityAnalyzer {
68    pub(crate) chain: ProviderChain,
69    pub(crate) cache: Cache,
70    cache_only: bool,
71}
72
73#[derive(Clone, Copy)]
74enum CacheMode {
75    Prefer,
76    Only,
77    Bypass,
78}
79
80impl CodeQualityAnalyzer {
81    /// Build from a provider chain and a shared cache.
82    ///
83    /// Infallible: `ProviderChain::new` has already rejected an empty or
84    /// misconfigured chain, so there is nothing left for this to validate.
85    /// `cache` is a parameter rather than constructed here so the key stays
86    /// independent of the `Cache` root (see [`Cache::key`]) and a test can
87    /// point it at a `TempDir`.
88    pub fn new(chain: ProviderChain, cache: Cache) -> Self {
89        Self {
90            chain,
91            cache,
92            cache_only: false,
93        }
94    }
95
96    /// Select a cache-only pass. The analyzer keeps parsing cached responses
97    /// through the normal schema path; only the backend request is forbidden.
98    pub fn with_cache_only(mut self, cache_only: bool) -> Self {
99        self.cache_only = cache_only;
100        self
101    }
102
103    /// The provider chain, for a caller reporting which providers served.
104    pub fn chain(&self) -> &ProviderChain {
105        &self.chain
106    }
107
108    /// Analyze one file's hunks.
109    ///
110    /// Returns an [`AnalysisResult`] populated with whatever the file
111    /// produced: findings, a failure marker, or both. The result is never a
112    /// bare `Vec<Finding>`; the failure axis is part of the return type so
113    /// the caller cannot forget it.
114    pub async fn analyze_file(&self, hunks: &[Hunk]) -> AnalysisResult {
115        self.analyze_files_in_mode(std::iter::once(hunks), self.configured_cache_mode())
116            .await
117    }
118
119    async fn analyze_file_in_mode(&self, hunks: &[Hunk], cache_mode: CacheMode) -> AnalysisResult {
120        // Rule 1: no language, no analysis. `languages::detect` on the
121        // first hunk's file path is enough because every hunk in `by_file`
122        // shares a path (the diff module groups by file).
123        let Some(first) = hunks.first() else {
124            return AnalysisResult::default();
125        };
126        let Some(language) = languages::detect(&first.file_path) else {
127            return AnalysisResult::default();
128        };
129
130        // Rule 3: payload. `render` returns `None` only for an empty slice,
131        // which the `hunks.first()` guard above has already excluded - rule 2
132        // and rule 3 are the same check, so a second `hunks.is_empty()` here
133        // would be unreachable rather than defensive.
134        let Some(payload) = payload::render(language, hunks) else {
135            return AnalysisResult::default();
136        };
137
138        // The size ceiling is enforced on the *rendered payload*, so it holds
139        // for every input mode. Checking the file size during paths-mode input
140        // resolution - as this used to, and still does as a pre-filter - left
141        // `--staged` and `--diff` unguarded, which are the two modes a commit
142        // gate actually runs in: a newly-added 5 MB file reached the model
143        // whole. Too large is a *failure*, not a skip; a file drep declined to
144        // analyze is not clean.
145        let rendered = u64::try_from(payload.text.len()).unwrap_or(u64::MAX);
146        if rendered > payload::PAYLOAD_MAX_BYTES {
147            return AnalysisResult::failed(
148                first.file_path.clone(),
149                FailureReason::PayloadTooLarge {
150                    bytes: rendered,
151                    limit: payload::PAYLOAD_MAX_BYTES,
152                },
153            );
154        }
155
156        let system_prompt = build_analysis_prompt(language);
157
158        // Rules 4, 5 and the failover loop all live in the chain: the cache is
159        // consulted per provider (a hit costs no concurrency slot, because the
160        // slot represents in-flight HTTP work), and the key comes back naming
161        // whoever answered. Computing a key here would be computing it for a
162        // provider that may not be the one that serves the file.
163        let served = match cache_mode {
164            CacheMode::Only => {
165                match self
166                    .chain
167                    .cached_json(&system_prompt, &payload.text, &self.cache)
168                {
169                    Some(served) => Ok(served),
170                    None => {
171                        return AnalysisResult::failed(
172                            first.file_path.clone(),
173                            FailureReason::CacheMiss,
174                        );
175                    }
176                }
177            }
178            CacheMode::Prefer => {
179                self.chain
180                    .complete_json(&system_prompt, &payload.text, &self.cache)
181                    .await
182            }
183            CacheMode::Bypass => {
184                self.chain
185                    .complete_json_fresh(&system_prompt, &payload.text, &self.cache)
186                    .await
187            }
188        };
189
190        match served {
191            // Rule 6: complete → parse, store in the cache.
192            // Rules 6 and 7 in one arm. Both never-cache rules live in the
193            // `if let` below rather than being split across two arms, where
194            // the `Complete` arm's guard could only ever be true.
195            Ok(served) => {
196                let result = parse_response(&payload, &first.file_path, &served.extracted);
197                // Cache only a `Complete` response we fully understood. A
198                // truncated one is a prefix, and a body can be valid JSON and
199                // still schema-invalid - a missing `issues` array, a record
200                // with an unknown severity - which yields a file-level
201                // failure. Caching either replays it for the whole TTL
202                // instead of letting the next run ask again.
203                //
204                // `served.key`, never a key computed here: the entry must be
205                // filed under the model that produced it, or a later run with
206                // the head restored gets a hit that never came from the head.
207                //
208                // The write itself is best-effort: a cache failure is a
209                // diagnostic, not a failure of the analysis.
210                if let Extracted::Complete(value) = &served.extracted
211                    && !served.from_cache
212                    && result.failed_files.is_empty()
213                {
214                    let _ = self.cache.put(&served.key, value);
215                }
216                result
217            }
218            // Rule 8: no provider produced an answer → no findings, file in
219            // `failed_files` with every provider's reason. The detail is kept
220            // rather than discarded, so the CLI can render a line the user can
221            // act on.
222            Err(err) => AnalysisResult::failed(first.file_path.clone(), chain_failure_reason(err)),
223        }
224    }
225
226    /// Analyze many files concurrently, bounded by the limiter.
227    ///
228    /// Each entry of `by_file` is one file's hunks; the limiter bounds the
229    /// in-flight requests, so we spawn them all and let it queue. The
230    /// per-file results are merged with [`AnalysisResult::merge`].
231    pub async fn analyze_files(&self, by_file: &[Vec<Hunk>]) -> AnalysisResult {
232        self.analyze_files_in_mode(
233            by_file.iter().map(Vec::as_slice),
234            self.configured_cache_mode(),
235        )
236        .await
237    }
238
239    /// Analyze selected cache misses without rebuilding the provider chain.
240    ///
241    /// Push-gate and bounded-review modes use this after cache-only preflight.
242    /// It bypasses cache while preserving sticky demotion and backend
243    /// diagnostics, so another process cannot populate an entry between the
244    /// preflight and this call and make a cached verdict count as fresh.
245    pub async fn analyze_files_live(&self, by_file: &[&[Hunk]]) -> AnalysisResult {
246        self.analyze_files_in_mode(by_file.iter().copied(), CacheMode::Bypass)
247            .await
248    }
249
250    fn configured_cache_mode(&self) -> CacheMode {
251        if self.cache_only {
252            CacheMode::Only
253        } else {
254            CacheMode::Prefer
255        }
256    }
257
258    async fn analyze_files_in_mode<'a>(
259        &self,
260        by_file: impl IntoIterator<Item = &'a [Hunk]>,
261        cache_mode: CacheMode,
262    ) -> AnalysisResult {
263        let groups: Vec<HunkGroup<'a>> = by_file.into_iter().flat_map(partition_hunks).collect();
264        let futures = groups
265            .iter()
266            .map(|group| self.analyze_file_in_mode(group.as_slice(), cache_mode));
267        let results = join_all(futures).await;
268        let mut merged = AnalysisResult::default();
269        for result in results {
270            merged.merge(result);
271        }
272        merged
273    }
274}
275
276/// A correctly grouped borrowed slice, or owned groups recovered from a mixed one.
277enum HunkGroup<'a> {
278    Borrowed(&'a [Hunk]),
279    Owned(Vec<Hunk>),
280}
281
282impl HunkGroup<'_> {
283    fn as_slice(&self) -> &[Hunk] {
284        match self {
285            Self::Borrowed(hunks) => hunks,
286            Self::Owned(hunks) => hunks,
287        }
288    }
289}
290
291/// Preserve the zero-copy normal path and partition only malformed input.
292fn partition_hunks(hunks: &[Hunk]) -> Vec<HunkGroup<'_>> {
293    let mixed = hunks
294        .first()
295        .is_some_and(|first| hunks.iter().any(|hunk| hunk.file_path != first.file_path));
296    if !mixed {
297        return vec![HunkGroup::Borrowed(hunks)];
298    }
299    group_by_file(hunks.iter().cloned())
300        .into_iter()
301        .map(HunkGroup::Owned)
302        .collect()
303}
304
305/// Map an `LlmError` to the failure reason the caller carries in
306/// `AnalysisResult::failed_files`.
307///
308/// Distinct from the parsing-path reasons because the LLM layer's failure
309/// modes are a different axis. HTTP failures preserve a numeric status and
310/// process backends preserve a stable typed kind, so callers never have to
311/// recover policy from human-readable messages.
312pub(crate) fn into_failure_reason(err: LlmError) -> FailureReason {
313    match err {
314        LlmError::Transport { status, message } => FailureReason::Transport { status, message },
315        LlmError::Unparseable(message) => FailureReason::Unparseable(message),
316        LlmError::ModelStopped { finish, message } => {
317            FailureReason::ModelStopped { finish, message }
318        }
319        // `NotConfigured` is a configuration failure at the LLM boundary —
320        // not a connectivity failure, but indistinguishable from one to the
321        // gate, which only cares whether the file was analyzed. Mapping to
322        // `Transport { status: None }` keeps the exit code 2 path uniform
323        // without inventing a new variant the JSON output would have to
324        // distinguish.
325        LlmError::NotConfigured(message) => FailureReason::Transport {
326            status: None,
327            message,
328        },
329        LlmError::Backend { kind, message } => FailureReason::Backend { kind, message },
330    }
331}
332
333/// Map a whole-chain failure to the reason the caller carries.
334///
335/// **A one-provider chain collapses to that provider's own reason.** That keeps
336/// a single-provider config - what `drep init` writes - reporting exactly what
337/// it reported before failover existed, down to the JSON `kind`.
338///
339/// The trigger is the chain's *length*, not the number of providers that
340/// failed. Those differ precisely where it matters: a two-provider chain
341/// stopped at the head by a 401 produces one attempt, and collapsing it would
342/// discard the provider index and the model name just as the user is asking
343/// "I configured a fallback - why didn't it run?".
344fn chain_failure_reason(err: ChainError) -> FailureReason {
345    let mut attempts = err.attempts;
346    if err.chain_len == 1
347        && let Some(only) = attempts.pop()
348    {
349        // Move the attempt out so the error string is not cloned on the
350        // overwhelmingly common one-provider path.
351        return into_failure_reason(only.error);
352    }
353    FailureReason::ChainFailed(
354        attempts
355            .into_iter()
356            .map(|attempt| ProviderFailure {
357                provider: attempt.provider,
358                model: attempt.model,
359                reason: into_failure_reason(attempt.error),
360                skipped: attempt.skipped,
361            })
362            .collect(),
363    )
364}
365
366/// Turn an `Extracted` value into an [`AnalysisResult`].
367///
368/// A free function, not a method: it reads no analyzer state, and keeping it
369/// free means the whole parsing core is testable without a `MockServer`, a
370/// `Cache` and a `TempDir`.
371///
372/// The truncation flag is **read off the discriminant**, never passed in
373/// beside it. An earlier shape took `extracted` *and* a `truncated: bool`,
374/// which let `(Extracted::Truncated(v), false)` compile and report a
375/// truncated file as clean - the single outcome this module exists to
376/// prevent, resting on four call sites agreeing by convention.
377fn parse_response(
378    payload: &payload::Payload,
379    file_path: &Path,
380    extracted: &Extracted,
381) -> AnalysisResult {
382    let mut result = AnalysisResult::default();
383
384    let (value, truncated) = match extracted {
385        Extracted::Complete(value) => (value, false),
386        // Rule 7: a truncated response is a prefix of what the model meant,
387        // so the file is unanalyzed however good the partial findings look.
388        Extracted::Truncated(value) => (value, true),
389    };
390
391    // The response shape is `{"issues": [...], "summary": "..."}`. Anything
392    // else is malformed, and the whole file is unanalyzed.
393    let Some(issues) = value.get(ISSUES).and_then(Value::as_array) else {
394        // Truncation wins over "no `issues` array": a response cut off before
395        // it reached `issues` has no array *because* it was truncated, and
396        // reporting that as a malformed record hides the real cause.
397        let reason = if truncated {
398            FailureReason::Truncated
399        } else {
400            FailureReason::MalformedFinding("response has no `issues` array".to_owned())
401        };
402        result.failed_files.insert(file_path.to_path_buf(), reason);
403        return result;
404    };
405
406    // Every finding carries the same path string. Allocate it only once the
407    // response has an issues array; the missing-array failure above does not
408    // need it.
409    let path_string = file_path.to_string_lossy().into_owned();
410    let mut failure = truncated.then_some(FailureReason::Truncated);
411
412    // `issues: []` is a legitimate clean result: empty findings, no failure.
413    for issue in issues {
414        match parse_issue(issue, payload, &path_string) {
415            IssueOutcome::Finding(finding) => result.findings.push(finding),
416            IssueOutcome::Dropped => result.dropped_out_of_range += 1,
417            // Do not return early: a malformed record in the middle of an
418            // otherwise-valid array should still let the well-formed records
419            // through. The failure class is "we do not fully understand the
420            // response", not "every record is wrong".
421            // First reason wins, matching `union_failures`: the reasons are not
422            // meaningfully combinable, and the last-writer version reported
423            // whichever malformed record happened to sit at the end of the
424            // array rather than the one that first told us the response was
425            // not understood.
426            IssueOutcome::Malformed(detail) => {
427                failure.get_or_insert(FailureReason::MalformedFinding(detail));
428            }
429        }
430    }
431
432    if let Some(reason) = failure {
433        result.failed_files.insert(file_path.to_path_buf(), reason);
434    }
435    result
436}
437
438/// Parse one issue record into a [`Finding`], a drop, or a malformed
439/// marker with a reason.
440///
441/// The three outcomes are deliberately distinct:
442///
443/// - `Finding`: a valid record attributed to a real line in the
444///   payload. The caller adds it to `findings`.
445/// - `Dropped`: a valid record whose line was not in
446///   `payload.valid_lines`. The caller increments
447///   `dropped_out_of_range`. The file is **not** marked failed: we
448///   understood the record perfectly, it was simply about code the
449///   model was never shown.
450/// - `Malformed`: an unparseable record (unknown severity, missing
451///   field, non-integer `line`). The caller adds the file to
452///   `failed_files`. We cannot know what the record meant, so we
453///   cannot trust the rest of the response either.
454fn parse_issue(issue: &Value, payload: &payload::Payload, file_path: &str) -> IssueOutcome {
455    // `line` must be a positive integer. A missing field, a string,
456    // a float, or a non-positive number are all malformed.
457    let Some(line) = issue.get(LINE).and_then(Value::as_u64) else {
458        return IssueOutcome::Malformed("missing or non-integer `line`".to_owned());
459    };
460    // `Value::as_u64` already rejects non-integers; the only
461    // remaining "not a positive integer" case is zero. A line of
462    // zero is a model artifact, not a real line.
463    if line == 0 {
464        return IssueOutcome::Malformed("`line` is zero".to_owned());
465    }
466    // A line beyond `u32` is a model artifact of exactly the same class as
467    // a line of zero, and this module's whole thesis is that we do not guess.
468    // Clamping to `u32::MAX` happened to land in `Dropped` because that value
469    // is never in `valid_lines` - correct by accident, via a silent clamp.
470    let Ok(line) = u32::try_from(line) else {
471        return IssueOutcome::Malformed("`line` is beyond u32".to_owned());
472    };
473
474    // `severity` must be one of the levels the prompt asked for. Anything
475    // else is malformed: we cannot map it to a `Severity`, and we do not
476    // silently coerce. The vocabulary lives on `LlmSeverity` so the prompt
477    // and this parser cannot list different levels.
478    let Some(severity_str) = issue.get(SEVERITY).and_then(Value::as_str) else {
479        return IssueOutcome::Malformed("missing `severity`".to_owned());
480    };
481    let Ok(severity) = severity_str.parse::<LlmSeverity>() else {
482        return IssueOutcome::Malformed(format!("unknown severity `{severity_str}`"));
483    };
484    let severity = severity.to_severity();
485
486    // `message` is the only remaining required field. Missing or
487    // non-string is malformed.
488    let Some(message) = issue.get(MESSAGE).and_then(Value::as_str) else {
489        return IssueOutcome::Malformed("missing or non-string `message`".to_owned());
490    };
491
492    // `category` is optional, but a *present* non-string one is malformed, not
493    // a missing one. `.get().and_then(as_str).unwrap_or("unknown")` collapses
494    // the two, so `"category": 7` was reported as the finding kind "unknown" -
495    // a response we demonstrably did not understand, recorded as understood and
496    // then cached for the whole TTL. Same rule `severity` and `message` follow.
497    let kind = match issue.get(CATEGORY) {
498        None => "unknown".to_owned(),
499        Some(Value::String(text)) => text.clone(),
500        Some(_) => return IssueOutcome::Malformed("non-string `category`".to_owned()),
501    };
502    let message = message.to_owned();
503    let asserts_compile_failure = match issue.get(COMPILE_FAILURE) {
504        None => false,
505        Some(Value::Bool(value)) => *value,
506        Some(_) => return IssueOutcome::Malformed("non-boolean `compile_failure`".to_owned()),
507    };
508
509    // `suggestion` is optional on the same terms. Absent or empty → `None`, not
510    // `Some("")`: an empty suggestion is not a suggestion. A present non-string
511    // one is malformed rather than silently absent.
512    let suggestion = match issue.get(SUGGESTION) {
513        None => None,
514        Some(Value::String(text)) if text.is_empty() => None,
515        Some(Value::String(text)) => Some(text.clone()),
516        Some(_) => return IssueOutcome::Malformed("non-string `suggestion`".to_owned()),
517    };
518
519    // Membership is checked LAST, after the record's shape.
520    //
521    // Shape asks "did the model answer in our schema"; membership asks "did it
522    // talk about code we sent". A record with an unknown severity is evidence
523    // the response's vocabulary is wrong, and that contaminates the records we
524    // did accept - so it must fail the file even when the record also cites a
525    // line we never sent. Checking membership first would let a demonstrably
526    // schema-violating response be reported as fully understood.
527    //
528    // A well-formed record about code we did not send is different: we
529    // understood it perfectly, it is simply out of scope. It is dropped and
530    // counted, never clamped onto the nearest valid line, which would attach a
531    // real-looking finding to arbitrary code. Pinned by
532    // `out_of_range_line_is_dropped_not_clamped`.
533    if !payload.valid_lines.contains(&line) {
534        return IssueOutcome::Dropped;
535    }
536
537    IssueOutcome::Finding(Finding {
538        kind,
539        severity,
540        file_path: file_path.to_owned(),
541        line,
542        column: None,
543        message,
544        suggestion,
545        asserts_compile_failure,
546        fingerprint: None,
547    })
548}
549
550/// What one issue record became after parsing.
551enum IssueOutcome {
552    /// A valid record attributed to a real line in the payload.
553    Finding(Finding),
554    /// A valid record whose line was not in `payload.valid_lines`.
555    Dropped,
556    /// An unparseable record, with a reason naming what was wrong.
557    Malformed(String),
558}
559
560#[cfg(test)]
561mod partition_tests {
562    use super::{HunkGroup, partition_hunks};
563    use crate::diff::hunks::Hunk;
564    use std::path::PathBuf;
565
566    #[test]
567    fn already_grouped_hunks_remain_borrowed() {
568        let hunks = [Hunk::whole_file(PathBuf::from("same.rs"), "one\ntwo\n")];
569        let groups = partition_hunks(&hunks);
570        let [HunkGroup::Borrowed(group)] = groups.as_slice() else {
571            panic!("an already-grouped slice must stay on the zero-copy path");
572        };
573        assert!(std::ptr::eq(group.as_ptr(), hunks.as_ptr()));
574    }
575}