geolith-dataset-builder 0.5.0

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
//! `geolith dataset verify`: the checks a stage must pass before an upload.
//!
//! Ported from the former `scripts/datasets/verify.ts`. Every file under `tiles/` is in
//! the public set, every area of the country has its file, every JSON,
//! CSV, `PMTiles` archive and Parquet file carries its attribution, the
//! downloads have as many rows as their sources, `LICENSE.txt` names its
//! licence, `stage.json` lists exactly the staged files with their digests,
//! `published` matches the country's list, and no area of the previous stage
//! is gone. Null season fields print `SEASON-MISSING`/`SEASON-STALE`
//! warnings, which never fail.

use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::Path;

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, NumberResultExt as _,
    Result,
};
use serde_json::Value;

use crate::cli::VerifyArgs;
use crate::config::DatasetConfig;
use crate::downloads::{CheckReport, check_parquet};
use crate::exit::Exit;
use crate::layout::{
    Settings, boundaries_dir, boundaries_prefix, build_prefix, complete_stages, files_under,
    is_public, read_json, settings, sha256_hex,
};
use crate::normals::parse_csv;
use crate::period::missing_season;

/// What `verify` found: the area count, the warnings and the failures.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
    /// Build id of the stage.
    pub build_id: String,
    /// Areas of the country in the boundaries.
    pub areas: usize,
    /// `SEASON-*` lines, printed before the failures.
    pub warnings: Vec<String>,
    /// One `VERIFY FAIL <reason>` line each.
    pub failures: Vec<String>,
}

/// Whether `value` is a non-empty string.
fn non_empty(value: Option<&Value>) -> bool {
    value
        .and_then(Value::as_str)
        .is_some_and(|text| !text.is_empty())
}

/// The `attribution` of `value`, when it is a non-empty string.
fn attribution_of(value: &Value) -> Option<&str> {
    value
        .get("attribution")
        .and_then(Value::as_str)
        .filter(|text| !text.is_empty())
}

/// The metadata JSON of the `PMTiles` v3 archive at `path`.
///
/// # Errors
///
/// Fails when the file is not a `PMTiles` v3 archive, its metadata is not
/// JSON, or its compression is not none or gzip.
fn pmtiles_metadata(path: &Path) -> Result<Value> {
    let mut file = fs::File::open(path).io_at(IoOp::Open, path)?;
    let mut header = [0_u8; 127];
    file.read_exact(&mut header)
        .io_step(format!("reading the header of {}", path.display()))?;
    if &header[..7] != b"PMTiles" || header[7] != 3 {
        return Err(DatasetError::stage("not a PMTiles v3 archive"));
    }
    let offset = u64::from_le_bytes(
        header[24..32]
            .try_into()
            .expect("eight bytes of the header"),
    );
    let length = u64::from_le_bytes(
        header[32..40]
            .try_into()
            .expect("eight bytes of the header"),
    );
    file.seek(SeekFrom::Start(offset)).io_at(IoOp::Seek, path)?;
    let mut raw = vec![0_u8; usize::try_from(length).number_of("metadata length")?];
    file.read_exact(&mut raw).io_at(IoOp::Stat, path)?;
    let text = match header[97] {
        1 => raw,
        2 => {
            let mut out = Vec::new();
            flate2::read::GzDecoder::new(raw.as_slice())
                .read_to_end(&mut out)
                .io_step("gunzipping the metadata")?;
            out
        }
        other => {
            return Err(DatasetError::stage(format!(
                "PMTiles internal compression {other} not supported"
            )));
        }
    };
    serde_json::from_slice(&text).json_of("the metadata is not JSON")
}

/// The records of CSV `text`: its header and its non-empty rows.
fn csv_table(text: &str) -> Result<(Vec<String>, Vec<Vec<String>>)> {
    let mut rows = parse_csv(text)?;
    if rows.is_empty() {
        return Ok((Vec::new(), Vec::new()));
    }
    let header = rows.remove(0);
    rows.retain(|row| row.len() > 1 || row.first().is_some_and(|cell| !cell.is_empty()));
    Ok((header, rows))
}

/// The data rows of the CSV at `path`, a `#` line being a comment.
fn csv_rows(path: &Path) -> Result<usize> {
    let text = fs::read_to_string(path).io_at(IoOp::Read, path)?;
    Ok(text
        .lines()
        .filter(|line| !line.trim().is_empty() && !line.trim_start().starts_with('#'))
        .skip(1)
        .count())
}

