geolith-cli 0.2.2

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
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
#![allow(clippy::unwrap_used)] // tests and benches may unwrap (AGENTS.md).

//! End-to-end run of the tile pipeline on a tiny fixture source set.
//!
//! Writes one Overture `transportation/segment` Parquet file, an empty
//! Natural Earth database, and one land and one water shapefile, runs
//! [`geolith_cli::run_with_config`], then reads the `PMTiles` archive back with an
//! independent reader written from the `PMTiles` v3 spec and decodes the MVT
//! tiles. Nothing here uses geolith's own archive or directory code, so the
//! assertions check what a map client would actually receive.

use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;

use arrow::array::{
    Array, ArrayRef, BinaryArray, Float32Array, Float64Builder, ListArray, ListBuilder,
    StringArray, StringBuilder, StructArray,
};
use arrow::buffer::OffsetBuffer;
use arrow::datatypes::{DataType, Field, Fields, Schema};
use arrow::record_batch::RecordBatch;
use clap::Parser;
use geolith_cli::tile::mvt::proto;
use parquet::arrow::ArrowWriter;
use prost::Message;

/// One Overture segment row for the fixture.
struct Segment {
    id: &'static str,
    subtype: &'static str,
    class: &'static str,
    line: [(f64, f64); 2],
    /// `(flag, Some((start, end)))` for a partial rule, `None` for whole.
    flags: Vec<(&'static str, Option<(f64, f64)>)>,
}

fn wkb_line(line: &[(f64, f64)]) -> Vec<u8> {
    let mut b = vec![1u8];
    b.extend_from_slice(&2u32.to_le_bytes());
    b.extend_from_slice(&(line.len() as u32).to_le_bytes());
    for (x, y) in line {
        b.extend_from_slice(&x.to_le_bytes());
        b.extend_from_slice(&y.to_le_bytes());
    }
    b
}

/// `road_flags` shaped exactly as in Overture v1.18:
/// `list<struct<values: list<string>, between: list<double>>>`, one rule per flag.
fn road_flags(rows: &[Segment]) -> ListArray {
    let mut values = ListBuilder::new(StringBuilder::new());
    let mut between = ListBuilder::new(Float64Builder::new());
    let mut lengths = Vec::with_capacity(rows.len());
    for row in rows {
        lengths.push(row.flags.len());
        for (flag, range) in &row.flags {
            values.values().append_value(flag);
            values.append(true);
            match range {
                Some((a, b)) => {
                    between.values().append_value(*a);
                    between.values().append_value(*b);
                    between.append(true);
                }
                None => between.append(false),
            }
        }
    }
    let values = values.finish();
    let between = between.finish();
    let fields = Fields::from(vec![
        Field::new("values", values.data_type().clone(), true),
        Field::new("between", between.data_type().clone(), true),
    ]);
    let rules = StructArray::new(
        fields.clone(),
        vec![Arc::new(values) as ArrayRef, Arc::new(between)],
        None,
    );
    ListArray::new(
        Arc::new(Field::new("item", DataType::Struct(fields), true)),
        OffsetBuffer::from_lengths(lengths),
        Arc::new(rules),
        None,
    )
}

fn write_segments(dir: &Path, rows: &[Segment]) {
    write_segment_file(dir, "part-00000.parquet", rows);
}

fn write_segment_file(dir: &Path, file: &str, rows: &[Segment]) {
    let part = dir.join("theme=transportation/type=segment");
    std::fs::create_dir_all(&part).expect("partition dir");

    let bbox_fields = Fields::from(vec![
        Field::new("xmin", DataType::Float32, false),
        Field::new("ymin", DataType::Float32, false),
        Field::new("xmax", DataType::Float32, false),
        Field::new("ymax", DataType::Float32, false),
    ]);
    let coord = |f: fn(f64, f64) -> f64, i: usize| -> Float32Array {
        rows.iter()
            .map(|r| {
                let [(x0, y0), (x1, y1)] = r.line;
                let pair = if i == 0 { (x0, x1) } else { (y0, y1) };
                f(pair.0, pair.1) as f32
            })
            .collect()
    };
    let bbox = StructArray::new(
        bbox_fields.clone(),
        vec![
            Arc::new(coord(f64::min, 0)) as ArrayRef,
            Arc::new(coord(f64::min, 1)),
            Arc::new(coord(f64::max, 0)),
            Arc::new(coord(f64::max, 1)),
        ],
        None,
    );
    let flags = road_flags(rows);
    let wkb: Vec<Vec<u8>> = rows.iter().map(|r| wkb_line(&r.line)).collect();

    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("geometry", DataType::Binary, false),
        Field::new("bbox", DataType::Struct(bbox_fields), false),
        Field::new("subtype", DataType::Utf8, true),
        Field::new("class", DataType::Utf8, true),
        Field::new("road_flags", flags.data_type().clone(), true),
    ]));
    let batch = RecordBatch::try_new(
        schema.clone(),
        vec![
            Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.id))) as ArrayRef,
            Arc::new(BinaryArray::from_iter_values(wkb.iter())),
            Arc::new(bbox),
            Arc::new(StringArray::from_iter_values(
                rows.iter().map(|r| r.subtype),
            )),
            Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.class))),
            Arc::new(flags),
        ],
    )
    .expect("record batch");
    let file = std::fs::File::create(part.join(file)).expect("parquet file");
    let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
    writer.write(&batch).expect("write");
    writer.close().expect("close");
}

