geolith-dataset-builder 0.4.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
//! Area boundaries from an official boundary file.
//!
//! `geolith dataset areas --country-config countries/<cc>.json` runs this
//! module instead of the Overture reader when the country's boundaries come
//! from its own authority: two shapefiles (units and parents) with a field
//! mapping in the config, no crosswalk, no re-cut. One area per code, the
//! parts and holes of a record kept as the file draws them, a deterministic id
//! from the code ([`official_id`](super::country::official_id)), the parent
//! from the child's own parent field, and an antimeridian split so no ring
//! spans more than 180° of longitude.
//!
//! Gaps are always empty here: a gap piece exists because India's political
//! outline is bigger than its district coverage, and the union of an official
//! area set is the country itself.

use std::collections::BTreeMap;
use std::path::Path;

use crate::error::{DatasetError, IoOp, IoResultExt as _, Result};
use geo::{Area as _, Coord, LineString, MultiPolygon, Polygon};
use serde_json::{Value, json};
use shapefile::dbase::{FieldValue, Record as DbaseRecord};
use shapefile::record::traits::HasXY;

use super::areas::{Area, AreasFile, write_areas_geojson, write_collection, write_json};
use super::areas_tiles::write_areas_pmtiles;
use super::country::{BoundaryFile, CountryConfig, split_antimeridian};

/// One record of a boundary file.
struct BoundaryRecord {
    /// Position in the file, so an error can name it.
    index: usize,
    /// The publisher's code (`06037`).
    code: String,
    /// The publisher's name (`Los Angeles County`).
    name: String,
    /// The parent's code (`06`).
    parent: Option<String>,
    /// The record's rings, lon/lat.
    shape: MultiPolygon<f64>,
}

/// The text of `field` in `record`, when the record holds such a value.
fn field(record: &DbaseRecord, field: &str) -> Option<String> {
    record.get(field).and_then(|value| match value {
        FieldValue::Character(text) => text.clone(),
        _ => None,
    })
}

/// Write the areas of `config` from its boundary files.
///
/// # Errors
///
/// Fails when the config has no shapefile source, a file cannot be read, a
/// record is not a polygon or encloses no area, a code is blank or repeated, a
/// child names a parent the parent file lacks or skips, or the counts differ
/// from the config's invariants.
pub fn run(config: &CountryConfig, boundaries_dir: &Path, out: &Path, max_zoom: u8) -> Result<()> {
    let boundaries = &config.boundaries;
    let units = boundaries
        .units
        .as_ref()
        .ok_or_else(|| DatasetError::data("the country config has no boundaries.units"))?;
    let parents_file = boundaries
        .parents
        .as_ref()
        .ok_or_else(|| DatasetError::data("the country config has no boundaries.parents"))?;

    let mut parent_names: BTreeMap<String, String> = BTreeMap::new();
    for record in read_records(parents_file, boundaries_dir)? {
        if parents_file.skip.iter().any(|code| code == &record.code) {
            continue;
        }
        if parent_names
            .insert(record.code.clone(), record.name)
            .is_some()
        {
            return Err(DatasetError::data(format!(
                "the parent file repeats the code {} (record {})",
                record.code, record.index
            )));
        }
    }

    let unit_records = read_records(units, boundaries_dir)?;
    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
    let mut skipped = 0_usize;
    let mut areas: Vec<Area> = Vec::with_capacity(unit_records.len());
    for record in unit_records {
        if let Some(first) = seen.insert(record.code.clone(), record.index) {
            return Err(DatasetError::data(format!(
                "the units file repeats the code {}: records {first} and {}",
                record.code, record.index
            )));
        }
        let parent_code = record.parent.as_deref().ok_or_else(|| {
            DatasetError::data({
                format!(
                    "record {} ({}) has no {} value",
                    record.index, record.code, "parent"
                )
            })
        })?;
        if parents_file.skip.iter().any(|code| code == parent_code) {
            // A parent outside the country set (Puerto Rico, the island
            // areas): its children are not part of this country's areas.
            skipped += 1;
            tracing::debug!(
                record = record.index,
                code = record.code.as_str(),
                parent = parent_code,
                "area skipped with its parent"
            );
            continue;
        }
        let parent_name = parent_names.get(parent_code).ok_or_else(|| {
            DatasetError::data({
                format!(
                    "record {} ({}) names the parent {parent_code}, which the parent file lacks",
                    record.index, record.code
                )
            })
        })?;
        if record.shape.unsigned_area() == 0.0 {
            return Err(DatasetError::data(format!(
                "record {} ({}) encloses no area: its rings are empty or degenerate",
                record.index, record.code
            )));
        }
        areas.push(Area {
            id: config.area_id(&record.code),
            code: Some(record.code.clone()),
            name: record.name,
            country: config.code.to_uppercase(),
            level: boundaries.level.clone(),
            parent_id: Some(parent_code.to_string()),
            parent_name: Some(parent_name.clone()),
            region_code: Some(parent_code.to_string()),
            shape: split_antimeridian(&record.shape),
        });
    }
    areas.sort_by(|a, b| a.id.cmp(&b.id));
    config.check_counts(&areas)?;

    std::fs::create_dir_all(out).io_at(IoOp::Create, out)?;
    let file = AreasFile {
        areas,
        boundary_release: boundaries.release.clone(),
        attribution: boundaries.attribution.clone(),
    };
    write_areas_geojson(&out.join("areas.geojson"), &file)?;
    write_collection(
        &out.join("gaps.geojson"),
        std::iter::empty::<geojson::Feature>(),
        &file.boundary_release,
        &file.attribution,
    )?;
    let report = json!({
        "areas": file.areas.len(),
        "parents": parent_names.len(),
        "gaps": Vec::<Value>::new(),
        "skipped": skipped,
        "orphans": 0,
        "invariants": boundaries.invariants,
        "source": "shapefile",
        "release": file.boundary_release,
        "datum": datum(units, boundaries_dir),
        "subtype": boundaries.level,
        "attribution": file.attribution,
    });
    write_json(&out.join("areas-report.json"), &report)?;
    let gaps = Vec::new();
    write_areas_pmtiles(
        &out.join("areas.pmtiles"),
        &file.areas,
        &gaps,
        max_zoom,
        &file.attribution,
        Some(config.bounds),
    )?;
    tracing::info!(
        areas = file.areas.len(),
        parents = parent_names.len(),
        out = %out.display(),
        "official areas written"
    );
    Ok(())
}

