Skip to main content

fallow_engine/
flag_retirement.rs

1//! Per-flag retirement report for `fallow flags --retirement`.
2//!
3//! The per-site flag findings group into one row per flag identity. Each
4//! detector adds a reason and its evidence to a row. The report is advisory:
5//! every action is `auto_fixable: false`, and nothing here removes code.
6
7use std::path::{Path, PathBuf};
8
9use fallow_config::WorkspaceInfo;
10use fallow_types::envelope::RegressionStatus;
11use fallow_types::extract::FlagSiteFacts;
12use fallow_types::flag_retirement::{
13    FlagAgeGate, FlagAgeGateEntry, FlagAgeMode, FlagRetirementReport, FlagSiteRole,
14    RetirementAction, RetirementActionType, RetirementEvidence, RetirementFlag, RetirementFlagKind,
15    RetirementReason, RetirementSite, RetirementSummary,
16};
17use fallow_types::results::{FeatureFlag, FlagKind};
18use rustc_hash::FxHashMap;
19
20/// File-name markers of story files. A story renders a component in
21/// isolation, so a flag that only a story reads is not live in production.
22const STORY_FILE_MARKERS: &[&str] = &[".stories.", ".story."];
23
24/// Description of the one action on a retirement candidate.
25const REVIEW_DESCRIPTION: &str = "Review this flag for retirement. The evidence lists the reasons.";
26
27/// One site of a flag, before the sites group into rows.
28#[derive(Debug, Clone)]
29pub struct RetirementSiteInput {
30    /// Absolute path of the file.
31    pub path: PathBuf,
32    /// Flag identifier.
33    pub flag_name: String,
34    /// How the flag was detected.
35    pub kind: RetirementFlagKind,
36    /// SDK provider label, if known.
37    pub sdk_name: Option<String>,
38    /// 1-based line.
39    pub line: u32,
40    /// 0-based byte column.
41    pub col: u32,
42    /// What the site does with the flag.
43    pub role: FlagSiteRole,
44    /// Unused exports inside the block that the site guards.
45    pub guarded_dead_exports: Vec<String>,
46    /// Facts about the guard of the site.
47    pub facts: FlagSiteFacts,
48    /// The literal value of a `const` flag, on its definition site.
49    pub literal: Option<String>,
50    /// Why no code reads this definition, when that is known.
51    pub unread: Option<String>,
52}
53
54/// Flag facts that only the retirement report reads. The per-site
55/// `feature_flags[]` array does not carry them.
56#[derive(Debug, Default)]
57pub struct RetirementFacts {
58    /// Guard facts of each flag read, keyed by file, line and column.
59    pub(crate) site_facts: FxHashMap<(PathBuf, u32, u32), FlagSiteFacts>,
60    /// Sites that are not per-site flag findings: literal `const` flags
61    /// (a definition and the guard reads) and unused registry members.
62    pub(crate) constant_sites: Vec<RetirementSiteInput>,
63    /// Definition sites that no code reads, keyed by file, line and column,
64    /// with the reason.
65    pub(crate) unread_definitions: FxHashMap<(PathBuf, u32, u32), String>,
66}
67
68impl RetirementFacts {
69    /// Retirement sites for per-site flag findings, with their guard facts,
70    /// followed by the sites of literal `const` flags.
71    #[must_use]
72    pub fn sites_for(&self, flags: &[FeatureFlag]) -> Vec<RetirementSiteInput> {
73        flags
74            .iter()
75            .map(|flag| {
76                let mut site = RetirementSiteInput::from_feature_flag(flag);
77                let key = (flag.path.clone(), flag.line, flag.col);
78                if let Some(facts) = self.site_facts.get(&key) {
79                    site.facts = *facts;
80                    if facts.definition() {
81                        site.role = FlagSiteRole::Definition;
82                    }
83                }
84                site.unread = self.unread_definitions.get(&key).cloned();
85                site
86            })
87            .chain(self.constant_sites.iter().cloned())
88            .collect()
89    }
90}
91
92impl RetirementSiteInput {
93    /// The retirement site of a per-site flag finding, without guard facts.
94    #[must_use]
95    fn from_feature_flag(flag: &FeatureFlag) -> Self {
96        Self {
97            path: flag.path.clone(),
98            flag_name: flag.flag_name.clone(),
99            kind: retirement_kind(flag.kind),
100            sdk_name: flag.sdk_name.clone(),
101            line: flag.line,
102            col: flag.col,
103            role: FlagSiteRole::Read,
104            guarded_dead_exports: flag.guarded_dead_exports.clone(),
105            facts: FlagSiteFacts::default(),
106            literal: None,
107            unread: None,
108        }
109    }
110}
111
112const fn retirement_kind(kind: FlagKind) -> RetirementFlagKind {
113    match kind {
114        FlagKind::EnvironmentVariable => RetirementFlagKind::EnvironmentVariable,
115        FlagKind::SdkCall => RetirementFlagKind::SdkCall,
116        FlagKind::ConfigObject => RetirementFlagKind::ConfigObject,
117    }
118}
119
120/// How the report orders its rows.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
122pub enum RetirementSort {
123    /// Oldest flag first. Flags without an age come last.
124    #[default]
125    Age,
126    /// Fewest read sites first.
127    Sites,
128    /// Flag name, ascending.
129    Name,
130}
131
132/// Options that narrow and order the rows of the report.
133#[derive(Debug, Clone, Default)]
134pub struct RetirementOptions {
135    /// Row order.
136    pub sort: RetirementSort,
137    /// Keep only flags at least this many days old. A flag without an age
138    /// does not pass.
139    pub min_age_days: Option<u64>,
140    /// Keep only flags with at least one of these reasons. Empty keeps all.
141    pub reasons: Vec<RetirementReason>,
142    /// Keep only the first N rows after the sort.
143    pub top: Option<usize>,
144}
145
146/// Identity of a flag: detection kind, SDK provider, name and workspace.
147#[derive(Debug, Clone, PartialEq, Eq, Hash)]
148struct FlagKey {
149    kind: RetirementFlagKind,
150    sdk_name: Option<String>,
151    flag_name: String,
152    workspace: Option<String>,
153}
154
155/// Group flag sites into one row per flag and run the reason detectors.
156///
157/// `root` makes paths relative. `workspaces` adds the workspace root to the
158/// flag identity, so two packages that use the same flag name get two rows.
159/// Pass every site of the project: `in_scope` selects the sites the rows
160/// show, but the read reasons count the reads outside the scope too, so a
161/// `--changed-since` run does not call a widely read flag single-read.
162/// Rows come back sorted by name; [`finish_report`] applies the final order.
163#[must_use]
164pub(crate) fn aggregate_flags(
165    sites: Vec<RetirementSiteInput>,
166    root: &Path,
167    workspaces: &[WorkspaceInfo],
168    in_scope: &dyn Fn(&Path) -> bool,
169) -> Vec<RetirementFlag> {
170    let mut groups: FxHashMap<FlagKey, Vec<RetirementSiteInput>> = FxHashMap::default();
171    let owners = fallow_config::WorkspaceOwners::new(workspaces);
172    for site in sites {
173        let key = FlagKey {
174            kind: site.kind,
175            sdk_name: site.sdk_name.clone(),
176            flag_name: site.flag_name.clone(),
177            workspace: workspace_of(&site.path, root, workspaces, &owners),
178        };
179        groups.entry(key).or_default().push(site);
180    }
181    for inputs in groups.values_mut() {
182        inputs.sort_by(|a, b| {
183            a.path
184                .cmp(&b.path)
185                .then(a.line.cmp(&b.line))
186                .then(a.col.cmp(&b.col))
187                .then(a.role.cmp(&b.role))
188        });
189        inputs.dedup_by(|a, b| {
190            a.path == b.path && a.line == b.line && a.col == b.col && a.role == b.role
191        });
192    }
193    let reads = count_reads_across_workspaces(&groups, root);
194    let mut rows: Vec<RetirementFlag> = groups
195        .into_iter()
196        .filter_map(|(key, mut sites)| {
197            sites.retain(|site| in_scope(&site.path));
198            if sites.is_empty() {
199                return None;
200            }
201            let all = reads
202                .get(&(key.kind, key.sdk_name.clone(), key.flag_name.clone()))
203                .copied()
204                .unwrap_or_default();
205            Some(build_row(key, &sites, all, root))
206        })
207        .collect();
208    rows.sort_by(compare_identity);
209    rows
210}
211
212/// Read counts of a flag over every workspace.
213#[derive(Debug, Clone, Copy, Default)]
214struct ReadCounts {
215    reads: usize,
216    production_reads: usize,
217}
218
219/// A flag with the same kind, SDK and name in two workspaces gets two rows,
220/// but a read in one workspace still reads the flag of the other. The read
221/// reasons use these counts, so an end-to-end test package does not make a
222/// flag test-only.
223fn count_reads_across_workspaces(
224    groups: &FxHashMap<FlagKey, Vec<RetirementSiteInput>>,
225    root: &Path,
226) -> FxHashMap<(RetirementFlagKind, Option<String>, String), ReadCounts> {
227    let mut counts: FxHashMap<(RetirementFlagKind, Option<String>, String), ReadCounts> =
228        FxHashMap::default();
229    for (key, inputs) in groups {
230        let entry = counts
231            .entry((key.kind, key.sdk_name.clone(), key.flag_name.clone()))
232            .or_default();
233        for input in inputs
234            .iter()
235            .filter(|input| input.role == FlagSiteRole::Read)
236        {
237            entry.reads += 1;
238            if !is_test_or_story(root, &relative(&input.path, root)) {
239                entry.production_reads += 1;
240            }
241        }
242    }
243    counts
244}
245
246fn build_row(
247    key: FlagKey,
248    inputs: &[RetirementSiteInput],
249    all: ReadCounts,
250    root: &Path,
251) -> RetirementFlag {
252    let sites: Vec<RetirementSite> = inputs
253        .iter()
254        .map(|input| {
255            let path = relative(&input.path, root);
256            RetirementSite {
257                in_test: is_test_or_story(root, &path),
258                path,
259                line: input.line,
260                col: input.col,
261                role: input.role,
262            }
263        })
264        .collect();
265    let read_sites = sites
266        .iter()
267        .filter(|site| site.role == FlagSiteRole::Read)
268        .count();
269    let test_only = all.reads > 0 && all.production_reads == 0;
270
271    let mut row = RetirementFlag {
272        flag_name: key.flag_name,
273        kind: key.kind,
274        sdk_name: key.sdk_name,
275        workspace: key.workspace,
276        sites,
277        read_sites,
278        test_only,
279        first_seen: None,
280        oldest_surviving_site: None,
281        last_touched: None,
282        age_days: None,
283        reasons: Vec::new(),
284        evidence: Vec::new(),
285        actions: Vec::new(),
286        vendor: None,
287    };
288    detect_single_read_site(&mut row, all);
289    detect_test_only(&mut row, all);
290    detect_literal_constant(&mut row, inputs, root);
291    detect_guard_facts(&mut row, inputs, root);
292    detect_guards_dead_code(&mut row, inputs, root);
293    detect_defined_never_read(&mut row, inputs, all, root);
294    row
295}
296
297fn detect_defined_never_read(
298    row: &mut RetirementFlag,
299    inputs: &[RetirementSiteInput],
300    all: ReadCounts,
301    root: &Path,
302) {
303    if all.reads > 0 {
304        return;
305    }
306    for input in inputs {
307        let Some(detail) = &input.unread else {
308            continue;
309        };
310        add_reason(
311            row,
312            RetirementEvidence {
313                reason: RetirementReason::DefinedNeverRead,
314                path: relative(&input.path, root),
315                line: input.line,
316                detail: detail.clone(),
317            },
318        );
319    }
320}
321
322fn detect_literal_constant(row: &mut RetirementFlag, inputs: &[RetirementSiteInput], root: &Path) {
323    if row.kind != RetirementFlagKind::Constant {
324        return;
325    }
326    let definition = inputs.iter().find(|input| input.literal.is_some());
327    let Some(site) = definition.or_else(|| inputs.first()) else {
328        return;
329    };
330    let detail = site.literal.as_ref().map_or_else(
331        || "the flag is a const with a literal value".to_string(),
332        |value| format!("const {} = {value}", row.flag_name),
333    );
334    add_reason(
335        row,
336        RetirementEvidence {
337            reason: RetirementReason::LiteralConstant,
338            path: relative(&site.path, root),
339            line: site.line,
340            detail,
341        },
342    );
343}
344
345fn detect_guard_facts(row: &mut RetirementFlag, inputs: &[RetirementSiteInput], root: &Path) {
346    for input in inputs {
347        if input.facts.identical_branches() {
348            add_reason(
349                row,
350                RetirementEvidence {
351                    reason: RetirementReason::IdenticalBranches,
352                    path: relative(&input.path, root),
353                    line: input.line,
354                    detail: "both branches of the guard are the same code".to_string(),
355                },
356            );
357        }
358        if input.facts.empty_branch() {
359            add_reason(
360                row,
361                RetirementEvidence {
362                    reason: RetirementReason::EmptyBranch,
363                    path: relative(&input.path, root),
364                    line: input.line,
365                    detail: "no branch of the guard holds code".to_string(),
366                },
367            );
368        }
369    }
370}
371
372fn detect_single_read_site(row: &mut RetirementFlag, all: ReadCounts) {
373    if row.read_sites != 1 || all.reads != 1 {
374        return;
375    }
376    let Some(site) = row
377        .sites
378        .iter()
379        .find(|site| site.role == FlagSiteRole::Read)
380    else {
381        return;
382    };
383    let evidence = RetirementEvidence {
384        reason: RetirementReason::SingleReadSite,
385        path: site.path.clone(),
386        line: site.line,
387        detail: "the flag has one read site".to_string(),
388    };
389    add_reason(row, evidence);
390}
391
392fn detect_test_only(row: &mut RetirementFlag, all: ReadCounts) {
393    if !row.test_only {
394        return;
395    }
396    let Some(site) = row
397        .sites
398        .iter()
399        .find(|site| site.role == FlagSiteRole::Read)
400    else {
401        return;
402    };
403    let detail = if all.reads == 1 {
404        "the only read site is in a test, story or mock file".to_string()
405    } else {
406        format!(
407            "all {} read sites are in test, story or mock files",
408            all.reads
409        )
410    };
411    let evidence = RetirementEvidence {
412        reason: RetirementReason::TestOnly,
413        path: site.path.clone(),
414        line: site.line,
415        detail,
416    };
417    add_reason(row, evidence);
418}
419
420fn detect_guards_dead_code(row: &mut RetirementFlag, inputs: &[RetirementSiteInput], root: &Path) {
421    for input in inputs {
422        if input.guarded_dead_exports.is_empty() {
423            continue;
424        }
425        let evidence = RetirementEvidence {
426            reason: RetirementReason::GuardsDeadCode,
427            path: relative(&input.path, root),
428            line: input.line,
429            detail: format!(
430                "the guarded block holds unused exports: {}",
431                input.guarded_dead_exports.join(", ")
432            ),
433        };
434        add_reason(row, evidence);
435    }
436}
437
438/// Record a reason once and keep every piece of evidence for it.
439fn add_reason(row: &mut RetirementFlag, evidence: RetirementEvidence) {
440    if !row.reasons.contains(&evidence.reason) {
441        row.reasons.push(evidence.reason);
442    }
443    row.evidence.push(evidence);
444}
445
446/// Count, filter, order and limit the rows, and add the review action to
447/// each candidate.
448#[must_use]
449pub(crate) fn finish_report(
450    mut rows: Vec<RetirementFlag>,
451    age_mode: FlagAgeMode,
452    generated_at_clock: Option<String>,
453    options: &RetirementOptions,
454) -> FlagRetirementReport {
455    for row in &mut rows {
456        row.reasons
457            .sort_by_key(|reason| RetirementReason::ALL.iter().position(|r| r == reason));
458        row.evidence.sort_by(|a, b| {
459            reason_rank(a.reason)
460                .cmp(&reason_rank(b.reason))
461                .then(a.path.cmp(&b.path))
462                .then(a.line.cmp(&b.line))
463        });
464        if !row.reasons.is_empty() {
465            row.actions = vec![RetirementAction {
466                kind: RetirementActionType::ReviewRetirement,
467                auto_fixable: false,
468                description: REVIEW_DESCRIPTION.to_string(),
469            }];
470        }
471    }
472    let summary = summarize(&rows);
473    rows.retain(|row| passes_filters(row, options));
474    rows.sort_by(|a, b| compare_for_sort(a, b, options.sort));
475    if let Some(top) = options.top {
476        rows.truncate(top);
477    }
478    FlagRetirementReport {
479        generated_at_clock,
480        age_mode,
481        vendor_state: None,
482        summary,
483        regression: None,
484        max_flag_age: None,
485        flags: rows,
486    }
487}
488
489/// Why a `--max-flag-age` gate without git history did not run.
490pub(crate) const AGE_GATE_NO_HISTORY: &str =
491    "git history is not available (a shallow clone or no repository), so no flag age was measured";
492
493/// Why a `--max-flag-age` gate with the age mode `off` did not run.
494pub(crate) const AGE_GATE_AGE_OFF: &str = "the flag age mode is off, so no flag age was measured";
495
496/// The `--max-flag-age` verdict over every row in scope. Pass the rows
497/// before [`finish_report`] filters and limits them. `skip_reason` is set
498/// when no age was measured; the gate is then `skipped`, not passed.
499#[must_use]
500pub(crate) fn max_age_gate(
501    rows: &[RetirementFlag],
502    max_days: u64,
503    skip_reason: Option<&str>,
504) -> FlagAgeGate {
505    let unmeasured = rows
506        .iter()
507        .filter(|row| row.kind != RetirementFlagKind::VendorExport && row.age_days.is_none())
508        .count();
509    if let Some(reason) = skip_reason {
510        return FlagAgeGate {
511            status: RegressionStatus::Skipped,
512            max_days,
513            exceeded: false,
514            unmeasured,
515            reason: Some(reason.to_string()),
516            flags: Vec::new(),
517        };
518    }
519    let mut old: Vec<&RetirementFlag> = rows
520        .iter()
521        .filter(|row| row.age_days.is_some_and(|age| age > max_days))
522        .collect();
523    old.sort_by(|a, b| compare_for_sort(a, b, RetirementSort::Age));
524    let exceeded = !old.is_empty();
525    FlagAgeGate {
526        status: if exceeded {
527            RegressionStatus::Exceeded
528        } else {
529            RegressionStatus::Pass
530        },
531        max_days,
532        exceeded,
533        unmeasured,
534        reason: None,
535        flags: old
536            .into_iter()
537            .map(|row| FlagAgeGateEntry {
538                flag_name: row.flag_name.clone(),
539                kind: row.kind,
540                sdk_name: row.sdk_name.clone(),
541                workspace: row.workspace.clone(),
542                age_days: row.age_days.unwrap_or_default(),
543            })
544            .collect(),
545    }
546}
547
548fn reason_rank(reason: RetirementReason) -> usize {
549    RetirementReason::ALL
550        .iter()
551        .position(|r| *r == reason)
552        .unwrap_or(usize::MAX)
553}
554
555fn summarize(rows: &[RetirementFlag]) -> RetirementSummary {
556    let mut summary = RetirementSummary {
557        distinct_flags: rows
558            .iter()
559            .filter(|row| row.kind != RetirementFlagKind::VendorExport)
560            .count(),
561        ..RetirementSummary::default()
562    };
563    for row in rows {
564        if !row.reasons.is_empty() {
565            summary.candidates += 1;
566        }
567        for reason in &row.reasons {
568            *summary.by_reason.entry(*reason).or_default() += 1;
569        }
570    }
571    summary
572}
573
574fn passes_filters(row: &RetirementFlag, options: &RetirementOptions) -> bool {
575    if let Some(min_age) = options.min_age_days
576        && row.age_days.is_none_or(|age| age < min_age)
577    {
578        return false;
579    }
580    options.reasons.is_empty() || row.reasons.iter().any(|r| options.reasons.contains(r))
581}
582
583fn compare_for_sort(
584    a: &RetirementFlag,
585    b: &RetirementFlag,
586    sort: RetirementSort,
587) -> std::cmp::Ordering {
588    let primary = match sort {
589        // Oldest first; a flag without an age sorts after every aged flag.
590        RetirementSort::Age => match (a.age_days, b.age_days) {
591            (Some(x), Some(y)) => y.cmp(&x),
592            (Some(_), None) => std::cmp::Ordering::Less,
593            (None, Some(_)) => std::cmp::Ordering::Greater,
594            (None, None) => std::cmp::Ordering::Equal,
595        },
596        RetirementSort::Sites => a.read_sites.cmp(&b.read_sites),
597        RetirementSort::Name => std::cmp::Ordering::Equal,
598    };
599    primary.then_with(|| compare_identity(a, b))
600}
601
602fn compare_identity(a: &RetirementFlag, b: &RetirementFlag) -> std::cmp::Ordering {
603    a.flag_name
604        .cmp(&b.flag_name)
605        .then(a.kind.cmp(&b.kind))
606        .then(a.sdk_name.cmp(&b.sdk_name))
607        .then(a.workspace.cmp(&b.workspace))
608}
609
610/// Root-relative workspace path of the deepest workspace that holds `path`,
611/// or `None` for a file outside every workspace or a project without them.
612fn workspace_of(
613    path: &Path,
614    root: &Path,
615    workspaces: &[WorkspaceInfo],
616    owners: &fallow_config::WorkspaceOwners,
617) -> Option<String> {
618    owners
619        .owner_of(path)
620        .and_then(|index| workspaces.get(index))
621        .filter(|ws| ws.root != root)
622        .map(|ws| relative(&ws.root, root))
623}
624
625pub(crate) fn relative(path: &Path, root: &Path) -> String {
626    path.strip_prefix(root)
627        .unwrap_or(path)
628        .to_string_lossy()
629        .replace('\\', "/")
630}
631
632fn is_test_or_story(root: &Path, relative_path: &str) -> bool {
633    if crate::test_paths::is_test_path_str(root, relative_path) {
634        return true;
635    }
636    let file_name = relative_path.rsplit('/').next().unwrap_or(relative_path);
637    let lower = file_name.to_ascii_lowercase();
638    STORY_FILE_MARKERS
639        .iter()
640        .any(|marker| lower.contains(marker))
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    const ROOT: &str = "/repo";
648
649    fn site(name: &str, path: &str, line: u32) -> RetirementSiteInput {
650        RetirementSiteInput {
651            path: PathBuf::from(ROOT).join(path),
652            flag_name: name.to_string(),
653            kind: RetirementFlagKind::EnvironmentVariable,
654            sdk_name: None,
655            line,
656            col: 4,
657            role: FlagSiteRole::Read,
658            guarded_dead_exports: Vec::new(),
659            facts: FlagSiteFacts::default(),
660            literal: None,
661            unread: None,
662        }
663    }
664
665    fn sdk_site(name: &str, sdk: &str, path: &str, line: u32) -> RetirementSiteInput {
666        RetirementSiteInput {
667            kind: RetirementFlagKind::SdkCall,
668            sdk_name: Some(sdk.to_string()),
669            ..site(name, path, line)
670        }
671    }
672
673    fn rows(sites: Vec<RetirementSiteInput>) -> Vec<RetirementFlag> {
674        aggregate_flags(sites, Path::new(ROOT), &[], &|_| true)
675    }
676
677    fn row<'r>(rows: &'r [RetirementFlag], name: &str) -> &'r RetirementFlag {
678        rows.iter()
679            .find(|row| row.flag_name == name)
680            .unwrap_or_else(|| panic!("no row for {name}"))
681    }
682
683    #[test]
684    fn one_row_per_kind_sdk_and_name() {
685        let rows = rows(vec![
686            site("FEATURE_A", "src/a.ts", 1),
687            site("FEATURE_A", "src/b.ts", 2),
688            sdk_site("checkout", "LaunchDarkly", "src/a.ts", 3),
689            sdk_site("checkout", "Statsig", "src/a.ts", 4),
690            sdk_site("checkout", "LaunchDarkly", "src/c.ts", 5),
691        ]);
692        assert_eq!(rows.len(), 3);
693        assert_eq!(row(&rows, "FEATURE_A").read_sites, 2);
694        let launchdarkly = rows
695            .iter()
696            .find(|row| row.sdk_name.as_deref() == Some("LaunchDarkly"))
697            .expect("LaunchDarkly row");
698        assert_eq!(launchdarkly.read_sites, 2);
699        assert_eq!(launchdarkly.sites[0].path, "src/a.ts");
700        assert_eq!(launchdarkly.sites[1].path, "src/c.ts");
701    }
702
703    #[test]
704    fn workspace_root_is_part_of_the_identity() {
705        let workspaces = vec![
706            WorkspaceInfo {
707                root: PathBuf::from("/repo/packages/web"),
708                name: "web".to_string(),
709                is_internal_dependency: false,
710            },
711            WorkspaceInfo {
712                root: PathBuf::from("/repo/packages/api"),
713                name: "api".to_string(),
714                is_internal_dependency: false,
715            },
716        ];
717        let rows = aggregate_flags(
718            vec![
719                site("FEATURE_A", "packages/web/src/a.ts", 1),
720                site("FEATURE_A", "packages/api/src/a.ts", 1),
721                site("FEATURE_A", "scripts/a.ts", 1),
722            ],
723            Path::new(ROOT),
724            &workspaces,
725            &|_| true,
726        );
727        let workspaces: Vec<Option<&str>> = rows.iter().map(|r| r.workspace.as_deref()).collect();
728        assert_eq!(
729            workspaces,
730            vec![None, Some("packages/api"), Some("packages/web")]
731        );
732    }
733
734    #[test]
735    fn reads_in_other_workspaces_count_for_the_read_reasons() {
736        let workspaces = vec![
737            WorkspaceInfo {
738                root: PathBuf::from("/repo/packages/web"),
739                name: "web".to_string(),
740                is_internal_dependency: false,
741            },
742            WorkspaceInfo {
743                root: PathBuf::from("/repo/packages/e2e"),
744                name: "e2e".to_string(),
745                is_internal_dependency: false,
746            },
747        ];
748        let rows = aggregate_flags(
749            vec![
750                site("FEATURE_X", "packages/web/src/a.ts", 1),
751                site("FEATURE_X", "packages/e2e/a.spec.ts", 1),
752            ],
753            Path::new(ROOT),
754            &workspaces,
755            &|_| true,
756        );
757        assert_eq!(rows.len(), 2, "one row per workspace");
758        for row in &rows {
759            assert_eq!(row.read_sites, 1);
760            assert!(!row.test_only, "production code reads the flag: {row:?}");
761            assert!(row.reasons.is_empty(), "{row:?}");
762        }
763    }
764
765    #[test]
766    fn reads_outside_the_scope_count_for_the_read_reasons() {
767        let rows = aggregate_flags(
768            vec![
769                // One read in scope: without the out-of-scope read this row
770                // gets single-read-site.
771                site("FEATURE_ONE", "src/changed.ts", 1),
772                site("FEATURE_ONE", "src/third.ts", 1),
773                // One test read in scope: without the out-of-scope production
774                // read this row gets test-only.
775                site("FEATURE_TEST", "src/other.test.ts", 1),
776                site("FEATURE_TEST", "src/third.ts", 2),
777                site("FEATURE_OUT", "src/third.ts", 3),
778            ],
779            Path::new(ROOT),
780            &[],
781            &|path| path.ends_with("changed.ts") || path.ends_with("other.test.ts"),
782        );
783        let names: Vec<&str> = rows.iter().map(|r| r.flag_name.as_str()).collect();
784        assert_eq!(
785            names,
786            vec!["FEATURE_ONE", "FEATURE_TEST"],
787            "a flag with no site in scope has no row"
788        );
789        for row in &rows {
790            assert_eq!(row.read_sites, 1, "{row:?}");
791            assert!(!row.test_only, "{row:?}");
792            assert!(row.reasons.is_empty(), "{row:?}");
793        }
794    }
795
796    #[test]
797    fn single_read_site_needs_exactly_one_read() {
798        let rows = rows(vec![
799            site("FEATURE_ONE", "src/a.ts", 7),
800            site("FEATURE_TWO", "src/a.ts", 1),
801            site("FEATURE_TWO", "src/b.ts", 1),
802        ]);
803        let one = row(&rows, "FEATURE_ONE");
804        assert_eq!(one.reasons, vec![RetirementReason::SingleReadSite]);
805        assert_eq!(one.evidence[0].path, "src/a.ts");
806        assert_eq!(one.evidence[0].line, 7);
807        assert!(row(&rows, "FEATURE_TWO").reasons.is_empty());
808    }
809
810    #[test]
811    fn test_only_needs_every_read_in_test_story_or_mock_files() {
812        let rows = rows(vec![
813            site("FEATURE_T", "src/a.test.ts", 1),
814            site("FEATURE_T", "src/Button.stories.tsx", 1),
815            site("FEATURE_T", "src/__mocks__/flags.ts", 1),
816            site("FEATURE_MIXED", "src/a.test.ts", 1),
817            site("FEATURE_MIXED", "src/a.ts", 1),
818        ]);
819        let only = row(&rows, "FEATURE_T");
820        assert!(only.test_only);
821        let evidence = only
822            .evidence
823            .iter()
824            .find(|e| e.reason == RetirementReason::TestOnly)
825            .expect("test-only evidence");
826        assert_eq!(
827            evidence.detail,
828            "all 3 read sites are in test, story or mock files"
829        );
830        assert!(only.reasons.contains(&RetirementReason::TestOnly));
831        assert!(only.sites.iter().all(|s| s.in_test));
832        let mixed = row(&rows, "FEATURE_MIXED");
833        assert!(!mixed.test_only);
834        assert!(!mixed.reasons.contains(&RetirementReason::TestOnly));
835    }
836
837    #[test]
838    fn guards_dead_code_lists_the_unused_exports() {
839        let mut guarded = site("FEATURE_G", "src/a.ts", 3);
840        guarded.guarded_dead_exports = vec!["legacy".to_string(), "old".to_string()];
841        let rows = rows(vec![guarded, site("FEATURE_G", "src/b.ts", 9)]);
842        let row = row(&rows, "FEATURE_G");
843        assert_eq!(row.reasons, vec![RetirementReason::GuardsDeadCode]);
844        assert_eq!(
845            row.evidence[0].detail,
846            "the guarded block holds unused exports: legacy, old"
847        );
848    }
849
850    #[test]
851    fn guard_facts_become_reasons_with_one_evidence_per_site() {
852        let mut identical = site("FEATURE_I", "src/a.ts", 3);
853        identical.facts = FlagSiteFacts::default().with_identical_branches(true);
854        let mut empty = site("FEATURE_I", "src/b.ts", 8);
855        empty.facts = FlagSiteFacts::default().with_empty_branch(true);
856        let rows = rows(vec![identical, empty]);
857        let row = row(&rows, "FEATURE_I");
858        assert_eq!(
859            row.reasons,
860            vec![
861                RetirementReason::IdenticalBranches,
862                RetirementReason::EmptyBranch
863            ]
864        );
865        assert_eq!(row.evidence[0].path, "src/a.ts");
866        assert_eq!(row.evidence[1].path, "src/b.ts");
867    }
868
869    #[test]
870    fn a_constant_row_is_a_literal_constant_with_the_value_as_evidence() {
871        let definition = RetirementSiteInput {
872            kind: RetirementFlagKind::Constant,
873            role: FlagSiteRole::Definition,
874            literal: Some("true".to_string()),
875            ..site("FEATURE_C", "src/a.ts", 1)
876        };
877        let read = RetirementSiteInput {
878            kind: RetirementFlagKind::Constant,
879            ..site("FEATURE_C", "src/a.ts", 4)
880        };
881        let rows = rows(vec![definition, read]);
882        let row = row(&rows, "FEATURE_C");
883        assert_eq!(row.read_sites, 1, "the definition is not a read");
884        assert_eq!(
885            row.reasons,
886            vec![
887                RetirementReason::SingleReadSite,
888                RetirementReason::LiteralConstant
889            ]
890        );
891        let evidence = row
892            .evidence
893            .iter()
894            .find(|e| e.reason == RetirementReason::LiteralConstant)
895            .expect("evidence");
896        assert_eq!(evidence.detail, "const FEATURE_C = true");
897        assert_eq!(evidence.line, 1);
898    }
899
900    #[test]
901    fn an_unread_definition_is_defined_never_read_only_without_reads() {
902        let definition = RetirementSiteInput {
903            kind: RetirementFlagKind::SdkCall,
904            role: FlagSiteRole::Definition,
905            unread: Some("export `x` is unused".to_string()),
906            ..site("show-x", "src/flags.ts", 2)
907        };
908        let alone = rows(vec![definition.clone()]);
909        assert_eq!(alone[0].read_sites, 0);
910        assert_eq!(alone[0].reasons, vec![RetirementReason::DefinedNeverRead]);
911        assert_eq!(alone[0].evidence[0].detail, "export `x` is unused");
912
913        let read = RetirementSiteInput {
914            kind: RetirementFlagKind::SdkCall,
915            ..site("show-x", "src/page.ts", 9)
916        };
917        let with_read = rows(vec![definition, read]);
918        assert!(
919            !with_read[0]
920                .reasons
921                .contains(&RetirementReason::DefinedNeverRead)
922        );
923    }
924
925    #[test]
926    fn facts_attach_to_sites_by_file_line_and_column() {
927        let flag = FeatureFlag {
928            path: PathBuf::from("/repo/src/a.ts"),
929            flag_name: "FEATURE_A".to_string(),
930            kind: FlagKind::EnvironmentVariable,
931            confidence: fallow_types::results::FlagConfidence::High,
932            line: 3,
933            col: 6,
934            guard_span_start: None,
935            guard_span_end: None,
936            sdk_name: None,
937            guard_line_start: None,
938            guard_line_end: None,
939            guarded_dead_exports: Vec::new(),
940        };
941        let mut facts = RetirementFacts::default();
942        facts.site_facts.insert(
943            (PathBuf::from("/repo/src/a.ts"), 3, 6),
944            FlagSiteFacts::default().with_empty_branch(true),
945        );
946        let sites = facts.sites_for(std::slice::from_ref(&flag));
947        assert!(sites[0].facts.empty_branch());
948        let other = FeatureFlag { col: 7, ..flag };
949        assert!(!facts.sites_for(&[other])[0].facts.empty_branch());
950    }
951
952    fn aged(name: &str, age: Option<u64>, reads: usize) -> RetirementFlag {
953        let sites = (0..reads)
954            .map(|i| site(name, "src/a.ts", u32::try_from(i).unwrap_or(0) + 1))
955            .collect();
956        let mut row = rows(sites).remove(0);
957        row.age_days = age;
958        row
959    }
960
961    fn names(report: &FlagRetirementReport) -> Vec<&str> {
962        report.flags.iter().map(|r| r.flag_name.as_str()).collect()
963    }
964
965    #[test]
966    fn max_age_gate_lists_only_flags_older_than_the_limit() {
967        let rows = vec![
968            aged("FEATURE_B", Some(90), 2),
969            aged("FEATURE_A", None, 2),
970            aged("FEATURE_C", Some(300), 2),
971            aged("FEATURE_D", Some(91), 2),
972        ];
973        let gate = max_age_gate(&rows, 90, None);
974        assert!(gate.exceeded);
975        assert_eq!(gate.status, RegressionStatus::Exceeded);
976        assert_eq!(gate.unmeasured, 1, "FEATURE_A has no age");
977        let names: Vec<&str> = gate.flags.iter().map(|f| f.flag_name.as_str()).collect();
978        assert_eq!(
979            names,
980            vec!["FEATURE_C", "FEATURE_D"],
981            "oldest first; 90 is not over 90"
982        );
983        let passed = max_age_gate(&rows, 300, None);
984        assert!(!passed.exceeded);
985        assert_eq!(passed.status, RegressionStatus::Pass);
986    }
987
988    #[test]
989    fn max_age_gate_without_history_is_skipped_not_passed() {
990        let rows = vec![aged("FEATURE_A", None, 2), aged("FEATURE_B", None, 1)];
991        let gate = max_age_gate(&rows, 1, Some(AGE_GATE_NO_HISTORY));
992        assert_eq!(gate.status, RegressionStatus::Skipped);
993        assert!(!gate.exceeded);
994        assert_eq!(gate.unmeasured, 2);
995        assert_eq!(gate.reason.as_deref(), Some(AGE_GATE_NO_HISTORY));
996        assert!(gate.flags.is_empty());
997    }
998
999    #[test]
1000    fn vendor_only_rows_do_not_count_as_distinct_flags() {
1001        let mut vendor_only = aged("web.new", None, 1);
1002        vendor_only.sites.clear();
1003        vendor_only.read_sites = 0;
1004        vendor_only.kind = RetirementFlagKind::VendorExport;
1005        vendor_only.reasons = vec![RetirementReason::VendorOnly];
1006        let report = finish_report(
1007            vec![aged("FEATURE_A", None, 2), vendor_only],
1008            FlagAgeMode::Off,
1009            None,
1010            &RetirementOptions::default(),
1011        );
1012        assert_eq!(report.summary.distinct_flags, 1);
1013        assert_eq!(report.summary.candidates, 1);
1014        assert_eq!(report.summary.listed_flags(), 2);
1015        assert_eq!(max_age_gate(&report.flags, 1, None).unmeasured, 1);
1016    }
1017
1018    #[test]
1019    fn sort_by_age_puts_the_oldest_first_and_unknown_ages_last() {
1020        let report = finish_report(
1021            vec![
1022                aged("FEATURE_B", Some(10), 2),
1023                aged("FEATURE_A", None, 2),
1024                aged("FEATURE_C", Some(300), 2),
1025                aged("FEATURE_D", Some(10), 2),
1026            ],
1027            FlagAgeMode::Blame,
1028            None,
1029            &RetirementOptions::default(),
1030        );
1031        assert_eq!(
1032            names(&report),
1033            vec!["FEATURE_C", "FEATURE_B", "FEATURE_D", "FEATURE_A"]
1034        );
1035    }
1036
1037    #[test]
1038    fn sort_by_sites_puts_the_fewest_reads_first() {
1039        let report = finish_report(
1040            vec![aged("FEATURE_A", None, 3), aged("FEATURE_B", None, 1)],
1041            FlagAgeMode::Off,
1042            None,
1043            &RetirementOptions {
1044                sort: RetirementSort::Sites,
1045                ..RetirementOptions::default()
1046            },
1047        );
1048        assert_eq!(names(&report), vec!["FEATURE_B", "FEATURE_A"]);
1049    }
1050
1051    #[test]
1052    fn filters_apply_after_the_summary() {
1053        let report = finish_report(
1054            vec![
1055                aged("FEATURE_OLD", Some(400), 1),
1056                aged("FEATURE_NEW", Some(3), 1),
1057                aged("FEATURE_WIDE", Some(900), 2),
1058                aged("FEATURE_UNKNOWN", None, 1),
1059            ],
1060            FlagAgeMode::Blame,
1061            None,
1062            &RetirementOptions {
1063                min_age_days: Some(30),
1064                reasons: vec![RetirementReason::SingleReadSite],
1065                ..RetirementOptions::default()
1066            },
1067        );
1068        assert_eq!(names(&report), vec!["FEATURE_OLD"]);
1069        assert_eq!(report.summary.distinct_flags, 4);
1070        assert_eq!(report.summary.candidates, 3);
1071        assert_eq!(
1072            report
1073                .summary
1074                .by_reason
1075                .get(&RetirementReason::SingleReadSite),
1076            Some(&3)
1077        );
1078    }
1079
1080    #[test]
1081    fn only_candidates_get_the_review_action_and_it_is_never_auto_fixable() {
1082        let report = finish_report(
1083            vec![aged("FEATURE_A", None, 1), aged("FEATURE_B", None, 2)],
1084            FlagAgeMode::Off,
1085            None,
1086            &RetirementOptions::default(),
1087        );
1088        let candidate = &report.flags[0];
1089        assert_eq!(candidate.actions.len(), 1);
1090        assert!(!candidate.actions[0].auto_fixable);
1091        assert!(report.flags[1].actions.is_empty());
1092    }
1093
1094    #[test]
1095    fn top_limits_rows_after_the_sort() {
1096        let report = finish_report(
1097            vec![aged("FEATURE_A", Some(1), 1), aged("FEATURE_B", Some(2), 1)],
1098            FlagAgeMode::Blame,
1099            None,
1100            &RetirementOptions {
1101                top: Some(1),
1102                ..RetirementOptions::default()
1103            },
1104        );
1105        assert_eq!(names(&report), vec!["FEATURE_B"]);
1106        assert_eq!(report.summary.distinct_flags, 2);
1107    }
1108}