geolith-search-builder 0.3.2

Builds geocoding indexes from Overture Maps and OpenStreetMap: Postgres COPY files, Photon and Pelias bulk files, and the search part of a .glx file
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
//! OSM-against-Overture dedup with bounded memory.
//!
//! An OSM venue or address is dropped when Overture has one of the same
//! layer within 50 m under a similar name ([`OvertureIndex::is_duplicate`]).
//! Holding every Overture venue and address in memory for that check needs
//! about 380 bytes each: some 211 GB for the 555 million of the planet. So
//! both sides go to disk instead, split into buckets by place, and each
//! bucket is checked on its own:
//!
//! 1. [`OvertureSpill`]: each Overture venue or address is written to the
//!    bucket of every H3 resolution-4 cell that holds one of the seven
//!    resolution-8 cells around it. The dedup looks only at those seven
//!    cells, so a bucket holds every Overture record its OSM records can
//!    match: the result is exactly the in-memory one.
//! 2. [`OsmSpill`]: each OSM venue or address is written to the bucket of
//!    its own resolution-4 cell.
//! 3. [`OsmSpill::finish`]: one bucket at a time, the Overture records are
//!    indexed by place, and the OSM records are checked against them in
//!    parallel batches and passed on in their order.
//!
//! Memory is one bucket's Overture records: about 1/1024 of the total.

use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};

use h3o::{CellIndex, LatLng, Resolution};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

use crate::osm::{OvertureIndex, OvertureIndexBuilder};
use crate::record::{AddressFields, GeocodingLayer, GeocodingRecord};
use geolith::admin::AdminHierarchy;
use geolith::conflation::spatial::{SpatialCandidate, SpatialDedupConfig};
use geolith::source::input::{DataSource, OsmElementType};

/// The coarse cells that split records into buckets (about 1,770 km²).
const BUCKET_RESOLUTION: Resolution = Resolution::Four;
/// The most buckets: the files of one side are open at the same time.
const MAX_BUCKETS: usize = 1024;
/// The fewest buckets, whatever the open-file limit.
const MIN_BUCKETS: usize = 16;
/// Open files kept free for everything else (the PBF, the output, logs).
const RESERVED_FILES: u64 = 64;
/// Write buffer of each bucket file.
const BUCKET_BUFFER: usize = 32 * 1024;
/// OSM records checked against a bucket's Overture records per parallel
/// batch.
const CHECK_BATCH: usize = 8 * 1024;

/// Whether OSM records of this layer are checked against Overture.
#[must_use]
pub const fn is_deduped(layer: GeocodingLayer) -> bool {
    matches!(layer, GeocodingLayer::Venue | GeocodingLayer::Address)
}

/// How many buckets to use: `MAX_BUCKETS`, or fewer when the process may
/// not open that many files. Raises the soft open-file limit first.
#[must_use]
pub fn bucket_count() -> usize {
    let files = raise_open_file_limit(MAX_BUCKETS as u64 + RESERVED_FILES);
    let usable = usize::try_from(files.saturating_sub(RESERVED_FILES)).unwrap_or(MAX_BUCKETS);
    usable.clamp(MIN_BUCKETS, MAX_BUCKETS)
}

/// Raise the soft open-file limit towards `want` (never above the hard
/// limit) and return the limit now in force.
#[cfg(unix)]
#[allow(
    unsafe_code,
    reason = "libc getrlimit and setrlimit on local structs; each unsafe block has a SAFETY comment"
)]
fn raise_open_file_limit(want: u64) -> u64 {
    let mut limit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    // SAFETY: `limit` is a valid, writable rlimit for the call to fill.
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } != 0 {
        return 256;
    }
    let want = want.min(limit.rlim_max);
    if limit.rlim_cur < want {
        let raised = libc::rlimit {
            rlim_cur: want,
            rlim_max: limit.rlim_max,
        };
        // SAFETY: `raised` is a valid rlimit no higher than the hard limit.
        if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const raised) } == 0 {
            return want;
        }
    }
    limit.rlim_cur
}

#[cfg(not(unix))]
fn raise_open_file_limit(_want: u64) -> u64 {
    512
}

