fallow-engine 3.48.0

Typed analysis engine facade for fallow consumers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#![allow(
    clippy::print_stderr,
    reason = "human stderr notes for snapshots and trends are preserved from the health pipeline"
)]

use fallow_config::ResolvedConfig;
use fallow_output::{FileHealthScore, HealthScore, HotspotEntry, HotspotSummary};

use crate::vital_signs;

use super::actions::active_health_coverage_model;
use super::filters::filter_large_functions_by_diff;
use super::large_functions::{LargeFunctionInput, collect_large_functions};
use super::scoring;
use super::{
    HealthError, HealthExecutionOptions, SubsetFilter, VitalSignsAndCountsInput,
    apply_duplication_metrics, compute_vital_signs_and_counts,
};

pub struct HealthVitalData {
    pub(crate) vital_signs: fallow_output::VitalSigns,
    /// Raw counts behind `vital_signs`, kept for the snapshot that the output
    /// stage saves after grouping.
    pub(crate) counts: fallow_output::VitalSignsCounts,
    pub(crate) health_score: Option<HealthScore>,
    pub(crate) health_trend: Option<fallow_output::HealthTrend>,
    /// The snapshot the project trend compared against. The group trend
    /// compares against the same snapshot.
    pub(crate) trend_baseline: Option<vital_signs::TrendBaseline>,
    pub(crate) large_functions: Vec<fallow_output::LargeFunctionEntry>,
}

pub struct HealthVitalDataInput<'a> {
    pub(crate) opts: &'a HealthExecutionOptions<'a>,
    pub(crate) modules: &'a [crate::source::ModuleInfo],
    pub(crate) file_paths:
        &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
    pub(crate) score_output: Option<&'a scoring::FileScoreOutput>,
    pub(crate) file_scores_slice: &'a [FileHealthScore],
    pub(crate) hotspots: &'a [HotspotEntry],
    pub(crate) dupes_report: Option<&'a crate::duplicates::DuplicationReport>,
    pub(crate) candidate_paths: &'a rustc_hash::FxHashSet<std::path::PathBuf>,
    pub(crate) total_files: usize,
    pub(crate) config: &'a ResolvedConfig,
    pub(crate) ignore_set: &'a globset::GlobSet,
    pub(crate) changed_files: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
    pub(crate) ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
    pub(crate) diff_index: Option<&'a fallow_output::DiffIndex>,
    pub(crate) needs_file_scores: bool,
    /// Run-wide override resolver from `prepare_health_core_sections`, reused
    /// for the large-function list so it shares the same ceilings as findings
    /// and file scoring instead of re-deriving them from raw config values.
    pub(crate) threshold_resolver: &'a super::threshold_overrides::ThresholdOverrideResolver,
}

/// Assign the prop-drilling chain count / max depth onto the vital signs. Prop
/// drilling is a whole-project graph signal (the chains live in AnalysisResults,
/// surfaced via FileScoreOutput); only populated when the opt-in `prop-drilling`
/// rule emitted chains, so the small capped penalty stays dormant by default.
fn apply_prop_drilling_metrics(
    vital_signs: &mut fallow_output::VitalSigns,
    score_output: &scoring::FileScoreOutput,
) {
    if score_output.prop_drilling_chains.is_empty() {
        return;
    }
    vital_signs.prop_drilling_chain_count =
        u32::try_from(score_output.prop_drilling_chains.len()).ok();
    vital_signs.prop_drilling_max_depth = score_output
        .prop_drilling_chains
        .iter()
        .map(|c| c.chain.depth)
        .max();
}

