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
//! A country's dataset settings: one JSON file per country.
//!
//! `packages/dataset-builder/data/datasets/countries/<cc>.json` carries everything the engine
//! and the scripts need to treat a country as data rather than as a branch:
//! the words the pages use, the map bounds, the boundary source and its field
//! mapping, the attribution and licence of that source, the area counts the
//! run must meet, and the per-dataset limits (coverage floor, zooms). The
//! engine loads it with [`CountryConfig::load`]; the former `scripts/datasets/` reads the
//! same file, so a number exists in one place.
//!
//! Areas of a country whose boundaries come from an official file get their id
//! from [`official_id`]: the publisher's own code, hashed into a stable UUID.
//! Their rings go through [`split_antimeridian`] so no ring spans more than
//! 180° of longitude.

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

use crate::error::{DatasetError, IoStepExt as _, JsonResultExt as _, Result, WithinExt as _};
use geo::{BooleanOps as _, Coord, MultiPolygon, Rect};
use md5::{Digest as _, Md5};
use serde::{Deserialize, Serialize};

use super::areas::Area;

/// Largest map-layer zoom a country config may ask for (the ceiling
/// `dataset::config` applies to a dataset config).
const MAX_ZOOM_LIMIT: u8 = 22;

/// Where a country's area boundaries come from.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BoundarySource {
    /// Overture Maps divisions, as India uses.
    Overture,
    /// An official shapefile the country's own authority publishes.
    Shapefile,
}

/// A unit's words: `1 district`, `3 districts`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnitWords {
    /// Singular form, e.g. `county`.
    pub one: String,
    /// Plural form, e.g. `counties`.
    pub many: String,
}

/// One boundary download and the fields its records carry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BoundaryFile {
    /// Archive URL.
    pub url: String,
    /// Member to unzip, e.g. `tl_2026_us_county.shp`.
    pub member: String,
    /// sha256 of the archive; `pending` until the first download records it.
    pub sha256: String,
    /// Field mapping of the shapefile's records.
    pub fields: Fields,
    /// Parent codes not part of this country set (for example Puerto Rico).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skip: Vec<String>,
}

/// Which record fields hold an area's code, name and parent code.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Fields {
    /// Field holding the official code (`GEOID`).
    pub code: String,
    /// Field holding the name (`NAME`).
    pub name: String,
    /// Field holding the parent's code (`STATEFP`); absent on a parent file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<String>,
}

/// Counts a run must meet, so a source change stops the build instead of
/// shipping a new area set.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Invariants {
    /// Number of areas the country holds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub areas: Option<usize>,
    /// Number of parents (states, territories) the country holds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parents: Option<usize>,
    /// Smallest number of areas a parent may hold.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_areas_per_parent: Option<usize>,
}

/// The boundary source of a country.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Boundaries {
    /// Where the areas come from.
    pub source: BoundarySource,
    /// Release label recorded in the outputs (`2026-10-06.0`).
    pub release: String,
    /// Licence line every boundary output carries.
    pub attribution: String,
    /// Second authority line; `null` when the source carries none.
    #[serde(default)]
    pub codes_attribution: Option<String>,
    /// SPDX identifier of the boundary licence (`CC0-1.0`).
    pub licence_id: String,
    /// Repo-relative file holding the licence text, when the built-in ODbL
    /// text does not apply.
    #[serde(default)]
    pub licence_file: Option<String>,
    /// Whether the country set holds land of India's Survey of India map, so
    /// the run needs the outline.
    #[serde(default)]
    pub holds_soi_land: bool,
    /// Level name of the areas, written to every area (`county`, `lga`).
    pub level: String,
    /// The area file; present exactly when `source` is `shapefile`.
    #[serde(default)]
    pub units: Option<BoundaryFile>,
    /// The parent file; present exactly when `source` is `shapefile`.
    #[serde(default)]
    pub parents: Option<BoundaryFile>,
    /// Counts the run must meet.
    #[serde(default)]
    pub invariants: Invariants,
}

/// What the build step takes from a country for one dataset.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DatasetLimits {
    /// Areas covered below this percentage get no page for the dataset;
    /// `null` keeps every area.
    #[serde(default)]
    pub min_coverage_pct: Option<f64>,
    /// Highest zoom of the map layer.
    #[serde(default)]
    pub max_zoom: Option<u8>,
    /// Highest zoom of the layers before the latest.
    #[serde(default)]
    pub history_max_zoom: Option<u8>,
}

fn default_published_first() -> usize {
    24
}

