fallow-engine 3.49.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! A warm churn cache must produce the same result as a cold build.
//!
//! `crates/core/tests/integration_test/graph_cache_transparency.rs` states the
//! invariant for the analysis graph: a cache hit has to produce identical
//! results to a cold build. Churn is the one subsystem where nothing enforced
//! it. The cache only ever appended, so an entry minted while a commit was
//! still inside the window kept reporting that commit long after a cold
//! `git log --after` stopped returning it.
//!
//! These tests drive the real `analyze_churn_cached` entry point over a real
//! git repository with commits placed deliberately on the window edge.

#![allow(
    clippy::expect_used,
    reason = "integration tests use expect to keep fixture setup concise"
)]

use fallow_engine::churn::{ChurnResult, ChurnWindowUnit, SinceDuration, analyze_churn_cached};
use fallow_engine::git_fixture::{
    FixtureIdentity, fixture_git_capture, fixture_git_command_with_identity,
};
use std::path::{Path, PathBuf};

/// Window used by every test here: 90 days, so the cutoff is exactly
/// `head_committer_epoch - 90 * 86400` with no calendar clamping to reason
/// about.
const WINDOW_DAYS: u64 = 90;

const SECS_PER_DAY: u64 = 86_400;

/// Fixed base instant (2023-11-14T22:13:20Z) so every commit timestamp in
/// these tests is an exact, reproducible epoch rather than an offset from the
/// wall clock.
const BASE_EPOCH: u64 = 1_700_000_000;

fn window() -> SinceDuration {
    SinceDuration::relative(WINDOW_DAYS, ChurnWindowUnit::Days, "90 days")
}

fn git(root: &Path, args: &[&str], epoch: Option<u64>) {
    let mut command = fixture_git_command_with_identity(root, FixtureIdentity::RepositoryConfig);
    command.args(args);
    if let Some(epoch) = epoch {
        let stamp = format!("{epoch} +0000");
        command
            .env("GIT_AUTHOR_DATE", &stamp)
            .env("GIT_COMMITTER_DATE", &stamp);
    }
    let status = command.status().expect("run git");
    assert!(status.success(), "git {args:?} failed");
}

/// The `file://` URL of a local repository. A Windows path has no leading
/// slash, and git refuses its backslashes in a URL.
fn file_url(path: &Path) -> String {
    let path = path.to_string_lossy().replace('\\', "/");
    if path.starts_with('/') {
        format!("file://{path}")
    } else {
        format!("file:///{path}")
    }
}

fn init_repo(root: &Path) {
    git(root, &["init", "--quiet", "--initial-branch=main"], None);
    git(root, &["config", "user.name", "Churn Fixture"], None);
    git(root, &["config", "user.email", "fixture@example.com"], None);
    git(root, &["config", "commit.gpgsign", "false"], None);
}

/// Write `path` and commit it with both author and committer date pinned to
/// `epoch`. `git log --after` filters on the committer date, and the run clock
/// reads HEAD's committer date, so pinning both makes the window boundary
/// exact.
fn commit_file(root: &Path, path: &str, contents: &str, epoch: u64) {
    let file = root.join(path);
    if let Some(parent) = file.parent() {
        std::fs::create_dir_all(parent).expect("create source directory");
    }
    std::fs::write(&file, contents).expect("write source file");
    git(root, &["add", path], None);
    git(root, &["commit", "--quiet", "-m", path], Some(epoch));
}

fn churn(root: &Path, cache_dir: &Path, no_cache: bool) -> (ChurnResult, bool) {
    analyze_churn_cached(root, &window(), cache_dir, no_cache).expect("churn analysis")
}

/// Files with retained churn, sorted, as project-relative strings.
fn changed_files(result: &ChurnResult, root: &Path) -> Vec<String> {
    let mut paths: Vec<String> = result
        .files
        .keys()
        .map(|path| {
            path.strip_prefix(root)
                .unwrap_or(path)
                .to_string_lossy()
                .replace('\\', "/")
        })
        .collect();
    paths.sort();
    paths
}

