Skip to main content

fallow_api/audit_run/
snapshot.rs

1//! The attribution key snapshot of one audit side, and the rules that make a
2//! base snapshot comparable with the head run.
3
4use std::path::Path;
5
6use fallow_engine::changed_files::RenamedFile;
7use rustc_hash::{FxHashMap, FxHashSet};
8
9use super::AuditAnalysesView;
10use crate::AuditProgrammaticKeySnapshot;
11use crate::audit_keys::{
12    ComplexityBaseline, complexity_baseline, complexity_baseline_keys, dead_code_keys,
13    relative_key_path, remap_complexity_baseline_for_renames, remap_keys_for_renames, styling_keys,
14};
15use crate::review_deltas::{boundary_edge_keys, cycle_keys};
16
17/// Attribution keys of one audit side (the base commit, or the head run when
18/// the base pass is skipped).
19///
20/// Every key set is root-relative, so a base snapshot taken in a temporary
21/// worktree joins the head run by key.
22#[derive(Debug, Clone, Default)]
23pub struct AuditKeySnapshot {
24    /// Semantic identity of a type-aware dead-code pass, `None` for a
25    /// syntactic pass.
26    pub type_aware_identity: Option<fallow_types::semantic::SemanticAnalysisIdentity>,
27    /// Sorted reasons and omissions of the semantic queries that did not
28    /// complete. Two sides with different gaps cannot compare semantic keys.
29    pub type_aware_gap_signature: Vec<String>,
30    /// Dead-code keys captured before type-aware refinement. `None` when the
31    /// pass ran without type-aware analysis (then `dead_code` is already
32    /// syntactic). The degraded attribution path compares these.
33    pub syntactic_dead_code: Option<FxHashSet<String>>,
34    /// Dead-code keys.
35    pub dead_code: FxHashSet<String>,
36    /// Complexity findings by identity key, with their metric values. The
37    /// new-only gate compares the metric values of matched findings.
38    pub health: ComplexityBaseline,
39    /// Styling keys.
40    pub styling: FxHashSet<String>,
41    /// Clone-group keys.
42    pub dupes: FxHashSet<String>,
43    /// Cross-zone boundary edge keys (`<from_zone>->-<to_zone>`), one for each
44    /// zone pair.
45    pub boundary_edges: FxHashSet<String>,
46    /// Canonical circular-dependency keys.
47    pub cycles: FxHashSet<String>,
48    /// Exports-aware public-export keys (`<rel_path>::<name>`). Empty unless
49    /// the surface computed them from the retained module graph.
50    pub public_api: FxHashSet<String>,
51    /// Branching totals per root-relative path. Threshold-blind and
52    /// suppression-blind, so a threshold override or an ignore comment cannot
53    /// move the head-versus-base comparison.
54    pub branching: FxHashMap<String, fallow_types::extract::FileBranching>,
55}
56
57impl AuditKeySnapshot {
58    /// Take the attribution keys of one set of analyses.
59    #[must_use]
60    pub fn from_view(view: &AuditAnalysesView<'_>) -> Self {
61        let mut snapshot = Self::default();
62        if let Some(dead_code) = view.dead_code.as_ref() {
63            snapshot.type_aware_identity =
64                dead_code.type_aware.and_then(|meta| meta.identity.clone());
65            snapshot.type_aware_gap_signature = dead_code
66                .type_aware
67                .map_or_else(Vec::new, type_aware_gap_signature);
68            snapshot.syntactic_dead_code = dead_code.syntactic_keys.cloned();
69            snapshot.dead_code = dead_code_keys(dead_code.results, dead_code.root);
70            snapshot.boundary_edges = boundary_edge_keys(&dead_code.results.boundary_violations);
71            snapshot.cycles = cycle_keys(&dead_code.results.circular_dependencies, dead_code.root);
72            snapshot.public_api = dead_code.public_api.cloned().unwrap_or_default();
73        }
74        if let Some(health) = view.health.as_ref() {
75            snapshot.health = complexity_baseline(health.report, health.root);
76            snapshot.styling = styling_keys(health.report, health.root);
77            snapshot.branching = health.branching.map_or_else(FxHashMap::default, |by_file| {
78                branching_keys(by_file, health.root)
79            });
80        }
81        if let Some(duplication) = view.duplication.as_ref() {
82            snapshot.dupes = duplication
83                .clone_groups
84                .iter()
85                .map(|group| crate::audit_keys::dupe_group_key(group, duplication.root))
86                .collect();
87        }
88        snapshot
89    }
90
91    /// Relocate the keys of renamed files onto their head paths.
92    ///
93    /// Applies to every path-keyed family (dead code, complexity, styling,
94    /// duplication, cycles, public API, branching). Boundary-edge keys are
95    /// zone-pair keys without a path, and the type-aware identity has no path,
96    /// so they stay as they are. The syntactic dead-code keys of the degraded
97    /// type-aware path also stay as they are.
98    pub fn remap_for_renames(&mut self, renames: &[RenamedFile], root: &Path) {
99        let rename_map: FxHashMap<String, String> = renames
100            .iter()
101            .filter_map(|rename| {
102                let from = relative_key_path(&rename.from, root);
103                let to = relative_key_path(&rename.to, root);
104                (from != to).then_some((from, to))
105            })
106            .collect();
107        if rename_map.is_empty() {
108            return;
109        }
110        self.dead_code = remap_keys_for_renames(&self.dead_code, &rename_map);
111        self.health =
112            remap_complexity_baseline_for_renames(std::mem::take(&mut self.health), &rename_map);
113        self.styling = remap_keys_for_renames(&self.styling, &rename_map);
114        self.dupes = remap_keys_for_renames(&self.dupes, &rename_map);
115        self.cycles = remap_keys_for_renames(&self.cycles, &rename_map);
116        self.public_api = remap_keys_for_renames(&self.public_api, &rename_map);
117        // The branching payload is keyed by a bare path, not by an opaque key
118        // string, so it needs its own remap.
119        self.branching = self
120            .branching
121            .drain()
122            .map(|(path, totals)| match rename_map.get(&path) {
123                Some(renamed) => (renamed.clone(), totals),
124                None => (path, totals),
125            })
126            .collect();
127    }
128
129    /// The public key snapshot of the programmatic audit output. Its health
130    /// set also holds the styling keys.
131    #[must_use]
132    pub fn to_programmatic(&self) -> AuditProgrammaticKeySnapshot {
133        let mut health = complexity_baseline_keys(&self.health);
134        health.extend(self.styling.iter().cloned());
135        AuditProgrammaticKeySnapshot {
136            dead_code: self.dead_code.clone(),
137            health,
138            dupes: self.dupes.clone(),
139        }
140    }
141}
142
143/// Re-key absolute branching paths into the root-relative key space of the
144/// audit, so base and head entries join and the rename remap can move them.
145#[must_use]
146pub fn branching_keys(
147    by_file: &fallow_engine::health::BranchingByFile,
148    root: &Path,
149) -> FxHashMap<String, fallow_types::extract::FileBranching> {
150    by_file
151        .iter()
152        .map(|(path, totals)| (relative_key_path(path, root), *totals))
153        .collect()
154}
155
156/// Why type-aware base and head attribution cannot be compared directly, or
157/// `None` when the comparison is sound (fully syntactic runs included).
158///
159/// With a reason, the audit does not fail. It compares the syntactic key sets
160/// that each side captured before refinement, so `--gate new-only` keeps
161/// working when base and head resolve incompatible semantic identities.
162/// Compatibility comes from `SemanticAnalysisIdentity::incompatible_fields`,
163/// not raw equality: a deferred project-config hash and an absent identity
164/// both mean a side ran no semantic queries, which is compatible with any
165/// concrete identity on the other side (#2102).
166#[must_use]
167pub fn type_aware_attribution_degrade_reason(
168    base: Option<&AuditKeySnapshot>,
169    head: Option<&fallow_types::envelope::TypeAwareMeta>,
170) -> Option<&'static str> {
171    let base = base?;
172    let base_identity = base.type_aware_identity.as_ref();
173    let head_identity = head.and_then(|meta| meta.identity.as_ref());
174    if let (Some(base_identity), Some(head_identity)) = (base_identity, head_identity)
175        && !base_identity.incompatible_fields(head_identity).is_empty()
176    {
177        return Some("their semantic analysis identities are incompatible");
178    }
179    if let Some(head) = head
180        && base.type_aware_gap_signature != type_aware_gap_signature(head)
181    {
182        return Some("their incomplete semantic query reasons or omissions differ");
183    }
184    None
185}
186
187/// The warning that an audit records when it degrades type-aware attribution
188/// for `reason`.
189#[must_use]
190pub fn type_aware_degrade_warning(reason: &str) -> String {
191    format!(
192        "audit compared base and head with syntactic attribution because {reason} \
193(usually a tsconfig or compiler-options change between base and head); \
194type-aware refinement still applies to head findings, and \
195semantic-only findings stay out of the new-only gate for this run; set \
196audit.typeAware: false or pass --no-type-aware to keep the gate syntactic"
197    )
198}
199
200/// Sorted reasons and omissions of the semantic queries that did not complete.
201#[must_use]
202pub fn type_aware_gap_signature(meta: &fallow_types::envelope::TypeAwareMeta) -> Vec<String> {
203    let mut signature = meta
204        .queries
205        .iter()
206        .filter(|query| query.status != fallow_types::semantic::SemanticCompleteness::Complete)
207        .map(|query| {
208            let mut omissions = query
209                .omissions
210                .iter()
211                .map(|omission| format!("{:?}:{}", omission.reason_code, omission.count))
212                .collect::<Vec<_>>();
213            omissions.sort();
214            format!(
215                "{:?}:{:?}:{}",
216                query.capability,
217                query.reason_code,
218                omissions.join(",")
219            )
220        })
221        .collect::<Vec<_>>();
222    signature.sort();
223    signature
224}