fallow-engine 3.50.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Warm equals cold over edit sequences.
//!
//! The model of a warm run is the cache-free run on the same tree. After each
//! step of a sequence, the warm run of each cached analysis (graph, extract
//! and dupes caches) must give the same JSON as the cache-free run.
//!
//! PR CI runs the regression sequences and a fixed set of seeds. Set
//! `FALLOW_CACHE_MODEL_SEEDS=<count>` and run the ignored sweep test for a
//! wide search. A failing sequence prints its template and steps. Add it to
//! [`REGRESSIONS`] when you fix the cause.

use super::project::{Observation, Project};
use super::templates::{ANGULAR, BUN, DENO, NODE, Step, TEMPLATES, Template, VITE, apply};

/// The seeds of the generated sequences in PR CI.
const PR_SEEDS: [u64; 4] = [0x5eed_0001, 0x5eed_0002, 0x5eed_0003, 0x5eed_0004];
/// The steps in one generated sequence.
const SEQUENCE_LEN: usize = 6;

/// A named sequence that once found, or was written for, a cache-key gap.
struct Regression {
    name: &'static str,
    template: &'static Template,
    steps: &'static [Step],
}

const REGRESSIONS: &[Regression] = &[
    Regression {
        name: "source edit",
        template: &NODE,
        steps: &[Step::SwapUtilUse { keep_mtime: false }],
    },
    Regression {
        name: "same-length edit with the old modification time",
        template: &NODE,
        steps: &[Step::SwapUtilUse { keep_mtime: true }],
    },
    Regression {
        name: "body edit that keeps the import statements",
        template: &NODE,
        steps: &[Step::SwapBodyUse, Step::SwapBodyUse],
    },
    Regression {
        name: "import edit, then a body edit",
        template: &NODE,
        steps: &[Step::SwapUtilUse { keep_mtime: false }, Step::SwapBodyUse],
    },
    Regression {
        name: "body edit, then a file at a missed candidate path",
        template: &NODE,
        steps: &[
            Step::SwapBodyUse,
            Step::ToggleExtensionlessUtil,
            Step::ToggleExtensionlessUtil,
        ],
    },
    Regression {
        name: "body edit, then npm install into node_modules",
        template: &NODE,
        steps: &[Step::SwapBodyUse, Step::ToggleNpmInstall],
    },
    Regression {
        name: "body edit, then a bun hoisted version with the same lockfile",
        template: &BUN,
        steps: &[
            Step::SwapBodyUse,
            Step::SwapBunHoistedVersion,
            Step::SwapBunHoistedVersion,
        ],
    },
    Regression {
        name: "file add and delete",
        template: &NODE,
        steps: &[Step::ToggleExtraFile, Step::ToggleExtraFile],
    },
    Regression {
        name: "file rename",
        template: &NODE,
        steps: &[Step::RenameOrphan],
    },
    Regression {
        name: "production mode",
        template: &NODE,
        steps: &[Step::ToggleProduction],
    },
    Regression {
        name: "ignore pattern",
        template: &NODE,
        steps: &[Step::ToggleIgnoreOrphan],
    },
    Regression {
        name: "resolve condition",
        template: &NODE,
        steps: &[Step::ToggleCondition],
    },
    Regression {
        name: "package.json imports (#3477)",
        template: &NODE,
        steps: &[Step::SwapPackageImports],
    },
    Regression {
        name: "workspace names (#3477)",
        template: &NODE,
        steps: &[Step::SwapWorkspaceNames],
    },
    Regression {
        name: "extended tsconfig (#3477)",
        template: &NODE,
        steps: &[Step::SwapExtendedTsconfig],
    },
    Regression {
        name: "nested tsconfig (#3477)",
        template: &NODE,
        steps: &[Step::SwapNestedTsconfig],
    },
    Regression {
        name: "deno import map (#3477)",
        template: &DENO,
        steps: &[Step::SwapDenoImportMap],
    },
    Regression {
        name: "npm install into node_modules (#4192)",
        template: &NODE,
        steps: &[Step::ToggleNpmInstall],
    },
    Regression {
        name: "bun install with the same lockfile (#4192)",
        template: &BUN,
        steps: &[Step::ToggleBunInstall],
    },
    Regression {
        name: "bun hoisted version with the same lockfile (#4197)",
        template: &BUN,
        steps: &[Step::SwapBunHoistedVersion, Step::SwapBunHoistedVersion],
    },
    Regression {
        name: "deno install with the same lockfile (#4197)",
        template: &DENO,
        steps: &[Step::ToggleDenoInstall, Step::ToggleDenoInstall],
    },
    Regression {
        name: "same-length clone edit with the old modification time",
        template: &NODE,
        steps: &[Step::EditClone { keep_mtime: true }],
    },
    Regression {
        name: "vite resolve alias (#4243)",
        template: &VITE,
        steps: &[Step::SwapViteAlias { keep_mtime: false }],
    },
    Regression {
        name: "same-length vite alias edit with the old modification time (#4243)",
        template: &VITE,
        steps: &[Step::SwapViteAlias { keep_mtime: true }],
    },
    Regression {
        name: "vitest setup file (#4243)",
        template: &VITE,
        steps: &[Step::SwapVitestSetup],
    },
    Regression {
        name: "vitest include glob (#4243)",
        template: &VITE,
        steps: &[Step::SwapVitestInclude],
    },
    Regression {
        name: "angular sass include path (#4243)",
        template: &ANGULAR,
        steps: &[Step::SwapAngularIncludePath],
    },
    Regression {
        name: "angular main entry (#4243)",
        template: &ANGULAR,
        steps: &[Step::SwapAngularMain],
    },
    Regression {
        name: "extensionless file at a missed candidate path (#4233)",
        template: &NODE,
        steps: &[Step::ToggleExtensionlessUtil, Step::ToggleExtensionlessUtil],
    },
    Regression {
        name: "json file at a missed candidate path (#4233)",
        template: &NODE,
        steps: &[Step::ToggleDataJson, Step::ToggleDataJson],
    },
    Regression {
        name: "build output in an ignored directory (#4233)",
        template: &NODE,
        steps: &[Step::ToggleBuildOutput, Step::ToggleBuildOutput],
    },
];