/// One country's dataset settings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CountryConfig {
    /// Lowercase ISO 3166-1 alpha-2 code (`us`).
    pub code: String,
    /// Display name (`United States`).
    pub name: String,
    /// Words of one area.
    pub unit: UnitWords,
    /// Words of one parent.
    pub parent: UnitWords,
    /// Map bounds `[min_lon, min_lat, max_lon, max_lat]`.
    pub bounds: [f64; 4],
    /// The boundary source.
    pub boundaries: Boundaries,
    /// Per-dataset limits, keyed by dataset id.
    #[serde(default)]
    pub datasets: BTreeMap<String, DatasetLimits>,
    /// Number of areas the first wave advertises in the sitemap.
    #[serde(default = "default_published_first")]
    pub published_first: usize,
}

impl CountryConfig {
    /// Read and validate the config at `path`.
    ///
    /// # Errors
    ///
    /// Fails, naming `path`, when the file cannot be read or is not a valid
    /// config.
    pub fn load(path: &Path) -> Result<Self> {
        let text = std::fs::read_to_string(path)
            .io_step(format!("reading country config {}", path.display()))?;
        Self::from_json_str(&text).within(format!("invalid country config {}", path.display()))
    }

    /// Parse and validate a config from JSON text.
    ///
    /// # Errors
    ///
    /// Fails on malformed JSON, an unknown key, a code that is not two
    /// lowercase letters, a release or attribution that is empty, bounds out
    /// of order, `units`/`parents` present or absent against the source kind,
    /// or a zoom above 22.
    pub fn from_json_str(s: &str) -> Result<Self> {
        let config: Self = serde_json::from_str(s).json_of("parsing country config JSON")?;
        config.validate()?;
        Ok(config)
    }

    fn validate(&self) -> Result<()> {
        let code_ok = self.code.len() == 2
            && self
                .code
                .chars()
                .all(|c| c.is_ascii_lowercase() && c.is_ascii_alphabetic());
        if !code_ok {
            return Err(DatasetError::config(format!(
                "code {:?} is not two lowercase letters",
                self.code
            )));
        }
        let [min_lon, min_lat, max_lon, max_lat] = self.bounds;
        let rises = |a: f64, b: f64| a.partial_cmp(&b) == Some(std::cmp::Ordering::Less);
        if !rises(min_lon, max_lon) || !rises(min_lat, max_lat) {
            return Err(DatasetError::config(format!(
                "bounds [{min_lon}, {min_lat}, {max_lon}, {max_lat}] are out of order: \
                 needs min_lon < max_lon and min_lat < max_lat"
            )));
        }
        if self.boundaries.release.trim().is_empty() {
            return Err(DatasetError::config("boundaries.release is empty"));
        }
        if self.boundaries.attribution.trim().is_empty() {
            return Err(DatasetError::config("boundaries.attribution is empty"));
        }
        if self.boundaries.licence_id.trim().is_empty() {
            return Err(DatasetError::config("boundaries.licence_id is empty"));
        }
        match self.boundaries.source {
            BoundarySource::Shapefile => {
                if self.boundaries.units.is_none() {
                    return Err(DatasetError::config(
                        "boundaries.source is shapefile, so it needs a units file",
                    ));
                }
                if self.boundaries.parents.is_none() {
                    return Err(DatasetError::config(
                        "boundaries.source is shapefile, so it needs a parents file",
                    ));
                }
            }
            BoundarySource::Overture => {
                if self.boundaries.units.is_some() {
                    return Err(DatasetError::config(
                        "boundaries.source is overture, so units must be absent",
                    ));
                }
                if self.boundaries.parents.is_some() {
                    return Err(DatasetError::config(
                        "boundaries.source is overture, so parents must be absent",
                    ));
                }
            }
        }
        for (dataset, limits) in &self.datasets {
            for (key, zoom) in [
                ("max_zoom", limits.max_zoom),
                ("history_max_zoom", limits.history_max_zoom),
            ] {
                if let Some(zoom) = zoom
                    && zoom > MAX_ZOOM_LIMIT
                {
                    return Err(DatasetError::config(format!(
                        "datasets.{dataset}.{key} {zoom} is above {MAX_ZOOM_LIMIT}"
                    )));
                }
            }
            if let Some(pct) = limits.min_coverage_pct
                && !(0.0..=100.0).contains(&pct)
            {
                return Err(DatasetError::config(format!(
                    "datasets.{dataset}.min_coverage_pct {pct} is not 0..=100"
                )));
            }
        }
        Ok(())
    }

    /// The limits of `dataset`, when the config sets any.
    #[must_use]
    pub fn limits(&self, dataset: &str) -> Option<&DatasetLimits> {
        self.datasets.get(dataset)
    }

