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