/// Every comparable field of a churn row, so a warm/cold comparison catches a
/// retained event even when the file set already matches.
fn churn_rows(result: &ChurnResult, root: &Path) -> Vec<(String, u32, u64, u64)> {
    let mut rows: Vec<(String, u32, u64, u64)> = result
        .files
        .iter()
        .map(|(path, file)| {
            (
                path.strip_prefix(root)
                    .unwrap_or(path)
                    .to_string_lossy()
                    .replace('\\', "/"),
                file.commits,
                u64::from(file.lines_added),
                u64::from(file.lines_deleted),
            )
        })
        .collect();
    rows.sort();
    rows
}

struct Fixture {
    _dir: tempfile::TempDir,
    root: PathBuf,
    cache: PathBuf,
}

impl Fixture {
    fn new() -> Self {
        let dir = tempfile::tempdir().expect("churn fixture tempdir");
        // The macOS tempdir lives behind a /var -> /private/var symlink, and
        // churn keys files by the path git reports under `root`. Canonicalize
        // once so `strip_prefix` in the assertions lines up.
        let root = dir.path().canonicalize().expect("canonical fixture root");
        let cache = root.join(".fallow-cache");
        init_repo(&root);
        Self {
            _dir: dir,
            root,
            cache,
        }
    }
}

#[test]
fn warm_cache_drops_commits_the_window_no_longer_covers() {
    let fixture = Fixture::new();
    let root = &fixture.root;

    // Two commits inside the window as of the second commit's own date.
    commit_file(root, "src/old.ts", "export const old = 1;\n", BASE_EPOCH);
    commit_file(
        root,
        "src/mid.ts",
        "export const mid = 1;\n",
        BASE_EPOCH + 10 * SECS_PER_DAY,
    );

    // Mint the cache while both commits still qualify.
    let (warm_seed, seeded_from_cache) = churn(root, &fixture.cache, false);
    assert!(!seeded_from_cache, "first run must be a cold build");
    assert_eq!(
        changed_files(&warm_seed, root),
        vec!["src/mid.ts".to_owned(), "src/old.ts".to_owned()],
        "both commits are inside the window at the seeding commit"
    );

    // Advance HEAD far enough that the run clock moves the cutoff past both
    // earlier commits. This is the "cache minted months ago" case, expressed
    // as HEAD advancing rather than as the wall clock drifting.
    commit_file(
        root,
        "src/new.ts",
        "export const fresh = 1;\n",
        BASE_EPOCH + 200 * SECS_PER_DAY,
    );

    let (warm, from_cache) = churn(root, &fixture.cache, false);
    assert!(from_cache, "second run must reuse the seeded cache");

    let cold_cache = root.join(".fallow-cold-cache");
    let (cold, _) = churn(root, &cold_cache, true);

    assert_eq!(
        changed_files(&cold, root),
        vec!["src/new.ts".to_owned()],
        "a cold build only sees the commit inside the 90 day window"
    );
    assert_eq!(
        churn_rows(&warm, root),
        churn_rows(&cold, root),
        "a warm churn cache must produce the same rows as a cold build"
    );
    assert_eq!(
        warm.shallow_clone, cold.shallow_clone,
        "shallow-clone detection must survive the cache path"
    );
    assert_eq!(
        warm.clock.epoch_secs(),
        cold.clock.epoch_secs(),
        "both runs resolve the same clock from the same HEAD"
    );
}

