maps: map the coordinate array to a file, and time each tiling phase
- Commit
b7ef2c1b88605231f1b532e7677bd3e7ff2d86f9- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 05:58 UTC (3 months ago)
- Parents
9987dc6
Diff
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex df59635f37..f21935bb27 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -241,7 +241,7 @@ pub fn extract( for refs in members.values() { needed.extend_from_slice(refs); }- let table = NodeLocations::new(needed);+ let table = NodeLocations::new(needed)?; stats.nodes_needed = table.len() as u64; let table = resolve_nodes(input, &blobs, &blob_kinds, "Pass 3: nodes", table)?;
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex 4a684da272..6126c5d12f 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -190,13 +190,41 @@ fn run( // The spill is scratch. Removed on success; left behind on failure, where it is evidence. let _ = std::fs::remove_file(&spill); - println!("\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}", "zoom", "tiles", "features", "points", "dropped", "bytes");+ println!(+ "\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8}{:>8}{:>8}{:>8}",+ "zoom", "tiles", "features", "points", "dropped", "bytes", "map_s", "merge_s", "enc_s",+ "app_s",+ ); for z in &per_zoom { println!(- "z{:<5}{:>10}{:>12}{:>12}{:>10}{:>12}",- z.zoom, z.tiles, z.features, z.points, z.dropped, z.bytes,+ "z{:<5}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8.1}{:>8.1}{:>8.1}{:>8.1}",+ z.zoom,+ z.tiles,+ z.features,+ z.points,+ z.dropped,+ z.bytes,+ z.map_ms as f64 / 1000.0,+ z.merge_ms as f64 / 1000.0,+ z.encode_ms as f64 / 1000.0,+ z.append_ms as f64 / 1000.0, ); }+ // The four phase columns summed, because which of them dominates is the only thing that says+ // whether more cores would help: map and encode run on the pool, merge and append do not.+ let (map, merge, encode, append) = per_zoom.iter().fold((0u64, 0u64, 0u64, 0u64), |a, z| {+ (a.0 + z.map_ms, a.1 + z.merge_ms, a.2 + z.encode_ms, a.3 + z.append_ms)+ });+ let serial = (merge + append) as f64;+ let total = (map + merge + encode + append).max(1) as f64;+ println!(+ "total map {:.1}s merge {:.1}s encode {:.1}s append {:.1}s ({:.0}% of tiling is serial)",+ map as f64 / 1000.0,+ merge as f64 / 1000.0,+ encode as f64 / 1000.0,+ append as f64 / 1000.0,+ serial / total * 100.0,+ ); println!( "\nwrote {} ({} bytes, build_id {build_id:#018x}) in {:.1}s", out.display(),
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 93544aff58..4f0c9c36a3 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -167,6 +167,15 @@ pub struct ZoomStats { pub bytes: u64, /// What stage C had to correct. pub rings: crate::rings::Stats,+ /// Milliseconds in each phase of this zoom: map, merge, encode, append.+ ///+ /// Kept because guessing which one dominates has already cost two wrong optimisations. The map+ /// and encode phases run on the pool and the other two are serial, so the split is what says+ /// whether more cores would help at all or whether Amdahl has already won.+ pub map_ms: u64,+ pub merge_ms: u64,+ pub encode_ms: u64,+ pub append_ms: u64, } pub struct Settings {@@ -239,7 +248,9 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta let tolerance = simplify::tolerance_for(z, settings.max_zoom, settings.simplification); let buffer = geom::buffer_for(EXTENT); + let mapped = std::time::Instant::now(); let (chunks, tally) = map_zoom(store, z, tolerance, buffer)?;+ stats.map_ms = mapped.elapsed().as_millis() as u64; stats.features = tally.features; stats.points = tally.points; stats.dropped = tally.dropped;@@ -253,12 +264,21 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta // microseconds and rayon's stealing costs more than that. Batched rather than a whole // zoom at once because the batch is what bounds the encoded bytes held before the // writer takes them.+ //+ // The merge is timed around `collect` because that is where it happens: `merge` returns+ // a lazy iterator, so pulling a batch out of it is the k-way merge doing its work.+ let merging = std::time::Instant::now(); let batch: Vec<(u64, Vec<BodyLayer>)> = merged.by_ref().take(par::batch_len()).collect();+ stats.merge_ms += merging.elapsed().as_millis() as u64; if batch.is_empty() { break; }- for (id, encoded, rings) in encode_batch(batch)? {+ let encoding = std::time::Instant::now();+ let done = encode_batch(batch)?;+ stats.encode_ms += encoding.elapsed().as_millis() as u64;+ let appending = std::time::Instant::now();+ for (id, encoded, rings) in done { stats.rings.add(rings); let Some((stored, raw_len)) = encoded else { continue }; // Uncompressed, as this column has always meant.@@ -266,6 +286,7 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta stats.tiles += 1; writer.append_stored(id, &stored)?; }+ stats.append_ms += appending.elapsed().as_millis() as u64; } per_zoom.push(stats); }
scripts/maps/osm_ingest/Cargo.lock
diff --git a/scripts/maps/osm_ingest/Cargo.lock b/scripts/maps/osm_ingest/Cargo.lockindex cbbe116df1..a7567783d2 100644--- a/scripts/maps/osm_ingest/Cargo.lock+++ b/scripts/maps/osm_ingest/Cargo.lock@@ -39,6 +39,21 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" +[[package]]+name = "libc"+version = "0.2.189"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"++[[package]]+name = "memmap2"+version = "0.9.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"+dependencies = [+ "libc",+]+ [[package]] name = "miniz_oxide" version = "0.8.9"@@ -52,6 +67,7 @@ dependencies = [ name = "osm_ingest" version = "0.1.0" dependencies = [+ "memmap2", "miniz_oxide", "rayon", ]
scripts/maps/osm_ingest/Cargo.toml
diff --git a/scripts/maps/osm_ingest/Cargo.toml b/scripts/maps/osm_ingest/Cargo.tomlindex 814d2a9b6c..27cb388f52 100644--- a/scripts/maps/osm_ingest/Cargo.toml+++ b/scripts/maps/osm_ingest/Cargo.toml@@ -53,6 +53,14 @@ path = "src/bin/osm_extract.rs" # so a decode-only crate is enough and keeps the C toolchain out of the build. miniz_oxide = "0.8" rayon = "1"+# Pure Rust, one thin wrapper over the platform call, and no C toolchain — which is the bar every+# other dependency here clears too.+#+# It backs `nodeloc`'s coordinate array with a file instead of the heap. That array is 8 bytes per+# needed node, so 1.23 GB on a California extract, and it was half of `mamaps_build`'s whole peak.+# Mapped, the resident cost is whatever the OS decides to keep, and the access pattern is friendly to+# that: materialisation walks ways in id order and a way's nodes are close together in a PBF.+memmap2 = "0.9" [profile.release] opt-level = 3
scripts/maps/osm_ingest/src/extract.rs
diff --git a/scripts/maps/osm_ingest/src/extract.rs b/scripts/maps/osm_ingest/src/extract.rsindex 40f025b300..fa9a42b6a5 100644--- a/scripts/maps/osm_ingest/src/extract.rs+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -333,7 +333,7 @@ fn build_maxspeed( } println!("{} way(s) with a posted limit", rows.len()); - let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect());+ let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect())?; println!("{} node location(s) needed", table.len()); let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 2: nodes", table)?; @@ -481,7 +481,7 @@ fn build_roads( } println!("{} road way(s)", rows.len()); - let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect());+ let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect())?; println!("{} node location(s) needed", table.len()); let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 2: nodes", table)?; @@ -655,7 +655,7 @@ fn build_transit_lines( .chain(rel_rows.iter()) .flat_map(|r| r.parts.iter().flat_map(|p| p.iter().copied())) .collect(),- );+ )?; println!("{} node location(s) needed", table.len()); let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 3: nodes", table)?; @@ -883,7 +883,7 @@ fn build_admin_city( // Pass 3: node coordinates. let table = NodeLocations::new( member_refs.values().flat_map(|r| r.iter().copied()).collect(),- );+ )?; println!("{} node location(s) needed", table.len()); let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 3: nodes", table)?;
scripts/maps/osm_ingest/src/nodeloc.rs
diff --git a/scripts/maps/osm_ingest/src/nodeloc.rs b/scripts/maps/osm_ingest/src/nodeloc.rsindex 0b94e2e5f6..b5c8d30c21 100644--- a/scripts/maps/osm_ingest/src/nodeloc.rs+++ b/scripts/maps/osm_ingest/src/nodeloc.rs@@ -4,16 +4,15 @@ //! way geometry is the one thing every layer build does, and it is the one place //! where a careless data structure costs gigabytes. -use std::path::Path;+use std::path::{Path, PathBuf};+use std::sync::atomic; use crate::geojson::Coord; use crate::osm::{visit_block, Element}; use crate::pbf::{self, KIND_NODES};-use crate::proto::Result;+use crate::proto::{Error, Result}; /// Sentinel latitude for "this node's location was never seen".-const NO_LOC: i32 = i32::MIN;- /// Coordinates for a known set of node ids: a compressed id index plus an /// index-aligned coordinate array. ///@@ -37,9 +36,100 @@ const NO_LOC: i32 = i32::MIN; /// scans at most 63 contiguous bytes, which is one or two lines. pub struct NodeLocations { ids: IdIndex,- locs: Vec<(i32, i32)>,+ locs: Locs,+}++/// The coordinate array, in a memory-mapped file rather than on the heap.+///+/// Eight bytes per needed node is 1.23 GB on a California extract, and unlike the ids it will not+/// compress: latitude and longitude in id order are high-entropy, so there is no structure to exploit.+/// What there is instead is locality — materialisation walks ways in id order and a way's nodes sit+/// close together in a PBF — so a mapped file lets the OS keep the working set and nothing else.+///+/// # Resolved-ness is a bitset, not a sentinel+///+/// A fresh mapping reads as zeroes, and `(0, 0)` is a real coordinate, so zero cannot mean+/// "unresolved". Writing `i32::MIN` across the whole file would work and would also dirty every page+/// of 1.23 GB before the pass that fills it, which is most of the cost this exists to avoid. A bit per+/// node is 19 MB, stays in memory, and leaves the mapping untouched until something is actually+/// written to it.+struct Locs {+ map: Option<memmap2::MmapMut>,+ /// One bit per node, set when a coordinate has been written.+ resolved: Vec<u64>,+ /// Deleted on drop. Scratch, and large enough that leaving it behind would matter.+ path: Option<PathBuf>,+ len: usize,+}++impl Locs {+ fn new(len: usize) -> Result<Locs> {+ if len == 0 {+ return Ok(Locs { map: None, resolved: Vec::new(), path: None, len: 0 });+ }+ let path = std::env::temp_dir().join(format!(+ "osm_nodeloc_{}_{}.bin",+ std::process::id(),+ // Distinct per table, so two in one process cannot share a file.+ NEXT_LOCS.fetch_add(1, atomic::Ordering::Relaxed),+ ));+ let bytes = len as u64 * 8;+ let file = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(true)+ .open(&path)+ .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;+ // Sets the length without writing anything: on both platforms this leaves a sparse or+ // zero-filled file, so the 1.23 GB is not touched until a page is used.+ file.set_len(bytes)+ .map_err(|e| Error(format!("cannot size {}: {e}", path.display())))?;+ // SAFETY: this process owns `path` exclusively — it is named after the pid and a counter, was+ // just created with `truncate`, and is deleted in `Drop`. Nothing else can resize it while the+ // mapping is live, which is the one thing that would make the slice dangle.+ let map = unsafe { memmap2::MmapMut::map_mut(&file) }+ .map_err(|e| Error(format!("cannot map {}: {e}", path.display())))?;+ Ok(Locs {+ map: Some(map),+ resolved: vec![0u64; len.div_ceil(64)],+ path: Some(path),+ len,+ })+ }++ fn set(&mut self, index: usize, lat_e7: i32, lon_e7: i32) {+ let Some(map) = self.map.as_mut() else { return };+ let at = index * 8;+ map[at..at + 4].copy_from_slice(&lat_e7.to_le_bytes());+ map[at + 4..at + 8].copy_from_slice(&lon_e7.to_le_bytes());+ self.resolved[index / 64] |= 1 << (index % 64);+ }++ fn get(&self, index: usize) -> Option<(i32, i32)> {+ if index >= self.len || self.resolved[index / 64] & (1 << (index % 64)) == 0 {+ return None;+ }+ let map = self.map.as_ref()?;+ let at = index * 8;+ let lat = i32::from_le_bytes(map[at..at + 4].try_into().expect("four bytes"));+ let lon = i32::from_le_bytes(map[at + 4..at + 8].try_into().expect("four bytes"));+ Some((lat, lon))+ } } +impl Drop for Locs {+ fn drop(&mut self) {+ // The mapping goes before the file, or Windows refuses the delete.+ self.map = None;+ if let Some(path) = self.path.take() {+ let _ = std::fs::remove_file(path);+ }+ }+}++static NEXT_LOCS: atomic::AtomicU64 = atomic::AtomicU64::new(0);+ /// Ids per block of [`IdIndex`]. /// /// The trade is the usual one: a larger block amortises its 12 bytes of base and offset over more@@ -148,16 +238,19 @@ fn get_uvarint(bytes: &[u8]) -> (u64, usize) { impl NodeLocations { /// `ids` need not be sorted or unique; both are done here.- pub fn new(mut ids: Vec<i64>) -> NodeLocations {+ ///+ /// Fallible because the coordinate array is a mapped file, and a temporary directory that is full+ /// or read-only is a real thing to report rather than to panic on.+ pub fn new(mut ids: Vec<i64>) -> Result<NodeLocations> { ids.sort_unstable(); ids.dedup(); let index = IdIndex::build(&ids); // The plain vector goes here rather than being kept alongside: it is 8 bytes per id against // the index's ~1.2, and holding both would give back the saving. Freed before the coordinate- // array is allocated, so the two never peak together.+ // array is mapped, so the two never peak together. drop(ids);- let locs = vec![(NO_LOC, NO_LOC); index.len()];- NodeLocations { ids: index, locs }+ let locs = Locs::new(index.len())?;+ Ok(NodeLocations { ids: index, locs }) } pub fn len(&self) -> usize {@@ -173,8 +266,7 @@ impl NodeLocations { } pub fn get(&self, id: i64) -> Option<(i32, i32)> {- let (lat, lon) = self.locs[self.index_of(id)? as usize];- (lat != NO_LOC).then_some((lat, lon))+ self.locs.get(self.index_of(id)? as usize) } /// A way's geometry in lon/lat order, with unresolved refs skipped.@@ -213,7 +305,7 @@ pub fn resolve_nodes( if table.is_empty() { return Ok(table); }- // Moved out so the workers can search it while the sink writes to `locs`; put back below.+ // Moved out so the workers can search it while the sink writes coordinates; put back below. let ids = std::mem::take(&mut table.ids); let locs = &mut table.locs; pbf::run_pass_sink(@@ -237,7 +329,7 @@ pub fn resolve_nodes( }, |chunk| { for (idx, lat, lon) in chunk {- locs[idx as usize] = (lat, lon);+ locs.set(idx as usize, lat, lon); } Ok(()) },@@ -366,12 +458,12 @@ mod tests { // The point of the pattern: memory is O(needed), so ids can be as large as // OSM's real ones without allocating anything proportional to them. let huge = 12_345_678_901i64;- let mut table = NodeLocations::new(vec![huge, 5, 5, 1]);+ let mut table = NodeLocations::new(vec![huge, 5, 5, 1]).expect("map the coordinate file"); assert_eq!(table.len(), 3, "sorted and deduped"); assert_eq!(table.get(5), None, "unresolved until the node pass fills it"); // Fill by index, as the merge does. let idx = table.index_of(5).unwrap() as usize;- table.locs[idx] = (377_900_000, -1_224_200_000);+ table.locs.set(idx, 377_900_000, -1_224_200_000); assert_eq!(table.get(5), Some((377_900_000, -1_224_200_000))); assert_eq!(table.get(huge), None); assert_eq!(table.get(999), None, "not in the table at all");@@ -381,10 +473,10 @@ mod tests { fn an_unresolved_ref_leaves_a_gap_rather_than_dropping_the_way() { // An extract that cuts through a way leaves some of its nodes out of the // file. Keeping the rest is what osmium's complete_ways produces too.- let mut table = NodeLocations::new(vec![1, 2, 3]);+ let mut table = NodeLocations::new(vec![1, 2, 3]).expect("map the coordinate file"); for (id, lat, lon) in [(1i64, 370_000_000, -1_220_000_000), (3, 370_020_000, -1_220_020_000)] { let idx = table.index_of(id).unwrap() as usize;- table.locs[idx] = (lat, lon);+ table.locs.set(idx, lat, lon); } let line = table.line(&[1, 2, 3]); assert_eq!(line.len(), 2, "the middle vertex is missing, not the way");