/// The cell at `column` of `row`, when it has one.
fn csv_cell(row: &[String], column: usize) -> Option<&str> {
    row.get(column).map(String::as_str)
}

/// The attribution failure of one staged file, or `None`.
fn attribution_failure(
    key: &str,
    path: &Path,
    expected: Option<&str>,
    checks: &mut HashMap<String, CheckReport>,
) -> Option<String> {
    let extension = key.rsplit('.').next().unwrap_or_default();
    let wrong = |value: Option<&str>| {
        value.is_some_and(|text| !text.is_empty())
            && expected.is_some_and(|want| value != Some(want))
    };
    match extension {
        "json" | "geojson" => {
            let value = match read_json(path) {
                Ok(value) => value,
                Err(error) => return Some(format!("cannot read {key}: {error}")),
            };
            let attribution = attribution_of(&value);
            if wrong(attribution) {
                return Some(format!("other attribution in {key}"));
            }
            if attribution.is_none() {
                return Some(format!("no attribution in {key}"));
            }
            None
        }
        "csv" => {
            let text = match fs::read_to_string(path) {
                Ok(text) => text,
                Err(error) => return Some(format!("cannot read {key}: {error}")),
            };
            let (header, rows) = match csv_table(&text) {
                Ok(table) => table,
                Err(error) => return Some(format!("cannot read {key}: {error}")),
            };
            let Some(column) = header.iter().position(|name| name == "attribution") else {
                return Some(format!("no attribution on every row of {key}"));
            };
            if rows.iter().any(|row| {
                csv_cell(row, column).is_some_and(|text| {
                    !text.is_empty() && expected.is_some_and(|want| text != want)
                })
            }) {
                return Some(format!("other attribution on a row of {key}"));
            }
            if rows.is_empty()
                || rows
                    .iter()
                    .any(|row| csv_cell(row, column).is_none_or(str::is_empty))
            {
                return Some(format!("no attribution on every row of {key}"));
            }
            None
        }
        "pmtiles" | "parquet" => {
            let attribution = if extension == "pmtiles" {
                match pmtiles_metadata(path) {
                    Ok(value) => attribution_of(&value).map(str::to_owned),
                    Err(error) => return Some(format!("cannot read {key}: {error}")),
                }
            } else {
                let report = match checks.get(key) {
                    Some(report) => report.clone(),
                    None => match check_parquet(path) {
                        Ok(report) => {
                            checks.insert(key.to_owned(), report.clone());
                            report
                        }
                        Err(error) => return Some(format!("cannot read {key}: {error}")),
                    },
                };
                report.attribution
            };
            if wrong(attribution.as_deref()) {
                return Some(format!("other attribution in the metadata of {key}"));
            }
            if attribution.is_none_or(|text| text.is_empty()) {
                return Some(format!("no attribution in the metadata of {key}"));
            }
            None
        }
        _ => None,
    }
}

/// The `series.json` failures of build `prefix`.
fn series_failures(dir: &Path, prefix: &str, index: &Value) -> Vec<String> {
    let rows = index
        .get("areas")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    let key = format!("{prefix}series.json");
    let path = dir.join(&key);
    if !path.is_file() {
        return if rows.iter().any(|row| row.get("value_class").is_some()) {
            vec![format!("missing {key} (index.json carries classes)")]
        } else {
            Vec::new()
        };
    }
    let series = match read_json(&path) {
        Ok(series) => series,
        Err(error) => return vec![format!("cannot read {key}: {error}")],
    };
    let mut failures = Vec::new();
    let ids: Vec<&Value> = rows.iter().filter_map(|row| row.get("id")).collect();
    let listed = series
        .get("areas")
        .and_then(Value::as_array)
        .map_or_else(Vec::new, |areas| areas.iter().collect());
    if serde_json::to_string(&listed).ok() != serde_json::to_string(&ids).ok() {
        failures.push(format!("{key} areas are not the index.json ids in order"));
    }
    for period in series
        .get("periods")
        .and_then(Value::as_array)
        .map_or(&[][..], Vec::as_slice)
    {
        let end = period
            .get("period_end")
            .and_then(Value::as_str)
            .unwrap_or_default();
        for field in ["value", "comparison"] {
            let text = period.get(field).and_then(Value::as_str);
            if text.is_none_or(|text| text.chars().count() != ids.len()) {
                failures.push(format!("{key} {end} {field} has not one class per area"));
            }
        }
        if let Some(tiles) = period.get("tiles").and_then(Value::as_str)
            && !dir.join(prefix).join(tiles).exists()
        {
            failures.push(format!("{key} {end} names {tiles}, not staged"));
        }
    }
    failures
}