#[test]
fn cache_prune_and_git_after_agree_on_the_cutoff_second() {
    let fixture = Fixture::new();
    let root = &fixture.root;

    // Three commits laid out so that a later HEAD puts the cutoff exactly on
    // `edge.ts`'s committer second: `head.ts` is 90 days after `edge.ts`, and
    // the window is 90 days. `before-edge.ts` sits one second earlier.
    // Git's `--after` decides the cold answer and the cache prune decides the
    // warm one; if they disagree by a second, warm and cold differ by a commit.
    let edge_epoch = BASE_EPOCH;
    let head_epoch = edge_epoch + WINDOW_DAYS * SECS_PER_DAY;

    commit_file(
        root,
        "src/before-edge.ts",
        "export const before = 1;\n",
        edge_epoch - 1,
    );
    commit_file(root, "src/edge.ts", "export const edge = 1;\n", edge_epoch);

    // Seed the cache at a HEAD where both boundary commits are comfortably
    // inside the window, so the prune, not `git log`, is what decides their
    // fate on the warm run below.
    commit_file(
        root,
        "src/seed.ts",
        "export const seed = 1;\n",
        edge_epoch + 10 * SECS_PER_DAY,
    );
    let (seeded, seeded_from_cache) = churn(root, &fixture.cache, false);
    assert!(!seeded_from_cache, "first run must be a cold build");
    assert!(
        changed_files(&seeded, root).contains(&"src/before-edge.ts".to_owned()),
        "both boundary commits must reach the cache"
    );

    commit_file(root, "src/head.ts", "export const head = 1;\n", head_epoch);

    let (warm, from_cache) = churn(root, &fixture.cache, false);
    assert!(
        from_cache,
        "advancing HEAD must extend the cache, not miss it"
    );

    let cold_cache = root.join(".fallow-cold-cache");
    let (cold, _) = churn(root, &cold_cache, true);

    assert_eq!(
        changed_files(&cold, root),
        vec![
            "src/edge.ts".to_owned(),
            "src/head.ts".to_owned(),
            "src/seed.ts".to_owned(),
        ],
        "the cutoff second itself is inside the window, the second before it is not"
    );
    assert_eq!(
        churn_rows(&warm, root),
        churn_rows(&cold, root),
        "the cache prune must use the same boundary as git --after"
    );
}

/// A project root below the git toplevel (a workspace package, or a repo
/// where the app lives in a subdirectory) must key churn by paths under that
/// root, and must not count files outside it. `git log --numstat` reports
/// paths relative to the toplevel, so joining them to a subdirectory root
/// produced paths that match no source file.
#[test]
fn subdirectory_root_keys_churn_under_the_root() {
    let fixture = Fixture::new();
    let head = BASE_EPOCH + 200 * SECS_PER_DAY;
    commit_file(
        &fixture.root,
        "packages/app/src/a.ts",
        "a1",
        head - 20 * SECS_PER_DAY,
    );
    commit_file(&fixture.root, "other/b.ts", "b1", head - 10 * SECS_PER_DAY);
    commit_file(&fixture.root, "packages/app/src/a.ts", "a2", head);

    let app = fixture.root.join("packages/app");
    let cache = app.join(".fallow-cache");
    let (cold, _) = churn(&app, &cache, false);
    assert_eq!(changed_files(&cold, &app), vec!["src/a.ts".to_string()]);
    assert_eq!(cold.files[&app.join("src/a.ts")].commits, 2);

    // The incremental `<cached>..<head>` scan must apply the same scope.
    commit_file(&fixture.root, "other/b.ts", "b2", head + SECS_PER_DAY);
    commit_file(
        &fixture.root,
        "packages/app/src/a.ts",
        "a3",
        head + 2 * SECS_PER_DAY,
    );
    let (warm, reused) = churn(&app, &cache, false);
    assert!(reused, "second run must extend the cache");
    let (fresh, _) = churn(&app, &cache, true);
    assert_eq!(changed_files(&warm, &app), vec!["src/a.ts".to_string()]);
    assert_eq!(churn_rows(&warm, &app), churn_rows(&fresh, &app));
    assert_eq!(warm.files[&app.join("src/a.ts")].commits, 3);
}

/// Stage several files and commit them as one commit at `epoch`.
fn commit_files(root: &Path, files: &[(&str, &str)], epoch: u64) {
    for (path, contents) in files {
        let file = root.join(path);
        if let Some(parent) = file.parent() {
            std::fs::create_dir_all(parent).expect("create source directory");
        }
        std::fs::write(&file, contents).expect("write source file");
        git(root, &["add", path], None);
    }
    git(root, &["commit", "--quiet", "-m", "multi"], Some(epoch));
}

fn head_sha(root: &Path) -> String {
    fixture_git_capture(root, &["rev-parse", "HEAD"])
}

/// Commit file sets as `(sha, [relative paths])`, sorted, for comparison.
fn commit_sets(result: &ChurnResult, root: &Path) -> Vec<(String, Vec<String>)> {
    let mut sets: Vec<(String, Vec<String>)> = result
        .commits
        .iter()
        .map(|commit| {
            let mut files: Vec<String> = commit
                .files
                .iter()
                .map(|file| {
                    file.path
                        .strip_prefix(root)
                        .unwrap_or(&file.path)
                        .to_string_lossy()
                        .replace('\\', "/")
                })
                .collect();
            files.sort();
            (commit.sha.clone(), files)
        })
        .collect();
    sets.sort();
    sets
}

