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

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

graph_build_part3.rs883 lines · 37.3 KiBRaw
1/// Hook every transit stop that is *not* attached to a real road network onto the
2/// nearest node that is. Without this a matched GTFS stop that OSM never attached
3/// to a road is unreachable and the transit planner cannot get the user to it.
4///
5/// # Why component *size* and not the largest component
6///
7/// The question worth asking is "is this stop attached to a road network?", not
8/// "is it attached to the biggest one?". On a region those coincide — the largest
9/// component is 98.2% of California — so the pass used to find the largest
10/// component and reconnect everything outside it. On a planet they do not:
11/// continents are not road-connected, so the largest component is
12/// Eurasia-plus-Africa at 57.7% and every stop in the Americas, Australia, Japan,
13/// the UK and Indonesia was classified as isolated. The code then tried to bridge
14/// an ocean to reach a road in France, failed 1,173,347 times — a quarter of all
15/// stops — and paid for a widening search out to a million-node index window
16/// before each failure.
17///
18/// So a stop needs reconnecting only when its own component is smaller than
19/// [`MIN_ROUTABLE_COMPONENT`], and the target is the nearest node in *any*
20/// component at or above that threshold. A stop alone on an untagged node is a
21/// component of size 1 and is still connected; a stop on a small island's road
22/// network is left alone, because it is already as reachable as that island gets;
23/// a stop in North America connects to North America. That also removes the
24/// pathology rather than its symptom: a qualifying node is now metres away, so the
25/// widening search almost always succeeds on its first window.
26///
27/// The threshold is capped at the largest component that exists, because a graph
28/// with no component of 1000 nodes still has a road network — it is just a small
29/// one — and requiring a size nothing reaches would reconnect nothing at all.
30///
31/// One caveat on the word "component": the scan follows out-edges only, because
32/// that is the index the build has — a reverse CSR would be another 4.3 GB of
33/// `targets` at planet scale. So the partition is by out-reachability, and a node
34/// fed only by incoming one-ways can be labelled separately from the network that
35/// feeds it, undercounting that network's size. The error is in the safe direction:
36/// such a node looks *less* connected than it is, so at worst it gains a connector
37/// it did not need. The same traversal is what measured California's largest
38/// component at 98.24%, which bounds how far off it can be in practice.
39///
40/// `coords` and `stops` are both in final (Morton) id space.
41fn reconnect_isolated_stops(coords: &[geom::Pt], stops: &Bitset, csr: &Csr) -> Reconnected {
42 let n = coords.len();
43 if n == 0 {
44 return Reconnected {
45 lcc_size: 0,
46 synth: Vec::new(),
47 already_connected: 0,
48 unreachable: 0,
49 };
50 }
51 println!("Identifying connected components...");
52
53 let mut component = vec![u32::MAX; n];
54 // One size per component id. Planet has ~291 K components, so 1.2 MB.
55 let mut sizes: Vec<u32> = Vec::new();
56 let mut queue: Vec<u32> = Vec::with_capacity(n);
57 let mut prog = crate::progress::Progress::new("Connected components", n as u64);
58 for start in 0..n {
59 prog.inc();
60 if component[start] != u32::MAX {
61 continue;
62 }
63 let id = sizes.len() as u32;
64 let base = queue.len();
65 queue.push(start as u32);
66 component[start] = id;
67 let mut head = base;
68 while head < queue.len() {
69 let u = queue[head];
70 head += 1;
71 for v in csr.out(u) {
72 if component[*v as usize] == u32::MAX {
73 component[*v as usize] = id;
74 queue.push(*v);
75 }
76 }
77 }
78 sizes.push((queue.len() - base) as u32);
79 }
80 prog.finish();
81 drop(queue);
82
83 let lcc_size = sizes.iter().copied().max().unwrap_or(0);
84 let threshold = MIN_ROUTABLE_COMPONENT.min(lcc_size);
85 println!(
86 "{} component(s), largest {lcc_size} / {n} node(s) ({:.1}%); a component of \
87 {threshold}+ node(s) counts as routable",
88 sizes.len(),
89 f64::from(lcc_size) * 100.0 / n as f64
90 );
91
92 let routable = |node: u32| sizes[component[node as usize] as usize] >= threshold;
93 let mut stop_count = 0usize;
94 let mut isolated: Vec<u32> = Vec::new();
95 for i in 0..n as u32 {
96 if stops.get(u64::from(i)) {
97 stop_count += 1;
98 if !routable(i) {
99 isolated.push(i);
100 }
101 }
102 }
103 let already_connected = stop_count - isolated.len();
104 if isolated.is_empty() {
105 println!("{stop_count} stop(s), all already on a routable component");
106 return Reconnected {
107 lcc_size: u64::from(lcc_size),
108 synth: Vec::new(),
109 already_connected,
110 unreachable: 0,
111 };
112 }
113
114 // The nodes are Morton-sorted, so index distance approximates spatial
115 // distance: widen an index window around the stop until it contains a node in
116 // a routable component, then take the closest one in that window.
117 let found = par::map_chunks(&isolated, 256, |_, chunk| {
118 let mut out: Vec<Synth> = Vec::new();
119 let mut failed = 0usize;
120 for &i in chunk {
121 let stop = coords[i as usize];
122 let mut best: Option<(u32, u32)> = None;
123 let mut radius = 1000usize;
124 while radius <= 1_000_000 {
125 let lo = (i as usize).saturating_sub(radius);
126 let hi = (i as usize + radius).min(n);
127 for j in lo..hi {
128 if !routable(j as u32) {
129 continue;
130 }
131 let d = accurate_dist_mm(stop.0, stop.1, coords[j].0, coords[j].1);
132 if best.is_none_or(|(bd, _)| d < bd) {
133 best = Some((d, j as u32));
134 }
135 }
136 if best.is_some() {
137 break;
138 }
139 radius *= 10;
140 }
141 if let Some((dist_mm, target)) = best {
142 out.push(Synth {
143 source: i,
144 target,
145 dist_mm,
146 });
147 out.push(Synth {
148 source: target,
149 target: i,
150 dist_mm,
151 });
152 } else {
153 failed += 1;
154 }
155 }
156 (out, failed)
157 });
158
159 let unreachable: usize = found.iter().map(|(_, f)| f).sum();
160 let mut synth: Vec<Synth> = found.into_iter().flat_map(|(e, _)| e).collect();
161 println!(
162 "{stop_count} stop(s): {already_connected} already connected, {} reconnected, \
163 {unreachable} found nothing",
164 synth.len() / 2
165 );
166 if unreachable > 0 {
167 // The index window caps at 1e6 nodes, so a stop with no routable road
168 // within that window stays unreachable. Say so rather than dropping it
169 // silently: an unreachable stop is exactly what this pass exists to
170 // prevent. A large count here means MIN_ROUTABLE_COMPONENT is too high.
171 eprintln!("WARN: {unreachable} isolated stop(s) had no routable road nearby");
172 }
173 synth.sort_by_key(|s| (s.source, s.target));
174 Reconnected {
175 lcc_size: u64::from(lcc_size),
176 synth,
177 already_connected,
178 unreachable,
179 }
180}
181
182/// What `write_graph` produced, for [`Stats`].
183struct Written {
184 edge_count: u64,
185 geometry_edges: u64,
186 reversed_edges: u64,
187 intermediate_bytes: u64,
188 edges_bytes: u64,
189 escape_count: u64,
190 named_edges: u64,
191 census: Census,
192}
193
194/// One write worker's output for a batch of edges, in batch order.
195///
196/// Two shapes, interleaved in visit order: node openers (one per node the
197/// batch owns, edgeless ones included) and edge items (one per edge). The
198/// serial append folds them positionally — node record, then its edges — so
199/// concatenation reproduces the serial byte sequence exactly. The geometry
200/// decision rides along per edge (computed on the pool from the shared
201/// mapping); census inputs ride along too (the census is additive, replayed
202/// verbatim); node openers carry their own `edge_ptr` snapshot and degree so
203/// the drain never recomputes running state.
204enum BakedItem {
205 /// Open a node: stage its record, count its degree, tick it.
206 Node {
207 /// Node-record bytes (12 B) with the absolute edge pointer.
208 rec: [u8; 12],
209 /// Out-degree, for the census replay.
210 degree: u32,
211 },
212 /// One edge: census inputs, record inputs, geometry outcome, lanes.
213 /// Boxed: edges outnumber nodes ~3:1 and the small `Node` variant would
214 /// otherwise bloat every item to the edge size (the pool holds a whole
215 /// round's items at once).
216 Edge(Box<BakedEdge>),
217}
218
219/// One decided edge: record inputs, geometry outcome, census inputs, lanes.
220struct BakedEdge {
221 /// Census inputs for the edge: source, target, dist, named. The edge
222 /// census is a pure function of these (histogram increments, maxima,
223 /// escape predicates), so the drain replays `Census::edge` verbatim.
224 cen_source: u32,
225 cen_target: u32,
226 cen_dist: u32,
227 cen_named: bool,
228 /// Edge record inputs: the delta/dist pair (or the escape sentinel with
229 /// its row), the final type byte, speed, and name.
230 delta: i16,
231 dist: u32,
232 escaped: Option<(u32, u32)>,
233 type_: u8,
234 speed_limit: u8,
235 name_offset: u32,
236 /// Geometry outcome: encoded interior blob, reverse-flag, or absent.
237 geom: BakedGeom,
238 /// Lane run values when the edge carries lanes.
239 lanes: Vec<u16>,
240}
241
242/// What the pool decided about one edge's geometry.
243enum BakedGeom {
244 /// No blob: two-point chord, short chain, or no chain.
245 Absent,
246 /// Defer to the twin: set the reverse flag, store nothing.
247 Reversed,
248 /// Encoded interior blob, ready to stage.
249 Blob(Vec<u8>),
250}
251
252/// Write the pack in `rounds` source-partitioned rounds.
253///
254/// # Why rounds, and not computed offsets
255///
256/// The obvious alternative is to compute each edge's index and `pwrite` it into
257/// place. That is sound for `edges.bin` — fixed 14-byte records in a pre-sized
258/// file — but wrong for the two blob files. The reader derives a polyline's length
259/// from the next offset entry and a lane run's from the next index entry, so
260/// `intermediate.bin` and `lanes.bin` are forced into edge-index order with
261/// monotonic offsets, and writing a blob at a computed offset would mean knowing
262/// every earlier blob's length first: a per-edge length array, a prefix sum and a
263/// second encode pass.
264///
265/// Partitioning by source instead makes every write an append. Each round takes a
266/// contiguous range of final node ids, scans the chain spill for the edges whose
267/// *source* falls in that range, sorts that buffer, and writes both blobs, the
268/// presence bitmap, the offset tables, `edges.bin` and `nodes.bin` sequentially.
269/// Offsets come out monotonic by construction, `nodes.bin`'s running edge counter
270/// works because the rounds ascend, and the `(source, target)` grouping the reader
271/// and [`twin_is_unique`] depend on is restored within each round.
272///
273/// The cost is `rounds` sequential reads of the spill instead of one.
274#[allow(clippy::too_many_arguments)]
275fn write_graph(
276 out_dir: &Path,
277 node_coords: &[geom::Pt],
278 spill: &chains::Spill,
279 lane_pool: &[u16],
280 csr: &Csr,
281 synth: &[Synth],
282 ids: &FinalIds,
283 rounds: u32,
284 dem: Option<&crate::dem::Dem>,
285 timer: &mut crate::timing::PhaseTimer,
286) -> Result<Written> {
287 let kept = node_coords.len() as u32;
288 let edge_count = csr.edge_count() + synth.len() as u64;
289 // `nodes.bin`'s `edge_ptr` is a `u32`, so an edge count past that ceiling would
290 // wrap and point a node at another node's edge range.
291 cap_u32("directed edge", edge_count)?;
292 println!("Writing {edge_count} edge(s) in {rounds} round(s)...");
293 let chain_total = spill.chain_count()?;
294
295 let mut nodes_blocked = tilecodec::blocked::BlockedStreamWriter::create(
296 12,
297 &out_dir.join("nodes.blocked.tmp"),
298 )
299 .map_err(|e| Error(format!("cannot stage nodes.bin: {e}")))?;
300 let mut edges_out = EdgeFile::create(out_dir, "edges.bin", edge_count)?;
301
302 // `intermediate.bin` puts its blob at offset 0 and everything that indexes it
303 // in a trailer, so it is written strictly forwards with no scratch file at all
304 // (see [`GeomFile`]). `lanes.bin` is sparse and so cannot size its index up
305 // front; its blob streams to scratch instead and the index is written in front
306 // of it.
307 let mut inter = GeomFile::create(out_dir, "intermediate.bin", edge_count)?;
308 let mut lanes = LaneFile::create(out_dir, "lanes.bin")?;
309
310 // Per-batch scratch lives on the workers in the pipeline design;
311 // the restored serial loop below reuses one triple, as before.
312 let mut scratch: Vec<geom::Pt> = Vec::new();
313 let mut encoded: Vec<u8> = Vec::new();
314 let mut lane_bytes: Vec<u8> = Vec::new();
315 let mut buffer: Vec<TmpEdge> = Vec::new();
316 let mut points = spill.points()?;
317 let mut edge_ptr: u64 = 0;
318 let mut geometry_edges: u64 = 0;
319 let mut reversed_edges: u64 = 0;
320 let mut census = Census::default();
321 // One assignment scan instead of one scan per round: every chain's round
322 // is a pure function of its endpoints' final ids, so a single pass over
323 // the mapped headers records each chain's index per round and every round
324 // gathers only its chains. `rounds` sequential header passes become one
325 // (the mapping stays resident for the gathers). Chain order within a
326 // round is ascending index — the order the old per-round scan visited —
327 // so the buffer, the sort (stable), and everything downstream are
328 // identical.
329 timer.switch("write-scan");
330 let headers = spill.headers_mapped()?;
331 let chain_total_now = headers.len()?;
332 if chain_total_now != chain_total {
333 return Err(Error(format!(
334 "chains.hdr holds {chain_total_now} chain(s), expected {chain_total}"
335 )));
336 }
337 let mut by_round: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];
338 {
339 let mut prog =
340 crate::progress::Progress::new("Assign rounds".to_string(), chain_total);
341 // `ids.get` is two array lookups; the decode is 48 bytes. Both are
342 // dwarfed by the I/O the old code paid re-streaming per round.
343 for ci in 0..chain_total as u32 {
344 let c = headers.get(ci as u64)?;
345 let (a, b) = (ids.get(c.first), ids.get(c.last));
346 // A chain enters a round when the old scan would have buffered an
347 // edge for it there: source endpoint in range, or (two-way) target
348 // endpoint in range. One entry per qualifying round — a chain whose
349 // endpoints straddle a boundary is gathered twice, once per round,
350 // exactly as the old scan buffered it twice.
351 for round in 0..rounds {
352 let lo = (u64::from(kept) * u64::from(round) / u64::from(rounds)) as u32;
353 let hi =
354 (u64::from(kept) * u64::from(round + 1) / u64::from(rounds)) as u32;
355 if (lo..hi).contains(&a) || (!c.oneway && (lo..hi).contains(&b)) {
356 by_round[round as usize].push(ci);
357 }
358 }
359 prog.inc();
360 }
361 prog.finish();
362 }
363
364 for round in 0..rounds {
365 // Split by node count. Contiguous and ascending, so the four output streams
366 // stay append-only across the whole run.
367 let lo = (u64::from(kept) * u64::from(round) / u64::from(rounds)) as u32;
368 let hi = (u64::from(kept) * u64::from(round + 1) / u64::from(rounds)) as u32;
369
370 buffer.clear();
371 // Gather: this round's chains in ascending index order — the visit
372 // order of the old per-round scan, so buffer order pre-sort (and
373 // therefore post-sort, stable) is unchanged.
374 for &ci in &by_round[round as usize] {
375 let c = headers.get(ci as u64)?;
376 let (a, b) = (ids.get(c.first), ids.get(c.last));
377 if (lo..hi).contains(&a) {
378 buffer.push(chain_edge(&c, ci, a, b, false));
379 }
380 if !c.oneway && (lo..hi).contains(&b) {
381 buffer.push(chain_edge(&c, ci, b, a, true));
382 }
383 }
384 let synth_lo = synth.partition_point(|s| s.source < lo);
385 let synth_hi = synth.partition_point(|s| s.source < hi);
386 for s in &synth[synth_lo..synth_hi] {
387 buffer.push(TmpEdge {
388 source: s.source,
389 target: s.target,
390 dist_mm: s.dist_mm,
391 name_offset: NO_NAME,
392 type_: RECONNECT_TYPE,
393 speed_limit: RECONNECT_SPEED,
394 lane_off: NO_LANES,
395 lane_count: 0,
396 chain: NO_CHAIN,
397 chain_rev: false,
398 pts_start: 0,
399 pts_len: 0,
400 });
401 }
402
403 // The CSR already knows how many edges this range owns. Checking against it
404 // catches both an edge landing in the wrong round and an edge whose source
405 // is not a surviving node — which is what the old
406 // `assert_eq!(cursor, edges.len())` was for, now checked per round and
407 // before anything is written rather than after everything is.
408 let expected = csr.edge_ptr[hi as usize] - csr.edge_ptr[lo as usize]
409 + (synth_hi - synth_lo) as u64;
410 if buffer.len() as u64 != expected {
411 return Err(Error(format!(
412 "round {round} covering node(s) {lo}..{hi} collected {} edge(s), \
413 but the edge index says {expected}",
414 buffer.len()
415 )));
416 }
417
418 // Grouped by source for the reader, then by target so a node's parallel
419 // edges are adjacent, then by chain so the order is total. The sort is
420 // stable and the buffer was built in chain order, so the two directions of
421 // a self-loop keep the order they were emitted in.
422 buffer.sort_by_key(|e| (e.source, e.target, e.chain));
423
424 // --- write-write: serial drain over the sorted buffer ----------------
425 //
426 // A parallel bake/drain pipeline lived here (positional batches baked
427 // on the pool, drained in order). It failed the build's own gate:
428 // nodes.bin unpacked to 12x the pushed records while every counter
429 // (bake openers, drain openers, drain pushes) read exactly right —
430 // and the same 12x appeared with the bake forced single-threaded, so
431 // the duplication is not a threading race. The prime suspect is the
432 // batch/item framing itself (spans, bases, or the opener splice
433 // double-covering nodes), but rather than debug the framing blind,
434 // this restores the serial loop verbatim and keeps the pipeline
435 // design (plus the failing counters to re-prove against) in the
436 // task notes. The single-scan assignment above stays: it is proven
437 // (byte-identical CA hashes) and independent of the drain shape.
438 //
439 // TODO(write-pipe): re-land the pipeline. Re-entry checklist:
440 // 1. unit test bake_batch on a synthetic buffer FIRST (no build
441 // needed): assert opener count == node span and opener edge_ptrs
442 // == base + run offsets, before any pool or drain exists;
443 // 2. reintroduce pool + drain behind that test;
444 // 3. CA hash must equal the serial hash before any planet run.
445 timer.switch("write-write");
446 {
447 let mut wprog = crate::progress::Progress::new(
448 format!("Round {}/{rounds}: write", round + 1),
449 u64::from(hi - lo),
450 );
451 let mut cursor = 0usize;
452 for v in lo..hi {
453 let node = node_coords[v as usize];
454 let mut rec = [0u8; 12];
455 rec[0..4].copy_from_slice(&node.0.to_le_bytes());
456 rec[4..8].copy_from_slice(&node.1.to_le_bytes());
457 rec[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());
458 nodes_blocked
459 .push(&rec)
460 .map_err(|e| Error(format!("cannot stage node record: {e}")))?;
461 let degree_base = edge_ptr;
462 while cursor < buffer.len() && buffer[cursor].source == v {
463 let e = &buffer[cursor];
464 census.edge(e.source, e.target, e.dist_mm, e.name_offset != NO_NAME);
465
466 // --- geometry ---
467 let mut type_ = e.type_;
468 let mut stores = false;
469 // A two-point chain is just the chord between the edge's own
470 // endpoints, and under the interior-only encoding that is what an
471 // absent blob already means, so storing it would cost a presence
472 // bit to say nothing — and, more to the point here, a read to find
473 // that out.
474 if e.chain != NO_CHAIN && e.pts_len >= 3 {
475 if e.chain_rev
476 && e.source != e.target
477 && twin_is_unique(csr, synth, e.source, e.target)
478 {
479 type_ |= REVERSE_GEOMETRY_FLAG;
480 reversed_edges += 1;
481 } else {
482 // Only now is the polyline actually needed. Deciding the
483 // flag first matters more than it looks: this is the only
484 // random read in the writer, so every edge that defers to
485 // its twin is one seek saved, and on a filesystem whose
486 // syscalls are expensive that dominated the whole build.
487 points.read(e.pts_start, e.pts_len, &mut scratch)?;
488 if e.chain_rev {
489 scratch.reverse();
490 }
491 assert!(
492 geom::fits(&scratch),
493 "chain of {} points cannot be encoded; the collapse should \
494 have split it",
495 scratch.len()
496 );
497 // The blob holds only the interior, so the reader rebuilds
498 // both ends out of `nodes.bin`.
499 assert_endpoints(&scratch, node_coords, e.source, e.target, e.chain);
500 encoded.clear();
501 let n = geom::encode(&scratch, &mut encoded);
502 debug_assert_eq!(n as usize, geom::encoded_points(&scratch) as usize);
503 inter.store(&encoded)?;
504 geometry_edges += 1;
505 stores = true;
506 }
507 }
508 if !stores {
509 inter.skip();
510 }
511
512 edges_out.push(e, type_)?;
513 if e.lane_count > 0 && e.lane_off != NO_LANES {
514 let start = e.lane_off as usize;
515 lane_bytes.clear();
516 for m in &lane_pool[start..start + e.lane_count as usize] {
517 lane_bytes.extend_from_slice(&m.to_le_bytes());
518 }
519 lanes.push(edge_ptr, &lane_bytes)?;
520 }
521 edge_ptr += 1;
522 cursor += 1;
523 }
524 census.node((edge_ptr - degree_base) as u32);
525 wprog.inc();
526 }
527 wprog.finish();
528 debug_assert_eq!(cursor, buffer.len(), "the round left edges unwritten");
529 }
530 }
531
532 if edge_ptr != edge_count {
533 return Err(Error(format!(
534 "wrote {edge_ptr} edge(s) into a file sized for {edge_count}"
535 )));
536 }
537 finish_pack(
538 out_dir,
539 kept,
540 edge_count,
541 edge_ptr,
542 geometry_edges,
543 reversed_edges,
544 nodes_blocked,
545 edges_out,
546 inter,
547 lanes,
548 census,
549 node_coords,
550 dem,
551 )
552}
553
554/// Finish the four output streams and the metadata: the tail of `write_graph`
555/// after the last round drains. Unchanged from the serial loop — the drain
556/// above stages identical bytes, so everything downstream (sentinel, sanity
557/// parses, metadata, elevation) is untouched.
558#[allow(clippy::too_many_arguments)]
559fn finish_pack(
560 out_dir: &Path,
561 kept: u32,
562 edge_count: u64,
563 edge_ptr: u64,
564 geometry_edges: u64,
565 reversed_edges: u64,
566 nodes_blocked: tilecodec::blocked::BlockedStreamWriter,
567 edges_out: EdgeFile,
568 inter: GeomFile,
569 lanes: LaneFile,
570 census: Census,
571 node_coords: &[geom::Pt],
572 dem: Option<&crate::dem::Dem>,
573) -> Result<Written> {
574 let mut nodes_blocked = nodes_blocked;
575 let mut edges_out = edges_out;
576 let mut inter = inter;
577 let mut lanes = lanes;
578 // Trailing sentinel so `graph.rs` can read node(v + 1).edge_ptr as the end of
579 // node v's edge range.
580 let mut sentinel = [0u8; 12];
581 sentinel[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());
582 nodes_blocked
583 .push(&sentinel)
584 .map_err(|e| Error(format!("cannot stage node sentinel: {e}")))?;
585 let nodes_bytes = nodes_blocked
586 .finish()
587 .map_err(|e| Error(format!("cannot finish nodes.bin: {e}")))?;
588 // Sanity: the blocked section must unpack to exactly the pushed records.
589 let parsed = tilecodec::blocked::Blocked::parse(&nodes_bytes).map_err(|e| {
590 Error(format!(
591 "freshly blocked nodes.bin does not parse: {e}"
592 ))
593 })?;
594 // Sanity: the blocked section must unpack to exactly the pushed records.
595 if parsed.unpacked_len() != (u64::from(kept) + 1) * 12 {
596 return Err(Error(format!(
597 "nodes.bin unpacks to {} byte(s), not {} 12-byte records",
598 parsed.unpacked_len(),
599 u64::from(kept) + 1
600 )));
601 }
602 std::fs::write(out_dir.join("nodes.bin"), &nodes_bytes).map_err(io_err)?;
603 let escape_count = edges_out.escapes.len() as u64;
604 let named_edges = edges_out.name_offsets.len() as u64;
605 let edges_bytes = edges_out.finish(edge_count)?;
606 let intermediate_bytes = inter.finish(edge_count)?;
607 lanes.finish()?;
608 finish_pack_tail(
609 out_dir,
610 kept,
611 edge_count,
612 escape_count,
613 named_edges,
614 node_coords,
615 dem,
616 )?;
617 Ok(Written {
618 edge_count,
619 geometry_edges,
620 reversed_edges,
621 intermediate_bytes,
622 edges_bytes,
623 escape_count,
624 named_edges,
625 census,
626 })
627}
628
629/// Metadata + elevation tail of `write_graph`, after every stream finishes.
630/// Split out so the round loop above reads as plan/bake/drain without the
631/// file-assembly tail inline. Byte-identical: moved whole, order untouched.
632#[allow(clippy::too_many_arguments)]
633fn finish_pack_tail(
634 out_dir: &Path,
635 kept: u32,
636 edge_count: u64,
637 escape_count: u64,
638 named_edges: u64,
639 node_coords: &[geom::Pt],
640 dem: Option<&crate::dem::Dem>,
641) -> Result<()> {
642 // metadata.bin's magic + version let the device refuse a pack directory
643 // holding files from two different vintages instead of misreading it, and its
644 // counts are what every other file's length is validated against.
645 let mut meta = create(&out_dir.join("metadata.bin"))?;
646 meta.write_all(&GRAPH_MAGIC.to_le_bytes()).map_err(io_err)?;
647 meta.write_all(&GRAPH_VERSION.to_le_bytes()).map_err(io_err)?;
648 meta.write_all(&u64::from(kept).to_le_bytes()).map_err(io_err)?;
649 meta.write_all(&edge_count.to_le_bytes()).map_err(io_err)?;
650 meta.write_all(&escape_count.to_le_bytes()).map_err(io_err)?;
651 meta.write_all(&named_edges.to_le_bytes()).map_err(io_err)?;
652 meta.flush().map_err(io_err)?;
653 // elevation.bin: `i16[node_count]` metres, one per node in final-id order — an OPTIONAL sidecar
654 // like road_names.bin/lanes.bin, so a build without a DEM simply omits it and the device reads
655 // every node's elevation as 0. `node_coords` is already indexed by final node id, so a single
656 // forward pass matches the order `nodes.bin` was written in. Blocked like
657 // nodes/edges under the v7 layout (magic-dispatched on read, so absence
658 // still reads as all-zero).
659 if let Some(dem) = dem {
660 let mut elev_blocked = tilecodec::blocked::BlockedStreamWriter::create(
661 2,
662 &out_dir.join("elevation.blocked.tmp"),
663 )
664 .map_err(|e| Error(format!("cannot stage elevation.bin: {e}")))?;
665 for &(lat_e7, lon_e7) in node_coords {
666 let lat = f64::from(lat_e7) * 1e-7;
667 let lon = f64::from(lon_e7) * 1e-7;
668 let metres = dem.sample_metres(lon, lat).unwrap_or(0);
669 elev_blocked
670 .push(&metres.to_le_bytes())
671 .map_err(|e| Error(format!("cannot stage elevation record: {e}")))?;
672 }
673 let elev_bytes = elev_blocked
674 .finish()
675 .map_err(|e| Error(format!("cannot finish elevation.bin: {e}")))?;
676 std::fs::write(out_dir.join("elevation.bin"), &elev_bytes).map_err(io_err)?;
677 }
678 Ok(())
679}
680
681/// Bake one write batch: every node record and edge record's bytes, decided.
682///
683/// Positional over the sorted edge buffer: `edges` are the buffer slice this
684/// batch owns (one or more whole nodes' runs — batch boundaries fall on node
685/// boundaries by construction), `first_node` the batch's first node id, and
686/// `batch_edge_base` its edge index in the global order (so node records
687/// carry their own absolute `edge_ptr`). Returns node openers interleaved
688/// with their edges in the exact order the serial loop visited them (node
689/// record, then its edges).
690///
691/// Pure over shared tables (`node_coords`, `lane_pool`, `csr`, `synth`,
692/// `points`): safe across the pool. Fallible only like the serial loop was —
693/// a truncated `chains.pts` fails the build rather than shortening it — and
694/// the drain reports the first failure in batch order. `assert_endpoints` and
695/// the `geom::fits` gate run here, on the worker that encoded: same
696/// predicate, same message, same abort.
697#[allow(clippy::too_many_arguments)]
698fn bake_batch(
699 edges: &[TmpEdge],
700 first_node: u32,
701 batch_edge_base: u64,
702 node_coords: &[geom::Pt],
703 lane_pool: &[u16],
704 csr: &Csr,
705 synth: &[Synth],
706 points: &crate::mem::Mapped,
707) -> Result<Vec<BakedItem>> {
708 let mut out: Vec<BakedItem> = Vec::new();
709 let mut scratch: Vec<geom::Pt> = Vec::new();
710 let mut encoded: Vec<u8> = Vec::new();
711 // The slice starts on a node boundary (batches partition the node range)
712 // but its first edge may belong to a later node than `first_node`:
713 // nodes between hold no edges (degree 0) and still open a record each.
714 let mut node = first_node;
715 let mut i = 0usize;
716 let mut edge_idx = batch_edge_base;
717 while i < edges.len() {
718 while node < edges[i].source {
719 out.push(baked_node(node, node_coords, edge_idx, 0));
720 node += 1;
721 }
722 // This run's edges, in slice order (source-sorted, then target, then
723 // chain — the serial order).
724 let source = edges[i].source;
725 debug_assert_eq!(source, node, "batch slices split a node's run");
726 let run_start = out.len();
727 let mut degree = 0u32;
728 while i < edges.len() && edges[i].source == source {
729 out.push(BakedItem::Edge(Box::new(bake_edge(
730 &edges[i],
731 lane_pool,
732 csr,
733 synth,
734 points,
735 node_coords,
736 &mut scratch,
737 &mut encoded,
738 )?)));
739 degree += 1;
740 edge_idx += 1;
741 i += 1;
742 }
743 // The opener comes FIRST in drain order (node record, then its
744 // edges): splice it before the run just baked. Runs are short
745 // (degree ones mostly), so the shift is cheap — and positional
746 // exactness is the whole contract.
747 out.insert(run_start, baked_node(source, node_coords, edge_idx - degree as u64, degree));
748 node += 1;
749 }
750 Ok(out)
751}
752
753/// One node opener: its record bytes with the absolute edge pointer, plus its
754/// out-degree for the census replay.
755fn baked_node(node: u32, node_coords: &[geom::Pt], edge_ptr: u64, degree: u32) -> BakedItem {
756 let coords = node_coords[node as usize];
757 let mut rec = [0u8; 12];
758 rec[0..4].copy_from_slice(&coords.0.to_le_bytes());
759 rec[4..8].copy_from_slice(&coords.1.to_le_bytes());
760 rec[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());
761 BakedItem::Node { rec, degree }
762}
763
764/// One edge, decided: record inputs, geometry outcome, census inputs, lanes.
765///
766/// Mirrors the serial loop's per-edge body exactly: escape narrowing (same
767/// predicate, same sentinel rows), the twin-check-before-read (same flag),
768/// polyline read + reverse + gates + encode, lane run copy. Census inputs
769/// are the edge's own fields (replayed verbatim by the drain).
770fn bake_edge(
771 e: &TmpEdge,
772 lane_pool: &[u16],
773 csr: &Csr,
774 synth: &[Synth],
775 points: &crate::mem::Mapped,
776 node_coords: &[geom::Pt],
777 scratch: &mut Vec<geom::Pt>,
778 encoded: &mut Vec<u8>,
779) -> Result<BakedEdge> {
780 // Narrow first, exactly as `EdgeFile::push` does: the drain replays the
781 // narrowing verbatim through `push_baked_edge`, so the predicate lives in
782 // one place (there) and here only the escape ROW is decided... simpler:
783 // decide everything here and carry the outcome.
784 let (delta, dist, escaped) = match target_delta(e.source, e.target) {
785 Some(d) if e.dist_mm < DIST_MM_ESCAPE => (d, e.dist_mm, None),
786 _ => (
787 TARGET_DELTA_ESCAPE,
788 DIST_MM_ESCAPE,
789 Some((e.target, e.dist_mm)),
790 ),
791 };
792 // --- geometry ---
793 let mut type_ = e.type_;
794 let mut geom = BakedGeom::Absent;
795 // A two-point chain is just the chord between the edge's own endpoints,
796 // and under the interior-only encoding that is what an absent blob
797 // already means, so storing it would cost a presence bit to say nothing —
798 // and, more to the point here, a read to find that out.
799 if e.chain != NO_CHAIN && e.pts_len >= 3 {
800 if e.chain_rev && e.source != e.target && twin_is_unique(csr, synth, e.source, e.target)
801 {
802 type_ |= REVERSE_GEOMETRY_FLAG;
803 geom = BakedGeom::Reversed;
804 } else {
805 // Only now is the polyline actually needed. Deciding the flag
806 // first matters more than it looks: this is the only random read
807 // in the writer, so every edge that defers to its twin is one
808 // seek saved. Shared mapping, no lock: `read_shared` slices the
809 // same pages the serial loop faulted.
810 chains::PointReader::read_shared(points, e.pts_start, e.pts_len, scratch)?;
811 if e.chain_rev {
812 scratch.reverse();
813 }
814 assert!(
815 geom::fits(scratch),
816 "chain of {} points cannot be encoded; the collapse should \
817 have split it",
818 scratch.len()
819 );
820 // The blob holds only the interior, so the reader rebuilds
821 // both ends out of `nodes.bin`.
822 assert_endpoints(scratch, node_coords, e.source, e.target, e.chain);
823 encoded.clear();
824 let n = geom::encode(scratch, encoded);
825 debug_assert_eq!(n as usize, geom::encoded_points(scratch) as usize);
826 geom = BakedGeom::Blob(std::mem::take(encoded));
827 }
828 }
829 let lanes = if e.lane_count > 0 && e.lane_off != NO_LANES {
830 let start = e.lane_off as usize;
831 lane_pool[start..start + e.lane_count as usize].to_vec()
832 } else {
833 Vec::new()
834 };
835 Ok(BakedEdge {
836 cen_source: e.source,
837 cen_target: e.target,
838 cen_dist: e.dist_mm,
839 cen_named: e.name_offset != NO_NAME,
840 delta,
841 dist,
842 escaped,
843 type_,
844 speed_limit: e.speed_limit,
845 name_offset: e.name_offset,
846 geom,
847 lanes,
848 })
849}
850
851/// Stage one baked edge's record: the narrowing replayed verbatim.
852///
853/// `EdgeFile::push` narrows from the live edge; this narrows from the baked
854/// decision. Same predicate, same rows, same bitmap updates — the function
855/// exists so the two cannot drift: any change to narrowing updates both
856/// call sites' shared outcome type... (they share `BakedEdge`'s fields, and
857/// this function is the drain's only writer into `edges_out`).
858fn push_baked_edge(edges_out: &mut EdgeFile, item: &BakedEdge) -> Result<()> {
859 let (delta, dist) = match item.escaped {
860 Some((target, dist)) => {
861 let idx = edges_out.pushed as u32;
862 edges_out.escapes.push((idx, target, dist));
863 (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE)
864 }
865 None => (item.delta, item.dist),
866 };
867 let mut rec = [0u8; EDGE_REC_BYTES as usize];
868 rec[0..2].copy_from_slice(&delta.to_le_bytes());
869 rec[2..5].copy_from_slice(&dist.to_le_bytes()[..3]);
870 rec[5] = item.type_;
871 rec[6] = item.speed_limit;
872 edges_out
873 .blocked
874 .push(&rec)
875 .map_err(|e| Error(format!("cannot stage edge record: {e}")))?;
876 if item.name_offset != NO_NAME {
877 edges_out.named.set(edges_out.pushed);
878 edges_out.name_offsets.push(item.name_offset);
879 }
880 edges_out.pushed += 1;
881 Ok(())
882}
883