/// The rows of the Parquet file at `key`, read back through the cache.
fn parquet_rows(
    key: &str,
    dir: &Path,
    checks: &mut HashMap<String, CheckReport>,
    failures: &mut Vec<String>,
) -> Option<i64> {
    let path = dir.join(key);
    if !path.exists() {
        return None;
    }
    if let Some(report) = checks.get(key) {
        return Some(report.rows);
    }
    match check_parquet(&path) {
        Ok(report) => {
            let rows = report.rows;
            checks.insert(key.to_owned(), report);
            Some(rows)
        }
        Err(error) => {
            failures.push(format!("cannot read {key}: {error}"));
            None
        }
    }
}

/// Check the stage at `dir`; `s` names its country and dataset.
///
/// # Errors
///
/// Fails only when a check itself cannot run; the failures of the stage are
/// in the [`Report`].
pub fn check(dir: &Path, s: &Settings) -> Result<Report> {
    let build_id = dir
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let prefix = build_prefix(s, &build_id);
    let mut failures: Vec<String> = Vec::new();
    let area_file = |area_id: &str| {
        dir.join(&prefix)
            .join("areas")
            .join(format!("{area_id}.json"))
            .is_file()
    };
    let country = s.country_config();
    let upper = s.cc.to_uppercase();
    let india = s.cc.eq_ignore_ascii_case("in");

    // Areas the coverage floor kept out of the index: they are in the boundary
    // layer, so they have no area file.
    let mut excluded = Vec::new();
    if let Ok(index) = read_json(&dir.join(&prefix).join("index.json"))
        && let Some(rows) = index.get("excluded").and_then(Value::as_array)
    {
        for row in rows {
            if let Some(id) = row.get("id").and_then(Value::as_str) {
                excluded.push(id.to_owned());
            }
        }
    }

    // Every area of the country has its file.
    let mut areas = 0_usize;
    let geojson = s
        .data_root
        .join("datasets/boundaries")
        .join(&s.cc)
        .join(boundaries_dir(s))
        .join("areas.geojson");
    let mut region_counts: BTreeMap<String, usize> = BTreeMap::new();
    let features = match read_json(&geojson) {
        Ok(collection) => collection
            .get("features")
            .and_then(Value::as_array)
            .cloned(),
        Err(error) => {
            failures.push(format!("cannot read {}: {error}", geojson.display()));
            None
        }
    };
    if let Some(features) = features {
        let mut stateless = Vec::new();
        for feature in &features {
            let props = feature.get("properties").cloned().unwrap_or(Value::Null);
            if props.get("country").and_then(Value::as_str) != Some(upper.as_str()) {
                continue;
            }
            let Some(id) = props.get("id").and_then(Value::as_str) else {
                continue;
            };
            areas += 1;
            if !area_file(id) && !excluded.iter().any(|excluded| excluded == id) {
                failures.push(format!("missing area file {prefix}areas/{id}.json"));
            }
            let region = props.get("region_code").and_then(Value::as_str);
            let parent = props.get("parent_name").and_then(Value::as_str);
            if india && (region.is_none_or(str::is_empty) || parent.is_none_or(str::is_empty)) {
                stateless.push(id.to_owned());
            } else if india && let Some(region) = region.filter(|text| !text.is_empty()) {
                *region_counts.entry(region.to_owned()).or_default() += 1;
            }
        }
        if areas == 0 {
            failures.push(format!("no {upper} areas in areas.geojson"));
        }
        if let Ok(report) = read_json(&geojson.with_file_name("areas-report.json"))
            && let Some(expected) = report
                .get("invariants")
                .and_then(|invariants| invariants.get("areas"))
                .and_then(Value::as_u64)
            && expected != u64::try_from(areas).unwrap_or(u64::MAX)
        {
            failures.push(format!(
                "areas.geojson holds {areas} {upper} areas, its areas-report.json asserts {expected}"
            ));
        }
        if !stateless.is_empty() {
            failures.push(format!(
                "{} districts without a state in areas.geojson: {}",
                stateless.len(),
                stateless.join(", ")
            ));
        }
    }
    // India: every coded state/UT of the release holds a district.
    if india {
        let report_path = geojson.with_file_name("areas-report.json");
        match read_json(&report_path) {
            Ok(report) => {
                let regions = report
                    .get("india_regions")
                    .and_then(Value::as_object)
                    .cloned()
                    .unwrap_or_default();
                let allowed: Vec<String> = report
                    .get("india_districtless_allowed")
                    .and_then(Value::as_array)
                    .map_or_else(Vec::new, |codes| {
                        codes
                            .iter()
                            .filter_map(Value::as_str)
                            .map(str::to_owned)
                            .collect()
                    });
                if regions.is_empty() {
                    failures.push(format!("no india_regions in {}", report_path.display()));
                }
                for (code, count) in &regions {
                    let count = count.as_u64().unwrap_or_default();
                    if count == 0 && !allowed.iter().any(|allowed| allowed == code) {
                        failures.push(format!("coded Indian region {code} has no district"));
                    }
                    let actual =
                        u64::try_from(*region_counts.get(code).unwrap_or(&0)).unwrap_or(u64::MAX);
                    if actual != count {
                        failures.push(format!(
                            "areas.geojson has {actual} districts in {code}, areas-report.json says {count}"
                        ));
                    }
                }
                for code in region_counts.keys() {
                    if !regions.contains_key(code) {
                        failures.push(format!(
                            "region {code} of areas.geojson is not a coded Indian region of areas-report.json"
                        ));
                    }
                }
            }
            Err(error) => failures.push(format!("cannot read {}: {error}", report_path.display())),
        }
    }

    // Attribution in every file; the archives, downloads and build files exist.
    for key in [
        format!("{prefix}tiles.pmtiles"),
        format!("{prefix}index.json"),
        format!("{prefix}numbers.csv"),
        format!("{prefix}numbers.parquet"),
        format!("{}areas.pmtiles", boundaries_prefix(s)),
        format!("{}areas.parquet", boundaries_prefix(s)),
        format!("{}LICENSE.txt", boundaries_prefix(s)),
    ] {
        if !dir.join(&key).exists() {
            failures.push(format!("missing {key}"));
        }
    }
    let index = read_json(&dir.join(&prefix).join("index.json")).unwrap_or(Value::Null);
    let expected = attribution_of(&index).map(str::to_owned);
    failures.extend(series_failures(dir, &prefix, &index));

    let mut checks: HashMap<String, CheckReport> = HashMap::new();
    let mut seasons: Vec<Value> = Vec::new();
    let mut any_code = false;
    let mut codes_unacknowledged = false;
    let top = s.key_top();
    let staged: Vec<String> = if dir.join(top).exists() {
        files_under(&dir.join(top))?
            .into_iter()
            .map(|relative| format!("{top}/{relative}"))
            .collect()
    } else {
        Vec::new()
    };
    for key in &staged {
        if !is_public(s, &build_id, key) {
            failures.push(format!("not public: {key}"));
        }
        let path = dir.join(key);
        let boundaries = key.starts_with(&boundaries_prefix(s));
        if let Some(failure) = attribution_failure(
            key,
            &path,
            if boundaries {
                None
            } else {
                expected.as_deref()
            },
            &mut checks,
        ) {
            failures.push(failure);
        } else if key.starts_with(&format!("{prefix}areas/")) {
            let area = read_json(&path).unwrap_or(Value::Null);
            if india && !non_empty(area.get("state")) {
                failures.push(format!("state is null in {key}"));
            }
            if area.get("lgd_code").is_some_and(|code| !code.is_null()) {
                if !non_empty(area.get("codes_attribution")) {
                    failures.push(format!("lgd_code without codes_attribution in {key}"));
                    codes_unacknowledged = true;
                } else {
                    any_code = true;
                }
            }
            seasons.push(area);
        }
    }

    // The downloads read back with as many rows as their sources.
    let numbers_parquet = format!("{prefix}numbers.parquet");
    let numbers_rows = parquet_rows(&numbers_parquet, dir, &mut checks, &mut failures);
    let numbers_csv = dir.join(&prefix).join("numbers.csv");
    if let Some(numbers_rows) = numbers_rows
        && numbers_csv.exists()
    {
        let text = fs::read_to_string(&numbers_csv).io_at(IoOp::Read, &numbers_csv)?;
        let csv = csv_table(&text)?.1.len();
        if numbers_rows != i64::try_from(csv).unwrap_or(i64::MAX) {
            failures.push(format!(
                "{numbers_parquet} has {numbers_rows} rows, numbers.csv has {csv}"
            ));
        }
    }
    let areas_parquet = format!("{}areas.parquet", boundaries_prefix(s));
    let areas_rows = parquet_rows(&areas_parquet, dir, &mut checks, &mut failures);
    let boundaries_areas = read_json(&geojson).ok().and_then(|collection| {
        collection
            .get("features")
            .and_then(Value::as_array)
            .map(Vec::len)
    });
    if let (Some(areas_rows), Some(boundaries_areas)) = (areas_rows, boundaries_areas)
        && areas_rows != i64::try_from(boundaries_areas).unwrap_or(i64::MAX)
    {
        failures.push(format!(
            "{areas_parquet} has {areas_rows} rows, areas.geojson has {boundaries_areas} areas"
        ));
    }
    let license = dir.join(boundaries_prefix(s)).join("LICENSE.txt");
    if let Ok(text) = fs::read_to_string(&license) {
        let licence_id = country
            .as_ref()
            .map_or("ODbL-1.0", |config| config.boundaries.licence_id.as_str());
        let words: &[&str] = match licence_id {
            "ODbL-1.0" => &["ODbL", "OpenStreetMap"],
            "CC0-1.0" => &["CC0"],
            "CC-BY-4.0" => &["CC BY 4.0"],
            other => &[other],
        };
        for word in words {
            if !text.contains(word) {
                failures.push(format!(
                    "{}LICENSE.txt does not name {word}",
                    boundaries_prefix(s)
                ));
            }
        }
    }

    // An index of a build with LGD codes acknowledges them too.
    if (any_code || codes_unacknowledged)
        && let Ok(index) = read_json(&dir.join(&prefix).join("index.json"))
        && !non_empty(index.get("codes_attribution"))
    {
        failures.push(format!(
            "lgd codes without codes_attribution in {prefix}index.json"
        ));
    }

    // stage.json matches the files.
    let mut stage_files: Vec<(String, u64, String)> = Vec::new();
    let mut stage_read = false;
    match read_json(&dir.join("stage.json")) {
        Ok(stage) => match stage.get("files").and_then(Value::as_array) {
            Some(files) => {
                for file in files {
                    let key = file
                        .get("key")
                        .and_then(Value::as_str)
                        .unwrap_or_default()
                        .to_owned();
                    let bytes = file
                        .get("bytes")
                        .and_then(Value::as_u64)
                        .unwrap_or_default();
                    let sha256 = file
                        .get("sha256")
                        .and_then(Value::as_str)
                        .unwrap_or_default()
                        .to_owned();
                    stage_files.push((key, bytes, sha256));
                }
                stage_read = true;
            }
            None => failures.push("cannot read stage.json: no files list".to_owned()),
        },
        Err(error) => failures.push(format!("cannot read stage.json: {error}")),
    }
    let listed: Vec<&str> = stage_files.iter().map(|(key, _, _)| key.as_str()).collect();
    let empty: Vec<String> = Vec::new();
    for key in if stage_read { &staged } else { &empty } {
        if !listed.contains(&key.as_str()) {
            failures.push(format!("stage.json does not list {key}"));
        }
    }
    for (key, bytes, sha256) in &stage_files {
        let path = dir.join(key);
        if !path.exists() {
            failures.push(format!("stage.json lists missing {key}"));
        } else if fs::metadata(&path).io_at(IoOp::Read, &path)?.len() != *bytes {
            failures.push(format!("size of {key} differs from stage.json"));
        } else if sha256_hex(&path)? != *sha256 {
            failures.push(format!("sha256 of {key} differs from stage.json"));
        }
    }

    // published has one id per published.csv row, each with an area file.
    match read_json(&dir.join(&prefix).join("index.json")) {
        Ok(index) => {
            let published = index
                .get("published")
                .and_then(Value::as_array)
                .map_or_else(Vec::new, |ids| {
                    ids.iter()
                        .filter_map(Value::as_str)
                        .map(str::to_owned)
                        .collect()
                });
            match csv_rows(&s.published_csv) {
                Ok(rows) => {
                    if published.len() != rows {
                        failures.push(format!(
                            "index.json published has {} ids, {} has {rows} rows",
                            published.len(),
                            s.published_csv.display()
                        ));
                    }
                    for area_id in &published {
                        if !area_file(area_id) {
                            failures.push(format!(
                                "published area {area_id} has no areas/{area_id}.json"
                            ));
                        }
                    }
                }
                Err(error) => failures.push(format!("cannot check published: {error}")),
            }
        }
        Err(error) => failures.push(format!("cannot check published: {error}")),
    }

    // No area of the previous stage is gone.
    let previous = complete_stages(&s.stage_root)
        .into_iter()
        .rfind(|other| other < &build_id);
    if let Some(previous) = previous {
        let prev_areas = s
            .stage_root
            .join(&previous)
            .join(build_prefix(s, &previous))
            .join("areas");
        if let Ok(entries) = fs::read_dir(&prev_areas) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().into_owned();
                let id = name.strip_suffix(".json").unwrap_or(&name);
                if !area_file(id) {
                    failures.push(format!("area {id} of {previous} is missing"));
                }
            }
        }
    }

    // Null season fields: name the season periods not on disk (warnings).
    let mut warnings = Vec::new();
    let config_path = s
        .repo
        .join("packages/dataset-builder/data/datasets")
        .join(format!("{}.json", s.dataset));
    if let Ok(config) = DatasetConfig::load(&config_path)
        && let Some(area) = seasons.iter().find(|area| {
            non_empty(area.get("season_start"))
                && area.get("season_value").is_some_and(Value::is_null)
                && area.get("period_end").and_then(Value::as_str).is_some()
        })
    {
        let start = area
            .get("season_start")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let end = area
            .get("period_end")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let source = s.data_root.join("datasets").join(&s.dataset).join("src");
        let missing = missing_season(&config, &source, start, end)?;
        for key in &missing {
            warnings.push(format!("SEASON-MISSING {key}"));
        }
        if missing.is_empty() {
            warnings.push(format!("SEASON-STALE {build_id}"));
        }
    }

    Ok(Report {
        build_id,
        areas,
        warnings,
        failures,
    })
}

