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

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

nodeloc_part1.rs395 lines · 17.7 KiBRaw
1/// The node pass: fill in every coordinate the earlier passes asked for.
2///
3/// Uses [`pbf::run_pass_sink`] rather than [`pbf::run_pass`], because `run_pass`'s contract is to
4/// hand every chunk's accumulator back at once and these accumulators are the largest thing this
5/// pass touches. On California they are 154 M nodes at 16 bytes -- about 2.5 GB -- and they would be
6/// alive next to the 2.5 GB table they are about to be folded into, so the two peak together. Here a
7/// chunk is folded and freed while its neighbours are still decoding, which also overlaps the merge
8/// with the I/O. `pbf.rs` names this exact hazard in `run_pass_sink`'s own doc comment.
9///
10/// The merge order is unchanged: `run_pass_sink` calls its sink in chunk order, which is the order
11/// `run_pass` returned chunks in, so two blocks reporting the same node still resolve to the same
12/// coordinate.
13pub fn resolve_nodes(
14 input: &Path,
15 blobs: &[pbf::BlobLoc],
16 blob_kinds: &[u8],
17 label: &str,
18 table: NodeLocations,
19) -> Result<NodeLocations> {
20 if table.is_empty() {
21 return Ok(table);
22 }
23 // The plain node pass: coordinates only, no per-node classification. `road_graph` and the
24 // `osm_ingest` extract take this path; `mamaps_build` takes [`resolve_nodes_with`] to fold its
25 // label-node classification into the same inflate.
26 resolve_nodes_with(
27 input,
28 blobs,
29 blob_kinds,
30 label,
31 table,
32 |_: &NodeView| Option::<()>::None,
33 |_: Vec<()>| Ok(()),
34 )
35}
36
37/// [`resolve_nodes`] plus a per-node classification folded into the same pass.
38///
39/// The node region of a planet PBF is most of the file, so a caller that also needs to classify
40/// nodes -- `mamaps_build` spilling `places`/`poi` label points -- would otherwise inflate it a
41/// second time. `classify` runs inside the block visitor, in parallel with every other block, and
42/// must be pure: it sees one [`NodeView`] and returns an owned item or `None`. `drain` then receives
43/// each chunk's collected items **in chunk order**, serialised behind the same lock the coordinate
44/// writes go through, so a caller can push them straight to a sink without reordering the output.
45///
46/// The classification runs over every node blob regardless of whether the coordinate table is empty,
47/// because a label set is independent of the way-ref set the coordinates serve.
48pub fn resolve_nodes_with<L, C, D>(
49 input: &Path,
50 blobs: &[pbf::BlobLoc],
51 blob_kinds: &[u8],
52 label: &str,
53 mut table: NodeLocations,
54 classify: C,
55 mut drain: D,
56) -> Result<NodeLocations>
57where
58 L: Send,
59 C: Fn(&NodeView) -> Option<L> + Sync,
60 D: FnMut(Vec<L>) -> Result<()> + Send,
61{
62 // Moved out so the workers can search it while the sink writes coordinates; put back below.
63 let ids = std::mem::take(&mut table.ids);
64 let locs = &mut table.locs;
65 pbf::run_pass_sink(
66 input,
67 blobs,
68 Some(blob_kinds),
69 KIND_NODES,
70 label,
71 || (Vec::<(u64, i32, i32)>::new(), Vec::<L>::new()),
72 |state: &mut (Vec<(u64, i32, i32)>, Vec<L>), block| {
73 let mut kinds = 0u8;
74 // One cursor per block, because that is the run of ascending ids: a PBF block's dense
75 // nodes are delta-encoded and therefore sorted, so this pays one binary search here and
76 // walks the rest.
77 let mut cursor = ids.cursor();
78 visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {
79 if let Element::Node(n) = el {
80 if let Some(idx) = cursor.find(n.id) {
81 state.0.push((idx, n.lat_e7, n.lon_e7));
82 }
83 if let Some(item) = classify(&n) {
84 state.1.push(item);
85 }
86 }
87 Ok(())
88 })?;
89 Ok(kinds)
90 },
91 |(coords, items)| {
92 // Sorted by table index before the stores, so the mmap writes walk forward
93 // instead of scattering: a chunk's ids arrive in block order (ascending within
94 // a block, but blocks interleave across the chunk), and 8-byte stores to
95 // 1.23 GB touch one page per store when they jump. Ascending stores fault
96 // pages in order and reuse the TLB entry. Byte-identical: the table holds
97 // one coordinate per index and the bitset is order-independent, so write
98 // order is not observable. `items` (the classification drain) keeps its
99 // own order — only the coordinate writes are reordered.
100 let mut coords = coords;
101 coords.sort_unstable_by_key(|c| c.0);
102 for (idx, lat, lon) in coords {
103 locs.set(idx as usize, lat, lon);
104 }
105 // After the coordinate writes, so a caller that both resolves and classifies sees the
106 // two in the order this pass names them.
107 drain(items)?;
108 Ok(())
109 },
110 )?;
111 table.ids = ids;
112 Ok(table)
113}
114
115#[cfg(test)]
116mod tests {
117 /// **The test the cursor lives or dies by.** It has to answer exactly what [`IdIndex::find`] does
118 /// for every id, in ascending order (its fast path), in shuffled order (where it must re-seek),
119 /// and for ids that are absent — including ones below the first and above the last.
120 ///
121 /// Ascending alone would not catch it: the whole risk of a cursor is that it is correct while
122 /// walking forwards and wrong the moment something asks out of order, and nothing in the PBF
123 /// format actually promises sorted ids.
124 #[test]
125 fn the_cursor_answers_exactly_what_a_fresh_search_would() {
126 let mut state = 0x9E37_79B9_7F4A_7C15u64;
127 let mut next = || {
128 state ^= state << 13;
129 state ^= state >> 7;
130 state ^= state << 17;
131 state
132 };
133 // Spans several blocks, with gaps too large for a one-byte varint so the walk has to handle
134 // multi-byte deltas, and a run of dense ids so it handles the cheap case too.
135 let mut ids: Vec<i64> = Vec::new();
136 let mut id = 5i64;
137 for i in 0..1000 {
138 id += if i % 7 == 0 { (next() % 300_000) as i64 + 1 } else { (next() % 4) as i64 + 1 };
139 ids.push(id);
140 }
141 ids.sort_unstable();
142 ids.dedup();
143 let index = super::IdIndex::build(&ids);
144
145 // Every id, ascending: the path the node pass actually takes.
146 let mut cursor = index.cursor();
147 for &want in &ids {
148 assert_eq!(cursor.find(want), index.find(want), "ascending, id {want}");
149 }
150
151 // Absent ids interleaved with present ones, still ascending.
152 let mut cursor = index.cursor();
153 for &want in &ids {
154 assert_eq!(cursor.find(want - 1), index.find(want - 1), "ascending gap below {want}");
155 assert_eq!(cursor.find(want), index.find(want), "ascending, id {want}");
156 }
157
158 // Shuffled, which forces a re-seek on most calls.
159 let mut shuffled = ids.clone();
160 for i in (1..shuffled.len()).rev() {
161 shuffled.swap(i, (next() % (i as u64 + 1)) as usize);
162 }
163 let mut cursor = index.cursor();
164 for &want in &shuffled {
165 assert_eq!(cursor.find(want), index.find(want), "shuffled, id {want}");
166 }
167
168 // Strictly descending, the worst order for a forward cursor.
169 let mut cursor = index.cursor();
170 for &want in ids.iter().rev() {
171 assert_eq!(cursor.find(want), index.find(want), "descending, id {want}");
172 }
173
174 // Outside the set at both ends, and far enough past the end to trip the scan bound.
175 let first = ids[0];
176 let last = ids[ids.len() - 1];
177 let mut cursor = index.cursor();
178 for want in [i64::MIN, first - 1, 0, last + 1, last + 10_000_000, i64::MAX] {
179 assert_eq!(cursor.find(want), index.find(want), "outside, id {want}");
180 }
181
182 // A jump far ahead then far back, which is what work stealing does to a live cursor.
183 let mut cursor = index.cursor();
184 assert_eq!(cursor.find(ids[0]), index.find(ids[0]));
185 assert_eq!(cursor.find(last), index.find(last));
186 assert_eq!(cursor.find(ids[0]), index.find(ids[0]));
187 assert_eq!(cursor.find(ids[ids.len() / 2]), index.find(ids[ids.len() / 2]));
188 }
189
190 /// The cursor must be right on a set small enough to have one partial block, where `position`
191 /// arithmetic that assumed full blocks would still look plausible.
192 #[test]
193 fn the_cursor_is_right_on_a_set_smaller_than_one_block() {
194 for count in [1usize, 2, 63, 64, 65, 129] {
195 let ids: Vec<i64> = (0..count as i64).map(|i| i * 3 + 11).collect();
196 let index = super::IdIndex::build(&ids);
197 let mut cursor = index.cursor();
198 for &want in &ids {
199 assert_eq!(cursor.find(want), index.find(want), "{count} id(s), id {want}");
200 }
201 let mut cursor = index.cursor();
202 for &want in &ids {
203 let miss = want + 1;
204 assert_eq!(cursor.find(miss), index.find(miss), "{count} id(s), absent {miss}");
205 }
206 }
207 }
208
209 /// **The test the compressed index lives or dies by.** It has to answer exactly what a plain
210 /// `binary_search` over the same ids would, for ids that are present and ids that are not, and it
211 /// has to hold at block boundaries and across gaps too large for a one-byte varint.
212 ///
213 /// Driven by a deterministic LCG rather than a fixed list so it covers thousands of cases and
214 /// still fails identically every run.
215 #[test]
216 fn the_compressed_index_answers_exactly_what_a_binary_search_would() {
217 let mut state = 0x2545_F491_4F6C_DD1Du64;
218 let mut next = || {
219 state ^= state << 13;
220 state ^= state >> 7;
221 state ^= state << 17;
222 state
223 };
224
225 // Gaps drawn so most are tiny (the real distribution) and some are enormous, which is what
226 // forces multi-byte varints.
227 let mut ids: Vec<i64> = Vec::new();
228 let mut id: i64 = 1;
229 for _ in 0..5_000 {
230 let r = next();
231 let gap = match r % 100 {
232 0 => (r >> 8) % 5_000_000 + 1,
233 1..=9 => (r >> 8) % 1_000 + 1,
234 _ => (r >> 8) % 4 + 1,
235 };
236 id += gap as i64;
237 ids.push(id);
238 }
239 let index = IdIndex::build(&ids);
240 assert_eq!(index.len(), ids.len());
241
242 // Every id present resolves to its own position.
243 for (position, &id) in ids.iter().enumerate() {
244 assert_eq!(index.find(id), Some(position as u64), "id {id} at {position}");
245 }
246 // And nothing else resolves at all. Probing every id +/- 1 covers the interesting misses:
247 // just below a hit, just above one, and inside a gap.
248 for &id in &ids {
249 for probe in [id - 1, id + 1] {
250 let expected = ids.binary_search(&probe).ok().map(|i| i as u64);
251 assert_eq!(index.find(probe), expected, "probe {probe}");
252 }
253 }
254 // Outside the set entirely, at both ends.
255 assert_eq!(index.find(0), None);
256 assert_eq!(index.find(i64::MIN), None);
257 assert_eq!(index.find(ids[ids.len() - 1] + 1), None);
258 assert_eq!(index.find(i64::MAX), None);
259 }
260
261 /// A block boundary is the one place an off-by-one would hide, so it is checked directly rather
262 /// than left to the random case.
263 #[test]
264 fn a_block_boundary_resolves_on_both_sides() {
265 // Three full blocks and a partial one, with a gap of exactly one so positions and ids differ
266 // by a constant and an off-by-one is unmissable.
267 let ids: Vec<i64> = (0..BLOCK as i64 * 3 + 7).map(|i| 1_000 + i).collect();
268 let index = IdIndex::build(&ids);
269 for (position, &id) in ids.iter().enumerate() {
270 assert_eq!(index.find(id), Some(position as u64));
271 }
272 // The first id of each block is a base, which is the branch that returns without scanning.
273 for block in 0..4 {
274 let position = block * BLOCK;
275 if position < ids.len() {
276 assert_eq!(index.find(ids[position]), Some(position as u64));
277 }
278 }
279 assert_eq!(index.find(999), None, "below the set");
280 assert_eq!(index.find(1_000 + ids.len() as i64), None, "above the set");
281 }
282
283 #[test]
284 fn an_empty_or_single_id_set_is_not_a_special_case_that_panics() {
285 let empty = IdIndex::build(&[]);
286 assert_eq!(empty.len(), 0);
287 assert_eq!(empty.find(1), None);
288
289 let one = IdIndex::build(&[42]);
290 assert_eq!(one.len(), 1);
291 assert_eq!(one.find(42), Some(0));
292 assert_eq!(one.find(41), None);
293 assert_eq!(one.find(43), None);
294 }
295
296 /// The saving this was done for. A plain `Vec<i64>` is 8 bytes an id; this has to be a small
297 /// fraction of that or it is not worth the scan.
298 #[test]
299 fn the_index_costs_about_one_byte_per_id() {
300 // Gaps of one to four, which is roughly what a real needed-node set looks like.
301 let ids: Vec<i64> = (0..100_000i64).map(|i| 5 + i * 3).collect();
302 let index = IdIndex::build(&ids);
303 let bytes = index.bases.len() * 8 + index.offsets.len() * 8 + index.deltas.len();
304 let plain = ids.len() * 8;
305 assert!(
306 bytes * 4 < plain,
307 "the index is {bytes} bytes against {plain} for a plain vector, which is not worth it",
308 );
309 }
310
311 /// What replaces the two `u32` guards that used to live in [`IdIndex::build`].
312 ///
313 /// They errored when the id count or the delta bytes passed `u32::MAX`, and their own doc
314 /// comment said both were within reach at planet scale. They were, so the fields were widened
315 /// instead -- and a guard removed with nothing put in its place is how a ceiling comes back.
316 ///
317 /// Two halves, because only one of them is affordable. The reachable half is ids whose *values*
318 /// are past `u32::MAX`: OSM node ids are near 13 G today, so this is the real input, and it
319 /// exercises the multi-byte varint gaps a sparse set produces. The unreachable half is the
320 /// cardinality itself -- 4.29 G ids is ~4.7 GB of deltas and 67 M blocks, which no test can
321 /// allocate -- so it is pinned as the types rather than as an allocation.
322 #[test]
323 fn ids_past_the_old_u32_ceilings_build_and_resolve() {
324 // Spread from just under `u32::MAX` to past OSM's own high-water mark, with gaps large
325 // enough that most encode to several varint bytes.
326 let mut ids: Vec<i64> = Vec::new();
327 let mut id = u32::MAX as i64 - 5;
328 for i in 0..5_000i64 {
329 ids.push(id);
330 id += 1 + (i % 7) * 1_000_003;
331 }
332 assert!(*ids.last().expect("ids") > 13_000_000_000, "the set must reach planet-scale ids");
333 let index = IdIndex::build(&ids);
334 assert_eq!(index.len(), ids.len());
335
336 // Every id resolves to its own position, by search and by cursor, and nothing else resolves.
337 let mut cursor = index.cursor();
338 for (position, &id) in ids.iter().enumerate() {
339 assert_eq!(index.find(id), Some(position as u64), "id {id}");
340 assert_eq!(cursor.find(id), Some(position as u64), "id {id} by cursor");
341 }
342 for &id in &ids {
343 assert_eq!(index.find(id - 1), ids.binary_search(&(id - 1)).ok().map(|i| i as u64));
344 }
345
346 // And the fields themselves. A position and a delta offset must both be `u64`, or the
347 // ceiling is back and only a planet-sized allocation would find it.
348 let _: Option<u64> = index.find(ids[0]);
349 let _: Option<u64> = index.cursor().find(ids[0]);
350 let _: &Vec<u64> = &index.offsets;
351 }
352
353 #[test]
354 fn a_varint_round_trips_at_every_width() {
355 for value in [0u64, 1, 0x7f, 0x80, 0x3fff, 0x4000, u32::MAX as u64, u64::MAX] {
356 let mut bytes = Vec::new();
357 put_uvarint(value, &mut bytes);
358 let (read, used) = get_uvarint(&bytes);
359 assert_eq!((read, used), (value, bytes.len()), "value {value}");
360 }
361 }
362 use super::*;
363
364 #[test]
365 fn node_locations_are_keyed_by_a_sorted_table_not_by_raw_node_id() {
366 // The point of the pattern: memory is O(needed), so ids can be as large as
367 // OSM's real ones without allocating anything proportional to them.
368 let huge = 12_345_678_901i64;
369 let mut table = NodeLocations::new(vec![huge, 5, 5, 1]).expect("map the coordinate file");
370 assert_eq!(table.len(), 3, "sorted and deduped");
371 assert_eq!(table.get(5), None, "unresolved until the node pass fills it");
372 // Fill by index, as the merge does.
373 let idx = table.index_of(5).unwrap() as usize;
374 table.locs.set(idx, 377_900_000, -1_224_200_000);
375 assert_eq!(table.get(5), Some((377_900_000, -1_224_200_000)));
376 assert_eq!(table.get(huge), None);
377 assert_eq!(table.get(999), None, "not in the table at all");
378 }
379
380 #[test]
381 fn an_unresolved_ref_leaves_a_gap_rather_than_dropping_the_way() {
382 // An extract that cuts through a way leaves some of its nodes out of the
383 // file. Keeping the rest is what osmium's complete_ways produces too.
384 let mut table = NodeLocations::new(vec![1, 2, 3]).expect("map the coordinate file");
385 for (id, lat, lon) in [(1i64, 370_000_000, -1_220_000_000), (3, 370_020_000, -1_220_020_000)] {
386 let idx = table.index_of(id).unwrap() as usize;
387 table.locs.set(idx, lat, lon);
388 }
389 let line = table.line(&[1, 2, 3]);
390 assert_eq!(line.len(), 2, "the middle vertex is missing, not the way");
391 // lon/lat order, as GeoJSON wants.
392 assert!((line[0].0 - -122.0).abs() < 1e-9);
393 assert!((line[0].1 - 37.0).abs() < 1e-9);
394 }
395}