    /// The stable id of the area with `code` in this country.
    #[must_use]
    pub fn area_id(&self, code: &str) -> String {
        official_id(&self.code, code)
    }

    /// Assert the counts the config asks for.
    ///
    /// # Errors
    ///
    /// Fails naming the difference when the areas do not match
    /// [`Invariants`]: a count that moved, an area with no parent, or a parent
    /// under `min_areas_per_parent`.
    pub fn check_counts(&self, areas: &[Area]) -> Result<()> {
        let invariants = &self.boundaries.invariants;
        if let Some(expected) = invariants.areas
            && areas.len() != expected
        {
            return Err(DatasetError::config(format!(
                "expected {expected} areas, found {}",
                areas.len()
            )));
        }
        let mut per_parent: BTreeMap<&str, usize> = BTreeMap::new();
        let mut orphans = 0_usize;
        for area in areas {
            match area.parent_id.as_deref() {
                Some(parent) => *per_parent.entry(parent).or_default() += 1,
                None => orphans += 1,
            }
        }
        if let Some(expected) = invariants.parents
            && per_parent.len() != expected
        {
            return Err(DatasetError::config(format!(
                "expected {expected} parents, found {}",
                per_parent.len()
            )));
        }
        if (invariants.parents.is_some() || invariants.min_areas_per_parent.is_some())
            && orphans > 0
        {
            return Err(DatasetError::config(format!(
                "{orphans} areas have no parent: they name a parent the parent file lacks"
            )));
        }
        if let Some(minimum) = invariants.min_areas_per_parent {
            for (parent, count) in &per_parent {
                if *count < minimum {
                    return Err(DatasetError::config(format!(
                        "parent {parent} holds {count} areas, under the {minimum} the config asks for"
                    )));
                }
            }
        }
        Ok(())
    }
}

/// The stable id of the area with `code` in `country`.
///
/// The id is `md5("geolith:<country>:<code>")` with the version nibble set to
/// 3 and the variant bits to `10`, formatted as a lowercase UUID. It keeps the
/// serving layer's UUID check untouched and does not change when the boundary
/// file is re-published with the same code.
#[must_use]
pub fn official_id(country: &str, code: &str) -> String {
    let mut hasher = Md5::new();
    hasher.update(format!("geolith:{}:{code}", country.to_lowercase()).as_bytes());
    let mut bytes: [u8; 16] = hasher.finalize().into();
    bytes[6] = (bytes[6] & 0x0f) | 0x30;
    bytes[8] = (bytes[8] & 0x3f) | 0x80;
    let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
    format!(
        "{}-{}-{}-{}-{}",
        &hex[0..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..32]
    )
}

/// Shift every longitude of `shape` by `dx` degrees.
fn shift(shape: &MultiPolygon<f64>, dx: f64) -> MultiPolygon<f64> {
    shift_by(shape, |x| x + dx)
}

/// Move every negative longitude of `shape` into the 0..360 frame.
fn rebase_negative(shape: &MultiPolygon<f64>) -> MultiPolygon<f64> {
    shift_by(shape, |x| if x < 0.0 { x + 360.0 } else { x })
}

fn shift_by(shape: &MultiPolygon<f64>, f: impl Fn(f64) -> f64) -> MultiPolygon<f64> {
    let moved: Vec<geo::Polygon<f64>> = shape
        .0
        .iter()
        .map(|polygon| {
            let exterior = map_ring(polygon.exterior(), &f);
            let holes = polygon
                .interiors()
                .iter()
                .map(|ring| map_ring(ring, &f))
                .collect();
            geo::Polygon::new(exterior, holes)
        })
        .collect();
    MultiPolygon(moved)
}

fn map_ring(ring: &geo::LineString<f64>, f: &impl Fn(f64) -> f64) -> geo::LineString<f64> {
    geo::LineString::new(ring.0.iter().map(|c| Coord { x: f(c.x), y: c.y }).collect())
}

