geolith-dataset-builder 0.2.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! `geolith dataset prune`: the disk hygiene of the datasets pipeline.
//!
//! Ported from `prunePlan` of the former `scripts/datasets/refresh.ts`. It plans what may
//! go — source rasters outside a dataset's keep set, stages beyond the four
//! newest of their dataset and country, and the two temporary roots — and
//! deletes it only when asked. The keep set is what a rebuild or a rollback
//! still reads: the baseline years of the normals, the last twelve periods of
//! the series, the season of the newest period, the four newest stages of every
//! (dataset, country), the published build and every stage not yet uploaded.
//! Nothing a running pass is writing is ever a candidate.

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use anyhow::{Context, Result};

use crate::cli::PruneArgs;
use crate::config::{DatasetConfig, Reader};
use crate::layout::{data_root, read_json, repo_root};
use crate::rasters::match_template;

/// Stages kept per (dataset, country), beside the published and the unuploaded
/// ones: four builds, so a period can be re-published while the next two land.
pub const STAGES_KEPT: usize = 4;

/// Series periods whose source rasters stay: the length of a build's series.
pub const SERIES_PERIODS: usize = 12;

/// A source raster written this recently may belong to a pass that is still
/// reading it (a download in flight, a baseline file waiting for `values`), so
/// prune never deletes it: a day is two runs' worth of slack.
pub const RECENT_SECS: u64 = 24 * 60 * 60;

/// One file or directory prune may delete.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Candidate {
    /// `source`, `stage`, `temp` or `build`.
    pub kind: &'static str,
    /// The dataset the path belongs to.
    pub dataset: String,
    /// The file or directory.
    pub path: PathBuf,
    /// Its size in bytes.
    pub bytes: u64,
    /// Why it may go.
    pub reason: String,
}

/// One dataset prune looks at.
#[derive(Debug, Clone)]
pub struct DatasetInput {
    /// The dataset id.
    pub id: String,
    /// The country whose rasters this is.
    pub cc: String,
    /// Its config, for the reader kind.
    pub config: DatasetConfig,
    /// The source dir of the pair: `datasets/<id>/src`, or `src/<cc>` for a
    /// windowed dataset (NDVI), whose rasters are per country.
    pub src: PathBuf,
    /// The baseline years the normals read, `1991-2020`.
    pub baseline: String,
    /// The first month of the season (`06-01` → 6), when the dataset has one.
    pub season_month: Option<u8>,
}

/// One stage on disk.
#[derive(Debug, Clone)]
pub struct StageEntry {
    /// The dataset its keys name.
    pub dataset: String,
    /// The country its keys name.
    pub cc: String,
    /// The build id (its directory name).
    pub id: String,
    /// Its stage directory.
    pub dir: PathBuf,
    /// Whether `uploaded.json` is there.
    pub uploaded: bool,
    /// Whether `published.json` is there: a build that was once live.
    pub published: bool,
}

/// Everything prune decides over.
#[derive(Debug, Clone)]
pub struct PruneInput {
    /// The data root.
    pub root: PathBuf,
    /// The datasets to walk.
    pub datasets: Vec<DatasetInput>,
    /// Every stage on disk.
    pub stages: Vec<StageEntry>,
}

/// Run `geolith dataset prune`.
///
/// # Errors
///
/// Fails when the data root or a config cannot be read, and when a candidate
/// cannot be deleted.
pub fn run(args: &PruneArgs) -> Result<()> {
    let root = data_root()?;
    let repo = repo_root()?;
    let input = collect(&root, &repo)?;
    let candidates = plan(&input);
    let mut total: u64 = 0;
    for item in &candidates {
        total += item.bytes;
        let verb = if args.dry_run {
            "WOULD DELETE"
        } else {
            "DELETE"
        };
        println!(
            "{verb} {}\t{}\t({})",
            human_bytes(item.bytes),
            item.path.display(),
            item.reason
        );
        if !args.dry_run {
            remove(item)?;
        }
    }
    let tail = if args.dry_run {
        " (nothing deleted)"
    } else {
        ""
    };
    println!(
        "{}: {} items, {}{tail}",
        if args.dry_run {
            "prune --dry-run"
        } else {
            "prune"
        },
        candidates.len(),
        human_bytes(total)
    );
    Ok(())
}

