geodb_build: smaller mmap-readable v5 geocoder format, faster build
- Commit
65d8c1f91cd0f5ae96c013274f8a40eabb199b98- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 17:23 UTC (1 month ago)
- Parents
713693f
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex aea576fdeb..528657a524 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2001,7 +2001,9 @@ dependencies = [ name = "geodb_build" version = "0.1.0" dependencies = [+ "mimalloc", "osm_ingest",+ "rayon", "zstd", ]
scripts/networklocation/geodb_build/Cargo.toml
diff --git a/scripts/networklocation/geodb_build/Cargo.toml b/scripts/networklocation/geodb_build/Cargo.tomlindex 739fa3c8f6..abe172f82a 100644--- a/scripts/networklocation/geodb_build/Cargo.toml+++ b/scripts/networklocation/geodb_build/Cargo.toml@@ -1,4 +1,4 @@-# Host-side builder for `geocoder-v3.geodb`, the offline reverse/forward geocoder database+# Host-side builder for `geocoder.db`, the offline reverse/forward geocoder database # that `:networklocation` reads. # # Replaces the `osmium tags-filter | osmium export | geocoder_gen.cpp` chain. That pipeline@@ -16,7 +16,7 @@ version = "0.1.0" edition = "2021" publish = false license = "GPL-2.0-only"-description = "OSM .osm.pbf -> geocoder-v3.geodb for :networklocation"+description = "OSM .osm.pbf -> geocoder.db for :networklocation" [lib] name = "geodb_build"@@ -37,5 +37,14 @@ osm_ingest = { path = "../../maps/osm_ingest" } # never cross-compiles, so the C dependency stops here and does not reach the app. zstd.workspace = true +# Sorting and materialisation run on every core. Every parallel step here collects in input+# order, so the output stays byte-identical whatever the thread count.+rayon.workspace = true++# The Windows process heap serialises 64 threads that each allocate a few small `String`s per+# OSM feature: on North America the node-features pass sat at 1.4 of 64 cores. Same reason and+# same crate as `scripts/maps/mamaps_build`.+mimalloc.workspace = true+ [profile.release] opt-level = 3
scripts/networklocation/geodb_build/README.md
diff --git a/scripts/networklocation/geodb_build/README.md b/scripts/networklocation/geodb_build/README.mdindex 30c09cf7b1..b5c374b8e8 100644--- a/scripts/networklocation/geodb_build/README.md+++ b/scripts/networklocation/geodb_build/README.md@@ -1,6 +1,6 @@ # geodb_build — offline geocoder database builder -Builds `geocoder-v3.geodb`, the offline reverse/forward geocoder database that+Builds `geocoder.db`, the offline reverse/forward geocoder database that `:networklocation` serves the system `GeocodeProvider` from. Replaces the `osmium tags-filter | osmium export | scripts/geocoder_gen.cpp` chain, which@@ -15,28 +15,53 @@ was simply absent, in both directions: | Added | Why it mattered | | --- | --- |-| **Named streets**, sampled along their length | Reverse geocoding could return a house number or nothing; it could never say "you are on Market Street". |+| **Named streets**, sampled every ~250 m along their length (roads only, not footways, service aisles or bus stops) | Reverse geocoding could return a house number or nothing; it could never say "you are on Market Street". | | **Points of interest** — `amenity`/`shop`/`tourism`/`leisure`/`office`/`healthcare` with a name | A named building or shop was invisible. | | **Populated places** — `place=city\|town\|village\|hamlet\|suburb\|neighbourhood\|quarter\|borough\|island` | No way to say which neighbourhood or village a point is in. | | **`addr:place` addresses** | Much of Germany and Austria, and most of Japan and Korea, address buildings against a place rather than a street. Requiring `addr:street` silently discarded all of them. | -Coordinates also moved from **e6 to e7**, which is the precision OSM itself stores, so the-conversion no longer throws away a decimal digit.+On California, v3 held 8.96 M records where the old rules would have given 3.66 M. -On California the result is 8.96 M records where the old rules would have given 3.66 M.+## v4: cut down for size++v4 keeps everything v3 indexes but stores it more cheaply. The header version is 4; the+section layout is unchanged.++- **Coordinates are e5** (about 1.1 m). At e7 the two coordinate columns were nearly half the+ file, spent on centimetres no geocoder answer needs.+- **Fewer street samples**: ~250 m apart instead of ~100 m, roads only, and exact duplicate+ rows (adjacent ways meeting at a shared node) written once.+- **The forward index holds only records with a street.** A forward query always names one;+ keying on kind instead would lose POIs and places that carry a full address but no house+ number.+- **The name index holds one entry per street name per grid cell**, not one per sample.++## v5: read from a memory map++v5 changes no content, only the layout, so the app can serve the planet without holding it in+RAM. v4's reader inflated every dictionary on open: about 2 GB of native heap on the phone and+more than a minute before the first answer.++- **Dictionaries are stored in blocks** of 1,024 strings, each its own zstd frame, behind an+ uncompressed table of every block's first string. A lookup binary-searches that table in the+ mapped file and decompresses one block.+- **Column directories store end offsets**, so any block is located straight from the mapping.++On California this costs 1% of size (43.44 MiB vs 43.00 MiB). ## Building and running ```sh-cd scripts/networklocation/geodb_build-cargo build --release+cargo build --release -p geodb_build -# rehearse on a metro, then a state, before the planet-./target/release/geodb_build ../../../analysis/mamaps/SanFrancisco.osm.pbf --out sf.geodb-./target/release/geodb_build california-latest.osm.pbf --out ca.geodb-./target/release/geodb_build planet-latest.osm.pbf --out geocoder-v3.geodb+# The crate is a member of the repo-root workspace, so the binary lands in the root target/.+# rehearse on a state before the planet+target/release/geodb_build scripts/maps/inputs/california.osm.pbf --out analysis/geodb/ca.db+target/release/geodb_build scripts/maps/inputs/planet.osm.pbf --out analysis/geodb/geocoder.db ``` +Run from the repo root.+ Options: `--bbox W,S,E,N` to clip, `--threads N` (default: all cores, or `MAPS_THREADS`), `--no-verify` to skip the read-back. @@ -47,8 +72,8 @@ with the pure-Rust `ruzstd`, which has no encoder, and nothing here cross-compil ## Publishing ```sh-sha256sum geocoder-v3.geodb-../../maps/publish_r2.sh geocoder-v3.geodb+sha256sum geocoder.db+../../maps/publish_r2.sh geocoder.db ``` Then put the hash into `OfflineDatabases.sha256For` in the app.@@ -65,13 +90,13 @@ independent path and checks all three. -searches them with a UTF-16 comparator. UTF-8 and UTF-16 disagree above the BMP: `U+10000` sorts after `U+FFFF` in UTF-8 but before it in UTF-16, because surrogates start at `0xD800`. Sorting the wrong way makes forward lookups start missing entries near the disagreement.-3. **The forward and name indexes are permutations into grid order**, each sorted by its own- key. Out of step with its dictionary, forward search returns the wrong rows.+3. **The forward and name indexes point into grid order**, each sorted by its own key. Out of+ step with its dictionary, forward search returns the wrong rows. The Z-order interleave is the format's other landmine. v2 interleaved 16 bits per axis, which-worked only because an e6 cell is 50 000 units wide. **An e7 cell is 500 000 units and needs-19**, so `format::morton_in_cell` interleaves 20. Getting that wrong does not fail; it silently-produces a worse ordering, and on overflow a wrong one.+worked only because an e6 cell is 50 000 units wide. `format::morton_in_cell` interleaves 20,+which covers an e5 cell (5 000 units, 13 bits) with room to spare; too few bits does not fail,+it silently produces a worse ordering, and on overflow a wrong one. ## Determinism @@ -94,7 +119,7 @@ The two things that decide whether a planet build fits: ## Compression -Column blocks are zstd level 19 and are compressed **in parallel** — they are independent by-construction, and at level 19 zstd manages only a couple of megabytes a second per core. On-California this took the write phase from 335 s to 62 s, and the output is byte-identical to-the sequential version.+Column blocks and dictionaries are zstd **level 3**. Measured on California's column blocks,+level 3 is 38.85 MiB in 0.8 s against 35.48 MiB in 30 s at level 19: 9.5% larger for a ~37x+faster write. Blocks are compressed in parallel (they are independent by construction), and the+output is byte-identical whatever the thread count.
scripts/networklocation/geodb_build/src/bin/geodb_build.rs
diff --git a/scripts/networklocation/geodb_build/src/bin/geodb_build.rs b/scripts/networklocation/geodb_build/src/bin/geodb_build.rsindex 690fa6f96c..3b748d5ca4 100644--- a/scripts/networklocation/geodb_build/src/bin/geodb_build.rs+++ b/scripts/networklocation/geodb_build/src/bin/geodb_build.rs@@ -1,4 +1,4 @@-//! `geodb_build IN.osm.pbf --out geocoder-v3.geodb [--bbox BOX] [--threads N]`+//! `geodb_build IN.osm.pbf --out geocoder.db [--bbox BOX] [--threads N]` use std::path::PathBuf; use std::process::ExitCode;@@ -6,10 +6,14 @@ use std::process::ExitCode; use geodb_build::{commas, extract, human_bytes, write}; use osm_ingest::bbox::BBox; +/// An allocator decides where, never what, so this cannot change a byte of the output.+#[global_allocator]+static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;+ const USAGE: &str = "\ Usage: geodb_build IN.osm.pbf --out FILE [--bbox W,S,E,N] [--threads N] [--no-verify] - --out geocoder-v3.geodb to write+ --out geocoder.db to write --bbox clip to a box, for a metro or region rehearsal --threads worker threads (default: all cores, or MAPS_THREADS) --no-verify skip the read-back check (not recommended)";@@ -84,6 +88,9 @@ fn main() -> ExitCode { if let Some(n) = args.threads { osm_ingest::par::set_threads(n); }+ let _ = rayon::ThreadPoolBuilder::new()+ .num_threads(osm_ingest::par::threads())+ .build_global(); let started = std::time::Instant::now(); let (mut rows, mut strings, stats) = match extract::extract(&args.input, args.bbox.as_ref()) {
scripts/networklocation/geodb_build/src/codec.rs
diff --git a/scripts/networklocation/geodb_build/src/codec.rs b/scripts/networklocation/geodb_build/src/codec.rsindex c08f95f3d8..850c74a0bb 100644--- a/scripts/networklocation/geodb_build/src/codec.rs+++ b/scripts/networklocation/geodb_build/src/codec.rs@@ -16,7 +16,10 @@ use std::collections::HashMap; use std::io::{self, Write}; -use crate::format::{BLOCK, ZSTD_LEVEL};+use rayon::prelude::*;++use crate::format::{BLOCK, DICT_BLOCK, ZSTD_LEVEL};+use crate::progress::Progress; // --------------------------------------------------------------------------- interner /// Assigns a dense id to each distinct string, in first-seen order.@@ -76,13 +79,13 @@ impl Interner { pub fn finish(&self, searchable: bool) -> (Vec<&str>, Vec<u32>) { let mut order: Vec<u32> = (0..self.strings.len() as u32).collect(); if searchable {- order.sort_unstable_by(|&a, &b| {+ order.par_sort_unstable_by(|&a, &b| { cmp_utf16(&self.strings[a as usize], &self.strings[b as usize]) }); } else { // Descending frequency, ties broken by UTF-16 order so the output is deterministic // rather than dependent on the order strings happened to be seen in.- order.sort_unstable_by(|&a, &b| {+ order.par_sort_unstable_by(|&a, &b| { self.counts[b as usize] .cmp(&self.counts[a as usize]) .then_with(|| cmp_utf16(&self.strings[a as usize], &self.strings[b as usize]))@@ -138,35 +141,84 @@ fn write_varint(out: &mut Vec<u8>, mut v: u32) { } } -/// Encode a dictionary section body: `rawLen, compLen, zstd(count, [len, utf8]...)`.+/// Encode a dictionary section body, in independently compressed blocks:+///+/// ```text+/// u32 count, u32 strings_per_block, u32 blocks+/// u32 first_end[blocks] end of each block's first string within `firsts`+/// firsts each block's first string, uncompressed and concatenated+/// u32 block_end[blocks] end of each compressed block within `data`+/// data per block: zstd([u32 len, utf8]...) for its strings+/// ```+///+/// The reader binary-searches the uncompressed first strings straight out of the mapped file+/// and decompresses one block of [`DICT_BLOCK`] strings, so it never holds a dictionary in+/// memory. Blocks are compressed in parallel and reassembled in order, so the bytes do not+/// depend on the thread count. pub fn encode_dict(strings: &[&str]) -> io::Result<Vec<u8>> {- let mut raw = Vec::new();- be32(&mut raw, strings.len() as u32);- for s in strings {- be32(&mut raw, s.len() as u32);- raw.extend_from_slice(s.as_bytes());+ let blocks: Vec<io::Result<Vec<u8>>> =+ osm_ingest::par::map_chunks(strings, DICT_BLOCK, |_start, chunk| {+ let mut raw = Vec::new();+ for s in chunk {+ be32(&mut raw, s.len() as u32);+ raw.extend_from_slice(s.as_bytes());+ }+ zstd::encode_all(&raw[..], ZSTD_LEVEL)+ });+ let blocks: Vec<Vec<u8>> = blocks.into_iter().collect::<io::Result<_>>()?;++ let mut out = Vec::new();+ be32(&mut out, strings.len() as u32);+ be32(&mut out, DICT_BLOCK as u32);+ be32(&mut out, blocks.len() as u32);+ let firsts: Vec<&str> = strings.iter().step_by(DICT_BLOCK).copied().collect();+ let mut end = 0u32;+ for s in &firsts {+ end += s.len() as u32;+ be32(&mut out, end);+ }+ for s in &firsts {+ out.extend_from_slice(s.as_bytes());+ }+ let mut end = 0u32;+ for b in &blocks {+ end += b.len() as u32;+ be32(&mut out, end);+ }+ for b in &blocks {+ out.extend_from_slice(b); }- let comp = zstd::encode_all(&raw[..], ZSTD_LEVEL)?;- let mut out = Vec::with_capacity(comp.len() + 8);- be32(&mut out, raw.len() as u32);- be32(&mut out, comp.len() as u32);- out.extend_from_slice(&comp); Ok(out) } /// Encode a column section body. ///-/// `rawLen`/`compLen` for every block come first as a directory, then the blocks. `prev` resets-/// at each block boundary, which is what makes a block independently decodable and is exactly-/// what the reader relies on to random-access a record without touching its neighbours.+/// A directory of `(raw_len, end)` per block comes first, where `end` is the block's end+/// offset within the data that follows, so the reader finds any block straight from the mapped+/// file without a table in memory. `prev` resets at each block boundary, which is what makes a+/// block independently decodable. /// /// Blocks are compressed in parallel. At level 19 zstd manages a couple of megabytes a second /// per core, which on a planet-scale column is hours of the build spent in one thread; the /// blocks are independent by construction, so this is the one place parallelism is free. The /// results are reassembled in chunk order, so the output does not depend on the thread count. pub fn encode_column(values: &[i32], delta: bool) -> io::Result<Vec<u8>> {+ encode_column_with(values, delta, None)+}++/// Number of blocks [`encode_column`] writes for `n` values; an empty column still gets one.+pub fn column_blocks(n: usize) -> u64 {+ n.div_ceil(BLOCK).max(1) as u64+}++/// [`encode_column`], advancing `progress` once per compressed block.+pub fn encode_column_with(+ values: &[i32],+ delta: bool,+ progress: Option<&Progress>,+) -> io::Result<Vec<u8>> { let n = values.len();- let blocks = n.div_ceil(BLOCK).max(usize::from(n == 0));+ let blocks = column_blocks(n) as usize; let encoded: Vec<io::Result<(usize, Vec<u8>)>> = osm_ingest::par::map_chunks(values, BLOCK, |_start, chunk| {@@ -178,6 +230,9 @@ pub fn encode_column(values: &[i32], delta: bool) -> io::Result<Vec<u8>> { prev = v; } let comp = zstd::encode_all(&raw[..], ZSTD_LEVEL)?;+ if let Some(p) = progress {+ p.inc();+ } Ok((raw.len(), comp)) }); @@ -185,23 +240,26 @@ pub fn encode_column(values: &[i32], delta: bool) -> io::Result<Vec<u8>> { let mut bodies: Vec<u8> = Vec::new(); for r in encoded { let (raw_len, comp) = r?;- dir.push((raw_len as u32, comp.len() as u32)); bodies.extend_from_slice(&comp);+ dir.push((raw_len as u32, bodies.len() as u32)); } // `map_chunks` yields nothing for an empty input, but the format still wants one empty // block so the directory and the reader's block count agree. if dir.is_empty() { let comp = zstd::encode_all(&[][..], ZSTD_LEVEL)?;- dir.push((0, comp.len() as u32)); bodies.extend_from_slice(&comp);+ dir.push((0, bodies.len() as u32));+ if let Some(p) = progress {+ p.inc();+ } } let mut out = Vec::with_capacity(bodies.len() + dir.len() * 8 + 8); be32(&mut out, n as u32); be32(&mut out, dir.len() as u32);- for (raw_len, comp_len) in &dir {+ for (raw_len, end) in &dir { be32(&mut out, *raw_len);- be32(&mut out, *comp_len);+ be32(&mut out, *end); } out.extend_from_slice(&bodies); Ok(out)@@ -305,12 +363,13 @@ mod tests { }; let n = rd32(0) as usize; let blocks = rd32(4) as usize;- let mut offset = 8 + blocks * 8;+ let data = 8 + blocks * 8; let mut out = Vec::with_capacity(n);+ let mut start = 0usize; for b in 0..blocks {- let comp_len = rd32(8 + b * 8 + 4) as usize;- let raw = zstd::decode_all(&body[offset..offset + comp_len]).unwrap();- offset += comp_len;+ let end = rd32(8 + b * 8 + 4) as usize;+ let raw = zstd::decode_all(&body[data + start..data + end]).unwrap();+ start = end; let mut p = 0usize; let mut prev = 0i32; let count = (n - b * BLOCK).min(BLOCK);@@ -372,19 +431,31 @@ mod tests { fn dictionaries_round_trip() { let strings = vec!["", "Main Street", "café", "\u{10000}"]; let body = encode_dict(&strings).unwrap();- let raw_len = u32::from_be_bytes([body[0], body[1], body[2], body[3]]) as usize;- let raw = zstd::decode_all(&body[8..]).unwrap();- assert_eq!(raw.len(), raw_len);- let count = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;- assert_eq!(count, strings.len());- let mut p = 4;- for want in &strings {- let len =- u32::from_be_bytes([raw[p], raw[p + 1], raw[p + 2], raw[p + 3]]) as usize;- p += 4;- assert_eq!(std::str::from_utf8(&raw[p..p + len]).unwrap(), *want);- p += len;- }+ assert_eq!(crate::write::decode_dict(&body).unwrap(), strings);+ }++ #[test]+ fn dictionaries_round_trip_across_block_boundaries() {+ // Not a multiple of DICT_BLOCK, so the last block is short.+ let owned: Vec<String> = (0..DICT_BLOCK * 2 + 37).map(|i| format!("name {i:06}")).collect();+ let strings: Vec<&str> = owned.iter().map(String::as_str).collect();+ let body = encode_dict(&strings).unwrap();+ assert_eq!(crate::write::decode_dict(&body).unwrap(), strings);++ // The first-string table is uncompressed and names each block's first entry, which is+ // what lets the reader binary-search without decompressing.+ let rd32 = |p: usize| u32::from_be_bytes(body[p..p + 4].try_into().unwrap()) as usize;+ assert_eq!(rd32(8), 3, "three blocks");+ let firsts = 12 + 3 * 4;+ let (e0, e1) = (rd32(12), rd32(16));+ assert_eq!(&body[firsts..firsts + e0], strings[0].as_bytes());+ assert_eq!(&body[firsts + e0..firsts + e1], strings[DICT_BLOCK].as_bytes());+ }++ #[test]+ fn an_empty_dictionary_is_readable() {+ let body = encode_dict(&[]).unwrap();+ assert_eq!(crate::write::decode_dict(&body).unwrap(), Vec::<String>::new()); } #[test]
scripts/networklocation/geodb_build/src/extract.rs
diff --git a/scripts/networklocation/geodb_build/src/extract.rs b/scripts/networklocation/geodb_build/src/extract.rsindex 63c68ebd86..1bdd3fd64d 100644--- a/scripts/networklocation/geodb_build/src/extract.rs+++ b/scripts/networklocation/geodb_build/src/extract.rs@@ -27,11 +27,13 @@ use osm_ingest::nodeloc::{resolve_nodes, NodeLocations}; use osm_ingest::osm::{visit_block, Element, Tags, MEMBER_WAY}; use osm_ingest::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS}; use osm_ingest::proto::{Error, Result};+use rayon::prelude::*; use crate::codec::Interner; use crate::extract_extra::STREET_SAMPLE_E7;-use crate::format::{in_range, DICTS, D_CITY, D_COUNTRY, D_HOUSE, D_NAME, D_POSTCODE, D_STATE,- D_STREET, K_ADDRESS, K_PLACE, K_POI, K_STREET};+use crate::progress::Progress;+use crate::format::{e7_to_e5, in_range, DICTS, D_CITY, D_COUNTRY, D_HOUSE, D_NAME, D_POSTCODE,+ D_STATE, D_STREET, K_ADDRESS, K_PLACE, K_POI, K_STREET}; /// Cap on samples per street way, so one enormous way cannot dominate the database. const STREET_MAX_SAMPLES: usize = 32;@@ -39,6 +41,27 @@ const STREET_MAX_SAMPLES: usize = 32; /// Tag keys that make an object a POI when it also has a name. const POI_KEYS: [&str; 6] = ["amenity", "shop", "tourism", "leisure", "office", "healthcare"]; +/// `highway=*` values that are streets someone could be standing on or addressed against.+/// Named footways, cycleways, tracks, service aisles, links and bus stops used to be sampled+/// too; they were a large share of the street rows and a nearest-street answer of "Parking+/// Aisle B" or a bus stop name is worse than the road beside it.+const ROAD_VALUES: [&str; 10] = [+ "motorway",+ "trunk",+ "primary",+ "secondary",+ "tertiary",+ "unclassified",+ "residential",+ "living_street",+ "pedestrian",+ "road",+];++fn is_road(highway: &str) -> bool {+ ROAD_VALUES.contains(&highway)+}+ /// `place=*` values worth indexing: inhabited places people search for and expect to be told /// they are in. Deliberately excludes `place=locality` (often uninhabited), `region`, `ocean` /// and the administrative-only values.@@ -62,10 +85,10 @@ const PLACE_VALUES: [&str; 9] = [ /// strings stored once in [`Strings`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Row {- /// Latitude, e7.- pub lat_e7: i32,- /// Longitude, e7.- pub lon_e7: i32,+ /// Latitude, e5.+ pub lat: i32,+ /// Longitude, e5.+ pub lon: i32, /// One of the `K_*` constants. pub kind: u8, /// Dictionary ids, indexed by the `D_*` constants in [`crate::format`].@@ -111,7 +134,7 @@ fn attrs_ok(kind: u8, a: &Attrs) -> bool { /// Whether a classified feature is worth storing at all. fn is_useful(kind: u8, a: &Attrs, lat_e7: i32, lon_e7: i32) -> bool {- in_range(lat_e7, lon_e7) && attrs_ok(kind, a)+ in_range(e7_to_e5(lat_e7), e7_to_e5(lon_e7)) && attrs_ok(kind, a) } /// What a pass decided about one element.@@ -169,7 +192,7 @@ fn classify(tags: &Tags) -> Option<u8> { if !named { return None; }- if tags.get("highway").is_some() {+ if tags.get_str("highway").is_some_and(is_road) { return Some(K_STREET); } if let Some(place) = tags.get_str("place") {@@ -183,8 +206,9 @@ fn classify(tags: &Tags) -> Option<u8> { None } +/// OSM coordinates arrive as e7 and are rounded to the stored e5 here, once. fn row_from(kind: u8, ids: [u32; DICTS], lat_e7: i32, lon_e7: i32) -> Row {- Row { lat_e7, lon_e7, kind, ids }+ Row { lat: e7_to_e5(lat_e7), lon: e7_to_e5(lon_e7), kind, ids } } // --------------------------------------------------------------------------- way handling@@ -294,6 +318,18 @@ impl Stats { pub fn rows(&self) -> usize { self.addresses + self.streets + self.pois + self.places }++ fn add(&mut self, o: &Stats) {+ self.from_nodes += o.from_nodes;+ self.from_ways += o.from_ways;+ self.from_relations += o.from_relations;+ self.addresses += o.addresses;+ self.streets += o.streets;+ self.pois += o.pois;+ self.places += o.places;+ self.outside_bbox += o.outside_bbox;+ self.incomplete += o.incomplete;+ } } include!("extract_part1.rs");\ No newline at end of file
scripts/networklocation/geodb_build/src/extract_extra.rs
diff --git a/scripts/networklocation/geodb_build/src/extract_extra.rs b/scripts/networklocation/geodb_build/src/extract_extra.rsindex 03cd939c7e..a1a74c3d8a 100644--- a/scripts/networklocation/geodb_build/src/extract_extra.rs+++ b/scripts/networklocation/geodb_build/src/extract_extra.rs@@ -2,5 +2,6 @@ //! //! Minimum spacing and sampling helpers shared by the street extract passes. -/// Minimum spacing between samples along a street, in e7 latitude units (~100 m).-pub const STREET_SAMPLE_E7: i64 = 10_000;+/// Minimum spacing between samples along a street, in e7 latitude units (~250 m). Sampling+/// runs on OSM's e7 coordinates, before rows are rounded to the stored e5.+pub const STREET_SAMPLE_E7: i64 = 25_000;
scripts/networklocation/geodb_build/src/extract_part1.rs
diff --git a/scripts/networklocation/geodb_build/src/extract_part1.rs b/scripts/networklocation/geodb_build/src/extract_part1.rsindex 4878093888..08d5bb8c4f 100644--- a/scripts/networklocation/geodb_build/src/extract_part1.rs+++ b/scripts/networklocation/geodb_build/src/extract_part1.rs@@ -139,44 +139,72 @@ pub fn extract( let locs = resolve_nodes(input, &blobs, &kinds, "node coords", table)?; // --- materialize ways -------------------------------------------------- for w in &ways {- let coords: Vec<(i32, i32)> = w.refs.iter().filter_map(|&id| locs.get(id)).collect();- if coords.is_empty() {- continue;- }- let points: Vec<(i32, i32)> = if w.kind == K_STREET {- sample_line(&coords)- } else {- average(&coords).into_iter().collect()- };- for (lat, lon) in points {- if !bbox::keep_e7(bbox, lat, lon) {- stats.outside_bbox += 1;- continue;+ // Chunks run in parallel and are collected in input order, so `rows` comes out exactly as+ // a sequential loop would leave it.+ let p = Progress::new("materialize ways", ways.len() as u64);+ let parts: Vec<(Vec<Row>, Stats)> = ways+ .par_chunks(MATERIALIZE_CHUNK)+ .map(|chunk| {+ let mut out = Vec::new();+ let mut st = Stats::default();+ for w in chunk {+ let coords: Vec<(i32, i32)> =+ w.refs.iter().filter_map(|&id| locs.get(id)).collect();+ if coords.is_empty() {+ continue;+ }+ let points: Vec<(i32, i32)> = if w.kind == K_STREET {+ sample_line(&coords)+ } else {+ average(&coords).into_iter().collect()+ };+ for (lat, lon) in points {+ if !bbox::keep_e7(bbox, lat, lon) {+ st.outside_bbox += 1;+ continue;+ }+ push_counted(&mut out, &mut st, row_from(w.kind, w.ids, lat, lon), Origin::Way);+ } }- push_counted(&mut rows, &mut stats, row_from(w.kind, w.ids, lat, lon), Origin::Way);- }- }+ p.add(chunk.len() as u64);+ (out, st)+ })+ .collect();+ absorb(&mut rows, &mut stats, parts);+ p.finish();+ drop(ways); // --- materialize relations -------------------------------------------- for (kind, ids, members) in relations.drain(..) {- let mut coords: Vec<(i32, i32)> = Vec::new();- for id in &members {- if let Some(refs) = member_geom.get(id) {- coords.extend(refs.iter().filter_map(|&r| locs.get(r)));+ let p = Progress::new("materialize relations", relations.len() as u64);+ let parts: Vec<(Vec<Row>, Stats)> = relations+ .par_chunks(MATERIALIZE_CHUNK)+ .map(|chunk| {+ let mut out = Vec::new();+ let mut st = Stats::default();+ for (kind, ids, members) in chunk {+ let mut coords: Vec<(i32, i32)> = Vec::new();+ for id in members {+ if let Some(refs) = member_geom.get(id) {+ coords.extend(refs.iter().filter_map(|&r| locs.get(r)));+ }+ }+ let Some((lat, lon)) = average(&coords) else { continue };+ if !bbox::keep_e7(bbox, lat, lon) {+ st.outside_bbox += 1;+ continue;+ }+ push_counted(&mut out, &mut st, row_from(*kind, *ids, lat, lon), Origin::Relation); }- }- let Some((lat, lon)) = average(&coords) else { continue };- if !bbox::keep_e7(bbox, lat, lon) {- stats.outside_bbox += 1;- continue;- }- push_counted(&mut rows, &mut stats, row_from(kind, ids, lat, lon), Origin::Relation);- }+ p.add(chunk.len() as u64);+ (out, st)+ })+ .collect();+ absorb(&mut rows, &mut stats, parts);+ p.finish();+ drop(relations); drop(locs); drop(member_geom);- drop(ways); // --- pass 4: node features ------------------------------------------- {@@ -231,10 +259,22 @@ pub(crate) enum Origin { Relation, } +/// Ways or relations per parallel materialisation task.+const MATERIALIZE_CHUNK: usize = 1 << 14;++/// Append per-chunk results in chunk order, freeing each chunk as it goes.+fn absorb(rows: &mut Vec<Row>, stats: &mut Stats, parts: Vec<(Vec<Row>, Stats)>) {+ rows.reserve(parts.iter().map(|(r, _)| r.len()).sum());+ for (r, s) in parts {+ rows.extend_from_slice(&r);+ stats.add(&s);+ }+}+ /// Record a materialized row, dropping any whose coordinates fell outside the representable /// range. Tag-level completeness was already decided by [`attrs_ok`] before interning. fn push_counted(rows: &mut Vec<Row>, stats: &mut Stats, row: Row, origin: Origin) {- if !in_range(row.lat_e7, row.lon_e7) {+ if !in_range(row.lat, row.lon) { stats.incomplete += 1; return; }@@ -347,12 +387,28 @@ mod tests { assert!(attrs_ok(K_PLACE, &attrs("Mission District", "", ""))); } + #[test]+ fn only_roads_are_classified_as_streets() {+ for road in ["residential", "primary", "living_street", "pedestrian"] {+ assert!(is_road(road), "{road}");+ }+ for not_road in ["footway", "service", "bus_stop", "track", "motorway_link", "cycleway"] {+ assert!(!is_road(not_road), "{not_road}");+ }+ }++ #[test]+ fn rows_are_stored_at_e5() {+ let r = row_from(K_POI, [0; DICTS], 37_7749350, -122_4194249);+ assert_eq!((r.lat, r.lon), (3_777_494, -12_241_942));+ }+ #[test] fn out_of_range_coordinates_are_never_useful() { let a = attrs("somewhere", "", ""); assert!(is_useful(K_POI, &a, 37_7749300, -122_4194200));- assert!(!is_useful(K_POI, &a, 900_000_001, -122_4194200));- assert!(!is_useful(K_POI, &a, 37_7749300, -1_800_000_001));+ assert!(!is_useful(K_POI, &a, 900_000_100, -122_4194200));+ assert!(!is_useful(K_POI, &a, 37_7749300, -1_800_000_100)); } #[test]
scripts/networklocation/geodb_build/src/format.rs
diff --git a/scripts/networklocation/geodb_build/src/format.rs b/scripts/networklocation/geodb_build/src/format.rsindex 01765afb14..95003602e0 100644--- a/scripts/networklocation/geodb_build/src/format.rs+++ b/scripts/networklocation/geodb_build/src/format.rs@@ -1,4 +1,4 @@-//! The `geocoder-v3.geodb` on-disk format, in one place.+//! The `geocoder.db` on-disk format, in one place. //! //! Every constant here is duplicated by hand in the reader, //! `networklocation/src/main/rust/src/geocoder.rs`. That is the format's main hazard: the two@@ -9,19 +9,41 @@ //! //! ```text //! 0 magic u32 = "MAGE"-//! 4 version u32 = 3+//! 4 version u32 = 5 //! 8 n u32 //! 12 21 sections, each [u32 size][body]: //! [0..6] dictionaries: name, house, street, city, state, country, postcode //! [7..16] columns: lat, lon, name, house, street, city, state, country, postcode, kind //! [17] grid-//! [18] fwd (address-ordered permutation)+//! [18] fwd (records with a street, by structured address) //! [19] nm_name (name ids, ascending) //! [20] nm_rec (record index for each nm_name entry) //! ``` //! //! All integers are **big-endian**, matching v2. //!+//! ## What changed from v4+//!+//! v5 changes no content, only how it can be read. The reader memory-maps the file and must+//! never have to hold a section in RAM; v4's reader inflated every dictionary on open, about+//! 2 GB of heap for the planet.+//!+//! - **Dictionaries are blocked**: [`DICT_BLOCK`] strings per zstd frame, behind an+//! uncompressed table of each block's first string, so a lookup binary-searches that table+//! and decompresses one block. See `codec::encode_dict`.+//! - **Column directories store each block's end offset** instead of its compressed length, so+//! a block is located without a prefix-sum table.+//!+//! ## What changed from v3+//!+//! v4 is v3 cut down for size; the section layout is unchanged.+//!+//! - Coordinates are **e5** (about 1.1 m), not e7. Nobody needs centimetres from a geocoder,+//! and the two coordinate columns were nearly half the file.+//! - `fwd` holds only records that carry a street. A forward query always names one, so street+//! samples and unaddressed POIs and places could never match and were dead weight.+//! - The name index holds one entry per street name per grid cell, not one per street sample.+//! //! ## What changed from v2 //! //! - Coordinates are **e7**, not e6. OSM stores e7, so v2's e6 threw away a decimal digit for@@ -33,21 +55,27 @@ /// `"MAGE"`. pub const MAGIC: u32 = 0x4D41_4745;-/// Format version. v2 was address-only and e6.-pub const VERSION: u32 = 3;+/// Format version. v2 was address-only and e6; v3 was e7 with a full forward index; v4 was e5;+/// v5 is v4 laid out to be read from a memory map.+pub const VERSION: u32 = 5; /// Records per compressed column block. pub const BLOCK: usize = 4096;-/// Zstandard level for column blocks and dictionaries.-pub const ZSTD_LEVEL: i32 = 19;+/// Strings per compressed dictionary block. Small enough that a lookup decompresses only a few+/// kilobytes; large enough that the uncompressed first-string table stays a fraction of the+/// dictionary.+pub const DICT_BLOCK: usize = 1024;+/// Zstandard level for column blocks and dictionaries. Measured on California's column blocks:+/// level 3 is 9.5% larger than 19 and about 37x faster to write.+pub const ZSTD_LEVEL: i32 = 3; -/// Grid cell edge in e7 units: 0.05 degrees, about 5.5 km of latitude.-pub const CELL_E7: i64 = 500_000;+/// Grid cell edge in e5 units: 0.05 degrees, about 5.5 km of latitude.+pub const CELL: i64 = 5_000; /// Cell columns around the planet.-pub const COLS: i64 = 3_600_000_000 / CELL_E7;-/// Lowest representable latitude, e7.-pub const MIN_LAT_E7: i32 = -900_000_000;-/// Lowest representable longitude, e7.-pub const MIN_LON_E7: i32 = -1_800_000_000;+pub const COLS: i64 = 36_000_000 / CELL;+/// Lowest representable latitude, e5.+pub const MIN_LAT: i32 = -9_000_000;+/// Lowest representable longitude, e5.+pub const MIN_LON: i32 = -18_000_000; /// Number of string dictionaries. pub const DICTS: usize = 7;@@ -113,10 +141,15 @@ pub const K_POI: u8 = 3; /// A populated place: city, town, village, suburb, neighbourhood. pub const K_PLACE: u8 = 4; -/// Grid cell containing a coordinate. Row-major, `COLS` cells per row.-pub fn cell_id(lat_e7: i32, lon_e7: i32) -> i64 {- let row = (lat_e7 as i64 - MIN_LAT_E7 as i64) / CELL_E7;- let col = (lon_e7 as i64 - MIN_LON_E7 as i64) / CELL_E7;+/// Round an OSM e7 coordinate to the e5 the database stores.+pub fn e7_to_e5(v: i32) -> i32 {+ (v as i64 + 50).div_euclid(100) as i32+}++/// Grid cell containing an e5 coordinate. Row-major, `COLS` cells per row.+pub fn cell_id(lat: i32, lon: i32) -> i64 {+ let row = (lat as i64 - MIN_LAT as i64) / CELL;+ let col = (lon as i64 - MIN_LON as i64) / CELL; row * COLS + col } @@ -126,28 +159,30 @@ pub fn cell_id(lat_e7: i32, lon_e7: i32) -> i64 { /// `(lat, lon)` sort keeps the latitude delta tiny but lets longitude swing across the whole /// cell on every row. ///-/// v2 interleaved 16 bits per axis, which worked only because an e6 cell is 50 000 units wide.-/// **An e7 cell is 500 000 units and needs 19**, so this interleaves 20. Getting this wrong-/// does not fail — it silently produces a worse ordering and, if the offsets overflowed, a-/// wrong one.-pub fn morton_in_cell(lat_e7: i32, lon_e7: i32) -> u64 {- let lat_off = ((lat_e7 as i64 - MIN_LAT_E7 as i64) % CELL_E7) as u64;- let lon_off = ((lon_e7 as i64 - MIN_LON_E7 as i64) % CELL_E7) as u64;+/// An e5 cell is 5 000 units and needs 13 bits per axis; this interleaves 20, so the offsets+/// cannot overflow. Too few bits would not fail — it would silently produce a wrong ordering.+pub fn morton_in_cell(lat: i32, lon: i32) -> u64 {+ let lat_off = ((lat as i64 - MIN_LAT as i64) % CELL) as u64;+ let lon_off = ((lon as i64 - MIN_LON as i64) % CELL) as u64; (interleave20(lat_off) << 1) | interleave20(lon_off) } /// Spread the low 20 bits of `v` into the even bit positions of a 40-bit result.+///+/// Called twice per comparison while sorting hundreds of millions of rows, so it uses the+/// shift-and-mask spread rather than a bit-at-a-time loop. fn interleave20(v: u64) -> u64 {- let mut r = 0u64;- for i in 0..20 {- r |= ((v >> i) & 1) << (2 * i);- }- r+ let mut x = v & 0xF_FFFF;+ x = (x | (x << 16)) & 0x0000_FFFF_0000_FFFF;+ x = (x | (x << 8)) & 0x00FF_00FF_00FF_00FF;+ x = (x | (x << 4)) & 0x0F0F_0F0F_0F0F_0F0F;+ x = (x | (x << 2)) & 0x3333_3333_3333_3333;+ (x | (x << 1)) & 0x5555_5555_5555_5555 } -/// Whether a coordinate is inside the representable range.-pub fn in_range(lat_e7: i32, lon_e7: i32) -> bool {- (MIN_LAT_E7..=900_000_000).contains(&lat_e7) && (MIN_LON_E7..=1_800_000_000).contains(&lon_e7)+/// Whether an e5 coordinate is inside the representable range.+pub fn in_range(lat: i32, lon: i32) -> bool {+ (MIN_LAT..=9_000_000).contains(&lat) && (MIN_LON..=18_000_000).contains(&lon) } #[cfg(test)]@@ -158,13 +193,13 @@ mod tests { fn cells_tile_the_planet_without_gaps_or_overlap() { assert_eq!(COLS, 7200); // South-west corner is cell 0.- assert_eq!(cell_id(MIN_LAT_E7, MIN_LON_E7), 0);+ assert_eq!(cell_id(MIN_LAT, MIN_LON), 0); // One cell east.- assert_eq!(cell_id(MIN_LAT_E7, MIN_LON_E7 + CELL_E7 as i32), 1);+ assert_eq!(cell_id(MIN_LAT, MIN_LON + CELL as i32), 1); // One cell north.- assert_eq!(cell_id(MIN_LAT_E7 + CELL_E7 as i32, MIN_LON_E7), COLS);+ assert_eq!(cell_id(MIN_LAT + CELL as i32, MIN_LON), COLS); // The north-east corner stays inside i64 comfortably.- let last = cell_id(900_000_000, 1_800_000_000);+ let last = cell_id(9_000_000, 18_000_000); assert!(last > 0 && last < 26_000_000, "cell id {last} out of expected range"); } @@ -172,22 +207,36 @@ mod tests { fn a_cell_is_a_twentieth_of_a_degree() { // Anchored at a cell boundary so the arithmetic is unambiguous: 0.05 degrees is one // cell, so 0.04 stays inside and 0.06 does not.- let lat = MIN_LAT_E7 + 2555 * CELL_E7 as i32;- let a = cell_id(lat, -122_4194200);- assert_eq!(cell_id(lat + 400_000, -122_4194200), a);- assert_ne!(cell_id(lat + 600_000, -122_4194200), a);+ let lat = MIN_LAT + 2555 * CELL as i32;+ let a = cell_id(lat, -12_241_942);+ assert_eq!(cell_id(lat + 4_000, -12_241_942), a);+ assert_ne!(cell_id(lat + 6_000, -12_241_942), a); // And a cell step north moves by exactly one grid row.- assert_eq!(cell_id(lat + CELL_E7 as i32, -122_4194200), a + COLS);+ assert_eq!(cell_id(lat + CELL as i32, -12_241_942), a + COLS);+ }++ #[test]+ fn the_fast_interleave_matches_the_bit_loop() {+ let slow = |v: u64| (0..20).fold(0u64, |r, i| r | ((v >> i) & 1) << (2 * i));+ let mut v = 0x9E37_79B9u64;+ for _ in 0..100_000 {+ v ^= v << 13;+ v ^= v >> 7;+ v ^= v << 17;+ assert_eq!(interleave20(v), slow(v), "{v:#x}");+ }+ for v in [0, 1, 4_999, 0xF_FFFF, u64::MAX] {+ assert_eq!(interleave20(v), slow(v), "{v:#x}");+ } } #[test] fn morton_offsets_cannot_overflow_the_interleave() {- // The whole point of widening to 20 bits: an e7 cell is 500 000 units, which needs 19.- assert!(CELL_E7 <= (1 << 20), "cell wider than the interleave can represent");+ assert!(CELL <= (1 << 20), "cell wider than the interleave can represent"); // Extremes of a cell.- let base_lat = MIN_LAT_E7;- let base_lon = MIN_LON_E7;- let hi = morton_in_cell(base_lat + CELL_E7 as i32 - 1, base_lon + CELL_E7 as i32 - 1);+ let base_lat = MIN_LAT;+ let base_lon = MIN_LON;+ let hi = morton_in_cell(base_lat + CELL as i32 - 1, base_lon + CELL as i32 - 1); assert!(hi < (1u64 << 40), "morton escaped 40 bits: {hi:#x}"); assert_eq!(morton_in_cell(base_lat, base_lon), 0); }@@ -195,10 +244,10 @@ mod tests { #[test] fn morton_orders_nearby_points_together() { // Two points a metre apart must be far closer in Z-order than two a cell apart.- let a = morton_in_cell(37_7749300, -122_4194200);- let b = morton_in_cell(37_7749400, -122_4194200);+ let a = morton_in_cell(3_777_493, -12_241_942);+ let b = morton_in_cell(3_777_494, -12_241_942); let near = a.abs_diff(b);- let far = a.abs_diff(morton_in_cell(37_7749300 + 400_000, -122_4194200));+ let far = a.abs_diff(morton_in_cell(3_777_493 + 4_000, -12_241_942)); assert!(near < far, "z-order does not preserve locality: {near} vs {far}"); } @@ -207,24 +256,28 @@ mod tests { let mut seen = std::collections::HashSet::new(); for dlat in 0..40 { for dlon in 0..40 {- let m = morton_in_cell(- MIN_LAT_E7 + dlat * 12_345,- MIN_LON_E7 + dlon * 12_345,- );+ let m = morton_in_cell(MIN_LAT + dlat * 123, MIN_LON + dlon * 123); assert!(seen.insert(m), "collision at ({dlat}, {dlon})"); } } } #[test]- fn range_check_matches_the_e7_field_width() {+ fn range_check_matches_the_e5_field_width() { assert!(in_range(0, 0));- assert!(in_range(900_000_000, 1_800_000_000));- assert!(in_range(-900_000_000, -1_800_000_000));- assert!(!in_range(900_000_001, 0));- assert!(!in_range(0, -1_800_000_001));- // e7 longitude is the widest value stored and must still fit an i32.- assert!(1_800_000_000i64 < i32::MAX as i64);+ assert!(in_range(9_000_000, 18_000_000));+ assert!(in_range(-9_000_000, -18_000_000));+ assert!(!in_range(9_000_001, 0));+ assert!(!in_range(0, -18_000_001));+ }++ #[test]+ fn e7_rounds_to_the_nearest_e5() {+ assert_eq!(e7_to_e5(37_7749349), 3_777_493);+ assert_eq!(e7_to_e5(37_7749350), 3_777_494);+ assert_eq!(e7_to_e5(-122_4194249), -12_241_942);+ assert_eq!(e7_to_e5(-122_4194251), -12_241_943);+ assert_eq!(e7_to_e5(1_800_000_000), 18_000_000); } #[test]
scripts/networklocation/geodb_build/src/lib.rs
diff --git a/scripts/networklocation/geodb_build/src/lib.rs b/scripts/networklocation/geodb_build/src/lib.rsindex ab5b807297..841bfe34d5 100644--- a/scripts/networklocation/geodb_build/src/lib.rs+++ b/scripts/networklocation/geodb_build/src/lib.rs@@ -1,4 +1,4 @@-//! Build `geocoder-v3.geodb` from an OpenStreetMap `.osm.pbf`.+//! Build `geocoder.db` from an OpenStreetMap `.osm.pbf`. //! //! Replaces the `osmium tags-filter | osmium export | geocoder_gen.cpp` chain, which needed //! osmium, g++, OpenMP, simdjson and POSIX mmap — so WSL only — and wrote a 101 GB GeoJSONSeq@@ -15,6 +15,7 @@ pub mod codec; pub mod extract; pub mod extract_extra; pub mod format;+pub mod progress; pub mod write; pub mod write_extra;
scripts/networklocation/geodb_build/src/progress.rs
diff --git a/scripts/networklocation/geodb_build/src/progress.rs b/scripts/networklocation/geodb_build/src/progress.rsnew file mode 100644index 0000000000..dbd4e483b3--- /dev/null+++ b/scripts/networklocation/geodb_build/src/progress.rs@@ -0,0 +1,124 @@+//! A stderr progress meter for the steps `osm_ingest` does not cover: materializing ways and+//! relations, and everything in `write` and `verify`. Draws the same+//! `label [pct%] done/total elapsed, ETA` line as the extraction passes, and can be advanced+//! from worker threads, which the parallel column compression needs.++use std::io::Write;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::Instant;++/// Advance this many items between redraws; drawing per item would dominate a tight loop.+const REDRAW_STEP: u64 = 1 << 16;++/// A live meter on one stderr line.+pub struct Progress {+ label: String,+ total: u64,+ done: AtomicU64,+ step: u64,+ start: Instant,+}++impl Progress {+ /// Start a meter over `total` items and draw its 0% line.+ pub fn new(label: impl Into<String>, total: u64) -> Progress {+ Progress::with_step(label, total, REDRAW_STEP)+ }++ /// A meter whose items are each slow (a compressed block, a dictionary), so every one+ /// redraws.+ pub fn coarse(label: impl Into<String>, total: u64) -> Progress {+ Progress::with_step(label, total, 1)+ }++ /// A step with no measurable progress, such as a single sort: shows the label and elapsed+ /// time while it runs, then 100% on [`Progress::finish`].+ pub fn stage(label: impl Into<String>) -> Progress {+ Progress::coarse(label, 1)+ }++ fn with_step(label: impl Into<String>, total: u64, step: u64) -> Progress {+ let p = Progress { label: label.into(), total, done: AtomicU64::new(0), step, start: Instant::now() };+ p.draw(0);+ p+ }++ /// Record one item done.+ #[inline]+ pub fn inc(&self) {+ self.add(1);+ }++ /// Record `n` items done. Safe to call from several threads at once.+ pub fn add(&self, n: u64) {+ let before = self.done.fetch_add(n, Ordering::Relaxed);+ let after = before + n;+ if before / self.step != after / self.step {+ self.draw(after);+ }+ }++ fn draw(&self, done: u64) {+ let done = done.min(self.total);+ let pct = (done * 100).checked_div(self.total).unwrap_or(100);+ let elapsed = self.start.elapsed().as_secs_f64();+ let eta = if done == 0 || self.total == 0 {+ 0.0+ } else {+ elapsed * (self.total - done) as f64 / done as f64+ };+ let mut err = std::io::stderr().lock();+ let _ = write!(+ err,+ "\r{:<28} [{pct:>3}%] {done}/{} {} elapsed, {} ETA ",+ self.label,+ self.total,+ hms(elapsed),+ hms(eta),+ );+ let _ = err.flush();+ }++ /// Snap to 100% and move to a fresh line for the next step.+ pub fn finish(self) {+ self.draw(self.total);+ let _ = writeln!(std::io::stderr().lock());+ }+}++/// Whole seconds as `HhMMmSSs`, dropping units above the largest non-zero one.+fn hms(secs: f64) -> String {+ let s = secs.max(0.0) as u64;+ let (h, m, s) = (s / 3600, (s % 3600) / 60, s % 60);+ if h > 0 {+ format!("{h}h{m:02}m{s:02}s")+ } else if m > 0 {+ format!("{m}m{s:02}s")+ } else {+ format!("{s}s")+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn counts_from_many_threads_add_up() {+ let p = Progress::new("test", 4 * 10_000);+ std::thread::scope(|s| {+ for _ in 0..4 {+ s.spawn(|| (0..10_000).for_each(|_| p.inc()));+ }+ });+ assert_eq!(p.done.load(Ordering::Relaxed), 40_000);+ p.finish();+ }++ #[test]+ fn durations_are_compact() {+ assert_eq!(hms(5.0), "5s");+ assert_eq!(hms(65.0), "1m05s");+ assert_eq!(hms(3725.0), "1h02m05s");+ }+}
scripts/networklocation/geodb_build/src/write.rs
diff --git a/scripts/networklocation/geodb_build/src/write.rs b/scripts/networklocation/geodb_build/src/write.rsindex 20414131b0..f2e38f4e21 100644--- a/scripts/networklocation/geodb_build/src/write.rs+++ b/scripts/networklocation/geodb_build/src/write.rs@@ -1,4 +1,4 @@-//! Assembling extracted rows into a `geocoder-v3.geodb`.+//! Assembling extracted rows into a `geocoder.db`. //! //! Three orderings decide whether the finished database works, and none of them fails loudly: //!@@ -6,19 +6,25 @@ //! outward from the query's cell, so this ordering *is* the spatial index. //! 2. **Searchable dictionaries are UTF-16 sorted**, because the reader binary-searches them //! with a UTF-16 comparator. See `codec::cmp_utf16`.-//! 3. **The forward and name indexes are permutations** into grid order, each sorted by its own-//! key. Get one out of step with its dictionary and forward search returns the wrong rows.+//! 3. **The forward and name indexes point into grid order**, each sorted by its own key. Get+//! one out of step with its dictionary and forward search returns the wrong rows. //! //! [`verify`] reads the finished file back through a path that shares no code with the writer, //! which is the only real check that all three held. +use std::collections::HashSet; use std::fs::File; use std::io::{self, BufWriter, Read, Write}; use std::path::Path; -use crate::codec::{cmp_utf16, encode_column, encode_dict, encode_grid, write_section};+use rayon::prelude::*;++use crate::codec::{+ cmp_utf16, column_blocks, encode_column_with, encode_dict, encode_grid, write_section,+}; use crate::extract::{Row, Strings}; use crate::format::*;+use crate::progress::Progress; /// Sizes of each part of the finished file, for the build report. #[derive(Debug, Default, Clone)]@@ -55,60 +61,58 @@ impl Report { const DICT_NAME: [&str; DICTS] = ["name", "house", "street", "city", "state", "country", "postcode"]; -/// Sort `rows` into grid order and write the database to `out_path`.+/// Sort `rows` into grid order, drop exact duplicates, and write the database to `out_path`. /// /// `strings` holds the dictionaries the rows' ids refer to, filled during extraction. Consumes /// both in place: at planet scale this is tens of gigabytes and copying would double the peak.+/// On return `rows` is exactly what the file holds, in file order. pub fn write(out_path: &Path, rows: &mut Vec<Row>, strings: &mut Strings) -> io::Result<Report> {- // --- ordering -------------------------------------------------------- // Cell first so the grid directory is contiguous, Z-order within it so both coordinate- // columns delta well, then a total tiebreak so two runs produce identical bytes.- //- // The tiebreak compares dictionary ids rather than strings. Ids are assigned in- // first-seen order, which depends on how the PBF's blobs were chunked, so this alone- // would not be deterministic — `sort_rows_deterministically` below re-sorts each tied run- // once the final (content-derived) ids are known.- rows.sort_unstable_by(|a, b| {- cell_id(a.lat_e7, a.lon_e7)- .cmp(&cell_id(b.lat_e7, b.lon_e7))- .then_with(|| {- morton_in_cell(a.lat_e7, a.lon_e7).cmp(&morton_in_cell(b.lat_e7, b.lon_e7))- })- .then_with(|| a.kind.cmp(&b.kind))- .then_with(|| a.lat_e7.cmp(&b.lat_e7))- .then_with(|| a.lon_e7.cmp(&b.lon_e7))- });-- let n = rows.len();+ // Record order is decided once, after the dictionaries, by `sort_rows_deterministically`:+ // only then are ids content-derived, and nothing before it depends on the order. // --- dictionaries ---------------------------------------------------+ let p = Progress::coarse("dictionaries", DICTS as u64); let mut dict_bodies: Vec<Vec<u8>> = Vec::with_capacity(DICTS); let mut dict_counts = Vec::with_capacity(DICTS); let mut remaps: Vec<Vec<u32>> = Vec::with_capacity(DICTS);+ let mut empty_ids: Vec<Option<u32>> = Vec::with_capacity(DICTS); for d in 0..DICTS { let (sorted, remap) = strings.dicts[d].finish(SEARCHABLE[d]); dict_counts.push((DICT_NAME[d], sorted.len()));+ empty_ids.push(sorted.iter().position(|s| s.is_empty()).map(|i| i as u32)); dict_bodies.push(encode_dict(&sorted)?); remaps.push(remap);+ p.inc(); }+ p.finish(); // Interned ids are first-seen order; the file stores final order.- for row in rows.iter_mut() {- for d in 0..DICTS {- row.ids[d] = remaps[d][row.ids[d] as usize];+ let p = Progress::new("remap ids", rows.len() as u64);+ rows.par_chunks_mut(1 << 16).for_each(|chunk| {+ for row in chunk.iter_mut() {+ for d in 0..DICTS {+ row.ids[d] = remaps[d][row.ids[d] as usize];+ } }- }+ p.add(chunk.len() as u64);+ });+ p.finish(); drop(remaps); strings.dicts = Vec::new(); - // Now that ids are content-derived, break the remaining ties by them, so the output does- // not depend on the order the PBF happened to be read in.+ let p = Progress::stage("sort records + dedup"); sort_rows_deterministically(rows);+ // Adjacent ways of one street share their end node, and at e5 a building's node and its+ // outline often land on the same point; both arrive as identical rows, now adjacent.+ rows.dedup();+ p.finish();+ let n = rows.len(); // --- columns --------------------------------------------------------+ let p = Progress::new("columns", n as u64); let mut cols: Vec<Vec<i32>> = (0..COLUMNS).map(|_| Vec::with_capacity(n)).collect(); for r in rows.iter() {- cols[C_LAT].push(r.lat_e7);- cols[C_LON].push(r.lon_e7);+ cols[C_LAT].push(r.lat);+ cols[C_LON].push(r.lon); cols[C_NAME].push(r.ids[D_NAME] as i32); cols[C_HOUSE].push(r.ids[D_HOUSE] as i32); cols[C_STREET].push(r.ids[D_STREET] as i32);@@ -117,20 +121,28 @@ pub fn write(out_path: &Path, rows: &mut Vec<Row>, strings: &mut Strings) -> io: cols[C_COUNTRY].push(r.ids[D_COUNTRY] as i32); cols[C_POSTCODE].push(r.ids[D_POSTCODE] as i32); cols[C_KIND].push(r.kind as i32);+ p.inc(); }+ p.finish(); // --- grid directory -------------------------------------------------- let mut grid: Vec<(i64, u32)> = Vec::new(); for (i, r) in rows.iter().enumerate() {- let cell = cell_id(r.lat_e7, r.lon_e7);+ let cell = cell_id(r.lat, r.lon); if grid.last().map(|&(c, _)| c) != Some(cell) { grid.push((cell, i as u32)); } } - // --- forward index: sorted by (country, state, city, street, house) ---- let mut fwd: Vec<u32> = (0..n as u32).collect();- fwd.sort_unstable_by(|&a, &b| {+ // --- forward index: records with a street, by (country, state, city, street, house) ---+ // A forward query always names a street, so a record without one can never match. Keying+ // on the street rather than on kind keeps a POI or place that carries a full address but+ // no house number findable, which an address-only index silently lost.+ let p = Progress::stage("forward index");+ let empty_street = empty_ids[D_STREET];+ let mut fwd: Vec<u32> =+ (0..n as u32).filter(|&i| Some(rows[i as usize].ids[D_STREET]) != empty_street).collect();+ fwd.par_sort_unstable_by(|&a, &b| { let (x, y) = (&rows[a as usize].ids, &rows[b as usize].ids); x[D_COUNTRY] .cmp(&y[D_COUNTRY])@@ -140,22 +152,26 @@ pub fn write(out_path: &Path, rows: &mut Vec<Row>, strings: &mut Strings) -> io: .then(x[D_HOUSE].cmp(&y[D_HOUSE])) .then(a.cmp(&b)) });+ p.finish(); - // --- name index: every named record, by name id ----------------------- // Records with no name are excluded rather than bunched at id 0: they can never match a- // name query, and leaving them in would put tens of millions of dead entries in front of- // every binary search.- let empty_name = find_empty_name_id(&dict_bodies[D_NAME]);- let mut named: Vec<u32> = (0..n as u32)- .filter(|&i| Some(rows[i as usize].ids[D_NAME]) != empty_name)- .collect();- named.sort_unstable_by(|&a, &b| {+ // --- name index: named records, by name id ---------------------------+ let p = Progress::stage("name index");+ let empty_name = empty_ids[D_NAME];+ let mut named = name_index_records(rows, empty_name);+ named.par_sort_unstable_by(|&a, &b| { rows[a as usize].ids[D_NAME].cmp(&rows[b as usize].ids[D_NAME]).then(a.cmp(&b)) }); let nm_name: Vec<i32> = named.iter().map(|&i| rows[i as usize].ids[D_NAME] as i32).collect(); let nm_rec: Vec<i32> = named.iter().map(|&i| i as i32).collect();+ drop(named);+ p.finish(); // --- write ------------------------------------------------------------+ // Compression is the slow step, so it gets a meter over every block.+ let p = Progress::coarse(+ "compress + write",+ COLUMNS as u64 * column_blocks(n) + column_blocks(fwd.len()) + 2 * column_blocks(nm_name.len()),+ ); let mut out = BufWriter::with_capacity(1 << 22, File::create(out_path)?); out.write_all(&MAGIC.to_be_bytes())?; out.write_all(&VERSION.to_be_bytes())?;@@ -167,58 +183,63 @@ pub fn write(out_path: &Path, rows: &mut Vec<Row>, strings: &mut Strings) -> io: } drop(dict_bodies); for c in 0..COLUMNS {- let body = encode_column(&cols[c], DELTA[c])?;+ let body = encode_column_with(&cols[c], DELTA[c], Some(&p))?; report.columns.push((COL_NAME[c], write_section(&mut out, &body)?)); cols[c] = Vec::new(); } report.grid = write_section(&mut out, &encode_grid(&grid))?; let fwd_col: Vec<i32> = fwd.iter().map(|&v| v as i32).collect();- report.fwd = write_section(&mut out, &encode_column(&fwd_col, true)?)?;- report.name_index = write_section(&mut out, &encode_column(&nm_name, true)?)?- + write_section(&mut out, &encode_column(&nm_rec, false)?)?;+ report.fwd = write_section(&mut out, &encode_column_with(&fwd_col, true, Some(&p))?)?;+ report.name_index = write_section(&mut out, &encode_column_with(&nm_name, true, Some(&p))?)?+ + write_section(&mut out, &encode_column_with(&nm_rec, false, Some(&p))?)?; out.flush()?;+ p.finish(); report.dict_counts = dict_counts; report.total = std::fs::metadata(out_path)?.len(); Ok(report) } -/// Break ties among records that share a cell, Z-order, kind and position, using their final-/// dictionary ids.+/// Records that belong in the name index, in grid order. ///-/// Without this the output depends on the order the PBF's blobs happened to be chunked into,-/// because interned ids are assigned in first-seen order. Sorting once more on the *final*-/// ids — which are derived from the content, not the reading order — makes two runs over the-/// same input produce identical bytes.-fn sort_rows_deterministically(rows: &mut [Row]) {- rows.sort_unstable_by(|a, b| {- cell_id(a.lat_e7, a.lon_e7)- .cmp(&cell_id(b.lat_e7, b.lon_e7))- .then_with(|| {- morton_in_cell(a.lat_e7, a.lon_e7).cmp(&morton_in_cell(b.lat_e7, b.lon_e7))- })- .then_with(|| a.kind.cmp(&b.kind))- .then_with(|| a.lat_e7.cmp(&b.lat_e7))- .then_with(|| a.lon_e7.cmp(&b.lon_e7))- .then_with(|| a.ids.cmp(&b.ids))- });-}--/// Id of the empty string in an encoded dictionary, if it holds one.-fn find_empty_name_id(dict_body: &[u8]) -> Option<u32> {- let raw = zstd::decode_all(dict_body.get(8..)?).ok()?;- let count = u32::from_be_bytes(raw.get(0..4)?.try_into().ok()?);- let mut p = 4usize;- for id in 0..count {- let len = u32::from_be_bytes(raw.get(p..p + 4)?.try_into().ok()?) as usize;- p += 4;- if len == 0 {- return Some(id);+/// Unnamed records can never match a name query. A street is sampled every few hundred metres,+/// so indexing every sample would repeat one name dozens of times; one entry per street name per+/// grid cell still finds the street and still puts the hit near the right place.+fn name_index_records(rows: &[Row], empty_name: Option<u32>) -> Vec<u32> {+ let mut out = Vec::new();+ let mut cell = i64::MIN;+ let mut streets_in_cell: HashSet<u32> = HashSet::new();+ for (i, r) in rows.iter().enumerate() {+ if Some(r.ids[D_NAME]) == empty_name {+ continue;+ }+ if r.kind == K_STREET {+ // Rows are in cell order, so a per-cell set stays small at planet scale.+ let c = cell_id(r.lat, r.lon);+ if c != cell {+ cell = c;+ streets_in_cell.clear();+ }+ if !streets_in_cell.insert(r.ids[D_NAME]) {+ continue;+ } }- p += len;+ out.push(i as u32); }- None+ out+}++/// Order records by grid cell, then Z-order within the cell, then every remaining field.+///+/// Cell first so the grid directory is contiguous, Z-order so both coordinate columns delta+/// well. The key is total over the row's content, and the ids are already the final,+/// content-derived ones, so two runs over the same input produce identical bytes whatever+/// order the PBF was read in.+fn sort_rows_deterministically(rows: &mut [Row]) {+ rows.par_sort_unstable_by_key(|r| {+ (cell_id(r.lat, r.lon), morton_in_cell(r.lat, r.lon), r.kind, r.lat, r.lon, r.ids)+ }); } // --------------------------------------------------------------------------- verify@@ -230,8 +251,10 @@ fn find_empty_name_id(dict_body: &[u8]) -> Option<u32> { /// written in a different order from the one the grid describes, an off-by-one in a block /// directory. pub fn verify(path: &Path, expected: &[Row]) -> io::Result<()> {+ let p = Progress::stage("verify: read back"); let mut buf = Vec::new(); let _ = File::open(path)?.read_to_end(&mut buf)?;+ p.finish(); let bad = |m: String| io::Error::new(io::ErrorKind::InvalidData, m); let rd32 = |p: usize| -> u32 {@@ -267,6 +290,7 @@ pub fn verify(path: &Path, expected: &[Row]) -> io::Result<()> { return Err(bad(format!("{} trailing byte(s)", buf.len() - cursor))); } + let p = Progress::stage("verify: dictionaries"); let dicts: Vec<Vec<String>> = sections[..DICTS].iter().map(|s| decode_dict(s)).collect::<io::Result<_>>()?; for (d, dict) in dicts.iter().enumerate() {@@ -281,58 +305,44 @@ pub fn verify(path: &Path, expected: &[Row]) -> io::Result<()> { } } }-- let cols: Vec<Vec<i32>> = (0..COLUMNS)- .map(|c| decode_column(sections[DICTS + c], DELTA[c]))- .collect::<io::Result<_>>()?;- for (c, col) in cols.iter().enumerate() {+ p.finish();++ // One column at a time: each is decoded, compared field by field with `expected`, and+ // dropped. Holding all ten at once doubled the planet's peak memory (10 x 4 bytes x n on+ // top of the rows themselves) and pushed the read-back into paging. Once every column has+ // matched, `expected` *is* the file's content, so the index checks below read from it.+ let col_sections = §ions[DICTS..DICTS + COLUMNS];+ let blocks: u64 = col_sections+ .iter()+ .map(|s| s.get(4..8).map_or(0, |b| u32::from_be_bytes(b.try_into().unwrap()) as u64))+ .sum();+ let p = Progress::coarse("verify: columns", blocks);+ for c in 0..COLUMNS {+ let col = decode_column_with(col_sections[c], DELTA[c], Some(&p))?; if col.len() != n { return Err(bad(format!("column {} has {} values, expected {n}", COL_NAME[c], col.len()))); }- }-- let text = |c: usize, d: usize, i: usize| -> io::Result<&str> {- let id = cols[c][i];- dicts[d]- .get(id as usize)- .map(|s| s.as_str())- .ok_or_else(|| bad(format!("record {i}: {} id {id} out of range", COL_NAME[c])))- };-- for i in 0..n {- let e = &expected[i];- if cols[C_LAT][i] != e.lat_e7 || cols[C_LON][i] != e.lon_e7 {+ let dict = (C_NAME..=C_POSTCODE).contains(&c).then(|| &dicts[c - C_NAME]);+ let mismatch = col.par_iter().zip(expected.par_iter()).position_first(|(&v, e)| {+ let want = match c {+ C_LAT => e.lat,+ C_LON => e.lon,+ C_KIND => e.kind as i32,+ _ => e.ids[c - C_NAME] as i32,+ };+ v != want || dict.is_some_and(|d| v < 0 || v as usize >= d.len())+ });+ if let Some(i) = mismatch { return Err(bad(format!(- "record {i}: coords ({}, {}) != ({}, {})",- cols[C_LAT][i], cols[C_LON][i], e.lat_e7, e.lon_e7+ "record {i}: {} is {} on disk; expected {:?}",+ COL_NAME[c], col[i], expected[i] ))); }- if cols[C_KIND][i] != e.kind as i32 {- return Err(bad(format!("record {i}: kind {} != {}", cols[C_KIND][i], e.kind)));- }- // `write` rewrites each row's ids to their final, dictionary-order values, so the rows- // handed back are exactly what should be on disk. Every id must also address a real- // dictionary entry, which is what `text` checks.- for (c, d, label) in [- (C_NAME, D_NAME, "name"),- (C_HOUSE, D_HOUSE, "house"),- (C_STREET, D_STREET, "street"),- (C_CITY, D_CITY, "city"),- (C_STATE, D_STATE, "state"),- (C_COUNTRY, D_COUNTRY, "country"),- (C_POSTCODE, D_POSTCODE, "postcode"),- ] {- let _ = text(c, d, i)?;- if cols[c][i] != e.ids[d] as i32 {- return Err(bad(format!(- "record {i}: {label} id {} != {}",- cols[c][i], e.ids[d]- )));- }- } }+ p.finish(); // The grid must describe the record order that was actually written.+ let p = Progress::stage("verify: indexes"); let grid = decode_grid(sections[DICTS + COLUMNS])?; let mut prev_cell = i64::MIN; for &(cell, start) in &grid {@@ -341,40 +351,48 @@ pub fn verify(path: &Path, expected: &[Row]) -> io::Result<()> { } prev_cell = cell; let s = start as usize;- if s >= n || cell_id(cols[C_LAT][s], cols[C_LON][s]) != cell {+ if s >= n || cell_id(expected[s].lat, expected[s].lon) != cell { return Err(bad(format!("grid entry for cell {cell} points at the wrong record"))); } } for i in 1..n {- let a = cell_id(cols[C_LAT][i - 1], cols[C_LON][i - 1]);- let b = cell_id(cols[C_LAT][i], cols[C_LON][i]);- if b < a {+ let (a, b) = (&expected[i - 1], &expected[i]);+ if cell_id(b.lat, b.lon) < cell_id(a.lat, a.lon) { return Err(bad(format!("records are not in cell order at {i}"))); } } - // Both indexes must be permutations of valid record ids, each sorted by its own key.+ // The forward index must hold every record with a street exactly once and nothing else,+ // sorted by its key; the name index must hold valid named records, sorted by name id.+ let empty_street = dicts[D_STREET].iter().position(|s| s.is_empty()).map(|i| i as u32);+ let has_street = |r: &Row| Some(r.ids[D_STREET]) != empty_street; let fwd = decode_column(sections[DICTS + COLUMNS + 1], true)?;- if fwd.len() != n {- return Err(bad(format!("forward index has {} entries, expected {n}", fwd.len())));+ let with_street = expected.iter().filter(|r| has_street(r)).count();+ if fwd.len() != with_street {+ return Err(bad(format!(+ "forward index has {} entries, expected {with_street} records with a street",+ fwd.len()+ ))); } let mut seen = vec![false; n];- let mut prev_key: Option<[i32; 5]> = None;+ let mut prev_key: Option<[u32; 5]> = None; for &r in &fwd { let i = r as usize; if i >= n || seen[i] {- return Err(bad("forward index is not a permutation".into()));+ return Err(bad("forward index repeats or overruns a record".into()));+ }+ let e = &expected[i];+ if !has_street(e) {+ return Err(bad(format!("forward index points at record {i}, which has no street"))); } seen[i] = true;- let key =- [cols[C_COUNTRY][i], cols[C_STATE][i], cols[C_CITY][i], cols[C_STREET][i], cols[C_HOUSE][i]];- if let Some(p) = prev_key {- if key < p {- return Err(bad("forward index is not sorted by its key".into()));- }+ let key = [e.ids[D_COUNTRY], e.ids[D_STATE], e.ids[D_CITY], e.ids[D_STREET], e.ids[D_HOUSE]];+ if prev_key.is_some_and(|p| key < p) {+ return Err(bad("forward index is not sorted by its key".into())); } prev_key = Some(key); }+ drop(seen); let nm_name = decode_column(sections[DICTS + COLUMNS + 2], true)?; let nm_rec = decode_column(sections[DICTS + COLUMNS + 3], false)?;@@ -391,39 +409,75 @@ pub fn verify(path: &Path, expected: &[Row]) -> io::Result<()> { if i >= n { return Err(bad(format!("name index entry {k} points past the end"))); }- if cols[C_NAME][i] != name_id {+ if expected[i].ids[D_NAME] as i32 != name_id { return Err(bad(format!("name index entry {k} disagrees with the name column"))); } if dicts[D_NAME][name_id as usize].is_empty() { return Err(bad(format!("name index entry {k} points at an unnamed record"))); } }+ p.finish(); Ok(()) } +/// Decode a whole blocked dictionary (see `codec::encode_dict`), checking that every block+/// holds the expected number of strings and that the uncompressed first-string table agrees+/// with what each block actually starts with, since the reader trusts that table to search. pub(crate) fn decode_dict(body: &[u8]) -> io::Result<Vec<String>> { let bad = |m: &str| io::Error::new(io::ErrorKind::InvalidData, m.to_string());- if body.len() < 8 {- return Err(bad("dictionary section too short"));+ let rd32 = |p: usize| -> io::Result<usize> {+ let b = body.get(p..p + 4).ok_or_else(|| bad("dictionary section truncated"))?;+ Ok(u32::from_be_bytes(b.try_into().map_err(|_| bad("short dict"))?) as usize)+ };+ let (count, per, blocks) = (rd32(0)?, rd32(4)?, rd32(8)?);+ if per == 0 || blocks != count.div_ceil(per) {+ return Err(bad("dictionary block count does not match its string count")); }- let raw = zstd::decode_all(&body[8..])?;- let count = u32::from_be_bytes(raw[0..4].try_into().map_err(|_| bad("short dict"))?) as usize;+ let first_dir = 12;+ let firsts = first_dir + blocks * 4;+ let firsts_len = if blocks == 0 { 0 } else { rd32(firsts - 4)? };+ let block_dir = firsts + firsts_len;+ let data = block_dir + blocks * 4;+ let mut out = Vec::with_capacity(count);- let mut p = 4usize;- for _ in 0..count {- let len =- u32::from_be_bytes(raw[p..p + 4].try_into().map_err(|_| bad("short dict"))?) as usize;- p += 4;- out.push(- String::from_utf8(raw[p..p + len].to_vec())- .map_err(|_| bad("dictionary entry is not UTF-8"))?,- );- p += len;+ for b in 0..blocks {+ let start = if b == 0 { 0 } else { rd32(block_dir + (b - 1) * 4)? };+ let end = rd32(block_dir + b * 4)?;+ let comp = body.get(data + start..data + end).ok_or_else(|| bad("dictionary block truncated"))?;+ let raw = zstd::decode_all(comp)?;+ let want = per.min(count - b * per);+ let mut p = 0usize;+ for k in 0..want {+ let len = raw.get(p..p + 4).ok_or_else(|| bad("dictionary block ran out"))?;+ let len = u32::from_be_bytes(len.try_into().map_err(|_| bad("short dict"))?) as usize;+ p += 4;+ let s = raw.get(p..p + len).ok_or_else(|| bad("dictionary block ran out"))?;+ let s = String::from_utf8(s.to_vec()).map_err(|_| bad("dictionary entry is not UTF-8"))?;+ p += len;+ if k == 0 {+ let f0 = if b == 0 { 0 } else { rd32(first_dir + (b - 1) * 4)? };+ let f1 = rd32(first_dir + b * 4)?;+ if body.get(firsts + f0..firsts + f1) != Some(s.as_bytes()) {+ return Err(bad("first-string table disagrees with its block"));+ }+ }+ out.push(s);+ }+ if p != raw.len() {+ return Err(bad("dictionary block has trailing bytes"));+ }+ }+ if data + if blocks == 0 { 0 } else { rd32(data - 4)? } != body.len() {+ return Err(bad("dictionary section has trailing bytes")); } Ok(out) } pub(crate) fn decode_column(body: &[u8], delta: bool) -> io::Result<Vec<i32>> {+ decode_column_with(body, delta, None)+}++fn decode_column_with(body: &[u8], delta: bool, progress: Option<&Progress>) -> io::Result<Vec<i32>> { let bad = |m: &str| io::Error::new(io::ErrorKind::InvalidData, m.to_string()); let rd32 = |p: usize| -> u32 { u32::from_be_bytes([body[p], body[p + 1], body[p + 2], body[p + 3]])@@ -433,12 +487,14 @@ pub(crate) fn decode_column(body: &[u8], delta: bool) -> io::Result<Vec<i32>> { } let n = rd32(0) as usize; let blocks = rd32(4) as usize;- let mut offset = 8 + blocks * 8;+ let data = 8 + blocks * 8; let mut out = Vec::with_capacity(n);+ let mut start = 0usize; for b in 0..blocks {- let comp_len = rd32(8 + b * 8 + 4) as usize;- let raw = zstd::decode_all(&body[offset..offset + comp_len])?;- offset += comp_len;+ let end = rd32(8 + b * 8 + 4) as usize;+ let comp = body.get(data + start..data + end).ok_or_else(|| bad("column block out of range"))?;+ let raw = zstd::decode_all(comp)?;+ start = end; let mut p = 0usize; let mut prev = 0i32; let count = n.saturating_sub(b * BLOCK).min(BLOCK);@@ -459,6 +515,9 @@ pub(crate) fn decode_column(body: &[u8], delta: bool) -> io::Result<Vec<i32>> { out.push(value); prev = value; }+ if let Some(p) = progress {+ p.inc();+ } } Ok(out) }
scripts/networklocation/geodb_build/src/write_extra.rs
diff --git a/scripts/networklocation/geodb_build/src/write_extra.rs b/scripts/networklocation/geodb_build/src/write_extra.rsindex 41b95311c7..eccc67d7bf 100644--- a/scripts/networklocation/geodb_build/src/write_extra.rs+++ b/scripts/networklocation/geodb_build/src/write_extra.rs@@ -56,8 +56,8 @@ mod tests { strings.dicts[D_POSTCODE].intern(&format!("{:05}", i % 9000)), ]; Row {- lat_e7: (next() % 1_800_000_000) as i64 as i32 - 900_000_000,- lon_e7: ((next() % 3_600_000_000) as i64 - 1_800_000_000) as i32,+ lat: (next() % 18_000_000) as i64 as i32 - 9_000_000,+ lon: ((next() % 36_000_000) as i64 - 18_000_000) as i32, kind, ids, }@@ -66,11 +66,42 @@ mod tests { (rows, strings) } + /// Split a finished database into its sections.+ fn sections(buf: &[u8]) -> Vec<&[u8]> {+ let mut cursor = 12usize;+ let mut out = Vec::new();+ for _ in 0..SECTIONS {+ let size = u32::from_be_bytes(buf[cursor..cursor + 4].try_into().unwrap()) as usize;+ cursor += 4;+ out.push(&buf[cursor..cursor + size]);+ cursor += size;+ }+ out+ }++ /// A street sample named `name` at an e5 position.+ fn street(strings: &mut Strings, name: &str, lat: i32, lon: i32) -> Row {+ Row {+ lat,+ lon,+ kind: K_STREET,+ ids: [+ strings.dicts[D_NAME].intern(name),+ strings.dicts[D_HOUSE].intern(""),+ strings.dicts[D_STREET].intern(""),+ strings.dicts[D_CITY].intern(""),+ strings.dicts[D_STATE].intern(""),+ strings.dicts[D_COUNTRY].intern(""),+ strings.dicts[D_POSTCODE].intern(""),+ ],+ }+ }+ #[test] fn a_database_round_trips_through_the_verifier() { let d = TempDir::new("roundtrip"); let (mut rows, mut strings) = sample_rows(BLOCK * 2 + 123);- let out = d.0.join("geocoder-v3.geodb");+ let out = d.0.join("geocoder.db"); let report = write(&out, &mut rows, &mut strings).unwrap(); assert_eq!(report.n, rows.len()); assert!(report.total > 0);@@ -87,12 +118,12 @@ mod tests { let _ = write(&out, &mut rows, &mut strings).unwrap(); for w in rows.windows(2) { let (a, b) = (&w[0], &w[1]);- let ca = cell_id(a.lat_e7, a.lon_e7);- let cb = cell_id(b.lat_e7, b.lon_e7);+ let ca = cell_id(a.lat, a.lon);+ let cb = cell_id(b.lat, b.lon); assert!(ca <= cb, "cells out of order"); if ca == cb { assert!(- morton_in_cell(a.lat_e7, a.lon_e7) <= morton_in_cell(b.lat_e7, b.lon_e7),+ morton_in_cell(a.lat, a.lon) <= morton_in_cell(b.lat, b.lon), "z-order broken inside a cell" ); }@@ -121,8 +152,8 @@ mod tests { .iter() .enumerate() .map(|(i, name)| Row {- lat_e7: 37_0000000 + i as i32 * 1000,- lon_e7: -122_0000000,+ lat: 3_700_000 + i as i32 * 10,+ lon: -12_200_000, kind: K_POI, ids: [ strings.dicts[D_NAME].intern(name),@@ -151,24 +182,99 @@ mod tests { fn the_name_index_covers_named_records_and_excludes_the_rest() { let d = TempDir::new("nameidx"); let (mut rows, mut strings) = sample_rows(500);- let named = rows.iter().filter(|r| r.kind != K_ADDRESS).count(); let out = d.0.join("n.geodb"); let _ = write(&out, &mut rows, &mut strings).unwrap(); verify(&out, &rows).unwrap(); + let mut street_keys = std::collections::HashSet::new();+ let named = rows+ .iter()+ .filter(|r| match r.kind {+ K_ADDRESS => false,+ K_STREET => street_keys.insert((cell_id(r.lat, r.lon), r.ids[D_NAME])),+ _ => true,+ })+ .count(); let buf = std::fs::read(&out).unwrap();- let mut cursor = 12usize;- let mut sections = Vec::new();- for _ in 0..SECTIONS {- let size = u32::from_be_bytes(buf[cursor..cursor + 4].try_into().unwrap()) as usize;- cursor += 4;- sections.push(&buf[cursor..cursor + size]);- cursor += size;- }- let nm_rec = decode_column(sections[DICTS + COLUMNS + 3], false).unwrap();+ let nm_rec = decode_column(sections(&buf)[DICTS + COLUMNS + 3], false).unwrap(); assert_eq!(nm_rec.len(), named, "every named record must be indexed, and only those"); } + #[test]+ fn a_street_is_name_indexed_once_per_cell() {+ let d = TempDir::new("streetidx");+ let mut strings = Strings::default();+ // Three samples of one street inside one cell, and a fourth a cell to the north.+ let mut rows = vec![+ street(&mut strings, "Elm St", 3_700_010, -12_200_010),+ street(&mut strings, "Elm St", 3_700_200, -12_200_010),+ street(&mut strings, "Elm St", 3_700_400, -12_200_010),+ street(&mut strings, "Elm St", 3_700_010 + CELL as i32, -12_200_010),+ ];+ let out = d.0.join("s.geodb");+ let _ = write(&out, &mut rows, &mut strings).unwrap();+ verify(&out, &rows).unwrap();+ let buf = std::fs::read(&out).unwrap();+ let nm_rec = decode_column(sections(&buf)[DICTS + COLUMNS + 3], false).unwrap();+ assert_eq!(rows.len(), 4, "every sample stays a record for reverse lookup");+ assert_eq!(nm_rec.len(), 2, "one name entry per cell: {nm_rec:?}");+ }++ #[test]+ fn the_forward_index_holds_exactly_the_records_with_a_street() {+ let d = TempDir::new("fwd");+ let (mut rows, mut strings) = sample_rows(800);+ let out = d.0.join("f.geodb");+ let _ = write(&out, &mut rows, &mut strings).unwrap();+ verify(&out, &rows).unwrap();+ let buf = std::fs::read(&out).unwrap();+ let fwd = decode_column(sections(&buf)[DICTS + COLUMNS + 1], true).unwrap();+ let streets = decode_dict(sections(&buf)[D_STREET]).unwrap();+ let has_street = |i: usize| !streets[rows[i].ids[D_STREET] as usize].is_empty();+ let expected = (0..rows.len()).filter(|&i| has_street(i)).count();+ assert!(expected > 0 && expected < rows.len(), "premise: some records lack a street");+ assert_eq!(fwd.len(), expected);+ assert!(fwd.iter().all(|&i| has_street(i as usize)));+ }++ #[test]+ fn a_place_with_a_full_address_but_no_house_number_is_forward_indexed() {+ // Amundsen-Scott South Pole Station is a place tagged with street/city/state/country+ // and no house number. An address-only forward index made it unfindable.+ let d = TempDir::new("fwdplace");+ let mut strings = Strings::default();+ let mut place = street(&mut strings, "South Pole Station", -9_000_000, 0);+ place.kind = K_PLACE;+ place.ids[D_STREET] = strings.dicts[D_STREET].intern("PSC 798");+ place.ids[D_CITY] = strings.dicts[D_CITY].intern("APO");+ place.ids[D_STATE] = strings.dicts[D_STATE].intern("AP");+ place.ids[D_COUNTRY] = strings.dicts[D_COUNTRY].intern("US");+ let lone = street(&mut strings, "Elm St", 3_700_010, -12_200_010);+ let mut rows = vec![place, lone];+ let out = d.0.join("p.geodb");+ let _ = write(&out, &mut rows, &mut strings).unwrap();+ verify(&out, &rows).unwrap();+ let buf = std::fs::read(&out).unwrap();+ let fwd = decode_column(sections(&buf)[DICTS + COLUMNS + 1], true).unwrap();+ let place_at = rows.iter().position(|r| r.kind == K_PLACE).unwrap() as i32;+ assert_eq!(fwd, vec![place_at], "the place is indexed; the bare street sample is not");+ }++ #[test]+ fn identical_rows_are_written_once() {+ let d = TempDir::new("dedup");+ let mut strings = Strings::default();+ let a = street(&mut strings, "Elm St", 3_700_010, -12_200_010);+ let b = street(&mut strings, "Oak St", 3_700_010, -12_200_010);+ // Two ways of Elm St meeting at a shared node, plus a different street at that node.+ let mut rows = vec![a, b, a];+ let out = d.0.join("d.geodb");+ let report = write(&out, &mut rows, &mut strings).unwrap();+ assert_eq!(report.n, 2, "the shared end point must be stored once");+ assert_eq!(rows.len(), 2);+ verify(&out, &rows).unwrap();+ }+ #[test] fn a_single_record_database_is_valid() { let d = TempDir::new("one");