/// The source datum of the units file, from its `.prj` text.
fn datum(units: &BoundaryFile, boundaries_dir: &Path) -> &'static str {
    let prj = boundaries_dir.join(units.member.replace(".shp", ".prj"));
    let Ok(text) = std::fs::read_to_string(prj) else {
        return "unknown";
    };
    if text.contains("NAD83") || text.contains("NAD_1983") || text.contains("North_American_1983") {
        "NAD83"
    } else if text.contains("GDA2020") {
        "GDA2020"
    } else if text.contains("GDA94") {
        "GDA94"
    } else if text.contains("WGS_1984") || text.contains("WGS 84") {
        "WGS84"
    } else {
        "unknown"
    }
}

/// Every record of `file`, read from `boundaries_dir`.
///
/// The shapes come from the `.shp` and the attributes from the `.dbf` read as
/// UTF-8: an official file may carry a dBASE language driver byte the
/// attribute reader has no table for (the ABS state file declares none), and
/// its records are text. A byte that is not UTF-8 becomes the replacement
/// character rather than stopping the run.
fn read_records(file: &BoundaryFile, boundaries_dir: &Path) -> Result<Vec<BoundaryRecord>> {
    let path = boundaries_dir.join(&file.member);
    let dbf = path.with_extension("dbf");
    let shapes: Vec<shapefile::Shape> = shapefile::ShapeReader::from_path(&path)
        .io_at(IoOp::Open, &path)?
        .read()
        .io_at(IoOp::Read, &path)?;
    let mut table = shapefile::dbase::ReaderBuilder::new()
        .with_encoding(shapefile::dbase::encoding::UnicodeLossy)
        .open(&dbf)
        .io_at(IoOp::Open, &dbf)?;
    let records = table.read().io_at(IoOp::Read, &dbf)?;
    if shapes.len() != records.len() {
        return Err(DatasetError::data(format!(
            "{} holds {} shapes and {} records",
            path.display(),
            shapes.len(),
            records.len()
        )));
    }
    let mut found = Vec::with_capacity(records.len());
    let mut empty = 0_usize;
    for (index, (shape, record)) in shapes.iter().zip(records.iter()).enumerate() {
        // An official file may carry attribute records without a shape (the
        // ABS lists "no usual address", "migratory" and "outside Australia"
        // rows that way): they hold no land and are not areas.
        if matches!(shape, shapefile::Shape::NullShape) {
            empty += 1;
            continue;
        }
        let code = field(record, &file.fields.code).unwrap_or_default();
        let code = code.trim().to_string();
        if code.is_empty() {
            return Err(DatasetError::data(format!(
                "record {index} of {} has a blank {} code",
                path.display(),
                file.fields.code
            )));
        }
        let name = field(record, &file.fields.name)
            .ok_or_else(|| {
                DatasetError::data(format!(
                    "record {index} ({code}) has no {}",
                    file.fields.name
                ))
            })?
            .trim()
            .to_string();
        if name.is_empty() {
            return Err(DatasetError::data(format!(
                "record {index} ({code}) has a blank {} name",
                file.fields.name
            )));
        }
        let parent = match &file.fields.parent {
            Some(key) => Some(
                field(record, key)
                    .ok_or_else(|| {
                        DatasetError::data(format!("record {index} ({code}) has no {key}"))
                    })?
                    .trim()
                    .to_string(),
            ),
            None => None,
        };
        let shape = shape_to_multi(shape, index, &code)?;
        found.push(BoundaryRecord {
            index,
            code,
            name,
            parent,
            shape,
        });
    }
    if empty > 0 {
        tracing::info!(
            file = %path.display(),
            records = empty,
            "records without a shape are not areas"
        );
    }
    Ok(found)
}

