Skip to main content

fallow_api/
audit_complexity.rs

1//! New-only attribution of complexity findings.
2//!
3//! A complexity finding is identified by its path and function name. The
4//! exceeded category and the line are not part of the identity, so a line
5//! shift or a category change keeps the match with the base finding. The
6//! metric values then decide the attribution. A head finding is introduced
7//! when:
8//!
9//! - no base finding matches it,
10//! - it exceeds a metric that the base finding did not exceed, and that metric
11//!   grew (see [`newly_exceeded_metric_grew`]), or
12//! - a metric that it exceeds grew, and its severity tier is higher than the
13//!   tier of the base finding (see [`severity_tier_rose`]).
14//!
15//! The exceeded flags and the tier of the base finding come from the base run,
16//! so a threshold override in the same change cannot make an old finding
17//! introduced. Unchanged and decreased metrics stay inherited, also when the
18//! exceeded category changes (#3277).
19//!
20//! A matched finding that is not introduced is worsened when its cyclomatic,
21//! cognitive or CRAP value is higher than in its matched base finding. Growth
22//! of a metric that the base finding already exceeded, in the same tier, is
23//! worsened too. A line count must grow by a minimum (see
24//! [`line_count_grew`]). The `audit.worsened` setting decides how a worsened
25//! finding affects the verdict.
26//!
27//! A CRAP score from estimated coverage does not make a finding introduced.
28//! Under the `new-only` gate, a finding that exceeds only that CRAP score gets
29//! the gate severity `warn` (see [`demote_estimated_crap_gates`]).
30//!
31//! Under every gate, a finding in a test file gets the gate severity `warn`
32//! and the gate exemption `test-file` (see [`exempt_test_file_gates`]). The
33//! attribution of the finding does not change.
34
35use std::path::Path;
36
37use fallow_output::{
38    AuditFindingAttribution, AuditGateExemption, CoverageSource, DEFAULT_COGNITIVE_CRITICAL,
39    DEFAULT_COGNITIVE_HIGH, DEFAULT_CYCLOMATIC_CRITICAL, DEFAULT_CYCLOMATIC_HIGH,
40    ExceededThreshold, FindingSeverity, WorsenedMetric, WorsenedMetricKind,
41    compute_finding_severity,
42};
43use fallow_types::output_dead_code::EffectiveSeverity;
44use rustc_hash::{FxHashMap, FxHashSet};
45
46use crate::audit_keys::{health_finding_key, remap_key_for_renames};
47
48/// Metric values of one base complexity finding.
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct ComplexityMetrics {
51    /// 1-based line of the function. Only orders same-named findings.
52    pub line: u32,
53    /// Cyclomatic complexity.
54    pub cyclomatic: u16,
55    /// Cognitive complexity.
56    pub cognitive: u16,
57    /// CRAP score, when coverage data exists.
58    pub crap: Option<f64>,
59    /// Lines of code in the function body.
60    pub line_count: u32,
61    /// The thresholds that the finding exceeded in its own run.
62    pub exceeded: ExceededThreshold,
63    /// The severity tier of the finding in its own run.
64    pub severity: FindingSeverity,
65    /// Whether the CRAP score comes from estimated coverage.
66    pub crap_estimated: bool,
67}
68
69impl ComplexityMetrics {
70    /// The metric values of one finding.
71    #[must_use]
72    pub const fn of(finding: &fallow_output::ComplexityViolation) -> Self {
73        Self {
74            line: finding.line,
75            cyclomatic: finding.cyclomatic,
76            cognitive: finding.cognitive,
77            crap: finding.crap,
78            line_count: finding.line_count,
79            exceeded: finding.exceeded,
80            severity: finding.severity,
81            crap_estimated: crap_is_estimated(finding),
82        }
83    }
84
85    /// The metric values that a review comment shows for an inherited
86    /// finding.
87    const fn base_metrics(&self) -> fallow_output::AuditBaseMetrics {
88        fallow_output::AuditBaseMetrics {
89            cyclomatic: self.cyclomatic,
90            cognitive: self.cognitive,
91            crap: self.crap,
92            line_count: self.line_count,
93        }
94    }
95
96    /// Whether both findings have the same complexity values. The line and
97    /// the line count are not compared.
98    fn same_values(&self, other: &Self) -> bool {
99        self.cyclomatic == other.cyclomatic
100            && self.cognitive == other.cognitive
101            && self.crap.map(f64::to_bits) == other.crap.map(f64::to_bits)
102    }
103
104    /// Whether both findings have the same complexity values and the same
105    /// line count.
106    fn same_values_and_lines(&self, other: &Self) -> bool {
107        self.same_values(other) && self.line_count == other.line_count
108    }
109
110    /// Whether both findings have the same cyclomatic and cognitive values.
111    /// The CRAP score is not compared, because it also changes when only the
112    /// coverage input changes (#3815).
113    const fn same_structure(&self, other: &Self) -> bool {
114        self.cyclomatic == other.cyclomatic && self.cognitive == other.cognitive
115    }
116
117    /// Whether both findings have the same cyclomatic and cognitive values and
118    /// the same line count.
119    const fn same_structure_and_lines(&self, other: &Self) -> bool {
120        self.same_structure(other) && self.line_count == other.line_count
121    }
122}
123
124/// Attribution of one head complexity finding against the base findings.
125#[derive(Debug, Clone, PartialEq, Default)]
126pub struct ComplexityClass {
127    /// `true` when no base finding matches, when a newly exceeded metric
128    /// grew, or when growth moved the finding to a higher severity tier.
129    pub introduced: bool,
130    /// The measured metrics that are higher than in the matched base finding.
131    /// Empty when no base finding matches or when no metric grew.
132    pub worsened_metrics: Vec<WorsenedMetric>,
133    /// `true` when a metric that the finding exceeds grew. Before this rule,
134    /// that growth made the finding introduced, so `audit.worsened: off`
135    /// keeps it worsened (see [`Self::clear_worsened_for_off`]).
136    pub exceeded_metric_grew: bool,
137    /// The metric values of the matched base finding. `None` when no base
138    /// finding matches.
139    pub base: Option<fallow_output::AuditBaseMetrics>,
140}
141
142impl ComplexityClass {
143    /// `true` when a base finding matches, the finding is not introduced, and
144    /// a measured metric grew.
145    #[must_use]
146    pub fn is_worsened(&self) -> bool {
147        !self.introduced && !self.worsened_metrics.is_empty()
148    }
149
150    /// The audit-mode class of the finding.
151    #[must_use]
152    pub fn attribution(&self) -> AuditFindingAttribution {
153        if self.introduced {
154            AuditFindingAttribution::Introduced
155        } else if self.worsened_metrics.is_empty() {
156            AuditFindingAttribution::Inherited
157        } else {
158            AuditFindingAttribution::Worsened
159        }
160    }
161
162    /// Clear the grown metrics for `audit.worsened: off`. Growth only in
163    /// metrics that the finding does not exceed then stays inherited. Growth
164    /// of an exceeded metric stays worsened, so it gives at least `warn` and
165    /// does not disappear from the report.
166    pub fn clear_worsened_for_off(&mut self) {
167        if !self.introduced && !self.exceeded_metric_grew {
168            self.worsened_metrics.clear();
169        }
170    }
171
172    fn of_match(
173        head: &fallow_output::ComplexityViolation,
174        base: Option<&ComplexityMetrics>,
175    ) -> Self {
176        base.map_or(
177            Self {
178                introduced: true,
179                worsened_metrics: Vec::new(),
180                exceeded_metric_grew: false,
181                base: None,
182            },
183            |base| {
184                let exceeded_metric_grew = exceeded_metric_increased(head, base);
185                Self {
186                    introduced: newly_exceeded_metric_grew(head, base)
187                        || (exceeded_metric_grew && severity_tier_rose(head, base)),
188                    worsened_metrics: grown_metrics(head, base),
189                    exceeded_metric_grew,
190                    base: Some(base.base_metrics()),
191                }
192            },
193        )
194    }
195}
196
197/// The measured metrics of `head` that are higher than in `base`.
198///
199/// The line count must grow by a minimum, see [`line_count_grew`]. CRAP
200/// compares only when both sides have a score, because a score that
201/// only one side has reflects the coverage input, not the code.
202fn grown_metrics(
203    head: &fallow_output::ComplexityViolation,
204    base: &ComplexityMetrics,
205) -> Vec<WorsenedMetric> {
206    let mut grown = Vec::new();
207    let mut push = |metric, base: f64, head: f64| {
208        if head > base {
209            grown.push(WorsenedMetric { metric, base, head });
210        }
211    };
212    push(
213        WorsenedMetricKind::Cyclomatic,
214        f64::from(base.cyclomatic),
215        f64::from(head.cyclomatic),
216    );
217    push(
218        WorsenedMetricKind::Cognitive,
219        f64::from(base.cognitive),
220        f64::from(head.cognitive),
221    );
222    if let (Some(base_crap), Some(head_crap)) = (base.crap, head.crap) {
223        push(WorsenedMetricKind::Crap, base_crap, head_crap);
224    }
225    if line_count_grew(base.line_count, head.line_count) {
226        grown.push(WorsenedMetric {
227            metric: WorsenedMetricKind::LineCount,
228            base: f64::from(base.line_count),
229            head: f64::from(head.line_count),
230        });
231    }
232    grown
233}
234
235/// The smallest line count growth, in lines, that makes a finding worsened.
236const LINE_COUNT_MIN_GROWTH_LINES: u32 = 5;
237
238/// Whether the line count grew by at least [`LINE_COUNT_MIN_GROWTH_LINES`]
239/// lines. The floor is fixed and does not scale with the function size, so
240/// growth in a large function is not hidden.
241///
242/// The line count is the physical span of the function, so comments and blank
243/// lines in the body count. The minimum keeps a comment or a formatter rewrap
244/// from making a finding worsened.
245fn line_count_grew(base: u32, head: u32) -> bool {
246    head.saturating_sub(base) >= LINE_COUNT_MIN_GROWTH_LINES
247}
248
249/// Base complexity findings by identity key (`complexity:<path>:<function>`),
250/// each list sorted by line.
251pub type ComplexityBaseline = FxHashMap<String, Vec<ComplexityMetrics>>;
252
253/// The base complexity findings of a health report, by identity key.
254#[must_use]
255pub fn complexity_baseline(
256    report: &fallow_output::HealthReport,
257    root: &Path,
258) -> ComplexityBaseline {
259    let mut baseline = ComplexityBaseline::default();
260    for finding in &report.findings {
261        baseline
262            .entry(health_finding_key(finding, root))
263            .or_default()
264            .push(ComplexityMetrics::of(finding));
265    }
266    sort_by_line(&mut baseline);
267    baseline
268}
269
270/// The identity keys of a complexity baseline.
271#[must_use]
272pub fn complexity_baseline_keys(baseline: &ComplexityBaseline) -> FxHashSet<String> {
273    baseline.keys().cloned().collect()
274}
275
276/// Relocate the base findings of renamed files onto their head paths.
277///
278/// `renames` maps base-relative old paths to head-relative new paths, as in
279/// [`crate::audit_keys::remap_keys_for_renames`]. When two keys merge, their findings join
280/// one list, sorted by line.
281#[must_use]
282#[expect(
283    clippy::implicit_hasher,
284    reason = "fallow standardizes on FxHashMap across audit attribution keys"
285)]
286pub fn remap_complexity_baseline_for_renames(
287    baseline: ComplexityBaseline,
288    renames: &FxHashMap<String, String>,
289) -> ComplexityBaseline {
290    let mut remapped = ComplexityBaseline::default();
291    for (key, findings) in baseline {
292        remapped
293            .entry(remap_key_for_renames(&key, renames))
294            .or_default()
295            .extend(findings);
296    }
297    sort_by_line(&mut remapped);
298    remapped
299}
300
301fn sort_by_line(baseline: &mut ComplexityBaseline) {
302    for findings in baseline.values_mut() {
303        findings.sort_by_key(|metrics| metrics.line);
304    }
305}
306
307/// Whether `head` is worse than `base` in a metric that `head` exceeds.
308///
309/// CRAP counts only when both sides have a measured score (see
310/// [`measured_crap_grew`]).
311fn exceeded_metric_increased(
312    head: &fallow_output::ComplexityViolation,
313    base: &ComplexityMetrics,
314) -> bool {
315    let exceeded = head.exceeded;
316    (exceeded.includes_cyclomatic() && head.cyclomatic > base.cyclomatic)
317        || (exceeded.includes_cognitive() && head.cognitive > base.cognitive)
318        || (exceeded.includes_crap() && measured_crap_grew(head, base))
319        || (exceeded.is_file_lines() && line_count_grew(base.line_count, head.line_count))
320}
321
322/// Whether `head` exceeds a metric that `base` did not exceed in its own run,
323/// and that metric grew. A metric that crosses its limit only because a
324/// threshold changed does not grow, so it stays inherited.
325fn newly_exceeded_metric_grew(
326    head: &fallow_output::ComplexityViolation,
327    base: &ComplexityMetrics,
328) -> bool {
329    let (now, before) = (head.exceeded, base.exceeded);
330    (now.includes_cyclomatic()
331        && !before.includes_cyclomatic()
332        && head.cyclomatic > base.cyclomatic)
333        || (now.includes_cognitive()
334            && !before.includes_cognitive()
335            && head.cognitive > base.cognitive)
336        || (now.includes_crap() && !before.includes_crap() && measured_crap_grew(head, base))
337}
338
339/// Whether both sides have a CRAP score from measured coverage and the head
340/// score is higher. A score that only one side has, or a score from estimated
341/// coverage, reflects the coverage input, not the code.
342fn measured_crap_grew(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
343    crap_is_comparable(head, base)
344        && matches!((head.crap, base.crap), (Some(head), Some(base)) if head > base)
345}
346
347fn crap_is_comparable(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
348    head.crap.is_some() && base.crap.is_some() && !crap_is_estimated(head) && !base.crap_estimated
349}
350
351/// Whether the severity tier of `head` is higher than the tier of `base`.
352///
353/// The tiers use fixed limits, not the configured thresholds. The CRAP score
354/// takes part only when both sides have a measured score; else both tiers come
355/// from cyclomatic and cognitive complexity only.
356fn severity_tier_rose(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
357    if crap_is_comparable(head, base) {
358        return head.severity > base.severity;
359    }
360    complexity_tier(head.cognitive, head.cyclomatic)
361        > complexity_tier(base.cognitive, base.cyclomatic)
362}
363
364fn complexity_tier(cognitive: u16, cyclomatic: u16) -> FindingSeverity {
365    compute_finding_severity(
366        cognitive,
367        cyclomatic,
368        None,
369        DEFAULT_COGNITIVE_HIGH,
370        DEFAULT_COGNITIVE_CRITICAL,
371        DEFAULT_CYCLOMATIC_HIGH,
372        DEFAULT_CYCLOMATIC_CRITICAL,
373    )
374}
375
376/// Whether the CRAP score of the finding comes from estimated coverage, not
377/// from a measured coverage map (`--coverage` or runtime coverage).
378#[must_use]
379pub const fn crap_is_estimated(finding: &fallow_output::ComplexityViolation) -> bool {
380    matches!(
381        finding.coverage_source,
382        Some(CoverageSource::Estimated | CoverageSource::EstimatedComponentInherited)
383    )
384}
385
386/// Whether CRAP from estimated coverage is the only threshold that the
387/// finding exceeds.
388#[must_use]
389pub const fn exceeds_only_estimated_crap(finding: &fallow_output::ComplexityViolation) -> bool {
390    matches!(finding.exceeded, ExceededThreshold::Crap) && crap_is_estimated(finding)
391}
392
393/// Give the gate severity `warn` to each finding that exceeds only CRAP from
394/// estimated coverage, for the `new-only` gate.
395///
396/// The estimate comes from static test reachability, so it does not measure
397/// the change. The finding stays in the report, and the verdict reads `warn`
398/// for it. A finding that also exceeds cyclomatic or cognitive complexity
399/// keeps its gate severity. Measured coverage keeps the gate severity too.
400pub fn demote_estimated_crap_gates(findings: &mut [fallow_output::HealthFinding]) {
401    for finding in findings {
402        if exceeds_only_estimated_crap(finding)
403            && finding.effective_severity == Some(EffectiveSeverity::Error)
404        {
405            finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
406        }
407    }
408}
409
410/// Give the gate severity `warn` to each finding in a test file, and mark it
411/// with [`AuditGateExemption::TestFile`].
412///
413/// The shared test-path classifier ([`fallow_engine::test_paths::is_test_path`])
414/// decides what a test file is: specs, test directories, end-to-end suites,
415/// mocks and fixtures. The finding stays in the report. `fallow health` does
416/// not call this, so it keeps the rule severity there.
417pub fn exempt_test_file_gates(findings: &mut [fallow_output::HealthFinding], root: &Path) {
418    for finding in findings {
419        let relative = finding.path.strip_prefix(root).unwrap_or(&finding.path);
420        if fallow_engine::test_paths::is_test_path(root, relative) {
421            finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
422            finding.gate_exemption = Some(AuditGateExemption::TestFile);
423        }
424    }
425}
426
427/// Classify each head complexity finding as introduced (`true`) or inherited
428/// (`false`), in report order. See [`classify_complexity_attribution`].
429#[must_use]
430pub fn classify_complexity_findings(
431    findings: &[fallow_output::HealthFinding],
432    root: &Path,
433    base: &ComplexityBaseline,
434) -> Vec<bool> {
435    classify_complexity_attribution(findings, root, base)
436        .into_iter()
437        .map(|class| class.introduced)
438        .collect()
439}
440
441/// Classify each head complexity finding against one base, in report order.
442///
443/// Head and base findings match by identity key. When one key holds several
444/// findings on one side (same-named class methods or anonymous functions in
445/// one file), the match is ambiguous. This conservative rule then applies, per
446/// key:
447///
448/// 1. Each head finding, in line order, takes an unmatched base finding with
449///    the same complexity values and the same line count.
450/// 2. Each remaining head finding, in line order, takes an unmatched base
451///    finding with the same complexity values. Rules 1 and 2 keep unchanged
452///    findings inherited when a same-named finding is added, removed or
453///    edited. Rule 1 runs for all head findings first, so an earlier head
454///    finding cannot take the exact match of a later one.
455/// 3. Each remaining head finding, in line order, takes an unmatched base
456///    finding with the same cyclomatic and cognitive values and the same line
457///    count, and then one with the same cyclomatic and cognitive values. The
458///    CRAP score is not compared in this rule, because a change of the
459///    coverage input changes the CRAP score of an unchanged function (#3815).
460///    The pair still compares the CRAP score, so CRAP growth stays visible.
461/// 4. The remaining head findings, in line order, take the remaining base
462///    findings, in line order. Each pair compares the exceeded metrics.
463/// 5. A head finding without a base finding is introduced.
464///
465/// Every base finding matches at most one head finding, so a new same-named
466/// finding cannot hide behind an existing one. The rule does not identify
467/// functions beyond path and name (see #2010). Two same-named findings that
468/// swap their metric values in one change stay inherited.
469///
470/// Each matched pair also lists the measured metrics that grew, so an
471/// inherited finding that got worse is visible.
472#[must_use]
473pub fn classify_complexity_attribution(
474    findings: &[fallow_output::HealthFinding],
475    root: &Path,
476    base: &ComplexityBaseline,
477) -> Vec<ComplexityClass> {
478    let mut groups: FxHashMap<String, Vec<usize>> = FxHashMap::default();
479    for (index, finding) in findings.iter().enumerate() {
480        groups
481            .entry(health_finding_key(finding, root))
482            .or_default()
483            .push(index);
484    }
485    let mut matches: Vec<Option<&ComplexityMetrics>> = vec![None; findings.len()];
486    for (key, mut heads) in groups {
487        let Some(bases) = base.get(&key) else {
488            continue;
489        };
490        heads.sort_by_key(|&index| (findings[index].line, findings[index].col));
491        let mut unmatched_bases: Vec<Option<&ComplexityMetrics>> = bases.iter().map(Some).collect();
492        let rules: [fn(&ComplexityMetrics, &ComplexityMetrics) -> bool; 4] = [
493            ComplexityMetrics::same_values_and_lines,
494            ComplexityMetrics::same_values,
495            ComplexityMetrics::same_structure_and_lines,
496            ComplexityMetrics::same_structure,
497        ];
498        for rule in rules {
499            for &index in &heads {
500                if matches[index].is_some() {
501                    continue;
502                }
503                let head = ComplexityMetrics::of(&findings[index]);
504                if let Some(slot) = unmatched_bases
505                    .iter_mut()
506                    .find(|slot| slot.is_some_and(|base| rule(base, &head)))
507                {
508                    matches[index] = slot.take();
509                }
510            }
511        }
512        let mut remaining_bases = unmatched_bases.into_iter().flatten();
513        for &index in &heads {
514            if matches[index].is_none() {
515                matches[index] = remaining_bases.next();
516            }
517        }
518    }
519    findings
520        .iter()
521        .zip(matches)
522        .map(|(finding, base)| ComplexityClass::of_match(finding, base))
523        .collect()
524}
525
526/// Classify each head complexity finding against several bases, in report
527/// order. A finding is introduced only when it is introduced against every
528/// base, so a finding that one base already has is inherited.
529#[must_use]
530pub fn classify_complexity_findings_against_all<'a>(
531    findings: &[fallow_output::HealthFinding],
532    root: &Path,
533    bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
534) -> Vec<bool> {
535    classify_complexity_attribution_against_all(findings, root, bases)
536        .into_iter()
537        .map(|class| class.introduced)
538        .collect()
539}
540
541/// Classify each head complexity finding against several bases, in report
542/// order.
543///
544/// A finding is introduced only when it is introduced against every base. A
545/// finding that is not introduced takes the smallest list of grown metrics of
546/// the bases that it is not introduced against, so a finding that one base
547/// already has with the same values is inherited, not worsened. An introduced
548/// finding keeps the grown metrics of the first base that matches it.
549#[must_use]
550pub fn classify_complexity_attribution_against_all<'a>(
551    findings: &[fallow_output::HealthFinding],
552    root: &Path,
553    bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
554) -> Vec<ComplexityClass> {
555    let per_base: Vec<Vec<ComplexityClass>> = bases
556        .into_iter()
557        .map(|base| classify_complexity_attribution(findings, root, base))
558        .collect();
559    (0..findings.len())
560        .map(|index| {
561            let classes = per_base.iter().map(|classes| &classes[index]);
562            let inherited = classes
563                .clone()
564                .filter(|class| !class.introduced)
565                .min_by_key(|class| class.worsened_metrics.len());
566            inherited.cloned().unwrap_or_else(|| ComplexityClass {
567                introduced: true,
568                exceeded_metric_grew: false,
569                base: None,
570                worsened_metrics: classes
571                    .map(|class| &class.worsened_metrics)
572                    .find(|metrics| !metrics.is_empty())
573                    .cloned()
574                    .unwrap_or_default(),
575            })
576        })
577        .collect()
578}
579
580/// The ledger key of each complexity finding, in report order.
581///
582/// A repeated identity key gets an occurrence suffix, so each finding counts
583/// once in the attribution counts. Without the suffix, same-named findings
584/// collapse to one count.
585#[must_use]
586pub fn complexity_ledger_keys(
587    findings: &[fallow_output::HealthFinding],
588    root: &Path,
589) -> Vec<String> {
590    let mut seen: FxHashMap<String, usize> = FxHashMap::default();
591    findings
592        .iter()
593        .map(|finding| {
594            let key = health_finding_key(finding, root);
595            let occurrence = seen.entry(key.clone()).or_default();
596            *occurrence += 1;
597            if *occurrence == 1 {
598                key
599            } else {
600                format!("{key}#{occurrence}")
601            }
602        })
603        .collect()
604}
605
606#[cfg(test)]
607mod tests {
608    use std::path::PathBuf;
609
610    use fallow_output::{
611        ComplexityViolation, ExceededThreshold, FindingSeverity, HealthFinding, HealthReport,
612    };
613
614    use super::*;
615
616    const MAX: u16 = 15;
617
618    fn root() -> PathBuf {
619        PathBuf::from("/project")
620    }
621
622    fn finding(name: &str, line: u32, cyclomatic: u16, cognitive: u16) -> HealthFinding {
623        HealthFinding::from(ComplexityViolation {
624            path: root().join("src/index.js"),
625            name: name.to_string(),
626            line,
627            col: 0,
628            cyclomatic,
629            standard_cyclomatic: None,
630            cognitive,
631            line_count: 30,
632            param_count: 1,
633            react_hook_count: 0,
634            react_jsx_max_depth: 0,
635            react_prop_count: 0,
636            react_hook_profile: None,
637            exceeded: ExceededThreshold::from_bools(cyclomatic > MAX, cognitive > MAX, false),
638            effective_severity: None,
639            severity: FindingSeverity::High,
640            crap: None,
641            mutation: None,
642            coverage_pct: None,
643            coverage_tier: None,
644            coverage_source: None,
645            inherited_from: None,
646            component_rollup: None,
647            contributions: Vec::new(),
648            effective_thresholds: None,
649            threshold_source: None,
650            max_file_lines: None,
651        })
652    }
653
654    fn baseline(findings: Vec<HealthFinding>) -> ComplexityBaseline {
655        complexity_baseline(
656            &HealthReport {
657                findings,
658                ..HealthReport::default()
659            },
660            &root(),
661        )
662    }
663
664    fn classify(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<bool> {
665        classify_complexity_findings(head, &root(), &baseline(base))
666    }
667
668    #[test]
669    fn identity_key_excludes_category_and_line() {
670        let key = health_finding_key(&finding("hotspot", 4, 17, 16), &root());
671        assert_eq!(key, "complexity:src/index.js:hotspot");
672    }
673
674    #[test]
675    fn issue_cases() {
676        // Unchanged.
677        assert_eq!(
678            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 17, 16)]),
679            [false]
680        );
681        // Increased in the same severity tier: worsened, not introduced.
682        assert_eq!(
683            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 18, 17)]),
684            [false]
685        );
686        // Decreased, same category.
687        assert_eq!(
688            classify(vec![finding("f", 1, 18, 17)], &[finding("f", 1, 17, 16)]),
689            [false]
690        );
691        // Decreased, category change from both to cyclomatic.
692        assert_eq!(
693            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 16, 15)]),
694            [false]
695        );
696        // New threshold crossing.
697        assert_eq!(classify(vec![], &[finding("f", 1, 17, 16)]), [true]);
698    }
699
700    #[test]
701    fn only_exceeded_metrics_can_introduce() {
702        // Cognitive grows but stays under the limit: only cyclomatic is
703        // exceeded, and it did not grow.
704        assert_eq!(
705            classify(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]),
706            [false]
707        );
708        // A category change to a newly exceeded metric that grew.
709        assert_eq!(
710            classify(vec![finding("f", 1, 20, 14)], &[finding("f", 1, 19, 16)]),
711            [true]
712        );
713    }
714
715    #[test]
716    fn a_finding_that_any_base_has_is_inherited() {
717        let primary = baseline(vec![]);
718        let merged = baseline(vec![finding("f", 1, 17, 16)]);
719        let head = [finding("f", 1, 17, 16), finding("g", 9, 17, 16)];
720        assert_eq!(
721            classify_complexity_findings_against_all(&head, &root(), [&primary, &merged]),
722            [false, true]
723        );
724        // A finding that moved to a higher tier against every base stays
725        // introduced.
726        assert_eq!(
727            classify_complexity_findings_against_all(
728                &[finding("f", 1, 31, 17)],
729                &root(),
730                [&baseline(vec![finding("f", 1, 17, 16)]), &merged]
731            ),
732            [true]
733        );
734    }
735
736    #[test]
737    fn line_shift_keeps_the_match() {
738        assert_eq!(
739            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 40, 17, 16)]),
740            [false]
741        );
742    }
743
744    fn crap_finding(crap: Option<f64>, source: Option<CoverageSource>) -> HealthFinding {
745        let mut finding = finding("f", 1, 16, 5);
746        finding.violation.exceeded = ExceededThreshold::Crap;
747        finding.violation.crap = crap;
748        finding.violation.coverage_source = source;
749        finding.violation.effective_severity = Some(EffectiveSeverity::Error);
750        finding
751    }
752
753    #[test]
754    fn crap_without_base_value_is_not_an_increase() {
755        // A base without a CRAP score ran without that coverage input. The
756        // code did not grow.
757        let head = crap_finding(Some(50.0), Some(CoverageSource::Istanbul));
758        assert_eq!(
759            classify(vec![crap_finding(None, None)], std::slice::from_ref(&head)),
760            [false]
761        );
762        // Measured CRAP growth in the same tier is worsened.
763        assert_eq!(
764            classify(
765                vec![crap_finding(Some(40.0), Some(CoverageSource::Istanbul))],
766                std::slice::from_ref(&head)
767            ),
768            [false]
769        );
770        assert_eq!(
771            classify(
772                vec![crap_finding(Some(60.0), Some(CoverageSource::Istanbul))],
773                &[head]
774            ),
775            [false]
776        );
777    }
778
779    #[test]
780    fn estimated_crap_growth_is_worsened_not_introduced() {
781        let estimated = Some(CoverageSource::Estimated);
782        let classes = attribution(
783            vec![crap_finding(Some(40.0), estimated)],
784            &[crap_finding(Some(50.0), estimated)],
785        );
786        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
787        assert_eq!(
788            classes[0].worsened_metrics,
789            [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
790        );
791        // A grown cognitive value that the base already exceeds is worsened.
792        let mut base = crap_finding(Some(40.0), estimated);
793        base.violation.exceeded = ExceededThreshold::CognitiveCrap;
794        base.violation.cognitive = 20;
795        let mut head = base.clone();
796        head.violation.cognitive = 21;
797        head.violation.crap = Some(50.0);
798        assert_eq!(classify(vec![base.clone()], &[head.clone()]), [false]);
799        // A grown cognitive value that reaches the next tier is introduced.
800        head.violation.cognitive = 25;
801        assert_eq!(classify(vec![base], &[head]), [true]);
802    }
803
804    #[test]
805    fn test_file_findings_get_warn_gate_severity_and_the_exemption() {
806        // The project itself lives below a `tests` directory. Only the path
807        // below the project root decides.
808        let project = root().join("tests").join("project");
809        let at = |relative: &str| {
810            let mut finding = finding("f", 1, 16, 5);
811            finding.violation.path = project.join(relative);
812            finding.violation.effective_severity = Some(EffectiveSeverity::Error);
813            finding
814        };
815        let mut findings = [
816            at("src/__tests__/app.js"),
817            at("src/app.spec.ts"),
818            at("src/app.test.tsx"),
819            at("src/__mocks__/api.js"),
820            at("src/app.js"),
821            at("src/latest.js"),
822        ];
823        exempt_test_file_gates(&mut findings, &project);
824        let marks: Vec<_> = findings
825            .iter()
826            .map(|finding| (finding.effective_severity, finding.gate_exemption))
827            .collect();
828        let exempt = (
829            Some(EffectiveSeverity::Warn),
830            Some(AuditGateExemption::TestFile),
831        );
832        let gated = (Some(EffectiveSeverity::Error), None);
833        assert_eq!(marks, [exempt, exempt, exempt, exempt, gated, gated]);
834    }
835
836    #[test]
837    fn estimated_crap_only_findings_get_warn_gate_severity() {
838        let mut both = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
839        both.violation.exceeded = ExceededThreshold::CognitiveCrap;
840        let mut warn_rule = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
841        warn_rule.violation.effective_severity = Some(EffectiveSeverity::Warn);
842        let mut findings = [
843            crap_finding(Some(50.0), Some(CoverageSource::Estimated)),
844            crap_finding(
845                Some(50.0),
846                Some(CoverageSource::EstimatedComponentInherited),
847            ),
848            crap_finding(Some(50.0), Some(CoverageSource::Istanbul)),
849            both,
850            warn_rule,
851        ];
852        demote_estimated_crap_gates(&mut findings);
853        let severities: Vec<_> = findings
854            .iter()
855            .map(|finding| finding.effective_severity)
856            .collect();
857        assert_eq!(
858            severities,
859            [
860                Some(EffectiveSeverity::Warn),
861                Some(EffectiveSeverity::Warn),
862                Some(EffectiveSeverity::Error),
863                Some(EffectiveSeverity::Error),
864                Some(EffectiveSeverity::Warn),
865            ]
866        );
867    }
868
869    #[test]
870    fn same_named_findings_match_unchanged_values_first() {
871        let base = vec![finding("run", 1, 17, 16), finding("run", 30, 21, 20)];
872        // Unchanged.
873        assert_eq!(
874            classify(
875                base.clone(),
876                &[finding("run", 1, 17, 16), finding("run", 30, 21, 20)]
877            ),
878            [false, false]
879        );
880        // First one removed: the second one keeps its own base finding.
881        assert_eq!(
882            classify(base.clone(), &[finding("run", 1, 21, 20)]),
883            [false]
884        );
885        // A new one added before both.
886        assert_eq!(
887            classify(
888                base.clone(),
889                &[
890                    finding("run", 1, 30, 30),
891                    finding("run", 20, 17, 16),
892                    finding("run", 50, 21, 20)
893                ]
894            ),
895            [true, false, false]
896        );
897        // The first one worsened, the second one unchanged.
898        assert_eq!(
899            classify(
900                base.clone(),
901                &[finding("run", 1, 18, 17), finding("run", 30, 21, 20)]
902            ),
903            [false, false]
904        );
905        // The first one moved to a higher tier, the second one unchanged.
906        assert_eq!(
907            classify(
908                base,
909                &[finding("run", 1, 30, 17), finding("run", 30, 21, 20)]
910            ),
911            [true, false]
912        );
913    }
914
915    /// An anonymous finding with a CRAP score from the given coverage source.
916    fn arrow(
917        line: u32,
918        cyclomatic: u16,
919        cognitive: u16,
920        crap: Option<f64>,
921        source: CoverageSource,
922    ) -> HealthFinding {
923        let mut finding = finding("<arrow>", line, MAX + 1, MAX + 1);
924        finding.violation.cyclomatic = cyclomatic;
925        finding.violation.cognitive = cognitive;
926        finding.violation.crap = crap;
927        finding.violation.coverage_source = crap.map(|_| source);
928        finding.violation.exceeded = ExceededThreshold::from_bools(
929            cyclomatic > MAX,
930            cognitive > MAX,
931            crap.is_some_and(|crap| crap >= 30.0),
932        );
933        finding
934    }
935
936    #[test]
937    fn unchanged_arrow_keeps_its_base_when_only_crap_changes() {
938        // Issue #3815: the CRAP score of an unchanged arrow went from an
939        // estimated score to a measured score. Its cyclomatic and cognitive
940        // values did not change, so it must keep its own base finding, not the
941        // first remaining base finding in line order.
942        let estimated = CoverageSource::Estimated;
943        let measured = CoverageSource::Istanbul;
944        let base = [
945            (122, 36, 37, 1332.0),
946            (284, 26, 28, 702.0),
947            (352, 9, 6, 90.0),
948            (560, 7, 6, 56.0),
949            (637, 30, 42, 930.0),
950            (732, 13, 5, 182.0),
951            (872, 13, 12, 182.0),
952            (889, 6, 2, 42.0),
953            (945, 5, 3, 30.0),
954            (972, 16, 4, 272.0),
955            (1017, 11, 13, 132.0),
956            (1184, 14, 15, 210.0),
957            (1202, 12, 5, 156.0),
958        ]
959        .into_iter()
960        .map(|(line, cyclomatic, cognitive, crap)| {
961            arrow(line, cyclomatic, cognitive, Some(crap), estimated)
962        })
963        .collect();
964        let head = [
965            arrow(128, 36, 37, Some(36.0), measured),
966            arrow(294, 27, 29, None, measured),
967            arrow(663, 30, 42, Some(30.0), measured),
968        ];
969        let classes = attribution(base, &head);
970        assert!(!classes[0].introduced);
971        assert!(!classes[2].introduced, "{:?}", classes[2]);
972        assert!(classes[2].worsened_metrics.is_empty());
973    }
974
975    #[test]
976    fn crap_growth_of_an_unchanged_arrow_still_compares() {
977        let measured = CoverageSource::Istanbul;
978        let classes = attribution(
979            vec![
980                arrow(10, 9, 6, Some(40.0), measured),
981                arrow(40, 30, 42, Some(30.0), measured),
982            ],
983            &[arrow(40, 30, 42, Some(60.0), measured)],
984        );
985        assert_eq!(
986            classes[0].worsened_metrics,
987            [metric(WorsenedMetricKind::Crap, 30.0, 60.0)]
988        );
989    }
990
991    fn with_lines(mut finding: HealthFinding, line_count: u32) -> HealthFinding {
992        finding.violation.line_count = line_count;
993        finding
994    }
995
996    fn attribution(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<ComplexityClass> {
997        classify_complexity_attribution(head, &root(), &baseline(base))
998    }
999
1000    fn metric(kind: WorsenedMetricKind, base: f64, head: f64) -> WorsenedMetric {
1001        WorsenedMetric {
1002            metric: kind,
1003            base,
1004            head,
1005        }
1006    }
1007
1008    #[test]
1009    fn grown_line_count_is_worsened_not_introduced() {
1010        let classes = attribution(
1011            vec![with_lines(finding("f", 1, 17, 16), 80)],
1012            &[with_lines(finding("f", 1, 17, 16), 300)],
1013        );
1014        assert!(!classes[0].introduced);
1015        assert!(classes[0].is_worsened());
1016        assert_eq!(
1017            classes[0].worsened_metrics,
1018            [metric(WorsenedMetricKind::LineCount, 80.0, 300.0)]
1019        );
1020        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1021    }
1022
1023    #[test]
1024    fn grown_metric_that_the_finding_does_not_exceed_is_worsened() {
1025        // Only cyclomatic is exceeded; cognitive grows below the limit.
1026        let classes = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1027        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1028        assert_eq!(
1029            classes[0].worsened_metrics,
1030            [metric(WorsenedMetricKind::Cognitive, 5.0, 9.0)]
1031        );
1032    }
1033
1034    #[test]
1035    fn grown_exceeded_metric_in_the_same_tier_is_worsened() {
1036        // Cyclomatic 100 to 103 stays in the critical tier.
1037        let classes = attribution(vec![finding("f", 1, 100, 16)], &[finding("f", 1, 103, 16)]);
1038        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1039        assert!(classes[0].exceeded_metric_grew);
1040        assert_eq!(
1041            classes[0].worsened_metrics,
1042            [metric(WorsenedMetricKind::Cyclomatic, 100.0, 103.0)]
1043        );
1044        // Growth only in a metric that the finding does not exceed.
1045        let below = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1046        assert!(!below[0].exceeded_metric_grew);
1047    }
1048
1049    #[test]
1050    fn severity_tier_uses_the_base_values_not_todays_thresholds() {
1051        // The base finding exceeded only cyclomatic. A threshold override in
1052        // the same change lowers the cognitive limit, so the head finding
1053        // exceeds cognitive too, without cognitive growth.
1054        let mut head = finding("f", 1, 18, 10);
1055        head.violation.exceeded = ExceededThreshold::Both;
1056        assert_eq!(
1057            classify(vec![finding("f", 1, 17, 10)], &[head.clone()]),
1058            [false]
1059        );
1060        // Cognitive grew and the base did not exceed it: newly exceeded.
1061        head.violation.cognitive = 11;
1062        assert_eq!(classify(vec![finding("f", 1, 17, 10)], &[head]), [true]);
1063    }
1064
1065    #[test]
1066    fn measured_crap_tier_crossing_is_introduced() {
1067        let istanbul = Some(CoverageSource::Istanbul);
1068        let mut base = crap_finding(Some(40.0), istanbul);
1069        base.violation.severity = FindingSeverity::Moderate;
1070        let mut head = crap_finding(Some(120.0), istanbul);
1071        head.violation.severity = FindingSeverity::Critical;
1072        assert_eq!(classify(vec![base.clone()], &[head.clone()]), [true]);
1073        // The same values from estimated coverage do not cross a tier.
1074        let estimated = Some(CoverageSource::Estimated);
1075        base.violation.coverage_source = estimated;
1076        head.violation.coverage_source = estimated;
1077        assert_eq!(classify(vec![base], &[head]), [false]);
1078    }
1079
1080    #[test]
1081    fn grown_exceeded_metric_is_introduced_with_values() {
1082        let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 40, 16)]);
1083        assert_eq!(
1084            classes[0].attribution(),
1085            AuditFindingAttribution::Introduced
1086        );
1087        assert_eq!(
1088            classes[0].worsened_metrics,
1089            [metric(WorsenedMetricKind::Cyclomatic, 17.0, 40.0)]
1090        );
1091        assert!(!classes[0].is_worsened());
1092    }
1093
1094    #[test]
1095    fn improved_and_moved_functions_are_inherited() {
1096        let improved = attribution(
1097            vec![with_lines(finding("f", 1, 30, 30), 90)],
1098            &[with_lines(finding("f", 1, 20, 18), 60)],
1099        );
1100        assert_eq!(
1101            improved[0].attribution(),
1102            AuditFindingAttribution::Inherited
1103        );
1104        assert!(improved[0].worsened_metrics.is_empty());
1105        let moved = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 400, 17, 16)]);
1106        assert_eq!(moved[0].attribution(), AuditFindingAttribution::Inherited);
1107    }
1108
1109    #[test]
1110    fn new_function_is_introduced_without_values() {
1111        let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("g", 1, 17, 16)]);
1112        assert_eq!(
1113            classes[0].attribution(),
1114            AuditFindingAttribution::Introduced
1115        );
1116        assert!(classes[0].worsened_metrics.is_empty());
1117    }
1118
1119    #[test]
1120    fn crap_compares_only_when_both_sides_have_a_score() {
1121        let mut head = finding("f", 1, 20, 5);
1122        head.violation.crap = Some(50.0);
1123        let classes = attribution(vec![finding("f", 1, 20, 5)], std::slice::from_ref(&head));
1124        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1125        let mut base = finding("f", 1, 20, 5);
1126        base.violation.crap = Some(40.0);
1127        let classes = attribution(vec![base], &[head]);
1128        assert_eq!(
1129            classes[0].worsened_metrics,
1130            [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1131        );
1132    }
1133
1134    #[test]
1135    fn same_named_findings_prefer_the_base_with_equal_line_count() {
1136        // Two same-valued findings; the second one grew in lines.
1137        let base = vec![
1138            with_lines(finding("run", 1, 17, 16), 10),
1139            with_lines(finding("run", 30, 17, 16), 40),
1140        ];
1141        let head = [
1142            with_lines(finding("run", 1, 17, 16), 40),
1143            with_lines(finding("run", 50, 17, 16), 25),
1144        ];
1145        let classes = attribution(base, &head);
1146        // The first head finding takes the 40-line base finding; the second one
1147        // takes the 10-line base finding and grew.
1148        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1149        assert_eq!(classes[1].attribution(), AuditFindingAttribution::Worsened);
1150    }
1151
1152    #[test]
1153    fn an_exact_match_of_a_later_head_is_not_taken_by_an_earlier_head() {
1154        // The 10-line function moved up and grew to 30 lines. The 40-line
1155        // function did not change, but it now comes later in line order.
1156        let base = vec![
1157            with_lines(finding("run", 1, 17, 16), 40),
1158            with_lines(finding("run", 50, 17, 16), 10),
1159        ];
1160        let head = [
1161            with_lines(finding("run", 1, 17, 16), 30),
1162            with_lines(finding("run", 20, 17, 16), 40),
1163        ];
1164        let classes = attribution(base, &head);
1165        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1166        assert_eq!(
1167            classes[0].worsened_metrics,
1168            [metric(WorsenedMetricKind::LineCount, 10.0, 30.0)]
1169        );
1170        assert_eq!(classes[1].attribution(), AuditFindingAttribution::Inherited);
1171        assert!(classes[1].worsened_metrics.is_empty());
1172    }
1173
1174    #[test]
1175    fn small_line_growth_is_not_worsened() {
1176        // A comment line or a formatter rewrap adds a few physical lines.
1177        let classes = attribution(
1178            vec![with_lines(finding("f", 1, 17, 16), 80)],
1179            &[with_lines(finding("f", 1, 17, 16), 84)],
1180        );
1181        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1182        assert!(classes[0].worsened_metrics.is_empty());
1183    }
1184
1185    #[test]
1186    fn line_growth_needs_five_lines_at_any_function_size() {
1187        // 4 lines are below the floor, also on a short function.
1188        let short = attribution(
1189            vec![with_lines(finding("f", 1, 17, 16), 20)],
1190            &[with_lines(finding("f", 1, 17, 16), 24)],
1191        );
1192        assert_eq!(short[0].attribution(), AuditFindingAttribution::Inherited);
1193        let grown = attribution(
1194            vec![with_lines(finding("f", 1, 17, 16), 20)],
1195            &[with_lines(finding("f", 1, 17, 16), 25)],
1196        );
1197        assert_eq!(grown[0].attribution(), AuditFindingAttribution::Worsened);
1198        // The floor does not scale: 9 lines on a 300-line function count.
1199        let long = attribution(
1200            vec![with_lines(finding("f", 1, 17, 16), 300)],
1201            &[with_lines(finding("f", 1, 17, 16), 309)],
1202        );
1203        assert_eq!(long[0].attribution(), AuditFindingAttribution::Worsened);
1204    }
1205
1206    #[test]
1207    fn a_base_with_the_same_values_keeps_the_finding_inherited() {
1208        let primary = baseline(vec![with_lines(finding("f", 1, 17, 16), 20)]);
1209        let merged = baseline(vec![with_lines(finding("f", 1, 17, 16), 60)]);
1210        let head = [with_lines(finding("f", 1, 17, 16), 60)];
1211        let classes =
1212            classify_complexity_attribution_against_all(&head, &root(), [&primary, &merged]);
1213        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1214        let classes = classify_complexity_attribution_against_all(&head, &root(), [&primary]);
1215        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1216    }
1217
1218    #[test]
1219    fn rename_moves_the_base_findings() {
1220        let base = baseline(vec![finding("f", 1, 17, 16)]);
1221        let renames =
1222            FxHashMap::from_iter([("src/index.js".to_string(), "src/moved.js".to_string())]);
1223        let remapped = remap_complexity_baseline_for_renames(base, &renames);
1224        assert!(remapped.contains_key("complexity:src/moved.js:f"));
1225        assert!(!remapped.contains_key("complexity:src/index.js:f"));
1226    }
1227
1228    #[test]
1229    fn ledger_keys_count_same_named_findings_separately() {
1230        let keys = complexity_ledger_keys(
1231            &[finding("run", 1, 17, 16), finding("run", 30, 17, 16)],
1232            &root(),
1233        );
1234        assert_eq!(
1235            keys,
1236            [
1237                "complexity:src/index.js:run",
1238                "complexity:src/index.js:run#2"
1239            ]
1240        );
1241    }
1242}