/// One square polygon in EPSG:3857 metres, as the OSM land/water shapefiles are.
fn write_square_shapefile(dir: &Path, name: &str, min: f64, max: f64) {
    use shapefile::dbase::{Record, TableWriterBuilder};
    use shapefile::record::polygon::{Polygon, PolygonRing};
    use shapefile::{Point, Writer};

    std::fs::create_dir_all(dir).expect("shapefile dir");
    let mut writer = Writer::from_path(dir.join(format!("{name}.shp")), TableWriterBuilder::new())
        .expect("shapefile writer");
    let ring = vec![
        Point::new(min, min),
        Point::new(min, max),
        Point::new(max, max),
        Point::new(max, min),
        Point::new(min, min),
    ];
    writer
        .write_shape_and_record(
            &Polygon::with_rings(vec![PolygonRing::Outer(ring)]),
            &Record::default(),
        )
        .expect("write polygon");
}

// ─── Independent PMTiles v3 reader (spec: github.com/protomaps/PMTiles/spec/v3) ───

fn read_varint(buf: &[u8], pos: &mut usize) -> u64 {
    let mut value = 0u64;
    let mut shift = 0;
    loop {
        let byte = buf[*pos];
        *pos += 1;
        value |= u64::from(byte & 0x7f) << shift;
        if byte & 0x80 == 0 {
            return value;
        }
        shift += 7;
    }
}

fn decompress(bytes: &[u8], compression: u8) -> Vec<u8> {
    match compression {
        1 => bytes.to_vec(),
        2 => {
            let mut out = Vec::new();
            flate2::read::GzDecoder::new(bytes)
                .read_to_end(&mut out)
                .expect("gzip");
            out
        }
        other => panic!("unexpected PMTiles compression {other}"),
    }
}

fn u64_at(buf: &[u8], at: usize) -> u64 {
    u64::from_le_bytes(buf[at..at + 8].try_into().expect("8 bytes"))
}

/// Every tile payload in the archive, keyed by tile id.
fn read_all_tiles(archive: &[u8]) -> HashMap<u64, Vec<u8>> {
    assert_eq!(&archive[..7], b"PMTiles");
    assert_eq!(archive[7], 3);
    let (root_off, root_len) = (u64_at(archive, 8), u64_at(archive, 16));
    let leaf_off = u64_at(archive, 40);
    let data_off = u64_at(archive, 56);
    let (internal, tile_comp) = (archive[97], archive[98]);

    let mut tiles = HashMap::new();
    let mut stack = vec![(root_off, root_len)];
    while let Some((off, len)) = stack.pop() {
        let dir = decompress(&archive[off as usize..(off + len) as usize], internal);
        let mut p = 0;
        let n = read_varint(&dir, &mut p) as usize;
        let mut ids = Vec::with_capacity(n);
        let mut last = 0;
        for _ in 0..n {
            last += read_varint(&dir, &mut p);
            ids.push(last);
        }
        let runs: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
        let lens: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
        let mut offs = Vec::with_capacity(n);
        for i in 0..n {
            let raw = read_varint(&dir, &mut p);
            offs.push(if raw == 0 && i > 0 {
                offs[i - 1] + lens[i - 1]
            } else {
                raw - 1
            });
        }
        for i in 0..n {
            if runs[i] == 0 {
                stack.push((leaf_off + offs[i], lens[i]));
                continue;
            }
            let start = (data_off + offs[i]) as usize;
            let payload = decompress(&archive[start..start + lens[i] as usize], tile_comp);
            for k in 0..runs[i] {
                tiles.insert(ids[i] + k, payload.clone());
            }
        }
    }
    tiles
}

