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
//! `geolith dataset run`: download, build and verify, then stop before upload.
//!
//! Ported from `run_cmd` and `build_cmd` of the former `scripts/datasets/datasets.sh`.
//! Every step is skipped when its output is already on disk — areas, normals
//! and the engine build — so a re-run only does the work the sources demand.
//! `--dry-run` takes the same decisions and prints them, touching nothing.

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

use anyhow::{Context, Result, bail};
use serde_json::Value;

use crate::areas;
use crate::cli::{AreasArgs, BuildArgs, FetchArgs, NormalsArgs, RunArgs, StageArgs, VerifyArgs};
use crate::config::{DatasetConfig, PeriodKind, Reader};
use crate::country::{BoundarySource, CountryConfig};
use crate::fetch;
use crate::files;
use crate::inputs;
use crate::layout::{self, Settings, read_json, settings};
use crate::stage;
use crate::verify;

/// The boundary release whose P1 normals (`…/normals/<baseline>/normals.csv`)
/// may be read in place instead of regenerated.
pub const LEGACY_NORMALS_RELEASE: &str = "2026-10-21.0";

/// Whether a step's output is already on disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    /// The output exists; the step has nothing to do.
    Reuse,
    /// The output is missing.
    Build,
}

/// The work `run` would do, decided from what is on disk before any step runs.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Plan {
    /// `$DATA_ROOT/datasets/<dataset>/<cc>/lists`.
    lists: PathBuf,
    /// The rasters of the series.
    src: PathBuf,
    /// The areas directory of the boundary release.
    areas_dir: PathBuf,
    /// Whether the areas are already there.
    areas: State,
    /// The normals CSV the engine build reads.
    normals: PathBuf,
    /// Whether the normals are already there.
    normals_state: State,
    /// Whether `normals` is the P1 layout, read where it lies.
    normals_legacy: bool,
    /// `$DATA_ROOT/datasets/<dataset>/<cc>/engine`.
    engine: PathBuf,
    /// The complete build with equal inputs to reuse, when there is one.
    build: Option<PathBuf>,
    /// The last day of the newest period on disk.
    end: String,
}

/// Run `geolith dataset run`.
///
/// # Errors
///
/// Fails when a step fails, when no raster is on disk, and when an incomplete
/// areas directory has to be moved away by hand.
pub fn run(args: &RunArgs) -> Result<()> {
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    if args.dry_run {
        let plan = plan(&s, args.rebuild)?;
        for line in plan_lines(&plan) {
            println!("{line}");
        }
        return Ok(());
    }
    fetch::run(&FetchArgs {
        baseline: false,
        boundaries: false,
        mode: None,
        country: s.cc.clone(),
        dataset: Some(s.dataset.clone()),
    })?;
    let dir = build(&s, args.rebuild)?;
    println!("{}", dir.display());
    let id = build_id_of(&dir);
    verify::run(&VerifyArgs {
        build_id: Some(id.clone()),
        dataset: Some(s.dataset.clone()),
        country: Some(s.cc.clone()),
    })?;
    println!("next: geolith dataset upload {id}");
    Ok(())
}

/// The areas, normals, engine build and stage of `s`; returns the stage dir.
///
/// # Errors
///
/// Fails when a step fails, when no raster is on disk, and when an incomplete
/// areas directory has to be moved away by hand.
pub fn build(s: &Settings, rebuild: bool) -> Result<PathBuf> {
    let config = DatasetConfig::load(&s.config_path)?;
    let country = CountryConfig::load(&s.country_config_path)?;
    let plan = plan(s, rebuild)?;
    areas_step(s, &country, &plan)?;
    normals_step(s, &config, &country, &plan)?;
    let build = engine_step(s, &config, &country, &plan)?;
    stage::run(&StageArgs {
        engine_build_dir: build,
        dataset: Some(s.dataset.clone()),
        country: Some(s.cc.clone()),
    })
}

