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

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

chains.rs431 lines · 17.4 KiBRaw
1//! Within-way chain building: degree-2 collapsing that never materialises a
2//! segment array.
3//!
4//! [`crate::compact`] does the same job by building every segment, indexing them
5//! into a CSR of incidences, and walking chains across way boundaries. That is
6//! the better graph and the wrong shape for a planet: the segment array and its
7//! incidence index are 114 GB of a 217 GB working set, and no amount of shrinking
8//! records closes that on a 94 GB machine.
9//!
10//! This module gets the same collapse from two much smaller structures:
11//!
12//! * **one byte of degree per node**, accumulated by a pass that reads the way
13//! blobs and keeps nothing;
14//! * **the way's own ref list**, walked positionally as it is decoded.
15//!
16//! # What it costs
17//!
18//! Chains may not cross from one OSM way into another. Every segment in a chain
19//! then shares its way's type, speed limit, name, one-way-ness and lane masks *by
20//! construction*, so the entire attribute-agreement half of
21//! `compact::classify` — and the segment records it compared — disappears.
22//!
23//! The price is real and is an accepted regression: a node where two different
24//! ways meet end-to-end with matching tags is collapsed by `compact` and kept
25//! here. OSM splits long roads constantly, at every tag change and at the
26//! 2000-node way ceiling, so this is not a rare case. Two things soften it: the
27//! 256-point budget already forces cuts on long dense roads anyway, and more
28//! surviving nodes strictly *improves* snapping.
29//!
30//! # What it buys beyond memory
31//!
32//! Two correctness simplifications fall out of walking positions instead of a
33//! graph:
34//!
35//! * the walk cannot loop, because it advances through a finite ref list, so
36//! there is no "used" flag per segment and no anchorless-cycle phase — a ring
37//! way closes on its own first node for free;
38//! * within one way every segment runs along ref order, so a one-way chain is
39//! already oriented along its traffic and there is no reorientation step to get
40//! the forward and backward lane masks the wrong way round.
41//!
42//! Both of those were bugs that had to be fixed once already.
43
44use std::fs::File;
45use std::io::{BufWriter, Write};
46use std::path::{Path, PathBuf};
47
48use crate::compact::Chain;
49use crate::geom;
50use crate::graph_build::{way_attrs, AtomicBits, Bitset, NodeIndex, WayAttrs};
51use crate::names::{LocalNames, NamePool, NO_NAME};
52use crate::osm::{visit_block, Element};
53use crate::pbf::{self, BlobLoc, KIND_WAYS};
54use crate::proto::{Error, Result};
55use crate::spatial::accurate_dist_mm;
56use crate::tags;
57
58/// Is this consecutive pair of way refs a segment of the graph?
59///
60/// **Both the degree pass and the chain walk must ask this and nothing else.**
61/// The degree array is what decides where a chain is cut, so a disagreement
62/// between the two would either dead-end a chain at a node the degree array
63/// thinks is a pass-through, or walk a chain straight through one it thinks is a
64/// junction. Every other invariant here is recoverable; this one is not.
65#[inline]
66pub(crate) fn segment(index: &NodeIndex, a: i64, b: i64) -> Option<(u32, u32)> {
67 let (u, v) = (index.dense(a)?, index.dense(b)?);
68 // A way listing the same node twice in a row is a mapping artefact, not a
69 // zero-length road. Counting it would give that node two phantom incidences
70 // and so promote a genuine pass-through into a junction.
71 (u != v).then_some((u, v))
72}
73
74/// Nodes with more incidences than a byte can hold are junctions whatever the
75/// true count is, so the counter saturates. Only `== 2` changes a decision, and
76/// no node with 255 incidences is a pass-through.
77///
78/// Counted straight into the shared array from the decode workers: a
79/// saturating increment commutes (the result is `min(255, incidences)` in any
80/// order), so nothing reaches the sink and nothing about the order of chunks
81/// can show. The sink used to scatter every endpoint single-threaded, which
82/// bounded the whole pass to one core.
83#[derive(Default)]
84struct DegreePass;
85
86/// Saturating `+1` on a shared degree byte.
87#[inline]
88fn bump(d: &std::sync::atomic::AtomicU8) {
89 use std::sync::atomic::Ordering::Relaxed;
90 let _ = d.fetch_update(Relaxed, Relaxed, |v| v.checked_add(1));
91}
92
93/// One saturating incidence count per dense node id.
94///
95/// `filter` drops segments the same way the chain walk does: a way no node of
96/// which touches the region contributes no incidence, so its nodes stay degree
97/// 0 and never survive. Both this and [`build`] must ask the same question —
98/// see [`segment`] — or a chain dead-ends where the degrees say pass-through.
99///
100/// The region test reads pass 2's `coords`, exactly as [`build`]'s does. It used
101/// to resolve the marked nodes' locations again in a side table with an extra
102/// node scan; that table held the same coordinates for the same nodes
103/// (`coords[d]` is set for exactly the nodes `index.dense` accepts), so the
104/// test is unchanged and the scan is gone.
105pub(crate) fn count_degrees(
106 input: &Path,
107 blobs: &[BlobLoc],
108 blob_kinds: &[u8],
109 index: &NodeIndex,
110 coords: &[geom::Pt],
111 slots: u32,
112 filter: crate::graph_build::RegionFilter,
113) -> Result<Vec<u8>> {
114 let mut degree = vec![0u8; slots as usize];
115 {
116 let bytes: &mut [u8] = &mut degree;
117 // SAFETY: `AtomicU8` has the layout of `u8`, and the exclusive borrow of
118 // `degree` is held for as long as this view lives.
119 let shared: &[std::sync::atomic::AtomicU8] =
120 unsafe { &*(bytes as *mut [u8] as *const [std::sync::atomic::AtomicU8]) };
121 let touches = |refs: &[i64]| -> bool {
122 let Some(b) = filter.as_ref() else {
123 return true;
124 };
125 refs.iter().any(|r| {
126 index.dense(*r).is_some_and(|d| {
127 let (lat, lon) = coords[d as usize];
128 b.contains_e7(lat, lon)
129 })
130 })
131 };
132 let _ = pbf::run_pass_sink(
133 input,
134 blobs,
135 pbf::PassSpec {
136 blob_kinds: Some(blob_kinds),
137 want: KIND_WAYS,
138 label: "Pass 3: node degrees",
139 },
140 DegreePass::default,
141 |_state: &mut DegreePass, block| {
142 let mut kinds = 0u8;
143 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
144 if let Element::Way(w) = el {
145 if tags::get_hw_id(w.tags.get_str("highway")) != 0 && touches(w.refs) {
146 for pair in w.refs.windows(2) {
147 if let Some((u, v)) = segment(index, pair[0], pair[1]) {
148 bump(&shared[u as usize]);
149 bump(&shared[v as usize]);
150 }
151 }
152 }
153 }
154 Ok(())
155 })?;
156 Ok(kinds)
157 },
158 |_chunk| Ok(()),
159 )?;
160 }
161 Ok(degree)
162}
163
164/// Every chain in the file, plus the lane pool their offsets point into.
165/// What the chain pass leaves behind. The chains themselves are on disk.
166pub(crate) struct Chains {
167 pub chain_count: u64,
168 pub lanes: Vec<u16>,
169 /// Dense ids a chain starts or ends at. Together with "degree is not 2" this
170 /// is the surviving-node set.
171 pub endpoints: Bitset,
172 /// Chains cut because their geometry would not fit one edge.
173 pub splits: usize,
174 /// Directed edges an uncompacted build would have produced. Runs tile every
175 /// segment exactly once, so this is exact without keeping the segments.
176 pub raw_edge_count: u64,
177 /// Which blobs the chain pass actually had to read. The load-bearing
178 /// measurement for re-reading the way blobs rather than caching them.
179 pub kinds: Vec<u8>,
180}
181
182#[derive(Default)]
183struct ChainPass {
184 /// `chains.hdr` records, pre-encoded on the worker with CHUNK-LOCAL
185 /// `pts_start`, name id and lane offsets; the sink rebases those three
186 /// fields in place ([`rebase_header`]) and appends the bytes.
187 hdr: Vec<u8>,
188 /// `chains.pts` bytes for this chunk's chains, coordinates already
189 /// resolved — the random `coords` reads now happen on the pool instead of
190 /// in the single-threaded sink.
191 pts: Vec<u8>,
192 /// Points in `pts`, i.e. the next chain's chunk-local `pts_start`.
193 points: u64,
194 lanes: Vec<u16>,
195 names: LocalNames,
196 splits: usize,
197 raw_edge_count: u64,
198}
199
200/// Walk every routable way, cutting chains at nodes that must survive, and stream
201/// the result into `spill`.
202///
203/// `degree` comes from [`count_degrees`] and `stop` marks nodes carrying a
204/// transit stop code; both are indexed by dense id, as is `coords`.
205///
206/// Nothing chain-shaped is retained. Only one chunk's worth exists at a time,
207/// which is what keeps this pass's footprint proportional to a chunk rather than
208/// to the road network.
209///
210/// The workers do everything that does not depend on earlier chunks: encode
211/// each header record, resolve every point to coordinates, and mark chain
212/// endpoints (a set union, straight into a shared bitset). The ordered sink
213/// does only what does: intern the chunk's names, rebase the lane pool and the
214/// point offsets, and append two byte buffers. Same bytes as encoding each
215/// chain in the sink.
216#[allow(clippy::too_many_arguments)]
217pub(crate) fn build<W: Write + Send>(
218 input: &Path,
219 blobs: &[BlobLoc],
220 blob_kinds: &[u8],
221 index: &NodeIndex,
222 coords: &[geom::Pt],
223 degree: &[u8],
224 stop: &Bitset,
225 slots: u32,
226 filter: crate::graph_build::RegionFilter,
227 pool: &mut NamePool<W>,
228 spill: &Spill,
229) -> Result<Chains> {
230 let mut endpoints = Bitset::new(u64::from(slots));
231 let mut lanes: Vec<u16> = Vec::new();
232 let mut splits = 0usize;
233 let mut raw_edge_count = 0u64;
234 let mut writer = spill.writer()?;
235 let kinds = {
236 let ends = endpoints.atomic();
237 pbf::run_pass_sink(
238 input,
239 blobs,
240 pbf::PassSpec {
241 blob_kinds: Some(blob_kinds),
242 want: KIND_WAYS,
243 label: "Pass 4: chains",
244 },
245 ChainPass::default,
246 |state: &mut ChainPass, block| {
247 chain_blob(state, block, index, coords, degree, stop, filter, &ends)
248 },
249 |mut chunk| {
250 let name_map = chunk.names.flush(pool).map_err(|e| Error(e.to_string()))?;
251 let lane_base = lanes.len() as u32;
252 lanes.extend_from_slice(&chunk.lanes);
253 crate::graph_build::cap_lane_pool(lanes.len())?;
254 let points_base = writer.points;
255 for rec in chunk.hdr.chunks_exact_mut(CHAIN_REC_BYTES as usize) {
256 rebase_header(rec, points_base, &name_map, lane_base);
257 }
258 writer.push_encoded(
259 std::mem::take(&mut chunk.hdr),
260 std::mem::take(&mut chunk.pts),
261 chunk.points,
262 )?;
263 splits += chunk.splits;
264 raw_edge_count += chunk.raw_edge_count;
265 Ok(())
266 },
267 )?
268 };
269 let chain_count = writer.finish()?;
270 Ok(Chains { chain_count, lanes, endpoints, splits, raw_edge_count, kinds })
271}
272
273/// Turn a worker-encoded header's chunk-local fields into global ones: exactly
274/// what the sink used to do to the `Chain` before encoding it.
275#[inline]
276fn rebase_header(rec: &mut [u8], points_base: u64, name_map: &[u32], lane_base: u32) {
277 let u32_at = |r: &[u8], o: usize| u32::from_le_bytes(r[o..o + 4].try_into().expect("4 bytes"));
278 let u16_at = |r: &[u8], o: usize| u16::from_le_bytes(r[o..o + 2].try_into().expect("2 bytes"));
279 let start = u64::from_le_bytes(rec[0..8].try_into().expect("8 bytes")) + points_base;
280 rec[0..8].copy_from_slice(&start.to_le_bytes());
281 let name = u32_at(rec, 24);
282 let name = if name == u32::MAX { NO_NAME } else { name_map[name as usize] };
283 rec[24..28].copy_from_slice(&name.to_le_bytes());
284 if u16_at(rec, 36) > 0 {
285 let off = u32_at(rec, 28) + lane_base;
286 rec[28..32].copy_from_slice(&off.to_le_bytes());
287 }
288 if u16_at(rec, 38) > 0 {
289 let off = u32_at(rec, 32) + lane_base;
290 rec[32..36].copy_from_slice(&off.to_le_bytes());
291 }
292}
293
294#[allow(clippy::too_many_arguments)]
295fn chain_blob(
296 state: &mut ChainPass,
297 block: &pbf::PrimitiveBlock,
298 index: &NodeIndex,
299 coords: &[geom::Pt],
300 degree: &[u8],
301 stop: &Bitset,
302 filter: crate::graph_build::RegionFilter,
303 ends: &AtomicBits,
304) -> Result<u8> {
305 let mut kinds = 0u8;
306 let mut path: Vec<u32> = Vec::new();
307 let mut hops: Vec<u32> = Vec::new();
308 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
309 let Element::Way(w) = el else {
310 return Ok(());
311 };
312 let type_ = tags::get_hw_id(w.tags.get_str("highway"));
313 if type_ == 0 {
314 return Ok(());
315 }
316 // Region filter: keep the way when ANY node touches the box. Coords
317 // are resolved by now so this is a direct test, same rule as the
318 // reference path's `way_blob`.
319 if let Some(b) = filter.as_ref() {
320 let mut touches = false;
321 for r in w.refs {
322 if let Some(d) = index.dense(*r) {
323 let (lat_e7, lon_e7) = coords[d as usize];
324 if b.contains_e7(lat_e7, lon_e7) {
325 touches = true;
326 break;
327 }
328 }
329 }
330 if !touches {
331 return Ok(());
332 }
333 }
334 let attrs = way_attrs(&w, type_, &mut state.lanes, &mut state.names);
335 path.clear();
336 hops.clear();
337 for pair in w.refs.windows(2) {
338 let Some((u, v)) = segment(index, pair[0], pair[1]) else {
339 // Not a segment — a dangling ref, or the way listing one node
340 // twice in a row. Skip it and let the next accepted pair decide
341 // whether it continues this run.
342 continue;
343 };
344 if path.last() != Some(&u) {
345 // The start of the way, the far side of a gap the graph does not
346 // bridge, or the node the previous cut ended on.
347 flush(state, &path, &hops, &attrs, coords, ends);
348 path.clear();
349 hops.clear();
350 path.push(u);
351 }
352 let (a, b) = (coords[u as usize], coords[v as usize]);
353 hops.push(accurate_dist_mm(a.0, a.1, b.0, b.1));
354 path.push(v);
355 // `v` must survive when it is a junction, a dead end, or a transit
356 // stop the reconnect pass addresses directly. Cut there; the next pair
357 // restarts from it by the rule above.
358 if degree[v as usize] != 2 || stop.get(u64::from(v)) {
359 flush(state, &path, &hops, &attrs, coords, ends);
360 path.clear();
361 hops.clear();
362 }
363 }
364 // The way's last node is a chain boundary whatever its degree: a chain may
365 // not continue into the next way.
366 flush(state, &path, &hops, &attrs, coords, ends);
367 Ok(())
368 })?;
369 Ok(kinds)
370}
371
372/// Emit `path` as one or more chains, splitting it to fit the geometry budget.
373fn flush(
374 state: &mut ChainPass,
375 path: &[u32],
376 hops: &[u32],
377 attrs: &WayAttrs,
378 coords: &[geom::Pt],
379 ends: &AtomicBits,
380) {
381 if path.len() < 2 {
382 return;
383 }
384 debug_assert_eq!(hops.len(), path.len() - 1);
385 let runs = split_runs(path, coords);
386 if runs.len() > 1 {
387 state.splits += runs.len() - 1;
388 }
389 for (lo, hi) in runs {
390 ends.set(u64::from(path[lo]));
391 ends.set(u64::from(path[hi]));
392 let ids = &path[lo..=hi];
393 // Directed edges an uncompacted build would have emitted for this run:
394 // one per segment per permitted direction. Runs tile every segment of the
395 // way exactly once, so summing them is exact without keeping the segments.
396 state.raw_edge_count += (hi - lo) as u64 * if attrs.oneway { 1 } else { 2 };
397 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
398 ChainRec {
399 // Chunk-local; rebased by the sink.
400 pts_start: state.points,
401 pts_len: (hi - lo + 1) as u32,
402 first: ids[0],
403 last: ids[ids.len() - 1],
404 dist_mm: hops[lo..hi].iter().fold(0u32, |a, d| a.saturating_add(*d)),
405 // Chunk-local name id (or u32::MAX); rebased by the sink.
406 name_offset: attrs.name,
407 // Forward is along ref order, and so is the chain: no reorientation,
408 // so no chance of handing the masks to the wrong end. Chunk-local
409 // offsets; rebased by the sink when the count is non-zero.
410 fwd_lane_off: attrs.fwd_lane_off,
411 bwd_lane_off: attrs.bwd_lane_off,
412 fwd_lane_count: attrs.fwd_lane_count,
413 bwd_lane_count: attrs.bwd_lane_count,
414 type_: attrs.type_,
415 speed_limit: attrs.speed_limit,
416 oneway: attrs.oneway,
417 }
418 .encode(&mut rec);
419 state.hdr.extend_from_slice(&rec);
420 for id in ids {
421 let (lat_e7, lon_e7) = coords[*id as usize];
422 state.pts.extend_from_slice(&lat_e7.to_le_bytes());
423 state.pts.extend_from_slice(&lon_e7.to_le_bytes());
424 }
425 state.points += ids.len() as u64;
426 }
427}
428
429include!("chains_s1.rs");
430include!("chains_part1.rs");
431include!("chains_part2.rs");