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