/// The decisions of a run over the files at `s`.
fn plan(s: &Settings, rebuild: bool) -> Result<Plan> {
    let config = DatasetConfig::load(&s.config_path)?;
    let datasets = s.data_root.join("datasets");
    let src = datasets.join(&s.dataset).join("src");
    let areas_dir = datasets
        .join("boundaries")
        .join(&s.cc)
        .join(layout::boundaries_dir(s));
    let areas = areas_state(s, &areas_dir)?;
    let normals = datasets
        .join(&s.dataset)
        .join(&s.cc)
        .join("normals")
        .join(&s.boundary_release)
        .join(&s.baseline)
        .join("normals.csv");
    let legacy = datasets
        .join(&s.dataset)
        .join(&s.cc)
        .join("normals")
        .join(&s.baseline)
        .join("normals.csv");
    let (normals, normals_state, normals_legacy) = normals_state(s, &normals, &legacy);
    let Some((_, end)) = inputs::latest(&config, &src)? else {
        bail!("no raster to build in {}", src.display());
    };
    let engine = datasets.join(&s.dataset).join(&s.cc).join("engine");
    let mut build = None;
    if !rebuild && normals_state == State::Reuse {
        let record = inputs_record(s, &config, &src, &normals)?;
        let value = serde_json::to_value(&record).context("serializing the inputs record")?;
        build = matching_build(&engine, &end, &value);
    }
    Ok(Plan {
        lists: datasets.join(&s.dataset).join(&s.cc).join("lists"),
        src,
        areas_dir,
        areas,
        normals,
        normals_state,
        normals_legacy,
        engine,
        build,
        end,
    })
}

/// The script's lines for `plan`, in order.
fn plan_lines(plan: &Plan) -> Vec<String> {
    let mut lines = vec![format!(
        "download: PLAN refresh series.txt season.txt in {}",
        plan.lists.display()
    )];
    lines.push(match plan.areas {
        State::Reuse => format!("areas: reusing {}", plan.areas_dir.display()),
        State::Build => format!("areas: PLAN build {}", plan.areas_dir.display()),
    });
    lines.push(match (plan.normals_state, plan.normals_legacy) {
        (State::Reuse, true) => format!(
            "normals: reusing {} (P1 layout, read in place)",
            plan.normals.display()
        ),
        (State::Reuse, false) => format!("normals: reusing {}", plan.normals.display()),
        (State::Build, _) => format!("normals: PLAN write {}", plan.normals.display()),
    });
    match &plan.build {
        Some(build) => {
            let id = build_id_of(build);
            lines.push(format!("engine: reusing {}", build.display()));
            lines.push(format!("stage: PLAN {id}"));
            lines.push(format!("verify: PLAN {id}"));
            lines.push(format!("next: geolith dataset upload {id}"));
        }
        None => {
            lines.push(format!(
                "engine: PLAN build {}.*",
                plan.engine.join(&plan.end).display()
            ));
            lines.push("stage: PLAN after the build".to_owned());
            lines.push("verify: PLAN after the build".to_owned());
            lines.push("next: geolith dataset upload <build-id>".to_owned());
        }
    }
    lines
}