/// Zoom of a `PMTiles` tile id: ids start at sum(4^i for i < z).
fn zoom_of(tile_id: u64) -> u8 {
    let (mut z, mut base) = (0u8, 0u64);
    while tile_id >= base + 4u64.pow(u32::from(z)) {
        base += 4u64.pow(u32::from(z));
        z += 1;
    }
    z
}

/// A decoded road: zoom, kind, `kind_detail`, `is_bridge`, ref, and the primary
/// shield's network and text.
#[derive(Debug)]
struct Road {
    zoom: u8,
    kind: String,
    detail: Option<String>,
    bridge: bool,
    reference: Option<String>,
    network: Option<String>,
    shield: Option<String>,
}

fn roads_in(tiles: &HashMap<u64, Vec<u8>>) -> Vec<Road> {
    let mut out = Vec::new();
    for (&id, bytes) in tiles {
        let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
        for layer in tile.layers.iter().filter(|l| l.name == "roads") {
            for f in &layer.features {
                let mut props: HashMap<&str, &proto::tile::Value> = HashMap::new();
                for pair in f.tags.chunks(2) {
                    props.insert(
                        layer.keys[pair[0] as usize].as_str(),
                        &layer.values[pair[1] as usize],
                    );
                }
                let text = |k: &str| props.get(k).and_then(|v| v.string_value.clone());
                out.push(Road {
                    zoom: zoom_of(id),
                    kind: text("kind").unwrap_or_default(),
                    detail: text("kind_detail"),
                    bridge: props.get("is_bridge").and_then(|v| v.bool_value) == Some(true),
                    reference: text("ref"),
                    network: text("network"),
                    shield: text("shield_text"),
                });
            }
        }
    }
    out
}

/// Build a tiny archive around London at z0-z12 and return its roads.
fn build(rows: &[Segment]) -> Vec<Road> {
    build_with(rows, "overture", "-0.3,51.4,0.3,51.6", None)
}

/// Build a tiny archive at z0-z12 with roads from `source` in `bbox`, with
/// an OSM file if one is given, and return its roads.
fn build_with(rows: &[Segment], source: &str, bbox: &str, osm_pbf: Option<&Path>) -> Vec<Road> {
    let mut extra = vec!["--roads-source".to_string(), source.into()];
    if let Some(pbf) = osm_pbf {
        extra.extend(["--osm-pbf".into(), pbf.to_string_lossy().into_owned()]);
    }
    roads_in(&read_all_tiles(&run_fixture(rows, bbox, 12, &extra)))
}

/// Run the pipeline on `rows` in `bbox` up to `max_zoom`, with `extra`
/// flags, and return the `PMTiles` bytes. The land square spans ±40 km
/// around (0, 0), about ±0.36 degrees.
fn run_fixture(rows: &[Segment], bbox: &str, max_zoom: u8, extra: &[String]) -> Vec<u8> {
    run_fixture_on(rows, bbox, max_zoom, extra, None)
}

/// [`run_fixture`] on a rayon pool of `threads` threads, or the global pool.
fn run_fixture_on(
    rows: &[Segment],
    bbox: &str,
    max_zoom: u8,
    extra: &[String],
    threads: Option<usize>,
) -> Vec<u8> {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    write_segments(&root.join("overture"), rows);
    rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
    write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
    write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
    let out = root.join("out.pmtiles");

    let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
    let mut args = vec![
        "geolith".to_string(),
        "--data".into(),
        arg("overture"),
        "--natural-earth".into(),
        arg("ne.sqlite"),
        "--land-polygons".into(),
        arg("land"),
        "--water-polygons".into(),
        arg("water"),
        "--output".into(),
        out.to_string_lossy().into_owned(),
        "--tmpdir".into(),
        arg("tmp"),
        // The node store goes to the temporary directory, not next to an
        // OSM fixture.
        "--node-store".into(),
        arg("nodes.bin"),
        "--no-conflate".into(),
        "--bbox".into(),
        bbox.into(),
        "--max-zoom".into(),
        max_zoom.to_string(),
    ];
    args.extend_from_slice(extra);
    let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");

    match threads {
        Some(n) => rayon::ThreadPoolBuilder::new()
            .num_threads(n)
            .build()
            .expect("thread pool")
            .install(|| geolith_cli::run_with_config(&config)),
        None => geolith_cli::run_with_config(&config),
    }
    .expect("pipeline runs");
    std::fs::read(&out).expect("archive")
}