/// Delete every candidate without printing anything, returning the count and
/// the bytes deleted: the prune-on-publish of a refresh.
///
/// # Errors
///
/// Fails when a candidate cannot be deleted.
pub fn apply(candidates: &[Candidate]) -> Result<(usize, u64)> {
    let mut total = 0;
    for item in candidates {
        remove(item)?;
        total += item.bytes;
    }
    Ok((candidates.len(), total))
}

/// Delete one candidate.
fn remove(item: &Candidate) -> Result<()> {
    if item.path.is_dir() {
        fs::remove_dir_all(&item.path)
            .with_context(|| format!("removing {}", item.path.display()))?;
    } else {
        fs::remove_file(&item.path).with_context(|| format!("removing {}", item.path.display()))?;
    }
    Ok(())
}

/// The datasets and stages of `root`.
///
/// # Errors
///
/// Fails when the dataset config dir or the stage dir cannot be read.
pub fn collect(root: &Path, repo: &Path) -> Result<PruneInput> {
    let config_dir = repo.join("packages/dataset-builder/data/datasets");
    let current = crate::settings::current();
    let baseline = current
        .run
        .baseline
        .clone()
        .unwrap_or_else(|| "1991-2020".to_owned());
    let mut datasets = Vec::new();
    let countries = countries_of(&repo.join("packages/dataset-builder/data/datasets/countries"))?;
    for id in published_datasets(&config_dir)? {
        let config = DatasetConfig::load(&config_dir.join(format!("{id}.json")))?;
        let season_month = config
            .season_start
            .as_deref()
            .and_then(|day| day.split_once('-'))
            .and_then(|(month, _)| month.parse().ok());
        for cc in &countries {
            datasets.push(DatasetInput {
                src: source_dir(root, &id, cc, &config),
                season_month,
                config: config.clone(),
                id: id.clone(),
                cc: cc.clone(),
                baseline: baseline.clone(),
            });
        }
    }
    let stages = stages(root, current.key_root())?;
    Ok(PruneInput {
        root: root.to_path_buf(),
        datasets,
        stages,
    })
}

/// The country codes of `dir`: every `<cc>.json` config.
///
/// # Errors
///
/// Fails when `dir` cannot be read.
fn countries_of(dir: &Path) -> Result<Vec<String>> {
    let entries = fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?;
    let mut codes: Vec<String> = entries
        .flatten()
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .filter_map(|name| name.strip_suffix(".json").map(str::to_owned))
        .collect();
    codes.sort();
    Ok(codes)
}

/// The source dir of a dataset and country: a windowed dataset keeps one
/// folder per country, the others one folder shared by every country.
fn source_dir(root: &Path, dataset: &str, cc: &str, config: &DatasetConfig) -> PathBuf {
    let base = root.join("datasets").join(dataset).join("src");
    if config.reader == Reader::Windowed {
        base.join(cc)
    } else {
        base
    }
}

/// The dataset ids of `dir`: every config naming itself and holding a period
/// template, never `boundaries.json` and never a slot table.
///
/// # Errors
///
/// Fails when `dir` cannot be read.
pub fn published_datasets(dir: &Path) -> Result<Vec<String>> {
    let mut ids = Vec::new();
    let entries = fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?;
    let mut names: Vec<String> = entries
        .flatten()
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .filter(|name| name.ends_with(".json") && name != "boundaries.json")
        .collect();
    names.sort();
    for name in names {
        let Some(id) = name.strip_suffix(".json") else {
            continue;
        };
        let Ok(config) = DatasetConfig::load(&dir.join(&name)) else {
            continue;
        };
        if config.id == id {
            ids.push(id.to_owned());
        }
    }
    Ok(ids)
}

