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

Modern-Apps.git / scripts / maps / osm_ingest / src / pbf.rs

pbf.rs530 lines · 22.1 KiBRaw
1//! `.osm.pbf` container: blob framing, inflate, `PrimitiveBlock` decode, and the
2//! parallel pass driver.
3//!
4//! A `.osm.pbf` is a flat sequence of
5//! `[u32 big-endian header_len][BlobHeader][Blob]`. Because the framing is
6//! self-describing we can cheaply *scan* the file once, recording each blob's
7//! `(offset, len)`, and afterwards let N threads each seek to and inflate their
8//! own blobs from their own `File` handle. That replaces the old C++
9//! `ThreadPool`/`MoveTask`/throttling-condvar machinery — and the data race its
10//! comments described — with a plain `std::thread::scope`.
11//!
12//! Work is split into fixed contiguous *chunks* of blobs (not dynamically per
13//! blob) so results can be merged in chunk order. That is what makes the whole
14//! tool deterministic: name-pool offsets and record order no longer depend on
15//! thread scheduling, which the C++ generator's did.
16
17use std::fs::File;
18use std::io::{BufReader, Read, Seek, SeekFrom, Write};
19use std::path::Path;
20use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
21use std::sync::{Condvar, Mutex};
22
23use crate::proto::{self, Error, Reader, Result, WIRE_BYTES};
24use crate::pbf_extra::decode_blob_header;
25
26pub use crate::pbf_extra::probe_compression;
27pub use crate::pbf_extra::{load_blob_kinds, write_blob_kinds, BLOB_KINDS_FILE};
28
29/// Kind bits: which entity types a pass wants, and which a blob contains.
30pub const KIND_NODES: u8 = 1;
31pub const KIND_WAYS: u8 = 2;
32pub const KIND_RELATIONS: u8 = 4;
33
34/// A blob is capped at 32 MiB uncompressed by the format spec; allow some slack
35/// but refuse absurd sizes so a corrupt length can't trigger a huge allocation.
36const MAX_BLOB_BYTES: usize = 128 * 1024 * 1024;
37
38/// Blobs per work chunk. Fixed (rather than derived from the core count) so the
39/// merge order — and therefore every output byte — is identical on any machine.
40///
41/// **It also sets peak memory**, because it is the multiplier on the reorder buffer.
42/// [`run_pass_sink`] lets `2 * threads` chunk accumulators sit in [`Drain::slots`] at
43/// once, and a pass 1 accumulator holds every classified way in its chunk *with that
44/// way's node refs*. So the bytes in flight are `2 * threads * CHUNK_BLOBS` blobs' worth
45/// of ways, and only this constant is not a property of the machine.
46///
47/// **Lowered from 64.** On a 64-core box the window is 128 chunks, which at 64 blobs a
48/// chunk is 8192 blobs — more than a California extract has, so the "bound" bound nothing
49/// and the reorder buffer was the whole build's peak: 2.19 GB, a few seconds into pass 1.
50/// At 8 blobs a chunk the same window is 1024 blobs and the peak of stage A falls to
51/// 1.58 GB, which is the node-location table underneath it. It costs eight times as many
52/// `deposit` calls — one mutex acquisition each, against a chunk of work measured in
53/// milliseconds — and it was inside the noise on a California build.
54///
55/// Byte-neutral, which is what makes it safe to tune: chunks are contiguous blob ranges
56/// drained in ascending order, so regrouping them cannot reorder the ways inside them.
57pub(crate) const CHUNK_BLOBS: usize = 8;
58
59/// Where one `OSMData` blob lives in the file.
60#[derive(Clone, Copy)]
61pub struct BlobLoc {
62 pub offset: u64,
63 pub datasize: u32,
64}
65
66/// Scan the framing once, returning every `OSMData` blob's location. Only blob
67/// *headers* are read, so this is I/O-cheap even on a 1.3 GB extract.
68pub fn scan_blobs(path: &Path) -> Result<Vec<BlobLoc>> {
69 let file = File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;
70 let total = file
71 .metadata()
72 .map_err(|e| Error(format!("cannot stat {}: {e}", path.display())))?
73 .len();
74 let mut r = BufReader::with_capacity(1 << 20, file);
75 let mut out = Vec::new();
76 let mut pos: u64 = 0;
77 let mut header = Vec::new();
78
79 while pos < total {
80 let mut len_buf = [0u8; 4];
81 if let Err(e) = r.read_exact(&mut len_buf) {
82 return Err(Error(format!("truncated blob header length at {pos}: {e}")));
83 }
84 let header_len = u32::from_be_bytes(len_buf) as usize;
85 if header_len == 0 || header_len > 64 * 1024 {
86 return proto::err(format!("implausible BlobHeader length {header_len} at {pos}"));
87 }
88 header.clear();
89 header.resize(header_len, 0);
90 r.read_exact(&mut header)
91 .map_err(|e| Error(format!("truncated BlobHeader at {pos}: {e}")))?;
92
93 let (kind, datasize) = decode_blob_header(&header)?;
94 let blob_offset = pos + 4 + header_len as u64;
95 if datasize as usize > MAX_BLOB_BYTES {
96 return proto::err(format!("blob at {blob_offset} claims {datasize} bytes"));
97 }
98 if kind == b"OSMData" {
99 out.push(BlobLoc {
100 offset: blob_offset,
101 datasize,
102 });
103 }
104 pos = blob_offset + datasize as u64;
105 // seek_relative keeps the read buffer when the target is already inside it.
106 // Blobs average tens of KB, so one 1 MiB fill covers many headers; a plain
107 // `seek` would discard the buffer and refill it for every single blob.
108 r.seek_relative(datasize as i64)
109 .map_err(|e| Error(format!("seek to {pos} failed: {e}")))?;
110 }
111 Ok(out)
112}
113
114/// Inflate one blob's payload into `out`.
115///
116/// `Blob { bytes raw = 1; int32 raw_size = 2; bytes zlib_data = 3; ... }`.
117/// The compressions we cannot decode without a C library (lzma/bzip2/lz4/zstd)
118/// are reported as a clear error rather than silently skipped — a skipped blob
119/// would produce a quietly incomplete graph.
120///
121/// # `out` is the caller's buffer, and it is genuinely reused
122///
123/// [`run_pass_sink`]'s workers hoist one of these out of the blob loop each, so a pass
124/// allocates one inflate buffer per thread rather than one per blob. That only holds if
125/// this function inflates *into* the buffer: the obvious
126/// `*out = decompress_to_vec_zlib_with_limit(..)?` throws the caller's allocation away on
127/// every blob, and worse, the new buffer is allocated and zero-filled before the old one
128/// is dropped, so each worker is briefly holding two.
129///
130/// It measured 1.5 GB of a 2.19 GB California peak. The peak of that whole build was one
131/// second in, during the node region of pass 1 — before a single way had been classified
132/// and long before any tile existed — and it scaled with the core count at ~24 MB a
133/// thread, which is one and a bit blob buffers apiece.
134///
135/// `raw_size` is what makes inflating in place possible: the blob states its own
136/// uncompressed length, so the buffer can be sized exactly before decompressing rather
137/// than grown by doubling.
138pub fn inflate_blob(blob: &[u8], out: &mut Vec<u8>) -> Result<()> {
139 let mut r = Reader::new(blob);
140 let mut raw: Option<&[u8]> = None;
141 let mut raw_size: Option<usize> = None;
142 let mut zlib: Option<&[u8]> = None;
143 while let Some((field, wire)) = r.next_field()? {
144 match (field, wire) {
145 (1, WIRE_BYTES) => raw = Some(r.bytes()?),
146 (2, proto::WIRE_VARINT) => raw_size = Some(r.uvarint()? as usize),
147 (3, WIRE_BYTES) => zlib = Some(r.bytes()?),
148 (4, WIRE_BYTES) => return proto::err("blob uses lzma compression (unsupported)"),
149 (5, WIRE_BYTES) => return proto::err("blob uses bzip2 compression (unsupported)"),
150 (6, WIRE_BYTES) => return proto::err("blob uses lz4 compression (unsupported)"),
151 (7, WIRE_BYTES) => return proto::err("blob uses zstd compression (unsupported)"),
152 _ => r.skip(wire)?,
153 }
154 }
155
156 out.clear();
157 if let Some(z) = zlib {
158 match raw_size.filter(|want| *want <= MAX_BLOB_BYTES) {
159 Some(want) => {
160 // Reuses the caller's capacity: `clear` kept it and `resize` fills it.
161 out.resize(want, 0);
162 // `zlib_header` true and `ignore_adler32` false, so this still parses the
163 // zlib header and verifies the Adler-32 trailer — a mis-framed or corrupt
164 // blob fails just as loudly as it did through the allocating path.
165 let got = miniz_oxide::inflate::decompress_slice_iter_to_slice(
166 out,
167 std::iter::once(z),
168 true,
169 false,
170 )
171 .map_err(|e| Error(format!("inflate failed: {e:?}")))?;
172 // `out` is `want` long whatever happened, so a short inflate would slip
173 // past the raw_size check below. This is the one that catches it.
174 if got != want {
175 return proto::err(format!(
176 "blob inflated {got} byte(s) but raw_size says {want}"
177 ));
178 }
179 }
180 // No `raw_size`, so there is no length to size the buffer from and the growing
181 // allocator path is all that is left. Every conforming writer emits it, so this
182 // is the odd file rather than the hot path.
183 None => {
184 let limit = raw_size.unwrap_or(MAX_BLOB_BYTES).min(MAX_BLOB_BYTES);
185 let data = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(z, limit)
186 .map_err(|e| Error(format!("inflate failed: {e:?}")))?;
187 *out = data;
188 }
189 }
190 } else if let Some(bytes) = raw {
191 out.extend_from_slice(bytes);
192 } else {
193 return proto::err("blob has neither raw nor zlib_data");
194 }
195
196 if let Some(want) = raw_size {
197 if out.len() != want {
198 return proto::err(format!(
199 "blob inflated to {} bytes but raw_size says {want}",
200 out.len()
201 ));
202 }
203 }
204 Ok(())
205}
206
207/// One decoded `PrimitiveBlock`. Strings and group bodies are borrowed from the
208/// inflated buffer, so decoding a block allocates only the two index vectors.
209pub struct PrimitiveBlock<'a> {
210 pub strings: Vec<&'a [u8]>,
211 pub granularity: i64,
212 pub lat_offset: i64,
213 pub lon_offset: i64,
214 pub groups: Vec<&'a [u8]>,
215}
216
217impl<'a> PrimitiveBlock<'a> {
218 pub fn decode(buf: &'a [u8]) -> Result<PrimitiveBlock<'a>> {
219 let mut block = PrimitiveBlock {
220 strings: Vec::new(),
221 granularity: 100,
222 lat_offset: 0,
223 lon_offset: 0,
224 groups: Vec::new(),
225 };
226 let mut r = Reader::new(buf);
227 while let Some((field, wire)) = r.next_field()? {
228 match (field, wire) {
229 (1, WIRE_BYTES) => {
230 // StringTable { repeated bytes s = 1; }
231 let mut st = Reader::new(r.bytes()?);
232 while let Some((f, w)) = st.next_field()? {
233 if (f, w) == (1, WIRE_BYTES) {
234 block.strings.push(st.bytes()?);
235 } else {
236 st.skip(w)?;
237 }
238 }
239 }
240 (2, WIRE_BYTES) => block.groups.push(r.bytes()?),
241 (17, proto::WIRE_VARINT) => block.granularity = r.ivarint()?,
242 (19, proto::WIRE_VARINT) => block.lat_offset = r.ivarint()?,
243 (20, proto::WIRE_VARINT) => block.lon_offset = r.ivarint()?,
244 _ => r.skip(wire)?,
245 }
246 }
247 if block.granularity <= 0 {
248 return proto::err(format!("block granularity {}", block.granularity));
249 }
250 Ok(block)
251 }
252
253 #[inline]
254 pub fn string(&self, idx: u32) -> &'a [u8] {
255 self.strings.get(idx as usize).copied().unwrap_or(b"")
256 }
257
258 /// Raw coordinate delta -> hundredths of a nanodegree -> 1e-7 degrees, the
259 /// integer libosmium's `Location` stores. Truncating division matches
260 /// libosmium's `convert_pbf_lat`, so coordinates are bit-identical to what
261 /// the old C++ tools saw.
262 #[inline]
263 pub fn lat_e7(&self, delta: i64) -> i32 {
264 ((self.lat_offset + self.granularity * delta) / 100) as i32
265 }
266
267 #[inline]
268 pub fn lon_e7(&self, delta: i64) -> i32 {
269 ((self.lon_offset + self.granularity * delta) / 100) as i32
270 }
271}
272
273/// Run one pass over the file in parallel, folding each chunk's accumulator as
274/// soon as it is complete.
275///
276/// `make` builds a fresh accumulator per chunk, `body` is called once per blob
277/// with that chunk's accumulator and must return the kind bits the blob held, and
278/// `sink` receives finished accumulators **in chunk order** so merging stays
279/// deterministic.
280///
281/// Prefer this to [`run_pass`] for anything whose accumulators are large. A
282/// planet-scale pass cannot afford `run_pass`'s contract of handing back every
283/// chunk at once: on California the pass-2 node accumulators are about a
284/// gigabyte, and the caller then folds them into a second copy, so the two peak
285/// together. Here a chunk is folded and freed while its neighbours are still
286/// being decoded, which also overlaps the merge with the I/O.
287///
288/// `sink` is called under a lock, so it is serialised against the workers. That
289/// is the same single-threaded merge [`run_pass`]'s callers already do, only
290/// earlier.
291///
292/// `blob_kinds` (from a previous full pass) lets later passes skip blobs that
293/// hold nothing they want — a real win because a PBF stores all nodes first,
294/// then ways, then relations. A skipped blob's incoming kinds are carried into
295/// the returned mask, so a filtered pass's mask is still a complete description
296/// of the file and can be fed to the pass after it.
297pub fn run_pass_sink<S, F, G, H>(
298 path: &Path,
299 blobs: &[BlobLoc],
300 blob_kinds: Option<&[u8]>,
301 want: u8,
302 label: &str,
303 make: F,
304 body: G,
305 sink: H,
306) -> Result<Vec<u8>>
307where
308 S: Send,
309 F: Fn() -> S + Sync,
310 G: Fn(&mut S, &PrimitiveBlock) -> Result<u8> + Sync,
311 H: FnMut(S) -> Result<()> + Send,
312{
313 let n_chunks = blobs.len().div_ceil(CHUNK_BLOBS).max(1);
314 let drain: Mutex<Drain<S, H>> = Mutex::new(Drain {
315 slots: (0..n_chunks).map(|_| None).collect(),
316 next: 0,
317 sink,
318 err: None,
319 });
320 let kinds: Vec<AtomicU8> = (0..blobs.len()).map(|_| AtomicU8::new(0)).collect();
321
322 let next_chunk = AtomicUsize::new(0);
323 let done_blobs = AtomicUsize::new(0);
324 let last_pct = AtomicUsize::new(usize::MAX);
325 // Owns the meter's clock: `report` draws the progress.rs standard shape
326 // (`label [pct%] done/total elapsed, ETA`) from it on every redraw.
327 let pass_start = std::time::Instant::now();
328 let n_threads = crate::par::threads().min(n_chunks);
329 let mut first_err: Option<Error> = None;
330 // How far ahead of the sink the workers may run.
331 //
332 // Without this the reorder buffer is unbounded: a worker deposits and immediately
333 // claims another chunk, so one slow chunk 0 can park every other chunk's
334 // accumulator in `slots` at once. On a planet pass those accumulators are the
335 // largest things in the build, and raising the thread count widens the window,
336 // which is exactly the failure this plan is shaped to avoid. Two chunks per thread
337 // leaves slack for an uneven chunk without letting the buffer grow with the file.
338 //
339 // Note what this does NOT bound. It is a count of chunks, so the bytes it admits are
340 // `window * CHUNK_BLOBS` blobs' worth of accumulator — and on a 64-core box the window
341 // is 128 chunks, which exceeds the chunk count of anything smaller than a continent.
342 // For those the window binds on nothing and the bound is really [`CHUNK_BLOBS`]; see
343 // its doc for the 2.19 GB that cost. Bounding this in bytes would mean measuring `S`,
344 // which is opaque here by design.
345 let window = n_threads.saturating_mul(2).max(2);
346 let progressed = Condvar::new();
347
348 std::thread::scope(|scope| {
349 let mut handles = Vec::with_capacity(n_threads);
350 for _ in 0..n_threads {
351 handles.push(scope.spawn(|| -> Result<()> {
352 let mut file = File::open(path)
353 .map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;
354 let mut compressed = Vec::new();
355 let mut inflated = Vec::new();
356 loop {
357 let chunk = next_chunk.fetch_add(1, Ordering::Relaxed);
358 if chunk >= n_chunks {
359 return Ok(());
360 }
361 // Hold off until this chunk is inside the window. The worker that
362 // owns the lowest outstanding chunk always passes this test, so it
363 // always makes progress and the wait cannot deadlock.
364 {
365 let mut d = drain.lock().expect("chunk slot mutex");
366 while chunk >= d.next + window {
367 d = progressed.wait(d).expect("chunk slot mutex");
368 }
369 }
370 let start = chunk * CHUNK_BLOBS;
371 let end = ((chunk + 1) * CHUNK_BLOBS).min(blobs.len());
372 let mut state = make();
373 for (i, loc) in blobs[start..end].iter().enumerate() {
374 let idx = start + i;
375 match blob_kinds.filter(|k| k[idx] & want == 0) {
376 Some(k) => kinds[idx].store(k[idx], Ordering::Relaxed),
377 None => {
378 read_exact_at(&mut file, loc, &mut compressed)?;
379 inflate_blob(&compressed, &mut inflated)?;
380 let block = PrimitiveBlock::decode(&inflated)?;
381 let seen = body(&mut state, &block)?;
382 kinds[idx].store(seen, Ordering::Relaxed);
383 }
384 }
385 report(label, &done_blobs, &last_pct, blobs.len(), &pass_start);
386 }
387 drain.lock().expect("chunk slot mutex").deposit(chunk, state);
388 progressed.notify_all();
389 }
390 }));
391 }
392 for h in handles {
393 match h.join() {
394 Ok(Ok(())) => {}
395 Ok(Err(e)) => {
396 if first_err.is_none() {
397 first_err = Some(e);
398 }
399 }
400 Err(_) => {
401 if first_err.is_none() {
402 first_err = Some(Error("a reader thread panicked".into()));
403 }
404 }
405 }
406 }
407 });
408
409 if let Some(e) = first_err {
410 return Err(e);
411 }
412 let mut d = drain.into_inner().expect("chunk slot mutex");
413 if let Some(e) = d.err.take() {
414 return Err(e);
415 }
416 // Every chunk was deposited, and deposits drain in order, so nothing can be
417 // left behind unless a sink call failed above.
418 debug_assert_eq!(d.next, n_chunks, "chunks left undrained");
419 // Snap to 100% in the same standard shape, then a fresh line so the next
420 // stage starts clean instead of on top of the meter.
421 {
422 let n = blobs.len();
423 eprintln!(
424 "\r{label:<28} [100%] {n}/{n} {} elapsed, ETA 0s ",
425 crate::progress::hms(pass_start.elapsed().as_secs_f64()),
426 );
427 }
428 Ok(kinds.iter().map(|k| k.load(Ordering::Relaxed)).collect())
429}
430
431/// Holds finished chunks until their turn comes, so the sink sees chunk order
432/// however the workers finish.
433struct Drain<S, H> {
434 slots: Vec<Option<S>>,
435 next: usize,
436 sink: H,
437 err: Option<Error>,
438}
439
440impl<S, H: FnMut(S) -> Result<()>> Drain<S, H> {
441 fn deposit(&mut self, chunk: usize, state: S) {
442 self.slots[chunk] = Some(state);
443 while self.next < self.slots.len() {
444 let Some(s) = self.slots[self.next].take() else {
445 break;
446 };
447 self.next += 1;
448 // Keep draining after a failure: the pass reports the first error at
449 // the end, and stopping here would strand the remaining chunks.
450 if let Err(e) = (self.sink)(s) {
451 if self.err.is_none() {
452 self.err = Some(e);
453 }
454 }
455 }
456 }
457}
458
459/// Run one pass over the file in parallel, returning every chunk's accumulator.
460///
461/// Convenience over [`run_pass_sink`] for passes whose accumulators are small
462/// enough that holding them all costs nothing. Accumulators come back in chunk
463/// order, so merging them is deterministic.
464pub fn run_pass<S, F, G>(
465 path: &Path,
466 blobs: &[BlobLoc],
467 blob_kinds: Option<&[u8]>,
468 want: u8,
469 label: &str,
470 make: F,
471 body: G,
472) -> Result<(Vec<S>, Vec<u8>)>
473where
474 S: Send,
475 F: Fn() -> S + Sync,
476 G: Fn(&mut S, &PrimitiveBlock) -> Result<u8> + Sync,
477{
478 let mut out: Vec<S> = Vec::new();
479 let kinds = run_pass_sink(path, blobs, blob_kinds, want, label, make, body, |s| {
480 out.push(s);
481 Ok(())
482 })?;
483 Ok((out, kinds))
484}
485
486pub(crate) fn read_exact_at(file: &mut File, loc: &BlobLoc, out: &mut Vec<u8>) -> Result<()> {
487 file.seek(SeekFrom::Start(loc.offset))
488 .map_err(|e| Error(format!("seek to {} failed: {e}", loc.offset)))?;
489 out.clear();
490 out.resize(loc.datasize as usize, 0);
491 file.read_exact(out)
492 .map_err(|e| Error(format!("short read at {}: {e}", loc.offset)))
493}
494
495/// One redraw of the pass meter, in the single standard shape (`progress.rs`):
496/// `label [pct%] done/total elapsed, ETA` on one stderr line.
497fn report(
498 label: &str,
499 done: &AtomicUsize,
500 last_pct: &AtomicUsize,
501 total: usize,
502 start: &std::time::Instant,
503) {
504 let n = done.fetch_add(1, Ordering::Relaxed) + 1;
505 if total == 0 {
506 return;
507 }
508 let pct = n * 100 / total;
509 let prev = last_pct.load(Ordering::Relaxed);
510 if pct != prev
511 && last_pct
512 .compare_exchange(prev, pct, Ordering::Relaxed, Ordering::Relaxed)
513 .is_ok()
514 {
515 let elapsed = start.elapsed().as_secs_f64();
516 // ETA extrapolates the average rate so far; meaningless until something is
517 // done, so hold it at zero for the opening frame.
518 let eta = if n == 0 {
519 0.0
520 } else {
521 elapsed * (total - n) as f64 / n as f64
522 };
523 eprint!(
524 "\r{label:<28} [{pct:>3}%] {n}/{total} {} elapsed, ETA {} ",
525 crate::progress::hms(elapsed),
526 crate::progress::hms(eta),
527 );
528 let _ = std::io::stderr().flush();
529 }
530}