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
//! `.glx` writer: a single-file geocoding index (see the `geolith-glx` crate).
//!
//! The `glx` writer numbers documents in the order they are added, and that
//! order decides how well a reader can skip blocks: venues should come by
//! falling importance, then addresses by rising word count, each grouped by
//! place. Records arrive in source order, so this writer sorts them first,
//! in bounded memory: rows collect until a byte budget, go to disk as a
//! sorted LZ4 run, and the runs are merged when the file is finished.
//!
//! Field values match the `pg-copy` output as Postgres stores it (signed
//! 64-bit ids, coordinates to 7 decimals, importance to 4), so a file built
//! here answers like one built from the loaded table by `glx-build`.

use std::cmp::{Ordering, Reverse};
use std::collections::BinaryHeap;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};

use rayon::iter::ParallelIterator;
use rayon::prelude::ParallelDrainRange;
use rayon::slice::ParallelSliceMut;
use serde::{Deserialize, Serialize};

use crate::record::GeocodingRecord;

/// Importance weight in the rank; the geolith search API's default
/// `IMPORTANCE_WEIGHT`.
pub const IMPORTANCE_WEIGHT: f32 = 10.0;

/// Rows prepared together on every core when the index is written.
const PREPARE_BATCH: usize = 1 << 16;

/// Default memory for buffered rows before a sorted run goes to disk.
pub const DEFAULT_SORT_BYTES: usize = 1 << 30;

/// One document, in the shape the `glx` crate stores it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Row {
    id: i64,
    name: String,
    lon: f64,
    lat: f64,
    layer: String,
    country_code: String,
    country: String,
    region: String,
    county: String,
    locality: String,
    street: String,
    postcode: String,
    housenumber: String,
    source_id: String,
    search_text: String,
    name_text: String,
    importance: f32,
    /// The encoded shape, empty for none.
    shape: Vec<u8>,
    neighbourhood: String,
    borough: String,
    category: String,
    /// Names by language, in the glx `Record::languages` form.
    languages: String,
    /// The box of the shape.
    bbox: Option<[f64; 4]>,
}

/// A record's names by language (OSM `name:<code>`, codes only), sorted by
/// code, in the glx `Record::languages` form.
fn languages_column(record: &GeocodingRecord) -> String {
    let mut names: Vec<(&String, &String)> = record
        .names
        .iter()
        .filter(|(code, name)| crate::record::is_language_code(code) && !name.trim().is_empty())
        .collect();
    names.sort_unstable_by(|a, b| a.0.cmp(b.0));
    let mut out = String::new();
    for (code, name) in names {
        if !out.is_empty() {
            out.push(glx::format::LANGUAGE_ENTRY_SEP);
        }
        out.push_str(code);
        out.push(glx::format::LANGUAGE_SEP);
        out.push_str(&name.trim().replace(
            [glx::format::LANGUAGE_SEP, glx::format::LANGUAGE_ENTRY_SEP],
            " ",
        ));
    }
    out
}

/// Text as a Postgres `TEXT` column keeps it: no NUL characters.
fn pg_text(value: Option<&str>) -> String {
    value.map(|s| s.replace('\0', "")).unwrap_or_default()
}

/// A float as Postgres parses it from the COPY text.
fn rounded<T: std::str::FromStr + Default>(text: &str) -> T {
    text.parse().unwrap_or_default()
}

impl Row {
    fn from_record(record: &GeocodingRecord) -> Self {
        let address = record.address.as_ref();
        Self {
            id: crate::output::pg_copy::pg_bigint_id(record.id),
            name: pg_text(Some(&record.name)),
            lon: rounded(&format!("{:.7}", record.lon)),
            lat: rounded(&format!("{:.7}", record.lat)),
            layer: record.layer.as_str().to_owned(),
            country_code: pg_text(record.country_code.as_deref()),
            country: pg_text(record.admin.country.as_deref()),
            region: pg_text(record.admin.region.as_deref()),
            county: pg_text(record.admin.county.as_deref()),
            locality: pg_text(record.admin.locality.as_deref()),
            street: pg_text(address.and_then(|a| a.street.as_deref())),
            postcode: pg_text(
                address
                    .and_then(|a| a.postcode.as_deref())
                    .or(record.admin.postcode.as_deref()),
            ),
            housenumber: pg_text(address.and_then(|a| a.number.as_deref())),
            source_id: pg_text(record.source_id.as_deref()),
            search_text: pg_text(Some(&record.search_text)),
            name_text: pg_text(Some(&record.name_text())),
            importance: rounded(&format!("{:.4}", record.importance)),
            shape: record.shape.clone(),
            neighbourhood: pg_text(record.admin.neighbourhood.as_deref()),
            borough: pg_text(record.admin.borough.as_deref()),
            category: pg_text(record.category_words().as_deref()),
            languages: languages_column(record),
            bbox: (!record.shape.is_empty())
                .then(|| glx::format::decode_shape(&record.shape))
                .flatten()
                .and_then(|polygons| glx::format::shape_bbox(&polygons)),
        }
    }