/// Feature count per layer name in the one tile at `zoom`.
fn layer_counts_at(tiles: &HashMap<u64, Vec<u8>>, zoom: u8) -> HashMap<String, usize> {
    let at_zoom: Vec<&Vec<u8>> = tiles
        .iter()
        .filter(|(id, _)| zoom_of(**id) == zoom)
        .map(|(_, bytes)| bytes)
        .collect();
    assert_eq!(at_zoom.len(), 1, "expected one tile at z{zoom}");
    let tile = proto::Tile::decode(at_zoom[0].as_slice()).expect("valid MVT");
    tile.layers
        .iter()
        .map(|l| (l.name.clone(), l.features.len()))
        .collect()
}

/// The land square covers the whole bbox, so every tile in it has earth.
/// Across ±0.3 degrees, z14 tile x runs from floor(179.7 / 360 * 16384) =
/// 8178 to floor(180.3 / 360 * 16384) = 8205, 28 columns, and the Mercator
/// rows at the equator match: 784 tiles, more than one 512-tile encode
/// batch, so batches are flushed while the merge is still reading.
#[test]
fn a_build_larger_than_one_encode_batch_writes_every_tile() {
    for format in ["mvt", "mlt"] {
        let args = ["--tile-format".to_string(), format.into()];
        let tiles = read_all_tiles(&run_fixture(&[], "-0.3,-0.3,0.3,0.3", 14, &args));
        let z14 = tiles.keys().filter(|id| zoom_of(**id) == 14).count();
        assert_eq!(z14, 28 * 28, "{format}");
    }
}

/// A `--bbox` build records that bbox in the archive header, so a `TileJSON`
/// built from the header frames the region instead of the whole world. The
/// `PMTiles` v3 spec stores the bounds as little-endian i32 degrees x 1e7 at
/// bytes 102 to 117 (min lon, min lat, max lon, max lat).
#[test]
fn a_bbox_build_records_the_bbox_in_the_header() {
    let archive = run_fixture(&touching_motorways(), "-0.06,51.49,-0.02,51.51", 12, &[]);
    let e7 = |at: usize| i32::from_le_bytes(archive[at..at + 4].try_into().expect("four bytes"));
    assert_eq!(
        [e7(102), e7(106), e7(110), e7(114)],
        [-600_000, 514_900_000, -200_000, 515_100_000]
    );
}

/// Two motorways end to end, from -0.05 to -0.04 to -0.03 degrees at
/// latitude 51.5: both inside z12 tile x 2047, as (lon + 180) / 360 * 4096
/// is 2047.43 at one end and 2047.66 at the other.
fn touching_motorways() -> Vec<Segment> {
    [
        ("west", [(-0.05, 51.5), (-0.04, 51.5)]),
        ("east", [(-0.04, 51.5), (-0.03, 51.5)]),
    ]
    .into_iter()
    .map(|(id, line)| Segment {
        id,
        subtype: "road",
        class: "motorway",
        line,
        flags: Vec::new(),
    })
    .collect()
}

/// Same-attribute roads in a tile merge into one feature, as the protomaps
/// basemap's `postProcess` merges them.
#[test]
fn same_attribute_roads_merge_into_one_tile_feature() {
    let bbox = "-0.06,51.49,-0.02,51.51";
    let tiles = read_all_tiles(&run_fixture(&touching_motorways(), bbox, 12, &[]));
    assert_eq!(layer_counts_at(&tiles, 12).get("roads"), Some(&1));
}

/// `relations.osm` has two primary roads in Pune, ways 10 and 11, with no
/// `ref` tag of their own. Both are members of bus route relation 100,
/// which has `ref=42`: a bus line is not a road route, so the roads get
/// neither a ref nor a shield from it (protomaps keeps only `route=road`).
#[test]
fn a_bus_route_gives_an_osm_road_no_ref_or_shield() {
    let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relations.osm.pbf");
    let roads = build_with(&[], "osm", "73.8,18.5,73.9,18.6", Some(&pbf));
    let primary: Vec<&Road> = roads
        .iter()
        .filter(|r| r.detail.as_deref() == Some("primary"))
        .collect();
    assert!(!primary.is_empty(), "no primary road: {roads:?}");
    assert!(
        primary
            .iter()
            .all(|r| r.reference.is_none() && r.network.is_none() && r.shield.is_none()),
        "{primary:?}"
    );
}