/// The H3 cell the dedup index files a point under (as `SpatialDedup`
/// does: invalid coordinates fall back to the origin).
fn dedup_cell(lon: f64, lat: f64) -> CellIndex {
    let resolution = Resolution::try_from(SpatialDedupConfig::default().h3_resolution)
        .unwrap_or(Resolution::Eight);
    let origin = || LatLng::new(0.0, 0.0).map(|p| p.to_cell(resolution));
    LatLng::new(lat, lon)
        .map(|p| p.to_cell(resolution))
        .or_else(|_| origin())
        .unwrap_or_else(|_| unreachable!("the origin is a valid point"))
}

/// The bucket of a resolution-4 cell, spread by a multiplicative hash.
fn bucket_of(cell: CellIndex, buckets: usize) -> usize {
    let coarse = cell.parent(BUCKET_RESOLUTION).unwrap_or(cell);
    let spread = u64::from(coarse).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32;
    usize::try_from(spread).unwrap_or(0) % buckets
}

/// The bucket an OSM record at this point goes to.
fn osm_bucket(lon: f64, lat: f64, buckets: usize) -> usize {
    bucket_of(dedup_cell(lon, lat), buckets)
}

/// Every bucket an Overture record at this point goes to: those of the
/// seven cells the dedup looks at, without repeats.
fn overture_buckets(lon: f64, lat: f64, buckets: usize) -> Vec<usize> {
    let mut out: Vec<usize> = dedup_cell(lon, lat)
        .grid_disk::<Vec<_>>(1)
        .into_iter()
        .map(|cell| bucket_of(cell, buckets))
        .collect();
    out.sort_unstable();
    out.dedup();
    out
}

/// An Overture venue or address as the dedup sees it.
#[derive(Serialize, Deserialize)]
struct OvertureKey {
    venue: bool,
    id: u64,
    lon: f64,
    lat: f64,
    name: String,
}

/// An OSM record on disk: every field of [`GeocodingRecord`], with the
/// source as its element type (parent relations are not kept; no output
/// reads them) and the addendum as JSON text (`postcard` cannot read a
/// `serde_json::Value` back).
#[derive(Serialize, Deserialize)]
struct OsmRow {
    id: u64,
    element_type: OsmElementType,
    layer: GeocodingLayer,
    name: String,
    search_text: String,
    lon: f64,
    lat: f64,
    country_code: Option<String>,
    admin: AdminHierarchy,
    address: Option<AddressFields>,
    names: HashMap<String, String>,
    other_names: Vec<String>,
    article_names: Vec<String>,
    importance: f32,
    source_id: Option<String>,
    categories: Vec<String>,
    addendum: Vec<(String, String)>,
    shape: Vec<u8>,
}

impl OsmRow {
    fn new(record: &GeocodingRecord) -> io::Result<Self> {
        let DataSource::Osm { element_type, .. } = record.source else {
            return Err(io::Error::other("an OSM spill only takes OSM records"));
        };
        let addendum = record
            .addendum
            .iter()
            .map(|(k, v)| Ok((k.clone(), serde_json::to_string(v)?)))
            .collect::<io::Result<_>>()?;
        Ok(Self {
            id: record.id,
            element_type,
            layer: record.layer,
            name: record.name.clone(),
            search_text: record.search_text.clone(),
            lon: record.lon,
            lat: record.lat,
            country_code: record.country_code.clone(),
            admin: record.admin.clone(),
            address: record.address.clone(),
            names: record.names.clone(),
            other_names: record.other_names.clone(),
            article_names: record.article_names.clone(),
            importance: record.importance,
            source_id: record.source_id.clone(),
            categories: record.categories.clone(),
            addendum,
            shape: record.shape.clone(),
        })
    }