    /// Bytes this row holds in memory, roughly.
    const fn size(&self) -> usize {
        std::mem::size_of::<Self>()
            + self.name.len()
            + self.layer.len()
            + self.country_code.len()
            + self.country.len()
            + self.region.len()
            + self.county.len()
            + self.locality.len()
            + self.street.len()
            + self.postcode.len()
            + self.housenumber.len()
            + self.source_id.len()
            + self.search_text.len()
            + self.name_text.len()
            + self.shape.len()
            + self.neighbourhood.len()
            + self.borough.len()
            + self.category.len()
            + self.languages.len()
    }

    /// Venues sort by falling importance band; addresses all share band 0.
    fn band(&self) -> i64 {
        if self.layer == "address" {
            0
        } else {
            // Postgres widens the REAL to double before `floor`.
            let band = (f64::from(self.importance) * 20.0).floor() as i64;
            -band
        }
    }

    fn into_doc(self) -> glx::write::Doc {
        glx::write::Doc {
            importance: self.importance,
            record: glx::format::Record {
                id: self.id,
                lon: self.lon,
                lat: self.lat,
                name: self.name,
                layer: self.layer,
                country_code: self.country_code,
                country: self.country,
                region: self.region,
                county: self.county,
                locality: self.locality,
                street: self.street,
                postcode: self.postcode,
                housenumber: self.housenumber,
                source_id: self.source_id,
                search_text: self.search_text,
                name_text: self.name_text,
                importance: self.importance,
                neighbourhood: self.neighbourhood,
                borough: self.borough,
                category: self.category,
                languages: self.languages,
                bbox: self.bbox,
            },
            shape: self.shape,
        }
    }
}

/// Document order: venues and places before addresses; venues by falling
/// importance band (twentieths); then by word count; then grouped by place.
#[cfg(test)]
fn order(a: &Row, b: &Row) -> Ordering {
    Keyed::new(a.clone()).cmp(&Keyed::new(b.clone()))
}

/// The order's tie-break after the key: grouped by place, then by id.
fn by_place(a: &Row, b: &Row) -> Ordering {
    a.region
        .cmp(&b.region)
        .then_with(|| a.county.cmp(&b.county))
        .then_with(|| a.locality.cmp(&b.locality))
        .then_with(|| a.street.cmp(&b.street))
        .then_with(|| a.name.cmp(&b.name))
        .then_with(|| a.id.cmp(&b.id))
}

/// A row with the leading part of its document order worked out once: a
/// sort compares each row about log2(n) times, and counting the words of
/// its text each time took most of the write step on a planet.
struct Keyed {
    address: bool,
    band: i64,
    pieces: usize,
    row: Row,
}

impl Keyed {
    fn new(row: Row) -> Self {
        Self {
            address: row.layer == "address",
            band: row.band(),
            pieces: pieces(scored(&row.search_text)),
            row,
        }
    }

    fn cmp(&self, other: &Self) -> Ordering {
        self.address
            .cmp(&other.address)
            .then(self.band.cmp(&other.band))
            .then(self.pieces.cmp(&other.pieces))
            .then_with(|| by_place(&self.row, &other.row))
    }
}

/// The part of `search_text` BM25 scores the length of: names in other
/// languages after the language mark do not count (see
/// `glx::tokenize::text_length`).
fn scored(text: &str) -> &str {
    text.split(glx::tokenize::LANGUAGE_MARK)
        .next()
        .unwrap_or("")
}

/// Number of pieces `search_text` splits into on runs of characters that
/// are not letters or digits (empty edge pieces count, as in Postgres
/// `regexp_split_to_array`).
fn pieces(text: &str) -> usize {
    #[cfg(test)]
    PIECES_CALLS.with(|c| c.set(c.get() + 1));
    let mut count = 1;
    let mut in_separator = false;
    for ch in text.chars() {
        let separator = !ch.is_alphanumeric();
        if separator && !in_separator {
            count += 1;
        }
        in_separator = separator;
    }
    count
}