#[test]
fn churn_groups_files_by_commit_sha() {
    let fixture = Fixture::new();
    let root = &fixture.root;
    commit_files(
        root,
        &[
            ("src/a.ts", "export const a = 1;\n"),
            ("src/b.ts", "export const b = 1;\n"),
        ],
        BASE_EPOCH,
    );
    let first = head_sha(root);
    commit_file(
        root,
        "src/a.ts",
        "export const a = 2;\nexport const c = 3;\n",
        BASE_EPOCH + SECS_PER_DAY,
    );
    let second = head_sha(root);

    let (result, _) = churn(root, &fixture.cache, true);
    let mut expected = vec![
        (first, vec!["src/a.ts".to_owned(), "src/b.ts".to_owned()]),
        (second.clone(), vec!["src/a.ts".to_owned()]),
    ];
    expected.sort();
    assert_eq!(
        commit_sets(&result, root),
        expected,
        "each commit keeps the set of files it changed"
    );
    let latest = result
        .commits
        .iter()
        .find(|commit| commit.sha == second)
        .expect("second commit");
    assert_eq!(
        latest.files[0].lines_changed, 3,
        "1 deleted + 2 added lines"
    );
}

#[test]
fn incremental_cache_keeps_commit_file_sets_identical_to_a_cold_build() {
    let fixture = Fixture::new();
    let root = &fixture.root;
    commit_files(
        root,
        &[
            ("src/a.ts", "export const a = 1;\n"),
            ("src/b.ts", "export const b = 1;\n"),
        ],
        BASE_EPOCH,
    );
    let (_, seeded) = churn(root, &fixture.cache, false);
    assert!(!seeded);
    commit_files(
        root,
        &[
            ("src/a.ts", "export const a = 2;\n"),
            ("src/c.ts", "export const c = 1;\n"),
        ],
        BASE_EPOCH + SECS_PER_DAY,
    );

    let (warm, from_cache) = churn(root, &fixture.cache, false);
    assert!(from_cache, "the second run extends the cache");
    let (cold, _) = churn(root, &root.join(".fallow-cold-cache"), true);
    assert_eq!(commit_sets(&warm, root), commit_sets(&cold, root));
    assert_eq!(commit_sets(&cold, root).len(), 2);
}

#[test]
fn a_wider_cached_window_serves_a_narrower_request() {
    let fixture = Fixture::new();
    let root = &fixture.root;
    commit_file(root, "src/old.ts", "export const old = 1;\n", BASE_EPOCH);
    commit_file(
        root,
        "src/new.ts",
        "export const fresh = 1;\n",
        BASE_EPOCH + 200 * SECS_PER_DAY,
    );
    let wide = SinceDuration::relative(1, ChurnWindowUnit::Years, "1 year");

    let (wide_result, wide_hit) =
        analyze_churn_cached(root, &wide, &fixture.cache, false).expect("wide churn");
    assert!(!wide_hit);
    assert_eq!(
        changed_files(&wide_result, root),
        vec!["src/new.ts".to_owned(), "src/old.ts".to_owned()]
    );

    let (narrow, narrow_hit) =
        analyze_churn_cached(root, &window(), &fixture.cache, false).expect("narrow churn");
    assert!(narrow_hit, "the 1y cache entry covers the 90 day request");
    let (cold, _) = churn(root, &root.join(".fallow-cold-cache"), true);
    assert_eq!(churn_rows(&narrow, root), churn_rows(&cold, root));
    assert_eq!(commit_sets(&narrow, root), commit_sets(&cold, root));

    // The narrow run must not replace the wide entry.
    let (_, wide_again) =
        analyze_churn_cached(root, &wide, &fixture.cache, false).expect("wide churn again");
    assert!(wide_again, "the wide entry survives a narrow run");
}