/// The facts of one sequence run.
#[derive(Debug, Default)]
struct Outcome {
    /// Steps that changed the cache-free result. A sequence where no step
    /// changes it cannot show a stale cache.
    changed: usize,
    /// Steps where the warm run used the graph cache.
    graph_hits: usize,
}

/// Run `steps` on a fresh copy of `template`. After each step, compare the
/// warm run with the cache-free run, and panic with the sequence on a
/// difference.
fn run_sequence(label: &str, template: &Template, steps: &[Step]) -> Outcome {
    let mut project = Project::new(template.files);
    let mut previous = project.observe_cold();
    let first_warm = project.observe_warm();
    assert_observations_equal(label, template, &[], &first_warm, &previous);
    assert_caches_persisted(label, &project);

    let mut outcome = Outcome::default();
    for (index, step) in steps.iter().enumerate() {
        apply(&mut project, *step);
        let before = project.graph_cache_bytes();
        let warm = project.observe_warm();
        if before.is_some() && before == project.graph_cache_bytes() {
            outcome.graph_hits += 1;
        }
        let cold = project.observe_cold();
        assert_observations_equal(label, template, &steps[..=index], &warm, &cold);
        if cold != previous {
            outcome.changed += 1;
        }
        previous = cold;
    }
    outcome
}

/// The graph, extract and dupes caches each wrote their file, so the warm
/// runs read real caches.
fn assert_caches_persisted(label: &str, project: &Project) {
    let snapshot = project.cache_snapshot();
    let names: Vec<String> = snapshot
        .iter()
        .filter_map(|(path, _)| path.strip_prefix(&project.cache_dir).ok())
        .map(|path| path.to_string_lossy().replace('\\', "/"))
        .collect();
    for (cache, matches) in [
        ("graph", "graph-cache.bin"),
        ("extract", "cache.bin"),
        ("dupes", "dupes-tokens-"),
    ] {
        assert!(
            names
                .iter()
                .any(|name| name == matches || (matches.ends_with('-') && name.contains(matches))),
            "{label}: the warm run must persist the {cache} cache, found {names:?}"
        );
    }
}

fn assert_observations_equal(
    label: &str,
    template: &Template,
    steps: &[Step],
    warm: &Observation,
    cold: &Observation,
) {
    if warm == cold {
        return;
    }
    let mut report = format!(
        "{label}: the warm run differs from the cache-free run\n  template: {}\n  steps: {steps:?}\n",
        template.name
    );
    for (part, warm, cold) in [
        ("analysis", &warm.analysis, &cold.analysis),
        ("dupes", &warm.dupes, &cold.dupes),
    ] {
        describe_difference(&mut report, part, warm, cold);
    }
    panic!("{report}");
}