#[cfg(test)]
thread_local! {
    /// Calls to [`pieces`] on this thread, for the work-count test.
    static PIECES_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Writes geocoding records as one `.glx` file.
pub struct GlxWriter<W: Write> {
    out: W,
    dir: PathBuf,
    sort_bytes: usize,
    buffer: Vec<Keyed>,
    buffer_bytes: usize,
    runs: Vec<PathBuf>,
    count: u64,
}

impl<W: Write> GlxWriter<W> {
    /// A writer that keeps its temporary files under `dir`.
    ///
    /// # Errors
    ///
    /// Returns an error if `dir` cannot be created.
    pub fn new(out: W, dir: &Path, sort_bytes: usize) -> io::Result<Self> {
        std::fs::create_dir_all(dir)?;
        Ok(Self {
            out,
            dir: dir.to_path_buf(),
            sort_bytes,
            buffer: Vec::new(),
            buffer_bytes: 0,
            runs: Vec::new(),
            count: 0,
        })
    }

    /// Adds one record.
    ///
    /// # Errors
    ///
    /// Returns an error if a sorted run cannot be written.
    pub fn write_record(&mut self, record: &GeocodingRecord) -> io::Result<()> {
        self.push(Row::from_record(record))
    }

    /// Records added so far.
    #[must_use]
    pub const fn count(&self) -> u64 {
        self.count
    }

    /// Sorted runs written to disk so far.
    #[must_use]
    pub const fn runs(&self) -> usize {
        self.runs.len()
    }

    /// Buffers one row; past the budget, the buffer goes to disk as a run.
    fn push(&mut self, row: Row) -> io::Result<()> {
        self.buffer_bytes += row.size();
        self.buffer.push(Keyed::new(row));
        self.count += 1;
        if self.buffer_bytes >= self.sort_bytes {
            self.spill()?;
        }
        Ok(())
    }

    /// Sorts the buffer and writes it to disk as one LZ4 run of
    /// length-prefixed postcard rows.
    fn spill(&mut self) -> io::Result<()> {
        self.buffer.par_sort_by(Keyed::cmp);
        let path = self.dir.join(format!("run-{:05}.lz4", self.runs.len()));
        let mut out = lz4_flex::frame::FrameEncoder::new(BufWriter::new(File::create(&path)?));
        for keyed in self.buffer.drain(..) {
            let bytes = postcard::to_allocvec(&keyed.row).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)?;
        }
        out.finish().map_err(io::Error::other)?.flush()?;
        self.buffer_bytes = 0;
        self.runs.push(path);
        Ok(())
    }

    /// Every row in document order: the buffer and the runs, merged.
    fn merged(&mut self) -> io::Result<Merge> {
        let mut sources = Vec::with_capacity(self.runs.len() + 1);
        for path in &self.runs {
            let file = BufReader::with_capacity(1 << 20, File::open(path)?);
            sources.push(Source::Run(lz4_flex::frame::FrameDecoder::new(file)));
        }
        let mut memory = std::mem::take(&mut self.buffer);
        memory.par_sort_by(Keyed::cmp);
        sources.push(Source::Memory(memory.into_iter()));
        let mut merge = Merge {
            heap: BinaryHeap::with_capacity(sources.len()),
            sources,
        };
        for source in 0..merge.sources.len() {
            merge.refill(source)?;
        }
        Ok(merge)
    }

    /// Merges the runs, indexes every document in order and writes the
    /// file; removes the temporary files.
    ///
    /// The runs go as soon as every row is in the index writer, before it
    /// writes the file: its own temporary files then have the runs' disk
    /// space (about 28 GB on a planet). The index writer flushes `out`.
    ///
    /// # Errors
    ///
    /// Returns an error if a run cannot be read or the file cannot be
    /// written.
    pub fn finish(mut self) -> io::Result<glx::write::Stats> {
        let index_dir = self.dir.join("index");
        let mut writer = glx::write::Writer::new(&index_dir)?;
        // Preparing a document (tokenizing its text) takes most of the time
        // and needs no writer: batches are prepared on every core, then
        // added in order, so the file is the same.
        let mut merged = self.merged()?;
        let mut batch: Vec<Row> = Vec::with_capacity(PREPARE_BATCH);
        loop {
            batch.clear();
            for row in merged.by_ref().take(PREPARE_BATCH) {
                batch.push(row?);
            }
            if batch.is_empty() {
                break;
            }
            let prepared: Vec<glx::write::Prepared> = batch
                .par_drain(..)
                .map(|row| glx::write::Prepared::new(&row.into_doc()))
                .collect();
            for p in prepared {
                writer.add_prepared(p)?;
            }
        }
        for run in &self.runs {
            std::fs::remove_file(run)?;
        }
        let stats = writer.finish(&mut self.out, IMPORTANCE_WEIGHT)?;
        if index_dir.exists() {
            std::fs::remove_dir_all(&index_dir)?;
        }
        Ok(stats)
    }
}

