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, DeadCodeView};
10use crate::AuditProgrammaticKeySnapshot;
11use crate::audit_keys::{
12    ComplexityBaseline, collection_keys, complexity_baseline, complexity_baseline_keys,
13    dead_code_audit_ledger, dead_code_keys, relative_key_path,
14    remap_complexity_baseline_for_renames, remap_keys_for_renames, styling_keys,
15};
16use crate::review_deltas::{boundary_edge_keys, cycle_keys};
17
18/// Attribution keys of one audit side (the base commit, or the head run when
19/// the base pass is skipped).
20///
21/// Every key set is root-relative, so a base snapshot taken in a temporary
22/// worktree joins the head run by key.
23#[derive(Debug, Clone, Default)]
24pub struct AuditKeySnapshot {
25    /// Semantic identity of a type-aware dead-code pass, `None` for a
26    /// syntactic pass.
27    pub type_aware_identity: Option<fallow_types::semantic::SemanticAnalysisIdentity>,
28    /// Sorted reasons and omissions of the semantic queries that did not
29    /// complete. Two sides with different gaps cannot compare semantic keys.
30    pub type_aware_gap_signature: Vec<String>,
31    /// Dead-code keys captured before type-aware refinement. `None` when the
32    /// pass ran without type-aware analysis (then `dead_code` is already
33    /// syntactic). The degraded attribution path compares these.
34    pub syntactic_dead_code: Option<FxHashSet<String>>,
35    /// Dead-code keys.
36    pub dead_code: FxHashSet<String>,
37    /// Dead-code collections, by JSON key, that this side did not report
38    /// because it could not prove their findings (see
39    /// [`fallow_engine::unprovable::unprovable_dead_code_collections`]). A
40    /// head finding of such a collection is inherited.
41    pub unprovable_dead_code: FxHashSet<String>,
42    /// Complexity findings by identity key, with their metric values. The
43    /// new-only gate compares the metric values of matched findings.
44    pub health: ComplexityBaseline,
45    /// Styling keys.
46    pub styling: FxHashSet<String>,
47    /// Clone-group keys.
48    pub dupes: FxHashSet<String>,
49    /// Instance locations of the clone groups, for the `diverged-clone-sibling`
50    /// rule. The paths stay base paths: the rename remap does not move them.
51    pub dupe_groups: Vec<crate::diff_risk::clones::BaseCloneGroup>,
52    /// Cross-zone boundary edge keys (`<from_zone>->-<to_zone>`), one for each
53    /// zone pair.
54    pub boundary_edges: FxHashSet<String>,
55    /// Canonical circular-dependency keys.
56    pub cycles: FxHashSet<String>,
57    /// Exports-aware public-export keys (`<rel_path>::<name>`). Empty unless
58    /// the surface computed them from the retained module graph.
59    pub public_api: FxHashSet<String>,
60    /// Branching totals per root-relative path. Threshold-blind and
61    /// suppression-blind, so a threshold override or an ignore comment cannot
62    /// move the head-versus-base comparison.
63    pub branching: FxHashMap<String, fallow_types::extract::FileBranching>,
64    /// Complexity findings of the inherited bases (see
65    /// [`AuditKeySnapshot::absorb_inherited`]). A head finding is introduced
66    /// only when it is introduced against `health` and against each of these.
67    pub inherited_health: Vec<ComplexityBaseline>,
68    /// Keys of the unused files and unused exports that the base reports under
69    /// the config of the base commit. The other key sets come from a base pass
70    /// with the head config, so a rule that the change turns on does not make
71    /// old findings look new. That pass cannot see a file that a config change
72    /// made unreachable, for example a removed entry point. The set also holds
73    /// the unused code of the base that the base config ignores, because that
74    /// config cannot prove that such code was in use. `None` when the change
75    /// did not touch the config, or when the base config turns either rule off.
76    pub own_config_unused_code: Option<FxHashSet<String>>,
77}
78
79impl AuditKeySnapshot {
80    /// Take the attribution keys of one set of analyses.
81    #[must_use]
82    pub fn from_view(view: &AuditAnalysesView<'_>) -> Self {
83        let mut snapshot = Self::default();
84        if let Some(dead_code) = view.dead_code.as_ref() {
85            snapshot.type_aware_identity =
86                dead_code.type_aware.and_then(|meta| meta.identity.clone());
87            snapshot.type_aware_gap_signature = dead_code
88                .type_aware
89                .map_or_else(Vec::new, type_aware_gap_signature);
90            snapshot.syntactic_dead_code = dead_code.syntactic_keys.cloned();
91            snapshot.dead_code = dead_code_keys(dead_code.results, dead_code.root);
92            snapshot.unprovable_dead_code =
93                fallow_engine::unprovable::unprovable_dead_code_collections(dead_code.config)
94                    .into_iter()
95                    .map(str::to_owned)
96                    .collect();
97            snapshot.boundary_edges = boundary_edge_keys(&dead_code.results.boundary_violations);
98            snapshot.cycles = cycle_keys(&dead_code.results.circular_dependencies, dead_code.root);
99            snapshot.public_api = dead_code.public_api.cloned().unwrap_or_default();
100            snapshot.own_config_unused_code = dead_code.own_config_unused_code.cloned();
101        }
102        if let Some(health) = view.health.as_ref() {
103            snapshot.health = complexity_baseline(health.report, health.root);
104            snapshot.styling = styling_keys(health.report, health.root);
105            snapshot.branching = health.branching.map_or_else(FxHashMap::default, |by_file| {
106                branching_keys(by_file, health.root)
107            });
108        }
109        if let Some(duplication) = view.duplication.as_ref() {
110            snapshot.dupes = duplication
111                .clone_groups
112                .iter()
113                .map(|group| crate::audit_keys::dupe_group_key(group, duplication.root))
114                .collect();
115            snapshot.dupe_groups = duplication
116                .clone_groups
117                .iter()
118                .map(|group| crate::diff_risk::clones::BaseCloneGroup {
119                    instances: crate::diff_risk::clone_spans(group, duplication.root),
120                })
121                .collect();
122        }
123        snapshot
124    }
125
126    /// Whether this side reports the dead-code finding with `key`, in the
127    /// refined or in the syntactic key set.
128    #[must_use]
129    pub fn reports_dead_code(&self, key: &str) -> bool {
130        self.dead_code.contains(key)
131            || self
132                .syntactic_dead_code
133                .as_ref()
134                .is_some_and(|syntactic| syntactic.contains(key))
135    }
136
137    /// Remove the key of each head unused file and unused export that this
138    /// side does not report under the config of the base commit.
139    ///
140    /// The change touched the config, and the old config used that code (for
141    /// example as an entry point), so the head finding is introduced.
142    pub fn forget_unused_code_used_under_own_config(&mut self, head: &DeadCodeView<'_>) {
143        let Some(own) = self.own_config_unused_code.as_ref() else {
144            return;
145        };
146        let head_keys = collection_keys(&head.results.unused_files, head.root)
147            .into_iter()
148            .chain(collection_keys(&head.results.unused_exports, head.root));
149        for key in head_keys.filter(|key| !own.contains(key)) {
150            self.dead_code.remove(&key);
151            if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
152                syntactic.remove(&key);
153            }
154        }
155    }
156
157    /// Treat the findings of an inherited base as inherited too.
158    ///
159    /// An inherited base is a commit of the default branch that the change
160    /// merged. A key set takes the union, so a key that either side has is not
161    /// introduced. Complexity findings keep one baseline per side, because
162    /// their match rule pairs each base finding with at most one head finding.
163    /// The clone locations, the branching totals and the type-aware identity
164    /// stay those of the primary base. When the type-aware identity or the
165    /// query gaps differ, the refined dead-code keys stay out. `inherited`
166    /// must already use head paths.
167    pub fn absorb_inherited(&mut self, inherited: Self) {
168        let inherited_syntactic = inherited
169            .syntactic_dead_code
170            .unwrap_or_else(|| inherited.dead_code.clone());
171        if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
172            syntactic.extend(inherited_syntactic);
173        }
174        // Without its own config keys, the inherited base used the head config
175        // as its own, so its dead-code keys are the evidence.
176        if let Some(own) = self.own_config_unused_code.as_mut() {
177            own.extend(
178                inherited
179                    .own_config_unused_code
180                    .unwrap_or_else(|| inherited.dead_code.clone()),
181            );
182        }
183        // Refined keys of another semantic identity do not compare with the
184        // keys of this side, so they could hide a real finding.
185        if self.type_aware_identity == inherited.type_aware_identity
186            && self.type_aware_gap_signature == inherited.type_aware_gap_signature
187        {
188            self.dead_code.extend(inherited.dead_code);
189        }
190        self.unprovable_dead_code
191            .extend(inherited.unprovable_dead_code);
192        self.styling.extend(inherited.styling);
193        self.dupes.extend(inherited.dupes);
194        self.boundary_edges.extend(inherited.boundary_edges);
195        self.cycles.extend(inherited.cycles);
196        self.public_api.extend(inherited.public_api);
197        self.inherited_health.push(inherited.health);
198        self.inherited_health.extend(inherited.inherited_health);
199    }
200
201    /// Treat the head findings of each collection that this side could not
202    /// prove as inherited.
203    ///
204    /// The base snapshot is a checkout of committed files. A gitignored
205    /// workspace member (a cloned sub-repository) is missing there, so the
206    /// base does not report a class that the head reports. The keys of those
207    /// head findings join the dead-code key sets, so every surface that
208    /// compares keys (verdict, attribution counts, `introduced` flags) reads
209    /// them as inherited.
210    pub fn inherit_unprovable_dead_code(&mut self, head: &DeadCodeView<'_>) {
211        if self.unprovable_dead_code.is_empty() {
212            return;
213        }
214        let ledger = dead_code_audit_ledger(head.results, head.root, head.config, None);
215        let keys: Vec<String> = ledger
216            .records()
217            .iter()
218            .filter(|record| self.unprovable_dead_code.contains(record.collection))
219            .map(|record| record.stable_key.clone())
220            .collect();
221        if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
222            syntactic.extend(keys.iter().cloned());
223        }
224        self.dead_code.extend(keys);
225    }
226
227    /// Relocate the keys of renamed files onto their head paths.
228    ///
229    /// Applies to every path-keyed family (dead code, complexity, styling,
230    /// duplication, cycles, public API, branching). Boundary-edge keys are
231    /// zone-pair keys without a path, and the type-aware identity has no path,
232    /// so they stay as they are. The syntactic dead-code keys of the degraded
233    /// type-aware path also stay as they are.
234    pub fn remap_for_renames(&mut self, renames: &[RenamedFile], root: &Path) {
235        let rename_map: FxHashMap<String, String> = renames
236            .iter()
237            .filter_map(|rename| {
238                let from = relative_key_path(&rename.from, root);
239                let to = relative_key_path(&rename.to, root);
240                (from != to).then_some((from, to))
241            })
242            .collect();
243        if rename_map.is_empty() {
244            return;
245        }
246        self.dead_code = remap_keys_for_renames(&self.dead_code, &rename_map);
247        if let Some(own) = self.own_config_unused_code.as_mut() {
248            *own = remap_keys_for_renames(own, &rename_map);
249        }
250        self.health =
251            remap_complexity_baseline_for_renames(std::mem::take(&mut self.health), &rename_map);
252        self.styling = remap_keys_for_renames(&self.styling, &rename_map);
253        self.dupes = remap_keys_for_renames(&self.dupes, &rename_map);
254        self.cycles = remap_keys_for_renames(&self.cycles, &rename_map);
255        self.public_api = remap_keys_for_renames(&self.public_api, &rename_map);
256        // The branching payload is keyed by a bare path, not by an opaque key
257        // string, so it needs its own remap.
258        self.branching = self
259            .branching
260            .drain()
261            .map(|(path, totals)| match rename_map.get(&path) {
262                Some(renamed) => (renamed.clone(), totals),
263                None => (path, totals),
264            })
265            .collect();
266    }
267
268    /// The public key snapshot of the programmatic audit output. Its health
269    /// set also holds the styling keys.
270    #[must_use]
271    pub fn to_programmatic(&self) -> AuditProgrammaticKeySnapshot {
272        let mut health = complexity_baseline_keys(&self.health);
273        health.extend(self.styling.iter().cloned());
274        AuditProgrammaticKeySnapshot {
275            dead_code: self.dead_code.clone(),
276            health,
277            dupes: self.dupes.clone(),
278        }
279    }
280}
281
282/// Re-key absolute branching paths into the root-relative key space of the
283/// audit, so base and head entries join and the rename remap can move them.
284#[must_use]
285pub fn branching_keys(
286    by_file: &fallow_engine::health::BranchingByFile,
287    root: &Path,
288) -> FxHashMap<String, fallow_types::extract::FileBranching> {
289    by_file
290        .iter()
291        .map(|(path, totals)| (relative_key_path(path, root), *totals))
292        .collect()
293}
294
295/// Why type-aware base and head attribution cannot be compared directly, or
296/// `None` when the comparison is sound (fully syntactic runs included).
297///
298/// With a reason, the audit does not fail. It compares the syntactic key sets
299/// that each side captured before refinement, so `--gate new-only` keeps
300/// working when base and head resolve incompatible semantic identities.
301/// Compatibility comes from `SemanticAnalysisIdentity::incompatible_fields`,
302/// not raw equality: a deferred project-config hash and an absent identity
303/// both mean a side ran no semantic queries, which is compatible with any
304/// concrete identity on the other side (#2102).
305#[must_use]
306pub fn type_aware_attribution_degrade_reason(
307    base: Option<&AuditKeySnapshot>,
308    head: Option<&fallow_types::envelope::TypeAwareMeta>,
309) -> Option<&'static str> {
310    let base = base?;
311    let base_identity = base.type_aware_identity.as_ref();
312    let head_identity = head.and_then(|meta| meta.identity.as_ref());
313    if let (Some(base_identity), Some(head_identity)) = (base_identity, head_identity)
314        && !base_identity.incompatible_fields(head_identity).is_empty()
315    {
316        return Some("their semantic analysis identities are incompatible");
317    }
318    if let Some(head) = head
319        && base.type_aware_gap_signature != type_aware_gap_signature(head)
320    {
321        return Some("their incomplete semantic query reasons or omissions differ");
322    }
323    None
324}
325
326/// The warning that an audit records when it degrades type-aware attribution
327/// for `reason`.
328#[must_use]
329pub fn type_aware_degrade_warning(reason: &str) -> String {
330    format!(
331        "audit compared base and head with syntactic attribution because {reason} \
332(usually a tsconfig or compiler-options change between base and head); \
333type-aware refinement still applies to head findings, and \
334semantic-only findings stay out of the new-only gate for this run; set \
335audit.typeAware: false or pass --no-type-aware to keep the gate syntactic"
336    )
337}
338
339/// Sorted reasons and omissions of the semantic queries that did not complete.
340#[must_use]
341pub fn type_aware_gap_signature(meta: &fallow_types::envelope::TypeAwareMeta) -> Vec<String> {
342    let mut signature = meta
343        .queries
344        .iter()
345        .filter(|query| query.status != fallow_types::semantic::SemanticCompleteness::Complete)
346        .map(|query| {
347            let mut omissions = query
348                .omissions
349                .iter()
350                .map(|omission| format!("{:?}:{}", omission.reason_code, omission.count))
351                .collect::<Vec<_>>();
352            omissions.sort();
353            format!(
354                "{:?}:{:?}:{}",
355                query.capability,
356                query.reason_code,
357                omissions.join(",")
358            )
359        })
360        .collect::<Vec<_>>();
361    signature.sort();
362    signature
363}