/// Run `geolith dataset verify`.
///
/// # Errors
///
/// Fails with [`Exit`] `1` when the stage fails a check, and when a check
/// itself cannot run.
pub fn run(args: &VerifyArgs) -> Result<()> {
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    let id = args
        .build_id
        .clone()
        .or_else(|| complete_stages(&s.stage_root).last().cloned());
    let Some(id) = id else {
        println!(
            "VERIFY FAIL no complete stage in {}",
            s.stage_root.display()
        );
        return Err(Exit(1).into());
    };
    let dir = s.stage_root.join(&id);
    if !dir.join("stage.json").is_file() {
        println!(
            "VERIFY FAIL no complete stage {id} in {}",
            s.stage_root.display()
        );
        return Err(Exit(1).into());
    }
    let report = check(&dir, &s)?;
    for warning in &report.warnings {
        println!("{warning}");
    }
    for failure in &report.failures {
        println!("VERIFY FAIL {failure}");
    }
    if !report.failures.is_empty() {
        return Err(Exit(1).into());
    }
    println!("VERIFY OK {id} {} areas", report.areas);
    Ok(())
}

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

    #[test]
    fn a_csv_without_an_attribution_column_has_no_attribution() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("numbers.csv");
        fs::write(&path, "id,value\na,1\n").expect("write");
        let failure = attribution_failure("numbers.csv", &path, None, &mut HashMap::new())
            .expect("a failure");
        assert_eq!(failure, "no attribution on every row of numbers.csv");
    }

    #[test]
    fn a_csv_with_the_attribution_on_every_row_passes() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("numbers.csv");
        fs::write(&path, "id,attribution\na,CHIRPS\nb,CHIRPS\n").expect("write");
        assert!(
            attribution_failure("numbers.csv", &path, Some("CHIRPS"), &mut HashMap::new())
                .is_none()
        );
    }

    #[test]
    fn a_json_with_another_attribution_is_refused() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("index.json");
        fs::write(&path, r#"{"attribution":"Mine"}"#).expect("write");
        let failure = attribution_failure("index.json", &path, Some("Theirs"), &mut HashMap::new())
            .expect("a failure");
        assert_eq!(failure, "other attribution in index.json");
    }

    #[test]
    fn a_build_id_must_be_dated() {
        assert!(crate::layout::is_build_id("2026-11-20.20261121T2329Z"));
        assert!(!crate::layout::is_build_id("2026-11-20"));
    }
}