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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
//! Vector tiles of the district areas (`areas.pmtiles`).
//!
//! The MVT layer `areas` holds every district and every SOI gap piece, with
//! the properties `id` (the Overture `division_id` or `gap-<n>`) and `kind`
//! (`district` or `gap`). The web joins the period values to these features
//! with `promoteId: "id"`. The layer `gaps` holds the gap pieces again for
//! the hatch, with `id`, `region_code`, `region_name` (absent when no Indian
//! region holds the piece) and `label` ([`GAP_LABEL`]).

use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::Path;

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, Result,
};
use flate2::write::GzEncoder;
use geo::{BoundingRect as _, Coord, Polygon};
use geolith::geometry::mercator::TileCoord;
use geolith::output::hilbert::tile_to_pmtiles_id;
use geolith::output::writer::{Compression, PmtilesWriter, TileType};
use geolith::tile::feature::TILE_EXTENT;
use geolith::tile::mvt::{encode_polygon, proto};
use i_overlay::core::fill_rule::FillRule;
use i_overlay::core::overlay::{IntOverlayOptions, Overlay};
use i_overlay::core::overlay_rule::OverlayRule;
use i_overlay::core::solver::Solver;
use i_overlay::i_float::int::point::IntPoint;
use prost::Message as _;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::areas::{Area, GAP_LABEL, GapPiece};
use crate::topology::{Coverage, FeatureRings, MAX_ZOOM};

/// The boundaries config shared with the dataset scripts.
const BOUNDARIES_CONFIG: &str = include_str!("../data/datasets/boundaries.json");

/// Revision of the `areas.pmtiles` encoding: the dataset scripts upload the
/// tiles to `boundaries/<cc>/<release>-r<revision>/` (revision 1 is the bare
/// `<release>/`), so a change of the tiles never overwrites a published key.
/// Bump `tiles_revision` in `packages/dataset-builder/data/datasets/boundaries.json` with every
/// change of the tiles.
///
/// # Errors
///
/// Fails if the config has no positive integer `tiles_revision`.
pub fn tiles_revision() -> Result<u64> {
    let config: serde_json::Value =
        serde_json::from_str(BOUNDARIES_CONFIG).json_of("bad boundaries.json")?;
    config
        .get("tiles_revision")
        .and_then(serde_json::Value::as_u64)
        .filter(|r| *r >= 1)
        .ok_or_else(|| DatasetError::usage("boundaries.json has no positive tiles_revision"))
}

/// Name of the district layer.
const LAYER: &str = "areas";

/// Keys of the district layer.
const AREA_KEYS: [&str; 2] = ["id", "kind"];

/// Name of the gap hatch layer.
const GAPS_LAYER: &str = "gaps";

/// Keys of the gap hatch layer.
const GAP_KEYS: [&str; 4] = ["id", "region_code", "region_name", "label"];

/// `kind` of a district feature.
const DISTRICT: &str = "district";

/// `kind` of an SOI gap piece.
const GAP: &str = "gap";

/// One feature to tile: the values of its layer's keys in key order (the
/// first is the id; `None` leaves the key out) and its polygons (lon/lat).
struct Item<'a> {
    values: Vec<Option<&'a str>>,
    polygons: Vec<&'a Polygon<f64>>,
}

/// The id of `item`.
fn item_id<'a>(item: &Item<'a>) -> &'a str {
    item.values.first().copied().flatten().unwrap_or_default()
}

/// Areas and gap pieces of layer `areas`, sorted by id; a feature's
/// position is its MVT id.
fn items<'a>(areas: &'a [Area], gaps: &'a [GapPiece]) -> Vec<Item<'a>> {
    let mut items: Vec<Item<'a>> = Vec::with_capacity(areas.len() + gaps.len());
    items.extend(areas.iter().map(|a| Item {
        values: vec![Some(a.id.as_str()), Some(DISTRICT)],
        polygons: a.shape.0.iter().collect(),
    }));
    items.extend(gaps.iter().map(|g| Item {
        values: vec![Some(g.id.as_str()), Some(GAP)],
        polygons: g.shape.0.iter().collect(),
    }));
    items.sort_by(|a, b| item_id(a).cmp(item_id(b)));
    items
}

/// Gap pieces of layer `gaps`, sorted by id; a feature's position is its
/// MVT id.
fn gap_items(gaps: &[GapPiece]) -> Vec<Item<'_>> {
    let mut items: Vec<Item<'_>> = gaps
        .iter()
        .map(|g| Item {
            values: vec![
                Some(g.id.as_str()),
                g.region_code.as_deref(),
                g.region_name.as_deref(),
                Some(GAP_LABEL),
            ],
            polygons: g.shape.0.iter().collect(),
        })
        .collect();
    items.sort_by(|a, b| item_id(a).cmp(item_id(b)));
    items
}

/// Tile buffer in MVT units (4/256 of a tile, as the other tilers).
const BUFFER: i32 = 64;

/// MVT units per tile.
const EXTENT: i64 = TILE_EXTENT as i64;

/// Options of the tile cut: keep every vertex (a neighbour keeps it too),
/// and give OGC-valid rings (a ring that touches itself is split).
const CLIP_OPTIONS: IntOverlayOptions = IntOverlayOptions {
    preserve_input_collinear: true,
    output_direction: i_overlay::core::overlay::ContourDirection::CounterClockwise,
    preserve_output_collinear: true,
    min_output_area: 0,
    ogc: true,
};