/// The build id of a build directory.
fn build_id_of(build: &Path) -> String {
    build
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// Whether the areas of `dir` are complete, refused, or yet to be built.
fn areas_state(s: &Settings, dir: &Path) -> Result<State> {
    let complete = ["areas.geojson", "gaps.geojson", "areas.pmtiles"]
        .iter()
        .all(|name| dir.join(name).is_file());
    if complete {
        // An India areas dir from before the one-state-per-district check
        // lacks india_regions: its districts may have no state.
        if s.cc == "in" {
            let report = fs::read_to_string(dir.join("areas-report.json")).unwrap_or_default();
            if !report.contains("\"india_regions\"") {
                bail!(
                    "{} has no india_regions (made before the state check): move it away and rerun",
                    dir.join("areas-report.json").display()
                );
            }
        }
        return Ok(State::Reuse);
    }
    if dir.exists() {
        bail!(
            "{} lacks areas.geojson, gaps.geojson or areas.pmtiles: move it away and rerun",
            dir.display()
        );
    }
    Ok(State::Build)
}

/// The normals CSV to read and whether it exists, with the P1 fallback.
fn normals_state(s: &Settings, normals: &Path, legacy: &Path) -> (PathBuf, State, bool) {
    if normals.is_file() {
        return (normals.to_path_buf(), State::Reuse, false);
    }
    if s.boundary_release == LEGACY_NORMALS_RELEASE && legacy.is_file() {
        return (legacy.to_path_buf(), State::Reuse, true);
    }
    (normals.to_path_buf(), State::Build, false)
}

/// The newest complete build of `end` whose `inputs.json` equals `inputs`.
fn matching_build(engine: &Path, end: &str, inputs: &Value) -> Option<PathBuf> {
    complete_builds(engine, end)
        .into_iter()
        .rev()
        .find(|dir| read_json(&dir.join("inputs.json")).is_ok_and(|value| value == *inputs))
}

/// The complete builds of the period ending `end`, oldest first.
fn complete_builds(engine: &Path, end: &str) -> Vec<PathBuf> {
    let Ok(entries) = fs::read_dir(engine) else {
        return Vec::new();
    };
    let mut builds: Vec<PathBuf> = entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.join("manifest.json").is_file())
        .filter(|path| {
            build_id_of(path)
                .strip_prefix(end)
                .is_some_and(|rest| rest.starts_with('.'))
        })
        .collect();
    builds.sort();
    builds
}

/// The inputs record of a build over the files the plan names.
fn inputs_record(
    s: &Settings,
    config: &DatasetConfig,
    src: &Path,
    normals: &Path,
) -> Result<inputs::InputsRecord> {
    let engine = std::env::current_exe().context("reading the running binary")?;
    inputs::record(
        config,
        src,
        &engine,
        &s.published_csv,
        normals,
        &areas_geojson(s),
        crosswalk(s)?.as_deref(),
    )
}

/// `$DATA_ROOT/datasets/boundaries/<cc>/<release>/areas.geojson`.
fn areas_geojson(s: &Settings) -> PathBuf {
    s.data_root
        .join("datasets/boundaries")
        .join(&s.cc)
        .join(layout::boundaries_dir(s))
        .join("areas.geojson")
}

/// The district crosswalk: `CROSSWALK_CSV` wins, else the repo's file when
/// it exists.
fn crosswalk(s: &Settings) -> Result<Option<PathBuf>> {
    if let Some(path) = crate::settings::current().run.crosswalk_csv.clone() {
        if path.as_os_str().is_empty() {
            return Ok(None);
        }
        if !path.is_file() {
            bail!("crosswalk not found: {}", path.display());
        }
        return Ok(Some(path));
    }
    let path = s
        .repo
        .join("packages/dataset-builder/data/datasets")
        .join(&s.cc)
        .join("districts-crosswalk.csv");
    Ok(path.is_file().then_some(path))
}

/// `dir` as its sibling `.name.partial`, where a step writes before a rename.
fn partial_of(dir: &Path) -> PathBuf {
    let name = dir
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    dir.with_file_name(format!(".{name}.partial"))
}

/// The flags of `dataset areas` for a country's boundary source.
fn areas_args(s: &Settings, country: &CountryConfig, out: &Path) -> AreasArgs {
    let mut args = AreasArgs {
        overture: None,
        country_config: None,
        boundaries_dir: None,
        countries: None,
        subtype: "county".to_owned(),
        india_outline: None,
        release: Some(s.boundary_release.clone()),
        max_zoom: 8,
        allow_districtless: None,
        out: out.to_path_buf(),
    };
    match country.boundaries.source {
        BoundarySource::Overture => {
            args.overture = Some(s.data_root.join("overture").join(&s.boundary_release));
            args.countries = Some(s.cc.to_uppercase());
            args.india_outline = Some(s.data_root.join("india/india-composite.geojson"));
        }
        BoundarySource::Shapefile => {
            args.country_config = Some(s.country_config_path.clone());
            args.boundaries_dir = Some(
                s.data_root
                    .join("datasets/boundaries")
                    .join(&s.cc)
                    .join("src")
                    .join(&country.boundaries.release),
            );
        }
    }
    args
}