/// Assign the descriptive render fan-in blast-radius metric (p95 / high-pct / max
/// distinct parents plus a located top-N list) onto the vital signs. Aggregates
/// are precomputed in core and ride on FileScoreOutput; non-React runs leave the
/// fields `None` (skip_serializing_if), so the JSON contract is unchanged.
fn apply_render_fan_in_metrics(
    vital_signs: &mut fallow_output::VitalSigns,
    score_output: &scoring::FileScoreOutput,
    config: &ResolvedConfig,
) {
    let Some(metric) = score_output.render_fan_in.as_ref() else {
        return;
    };
    vital_signs.p95_render_fan_in = metric.p95_distinct_parents;
    vital_signs.render_fan_in_high_pct = metric.high_pct;
    // The public headline (`max_render_fan_in`) is the max DISTINCT-PARENTS:
    // honest blast radius = the most distinct render LOCATIONS any one
    // component is rendered from. `render_sites` (incl. repeats) is secondary.
    vital_signs.max_render_fan_in = metric.max_distinct_parents;

    // Located top-N list so a consumer sees WHICH component carries the
    // headline fan-in, not just the number. The core carrier is sorted by
    // (path, component) for run-stability and INCLUDES rendered-nowhere `0`
    // entries (for the percentile distribution), so re-sort by
    // distinct_parents (the honest headline axis) descending, tie-break on
    // render_sites descending, and drop the `0`-fan-in entries here. Final
    // tie-break on (path, component) so the cap is deterministic. Cap at a
    // small N.
    const MAX_TOP_RENDER_FAN_IN: usize = 20;
    let mut top: Vec<&fallow_types::results::RenderFanInComponent> = metric
        .per_component
        .iter()
        .filter(|c| c.distinct_parents > 0)
        .collect();
    top.sort_by(|a, b| {
        b.distinct_parents
            .cmp(&a.distinct_parents)
            .then_with(|| b.render_sites.cmp(&a.render_sites))
            .then_with(|| a.file.cmp(&b.file))
            .then_with(|| a.component.cmp(&b.component))
    });
    vital_signs.top_render_fan_in = top
        .into_iter()
        .take(MAX_TOP_RENDER_FAN_IN)
        .map(|c| fallow_output::RenderFanInTopComponent {
            component: c.component.clone(),
            path: c
                .file
                .strip_prefix(&config.root)
                .unwrap_or(&c.file)
                .to_path_buf(),
            render_sites: c.render_sites,
            distinct_parents: c.distinct_parents,
        })
        .collect();
}

/// Compute the scoped vital signs / counts for the candidate subset, then assign
/// the prop-drilling and render fan-in metrics onto the vital signs.
fn compute_scoped_vital_signs(
    input: &HealthVitalDataInput<'_>,
    total_files_scoped: usize,
    project_subset: &SubsetFilter<'_>,
) -> (fallow_output::VitalSigns, fallow_output::VitalSignsCounts) {
    let vital_signs_input = VitalSignsAndCountsInput {
        score_output: input.score_output,
        modules: input.modules,
        file_paths: input.file_paths,
        needs_file_scores: input.needs_file_scores,
        file_scores_slice: input.file_scores_slice,
        needs_hotspots: input.opts.hotspots || input.opts.targets,
        hotspots: input.hotspots,
        total_files: total_files_scoped,
        subset: project_subset,
    };
    let (mut vital_signs, counts) = compute_vital_signs_and_counts(&vital_signs_input);

    if let Some(score_output) = input.score_output {
        apply_prop_drilling_metrics(&mut vital_signs, score_output);
        apply_render_fan_in_metrics(&mut vital_signs, score_output, input.config);
    }
    (vital_signs, counts)
}

/// Persist the health snapshot when `--save-snapshot` was requested.
///
/// Runs in the output stage after grouping, so a grouped run stores its group
/// data in the same file. The trend baseline was loaded before this save, so
/// a trend never compares a run against its own snapshot.
pub(super) fn maybe_save_health_snapshot(
    input: &HealthSnapshotSaveInput<'_>,
) -> Result<(), HealthError> {
    if let Some(ref snapshot_path) = input.opts.save_snapshot {
        save_snapshot(SnapshotInput {
            opts: input.opts,
            snapshot_path,
            vital_signs: input.vital_signs,
            counts: input.counts,
            hotspot_summary: input.hotspot_summary,
            health_score: input.health_score,
            coverage_model: Some(active_health_coverage_model(input.has_istanbul_coverage)),
            groups: input.groups.clone(),
        })?;
    }
    Ok(())
}