/// `shape` as a lon/lat multi-polygon, keeping the file's own ring classes.
fn shape_to_multi(shape: &shapefile::Shape, index: usize, code: &str) -> Result<MultiPolygon<f64>> {
    let polygons = match shape {
        shapefile::Shape::Polygon(polygon) => rings_to_polygons(polygon.rings()),
        shapefile::Shape::PolygonM(polygon) => rings_to_polygons(polygon.rings()),
        shapefile::Shape::PolygonZ(polygon) => rings_to_polygons(polygon.rings()),
        _ => {
            return Err(DatasetError::data(format!(
                "record {index} ({code}) is not a polygon"
            )));
        }
    };
    if polygons.is_empty() {
        return Err(DatasetError::data(format!(
            "record {index} ({code}) holds no ring"
        )));
    }
    Ok(MultiPolygon(polygons))
}

/// `rings` as polygons: each outer ring opens a polygon, the inner rings that
/// follow it are its holes.
fn rings_to_polygons<T: HasXY>(rings: &[shapefile::PolygonRing<T>]) -> Vec<Polygon<f64>> {
    let mut polygons: Vec<Polygon<f64>> = Vec::new();
    let mut open: Option<(LineString<f64>, Vec<LineString<f64>>)> = None;
    for ring in rings {
        let points: Vec<Coord<f64>> = ring
            .points()
            .iter()
            .map(|p| Coord { x: p.x(), y: p.y() })
            .collect();
        if points.len() < 4 {
            continue;
        }
        match ring {
            shapefile::PolygonRing::Outer(_) => {
                if let Some((exterior, holes)) = open.take() {
                    polygons.push(Polygon::new(exterior, holes));
                }
                open = Some((LineString::new(points), Vec::new()));
            }
            shapefile::PolygonRing::Inner(_) => {
                if let Some((_, holes)) = open.as_mut() {
                    holes.push(LineString::new(points));
                }
            }
        }
    }
    if let Some((exterior, holes)) = open.take() {
        polygons.push(Polygon::new(exterior, holes));
    }
    polygons
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::areas::read_areas_geojson;
    use crate::country::official_id;
    use std::path::PathBuf;

    fn config_dir() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/countries")
    }

    fn us_config() -> CountryConfig {
        CountryConfig::load(&config_dir().join("us.json")).expect("us.json loads")
    }

    /// A record the fixture writes: code, name, parent code and rings, each
    /// `(ring, clockwise)`. A clockwise ring is an outer ring, a
    /// counter-clockwise one a hole (ESRI classification).
    struct Fixture {
        code: &'static str,
        name: &'static str,
        parent: Option<&'static str>,
        rings: Vec<(Vec<(f64, f64)>, bool)>,
    }

    fn outer(x0: f64, y0: f64, x1: f64, y1: f64) -> (Vec<(f64, f64)>, bool) {
        (vec![(x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)], true)
    }

    fn hole(x0: f64, y0: f64, x1: f64, y1: f64) -> (Vec<(f64, f64)>, bool) {
        (
            vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)],
            false,
        )
    }

    fn write_file(dir: &Path, name: &str, parent_field: bool, records: &[Fixture]) {
        let mut table = shapefile::dbase::TableWriterBuilder::new()
            .add_character_field("GEOID".try_into().expect("field"), 16)
            .add_character_field("NAME".try_into().expect("field"), 60);
        if parent_field {
            table = table.add_character_field("STATEFP".try_into().expect("field"), 4);
        }
        let mut writer =
            shapefile::Writer::from_path(dir.join(name), table).expect("shapefile writer");
        for fixture in records {
            let rings: Vec<shapefile::PolygonRing<shapefile::Point>> = fixture
                .rings
                .iter()
                .map(|(points, clockwise)| {
                    let points: Vec<shapefile::Point> = points
                        .iter()
                        .map(|(x, y)| shapefile::Point::new(*x, *y))
                        .collect();
                    if *clockwise {
                        shapefile::PolygonRing::Outer(points)
                    } else {
                        shapefile::PolygonRing::Inner(points)
                    }
                })
                .collect();
            let shape = shapefile::Polygon::with_rings(rings);
            let mut record = DbaseRecord::default();
            record.insert(
                "GEOID".into(),
                FieldValue::Character(Some(fixture.code.into())),
            );
            record.insert(
                "NAME".into(),
                FieldValue::Character(Some(fixture.name.into())),
            );
            if let Some(parent) = fixture.parent {
                record.insert("STATEFP".into(), FieldValue::Character(Some(parent.into())));
            }
            writer
                .write_shape_and_record(&shape, &record)
                .expect("record written");
        }
    }

    /// A config over the fixture files, with `invariants` as the JSON text.
    fn fixture_config(units: &str, parents: &str, invariants: &str) -> CountryConfig {
        let json = format!(
            r#"{{
                "code": "us", "name": "Fixture",
                "unit": {{"one": "county", "many": "counties"}},
                "parent": {{"one": "state", "many": "states"}},
                "bounds": [-170.0, 18.0, -66.0, 72.0],
                "boundaries": {{
                    "source": "shapefile", "release": "2026-10-06.0", "level": "county",
                    "attribution": "Boundaries: fixture",
                    "licence_id": "CC0-1.0",
                    "units": {{"url": "https://x/{units}", "member": "{units}", "sha256": "pending",
                        "fields": {{"code": "GEOID", "name": "NAME", "parent": "STATEFP"}}}},
                    "parents": {{"url": "https://y/{parents}", "member": "{parents}", "sha256": "pending",
                        "fields": {{"code": "GEOID", "name": "NAME"}}, "skip": ["72"]}},
                    "invariants": {invariants}
                }}
            }}"#
        );
        CountryConfig::from_json_str(&json).expect("fixture config parses")
    }

    fn two_parents() -> Vec<Fixture> {
        vec![
            Fixture {
                code: "06",
                name: "California",
                parent: None,
                rings: vec![outer(0.0, 0.0, 10.0, 10.0)],
            },
            Fixture {
                code: "36",
                name: "New York",
                parent: None,
                rings: vec![outer(10.0, 0.0, 20.0, 10.0)],
            },
            Fixture {
                code: "72",
                name: "Puerto Rico",
                parent: None,
                rings: vec![outer(20.0, 0.0, 30.0, 10.0)],
            },
        ]
    }

    /// Runs the fixture and returns the out dir (kept alive by the guard).
    fn run_with(units: &[Fixture], invariants: &str) -> (tempfile::TempDir, PathBuf, Result<()>) {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("boundaries");
        std::fs::create_dir_all(&dir).expect("mkdir");
        write_file(&dir, "units.shp", true, units);
        write_file(&dir, "parents.shp", false, &two_parents());
        let config = fixture_config("units.shp", "parents.shp", invariants);
        let out = tmp.path().join("out");
        let result = run(&config, &dir, &out, 8);
        (tmp, out, result)
    }

    fn three_counties() -> Vec<Fixture> {
        vec![
            Fixture {
                code: "06001",
                name: "Alameda County",
                parent: Some("06"),
                rings: vec![outer(0.0, 0.0, 10.0, 10.0)],
            },
            Fixture {
                code: "36001",
                name: "Albany County",
                parent: Some("36"),
                rings: vec![outer(10.0, 0.0, 20.0, 10.0)],
            },
            Fixture {
                code: "06002",
                name: "Amador County",
                parent: Some("06"),
                rings: vec![outer(0.0, 10.0, 10.0, 20.0)],
            },
        ]
    }

    #[test]
    fn the_ids_are_the_official_ones() {
        let (tmp, out, result) = run_with(&three_counties(), r#"{"areas": 3}"#);
        result.expect("fixture runs");
        let file = read_areas_geojson(&out.join("areas.geojson")).expect("areas.geojson reads");
        assert_eq!(file.areas.len(), 3);
        for area in &file.areas {
            let code = area.code.as_ref().expect("a code");
            assert_eq!(area.id, official_id("us", code), "{code}");
            assert_eq!(area.level, "county");
            assert_eq!(area.country, "US");
            assert_eq!(
                area.parent_name.as_deref(),
                Some(match code.as_str() {
                    "36001" => "New York",
                    _ => "California",
                })
            );
        }
        let ids: Vec<&str> = file.areas.iter().map(|a| a.id.as_str()).collect();
        assert!(ids.is_sorted(), "sorted by id: {ids:?}");
        drop(tmp);
    }

    #[test]
    fn a_multipart_record_with_a_hole_keeps_its_hole() {
        let units = vec![
            Fixture {
                code: "06001",
                name: "Two parts",
                parent: Some("06"),
                rings: vec![
                    outer(0.0, 0.0, 4.0, 10.0),
                    hole(1.0, 1.0, 2.0, 2.0),
                    outer(6.0, 0.0, 10.0, 10.0),
                ],
            },
            Fixture {
                code: "06002",
                name: "Plain",
                parent: Some("06"),
                rings: vec![outer(0.0, 20.0, 10.0, 30.0)],
            },
        ];
        let (tmp, out, result) = run_with(&units, r#"{"areas": 2}"#);
        result.expect("fixture runs");
        let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
        let area = file
            .areas
            .iter()
            .find(|a| a.code.as_deref() == Some("06001"))
            .expect("06001");
        assert_eq!(area.shape.0.len(), 2, "two polygons, one per outer ring");
        assert_eq!(area.shape.0[0].interiors().len(), 1, "the hole stays");
        // 4×10 + 4×10, minus the 1×1 hole.
        assert!((area.shape.unsigned_area() - 79.0).abs() < 1e-9);
        drop(tmp);
    }

    #[test]
    fn holes_stay_out_of_the_land() {
        let units = vec![Fixture {
            code: "06001",
            name: "Square with hole",
            parent: Some("06"),
            rings: vec![outer(0.0, 0.0, 10.0, 10.0), hole(4.0, 4.0, 6.0, 6.0)],
        }];
        let (tmp, out, result) = run_with(&units, r#"{"areas": 1}"#);
        result.expect("fixture runs");
        let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
        assert!((file.areas[0].shape.unsigned_area() - 96.0).abs() < 1e-9);
        drop(tmp);
    }

    #[test]
    fn a_repeated_or_blank_code_is_an_error_naming_it() {
        let repeated = vec![
            Fixture {
                code: "01001",
                name: "A",
                parent: Some("06"),
                rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
            },
            Fixture {
                code: "01001",
                name: "B",
                parent: Some("06"),
                rings: vec![outer(2.0, 0.0, 3.0, 1.0)],
            },
        ];
        let (_tmp, _out, result) = run_with(&repeated, "{}");
        let err = result.expect_err("a repeated code");
        let text = geolith::error::report(&err);
        assert!(text.contains("01001"), "{text}");
        assert!(text.contains("records 0 and 1"), "{text}");

        let blank = vec![Fixture {
            code: "  ",
            name: "Blank",
            parent: Some("06"),
            rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
        }];
        let (_tmp, _out, result) = run_with(&blank, "{}");
        let err = result.expect_err("a blank code");
        assert!(geolith::error::report(&err).contains("blank"), "{err:#}");
    }

    #[test]
    fn an_orphan_parent_is_an_error() {
        let units = vec![Fixture {
            code: "01001",
            name: "Orphan",
            parent: Some("99"),
            rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
        }];
        let (_tmp, _out, result) = run_with(&units, "{}");
        let err = result.expect_err("no parent 99");
        let text = geolith::error::report(&err);
        assert!(text.contains("99") && text.contains("01001"), "{text}");
    }

    #[test]
    fn a_parent_in_skip_drops_its_children() {
        let units = vec![
            Fixture {
                code: "72001",
                name: "Skipped",
                parent: Some("72"),
                rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
            },
            Fixture {
                code: "06001",
                name: "Kept",
                parent: Some("06"),
                rings: vec![outer(2.0, 0.0, 3.0, 1.0)],
            },
        ];
        let (tmp, out, result) = run_with(&units, r#"{"areas": 1, "parents": 1}"#);
        result.expect("the skipped parent drops its child");
        let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
        assert_eq!(file.areas.len(), 1);
        assert_eq!(file.areas[0].code.as_deref(), Some("06001"));
        let text = std::fs::read_to_string(out.join("areas-report.json")).expect("report");
        let report: Value = serde_json::from_str(&text).expect("report json");
        assert_eq!(report["skipped"], 1);
        drop(tmp);
    }

    #[test]
    fn the_invariants_run_on_the_real_areas() {
        let (_tmp, _out, result) = run_with(&three_counties(), r#"{"areas": 4}"#);
        let err = result.expect_err("3 areas, 4 expected");
        assert!(
            geolith::error::report(&err).contains("expected 4 areas, found 3"),
            "{err:#}"
        );
    }

    #[test]
    fn a_degenerate_area_is_an_error() {
        let units = vec![
            Fixture {
                code: "06001",
                name: "Line",
                parent: Some("06"),
                rings: vec![(vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (0.0, 0.0)], true)],
            },
            Fixture {
                code: "06002",
                name: "Fine",
                parent: Some("06"),
                rings: vec![outer(0.0, 20.0, 1.0, 21.0)],
            },
        ];
        let (_tmp, _out, result) = run_with(&units, "{}");
        let err = result.expect_err("a zero-area record");
        assert!(geolith::error::report(&err).contains("06001"), "{err:#}");
    }

    #[test]
    fn nothing_in_the_output_spans_more_than_180_degrees() {
        let units = vec![Fixture {
            code: "02016",
            name: "Aleutians West",
            parent: Some("06"),
            rings: vec![(
                vec![
                    (179.0, -10.0),
                    (-179.5, -10.0),
                    (-179.5, 10.0),
                    (179.0, 10.0),
                    (179.0, -10.0),
                ],
                true,
            )],
        }];
        let (tmp, out, result) = run_with(&units, "{}");
        result.expect("fixture runs");
        let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
        for area in &file.areas {
            for polygon in &area.shape.0 {
                for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
                    let xs: Vec<f64> = ring.0.iter().map(|c| c.x).collect();
                    let lo = xs.iter().fold(f64::INFINITY, |a, b| a.min(*b));
                    let hi = xs.iter().fold(f64::NEG_INFINITY, |a, b| a.max(*b));
                    assert!(
                        hi - lo <= 180.0 + 1e-9,
                        "{} spans {lo}..{hi}",
                        area.code.as_deref().unwrap_or("?")
                    );
                }
            }
        }
        drop(tmp);
    }

    #[test]
    fn the_report_names_the_source_and_the_release() {
        let (tmp, out, result) = run_with(&three_counties(), r#"{"areas": 3}"#);
        result.expect("fixture runs");
        let text = std::fs::read_to_string(out.join("areas-report.json")).expect("report");
        let report: Value = serde_json::from_str(&text).expect("report json");
        assert_eq!(report["areas"], 3);
        assert_eq!(report["parents"], 2);
        assert_eq!(report["orphans"], 0);
        assert_eq!(report["source"], "shapefile");
        assert_eq!(report["release"], "2026-10-06.0");
        assert_eq!(report["subtype"], "county");
        assert_eq!(report["gaps"].as_array().map(Vec::len), Some(0));
        drop(tmp);
    }

    #[test]
    fn the_us_config_boundary_files_are_readable() {
        let config = us_config();
        let units = config.boundaries.units.as_ref().expect("units");
        assert_eq!(units.member, "tl_2026_us_county.shp");
        assert_eq!(
            config.boundaries.parents.as_ref().expect("parents").skip,
            vec!["60", "66", "69", "72", "78"]
        );
    }
}