/// Cut the areas when the plan says they are missing.
fn areas_step(s: &Settings, country: &CountryConfig, plan: &Plan) -> Result<()> {
    build_areas(s, country, &plan.areas_dir, plan.areas)
}

/// Make sure a country's areas exist; returns their directory. Used by the
/// NDVI clip, which needs the areas before any raster is on disk.
///
/// # Errors
///
/// Fails when an incomplete areas directory has to be moved away by hand, and
/// when the areas step fails.
pub fn ensure_areas(s: &Settings) -> Result<PathBuf> {
    let country = CountryConfig::load(&s.country_config_path)?;
    let dir = s
        .data_root
        .join("datasets/boundaries")
        .join(&s.cc)
        .join(layout::boundaries_dir(s));
    let state = areas_state(s, &dir)?;
    build_areas(s, &country, &dir, state)?;
    Ok(dir)
}

/// Build the areas of `dir` unless they are complete, then move the partial
/// tree into place.
fn build_areas(s: &Settings, country: &CountryConfig, dir: &Path, state: State) -> Result<()> {
    if state == State::Reuse {
        println!("areas: reusing {}", dir.display());
        return Ok(());
    }
    let partial = partial_of(dir);
    if partial.exists() {
        fs::remove_dir_all(&partial).with_context(|| format!("removing {}", partial.display()))?;
    }
    areas::run(&areas_args(s, country, &partial))?;
    fs::create_dir_all(
        dir.parent()
            .with_context(|| format!("{} has no parent", dir.display()))?,
    )
    .with_context(|| format!("creating the parent of {}", dir.display()))?;
    fs::rename(&partial, dir)
        .with_context(|| format!("renaming {} to {}", partial.display(), dir.display()))?;
    Ok(())
}

/// Every slot of a period kind, comma-separated: `01-1` … `12-6` (pentad) or
/// `01-1` … `12-3` (dekad).
#[must_use]
pub fn all_slots(kind: PeriodKind) -> String {
    let last = kind.periods_per_month();
    let mut slots: Vec<String> = Vec::new();
    for month in 1..=12_u8 {
        for index in 1..=last {
            slots.push(format!("{month:02}-{index}"));
        }
    }
    slots.join(",")
}

/// Write the normals when the plan says they are missing.
fn normals_step(
    s: &Settings,
    config: &DatasetConfig,
    country: &CountryConfig,
    plan: &Plan,
) -> Result<()> {
    if plan.normals_state == State::Reuse {
        if plan.normals_legacy {
            println!(
                "normals: reusing {} (P1 layout, read in place)",
                plan.normals.display()
            );
        } else {
            println!("normals: reusing {}", plan.normals.display());
        }
        return Ok(());
    }
    let dir = plan
        .normals
        .parent()
        .with_context(|| format!("{} has no parent", plan.normals.display()))?;
    let partial = dir.join(".normals.partial");
    if partial.exists() {
        fs::remove_dir_all(&partial).with_context(|| format!("removing {}", partial.display()))?;
    }
    fs::create_dir_all(&partial).with_context(|| format!("creating {}", partial.display()))?;
    let windowed = config.reader == Reader::Windowed;
    let cache_dir = s
        .data_root
        .join("datasets")
        .join(&s.dataset)
        .join(&s.cc)
        .join("cache")
        .join(&s.boundary_release)
        .join("values");
    let args = NormalsArgs {
        config: s.config_path.clone(),
        rasters: if windowed {
            cache_dir.clone()
        } else {
            plan.src.clone()
        },
        areas: areas_geojson(s),
        baseline: s.baseline.clone(),
        slots: all_slots(config.period),
        out: partial.join("normals.csv"),
        cache: if windowed { Some(cache_dir) } else { None },
        allow_empty: country
            .limits(&s.dataset)
            .is_some_and(|limits| limits.min_coverage_pct.is_some()),
    };
    crate::normals::run(&args)?;
    let stats = partial.join("normals-stats.json");
    if stats.is_file() {
        let dest = dir.join("normals-stats.json");
        fs::rename(&stats, &dest)
            .with_context(|| format!("renaming {} to {}", stats.display(), dest.display()))?;
    }
    let written = partial.join("normals.csv");
    fs::rename(&written, &plan.normals).with_context(|| {
        format!(
            "renaming {} to {}",
            written.display(),
            plan.normals.display()
        )
    })?;
    fs::remove_dir_all(&partial).with_context(|| format!("removing {}", partial.display()))?;
    Ok(())
}