    fn into_record(self) -> io::Result<GeocodingRecord> {
        let addendum = self
            .addendum
            .into_iter()
            .map(|(k, v)| Ok((k, serde_json::from_str(&v)?)))
            .collect::<io::Result<_>>()?;
        Ok(GeocodingRecord {
            id: self.id,
            source: DataSource::Osm {
                element_type: self.element_type,
                relations: Vec::new(),
            },
            layer: self.layer,
            name: self.name,
            search_text: self.search_text,
            lon: self.lon,
            lat: self.lat,
            country_code: self.country_code,
            admin: self.admin,
            address: self.address,
            names: self.names,
            other_names: self.other_names,
            article_names: self.article_names,
            importance: self.importance,
            source_id: self.source_id,
            categories: self.categories,
            addendum,
            shape: self.shape,
        })
    }
}

/// Append one length-prefixed `postcard` value.
fn put<T: Serialize>(
    out: &mut BufWriter<File>,
    value: &T,
    scratch: &mut Vec<u8>,
) -> io::Result<()> {
    scratch.clear();
    let bytes = postcard::to_extend(value, std::mem::take(scratch)).map_err(io::Error::other)?;
    let len = u32::try_from(bytes.len()).map_err(io::Error::other)?;
    out.write_all(&len.to_le_bytes())?;
    out.write_all(&bytes)?;
    *scratch = bytes;
    Ok(())
}

/// Read every length-prefixed value of a file, in order.
fn each(path: &Path, mut f: impl FnMut(&[u8]) -> io::Result<()>) -> io::Result<()> {
    let mut input = BufReader::new(File::open(path)?);
    let mut len = [0_u8; 4];
    let mut bytes = Vec::new();
    loop {
        match input.read_exact(&mut len) {
            Ok(()) => {}
            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(()),
            Err(e) => return Err(e),
        }
        bytes.resize(u32::from_le_bytes(len) as usize, 0);
        input.read_exact(&mut bytes)?;
        f(&bytes)?;
    }
}

/// OSM records held on disk until the end of the OSM pass, in the order
/// they were added: settlements whose outline comes from a boundary
/// relation, which the PBF stores after the nodes.
pub struct RecordSpill {
    path: PathBuf,
    out: BufWriter<File>,
    scratch: Vec<u8>,
    added: u64,
}

impl RecordSpill {
    /// A spill file in `dir`.
    ///
    /// # Errors
    /// When the file cannot be created.
    pub fn new(dir: &Path) -> io::Result<Self> {
        let path = dir.join("osm-deferred.bin");
        Ok(Self {
            out: BufWriter::new(File::create(&path)?),
            path,
            scratch: Vec::new(),
            added: 0,
        })
    }

    /// Adds an OSM record.
    ///
    /// # Errors
    /// When it is not an OSM record or cannot be written.
    pub fn add(&mut self, record: &GeocodingRecord) -> io::Result<()> {
        put(&mut self.out, &OsmRow::new(record)?, &mut self.scratch)?;
        self.added += 1;
        Ok(())
    }

    /// Passes every record to `f` in the order added, then removes the file.
    ///
    /// # Errors
    /// When the file cannot be read or `f` fails.
    pub fn drain(self, mut f: impl FnMut(GeocodingRecord) -> io::Result<()>) -> io::Result<()> {
        let Self { path, out, .. } = self;
        out.into_inner()
            .map_err(io::IntoInnerError::into_error)?
            .sync_all()?;
        each(&path, |bytes| f(decode::<OsmRow>(bytes)?.into_record()?))?;
        std::fs::remove_file(&path)
    }
}

/// One `postcard` value.
fn decode<T: for<'de> Deserialize<'de>>(bytes: &[u8]) -> io::Result<T> {
    postcard::from_bytes(bytes).map_err(io::Error::other)
}

/// Check a batch of OSM records against `index` in parallel, then pass the
/// ones Overture does not repeat to `keep`, in their order.
fn check(
    index: &OvertureIndex,
    batch: &mut Vec<Vec<u8>>,
    stats: &mut DedupStats,
    keep: &mut impl FnMut(GeocodingRecord) -> io::Result<()>,
) -> io::Result<()> {
    let checked: Vec<io::Result<Option<GeocodingRecord>>> = batch
        .par_drain(..)
        .map(|bytes| {
            let record = decode::<OsmRow>(&bytes)?.into_record()?;
            Ok((!index.is_duplicate(&record)).then_some(record))
        })
        .collect();
    for record in checked {
        match record? {
            Some(record) => {
                stats.kept += 1;
                keep(record)?;
            }
            None => stats.duplicates += 1,
        }
    }
    Ok(())
}