#[test]
fn history_window_keeps_older_commits_while_files_use_the_narrow_window() {
    let fixture = Fixture::new();
    let root = &fixture.root;
    commit_files(
        root,
        &[
            ("src/a.ts", "export const a = 1;\n"),
            ("src/b.ts", "export const b = 1;\n"),
        ],
        BASE_EPOCH,
    );
    commit_file(
        root,
        "src/c.ts",
        "export const c = 1;\n",
        BASE_EPOCH + 200 * SECS_PER_DAY,
    );
    let history = SinceDuration::relative(1, ChurnWindowUnit::Years, "1 year");

    let (result, _) = fallow_engine::churn::analyze_churn_cached_with_history(
        root,
        &window(),
        &history,
        &fixture.cache,
        true,
    )
    .expect("churn with history");
    assert_eq!(
        changed_files(&result, root),
        vec!["src/c.ts".to_owned()],
        "per-file churn uses the 90 day window"
    );
    assert_eq!(
        result.commits.len(),
        2,
        "the commit list covers the one year history window"
    );
}

/// A shallow clone of an origin with `commits` commits to `src/index.ts`.
/// The clone has depth 1, so a cold churn run sees only the HEAD commit.
struct ShallowFixture {
    _dir: tempfile::TempDir,
    root: PathBuf,
    cache: PathBuf,
}

impl ShallowFixture {
    fn new(commits: u64) -> Self {
        let dir = tempfile::tempdir().expect("shallow fixture tempdir");
        let base = dunce::canonicalize(dir.path()).expect("canonical fixture base");
        let origin = base.join("origin");
        std::fs::create_dir_all(&origin).expect("create origin");
        init_repo(&origin);
        for index in 0..commits {
            commit_file(
                &origin,
                "src/index.ts",
                &format!("export const value = {index};\n"),
                BASE_EPOCH + index * SECS_PER_DAY,
            );
        }
        let url = file_url(&origin);
        git(
            &base,
            &["clone", "--quiet", "--depth", "1", &url, "clone"],
            None,
        );
        let root = base.join("clone");
        git(&root, &["config", "user.name", "Churn Fixture"], None);
        git(
            &root,
            &["config", "user.email", "fixture@example.com"],
            None,
        );
        git(&root, &["config", "commit.gpgsign", "false"], None);
        let cache = root.join(".fallow-cache");
        Self {
            _dir: dir,
            root,
            cache,
        }
    }

    /// Run churn warm and cold, assert that both agree, and return the warm
    /// result.
    fn warm_matching_cold(&self) -> ChurnResult {
        let (warm, _) = churn(&self.root, &self.cache, false);
        let (cold, _) = churn(&self.root, &self.root.join(".fallow-cold-cache"), true);
        assert_eq!(warm.shallow_clone, cold.shallow_clone);
        assert_eq!(churn_rows(&warm, &self.root), churn_rows(&cold, &self.root));
        assert_eq!(
            commit_sets(&warm, &self.root),
            commit_sets(&cold, &self.root)
        );
        warm
    }

    fn index_commits(&self, result: &ChurnResult) -> u32 {
        churn_rows(result, &self.root)
            .into_iter()
            .find(|row| row.0 == "src/index.ts")
            .expect("src/index.ts has churn")
            .1
    }
}

#[test]
fn warm_cache_after_unshallow_at_the_same_head_matches_cold() {
    let fixture = ShallowFixture::new(3);
    let (shallow, _) = churn(&fixture.root, &fixture.cache, false);
    assert!(shallow.shallow_clone);
    assert_eq!(fixture.index_commits(&shallow), 1);
    let (_, still_shallow_hit) = churn(&fixture.root, &fixture.cache, false);
    assert!(
        still_shallow_hit,
        "an unchanged shallow clone reuses the cache"
    );

    git(&fixture.root, &["fetch", "--quiet", "--unshallow"], None);

    let warm = fixture.warm_matching_cold();
    assert!(!warm.shallow_clone);
    assert_eq!(fixture.index_commits(&warm), 3);
}

#[test]
fn warm_cache_after_unshallow_and_a_new_commit_matches_cold() {
    let fixture = ShallowFixture::new(3);
    let (shallow, _) = churn(&fixture.root, &fixture.cache, false);
    assert!(shallow.shallow_clone);

    git(&fixture.root, &["fetch", "--quiet", "--unshallow"], None);
    commit_file(
        &fixture.root,
        "src/index.ts",
        "export const value = 99;\n",
        BASE_EPOCH + 10 * SECS_PER_DAY,
    );

    let warm = fixture.warm_matching_cold();
    assert!(!warm.shallow_clone);
    assert_eq!(fixture.index_commits(&warm), 4);
}