/// Twice the signed area of a ring in tile pixels (y down): negative for a
/// clockwise ring on screen.
fn signed_area_2x(ring: &[(i32, i32)]) -> i64 {
    let n = ring.len();
    (0..n)
        .map(|i| {
            let (x1, y1) = ring[i];
            let (x2, y2) = ring[(i + 1) % n];
            (i64::from(x2) - i64::from(x1)) * (i64::from(y2) + i64::from(y1))
        })
        .sum()
}

/// `ring` wound per the MVT spec: exterior clockwise, hole counter-clockwise
/// (y down).
fn wind(mut ring: Vec<(i32, i32)>, exterior: bool) -> Vec<(i32, i32)> {
    let area = signed_area_2x(&ring);
    if (exterior && area > 0) || (!exterior && area < 0) {
        ring.reverse();
    }
    ring
}

/// MVT rings per tile `(x, y)`, each exterior followed by its holes.
type TileRings = BTreeMap<(u32, u32), Vec<Vec<(i32, i32)>>>;

/// The MVT rings of one feature's polygons (zoom grid, see
/// [`Coverage::rings_at_zoom`]) per tile at zoom `z`: each polygon is cut to
/// each tile plus [`BUFFER`] on integers, so a vertex keeps its grid point and
/// two neighbours keep the border they share.
fn tile_rings(feature: &FeatureRings, z: u8) -> TileRings {
    let last = (1_i64 << z) - 1;
    let (b, e) = (BUFFER, TILE_EXTENT as i32);
    let rect = vec![
        IntPoint::new(-b, -b),
        IntPoint::new(e + b, -b),
        IntPoint::new(e + b, e + b),
        IntPoint::new(-b, e + b),
    ];
    let mut out = TileRings::new();
    for polygon in feature {
        let Some(exterior) = polygon.first() else {
            continue;
        };
        let (mut x0, mut y0, mut x1, mut y1) = (i64::MAX, i64::MAX, i64::MIN, i64::MIN);
        for &(x, y) in exterior {
            (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));
        }
        let tiles = |lo: i64, hi: i64| {
            let from = (lo - i64::from(b)).div_euclid(EXTENT).max(0);
            let to = (hi + i64::from(b)).div_euclid(EXTENT).min(last);
            from..=to
        };
        for tx in tiles(x0, x1) {
            for ty in tiles(y0, y1) {
                let (ox, oy) = (tx * EXTENT, ty * EXTENT);
                let contours: Vec<Vec<IntPoint>> = polygon
                    .iter()
                    .map(|ring| {
                        ring.iter()
                            .map(|&(x, y)| IntPoint::new((x - ox) as i32, (y - oy) as i32))
                            .collect()
                    })
                    .collect();
                let shapes = Overlay::with_contours_custom(
                    &contours,
                    std::slice::from_ref(&rect),
                    CLIP_OPTIONS,
                    Solver::default(),
                )
                .overlay(OverlayRule::Intersect, FillRule::Positive);
                if shapes.is_empty() {
                    continue;
                }
                let group = out.entry((tx as u32, ty as u32)).or_default();
                for shape in shapes {
                    for (k, contour) in shape.into_iter().enumerate() {
                        let ring: Vec<(i32, i32)> = contour.iter().map(|p| (p.x, p.y)).collect();
                        group.push(wind(ring, k == 0));
                    }
                }
            }
        }
    }
    out
}

/// One layer of one tile: string values deduplicated.
struct LayerBuilder {
    name: &'static str,
    keys: &'static [&'static str],
    values: Vec<proto::tile::Value>,
    value_index: BTreeMap<String, u32>,
    features: Vec<proto::tile::Feature>,
}

impl LayerBuilder {
    const fn new(name: &'static str, keys: &'static [&'static str]) -> Self {
        Self {
            name,
            keys,
            values: Vec::new(),
            value_index: BTreeMap::new(),
            features: Vec::new(),
        }
    }

    fn value(&mut self, text: &str) -> u32 {
        if let Some(&i) = self.value_index.get(text) {
            return i;
        }
        let i = self.values.len() as u32;
        self.values.push(proto::tile::Value {
            string_value: Some(text.to_string()),
            ..Default::default()
        });
        self.value_index.insert(text.to_string(), i);
        i
    }

    fn push(&mut self, mvt_id: u64, item: &Item<'_>, geometry: Vec<u32>) {
        let mut tags = Vec::with_capacity(2 * item.values.len());
        for (key, value) in (0_u32..).zip(&item.values) {
            if let Some(text) = value {
                let value = self.value(text);
                tags.extend([key, value]);
            }
        }
        self.features.push(proto::tile::Feature {
            id: Some(mvt_id),
            tags,
            r#type: Some(proto::tile::GeomType::Polygon as i32),
            geometry,
        });
    }

    fn into_layer(self) -> proto::tile::Layer {
        proto::tile::Layer {
            version: 2,
            name: self.name.to_string(),
            features: self.features,
            keys: self.keys.iter().map(|k| (*k).to_string()).collect(),
            values: self.values,
            extent: Some(TILE_EXTENT),
        }
    }
}

/// One layer to write: name, keys, and each feature with its rings per tile.
type LayerFeatures<'a, 'r> = (
    &'static str,
    &'static [&'static str],
    Vec<(&'r Item<'a>, &'r TileRings)>,
);

/// The layers of one tile, in layer order (`areas`, then `gaps`).
type TileLayers = [Option<LayerBuilder>; 2];

/// Counts of one `areas.pmtiles` write.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TileStats {
    /// Tiles written, counting duplicates.
    pub tiles_written: u64,
    /// Distinct tile blobs stored.
    pub unique_tiles: u64,
    /// Size of the archive in bytes.
    pub bytes: u64,
}

