maps: archive builder improvements
- Commit
7ff5b747160270baa94eee7c224d29defc640e74- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-24 04:56 UTC (1 month ago)
- Parents
2b9fa08
Diff
scripts/maps/mamaps_build/src/dem.rs
diff --git a/scripts/maps/mamaps_build/src/dem.rs b/scripts/maps/mamaps_build/src/dem.rsindex e2e1ca7719..3cfadf7570 100644--- a/scripts/maps/mamaps_build/src/dem.rs+++ b/scripts/maps/mamaps_build/src/dem.rs@@ -20,6 +20,8 @@ use std::collections::HashMap; use std::f64::consts::PI; use std::path::Path; +use rayon::prelude::*;+use tile_build::par; use tilecodec::mamaps::body::Heightmap; use tilecodec::pmtiles::tile_id; use tilecodec::proto::{err, Error, Result};@@ -91,14 +93,29 @@ pub struct Dem { impl Dem { /// Read and parse a `.mdem` dataset from disk.+ ///+ /// Mapped, not read: the 13 GB world file would otherwise cost a+ /// single-threaded `fs::read` plus a full copy before parsing starts.+ /// The mapping faults pages in on the pool's 64 threads during the+ /// parallel parse below, and the bytes are never copied — each tile's+ /// samples land directly in its grid `Vec`. The mapping drops on return;+ /// the `Dem` owns its grids. pub fn load(path: &Path) -> Result<Dem> {- let bytes = std::fs::read(path)- .map_err(|e| Error(format!("reading the DEM dataset {}: {e}", path.display())))?;- Dem::parse(&bytes)+ let mapped = osm_ingest::mem::Mapped::open(path).map_err(Error)?;+ Dem::parse(&mapped) } /// Parse a `.mdem` dataset: a 12-byte header (`MDEM`, version, out_zoom, `dim` u16, tile count /// u32), then per tile a `u64` tile id and its `dim * dim` `u16` samples, little-endian.+ ///+ /// Tiles parse on the pool: records are fixed-stride (`8 + cells * 2` bytes), so tile `i`+ /// starts at `12 + i * stride` with no dependency on any other tile. Each worker decodes a+ /// contiguous run into owned `(id, samples)` pairs; the single-threaded fold inserts them in+ /// file order. Same pairs as the serial loop — the map holds the same contents, and nothing+ /// ever iterates it (only `heightmap_for`'s `.get`), so no byte can move. The 13 GB world+ /// dataset's per-sample `u16::from_le_bytes` + per-tile alloc + hash insert runs ~50 s+ /// serially on every build regardless of region; fanning out the decode leaves only the+ /// `fs::read` and the inserts. fn parse(bytes: &[u8]) -> Result<Dem> { if bytes.len() < 12 { return err("a .mdem dataset is shorter than its 12-byte header");@@ -118,21 +135,43 @@ impl Dem { let cells = dim as usize * dim as usize; // One tile: an 8-byte id then `cells` little-endian u16 samples. let stride = 8 + cells * 2;- let mut at = 12usize;+ if bytes.len() < 12 + count.saturating_mul(stride) {+ return err("a .mdem dataset ends before its tile count");+ }+ // Decoded tile indices, not tiles: the byte slices borrow `bytes`, so the+ // pool maps indices to owned pairs and the fold inserts in file order.+ // Chunks of 1024 tiles balance scheduling against per-task overhead+ // (~170 KB of samples per chunk at dim 9 — L2-resident working set).+ const PARSE_CHUNK_TILES: usize = 1024;+ let chunks = count.div_ceil(PARSE_CHUNK_TILES);+ let mut pairs: Vec<Vec<(u64, Vec<u16>)>> = Vec::with_capacity(chunks);+ par::install(|| {+ (0..chunks)+ .into_par_iter()+ .map(|chunk| {+ let lo = chunk * PARSE_CHUNK_TILES;+ let hi = (lo + PARSE_CHUNK_TILES).min(count);+ let mut out = Vec::with_capacity(hi - lo);+ for i in lo..hi {+ let at = 12 + i * stride;+ let id =+ u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"));+ let mut samples = Vec::with_capacity(cells);+ for c in 0..cells {+ let o = at + 8 + c * 2;+ samples.push(u16::from_le_bytes([bytes[o], bytes[o + 1]]));+ }+ out.push((id, samples));+ }+ out+ })+ .collect_into_vec(&mut pairs);+ }); let mut grids = HashMap::with_capacity(count);- for _ in 0..count {- if at + stride > bytes.len() {- return err("a .mdem tile runs past the end of the dataset");- }- let id = u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"));- at += 8;- let mut samples = Vec::with_capacity(cells);- for i in 0..cells {- let o = at + i * 2;- samples.push(u16::from_le_bytes([bytes[o], bytes[o + 1]]));+ for chunk in pairs.drain(..) {+ for (id, samples) in chunk {+ grids.insert(id, samples); }- at += cells * 2;- grids.insert(id, samples); } Ok(Dem { out_zoom, dim, grids }) }
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 89664901e6..b20fcbe997 100644--- a/scripts/maps/mamaps_build/src/extract_fallback.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -293,9 +293,12 @@ fn point_on_segment(point: (f64, f64), a: (f64, f64), b: (f64, f64)) -> bool { if len2 == 0.0 { return (px - a.0).abs() <= EPS && (py - a.1).abs() <= EPS; }- // Perpendicular distance, scale-aware: |cross| / |segment|.+ // Perpendicular distance, scale-aware: |cross| / |segment|. Compared+ // without the square root (|cross|^2 <= EPS^2 * len2, all sides+ // non-negative) — same predicate, no sqrt per segment on the hottest+ // inner loop of the link pass. let cross = dx * (py - a.1) - dy * (px - a.0);- if (cross / len2.sqrt()).abs() > EPS {+ if cross * cross > EPS * EPS * len2 { return false; } px >= a.0.min(b.0) - EPS@@ -385,24 +388,59 @@ pub fn extend_region_links_with( country_zooms: &mut HashMap<u64, u8>, populations: &HashMap<u64, u64>, ) -> Result<FallbackStats> {- // Pass 1: boundary shapes. Only `region_area` areas (the mask's own shapes, carrying the- // admin level in `kind_detail`); border lines enclose nothing.+ // Pass 1: boundary shapes AND places, in one scan. Only `region_area`+ // areas (the mask's own shapes, carrying the admin level in `kind_detail`);+ // border lines enclose nothing. Places are positional, so node,+ // way-centroided and relation-centroided labels all link by the tagged id+ // they already carry.+ //+ // One scan, not two: the store reader is one sequential cursor over tens+ // of GB of spill, and both passes filtered it by layer. Collecting both+ // vectors in a single streaming pass deletes a full decode. Peak is+ // unchanged — boundaries already lived through place collection.+ struct PlacePoint {+ id: u64,+ point: (f64, f64),+ kind: Band,+ kind_name: String,+ } let mut boundaries: Vec<Boundary> = Vec::new();- let mut reader = store.reader()?;- while let Some(feature) = reader.next()? {- if feature.class.layer != LAYER_BOUNDARIES || !feature.class.area {- continue;- }- if feature.id == ID_NONE {- continue;- }- let Geometry::Polygons(polygons) = feature.geometry else {- continue;- };- if polygons.is_empty() {- continue;+ let mut places: Vec<PlacePoint> = Vec::new();+ {+ let mut reader = store.reader()?;+ while let Some(feature) = reader.next()? {+ if feature.id == ID_NONE {+ continue;+ }+ if feature.class.layer == LAYER_BOUNDARIES && feature.class.area {+ let Geometry::Polygons(polygons) = feature.geometry else {+ continue;+ };+ if polygons.is_empty() {+ continue;+ }+ boundaries.push(Boundary::new(feature.id, feature.class.kind_detail, polygons));+ } else if feature.class.layer == LAYER_PLACES {+ 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(),+ });+ } }- boundaries.push(Boundary::new(feature.id, feature.class.kind_detail, polygons)); } boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0); let grid = Grid::build(&boundaries);@@ -426,42 +464,11 @@ pub fn extend_region_links_with( // 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(),- });- }- }+ //+ // NOTE: `places` now arrives from the fused pass-1 scan above (same+ // reader, same filter, same spill order), not from a second scan. What+ // follows is unchanged: drain order — and therefore every inserted key,+ // value, stat and country zoom — is identical. let mut stats = FallbackStats::default(); let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new(); // Member links always win: counted exactly as the serial loop did,
scripts/maps/mamaps_build/src/extract_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1.rs b/scripts/maps/mamaps_build/src/extract_part1.rsindex fc1d85bd36..d8c4ded8e8 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -83,19 +83,24 @@ pub fn extract( way_max_ref, ways_anon, region_label_nodes,+ mut needed, } = pass1;- // The ways spill, shared by refcount with every reader below (collectors,- // lanefill scan, materialise). Last use is `materialise_ways`; freed there.+ // The ways spill, shared by refcount with the readers below (lanefill+ // scan, materialise). Last use is `materialise_ways`; freed there. timer.switch("refs-collect");+ // Member ways' refs join the fused bitset: the great majority carry no+ // tags of their own, so nothing else asked for them.+ for refs in members.values() {+ for &id in refs {+ needed.set_growable(id)?;+ }+ } let table = build_resolved_table( input, &blobs, &blob_kinds,- &ways_path,- &ways_anon, &members,- way_refs,- way_max_ref,+ needed, &select, layers, region.as_ref(),@@ -350,6 +355,10 @@ struct Pass1Out { /// `label` wins over `admin_centre` when a relation lists both, since `label` is the place node /// the map actually renders. region_label_nodes: HashMap<i64, i64>,+ /// The needed-node bitset, collected during the drain above: every+ /// classified way's refs plus (set by the caller) the member ways' refs.+ /// Pass 3 resolves exactly these ids, without re-reading the ways spill.+ needed: NeededBits, } /// Pass 1 (ways + relations) plus the corridor promotion. Moved whole from@@ -384,6 +393,11 @@ fn run_pass1( // planet extract is most of the file. let mut ways = WaySink::create_planned(&ways_path, spill_plan)?; let mut relations: Vec<Relation> = Vec::new();+ // The needed-node bitset, fused into this pass: every classified way sets+ // its refs here in the drain below, so pass 3 never re-reads the ways+ // spill to collect them. Grows on demand (the maximum is not known until+ // the last push); member refs join after the drain.+ let mut needed = NeededBits::new_growable(); // `admin_centre`/`label` node member -> boundary relation id (raw), gathered as region shapes // are classified below. See [`Pass1Out::region_label_nodes`]. let mut region_label_nodes: HashMap<i64, i64> = HashMap::new();@@ -568,6 +582,12 @@ fn run_pass1( // leaves the file in ascending id order. `WaySink::push` refuses an id that does not // advance rather than letting an unsorted file reorder the archive silently. for (id, way) in chunk_ways {+ // Fused ref collection: the refs are decoded and in hand here,+ // so the bitset takes them now instead of a later pass+ // re-reading the spill to find them again.+ for &node in &way.refs {+ needed.set_growable(node)?;+ } ways.push( id, &way.class,@@ -613,5 +633,6 @@ fn run_pass1( way_max_ref, ways_anon, region_label_nodes,+ needed, }) }\ No newline at end of file
scripts/maps/mamaps_build/src/extract_part2.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part2.rs b/scripts/maps/mamaps_build/src/extract_part2.rsindex 8217eb7a33..03ebb4dadc 100644--- a/scripts/maps/mamaps_build/src/extract_part2.rs+++ b/scripts/maps/mamaps_build/src/extract_part2.rs@@ -147,11 +147,8 @@ fn build_resolved_table( input: &Path, blobs: &[pbf::BlobLoc], blob_kinds: &[u8],- ways_path: &Path,- ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>, members: &MemberWays,- way_refs: u64,- way_max_ref: i64,+ needed: NeededBits, select: &Select, layers: Layers, region: Option<&osm_ingest::bbox::BBox>,@@ -159,20 +156,30 @@ fn build_resolved_table( stats: &mut Stats, timer: &mut crate::timing::PhaseTimer, ) -> Result<NodeLocations> {- // --- pass 3: the coordinates those two asked for, plus the label nodes ----------------- //- // The classified ways are read off disk instead of walked in memory. Order does not matter to- // either path below, so this is a plain streaming pass over the spill.- let member_refs: usize = members.values().map(|refs| refs.len()).sum();- let refs_total = way_refs as usize + member_refs;- let max_ref = members- .values()- .flat_map(|refs| refs.iter().copied())- .fold(way_max_ref, i64::max);- let table = if refs_total <= REFS_IN_MEMORY {- collect_needed_in_memory(&ways_path, ways_anon, &members, refs_total, timer)?+ // The fused bitset already holds every classified way's refs (set in pass+ // 1's drain); member ways join here. No ways-spill re-scan: the refs were+ // decoded and in hand where they were set.+ let mut needed = needed;+ for refs in members.values() {+ for &id in refs {+ needed.set_growable(id)?;+ }+ }+ // Small extracts take the exact vector; planet-scale takes the bitset the+ // words move straight into. The threshold now counts distinct ids (the old+ // one counted duplicates), which only moves borderline extracts toward the+ // vector path — whose input arrives sorted-unique, so its sort is trivial.+ let table = if needed.len() <= REFS_IN_MEMORY {+ let ids: Vec<i64> = needed.ids().collect();+ timer.switch("id-index");+ NodeLocations::new(ids)? } else {- collect_needed_by_bitset(&ways_path, ways_anon, &members, max_ref, timer)?+ timer.switch("id-index");+ // The bitset's words move into the rank index directly (`from_bitset`),+ // not through `ids()`: walking them out as ids and re-setting them+ // would hold two ~1.5 GB words arrays at once.+ let (words, count) = needed.into_words();+ NodeLocations::from_bitset(words, count)? }; timer.switch("coords-resolve"); stats.nodes_needed = table.len() as u64;@@ -212,7 +219,9 @@ fn build_resolved_table( }; let drain = |hits: Vec<(Class, f64, f64, Option<String>, u64)>| -> Result<()> { for (class, lon, lat, name, id) in hits {- sink.push_named(&class, &Geometry::Points(vec![(lon, lat)]), name.as_deref(), id)?;+ let encoded =+ crate::store::EncodedGeom::live(&Geometry::Points(vec![(lon, lat)]))?;+ sink.push_named(&class, &encoded, name.as_deref(), id)?; stats.features += 1; stats.nodes_classified += 1; }@@ -462,6 +471,41 @@ fn inherit_lane_counts( Ok(inherited_lanes) } +/// One materialised way, decided on the pool: the serial drain only appends.+///+/// `Failed` (no geometry) counts `geometry_failed`; `Dropped` (region-filtered)+/// counts nothing — exactly the two non-pushed paths the inline drain had.+/// `Kept` carries the spill record's geometry bytes plus the facts the spill+/// derives, so the drain does no vertex walk.+enum BuiltWay {+ Failed,+ Dropped,+ Kept(crate::store::EncodedGeom),+}++/// Resolve one batch item's fate: geometry, region keep/drop, spill encoding.+///+/// Pure over shared tables (`table`, `region`): safe across the pool. The+/// region test runs here rather than in the drain — it walks every vertex+/// (`geometry_touches`), and the drain must not. Order-independent: one slot+/// per batch item, drained positionally.+fn build_way(+ class: &Class,+ geometry: Option<Geometry>,+ region: Option<&osm_ingest::bbox::BBox>,+) -> Result<BuiltWay> {+ let Some(geometry) = geometry else {+ return Ok(BuiltWay::Failed);+ };+ // Region filter: roads, pois and buildings outside the bbox are dropped.+ // The geometry is resolved by now, so this is a direct touches-box test+ // on the line the way produced (a centroided point for labels).+ if is_region_filtered(class.layer) && !geometry_touches(&geometry, region) {+ return Ok(BuiltWay::Dropped);+ }+ Ok(BuiltWay::Kept(crate::store::EncodedGeom::live(&geometry)?))+}+ /// Materialise classified ways off disk, in id order. Moved whole from `extract`. /// /// `region` filters the built layers (`roads`, `poi`, `buildings`): a way in@@ -509,7 +553,14 @@ fn materialise_ways( Carriageway, Option<BuildingAttrs>, )> = Vec::with_capacity(MATERIALISE_BATCH);- let mut built: Vec<Option<Geometry<(f64, f64)>>> = Vec::with_capacity(MATERIALISE_BATCH);+ let mut built: Vec<Result<BuiltWay>> = Vec::with_capacity(MATERIALISE_BATCH);+ // TEMP-PROFILE: split the batch loop into fill / resolve / drain walls.+ // Removed once the split is measured (naonly run).+ let mut t_fill = std::time::Duration::ZERO;+ let mut t_resolve = std::time::Duration::ZERO;+ let mut t_push = std::time::Duration::ZERO;+ let mut t_rest = std::time::Duration::ZERO;+ let mut t0 = std::time::Instant::now(); loop { let more = reader.next(&mut refs)?; // Moved out of `more` by value below, so named ways cost no `String` clone and@@ -560,6 +611,8 @@ fn materialise_ways( } // Flushed when full, and once more at the end with whatever is left. if batch.len() >= MATERIALISE_BATCH || (done && !batch.is_empty()) {+ t_fill += t0.elapsed();+ let t1 = std::time::Instant::now(); built.clear(); par::install(|| { batch@@ -568,35 +621,34 @@ fn materialise_ways( let line = table.line(refs); // A label layer's ways are centroided to points: a town mapped as an area // is still one label, not a loop. Everything else keeps its geometry.- if is_label(class.layer) {+ let geometry = if is_label(class.layer) { centroid(&line).map(|point| Geometry::Points(vec![point])) } else { way_geometry(&line, class.area)- }+ };+ build_way(class, geometry, region) }) .collect_into_vec(&mut built); });+ t_resolve += t1.elapsed();+ let t2 = std::time::Instant::now();+ let push_before = t_push; for ( (class, name, _, id, lane_count, turn_fwd, turn_bwd, carriageway, building),- geometry,+ built, ) in batch.iter().zip(built.drain(..)) {- match geometry {- Some(geometry) => {- // Region filter: roads, pois and buildings outside the- // bbox are dropped. The geometry is resolved by now, so- // this is a direct touches-box test on the line the- // way produced (a centroided point for labels).- if is_region_filtered(class.layer)- && !geometry_touches(&geometry, region)- {- bar.tick("way(s)");- continue;- }+ // `?` in spill order: the first encode failure in feature order,+ // exactly as inline encoding would report it.+ let tp0 = std::time::Instant::now();+ match built? {+ BuiltWay::Failed => stats.geometry_failed += 1,+ BuiltWay::Dropped => {}+ BuiltWay::Kept(encoded) => { // A building carries its S3DB attributes; a road with lane data carries // those; everything else — and a plain road — goes the plain, named way. if let Some(b) = building {- sink.push_building(class, &geometry, name.as_deref(), *b)?;+ sink.push_building(class, &encoded, name.as_deref(), *b)?; } else if *lane_count > 0 || !turn_fwd.is_empty() || !turn_bwd.is_empty()@@ -604,7 +656,7 @@ fn materialise_ways( { sink.push_road( class,- &geometry,+ &encoded, name.as_deref(), *lane_count, turn_fwd,@@ -612,20 +664,31 @@ fn materialise_ways( *carriageway, )?; } else {- sink.push_named(class, &geometry, name.as_deref(), *id)?;+ sink.push_named(class, &encoded, name.as_deref(), *id)?; } stats.features += 1; }- None => stats.geometry_failed += 1, }+ t_push += tp0.elapsed(); bar.tick("way(s)"); } batch.clear();+ // Drain wall minus the sink pushes: match + stats + tick + drops.+ t_rest += t2.elapsed() - (t_push - push_before);+ t0 = std::time::Instant::now(); } if done { break; } }+ eprintln!(+ " [profile] materialise-ways fill={:.1}s resolve={:.1}s push={:.1}s rest={:.1}s spill={:.2}GB",+ t_fill.as_secs_f64(),+ t_resolve.as_secs_f64(),+ t_push.as_secs_f64(),+ t_rest.as_secs_f64(),+ sink.staged_bytes() as f64 / 1e9+ ); bar.finish("way(s)"); // Nothing reads the ways spill after this: the relations below reach their members through // `members`, which is why that table is kept at all. The file backend's `.tmp` is removed;
scripts/maps/mamaps_build/src/extract_part3.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part3.rs b/scripts/maps/mamaps_build/src/extract_part3.rsindex d2ae35d172..29d2c501ea 100644--- a/scripts/maps/mamaps_build/src/extract_part3.rs+++ b/scripts/maps/mamaps_build/src/extract_part3.rs@@ -2,23 +2,47 @@ /// them fans out across the pool exactly as [`materialise_ways`] does. The sink and the conventions /// grid are fed from these **in relation order** in the serial drain, which is what keeps the /// archive byte-identical: the drain order is the spill order is the archive's.+///+/// Geometry arrives spill-encoded ([`EncodedGeom`](crate::store::EncodedGeom)): the pool walks+/// vertices, the drain appends bytes. The region keep/drop decision is precomputed alongside+/// (pure per-relation work over the resolved shape), so the drain's only vertex touch is+/// `conventions.add`'s grid stamp — which must stay serial and ordered anyway (precedence). enum BuiltRelation { /// A label relation centroided to a point, `None` when it had no locatable members. Label(Option<(f64, f64)>),- /// A border relation's member lines, already filtered to those with two or more points.- Border(Vec<Vec<(f64, f64)>>),+ /// A border relation's member lines, spill-encoded, already filtered to those with two or+ /// more points. Borders are never region-filtered (region shapes are always kept), so no+ /// keep flag rides along. `empty` is the pre-encode shape test (`lines.is_empty()`): an+ /// encoded empty still carries count bytes, so the drain cannot tell it from content by+ /// looking at the bytes — and the old drain counted it `geometry_failed` rather than+ /// pushing an empty record.+ Border { encoded: Result<crate::store::EncodedGeom>, empty: bool }, /// An area relation's stitched rings and the ring stats that stitching produced. The stats are /// per-relation here and summed into [`Stats::rings`] serially — they are four additive counts,- /// so the sum is the same in any order.- Area { polygons: Vec<rings::Polygon>, rings: RingStats },+ /// so the sum is the same in any order. `encoded` is the assembled polygons, spill-ready;+ /// `polygons` travels alongside for `conventions.add`, which needs rings rather than bytes.+ /// `empty` is the pre-encode shape test (`polygons.is_empty()`), for the same reason as+ /// [`BuiltRelation::Border`]'s.+ Area {+ polygons: Vec<rings::Polygon>,+ encoded: Result<crate::store::EncodedGeom>,+ empty: bool,+ keep: bool,+ rings: RingStats,+ }, } /// Build one relation's geometry. Reads only the shared `members` map and the resolved `table`, /// both immutable, so it is safe to call across the pool. See [`BuiltRelation`].+///+/// `region` joins the pool inputs (shared ref): the buildings-area keep/drop test walks every+/// vertex (`polygons_touch`), and the drain must not. Labels keep their O(1) `point_touches`+/// in the drain — no walk to move. fn build_relation( relation: &Relation, members: &MemberWays, table: &NodeLocations,+ region: Option<&osm_ingest::bbox::BBox>, ) -> BuiltRelation { // A `places` relation (a country, a region) is labelled at its centroid: one point, not a // stitched shape. The border itself lives in `boundaries`; this is the name.@@ -42,7 +66,12 @@ fn build_relation( .map(|refs| table.line(refs)) .filter(|line| line.len() >= 2) .collect();- return BuiltRelation::Border(lines);+ // Captured, not `?`: encode counts cannot overflow on real ways, but a+ // pool panic would abort the build where a channelled error fails it in+ // spill order. The drain reports the first failure in relation order.+ let empty = lines.is_empty();+ let encoded = crate::store::EncodedGeom::live(&Geometry::Lines(lines));+ return BuiltRelation::Border { encoded, empty }; } let member_ways: Vec<MemberWay> = relation .members@@ -53,7 +82,23 @@ fn build_relation( .collect(); let mut rings = RingStats::default(); let polygons = rings::assemble(&member_ways, |id| locate(table, id), &mut rings);- BuiltRelation::Area { polygons, rings }+ // Buildings are region-filtered; every other area layer is always kept.+ // Decided here, on the assembled rings, so the drain never walks vertices.+ let keep = relation.class.layer != tilecodec::mamaps::dict::LAYER_BUILDINGS+ || polygons_touch(&polygons, region);+ let geometry = Geometry::Polygons(polygons);+ let empty = match &geometry {+ Geometry::Polygons(polygons) => polygons.is_empty(),+ // Unreachable: built as Polygons two lines up. The match (rather than+ // reading `polygons` before the move) keeps the emptiness test next to+ // the value the drain decides on.+ _ => unreachable!("just built as Polygons"),+ };+ let encoded = crate::store::EncodedGeom::live(&geometry);+ let Geometry::Polygons(polygons) = geometry else {+ unreachable!("just built as Polygons");+ };+ BuiltRelation::Area { polygons, encoded, empty, keep, rings } } /// Materialise relations; returns the driving-side conventions.@@ -92,13 +137,16 @@ fn materialise_relations( par::install(|| { batch .par_iter()- .map(|relation| build_relation(relation, members, table))+ .map(|relation| build_relation(relation, members, table, region)) .collect_into_vec(&mut built); });- for (relation, geometry) in batch.iter().zip(built.drain(..)) {- match geometry {+ for (relation, built) in batch.iter().zip(built.drain(..)) {+ // `?` in spill order: the first encode failure in relation order,+ // exactly as inline encoding would report it.+ match built { BuiltRelation::Label(Some(point)) => { // `poi` labels are region-filtered; `places` always kept.+ // O(1) point test, no vertex walk — stays in the drain. if relation.class.layer == tilecodec::mamaps::dict::LAYER_POI && !point_touches(&point, region) {@@ -107,22 +155,28 @@ fn materialise_relations( } sink.push_named( &relation.class,- &Geometry::Points(vec![point]),+ &crate::store::EncodedGeom::live(&Geometry::Points(vec![point]))?, relation.name.as_deref(), tagged_id(relation.id, ELEMENT_RELATION), )?; stats.features += 1; } BuiltRelation::Label(None) => stats.geometry_failed += 1,- BuiltRelation::Border(lines) => {- if lines.is_empty() {+ BuiltRelation::Border { encoded, empty } => {+ let encoded = encoded?;+ if empty { stats.geometry_failed += 1; } else {- sink.push(&relation.class, &Geometry::Lines(lines))?;+ sink.push_named(+ &relation.class,+ &encoded,+ None,+ tilecodec::mamaps::body::ID_NONE,+ )?; stats.features += 1; } }- BuiltRelation::Area { polygons, rings } => {+ BuiltRelation::Area { polygons, encoded, empty, keep, rings } => { // Accumulated whether or not the stitch produced anything, exactly as the // in-place `&mut stats.rings` did: a failed stitch still counted its unclosed // and orphan rings.@@ -130,14 +184,13 @@ fn materialise_relations( stats.rings.inner_rings += rings.inner_rings; stats.rings.unclosed += rings.unclosed; stats.rings.orphan_inner += rings.orphan_inner;- if polygons.is_empty() {+ let encoded = encoded?;+ if empty { stats.geometry_failed += 1; } else {- // Buildings are region-filtered; every other area- // layer is always kept.- if relation.class.layer == tilecodec::mamaps::dict::LAYER_BUILDINGS- && !polygons_touch(&polygons, region)- {+ // The buildings keep/drop was decided on the pool; every+ // other area layer is always kept.+ if !keep { bar.tick("relation(s)"); continue; }@@ -151,12 +204,7 @@ fn materialise_relations( // A multipolygon building carries its S3DB attributes into the building side // table, just as a building way does. if let Some(building) = relation.building {- sink.push_building(- &relation.class,- &Geometry::Polygons(polygons),- None,- building,- )?;+ sink.push_building(&relation.class, &encoded, None, building)?; } else { // The country's own shape is also what says how its roads are marked. // Stamped before the shape is moved into the sink, from the assembled@@ -164,12 +212,7 @@ fn materialise_relations( if let Some(iso) = &relation.iso { conventions.add(iso, &polygons); }- sink.push_named(- &relation.class,- &Geometry::Polygons(polygons),- None,- id,- )?;+ sink.push_named(&relation.class, &encoded, None, id)?; } stats.features += 1; }@@ -283,80 +326,6 @@ const MAX_NODE_ID: i64 = 48 << 30; /// The ids pass 3 must resolve, collected the way stage A always did. ///-/// One exactly-sized vector, then [`NodeLocations::new`] sorts and dedups it in place. Sized rather-/// than grown into because a `Vec` that doubles its way to 200 M ids holds the old and the new-/// allocation at once across the last realloc -- 1.1 GB plus 2.1 GB, for a length both earlier passes-/// already know.-fn collect_needed_in_memory(- ways_path: &Path,- ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,- members: &MemberWays,- refs_total: usize,- timer: &mut crate::timing::PhaseTimer,-) -> Result<NodeLocations> {- let mut needed: Vec<i64> = Vec::with_capacity(refs_total);- {- let mut reader = open_ways_reader(ways_path, ways_anon)?;- let mut refs: Vec<i64> = Vec::new();- while reader.next(&mut refs)?.is_some() {- needed.extend_from_slice(&refs);- }- }- // A member way that pass 1 also classified already contributed its refs above; `members` adds- // the ones — the great majority, since a multipolygon's rings usually carry no tags of their- // own — that nothing else asked for.- for refs in members.values() {- needed.extend_from_slice(refs);- }- timer.switch("id-index");- NodeLocations::new(needed)-}--/// The same ids, through a bitset over the node id space.-///-/// The vector above is `way_refs + member_refs` entries of eight bytes **with duplicates**, then a-/// sort of all of them. On a north-america extract that is ~19 GB; on a planet one it projects to-/// ~96 GB and a sort of 12 G elements, which is the second of the two things that stopped a planet-/// build before anything else got the chance to.-///-/// A bit per node id costs `max_id / 8` and **does not scale with the extract**: OSM node ids are-/// assigned monotonically and top out near 13 G, so this is at most ~1.7 GB for any extract, forever.-/// Streaming the refs into it and then walking it low to high yields sorted unique ids directly ---/// which removes the vector *and* the sort in one pass, with no extra I/O.-///-/// Not an external merge sort of the ref stream. That is the general answer and needs no assumption-/// about the ids, and it costs ~96 GB written and ~96 GB read at planet scale to compute what this-/// gets in one pass. The bound that makes the bitset safe -- monotonic, bounded ids -- is a property-/// of OSM's data rather than a hope about it, and [`MAX_NODE_ID`] is where that property is enforced.-fn collect_needed_by_bitset(- ways_path: &Path,- ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,- members: &MemberWays,- max_ref: i64,- timer: &mut crate::timing::PhaseTimer,-) -> Result<NodeLocations> {- let mut bits = NeededBits::new(max_ref)?;- {- let mut reader = open_ways_reader(ways_path, ways_anon)?;- let mut refs: Vec<i64> = Vec::new();- while reader.next(&mut refs)?.is_some() {- for &id in &refs {- bits.set(id)?;- }- }- }- for refs in members.values() {- for &id in refs {- bits.set(id)?;- }- }- timer.switch("id-index");- // The bitset's words move into the rank index directly (`from_bitset`), not through `ids()`:- // walking them out as ids and re-setting them would hold two ~1.5 GB words arrays at once.- let (words, count) = bits.into_words();- NodeLocations::from_bitset(words, count)-}- /// One bit per node id in `0..=max_id`. struct NeededBits { words: Vec<u64>,@@ -379,6 +348,42 @@ impl NeededBits { Ok(NeededBits { words: vec![0u64; bits.div_ceil(64)], bits, count: 0 }) } + /// An unsized bitset that grows as larger ids arrive, for fusing collection+ /// into pass 1's drain: the maximum is not known until the last way is+ /// pushed, so the words extend on demand instead. Same guards as [`new`];+ /// the final size is identical to a sized bitset over the same ids.+ fn new_growable() -> NeededBits {+ NeededBits { words: Vec::new(), bits: 0, count: 0 }+ }++ /// Set a bit, growing the words when the id lands past them.+ ///+ /// Refused rather than grown past [`MAX_NODE_ID`], like [`new`]: an id out+ /// there is not an OSM node and growing for it would size the bitset for+ /// one corrupt ref.+ fn set_growable(&mut self, id: i64) -> Result<()> {+ if id < 0 {+ return err(format!("node ref {id} is negative"));+ }+ if id > MAX_NODE_ID {+ return err(format!(+ "node ref {id} is past the {MAX_NODE_ID} this build will size a bitset for"+ ));+ }+ let at = id as usize;+ if at >= self.bits {+ self.bits = at + 1;+ self.words.resize(self.bits.div_ceil(64), 0);+ }+ let word = &mut self.words[at / 64];+ let bit = 1u64 << (at % 64);+ if *word & bit == 0 {+ *word |= bit;+ self.count += 1;+ }+ Ok(())+ }+ fn set(&mut self, id: i64) -> Result<()> { // A negative ref is not a node this planet has. Refused rather than skipped: it means the // spill or the PBF is not what it claims, and skipping would show as a way with a gap in it.
scripts/maps/mamaps_build/src/extract_part4.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part4.rs b/scripts/maps/mamaps_build/src/extract_part4.rsindex ccd0481226..bec0c0d154 100644--- a/scripts/maps/mamaps_build/src/extract_part4.rs+++ b/scripts/maps/mamaps_build/src/extract_part4.rs@@ -199,9 +199,11 @@ mod tests { assert!(bits.set(100).is_ok()); } - /// End to end over a real ways spill: the two collectors must agree on the set they hand pass 3.+ /// End to end over a real ways spill: the fused growable bitset must hand+ /// pass 3 the same set the old re-scan collectors did — every asked-for id+ /// and nothing between them that was never asked for. #[test]- fn the_two_ref_collectors_agree_on_the_same_input() {+ fn the_fused_bitset_collects_what_the_spill_holds() { let path = std::env::temp_dir().join(format!( "mamaps_refcollect_{}_{:?}.ways.tmp", std::process::id(),@@ -214,50 +216,41 @@ mod tests { ); let mut sink = WaySink::create_anon(&path).expect("create the ways spill"); // Ascending way ids, as pass 1 produces; overlapping refs, as real ways have.+ // Bits are set as each way pushes, the way the pass-1 drain does it.+ let mut bits = NeededBits::new_growable(); for way in 0..64i64 { let refs: Vec<i64> = (0..8).map(|i| way * 5 + i).collect();+ for &id in &refs {+ bits.set_growable(id).expect("set a bit");+ } sink.push(way + 1, &class, &refs, None, 0, &[], &[], Carriageway::default(), None) .expect("push"); } let (counts, store) = sink.finish_anon().expect("finish");+ let _ = store; let mut member_map: HashMap<i64, Vec<i64>> = HashMap::new(); // One member whose refs overlap the spill's, and one that is entirely new. member_map.insert(7, vec![30, 31, 32, 30]); member_map.insert(9, vec![10_000, 9_999, 10_000]); let members = MemberWays::from_map(member_map);- let member_refs: usize = members.values().map(|refs| refs.len()).sum();- let max_ref = members- .values()- .flat_map(|refs| refs.iter().copied())- .fold(counts.max_ref, i64::max);-- // A throwaway clock: the collectors take the run's timer, and this test has- // no run. Dropped without `finish`, so no `TIMING` line reaches test output.- let mut timer = crate::timing::PhaseTimer::start("tiles");- let anon = Some(std::sync::Arc::new(store));- let in_memory =- collect_needed_in_memory(&path, &anon, &members, counts.refs as usize + member_refs, &mut timer)- .expect("the in-memory path");- let by_bitset =- collect_needed_by_bitset(&path, &anon, &members, max_ref, &mut timer).expect("the bitset path");+ for refs in members.values() {+ for &id in refs {+ bits.set_growable(id).expect("set a member bit");+ }+ } - assert_eq!(- in_memory.len(),- by_bitset.len(),- "the two paths disagree on how many distinct nodes are needed",- );- // And the same ids, not merely the same count: both tables must answer for every ref and- // for nothing between them that was never asked for.+ // The same ids, not merely the same count: the table must answer for+ // every ref and for nothing between them that was never asked for.+ let count = bits.len();+ let (words, _) = bits.into_words();+ let table = NodeLocations::from_bitset(words, count).expect("build the table");+ let _ = counts; for id in [0i64, 1, 30, 31, 32, 319, 9_999, 10_000] {- assert_eq!(- in_memory.contains(id),- by_bitset.contains(id),- "the two paths disagree about node {id}",- );+ assert!(table.contains(id), "node {id} is missing"); }- assert!(in_memory.contains(10_000), "a member-only ref is missing");- assert!(!in_memory.contains(5_000), "an id nothing asked for is present");+ assert!(table.contains(10_000), "a member-only ref is missing");+ assert!(!table.contains(5_000), "an id nothing asked for is present"); let _ = std::fs::remove_file(&path); }
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 c712b7ae44..0578524f47 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part2.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part2.rs@@ -269,7 +269,7 @@ pub fn stream_junctions(dir: &Path, conventions: &Conventions, sink: &mut Sink) }); for node_geoms in built.drain(..) { for points in node_geoms {- sink.push(&class, &Geometry::Lines(vec![points]))?;+ sink.push(&class, &crate::store::EncodedGeom::live(&Geometry::Lines(vec![points]))?)?; emitted += 1; } bar.tick("node(s)");
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 62da4ecaf2..0f003d8630 100644--- a/scripts/maps/mamaps_build/src/schema/landtype.rs+++ b/scripts/maps/mamaps_build/src/schema/landtype.rs@@ -364,7 +364,7 @@ pub fn stream_prepared( // 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) {- sink.push(&class, &Geometry::Polygons(vec![polygon]))?;+ sink.push(&class, &crate::store::EncodedGeom::live(&Geometry::Polygons(vec![polygon]))?)?; written += 1; } }@@ -403,7 +403,7 @@ pub fn stream_prepared( if polygon.is_empty() || !meets(&polygon, bbox) { continue; }- sink.push(&class, &Geometry::Polygons(vec![polygon]))?;+ sink.push(&class, &crate::store::EncodedGeom::live(&Geometry::Polygons(vec![polygon]))?)?; written += 1; } }
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 19abd8317b..abc6e2d931 100644--- a/scripts/maps/mamaps_build/src/schema/traffic.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -553,7 +553,7 @@ pub fn stream_graph(dir: &Path, sink: &mut Sink) -> Result<u64> { (a_lon as f64 * 1e-7, a_lat as f64 * 1e-7), (b_lon as f64 * 1e-7, b_lat as f64 * 1e-7), ]];- sink.push_named(&class, &Geometry::Lines(line), None, component_id)?;+ sink.push_named(&class, &crate::store::EncodedGeom::live(&Geometry::Lines(line))?, None, component_id)?; emitted += 1; } }
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 03207c7638..13958cdbe2 100644--- a/scripts/maps/mamaps_build/src/schema/transit.rs+++ b/scripts/maps/mamaps_build/src/schema/transit.rs@@ -150,7 +150,7 @@ pub fn stream_routes( skipped += 1; continue; }- sink.push_transit(&class, &Geometry::Lines(vec![line]), color, ordinal, lanes, taper)?;+ sink.push_transit(&class, &crate::store::EncodedGeom::live(&Geometry::Lines(vec![line]))?, color, ordinal, lanes, taper)?; written += 1; } }
scripts/maps/mamaps_build/src/store.rs
diff --git a/scripts/maps/mamaps_build/src/store.rs b/scripts/maps/mamaps_build/src/store.rsindex c49186f380..3eeaf960f9 100644--- a/scripts/maps/mamaps_build/src/store.rs+++ b/scripts/maps/mamaps_build/src/store.rs@@ -55,10 +55,11 @@ use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; use osm_ingest::proto::{err, zigzag, Error, Result};-use tile_build::geom::Geometry;+use tile_build::geom::{bounds as geom_bounds, Geometry, Rect}; use tile_build::mvt::Value; use tile_build::spill::{- NormalizedChunks, NormalizedReader, NormalizedWriter, NORM_CHUNK_FEATURES,+ encode_geometry, GeomKind, NormalizedChunks, NormalizedReader, NormalizedWriter,+ NORM_CHUNK_FEATURES, }; use crate::extract::Feature;@@ -241,6 +242,69 @@ fn unpack(bits: u64) -> Class { } } +/// A geometry encoded for the feature spill, plus the two facts the spill+/// derives from it.+///+/// Built on the pool by the materialise drains (`EncodedGeom::live` is pure:+/// [`encode_geometry`](tile_build::spill::encode_geometry),+/// [`GeomKind::of`](tile_build::spill::GeomKind::of), [`bounds`](tile_build::geom::bounds)+/// and the e7 box below touch nothing shared), appended in order by the serial+/// drain. Byte-identical to encoding in the sink: all four are pure functions+/// of the same geometry.+pub struct EncodedGeom {+ kind: GeomKind,+ bytes: Vec<u8>,+ bounds: Option<Rect>,+ ebbx: Option<(i32, i32, i32, i32)>,+}++impl EncodedGeom {+ /// Encode a live geometry: what the sink always did inline, exposed so+ /// callers with no pool pass the same shape the pool-built path does.+ /// One path, two speeds.+ pub fn live(geometry: &Geometry) -> Result<EncodedGeom> {+ let mut bytes = Vec::new();+ encode_geometry(geometry, &mut bytes)+ .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+ Ok(EncodedGeom {+ kind: GeomKind::of(geometry),+ bytes,+ bounds: geom_bounds(geometry),+ ebbx: ebbx_of(geometry),+ })+ }+}++/// The sink bbox's e7 box for one geometry: min/max over ALL vertices with+/// [`Sink::grow`]'s exact conversion.+///+/// `bounds` above skips non-finite vertices (matching+/// [`tile_build::geom::bounds`]); this must not: the old per-vertex walk+/// folded `(NaN * 1e7) as i32` — which saturates to 0 — so a NaN vertex+/// contributed 0 to the box. Reproducing the walk exactly (rather than+/// converting `bounds`' corners) keeps the box identical even where a+/// shapefile-derived coordinate misbehaves. `None` only when the geometry+/// holds no vertices at all, in which case the old walk visited nothing and+/// the box was unchanged.+fn ebbx_of(geometry: &Geometry) -> Option<(i32, i32, i32, i32)> {+ let mut acc: Option<(i32, i32, i32, i32)> = None;+ let mut visit = |&(lon, lat): &(f64, f64)| {+ let (x, y) = ((lon * 1e7) as i32, (lat * 1e7) as i32);+ acc = Some(match acc {+ None => (x, y, x, y),+ Some(b) => (b.0.min(x), b.1.min(y), b.2.max(x), b.3.max(y)),+ });+ };+ match geometry {+ Geometry::Points(points) => points.iter().for_each(&mut visit),+ Geometry::Lines(lines) => lines.iter().flatten().for_each(&mut visit),+ Geometry::Polygons(polygons) => {+ polygons.iter().flatten().flatten().for_each(&mut visit)+ }+ }+ acc+}+ /// Accumulates features into a file, tracking the bounding box as it goes. /// /// The bbox is computed here rather than in a pass of its own, because a pass of its own would be a
scripts/maps/mamaps_build/src/store_part1.rs
diff --git a/scripts/maps/mamaps_build/src/store_part1.rs b/scripts/maps/mamaps_build/src/store_part1.rsindex d6ebf129e4..900bae2d88 100644--- a/scripts/maps/mamaps_build/src/store_part1.rs+++ b/scripts/maps/mamaps_build/src/store_part1.rs@@ -34,10 +34,15 @@ impl Sink { }) } - pub fn push(&mut self, class: &Class, geometry: &Geometry) -> Result<()> {+ pub fn push(&mut self, class: &Class, geometry: &EncodedGeom) -> Result<()> { self.push_named(class, geometry, None, tilecodec::mamaps::body::ID_NONE) } + /// TEMP-PROFILE: compressed spill bytes staged so far. Removed with the probes.+ pub fn staged_bytes(&self) -> u64 {+ self.writer.staged_bytes()+ }+ /// Push a transit line: like [`Sink::push`], plus the route colour that becomes the body's /// `transit_color` and the lane inputs that become its `transit_ordinal`, `transit_lanes` and /// `transit_taper`. A zero colour is refused, not written as absent — zero means "no colour"@@ -45,7 +50,7 @@ impl Sink { pub fn push_transit( &mut self, class: &Class,- geometry: &Geometry,+ geometry: &EncodedGeom, color: u32, ordinal: u8, lanes: u8,@@ -76,7 +81,7 @@ impl Sink { pub fn push_named( &mut self, class: &Class,- geometry: &Geometry,+ geometry: &EncodedGeom, name: Option<&str>, id: u64, ) -> Result<()> {@@ -106,7 +111,7 @@ impl Sink { pub fn push_road( &mut self, class: &Class,- geometry: &Geometry,+ geometry: &EncodedGeom, name: Option<&str>, lane_count: u8, turn_fwd: &[u16],@@ -152,7 +157,7 @@ impl Sink { pub fn push_building( &mut self, class: &Class,- geometry: &Geometry,+ geometry: &EncodedGeom, name: Option<&str>, attrs: BuildingAttrs, ) -> Result<()> {@@ -168,9 +173,9 @@ impl Sink { self.write_record(class, geometry) } - fn write_record(&mut self, class: &Class, geometry: &Geometry) -> Result<()> {+ fn write_record(&mut self, class: &Class, geometry: &EncodedGeom) -> Result<()> { self.writer- .push(geometry, &self.props)+ .push_preencoded(geometry.kind, &geometry.bytes, geometry.bounds, &self.props) .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; self.filling = self.filling.min(class.min_zoom); self.count += 1;@@ -180,10 +185,30 @@ impl Sink { self.chunk_mins.push(self.filling); self.filling = u8::MAX; }- self.grow(geometry);+ self.grow_bounds(geometry.ebbx); Ok(()) } + /// Extend the bounding box by one geometry's precomputed e7 box.+ ///+ /// [`Sink::grow`] walked vertices; the encoder already did on the pool (see+ /// [`ebbx_of`](crate::store::ebbx_of)). `None` (no vertices at all)+ /// contributes nothing — identical to the walk visiting nothing.+ fn grow_bounds(&mut self, ebbx: Option<(i32, i32, i32, i32)>) {+ let Some((x0, y0, x1, y1)) = ebbx else {+ return;+ };+ match &mut self.bbox {+ None => self.bbox = Some((x0, y0, x1, y1)),+ Some(s) => {+ s.0 = s.0.min(x0);+ s.1 = s.1.min(y0);+ s.2 = s.2.max(x1);+ s.3 = s.3.max(y1);+ }+ }+ }+ /// Extend the bounding box by a geometry, in degrees times 1e7. fn grow(&mut self, geometry: &Geometry) { let mut visit = |&(lon, lat): &(f64, f64)| {
scripts/maps/mamaps_build/src/store_part2.rs
diff --git a/scripts/maps/mamaps_build/src/store_part2.rs b/scripts/maps/mamaps_build/src/store_part2.rsindex 35c19eeb51..bcf23c28da 100644--- a/scripts/maps/mamaps_build/src/store_part2.rs+++ b/scripts/maps/mamaps_build/src/store_part2.rs@@ -176,10 +176,13 @@ impl Store { )); let mut sink = Sink::create(&path)?; for feature in features {+ // Test-only path: encode inline (the pool-built path is exercised+ // by the materialise drains, not here).+ let encoded = EncodedGeom::live(&feature.geometry)?; if feature.transit_color != 0 { sink.push_transit( &feature.class,- &feature.geometry,+ &encoded, feature.transit_color, feature.transit_ordinal, feature.transit_lanes,@@ -188,7 +191,7 @@ impl Store { } else if let Some(attrs) = feature.building { sink.push_building( &feature.class,- &feature.geometry,+ &encoded, feature.name.as_deref(), attrs, )?;@@ -199,7 +202,7 @@ impl Store { { sink.push_road( &feature.class,- &feature.geometry,+ &encoded, feature.name.as_deref(), feature.lane_count, &feature.turn_fwd,@@ -207,7 +210,7 @@ impl Store { feature.carriageway, )?; } else {- sink.push_named(&feature.class, &feature.geometry, feature.name.as_deref(), feature.id)?;+ sink.push_named(&feature.class, &encoded, feature.name.as_deref(), feature.id)?; } } sink.finish(&path)
scripts/maps/mamaps_build/src/store_part5.rs
diff --git a/scripts/maps/mamaps_build/src/store_part5.rs b/scripts/maps/mamaps_build/src/store_part5.rsindex 837a98ff2b..5d3126b833 100644--- a/scripts/maps/mamaps_build/src/store_part5.rs+++ b/scripts/maps/mamaps_build/src/store_part5.rs@@ -14,7 +14,7 @@ mod tests { let kind = i.max(1); let class = Class::line(dict::LAYER_ROADS, kind, min_zoom); let line = vec![(-120.0 + i as f64 * 0.001, 35.0), (-119.9, 35.1)];- sink.push(&class, &Geometry::Lines(vec![line])).expect("push");+ sink.push(&class, &EncodedGeom::live(&Geometry::Lines(vec![line])).expect("encode")).expect("push"); for z in min_zoom as usize..15 { expected_by_zoom[z].push(kind); }@@ -148,7 +148,7 @@ mod tests { let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 0); for i in 0..count { let (x, y) = at(i);- sink.push(&class, &Geometry::Lines(vec![vec![(x, y), (x, y + 0.0001)]]))+ sink.push(&class, &EncodedGeom::live(&Geometry::Lines(vec![vec![(x, y), (x, y + 0.0001)]])).expect("encode")) .expect("push"); } let store = sink.finish(&path).expect("finish");@@ -190,8 +190,8 @@ mod tests { ]]; let lake = Class::area(dict::LAYER_LANDTYPE, schema::kind("lake"), 6); let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);- sink.push(&lake, &Geometry::Polygons(vec![square.clone()])).expect("push");- sink.push(&road, &Geometry::Lines(vec![vec![(-120.0, 35.0), (-119.5, 35.5)]]))+ sink.push(&lake, &EncodedGeom::live(&Geometry::Polygons(vec![square.clone()])).expect("encode")).expect("push");+ sink.push(&road, &EncodedGeom::live(&Geometry::Lines(vec![vec![(-120.0, 35.0), (-119.5, 35.5)]])).expect("encode")) .expect("push"); let store = sink.finish(&path).expect("finish");
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex 25be47f1f1..3719505b69 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -287,6 +287,23 @@ fn adopt_thread_budget() { }); } +/// TEMP-PROFILE: reader-thread wall stash for the mapprofile line. The+/// reader runs on its own thread inside `map_zoom`'s scope; the tally fold+/// (which prints) runs after the scope joins. A process-wide cell carries+/// the wall across. Removed with the probes.+static READER_WALL_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++/// TEMP-PROFILE: stash the reader wall (millis). Removed with the probes.+pub(crate) fn stash_reader_wall(_z: u8, wall: std::time::Duration) {+ READER_WALL_MS.store(wall.as_millis() as u64, std::sync::atomic::Ordering::Relaxed);+}++/// TEMP-PROFILE: take the stashed reader wall as a Duration. Removed with+/// the probes.+pub(crate) fn take_reader_wall() -> std::time::Duration {+ std::time::Duration::from_millis(READER_WALL_MS.load(std::sync::atomic::Ordering::Relaxed))+}+ /// Per-zoom counts for the build report. #[derive(Debug, Default, Clone, Copy)] pub struct ZoomStats {@@ -426,6 +443,20 @@ struct Tally { features: u64, points: u64, dropped: u64,+ // TEMP-PROFILE: per-stage map walls, summed across chunks (durations+ // add; order irrelevant). Removed with the probes. NOT Copy (Duration+ // is, but the explicit add below keeps the accounting visible).+ profile: TallyProfile,+}++/// TEMP-PROFILE: per-stage map-phase walls carried in the tally. Removed+/// with the probes.+#[derive(Debug, Default, Clone, Copy)]+struct TallyProfile {+ project: std::time::Duration,+ annotate: std::time::Duration,+ filter: std::time::Duration,+ subdiv: std::time::Duration, } impl Tally {@@ -433,6 +464,24 @@ impl Tally { self.features += other.features; self.points += other.points; self.dropped += other.dropped;+ self.profile.project += other.profile.project;+ self.profile.annotate += other.profile.annotate;+ self.profile.filter += other.profile.filter;+ self.profile.subdiv += other.profile.subdiv;+ }++ /// TEMP-PROFILE: attach this chunk's stage walls. Removed with the probes.+ fn profile_add(+ &mut self,+ project: std::time::Duration,+ annotate: std::time::Duration,+ filter: std::time::Duration,+ subdiv: std::time::Duration,+ ) {+ self.profile.project += project;+ self.profile.annotate += annotate;+ self.profile.filter += filter;+ self.profile.subdiv += subdiv; } }
scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex 423a96c183..d6040ac99e 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -123,19 +123,148 @@ fn tile_zooms( // remembered. A `BTreeMap` per chunk and a heap across them is the same guarantee the // single-threaded `BTreeMap` gave; the maps now live on disk and the guarantee does not // change, because a chunk's bytes are written in its key order and read back in file order.- let mut merged = merge(&chunks, &spill);- // Merge, encode and append have no total to count against -- the tile count is only known once- // the merge has produced it -- so the merge bar counts tiles merged and the encode line below- // counts tiles written. Two numbers that converge at the end of the zoom. Still the difference- // between forty silent minutes and a number that moves: the merge is single-threaded and is- // where a zoom's wall clock goes. Count shape (no percent: the total is unknowable until the- // merge ends), with elapsed so a stalled merge is visible.- let zoom_start = std::time::Instant::now();- let mut merged_tiles = 0usize;- let mut merge_shown = 0usize;- let mut written = 0usize;- let mut shown = 0usize;- loop {+ //+ // Range-parallel merge when the zoom repays planning: one worker k-way merges each+ // cost-balanced tile range (see `tiler_part3::merge_parallel`), drained in order by the+ // same consume loop below — sequence-identical to serial, so batches, prune and append+ // are untouched. Small zooms stay serial: planning costs more than it saves there. So do+ // z0–z3, whose tile spans (1–64) don't divide by the 256 cost buckets — the bucket table+ // can't invert those edges exactly (see `parallel_merge_supported`).+ //+ // The choice is `merge_gate` below, hardcoded: no environment override.+ // Operator control arrives through `--threads`/`MAPS_THREADS` (which sizes the+ // worker count) exactly like every other parallel stage in this tree.+ let merge_parallel = merge_gate(&chunks, z);+ if merge_parallel {+ let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS);+ // One worker owns the whole tile space on a one-thread box, which is+ // the serial sequence by construction — correctness never depends on+ // the count, only speed does.+ let merge_workers = merge_workers.max(1);+ // Timed as its own subphase: the planning scan is a serial+ // skip-walk over every chunk, and at z14 it is large enough to+ // matter against the merge it parallelises.+ timer.switch("merge-plan");+ let planning = std::time::Instant::now();+ let plan = crate::tiler::plan_ranges(&chunks, &spill, z, merge_workers)?;+ stats.merge_ms += planning.elapsed().as_millis() as u64;+ // One line per zoom on the parallel path: per-range cost estimates+ // from the planning histogram. The coordinator drains ranges in+ // order, so the slowest range sets the merge wall — a lopsided+ // split here names the balancer, not the workers, as the limit.+ // `hot` is the costliest single tile: ranges assign whole tiles,+ // so the wall cannot go below it however the ranges split.+ eprintln!(+ " [merge] z{z}: {} range(s), cost {:?}, hot tile {} at {}, entries {}",+ merge_workers,+ plan.range_cost,+ plan.hot_tile,+ plan.hot_cost,+ plan.remaining+ .iter()+ .map(|row| row.iter().sum::<u64>())+ .sum::<u64>(),+ );+ std::thread::scope(|s| -> Result<()> {+ let mut receivers = Vec::with_capacity(merge_workers);+ // Shared refs are `Copy`: each spawned closure gets its own+ // copy rather than moving `chunks`/`spill` on first use.+ let chunks_ref = &chunks;+ let spill_ref = &spill;+ for r in 0..merge_workers {+ let (tx, rx) =+ std::sync::mpsc::sync_channel(crate::tiler::RANGE_QUEUE_BOUND);+ receivers.push(rx);+ let range_plan = &plan;+ s.spawn(move || {+ crate::tiler::merge_range_into(+ chunks_ref,+ spill_ref,+ range_plan,+ r,+ tx,+ );+ });+ }+ let mut stream =+ crate::tiler::MergeStream::Parallel(crate::tiler::ParallelMerge::new(+ receivers,+ ));+ consume_merged(+ &mut stream,+ &mut stats,+ z,+ timer,+ &settings.dem,+ store.conventions(),+ &settings.region_links,+ writer,+ )?;+ Ok(())+ })?;+ } else {+ let mut stream = crate::tiler::MergeStream::Serial(merge(&chunks, &spill));+ consume_merged(+ &mut stream,+ &mut stats,+ z,+ timer,+ &settings.dem,+ store.conventions(),+ &settings.region_links,+ writer,+ )?;+ }+ // Reserved, written, on disk and read back must agree. A chunk that quietly lost entries+ // would produce an archive with holes in it and nothing downstream could tell.+ spill.check_books()?;+ per_zoom.push(stats);+ }++ Ok(per_zoom)+}++/// The entry gate for the range-parallel merge: big supported zoom on a+/// multi-thread box.+///+/// Split out so the call site reads as intent rather than inline conditions.+/// z0–z3 stay serial however threaded: they can't invert their bucket edges+/// exactly, so they have one path and no divergence to compare.+fn merge_gate(chunks: &[ChunkRef], z: u8) -> bool {+ let total_entries: u64 = chunks.iter().map(|c| c.entries).sum();+ let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS);+ total_entries >= crate::tiler::PARALLEL_MERGE_MIN_ENTRIES+ && merge_workers > 1+ && crate::tiler::parallel_merge_supported(z)+}++/// Merge → encode → prune → append for one zoom, over any tile-ordered merge+/// iterator.+///+/// Extracted whole from the zoom loop so serial and range-parallel merges share+/// it: batches are contiguous pulls in merge order, `encode_batch` preserves+/// tile order, and prune/append see the identical sequence either way — which+/// is why the archive does not move between the two paths.+#[allow(clippy::too_many_arguments)]+fn consume_merged(+ merged: &mut impl Iterator<Item = Result<(u64, Vec<ChunkEntry>)>>,+ stats: &mut ZoomStats,+ z: u8,+ timer: &mut crate::timing::PhaseTimer,+ dem: &crate::dem::Dem,+ conventions: &crate::schema::boundaries::Conventions,+ region_links: &std::collections::HashMap<u64, u64>,+ writer: &mut tilecodec::mamaps::write::StreamWriter,+) -> Result<()> {+ // Merge, encode and append have no total to count against -- the tile count is only known once+ // the merge has produced it -- so the merge bar counts tiles merged and the encode line below+ // counts tiles written.+ let zoom_start = std::time::Instant::now();+ let mut merged_tiles = 0usize;+ let mut merge_shown = 0usize;+ let mut written = 0usize;+ let mut shown = 0usize;+ loop { // Cost-batched rather than count-batched: z14 has tiles whose merged geometry is tens // of MB (a dense city tile's whole layer set) beside rural tiles worth bytes. A // fixed `batch_len()` of those holds ~GB of merged tiles plus their encoded copies@@ -160,7 +289,7 @@ fn tile_zooms( // `collect` into a `Result`, because a truncated scratch file must fail the build rather // than end the zoom early and publish a short archive. let batch: Vec<(u64, Vec<ChunkEntry>)> =- merge_batch(&mut merged, par::batch_len())?;+ merge_batch(&mut *merged, par::batch_len())?; stats.merge_ms += merging.elapsed().as_millis() as u64; if batch.is_empty() { break;@@ -180,7 +309,7 @@ fn tile_zooms( // Per-zoom `encode`: repeat visits merge into one total at `finish`. timer.switch("encode"); let encoding = std::time::Instant::now();- let mut done = encode_batch(batch, &settings.dem, store.conventions(), &settings.region_links)?;+ let mut done = encode_batch(batch, dem, conventions, region_links)?; stats.encode_ms += encoding.elapsed().as_millis() as u64; // Phase B: prune barren subtrees. A tile whose four children all came back // empty (`None` — genuinely featureless, or full-bleed water background) is@@ -232,14 +361,7 @@ fn tile_zooms( tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), ); }- // Reserved, written, on disk and read back must agree. A chunk that quietly lost entries- // would produce an archive with holes in it and nothing downstream could tell.- drop(merged);- spill.check_books()?;- per_zoom.push(stats);- }-- Ok(per_zoom)+ Ok(()) } /// One merge pull, capped by merged-geometry cost rather than by tile count.@@ -256,7 +378,7 @@ fn tile_zooms( /// split across a batch boundary — and only the first case prunes, which keeps the archive /// independent of where the batcher cut. fn merge_batch(- merged: &mut Merged<'_>,+ merged: &mut impl Iterator<Item = Result<(u64, Vec<ChunkEntry>)>>, max_tiles: usize, ) -> Result<Vec<(u64, Vec<ChunkEntry>)>> { let mut batch: Vec<(u64, Vec<ChunkEntry>)> = Vec::new();@@ -435,9 +557,17 @@ fn map_zoom( let failed = std::sync::atomic::AtomicBool::new(false); std::thread::scope(|scope| -> Result<()> {+ // TEMP-PROFILE: reader wall (feed rate). The reader thread returns+ // its wall clock alongside its result; compared against the zoom's+ // map wall it answers feed-bound vs worker-bound. Removed with the+ // probes.+ let reader_start = std::time::Instant::now(); let reader = std::thread::Builder::new() .name("mamaps-read".to_string())- .spawn_scoped(scope, move || read_chunks(store, z, send))+ .spawn_scoped(scope, move || {+ let r = read_chunks(store, z, send);+ (r, reader_start.elapsed())+ }) .map_err(|e| tile_build::proto::Error(format!("cannot start the store reader: {e}")))?; // One worker runs on this thread whatever happens, so a machine that will not give us@@ -464,9 +594,13 @@ fn map_zoom( tile_build::proto::Error("a tiling thread panicked".to_string()) })?; }- reader.join().map_err(|_| {+ let (reader_result, reader_wall) = reader.join().map_err(|_| { tile_build::proto::Error("the store reader thread panicked".to_string())- })?+ })?;+ // TEMP-PROFILE: stash the reader wall where the tally fold prints+ // it. Removed with the probes.+ crate::tiler::stash_reader_wall(z, reader_wall);+ reader_result })?; if failed.load(Ordering::Relaxed) {@@ -485,6 +619,20 @@ fn map_zoom( for (_, _, chunk_tally) in &chunks { tally.add(*chunk_tally); }+ // TEMP-PROFILE: per-stage map walls, summed across chunks (CPU time, so+ // the sum exceeds wall on 64 threads — ratios, not walls, are the read),+ // plus the reader thread's own wall (feed rate) and the map wall implied+ // by the caller. `reader_ms` vs the zoom's `map_ms` answers feed-bound+ // vs worker-bound: a reader wall near the map wall means workers starved.+ // Removed with the probes.+ eprintln!(+ " [mapprofile] z{z}: project={:.1}s annotate={:.1}s filter={:.1}s subdiv={:.1}s reader={:.1}s",+ tally.profile.project.as_secs_f64(),+ tally.profile.annotate.as_secs_f64(),+ tally.profile.filter.as_secs_f64(),+ tally.profile.subdiv.as_secs_f64(),+ crate::tiler::take_reader_wall().as_secs_f64()+ ); Ok((chunks.into_iter().map(|(_, at, _)| at).collect(), tally)) }
scripts/maps/mamaps_build/src/tiler_part2.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part2.rs b/scripts/maps/mamaps_build/src/tiler_part2.rsindex 9724a8db1d..3987a6b331 100644--- a/scripts/maps/mamaps_build/src/tiler_part2.rs+++ b/scripts/maps/mamaps_build/src/tiler_part2.rs@@ -343,6 +343,13 @@ fn tile_chunk( ) -> (Chunk, Tally) { let mut tiles: Chunk = BTreeMap::new(); let mut tally = Tally::default();+ // TEMP-PROFILE: per-stage walls inside the map phase. Thread-local (each+ // worker runs its own `tile_chunk`), summed into the process log at+ // `map_zoom` end. Removed once the hotspot is measured (CA run).+ let mut t_project = std::time::Duration::ZERO;+ let mut t_annotate = std::time::Duration::ZERO;+ let mut t_filter = std::time::Duration::ZERO;+ let mut t_subdiv = std::time::Duration::ZERO; for feature in features { // Country label gating: the score (footprint × headcount) decided in stage A // (see `extract_fallback::country_zoom`); this is where it is enforced. A@@ -363,15 +370,21 @@ fn tile_chunk( tally.dropped += 1; continue; }+ let t = std::time::Instant::now(); let mut projected = geom::project_geometry(&feature.geometry, z, EXTENT);+ t_project += t.elapsed(); // Significance first, then filter: computed on the whole geometry so a vertex's fate // does not depend on which tile it lands in.+ let t = std::time::Instant::now(); simplify::annotate(&mut projected);+ t_annotate += t.elapsed(); // Buildings live only at z14, where the policy tolerance is 0.0; the floor below // keeps only collinear midpoints and sub-pixel jaggies — see `tolerance_for_layer`. // Roads take the per-feature floor at z14 (washable classes only). let layer_tolerance = tolerance_for_feature(feature, z, tolerance);+ let t = std::time::Instant::now(); let thinned = simplify::filter(&projected, layer_tolerance);+ t_filter += t.elapsed(); // Near-rectangles digitised by hand gain a cheap varint delta when their edges snap // exactly axis-aligned — see `snap_building_rings`. Survivors only, so the measured // significance above is never stale; a pure function of the feature, so the archive@@ -386,6 +399,7 @@ fn tile_chunk( tally.dropped += 1; continue; }+ let t = std::time::Instant::now(); subdivide::subdivide(&thinned, z, EXTENT, buffer, &mut |tx, ty, clipped| { // The descent prunes on a part surviving at all; this is the stricter test that // decides whether a tile is worth writing, and it stays exactly where it was.@@ -400,7 +414,11 @@ fn tile_chunk( tally.features += added.0; tally.points += added.1; });+ t_subdiv += t.elapsed(); }+ // TEMP-PROFILE: summed per worker; see `map_zoom` for the fold.+ // Removed with the probes.+ tally.profile_add(t_project, t_annotate, t_filter, t_subdiv); (tiles, tally) }
scripts/maps/mamaps_build/src/tiler_part3.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part3.rs b/scripts/maps/mamaps_build/src/tiler_part3.rsindex 7943efbe2f..ec840e8336 100644--- a/scripts/maps/mamaps_build/src/tiler_part3.rs+++ b/scripts/maps/mamaps_build/src/tiler_part3.rs@@ -239,3 +239,731 @@ pub fn widest_layers() -> Vec<(u8, u64)> { /// Folded by the caller in `tile_id` order rather than accumulated across workers, so the counters /// need no atomics and a million tiles do not contend on three cache lines. type Encoded = (u64, Option<(Vec<u8>, usize, u64)>, crate::rings::Stats, crate::coalesce::Stats);++/// Parallel range merge: the same k-way merge as [`merge`], partitioned by tile id.+///+/// Serial `merge` is one heap over every chunk — at z14, ~27k streams and 240 M+/// entries on one core. This splits the zoom's tile-id space into cost-balanced+/// ranges; one worker k-way merges each range over the same chunks; a+/// coordinator drains ranges in order into the unchanged downstream+/// (`merge_batch` → encode → prune → append).+///+/// Byte-identity rests on three facts, each pinned by test:+/// 1. Every tile belongs to exactly one range, and ranges drain ascending, so+/// the yielded tile sequence is the serial one.+/// 2. Within a range, chunks are consumed in global chunk order through the+/// same heap discipline, so each tile's fragments concatenate identically.+/// 3. Range boundaries never alter batch cuts: the coordinator yields the same+/// sequence `merge_batch` would pull from the serial iterator, so batches —+/// and therefore `prune_barren_subtree` — are unchanged.+///+/// Workers borrow the spill through `thread::scope` at the call site; nothing+/// here is `'static`, and no chunk bytes are duplicated (each entry is decoded+/// exactly once, by its range's worker). A corrupt spill fails the build with+/// the lowest-indexed range's error — deterministic, matching serial's+/// earliest-tile failure.+const RANGE_BUCKETS: usize = 256;+/// At or above this many tile-layer entries, the planning scan pays for+/// itself; below it the serial [`merge`] runs (small zooms merge in+/// milliseconds either way, and spawning buys nothing).+const PARALLEL_MERGE_MIN_ENTRIES: u64 = 1_000_000;+/// Worker cap: each worker holds one cursor per chunk, so live readers scale+/// as chunks × workers. More workers also duplicate more skip-walk; 8 is the+/// shape until a bigger box says otherwise.+const PARALLEL_MERGE_MAX_WORKERS: usize = 8;+/// Per-worker output queue bound: backpressure without unbounded buffering.+/// Tiles vary wildly in cost (city vs ocean), so this counts entries, not+/// bytes; the coordinator drains continuously, so queues only ever hold a+/// scheduling bubble, not a range.+const RANGE_QUEUE_BOUND: usize = 32;++/// Whether the range-parallel merge supports zoom `z`.+///+/// The bucket table inverts exactly only when the zoom's tile span divides by+/// [`RANGE_BUCKETS`] (z4 and up: spans 256, 1024, …). On z0–z3 (spans 1–64)+/// an edge lands mid-bucket, the inversion floors a bucket low, and the+/// `remaining` difference undercounts the range's tail — which drops entries.+/// Those zooms stay serial: they merge in milliseconds either way, so planning+/// buys nothing there anyway. The caller gates on this; `plan_ranges` asserts+/// it in debug.+fn parallel_merge_supported(z: u8) -> bool {+ use tilecodec::pmtiles::zoom_base;+ (zoom_base(z + 1) - zoom_base(z)) % RANGE_BUCKETS as u64 == 0+}++/// Phase-A plan: cost-balanced tile ranges plus per-chunk seek positions.+struct RangePlan {+ /// Range starts in tile ids, ascending, length workers+1 (last is the+ /// zoom's end sentinel, exclusive).+ bounds: Vec<u64>,+ /// Per-range merge cost (entry-cost units from the planning scan), for the+ /// balance report. The coordinator drains ranges in order, so the slowest+ /// range sets the merge wall; a range holding most of the cost means the+ /// greedy cut failed and workers idle.+ range_cost: Vec<u64>,+ /// Hottest single tile and its cost: no range split can beat this tile,+ /// so it is the structural floor under the merge wall. See `plan_ranges`.+ hot_tile: u64,+ hot_cost: u64,+ /// Per chunk: file offset of the first entry at-or-after each range start+ /// (chunk end when the range starts past the chunk).+ offsets: Vec<Vec<u64>>,+ /// Per chunk: entries remaining from each range start (0 when the range+ /// starts past the chunk).+ remaining: Vec<Vec<u64>>,+ /// Per chunk: whether each range reaches the chunk's last byte (gates the+ /// no-trailing-bytes check in `next`).+ exact_end: Vec<Vec<bool>>,+}++/// Cost-balanced range boundaries over one zoom's tile space, with seek+/// positions.+///+/// Two serial skip-walks over every chunk — header parses and length walks+/// only, no allocation, no UTF-8, no struct builds, roughly a tenth of a full+/// decode each. Pass 1 accumulates per-tile cost into a histogram and cuts+/// tile-granular ranges from it; pass 2 records each chunk's cursor at every+/// range bound, so seeks are exact and ranges never overlap.+///+/// Exactness is load-bearing, not decorative: the spill's `check_books` gate+/// requires every entry decoded exactly once, so a range that re-reads+/// another's entries fails the build. An earlier revision sought+/// bucket-granular cursors with a skip loop absorbing the difference — the+/// loop walked entries the neighbouring range also walked, the books showed+/// ~196 KB read past written on a California z14, and the build rightly+/// refused. Two walks cost one extra scan; overlapping seeks cost the build.+///+/// Cuts are tile-granular because bucket edges proved too coarse: z14's cost+/// concentrates inside single buckets (one bucket held 97% of a California+/// z14), so no bucket-edge cut could balance and seven of eight workers+/// idled. The sorted key walk (never the map's own order) is what keeps the+/// cuts independent of hashing.+fn plan_ranges(+ chunks: &[ChunkRef],+ spill: &ChunkSpill,+ z: u8,+ workers: usize,+) -> Result<RangePlan> {+ use tilecodec::pmtiles::zoom_base;+ debug_assert!(+ parallel_merge_supported(z),+ "plan_ranges needs an exact span/256 split (z4+); z{z} must stay serial"+ );+ let base = zoom_base(z);+ // Pass 1: per-tile cost across all chunks, plus per-chunk max tile.+ // A HashMap, not a Vec over the span: z14's span is 268 M tiles but only+ // ~7.5 M carry entries, so the dense form would be ~2 GB of mostly+ // zeroes. Never iterated — cuts traverse a sorted key vec, so the map's+ // own order (and its hasher) is unobservable in the output.+ let mut tile_cost: HashMap<u64, u64> = HashMap::new();+ let mut chunk_max: Vec<u64> = Vec::with_capacity(chunks.len());+ let mut chunk_total: Vec<u64> = Vec::with_capacity(chunks.len());+ // Hottest single tile and its cost, across all chunks: the merge assigns+ // whole tiles to one range worker (a tile's layers concatenate in chunk+ // order), so no range split can beat this tile. Reported alongside the+ // per-range costs — when it approaches the largest range, the ceiling is+ // structural, not a balancer bug.+ let mut hot_tile = 0u64;+ let mut hot_cost = 0u64;+ for chunk in chunks {+ let mut reader = spill.reader(chunk, 8192);+ let mut consumed = 0u64;+ let mut max_tile = 0u64;+ // Current tile's accumulated cost, flushed when the tile id changes:+ // chunks store entries tile-major ((tile, layer) order), so a run of+ // equal tile ids is the whole tile.+ let mut run_tile = u64::MAX;+ let mut run_cost = 0u64;+ loop {+ let Some(((tile, _), cost)) = reader.skip_entry()? else {+ break;+ };+ if tile != run_tile {+ if run_tile != u64::MAX {+ *tile_cost.entry(run_tile).or_insert(0) += run_cost;+ if run_cost > hot_cost {+ hot_tile = run_tile;+ hot_cost = run_cost;+ }+ }+ run_tile = tile;+ run_cost = 0;+ }+ run_cost += cost;+ consumed += 1;+ max_tile = max_tile.max(tile);+ }+ // Flush the trailing tile run — the loop only flushes on a tile+ // change, so the chunk's last tile would otherwise never count.+ if run_tile != u64::MAX {+ *tile_cost.entry(run_tile).or_insert(0) += run_cost;+ if run_cost > hot_cost {+ hot_tile = run_tile;+ hot_cost = run_cost;+ }+ }+ chunk_max.push(max_tile);+ chunk_total.push(consumed);+ }+ // Greedy cost balance over TILES, not buckets: cut when crossing each+ // multiple of total/workers, with the cut falling between the tiles that+ // straddle the mark. Fixed rule on scanned data — deterministic across+ // runs and machines. Tile-granular because bucket edges proved too coarse:+ // cost concentrates inside single buckets, and only tile steps can split+ // that mass. The sorted key walk (never the map's own order) is what keeps+ // the cuts independent of hashing.+ let total: u64 = tile_cost.values().sum();+ let mut tiles: Vec<u64> = tile_cost.keys().copied().collect();+ tiles.sort_unstable();+ let mut bounds = vec![base];+ let mut acc = 0u64;+ let mut cuts = 1usize;+ for tile in &tiles {+ // Commit the cut BEFORE adding this tile's cost when the mark was+ // already reached: the cut then falls between the previous tile and+ // this one, and this tile opens the next range. Cutting after would+ // hand the straddling tile's whole cost to the range that already+ // crossed its mark — which is how one range ends up owning nearly the+ // whole zoom.+ while cuts < workers && acc * workers as u64 >= total * cuts as u64 {+ let edge = *tile;+ if edge > *bounds.last().expect("bounds") {+ bounds.push(edge);+ }+ cuts += 1;+ }+ acc += tile_cost[tile];+ }+ // The trailing range owns through the last tile: no cut is committed+ // after the loop (the zoom end sentinel below closes it). A mark crossed+ // only by the final tile still leaves that tile in the last range rather+ // than stranding it past every cut.+ bounds.push(zoom_base(z + 1));+ bounds.dedup();+ // Padding: fewer distinct cut positions than workers (tiny zoom, or one+ // tile holding everything). Pad with the zoom end — never with a tile+ // strictly inside the span, which would hand two ranges the same tile.+ while bounds.len() < workers + 1 {+ bounds.push(zoom_base(z + 1));+ }+ // Per-range cost from the same tile histogram the cuts came from: exact,+ // not bucket-approximated. Reported by the caller (one line per zoom on+ // the parallel path).+ let range_cost = {+ let mut costs = Vec::with_capacity(workers);+ for r in 0..workers {+ // Binary search: tiles are sorted, bounds ascending.+ let lo = tiles.partition_point(|&t| t < bounds[r]);+ let hi = tiles.partition_point(|&t| t < bounds[r + 1]);+ costs.push(tiles[lo..hi].iter().map(|t| tile_cost[t]).sum());+ }+ costs+ };+ // Pass 2: each chunk's cursor at every range bound. Bounds ascend and the+ // walk is tile-ordered, so one pointer walks the bounds while the entries+ // stream past: bound `r` records the cursor (and consumed count) of the+ // first entry with tile >= bounds[r] — exactly the first entry the range+ // can own. No bucket machinery: the cursor IS the range start, so the+ // pre-bound skip loop is a provable no-op and `remaining` is the exact+ // owned-entry difference. Ranges partition tiles, so seeks partition+ // entries: nothing is read twice, and the books balance by construction.+ let mut offsets = Vec::with_capacity(chunks.len());+ let mut remaining = Vec::with_capacity(chunks.len());+ let mut exact_end = Vec::with_capacity(chunks.len());+ for (ci, chunk) in chunks.iter().enumerate() {+ let mut reader = spill.reader(chunk, 8192);+ // Bound cursors in walk order: bound 0 is always `base` (every entry+ // qualifies), so it records the chunk start with nothing consumed.+ let mut at_bound = 0usize;+ let mut bound_off = vec![0u64; workers + 1];+ let mut bound_con = vec![0u64; workers + 1];+ bound_off[0] = chunk.at;+ let mut consumed = 0u64;+ loop {+ let off = reader.position();+ let Some(((tile, _), _)) = reader.skip_entry()? else {+ break;+ };+ // Record every bound this entry is the first at-or-after: bounds+ // ascend, entries ascend, so one forward pointer suffices and gap+ // bounds (past this tile but unmet by later ones) are filled by+ // the chunk-end fill below.+ while at_bound < workers && tile >= bounds[at_bound] {+ bound_off[at_bound] = off;+ bound_con[at_bound] = consumed;+ at_bound += 1;+ }+ consumed += 1;+ }+ // Bounds past the chunk's last tile (or past every tile, for a chunk+ // entirely below the bound): chunk end, everything consumed. The+ // range then seeks to chunk end with nothing remaining — it owns+ // nothing here.+ while at_bound <= workers {+ bound_off[at_bound] = chunk.at + chunk.len;+ bound_con[at_bound] = consumed;+ at_bound += 1;+ }+ debug_assert_eq!(+ consumed, chunk_total[ci],+ "the two planning walks must agree on chunk {ci}'s entry count"+ );+ let mut orow = Vec::with_capacity(workers);+ let mut rrow = Vec::with_capacity(workers);+ let mut erow = Vec::with_capacity(workers);+ for r in 0..workers {+ orow.push(bound_off[r]);+ // Owned entries: everything from this bound to the next. Exact —+ // no prefix, no tail — because the cursors are the bounds.+ rrow.push(bound_con[r + 1].saturating_sub(bound_con[r]));+ // Exact end iff the chunk's max tile sits inside this range.+ erow.push(chunk_max[ci] < bounds[r + 1] && chunk_max[ci] >= bounds[r]);+ }+ offsets.push(orow);+ remaining.push(rrow);+ exact_end.push(erow);+ }+ Ok(RangePlan { bounds, range_cost, hot_tile, hot_cost, offsets, remaining, exact_end })+}++/// One range worker's output: tiles in ascending order, or the first error.+///+/// The error carries its range index so the coordinator reports the+/// lowest-indexed failure — deterministic, matching serial's earliest-tile+/// failure. Workers exit when their range is drained or the coordinator drops+/// the receiver (abort on an earlier range's failure): a failed `send` ends+/// the worker rather than blocking it forever.+type RangeOut = Result<(u64, Vec<ChunkEntry>)>;++/// Merge one tile range over all chunks, streaming results in order.+///+/// Same heap discipline as [`Merged`]: chunks consumed in global chunk order,+/// entries for one tile arriving layer-major, concatenated as they arrive. A+/// range is exactly the serial merge restricted to its tile span, so its+/// output is the serial output's subsequence — concatenating ranges in order+/// reproduces the serial tile sequence byte for byte.+///+/// `end_tile` bounds the range (exclusive); entries at-or-after it stay+/// unread for the next range. Chunks not touching the range are skipped+/// without opening a reader.+fn merge_range(+ chunks: &[ChunkRef],+ spill: &ChunkSpill,+ plan: &RangePlan,+ range: usize,+ end_tile: u64,+ out: &std::sync::mpsc::SyncSender<RangeOut>,+) {+ use std::cmp::Reverse;+ use std::collections::BinaryHeap;+ // Padded trailing ranges ([zoom end, zoom end)) own nothing: yield+ // nothing rather than decoding bucket 255 a second time.+ if plan.bounds[range] >= end_tile {+ return;+ }+ let window = crate::tilespill::read_window_bytes(chunks.len());+ let start_tile = plan.bounds[range];+ let mut readers: Vec<Option<ChunkReader<'_>>> = Vec::with_capacity(chunks.len());+ for (ci, chunk) in chunks.iter().enumerate() {+ let remaining = plan.remaining[ci][range];+ if remaining == 0 {+ readers.push(None);+ continue;+ }+ let mut reader = spill.reader(chunk, window);+ reader.seek_to(plan.offsets[ci][range], remaining, plan.exact_end[ci][range]);+ // Bucket edges are coarser than range bounds: advance past entries+ // below the bound (skip-walked, uncounted, `left` adjusted by the+ // skips themselves so it still exhausts exactly at range end). A+ // corrupt entry reports through the channel like a decode error.+ loop {+ let below = match reader.peek_tile() {+ Ok(Some(t)) => t < start_tile,+ Ok(None) => false,+ Err(e) => {+ let _ = out.send(Err(e));+ readers.push(None);+ continue;+ }+ };+ if !below {+ break;+ }+ match reader.skip_entry() {+ Ok(Some(_)) => {}+ Ok(None) => break,+ Err(e) => {+ let _ = out.send(Err(e));+ readers.push(None);+ continue;+ }+ }+ }+ readers.push(Some(reader));+ }+ let mut heap: BinaryHeap<Reverse<(u64, u8, usize)>> = BinaryHeap::new();+ let mut front: Vec<Held> = Vec::with_capacity(chunks.len());+ for (index, reader) in readers.iter_mut().enumerate() {+ let head = match reader {+ Some(r) => r.next().transpose(),+ None => None,+ };+ match &head {+ Some(Ok(((tile, layer), _))) => heap.push(Reverse((*tile, *layer, index))),+ Some(Err(_)) => heap.push(Reverse((0, 0, index))),+ None => {}+ }+ front.push(head);+ }+ // Mirrors `Merged::next`: the heap top names the tile, the inner loop+ // drains it, entries concatenate layer-major in chunk order.+ while let Some(&Reverse((tile, _, _))) = heap.peek() {+ if tile >= end_tile {+ break;+ }+ let mut layers: Vec<ChunkEntry> = Vec::new();+ while let Some(&Reverse((at, layer_id, index))) = heap.peek() {+ if at != tile {+ break;+ }+ heap.pop();+ let held = front[index].take().expect("a heap key without its entry");+ let (_, mut layer) = match held {+ Ok(entry) => entry,+ Err(e) => {+ let _ = out.send(Err(e));+ return;+ }+ };+ match layers.last_mut() {+ Some(last) if last.layer.layer_id == layer_id => {+ concatenate(last, &mut layer);+ if let Some(r) = readers[index].as_mut() {+ r.recycle(layer);+ }+ }+ _ => layers.push(layer),+ }+ let head = match &mut readers[index] {+ Some(r) => r.next().transpose(),+ None => None,+ };+ match &head {+ Some(Ok(((t, l), _))) => heap.push(Reverse((*t, *l, index))),+ Some(Err(_)) => heap.push(Reverse((0, 0, index))),+ None => {}+ }+ front[index] = head;+ }+ if out.send(Ok((tile, layers))).is_err() {+ return;+ }+ }+}++/// Range-worker entry point for `thread::scope` spawning: merges range `r`+/// and streams it, converting panics-by-Result into channel values.+///+/// Never returns `Err` itself (there is nowhere for it to go — the+/// coordinator owns failure reporting): fallible setup is unreachable here+/// because planning already validated every seek position, so the body is+/// infallible by construction and any `Err` produced mid-merge travels as a+/// value.+fn merge_range_into(+ chunks: &[ChunkRef],+ spill: &ChunkSpill,+ plan: &RangePlan,+ r: usize,+ tx: std::sync::mpsc::SyncSender<RangeOut>,+) {+ let end_tile = plan.bounds[r + 1];+ merge_range(chunks, spill, plan, r, end_tile, &tx);+}++/// Ordered coordinator over range workers: an iterator yielding the serial+/// tile sequence.+///+/// Ranges drain strictly in order (range 0 to exhaustion, then range 1, ...),+/// so the yielded sequence is tile-ascending regardless of completion order.+/// A range's error aborts the drain with the lowest-indexed failure: ranges+/// before it drained cleanly, so it is the earliest tile-ordered failure —+/// deterministic, like serial.+struct ParallelMerge {+ receivers: Vec<std::sync::mpsc::Receiver<RangeOut>>,+ at: usize,+ failed: Option<tilecodec::proto::Error>,+}++impl ParallelMerge {+ fn new(receivers: Vec<std::sync::mpsc::Receiver<RangeOut>>) -> ParallelMerge {+ ParallelMerge { receivers, at: 0, failed: None }+ }+}++impl Iterator for ParallelMerge {+ type Item = Result<(u64, Vec<ChunkEntry>)>;++ fn next(&mut self) -> Option<Result<(u64, Vec<ChunkEntry>)>> {+ loop {+ if self.at >= self.receivers.len() {+ return None;+ }+ if let Some(e) = self.failed.take() {+ // Drain nothing further: receivers drop here, workers exit on+ // send failure, scope joins them. Lowest-indexed failure wins+ // because lower ranges already drained clean.+ self.at = self.receivers.len();+ self.receivers.clear();+ return Some(Err(e));+ }+ match self.receivers[self.at].recv() {+ Ok(Ok(tile)) => return Some(Ok(tile)),+ Ok(Err(e)) => {+ self.failed = Some(e);+ }+ Err(_) => {+ // Sender dropped = range drained cleanly. Advance.+ self.at += 1;+ }+ }+ }+ }+}++/// Merge one zoom's chunks with `workers` range workers, or serially when the+/// zoom is too small to repay planning.+///+/// Returns the tile sequence as an iterator (serial [`Merged`] or parallel+/// coordinator — both yield `(tile, layers)` ascending), plus a flag the+/// caller uses only for reporting. Errors surface identically either way.+enum MergeStream<'a> {+ Serial(Merged<'a>),+ Parallel(ParallelMerge),+}++impl Iterator for MergeStream<'_> {+ type Item = Result<(u64, Vec<ChunkEntry>)>;++ fn next(&mut self) -> Option<Result<(u64, Vec<ChunkEntry>)>> {+ match self {+ MergeStream::Serial(m) => m.next(),+ MergeStream::Parallel(m) => m.next(),+ }+ }+}++#[cfg(test)]+mod tests_parallel {+ use super::*;+ use crate::tiler::tests::*;+ use crate::tilespill::{ChunkRef, ChunkSpill};++ /// Drive a merge iterator to a vec, failing the test on the first error+ /// rather than publishing a short sequence.+ fn collect<I>(merged: &mut I) -> Vec<(u64, Vec<ChunkEntry>)>+ where+ I: Iterator<Item = Result<(u64, Vec<ChunkEntry>)>>,+ {+ merged+ .by_ref()+ .collect::<Result<Vec<_>>>()+ .expect("merge the chunks")+ }++ /// Map a fixture into spill chunks at `z`, returning refs plus the spill.+ /// The spill outlives the refs: callers keep both alive together. Forces+ /// small vertex chunks so the fixture spans several chunks even at test+ /// scale (a single-chunk merge exercises nothing).+ fn map_chunks(+ features: &[crate::extract::Feature],+ z: u8,+ ) -> (Vec<ChunkRef>, ChunkSpill) {+ let _guard = budget();+ crate::tiler::set_chunk_vertices(64);+ let store = spilled(features);+ let spill = ChunkSpill::create(scratch()).expect("spill");+ let tolerance = tile_build::simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, 1.0);+ let buffer = tile_build::geom::buffer_for(crate::tiler::EXTENT);+ let settings = settings(0, 14);+ let _ = &settings;+ let (chunks, _) =+ crate::tiler::map_zoom(&store, &settings, z, tolerance, buffer, &spill)+ .expect("map the fixture");+ crate::tiler::set_chunk_vertices(0);+ (chunks, spill)+ }++ /// The gate this work stands on: range-parallel output is the serial+ /// output, tile for tile, layer for layer, byte for byte — over a+ /// multi-chunk fixture with lakes, buildings and cross-tile rivers, at a+ /// zoom where the wash gate fires (z14) and one where it does not (z10).+ /// Both zooms are above z3, where the bucket table inverts exactly (see+ /// `parallel_merge_supported`) — the identity below rests on that.+ #[test]+ fn parallel_merge_is_the_serial_merge() {+ for z in [10u8, 14] {+ let (chunks, spill) = map_chunks(&a_crowd(), z);+ assert!(chunks.len() > 1, "the fixture must span chunks at z{z}");+ let mut serial = super::merge(&chunks, &spill);+ let want = collect(&mut serial);+ assert!(!want.is_empty(), "the fixture must yield tiles at z{z}");+ for workers in [2usize, 3, 7] {+ let plan =+ super::plan_ranges(&chunks, &spill, z, workers).expect("plan the ranges");+ let got = std::thread::scope(|s| {+ let mut receivers = Vec::with_capacity(workers);+ let chunks_ref = &chunks;+ let spill_ref = &spill;+ let plan_ref = &plan;+ for r in 0..workers {+ let (tx, rx) = std::sync::mpsc::sync_channel(super::RANGE_QUEUE_BOUND);+ receivers.push(rx);+ s.spawn(move || {+ super::merge_range_into(chunks_ref, spill_ref, plan_ref, r, tx);+ });+ }+ let mut coord = super::ParallelMerge::new(receivers);+ collect(&mut coord)+ });+ assert_eq!(got, want, "worker count {workers} moved z{z}");+ }+ }+ }++ /// Ranges that hold nothing yield nothing: a single-tile fixture merged+ /// under more workers than tiles still produces exactly that tile.+ /// (A pool, not a lake: wash areas never reach z14 tiles under the cap.)+ #[test]+ fn empty_ranges_yield_nothing() {+ let pool = crate::extract::Feature {+ class: crate::schema::Class::area(+ tilecodec::mamaps::dict::LAYER_LANDTYPE,+ crate::schema::kind("swimming_pool"),+ 14,+ ),+ geometry: crate::tiler::tests::square(-122.0, 37.0, 0.005),+ name: None,+ id: tilecodec::mamaps::body::ID_NONE,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ turn_fwd: Vec::new(),+ turn_bwd: Vec::new(),+ building: None,+ carriageway: tilecodec::mamaps::body::Carriageway::default(),+ };+ let (chunks, spill) = map_chunks(&[pool], 14);+ let mut serial = super::merge(&chunks, &spill);+ let want = collect(&mut serial);+ assert!(!want.is_empty());+ let workers = 4usize;+ let plan = super::plan_ranges(&chunks, &spill, 14, workers).expect("plan");+ let got = std::thread::scope(|s| {+ let mut receivers = Vec::with_capacity(workers);+ let chunks_ref = &chunks;+ let spill_ref = &spill;+ let plan_ref = &plan;+ for r in 0..workers {+ let (tx, rx) = std::sync::mpsc::sync_channel(super::RANGE_QUEUE_BOUND);+ receivers.push(rx);+ s.spawn(move || {+ super::merge_range_into(chunks_ref, spill_ref, plan_ref, r, tx);+ });+ }+ let mut coord = super::ParallelMerge::new(receivers);+ collect(&mut coord)+ });+ assert_eq!(got, want, "empty ranges must not add or drop tiles");+ }++ /// The seek/count half of the plan, pinned directly: per-chunk+ /// `remaining` summed over chunks must cover the range's tile-layer+ /// entries — every (tile, layer) pair the range owns must be walked, no+ /// fewer. The serial merge yields each tile with its layers; counting+ /// layer entries per tile over the serial output gives the per-tile+ /// histogram, and each range's share must be covered by the plan's rows.+ ///+ /// Coverage, not equality: the plan counts from the containing bucket's+ /// cursor, so it INCLUDES the below-bound prefix the skip loop walks AND+ /// the mid-bucket tail past the end bound that the `end_tile` stop+ /// discards. Planned >= wanted always; planned < wanted means a starved+ /// reader — the failure this test exists to catch.+ #[test]+ fn plan_seek_counts_match_the_tile_histogram() {+ for z in [10u8, 14] {+ let (chunks, spill) = map_chunks(&a_crowd(), z);+ assert!(chunks.len() > 1, "the fixture must span chunks at z{z}");+ // Per-tile LAYER-entry counts from the serial output: one per+ // (tile, layer) pair, which is the unit the spill — and the+ // reader's `left` budget — counts in.+ let mut serial = super::merge(&chunks, &spill);+ let mut tile_entries: HashMap<u64, u64> = HashMap::new();+ for (tile, layers) in collect(&mut serial) {+ *tile_entries.entry(tile).or_insert(0) += layers.len() as u64;+ }+ for workers in [2usize, 3, 7] {+ let plan =+ super::plan_ranges(&chunks, &spill, z, workers).expect("plan the ranges");+ // Bounds ascend and partition the zoom: first is the base,+ // last is the end sentinel, workers+1 entries.+ assert_eq!(plan.bounds.len(), workers + 1, "z{z} w{workers}");+ for w in plan.bounds.windows(2) {+ assert!(w[0] <= w[1], "bounds ascend at z{z} w{workers}");+ }+ for r in 0..workers {+ // Entries the plan says range r walks, summed over chunks.+ let planned: u64 =+ plan.remaining.iter().map(|row| row[r]).sum();+ // Layer entries the histogram puts inside the range.+ let want: u64 = tile_entries+ .iter()+ .filter(|(&t, _)| t >= plan.bounds[r] && t < plan.bounds[r + 1])+ .map(|(_, &n)| n)+ .sum();+ assert!(+ planned >= want,+ "z{z} w{workers} range {r}: plan walks {planned}, histogram holds {want}"+ );+ }+ }+ }+ }++ /// z0–z3 stay serial: their spans (1–64 tiles) don't divide the 256 cost+ /// buckets, so range edges can't invert exactly. The zoom loop gates on+ /// this — if the gate ever lets a low zoom through, planning must refuse.+ #[test]+ fn low_zooms_stay_serial() {+ for z in [0u8, 1, 2, 3] {+ assert!(!super::parallel_merge_supported(z), "z{z} must stay serial");+ }+ for z in [4u8, 10, 14] {+ assert!(super::parallel_merge_supported(z), "z{z} must parallelise");+ }+ }++ /// The full-archive version of the merge gate: the zoom loop's own+ /// selection (`merge_gate` → plan/workers vs serial) agrees with itself+ /// across thread counts. The unit tests above drive the planner and+ /// workers directly; this drives `build()` end to end — so a miswired+ /// gate can't hide behind correct components. One thread takes the+ /// serial path (single worker cap... no: `merge_workers > 1` fails, so+ /// serial), four threads take the range workers wherever the zoom is big+ /// enough; both must produce the same archive.+ #[test]+ fn gate_paths_agree_through_build() {+ use crate::tiler::tests::{budget, release_threads};+ let _guard = budget();+ crate::tiler::set_chunk_vertices(64);+ let store = spilled(&a_crowd());+ tile_build::par::set_threads(1);+ let serial = crate::tiler::build(&store, &settings(0, 14)).expect("one thread").0;+ tile_build::par::set_threads(4);+ let parallel = crate::tiler::build(&store, &settings(0, 14)).expect("four threads").0;+ crate::tiler::set_chunk_vertices(0);+ release_threads();+ assert_eq!(parallel, serial, "thread count moved the archive");+ }+}
scripts/maps/mamaps_build/src/tilespill.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill.rs b/scripts/maps/mamaps_build/src/tilespill.rsindex 91a9b11eea..ac70b8f41a 100644--- a/scripts/maps/mamaps_build/src/tilespill.rs+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -355,6 +355,7 @@ impl ChunkSpill { used: 0, window: window.max(ENTRY_HEADER_BYTES), spare: None,+ exact_end: true, } } @@ -437,6 +438,11 @@ pub struct ChunkReader<'a> { /// `None` until the merge returns one; a decoded entry is byte-identical whether it was built /// from a recycled arena or a fresh one, because the contents are written the same way. spare: Option<ChunkEntry>,+ /// Whether this cursor runs to the chunk's last byte. A range worker's+ /// segment ends mid-chunk (the next range owns what follows), so only a+ /// cursor that does reach the end enforces the no-trailing-bytes check —+ /// any other segment legitimately stops with unread bytes after it.+ exact_end: bool, } include!("tilespill_part1.rs");
scripts/maps/mamaps_build/src/tilespill_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill_part1.rs b/scripts/maps/mamaps_build/src/tilespill_part1.rsindex 33e2caef00..a07ab924a5 100644--- a/scripts/maps/mamaps_build/src/tilespill_part1.rs+++ b/scripts/maps/mamaps_build/src/tilespill_part1.rs@@ -1,12 +1,116 @@ impl ChunkReader<'_> {- /// The next entry, or `None` at the end of the chunk.+ /// Skip one entry without decoding it, returning its key and merge cost.+ ///+ /// Byte-for-byte the same cursor movement as [`next`](Self::next) —+ /// header, fixed arenas, name lengths, turn counts, building and+ /// carriageway sections — minus every allocation, UTF-8 check and struct+ /// build. The range planner uses it to walk chunks cheaply (cost histogram+ /// + boundary offsets); the merge workers then decode for real. A corrupt+ /// entry errors here exactly as `next` would surface it, so planning fails+ /// fast rather than handing workers a desynced stream.+ ///+ /// Never touches the spill's read counters: planning reads are not+ /// decoded entries, and `check_books` must see each entry counted once —+ /// by the worker that decodes it.+ pub fn skip_entry(&mut self) -> Result<Option<((u64, u8), u64)>> {+ if self.left == 0 {+ return Ok(None);+ }+ self.fill(ENTRY_HEADER_BYTES)?;+ let head: &[u8; ENTRY_HEADER_BYTES] = self.buf[self.used..self.used + ENTRY_HEADER_BYTES]+ .try_into()+ .expect("a header's worth of bytes");+ let header = entry_header(head)?;+ let fixed =+ payload_bytes(header.features, header.parts, header.coords, header.ids) as usize;+ self.fill(ENTRY_HEADER_BYTES + fixed)?;+ self.used += ENTRY_HEADER_BYTES + fixed;+ for _ in 0..header.names {+ self.fill(4)?;+ let len = u32::from_le_bytes(+ self.buf[self.used..self.used + 4].try_into().expect("4 bytes"),+ ) as usize;+ if len > 1 << 20 {+ return err("a tile chunk entry names a megabyte-plus string".to_string());+ }+ self.fill(4 + len)?;+ self.used += 4 + len;+ }+ if header.has_turns {+ for _ in 0..header.features {+ self.fill(2)?;+ let (fwd, bwd) =+ (self.buf[self.used] as usize, self.buf[self.used + 1] as usize);+ let bytes = 2 + 2 * (fwd + bwd);+ self.fill(bytes)?;+ self.used += bytes;+ }+ }+ if header.has_buildings {+ let bytes = BUILDING_BYTES * header.features;+ self.fill(bytes)?;+ self.used += bytes;+ }+ if header.has_carriageways {+ let bytes = CARRIAGEWAY_RECORD_LEN * header.features;+ self.fill(bytes)?;+ self.used += bytes;+ }+ self.left -= 1;+ // Same cost unit the merge batches by (`tile_cost`): features plus+ // coordinates, the proxy the encode pass balances tasks by.+ let cost = header.features as u64 + header.coords as u64;+ Ok(Some(((header.tile, header.layer_id), cost)))+ }++ /// File offset of the next unread byte: what a range worker seeks to.+ ///+ /// `at` is the first byte not yet buffered, so the unread position is+ /// behind it by exactly the buffered-but-unconsumed span.+ pub fn position(&self) -> u64 {+ self.at - (self.buf.len() - self.used) as u64+ }++ /// The next entry's tile id without consuming it.+ ///+ /// A range worker seeks to a bucket edge (coarser than its tile bound),+ /// then advances past entries below the bound with [`skip_entry`](Self::skip_entry)+ /// — counted down from `left` like any consumed entry, uncounted in the+ /// spill books like any skip. `None` past the last entry (no trailing+ /// check here; [`next`](Self::next) owns that).+ pub fn peek_tile(&mut self) -> Result<Option<u64>> {+ if self.left == 0 {+ return Ok(None);+ }+ self.fill(ENTRY_HEADER_BYTES)?;+ let head: &[u8; ENTRY_HEADER_BYTES] = self.buf[self.used..self.used + ENTRY_HEADER_BYTES]+ .try_into()+ .expect("a header's worth of bytes");+ Ok(Some(entry_header(head)?.tile))+ }++ /// Reposition a reader at a planned offset with a planned entry count.+ ///+ /// The buffer is discarded (its bytes belong to another range now and+ /// will be re-read through the window); `end` is unchanged. `exact_end`+ /// says whether this segment runs to the chunk's last byte: only then+ /// does [`next`](Self::next) enforce the no-trailing-bytes check, since+ /// any other segment legitimately ends mid-chunk with the next range's+ /// bytes after it.+ pub fn seek_to(&mut self, offset: u64, remaining: u64, exact_end: bool) {+ self.buf.clear();+ self.used = 0;+ self.at = offset;+ self.left = remaining;+ self.exact_end = exact_end;+ } /// /// Fallible, and that matters: a truncated scratch file must fail the build rather than silently /// shorten the archive. #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Result<Option<((u64, u8), ChunkEntry)>> { if self.left == 0 {- if self.used < self.buf.len() || self.at < self.end {+ if self.exact_end && (self.used < self.buf.len() || self.at < self.end) { return err(format!( "a tile chunk in {} holds bytes past its last entry", self.spill.path.display()
scripts/maps/osm_ingest/src/chains_part1.rs
diff --git a/scripts/maps/osm_ingest/src/chains_part1.rs b/scripts/maps/osm_ingest/src/chains_part1.rsindex a11b4aa392..3532df23df 100644--- a/scripts/maps/osm_ingest/src/chains_part1.rs+++ b/scripts/maps/osm_ingest/src/chains_part1.rs@@ -192,8 +192,8 @@ impl Spill { } /// Sequential reader over `chains.hdr`. Every stage after the chain pass is one- /// of these: the degree count for the CSR, the target scatter, and one per- /// write round.+ /// of these: the degree count for the CSR, the target scatter, and the single+ /// round-assignment scan feeding [`Spill::headers_mapped`](Self::headers_mapped). pub fn headers(&self) -> Result<HeaderReader> { Ok(HeaderReader { src: BufReader::with_capacity(1 << 20, open(&self.hdr)?),@@ -201,17 +201,27 @@ impl Spill { }) } + /// Random-access reader over `chains.hdr`, for the write rounds.+ ///+ /// Records are fixed-stride (`CHAIN_REC_BYTES` each), so chain `i` starts+ /// at byte `i * CHAIN_REC_BYTES` — no index, no scan. The write used to+ /// re-stream the whole file once per round (3 rounds on a continent: 3+ /// full header passes); now one assignment scan records each chain's+ /// round and every round gathers only its chains through this mapping.+ /// Page-cached after the assignment scan, so the gather faults almost+ /// nothing new.+ pub fn headers_mapped(&self) -> Result<HeaderMap> {+ Ok(HeaderMap { map: crate::mem::Mapped::open(&self.hdr).map_err(Error)? })+ }+ /// Random-access reader over `chains.pts`. /// /// The write rounds visit chains in edge order, not chain order, so this is the- /// one place the spill is not read sequentially. Each polyline is contiguous- /// and only a few dozen bytes, so it is one seek per edge into a file the page- /// cache has largely seen already.+ /// one place the spill is not read sequentially. The file is mapped once and+ /// read as slices: one seek per edge into a file the page cache has largely+ /// seen already became zero syscalls per edge. pub fn points(&self) -> Result<PointReader> {- Ok(PointReader {- file: open(&self.pts)?,- buf: Vec::new(),- })+ Ok(PointReader { map: crate::mem::Mapped::open(&self.pts).map_err(Error)? }) } #[cfg(test)]@@ -336,60 +346,91 @@ impl HeaderReader { } } +/// Random-access view over `chains.hdr`. See [`Spill::headers_mapped`].+pub(crate) struct HeaderMap {+ map: crate::mem::Mapped,+}++impl HeaderMap {+ /// How many records the mapping holds, from its length alone — the same+ /// width check [`Spill::chain_count`] applies to the file.+ pub fn len(&self) -> Result<u64> {+ let len = self.map.len() as u64;+ if len % CHAIN_REC_BYTES != 0 {+ return Err(Error(format!(+ "chains.hdr is {len} bytes, not a multiple of {CHAIN_REC_BYTES}"+ )));+ }+ Ok(len / CHAIN_REC_BYTES)+ }++ /// Decode chain `i`. Bounds-checked: a short mapping fails rather than+ /// slicing past the end.+ pub fn get(&self, i: u64) -> Result<ChainRec> {+ let at = i.checked_mul(CHAIN_REC_BYTES).expect("chain index * stride fits u64");+ let end = at + CHAIN_REC_BYTES;+ if end > self.map.len() as u64 {+ return Err(Error(format!("chains.hdr ends before chain {i}")));+ }+ let (at, end) = (at as usize, end as usize);+ let mut rec = [0u8; CHAIN_REC_BYTES as usize];+ rec.copy_from_slice(&self.map[at..end]);+ Ok(ChainRec::decode(&rec))+ }+}+ /// Reads one chain's polyline out of `chains.pts`. pub(crate) struct PointReader {- file: File,- /// Reused across reads: the write rounds call this once per edge, so a fresh- /// allocation each time would be a billion of them at planet scale.- buf: Vec<u8>,+ map: crate::mem::Mapped,+}++/// The shared mapping behind a [`PointReader`]: pool workers read the same+/// bytes through [`PointReader::read_shared`] with no lock and no cursor.+pub(crate) fn points_map(reader: &PointReader) -> &crate::mem::Mapped {+ &reader.map } impl PointReader { /// Replace `out` with the `len` points starting at point index `start`. ///- /// One positional read rather than a seek followed by a read. This is the only- /// random read in the graph writer — once per edge that stores a polyline — and- /// `osm_ingest/README.md` records that pass as 47 minutes at 21% CPU with 17.8 M- /// voluntary context switches, so halving its syscall count is worth the platform- /// split.+ /// A slice of one persistent mapping, not a positional read: the write+ /// rounds visit chains in edge order, not chain order, so a `File` paid+ /// one syscall per edge (~300 M at planet scale) for a few dozen bytes+ /// each. The mapping faults the same pages with zero syscalls, no+ /// per-edge buffer zeroing, and no cursor to keep — which is also what a+ /// parallel writer would need first. ///- /// Still `&mut self`, because `buf` is reused: the writer is sequential, and an- /// allocation per edge would cost more than the seek this removes. Making the read- /// positional is nonetheless what a parallel writer would need first, since the- /// handle's cursor is no longer part of the result.+ /// Short reads fail exactly as the positional path did (`UnexpectedEof`+ /// naming the file), so a truncated spill surfaces here rather than as a+ /// wrong polyline downstream. pub fn read(&mut self, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> {+ Self::read_from(&self.map, start, len, out)+ }++ /// [`read`](Self::read) over an explicit mapping: the shared-read form.+ ///+ /// `read` takes `&mut self` for the historical reason that the reader+ /// used to hold a cursor; the mapping itself is never mutated, so pool+ /// workers share one `&Mapped` and read through this instead. Same+ /// slices, same errors, no lock.+ pub fn read_shared(map: &crate::mem::Mapped, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> {+ Self::read_from(map, start, len, out)+ }++ fn read_from(map: &crate::mem::Mapped, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> { out.clear(); if len == 0 { return Ok(()); }- self.buf.clear();- self.buf.resize(len as usize * CHAIN_PT_BYTES as usize, 0);- read_exact_at(&self.file, &mut self.buf, start * CHAIN_PT_BYTES).map_err(io_err)?;- out.extend(self.buf.chunks_exact(CHAIN_PT_BYTES as usize).map(decode_pt));- Ok(())- }-}--/// Fill `buf` from `offset` in one call, without moving the file's cursor.-///-/// Neither platform's positional read is guaranteed to return everything at once,-/// hence the loop; in practice it goes round once.-fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> {- while !buf.is_empty() {- #[cfg(windows)]- let n = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?;- #[cfg(unix)]- let n = std::os::unix::fs::FileExt::read_at(file, buf, offset)?;- if n == 0 {- return Err(std::io::Error::new(- std::io::ErrorKind::UnexpectedEof,- "chains.pts ended mid-chain",- ));+ let at = start as u128 * CHAIN_PT_BYTES as u128;+ let bytes = len as u128 * CHAIN_PT_BYTES as u128;+ if at + bytes > map.len() as u128 {+ return Err(Error(format!("chains.pts ended mid-chain"))); }- buf = &mut buf[n..];- offset += n as u64;+ let (at, bytes) = (at as usize, bytes as usize);+ out.extend(map[at..at + bytes].chunks_exact(CHAIN_PT_BYTES as usize).map(decode_pt));+ Ok(()) }- Ok(()) } fn io_err(e: std::io::Error) -> Error {
scripts/maps/osm_ingest/src/graph_build_part3.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part3.rs b/scripts/maps/osm_ingest/src/graph_build_part3.rsindex 6622b1413e..032a06ebbe 100644--- a/scripts/maps/osm_ingest/src/graph_build_part3.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part3.rs@@ -191,6 +191,64 @@ struct Written { census: Census, } +/// One write worker's output for a batch of edges, in batch order.+///+/// Two shapes, interleaved in visit order: node openers (one per node the+/// batch owns, edgeless ones included) and edge items (one per edge). The+/// serial append folds them positionally — node record, then its edges — so+/// concatenation reproduces the serial byte sequence exactly. The geometry+/// decision rides along per edge (computed on the pool from the shared+/// mapping); census inputs ride along too (the census is additive, replayed+/// verbatim); node openers carry their own `edge_ptr` snapshot and degree so+/// the drain never recomputes running state.+enum BakedItem {+ /// Open a node: stage its record, count its degree, tick it.+ Node {+ /// Node-record bytes (12 B) with the absolute edge pointer.+ rec: [u8; 12],+ /// Out-degree, for the census replay.+ degree: u32,+ },+ /// One edge: census inputs, record inputs, geometry outcome, lanes.+ /// Boxed: edges outnumber nodes ~3:1 and the small `Node` variant would+ /// otherwise bloat every item to the edge size (the pool holds a whole+ /// round's items at once).+ Edge(Box<BakedEdge>),+}++/// One decided edge: record inputs, geometry outcome, census inputs, lanes.+struct BakedEdge {+ /// Census inputs for the edge: source, target, dist, named. The edge+ /// census is a pure function of these (histogram increments, maxima,+ /// escape predicates), so the drain replays `Census::edge` verbatim.+ cen_source: u32,+ cen_target: u32,+ cen_dist: u32,+ cen_named: bool,+ /// Edge record inputs: the delta/dist pair (or the escape sentinel with+ /// its row), the final type byte, speed, and name.+ delta: i16,+ dist: u32,+ escaped: Option<(u32, u32)>,+ type
Diff truncated.