mamaps: parallelize junction streaming with ordered drain
- Commit
af7e3d8a0265a8380e5c3fc03c5b064f2dd4c943- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-06 00:30 UTC (2 months ago)
- Parents
ebc758e
Diff
scripts/maps/mamaps_build/src/extract_fallback.rs
diff --git a/scripts/maps/mamaps_build/src/extract_fallback.rs b/scripts/maps/mamaps_build/src/extract_fallback.rsindex 20534e4554..89664901e6 100644--- a/scripts/maps/mamaps_build/src/extract_fallback.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -56,7 +56,10 @@ use std::collections::HashMap; use osm_ingest::proto::Result; use osm_ingest::rings::{point_in_ring, ring_area, Polygon};+use rayon::prelude::*; use tile_build::geom::Geometry;+use tile_build::par;+use tile_build::progress::Progress; use tilecodec::mamaps::body::ID_NONE; use tilecodec::mamaps::dict::{KINDS, LAYER_BOUNDARIES, LAYER_PLACES}; @@ -403,6 +406,11 @@ pub fn extend_region_links_with( } boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0); let grid = Grid::build(&boundaries);+ // The `country_zoom` lookup below used to walk `boundaries` linearly per+ // linked country; indexed by id so it is a hash lookup instead. Built+ // once — the vec never moves again after this.+ let boundary_by_id: HashMap<u64, usize> =+ boundaries.iter().enumerate().map(|(i, b)| (b.id, i)).collect(); // Pass 2: places. Positional, so node, way-centroided and relation-centroided labels all // link by the tagged id they already carry — the only path that can link non-node places,@@ -411,69 +419,142 @@ pub fn extend_region_links_with( // so no third pass is needed. The headcount comes from `populations` (relation // places, filled by the caller while tags were in hand); absent entries score as // unpopulated — Antarctica's case — never as missing.+ //+ // Collected serially first — the store reader is one sequential cursor —+ // then linked on the pool: `select_link` is pure per-place work over the+ // shared grid, and the drain inserts in collection order with member+ // links winning, exactly as the serial loop did. `select_link` returns+ // at most one target per place, so the drain cannot double-insert and+ // the map bytes are identical.+ struct PlacePoint {+ id: u64,+ point: (f64, f64),+ kind: Band,+ kind_name: String,+ }+ let mut places: Vec<PlacePoint> = Vec::new();+ {+ let mut reader = store.reader()?;+ while let Some(feature) = reader.next()? {+ if feature.class.layer != LAYER_PLACES {+ continue;+ }+ if feature.id == ID_NONE {+ continue;+ }+ let Geometry::Points(points) = feature.geometry else {+ continue;+ };+ let Some(&point) = points.first() else {+ continue;+ };+ let Some(kind_name) = place_kind_name(feature.class.kind) else {+ continue;+ };+ let Some(band) = band_for_place_kind(kind_name) else {+ continue;+ };+ places.push(PlacePoint {+ id: feature.id,+ point,+ kind: band,+ kind_name: kind_name.to_string(),+ });+ }+ } let mut stats = FallbackStats::default(); let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new();- let mut buf: Vec<&Boundary> = Vec::new();- let mut reader = store.reader()?;- while let Some(feature) = reader.next()? {- if feature.class.layer != LAYER_PLACES {- continue;- }- if feature.id == ID_NONE {- continue;- }- let Geometry::Points(points) = feature.geometry else {- continue;- };- let Some(&point) = points.first() else {- continue;- };- let Some(kind_name) = place_kind_name(feature.class.kind) else {- continue;- };+ // Member links always win: counted exactly as the serial loop did,+ // and skipped in the link pass so nothing contends on the map.+ for place in &places { stats.places_total += 1;- let entry = per_kind.entry(kind_name.to_string()).or_insert((0, 0));+ let entry = per_kind.entry(place.kind_name.clone()).or_insert((0, 0)); entry.0 += 1;- if region_links.contains_key(&feature.id) {+ if region_links.contains_key(&place.id) { stats.member_linked += 1; entry.1 += 1;- continue; }- let Some(band) = band_for_place_kind(kind_name) else {+ }+ // Parallel link: one candidate-set build + `select_link` per+ // member-less place, on the pool; the drain inserts in collection+ // order, so the map — and the stats — are identical at every thread+ // count. `select_link` returns at most one target per place, so the+ // drain cannot double-insert. The bar ticks in the drain per place, so+ // it spans the whole pass even though the expensive half runs on the+ // pool.+ let mut bar =+ Progress::new("Fallback: places".to_string(), places.len(), "place(s)", true);+ const FALLBACK_BATCH: usize = 16 * 1024;+ let mut batch: Vec<usize> = Vec::with_capacity(FALLBACK_BATCH);+ let mut built: Vec<Option<u64>> = Vec::with_capacity(FALLBACK_BATCH);+ let mut at = 0usize;+ while at < places.len() {+ batch.clear();+ while at < places.len() && batch.len() < FALLBACK_BATCH {+ if region_links.contains_key(&places[at].id) {+ // Member-linked: counted above, nothing to compute. The tick+ // keeps the bar spanning every place, not just computed ones.+ bar.tick("place(s)");+ at += 1;+ continue;+ }+ batch.push(at);+ at += 1;+ }+ if batch.is_empty() { continue;- };- buf.clear();- buf.extend(grid.candidates_for(point).map(|i| &boundaries[i]));- if let Some(target) = select_link(point, band, &buf) {- region_links.insert(feature.id, target);- stats.fallback_linked += 1;- entry.1 += 1; }- // A country label starts at the zoom its footprint earns. The linked- // boundary (member half inserted before this pass, fallback half just- // above — both visible in `region_links` now) carries the ground area;- // the place feature carries the headcount via its population rank... but- // the rank buckets are lossy, so read the headcount from the store- // feature's own tags is impossible here — instead the population comes- // from the place feature's `kind_detail` rank inverted through the same- // buckets `schema::places` used. Simpler and exact: keep a place-id →- // population map from the pass-2 scan itself (see `populations` below).- // Unlinked countries keep the schema floor (z0): a missing link must- // never hide a country.- if kind_name == "country" {- if let Some(target) = region_links.get(&feature.id) {- if let Some(boundary) = boundaries.iter().find(|b| b.id == *target) {- let mid_lat = boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0);- let population = populations.get(&feature.id).copied().unwrap_or(0);- country_zooms.insert(- feature.id,- country_zoom(boundary.area, mid_lat, population),- );- stats.country_zooms += 1;+ built.clear();+ par::install(|| {+ batch+ .par_iter()+ .map(|&pi| {+ let place = &places[pi];+ let candidates: Vec<&Boundary> = grid+ .candidates_for(place.point)+ .map(|i| &boundaries[i])+ .collect();+ select_link(place.point, place.kind, &candidates)+ })+ .collect_into_vec(&mut built)+ });+ for (&pi, target) in batch.iter().zip(built.drain(..)) {+ let place = &places[pi];+ if let Some(target) = target {+ region_links.insert(place.id, target);+ stats.fallback_linked += 1;+ if let Some(entry) = per_kind.get_mut(&place.kind_name) {+ entry.1 += 1;+ }+ }+ // A country label starts at the zoom its footprint earns. The+ // linked boundary (member half inserted before this pass,+ // fallback half just above — both visible in `region_links`+ // now) carries the ground area; the headcount comes from+ // `populations` (relation places, filled by the caller while+ // tags were in hand); absent entries score as unpopulated —+ // Antarctica's case — never as missing. Unlinked countries keep+ // the schema floor (z0): a missing link must never hide a+ // country.+ if place.kind_name == "country" {+ if let Some(target) = region_links.get(&place.id) {+ if let Some(&bi) = boundary_by_id.get(target) {+ let boundary = &boundaries[bi];+ let mid_lat =+ boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0);+ let population = populations.get(&place.id).copied().unwrap_or(0);+ country_zooms.insert(+ place.id,+ country_zoom(boundary.area, mid_lat, population),+ );+ stats.country_zooms += 1;+ } } }+ bar.tick("place(s)"); } }+ bar.finish("place(s)"); stats.fallback_missed = stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked); let mut kinds: Vec<(String, u64, u64)> = per_kind
scripts/maps/mamaps_build/src/schema/junction.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction.rs b/scripts/maps/mamaps_build/src/schema/junction.rsindex 62d6e5ed77..2a6f0c73d7 100644--- a/scripts/maps/mamaps_build/src/schema/junction.rs+++ b/scripts/maps/mamaps_build/src/schema/junction.rs@@ -188,7 +188,10 @@ use std::collections::BTreeSet; use std::path::Path; use osm_ingest::proto::{err, Result};+use rayon::prelude::*; use tile_build::geom::Geometry;+use tile_build::par;+use tile_build::progress::Progress; use tilecodec::mamaps::body::{ LANE_LEFT, LANE_NONE, LANE_REVERSE, LANE_RIGHT, LANE_SHARP_LEFT, LANE_SHARP_RIGHT, LANE_SLIGHT_LEFT, LANE_SLIGHT_RIGHT, LANE_THROUGH,
scripts/maps/mamaps_build/src/schema/junction_part1.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part1.rs b/scripts/maps/mamaps_build/src/schema/junction_part1.rsindex 8c2f3f10b9..157ef80d48 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part1.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part1.rs@@ -116,39 +116,163 @@ struct InEdges { impl InEdges { fn build(graph: &Graph) -> Result<InEdges> { let node_count = graph.node_count;- let mut start = vec![0u32; node_count as usize + 2];- let mut total = 0usize;- for n in 0..node_count {- for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {- if !is_drivable(graph.edge_type(idx)) {- continue;- }- let target = graph.edge_target(idx, n as u32)?;- if u64::from(target) >= node_count {- return err(format!(- "edge {idx} targets node {target}, past the {node_count} in the graph"- ));+ // Parallel counting sort, not a naive `par_iter`: the serial+ // `start[target + 1] += 1` is a cross-iteration hazard, so the count+ // goes through one shared atomic slot per target instead — spread+ // over `node_count + 1` slots, so the updates are essentially+ // uncontended — and the fill through the same slots as cursors.+ //+ // Memory is the serial shape, not per-shard histograms (shards x+ // nodes would be tens of GB at planet scale): one atomic slot per+ // node plus the edge table itself, the same peak as the serial+ // `start` + `fill` pair this replaces.+ //+ // Order is the serial order: sources are visited `n` ascending,+ // `edge_ptr` ascending, and each node's slice is restored to+ // ascending `edge_idx` after the fill, so `incoming.of(n)` holds+ // exactly what the serial loop built and downstream pairing is+ // unchanged at every thread count.+ use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};+ use std::sync::Mutex;+ let slots = node_count as usize + 2;+ let counts: Vec<AtomicU32> = (0..slots).map(|_| AtomicU32::new(0)).collect();+ // The first corrupt edge met, serialised: a bounds failure and an+ // escape-row failure are both fatal, and the message keeps the+ // serial wording. Checked between phases, so a corrupt graph never+ // fills (or sorts) a partial index.+ let first_err: Mutex<Option<osm_ingest::proto::Error>> = Mutex::new(None);+ let failed = AtomicBool::new(false);+ // Shards partition the *source* nodes: every edge is visited exactly+ // once however the ranges fall, so each target's total is exact.+ let threads = par::threads().max(1);+ let want_tasks = threads.saturating_mul(4).max(1);+ let shard_len = ((node_count as usize) / want_tasks).max(1);+ let mut shards: Vec<std::ops::Range<u64>> = Vec::new();+ let mut lo = 0u64;+ while lo < node_count {+ let hi = (lo + shard_len as u64).min(node_count);+ shards.push(lo..hi);+ lo = hi;+ }+ // Phase 1: count one slot high, so the prefix sum below leaves+ // `start[t]` pointing at node `t`'s first slot.+ par::install(|| {+ shards.par_iter().for_each(|range| {+ for n in range.clone() {+ // Another shard already found corruption: stop feeding+ // counts nobody will read. Checked per node, not per+ // edge, so the fast path pays one relaxed load.+ if failed.load(Ordering::Relaxed) {+ break;+ }+ for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {+ if !is_drivable(graph.edge_type(idx)) {+ continue;+ }+ let target = match graph.edge_target(idx, n as u32) {+ Ok(t) => t,+ Err(e) => {+ failed.store(true, Ordering::Relaxed);+ let mut guard = first_err+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ if guard.is_none() {+ *guard = Some(e);+ }+ break;+ }+ };+ if u64::from(target) >= node_count {+ failed.store(true, Ordering::Relaxed);+ let mut guard =+ first_err.lock().unwrap_or_else(|p| p.into_inner());+ if guard.is_none() {+ *guard = Some(osm_ingest::proto::Error(format!(+ "edge {idx} targets node {target}, past the {node_count} in the graph"+ )));+ }+ break;+ }+ counts[target as usize + 1].fetch_add(1, Ordering::Relaxed);+ } }- // Counted one slot high, so the prefix sum below leaves `start[t]` pointing at- // node `t`'s first slot and `start[t + 1]` one past its last.- start[target as usize + 1] += 1;- total += 1;- }+ });+ });+ if let Some(e) = first_err.lock().unwrap_or_else(|p| p.into_inner()).take() {+ return Err(e); }- for i in 1..start.len() {- start[i] += start[i - 1];+ // Serial prefix sum, in place: the same array then serves as the+ // phase-2 fill cursors with no second allocation. The add comes+ // *before* the snapshot — slot i counts edges targeting node i-1,+ // so the running total *with* this slot folded in is node i's+ // block start (slot 0 targets no node and is always empty, pinning+ // start[0] at 0). Snapshotting before the add shifts every block+ // one slot down and empties node 0, which is exactly the failure+ // mode to watch for here.+ let mut total = 0u32;+ let mut start = vec![0u32; slots];+ for (i, slot) in counts.iter().enumerate() {+ let c = slot.load(Ordering::Relaxed);+ total = total.checked_add(c).expect(+ "drivable edges fit u32: Graph::load refuses an edge_count past u32::MAX",+ );+ slot.store(total, Ordering::Relaxed);+ start[i] = total; }- let mut fill = start.clone();- let mut edges = vec![0u32; total];- for n in 0..node_count {- for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {- if !is_drivable(graph.edge_type(idx)) {- continue;+ // Phase 2: disjoint-slice fill. Every slot written is claimed by+ // exactly one `fetch_add`, so no two threads share one; phase 1+ // validated every edge, so the defensive skips below are unreachable+ // and only guard against filling a corrupt index silently.+ //+ // `Vec<AtomicU32>` rather than `&mut Vec<u32>`: the table is shared+ // across workers, and atomics are `Sync` where a unique borrow is+ // not. Same 4 bytes a slot, converted back after the join.+ let edges: Vec<AtomicU32> =+ std::iter::repeat_with(|| AtomicU32::new(0)).take(total as usize).collect();+ failed.store(false, Ordering::Relaxed);+ par::install(|| {+ shards.par_iter().for_each(|range| {+ for n in range.clone() {+ if failed.load(Ordering::Relaxed) {+ break;+ }+ for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {+ if !is_drivable(graph.edge_type(idx)) {+ continue;+ }+ let Ok(target) = graph.edge_target(idx, n as u32) else {+ failed.store(true, Ordering::Relaxed);+ continue;+ };+ if u64::from(target) >= node_count {+ failed.store(true, Ordering::Relaxed);+ continue;+ }+ let at =+ counts[target as usize].fetch_add(1, Ordering::Relaxed) as usize;+ // `at` is in-bounds by construction (cursor < start+ // + count); the check keeps a logic bug a panic+ // rather than memory unsafety.+ if let Some(slot) = edges.get(at) {+ slot.store(idx, Ordering::Relaxed);+ }+ } }- let target = graph.edge_target(idx, n as u32)? as usize;- edges[fill[target] as usize] = idx;- fill[target] += 1;- }+ });+ });+ if failed.load(Ordering::Relaxed) {+ return err(+ "the graph changed between the junction count and fill passes".to_string(),+ );+ }+ let mut edges: Vec<u32> =+ edges.into_iter().map(AtomicU32::into_inner).collect();+ // Restore ascending `edge_idx` within each node: the serial visit+ // order, and what `incoming.of(n)` has always held. Slices average a+ // couple of edges, so this pass is a linear walk, not a sort cost.+ for n in 0..node_count as usize {+ let (lo, hi) = (start[n] as usize, start[n + 1] as usize);+ edges[lo..hi].sort_unstable(); } start.truncate(node_count as usize + 1); Ok(InEdges { start, edges })
scripts/maps/mamaps_build/src/schema/junction_part2.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part2.rs b/scripts/maps/mamaps_build/src/schema/junction_part2.rsindex 482edf0d92..04af937fde 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part2.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part2.rs@@ -23,6 +23,181 @@ fn distribute(lanes: &[usize], exits: &[usize]) -> Vec<(usize, usize)> { } } +/// The lane connectors through the junction at node `n`, in emission order.+///+/// The whole of [`stream_junctions`]'s loop body except the `sink.push` /+/// `emitted` counting: pure per-node work over shared-read-only tables+/// (`Graph`/`LaneTable` are file mappings with `&self` accessors,+/// `InEdges::of` is a pure slice, `Conventions::at_tile` is a+/// `HashMap::get`), so a batch of node ids fans out across the pool exactly+/// as `materialise_ways` does and the serial drain pushes the results in `n`+/// order — which is what keeps the spill, and therefore the archive,+/// byte-identical at every thread count.+///+/// Within a node the order is exactly the serial loop's: `incoming` order,+/// `legal.sort_by(angle)`, `pairs.sort_unstable(); dedup()`.+fn junctions_for_node(+ n: u64,+ graph: &Graph,+ lanes: Option<&LaneTable>,+ incoming: &InEdges,+ conventions: &Conventions,+) -> Vec<Vec<(f64, f64)>> {+ let mut out: Vec<Vec<(f64, f64)>> = Vec::new();+ let node = graph.node(n);+ let in_arms: Vec<Arm> = incoming+ .of(n)+ .iter()+ .filter_map(|&idx| {+ arm(graph, lanes, idx, source_of(graph, idx) as u32, n as u32, false)+ })+ .collect();+ let out_arms: Vec<Arm> = (graph.edge_ptr(n)..graph.edge_ptr(n + 1))+ .filter(|&idx| is_drivable(graph.edge_type(idx)))+ .filter_map(|idx| {+ let target = graph.edge_target(idx, n as u32).ok()?;+ arm(graph, lanes, idx, n as u32, target, true)+ })+ .collect();+ if in_arms.is_empty() || out_arms.len() < 2 {+ return out;+ }+ // A junction is a node three or more distinct roads meet at. Degree-2 chains are collapsed+ // by the generator, so the survivors below this bar are dead ends, attribute breaks and+ // transit stops — none of which anything turns at.+ let degree: BTreeSet<u32> =+ in_arms.iter().chain(&out_arms).map(|a| a.neighbour).collect();+ if degree.len() < 3 {+ return out;+ }++ let (tx, ty) = tile_build::geom::project(+ f64::from(node.1) * 1e-7,+ f64::from(node.0) * 1e-7,+ super::boundaries::COARSE_ZOOM,+ );+ let left_hand = conventions+ .at_tile(+ super::boundaries::COARSE_ZOOM,+ tx.max(0.0) as u64,+ ty.max(0.0) as u64,+ )+ .left_hand;++ for approach in &in_arms {+ // Every exit but the one back the way you came. The graph carries no turn restrictions,+ // so this is the whole legality model: inference, and generous.+ let mut legal: Vec<(usize, f64, Turn)> = out_arms+ .iter()+ .enumerate()+ .filter(|(_, exit)| exit.neighbour != approach.neighbour)+ .map(|(i, exit)| {+ let delta = normalise_degrees(exit.heading - approach.heading);+ (i, delta, classify_turn(delta))+ })+ // A reversal is not a movement this layer draws, and the neighbour test above does+ // not catch it. On a divided highway the median slot reverses onto the *opposing+ // carriageway*, which is a different node, so it survives that filter and arrives+ // here as a legal 180-degree movement. The curve it produces never enters the+ // junction at all: with `f_out = -f_in` all four bezier control points sit behind+ // the node, so it draws as a flat hook doubling back along the approach.+ .filter(|(_, _, turn)| *turn != Turn::Reverse)+ .collect();+ if legal.is_empty() {+ continue;+ }+ // Left→right as the driver sees them, which is the order lane masks are stored in.+ legal.sort_by(|a, b| a.1.total_cmp(&b.1));++ // Both ends read the same function of their own arm, so neither can drift from the+ // other and neither depends on who is looking. No count is derived from the junction's+ // shape: `legal.len()` counts exits, not lanes, and using it as a width fanned the+ // endpoints across phantom lanes and off the carriageway.+ let approach_lanes = effective_lanes(approach);++ // `turn:lanes` where it exists, the arm's own lane count where it does not.+ let mut pairs: Vec<(usize, usize)> = match &approach.masks {+ Some(masks) => {+ let mut pairs = Vec::new();+ for turn in Turn::ALL {+ let bit = turn.bit();+ let claimants: Vec<usize> = masks+ .iter()+ .enumerate()+ .filter(|(_, m)| {+ // A lane whose only marking is "none" is treated as a through lane,+ // which is what an unmarked lane at a junction means in practice.+ **m & bit != 0+ || (turn == Turn::Through+ && (**m == 0 || **m == LANE_NONE))+ })+ .map(|(k, _)| k)+ .collect();+ if claimants.is_empty() {+ continue;+ }+ pairs.extend(distribute(&claimants, &exits_for(turn, &legal)));+ }+ pairs+ }+ // Untagged, which is the overwhelming majority of roads. The arm's real lanes are+ // spread over its legal exits — and since an untagged arm has exactly one, every+ // movement leaves from lane 0 and the connectors share the arm's mouth. Assigning+ // a lane *index* per exit here was the other half of the fabricated width: it put+ // the third movement 1.5 lane widths out on a road with one lane.+ None => {+ let lanes: Vec<usize> = (0..approach_lanes).collect();+ let exits: Vec<usize> = legal.iter().map(|(i, _, _)| *i).collect();+ distribute(&lanes, &exits)+ }+ };++ // Ordered so a movement's lanes rank left→right, and deduplicated because two tagged+ // indications can fall back to the same exit and would otherwise draw one connector+ // twice on top of itself.+ pairs.sort_unstable();+ pairs.dedup();++ for &(in_lane, exit_index) in &pairs {+ let exit = &out_arms[exit_index];+ let Some((_, _, turn)) = legal.iter().find(|(i, _, _)| *i == exit_index) else {+ continue;+ };+ // Through movements need no connector: the approach lane's own+ // carriageway ribbon already paints the straight path, and the+ // connector draws as an exact identity over it (same style entry,+ // same colour — see the module docs on reading a screenshot).+ // Dropping them keeps only turns, which is where the markings+ // actually differ from the road beneath.+ if *turn == Turn::Through {+ continue;+ };+ let out_lanes = effective_lanes(exit);+ // This lane's place among the lanes making the same movement into the same exit.+ let siblings: Vec<usize> =+ pairs.iter().filter(|(_, e)| *e == exit_index).map(|&(l, _)| l).collect();+ let rank = siblings.iter().position(|&l| l == in_lane).unwrap_or(0);+ let out_lane =+ exit_lane(*turn, in_lane, approach_lanes, out_lanes, rank, siblings.len());+ let Some(points) = connector(+ node,+ approach,+ in_lane,+ approach_lanes,+ exit,+ out_lane,+ out_lanes,+ *turn,+ left_hand,+ ) else {+ continue;+ };+ out.push(points);+ }+ }+ out+}+ /// Read the v6 graph at `dir` and push one line feature per lane connector into `sink`. Returns the /// number of connectors emitted. ///@@ -39,159 +214,49 @@ pub fn stream_junctions(dir: &Path, conventions: &Conventions, sink: &mut Sink) let class = junction_class(); let mut emitted = 0u64; - for n in 0..graph.node_count {- let node = graph.node(n);- let in_arms: Vec<Arm> = incoming- .of(n)- .iter()- .filter_map(|&idx| {- arm(&graph, lanes.as_ref(), idx, source_of(&graph, idx) as u32, n as u32, false)- })- .collect();- let out_arms: Vec<Arm> = (graph.edge_ptr(n)..graph.edge_ptr(n + 1))- .filter(|&idx| is_drivable(graph.edge_type(idx)))- .filter_map(|idx| {- let target = graph.edge_target(idx, n as u32).ok()?;- arm(&graph, lanes.as_ref(), idx, n as u32, target, true)- })- .collect();- if in_arms.is_empty() || out_arms.len() < 2 {- continue;+ // Batched, the `materialise_ways` pattern: `junctions_for_node` is pure+ // per-node work over shared-read-only tables, so a batch of node ids goes+ // as wide as the pool while the drain pushes **in `n` order**, which is+ // what keeps the spill — and therefore the archive — byte-identical at+ // every thread count. The bar ticks in the drain, per node, so it spans+ // the whole graph and this phase is never silent again.+ //+ // 32 Ki node ids is a few hundred KB of ids in flight; junctions are+ // sparse, so the geometry coming back is far smaller than a ways batch of+ // the same count.+ const JUNCTION_BATCH: usize = 32 * 1024;+ let mut bar = Progress::new(+ "Junctions".to_string(),+ graph.node_count as usize,+ "node(s)",+ true,+ );+ let mut ids: Vec<u64> = Vec::with_capacity(JUNCTION_BATCH);+ let mut built: Vec<Vec<Vec<(f64, f64)>>> = Vec::with_capacity(JUNCTION_BATCH);+ let mut next = 0u64;+ loop {+ ids.clear();+ while ids.len() < JUNCTION_BATCH && next < graph.node_count {+ ids.push(next);+ next += 1; }- // A junction is a node three or more distinct roads meet at. Degree-2 chains are collapsed- // by the generator, so the survivors below this bar are dead ends, attribute breaks and- // transit stops — none of which anything turns at.- let degree: BTreeSet<u32> =- in_arms.iter().chain(&out_arms).map(|a| a.neighbour).collect();- if degree.len() < 3 {- continue;+ if ids.is_empty() {+ break; }-- let (tx, ty) = tile_build::geom::project(- f64::from(node.1) * 1e-7,- f64::from(node.0) * 1e-7,- super::boundaries::COARSE_ZOOM,- );- let left_hand = conventions- .at_tile(- super::boundaries::COARSE_ZOOM,- tx.max(0.0) as u64,- ty.max(0.0) as u64,- )- .left_hand;-- for approach in &in_arms {- // Every exit but the one back the way you came. The graph carries no turn restrictions,- // so this is the whole legality model: inference, and generous.- let mut legal: Vec<(usize, f64, Turn)> = out_arms- .iter()- .enumerate()- .filter(|(_, exit)| exit.neighbour != approach.neighbour)- .map(|(i, exit)| {- let delta = normalise_degrees(exit.heading - approach.heading);- (i, delta, classify_turn(delta))- })- // A reversal is not a movement this layer draws, and the neighbour test above does- // not catch it. On a divided highway the median slot reverses onto the *opposing- // carriageway*, which is a different node, so it survives that filter and arrives- // here as a legal 180-degree movement. The curve it produces never enters the- // junction at all: with `f_out = -f_in` all four bezier control points sit behind- // the node, so it draws as a flat hook doubling back along the approach.- .filter(|(_, _, turn)| *turn != Turn::Reverse)- .collect();- if legal.is_empty() {- continue;- }- // Left→right as the driver sees them, which is the order lane masks are stored in.- legal.sort_by(|a, b| a.1.total_cmp(&b.1));-- // Both ends read the same function of their own arm, so neither can drift from the- // other and neither depends on who is looking. No count is derived from the junction's- // shape: `legal.len()` counts exits, not lanes, and using it as a width fanned the- // endpoints across phantom lanes and off the carriageway.- let approach_lanes = effective_lanes(approach);-- // `turn:lanes` where it exists, the arm's own lane count where it does not.- let mut pairs: Vec<(usize, usize)> = match &approach.masks {- Some(masks) => {- let mut pairs = Vec::new();- for turn in Turn::ALL {- let bit = turn.bit();- let claimants: Vec<usize> = masks- .iter()- .enumerate()- .filter(|(_, m)| {- // A lane whose only marking is "none" is treated as a through lane,- // which is what an unmarked lane at a junction means in practice.- **m & bit != 0- || (turn == Turn::Through- && (**m == 0 || **m == LANE_NONE))- })- .map(|(k, _)| k)- .collect();- if claimants.is_empty() {- continue;- }- pairs.extend(distribute(&claimants, &exits_for(turn, &legal)));- }- pairs- }- // Untagged, which is the overwhelming majority of roads. The arm's real lanes are- // spread over its legal exits — and since an untagged arm has exactly one, every- // movement leaves from lane 0 and the connectors share the arm's mouth. Assigning- // a lane *index* per exit here was the other half of the fabricated width: it put- // the third movement 1.5 lane widths out on a road with one lane.- None => {- let lanes: Vec<usize> = (0..approach_lanes).collect();- let exits: Vec<usize> = legal.iter().map(|(i, _, _)| *i).collect();- distribute(&lanes, &exits)- }- };-- // Ordered so a movement's lanes rank left→right, and deduplicated because two tagged- // indications can fall back to the same exit and would otherwise draw one connector- // twice on top of itself.- pairs.sort_unstable();- pairs.dedup();-- for &(in_lane, exit_index) in &pairs {- let exit = &out_arms[exit_index];- let Some((_, _, turn)) = legal.iter().find(|(i, _, _)| *i == exit_index) else {- continue;- };- // Through movements need no connector: the approach lane's own- // carriageway ribbon already paints the straight path, and the- // connector draws as an exact identity over it (same style entry,- // same colour — see the module docs on reading a screenshot).- // Dropping them keeps only turns, which is where the markings- // actually differ from the road beneath.- if *turn == Turn::Through {- continue;- };- let out_lanes = effective_lanes(exit);- // This lane's place among the lanes making the same movement into the same exit.- let siblings: Vec<usize> =- pairs.iter().filter(|(_, e)| *e == exit_index).map(|&(l, _)| l).collect();- let rank = siblings.iter().position(|&l| l == in_lane).unwrap_or(0);- let out_lane =- exit_lane(*turn, in_lane, approach_lanes, out_lanes, rank, siblings.len());- let Some(points) = connector(- node,- approach,- in_lane,- approach_lanes,- exit,- out_lane,- out_lanes,- *turn,- left_hand,- ) else {- continue;- };+ built.clear();+ par::install(|| {+ ids.par_iter()+ .map(|&n| junctions_for_node(n, &graph, lanes.as_ref(), &incoming, conventions))+ .collect_into_vec(&mut built)+ });+ for node_geoms in built.drain(..) {+ for points in node_geoms { sink.push(&class, &Geometry::Lines(vec![points]))?; emitted += 1; }+ bar.tick("node(s)"); } }+ bar.finish("node(s)"); Ok(emitted) }
scripts/maps/mamaps_build/src/schema/junction_part3.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part3.rs b/scripts/maps/mamaps_build/src/schema/junction_part3.rsindex f37af9ceb1..86157f6d12 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part3.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part3.rs@@ -71,6 +71,46 @@ mod tests { (emitted, lines) } + /// **The property the parallel junction streamer exists to keep.** The+ /// spill is a function of the graph, not of the thread count.+ ///+ /// The crossroads fixture is tiny, so this pins the ordering discipline+ /// (parallel map, serial ordered drain) rather than measuring a speedup:+ /// 1 thread is the configuration where the pool is degenerate, 3 is the+ /// awkward one where completion order is guaranteed not to be read+ /// order. The count and the decoded geometry must agree everywhere —+ /// `sink.push` order is the spill order is the archive, so any drift+ /// here is a byte drift downstream.+ #[test]+ fn connectors_are_identical_at_every_thread_count() {+ let outer = crossroads(&[(4u32, vec![LANE_LEFT, LANE_THROUGH, LANE_RIGHT])]);+ // The tagged north approach keeps left + right (through dropped);+ // the three untagged approaches keep two turns each: 2 + 6.+ par::set_threads(1);+ let (emitted_one, lines_one) = stream(&outer);+ assert_eq!(emitted_one as usize, lines_one.len());+ for threads in [2usize, 3, 8] {+ par::set_threads(threads);+ // A fresh fixture per count: `stream` spills beside the graph+ // dir, and reusing one dir would serialize the runs through the+ // same `features.tmp`.+ let fixture =+ crossroads(&[(4u32, vec![LANE_LEFT, LANE_THROUGH, LANE_RIGHT])]);+ let (emitted, lines) = stream(&fixture);+ assert_eq!(+ emitted, emitted_one,+ "{threads} threads changed the connector count"+ );+ assert_eq!(+ lines, lines_one,+ "{threads} threads changed the connector bytes"+ );+ }+ par::set_threads(+ std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4),+ );+ }+ /// **A connector must start and end on the asphalt the renderer actually paints.** /// /// Two defects met here and neither could be fixed alone. The ends disagreed — the approach was
scripts/maps/mamaps_build/src/schema/landtype.rs
diff --git a/scripts/maps/mamaps_build/src/schema/landtype.rs b/scripts/maps/mamaps_build/src/schema/landtype.rsindex 224165e236..7558656430 100644--- a/scripts/maps/mamaps_build/src/schema/landtype.rs+++ b/scripts/maps/mamaps_build/src/schema/landtype.rs@@ -48,6 +48,7 @@ use std::path::Path; use osm_ingest::proto::{err, Result}; use tile_build::geom::Geometry;+use tile_build::progress::Progress; use tilecodec::mamaps::dict::LAYER_LANDTYPE; use super::{kind, Class, TagSource};@@ -351,7 +352,15 @@ pub fn stream_prepared( if is_shapefile { let mut reader = crate::shapefile::ShapeReader::open(path)?; reader.clip_to(bbox);+ // The `.shp` cursor is single-threaded by construction — one+ // sequential record stream — so this stays serial and the bar is+ // the fix: a planet coastline product is ~1 GB of records with+ // nothing on stdout today. Ticked per record read, kept or not, so+ // it spans the whole file.+ let mut bar =+ Progress::new("Land: coastline".to_string(), reader.records(), "record(s)", true); while let Some(rings) = reader.next()? {+ bar.tick("record(s)"); // One mamaps feature per polygon, not per record: a record can hold several islands, and // the tessellator wants one exterior with its own holes. for polygon in crate::shapefile::group(rings) {@@ -359,6 +368,7 @@ pub fn stream_prepared( written += 1; } }+ bar.finish("record(s)"); println!( " {} land polygon(s) kept, {} outside the extract", written, reader.skipped,@@ -367,10 +377,18 @@ pub fn stream_prepared( let text = std::fs::read_to_string(path).map_err(|e| { osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display())) })?;+ // GeoJSON-seq is line-delimited, so the count is known up front and+ // the bar spans the file. Lines still parse serially in file order:+ // a malformed line is a fail-fast error naming its line, and+ // parallel parse would reorder that diagnostic.+ let total_lines = text.lines().filter(|line| !line.trim().is_empty()).count();+ let mut bar =+ Progress::new("Land: coastline".to_string(), total_lines, "line(s)", true); for (line_number, line) in text.lines().enumerate() { if line.trim().is_empty() { continue; }+ bar.tick("line(s)"); let Some(feature) = tile_build::geojson::parse_feature(line) else { return err(format!( "{}:{}: not a GeoJSON feature",@@ -389,6 +407,7 @@ pub fn stream_prepared( written += 1; } }+ bar.finish("line(s)"); } if written == 0 { return err(format!(
scripts/maps/mamaps_build/src/schema/traffic.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic.rs b/scripts/maps/mamaps_build/src/schema/traffic.rsindex ebeb1d64a4..aeb980d15f 100644--- a/scripts/maps/mamaps_build/src/schema/traffic.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -174,9 +174,6 @@ pub(crate) struct Graph { impl Graph { pub(crate) fn load(dir: &Path) -> Result<Graph> {- let map = |name: &str| -> Result<osm_ingest::mem::Mapped> {- osm_ingest::mem::Mapped::open(&dir.join(name)).map_err(osm_ingest::proto::Error)- }; let meta = std::fs::read(dir.join("metadata.bin")).map_err(|e| { osm_ingest::proto::Error(format!( "cannot read {}: {e}",@@ -207,7 +204,24 @@ impl Graph { )); } - let nodes = map("nodes.bin")?;+ // The three tables open concurrently: three page-cache faults on+ // three files, no dependency between them. Metadata validation above+ // stays serial — it sizes everything below. Small win, almost free.+ let (nodes, edges, inter) = std::thread::scope(|scope| {+ let open = |name: &'static str| {+ scope.spawn(move || {+ osm_ingest::mem::Mapped::open(&dir.join(name))+ .map_err(osm_ingest::proto::Error)+ })+ };+ let (a, b, c) = (open("nodes.bin"), open("edges.bin"), open("intermediate.bin"));+ let nodes = a.join().expect("the nodes.bin opener");+ let edges = b.join().expect("the edges.bin opener");+ let inter = c.join().expect("the intermediate.bin opener");+ nodes.and_then(|nodes| edges.map(|edges| (nodes, edges))).and_then(+ |(nodes, edges)| inter.map(|inter| (nodes, edges, inter)),+ )+ })?; let want_nodes = (node_count + 1) .checked_mul(12) .ok_or_else(|| osm_ingest::proto::Error("node table size overflows".to_string()))?;@@ -219,7 +233,6 @@ impl Graph { )); } - let edges = map("edges.bin")?; let escape_first_off = align_up8((edge_count as usize) * 7); let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1; let escapes_off = escape_first_off + (escape_blocks as usize) * 4;@@ -231,7 +244,6 @@ impl Graph { )); } - let inter = map("intermediate.bin")?; if inter.len() < 8 { return err("intermediate.bin is too short to hold its geometry-edge count".to_string()); }
scripts/maps/mamaps_build/src/schema/transit.rs
diff --git a/scripts/maps/mamaps_build/src/schema/transit.rs b/scripts/maps/mamaps_build/src/schema/transit.rsindex 23bf3bd7b2..03207c7638 100644--- a/scripts/maps/mamaps_build/src/schema/transit.rs+++ b/scripts/maps/mamaps_build/src/schema/transit.rs@@ -28,6 +28,7 @@ use std::path::Path; use osm_ingest::proto::{err, Result}; use tile_build::geom::Geometry;+use tile_build::progress::Progress; use tilecodec::mamaps::dict::LAYER_TRANSIT; use tilecodec::mvt::Value; @@ -103,10 +104,18 @@ pub fn stream_routes( } let mut written = 0u64; let mut skipped = 0u64;+ // File order is feature order and the layer is coalesced, so the push+ // stays serial; the bar is what keeps a large feed from reading as a+ // hang. Ticked per line read (not per route kept), so it spans the+ // whole file even when most of it is outside the extract.+ let total_lines = text.lines().filter(|line| !line.trim().is_empty()).count();+ let mut bar =+ Progress::new("Transit: routes".to_string(), total_lines, "line(s)", true); for (line_number, line) in text.lines().enumerate() { if line.trim().is_empty() { continue; }+ bar.tick("line(s)"); let at = |what: &str| { osm_ingest::proto::Error(format!("{}:{}: {what}", path.display(), line_number + 1)) };@@ -151,6 +160,7 @@ pub fn stream_routes( path.display(), )); }+ bar.finish("line(s)"); println!(" {written} transit route(s) kept, {skipped} outside the extract"); Ok(written) }
scripts/maps/mamaps_build/src/shapefile.rs
diff --git a/scripts/maps/mamaps_build/src/shapefile.rs b/scripts/maps/mamaps_build/src/shapefile.rsindex 10fc3cc7d7..d0e506fb8d 100644--- a/scripts/maps/mamaps_build/src/shapefile.rs+++ b/scripts/maps/mamaps_build/src/shapefile.rs@@ -95,6 +95,16 @@ impl ShapeReader { self.filter = Some(bbox); } + /// How many records the header declares, for progress sizing: the file+ /// length in words minus the header, over the 8-byte record header plus+ /// the smallest a `Polygon` body can be. An underestimate when records+ /// run large, which a progress bar tolerates (it clamps at 100%) — and+ /// exact for sizing, never for logic.+ pub fn records(&self) -> usize {+ const MIN_RECORD_BYTES: u64 = 8 + 44;+ (self.remaining / MIN_RECORD_BYTES) as usize+ }+ /// The next record's rings, or `None` at the end of the file. /// /// Rings come back as `(ring, is_exterior)` in file order, so the caller can group them without