/// Render the areas and gap pieces as uncompressed MVT tiles, z0 to
/// `max_zoom` (at most [`MAX_ZOOM`]), sorted by zoom, column and row.
///
/// Layer `areas` (extent 4096): a feature carries `id` and `kind`
/// (`district` or `gap`). Layer `gaps` (extent 4096, only in tiles a gap
/// reaches): a gap carries `id`, `region_code` and `region_name` (when an
/// Indian region holds it) and `label`. A feature's MVT id is its position
/// in its layer's features sorted by `id`. The borders are simplified as one
/// coverage ([`Coverage`]): neighbours share the same simplified border at
/// every zoom, and every ring is simple.
#[must_use]
pub fn render_area_tiles(
    areas: &[Area],
    gaps: &[GapPiece],
    max_zoom: u8,
) -> Vec<(TileCoord, Vec<u8>)> {
    let max_zoom = max_zoom.min(MAX_ZOOM);
    let area_items = items(areas, gaps);
    let gap_list = gap_items(gaps);
    let polygons: Vec<Vec<&Polygon<f64>>> = area_items.iter().map(|i| i.polygons.clone()).collect();
    let coverage = Coverage::build(&polygons);
    let s = coverage.stats;
    tracing::info!(
        shared_before = s.shared_before / s.total_before.max(1.0),
        shared_after = s.shared_after / s.total_after.max(1.0),
        merged = s.merged,
        inserted = s.inserted,
        arcs = s.arcs,
        nodes = s.nodes,
        "area borders built"
    );
    let position: BTreeMap<&str, usize> = area_items
        .iter()
        .enumerate()
        .map(|(i, item)| (item_id(item), i))
        .collect();
    let gap_of: Vec<Option<usize>> = gap_list
        .iter()
        .map(|g| position.get(item_id(g)).copied())
        .collect();
    let mut tiles: Vec<(TileCoord, Vec<u8>)> = Vec::new();
    for z in 0..=max_zoom {
        let (rings, stats) = coverage.rings_at_zoom(z);
        tracing::info!(
            z,
            vertices = stats.vertices,
            repaired = stats.repaired,
            crossing = stats.crossing,
            dropped_rings = stats.dropped_rings,
            "area borders simplified"
        );
        let per_feature: Vec<TileRings> = rings.par_iter().map(|f| tile_rings(f, z)).collect();
        let empty = TileRings::new();
        let mut by_tile: BTreeMap<(u32, u32), TileLayers> = BTreeMap::new();
        let layers: [LayerFeatures<'_, '_>; 2] = [
            (
                LAYER,
                &AREA_KEYS,
                area_items.iter().zip(&per_feature).collect(),
            ),
            (
                GAPS_LAYER,
                &GAP_KEYS,
                gap_list
                    .iter()
                    .zip(&gap_of)
                    .map(|(g, at)| (g, at.and_then(|i| per_feature.get(i)).unwrap_or(&empty)))
                    .collect(),
            ),
        ];
        for (slot, (name, keys, features)) in layers.iter().enumerate() {
            for (mvt_id, (item, per_tile)) in (0_u64..).zip(features) {
                for (xy, rings) in per_tile.iter() {
                    let geometry = encode_polygon(rings);
                    if geometry.is_empty() {
                        continue;
                    }
                    let tile = by_tile.entry(*xy).or_default();
                    if let Some(layer) = tile.get_mut(slot) {
                        layer
                            .get_or_insert_with(|| LayerBuilder::new(name, keys))
                            .push(mvt_id, item, geometry);
                    }
                }
            }
        }
        tiles.reserve(by_tile.len());
        tiles.extend(by_tile.into_iter().map(|((x, y), layers)| {
            let tile = proto::Tile {
                layers: layers
                    .into_iter()
                    .flatten()
                    .map(LayerBuilder::into_layer)
                    .collect(),
            };
            (TileCoord::new(z, x, y), tile.encode_to_vec())
        }));
    }
    tiles
}