/// `berlin-a115.osm.pbf` is cut from the Geofabrik Berlin extract of
/// 2026-10 with `osmium getid`: motorway way 81631742 (the AVUS,
/// `ref=A 115`, `int_ref=E 51`) with its nodes, and six of the route
/// relations it belongs to: 80053 (`route=road`, `network=e-road`,
/// `ref=E 51`), 5485765 (`route=road`, `network=BAB`, `ref=A 115`), 1516377
/// (`route=road`, no network or ref), 3046906 (Flixbus bus `009`), 9581031
/// (Eurolines bus `EU0328`) and 3144678 (Flixbus `038`, `disused:route=bus`).
/// On every zoom and thread count the primary shield is the Autobahn
/// number, never the E-road (the lowest relation id) or a coach line.
#[test]
fn the_avus_shield_is_its_autobahn_number_on_any_thread_count() {
    let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/berlin-a115.osm.pbf");
    let extra = [
        "--roads-source".to_string(),
        "osm".into(),
        "--osm-pbf".into(),
        pbf.to_string_lossy().into_owned(),
    ];
    let bbox = "13.19,52.40,13.20,52.42";
    let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
    let roads = roads_in(&read_all_tiles(&serial));
    assert!(!roads.is_empty(), "no roads");
    assert!(
        roads.iter().all(|r| r.reference.as_deref() == Some("A 115")
            && r.network.as_deref() == Some("BAB")
            && r.shield.as_deref() == Some("A115")),
        "{roads:?}"
    );
    for threads in [2, 4, 8] {
        let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
        assert!(
            parallel == serial,
            "{threads} threads: archive bytes differ"
        );
    }
}

/// `route-relations-many-blobs.osm.pbf`: two touching motorway ways in
/// London, both members of road routes 1 (`A 1`, `BAB`), 10001 (`E 51`,
/// `e-road`) and 20001 (`039`, `Flixbus`), which osmium wrote into three
/// different blobs. Built from a generated `.osm` (3 nodes, ways 10 and 11,
/// the three routes, and `type=site` relations 2..=20000 between them,
/// each with node 1 as its one member so a `--bbox` extract keeps them)
/// with `osmium cat`.
///
/// The primary shield is the `BAB` route on every run and thread count,
/// and the two pieces, with one set of attributes, merge into one feature.
#[test]
fn osm_route_attributes_and_merged_roads_are_identical_on_any_thread_count() {
    let pbf = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/route-relations-many-blobs.osm.pbf");
    let extra = [
        "--roads-source".to_string(),
        "osm".into(),
        "--osm-pbf".into(),
        pbf.to_string_lossy().into_owned(),
    ];
    let bbox = "-0.06,51.49,-0.02,51.51";
    let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
    let tiles = read_all_tiles(&serial);
    let roads = roads_in(&tiles);
    assert!(
        !roads.is_empty()
            && roads
                .iter()
                .all(|r| r.shield.as_deref() == Some("A1") && r.network.as_deref() == Some("BAB")),
        "{roads:?}"
    );
    assert_eq!(
        layer_counts_at(&tiles, 12).get("roads"),
        Some(&1),
        "the two ways merge"
    );
    for (run, threads) in [8, 4, 8, 2, 8].into_iter().enumerate() {
        let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
        assert!(
            parallel == serial,
            "run {run} on {threads} threads: archive bytes differ: {:?}",
            roads_in(&read_all_tiles(&parallel))
        );
    }
}

/// A motorway with a bridge on its middle 20%-50%: at every zoom the road
/// is drawn, and at z12 it is split into bridge and non-bridge pieces.
#[test]
fn partially_bridged_overture_road_is_split_in_the_archive() {
    let roads = build(&[Segment {
        id: "road",
        subtype: "road",
        class: "motorway",
        line: [(-0.2, 51.5), (0.2, 51.5)],
        flags: vec![("is_bridge", Some((0.2, 0.5)))],
    }]);

    let z12: Vec<_> = roads.iter().filter(|r| r.zoom == 12).collect();
    assert!(z12.iter().all(|r| r.kind == "highway"), "{z12:?}");
    assert!(z12.iter().any(|r| r.bridge), "no bridge piece: {z12:?}");
    assert!(
        z12.iter().any(|r| !r.bridge),
        "whole road marked bridge: {z12:?}"
    );
    // Motorways start at z3.
    assert!(roads.iter().any(|r| r.zoom == 3 && r.kind == "highway"));
    assert!(!roads.iter().any(|r| r.zoom < 3));
}

