use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use crate::error::{IoOp, IoResultExt as _, Result};
use crate::cli::PruneArgs;
use crate::config::{DatasetConfig, Reader};
use crate::layout::{data_root, read_json, repo_root};
use crate::rasters::match_template;
pub const STAGES_KEPT: usize = 4;
pub const SERIES_PERIODS: usize = 12;
pub const RECENT_SECS: u64 = 24 * 60 * 60;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Candidate {
pub kind: &'static str,
pub dataset: String,
pub path: PathBuf,
pub bytes: u64,
pub reason: String,
}
#[derive(Debug, Clone)]
pub struct DatasetInput {
pub id: String,
pub cc: String,
pub config: DatasetConfig,
pub src: PathBuf,
pub baseline: String,
pub season_month: Option<u8>,
}
#[derive(Debug, Clone)]
pub struct StageEntry {
pub dataset: String,
pub cc: String,
pub id: String,
pub dir: PathBuf,
pub uploaded: bool,
pub published: bool,
}
#[derive(Debug, Clone)]
pub struct PruneInput {
pub root: PathBuf,
pub datasets: Vec<DatasetInput>,
pub stages: Vec<StageEntry>,
}
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(())
}
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))
}
fn remove(item: &Candidate) -> Result<()> {
if item.path.is_dir() {
fs::remove_dir_all(&item.path).io_at(IoOp::Remove, &item.path)?;
} else {
fs::remove_file(&item.path).io_at(IoOp::Remove, &item.path)?;
}
Ok(())
}
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,
})
}
fn countries_of(dir: &Path) -> Result<Vec<String>> {
let entries = fs::read_dir(dir).io_at(IoOp::Read, dir)?;
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)
}
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
}
}
pub fn published_datasets(dir: &Path) -> Result<Vec<String>> {
let mut ids = Vec::new();
let entries = fs::read_dir(dir).io_at(IoOp::Read, dir)?;
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)
}
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).io_at(IoOp::Read, &stage_root)?;
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)
}
#[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
}
fn groups(stages: &[StageEntry]) -> BTreeSet<(String, String)> {
stages
.iter()
.map(|stage| (stage.dataset.clone(), stage.cc.clone()))
.collect()
}
fn path_to_name(path: &Path) -> String {
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default()
}
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")
}
}
#[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
}
#[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
}
fn key_year(key: &str) -> Option<i32> {
key.split('.').next()?.parse().ok()
}
fn key_month(key: &str) -> Option<u8> {
key.split('.').nth(1)?.parse().ok()
}
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 {
return true;
};
age.as_secs() < RECENT_SECS
}
#[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()
}
#[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));
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:?}");
assert!(!keep.contains("2025.12.1"), "{keep:?}");
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();
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);
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,
};
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(),
};
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());
}
}