Skip to main content

fallow_engine/
flag_vendor.rs

1//! Vendor flag state for `fallow flags --retirement --flag-state <FILE>`.
2//!
3//! The export is a local JSON file in one vendor-neutral schema. Fallow reads
4//! it offline: no credentials, no network calls and no vendor clients. The
5//! docs give `jq` recipes that turn the export of each vendor into this
6//! schema.
7//!
8//! The export adds four reasons to the report. `fully-rolled-out` and
9//! `archived-in-vendor` come from the vendor state of a flag in the code.
10//! `missing-in-vendor` marks a flag in the code whose key is not in the
11//! export. `vendor-only` adds a row for a key in the export that no code
12//! reads.
13
14use std::io::Read;
15use std::path::Path;
16
17use fallow_types::flag_retirement::{
18    FlagSiteRole, RetirementEvidence, RetirementFlag, RetirementFlagKind, RetirementReason,
19    RetirementVendor, RetirementVendorState, VendorFlagState,
20};
21use rustc_hash::{FxHashMap, FxHashSet};
22use serde::Deserialize;
23
24/// The schema version of the export that this build reads.
25const FLAG_STATE_SCHEMA_VERSION: u32 = 1;
26
27/// Largest export that Fallow reads, in bytes.
28pub const MAX_FLAG_STATE_BYTES: u64 = 16 * 1024 * 1024;
29
30/// An export older than this many days gets a warning.
31pub const STALE_EXPORT_DAYS: u64 = 30;
32
33/// Seconds in one day.
34const SECS_PER_DAY: u64 = 86_400;
35
36/// Hint for every invalid export.
37const FLAG_STATE_HELP: &str = "See https://fallow.tools/docs/cli/flags/#vendor-flag-state for the schema and a jq recipe for each vendor.";
38
39/// Why the export cannot be used.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct FlagStateError {
42    /// What is wrong with the export.
43    pub message: String,
44    /// How to make a valid export.
45    pub help: &'static str,
46}
47
48impl FlagStateError {
49    fn new(message: impl Into<String>) -> Self {
50        Self {
51            message: message.into(),
52            help: FLAG_STATE_HELP,
53        }
54    }
55}
56
57#[derive(Debug, Deserialize)]
58#[serde(deny_unknown_fields)]
59struct FlagStateFile {
60    schema_version: u32,
61    source: String,
62    exported_at: String,
63    flags: Vec<FlagStateEntry>,
64}
65
66#[derive(Debug, Deserialize)]
67#[serde(deny_unknown_fields)]
68struct FlagStateEntry {
69    key: String,
70    state: VendorFlagState,
71    #[serde(default)]
72    serves_single_variation: Option<bool>,
73    #[serde(default)]
74    created_at: Option<String>,
75    #[serde(default)]
76    last_evaluated_at: Option<String>,
77}
78
79/// One flag of the export.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct VendorFlag {
82    /// The vendor state of the flag.
83    pub state: RetirementVendor,
84    /// 1-based line of the key in the export file.
85    pub line: u32,
86}
87
88/// A valid vendor export.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct VendorExport {
91    /// The vendor name, for example `launchdarkly`.
92    pub source: String,
93    /// When the export was made, as the file gives it.
94    pub exported_at: String,
95    /// The export path for evidence: relative to the root when the file is
96    /// inside it, else the file name only.
97    pub display_path: String,
98    /// The flags, in file order.
99    pub flags: Vec<VendorFlag>,
100}
101
102impl VendorExport {
103    /// Check that no two keys name one code flag after `prefix`
104    /// (`flags.vendorKeyPrefix`) is removed. With the prefix `app.`, the keys
105    /// `checkout` and `app.checkout` both name the code flag `checkout`, so
106    /// the export cannot give one state for that flag.
107    ///
108    /// # Errors
109    ///
110    /// Returns an error that names the two keys.
111    pub fn check_key_prefix(&self, prefix: Option<&str>) -> Result<(), FlagStateError> {
112        let mut keys_by_name: FxHashMap<&str, &str> = FxHashMap::default();
113        for flag in &self.flags {
114            let key = flag.state.key.as_str();
115            let name = code_name(key, prefix);
116            if let Some(first) = keys_by_name.insert(name, key) {
117                return Err(FlagStateError::new(format!(
118                    "{} has the keys {first:?} and {key:?}, which both name the flag {name:?} after flags.vendorKeyPrefix {:?} is removed",
119                    self.display_path,
120                    prefix.unwrap_or_default()
121                )));
122            }
123        }
124        Ok(())
125    }
126}
127
128/// Read and check the export at `path`.
129///
130/// # Errors
131///
132/// Returns an error when the file cannot be read, is larger than
133/// [`MAX_FLAG_STATE_BYTES`], or does not match the schema.
134pub fn load_flag_state(path: &Path, root: &Path) -> Result<VendorExport, FlagStateError> {
135    let file = std::fs::File::open(path).map_err(|error| {
136        FlagStateError::new(format!(
137            "cannot read the flag state file {}: {error}",
138            path.display()
139        ))
140    })?;
141    let mut bytes = Vec::new();
142    file.take(MAX_FLAG_STATE_BYTES + 1)
143        .read_to_end(&mut bytes)
144        .map_err(|error| {
145            FlagStateError::new(format!(
146                "cannot read the flag state file {}: {error}",
147                path.display()
148            ))
149        })?;
150    if bytes.len() as u64 > MAX_FLAG_STATE_BYTES {
151        return Err(FlagStateError::new(format!(
152            "the flag state file {} is larger than {} MiB",
153            path.display(),
154            MAX_FLAG_STATE_BYTES / (1024 * 1024)
155        )));
156    }
157    parse_flag_state(&bytes, display_path(path, root))
158}
159
160/// The export path relative to the root when the file is inside it, else
161/// the file name only. Output paths are root-relative, and an absolute path
162/// outside the root (for example a CI temp directory) is local to one
163/// machine. Both sides are canonical, so a relative `--flag-state` path and
164/// a symlinked root still match.
165fn display_path(path: &Path, root: &Path) -> String {
166    let canonical_path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
167    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
168    let shown = match canonical_path.strip_prefix(&canonical_root) {
169        Ok(relative) => relative.to_path_buf(),
170        Err(_) => canonical_path
171            .file_name()
172            .map_or_else(|| path.to_path_buf(), std::path::PathBuf::from),
173    };
174    shown.to_string_lossy().replace('\\', "/")
175}
176
177/// Parse and check the bytes of an export.
178///
179/// # Errors
180///
181/// Returns an error when the bytes are not valid JSON in the schema, when
182/// `schema_version` is not [`FLAG_STATE_SCHEMA_VERSION`], when `exported_at`
183/// has no `YYYY-MM-DD` date, or when a key is empty or occurs two times.
184fn parse_flag_state(bytes: &[u8], display_path: String) -> Result<VendorExport, FlagStateError> {
185    let text = std::str::from_utf8(bytes)
186        .map_err(|_| FlagStateError::new(format!("{display_path} is not UTF-8 text")))?;
187    let file: FlagStateFile = serde_json::from_str(text)
188        .map_err(|error| FlagStateError::new(format!("{display_path} is not valid: {error}")))?;
189    if file.schema_version != FLAG_STATE_SCHEMA_VERSION {
190        return Err(FlagStateError::new(format!(
191            "{display_path} has schema_version {}, but this build reads schema_version {FLAG_STATE_SCHEMA_VERSION}",
192            file.schema_version
193        )));
194    }
195    if file.source.trim().is_empty() {
196        return Err(FlagStateError::new(format!(
197            "{display_path} has an empty source"
198        )));
199    }
200    if date_epoch(&file.exported_at).is_none() {
201        return Err(FlagStateError::new(format!(
202            "{display_path} has exported_at {:?}, which does not start with a YYYY-MM-DD date",
203            file.exported_at
204        )));
205    }
206    let lines = key_lines(text);
207    let mut seen: FxHashSet<&str> = FxHashSet::default();
208    for entry in &file.flags {
209        if entry.key.is_empty() {
210            return Err(FlagStateError::new(format!(
211                "{display_path} has a flag with an empty key"
212            )));
213        }
214        if !seen.insert(entry.key.as_str()) {
215            return Err(FlagStateError::new(format!(
216                "{display_path} has the key {:?} more than one time",
217                entry.key
218            )));
219        }
220    }
221    let flags = file
222        .flags
223        .into_iter()
224        .map(|entry| VendorFlag {
225            line: lines.get(entry.key.as_str()).copied().unwrap_or(1),
226            state: RetirementVendor {
227                key: entry.key,
228                state: entry.state,
229                serves_single_variation: entry.serves_single_variation,
230                created_at: entry.created_at,
231                last_evaluated_at: entry.last_evaluated_at,
232            },
233        })
234        .collect();
235    Ok(VendorExport {
236        source: file.source,
237        exported_at: file.exported_at,
238        display_path,
239        flags,
240    })
241}
242
243/// The line of the first `"key": "<value>"` pair for each value.
244fn key_lines(text: &str) -> FxHashMap<String, u32> {
245    const KEY_TOKEN: &str = "\"key\"";
246    let mut lines = FxHashMap::default();
247    let mut from = 0;
248    while let Some(offset) = text[from..].find(KEY_TOKEN) {
249        let start = from + offset;
250        from = start + KEY_TOKEN.len();
251        let rest = text[from..].trim_start();
252        let Some(value) = rest.strip_prefix(':') else {
253            continue;
254        };
255        let mut values =
256            serde_json::Deserializer::from_str(value.trim_start()).into_iter::<String>();
257        let Some(Ok(key)) = values.next() else {
258            continue;
259        };
260        let line = u32::try_from(text[..start].matches('\n').count() + 1).unwrap_or(u32::MAX);
261        lines.entry(key).or_insert(line);
262    }
263    lines
264}
265
266/// Epoch of the UTC midnight of the `YYYY-MM-DD` date at the start of `text`.
267fn date_epoch(text: &str) -> Option<u64> {
268    crate::clock::utc_midnight_epoch(text.get(..10)?)
269}
270
271/// The location of a flag site: project-relative path, line and column.
272pub(crate) type SiteLocation = (String, u32, u32);
273
274/// Inputs to match an export with the rows of the report.
275pub struct VendorMatch<'a> {
276    /// The export.
277    pub export: &'a VendorExport,
278    /// `flags.vendorKeyPrefix`: removed from each vendor key before the
279    /// match.
280    pub key_prefix: Option<&'a str>,
281    /// Every flag name in the project, also outside the scope of the run.
282    pub code_flag_names: &'a FxHashSet<String>,
283    /// The SDK label of every SDK site in the project, also outside the
284    /// scope of the run.
285    pub project_sdk_labels: &'a FxHashSet<String>,
286    /// The default provider of each SDK call that the report shows without
287    /// an SDK name, keyed by the location of the call.
288    pub hidden_sdk_labels: &'a FxHashMap<SiteLocation, String>,
289    /// Whether to add `vendor-only` rows. A run narrowed to part of the
290    /// project cannot tell that no code reads a key, so it adds none.
291    pub add_vendor_only: bool,
292    /// The analysis clock, in unix seconds.
293    pub clock_epoch_secs: u64,
294}
295
296/// Add the vendor reasons to `rows`, and add a row for each `vendor-only`
297/// key. Returns the export summary for the report.
298///
299/// Only SDK rows match the export. When an SDK label in the project matches
300/// the export `source` (for example `LaunchDarkly` and `launchdarkly`), only
301/// the rows of that SDK, and the SDK rows without a label, match. Thus an
302/// export of one vendor does not mark the flags of another SDK as
303/// `missing-in-vendor`. The label check reads every SDK site of the project,
304/// so a run narrowed to part of the project gives the same result for a row.
305pub(crate) fn apply_vendor_state(
306    rows: &mut Vec<RetirementFlag>,
307    input: &VendorMatch<'_>,
308) -> RetirementVendorState {
309    let export = input.export;
310    let by_name: FxHashMap<&str, &VendorFlag> = export
311        .flags
312        .iter()
313        .map(|flag| (code_name(&flag.state.key, input.key_prefix), flag))
314        .collect();
315    let source = normalize_label(&export.source);
316    let source_is_project_sdk = input
317        .project_sdk_labels
318        .iter()
319        .any(|sdk| label_matches_source(sdk, &source));
320    for row in rows.iter_mut() {
321        if row.kind != RetirementFlagKind::SdkCall
322            || (source_is_project_sdk && !row_matches_source(row, &source, input.hidden_sdk_labels))
323        {
324            continue;
325        }
326        match by_name.get(row.flag_name.as_str()) {
327            Some(flag) => add_state_reasons(row, flag, export),
328            None => add_missing_reason(row, export),
329        }
330    }
331    if input.add_vendor_only {
332        for flag in &export.flags {
333            let name = code_name(&flag.state.key, input.key_prefix);
334            if !input.code_flag_names.contains(name) {
335                rows.push(vendor_only_row(name, flag, export));
336            }
337        }
338    }
339    RetirementVendorState {
340        source: export.source.clone(),
341        exported_at: export.exported_at.clone(),
342        export_age_days: date_epoch(&export.exported_at)
343            .map(|epoch| input.clock_epoch_secs.saturating_sub(epoch) / SECS_PER_DAY),
344        flags: export.flags.len(),
345    }
346}
347
348/// The name that the code uses for a vendor key.
349fn code_name<'k>(key: &'k str, prefix: Option<&str>) -> &'k str {
350    prefix
351        .filter(|prefix| !prefix.is_empty())
352        .and_then(|prefix| key.strip_prefix(prefix))
353        .filter(|name| !name.is_empty())
354        .unwrap_or(key)
355}
356
357/// Lowercase ASCII letters and digits only, so `LaunchDarkly`,
358/// `launch-darkly` and `launchdarkly` compare equal.
359fn normalize_label(label: &str) -> String {
360    label
361        .chars()
362        .filter(char::is_ascii_alphanumeric)
363        .map(|c| c.to_ascii_lowercase())
364        .collect()
365}
366
367/// Whether a row can belong to the vendor of the export. A row without an
368/// SDK name uses the default provider of each of its calls, and a call
369/// without a provider can belong to every vendor. `source` is normalized.
370fn row_matches_source(
371    row: &RetirementFlag,
372    source: &str,
373    hidden: &FxHashMap<SiteLocation, String>,
374) -> bool {
375    if let Some(sdk) = row.sdk_name.as_deref() {
376        return label_matches_source(sdk, source);
377    }
378    row.sites.iter().any(|site| {
379        hidden
380            .get(&(site.path.clone(), site.line, site.col))
381            .is_none_or(|sdk| label_matches_source(sdk, source))
382    })
383}
384
385/// Whether an SDK label names the vendor of the export. `source` is
386/// normalized.
387fn label_matches_source(sdk: &str, source: &str) -> bool {
388    if source.is_empty() {
389        return false;
390    }
391    let sdk = normalize_label(sdk);
392    !sdk.is_empty() && (sdk.starts_with(source) || source.starts_with(&sdk))
393}
394
395/// The code site that evidence of a vendor reason points at: the first read
396/// site, else the first site.
397fn evidence_site(row: &RetirementFlag) -> Option<(String, u32)> {
398    row.sites
399        .iter()
400        .find(|site| site.role == FlagSiteRole::Read)
401        .or_else(|| row.sites.first())
402        .map(|site| (site.path.clone(), site.line))
403}
404
405fn add_state_reasons(row: &mut RetirementFlag, flag: &VendorFlag, export: &VendorExport) {
406    row.vendor = Some(flag.state.clone());
407    let Some((path, line)) = evidence_site(row) else {
408        return;
409    };
410    let state = &flag.state;
411    let single = state.serves_single_variation == Some(true);
412    if state.state == VendorFlagState::RolledOut || single {
413        let mut detail = format!("{} state {}", export.source, state_code(state.state));
414        if single {
415            detail.push_str(", serves one variation");
416        }
417        push_reason(row, RetirementReason::FullyRolledOut, &path, line, detail);
418    }
419    if state.state == VendorFlagState::Archived {
420        let detail = format!("{} state archived", export.source);
421        push_reason(row, RetirementReason::ArchivedInVendor, &path, line, detail);
422    }
423}
424
425fn add_missing_reason(row: &mut RetirementFlag, export: &VendorExport) {
426    let Some((path, line)) = evidence_site(row) else {
427        return;
428    };
429    let detail = format!(
430        "the key is not in the {} export ({})",
431        export.source, export.display_path
432    );
433    push_reason(row, RetirementReason::MissingInVendor, &path, line, detail);
434}
435
436fn push_reason(
437    row: &mut RetirementFlag,
438    reason: RetirementReason,
439    path: &str,
440    line: u32,
441    detail: String,
442) {
443    if !row.reasons.contains(&reason) {
444        row.reasons.push(reason);
445    }
446    row.evidence.push(RetirementEvidence {
447        reason,
448        path: path.to_string(),
449        line,
450        detail,
451    });
452}
453
454fn vendor_only_row(name: &str, flag: &VendorFlag, export: &VendorExport) -> RetirementFlag {
455    RetirementFlag {
456        flag_name: name.to_string(),
457        kind: RetirementFlagKind::VendorExport,
458        sdk_name: None,
459        workspace: None,
460        sites: Vec::new(),
461        read_sites: 0,
462        test_only: false,
463        first_seen: None,
464        oldest_surviving_site: None,
465        last_touched: None,
466        age_days: None,
467        reasons: vec![RetirementReason::VendorOnly],
468        evidence: vec![RetirementEvidence {
469            reason: RetirementReason::VendorOnly,
470            path: export.display_path.clone(),
471            line: flag.line,
472            detail: format!(
473                "the key is in the {} export, but no code reads it",
474                export.source
475            ),
476        }],
477        actions: Vec::new(),
478        vendor: Some(flag.state.clone()),
479    }
480}
481
482const fn state_code(state: VendorFlagState) -> &'static str {
483    match state {
484        VendorFlagState::On => "on",
485        VendorFlagState::Off => "off",
486        VendorFlagState::RolledOut => "rolled_out",
487        VendorFlagState::Archived => "archived",
488        VendorFlagState::Experiment => "experiment",
489    }
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495    use fallow_types::flag_retirement::RetirementSite;
496
497    const EXPORT: &str = r#"{
498  "schema_version": 1,
499  "source": "launchdarkly",
500  "exported_at": "2026-09-20T00:00:00Z",
501  "flags": [
502    { "key": "web.rolled", "state": "rolled_out" },
503    { "key": "web.single", "state": "off", "serves_single_variation": true },
504    { "key": "web.archived", "state": "archived" },
505    { "key": "web.live", "state": "on", "serves_single_variation": false },
506    { "key": "web.orphan", "state": "on" }
507  ]
508}"#;
509
510    /// 2026-09-25T00:00:00Z.
511    const CLOCK: u64 = 1_790_294_400;
512
513    fn export() -> VendorExport {
514        parse_flag_state(EXPORT.as_bytes(), "flag-state.json".to_string()).expect("valid export")
515    }
516
517    fn sdk_row(name: &str, sdk: Option<&str>) -> RetirementFlag {
518        RetirementFlag {
519            flag_name: name.to_string(),
520            kind: RetirementFlagKind::SdkCall,
521            sdk_name: sdk.map(str::to_string),
522            workspace: None,
523            sites: vec![RetirementSite {
524                path: "src/app.ts".to_string(),
525                line: 3,
526                col: 2,
527                role: FlagSiteRole::Read,
528                in_test: false,
529            }],
530            read_sites: 1,
531            test_only: false,
532            first_seen: None,
533            oldest_surviving_site: None,
534            last_touched: None,
535            age_days: None,
536            reasons: Vec::new(),
537            evidence: Vec::new(),
538            actions: Vec::new(),
539            vendor: None,
540        }
541    }
542
543    fn apply(rows: &mut Vec<RetirementFlag>, add_vendor_only: bool) -> RetirementVendorState {
544        let labels: FxHashSet<String> =
545            rows.iter().filter_map(|row| row.sdk_name.clone()).collect();
546        apply_with_labels(rows, add_vendor_only, &labels)
547    }
548
549    fn apply_with_labels(
550        rows: &mut Vec<RetirementFlag>,
551        add_vendor_only: bool,
552        labels: &FxHashSet<String>,
553    ) -> RetirementVendorState {
554        let export = export();
555        let names: FxHashSet<String> = rows.iter().map(|row| row.flag_name.clone()).collect();
556        apply_vendor_state(
557            rows,
558            &VendorMatch {
559                export: &export,
560                key_prefix: Some("web."),
561                code_flag_names: &names,
562                project_sdk_labels: labels,
563                hidden_sdk_labels: &FxHashMap::default(),
564                add_vendor_only,
565                clock_epoch_secs: CLOCK,
566            },
567        )
568    }
569
570    fn reasons_of<'r>(rows: &'r [RetirementFlag], name: &str) -> &'r [RetirementReason] {
571        &rows
572            .iter()
573            .find(|row| row.flag_name == name)
574            .unwrap_or_else(|| panic!("no row {name}"))
575            .reasons
576    }
577
578    #[test]
579    fn vendor_states_give_the_vendor_reasons() {
580        let mut rows = vec![
581            sdk_row("rolled", Some("LaunchDarkly")),
582            sdk_row("single", Some("LaunchDarkly")),
583            sdk_row("archived", Some("LaunchDarkly")),
584            sdk_row("live", Some("LaunchDarkly")),
585            sdk_row("typo", Some("LaunchDarkly")),
586        ];
587        let state = apply(&mut rows, true);
588        assert_eq!(
589            reasons_of(&rows, "rolled"),
590            [RetirementReason::FullyRolledOut]
591        );
592        assert_eq!(
593            reasons_of(&rows, "single"),
594            [RetirementReason::FullyRolledOut]
595        );
596        assert_eq!(
597            reasons_of(&rows, "archived"),
598            [RetirementReason::ArchivedInVendor]
599        );
600        assert!(reasons_of(&rows, "live").is_empty());
601        assert_eq!(
602            reasons_of(&rows, "typo"),
603            [RetirementReason::MissingInVendor]
604        );
605        assert_eq!(reasons_of(&rows, "orphan"), [RetirementReason::VendorOnly]);
606
607        let single = rows
608            .iter()
609            .find(|row| row.flag_name == "single")
610            .expect("row");
611        assert_eq!(
612            single.evidence[0].detail,
613            "launchdarkly state off, serves one variation"
614        );
615        assert_eq!(
616            single.vendor.as_ref().map(|v| v.key.as_str()),
617            Some("web.single")
618        );
619
620        let orphan = rows
621            .iter()
622            .find(|row| row.flag_name == "orphan")
623            .expect("row");
624        assert_eq!(orphan.kind, RetirementFlagKind::VendorExport);
625        assert!(orphan.sites.is_empty());
626        assert_eq!(orphan.evidence[0].path, "flag-state.json");
627        assert_eq!(orphan.evidence[0].line, 10, "the line of the orphan key");
628
629        assert_eq!(state.source, "launchdarkly");
630        assert_eq!(state.flags, 5);
631        assert_eq!(state.export_age_days, Some(5));
632    }
633
634    #[test]
635    fn a_narrowed_run_adds_no_vendor_only_rows() {
636        let mut rows = vec![sdk_row("rolled", Some("LaunchDarkly"))];
637        apply(&mut rows, false);
638        assert_eq!(rows.len(), 1);
639    }
640
641    #[test]
642    fn a_key_that_the_code_reads_under_another_kind_is_not_vendor_only() {
643        let mut rows = vec![RetirementFlag {
644            kind: RetirementFlagKind::EnvironmentVariable,
645            ..sdk_row("orphan", None)
646        }];
647        apply(&mut rows, true);
648        assert_eq!(
649            rows.len(),
650            1 + 4,
651            "the env row and four keys that no code reads"
652        );
653        assert!(
654            reasons_of(&rows, "orphan").is_empty(),
655            "an env row never matches the export"
656        );
657    }
658
659    #[test]
660    fn an_export_of_one_vendor_leaves_other_sdks_alone() {
661        let mut rows = vec![
662            sdk_row("typo", Some("LaunchDarkly")),
663            sdk_row("other", Some("Statsig")),
664            sdk_row("custom", None),
665        ];
666        apply(&mut rows, false);
667        assert_eq!(
668            reasons_of(&rows, "typo"),
669            [RetirementReason::MissingInVendor]
670        );
671        assert!(reasons_of(&rows, "other").is_empty());
672        assert_eq!(
673            reasons_of(&rows, "custom"),
674            [RetirementReason::MissingInVendor],
675            "an SDK row without a label can belong to the vendor"
676        );
677    }
678
679    #[test]
680    fn a_row_without_a_name_uses_the_default_provider_of_its_calls() {
681        // Both rows show no SDK name. The calls of `hidden` default to
682        // Statsig, so the LaunchDarkly export does not cover them. The
683        // `mixed` row has a call that defaults to LaunchDarkly.
684        let mut hidden_row = sdk_row("hidden", None);
685        hidden_row.sites[0].line = 7;
686        let mut mixed_row = sdk_row("mixed", None);
687        mixed_row.sites[0].line = 8;
688        let mut second = mixed_row.sites[0].clone();
689        second.line = 9;
690        mixed_row.sites.push(second);
691        let mut rows = vec![hidden_row, mixed_row];
692        let hidden: FxHashMap<SiteLocation, String> = [
693            (("src/app.ts".to_string(), 7, 2), "Statsig".to_string()),
694            (("src/app.ts".to_string(), 8, 2), "Statsig".to_string()),
695            (("src/app.ts".to_string(), 9, 2), "LaunchDarkly".to_string()),
696        ]
697        .into_iter()
698        .collect();
699        let labels: FxHashSet<String> = ["Statsig", "LaunchDarkly"]
700            .into_iter()
701            .map(str::to_string)
702            .collect();
703        let export = export();
704        let names: FxHashSet<String> = rows.iter().map(|row| row.flag_name.clone()).collect();
705        apply_vendor_state(
706            &mut rows,
707            &VendorMatch {
708                export: &export,
709                key_prefix: Some("web."),
710                code_flag_names: &names,
711                project_sdk_labels: &labels,
712                hidden_sdk_labels: &hidden,
713                add_vendor_only: false,
714                clock_epoch_secs: CLOCK,
715            },
716        );
717        assert!(reasons_of(&rows, "hidden").is_empty());
718        assert_eq!(
719            reasons_of(&rows, "mixed"),
720            [RetirementReason::MissingInVendor]
721        );
722    }
723
724    #[test]
725    fn a_narrowed_run_reads_the_sdk_labels_of_the_whole_project() {
726        // Only the Statsig row is in scope, but the project also has
727        // LaunchDarkly sites, so the LaunchDarkly export does not cover it.
728        let mut rows = vec![sdk_row("other", Some("Statsig"))];
729        let labels: FxHashSet<String> = ["Statsig", "LaunchDarkly"]
730            .into_iter()
731            .map(str::to_string)
732            .collect();
733        apply_with_labels(&mut rows, false, &labels);
734        assert!(
735            reasons_of(&rows, "other").is_empty(),
736            "{:?}",
737            rows[0].reasons
738        );
739    }
740
741    #[test]
742    fn an_export_of_an_unknown_vendor_matches_every_sdk_row() {
743        let mut rows = vec![sdk_row("typo", Some("Statsig"))];
744        let export = parse_flag_state(
745            br#"{"schema_version":1,"source":"in-house","exported_at":"2026-09-20","flags":[]}"#,
746            "state.json".to_string(),
747        )
748        .expect("valid");
749        apply_vendor_state(
750            &mut rows,
751            &VendorMatch {
752                export: &export,
753                key_prefix: None,
754                code_flag_names: &FxHashSet::default(),
755                project_sdk_labels: &std::iter::once("Statsig".to_string()).collect(),
756                hidden_sdk_labels: &FxHashMap::default(),
757                add_vendor_only: true,
758                clock_epoch_secs: CLOCK,
759            },
760        );
761        assert_eq!(
762            reasons_of(&rows, "typo"),
763            [RetirementReason::MissingInVendor]
764        );
765    }
766
767    #[test]
768    fn invalid_exports_are_rejected() {
769        let cases: [(&str, &str); 6] = [
770            ("not json", "is not valid"),
771            (
772                r#"{"schema_version":2,"source":"x","exported_at":"2026-01-01","flags":[]}"#,
773                "schema_version 2",
774            ),
775            (
776                r#"{"schema_version":1,"source":"x","exported_at":"yesterday","flags":[]}"#,
777                "YYYY-MM-DD",
778            ),
779            (
780                r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"paused"}]}"#,
781                "unknown variant",
782            ),
783            (
784                r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"on"},{"key":"a","state":"off"}]}"#,
785                "more than one time",
786            ),
787            (
788                r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"on","enabled":true}]}"#,
789                "unknown field",
790            ),
791        ];
792        for (input, expected) in cases {
793            let error =
794                parse_flag_state(input.as_bytes(), "state.json".to_string()).expect_err(input);
795            assert!(
796                error.message.contains(expected),
797                "{input}: {}",
798                error.message
799            );
800        }
801    }
802
803    #[test]
804    fn two_keys_that_name_one_flag_after_the_prefix_are_rejected() {
805        let export = parse_flag_state(
806            br#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"checkout","state":"on"},{"key":"app.checkout","state":"off"},{"key":"app.banner","state":"on"}]}"#,
807            "state.json".to_string(),
808        )
809        .expect("valid export");
810        assert!(export.check_key_prefix(None).is_ok());
811        assert!(export.check_key_prefix(Some("web.")).is_ok());
812        let error = export
813            .check_key_prefix(Some("app."))
814            .expect_err("two keys name `checkout`");
815        assert!(
816            error.message.contains(r#""checkout" and "app.checkout""#),
817            "{}",
818            error.message
819        );
820    }
821
822    #[test]
823    fn an_oversized_export_is_rejected_before_parse() {
824        let dir = tempfile::tempdir().expect("temp dir");
825        let path = dir.path().join("state.json");
826        let file = std::fs::File::create(&path).expect("create");
827        file.set_len(MAX_FLAG_STATE_BYTES + 1).expect("grow");
828        let error = load_flag_state(&path, dir.path()).expect_err("too large");
829        assert!(
830            error.message.contains("larger than 16 MiB"),
831            "{}",
832            error.message
833        );
834    }
835
836    #[test]
837    fn the_display_path_is_relative_to_the_root_only_inside_it() {
838        let dir = tempfile::tempdir().expect("temp dir");
839        let inside = dir.path().join("state.json");
840        std::fs::write(&inside, "{}").expect("write");
841        assert_eq!(display_path(&inside, dir.path()), "state.json");
842        let other = tempfile::tempdir().expect("temp dir");
843        let outside = other.path().join("state.json");
844        std::fs::write(&outside, "{}").expect("write");
845        assert_eq!(
846            display_path(&outside, dir.path()),
847            "state.json",
848            "a file outside the root shows its file name only"
849        );
850    }
851
852    #[test]
853    fn a_prefix_that_is_the_whole_key_keeps_the_key() {
854        assert_eq!(code_name("web.", Some("web.")), "web.");
855        assert_eq!(code_name("web.a", Some("")), "web.a");
856        assert_eq!(code_name("app.a", Some("web.")), "app.a");
857    }
858}