/// Standard-gauge rail reaches the archive as `kind = rail` from z11, with a
/// whole-segment bridge flag, and never as a road class.
#[test]
fn overture_rail_is_rail_in_the_archive() {
    let roads = build(&[Segment {
        id: "rail",
        subtype: "rail",
        class: "standard_gauge",
        line: [(-0.2, 51.45), (0.2, 51.55)],
        flags: vec![("is_bridge", None)],
    }]);

    assert!(!roads.is_empty());
    assert!(
        roads.iter().all(|r| r.kind == "rail" && r.zoom >= 11),
        "{roads:?}"
    );
    assert!(
        roads
            .iter()
            .all(|r| r.detail.as_deref() == Some("standard_gauge") && r.bridge),
        "{roads:?}"
    );
    assert!(roads.iter().any(|r| r.zoom == 11));
}

/// Build the London fixture from several Overture Parquet files on a rayon
/// pool of `threads` threads and return the raw `PMTiles` bytes.
fn build_archive(files: &[Vec<Segment>], threads: usize) -> Vec<u8> {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    for (i, rows) in files.iter().enumerate() {
        write_segment_file(
            &root.join("overture"),
            &format!("part-{i:05}.parquet"),
            rows,
        );
    }
    rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
    write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
    write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
    let out = root.join("out.pmtiles");

    let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
    let args = vec![
        "geolith".to_string(),
        "--data".into(),
        arg("overture"),
        "--natural-earth".into(),
        arg("ne.sqlite"),
        "--land-polygons".into(),
        arg("land"),
        "--water-polygons".into(),
        arg("water"),
        "--output".into(),
        out.to_string_lossy().into_owned(),
        "--tmpdir".into(),
        arg("tmp"),
        "--roads-source".into(),
        "overture".into(),
        "--no-conflate".into(),
        "--bbox".into(),
        "-0.3,51.4,0.3,51.6".into(),
        "--max-zoom".into(),
        "10".into(),
    ];
    let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
    rayon::ThreadPoolBuilder::new()
        .num_threads(threads)
        .build()
        .expect("thread pool")
        .install(|| geolith_cli::run_with_config(&config))
        .expect("pipeline runs");
    std::fs::read(&out).expect("archive")
}

/// Motorways that share tiles, layer and sort rank but live in different
/// Parquet files, so their features tie on the sort key and reach the merge
/// from different chunks. The first file is much larger than the rest, so
/// on a parallel pool it finishes last while on one thread it finishes
/// first.
fn tied_motorway_files() -> Vec<Vec<Segment>> {
    let motorway = |file: usize, k: usize| {
        let y = 51.45 + 0.1 * (file * 64 + k) as f64 / 1024.0;
        Segment {
            id: Box::leak(format!("motorway-{file}-{k}").into_boxed_str()),
            subtype: "road",
            class: "motorway",
            line: [(-0.25, y), (0.25, y + 0.001)],
            flags: Vec::new(),
        }
    };
    (0..8)
        .map(|file| {
            let rows = if file == 0 { 2_000 } else { 1 };
            (0..rows).map(|k| motorway(file, k)).collect()
        })
        .collect()
}

/// The same input gives the same archive bytes on every run and on any
/// number of threads: feature order inside a tile must not depend on which
/// worker finished first.
#[test]
fn tile_archive_is_byte_identical_across_runs_and_thread_counts() {
    let files = tied_motorway_files();
    let serial = build_archive(&files, 1);
    let tiles = read_all_tiles(&serial);
    assert!(
        !roads_in(&tiles).is_empty(),
        "fixture produced no roads to order"
    );
    for (run, threads) in [4, 8, 4, 8].into_iter().enumerate() {
        let parallel = build_archive(&files, threads);
        let other = read_all_tiles(&parallel);
        let differing = tiles
            .iter()
            .filter(|(id, bytes)| other.get(id) != Some(bytes))
            .count();
        assert_eq!(
            differing,
            0,
            "run {run} on {threads} threads: {differing} of {} tiles differ",
            tiles.len()
        );
        assert!(
            parallel == serial,
            "run {run} on {threads} threads: archive bytes differ"
        );
    }
}