/// Merges sorted runs (and the in-memory remainder) into one ordered stream.
struct Merge {
    heap: BinaryHeap<Reverse<Head>>,
    sources: Vec<Source>,
}

/// A run's next row, ordered by document order, then by run number so the
/// merge is stable.
struct Head {
    row: Keyed,
    source: usize,
}

impl PartialEq for Head {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Head {}

impl PartialOrd for Head {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Head {
    fn cmp(&self, other: &Self) -> Ordering {
        self.row
            .cmp(&other.row)
            .then(self.source.cmp(&other.source))
    }
}

/// Where merged rows come from.
enum Source {
    Run(lz4_flex::frame::FrameDecoder<BufReader<File>>),
    Memory(std::vec::IntoIter<Keyed>),
}

impl Iterator for Merge {
    type Item = io::Result<Row>;

    fn next(&mut self) -> Option<Self::Item> {
        let Reverse(head) = self.heap.pop()?;
        match self.refill(head.source) {
            Ok(()) => Some(Ok(head.row.row)),
            Err(e) => Some(Err(e)),
        }
    }
}

impl Merge {
    /// Pushes the next row of `source`, if it has one.
    fn refill(&mut self, source: usize) -> io::Result<()> {
        let row = match &mut self.sources[source] {
            Source::Memory(rows) => rows.next(),
            Source::Run(reader) => read_row(reader)?.map(Keyed::new),
        };
        if let Some(row) = row {
            self.heap.push(Reverse(Head { row, source }));
        }
        Ok(())
    }
}

/// Reads one length-prefixed row; `None` at the end of the run.
fn read_row(reader: &mut impl Read) -> io::Result<Option<Row>> {
    let mut len = [0_u8; 4];
    match reader.read_exact(&mut len) {
        Ok(()) => {}
        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
        Err(e) => return Err(e),
    }
    let mut bytes = vec![0_u8; u32::from_le_bytes(len) as usize];
    reader.read_exact(&mut bytes)?;
    postcard::from_bytes(&bytes)
        .map(Some)
        .map_err(io::Error::other)
}

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

    fn row(layer: &str, importance: f32, text: &str, locality: &str, id: i64) -> Row {
        Row {
            id,
            name: text.to_owned(),
            lon: 0.0,
            lat: 0.0,
            layer: layer.to_owned(),
            country_code: String::new(),
            country: String::new(),
            region: String::new(),
            county: String::new(),
            locality: locality.to_owned(),
            street: String::new(),
            postcode: String::new(),
            housenumber: String::new(),
            source_id: String::new(),
            search_text: text.to_owned(),
            name_text: text.to_owned(),
            importance,
            shape: Vec::new(),
            neighbourhood: String::new(),
            borough: String::new(),
            category: String::new(),
            languages: String::new(),
            bbox: None,
        }
    }

    /// A record's languages column holds its `name:<code>` names sorted by
    /// code, and its bbox the box of its shape.
    #[test]
    fn a_row_carries_languages_neighbourhood_and_the_shape_box() {
        let mut record = GeocodingRecord::new(RecordInit {
            id: 1,
            source: geolith::source::input::DataSource::Overture {
                theme: "divisions".into(),
                otype: "division_area".into(),
            },
            layer: crate::record::GeocodingLayer::Region,
            name: "Maharashtra".into(),
            lon: 75.0,
            lat: 19.0,
            admin: geolith::admin::AdminHierarchy {
                neighbourhood: Some("Seawoods East".into()),
                borough: Some("Nerul".into()),
                ..Default::default()
            },
            address: None,
            names: std::collections::HashMap::from([
                ("mr".to_owned(), "महाराष्ट्र".to_owned()),
                ("hi".to_owned(), "महाराष्ट्र".to_owned()),
                ("name:etymology".to_owned(), "great nation".to_owned()),
            ]),
            importance: 0.5,
        });
        glx::format::encode_shape(
            &[vec![vec![
                [72.6, 15.6],
                [80.9, 15.6],
                [80.9, 22.0],
                [72.6, 15.6],
            ]]],
            &mut record.shape,
        );
        let row = Row::from_record(&record);
        assert_eq!(row.languages, "hi\u{1F}महाराष्ट्र\u{1E}mr\u{1F}महाराष्ट्र");
        assert_eq!(row.neighbourhood, "Seawoods East");
        assert_eq!(row.borough, "Nerul");
        assert_eq!(row.bbox, Some([72.6, 15.6, 80.9, 22.0]));
    }