/// `shape` with every ring that crosses the antimeridian split at ±180.
///
/// A shape whose rings all span 180° of longitude or less is returned
/// unchanged. Otherwise its negative longitudes move to the +360 frame, the
/// shape is cut at 180° and 360° (the antimeridian and the seam), and the
/// eastern part moves back by −360°, so the result has one part east of +180
/// and one west of −180. County sets hold one such area (Aleutians West);
/// without the split its tile and its bounds span the whole world.
#[must_use]
pub fn split_antimeridian(shape: &MultiPolygon<f64>) -> MultiPolygon<f64> {
    let mut crosses = false;
    for polygon in &shape.0 {
        let mut lo = f64::INFINITY;
        let mut hi = f64::NEG_INFINITY;
        for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
            for coord in &ring.0 {
                lo = lo.min(coord.x);
                hi = hi.max(coord.x);
            }
        }
        if hi - lo > 180.0 {
            crosses = true;
            break;
        }
    }
    if !crosses {
        return shape.clone();
    }
    let shifted = rebase_negative(shape);
    let seam = |x0: f64, x1: f64| {
        Rect::new(Coord { x: x0, y: -90.0 }, Coord { x: x1, y: 90.0 }).to_polygon()
    };
    let mut parts: Vec<MultiPolygon<f64>> = Vec::new();
    for (band, back) in [(seam(0.0, 180.0), 0.0), (seam(180.0, 360.0), -360.0)] {
        let piece = shifted.intersection(&band);
        if piece.0.is_empty() {
            continue;
        }
        parts.push(if back == 0.0 {
            piece
        } else {
            shift(&piece, back)
        });
    }
    if parts.is_empty() {
        return shape.clone();
    }
    use geo::orient::{Direction, Orient as _};
    geo::unary_union(&parts).orient(Direction::Default)
}

#[cfg(test)]
mod tests {
    use super::*;
    use geo::{Area as _, LineString, Polygon};
    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> MultiPolygon<f64> {
        MultiPolygon(vec![Polygon::new(
            LineString::new(vec![
                Coord { x: x0, y: y0 },
                Coord { x: x1, y: y0 },
                Coord { x: x1, y: y1 },
                Coord { x: x0, y: y1 },
                Coord { x: x0, y: y0 },
            ]),
            Vec::new(),
        )])
    }

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

    fn load(code: &str) -> CountryConfig {
        CountryConfig::load(&config_dir().join(format!("{code}.json")))
            .unwrap_or_else(|e| panic!("{code}.json loads: {e:#}"))
    }

    #[test]
    fn the_three_repo_configs_load() {
        let india = load("in");
        assert_eq!(india.boundaries.source, BoundarySource::Overture);
        assert!(india.boundaries.holds_soi_land);
        assert!(india.boundaries.units.is_none());
        assert_eq!(india.boundaries.release, "2026-10-21.0");
        assert_eq!(india.boundaries.invariants.areas, Some(787));
        assert_eq!(
            india.boundaries.attribution,
            crate::areas::BOUNDARIES_ATTRIBUTION
        );
        assert_eq!(india.published_first, 20);

        let us = load("us");
        assert_eq!(us.boundaries.source, BoundarySource::Shapefile);
        assert_eq!(us.bounds, [-170.0, 18.0, -66.0, 72.0]);
        assert_eq!(us.unit.many, "counties");
        assert_eq!(us.parent.many, "states");
        let units = us.boundaries.units.as_ref().expect("units");
        assert_eq!(units.fields.code, "GEOID");
        let parents = us.boundaries.parents.as_ref().expect("parents");
        assert_eq!(parents.skip, vec!["60", "66", "69", "72", "78"]);
        assert_eq!(
            us.limits("rainfall")
                .expect("rainfall limits")
                .min_coverage_pct,
            Some(60.0)
        );
        assert_eq!(us.limits("ndvi").expect("ndvi limits").max_zoom, Some(8));
        assert_eq!(us.published_first, 24);

        let au = load("au");
        assert_eq!(au.boundaries.release, "2025-07-22.0");
        assert_eq!(au.unit.many, "local government areas");
        assert_eq!(au.boundaries.invariants.areas, Some(548));
        assert_eq!(au.boundaries.invariants.parents, Some(9));
    }

