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

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

nodeloc.rs463 lines · 19.7 KiBRaw
1//! Coordinates for a known set of node ids, and the PBF pass that fills them.
2//!
3//! Split out of [`crate::extract`] so the tile generators can share it: resolving
4//! way geometry is the one thing every layer build does, and it is the one place
5//! where a careless data structure costs gigabytes.
6
7use std::path::{Path, PathBuf};
8use std::sync::atomic;
9
10use crate::geojson::Coord;
11use crate::osm::{visit_block, Element, NodeView};
12use crate::pbf::{self, KIND_NODES};
13use crate::proto::{Error, Result};
14
15/// Sentinel latitude for "this node's location was never seen".
16/// Coordinates for a known set of node ids: a compressed id index plus an
17/// index-aligned coordinate array.
18///
19/// **This, and not [`crate::graph_build`]'s bitset.** That module allocates
20/// `BITSET_SIZE = 20e9` bits -- 2.5 GB keyed by raw OSM node id, whatever the
21/// extract -- and peaks around 10 GB on California. This form costs per *needed*
22/// node, so a layer that wants a few hundred thousand nodes pays megabytes. Same
23/// pattern as [`crate::poi_build`], which worked it out first.
24///
25/// # Why the ids are compressed
26///
27/// A sorted `Vec<i64>` is the obvious id table and it was the first one here. On a California
28/// extract it is 154 M ids, so 1.23 GB -- and next to an equally large coordinate array it made this
29/// structure about 73% of the whole generator's peak. The ids are sorted and dense enough that the
30/// gaps between them are tiny: they are a *subset* of a PBF's node ids, but a large one, so the
31/// average gap is a couple of units and encodes in a single byte. [`IdIndex`] stores one full id per
32/// block of [`BLOCK`] and varint gaps for the rest, which is about 1.2 bytes per id instead of 8.
33///
34/// Lookup did not get slower for it, and probably got faster. A binary search over 1.23 GB touches
35/// ~27 scattered cache lines and misses on most of them; this searches a 19 MB base array and then
36/// scans at most 63 contiguous bytes, which is one or two lines.
37pub struct NodeLocations {
38 ids: NodeIds,
39 locs: Locs,
40}
41
42/// The coordinate array, in a memory-mapped file rather than on the heap.
43///
44/// Eight bytes per needed node is 1.23 GB on a California extract, and unlike the ids it will not
45/// compress: latitude and longitude in id order are high-entropy, so there is no structure to exploit.
46/// What there is instead is locality — materialisation walks ways in id order and a way's nodes sit
47/// close together in a PBF — so a mapped file lets the OS keep the working set and nothing else.
48///
49/// # Resolved-ness is a bitset, not a sentinel
50///
51/// A fresh mapping reads as zeroes, and `(0, 0)` is a real coordinate, so zero cannot mean
52/// "unresolved". Writing `i32::MIN` across the whole file would work and would also dirty every page
53/// of 1.23 GB before the pass that fills it, which is most of the cost this exists to avoid. A bit per
54/// node is 19 MB, stays in memory, and leaves the mapping untouched until something is actually
55/// written to it.
56struct Locs {
57 map: Option<memmap2::MmapMut>,
58 /// One bit per node, set when a coordinate has been written.
59 resolved: Vec<u64>,
60 /// Deleted on drop. Scratch, and large enough that leaving it behind would matter.
61 path: Option<PathBuf>,
62 len: usize,
63}
64
65impl Locs {
66 fn new(len: usize) -> Result<Locs> {
67 if len == 0 {
68 return Ok(Locs { map: None, resolved: Vec::new(), path: None, len: 0 });
69 }
70 let path = std::env::temp_dir().join(format!(
71 "osm_nodeloc_{}_{}.bin",
72 std::process::id(),
73 // Distinct per table, so two in one process cannot share a file.
74 NEXT_LOCS.fetch_add(1, atomic::Ordering::Relaxed),
75 ));
76 let bytes = len as u64 * 8;
77 let file = std::fs::OpenOptions::new()
78 .read(true)
79 .write(true)
80 .create(true)
81 .truncate(true)
82 .open(&path)
83 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
84 // Sets the length without writing anything: on both platforms this leaves a sparse or
85 // zero-filled file, so the 1.23 GB is not touched until a page is used.
86 file.set_len(bytes)
87 .map_err(|e| Error(format!("cannot size {}: {e}", path.display())))?;
88 // SAFETY: this process owns `path` exclusively — it is named after the pid and a counter, was
89 // just created with `truncate`, and is deleted in `Drop`. Nothing else can resize it while the
90 // mapping is live, which is the one thing that would make the slice dangle.
91 let map = unsafe { memmap2::MmapMut::map_mut(&file) }
92 .map_err(|e| Error(format!("cannot map {}: {e}", path.display())))?;
93 Ok(Locs {
94 map: Some(map),
95 resolved: vec![0u64; len.div_ceil(64)],
96 path: Some(path),
97 len,
98 })
99 }
100
101 fn set(&mut self, index: usize, lat_e7: i32, lon_e7: i32) {
102 let Some(map) = self.map.as_mut() else { return };
103 let at = index * 8;
104 map[at..at + 4].copy_from_slice(&lat_e7.to_le_bytes());
105 map[at + 4..at + 8].copy_from_slice(&lon_e7.to_le_bytes());
106 self.resolved[index / 64] |= 1 << (index % 64);
107 }
108
109 fn get(&self, index: usize) -> Option<(i32, i32)> {
110 if index >= self.len || self.resolved[index / 64] & (1 << (index % 64)) == 0 {
111 return None;
112 }
113 let map = self.map.as_ref()?;
114 let at = index * 8;
115 let lat = i32::from_le_bytes(map[at..at + 4].try_into().expect("four bytes"));
116 let lon = i32::from_le_bytes(map[at + 4..at + 8].try_into().expect("four bytes"));
117 Some((lat, lon))
118 }
119}
120
121impl Drop for Locs {
122 fn drop(&mut self) {
123 // The mapping goes before the file, or Windows refuses the delete.
124 self.map = None;
125 if let Some(path) = self.path.take() {
126 let _ = std::fs::remove_file(path);
127 }
128 }
129}
130
131static NEXT_LOCS: atomic::AtomicU64 = atomic::AtomicU64::new(0);
132
133/// Ids per block of [`IdIndex`].
134///
135/// The trade is the usual one: a larger block amortises its 16 bytes of base and offset over more
136/// ids, and lengthens the scan that follows the binary search. 64 puts the overhead at 0.25 bytes per
137/// id and keeps the worst-case scan inside a couple of cache lines.
138const BLOCK: usize = 64;
139
140/// A sorted, unique id set as block bases plus varint gaps.
141///
142/// Searchable through `&self` alone, because [`resolve_nodes`] hands it to every worker in a PBF pass
143/// while the sink writes coordinates.
144///
145/// # When this is used, and when [`RankIndex`] is instead
146///
147/// This compressed form costs `O(count)` -- ~1.2 bytes per *needed* id -- so it is the right shape
148/// for a sub-continent extract, where the needed set is a sparse subset of a 13 G id space and a
149/// bitset over that space would dwarf it. [`NodeLocations::new`] builds it. The planet path
150/// ([`NodeLocations::from_sorted`], fed by a caller-side bitset) builds a [`RankIndex`] instead: at
151/// planet scale the needed set is most of the id space, so a rank-select bitset that costs
152/// `O(id space)` -- ~2 GB, bounded -- beats this index's ~12.9 GB, and its `find` is `O(1)` rather
153/// than a binary search plus a varint scan. [`NodeIds`] is the switch between the two.
154#[derive(Default)]
155struct IdIndex {
156 /// The first id of each block, ascending. What the binary search runs over.
157 bases: Vec<i64>,
158 /// Where each block's gaps start in `deltas`, with a sentinel so `offsets[b + 1]` is always the
159 /// end of block `b`.
160 ///
161 /// `u64`, not `u32`. It was `u32` behind a guard that errored when `deltas` outgrew 4.29 GB, and
162 /// at ~1.1 bytes per id that guard fires at roughly 3.9 G ids -- reached by a planet extract's
163 /// 9.5 G. Widening costs 4 bytes per block of 64 ids, which is 2.38 GB against 1.19 GB at planet
164 /// scale and noise against what the bitset in [`crate::extract`]'s caller saves.
165 offsets: Vec<u64>,
166 /// `BLOCK - 1` varint gaps per block, each the difference from the previous id.
167 deltas: Vec<u8>,
168 len: usize,
169}
170
171impl IdIndex {
172 /// Build from ids that are already sorted and unique.
173 ///
174 /// Infallible, and it was not. Two guards used to live here, one on the id count and one on the
175 /// delta bytes, because `find` returned a `u32` position and `offsets` held `u32` byte offsets --
176 /// and their own doc comment predicted that "both are within reach at planet scale and both fail
177 /// silently". They were right and they were reached, so the types were widened instead. Both
178 /// ceilings are now `u64`, which no extract of this planet can approach.
179 fn build(ids: &[i64]) -> IdIndex {
180 IdIndex::build_sorted(ids.iter().copied(), ids.len())
181 }
182
183 /// Build from an ascending, unique id **stream** of known length.
184 ///
185 /// The streaming form exists because a planet extract cannot afford the slice. [`crate::extract`]
186 /// gets its ids by walking a bitset over the node id space, and materialising them first would
187 /// be 8 bytes an id -- the very vector the bitset replaced.
188 ///
189 /// `len` sizes the three arenas up front and is not otherwise trusted: the index's own length is
190 /// what the stream actually yielded.
191 fn build_sorted(ids: impl Iterator<Item = i64>, len: usize) -> IdIndex {
192 let blocks = len.div_ceil(BLOCK);
193 let mut index = IdIndex {
194 bases: Vec::with_capacity(blocks),
195 offsets: Vec::with_capacity(blocks + 1),
196 // One byte per gap is the common case, so this is the right first guess.
197 deltas: Vec::with_capacity(len),
198 len: 0,
199 };
200 let mut in_block = 0usize;
201 let mut previous = 0i64;
202 for id in ids {
203 if in_block == 0 {
204 index.bases.push(id);
205 index.offsets.push(index.deltas.len() as u64);
206 } else {
207 // Non-negative because the input is sorted and unique, so the gap is at least one.
208 put_uvarint((id - previous) as u64, &mut index.deltas);
209 }
210 previous = id;
211 index.len += 1;
212 in_block = (in_block + 1) % BLOCK;
213 }
214 index.offsets.push(index.deltas.len() as u64);
215 index.deltas.shrink_to_fit();
216 index
217 }
218
219 fn len(&self) -> usize {
220 self.len
221 }
222
223 /// The position of `id`, or `None` if it is not in the set.
224 fn find(&self, id: i64) -> Option<u64> {
225 let block = match self.bases.binary_search(&id) {
226 // A base is an id, so this is a hit on the first of a block.
227 Ok(block) => return Some((block * BLOCK) as u64),
228 // Before the first id in the set.
229 Err(0) => return None,
230 Err(next) => next - 1,
231 };
232 let mut current = self.bases[block];
233 let mut at = self.offsets[block] as usize;
234 let end = self.offsets[block + 1] as usize;
235 let mut position = 0usize;
236 while at < end {
237 let (gap, used) = get_uvarint(&self.deltas[at..]);
238 at += used;
239 current += gap as i64;
240 position += 1;
241 if current == id {
242 return Some((block * BLOCK + position) as u64);
243 }
244 // The block is ascending, so once it is past `id` the id is absent.
245 if current > id {
246 return None;
247 }
248 }
249 None
250 }
251
252 /// A cursor for a run of **ascending** lookups.
253 ///
254 /// [`Self::find`] pays a binary search over `bases` per call. That is the right shape for a random
255 /// lookup and the wrong one for the node pass, which asks about every node in a PBF block in
256 /// ascending order: `bases` grew from 53 MB on a us-west extract to 290 MB on a north-america one,
257 /// so each of those searches became about twenty-two cache misses plus the page walks to reach
258 /// them. Measured, the pass spent 317.9 s of CPU searching against 5.1 s writing, and went 90x
259 /// between those two extracts for 5.4x the nodes -- superlinear, because the array stopped
260 /// fitting rather than because there was more work.
261 ///
262 /// A cursor searches once and then walks, which is one sequential sweep instead of thousands of
263 /// scattered probes. Correct for any query order -- a query that goes backwards re-seeks -- so it
264 /// does not depend on the PBF actually being sorted, only on it usually being sorted to be fast.
265 fn cursor(&self) -> Cursor<'_> {
266 Cursor { index: self, block: 0, at: 0, current: 0, position: 0, live: false }
267 }
268}
269
270/// How many blocks a cursor will walk past before it gives up and searches instead.
271///
272/// Without a bound, a worker handed a distant blob would scan from wherever it happened to be, which
273/// is the pathological case this whole change is meant to avoid. Sixty-four blocks is 4096 ids: past
274/// that a binary search is cheaper than the walk.
275const FORWARD_SCAN_BLOCKS: usize = 64;
276
277/// A forward cursor into an [`IdIndex`]. See [`IdIndex::cursor`].
278struct Cursor<'a> {
279 index: &'a IdIndex,
280 /// The block the cursor sits inside.
281 block: usize,
282 /// Offset into `deltas` just past `current`.
283 at: usize,
284 /// The id the cursor is on.
285 current: i64,
286 /// Position of `current` in the set.
287 position: usize,
288 /// False before the first lookup, when `current` means nothing.
289 live: bool,
290}
291
292impl Cursor<'_> {
293 /// The position of `id`, or `None` if it is not in the set.
294 ///
295 /// Answers exactly what [`IdIndex::find`] would, which a test asserts over thousands of cases in
296 /// both ascending and shuffled order.
297 fn find(&mut self, id: i64) -> Option<u64> {
298 if !self.live || id < self.current || self.too_far(id) {
299 let block = match self.index.bases.binary_search(&id) {
300 Ok(block) => block,
301 // Before the first id in the set. The cursor is left alone: a miss says nothing about
302 // where the next hit will be.
303 Err(0) => return None,
304 Err(next) => next - 1,
305 };
306 self.enter(block);
307 }
308 while self.current < id {
309 if !self.step() {
310 return None;
311 }
312 }
313 if self.current == id {
314 Some(self.position as u64)
315 } else {
316 None
317 }
318 }
319
320 /// Whether `id` is far enough ahead that walking to it would cost more than a search.
321 fn too_far(&self, id: i64) -> bool {
322 let ahead = self.block + FORWARD_SCAN_BLOCKS;
323 ahead < self.index.bases.len() && self.index.bases[ahead] <= id
324 }
325
326 /// Sit on `block`'s first id.
327 fn enter(&mut self, block: usize) {
328 self.block = block;
329 self.current = self.index.bases[block];
330 self.at = self.index.offsets[block] as usize;
331 self.position = block * BLOCK;
332 self.live = true;
333 }
334
335 /// Move to the next id in the set. `false` at the end, leaving the cursor where it was.
336 fn step(&mut self) -> bool {
337 let end = self.index.offsets[self.block + 1] as usize;
338 if self.at < end {
339 let (gap, used) = get_uvarint(&self.index.deltas[self.at..]);
340 self.at += used;
341 self.current += gap as i64;
342 self.position += 1;
343 return true;
344 }
345 // The block is spent, and the next block's base is the next id.
346 if self.block + 1 >= self.index.bases.len() {
347 return false;
348 }
349 self.enter(self.block + 1);
350 true
351 }
352}
353
354/// LEB128, as the rest of this crate spells varints.
355fn put_uvarint(mut value: u64, out: &mut Vec<u8>) {
356 while value >= 0x80 {
357 out.push((value as u8) | 0x80);
358 value >>= 7;
359 }
360 out.push(value as u8);
361}
362
363/// Returns `(value, bytes consumed)`.
364fn get_uvarint(bytes: &[u8]) -> (u64, usize) {
365 let mut value = 0u64;
366 let mut shift = 0u32;
367 for (i, &b) in bytes.iter().enumerate() {
368 value |= ((b & 0x7f) as u64) << shift;
369 if b < 0x80 {
370 return (value, i + 1);
371 }
372 shift += 7;
373 }
374 (value, bytes.len())
375}
376
377impl NodeLocations {
378 /// `ids` need not be sorted or unique; both are done here.
379 ///
380 /// Fallible because the coordinate array is a mapped file, and a temporary directory that is full
381 /// or read-only is a real thing to report rather than to panic on.
382 pub fn new(mut ids: Vec<i64>) -> Result<NodeLocations> {
383 ids.sort_unstable();
384 ids.dedup();
385 let index = NodeIds::build(&ids);
386 // The plain vector goes here rather than being kept alongside: it is 8 bytes per id against
387 // the index's ~1.2, and holding both would give back the saving. Freed before the coordinate
388 // array is mapped, so the two never peak together.
389 drop(ids);
390 let locs = Locs::new(index.len())?;
391 Ok(NodeLocations { ids: index, locs })
392 }
393
394 /// The same table from an **ascending, unique** id stream of known length.
395 ///
396 /// [`Self::new`] takes a vector because most callers have one. A continental or planet extract
397 /// does not want one: [`crate::extract`]-shaped callers hold the needed ids as a bitset over the
398 /// node id space, which is a fixed ~1.7 GB for any extract, and turning that back into 8 bytes an
399 /// id to hand it over would be the allocation the bitset exists to avoid.
400 ///
401 /// **Sorted and unique is a precondition, not a request.** It is what makes every gap positive,
402 /// and an out-of-order id would encode as a ten-byte varint and quietly corrupt the index. A
403 /// bitset walked low to high satisfies it by construction, which is the only reason this is safe
404 /// to expose.
405 pub fn from_sorted(ids: impl Iterator<Item = i64>, len: usize) -> Result<NodeLocations> {
406 let index = NodeIds::build_sorted(ids, len);
407 let locs = Locs::new(index.len())?;
408 Ok(NodeLocations { ids: index, locs })
409 }
410
411 /// The same table from an already-populated bitset over the id space, taking ownership of its
412 /// words: bit `i` set iff id `i` is needed, `len` the number of set bits.
413 ///
414 /// [`Self::from_sorted`] walks the caller's bitset into ids and re-sets them here, holding two
415 /// words arrays at once. This moves the words across and builds the rank directory in place, so
416 /// the peak is one bitset rather than two. The only production caller is the planet ref
417 /// collector; the vector path ([`Self::new`]) is untouched.
418 pub fn from_bitset(words: Vec<u64>, len: usize) -> Result<NodeLocations> {
419 let index = NodeIds::from_words(words, len);
420 let locs = Locs::new(index.len())?;
421 Ok(NodeLocations { ids: index, locs })
422 }
423
424 pub fn len(&self) -> usize {
425 self.ids.len()
426 }
427
428 pub fn is_empty(&self) -> bool {
429 self.ids.len() == 0
430 }
431
432 fn index_of(&self, id: i64) -> Option<u64> {
433 self.ids.find(id)
434 }
435
436 /// Whether `id` is one of the ids this table was built for.
437 ///
438 /// Distinct from [`Self::get`] returning `None`, which also means "in the set but the node pass
439 /// never found it" -- the legitimate case at an extract's cut edges.
440 pub fn contains(&self, id: i64) -> bool {
441 self.index_of(id).is_some()
442 }
443
444 pub fn get(&self, id: i64) -> Option<(i32, i32)> {
445 self.locs.get(self.index_of(id)? as usize)
446 }
447
448 /// A way's geometry in lon/lat order, with unresolved refs skipped.
449 ///
450 /// A ref can be unresolved for a legitimate reason: an extract cut through the
451 /// way, so some of its nodes are simply not in the file. Skipping the gap keeps
452 /// the rest of the line rather than discarding the whole way, which is what
453 /// `osmium extract`'s `complete_ways` produces for the same input.
454 pub fn line(&self, refs: &[i64]) -> Vec<Coord> {
455 refs.iter()
456 .filter_map(|id| self.get(*id))
457 .map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7))
458 .collect()
459 }
460}
461
462include!("nodeloc_part1.rs");
463include!("nodeloc_part2.rs");