/// Every stage of the data root that holds a dataset key under `key_root`.
///
/// # Errors
///
/// Fails when the stage root cannot be read.
pub fn stages(root: &Path, key_root: &str) -> Result<Vec<StageEntry>> {
    let stage_root = root.join("datasets/stage");
    if !stage_root.is_dir() {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    let entries =
        fs::read_dir(&stage_root).with_context(|| format!("reading {}", stage_root.display()))?;
    for entry in entries.flatten() {
        let dir = entry.path();
        if !dir.is_dir() {
            continue;
        }
        let Ok(value) = read_json(&dir.join("stage.json")) else {
            continue;
        };
        let Some((dataset, cc)) = value
            .get("files")
            .and_then(|files| files.as_array())
            .into_iter()
            .flatten()
            .filter_map(|file| file.get("key").and_then(|key| key.as_str()))
            .filter_map(|key| key.strip_prefix(key_root))
            .map(|rest| rest.split('/').collect::<Vec<_>>())
            .find(|parts| parts.len() >= 2 && parts[0] != "boundaries")
            .map(|parts| (parts[0].to_owned(), parts[1].to_owned()))
        else {
            continue;
        };
        let id = entry.file_name().to_string_lossy().into_owned();
        out.push(StageEntry {
            dataset,
            cc,
            id,
            dir: dir.clone(),
            uploaded: dir.join("uploaded.json").is_file(),
            published: dir.join("published.json").is_file(),
        });
    }
    out.sort_by(|a, b| a.id.cmp(&b.id));
    Ok(out)
}

/// What prune would delete, largest first.
#[must_use]
pub fn plan(input: &PruneInput) -> Vec<Candidate> {
    let mut out = Vec::new();
    for dataset in &input.datasets {
        let rasters = source_rasters(&dataset.src, &dataset.config);
        let keys: Vec<String> = rasters.iter().map(|(key, _)| key.clone()).collect();
        let keep = kept_source_keys(
            &dataset.config,
            &keys,
            &dataset.baseline,
            dataset.season_month,
        );
        for (key, path) in rasters {
            if keep.contains(&key) || in_use(&path) || written_recently(&path) {
                continue;
            }
            out.push(Candidate {
                kind: "source",
                dataset: dataset.id.clone(),
                bytes: bytes_of(&path),
                path,
                reason: format!(
                    "period {key} is neither in the baseline nor in the last {SERIES_PERIODS} periods"
                ),
            });
        }
    }
    for (dataset, cc) in groups(&input.stages) {
        let group: Vec<&StageEntry> = input
            .stages
            .iter()
            .filter(|stage| stage.dataset == dataset && stage.cc == cc)
            .collect();
        let newest: Vec<&str> = group
            .iter()
            .rev()
            .take(STAGES_KEPT)
            .map(|stage| stage.id.as_str())
            .collect();
        for stage in group {
            if newest.contains(&stage.id.as_str()) || !stage.uploaded || stage.published {
                continue;
            }
            if in_use(&stage.dir) {
                continue;
            }
            out.push(Candidate {
                kind: "stage",
                dataset: dataset.clone(),
                bytes: bytes_of(&stage.dir),
                path: stage.dir.clone(),
                reason: format!(
                    "not one of the {STAGES_KEPT} newest stages of {dataset}/{cc} ({})",
                    newest.join(", ")
                ),
            });
        }
    }
    let build_root = input.root.join("datasets/build");
    if build_root.is_dir() {
        let mut dirs: Vec<PathBuf> = fs::read_dir(&build_root)
            .into_iter()
            .flatten()
            .flatten()
            .map(|entry| entry.path())
            .filter(|path| path.is_dir() && !path_to_name(path).starts_with('.'))
            .collect();
        dirs.sort();
        if let Some((_, older)) = dirs.split_last() {
            for dir in older {
                out.push(Candidate {
                    kind: "build",
                    dataset: "rainfall".to_owned(),
                    bytes: bytes_of(dir),
                    path: dir.clone(),
                    reason: "a pre-stage copy of an earlier build; the newest is kept".to_owned(),
                });
            }
        }
    }
    out.sort_by_key(|item| std::cmp::Reverse(item.bytes));
    out
}

/// The distinct `(dataset, country)` pairs of `stages`.
fn groups(stages: &[StageEntry]) -> BTreeSet<(String, String)> {
    stages
        .iter()
        .map(|stage| (stage.dataset.clone(), stage.cc.clone()))
        .collect()
}

/// The last path segment.
fn path_to_name(path: &Path) -> String {
    path.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// Whether a running pass is writing `path`: any part file or partial
/// directory inside it, or a dump next to it.
fn in_use(path: &Path) -> bool {
    fn walk(dir: &Path) -> bool {
        let Ok(entries) = fs::read_dir(dir) else {
            return false;
        };
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            if name.ends_with(".part") || name.ends_with(".partial") || name.starts_with('.') {
                return true;
            }
            if entry.path().is_dir() && walk(&entry.path()) {
                return true;
            }
        }
        false
    }
    if path.is_dir() {
        walk(path)
    } else {
        let name = path_to_name(path);
        name.ends_with(".part") || name.ends_with(".partial")
    }
}

/// The source rasters under `src`: `(YYYY.MM.P, path)`, the prelim folder
/// first, and one entry per file.
#[must_use]
pub fn source_rasters(src: &Path, config: &DatasetConfig) -> Vec<(String, PathBuf)> {
    let mut out = Vec::new();
    let folders: [(&str, &str); 2] = [
        ("prelim", config.prelim_template()),
        ("final", config.file_template.as_str()),
    ];
    for (status, template) in folders {
        let dir = src.join(status);
        let Ok(entries) = fs::read_dir(&dir) else {
            continue;
        };
        let mut names: Vec<String> = entries
            .flatten()
            .filter(|entry| entry.path().is_file())
            .map(|entry| entry.file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        for name in names {
            if let Some(period) = match_template(template, &name) {
                out.push((
                    format!("{}.{:02}.{}", period.year, period.month, period.index),
                    dir.join(&name),
                ));
            }
        }
    }
    out
}

/// The period keys a dataset keeps as source rasters: every baseline year
/// (not for a windowed dataset, which keeps its normals in the values cache),
/// the last [`SERIES_PERIODS`], and the season of the newest period.
#[must_use]
pub fn kept_source_keys(
    config: &DatasetConfig,
    all: &[String],
    baseline: &str,
    season_month: Option<u8>,
) -> BTreeSet<String> {
    let mut sorted: Vec<&String> = all.iter().collect();
    sorted.sort();
    sorted.dedup();
    let mut keep = BTreeSet::new();
    let years: Vec<i32> = baseline
        .split_once('-')
        .map(|(from, to)| vec![from.parse().unwrap_or(0), to.parse().unwrap_or(0)])
        .unwrap_or_default();
    let keep_baseline = config.reader != Reader::Windowed;
    for key in &sorted {
        if let Some(year) = key_year(key)
            && keep_baseline
            && years.len() == 2
            && year >= years[0]
            && year <= years[1]
        {
            keep.insert((*key).clone());
        }
    }
    for key in sorted.iter().rev().take(SERIES_PERIODS) {
        keep.insert((*key).clone());
    }
    if let (Some(month), Some(latest)) = (season_month, sorted.last()) {
        let year = key_year(latest);
        for key in &sorted {
            if key_year(key) == year && key_month(key).is_some_and(|m| m >= month) {
                keep.insert((*key).clone());
            }
        }
    }
    keep
}

/// The year of a `YYYY.MM.P` key.
fn key_year(key: &str) -> Option<i32> {
    key.split('.').next()?.parse().ok()
}

/// The month of a `YYYY.MM.P` key.
fn key_month(key: &str) -> Option<u8> {
    key.split('.').nth(1)?.parse().ok()
}

/// Whether `path` was written within [`RECENT_SECS`]: a pass may still read it.
fn written_recently(path: &Path) -> bool {
    let Ok(modified) = fs::metadata(path).and_then(|meta| meta.modified()) else {
        return false;
    };
    let Ok(age) = SystemTime::now().duration_since(modified) else {
        // A clock before the file's mtime is a file being written now.
        return true;
    };
    age.as_secs() < RECENT_SECS
}

/// The size of a file or of everything under a directory.
#[must_use]
pub fn bytes_of(path: &Path) -> u64 {
    let Ok(meta) = fs::metadata(path) else {
        return 0;
    };
    if !meta.is_dir() {
        return meta.len();
    }
    let Ok(entries) = fs::read_dir(path) else {
        return 0;
    };
    entries.flatten().map(|entry| bytes_of(&entry.path())).sum()
}

/// `1.2 GB` of a byte count: 1000 to the unit, one decimal above bytes.
#[must_use]
pub fn human_bytes(bytes: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1000.0 && unit < UNITS.len() - 1 {
        value /= 1000.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{value:.0} {}", UNITS[unit])
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::UNIX_EPOCH;

    fn write(path: &Path, text: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("mkdir");
        }
        fs::write(path, text).expect("write");
    }

    fn config() -> DatasetConfig {
        DatasetConfig::load(
            &Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/rainfall.json"),
        )
        .expect("rainfall.json loads")
    }

    #[test]
    fn the_keep_set_is_the_baseline_the_last_twelve_and_the_season() {
        let config = config();
        let mut keys: Vec<String> = ["1985.01.1", "1991.01.1", "2020.12.6", "2025.12.1"]
            .iter()
            .map(|key| (*key).to_owned())
            .collect();
        for month in 1..=12 {
            keys.push(format!("2026.{month:02}.1"));
        }
        let keep = kept_source_keys(&config, &keys, "1991-2020", Some(6));
        // The baseline years; the last twelve (all of 2026); the season of the
        // newest period (2026, month 06 on).
        assert!(keep.contains("1991.01.1"), "{keep:?}");
        assert!(keep.contains("2020.12.6"), "{keep:?}");
        assert!(keep.contains("2026.03.1"), "{keep:?}");
        assert!(keep.contains("2026.12.1"), "{keep:?}");
        assert!(!keep.contains("1985.01.1"), "{keep:?}");
        // 2025.12.1 is not a baseline year, is older than the last twelve and
        // is not in the newest period's year.
        assert!(!keep.contains("2025.12.1"), "{keep:?}");
        // Two baseline years outside the last twelve, plus the twelve of 2026.
        assert_eq!(keep.len(), 14, "{keep:?}");
    }

    #[test]
    fn a_windowed_dataset_keeps_no_baseline_years() {
        let mut config = config();
        config.reader = Reader::Windowed;
        let mut keys: Vec<String> = vec!["1995.06.1".to_owned()];
        for month in 1..=12 {
            keys.push(format!("2026.{month:02}.1"));
        }
        let keep = kept_source_keys(&config, &keys, "1991-2020", None);
        assert_eq!(keep.len(), 12, "{keep:?}");
        assert!(!keep.contains("1995.06.1"), "{keep:?}");
    }

    #[test]
    fn the_last_twelve_periods_are_kept_in_period_order() {
        let config = config();
        let mut keys = vec!["2025.12.6".to_owned()];
        for month in 1..=12 {
            keys.push(format!("2026.{month:02}.1"));
        }
        let keep = kept_source_keys(&config, &keys, "1991-2020", None);
        assert_eq!(keep.len(), 12);
        assert!(!keep.contains("2025.12.6"), "{keep:?}");
        assert!(keep.contains("2026.01.1") && keep.contains("2026.12.1"));
    }

    #[test]
    fn four_stages_per_country_stay_and_the_older_uploaded_one_goes() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let mut stages = Vec::new();
        for (index, id) in [
            "2026-11-01.20261101T0000Z",
            "2026-11-02.20261102T0000Z",
            "2026-11-03.20261103T0000Z",
            "2026-11-04.20261104T0000Z",
            "2026-11-05.20261105T0000Z",
            "2026-11-06.20261106T0000Z",
            "2026-11-07.20261107T0000Z",
        ]
        .iter()
        .enumerate()
        {
            let path = dir.path().join(id);
            write(&path.join("stage.json"), "{}");
            stages.push(StageEntry {
                dataset: "rainfall".to_owned(),
                cc: "in".to_owned(),
                id: (*id).to_owned(),
                dir: path,
                uploaded: true,
                published: index == 3,
            });
        }
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: Vec::new(),
            stages,
        };
        let candidates = plan(&input);
        let ids: Vec<&str> = candidates
            .iter()
            .filter(|item| item.kind == "stage")
            .map(|item| item.path.file_name().unwrap().to_str().unwrap())
            .collect();
        // The three newest stay and 11-04 stays because it was published.
        assert_eq!(
            ids,
            vec![
                "2026-11-01.20261101T0000Z",
                "2026-11-02.20261102T0000Z",
                "2026-11-03.20261103T0000Z",
            ],
            "{candidates:?}"
        );
    }

    #[test]
    fn an_unuploaded_or_published_stage_is_never_a_candidate() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let mut stages = Vec::new();
        for (id, uploaded, published) in [
            ("2026-11-01.20261101T0000Z", false, false),
            ("2026-11-02.20261102T0000Z", true, true),
            ("2026-11-03.20261103T0000Z", true, false),
            ("2026-11-04.20261104T0000Z", true, false),
            ("2026-11-05.20261105T0000Z", true, false),
            ("2026-11-06.20261106T0000Z", true, false),
        ] {
            let path = dir.path().join(id);
            write(&path.join("stage.json"), "{}");
            stages.push(StageEntry {
                dataset: "ndvi".to_owned(),
                cc: "in".to_owned(),
                id: id.to_owned(),
                dir: path,
                uploaded,
                published,
            });
        }
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: Vec::new(),
            stages,
        };
        assert!(plan(&input).is_empty());
    }

    #[test]
    fn the_countries_of_one_dataset_keep_their_own_four() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let mut stages = Vec::new();
        for id in [
            "2026-11-01.20261101T0000Z",
            "2026-11-02.20261102T0000Z",
            "2026-11-03.20261103T0000Z",
            "2026-11-04.20261104T0000Z",
            "2026-11-05.20261105T0000Z",
        ] {
            for cc in ["in", "us"] {
                let path = dir.path().join(format!("{cc}-{id}"));
                write(&path.join("stage.json"), "{}");
                stages.push(StageEntry {
                    dataset: "rainfall".to_owned(),
                    cc: cc.to_owned(),
                    id: id.to_owned(),
                    dir: path,
                    uploaded: true,
                    published: false,
                });
            }
        }
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: Vec::new(),
            stages,
        };
        let candidates = plan(&input);
        // The oldest of each country goes: two candidates, not one.
        assert_eq!(candidates.len(), 2, "{candidates:?}");
        assert!(candidates.iter().all(|item| item.kind == "stage"));
    }

    #[test]
    fn a_stage_with_a_part_file_is_in_use_and_stays() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let mut stages = Vec::new();
        for (index, id) in [
            "2026-11-01.20261101T0000Z",
            "2026-11-02.20261102T0000Z",
            "2026-11-03.20261103T0000Z",
            "2026-11-04.20261104T0000Z",
            "2026-11-05.20261105T0000Z",
        ]
        .iter()
        .enumerate()
        {
            let path = dir.path().join(id);
            write(&path.join("stage.json"), "{}");
            if index == 0 {
                write(&path.join("tiles/.numbers.parquet.part"), "x");
            }
            stages.push(StageEntry {
                dataset: "rainfall".to_owned(),
                cc: "in".to_owned(),
                id: (*id).to_owned(),
                dir: path,
                uploaded: true,
                published: false,
            });
        }
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: Vec::new(),
            stages,
        };
        assert!(plan(&input).is_empty());
    }

    #[test]
    fn a_stage_with_a_partial_or_a_hidden_file_is_in_use_and_stays() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let mut stages = Vec::new();
        for (index, id) in [
            "2026-11-01.20261101T0000Z",
            "2026-11-02.20261102T0000Z",
            "2026-11-03.20261103T0000Z",
            "2026-11-04.20261104T0000Z",
            "2026-11-05.20261105T0000Z",
        ]
        .iter()
        .enumerate()
        {
            let path = dir.path().join(id);
            write(&path.join("stage.json"), "{}");
            if index == 0 {
                write(&path.join("tiles/numbers.partial"), "x");
            }
            if index == 1 {
                write(&path.join("tiles/.manifest.json"), "{}");
            }
            stages.push(StageEntry {
                dataset: "rainfall".to_owned(),
                cc: "in".to_owned(),
                id: (*id).to_owned(),
                dir: path,
                uploaded: true,
                published: false,
            });
        }
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: Vec::new(),
            stages,
        };
        // Two of the five uploaded stages would go by age, but both carry a
        // file a running pass is writing: a `.partial` and a dotfile.
        assert!(plan(&input).is_empty());
    }

    #[test]
    fn an_old_source_raster_goes_and_a_kept_one_stays() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let config = config();
        write(
            &dir.path().join("src/final/chirps-v3.0.1985.01.1.cog"),
            "old",
        );
        for month in 1..=12 {
            write(
                &dir.path()
                    .join(format!("src/final/chirps-v3.0.2026.{month:02}.1.cog")),
                "new",
            );
        }
        let dataset = DatasetInput {
            id: "rainfall".to_owned(),
            cc: "in".to_owned(),
            config,
            src: dir.path().join("src"),
            baseline: "1991-2020".to_owned(),
            season_month: Some(6),
        };
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: vec![dataset],
            stages: Vec::new(),
        };
        for entry in fs::read_dir(dir.path().join("src/final")).expect("read") {
            let path = entry.expect("entry").path();
            let file = fs::File::options().write(true).open(&path).expect("open");
            file.set_modified(UNIX_EPOCH).expect("an old mtime");
        }
        let candidates = plan(&input);
        assert_eq!(candidates.len(), 1, "{candidates:?}");
        assert!(candidates[0].path.ends_with("chirps-v3.0.1985.01.1.cog"));
        assert_eq!(candidates[0].bytes, 3);
        assert!(candidates[0].reason.contains("1985.01.1"));
    }

    #[test]
    fn a_raster_written_today_is_a_running_pass_and_stays() {
        let dir = tempfile::tempdir().expect("a temp dir");
        write(
            &dir.path().join("src/final/chirps-v3.0.1985.01.1.cog"),
            "old",
        );
        for month in 1..=12 {
            write(
                &dir.path()
                    .join(format!("src/final/chirps-v3.0.2026.{month:02}.1.cog")),
                "new",
            );
        }
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: vec![DatasetInput {
                id: "rainfall".to_owned(),
                cc: "in".to_owned(),
                config: config(),
                src: dir.path().join("src"),
                baseline: "1991-2020".to_owned(),
                season_month: Some(6),
            }],
            stages: Vec::new(),
        };
        // The 1985 file is outside the keep set, but it was written now.
        let candidates = plan(&input);
        assert!(candidates.is_empty(), "{candidates:?}");
    }

    #[test]
    fn only_the_newest_prestage_build_survives() {
        let dir = tempfile::tempdir().expect("a temp dir");
        for (name, bytes) in [("2026-11-01", 1), ("2026-11-02", 2), ("2026-11-03", 3)] {
            fs::create_dir_all(dir.path().join("datasets/build").join(name)).expect("mkdir");
            write(
                &dir.path().join("datasets/build").join(name).join("a.json"),
                &"x".repeat(bytes),
            );
        }
        let input = PruneInput {
            root: dir.path().to_path_buf(),
            datasets: Vec::new(),
            stages: Vec::new(),
        };
        let candidates = plan(&input);
        assert_eq!(candidates.len(), 2);
        assert!(candidates.iter().all(|item| item.kind == "build"));
        assert!(
            candidates
                .iter()
                .all(|item| !item.path.ends_with("2026-11-03"))
        );
    }

    #[test]
    fn byte_counts_are_human_in_powers_of_a_thousand() {
        assert_eq!(human_bytes(0), "0 B");
        assert_eq!(human_bytes(999), "999 B");
        assert_eq!(human_bytes(1000), "1.0 KB");
        assert_eq!(human_bytes(1_500_000), "1.5 MB");
        assert_eq!(human_bytes(2_500_000_000), "2.5 GB");
    }

    #[test]
    fn a_slot_table_is_not_a_dataset() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets");
        for name in ["rainfall.json", "rainfall-slots.json", "boundaries.json"] {
            fs::copy(source.join(name), dir.path().join(name)).expect("copy");
        }
        assert_eq!(
            published_datasets(dir.path()).expect("ids"),
            vec!["rainfall".to_owned()]
        );
    }

    #[test]
    fn a_stage_naming_a_boundaries_dataset_alone_is_skipped() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let stage = dir.path().join("datasets/stage/2026-11-01.20261101T0000Z");
        write(
            &stage.join("stage.json"),
            r#"{"files":[{"key":"datasets/boundaries/in/2026-10-21.0/areas.pmtiles"}]}"#,
        );
        assert!(stages(dir.path(), "datasets/").expect("stages").is_empty());
    }

    #[test]
    fn a_stage_is_read_under_the_configured_key_prefix_only() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let stage = dir.path().join("datasets/stage/2026-11-01.20261101T0000Z");
        write(
            &stage.join("stage.json"),
            r#"{"files":[{"key":"mirror/ds/rainfall/us/2026-11-01.20261101T0000Z/index.json"}]}"#,
        );
        let found = stages(dir.path(), "mirror/ds/").expect("stages");
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].dataset, "rainfall");
        assert_eq!(found[0].cc, "us");
        assert!(stages(dir.path(), "datasets/").expect("stages").is_empty());
    }
}