/// The flags of `dataset build` for a country.
fn build_args(s: &Settings, country: &CountryConfig, plan: &Plan) -> Result<BuildArgs> {
    Ok(BuildArgs {
        config: s.config_path.clone(),
        rasters: plan.src.clone(),
        areas: areas_geojson(s),
        normals: Some(plan.normals.clone()),
        india_outline: country
            .boundaries
            .holds_soi_land
            .then(|| s.data_root.join("india/india-composite.geojson")),
        published: Some(s.published_csv.clone()),
        crosswalk: crosswalk(s)?,
        layer_periods: None,
        country_config: Some(s.country_config_path.clone()),
        bounds: None,
        min_coverage: None,
        codes_attribution: None,
        out: plan.engine.clone(),
    })
}

/// Reuse the matching build or run a new one, and record its inputs.
fn engine_step(
    s: &Settings,
    config: &DatasetConfig,
    country: &CountryConfig,
    plan: &Plan,
) -> Result<PathBuf> {
    if let Some(build) = &plan.build {
        println!("engine: reusing {}", build.display());
        return Ok(build.clone());
    }
    fs::create_dir_all(&plan.engine)
        .with_context(|| format!("creating {}", plan.engine.display()))?;
    remove_partials(&plan.engine)?;
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .context("system clock is before 1970")?;
    let mut built_at = i64::try_from(now.as_secs()).context("system clock out of range")?;
    // Two builds started in one minute would share a build id.
    while plan
        .engine
        .join(files::build_id(&plan.end, built_at))
        .exists()
    {
        built_at += 60;
    }
    let build = files::run_at(&build_args(s, country, plan)?, built_at)?;
    let record = inputs_record(s, config, &plan.src, &plan.normals)?;
    let text = serde_json::to_string_pretty(&record).context("serializing the inputs record")?;
    let tmp = build.join(".inputs.json.tmp");
    fs::write(&tmp, format!("{text}\n")).with_context(|| format!("writing {}", tmp.display()))?;
    let dest = build.join("inputs.json");
    fs::rename(&tmp, &dest)
        .with_context(|| format!("renaming {} to {}", tmp.display(), dest.display()))?;
    println!("engine: built {}", build.display());
    Ok(build)
}