#[test]
fn warm_cache_after_deepen_matches_cold() {
    let fixture = ShallowFixture::new(4);
    let (shallow, _) = churn(&fixture.root, &fixture.cache, false);
    assert!(shallow.shallow_clone);

    git(&fixture.root, &["fetch", "--quiet", "--deepen", "1"], None);

    let warm = fixture.warm_matching_cold();
    assert!(warm.shallow_clone, "a deepened clone is still shallow");
    assert_eq!(fixture.index_commits(&warm), 2);
}

#[test]
fn sibling_roots_that_share_a_cache_dir_do_not_share_churn() {
    let fixture = Fixture::new();
    let root = &fixture.root;
    commit_file(root, "packages/app/src/a.ts", "a1", BASE_EPOCH);
    commit_file(
        root,
        "packages/lib/src/b.ts",
        "b1",
        BASE_EPOCH + SECS_PER_DAY,
    );
    let app = root.join("packages/app");
    let lib = root.join("packages/lib");
    let shared = tempfile::tempdir().expect("shared cache directory");

    let (app_result, _) = churn(&app, shared.path(), false);
    assert_eq!(
        changed_files(&app_result, &app),
        vec!["src/a.ts".to_string()]
    );

    let (lib_result, from_cache) = churn(&lib, shared.path(), false);
    assert!(!from_cache, "the entry of another root is not reused");
    assert_eq!(
        changed_files(&lib_result, &lib),
        vec!["src/b.ts".to_string()]
    );
    let (cold, _) = churn(&lib, shared.path(), true);
    assert_eq!(churn_rows(&lib_result, &lib), churn_rows(&cold, &lib));
}

#[test]
fn an_older_head_date_does_not_reuse_a_cache_with_a_later_cutoff() {
    let fixture = Fixture::new();
    let root = &fixture.root;
    commit_file(root, "src/old.ts", "old", BASE_EPOCH);
    commit_file(root, "src/new.ts", "new", BASE_EPOCH + 100 * SECS_PER_DAY);
    // The cutoff is day 10, so this entry does not hold `src/old.ts`.
    let (first, _) = churn(root, &fixture.cache, false);
    assert_eq!(changed_files(&first, root), vec!["src/new.ts".to_string()]);

    // HEAD is dated day 80. The cutoff moves back to day -10.
    commit_file(root, "src/late.ts", "late", BASE_EPOCH + 80 * SECS_PER_DAY);
    let (warm, _) = churn(root, &fixture.cache, false);
    let (cold, _) = churn(root, &root.join(".fallow-cold-cache"), true);
    assert_eq!(churn_rows(&warm, root), churn_rows(&cold, root));
    assert!(changed_files(&warm, root).contains(&"src/old.ts".to_string()));
}

#[test]
fn an_old_dated_commit_does_not_hide_an_in_window_ancestor() {
    let fixture = Fixture::new();
    let root = &fixture.root;
    let head = BASE_EPOCH + 400 * SECS_PER_DAY;
    commit_file(root, "src/x.ts", "x", head - 10 * SECS_PER_DAY);
    commit_file(root, "src/o.ts", "o", head - 200 * SECS_PER_DAY);
    commit_file(root, "src/h.ts", "h", head);

    let (cold, _) = churn(root, &root.join(".fallow-cold-cache"), true);
    assert_eq!(
        changed_files(&cold, root),
        vec!["src/h.ts".to_string(), "src/x.ts".to_string()]
    );

    let wide = SinceDuration::relative(1, ChurnWindowUnit::Years, "1 year");
    analyze_churn_cached(root, &wide, &fixture.cache, false).expect("wide churn");
    let (narrow, narrow_hit) =
        analyze_churn_cached(root, &window(), &fixture.cache, false).expect("narrow churn");
    assert!(narrow_hit, "the 1y entry covers the 90 day request");
    assert_eq!(churn_rows(&narrow, root), churn_rows(&cold, root));
}