    #[test]
    fn pieces_count_like_postgres_regexp_split() {
        assert_eq!(pieces("India Gate"), 2);
        assert_eq!(pieces("12, MG Road"), 3);
        // A leading separator leaves an empty first piece.
        assert_eq!(pieces(" Pune"), 2);
        assert_eq!(pieces("Pune"), 1);
        assert_eq!(pieces(""), 1);
    }

    #[test]
    fn venues_come_by_falling_importance_band_then_addresses_by_word_count() {
        let mut rows = [
            row("address", 0.0, "7 MG Road Pune", "Pune", 1),
            row("venue", 0.10, "Cafe", "Pune", 2),
            row("address", 0.0, "MG Road", "Pune", 3),
            row("locality", 0.95, "Pune", "Pune", 4),
            // 0.95 and 0.92 share band 18 (floor of 20 x importance: 18.99
            // and 18.4), so word count decides: one word before two.
            row("venue", 0.92, "Shaniwar Wada", "Pune", 5),
        ];
        rows.sort_by(order);
        let ids: Vec<i64> = rows.iter().map(|r| r.id).collect();
        assert_eq!(ids, vec![4, 5, 2, 3, 1]);
    }

    #[test]
    fn rows_of_one_place_sit_together_then_by_id() {
        let mut rows = [
            row("address", 0.0, "1 A Road", "Wakad", 9),
            row("address", 0.0, "1 A Road", "Aundh", 8),
            row("address", 0.0, "1 A Road", "Wakad", 7),
        ];
        rows.sort_by(order);
        let ids: Vec<i64> = rows.iter().map(|r| r.id).collect();
        assert_eq!(ids, vec![8, 7, 9]);
    }

    #[test]
    fn row_keeps_values_as_postgres_stores_them() {
        use crate::record::{AddressFields, GeocodingLayer};
        use geolith::admin::AdminHierarchy;
        use geolith::source::input::{DataSource, OsmElementType};
        let admin = AdminHierarchy {
            country_code: Some("IN".to_owned()),
            country: Some("India".to_owned()),
            region: Some("Maharashtra".to_owned()),
            locality: Some("Pune".to_owned()),
            ..AdminHierarchy::default()
        };
        let record = GeocodingRecord::new(RecordInit {
            id: u64::MAX,
            source: DataSource::Osm {
                element_type: OsmElementType::Node,
                relations: Vec::new(),
            },
            layer: GeocodingLayer::Address,
            name: "7".to_owned(),
            lon: 73.856_743_21,
            lat: 18.520_430_49,
            admin,
            address: Some(AddressFields {
                number: Some("7".to_owned()),
                street: Some("MG Road".to_owned()),
                unit: None,
                postcode: None,
                city: None,
            }),
            names: std::collections::HashMap::new(),
            importance: 0.123_456,
        });
        let row = Row::from_record(&record);
        // u64::MAX read as signed 64 bits.
        assert_eq!(row.id, -1);
        assert_eq!(row.lon, 73.856_743_2);
        assert_eq!(row.lat, 18.520_430_5);
        assert_eq!(row.importance, 0.1235);
        assert_eq!(row.layer, "address");
        assert_eq!(row.street, "MG Road");
        assert_eq!(row.county, "");
        assert_eq!(row.postcode, "");
        assert_eq!(row.region, "Maharashtra");
    }

    fn sorted_ids_through_writer(rows: &[Row], sort_bytes: usize) -> (Vec<i64>, usize) {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut writer = GlxWriter::new(Vec::new(), dir.path(), sort_bytes).expect("writer");
        for r in rows {
            writer.push(r.clone()).expect("push");
        }
        let runs_before = writer.runs();
        let merged: Vec<i64> = writer
            .merged()
            .expect("merge")
            .map(|r| r.expect("row").id)
            .collect();
        (merged, runs_before)
    }