/// Inputs for [`maybe_save_health_snapshot`].
pub(super) struct HealthSnapshotSaveInput<'a> {
    pub(super) opts: &'a HealthExecutionOptions<'a>,
    pub(super) vital_signs: &'a fallow_output::VitalSigns,
    pub(super) counts: &'a fallow_output::VitalSignsCounts,
    pub(super) health_score: Option<&'a HealthScore>,
    pub(super) hotspot_summary: Option<&'a HotspotSummary>,
    pub(super) has_istanbul_coverage: bool,
    pub(super) groups: Option<fallow_output::SnapshotGrouping>,
}

/// Whether the run asked for a trend, through `--trend` or `--trend-from`.
const fn trend_requested(opts: &HealthExecutionOptions<'_>) -> bool {
    opts.trend || opts.trend_from.is_some()
}

pub fn prepare_health_vital_data(
    input: &HealthVitalDataInput<'_>,
) -> Result<HealthVitalData, HealthError> {
    let project_subset = if input.candidate_paths.len() == input.total_files {
        SubsetFilter::Full
    } else {
        SubsetFilter::Paths(input.candidate_paths)
    };
    let total_files_scoped = input.candidate_paths.len();
    let (mut vital_signs, mut counts) =
        compute_scoped_vital_signs(input, total_files_scoped, &project_subset);

    let health_score = compute_health_score_metrics(
        input.opts,
        input.dupes_report,
        &mut vital_signs,
        &mut counts,
        total_files_scoped,
    );
    let large_functions = collect_filtered_large_functions(FilteredLargeFunctionInput {
        vital_signs: &vital_signs,
        modules: input.modules,
        file_paths: input.file_paths,
        config: input.config,
        ignore_set: input.ignore_set,
        changed_files: input.changed_files,
        ws_roots: input.ws_roots,
        diff_index: input.diff_index,
        threshold_resolver: input.threshold_resolver,
    });
    let trend_baseline = load_health_trend_baseline(input.opts)?;
    let health_trend = trend_baseline.as_ref().map(|baseline| {
        vital_signs::compute_trend_against(
            &baseline.snapshot,
            baseline.snapshots_loaded,
            &vital_signs,
            &counts,
            health_score.as_ref(),
        )
    });

    Ok(HealthVitalData {
        vital_signs,
        counts,
        health_score,
        health_trend,
        trend_baseline,
        large_functions,
    })
}

fn compute_health_score_metrics(
    opts: &HealthExecutionOptions<'_>,
    dupes_report: Option<&crate::duplicates::DuplicationReport>,
    vital_signs: &mut fallow_output::VitalSigns,
    counts: &mut fallow_output::VitalSignsCounts,
    total_files_scoped: usize,
) -> Option<HealthScore> {
    if opts.score
        && let Some(report) = dupes_report
    {
        apply_duplication_metrics(vital_signs, counts, &report.stats);
    }
    opts.score
        .then(|| vital_signs::compute_health_score(vital_signs, total_files_scoped))
}

#[derive(Clone, Copy)]
struct FilteredLargeFunctionInput<'a> {
    vital_signs: &'a fallow_output::VitalSigns,
    modules: &'a [crate::source::ModuleInfo],
    file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
    config: &'a ResolvedConfig,
    ignore_set: &'a globset::GlobSet,
    changed_files: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
    ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
    diff_index: Option<&'a fallow_output::DiffIndex>,
    threshold_resolver: &'a super::threshold_overrides::ThresholdOverrideResolver,
}

fn collect_filtered_large_functions(
    input: FilteredLargeFunctionInput<'_>,
) -> Vec<fallow_output::LargeFunctionEntry> {
    let large_input = LargeFunctionInput {
        vital_signs: input.vital_signs,
        modules: input.modules,
        file_paths: input.file_paths,
        config_root: &input.config.root,
        ignore_set: input.ignore_set,
        changed_files: input.changed_files,
        ws_roots: input.ws_roots,
        thresholds: input.threshold_resolver,
    };
    let mut large_functions = collect_large_functions(&large_input);
    if let Some(diff_index) = input.diff_index {
        filter_large_functions_by_diff(&mut large_functions, diff_index, &input.config.root);
    }
    large_functions
}