/// Remove the leftover `.<build-id>.partial` directories of an engine folder.
fn remove_partials(engine: &Path) -> Result<()> {
    for entry in fs::read_dir(engine).with_context(|| format!("reading {}", engine.display()))? {
        let entry = entry.with_context(|| format!("reading {}", engine.display()))?;
        let hidden = entry.file_name().to_string_lossy().starts_with('.');
        if hidden && entry.path().is_dir() {
            fs::remove_dir_all(entry.path())
                .with_context(|| format!("removing {}", entry.path().display()))?;
        }
    }
    Ok(())
}

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

    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 settings_for(data_root: &Path) -> Settings {
        let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
        s.data_root = data_root.to_path_buf();
        s
    }

    #[test]
    fn a_complete_areas_dir_is_reused() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let areas = dir.path().join("2026-10-21.0");
        for name in ["areas.geojson", "gaps.geojson", "areas.pmtiles"] {
            write(&areas.join(name), "{}");
        }
        write(&areas.join("areas-report.json"), r#"{"india_regions": 36}"#);
        let s = settings_for(dir.path());
        assert_eq!(areas_state(&s, &areas).expect("complete"), State::Reuse);
    }

    #[test]
    fn an_areas_dir_missing_a_file_is_refused_naming_it() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let areas = dir.path().join("2026-10-21.0");
        write(&areas.join("areas.geojson"), "{}");
        write(&areas.join("gaps.geojson"), "{}");
        let s = settings_for(dir.path());
        let err = areas_state(&s, &areas).expect_err("no areas.pmtiles");
        let text = format!("{err:#}");
        assert!(text.contains(&areas.display().to_string()), "{text}");
        assert!(text.contains("move it away and rerun"), "{text}");
    }

    #[test]
    fn an_india_report_without_india_regions_is_refused() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let areas = dir.path().join("2026-10-21.0");
        for name in ["areas.geojson", "gaps.geojson", "areas.pmtiles"] {
            write(&areas.join(name), "{}");
        }
        write(&areas.join("areas-report.json"), r#"{"areas": 787}"#);
        let s = settings_for(dir.path());
        let err = areas_state(&s, &areas).expect_err("no india_regions");
        assert!(format!("{err:#}").contains("no india_regions"), "{err:#}");
    }

    #[test]
    fn absent_areas_are_built() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let s = settings_for(dir.path());
        assert_eq!(
            areas_state(&s, &dir.path().join("2026-10-21.0")).expect("absent"),
            State::Build
        );
    }

    #[test]
    fn the_legacy_normals_are_read_only_for_their_release() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let legacy = dir.path().join("normals/1991-2020/normals.csv");
        write(&legacy, "area_id,06-1\n");
        let normals = dir
            .path()
            .join("normals/2026-10-21.0/1991-2020/normals.csv");
        let mut s = settings_for(dir.path());
        assert_eq!(
            normals_state(&s, &normals, &legacy),
            (legacy.clone(), State::Reuse, true)
        );
        s.boundary_release = "2026-12-01.0".to_owned();
        assert_eq!(
            normals_state(&s, &normals, &legacy),
            (normals.clone(), State::Build, false)
        );
        write(&normals, "area_id,06-1\n");
        assert_eq!(
            normals_state(&s, &normals, &legacy),
            (normals.clone(), State::Reuse, false)
        );
    }

    #[test]
    fn the_matching_build_is_the_newest_complete_one_with_equal_inputs() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let engine = dir.path().join("engine");
        let same = serde_json::json!({"engine_sha256": "aa", "rasters": []});
        let other = serde_json::json!({"engine_sha256": "bb", "rasters": []});
        for (name, inputs) in [
            ("2026-10-31.20261101T0000Z", Some(&same)),
            ("2026-10-31.20261102T0000Z", Some(&other)),
            ("2026-11-05.20261105T0000Z", Some(&same)),
        ] {
            let build = engine.join(name);
            write(&build.join("manifest.json"), "{}");
            if let Some(inputs) = inputs {
                write(&build.join("inputs.json"), &inputs.to_string());
            }
        }
        // A build without a manifest is not complete.
        let incomplete = engine.join("2026-10-31.20261031T0000Z");
        write(&incomplete.join("inputs.json"), &same.to_string());
        assert_eq!(
            matching_build(&engine, "2026-10-31", &same),
            Some(engine.join("2026-10-31.20261101T0000Z"))
        );
        assert_eq!(
            matching_build(&engine, "2026-10-31", &other),
            Some(engine.join("2026-10-31.20261102T0000Z"))
        );
        let none = serde_json::json!({"engine_sha256": "cc"});
        assert_eq!(matching_build(&engine, "2026-10-31", &none), None);
    }

    #[test]
    fn all_slots_are_the_pentads_and_dekads_of_a_year() {
        let pentads = all_slots(PeriodKind::Pentad);
        let list: Vec<&str> = pentads.split(',').collect();
        assert_eq!(list.len(), 72);
        assert_eq!(list.first().copied(), Some("01-1"));
        assert_eq!(list.last().copied(), Some("12-6"));
        assert_eq!(list[5], "01-6");
        assert_eq!(list[6], "02-1");
        let dekads = all_slots(PeriodKind::Dekad);
        let list: Vec<&str> = dekads.split(',').collect();
        assert_eq!(list.len(), 36);
        assert_eq!(list.first().copied(), Some("01-1"));
        assert_eq!(list.last().copied(), Some("12-3"));
    }

    #[test]
    fn the_plan_lines_name_every_step_in_the_script_order() {
        let plan = Plan {
            lists: PathBuf::from("/d/datasets/rainfall/in/lists"),
            src: PathBuf::from("/d/datasets/rainfall/src"),
            areas_dir: PathBuf::from("/d/datasets/boundaries/in/2026-10-21.0"),
            areas: State::Reuse,
            normals: PathBuf::from("/d/datasets/rainfall/in/normals/1991-2020/normals.csv"),
            normals_state: State::Reuse,
            normals_legacy: true,
            engine: PathBuf::from("/d/datasets/rainfall/in/engine"),
            build: Some(PathBuf::from(
                "/d/datasets/rainfall/in/engine/2026-10-31.20261101T0000Z",
            )),
            end: "2026-10-31".to_owned(),
        };
        assert_eq!(
            plan_lines(&plan),
            vec![
                "download: PLAN refresh series.txt season.txt in /d/datasets/rainfall/in/lists"
                    .to_owned(),
                "areas: reusing /d/datasets/boundaries/in/2026-10-21.0".to_owned(),
                "normals: reusing /d/datasets/rainfall/in/normals/1991-2020/normals.csv (P1 layout, read in place)"
                    .to_owned(),
                "engine: reusing /d/datasets/rainfall/in/engine/2026-10-31.20261101T0000Z"
                    .to_owned(),
                "stage: PLAN 2026-10-31.20261101T0000Z".to_owned(),
                "verify: PLAN 2026-10-31.20261101T0000Z".to_owned(),
                "next: geolith dataset upload 2026-10-31.20261101T0000Z".to_owned(),
            ]
        );
    }

    #[test]
    fn a_plan_without_a_build_plans_a_build() {
        let plan = Plan {
            lists: PathBuf::from("/d/lists"),
            src: PathBuf::from("/d/src"),
            areas_dir: PathBuf::from("/d/areas"),
            areas: State::Build,
            normals: PathBuf::from("/d/normals.csv"),
            normals_state: State::Build,
            normals_legacy: false,
            engine: PathBuf::from("/d/engine"),
            build: None,
            end: "2026-10-31".to_owned(),
        };
        let lines = plan_lines(&plan);
        assert_eq!(lines[1], "areas: PLAN build /d/areas");
        assert_eq!(lines[2], "normals: PLAN write /d/normals.csv");
        assert_eq!(lines[3], "engine: PLAN build /d/engine/2026-10-31.*");
        assert_eq!(
            lines.last().map(String::as_str),
            Some("next: geolith dataset upload <build-id>")
        );
    }

    #[test]
    fn a_partial_dir_is_the_hidden_sibling_of_its_target() {
        assert_eq!(
            partial_of(Path::new("/d/datasets/boundaries/in/2026-10-21.0")),
            PathBuf::from("/d/datasets/boundaries/in/.2026-10-21.0.partial")
        );
    }
}