    /// An output that counts, at its first write, the runs still on disk.
    struct Watch {
        dir: PathBuf,
        runs_at_first_write: Option<usize>,
        bytes: Vec<u8>,
    }

    impl Write for Watch {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if self.runs_at_first_write.is_none() {
                let runs = std::fs::read_dir(&self.dir)
                    .expect("dir")
                    .filter_map(Result::ok)
                    .filter(|entry| entry.file_name().to_string_lossy().starts_with("run-"))
                    .count();
                self.runs_at_first_write = Some(runs);
            }
            self.bytes.extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn the_runs_are_gone_before_the_file_is_written() {
        // 200 rows with a 2,000-byte budget: many runs on disk.
        let dir = tempfile::tempdir().expect("tempdir");
        let mut watch = Watch {
            dir: dir.path().to_path_buf(),
            runs_at_first_write: None,
            bytes: Vec::new(),
        };
        let mut writer = GlxWriter::new(&mut watch, dir.path(), 2_000).expect("writer");
        for id in 0..200 {
            writer
                .push(row("venue", 0.5, "Some Place Name", "Pune", id))
                .expect("push");
        }
        let runs = writer.runs();
        assert!(runs > 5, "only {runs} runs");
        writer.finish().expect("finish");

        assert_eq!(watch.runs_at_first_write, Some(0));
        // Every row reached the file before its run was removed.
        // The search part follows the file header.
        let start = glx::format::FILE_HEADER_LEN;
        let part = glx::format::Span {
            offset: start,
            len: watch.bytes.len() as u64 - start,
        };
        let header =
            glx::format::Header::decode(&watch.bytes[start as usize..], part).expect("header");
        assert_eq!(header.docs, 200);
    }

    #[test]
    fn a_file_that_cannot_be_written_fails_the_build() {
        let dir = tempfile::tempdir().expect("tempdir");
        // An output with no room: its first write fails.
        let full: &mut [u8] = &mut [];
        let mut writer = GlxWriter::new(full, dir.path(), DEFAULT_SORT_BYTES).expect("writer");
        writer
            .push(row("venue", 0.5, "Some Place Name", "Pune", 1))
            .expect("push");
        let err = writer.finish().expect_err("a full output fails the build");
        assert_eq!(err.kind(), io::ErrorKind::WriteZero);
    }

    /// The sort works out each row's word count once: compared again on
    /// every comparison, it scanned each planet row's text about forty times
    /// (sort and merge), most of the write step's time.
    #[test]
    fn a_sort_counts_each_rows_words_once() {
        let rows: Vec<Row> = (0..1_000)
            .map(|i| {
                let text = ["Some Place Name", "Café", "12, MG Road Pune", "東京タワー"]
                    [usize::try_from(i % 4).unwrap_or(0)];
                row("address", 0.0, text, "Pune", i)
            })
            .collect();
        PIECES_CALLS.with(|c| c.set(0));
        let (spilled, _) = sorted_ids_through_writer(&rows, 20_000);
        let calls = PIECES_CALLS.with(std::cell::Cell::get);
        assert_eq!(spilled.len(), 1_000);
        // Once when buffered and once when read back from a run.
        assert!(calls <= 2_000, "{calls} word counts for 1,000 rows");
    }

    #[test]
    fn spilled_runs_merge_into_the_same_order_as_one_sort() {
        let rows: Vec<Row> = (0..200)
            .map(|i| {
                let layer = if i % 3 == 0 { "address" } else { "venue" };
                let importance = f32::from(u8::try_from(i % 20).unwrap_or(0)) / 20.0;
                let locality = ["Aundh", "Baner", "Wakad"][usize::try_from(i % 3).unwrap_or(0)];
                row(layer, importance, "Some Place Name", locality, i)
            })
            .collect();
        let mut expected = rows.clone();
        expected.sort_by(order);
        let expected: Vec<i64> = expected.iter().map(|r| r.id).collect();

        let (in_memory, no_runs) = sorted_ids_through_writer(&rows, usize::MAX);
        assert_eq!(no_runs, 0);
        assert_eq!(in_memory, expected);

        // A tiny budget spills many runs; the merge must give the same order.
        let (spilled, runs) = sorted_ids_through_writer(&rows, 2_000);
        assert!(runs > 5, "expected many runs, got {runs}");
        assert_eq!(spilled, expected);
    }
}