/// One bucket file per bucket, all open.
fn create_buckets(dir: &Path, side: &str, buckets: usize) -> io::Result<Vec<BufWriter<File>>> {
    (0..buckets)
        .map(|i| {
            let file = File::create(dir.join(format!("{side}-{i:04}")))?;
            Ok(BufWriter::with_capacity(BUCKET_BUFFER, file))
        })
        .collect()
}

/// Flush and close bucket files.
fn close(files: Vec<BufWriter<File>>) -> io::Result<()> {
    for file in files {
        file.into_inner().map_err(io::IntoInnerError::into_error)?;
    }
    Ok(())
}

/// The bucket directory; removed when dropped.
struct Dir(PathBuf);

impl Drop for Dir {
    fn drop(&mut self) {
        if let Err(e) = std::fs::remove_dir_all(&self.0) {
            tracing::warn!(path = %self.0.display(), error = %e, "could not remove dedup buckets");
        }
    }
}

/// Step 1: collects the Overture venues and addresses.
pub struct OvertureSpill {
    dir: Dir,
    buckets: usize,
    files: Vec<BufWriter<File>>,
    scratch: Vec<u8>,
    added: u64,
}

impl OvertureSpill {
    /// Buckets in a new directory `geolith-dedup-<pid>` under `tmp`.
    ///
    /// # Errors
    /// When the directory or a bucket file cannot be created.
    pub fn new(tmp: &Path, buckets: usize) -> io::Result<Self> {
        let path = tmp.join(format!("geolith-dedup-{}", std::process::id()));
        std::fs::create_dir_all(&path)?;
        let dir = Dir(path);
        let files = create_buckets(&dir.0, "overture", buckets)?;
        Ok(Self {
            dir,
            buckets,
            files,
            scratch: Vec::with_capacity(256),
            added: 0,
        })
    }

    /// Keep an Overture record for the dedup; layers other than venues and
    /// addresses are ignored.
    ///
    /// # Errors
    /// When a bucket file cannot be written.
    pub fn add(&mut self, record: &GeocodingRecord) -> io::Result<()> {
        if !is_deduped(record.layer) {
            return Ok(());
        }
        let key = OvertureKey {
            venue: record.layer == GeocodingLayer::Venue,
            id: record.id,
            lon: record.lon,
            lat: record.lat,
            name: record.name.clone(),
        };
        for bucket in overture_buckets(record.lon, record.lat, self.buckets) {
            put(&mut self.files[bucket], &key, &mut self.scratch)?;
        }
        self.added += 1;
        Ok(())
    }

    /// Close the Overture buckets and start collecting OSM records.
    ///
    /// # Errors
    /// When a bucket file cannot be flushed or created.
    pub fn into_osm(self) -> io::Result<OsmSpill> {
        let Self {
            dir,
            buckets,
            files,
            scratch,
            added,
        } = self;
        close(files)?;
        tracing::info!(overture = added, buckets, "overture dedup records on disk");
        let files = create_buckets(&dir.0, "osm", buckets)?;
        Ok(OsmSpill {
            dir,
            buckets,
            files,
            scratch,
            added: 0,
        })
    }
}

/// Step 2: collects the OSM venues and addresses.
pub struct OsmSpill {
    dir: Dir,
    buckets: usize,
    files: Vec<BufWriter<File>>,
    scratch: Vec<u8>,
    added: u64,
}

/// What [`OsmSpill::finish`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DedupStats {
    /// OSM records passed on.
    pub kept: u64,
    /// OSM records dropped as repeats of Overture ones.
    pub duplicates: u64,
}

impl OsmSpill {
    /// Keep an OSM venue or address for the dedup.
    ///
    /// # Errors
    /// When the record is not from OSM or a bucket file cannot be written.
    pub fn add(&mut self, record: &GeocodingRecord) -> io::Result<()> {
        let bucket = osm_bucket(record.lon, record.lat, self.buckets);
        put(
            &mut self.files[bucket],
            &OsmRow::new(record)?,
            &mut self.scratch,
        )?;
        self.added += 1;
        Ok(())
    }