    #[test]
    fn a_config_without_bounds_is_refused() {
        let json = r#"{
            "code": "us", "name": "United States",
            "unit": {"one": "county", "many": "counties"},
            "parent": {"one": "state", "many": "states"},
            "boundaries": {"source": "overture", "release": "2026-01-01.0",
                "attribution": "x", "licence_id": "CC0-1.0", "level": "county"}
        }"#;
        let err = CountryConfig::from_json_str(json).expect_err("no bounds");
        assert!(geolith::error::report(&err).contains("bounds"), "{err:#}");
    }

    #[test]
    fn shapefile_needs_units_and_parents() {
        let json = r#"{
            "code": "us", "name": "United States",
            "unit": {"one": "county", "many": "counties"},
            "parent": {"one": "state", "many": "states"},
            "bounds": [-170.0, 18.0, -66.0, 72.0],
            "boundaries": {"source": "shapefile", "release": "2026-01-01.0",
                "attribution": "x", "licence_id": "CC0-1.0", "level": "county"}
        }"#;
        let err = CountryConfig::from_json_str(json).expect_err("no units");
        assert!(geolith::error::report(&err).contains("units"), "{err:#}");
    }

    fn area(id: &str, parent: Option<&str>) -> Area {
        Area {
            code: None,
            id: id.to_string(),
            name: id.to_string(),
            country: "US".to_string(),
            level: "county".to_string(),
            parent_id: parent.map(str::to_string),
            parent_name: parent.map(str::to_string),
            region_code: parent.map(str::to_string),
            shape: rect(0.0, 0.0, 1.0, 1.0),
        }
    }

    fn with_invariants(invariants: &str) -> CountryConfig {
        let json = format!(
            r#"{{
                "code": "us", "name": "United States",
                "unit": {{"one": "county", "many": "counties"}},
                "parent": {{"one": "state", "many": "states"}},
                "bounds": [-170.0, 18.0, -66.0, 72.0],
                "boundaries": {{"source": "overture", "release": "2026-01-01.0",
                    "attribution": "x", "licence_id": "CC0-1.0", "level": "county",
                    "invariants": {invariants}}}
            }}"#
        );
        CountryConfig::from_json_str(&json).expect("config parses")
    }

    #[test]
    fn the_invariants_fail_naming_the_difference() {
        let config = with_invariants(r#"{"areas": 4}"#);
        let areas = vec![
            area("a", Some("s1")),
            area("b", Some("s1")),
            area("c", Some("s2")),
        ];
        let err = config
            .check_counts(&areas)
            .expect_err("3 areas, 4 expected");
        assert!(
            geolith::error::report(&err).contains("expected 4 areas, found 3"),
            "{err:#}"
        );

        let config = with_invariants(r#"{"min_areas_per_parent": 2}"#);
        let err = config.check_counts(&areas).expect_err("s2 holds one area");
        assert!(geolith::error::report(&err).contains("s2"), "{err:#}");

        let config = with_invariants(r#"{"parents": 3}"#);
        let err = config
            .check_counts(&[area("a", Some("s1")), area("b", None)])
            .expect_err("a parentless area and one parent");
        assert!(geolith::error::report(&err).contains("parent"), "{err:#}");
    }

    #[test]
    fn an_official_id_is_a_stable_uuid() {
        let id = official_id("us", "06037");
        assert_eq!(id, "8d1a0c7e-33b1-3492-ae2e-9c21f98bc708");
        assert_eq!(id, official_id("us", "06037"));
        assert_ne!(id, official_id("us", "06038"));
        assert_ne!(id, official_id("au", "06037"));
        let groups: Vec<&str> = id.split('-').collect();
        assert_eq!(
            groups.iter().map(|g| g.len()).collect::<Vec<_>>(),
            vec![8, 4, 4, 4, 12]
        );
        assert!(
            id.chars()
                .filter(|c| *c != '-')
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),
            "{id} is lowercase hex"
        );
        assert!(groups[2].starts_with('3'), "version 3: {id}");
        assert!(
            matches!(groups[3].as_bytes()[0], b'8' | b'9' | b'a' | b'b'),
            "variant 10: {id}"
        );
    }

    #[test]
    fn a_ring_crossing_the_antimeridian_is_split() {
        let input = rect(179.0, -10.0, -179.5, 10.0);
        let split = split_antimeridian(&input);
        assert_eq!(split.0.len(), 2, "two parts");
        let spans: Vec<(f64, f64)> = split
            .0
            .iter()
            .map(|p| {
                let xs: Vec<f64> = p.exterior().0.iter().map(|c| c.x).collect();
                (
                    xs.iter().fold(f64::INFINITY, |a, b| a.min(*b)),
                    xs.iter().fold(f64::NEG_INFINITY, |a, b| a.max(*b)),
                )
            })
            .collect();
        assert!(spans.iter().any(|(lo, _)| *lo >= 179.0), "{spans:?}");
        assert!(spans.iter().any(|(_, hi)| *hi <= -179.0), "{spans:?}");
        assert_eq!(
            split,
            split_antimeridian(&split),
            "a second split is a no-op"
        );
        // The ring wraps: 179.0 .. 180.5 in the shifted frame, so 1.5° of
        // longitude over 20° of latitude. Its planar area before the split
        // (358.5° wide) is not a meaningful number.
        let after = split.unsigned_area();
        assert!((after - 30.0).abs() < 1e-9, "{after} vs 30.0");
    }

    #[test]
    fn nothing_spans_more_than_180_degrees() {
        let split = split_antimeridian(&rect(179.0, -10.0, -179.5, 10.0));
        for polygon in &split.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, "ring spans {lo}..{hi}");
            }
        }
    }
}