Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / networklocation / geodb_build / src / write.rs

write.rs429 lines · 17.2 KiBRaw
1//! Assembling extracted rows into a `geocoder.db`.
2//!
3//! Three orderings decide whether the finished database works, and none of them fails loudly:
4//!
5//! 1. **Records are ordered by grid cell, then Z-order within the cell.** Reverse lookup walks
6//! outward from the query's cell, so this ordering *is* the spatial index.
7//! 2. **Searchable dictionaries are UTF-16 sorted**, because the reader binary-searches them
8//! with a UTF-16 comparator. See `codec::cmp_utf16`.
9//! 3. **The forward and name indexes point into grid order**, each sorted by its own key. Get
10//! one out of step with its dictionary and forward search returns the wrong rows.
11//!
12//! [`verify`] reads the finished file back through a path that shares no code with the writer,
13//! which is the only real check that all three held.
14
15use std::collections::HashSet;
16use std::fs::File;
17use std::io::{self, BufWriter, Read, Write};
18use std::path::Path;
19
20use rayon::prelude::*;
21
22use crate::codec::{
23 cmp_utf16, column_blocks, encode_column_with, encode_dict, encode_grid, write_section,
24};
25use crate::extract::{Row, Strings};
26use crate::format::*;
27use crate::progress::Progress;
28
29/// Sizes of each part of the finished file, for the build report.
30#[derive(Debug, Default, Clone)]
31pub struct Report {
32 /// Records written.
33 pub n: usize,
34 /// Total file size.
35 pub total: u64,
36 /// `(name, bytes)` per dictionary.
37 pub dicts: Vec<(&'static str, u64)>,
38 /// `(name, bytes)` per column.
39 pub columns: Vec<(&'static str, u64)>,
40 /// Grid directory size.
41 pub grid: u64,
42 /// Forward index size.
43 pub fwd: u64,
44 /// Name index size, both sections.
45 pub name_index: u64,
46 /// Distinct strings per dictionary.
47 pub dict_counts: Vec<(&'static str, usize)>,
48}
49
50impl Report {
51 /// Bits per record, the number worth watching between builds.
52 pub fn bits_per_record(&self) -> f64 {
53 if self.n == 0 {
54 0.0
55 } else {
56 (self.total as f64 * 8.0) / self.n as f64
57 }
58 }
59}
60
61const DICT_NAME: [&str; DICTS] =
62 ["name", "house", "street", "city", "state", "country", "postcode"];
63
64/// Sort `rows` into grid order, drop exact duplicates, and write the database to `out_path`.
65///
66/// `strings` holds the dictionaries the rows' ids refer to, filled during extraction. Consumes
67/// both in place: at planet scale this is tens of gigabytes and copying would double the peak.
68/// On return `rows` is exactly what the file holds, in file order.
69pub fn write(out_path: &Path, rows: &mut Vec<Row>, strings: &mut Strings) -> io::Result<Report> {
70 // Record order is decided once, after the dictionaries, by `sort_rows_deterministically`:
71 // only then are ids content-derived, and nothing before it depends on the order.
72
73 // --- dictionaries ---------------------------------------------------
74 let p = Progress::coarse("dictionaries", DICTS as u64);
75 let mut dict_bodies: Vec<Vec<u8>> = Vec::with_capacity(DICTS);
76 let mut dict_counts = Vec::with_capacity(DICTS);
77 let mut remaps: Vec<Vec<u32>> = Vec::with_capacity(DICTS);
78 let mut empty_ids: Vec<Option<u32>> = Vec::with_capacity(DICTS);
79 for d in 0..DICTS {
80 let (sorted, remap) = strings.dicts[d].finish(SEARCHABLE[d]);
81 dict_counts.push((DICT_NAME[d], sorted.len()));
82 empty_ids.push(sorted.iter().position(|s| s.is_empty()).map(|i| i as u32));
83 dict_bodies.push(encode_dict(&sorted)?);
84 remaps.push(remap);
85 p.inc();
86 }
87 p.finish();
88 // Interned ids are first-seen order; the file stores final order.
89 let p = Progress::new("remap ids", rows.len() as u64);
90 rows.par_chunks_mut(1 << 16).for_each(|chunk| {
91 for row in chunk.iter_mut() {
92 for d in 0..DICTS {
93 row.ids[d] = remaps[d][row.ids[d] as usize];
94 }
95 }
96 p.add(chunk.len() as u64);
97 });
98 p.finish();
99 drop(remaps);
100 strings.dicts = Vec::new();
101
102 let p = Progress::stage("sort records + dedup");
103 sort_rows_deterministically(rows);
104 // Adjacent ways of one street share their end node, and at e5 a building's node and its
105 // outline often land on the same point; both arrive as identical rows, now adjacent.
106 rows.dedup();
107 p.finish();
108 let n = rows.len();
109
110 // --- columns --------------------------------------------------------
111 let p = Progress::new("columns", n as u64);
112 let mut cols: Vec<Vec<i32>> = (0..COLUMNS).map(|_| Vec::with_capacity(n)).collect();
113 for r in rows.iter() {
114 cols[C_LAT].push(r.lat);
115 cols[C_LON].push(r.lon);
116 cols[C_NAME].push(r.ids[D_NAME] as i32);
117 cols[C_HOUSE].push(r.ids[D_HOUSE] as i32);
118 cols[C_STREET].push(r.ids[D_STREET] as i32);
119 cols[C_CITY].push(r.ids[D_CITY] as i32);
120 cols[C_STATE].push(r.ids[D_STATE] as i32);
121 cols[C_COUNTRY].push(r.ids[D_COUNTRY] as i32);
122 cols[C_POSTCODE].push(r.ids[D_POSTCODE] as i32);
123 cols[C_KIND].push(r.kind as i32);
124 p.inc();
125 }
126 p.finish();
127
128 // --- grid directory --------------------------------------------------
129 let mut grid: Vec<(i64, u32)> = Vec::new();
130 for (i, r) in rows.iter().enumerate() {
131 let cell = cell_id(r.lat, r.lon);
132 if grid.last().map(|&(c, _)| c) != Some(cell) {
133 grid.push((cell, i as u32));
134 }
135 }
136
137 // --- forward index: records with a street, by (country, state, city, street, house) ---
138 // A forward query always names a street, so a record without one can never match. Keying
139 // on the street rather than on kind keeps a POI or place that carries a full address but
140 // no house number findable, which an address-only index silently lost.
141 let p = Progress::stage("forward index");
142 let empty_street = empty_ids[D_STREET];
143 let mut fwd: Vec<u32> =
144 (0..n as u32).filter(|&i| Some(rows[i as usize].ids[D_STREET]) != empty_street).collect();
145 fwd.par_sort_unstable_by(|&a, &b| {
146 let (x, y) = (&rows[a as usize].ids, &rows[b as usize].ids);
147 x[D_COUNTRY]
148 .cmp(&y[D_COUNTRY])
149 .then(x[D_STATE].cmp(&y[D_STATE]))
150 .then(x[D_CITY].cmp(&y[D_CITY]))
151 .then(x[D_STREET].cmp(&y[D_STREET]))
152 .then(x[D_HOUSE].cmp(&y[D_HOUSE]))
153 .then(a.cmp(&b))
154 });
155 p.finish();
156
157 // --- name index: named records, by name id ---------------------------
158 let p = Progress::stage("name index");
159 let empty_name = empty_ids[D_NAME];
160 let mut named = name_index_records(rows, empty_name);
161 named.par_sort_unstable_by(|&a, &b| {
162 rows[a as usize].ids[D_NAME].cmp(&rows[b as usize].ids[D_NAME]).then(a.cmp(&b))
163 });
164 let nm_name: Vec<i32> = named.iter().map(|&i| rows[i as usize].ids[D_NAME] as i32).collect();
165 let nm_rec: Vec<i32> = named.iter().map(|&i| i as i32).collect();
166 drop(named);
167 p.finish();
168
169 // --- write ------------------------------------------------------------
170 // Compression is the slow step, so it gets a meter over every block.
171 let p = Progress::coarse(
172 "compress + write",
173 COLUMNS as u64 * column_blocks(n)
174 + column_blocks(fwd.len())
175 + 2 * column_blocks(nm_name.len()),
176 );
177 let mut out = BufWriter::with_capacity(1 << 22, File::create(out_path)?);
178 out.write_all(&MAGIC.to_be_bytes())?;
179 out.write_all(&VERSION.to_be_bytes())?;
180 out.write_all(&(n as u32).to_be_bytes())?;
181
182 let mut report = Report { n, ..Report::default() };
183 for d in 0..DICTS {
184 report.dicts.push((DICT_NAME[d], write_section(&mut out, &dict_bodies[d])?));
185 }
186 drop(dict_bodies);
187 for c in 0..COLUMNS {
188 let body = encode_column_with(&cols[c], DELTA[c], Some(&p))?;
189 report.columns.push((COL_NAME[c], write_section(&mut out, &body)?));
190 cols[c] = Vec::new();
191 }
192 report.grid = write_section(&mut out, &encode_grid(&grid))?;
193
194 let fwd_col: Vec<i32> = fwd.iter().map(|&v| v as i32).collect();
195 report.fwd = write_section(&mut out, &encode_column_with(&fwd_col, true, Some(&p))?)?;
196 report.name_index = write_section(&mut out, &encode_column_with(&nm_name, true, Some(&p))?)?
197 + write_section(&mut out, &encode_column_with(&nm_rec, false, Some(&p))?)?;
198
199 out.flush()?;
200 p.finish();
201 report.dict_counts = dict_counts;
202 report.total = std::fs::metadata(out_path)?.len();
203 Ok(report)
204}
205
206/// Records that belong in the name index, in grid order.
207///
208/// Unnamed records can never match a name query. A street is sampled every few hundred metres,
209/// so indexing every sample would repeat one name dozens of times; one entry per street name per
210/// grid cell still finds the street and still puts the hit near the right place.
211fn name_index_records(rows: &[Row], empty_name: Option<u32>) -> Vec<u32> {
212 let mut out = Vec::new();
213 let mut cell = i64::MIN;
214 let mut streets_in_cell: HashSet<u32> = HashSet::new();
215 for (i, r) in rows.iter().enumerate() {
216 if Some(r.ids[D_NAME]) == empty_name {
217 continue;
218 }
219 if r.kind == K_STREET {
220 // Rows are in cell order, so a per-cell set stays small at planet scale.
221 let c = cell_id(r.lat, r.lon);
222 if c != cell {
223 cell = c;
224 streets_in_cell.clear();
225 }
226 if !streets_in_cell.insert(r.ids[D_NAME]) {
227 continue;
228 }
229 }
230 out.push(i as u32);
231 }
232 out
233}
234
235/// Order records by grid cell, then Z-order within the cell, then every remaining field.
236///
237/// Cell first so the grid directory is contiguous, Z-order so both coordinate columns delta
238/// well. The key is total over the row's content, and the ids are already the final,
239/// content-derived ones, so two runs over the same input produce identical bytes whatever
240/// order the PBF was read in.
241fn sort_rows_deterministically(rows: &mut [Row]) {
242 rows.par_sort_unstable_by_key(|r| {
243 (cell_id(r.lat, r.lon), morton_in_cell(r.lat, r.lon), r.kind, r.lat, r.lon, r.ids)
244 });
245}
246
247// --------------------------------------------------------------------------- verify
248/// Read a finished database back and check it against the rows it was built from.
249///
250/// Independent of the writer: it walks the file sequentially, decodes every column, and
251/// reconstructs each record's strings through the dictionaries. That catches the failures the
252/// writer cannot see in itself — a dictionary sorted one way and indexed another, a column
253/// written in a different order from the one the grid describes, an off-by-one in a block
254/// directory.
255pub fn verify(path: &Path, expected: &[Row]) -> io::Result<()> {
256 let p = Progress::stage("verify: read back");
257 let mut buf = Vec::new();
258 let _ = File::open(path)?.read_to_end(&mut buf)?;
259 p.finish();
260 let bad = |m: String| io::Error::new(io::ErrorKind::InvalidData, m);
261
262 let rd32 =
263 |p: usize| -> u32 { u32::from_be_bytes([buf[p], buf[p + 1], buf[p + 2], buf[p + 3]]) };
264 if rd32(0) != MAGIC {
265 return Err(bad("bad magic".into()));
266 }
267 if rd32(4) != VERSION {
268 return Err(bad(format!("version {}, expected {VERSION}", rd32(4))));
269 }
270 let n = rd32(8) as usize;
271 if n != expected.len() {
272 return Err(bad(format!("{n} records, expected {}", expected.len())));
273 }
274
275 let mut cursor = 12usize;
276 let mut sections: Vec<&[u8]> = Vec::with_capacity(SECTIONS);
277 for s in 0..SECTIONS {
278 if cursor + 4 > buf.len() {
279 return Err(bad(format!("file ends before section {s}")));
280 }
281 let size = rd32(cursor) as usize;
282 cursor += 4;
283 let end = cursor.checked_add(size).ok_or_else(|| bad("section size overflow".into()))?;
284 if end > buf.len() {
285 return Err(bad(format!("section {s} runs past the end of the file")));
286 }
287 sections.push(&buf[cursor..end]);
288 cursor = end;
289 }
290 if cursor != buf.len() {
291 return Err(bad(format!("{} trailing byte(s)", buf.len() - cursor)));
292 }
293
294 let p = Progress::stage("verify: dictionaries");
295 let dicts: Vec<Vec<String>> =
296 sections[..DICTS].iter().map(|s| decode_dict(s)).collect::<io::Result<_>>()?;
297 for (d, dict) in dicts.iter().enumerate() {
298 if SEARCHABLE[d] {
299 for w in dict.windows(2) {
300 if cmp_utf16(&w[0], &w[1]) != std::cmp::Ordering::Less {
301 return Err(bad(format!(
302 "dictionary {} is not in UTF-16 order: {:?} then {:?}",
303 DICT_NAME[d], w[0], w[1]
304 )));
305 }
306 }
307 }
308 }
309 p.finish();
310
311 // One column at a time: each is decoded, compared field by field with `expected`, and
312 // dropped. Holding all ten at once doubled the planet's peak memory (10 x 4 bytes x n on
313 // top of the rows themselves) and pushed the read-back into paging. Once every column has
314 // matched, `expected` *is* the file's content, so the index checks below read from it.
315 let col_sections = &sections[DICTS..DICTS + COLUMNS];
316 let blocks: u64 = col_sections
317 .iter()
318 .map(|s| s.get(4..8).map_or(0, |b| u32::from_be_bytes(b.try_into().unwrap()) as u64))
319 .sum();
320 let p = Progress::coarse("verify: columns", blocks);
321 for c in 0..COLUMNS {
322 let col = decode_column_with(col_sections[c], DELTA[c], Some(&p))?;
323 if col.len() != n {
324 return Err(bad(format!(
325 "column {} has {} values, expected {n}",
326 COL_NAME[c],
327 col.len()
328 )));
329 }
330 let dict = (C_NAME..=C_POSTCODE).contains(&c).then(|| &dicts[c - C_NAME]);
331 let mismatch = col.par_iter().zip(expected.par_iter()).position_first(|(&v, e)| {
332 let want = match c {
333 C_LAT => e.lat,
334 C_LON => e.lon,
335 C_KIND => e.kind as i32,
336 _ => e.ids[c - C_NAME] as i32,
337 };
338 v != want || dict.is_some_and(|d| v < 0 || v as usize >= d.len())
339 });
340 if let Some(i) = mismatch {
341 return Err(bad(format!(
342 "record {i}: {} is {} on disk; expected {:?}",
343 COL_NAME[c], col[i], expected[i]
344 )));
345 }
346 }
347 p.finish();
348
349 // The grid must describe the record order that was actually written.
350 let p = Progress::stage("verify: indexes");
351 let grid = decode_grid(sections[DICTS + COLUMNS])?;
352 let mut prev_cell = i64::MIN;
353 for &(cell, start) in &grid {
354 if cell <= prev_cell {
355 return Err(bad(format!("grid cells not ascending at {cell}")));
356 }
357 prev_cell = cell;
358 let s = start as usize;
359 if s >= n || cell_id(expected[s].lat, expected[s].lon) != cell {
360 return Err(bad(format!("grid entry for cell {cell} points at the wrong record")));
361 }
362 }
363 for i in 1..n {
364 let (a, b) = (&expected[i - 1], &expected[i]);
365 if cell_id(b.lat, b.lon) < cell_id(a.lat, a.lon) {
366 return Err(bad(format!("records are not in cell order at {i}")));
367 }
368 }
369
370 // The forward index must hold every record with a street exactly once and nothing else,
371 // sorted by its key; the name index must hold valid named records, sorted by name id.
372 let empty_street = dicts[D_STREET].iter().position(|s| s.is_empty()).map(|i| i as u32);
373 let has_street = |r: &Row| Some(r.ids[D_STREET]) != empty_street;
374 let fwd = decode_column(sections[DICTS + COLUMNS + 1], true)?;
375 let with_street = expected.iter().filter(|r| has_street(r)).count();
376 if fwd.len() != with_street {
377 return Err(bad(format!(
378 "forward index has {} entries, expected {with_street} records with a street",
379 fwd.len()
380 )));
381 }
382 let mut seen = vec![false; n];
383 let mut prev_key: Option<[u32; 5]> = None;
384 for &r in &fwd {
385 let i = r as usize;
386 if i >= n || seen[i] {
387 return Err(bad("forward index repeats or overruns a record".into()));
388 }
389 let e = &expected[i];
390 if !has_street(e) {
391 return Err(bad(format!("forward index points at record {i}, which has no street")));
392 }
393 seen[i] = true;
394 let key =
395 [e.ids[D_COUNTRY], e.ids[D_STATE], e.ids[D_CITY], e.ids[D_STREET], e.ids[D_HOUSE]];
396 if prev_key.is_some_and(|p| key < p) {
397 return Err(bad("forward index is not sorted by its key".into()));
398 }
399 prev_key = Some(key);
400 }
401 drop(seen);
402
403 let nm_name = decode_column(sections[DICTS + COLUMNS + 2], true)?;
404 let nm_rec = decode_column(sections[DICTS + COLUMNS + 3], false)?;
405 if nm_name.len() != nm_rec.len() {
406 return Err(bad("name index halves disagree on length".into()));
407 }
408 let mut prev = i32::MIN;
409 for (k, (&name_id, &rec)) in nm_name.iter().zip(nm_rec.iter()).enumerate() {
410 if name_id < prev {
411 return Err(bad(format!("name index not ascending at {k}")));
412 }
413 prev = name_id;
414 let i = rec as usize;
415 if i >= n {
416 return Err(bad(format!("name index entry {k} points past the end")));
417 }
418 if expected[i].ids[D_NAME] as i32 != name_id {
419 return Err(bad(format!("name index entry {k} disagrees with the name column")));
420 }
421 if dicts[D_NAME][name_id as usize].is_empty() {
422 return Err(bad(format!("name index entry {k} points at an unnamed record")));
423 }
424 }
425 p.finish();
426 Ok(())
427}
428
429include!("write_s1.rs");