/// Write `areas.pmtiles`: the tiles of [`render_area_tiles`], gzip
/// compressed, with metadata `vector_layers`, `attribution` and
/// `generator`. The header bounds are those of the areas and gap pieces.
///
/// # Errors
///
/// Fails if a tile cannot be compressed or the archive cannot be written.
pub fn write_areas_pmtiles(
    path: &Path,
    areas: &[Area],
    gaps: &[GapPiece],
    max_zoom: u8,
    attribution: &str,
    bounds: Option<[f64; 4]>,
) -> Result<TileStats> {
    if max_zoom > MAX_ZOOM {
        return Err(DatasetError::usage(format!(
            "areas tiles reach zoom {MAX_ZOOM} at most, not {max_zoom}"
        )));
    }
    let revision = tiles_revision()?;
    let mut tiles: Vec<(u64, Vec<u8>)> = render_area_tiles(areas, gaps, max_zoom)
        .into_iter()
        .map(|(coord, mvt)| (tile_to_pmtiles_id(coord), mvt))
        .collect();
    tiles.sort_unstable_by_key(|(id, _)| *id);

    let mut writer = PmtilesWriter::create(path, Compression::Gzip, TileType::Mvt, 0, max_zoom)
        .io_at(IoOp::Create, path)?;
    let header_bounds = match bounds {
        Some([min_lon, min_lat, max_lon, max_lat]) => Some((min_lon, min_lat, max_lon, max_lat)),
        None => {
            let rects = areas
                .iter()
                .filter_map(|a| a.shape.bounding_rect())
                .chain(gaps.iter().filter_map(|g| g.shape.bounding_rect()));
            rects
                .reduce(|a, b| {
                    geo::Rect::new(
                        Coord {
                            x: a.min().x.min(b.min().x),
                            y: a.min().y.min(b.min().y),
                        },
                        Coord {
                            x: a.max().x.max(b.max().x),
                            y: a.max().y.max(b.max().y),
                        },
                    )
                })
                .map(|r| (r.min().x, r.min().y, r.max().x, r.max().y))
        }
    };
    if let Some((min_lon, min_lat, max_lon, max_lat)) = header_bounds {
        writer.set_bounds(min_lon, min_lat, max_lon, max_lat);
    }
    for (id, mvt) in &tiles {
        let mut gz = GzEncoder::new(
            Vec::with_capacity(mvt.len()),
            flate2::Compression::default(),
        );
        gz.write_all(mvt).io_step("failed to gzip a tile")?;
        let compressed = gz.finish().io_step("failed to gzip a tile")?;
        writer
            .write_tile(*id, &compressed)
            .io_at(IoOp::Write, path)?;
    }
    let tiles_written = writer.tiles_written();
    let unique_tiles = writer.unique_tiles() as u64;
    let metadata = json!({
        "vector_layers": [{
            "id": LAYER,
            "fields": { "id": "String", "kind": "String" },
            "minzoom": 0,
            "maxzoom": max_zoom,
        }, {
            "id": GAPS_LAYER,
            "fields": {
                "id": "String",
                "region_code": "String",
                "region_name": "String",
                "label": "String",
            },
            "minzoom": 0,
            "maxzoom": max_zoom,
        }],
        "attribution": attribution,
        "tiles_revision": revision,
        "generator": concat!("geolith ", env!("CARGO_PKG_VERSION")),
    });
    writer
        .finalize(serde_json::to_string(&metadata)?.as_bytes())
        .io_at(IoOp::Write, path)?;
    let bytes = std::fs::metadata(path).io_at(IoOp::Stat, path)?.len();
    Ok(TileStats {
        tiles_written,
        unique_tiles,
        bytes,
    })
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::io::Read as _;

    use super::*;
    use geo::{LineString, MultiPolygon, Polygon};
    use geolith::geometry::mercator::{wgs84_to_world, world_to_tile};
    use std::collections::BTreeMap;

    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> LineString<f64> {
        LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)])
    }

    fn area(id: &str, polygon: Polygon<f64>) -> Area {
        Area {
            code: None,
            id: id.to_string(),
            name: id.to_string(),
            country: "IN".to_string(),
            level: "county".to_string(),
            parent_id: None,
            parent_name: None,
            region_code: None,
            shape: MultiPolygon(vec![polygon]),
        }
    }

    fn decode(bytes: &[u8]) -> proto::Tile {
        proto::Tile::decode(bytes).expect("tile decodes")
    }

    /// The string properties of `feature` in `layer`.
    fn props(
        layer: &proto::tile::Layer,
        feature: &proto::tile::Feature,
    ) -> HashMap<String, String> {
        feature
            .tags
            .chunks(2)
            .map(|kv| {
                let key = layer.keys[kv[0] as usize].clone();
                let value = layer.values[kv[1] as usize]
                    .string_value
                    .clone()
                    .expect("string value");
                (key, value)
            })
            .collect()
    }

    /// Every feature of every tile, with its tile and properties.
    fn features(
        tiles: &[(TileCoord, Vec<u8>)],
    ) -> Vec<(TileCoord, proto::tile::Feature, HashMap<String, String>)> {
        tiles
            .iter()
            .flat_map(|(coord, bytes)| {
                let tile = decode(bytes);
                tile.layers
                    .iter()
                    .flat_map(|layer| {
                        layer
                            .features
                            .iter()
                            .map(|f| (*coord, f.clone(), props(layer, f)))
                            .collect::<Vec<_>>()
                    })
                    .collect::<Vec<_>>()
            })
            .collect()
    }

    /// Number of `ClosePath` commands (id 7) in MVT geometry commands.
    fn close_paths(geometry: &[u32]) -> usize {
        let (mut i, mut closes) = (0, 0);
        while i < geometry.len() {
            let (id, count) = (geometry[i] & 7, (geometry[i] >> 3) as usize);
            i += 1;
            match id {
                1 | 2 => i += 2 * count,
                7 => closes += count,
                _ => panic!("bad command {id}"),
            }
        }
        closes
    }

    #[test]
    fn tiles_carry_one_areas_layer() {
        let areas = [area(
            "div-x",
            Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![]),
        )];
        let tiles = render_area_tiles(&areas, &[], 4);
        assert!(!tiles.is_empty(), "no tiles rendered");
        for (coord, bytes) in &tiles {
            let tile = decode(bytes);
            assert_eq!(tile.layers.len(), 1, "layers of {coord:?}");
            let layer = tile.layers.first().expect("one layer");
            assert_eq!(layer.name, "areas");
            assert_eq!(layer.extent, Some(4096));
        }
    }

    #[test]
    fn the_tile_under_a_centroid_holds_that_area() {
        let areas = [
            area("div-x", Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![])),
            area("div-y", Polygon::new(rect(10.0, 10.0, 11.0, 11.0), vec![])),
        ];
        let tiles = render_area_tiles(&areas, &[], 5);
        let (wx, wy) = wgs84_to_world(72.5, 25.5);
        let under = world_to_tile(wx, wy, 5);
        let ids: Vec<String> = features(&tiles)
            .into_iter()
            .filter(|(coord, _, _)| *coord == under)
            .filter_map(|(_, _, p)| p.get("id").cloned())
            .collect();
        assert!(
            ids.iter().any(|id| id == "div-x"),
            "ids under {under:?}: {ids:?}"
        );
        assert!(
            !ids.iter().any(|id| id == "div-y"),
            "div-y is far away: {ids:?}"
        );
    }

    #[test]
    fn holes_survive_clipping() {
        let holed = Polygon::new(
            rect(60.0, 10.0, 90.0, 40.0),
            vec![rect(70.0, 20.0, 80.0, 30.0)],
        );
        let tiles = render_area_tiles(&[area("div-h", holed)], &[], 3);
        let (wx, wy) = wgs84_to_world(75.0, 25.0);
        let under = world_to_tile(wx, wy, 3);
        let (_, feature, _) = features(&tiles)
            .into_iter()
            .find(|(coord, _, p)| *coord == under && p.get("id").is_some_and(|id| id == "div-h"))
            .expect("div-h in the tile under the hole");
        assert_eq!(close_paths(&feature.geometry), 2, "exterior and hole");
    }

    #[test]
    fn gaps_are_tagged() {
        let areas = [area(
            "div-x",
            Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![]),
        )];
        let gap = GapPiece {
            id: "gap-1".to_string(),
            area_sq_deg: 1.0,
            centroid: (74.5, 25.5),
            region_id: None,
            region_name: None,
            region_code: None,
            shape: MultiPolygon(vec![Polygon::new(rect(74.0, 25.0, 75.0, 26.0), vec![])]),
        };
        let tiles = render_area_tiles(&areas, &[gap], 4);
        let all = features(&tiles);
        let (_, _, p) = all
            .iter()
            .find(|(_, _, p)| p.get("kind").is_some_and(|k| k == "gap"))
            .expect("a gap feature");
        assert_eq!(p.get("id").map(String::as_str), Some("gap-1"));
        let (_, _, d) = all
            .iter()
            .find(|(_, _, p)| p.get("id").is_some_and(|id| id == "div-x"))
            .expect("the district feature");
        assert_eq!(d.get("kind").map(String::as_str), Some("district"));
    }

    #[test]
    fn the_gaps_layer_carries_region_and_label() {
        let gap = GapPiece {
            id: "gap-1".to_string(),
            area_sq_deg: 1.0,
            centroid: (74.5, 25.5),
            region_id: Some("div-jk".to_string()),
            region_name: Some("JK name".to_string()),
            region_code: Some("IN-JK".to_string()),
            shape: MultiPolygon(vec![Polygon::new(rect(74.0, 25.0, 75.0, 26.0), vec![])]),
        };
        let tiles = render_area_tiles(&[], &[gap], 4);
        let (wx, wy) = wgs84_to_world(74.5, 25.5);
        let under = world_to_tile(wx, wy, 4);
        let (_, bytes) = tiles
            .iter()
            .find(|(coord, _)| *coord == under)
            .expect("the tile under the gap");
        let tile = decode(bytes);
        let layer = tile
            .layers
            .iter()
            .find(|l| l.name == "gaps")
            .expect("a gaps layer");
        assert_eq!(layer.extent, Some(4096));
        let feature = layer.features.first().expect("a gap feature");
        let p = props(layer, feature);
        assert_eq!(p.get("id").map(String::as_str), Some("gap-1"));
        assert_eq!(p.get("region_code").map(String::as_str), Some("IN-JK"));
        assert_eq!(p.get("region_name").map(String::as_str), Some("JK name"));
        assert_eq!(
            p.get("label").map(String::as_str),
            Some("District data not available")
        );
    }

    #[test]
    fn a_gap_without_a_region_has_no_region_tags() {
        let gap = GapPiece {
            id: "gap-1".to_string(),
            area_sq_deg: 1.0,
            centroid: (74.5, 25.5),
            region_id: None,
            region_name: None,
            region_code: None,
            shape: MultiPolygon(vec![Polygon::new(rect(74.0, 25.0, 75.0, 26.0), vec![])]),
        };
        let tiles = render_area_tiles(&[], &[gap], 2);
        let tagged: Vec<HashMap<String, String>> = tiles
            .iter()
            .flat_map(|(_, bytes)| {
                let tile = decode(bytes);
                tile.layers
                    .iter()
                    .filter(|l| l.name == "gaps")
                    .flat_map(|l| l.features.iter().map(|f| props(l, f)).collect::<Vec<_>>())
                    .collect::<Vec<_>>()
            })
            .collect();
        assert!(!tagged.is_empty(), "gap features rendered");
        for p in &tagged {
            assert!(!p.contains_key("region_code"), "{p:?}");
            assert!(!p.contains_key("region_name"), "{p:?}");
            assert!(p.get("label").is_some_and(|l| !l.is_empty()), "{p:?}");
        }
    }

    #[test]
    fn the_archive_records_attribution() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("areas.pmtiles");
        let areas = [area(
            "div-x",
            Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![]),
        )];
        let attribution = "Boundaries: test attribution ©";
        let stats = write_areas_pmtiles(&path, &areas, &[], 3, attribution, None).expect("write");
        let bytes = std::fs::read(&path).expect("archive bytes");
        assert_eq!(&bytes[0..7], b"PMTiles");
        assert_eq!(bytes[7], 3, "PMTiles v3");
        assert_eq!(stats.bytes, bytes.len() as u64);
        let field =
            |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")) as usize;
        let (offset, length) = (field(24), field(32));
        let mut metadata = String::new();
        flate2::read::GzDecoder::new(&bytes[offset..offset + length])
            .read_to_string(&mut metadata)
            .expect("gunzip metadata");
        let json: serde_json::Value = serde_json::from_str(&metadata).expect("metadata json");
        assert_eq!(json["attribution"], attribution);
        let layer = json["vector_layers"]
            .as_array()
            .expect("vector_layers")
            .iter()
            .find(|l| l["id"] == "areas")
            .expect("areas layer");
        assert_eq!(layer["maxzoom"], 3);
        assert_eq!(layer["fields"]["kind"], "String");
        let gaps = json["vector_layers"]
            .as_array()
            .expect("vector_layers")
            .iter()
            .find(|l| l["id"] == "gaps")
            .expect("gaps layer");
        assert_eq!(gaps["fields"]["region_code"], "String");
        assert_eq!(gaps["fields"]["label"], "String");
    }

    // ---- a coverage with shared, wiggly borders -------------------------

    /// A border from `a` to `b` (lon/lat) with 200 vertices of deterministic
    /// wiggle across it, tapered to the ends (none when `straight`).
    fn border(a: (f64, f64), b: (f64, f64), seed: f64, straight: bool) -> Vec<(f64, f64)> {
        let (dx, dy) = (b.0 - a.0, b.1 - a.1);
        let len = dx.hypot(dy);
        let (nx, ny) = (-dy / len, dx / len);
        (0..=200)
            .map(|k| {
                let t = f64::from(k) / 200.0;
                let w = if straight || k == 0 || k == 200 {
                    0.0
                } else {
                    // Tapered to the ends, so borders meeting at a node do not
                    // cross there.
                    (std::f64::consts::PI * t).sin()
                        * (0.004 * (37.0 * t + seed).sin() + 0.002 * (91.0 * t + 2.0 * seed).sin())
                };
                (a.0 + t * dx + w * nx, a.1 + t * dy + w * ny)
            })
            .collect()
    }

    /// A 3×3 block of districts (0.1° cells at 77°E 28°N) with wiggly inner
    /// borders and a straight outside; the last cell is a gap piece; the
    /// centre cell holds an enclave; plus an island with a lake far away.
    fn block() -> (Vec<Area>, Vec<GapPiece>) {
        let node = |i: usize, j: usize| (77.0 + 0.1 * i as f64, 28.0 + 0.1 * j as f64);
        // Horizontal border j from node (i, j) to (i + 1, j); vertical border
        // i from (i, j) to (i, j + 1).
        let h = |i: usize, j: usize| {
            border(
                node(i, j),
                node(i + 1, j),
                (i * 7 + j) as f64,
                j == 0 || j == 3,
            )
        };
        let v = |i: usize, j: usize| {
            border(
                node(i, j),
                node(i, j + 1),
                (i * 11 + j + 50) as f64,
                i == 0 || i == 3,
            )
        };
        let enclave: Vec<(f64, f64)> = (0..=60)
            .map(|k| {
                let a = f64::from(k) / 60.0 * std::f64::consts::TAU;
                let r = 0.02 + 0.004 * (5.0 * a).sin();
                (77.15 + r * a.cos(), 28.15 + r * a.sin())
            })
            .collect();
        let mut areas = Vec::new();
        let mut gaps = Vec::new();
        for i in 0..3 {
            for j in 0..3 {
                let mut ring: Vec<(f64, f64)> = h(i, j);
                ring.extend(v(i + 1, j).into_iter().skip(1));
                ring.extend(h(i, j + 1).into_iter().rev().skip(1));
                ring.extend(v(i, j).into_iter().rev().skip(1));
                let holes = if (i, j) == (1, 1) {
                    vec![LineString::from(
                        enclave.iter().rev().copied().collect::<Vec<_>>(),
                    )]
                } else {
                    vec![]
                };
                let polygon = Polygon::new(LineString::from(ring), holes);
                if (i, j) == (2, 2) {
                    gaps.push(GapPiece {
                        id: "gap-1".to_string(),
                        area_sq_deg: 0.01,
                        centroid: (77.25, 28.25),
                        region_id: None,
                        region_name: None,
                        region_code: None,
                        shape: MultiPolygon(vec![polygon]),
                    });
                } else {
                    areas.push(area(&format!("div-{i}{j}"), polygon));
                }
            }
        }
        areas.push(area(
            "div-enclave",
            Polygon::new(LineString::from(enclave), vec![]),
        ));
        let island: Vec<(f64, f64)> = (0..=80)
            .map(|k| {
                let a = f64::from(k) / 80.0 * std::f64::consts::TAU;
                let r = 0.05 + 0.01 * (7.0 * a).sin();
                (78.0 + r * a.cos(), 27.5 + r * a.sin())
            })
            .collect();
        areas.push(area(
            "div-island",
            Polygon::new(
                LineString::from(island),
                vec![rect(77.99, 27.49, 78.01, 27.51)],
            ),
        ));
        (areas, gaps)
    }

    /// Rings (tile units, open) of every feature of layer `name`, by id.
    /// A decoded feature: id and rings (tile units, open).
    type Decoded = (String, Vec<Vec<(i64, i64)>>);

    /// Edges by their ends (smaller first) and the ids drawing them.
    type EdgeOwners<'a> = BTreeMap<((i64, i64), (i64, i64)), Vec<&'a str>>;

    fn layer_rings(bytes: &[u8], name: &str) -> Vec<Decoded> {
        let tile = decode(bytes);
        let Some(layer) = tile.layers.iter().find(|l| l.name == name) else {
            return Vec::new();
        };
        layer
            .features
            .iter()
            .map(|f| {
                let id = props(layer, f).remove("id").expect("id");
                let mut rings: Vec<Vec<(i64, i64)>> = Vec::new();
                let (mut x, mut y, mut i) = (0_i64, 0_i64, 0);
                let zz = |v: u32| i64::from((v >> 1) as i32 ^ -((v & 1) as i32));
                let g = &f.geometry;
                while i < g.len() {
                    let (cmd, count) = (g[i] & 7, (g[i] >> 3) as usize);
                    i += 1;
                    if cmd == 7 {
                        continue;
                    }
                    for _ in 0..count {
                        x += zz(g[i]);
                        y += zz(g[i + 1]);
                        i += 2;
                        if cmd == 1 {
                            rings.push(Vec::new());
                        }
                        if let Some(r) = rings.last_mut() {
                            r.push((x, y));
                        }
                    }
                }
                (id, rings)
            })
            .collect()
    }

    /// Whether two segments of `ring` meet anywhere but at the vertex two
    /// consecutive segments share.
    fn self_intersects(ring: &[(i64, i64)]) -> bool {
        use crate::topology::{Contact, contact};
        let n = ring.len();
        for i in 0..n {
            for j in i + 1..n {
                let c = contact(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n]);
                let adjacent = j == i + 1 || (i == 0 && j == n - 1);
                match c {
                    Contact::None => {}
                    Contact::SharedEnd if adjacent => {}
                    _ => return true,
                }
            }
        }
        false
    }

    /// Pixels (centres) of the tile interior that two areas cover, and
    /// uncovered pixels inside `region` (tile units) no uncovered path joins
    /// to its edge.
    fn overlap_and_gap(features: &[Decoded], region: (i64, i64, i64, i64)) -> (usize, usize) {
        let (x0, y0, x1, y1) = (
            region.0.max(0),
            region.1.max(0),
            region.2.min(4096),
            region.3.min(4096),
        );
        if x0 >= x1 || y0 >= y1 {
            return (0, 0);
        }
        let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);
        let mut count = vec![0_u8; w * h];
        for (_, rings) in features {
            for row in 0..h {
                let yc = (y0 + row as i64) as f64 + 0.5;
                let mut xs: Vec<f64> = Vec::new();
                for ring in rings {
                    for k in 0..ring.len() {
                        let (mut a, mut b) = (ring[k], ring[(k + 1) % ring.len()]);
                        if a.1 == b.1 {
                            continue;
                        }
                        if a.1 > b.1 {
                            std::mem::swap(&mut a, &mut b);
                        }
                        let (ay, by) = (a.1 as f64, b.1 as f64);
                        if ay <= yc && yc < by {
                            xs.push(a.0 as f64 + (yc - ay) * (b.0 - a.0) as f64 / (by - ay));
                        }
                    }
                }
                xs.sort_by(f64::total_cmp);
                for pair in xs.chunks(2) {
                    if let [l, r] = pair {
                        let from = ((l - 0.5).ceil() as i64).max(x0);
                        let to = ((r - 0.5).ceil() as i64).min(x1);
                        for x in from..to {
                            let i = row * w + (x - x0) as usize;
                            count[i] = count[i].saturating_add(1);
                        }
                    }
                }
            }
        }
        let overlap = count.iter().filter(|&&c| c >= 2).count();
        let mut outside = vec![false; w * h];
        let mut stack: Vec<usize> = (0..w)
            .flat_map(|x| [x, (h - 1) * w + x])
            .chain((0..h).flat_map(|y| [y * w, y * w + w - 1]))
            .collect();
        while let Some(i) = stack.pop() {
            if outside[i] || count[i] != 0 {
                continue;
            }
            outside[i] = true;
            let (x, y) = (i % w, i / w);
            if x > 0 {
                stack.push(i - 1);
            }
            if x + 1 < w {
                stack.push(i + 1);
            }
            if y > 0 {
                stack.push(i - w);
            }
            if y + 1 < h {
                stack.push(i + w);
            }
        }
        let gap = (0..w * h).filter(|&i| count[i] == 0 && !outside[i]).count();
        (overlap, gap)
    }

    #[test]
    fn every_ring_of_a_coverage_is_simple_at_every_zoom() {
        let (areas, gaps) = block();
        for (coord, bytes) in render_area_tiles(&areas, &gaps, 10) {
            for name in ["areas", "gaps"] {
                for (id, rings) in layer_rings(&bytes, name) {
                    for ring in &rings {
                        assert!(
                            ring.len() >= 3,
                            "{coord:?} {id}: ring of {} points",
                            ring.len()
                        );
                        assert!(
                            !self_intersects(ring),
                            "{coord:?} {id}: ring crosses itself"
                        );
                    }
                }
            }
        }
    }

    /// Every inner edge is drawn by both neighbours and the block has no
    /// overlap or gap (pixel centres, one MVT unit each). From z4, where a 0.1° cell spans two pixels of a 512 px tile (below
    /// that, a cell may collapse to no area and leave its neighbours' borders
    /// unpaired, which draws no gap).
    #[test]
    fn neighbours_share_every_inner_border_at_every_zoom() {
        let (areas, gaps) = block();
        let mut total_shared = 0.0;
        for (coord, bytes) in render_area_tiles(&areas, &gaps, 10)
            .into_iter()
            .filter(|(c, _)| c.z >= 4)
        {
            let features = layer_rings(&bytes, "areas");
            let mut owners: EdgeOwners<'_> = BTreeMap::new();
            for (id, rings) in &features {
                for ring in rings {
                    for k in 0..ring.len() {
                        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
                        owners
                            .entry(if a < b { (a, b) } else { (b, a) })
                            .or_default()
                            .push(id);
                    }
                }
            }
            // The block's outside, in this tile's units.
            let n = f64::from(1_u32 << coord.z);
            let to_tile = |lon: f64, lat: f64| {
                let (wx, wy) = wgs84_to_world(lon, lat);
                (
                    ((wx * n - f64::from(coord.x)) * 4096.0).round() as i64,
                    ((wy * n - f64::from(coord.y)) * 4096.0).round() as i64,
                )
            };
            let (left, top) = to_tile(77.0, 28.3);
            let (right, bottom) = to_tile(77.3, 28.0);
            let inside = |p: (i64, i64)| (0..=4096).contains(&p.0) && (0..=4096).contains(&p.1);
            let outer = |a: (i64, i64), b: (i64, i64)| {
                (a.0 == b.0 && (a.0 == left || a.0 == right))
                    || (a.1 == b.1 && (a.1 == top || a.1 == bottom))
            };
            let (overlap, gap) = overlap_and_gap(&features, (left, top, right, bottom));
            assert_eq!((overlap, gap), (0, 0), "{coord:?}: overlap and gap, units²");
            let (mut shared, mut alone) = (0.0, 0.0);
            for ((a, b), ids) in &owners {
                let island = ids.iter().all(|id| *id == "div-island");
                if !inside(*a) || !inside(*b) || outer(*a, *b) || island {
                    continue;
                }
                let len = ((b.0 - a.0) as f64).hypot((b.1 - a.1) as f64);
                assert!(
                    ids.len() <= 2,
                    "{coord:?}: edge {a:?}-{b:?} drawn by {ids:?}"
                );
                if ids.len() == 2 {
                    shared += len;
                } else {
                    alone += len;
                }
            }
            total_shared += shared;
            assert!(
                alone == 0.0,
                "{coord:?}: {alone:.0} units of inner border drawn by one side, {shared:.0} by both"
            );
        }
        assert!(total_shared > 0.0, "no shared border drawn");
    }

    #[test]
    fn the_gaps_layer_draws_the_gap_pieces_as_the_areas_layer() {
        let (areas, gaps) = block();
        for (coord, bytes) in render_area_tiles(&areas, &gaps, 8) {
            let gap_rings = layer_rings(&bytes, "gaps");
            let in_areas: Vec<_> = layer_rings(&bytes, "areas")
                .into_iter()
                .filter(|(id, _)| id.starts_with("gap-"))
                .collect();
            assert_eq!(gap_rings, in_areas, "{coord:?}");
        }
    }

    #[test]
    fn small_areas_keep_a_shape_while_they_span_two_pixels() {
        let (areas, gaps) = block();
        // The enclave is 0.04° across: at z5 about 4.6 px of a 512 px tile.
        for z in 5..=10_u8 {
            let present = render_area_tiles(&areas, &gaps, z)
                .iter()
                .filter(|(c, _)| c.z == z)
                .any(|(_, bytes)| {
                    layer_rings(bytes, "areas")
                        .iter()
                        .any(|(id, rings)| id == "div-enclave" && !rings.is_empty())
                });
            assert!(present, "z{z}: the enclave vanished");
        }
    }

    #[test]
    fn two_renders_are_byte_identical() {
        let (areas, gaps) = block();
        assert_eq!(
            render_area_tiles(&areas, &gaps, 8),
            render_area_tiles(&areas, &gaps, 8)
        );
    }

    /// Fingerprint (xxh3 of every tile's coordinate and bytes) of the block
    /// rendered to z8, per tiles revision. A change of the tiles must bump
    /// `tiles_revision` in `packages/dataset-builder/data/datasets/boundaries.json` (the
    /// published archive of a revision is immutable) and record the new
    /// fingerprint here.
    const FINGERPRINTS: &[(u64, u64)] = &[(2, 0xf9db_9a2a_1b4a_6fde)];

    #[test]
    fn a_change_of_the_tiles_bumps_the_tiles_revision() {
        let (areas, gaps) = block();
        let mut bytes = Vec::new();
        for (coord, tile) in render_area_tiles(&areas, &gaps, 8) {
            bytes.extend_from_slice(&[coord.z]);
            bytes.extend_from_slice(&coord.x.to_le_bytes());
            bytes.extend_from_slice(&coord.y.to_le_bytes());
            bytes.extend_from_slice(&(tile.len() as u64).to_le_bytes());
            bytes.extend_from_slice(&tile);
        }
        let fingerprint = xxhash_rust::xxh3::xxh3_64(&bytes);
        let revision = tiles_revision().expect("tiles revision");
        let recorded = FINGERPRINTS
            .iter()
            .find(|(r, _)| *r == revision)
            .map(|(_, f)| *f);
        assert_eq!(
            recorded,
            Some(fingerprint),
            "the areas tiles changed (fingerprint {fingerprint:#x}) under tiles_revision \
             {revision}: bump tiles_revision in packages/dataset-builder/data/datasets/boundaries.json and \
             record ({}, {fingerprint:#x}) in FINGERPRINTS",
            revision + 1
        );
        assert!(
            FINGERPRINTS.iter().all(|(r, _)| *r <= revision),
            "a fingerprint is recorded for a revision above {revision}"
        );
    }

    #[test]
    fn the_tiles_revision_is_at_least_two() {
        // Revision 1 is the published per-polygon simplification.
        assert!(tiles_revision().expect("tiles revision") >= 2);
    }
}