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

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

nodeloc.rs389 lines · 16.9 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 where it could not be unlinked at creation (Windows). Scratch, and large
61 /// enough that leaving it behind matters: 83 GB on a planet.
62 path: Option<PathBuf>,
63 len: usize,
64}
65
66impl Locs {
67 fn new(len: usize) -> Result<Locs> {
68 Self::new_in(&crate::mem::scratch_dir(), len)
69 }
70
71 /// [`new`](Self::new) with the scratch file in `dir`.
72 fn new_in(dir: &std::path::Path, len: usize) -> Result<Locs> {
73 if len == 0 {
74 return Ok(Locs { map: None, resolved: Vec::new(), path: None, len: 0 });
75 }
76 let path = dir.join(format!(
77 "osm_nodeloc_{}_{}.bin",
78 std::process::id(),
79 // Distinct per table, so two in one process cannot share a file.
80 NEXT_LOCS.fetch_add(1, atomic::Ordering::Relaxed),
81 ));
82 let bytes = len as u64 * 8;
83 let file = std::fs::OpenOptions::new()
84 .read(true)
85 .write(true)
86 .create(true)
87 .truncate(true)
88 .open(&path)
89 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
90 // Uncompressed on a `compress-force` btrfs: random 8-byte reads through the mapping
91 // must not inflate a 128 KiB extent per page fault, and coordinates do not compress
92 // anyway. Must precede `set_len`/any data; see `mark_scratch_uncompressed`.
93 crate::mem::mark_scratch_uncompressed(&file);
94 // Sets the length without writing anything: on both platforms this leaves a sparse or
95 // zero-filled file, so the 1.23 GB is not touched until a page is used.
96 file.set_len(bytes).map_err(|e| Error(format!("cannot size {}: {e}", path.display())))?;
97 // SAFETY: this process owns `path` exclusively — it is named after the pid and a counter, was
98 // just created with `truncate`, and is deleted in `Drop`. Nothing else can resize it while the
99 // mapping is live, which is the one thing that would make the slice dangle.
100 let map = unsafe { memmap2::MmapMut::map_mut(&file) }
101 .map_err(|e| Error(format!("cannot map {}: {e}", path.display())))?;
102 // The mapping keeps the file alive; its name can go now, so a process that dies -- an
103 // OOM kill, a SIGKILL -- leaves nothing behind (an orphaned 83 GB table in /tmp once
104 // failed the next planet build's disk gate). Where that is impossible, drop deletes it.
105 let path = if crate::mem::unlink_open_scratch(&path) { None } else { Some(path) };
106 Ok(Locs { map: Some(map), resolved: vec![0u64; len.div_ceil(64)], path, len })
107 }
108
109 fn set(&mut self, index: usize, lat_e7: i32, lon_e7: i32) {
110 let Some(map) = self.map.as_mut() else { return };
111 let at = index * 8;
112 map[at..at + 4].copy_from_slice(&lat_e7.to_le_bytes());
113 map[at + 4..at + 8].copy_from_slice(&lon_e7.to_le_bytes());
114 self.resolved[index / 64] |= 1 << (index % 64);
115 }
116
117 fn is_resolved(&self, index: usize) -> bool {
118 index < self.len && self.resolved[index / 64] & (1 << (index % 64)) != 0
119 }
120
121 fn get(&self, index: usize) -> Option<(i32, i32)> {
122 if index >= self.len || self.resolved[index / 64] & (1 << (index % 64)) == 0 {
123 return None;
124 }
125 let map = self.map.as_ref()?;
126 let at = index * 8;
127 let lat = i32::from_le_bytes(map[at..at + 4].try_into().expect("four bytes"));
128 let lon = i32::from_le_bytes(map[at + 4..at + 8].try_into().expect("four bytes"));
129 Some((lat, lon))
130 }
131}
132
133impl Drop for Locs {
134 fn drop(&mut self) {
135 // The mapping goes before the file, or Windows refuses the delete.
136 self.map = None;
137 if let Some(path) = self.path.take() {
138 let _ = std::fs::remove_file(path);
139 }
140 }
141}
142
143static NEXT_LOCS: atomic::AtomicU64 = atomic::AtomicU64::new(0);
144
145/// Ids per block of [`IdIndex`].
146///
147/// The trade is the usual one: a larger block amortises its 16 bytes of base and offset over more
148/// ids, and lengthens the scan that follows the binary search. 64 puts the overhead at 0.25 bytes per
149/// id and keeps the worst-case scan inside a couple of cache lines.
150const BLOCK: usize = 64;
151
152/// A sorted, unique id set as block bases plus varint gaps.
153///
154/// Searchable through `&self` alone, because [`resolve_nodes`] hands it to every worker in a PBF pass
155/// while the sink writes coordinates.
156///
157/// # When this is used, and when [`RankIndex`] is instead
158///
159/// This compressed form costs `O(count)` -- ~1.2 bytes per *needed* id -- so it is the right shape
160/// for a sub-continent extract, where the needed set is a sparse subset of a 13 G id space and a
161/// bitset over that space would dwarf it. [`NodeLocations::new`] builds it. The planet path
162/// ([`NodeLocations::from_sorted`], fed by a caller-side bitset) builds a [`RankIndex`] instead: at
163/// planet scale the needed set is most of the id space, so a rank-select bitset that costs
164/// `O(id space)` -- ~2 GB, bounded -- beats this index's ~12.9 GB, and its `find` is `O(1)` rather
165/// than a binary search plus a varint scan. [`NodeIds`] is the switch between the two.
166#[derive(Default)]
167struct IdIndex {
168 /// The first id of each block, ascending. What the binary search runs over.
169 bases: Vec<i64>,
170 /// Where each block's gaps start in `deltas`, with a sentinel so `offsets[b + 1]` is always the
171 /// end of block `b`.
172 ///
173 /// `u64`, not `u32`. It was `u32` behind a guard that errored when `deltas` outgrew 4.29 GB, and
174 /// at ~1.1 bytes per id that guard fires at roughly 3.9 G ids -- reached by a planet extract's
175 /// 9.5 G. Widening costs 4 bytes per block of 64 ids, which is 2.38 GB against 1.19 GB at planet
176 /// scale and noise against what the bitset in [`crate::extract`]'s caller saves.
177 offsets: Vec<u64>,
178 /// `BLOCK - 1` varint gaps per block, each the difference from the previous id.
179 deltas: Vec<u8>,
180 len: usize,
181}
182
183impl IdIndex {
184 /// Build from ids that are already sorted and unique.
185 ///
186 /// Infallible, and it was not. Two guards used to live here, one on the id count and one on the
187 /// delta bytes, because `find` returned a `u32` position and `offsets` held `u32` byte offsets --
188 /// and their own doc comment predicted that "both are within reach at planet scale and both fail
189 /// silently". They were right and they were reached, so the types were widened instead. Both
190 /// ceilings are now `u64`, which no extract of this planet can approach.
191 fn build(ids: &[i64]) -> IdIndex {
192 IdIndex::build_sorted(ids.iter().copied(), ids.len())
193 }
194
195 /// Build from an ascending, unique id **stream** of known length.
196 ///
197 /// The streaming form exists because a planet extract cannot afford the slice. [`crate::extract`]
198 /// gets its ids by walking a bitset over the node id space, and materialising them first would
199 /// be 8 bytes an id -- the very vector the bitset replaced.
200 ///
201 /// `len` sizes the three arenas up front and is not otherwise trusted: the index's own length is
202 /// what the stream actually yielded.
203 fn build_sorted(ids: impl Iterator<Item = i64>, len: usize) -> IdIndex {
204 let blocks = len.div_ceil(BLOCK);
205 let mut index = IdIndex {
206 bases: Vec::with_capacity(blocks),
207 offsets: Vec::with_capacity(blocks + 1),
208 // One byte per gap is the common case, so this is the right first guess.
209 deltas: Vec::with_capacity(len),
210 len: 0,
211 };
212 let mut in_block = 0usize;
213 let mut previous = 0i64;
214 for id in ids {
215 if in_block == 0 {
216 index.bases.push(id);
217 index.offsets.push(index.deltas.len() as u64);
218 } else {
219 // Non-negative because the input is sorted and unique, so the gap is at least one.
220 put_uvarint((id - previous) as u64, &mut index.deltas);
221 }
222 previous = id;
223 index.len += 1;
224 in_block = (in_block + 1) % BLOCK;
225 }
226 index.offsets.push(index.deltas.len() as u64);
227 index.deltas.shrink_to_fit();
228 index
229 }
230
231 fn len(&self) -> usize {
232 self.len
233 }
234
235 /// The position of `id`, or `None` if it is not in the set.
236 fn find(&self, id: i64) -> Option<u64> {
237 let block = match self.bases.binary_search(&id) {
238 // A base is an id, so this is a hit on the first of a block.
239 Ok(block) => return Some((block * BLOCK) as u64),
240 // Before the first id in the set.
241 Err(0) => return None,
242 Err(next) => next - 1,
243 };
244 let mut current = self.bases[block];
245 let mut at = self.offsets[block] as usize;
246 let end = self.offsets[block + 1] as usize;
247 let mut position = 0usize;
248 while at < end {
249 let (gap, used) = get_uvarint(&self.deltas[at..]);
250 at += used;
251 current += gap as i64;
252 position += 1;
253 if current == id {
254 return Some((block * BLOCK + position) as u64);
255 }
256 // The block is ascending, so once it is past `id` the id is absent.
257 if current > id {
258 return None;
259 }
260 }
261 None
262 }
263
264 /// A cursor for a run of **ascending** lookups.
265 ///
266 /// [`Self::find`] pays a binary search over `bases` per call. That is the right shape for a random
267 /// lookup and the wrong one for the node pass, which asks about every node in a PBF block in
268 /// ascending order: `bases` grew from 53 MB on a us-west extract to 290 MB on a north-america one,
269 /// so each of those searches became about twenty-two cache misses plus the page walks to reach
270 /// them. Measured, the pass spent 317.9 s of CPU searching against 5.1 s writing, and went 90x
271 /// between those two extracts for 5.4x the nodes -- superlinear, because the array stopped
272 /// fitting rather than because there was more work.
273 ///
274 /// A cursor searches once and then walks, which is one sequential sweep instead of thousands of
275 /// scattered probes. Correct for any query order -- a query that goes backwards re-seeks -- so it
276 /// does not depend on the PBF actually being sorted, only on it usually being sorted to be fast.
277 fn cursor(&self) -> Cursor<'_> {
278 Cursor { index: self, block: 0, at: 0, current: 0, position: 0, live: false }
279 }
280}
281
282/// How many blocks a cursor will walk past before it gives up and searches instead.
283///
284/// Without a bound, a worker handed a distant blob would scan from wherever it happened to be, which
285/// is the pathological case this whole change is meant to avoid. Sixty-four blocks is 4096 ids: past
286/// that a binary search is cheaper than the walk.
287const FORWARD_SCAN_BLOCKS: usize = 64;
288
289/// A forward cursor into an [`IdIndex`]. See [`IdIndex::cursor`].
290struct Cursor<'a> {
291 index: &'a IdIndex,
292 /// The block the cursor sits inside.
293 block: usize,
294 /// Offset into `deltas` just past `current`.
295 at: usize,
296 /// The id the cursor is on.
297 current: i64,
298 /// Position of `current` in the set.
299 position: usize,
300 /// False before the first lookup, when `current` means nothing.
301 live: bool,
302}
303
304impl Cursor<'_> {
305 /// The position of `id`, or `None` if it is not in the set.
306 ///
307 /// Answers exactly what [`IdIndex::find`] would, which a test asserts over thousands of cases in
308 /// both ascending and shuffled order.
309 fn find(&mut self, id: i64) -> Option<u64> {
310 if !self.live || id < self.current || self.too_far(id) {
311 let block = match self.index.bases.binary_search(&id) {
312 Ok(block) => block,
313 // Before the first id in the set. The cursor is left alone: a miss says nothing about
314 // where the next hit will be.
315 Err(0) => return None,
316 Err(next) => next - 1,
317 };
318 self.enter(block);
319 }
320 while self.current < id {
321 if !self.step() {
322 return None;
323 }
324 }
325 if self.current == id {
326 Some(self.position as u64)
327 } else {
328 None
329 }
330 }
331
332 /// Whether `id` is far enough ahead that walking to it would cost more than a search.
333 fn too_far(&self, id: i64) -> bool {
334 let ahead = self.block + FORWARD_SCAN_BLOCKS;
335 ahead < self.index.bases.len() && self.index.bases[ahead] <= id
336 }
337
338 /// Sit on `block`'s first id.
339 fn enter(&mut self, block: usize) {
340 self.block = block;
341 self.current = self.index.bases[block];
342 self.at = self.index.offsets[block] as usize;
343 self.position = block * BLOCK;
344 self.live = true;
345 }
346
347 /// Move to the next id in the set. `false` at the end, leaving the cursor where it was.
348 fn step(&mut self) -> bool {
349 let end = self.index.offsets[self.block + 1] as usize;
350 if self.at < end {
351 let (gap, used) = get_uvarint(&self.index.deltas[self.at..]);
352 self.at += used;
353 self.current += gap as i64;
354 self.position += 1;
355 return true;
356 }
357 // The block is spent, and the next block's base is the next id.
358 if self.block + 1 >= self.index.bases.len() {
359 return false;
360 }
361 self.enter(self.block + 1);
362 true
363 }
364}
365
366/// LEB128, as the rest of this crate spells varints.
367fn put_uvarint(mut value: u64, out: &mut Vec<u8>) {
368 while value >= 0x80 {
369 out.push((value as u8) | 0x80);
370 value >>= 7;
371 }
372 out.push(value as u8);
373}
374
375/// Returns `(value, bytes consumed)`.
376fn get_uvarint(bytes: &[u8]) -> (u64, usize) {
377 let mut value = 0u64;
378 let mut shift = 0u32;
379 for (i, &b) in bytes.iter().enumerate() {
380 value |= ((b & 0x7f) as u64) << shift;
381 if b < 0x80 {
382 return (value, i + 1);
383 }
384 shift += 7;
385 }
386 (value, bytes.len())
387}
388
389include!("nodeloc_s1.rs");