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

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

write.rs542 lines · 21.9 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) + column_blocks(fwd.len()) + 2 * column_blocks(nm_name.len()),
174 );
175 let mut out = BufWriter::with_capacity(1 << 22, File::create(out_path)?);
176 out.write_all(&MAGIC.to_be_bytes())?;
177 out.write_all(&VERSION.to_be_bytes())?;
178 out.write_all(&(n as u32).to_be_bytes())?;
179
180 let mut report = Report { n, ..Report::default() };
181 for d in 0..DICTS {
182 report.dicts.push((DICT_NAME[d], write_section(&mut out, &dict_bodies[d])?));
183 }
184 drop(dict_bodies);
185 for c in 0..COLUMNS {
186 let body = encode_column_with(&cols[c], DELTA[c], Some(&p))?;
187 report.columns.push((COL_NAME[c], write_section(&mut out, &body)?));
188 cols[c] = Vec::new();
189 }
190 report.grid = write_section(&mut out, &encode_grid(&grid))?;
191
192 let fwd_col: Vec<i32> = fwd.iter().map(|&v| v as i32).collect();
193 report.fwd = write_section(&mut out, &encode_column_with(&fwd_col, true, Some(&p))?)?;
194 report.name_index = write_section(&mut out, &encode_column_with(&nm_name, true, Some(&p))?)?
195 + write_section(&mut out, &encode_column_with(&nm_rec, false, Some(&p))?)?;
196
197 out.flush()?;
198 p.finish();
199 report.dict_counts = dict_counts;
200 report.total = std::fs::metadata(out_path)?.len();
201 Ok(report)
202}
203
204/// Records that belong in the name index, in grid order.
205///
206/// Unnamed records can never match a name query. A street is sampled every few hundred metres,
207/// so indexing every sample would repeat one name dozens of times; one entry per street name per
208/// grid cell still finds the street and still puts the hit near the right place.
209fn name_index_records(rows: &[Row], empty_name: Option<u32>) -> Vec<u32> {
210 let mut out = Vec::new();
211 let mut cell = i64::MIN;
212 let mut streets_in_cell: HashSet<u32> = HashSet::new();
213 for (i, r) in rows.iter().enumerate() {
214 if Some(r.ids[D_NAME]) == empty_name {
215 continue;
216 }
217 if r.kind == K_STREET {
218 // Rows are in cell order, so a per-cell set stays small at planet scale.
219 let c = cell_id(r.lat, r.lon);
220 if c != cell {
221 cell = c;
222 streets_in_cell.clear();
223 }
224 if !streets_in_cell.insert(r.ids[D_NAME]) {
225 continue;
226 }
227 }
228 out.push(i as u32);
229 }
230 out
231}
232
233/// Order records by grid cell, then Z-order within the cell, then every remaining field.
234///
235/// Cell first so the grid directory is contiguous, Z-order so both coordinate columns delta
236/// well. The key is total over the row's content, and the ids are already the final,
237/// content-derived ones, so two runs over the same input produce identical bytes whatever
238/// order the PBF was read in.
239fn sort_rows_deterministically(rows: &mut [Row]) {
240 rows.par_sort_unstable_by_key(|r| {
241 (cell_id(r.lat, r.lon), morton_in_cell(r.lat, r.lon), r.kind, r.lat, r.lon, r.ids)
242 });
243}
244
245// --------------------------------------------------------------------------- verify
246/// Read a finished database back and check it against the rows it was built from.
247///
248/// Independent of the writer: it walks the file sequentially, decodes every column, and
249/// reconstructs each record's strings through the dictionaries. That catches the failures the
250/// writer cannot see in itself — a dictionary sorted one way and indexed another, a column
251/// written in a different order from the one the grid describes, an off-by-one in a block
252/// directory.
253pub fn verify(path: &Path, expected: &[Row]) -> io::Result<()> {
254 let p = Progress::stage("verify: read back");
255 let mut buf = Vec::new();
256 let _ = File::open(path)?.read_to_end(&mut buf)?;
257 p.finish();
258 let bad = |m: String| io::Error::new(io::ErrorKind::InvalidData, m);
259
260 let rd32 = |p: usize| -> u32 {
261 u32::from_be_bytes([buf[p], buf[p + 1], buf[p + 2], buf[p + 3]])
262 };
263 if rd32(0) != MAGIC {
264 return Err(bad("bad magic".into()));
265 }
266 if rd32(4) != VERSION {
267 return Err(bad(format!("version {}, expected {VERSION}", rd32(4))));
268 }
269 let n = rd32(8) as usize;
270 if n != expected.len() {
271 return Err(bad(format!("{n} records, expected {}", expected.len())));
272 }
273
274 let mut cursor = 12usize;
275 let mut sections: Vec<&[u8]> = Vec::with_capacity(SECTIONS);
276 for s in 0..SECTIONS {
277 if cursor + 4 > buf.len() {
278 return Err(bad(format!("file ends before section {s}")));
279 }
280 let size = rd32(cursor) as usize;
281 cursor += 4;
282 let end = cursor.checked_add(size).ok_or_else(|| bad("section size overflow".into()))?;
283 if end > buf.len() {
284 return Err(bad(format!("section {s} runs past the end of the file")));
285 }
286 sections.push(&buf[cursor..end]);
287 cursor = end;
288 }
289 if cursor != buf.len() {
290 return Err(bad(format!("{} trailing byte(s)", buf.len() - cursor)));
291 }
292
293 let p = Progress::stage("verify: dictionaries");
294 let dicts: Vec<Vec<String>> =
295 sections[..DICTS].iter().map(|s| decode_dict(s)).collect::<io::Result<_>>()?;
296 for (d, dict) in dicts.iter().enumerate() {
297 if SEARCHABLE[d] {
298 for w in dict.windows(2) {
299 if cmp_utf16(&w[0], &w[1]) != std::cmp::Ordering::Less {
300 return Err(bad(format!(
301 "dictionary {} is not in UTF-16 order: {:?} then {:?}",
302 DICT_NAME[d], w[0], w[1]
303 )));
304 }
305 }
306 }
307 }
308 p.finish();
309
310 // One column at a time: each is decoded, compared field by field with `expected`, and
311 // dropped. Holding all ten at once doubled the planet's peak memory (10 x 4 bytes x n on
312 // top of the rows themselves) and pushed the read-back into paging. Once every column has
313 // matched, `expected` *is* the file's content, so the index checks below read from it.
314 let col_sections = &sections[DICTS..DICTS + COLUMNS];
315 let blocks: u64 = col_sections
316 .iter()
317 .map(|s| s.get(4..8).map_or(0, |b| u32::from_be_bytes(b.try_into().unwrap()) as u64))
318 .sum();
319 let p = Progress::coarse("verify: columns", blocks);
320 for c in 0..COLUMNS {
321 let col = decode_column_with(col_sections[c], DELTA[c], Some(&p))?;
322 if col.len() != n {
323 return Err(bad(format!("column {} has {} values, expected {n}", COL_NAME[c], col.len())));
324 }
325 let dict = (C_NAME..=C_POSTCODE).contains(&c).then(|| &dicts[c - C_NAME]);
326 let mismatch = col.par_iter().zip(expected.par_iter()).position_first(|(&v, e)| {
327 let want = match c {
328 C_LAT => e.lat,
329 C_LON => e.lon,
330 C_KIND => e.kind as i32,
331 _ => e.ids[c - C_NAME] as i32,
332 };
333 v != want || dict.is_some_and(|d| v < 0 || v as usize >= d.len())
334 });
335 if let Some(i) = mismatch {
336 return Err(bad(format!(
337 "record {i}: {} is {} on disk; expected {:?}",
338 COL_NAME[c], col[i], expected[i]
339 )));
340 }
341 }
342 p.finish();
343
344 // The grid must describe the record order that was actually written.
345 let p = Progress::stage("verify: indexes");
346 let grid = decode_grid(sections[DICTS + COLUMNS])?;
347 let mut prev_cell = i64::MIN;
348 for &(cell, start) in &grid {
349 if cell <= prev_cell {
350 return Err(bad(format!("grid cells not ascending at {cell}")));
351 }
352 prev_cell = cell;
353 let s = start as usize;
354 if s >= n || cell_id(expected[s].lat, expected[s].lon) != cell {
355 return Err(bad(format!("grid entry for cell {cell} points at the wrong record")));
356 }
357 }
358 for i in 1..n {
359 let (a, b) = (&expected[i - 1], &expected[i]);
360 if cell_id(b.lat, b.lon) < cell_id(a.lat, a.lon) {
361 return Err(bad(format!("records are not in cell order at {i}")));
362 }
363 }
364
365 // The forward index must hold every record with a street exactly once and nothing else,
366 // sorted by its key; the name index must hold valid named records, sorted by name id.
367 let empty_street = dicts[D_STREET].iter().position(|s| s.is_empty()).map(|i| i as u32);
368 let has_street = |r: &Row| Some(r.ids[D_STREET]) != empty_street;
369 let fwd = decode_column(sections[DICTS + COLUMNS + 1], true)?;
370 let with_street = expected.iter().filter(|r| has_street(r)).count();
371 if fwd.len() != with_street {
372 return Err(bad(format!(
373 "forward index has {} entries, expected {with_street} records with a street",
374 fwd.len()
375 )));
376 }
377 let mut seen = vec![false; n];
378 let mut prev_key: Option<[u32; 5]> = None;
379 for &r in &fwd {
380 let i = r as usize;
381 if i >= n || seen[i] {
382 return Err(bad("forward index repeats or overruns a record".into()));
383 }
384 let e = &expected[i];
385 if !has_street(e) {
386 return Err(bad(format!("forward index points at record {i}, which has no street")));
387 }
388 seen[i] = true;
389 let key = [e.ids[D_COUNTRY], e.ids[D_STATE], e.ids[D_CITY], e.ids[D_STREET], e.ids[D_HOUSE]];
390 if prev_key.is_some_and(|p| key < p) {
391 return Err(bad("forward index is not sorted by its key".into()));
392 }
393 prev_key = Some(key);
394 }
395 drop(seen);
396
397 let nm_name = decode_column(sections[DICTS + COLUMNS + 2], true)?;
398 let nm_rec = decode_column(sections[DICTS + COLUMNS + 3], false)?;
399 if nm_name.len() != nm_rec.len() {
400 return Err(bad("name index halves disagree on length".into()));
401 }
402 let mut prev = i32::MIN;
403 for (k, (&name_id, &rec)) in nm_name.iter().zip(nm_rec.iter()).enumerate() {
404 if name_id < prev {
405 return Err(bad(format!("name index not ascending at {k}")));
406 }
407 prev = name_id;
408 let i = rec as usize;
409 if i >= n {
410 return Err(bad(format!("name index entry {k} points past the end")));
411 }
412 if expected[i].ids[D_NAME] as i32 != name_id {
413 return Err(bad(format!("name index entry {k} disagrees with the name column")));
414 }
415 if dicts[D_NAME][name_id as usize].is_empty() {
416 return Err(bad(format!("name index entry {k} points at an unnamed record")));
417 }
418 }
419 p.finish();
420 Ok(())
421}
422
423/// Decode a whole blocked dictionary (see `codec::encode_dict`), checking that every block
424/// holds the expected number of strings and that the uncompressed first-string table agrees
425/// with what each block actually starts with, since the reader trusts that table to search.
426pub(crate) fn decode_dict(body: &[u8]) -> io::Result<Vec<String>> {
427 let bad = |m: &str| io::Error::new(io::ErrorKind::InvalidData, m.to_string());
428 let rd32 = |p: usize| -> io::Result<usize> {
429 let b = body.get(p..p + 4).ok_or_else(|| bad("dictionary section truncated"))?;
430 Ok(u32::from_be_bytes(b.try_into().map_err(|_| bad("short dict"))?) as usize)
431 };
432 let (count, per, blocks) = (rd32(0)?, rd32(4)?, rd32(8)?);
433 if per == 0 || blocks != count.div_ceil(per) {
434 return Err(bad("dictionary block count does not match its string count"));
435 }
436 let first_dir = 12;
437 let firsts = first_dir + blocks * 4;
438 let firsts_len = if blocks == 0 { 0 } else { rd32(firsts - 4)? };
439 let block_dir = firsts + firsts_len;
440 let data = block_dir + blocks * 4;
441
442 let mut out = Vec::with_capacity(count);
443 for b in 0..blocks {
444 let start = if b == 0 { 0 } else { rd32(block_dir + (b - 1) * 4)? };
445 let end = rd32(block_dir + b * 4)?;
446 let comp = body.get(data + start..data + end).ok_or_else(|| bad("dictionary block truncated"))?;
447 let raw = zstd::decode_all(comp)?;
448 let want = per.min(count - b * per);
449 let mut p = 0usize;
450 for k in 0..want {
451 let len = raw.get(p..p + 4).ok_or_else(|| bad("dictionary block ran out"))?;
452 let len = u32::from_be_bytes(len.try_into().map_err(|_| bad("short dict"))?) as usize;
453 p += 4;
454 let s = raw.get(p..p + len).ok_or_else(|| bad("dictionary block ran out"))?;
455 let s = String::from_utf8(s.to_vec()).map_err(|_| bad("dictionary entry is not UTF-8"))?;
456 p += len;
457 if k == 0 {
458 let f0 = if b == 0 { 0 } else { rd32(first_dir + (b - 1) * 4)? };
459 let f1 = rd32(first_dir + b * 4)?;
460 if body.get(firsts + f0..firsts + f1) != Some(s.as_bytes()) {
461 return Err(bad("first-string table disagrees with its block"));
462 }
463 }
464 out.push(s);
465 }
466 if p != raw.len() {
467 return Err(bad("dictionary block has trailing bytes"));
468 }
469 }
470 if data + if blocks == 0 { 0 } else { rd32(data - 4)? } != body.len() {
471 return Err(bad("dictionary section has trailing bytes"));
472 }
473 Ok(out)
474}
475
476pub(crate) fn decode_column(body: &[u8], delta: bool) -> io::Result<Vec<i32>> {
477 decode_column_with(body, delta, None)
478}
479
480fn decode_column_with(body: &[u8], delta: bool, progress: Option<&Progress>) -> io::Result<Vec<i32>> {
481 let bad = |m: &str| io::Error::new(io::ErrorKind::InvalidData, m.to_string());
482 let rd32 = |p: usize| -> u32 {
483 u32::from_be_bytes([body[p], body[p + 1], body[p + 2], body[p + 3]])
484 };
485 if body.len() < 8 {
486 return Err(bad("column section too short"));
487 }
488 let n = rd32(0) as usize;
489 let blocks = rd32(4) as usize;
490 let data = 8 + blocks * 8;
491 let mut out = Vec::with_capacity(n);
492 let mut start = 0usize;
493 for b in 0..blocks {
494 let end = rd32(8 + b * 8 + 4) as usize;
495 let comp = body.get(data + start..data + end).ok_or_else(|| bad("column block out of range"))?;
496 let raw = zstd::decode_all(comp)?;
497 start = end;
498 let mut p = 0usize;
499 let mut prev = 0i32;
500 let count = n.saturating_sub(b * BLOCK).min(BLOCK);
501 for _ in 0..count {
502 let mut v = 0u32;
503 let mut shift = 0;
504 loop {
505 let byte = *raw.get(p).ok_or_else(|| bad("block ran out of bytes"))?;
506 p += 1;
507 v |= ((byte & 0x7F) as u32) << shift;
508 if byte & 0x80 == 0 {
509 break;
510 }
511 shift += 7;
512 }
513 let dec = ((v >> 1) as i32) ^ -((v & 1) as i32);
514 let value = if delta { prev.wrapping_add(dec) } else { dec };
515 out.push(value);
516 prev = value;
517 }
518 if let Some(p) = progress {
519 p.inc();
520 }
521 }
522 Ok(out)
523}
524
525fn decode_grid(body: &[u8]) -> io::Result<Vec<(i64, u32)>> {
526 let count = u32::from_be_bytes(
527 body[0..4].try_into().map_err(|_| io::Error::other("short grid"))?,
528 ) as usize;
529 let mut out = Vec::with_capacity(count);
530 let mut p = 4usize;
531 for _ in 0..count {
532 let cell = i64::from_be_bytes(
533 body[p..p + 8].try_into().map_err(|_| io::Error::other("short grid"))?,
534 );
535 let start = u32::from_be_bytes(
536 body[p + 8..p + 12].try_into().map_err(|_| io::Error::other("short grid"))?,
537 );
538 out.push((cell, start));
539 p += 12;
540 }
541 Ok(out)
542}