/// Name each top-level field that differs, with both values in short form.
fn describe_difference(
    report: &mut String,
    part: &str,
    warm: &serde_json::Value,
    cold: &serde_json::Value,
) {
    use std::fmt::Write as _;

    let (Some(warm_fields), Some(cold_fields)) = (warm.as_object(), cold.as_object()) else {
        if warm != cold {
            let _ = writeln!(report, "  {part}: {} != {}", short(warm), short(cold));
        }
        return;
    };
    for (key, cold_value) in cold_fields {
        let warm_value = warm_fields.get(key).unwrap_or(&serde_json::Value::Null);
        if warm_value != cold_value {
            let _ = writeln!(
                report,
                "  {part}.{key}:\n    warm: {}\n    cold: {}",
                short(warm_value),
                short(cold_value)
            );
        }
    }
}

fn short(value: &serde_json::Value) -> String {
    const LIMIT: usize = 600;
    let text = value.to_string();
    if text.len() <= LIMIT {
        return text;
    }
    let end = (0..=LIMIT)
        .rev()
        .find(|&i| text.is_char_boundary(i))
        .unwrap_or(0);
    format!("{}...", &text[..end])
}

/// A xorshift generator, so a seed gives the same sequence on every platform.
struct SeqRng(u64);

impl SeqRng {
    fn next(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        x
    }

    fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T {
        let index = usize::try_from(self.next() % items.len() as u64).expect("index fits");
        &items[index]
    }
}

fn generate(seed: u64, template: &Template) -> Vec<Step> {
    let mut rng = SeqRng(seed | 1);
    std::iter::repeat_with(|| *rng.pick(template.steps))
        .take(SEQUENCE_LEN)
        .collect()
}

/// Run each template over each `(label, seed)` pair.
fn run_seeds(seeds: impl IntoIterator<Item = (String, u64)>) -> Outcome {
    let mut total = Outcome::default();
    for (label, seed) in seeds {
        for template in TEMPLATES {
            let steps = generate(seed, template);
            let outcome = run_sequence(&label, template, &steps);
            total.changed += outcome.changed;
            total.graph_hits += outcome.graph_hits;
        }
    }
    total
}

/// The regression sequences. `FALLOW_CACHE_MODEL_REGRESSIONS=<text>` runs only
/// the sequences whose name contains the text, so a proof of one fix commit
/// can leave out the sequences of later fixes.
#[test]
fn regression_sequences_match_cache_free_runs() {
    let filter = std::env::var("FALLOW_CACHE_MODEL_REGRESSIONS").unwrap_or_default();
    let selected: Vec<&Regression> = REGRESSIONS
        .iter()
        .filter(|regression| regression.name.contains(filter.as_str()))
        .collect();
    assert!(
        !selected.is_empty(),
        "no regression sequence name contains {filter:?}"
    );
    for regression in selected {
        let outcome = run_sequence(regression.name, regression.template, regression.steps);
        assert_eq!(
            outcome.changed,
            regression.steps.len(),
            "{}: each step must change the cache-free result, or that step proves nothing",
            regression.name
        );
    }
}

#[test]
fn generated_sequences_match_cache_free_runs() {
    let outcome = run_seeds(PR_SEEDS.map(|seed| (format!("seed {seed:#x}"), seed)));
    assert!(
        outcome.changed > 0,
        "no generated step changed the cache-free result"
    );
    assert!(
        outcome.graph_hits > 0,
        "no warm run used the graph cache, so the comparison tests no cache"
    );
}

/// The wide seed sweep over seed numbers `start..start + count`. Run it with
/// `FALLOW_CACHE_MODEL_SEEDS=200 cargo test -p fallow-engine --test integration
/// cache_model -- --ignored`. `FALLOW_CACHE_MODEL_SEED_START` (default 1) sets
/// the first seed number, so a scheduled run can search seeds that earlier
/// runs did not. A failure names the seed number, and the same start and
/// count run it again.
#[test]
#[ignore = "wide seed sweep, run by hand or on a schedule"]
fn seed_sweep_matches_cache_free_runs() {
    let count = seed_env("FALLOW_CACHE_MODEL_SEEDS", 50);
    let start = seed_env("FALLOW_CACHE_MODEL_SEED_START", 1);
    run_seeds((start..start.saturating_add(count)).map(|n| {
        let seed = n.wrapping_mul(0x9e37_79b9_7f4a_7c15);
        (format!("seed number {n} (seed {seed:#x})"), seed)
    }));
}

/// A `u64` from the environment variable `name`. An unset variable gives
/// `default`, and a value that is not a number fails the test.
fn seed_env(name: &str, default: u64) -> u64 {
    match std::env::var(name) {
        Ok(value) => value
            .trim()
            .parse()
            .unwrap_or_else(|_| panic!("{name} must be a whole number, found {value:?}")),
        Err(_) => default,
    }
}