    /// Check every OSM record against the Overture records of its bucket,
    /// pass the ones Overture does not repeat to `keep`, bucket by bucket,
    /// and remove the buckets.
    ///
    /// # Errors
    /// When a bucket file cannot be read, or `keep` fails.
    pub fn finish(
        self,
        mut keep: impl FnMut(GeocodingRecord) -> io::Result<()>,
    ) -> io::Result<DedupStats> {
        let Self {
            dir,
            buckets,
            files,
            added,
            ..
        } = self;
        close(files)?;
        tracing::info!(osm = added, buckets, "osm dedup records on disk");
        let mut stats = DedupStats {
            kept: 0,
            duplicates: 0,
        };
        let mut batch = Vec::with_capacity(CHECK_BATCH);
        for bucket in 0..buckets {
            let overture_path = dir.0.join(format!("overture-{bucket:04}"));
            let osm_path = dir.0.join(format!("osm-{bucket:04}"));
            let mut overture = OvertureIndexBuilder::default();
            each(&overture_path, |bytes| {
                let key: OvertureKey = decode(bytes)?;
                let layer = if key.venue {
                    GeocodingLayer::Venue
                } else {
                    GeocodingLayer::Address
                };
                overture.add_candidate(
                    layer,
                    SpatialCandidate {
                        id: key.id,
                        centroid_lon: key.lon,
                        centroid_lat: key.lat,
                        area_m2: None,
                        name: Some(key.name),
                    },
                );
                Ok(())
            })?;
            std::fs::remove_file(&overture_path)?;
            let index = overture.build();
            each(&osm_path, |bytes| {
                batch.push(bytes.to_vec());
                if batch.len() == CHECK_BATCH {
                    check(&index, &mut batch, &mut stats, &mut keep)?;
                }
                Ok(())
            })?;
            check(&index, &mut batch, &mut stats, &mut keep)?;
            std::fs::remove_file(&osm_path)?;
        }
        Ok(stats)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::record::RecordInit;
    use geolith::admin::AdminHierarchy;

    fn venue(name: &str, lon: f64, lat: f64, source: DataSource) -> GeocodingRecord {
        GeocodingRecord::new(RecordInit {
            id: 7,
            source,
            layer: GeocodingLayer::Venue,
            name: name.to_string(),
            lon,
            lat,
            admin: AdminHierarchy::default(),
            address: None,
            names: HashMap::new(),
            importance: 0.5,
        })
    }

    fn overture() -> DataSource {
        DataSource::Overture {
            theme: "places".into(),
            otype: "place".into(),
        }
    }

    fn osm() -> DataSource {
        DataSource::Osm {
            element_type: OsmElementType::Node,
            relations: Vec::new(),
        }
    }

    /// Run the two spill steps and return the kept OSM records.
    fn dedup(
        buckets: usize,
        overture: &[GeocodingRecord],
        osm: &[GeocodingRecord],
    ) -> (Vec<GeocodingRecord>, DedupStats) {
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut spill = OvertureSpill::new(tmp.path(), buckets).expect("spill");
        for record in overture {
            spill.add(record).expect("add overture");
        }
        let mut spill = spill.into_osm().expect("osm side");
        for record in osm {
            spill.add(record).expect("add osm");
        }
        let mut kept = Vec::new();
        let stats = spill
            .finish(|record| {
                kept.push(record);
                Ok(())
            })
            .expect("finish");
        assert_eq!(
            std::fs::read_dir(tmp.path()).expect("tmp").count(),
            0,
            "the buckets are removed"
        );
        (kept, stats)
    }

    /// Two points 20 m apart on a meridian whose OSM buckets differ: the
    /// resolution-8 cells sit in different resolution-4 cells that hash to
    /// different buckets. Found by walking north in 10 m steps.
    fn across_a_border(buckets: usize) -> ((f64, f64), (f64, f64)) {
        const M_PER_DEG: f64 = 111_194.926;
        let lon = 73.85;
        let mut lat = 18.5;
        loop {
            let next = lat + 20.0 / M_PER_DEG;
            if osm_bucket(lon, lat, buckets) != osm_bucket(lon, next, buckets) {
                return ((lon, lat), (lon, next));
            }
            lat += 10.0 / M_PER_DEG;
        }
    }

    #[test]
    fn a_repeat_across_a_bucket_border_is_still_dropped() {
        let buckets = 64;
        let ((lon_a, lat_a), (lon_b, lat_b)) = across_a_border(buckets);
        let (kept, stats) = dedup(
            buckets,
            &[venue("Cafe Coffee Day", lon_a, lat_a, overture())],
            &[
                venue("cafe coffee day", lon_b, lat_b, osm()),
                venue("Haldiram", lon_b, lat_b, osm()),
            ],
        );
        assert_eq!(
            stats,
            DedupStats {
                kept: 1,
                duplicates: 1
            }
        );
        assert_eq!(kept[0].name, "Haldiram");
    }

    #[test]
    fn a_far_or_other_layer_overture_record_keeps_the_osm_one() {
        // 200 m north: past the 50 m limit.
        let far = 18.5 + 200.0 / 111_194.926;
        let mut address = venue("Cafe Coffee Day", 73.85, 18.5, overture());
        address.layer = GeocodingLayer::Address;
        let (kept, stats) = dedup(
            16,
            &[venue("Cafe Coffee Day", 73.85, far, overture()), address],
            &[venue("Cafe Coffee Day", 73.85, 18.5, osm())],
        );
        assert_eq!(stats.duplicates, 0);
        assert_eq!(kept.len(), 1);
    }

    #[test]
    fn a_record_comes_back_with_every_field() {
        let mut record = GeocodingRecord::new(RecordInit {
            id: (1 << 62) | 42,
            source: DataSource::Osm {
                element_type: OsmElementType::Way,
                relations: Vec::new(),
            },
            layer: GeocodingLayer::Address,
            name: "7 MG Road".into(),
            lon: 73.856_743,
            lat: 18.519_574,
            admin: AdminHierarchy {
                country_code: Some("IN".into()),
                country: Some("India".into()),
                region: Some("Maharashtra".into()),
                county: Some("Pune".into()),
                locality: None,
                neighbourhood: Some("Camp".into()),
                borough: None,
                postcode: None,
                city: None,
            },
            address: Some(AddressFields {
                number: Some("7".into()),
                street: Some("MG Road".into()),
                unit: Some("2B".into()),
                postcode: Some("411001".into()),
                city: None,
            }),
            names: HashMap::from([("mr".to_string(), "ą„­ ą¤ą¤®ą¤œą„€ ą¤°ą„‹ą¤”".to_string())]),
            importance: 0.3,
        })
        .with_source_id("way/42")
        .with_categories(vec!["shop".into()]);
        record
            .addendum
            .insert("osm".into(), serde_json::json!({ "wheelchair": "yes" }));
        record.other_names = vec!["Old MG Road".into()];
        record.article_names = vec!["Mahatma Gandhi Road".into()];

        let (kept, _) = dedup(16, &[], std::slice::from_ref(&record));
        let back = &kept[0];
        assert_eq!(back.id, (1 << 62) | 42);
        assert!(matches!(
            back.source,
            DataSource::Osm {
                element_type: OsmElementType::Way,
                ..
            }
        ));
        assert_eq!(back.layer, GeocodingLayer::Address);
        assert_eq!(back.name, "7 MG Road");
        assert_eq!(back.search_text, record.search_text);
        assert_eq!((back.lon, back.lat), (73.856_743, 18.519_574));
        assert_eq!(back.country_code.as_deref(), Some("IN"));
        assert_eq!(back.admin, record.admin);
        assert_eq!(back.address, record.address);
        assert_eq!(back.names.get("mr").map(String::as_str), Some("ą„­ ą¤ą¤®ą¤œą„€ ą¤°ą„‹ą¤”"));
        assert_eq!(back.importance, 0.3);
        assert_eq!(back.source_id.as_deref(), Some("way/42"));
        assert_eq!(back.categories, ["shop"]);
        assert_eq!(back.addendum["osm"]["wheelchair"], "yes");
        assert_eq!(back.other_names, ["Old MG Road"]);
        assert_eq!(back.article_names, ["Mahatma Gandhi Road"]);
    }

    #[test]
    fn a_bucket_of_several_batches_keeps_every_record_in_order() {
        // Every record at one place, so in one bucket; record `repeat`, in
        // the second batch, repeats the Overture venue.
        let n = 2 * CHECK_BATCH + 7;
        let repeat = CHECK_BATCH + 3;
        let rows: Vec<GeocodingRecord> = (0..n)
            .map(|i| {
                let name = if i == repeat {
                    "zebra crossing cafe".to_string()
                } else {
                    format!("osm {i}")
                };
                venue(&name, 73.85, 18.5, osm())
            })
            .collect();
        let (kept, stats) = dedup(
            16,
            &[venue("Zebra Crossing Cafe", 73.85, 18.5, overture())],
            &rows,
        );
        assert_eq!(
            stats,
            DedupStats {
                kept: u64::try_from(n - 1).expect("fits"),
                duplicates: 1
            }
        );
        let names: Vec<&str> = kept.iter().map(|r| r.name.as_str()).collect();
        let expected: Vec<String> = (0..n)
            .filter(|&i| i != repeat)
            .map(|i| format!("osm {i}"))
            .collect();
        assert_eq!(names, expected);
    }

    #[test]
    fn a_broken_bucket_or_writer_fails_the_dedup() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut scratch = Vec::new();
        let place = venue("Cafe", 73.85, 18.5, osm());
        let bucket = osm_bucket(place.lon, place.lat, 16);
        let mut kept = Vec::new();
        let mut keep = |record: GeocodingRecord| -> io::Result<()> {
            kept.push(record.name);
            Ok(())
        };

        // A frame that is no Overture key.
        let mut spill = OvertureSpill::new(tmp.path(), 16).expect("spill");
        put(&mut spill.files[bucket], &1_u8, &mut scratch).expect("put");
        let spill = spill.into_osm().expect("osm side");
        spill
            .finish(&mut keep)
            .expect_err("a broken Overture bucket");

        // A good OSM record, then a frame that is no OSM record: the good
        // record is passed on, then the dedup fails.
        let mut spill = OvertureSpill::new(tmp.path(), 16)
            .expect("spill")
            .into_osm()
            .expect("osm side");
        spill.add(&place).expect("add");
        put(&mut spill.files[bucket], &1_u8, &mut scratch).expect("put");
        spill.finish(&mut keep).expect_err("a broken OSM bucket");

        // An OSM record whose addendum is not JSON.
        let mut spill = OvertureSpill::new(tmp.path(), 16)
            .expect("spill")
            .into_osm()
            .expect("osm side");
        let mut row = OsmRow::new(&place).expect("row");
        row.addendum = vec![("osm".into(), "{".into())];
        put(&mut spill.files[bucket], &row, &mut scratch).expect("put");
        spill.finish(&mut keep).expect_err("a broken addendum");
        assert_eq!(kept, ["Cafe"]);

        // A writer that fails on the first full batch.
        let mut spill = OvertureSpill::new(tmp.path(), 16)
            .expect("spill")
            .into_osm()
            .expect("osm side");
        for _ in 0..CHECK_BATCH {
            spill.add(&place).expect("add");
        }
        let err = spill
            .finish(|_| Err(io::Error::other("disk full")))
            .expect_err("a failing writer");
        assert_eq!(err.to_string(), "disk full");
    }

    #[test]
    fn an_overture_record_is_never_spilled_as_osm() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut spill = OvertureSpill::new(tmp.path(), 16)
            .expect("spill")
            .into_osm()
            .expect("osm side");
        assert!(spill.add(&venue("x", 0.0, 0.0, overture())).is_err());
    }

    #[test]
    fn bucket_count_stays_in_range() {
        let n = bucket_count();
        assert!((MIN_BUCKETS..=MAX_BUCKETS).contains(&n), "{n}");
    }
}