/// Save a vital signs snapshot to disk if requested.
struct SnapshotInput<'a> {
    opts: &'a HealthExecutionOptions<'a>,
    snapshot_path: &'a std::path::Path,
    vital_signs: &'a fallow_output::VitalSigns,
    counts: &'a fallow_output::VitalSignsCounts,
    hotspot_summary: Option<&'a fallow_output::HotspotSummary>,
    health_score: Option<&'a fallow_output::HealthScore>,
    coverage_model: Option<fallow_output::CoverageModel>,
    groups: Option<fallow_output::SnapshotGrouping>,
}

fn save_snapshot(input: SnapshotInput<'_>) -> Result<(), HealthError> {
    let shallow = input.hotspot_summary.is_some_and(|s| s.shallow_clone);
    let mut snapshot = vital_signs::build_snapshot(
        input.vital_signs.clone(),
        input.counts.clone(),
        input.opts.root,
        shallow,
        input.health_score,
        input.coverage_model,
        input.opts.analysis_identity.clone(),
    );
    snapshot.groups = input.groups;
    let explicit = if input.snapshot_path.as_os_str().is_empty() {
        None
    } else {
        Some(input.snapshot_path)
    };
    match vital_signs::save_snapshot(&snapshot, input.opts.root, explicit) {
        Ok(saved_path) => {
            if !input.opts.quiet {
                eprintln!("Saved vital signs snapshot to {}", saved_path.display());
            }
            Ok(())
        }
        Err(e) => Err(HealthError::message(e, 2)),
    }
}

/// Load the trend baseline when a trend was requested.
///
/// The project trend and the group trend both compare against the result.
fn load_health_trend_baseline(
    opts: &HealthExecutionOptions<'_>,
) -> Result<Option<vital_signs::TrendBaseline>, HealthError> {
    if !trend_requested(opts) {
        return Ok(None);
    }
    if opts.changed_since.is_some() && !opts.quiet {
        eprintln!(
            "warning: --trend comparison may be inaccurate with --changed-since; \
             snapshots are typically from full-project runs"
        );
    }
    let baseline = vital_signs::load_trend_baseline(opts.root, opts.trend_from)
        .map_err(|message| HealthError::message(message, 2))?;
    let Some(baseline) = baseline else {
        if !opts.quiet {
            eprintln!(
                "No snapshots found. Run `fallow health --save-snapshot` to save a \
                 baseline, then use --trend on subsequent runs to track progress."
            );
        }
        return Ok(None);
    };
    let incompatible = baseline
        .snapshot
        .analysis_identity
        .incompatible_fields(&opts.analysis_identity);
    if !incompatible.is_empty() {
        return Err(HealthError::message(
            format!(
                "health trend snapshot has an incompatible analysis identity ({}). {}",
                incompatible.join(", "),
                trend_snapshot_repair(opts),
            ),
            2,
        ));
    }
    Ok(Some(baseline))
}

fn trend_snapshot_repair(opts: &HealthExecutionOptions<'_>) -> String {
    use crate::shell_quote::shell_quote;
    use crate::write_guard::{WriteScope, shared_dirs};
    use fallow_types::semantic::SemanticAnalysisMode;

    let mode = match opts.analysis_identity.mode {
        SemanticAnalysisMode::Syntactic => "--no-type-aware",
        SemanticAnalysisMode::TypeAware => "--type-aware",
    };
    let root = shell_quote(&opts.root.to_string_lossy());
    let health = format!("fallow health --root {root} {mode}");
    let mut save = format!("{health} --save-snapshot");
    if let Some(path) = opts.trend_from {
        let allowed = std::env::current_dir().is_ok_and(|cwd| {
            WriteScope::new(opts.root, &cwd, shared_dirs())
                .is_ok_and(|scope| scope.check("--save-snapshot", path, &cwd).is_none())
        });
        if !allowed {
            return format!(
                "Save a snapshot in the project with `{save}`. Then compare with `{health} --trend`. Use the same analysis options for both commands."
            );
        }
        let path = path.to_string_lossy();
        save.push(if path.starts_with('-') { '=' } else { ' ' });
        save.push_str(&shell_quote(&path));
    }
    format!("Regenerate the snapshot with `{save}` using the same analysis options.")
}