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