mamaps: rework tile build for speed - us-west 430s to 157s
- Commit
0fff85fa80bea241854c859640c04285b11834ff- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-31 16:12 UTC (3 months ago)
- Parents
cfd0999
Diff
library/tilecodec/src/main/rust/src/mamaps/body.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body.rs b/library/tilecodec/src/main/rust/src/mamaps/body.rsindex dd47690e3a..9e39ca4095 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body.rs@@ -371,8 +371,29 @@ pub(crate) fn align4(at: usize) -> usize { /// /// Deliberately available without the `write` feature: a synthetic body is how the reader's own /// tests get something to read, and `mamaps_dump` round-trips one to check a body is sane.-pub fn serialize(body: &Body) -> Result<Vec<u8>> {- let mut layers = body.layers.clone();+/// Reusable buffers for [`serialize_into`].+///+/// One per worker, not one per tile. Serialising allocated a payload `Vec` per layer plus the+/// output `Vec` per tile, and on a us-west z14 build across 64 threads that allocation traffic --+/// not the encoding -- was the cost: measured with the encode pass split three ways, serialisation+/// took 20.9 s of CPU at 16 threads and 1120 s at 64, while DEFLATE over the same work merely+/// doubled. Encode wall time was *lower* at 16 threads than at 64. Buffers that outlive a tile take+/// the allocator out of the loop.+#[derive(Default)]+pub struct Scratch {+ payloads: Vec<Vec<u8>>,+ meta: Vec<(u8, u16)>,+ out: Vec<u8>,+}++/// Serialise a body into `scratch`, returning the bytes it holds.+///+/// Byte for byte what [`serialize`] returns; that function is this one with a fresh [`Scratch`].+pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [u8]> {+ // Borrowed and sorted by reference, never cloned. Cloning to sort copied every layer's whole+ // coordinate arena per tile, which is 2.5 GB of memcpy on a us-west z14 build. Nothing here+ // mutates a layer, so the sort only ever needed the order.+ let mut layers: Vec<&Layer> = body.layers.iter().collect(); // Ascending by id, which the parser requires and `Body::layer` assumes. Sorted rather than // rejected, because a caller assembling a tile per style layer has no reason to care. layers.sort_by_key(|l| l.layer_id);@@ -425,9 +446,26 @@ pub fn serialize(body: &Body) -> Result<Vec<u8>> { } let index_end = BODY_HEADER_LEN + layers.len() * LAYER_INDEX_LEN;- let mut payloads: Vec<(u8, u16, Vec<u8>)> = Vec::with_capacity(layers.len());- for layer in &layers {- let mut out = Vec::new();+ // Both fields at once, which needs the struct broken apart: the payloads are built first and+ // then copied into the output, and each wants its own mutable borrow.+ let Scratch { payloads, meta, out: assembled } = scratch;+ meta.clear();+ for (i, layer) in layers.iter().enumerate() {+ if i >= payloads.len() {+ payloads.push(Vec::new());+ }+ let out = &mut payloads[i];+ out.clear();+ // Sized up front rather than doubled into. Feature and part records are fixed width, and+ // two zigzag varints average under three bytes a point on clipped tile geometry -- an+ // estimate that is allowed to be wrong, because the only cost of being wrong is the growth+ // this avoids in the common case. On a reused buffer it is usually already large enough.+ out.reserve(+ layer.features.len() * FEATURE_RECORD_LEN+ + layer.parts.len() * PART_ENTRY_LEN+ + layer.coords.len() * 3+ + 4,+ ); for feature in &layer.features { out.extend_from_slice(&feature.kind.to_le_bytes()); out.extend_from_slice(&feature.kind_detail.to_le_bytes());@@ -448,49 +486,69 @@ pub fn serialize(body: &Body) -> Result<Vec<u8>> { } // The arena, in parts-table order. Deltas restart at each part so a part decodes // independently and a long line accumulates nothing.- let mut writer = crate::proto::Writer::new();+ //+ // Written straight into `out` rather than through a `proto::Writer` and copied: the writer+ // is a `Vec<u8>` with a varint method, so routing through one bought a second allocation+ // and a second pass over every coordinate in the archive. for part in &layer.parts { let (mut px, mut py) = (0i32, 0i32); for &(x, y) in layer.points(part) {- writer.uvarint(crate::proto::zigzag_encode(x as i64 - px as i64));- writer.uvarint(crate::proto::zigzag_encode(y as i64 - py as i64));+ push_uvarint(out, crate::proto::zigzag_encode(x as i64 - px as i64));+ push_uvarint(out, crate::proto::zigzag_encode(y as i64 - py as i64)); (px, py) = (x as i32, y as i32); } }- out.extend_from_slice(writer.as_slice());- payloads.push((layer.layer_id, layer.features.len() as u16, out));+ meta.push((layer.layer_id, layer.features.len() as u16)); } let mut offset = align4(index_end);- let mut index = Vec::with_capacity(layers.len() * LAYER_INDEX_LEN);- for (layer_id, feature_count, payload) in &payloads {- index.push(*layer_id);- index.push(0);- index.extend_from_slice(&feature_count.to_le_bytes());- index.extend_from_slice(&(offset as u32).to_le_bytes());- index.extend_from_slice(&(payload.len() as u32).to_le_bytes());- offset += payload.len();- }-- let mut out = Vec::with_capacity(offset);- out.extend_from_slice(b"MBD");- out.push(super::header::FORMAT_VERSION);+ assembled.clear();+ assembled.reserve(index_end + payloads[..layers.len()].iter().map(Vec::len).sum::<usize>() + 4);+ assembled.extend_from_slice(b"MBD");+ assembled.push(super::header::FORMAT_VERSION); // Patched below, once the length is known.- out.extend_from_slice(&0u32.to_le_bytes());- out.extend_from_slice(&body.extent.to_le_bytes());- out.push(layers.len() as u8);- out.push(0);- out.extend_from_slice(&0u32.to_le_bytes());- out.extend_from_slice(&index);- while out.len() % 4 != 0 {- out.push(0);- }- for (_, _, payload) in &payloads {- out.extend_from_slice(payload);- }- let raw_len = out.len() as u32;- out[4..8].copy_from_slice(&raw_len.to_le_bytes());- Ok(out)+ assembled.extend_from_slice(&0u32.to_le_bytes());+ assembled.extend_from_slice(&body.extent.to_le_bytes());+ assembled.push(layers.len() as u8);+ assembled.push(0);+ assembled.extend_from_slice(&0u32.to_le_bytes());+ for (i, (layer_id, feature_count)) in meta.iter().enumerate() {+ assembled.push(*layer_id);+ assembled.push(0);+ assembled.extend_from_slice(&feature_count.to_le_bytes());+ assembled.extend_from_slice(&(offset as u32).to_le_bytes());+ assembled.extend_from_slice(&(payloads[i].len() as u32).to_le_bytes());+ offset += payloads[i].len();+ }+ while assembled.len() % 4 != 0 {+ assembled.push(0);+ }+ for payload in &payloads[..layers.len()] {+ assembled.extend_from_slice(payload);+ }+ let raw_len = assembled.len() as u32;+ assembled[4..8].copy_from_slice(&raw_len.to_le_bytes());+ Ok(assembled)+}++/// Serialise a body to a fresh buffer. [`serialize_into`] is the same thing with the buffer reused.+pub fn serialize(body: &Body) -> Result<Vec<u8>> {+ let mut scratch = Scratch::default();+ serialize_into(body, &mut scratch).map(<[u8]>::to_vec)+}++/// One unsigned LEB128 varint, appended.+///+/// The same encoding [`crate::proto::Writer::uvarint`] writes, spelled out here so the arena can go+/// straight into the payload buffer. Byte for byte identical by construction: seven bits at a time,+/// low group first, continuation bit on every group but the last.+#[inline]+fn push_uvarint(out: &mut Vec<u8>, mut value: u64) {+ while value >= 0x80 {+ out.push((value as u8) | 0x80);+ value >>= 7;+ }+ out.push(value as u8); } #[cfg(test)]
library/tilecodec/src/main/rust/src/mamaps/write.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write.rs b/library/tilecodec/src/main/rust/src/mamaps/write.rsindex c37043c988..82e4517ad7 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -128,13 +128,10 @@ pub struct StreamWriter { /// accumulated in memory here. data: Spill, /// One per stored body, ascending by tile id, partitioned into leaves at `finish`.- ///- /// The [`LeafEntry::offset_delta`] here is still **absolute** within the data section; it is- /// rebased onto its leaf's `base_data_offset` by [`Self::partition`].- entries: Vec<(u64, LeafEntry)>,+ entries: Vec<Pending>, /// `(hash, stored length) -> offsets already written`. Several per key only on a collision, /// which is why it is a list. Probed, never iterated.- seen: HashMap<(u64, u32), Vec<u32>>,+ seen: HashMap<(u64, u32), Vec<u64>>, last_id: Option<u64>, /// The stored bytes of the body `entries.last()` points at, which is what a run-length compare /// is against.@@ -153,6 +150,39 @@ pub struct StreamWriter { runs_used: bool, } +/// One stored body's index entry, before it knows which leaf it belongs to.+///+/// Deliberately not a [`LeafEntry`]: that type's `offset_delta` is 32-bit *relative to its leaf's*+/// `base_data_offset`, which is exactly what makes the format hold a data section past 4 GiB. Holding+/// an absolute offset in that field meant the writer could not build one -- a north-america z13+/// archive stopped at `a .mamaps data section past 4 GiB needs a wider offset field` after 56 minutes+/// of work, on a limit the format does not actually have. The narrowing belongs at+/// [`StreamWriter::partition`], where the leaf base is known.+struct Pending {+ tile_id: u64,+ /// Absolute within the data section.+ offset: u64,+ run_length: u32,+ length: u32,+}++/// A root index and its leaves, as [`StreamWriter::partition`] produces them.+type Split = (Vec<RootEntry>, Vec<Vec<LeafEntry>>);++/// How far back content dedup may point, in bytes of the data section.+///+/// [`LeafEntry::offset_delta`] is 32-bit relative to its leaf's `base_data_offset`, and that base is+/// the **minimum** offset in the leaf because dedup lets a tile reuse a body written for an earlier+/// one. So a leaf late in a large archive that reuses a body from the very beginning would need a+/// delta of the whole archive -- past 4 GiB on a north-america z13 build, which no `u32` holds.+///+/// Bounding the reach bounds the delta: every offset in a leaf is then within `MAX_DEDUP_REACH` of+/// the write head when that leaf was written, so the span cannot approach 4 GiB. The cost is a+/// re-appended body when a match is older than this, and it is small in practice because tile ids are+/// Hilbert-ordered -- tiles that share a body are neighbours, and neighbours are written close+/// together.+const MAX_DEDUP_REACH: u64 = 2 << 30;+ impl StreamWriter { pub fn new(options: Options) -> Result<StreamWriter> { if options.min_zoom > options.max_zoom || options.max_zoom > MAX_ZOOM {@@ -256,14 +286,14 @@ impl StreamWriter { // Run-length first: a consecutive repeat needs no dedup lookup and no new entry at all. // The compare is against `last_body` rather than the spill, because the bytes the last // entry points at are the one body always worth keeping to hand.- if let Some((previous_id, previous)) = self.entries.last_mut() {+ if let Some(previous) = self.entries.last_mut() { debug_assert!(- self.data.matches_at(previous.offset_delta, &self.last_body)?,+ self.data.matches_at(previous.offset, &self.last_body)?, "last_body must be the bytes the last entry points at, or the shortcut below is \ answering for a body that is not there", ); if previous.length == length- && *previous_id + previous.run_length as u64 == tile_id+ && previous.tile_id + previous.run_length as u64 == tile_id && self.last_body == stored { previous.run_length += 1;@@ -278,7 +308,13 @@ impl StreamWriter { let StreamWriter { seen, data, distinct, .. } = &mut *self; let bucket = seen.entry(key).or_default(); let mut hit = None;+ let head = data.len(); for &at in bucket.iter() {+ // Too far back to be addressable from a leaf that ends here. Skipped rather than+ // matched, so the body is written again and the delta stays inside a `u32`.+ if head - at > MAX_DEDUP_REACH {+ continue;+ } if data.matches_at(at, &stored)? { hit = Some(at); break;@@ -287,21 +323,14 @@ impl StreamWriter { let offset = match hit { Some(at) => at, None => {- let at = u32::try_from(data.len()).map_err(|_| {- crate::proto::Error(- "a .mamaps data section past 4 GiB needs a wider offset field".to_string(),- )- })?;+ let at = data.len(); data.append(&stored)?; bucket.push(at); *distinct += 1; at } };- self.entries.push((- tile_id,- LeafEntry { tile_id_lo: 0, run_length: 1, offset_delta: offset, length },- ));+ self.entries.push(Pending { tile_id, offset, run_length: 1, length }); self.last_body.clear(); self.last_body.extend_from_slice(stored); Ok(())@@ -380,16 +409,15 @@ impl StreamWriter { // entries per leaf; a root that still does not fit is a build failure, never a silent // third round trip charged to every reader forever. let (root, leaves) = loop {- match self.partition(capacity) {- Some(split) => {- let root_len = split.0.len() * index::ROOT_ENTRY_LEN;- if HEADER_LEN + dictionary.len() + root_len <= OPEN_PREFIX_BYTES as usize {- break split;- }+ // A `None` is a leaf whose tile-id span will not fit a `u32`. A wider leaf spans more+ // ids, not fewer, so growing the capacity does not fix that one -- it runs out at the+ // cap below and reports. Kept distinct from the root-too-large case because the two want+ // opposite things from the capacity and a future fix has to choose between them.+ if let Some(split) = self.partition(capacity)? {+ let root_len = split.0.len() * index::ROOT_ENTRY_LEN;+ if HEADER_LEN + dictionary.len() + root_len <= OPEN_PREFIX_BYTES as usize {+ break split; }- // A leaf whose tile-id span will not fit a `u32`. Splitting further makes each- // leaf narrower, which is the fix.- None => {} } if capacity >= 1 << 24 { return err(format!(@@ -458,28 +486,37 @@ impl StreamWriter { /// Chop the entries into leaves of at most `capacity`, rebasing each leaf's ids and offsets. /// /// `None` when some leaf's tile-id span will not fit the `u32` a [`LeafEntry::tile_id_lo`]- /// carries. That is a real possibility at a deep zoom with a large capacity, and truncating it- /// would put a body at the wrong tile with no diagnostic at all -- so the caller splits instead.- fn partition(&self, capacity: u32) -> Option<(Vec<RootEntry>, Vec<Vec<LeafEntry>>)> {+ /// carries, which the caller answers by choosing a different capacity. `Err` when a leaf's+ /// data-offset span will not fit [`LeafEntry::offset_delta`], which no capacity fixes and which+ /// [`MAX_DEDUP_REACH`] exists to make unreachable -- so it is reported rather than retried.+ /// Truncating either would put a body at the wrong tile or the wrong offset with no diagnostic.+ fn partition(&self, capacity: u32) -> Result<Option<Split>> { let mut root = Vec::new(); let mut leaves = Vec::new(); for chunk in self.entries.chunks(capacity as usize) {- let (base_tile_id, _) = chunk[0];+ let base_tile_id = chunk[0].tile_id; // The **minimum** offset in the chunk, not the first. Content dedup lets a tile in // this leaf point at a body written for an earlier one, so basing on the first entry // would make that delta negative.- let base_data_offset =- chunk.iter().map(|(_, e)| e.offset_delta).min().unwrap_or(0) as u64;- let (last_id, last) = chunk[chunk.len() - 1];- if !index::span_fits(last_id + last.run_length as u64 - 1 - base_tile_id) {- return None;+ let base_data_offset = chunk.iter().map(|e| e.offset).min().unwrap_or(0);+ let last = &chunk[chunk.len() - 1];+ if !index::span_fits(last.tile_id + last.run_length as u64 - 1 - base_tile_id) {+ return Ok(None); } let mut leaf = Vec::with_capacity(chunk.len());- for (tile_id, entry) in chunk {+ for entry in chunk {+ let delta = u32::try_from(entry.offset - base_data_offset).map_err(|_| {+ crate::proto::Error(format!(+ "a .mamaps leaf spans {} bytes of the data section, past the {} a leaf entry \+ addresses",+ entry.offset - base_data_offset,+ u32::MAX,+ ))+ })?; leaf.push(LeafEntry {- tile_id_lo: (tile_id - base_tile_id) as u32,+ tile_id_lo: (entry.tile_id - base_tile_id) as u32, run_length: entry.run_length,- offset_delta: entry.offset_delta - base_data_offset as u32,+ offset_delta: delta, length: entry.length, }); }@@ -491,7 +528,7 @@ impl StreamWriter { }); leaves.push(leaf); }- Some((root, leaves))+ Ok(Some((root, leaves))) } } @@ -582,7 +619,7 @@ impl Spill { /// /// The compare that makes a content-dedup hit a fact rather than a probability. Answered out of /// the buffer when the body is still in it, which costs nothing at all.- fn matches_at(&mut self, offset: u32, candidate: &[u8]) -> Result<bool> {+ fn matches_at(&mut self, offset: u64, candidate: &[u8]) -> Result<bool> { let start = offset as u64; let end = start + candidate.len() as u64; debug_assert!(end <= self.len(), "a dedup candidate past the end of the data section");
scripts/maps/mamaps_build/Cargo.lock
diff --git a/scripts/maps/mamaps_build/Cargo.lock b/scripts/maps/mamaps_build/Cargo.lockindex 4929cab808..a788550dbf 100644--- a/scripts/maps/mamaps_build/Cargo.lock+++ b/scripts/maps/mamaps_build/Cargo.lock@@ -8,6 +8,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]]+name = "cc"+version = "1.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273"+dependencies = [+ "find-msvc-tools",+ "shlex",+]+ [[package]] name = "crossbeam-deque" version = "0.8.7"@@ -39,16 +49,32 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +[[package]]+name = "find-msvc-tools"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"+ [[package]] name = "libc" version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]]+name = "libmimalloc-sys"+version = "0.1.49"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"+dependencies = [+ "cc",+]+ [[package]] name = "mamaps_build" version = "0.1.0" dependencies = [+ "mimalloc", "osm_ingest", "rayon", "tile_build",@@ -64,6 +90,15 @@ dependencies = [ "libc", ] +[[package]]+name = "mimalloc"+version = "0.1.52"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862"+dependencies = [+ "libmimalloc-sys",+]+ [[package]] name = "miniz_oxide" version = "0.8.9"@@ -102,6 +137,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+ [[package]] name = "tile_build" version = "0.1.0"
scripts/maps/mamaps_build/Cargo.toml
diff --git a/scripts/maps/mamaps_build/Cargo.toml b/scripts/maps/mamaps_build/Cargo.tomlindex ed8cc1dff4..88f5c0cd51 100644--- a/scripts/maps/mamaps_build/Cargo.toml+++ b/scripts/maps/mamaps_build/Cargo.toml@@ -36,6 +36,10 @@ osm_ingest = { path = "../osm_ingest" } # a name to link and not a crate to fetch. The tiler runs on `tile_build::par`'s # pool, which is where `--threads` and `MAPS_THREADS` are honoured. rayon = "1"+# The allocator. See `main.rs` for why a build tool takes a dependency on one.+# `default-features = false` drops mimalloc's own secure-hardening and stats builds:+# this is a batch tool over a file it just parsed itself, not a network service.+mimalloc = { version = "0.1", default-features = false } [profile.release] opt-level = 3
scripts/maps/mamaps_build/src/coalesce.rs
diff --git a/scripts/maps/mamaps_build/src/coalesce.rs b/scripts/maps/mamaps_build/src/coalesce.rsnew file mode 100644index 0000000000..88f4ca1ddd--- /dev/null+++ b/scripts/maps/mamaps_build/src/coalesce.rs@@ -0,0 +1,471 @@+//! Merging a layer's line features into one per class, and joining the fragments that continue each+//! other.+//!+//! # Why this exists+//!+//! An OSM way is an **editing** unit. It is split at every junction, bridge, surface change and tag+//! edit, none of which has anything to do with what gets drawn. Carrying one way as one rendering+//! feature therefore pays a feature header and a part entry for each fragment of a road, and on a+//! us-west z7 tile that came to:+//!+//! | | count | width | bytes |+//! |---|---|---|---|+//! | feature records | 57,218 | 16 | 916 KB |+//! | part entries | 57,218 | 12 | 687 KB |+//! | coordinate arena | 189,484 points | ~2-3 | ~0.5 MB |+//!+//! Three quarters of the layer was bookkeeping, 61% of its parts held exactly two points, and the+//! mean was 3.31 points per part. The same tile's `boundaries` layer -- whose relations arrive+//! already merged -- ran 139 features over 667 parts, which is what healthy looks like.+//!+//! It compounds three ways. The headers are the obvious cost. Less obvious is that+//! [`tilecodec::mamaps::body`] restarts its coordinate deltas at every part so a part decodes+//! independently, so at 3.3 points per part most points are the *first* of their part and pay a full+//! absolute coordinate where a continued line would pay one byte. And a `.mamaps` layer indexes its+//! features with a `u16`, so a North America build stopped outright at `layer 4 has 79407 features,+//! past the 65535 a .mamaps body can index`.+//!+//! This is not a container-format problem -- MVT has the same one, which is why `tippecanoe` ships+//! `--coalesce`. It is that nothing in this pipeline ever merged what OSM had split.+//!+//! # What it does+//!+//! Two steps, and the first is the one that matters for the `u16`:+//!+//! 1. **Group by class.** Line features drawn identically -- same `kind`, `kind_detail` and `flags`+//! -- become one multi-part feature. Nothing about the geometry changes; a `.mamaps` line feature+//! has always been able to hold many parts, and `boundaries` already did.+//! 2. **Join what continues.** Within a group, a part whose last point is another's first point is+//! the same line cut in half, so they are spliced into one part. That removes the part entry and+//! lets the delta run through the joint instead of restarting.+//!+//! # Why it is safe+//!+//! A `.mamaps` feature carries no identity of its own: [`Feature`] is `kind`, `kind_detail`,+//! `geom_type`, `flags` and a part range, and nothing else. Two line features with the same first+//! three fields are indistinguishable to a renderer, so merging them cannot change a pixel. There+//! are no names or ids on a feature to lose, and `winding` is meaningless on an open path -- which+//! [`crate::rings::normalise`] states outright.+//!+//! Direction is not preserved through a join and does not need to be: nothing in+//! [`tilecodec::mamaps::body`]'s flag set reads a line's direction, so `A -> B` and `B -> A` draw+//! the same. Joins are made head-to-tail only, so a part is never reversed anyway.+//!+//! # Ordering, and why the archive stays reproducible+//!+//! Called on a tile that the merge has already assembled, so it sees a layer's features in the order+//! the store yielded them, and it emits each class at the position of that class's **first** feature.+//! A group's parts stay in feature-then-part order and chains are built by walking them in that+//! order, so nothing here depends on a hash map's iteration order or on how the map phase chunked+//! its input.++use std::collections::HashMap;++use tilecodec::mamaps::body::{Layer, Part, GEOM_LINE, WINDING_OUTER};++/// What coalescing a build saved, for the report.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+pub struct Stats {+ pub features_before: u64,+ pub features_after: u64,+ pub parts_before: u64,+ pub parts_after: u64,+}++impl Stats {+ pub fn add(&mut self, other: Stats) {+ self.features_before += other.features_before;+ self.features_after += other.features_after;+ self.parts_before += other.parts_before;+ self.parts_after += other.parts_after;+ }+}++/// What makes two line features interchangeable to a renderer.+type Class = (u16, u16, u8);++/// One line part, as `(coord_start, point_count)` into a layer's existing arena.+///+/// Indices rather than copied points: a group can hold tens of thousands of parts, and a `Vec` of+/// points each would be the allocation this module exists to remove.+type Span = (u32, u32);++/// The spans of one continuous polyline, in the order they join.+type Run = Vec<Span>;++/// Merge a layer's line features by class and splice the parts that continue each other.+///+/// Polygon features are left exactly as they were, in place; only the parts table and the arena are+/// rebuilt around them, which [`crate::rings::normalise`] does immediately afterwards anyway.+pub fn coalesce_lines(layer: &mut Layer) -> Stats {+ let mut stats = Stats {+ features_before: layer.features.len() as u64,+ parts_before: layer.parts.len() as u64,+ ..Stats::default()+ };+ let lines = layer.features.iter().filter(|f| f.geom_type == GEOM_LINE).count();+ // One line feature cannot be merged with anything, and a layer of pure polygons is the common+ // case: both would only pay for a rebuild that changes nothing.+ if lines < 2 {+ stats.features_after = stats.features_before;+ stats.parts_after = stats.parts_before;+ return stats;+ }++ // Every line part, grouped by class, in feature-then-part order.+ let mut order: Vec<Class> = Vec::new();+ let mut group_of: HashMap<Class, usize> = HashMap::new();+ let mut groups: Vec<Vec<Span>> = Vec::new();+ for feature in &layer.features {+ if feature.geom_type != GEOM_LINE {+ continue;+ }+ let class = (feature.kind, feature.kind_detail, feature.flags);+ let at = *group_of.entry(class).or_insert_with(|| {+ order.push(class);+ groups.push(Vec::new());+ groups.len() - 1+ });+ let from = feature.parts_offset as usize;+ for part in &layer.parts[from..from + feature.part_count as usize] {+ groups[at].push((part.coord_start, part.point_count));+ }+ }++ // Chains first, so the arena can be laid down in one pass below.+ let chains: Vec<Vec<Run>> =+ groups.iter().map(|parts| chain(parts, &layer.coords)).collect();++ let mut features = Vec::with_capacity(layer.features.len() - lines + order.len());+ let mut parts: Vec<Part> = Vec::with_capacity(layer.parts.len());+ let mut coords: Vec<(i16, i16)> = Vec::with_capacity(layer.coords.len());+ let mut emitted: Vec<bool> = vec![false; order.len()];++ for feature in &layer.features {+ if feature.geom_type != GEOM_LINE {+ // Copied through at its original position, so a mixed layer keeps its feature order.+ let from = feature.parts_offset as usize;+ let start = parts.len() as u32;+ for part in &layer.parts[from..from + feature.part_count as usize] {+ let points = points_of(&layer.coords, *part);+ parts.push(Part {+ coord_start: coords.len() as u32,+ point_count: points.len() as u32,+ winding: part.winding,+ });+ coords.extend_from_slice(points);+ }+ let mut copy = *feature;+ copy.parts_offset = start;+ features.push(copy);+ continue;+ }+ let class = (feature.kind, feature.kind_detail, feature.flags);+ let at = group_of[&class];+ if emitted[at] {+ continue;+ }+ emitted[at] = true;+ let start = parts.len() as u32;+ for run in &chains[at] {+ let first = coords.len() as u32;+ for (i, &(coord_start, point_count)) in run.iter().enumerate() {+ let points = points_of(+ &layer.coords,+ Part { coord_start, point_count, winding: WINDING_OUTER },+ );+ // The joint is one point in two parts; the second copy would be a zero-length+ // segment and `geom::quantize` is no longer around to drop it.+ let points = if i == 0 { points } else { &points[1..] };+ coords.extend_from_slice(points);+ }+ parts.push(Part {+ coord_start: first,+ point_count: coords.len() as u32 - first,+ winding: WINDING_OUTER,+ });+ }+ let mut merged = *feature;+ merged.parts_offset = start;+ merged.part_count = parts.len() as u32 - start;+ features.push(merged);+ }++ layer.features = features;+ layer.parts = parts;+ layer.coords = coords;+ stats.features_after = layer.features.len() as u64;+ stats.parts_after = layer.parts.len() as u64;+ stats+}++fn points_of(coords: &[(i16, i16)], part: Part) -> &[(i16, i16)] {+ let at = part.coord_start as usize;+ &coords[at..at + part.point_count as usize]+}++/// Group `parts` into runs that each form one continuous polyline.+///+/// Head-to-tail only: a part joins the chain when its first point is the chain's last. Parts are+/// never reversed, so the result is a subset of the joins a reversing walk would find -- and it is+/// the subset that needs no argument about direction.+///+/// Chains start at parts nothing runs into, so a road is grown from its end rather than from its+/// middle; only then are the leftovers taken, which is what closes a ring road onto itself. Both+/// loops walk `parts` in order, so the output does not depend on the hash map.+fn chain(parts: &[Span], coords: &[(i16, i16)]) -> Vec<Run> {+ let ends: Vec<((i16, i16), (i16, i16))> = parts+ .iter()+ .map(|&(coord_start, point_count)| {+ let points = points_of(coords, Part { coord_start, point_count, winding: WINDING_OUTER });+ // A part with nothing in it cannot join anything; a sentinel keeps the index aligned.+ match (points.first(), points.last()) {+ (Some(a), Some(b)) => (*a, *b),+ _ => ((i16::MIN, i16::MIN), (i16::MAX, i16::MAX)),+ }+ })+ .collect();++ let mut by_start: HashMap<(i16, i16), Vec<usize>> = HashMap::new();+ for (i, (first, _)) in ends.iter().enumerate() {+ by_start.entry(*first).or_default().push(i);+ }+ // Whether anything ends where this part starts. A part that nothing runs into is a chain head.+ let mut continued = vec![false; parts.len()];+ for (_, last) in &ends {+ if let Some(hits) = by_start.get(last) {+ for &i in hits {+ continued[i] = true;+ }+ }+ }++ let mut used = vec![false; parts.len()];+ let mut out: Vec<Run> = Vec::new();+ let grow = |from: usize, used: &mut Vec<bool>, out: &mut Vec<Run>| {+ let mut run: Run = vec![parts[from]];+ used[from] = true;+ let mut tail = ends[from].1;+ while let Some(next) =+ by_start.get(&tail).and_then(|hits| hits.iter().copied().find(|&j| !used[j]))+ {+ used[next] = true;+ run.push(parts[next]);+ tail = ends[next].1;+ }+ out.push(run);+ };+ for i in 0..parts.len() {+ if !used[i] && !continued[i] {+ grow(i, &mut used, &mut out);+ }+ }+ // Whatever is left is a cycle: every part in it is continued by another, so none is a head.+ for i in 0..parts.len() {+ if !used[i] {+ grow(i, &mut used, &mut out);+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use tilecodec::mamaps::body::{Feature, GEOM_POLYGON};++ /// One fixture feature: `(kind, geom_type, [part, ...])`, each part a list of points.+ type Fixture = (u16, u8, Vec<Vec<(i16, i16)>>);++ /// Build a layer from a list of fixture features.+ fn layer_of(features: &[Fixture]) -> Layer {+ let mut layer = Layer::new(4);+ for (kind, geom_type, parts) in features {+ let parts_offset = layer.parts.len() as u32;+ for points in parts {+ layer.parts.push(Part {+ coord_start: layer.coords.len() as u32,+ point_count: points.len() as u32,+ winding: WINDING_OUTER,+ });+ layer.coords.extend_from_slice(points);+ }+ layer.features.push(Feature {+ kind: *kind,+ kind_detail: 0,+ geom_type: *geom_type,+ flags: 0,+ parts_offset,+ part_count: parts.len() as u32,+ });+ }+ layer+ }++ /// Every part's points, so a test can compare geometry without caring how it is grouped.+ fn all_parts(layer: &Layer) -> Vec<Vec<(i16, i16)>> {+ layer+ .parts+ .iter()+ .map(|p| points_of(&layer.coords, *p).to_vec())+ .collect()+ }++ /// The arena must be tiled exactly by the parts table, in order, or the encoder rejects the+ /// body. Asserted on every result below, because it is the invariant easiest to break here.+ fn assert_arena_is_tiled(layer: &Layer) {+ let mut at = 0u32;+ for part in &layer.parts {+ assert_eq!(part.coord_start, at, "parts must tile the arena with no gaps");+ at += part.point_count;+ }+ assert_eq!(at as usize, layer.coords.len(), "the arena must end where the parts do");+ for feature in &layer.features {+ let end = feature.parts_offset as usize + feature.part_count as usize;+ assert!(end <= layer.parts.len(), "a feature indexes past the parts table");+ assert!(feature.part_count > 0, "a feature with no parts draws nothing");+ }+ }++ #[test]+ fn features_of_one_class_become_one_feature() {+ // Four disjoint fragments of the same class: one feature, four parts, same geometry.+ let mut layer = layer_of(&[+ (7, GEOM_LINE, vec![vec![(0, 0), (1, 1)]]),+ (7, GEOM_LINE, vec![vec![(10, 10), (11, 11)]]),+ (7, GEOM_LINE, vec![vec![(20, 20), (21, 21)]]),+ (7, GEOM_LINE, vec![vec![(30, 30), (31, 31)]]),+ ]);+ let before = all_parts(&layer);+ let stats = coalesce_lines(&mut layer);+ assert_arena_is_tiled(&layer);+ assert_eq!(layer.features.len(), 1);+ assert_eq!(layer.features[0].part_count, 4);+ assert_eq!(all_parts(&layer), before, "nothing disjoint may be joined");+ assert_eq!(stats, Stats { features_before: 4, features_after: 1, parts_before: 4, parts_after: 4 });+ }++ #[test]+ fn different_classes_stay_apart() {+ let mut layer = layer_of(&[+ (7, GEOM_LINE, vec![vec![(0, 0), (1, 1)]]),+ (9, GEOM_LINE, vec![vec![(1, 1), (2, 2)]]),+ (7, GEOM_LINE, vec![vec![(5, 5), (6, 6)]]),+ ]);+ coalesce_lines(&mut layer);+ assert_arena_is_tiled(&layer);+ assert_eq!(layer.features.len(), 2, "two classes, two features");+ assert_eq!(layer.features[0].kind, 7, "the first class keeps the first position");+ assert_eq!(layer.features[1].kind, 9);+ // Class 9 touches class 7's endpoint but must not be spliced onto it.+ assert_eq!(layer.features[1].part_count, 1);+ }++ #[test]+ fn fragments_that_continue_each_other_are_spliced() {+ // Three pieces of one road, given out of order, plus a fourth that is elsewhere.+ let mut layer = layer_of(&[+ (7, GEOM_LINE, vec![vec![(0, 0), (1, 0)]]),+ (7, GEOM_LINE, vec![vec![(2, 0), (3, 0)]]),+ (7, GEOM_LINE, vec![vec![(1, 0), (2, 0)]]),+ (7, GEOM_LINE, vec![vec![(50, 50), (51, 50)]]),+ ]);+ let stats = coalesce_lines(&mut layer);+ assert_arena_is_tiled(&layer);+ assert_eq!(layer.features.len(), 1);+ assert_eq!(stats.parts_before, 4);+ assert_eq!(stats.parts_after, 2, "three joined into one, plus the far piece");+ let parts = all_parts(&layer);+ assert!(+ parts.contains(&vec![(0, 0), (1, 0), (2, 0), (3, 0)]),+ "the joint point appears once, not twice: {parts:?}"+ );+ assert!(parts.contains(&vec![(50, 50), (51, 50)]));+ }++ #[test]+ fn a_chain_starts_at_its_head_rather_than_its_middle() {+ // If a chain were grown from the middle piece the result would be two runs, not one.+ let mut layer = layer_of(&[+ (7, GEOM_LINE, vec![vec![(1, 0), (2, 0)]]),+ (7, GEOM_LINE, vec![vec![(0, 0), (1, 0)]]),+ (7, GEOM_LINE, vec![vec![(2, 0), (3, 0)]]),+ ]);+ coalesce_lines(&mut layer);+ assert_arena_is_tiled(&layer);+ assert_eq!(layer.parts.len(), 1, "one road, one part");+ assert_eq!(all_parts(&layer)[0], vec![(0, 0), (1, 0), (2, 0), (3, 0)]);+ }++ /// A ring road: every piece is continued by another, so none is a head. Without the second pass+ /// over the leftovers this would emit nothing and the road would vanish.+ #[test]+ fn a_closed_loop_survives_having_no_head() {+ let mut layer = layer_of(&[+ (7, GEOM_LINE, vec![vec![(0, 0), (10, 0)]]),+ (7, GEOM_LINE, vec![vec![(10, 0), (10, 10)]]),+ (7, GEOM_LINE, vec![vec![(10, 10), (0, 0)]]),+ ]);+ coalesce_lines(&mut layer);+ assert_arena_is_tiled(&layer);+ assert_eq!(layer.parts.len(), 1);+ assert_eq!(+ all_parts(&layer)[0],+ vec![(0, 0), (10, 0), (10, 10), (0, 0)],+ "the loop closes on the point it started at"+ );+ }++ #[test]+ fn polygons_are_untouched_and_keep_their_place() {+ let square = vec![(0, 0), (4, 0), (4, 4), (0, 4), (0, 0)];+ let hole = vec![(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)];+ let mut layer = layer_of(&[+ (3, GEOM_POLYGON, vec![square.clone(), hole.clone()]),+ (7, GEOM_LINE, vec![vec![(0, 0), (1, 0)]]),+ (7, GEOM_LINE, vec![vec![(1, 0), (2, 0)]]),+ ]);+ coalesce_lines(&mut layer);+ assert_arena_is_tiled(&layer);+ assert_eq!(layer.features.len(), 2);+ assert_eq!(layer.features[0].geom_type, GEOM_POLYGON, "the polygon keeps its position");+ assert_eq!(layer.features[0].part_count, 2, "exterior and hole both survive");+ let parts = all_parts(&layer);+ assert_eq!(parts[0], square);+ assert_eq!(parts[1], hole);+ assert_eq!(parts[2], vec![(0, 0), (1, 0), (2, 0)], "the lines still merged");+ }++ #[test]+ fn a_layer_with_nothing_to_merge_is_left_alone() {+ for features in [+ vec![],+ vec![(7u16, GEOM_LINE, vec![vec![(0i16, 0i16), (1, 1)]])],+ vec![(3, GEOM_POLYGON, vec![vec![(0, 0), (4, 0), (4, 4), (0, 0)]])],+ ] {+ let mut layer = layer_of(&features);+ let before = layer.clone();+ let stats = coalesce_lines(&mut layer);+ assert_eq!(layer, before, "a layer with fewer than two lines must not be rebuilt");+ assert_eq!(stats.features_before, stats.features_after);+ assert_eq!(stats.parts_before, stats.parts_after);+ }+ }++ /// The point of the whole module, in the shape the real data has: thousands of two-point+ /// fragments of one class laid end to end.+ #[test]+ fn a_fragmented_road_collapses_to_one_part() {+ let features: Vec<Fixture> = (0..2000)+ .map(|i| (7u16, GEOM_LINE, vec![vec![(i as i16, 0), (i as i16 + 1, 0)]]))+ .collect();+ let mut layer = layer_of(&features);+ let stats = coalesce_lines(&mut layer);+ assert_arena_is_tiled(&layer);+ assert_eq!(stats.features_before, 2000);+ assert_eq!(stats.features_after, 1);+ assert_eq!(stats.parts_before, 2000);+ assert_eq!(stats.parts_after, 1);+ assert_eq!(layer.coords.len(), 2001, "2000 segments share 1999 joints");+ }+}
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 f4ef4f0578..4c173b3a0c 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -35,6 +35,9 @@ use osm_ingest::proto::{err, Result}; use osm_ingest::rings::{self, MemberWay, RingStats}; use osm_ingest::select::Select; use tile_build::geom::Geometry;+use tile_build::par;+use tile_build::progress::Progress;+use rayon::prelude::*; use crate::schema::{self, Class, Layers}; use crate::store::{Sink, Store, WayCounts, WayReader, WaySink};@@ -255,6 +258,16 @@ pub fn extract( stats.nodes_needed = table.len() as u64; let table = resolve_nodes(input, &blobs, &blob_kinds, "Pass 3: nodes", table)?; mark("coordinates resolved");+ // The split, when asked for. Note what it does and does not separate: the first number is the+ // protobuf decode of each block *plus* the id lookups inside it, because bracketing the lookups+ // alone would need a clock read per node and there are billions. The second is the write, which+ // is the half that is serialised behind `run_pass_sink`'s lock.+ let (scan, write) = osm_ingest::nodeloc::resolve_seconds();+ if scan + write > 0.0 {+ println!(+ " [stage A] node pass CPU: decode+lookup {scan:.1}s write {write:.1}s (serialised)",+ );+ } // --- materialise ---------------------------------------------------------------------- //@@ -266,22 +279,69 @@ pub fn extract( let mut sink = Sink::create(spill_path)?; let mut reader = WayReader::open(&ways_path)?; let mut refs: Vec<i64> = Vec::new();- while let Some((_, class)) = reader.next(&mut refs)? {- let line = table.line(&refs);- match way_geometry(&line, class.area) {- Some(geometry) => {- sink.push(&class, &geometry)?;- stats.features += 1;+ // Silent until now, and it is not a short step: on a north-america extract this loop ran 623+ // seconds on one thread with nothing on stdout, which is indistinguishable from a hang.+ let mut bar = Progress::new(+ "Materialise: ways".to_string(),+ stats.ways_classified as usize,+ "way(s)",+ true,+ );+ // Batched, because the expensive part of a way is embarrassingly parallel and the cheap part+ // cannot be. `table.line` is a coordinate lookup per node -- an id search plus a random read of a+ // mapped file -- and `way_geometry` closes and winds rings; neither touches shared mutable state,+ // so a batch of them goes as wide as the pool. The sink then takes the results **in order**,+ // which is what keeps the archive byte-identical: the spill's feature order is the archive's.+ //+ // 64 Ki ways at ~10 nodes each is a few tens of MB of geometry in flight, against a build that+ // peaks near 7 GB.+ const MATERIALISE_BATCH: usize = 64 * 1024;+ let mut batch: Vec<(Class, Vec<i64>)> = Vec::with_capacity(MATERIALISE_BATCH);+ let mut built: Vec<Option<Geometry<(f64, f64)>>> = Vec::with_capacity(MATERIALISE_BATCH);+ loop {+ let more = reader.next(&mut refs)?;+ if let Some((_, class)) = more {+ batch.push((class, std::mem::take(&mut refs)));+ }+ // Flushed when full, and once more at the end with whatever is left.+ if batch.len() >= MATERIALISE_BATCH || (more.is_none() && !batch.is_empty()) {+ built.clear();+ par::install(|| {+ batch+ .par_iter()+ .map(|(class, refs)| way_geometry(&table.line(refs), class.area))+ .collect_into_vec(&mut built);+ });+ for ((class, _), geometry) in batch.iter().zip(built.drain(..)) {+ match geometry {+ Some(geometry) => {+ sink.push(class, &geometry)?;+ stats.features += 1;+ }+ None => stats.geometry_failed += 1,+ }+ bar.tick("way(s)"); }- None => stats.geometry_failed += 1,+ batch.clear();+ }+ if more.is_none() {+ break; } }+ 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. drop(reader); let _ = std::fs::remove_file(&ways_path); + let mut bar = Progress::new(+ "Materialise: relations".to_string(),+ relations.len(),+ "relation(s)",+ true,+ ); for relation in &relations {+ bar.tick("relation(s)"); // A boundary relation's members are the border. Each is emitted as its own line rather than // stitched: the renderer strokes them, and a gap between two member ways is invisible in a // stroke while a failed stitch would drop the whole border.@@ -316,6 +376,7 @@ pub fn extract( sink.push(&relation.class, &Geometry::Polygons(polygons))?; stats.features += 1; }+ bar.finish("relation(s)"); // The mainland, last, because clipping it needs the extract's own bounding box and that is // only known once every OSM feature has been through the sink. Order in the file does not // matter: the tiler groups by layer id, so `earth` is the first layer of every body whenever it
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 e97bb94054..753dacf18d 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -8,6 +8,14 @@ //! mamaps_build --input california.osm.pbf --out california.mamaps //! [--layers water,buildings] [--min-zoom 0] [--max-zoom 14] //! [--simplification 1.0] [--build-id N] [--report FILE]+//! [--keep-store] [--reuse-store]+//!+//! `--keep-store` leaves the feature spill and writes a small index beside it; `--reuse-store` then+//! skips stage A entirely and tiles from that spill. Stage A is 17.6 minutes of a north-america+//! build and identical every run for the same input and layer set, so the pair is what makes+//! iterating on the tiler affordable. The index records the source's length and mtime plus the layer+//! selection, and reuse refuses a spill that does not match — a stale spill would otherwise produce+//! an archive that looks fine and is missing most of the world. //! ``` //! //! # Why not through the existing tiler@@ -22,6 +30,7 @@ use std::path::PathBuf; use std::process::ExitCode; +mod coalesce; mod extract; mod rings; mod shapefile;@@ -29,11 +38,57 @@ mod schema; mod store; mod tiler; +/// The allocator, replaced because the default one was three quarters of the build.+///+/// A build tool has no business caring which allocator it gets, and this one did not until the+/// encode pass was measured against the machine it runs on: **1358 s of worker CPU against 180 s of+/// wall on a 32-core, 64-thread box** — a speed-up of 7.5 where the pool can give 64. Nothing in+/// that pass is shared. [`rings::normalise`], `body::serialize_into` and DEFLATE each read one tile+/// and write one tile, there is no lock and no atomic in the path with `MAPS_TIMING` off, and the+/// memory traffic works out at a few hundred MB/s against eight channels of DDR5. The only thing+/// all sixty-four threads still contend on is the heap.+///+/// And they hit it hard. `normalise` allocates a `Vec` per polygon group, another for its exterior+/// and one per hole it keeps, on the way to rebuilding a layer's arenas; z14 of a us-west build is+/// 44.4 M features across 943,401 tiles, which is tens of millions of allocate/free pairs on+/// Windows' process heap in about two and a half minutes.+///+/// Swapping it out took the tiling stage from **351 s to 110 s** on the same spill, for a+/// byte-identical archive:+///+/// | phase | default heap | mimalloc |+/// |---|---|---|+/// | map | 125.1 s | 72.9 s |+/// | merge | 33.2 s | 9.6 s |+/// | encode | 180.3 s | 21.6 s |+/// | append | 12.4 s | 3.3 s |+/// | *encode CPU: stage C* | *452.6 s* | *54.4 s* |+/// | *encode CPU: serialise* | *355.9 s* | *5.4 s* |+/// | *encode CPU: deflate* | *550.0 s* | *181.1 s* |+///+/// Serialisation is the one that says what this really was. It is a memcpy into a reused+/// [`tilecodec::mamaps::body::Scratch`] and it cost 356 s of CPU; it now costs 5.4 s. That was never+/// encoding, it was the handful of buffer growths per tile going to `HeapAlloc` under sixty-four+/// threads of contention.+///+/// Two things this is not. It is not a substitute for allocating less — `normalise` should be+/// threading scratch buffers through rather than building a `Vec` per ring, and a cheaper allocator+/// only makes that less urgent. And it is not free: mimalloc holds freed pages back rather than+/// returning them promptly, which took peak RSS from 6.86 GB to 10.14 GB on the same build. That+/// trade is worth revisiting if memory becomes the binding constraint again.+///+/// It cannot change a byte of the output — an allocator decides *where*, never *what* — so it needed+/// no argument about ordering, only a measurement. The us-west archive hashes the same either way.+#[global_allocator]+static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;+ fn main() -> ExitCode { let args: Vec<String> = std::env::args().collect(); let mut input: Option<PathBuf> = None; let mut out: Option<PathBuf> = None; let mut report: Option<PathBuf> = None;+ let mut keep_store = false;+ let mut reuse_store = false; let mut layers = schema::Layers::all(); let mut min_zoom = 0u8; let mut max_zoom = 14u8;@@ -59,6 +114,14 @@ fn main() -> ExitCode { report = Some(PathBuf::from(v)); 2 }),+ "--keep-store" => {+ keep_store = true;+ Ok(1)+ }+ "--reuse-store" => {+ reuse_store = true;+ Ok(1)+ } "--coastline" => value("--coastline").map(|v| { coastline = Some(PathBuf::from(v)); 2@@ -111,6 +174,8 @@ fn main() -> ExitCode { let settings = RunSettings { report,+ keep_store,+ reuse_store, coastline, layers, min_zoom,@@ -137,6 +202,10 @@ struct RunSettings { max_zoom: u8, simplification: f64, build_id: Option<u64>,+ /// Keep the feature spill and write its index, so a later run can `--reuse-store`.+ keep_store: bool,+ /// Skip stage A and read the spill an earlier `--keep-store` run left behind.+ reuse_store: bool, } fn run(@@ -160,21 +229,42 @@ fn run( // not an error: an island is real data and the renderer's backdrop is the water colour. println!("no --coastline given, so `earth` carries islands only and there is no mainland"); }- let (store, stats) = extract::extract(input, layers, run.coastline.as_deref(), &spill)- .map_err(|e| format!("{}: {e}", input.display()))?;- println!(- "classified {} way(s) and {} relation(s) -> {} feature(s), {} node(s) resolved",- stats.ways_classified, stats.relations_classified, stats.features, stats.nodes_needed,- );- if stats.geometry_failed > 0 {- // Expected at an extract's cut edges, and worth reporting because a large count means- // something else.- println!(" {} classified element(s) produced no geometry", stats.geometry_failed);- }-- if stats.land_polygons > 0 {- println!(" including {} prepared land polygon(s)", stats.land_polygons);- }+ let provenance = store::Provenance::of(input, layers, run.coastline.is_some())+ .map_err(|e| e.to_string())?;+ // Stage A is most of a large build -- 17.6 minutes of a north-america run, and identical every+ // time for the same input and layer set. `--reuse-store` skips it, which is what makes iterating+ // on the tiler affordable. The index records what it was built from and `Store::open` refuses a+ // mismatch, so the shortcut cannot silently produce an archive missing most of the world.+ let (store, stats) = if run.reuse_store {+ let (store, features) =+ store::Store::open(&spill, provenance).map_err(|e| e.to_string())?;+ println!(+ "reusing the feature spill at {} ({} feature(s)); stage A skipped",+ spill.display(),+ features,+ );+ (store, extract::Stats { features, ..Default::default() })+ } else {+ let (store, stats) = extract::extract(input, layers, run.coastline.as_deref(), &spill)+ .map_err(|e| format!("{}: {e}", input.display()))?;+ println!(+ "classified {} way(s) and {} relation(s) -> {} feature(s), {} node(s) resolved",+ stats.ways_classified, stats.relations_classified, stats.features, stats.nodes_needed,+ );+ if stats.geometry_failed > 0 {+ // Expected at an extract's cut edges, and worth reporting because a large count means+ // something else.+ println!(" {} classified element(s) produced no geometry", stats.geometry_failed);+ }+ if stats.land_polygons > 0 {+ println!(" including {} prepared land polygon(s)", stats.land_polygons);+ }+ if run.keep_store {+ let index = store.save_index(provenance, stats.features).map_err(|e| e.to_string())?;+ println!(" wrote {} so --reuse-store can skip stage A", index.display());+ }+ (store, stats)+ }; // The build id identifies the *data*: change the input, the zoom range, the layer set or the // simplification and every reader has to drop its cache. Derived rather than asked for, so a@@ -187,8 +277,11 @@ fn run( let (bytes, per_zoom) = tiler::build(&store, &settings).map_err(|e| e.to_string())?; tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?; std::fs::write(out, &bytes).map_err(|e| format!("cannot write {}: {e}", out.display()))?;- // The spill is scratch. Removed on success; left behind on failure, where it is evidence.- let _ = std::fs::remove_file(&spill);+ // The spill is scratch. Removed on success; left behind on failure, where it is evidence, and+ // kept deliberately under `--keep-store`, where it is the input to the next run.+ if !run.keep_store && !run.reuse_store {+ let _ = std::fs::remove_file(&spill);+ } println!( "\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8}{:>8}{:>8}{:>8}",@@ -217,6 +310,26 @@ fn run( }); let serial = (merge + append) as f64; let total = (map + merge + encode + append).max(1) as f64;+ // What coalescing removed. The `features` column above is counted in `push`, during the map+ // phase and therefore BEFORE the merge that coalescing runs after, so it reports what OSM+ // yielded rather than what was written -- which is the number the map phase's cost tracks. This+ // line is what was actually encoded.+ let lines = per_zoom.iter().fold(coalesce::Stats::default(), |mut a, z| {+ a.add(z.lines);+ a+ });+ if lines.features_before > lines.features_after {+ println!(+ " coalesced: {} line feature(s) -> {} ({:.0}x), {} part(s) -> {} ({:.1}x)",+ lines.features_before,+ lines.features_after,+ lines.features_before as f64 / lines.features_after.max(1) as f64,+ lines.parts_before,+ lines.parts_after,+ lines.parts_before as f64 / lines.parts_after.max(1) as f64,+ );+ }+ let (stage_c, serialize, deflate) = tiler::encode_seconds(); println!( "total map {:.1}s (of which {:.1}s deserialising the spill, on one thread) merge {:.1}s encode {:.1}s append {:.1}s ({:.0}% of tiling is serial)", map as f64 / 1000.0,@@ -226,6 +339,17 @@ fn run( append as f64 / 1000.0, serial / total * 100.0, );+ // CPU, not wall, and summed across workers: compared against the encode wall above it says+ // whether that phase is short of work or short of parallelism. Only under `MAPS_TIMING`,+ // because three atomics per tile is not free at a million tiles.+ if stage_c + serialize + deflate > 0.0 {+ println!(+ " encode CPU: stage C {stage_c:.1}s serialise {serialize:.1}s deflate {deflate:.1}s \+ (={:.1}s of CPU against {:.1}s of wall)",+ stage_c + serialize + deflate,+ encode as f64 / 1000.0,+ );+ } println!( "\nwrote {} ({} bytes, build_id {build_id:#018x}) in {:.1}s", out.display(),@@ -305,17 +429,31 @@ fn build_report( out.push_str(&format!(" \"features\": {},\n", stats.features)); out.push_str(&format!(" \"geometry_failed\": {},\n", stats.geometry_failed)); out.push_str(&format!(" \"nodes_needed\": {},\n", stats.nodes_needed));+ let lines = per_zoom.iter().fold(coalesce::Stats::default(), |mut a, z| {+ a.add(z.lines);+ a+ });+ out.push_str(&format!(+ " \"coalesced\": {{ \"line_features_before\": {}, \"line_features_after\": {}, \+ \"parts_before\": {}, \"parts_after\": {} }},\n",+ lines.features_before, lines.features_after, lines.parts_before, lines.parts_after,+ )); out.push_str(" \"zooms\": [\n"); for (i, z) in per_zoom.iter().enumerate() { out.push_str(&format!( " {{ \"zoom\": {}, \"tiles\": {}, \"features\": {}, \"points\": {}, \- \"dropped\": {}, \"bytes\": {} }}{}\n",+ \"dropped\": {}, \"bytes\": {}, \"map_ms\": {}, \"merge_ms\": {}, \+ \"encode_ms\": {}, \"append_ms\": {} }}{}\n", z.zoom, z.tiles, z.features, z.points, z.dropped, z.bytes,+ z.map_ms,+ z.merge_ms,+ z.encode_ms,+ z.append_ms, if i + 1 == per_zoom.len() { "" } else { "," }, )); }@@ -329,7 +467,11 @@ fn usage() { \x20 [--layers earth,water,buildings,roads,boundaries,landcover,landuse]\n\ \x20 [--min-zoom N] [--max-zoom N]\n\ \x20 [--coastline LAND.geojsonseq]\n\- \x20 [--simplification F] [--build-id N] [--report FILE]"+ \x20 [--simplification F] [--build-id N] [--report FILE]\n\+ \x20 [--keep-store] [--reuse-store]\n\+ \n\+ --keep-store leave the feature spill and its index behind\n\+ --reuse-store tile from that spill instead of re-running stage A" ); }
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 4251be92f9..c086bbc3ed 100644--- a/scripts/maps/mamaps_build/src/store.rs+++ b/scripts/maps/mamaps_build/src/store.rs@@ -237,6 +237,192 @@ pub struct Store { bbox: (i32, i32, i32, i32), } +/// What a spill was built from, so reusing one cannot silently build the wrong archive.+///+/// A store is only valid for the input and layer selection that produced it. Reusing one built from+/// a different `.pbf`, or with `--layers water` when this run wants all seven, would produce an+/// archive that looks fine and is missing most of the world. Cheap to record, impossible to diagnose+/// from the symptom.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Provenance {+ /// Length and modification time of the source `.pbf`. Not a hash: hashing 18 GB to save 18+ /// minutes of stage A would give most of the saving back.+ pub source_len: u64,+ pub source_mtime: u64,+ /// The layer selection, one bit each, in [`crate::schema::Layers`] declaration order.+ pub layers: u8,+ /// Whether a coastline product was folded in, which adds features nothing else would.+ pub coastline: bool,+}++impl Provenance {+ /// Read the source file's identity, or an error naming it.+ pub fn of(source: &Path, layers: crate::schema::Layers, coastline: bool) -> Result<Provenance> {+ let meta = std::fs::metadata(source)+ .map_err(|e| osm_ingest::proto::Error(format!("cannot stat {}: {e}", source.display())))?;+ let mtime = meta+ .modified()+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_secs())+ .unwrap_or(0);+ Ok(Provenance {+ source_len: meta.len(),+ source_mtime: mtime,+ layers: u8::from(layers.earth)+ | u8::from(layers.water) << 1+ | u8::from(layers.buildings) << 2+ | u8::from(layers.roads) << 3+ | u8::from(layers.boundaries) << 4+ | u8::from(layers.landcover) << 5+ | u8::from(layers.landuse) << 6,+ coastline,+ })+ }+}++/// Magic and version of the sidecar index. Bumped whenever the layout below changes, so an index+/// written by an older build is refused rather than misread.+const INDEX_MAGIC: &[u8; 8] = b"MAMASTOR";+const INDEX_VERSION: u32 = 1;++impl Store {+ /// Write the sidecar that lets [`Store::open`] skip stage A.+ ///+ /// Beside the spill, as `<spill>.index`. Everything a `Store` holds that is not the spill itself:+ /// the chunk offsets, the per-chunk shallowest zoom, the count and the bounding box. On a+ /// north-america build that is about 28 MB against a 29 GB spill, and it buys eighteen minutes+ /// per subsequent run.+ ///+ /// `features` is [`crate::extract::Stats::features`], which the build id is derived from. Stored+ /// rather than recomputed so a reused run derives the **same** id as the run that built the+ /// spill -- otherwise reuse would quietly republish under a different id.+ pub fn save_index(&self, provenance: Provenance, features: u64) -> Result<PathBuf> {+ let path = index_path(&self.path);+ let mut out = Vec::with_capacity(16 + self.chunks.len() * 8 + self.chunk_mins.len());+ out.extend_from_slice(INDEX_MAGIC);+ out.extend_from_slice(&INDEX_VERSION.to_le_bytes());+ out.extend_from_slice(&provenance.source_len.to_le_bytes());+ out.extend_from_slice(&provenance.source_mtime.to_le_bytes());+ out.push(provenance.layers);+ out.push(u8::from(provenance.coastline));+ out.extend_from_slice(&features.to_le_bytes());+ out.extend_from_slice(&self.count.to_le_bytes());+ for v in [self.bbox.0, self.bbox.1, self.bbox.2, self.bbox.3] {+ out.extend_from_slice(&v.to_le_bytes());+ }+ out.extend_from_slice(&(self.chunks.len() as u64).to_le_bytes());+ for c in &self.chunks {+ out.extend_from_slice(&c.to_le_bytes());+ }+ out.extend_from_slice(&(self.chunk_mins.len() as u64).to_le_bytes());+ out.extend_from_slice(&self.chunk_mins);+ std::fs::write(&path, &out)+ .map_err(|e| osm_ingest::proto::Error(format!("cannot write {}: {e}", path.display())))?;+ Ok(path)+ }++ /// Reopen a spill written by an earlier run, refusing one that does not match `want`.+ ///+ /// Returns the store and the feature count the build id is derived from. The whole point is+ /// iterating on tiling without paying for stage A again, so the checks are what make that safe+ /// rather than merely fast.+ pub fn open(spill: &Path, want: Provenance) -> Result<(Store, u64)> {+ let path = index_path(spill);+ if !spill.exists() {+ return err(format!("no feature spill at {}", spill.display()));+ }+ let raw = std::fs::read(&path).map_err(|e| {+ osm_ingest::proto::Error(format!(+ "cannot read {} ({e}) -- a store can only be reused if the run that built it wrote \+ its index",+ path.display(),+ ))+ })?;+ let mut at = 0usize;+ let mut take = |n: usize| -> Result<&[u8]> {+ let end = at + n;+ if end > raw.len() {+ return err(format!("{} is truncated", path.display()));+ }+ let slice = &raw[at..end];+ at = end;+ Ok(slice)+ };+ if take(8)? != INDEX_MAGIC {+ return err(format!("{} is not a store index", path.display()));+ }+ let version = u32::from_le_bytes(take(4)?.try_into().expect("four bytes"));+ if version != INDEX_VERSION {+ return err(format!(+ "{} is version {version}, this build writes {INDEX_VERSION}",+ path.display(),+ ));+ }+ let got = Provenance {+ source_len: u64::from_le_bytes(take(8)?.try_into().expect("eight bytes")),+ source_mtime: u64::from_le_bytes(take(8)?.try_into().expect("eight bytes")),+ layers: take(1)?[0],+ coastline: take(1)?[0] != 0,+ };+ if got != want {+ return err(format!(+ "{} was built from a different input or layer set (source {} bytes at mtime {}, \+ layers {:#04x}, coastline {}) than this run wants (source {} bytes at mtime {}, \+ layers {:#04x}, coastline {}) -- delete it or drop --reuse-store",+ path.display(),+ got.source_len,+ got.source_mtime,+ got.layers,+ got.coastline,+ want.source_len,+ want.source_mtime,+ want.layers,+ want.coastline,+ ));+ }+ let features = u64::from_le_bytes(take(8)?.try_into().expect("eight bytes"));+ let count = u64::from_le_bytes(take(8)?.try_into().expect("eight bytes"));+ let mut bbox = [0i32; 4];+ for slot in &mut bbox {+ *slot = i32::from_le_bytes(take(4)?.try_into().expect("four bytes"));+ }+ let chunk_count = u64::from_le_bytes(take(8)?.try_into().expect("eight bytes")) as usize;+ let mut chunks = Vec::with_capacity(chunk_count);+ for _ in 0..chunk_count {+ chunks.push(u64::from_le_bytes(take(8)?.try_into().expect("eight bytes")));+ }+ let min_count = u64::from_le_bytes(take(8)?.try_into().expect("eight bytes")) as usize;+ let chunk_mins = take(min_count)?.to_vec();+ // The same cross-check `WaySink::finish` makes, for the same reason: two indexes that+ // disagree silently drop real features from a handful of tiles at one zoom.+ if chunk_mins.len() != chunks.len().saturating_sub(1) {+ return err(format!(+ "{} describes {} chunk(s) but {} zoom entr(ies)",+ path.display(),+ chunks.len().saturating_sub(1),+ chunk_mins.len(),+ ));+ }+ Ok((+ Store {+ path: spill.to_path_buf(),+ count,+ bbox: (bbox[0], bbox[1], bbox[2], bbox[3]),+ chunks,+ chunk_mins,+ },+ features,+ ))+ }+}++fn index_path(spill: &Path) -> PathBuf {+ let mut p = spill.as_os_str().to_owned();+ p.push(".index");+ PathBuf::from(p)+}+ impl Store { /// How many features are in the file. #[cfg_attr(not(test), allow(dead_code))]@@ -255,20 +441,18 @@ impl Store { /// skipped outright — not read, not parsed. Order is unchanged, because the chunks that survive /// are still visited in file order, and that is what keeps the archive byte-identical. pub fn reader_for_zoom(&self, z: u8) -> Result<ZoomReader> {- Ok(ZoomReader {- inner: NormalizedChunks::open(self.path.clone(), self.chunks.clone())+ let wanted: Vec<usize> = self+ .chunk_mins+ .iter()+ .enumerate()+ .filter(|(_, min)| **min <= z)+ .map(|(i, _)| i)+ .collect();+ ZoomReader::spawn(+ NormalizedChunks::open(self.path.clone(), self.chunks.clone()) .map_err(|e| osm_ingest::proto::Error(e.to_string()))?,- wanted: self- .chunk_mins- .iter()- .enumerate()- .filter(|(_, min)| **min <= z)- .map(|(i, _)| i)- .collect(),- at: 0,- scratch: Vec::new(),- records: Vec::new(),- })+ wanted,+ ) } /// Read every feature, in the order they were written.@@ -319,30 +503,174 @@ fn feature_of(record: tile_build::spill::NormalizedFeature) -> Result<Feature> { Ok(Feature { class: unpack(bits), geometry: record.geometry }) } +/// Chunks of features as the lanes hand them over, or the error that stopped one.+///+/// [`Feature`] rather than the decoder's own record, because turning one into the other is where+/// the reader thread's remaining time went. It looks like a field lookup and a move, and the field+/// lookup and the move are free; what is not is dropping the `props` the decoder built — a `Vec` and+/// an owned key `String` per feature, freed one at a time on the one thread the whole map phase+/// waits on. Converting in the lane puts that on the lane.+type Decoded = Result<Vec<Feature>>;++/// Threads decoding spill chunks ahead of the tiler.+///+/// Four rather than the pool, and four rather than one. See [`ZoomReader::spawn`] for why it is not+/// the pool. Four because the decode was 62.6 s of a 175 s build and four is where that stops being+/// the constraint: at four the tiling stage is 95.1 s, at eight it is 96.0 s and the reader's own+/// time is 30.9 s against 30.0 s — inside this machine's run-to-run noise. What is left on the+/// reader after four lanes is not decode waiting to be spread, it is the reader's own per-feature+/// work, and more lanes cannot touch it.+const PREFETCH_LANES: usize = 4;++/// Chunks one lane may run ahead by.+///+/// A chunk is [`NORM_CHUNK_FEATURES`] features, so the whole prefetch holds at most+/// `PREFETCH_LANES * (PREFETCH_DEPTH + 1) * 64` features — a few thousand, against the 512 Ki+/// *vertices* the tiler batches downstream. Depth is here to absorb a slow chunk, not to buffer.+const PREFETCH_DEPTH: usize = 32;+ /// Reads the chunks one zoom needs and seeks past the rest. pub struct ZoomReader {- inner: NormalizedChunks,- /// Indices of the chunks this zoom wants, ascending.- wanted: Vec<usize>,+ /// One receiver per lane. Chunk `k` of the wanted list is decoded by lane `k % lanes.len()`, so+ /// taking them round-robin reproduces file order exactly. Empty when there is nothing to read.+ lanes: Vec<std::sync::mpsc::Receiver<Decoded>>,+ /// Joined on drop, after the receivers are dropped: a lane blocked on a full channel exits when+ /// its receiver goes, so the order of those two steps is what makes the join finite.+ lanes_running: Vec<std::thread::JoinHandle<()>>,+ /// Chunks taken so far, which is also the lane to take the next one from. at: usize,- scratch: Vec<u8>,- records: Vec<tile_build::spill::NormalizedFeature>,+ total: usize,+ records: Vec<Feature>,+}++impl Drop for ZoomReader {+ fn drop(&mut self) {+ // Receivers first. A lane parked on `send` to a full channel wakes with an error the moment+ // its receiver is gone, and only then is the join below guaranteed to finish -- which+ // matters on the error path, where the tiler abandons a zoom with every lane backed up.+ self.lanes.clear();+ for lane in self.lanes_running.drain(..) {+ let _ = lane.join();+ }+ } } impl ZoomReader {+ /// Start a lane per [`PREFETCH_LANES`] over `wanted`, dealt round-robin.+ ///+ /// # Why dedicated threads and not the pool+ ///+ /// This decode is 62.6 s of a 175 s us-west build, all of it on one thread, and+ /// [`NormalizedChunks::read_into`] is an obvious candidate for the pool: it takes `&self`, reads+ /// its own byte range positionally, and is pure. Decoding 512 chunks at a time across the pool+ /// was tried and made the map phase **62% slower** — 102.4 s to 165.5 s — for byte-identical+ /// output.+ ///+ /// The reason is what this reader is: it feeds the clipping workers through a channel. Handing+ /// the refill to the same pool queues it *behind* the clipping tasks it exists to supply, so the+ /// reader blocks waiting on a pool that is busy with work only the reader can extend. The+ /// overlap between reading and clipping — the entire point of the arrangement — disappears, and+ /// both halves get slower.+ ///+ /// So: threads of their own, outside the pool, which is what [`crate::tiler`] does for the+ /// reader itself and for the same reason.+ ///+ /// # Why the order cannot move+ ///+ /// Lane `j` takes wanted-chunks `j`, `j + n`, `j + 2n`, ... and a lane's own channel is FIFO, so+ /// the `k`th chunk out of lane `k % n` is wanted-chunk `k`. Reading the lanes round-robin is+ /// therefore the wanted list in order, which is the file in order, which is what the archive's+ /// feature ordering rests on. Nothing here depends on which lane finishes first; a lane that+ /// races ahead simply fills its channel and parks.+ fn spawn(inner: NormalizedChunks, wanted: Vec<usize>) -> Result<ZoomReader> {+ let total = wanted.len();+ if total == 0 {+ return Ok(ZoomReader {+ lanes: Vec::new(),+ lanes_running: Vec::new(),+ at: 0,+ total: 0,+ records: Vec::new(),+ });+ }+ // One handle shared rather than one file open per lane: `read_into` is positional and+ // documented to serve every thread from one handle.+ let inner = std::sync::Arc::new(inner);+ let count = PREFETCH_LANES.min(total);+ let mut lanes = Vec::with_capacity(count);+ let mut lanes_running = Vec::with_capacity(count);+ for lane in 0..count {+ let (send, receive) = std::sync::mpsc::sync_channel::<Decoded>(PREFETCH_DEPTH);+ let inner = std::sync::Arc::clone(&inner);+ let mine: Vec<usize> = wanted.iter().skip(lane).step_by(count).copied().collect();+ let running = std::thread::Builder::new()+ .name(format!("mamaps-spill-{lane}"))+ .spawn(move || {+ // One byte buffer and one record buffer for the lane, reused across its+ // chunks. What is sent is a third `Vec`, allocated per chunk -- one allocation+ // per 64 features, against the per-feature geometry the decode allocates+ // anyway.+ let mut scratch = Vec::new();+ let mut records = Vec::new();+ for chunk in mine {+ let decoded = inner+ .read_into(chunk, &mut scratch, &mut records)+ .map_err(|e| osm_ingest::proto::Error(e.to_string()))+ // Reversed here rather than by the consumer, which takes from the+ // back: same reason as everything else in this closure, it is work and+ // it does not have to be the reader's.+ .and_then(|()| {+ let mut out = Vec::with_capacity(records.len());+ for record in records.drain(..).rev() {+ out.push(feature_of(record)?);+ }+ Ok(out)+ });+ // Stop on the first error: the consumer surfaces it and abandons the zoom,+ // and carrying on would only queue work behind a build that is already+ // failing.+ let stop = decoded.is_err();+ if send.send(decoded).is_err() || stop {+ return;+ }+ }+ })+ .map_err(|e| {+ osm_ingest::proto::Error(format!("cannot start spill prefetch lane {lane}: {e}"))+ })?;+ lanes.push(receive);+ lanes_running.push(running);+ }+ Ok(ZoomReader { lanes, lanes_running, at: 0, total, records: Vec::new() })+ }++ /// How many spill chunks this zoom will read, and how many it has.+ ///+ /// Exposed so the tiler can show progress: the map phase is the longest in the build and was+ /// silent for all of it, which on a continent is forty minutes of no output at all.+ pub fn chunks(&self) -> (usize, usize) {+ (self.at.min(self.total), self.total)+ }+ /// The next feature, or `None` once this zoom's chunks are exhausted. pub fn next(&mut self) -> Result<Option<Feature>> { loop {- if let Some(record) = self.records.pop() {- return Ok(Some(feature_of(record)?));+ // From the back, which is why the lane reversed the chunk before sending it.+ if let Some(feature) = self.records.pop() {+ return Ok(Some(feature));+ }+ if self.at >= self.total {+ return Ok(None); }- let Some(&chunk) = self.wanted.get(self.at) else { return Ok(None) };+ let lane = self.at % self.lanes.len(); self.at += 1;- self.inner- .read_into(chunk, &mut self.scratch, &mut self.records)- .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;- // Taken from the back, so reversing here is what preserves file order.- self.records.reverse();+ // A lane that hung up before delivering all of its chunks panicked: it returns only+ // after sending every one of them or after sending an error, and an error arrives as a+ // value rather than a hangup.+ let decoded = self.lanes[lane].recv().map_err(|_| {+ osm_ingest::proto::Error(format!("spill prefetch lane {lane} stopped early"))+ })?;+ self.records = decoded?; } } }
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 b350f3f3f6..af3973c138 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -15,10 +15,11 @@ //! zoom, so the same vertex survives or does not regardless of which tile it lands in. Doing it //! the other way round is what lets a shared edge simplify differently on each side and open a //! seam.-//! * [`geom::tiles_touched`], whose per-segment bisection is not optional: a transcontinental line-//! touches 16 632 tiles against 34 535 986 for its bounding box.-//! * [`clip`]'s Liang-Barsky for lines and Sutherland-Hodgman for rings, against a tile rect with a-//! buffer so a stroke at the edge has geometry to join to.+//! * [`subdivide::subdivide`], which walks a feature down the tile quadtree instead of clipping it+//! in full against every tile it touches. A feature inside one tile is clipped once, exactly as+//! before; one spanning three states pays one vertex pass per zoom level rather than one per tile.+//! * [`clip`](tile_build::clip)'s Liang-Barsky for lines and Sutherland-Hodgman for rings, against a+//! tile rect with a buffer so a stroke at the edge has geometry to join to. //! //! # Memory //!@@ -35,13 +36,25 @@ //! //! 1. **Map.** One reader thread cuts the feature stream into chunks of roughly //! [`CHUNK_VERTICES`] input vertices and hands them over a bounded channel to a pool of workers.-//! Each worker projects, simplifies, bisects and clips its own chunk into a private [`Chunk`]-//! map, touching nothing shared.+//! Each worker projects, simplifies and clips its own chunk into a private [`Chunk`] map,+//! touching nothing shared. //! 2. **Reduce.** The chunks are ordered by the index they were *read* at — never by the order they //! finished in — and k-way merged on the tile id. //! 3. **Encode.** Stage C and body serialisation are pure functions of one tile, so a batch of //! merged tiles is encoded in parallel and appended in tile order on one thread. //!+//! Steps 2 and 3 alternate, and **overlapping them has been tried and made the build slower.** The+//! reduce is single-threaded and the encode is the whole pool, so a merge thread behind a+//! one-batch channel looks like free time: 33 s of a 351 s us-west tiling stage with sixty-three+//! cores idle. Measured, it cost 53 s instead — 351 s to 404 s, byte-identical — and the merge's own+//! busy time went 33 s to 217 s. Two reasons, both about the machine rather than the code. The pool+//! is already one thread per logical CPU, so the merge thread is a sixty-fifth on sixty-four and has+//! to be timesliced against threads that never yield; and the merge is a pointer walk over+//! `BTreeMap` nodes, which was fast because it had L3 to itself and is not once sixty-four encode+//! workers are streaming gigabytes through it. This is the same shape as the parallel spill refill+//! in [`crate::store`], and it is recorded here for the same reason: it reads like an obvious win+//! and it is not one.+//! //! The reason this is byte-identical is stronger than "the merge is sorted". Concatenating a //! partition of a sequence in partition order reproduces the sequence, so a tile layer's features //! land in exactly the order the store yielded them — which makes the archive independent not only@@ -76,7 +89,9 @@ use std::sync::Mutex; use rayon::prelude::*; use tile_build::geom::{self, Geometry, IntGeometry, SigPt}; use tile_build::par;-use tile_build::{clip, simplify};+use tile_build::subdivide;+use tile_build::progress::Progress;+use tile_build::simplify; use tilecodec::mamaps::body::{ Body, Feature as BodyFeature, Layer as BodyLayer, Part, GEOM_LINE, GEOM_POLYGON, WINDING_HOLE, WINDING_OUTER,@@ -177,6 +192,8 @@ pub struct ZoomStats { pub bytes: u64, /// What stage C had to correct. pub rings: crate::rings::Stats,+ /// What coalescing merged away: an OSM way is an editing unit, not a rendering one.+ pub lines: crate::coalesce::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@@ -269,6 +286,11 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta // remembered. A `BTreeMap` per chunk and a heap across them is the same guarantee the // single-threaded `BTreeMap` gave. let mut merged = merge(chunks);+ // Merge, encode and append have no total to count against -- the tile count is only known once+ // the merge has produced it -- so this reports what has been written rather than a+ // percentage. Still the difference between forty silent minutes and a number that moves.+ let mut written = 0usize;+ let mut shown = 0usize; loop { // Batched rather than a task per tile: one tile's stage C and encode is tens of // microseconds and rayon's stealing costs more than that. Batched rather than a whole@@ -288,16 +310,28 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta 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 {+ for (id, encoded, rings, lines) in done { stats.rings.add(rings);+ stats.lines.add(lines); let Some((stored, raw_len)) = encoded else { continue }; // Uncompressed, as this column has always meant. stats.bytes += raw_len as u64; stats.tiles += 1; writer.append_stored(id, &stored)?;+ written += 1;+ // Every 25k tiles: often enough to look alive on a continent, rare enough that the+ // write itself is never the cost.+ if written - shown >= 25_000 {+ shown = written;+ print!("\r{:<28} [{written:>10} tile(s)]", format!("Encode z{z}"));+ let _ = std::io::Write::flush(&mut std::io::stdout());+ } } stats.append_ms += appending.elapsed().as_millis() as u64; }+ if written > 0 {+ println!("\r{:<28} [{written:>10} tile(s)]", format!("Encode z{z}"));+ } per_zoom.push(stats); } @@ -414,12 +448,24 @@ fn read_chunks( let mut vertices = 0usize; let mut index = 0usize; let mut read_nanos = 0u64;+ // The map phase's only visible progress. Chunks rather than features, because the count is known+ // up front: `reader_for_zoom` has already worked out which of the spill's chunks this zoom wants.+ let (_, total) = reader.chunks();+ let mut bar = Progress::new(format!("Map z{z}"), total, "chunk(s)", true);+ let mut ticked = 0usize; loop { // Timed around the deserialise alone. The send below can block on a full channel, and that is // the workers being busy rather than the reader being the bottleneck. let at = std::time::Instant::now(); let next = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))?; read_nanos += at.elapsed().as_nanos() as u64;+ // Ticked from the reader's own cursor rather than counted here, so the bar cannot drift from+ // what is actually being read.+ let (done, _) = reader.chunks();+ while ticked < done {+ bar.tick("chunk(s)");+ ticked += 1;+ } let Some(feature) = next else { break }; if z < feature.class.min_zoom { continue;@@ -440,6 +486,7 @@ fn read_chunks( if !chunk.is_empty() { let _ = send.send((index, chunk)); }+ bar.finish("chunk(s)"); READ_NANOS.fetch_add(read_nanos, Ordering::Relaxed); Ok(()) }@@ -460,19 +507,15 @@ fn tile_chunks( tolerance: f64, buffer: f64, ) {- // Reused across chunks, because `tiles_touched` fills a caller's buffer precisely so that a- // transcontinental line's 16 632 tiles are not a fresh allocation per feature.- let mut touched: Vec<(u64, u64)> = Vec::new(); loop { // Held to take a chunk and never while tiling one: the lock covers a pointer move, and the // work either side of it is milliseconds. let next = receive.lock().expect("the chunk queue").recv(); let Ok((index, features)) = next else { return }; // `AssertUnwindSafe` because everything the closure touches is a local: the chunk map it- // builds is thrown away on a panic and `touched` is a scratch buffer that `tiles_touched`- // overwrites from the start each time.+ // builds is thrown away on a panic. let tiled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- tile_chunk(&features, z, tolerance, buffer, &mut touched)+ tile_chunk(&features, z, tolerance, buffer) })); match tiled { Ok((chunk, tally)) => done.lock().expect("the chunk list").push((index, chunk, tally)),@@ -484,19 +527,19 @@ fn tile_chunks( } } -/// Project, simplify, bisect and clip one chunk of features into a tile map of its own.+/// Project, simplify and clip one chunk of features into a tile map of its own. /// /// Verbatim the loop this module used to run on the main thread over the whole store, with the /// destination private to the caller. Nothing here reads shared state, and that is why the chunk /// boundaries cannot change a result: a feature's fate depends on the feature, the zoom and the /// tolerance, and on nothing else in the chunk it happens to be in.-fn tile_chunk(- features: &[Feature],- z: u8,- tolerance: f64,- buffer: f64,- touched: &mut Vec<(u64, u64)>,-) -> (Chunk, Tally) {+///+/// The tile loop is a quadtree descent ([`subdivide::subdivide`]), not a pass over every tile the+/// feature touches. A boundary relation spanning three states used to be clipped in full against+/// each of its hundreds of thousands of z13 tiles; now it is clipped once per zoom level. Filtering+/// stays where it was, **before** the descent: significance is measured on the whole geometry, so a+/// vertex's fate must not depend on which tile it lands in.+fn tile_chunk(features: &[Feature], z: u8, tolerance: f64, buffer: f64) -> (Chunk, Tally) { let mut tiles: Chunk = BTreeMap::new(); let mut tally = Tally::default(); for feature in features {@@ -509,21 +552,20 @@ fn tile_chunk( tally.dropped += 1; continue; }- geom::tiles_touched(&thinned, z, EXTENT, buffer, touched);- for &(tx, ty) in touched.iter() {- let rect = geom::tile_rect(tx, ty, EXTENT, buffer);- let clipped = clip::clip_geometry(&thinned, &rect);- if is_empty(&clipped) {- continue;+ 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.+ if is_empty(clipped) {+ return; }- let local = geom::to_tile(&clipped, tx, ty, EXTENT);+ let local = geom::to_tile(clipped, tx, ty, EXTENT); let layer = tiles .entry((tile_id(z, tx, ty), feature.class.layer)) .or_insert_with(|| BodyLayer::new(feature.class.layer)); let added = push(layer, feature, &local); tally.features += added.0; tally.points += added.1;- }+ }); } (tiles, tally) }@@ -642,39 +684,109 @@ fn concatenate(into: &mut BodyLayer, from: BodyLayer) { /// Returns the raw length alongside the compressed frame, because the per-zoom `bytes` column has /// always reported *uncompressed* body size and moving compression must not silently change what a /// build report means.-fn encode_batch(- batch: Vec<(u64, Vec<BodyLayer>)>,-) -> Result<Vec<(u64, Option<(Vec<u8>, usize)>, crate::rings::Stats)>> {+/// Where the encode pass's CPU actually goes, accumulated across workers.+///+/// Nanoseconds, summed per tile. Split three ways because the three steps have nothing to do with+/// each other and the totals cannot say which is which: stage C is geometry with a quadratic+/// hole-versus-hole test in it, serialisation is a memcpy, and DEFLATE at level nine is a+/// throughput-bound compressor. This exists for the same reason+/// [`tile_build::pyramid`]'s `MVT_NANOS` and `GZIP_NANOS` do -- four rounds of plausible-sounding+/// optimisation there bought 3% between them, and splitting the measurement is what found the real+/// cost. Here it found a `clone` of every tile's coordinate arena.+///+/// **Off unless `MAPS_TIMING` is set**, and that is not tidiness. `pyramid`'s counters are hit once+/// per gzip probe, a handful per tile; these are hit three times per tile, and at 943,401 tiles+/// across 64 workers three contended atomics per tile is itself a scalability problem. Leaving them+/// always-on would mean the instrument changed what it measured.+static STAGE_C_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+static SERIALIZE_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+static DEFLATE_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++/// Whether to time the encode split at all. Read once; an `Instant::now()` pair and an atomic per+/// step per tile is not free at this tile count.+fn timing() -> bool {+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *ON.get_or_init(|| std::env::var_os("MAPS_TIMING").is_some())+}++/// The encode split in seconds of CPU: `(stage C, serialise, deflate)`. All zero without+/// `MAPS_TIMING`.+pub fn encode_seconds() -> (f64, f64, f64) {+ let s = |c: &std::sync::atomic::AtomicU64| c.load(Ordering::Relaxed) as f64 / 1e9;+ (s(&STAGE_C_NANOS), s(&SERIALIZE_NANOS), s(&DEFLATE_NANOS))+}++/// Time `f` into `counter`, or just run it when timing is off.+#[inline]+fn timed<R>(on: bool, counter: &std::sync::atomic::AtomicU64, f: impl FnOnce() -> R) -> R {+ if !on {+ return f();+ }+ let at = std::time::Instant::now();+ let out = f();+ counter.fetch_add(at.elapsed().as_nanos() as u64, Ordering::Relaxed);+ out+}++/// One encoded tile on its way back from [`encode_batch`]: its id, the compressed body with its raw+/// length, and what stage C and coalescing did to it.+///+/// 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)>, crate::rings::Stats, crate::coalesce::Stats);++fn encode_batch(batch: Vec<(u64, Vec<BodyLayer>)>) -> Result<Vec<Encoded>> { let min_len = par::min_task_len(batch.len());+ let on = timing(); par::install(|| { batch .into_par_iter() .with_min_len(min_len)- // One DEFLATE state per worker, not one per tile. `compress_to_vec` builds a- // 65,712-byte `CompressorOxide` every call, and at a tile each across 64 cores that- // construction swamps the compression it exists to do -- see- // `mamaps::write::compress_body_with`.- .map_init(tilecodec::gz::Compressor::new, |deflate, (id, mut layers)| {- // **Stage C**, per tile: winding normalised, hole containment resolved, degenerate- // rings dropped. Once, here, in `f64` with no frame budget, instead of every frame- // on device in `i32` under one. This is what makes `FLAG_RINGS_VALIDATED` true.- let mut rings = crate::rings::Stats::default();- for layer in &mut layers {- rings.add(crate::rings::normalise(layer));- }- // A layer that ended up empty - every feature in it fell below the minimum area- // after clipping, or lost its exterior to stage C - costs bytes in the archive and- // a draw call on device for nothing.- layers.retain(|layer| !layer.features.is_empty());- if layers.is_empty() {- return Ok((id, None, rings));- }- let body = Body { extent: EXTENT as u16, layers };- let encoded = tilecodec::mamaps::body::serialize(&body)?;- let raw_len = encoded.len();- let stored = tilecodec::mamaps::write::compress_body_with(deflate, &encoded);- Ok((id, Some((stored, raw_len)), rings))- })+ // One DEFLATE state and one serialisation buffer per worker, not one per tile.+ // `compress_to_vec` builds a 65,712-byte `CompressorOxide` every call, and at a tile+ // each across 64 cores that construction swamps the compression it exists to do -- see+ // `mamaps::write::compress_body_with`. The `Scratch` is there for the same reason on+ // the serialisation side: its allocations, not its encoding, were what made+ // serialisation cost 20.9 s of CPU at 16 threads and 1120 s at 64.+ .map_init(+ || (tilecodec::gz::Compressor::new(), tilecodec::mamaps::body::Scratch::default()),+ |(deflate, scratch), (id, mut layers)| {+ // **Coalesce first.** An OSM way is an editing unit, not a rendering one, so a+ // road arrives as hundreds of two-point fragments each carrying its own 28 bytes+ // of header -- see `crate::coalesce`. Merging them before stage C is also what+ // keeps stage C off tens of thousands of features it would only copy through.+ let mut lines = crate::coalesce::Stats::default();+ for layer in &mut layers {+ lines.add(crate::coalesce::coalesce_lines(layer));+ }+ // **Stage C**, per tile: winding normalised, hole containment resolved,+ // degenerate rings dropped. Once, here, in `f64` with no frame budget, instead+ // of every frame on device in `i32` under one. This is what makes+ // `FLAG_RINGS_VALIDATED` true.+ let mut rings = crate::rings::Stats::default();+ timed(on, &STAGE_C_NANOS, || {+ for layer in &mut layers {+ rings.add(crate::rings::normalise(layer));+ }+ // A layer that ended up empty - every feature in it fell below the minimum+ // area after clipping, or lost its exterior to stage C - costs bytes in the+ // archive and a draw call on device for nothing.+ layers.retain(|layer| !layer.features.is_empty());+ });+ if layers.is_empty() {+ return Ok((id, None, rings, lines));+ }+ let body = Body { extent: EXTENT as u16, layers };+ let encoded = timed(on, &SERIALIZE_NANOS, || {+ tilecodec::mamaps::body::serialize_into(&body, scratch)+ })?;+ let raw_len = encoded.len();+ let stored = timed(on, &DEFLATE_NANOS, || {+ tilecodec::mamaps::write::compress_body_with(deflate, encoded)+ });+ Ok((id, Some((stored, raw_len)), rings, lines))+ },+ ) .collect() }) }
scripts/maps/measure_build.ps1
diff --git a/scripts/maps/measure_build.ps1 b/scripts/maps/measure_build.ps1new file mode 100644index 0000000000..d878aefdc3--- /dev/null+++ b/scripts/maps/measure_build.ps1@@ -0,0 +1,235 @@+# measure_build.ps1 — build one .mamaps and report what it cost.+#+# One command, live progress, and a summary at the end.+#+# The build's own output goes **straight to the console**, not through a pipeline. That+# matters: the progress bars redraw with a carriage return and no newline, and anything+# that pipes them buffers until the line ends, so a piped bar does not animate — it+# appears once, finished. The numbers for the summary come from `--report`, which the+# build already writes as JSON, rather than from screen-scraping what you just watched.+#+# What this adds that the binary cannot easily measure about itself on Windows:+# * Peak resident memory. `PeakWorkingSet64` is a kernel high-water mark, so sampling+# from outside cannot miss a spike between two polls.+# * Peak scratch disk. The spill is written during stage A and drained during tiling,+# so it is gone before the build ends and only a sampler ever sees its size.+# * The archive's section breakdown, from `mamaps_dump`, which already decodes the+# header — reimplementing that here would be a second copy to keep in step.+#+# Usage:+# .\measure_build.ps1 -Pbf ..\..\..\maps-work\us-west-latest.osm.pbf -Out usw.mamaps+# .\measure_build.ps1 -Pbf north-america-latest.osm.pbf -Out na.mamaps -MaxZoom 13 -Keep+# .\measure_build.ps1 -Pbf x.osm.pbf -Out x.mamaps -Timing # + encode / node-pass CPU+param(+ [Parameter(Mandatory = $true)][string] $Pbf,+ [Parameter(Mandatory = $true)][string] $Out,+ [int] $MaxZoom = 14,+ [int] $MinZoom = 0,+ [int] $Threads = 0,+ # Prints the encode and node-pass CPU splits. Off by default because the counters+ # behind it are hit per tile on every worker, and an instrument that contends changes+ # what it measures.+ [switch] $Timing,+ [switch] $Keep,+ # Leave the feature spill and its index behind, so a later -ReuseStore run skips stage A.+ [switch] $KeepStore,+ # Tile from a spill an earlier -KeepStore run left. Stage A is most of a large build and is+ # identical every time for the same input, so this is the difference between a 20-minute+ # experiment and a 60-minute one. Refused if the spill was built from anything else.+ [switch] $ReuseStore,+ [string] $Exe,+ [string] $Dump+)++$ErrorActionPreference = "Stop"+$repo = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)++function Find-Binary([string] $given, [string] $crate, [string] $name) {+ if ($given) { return (Resolve-Path $given).Path }+ $built = Join-Path $repo "scripts\maps\$crate\target\release\$name.exe"+ if (Test-Path $built) { return $built }+ throw "no $name.exe — run: cargo build --release --manifest-path scripts\maps\$crate\Cargo.toml"+}++$build = Find-Binary $Exe "mamaps_build" "mamaps_build"+$dump = Find-Binary $Dump "tile_build" "mamaps_dump"+$Pbf = (Resolve-Path $Pbf).Path+$Out = [System.IO.Path]::GetFullPath($Out)+# Named by the writer, beside the output. This is the scratch that peaks.+$spill = [System.IO.Path]::ChangeExtension($Out, "features.tmp")+$json = "$Out.report.json"+$name = [System.IO.Path]::GetFileNameWithoutExtension($build)++if (Test-Path $Out) { Remove-Item $Out -Force }+if (Test-Path $json) { Remove-Item $json -Force }+if ($KeepStore -and $ReuseStore) { throw "-KeepStore and -ReuseStore are opposites; pass one" }+if ($ReuseStore -and -not (Test-Path $spill)) {+ throw "-ReuseStore needs a spill at $spill — run once with -KeepStore first"+}+if ($Threads -gt 0) { $env:MAPS_THREADS = "$Threads" } else { Remove-Item Env:MAPS_THREADS -ErrorAction SilentlyContinue }+if ($Timing) { $env:MAPS_TIMING = "1" } else { Remove-Item Env:MAPS_TIMING -ErrorAction SilentlyContinue }++# Started before the build, so the first spike cannot be missed.+$sampler = Start-Job -ArgumentList $name, $spill, $Out -ScriptBlock {+ param($name, $spill, $out)+ $peakWs = 0L; $peakPriv = 0L; $peakSpill = 0L; $peakData = 0L+ while ($true) {+ $p = Get-Process -Name $name -ErrorAction SilentlyContinue+ if ($p) {+ $peakWs = [Math]::Max($peakWs, ($p | Measure-Object PeakWorkingSet64 -Maximum).Maximum)+ $peakPriv = [Math]::Max($peakPriv, ($p | Measure-Object PrivateMemorySize64 -Maximum).Maximum)+ }+ foreach ($pair in @(@($spill, [ref]$peakSpill), @("$out.tiledata", [ref]$peakData))) {+ if (Test-Path $pair[0]) {+ $len = (Get-Item $pair[0] -ErrorAction SilentlyContinue).Length+ if ($len -gt $pair[1].Value) { $pair[1].Value = $len }+ }+ }+ [pscustomobject]@{ Ws = $peakWs; Priv = $peakPriv; Spill = $peakSpill; Data = $peakData }+ Start-Sleep -Milliseconds 250+ }+}++$flags = @()+if ($KeepStore) { $flags += "--keep-store" }+if ($ReuseStore) { $flags += "--reuse-store" }++Write-Output ("=== {0} -> {1} z{2}..z{3}{4}{5} ===" -f `+ (Split-Path $Pbf -Leaf), (Split-Path $Out -Leaf), $MinZoom, $MaxZoom,+ $(if ($Threads -gt 0) { ", $Threads thread(s)" } else { "" }),+ $(if ($ReuseStore) { ", reusing the spill" } elseif ($KeepStore) { ", keeping the spill" } else { "" }))+Write-Output ""++# No pipeline, no redirect: the bars need the console to redraw on.+$sw = [System.Diagnostics.Stopwatch]::StartNew()+& $build --input $Pbf --out $Out --min-zoom $MinZoom --max-zoom $MaxZoom --report $json @flags+$exit = $LASTEXITCODE+$sw.Stop()++Start-Sleep -Milliseconds 400+$s = Receive-Job $sampler+Stop-Job $sampler; Remove-Job $sampler -Force+$peakWs = ($s | Measure-Object Ws -Maximum).Maximum+$peakPriv = ($s | Measure-Object Priv -Maximum).Maximum+$peakSpill = ($s | Measure-Object Spill -Maximum).Maximum+$peakData = ($s | Measure-Object Data -Maximum).Maximum++# Adaptive, because these span a 128-byte header and a 30 GB spill; a fixed unit makes+# one end of that unreadable.+function Size([double] $b) {+ if ($b -ge 1GB) { return "{0,9:N2} GB" -f ($b / 1GB) }+ if ($b -ge 1MB) { return "{0,9:N1} MB" -f ($b / 1MB) }+ if ($b -ge 1KB) { return "{0,9:N1} KB" -f ($b / 1KB) }+ return "{0,9:N0} B " -f $b+}++Write-Output ""+Write-Output "======================== RESULT ========================"+if ($exit -ne 0) {+ Write-Output ("FAILED, exit {0}, after {1:N1} s" -f $exit, $sw.Elapsed.TotalSeconds)+ exit $exit+}+$r = Get-Content $json -Raw | ConvertFrom-Json+$archive = if (Test-Path $Out) { (Get-Item $Out).Length } else { 0 }++# --- time, per step -------------------------------------------------------+# Tiling is per zoom and comes from the report; stage A's marks are cumulative and are+# printed by the build itself as it goes, so they are summarised rather than repeated.+$map = ($r.zooms | Measure-Object map_ms -Sum).Sum+$mrg = ($r.zooms | Measure-Object merge_ms -Sum).Sum+$enc = ($r.zooms | Measure-Object encode_ms -Sum).Sum+$app = ($r.zooms | Measure-Object append_ms -Sum).Sum+$tiling = ($map + $mrg + $enc + $app) / 1000.0+$stageA = $sw.Elapsed.TotalSeconds - $tiling+Write-Output ""+Write-Output "TIME"+Write-Output (" {0,-24} {1,8:N1} s {2,5:N1}% {3}" -f `+ "stage A", $stageA, (100.0 * $stageA / $sw.Elapsed.TotalSeconds),+ $(if ($ReuseStore) { "SKIPPED (spill reused) - this is open/report overhead" } else { "parse, resolve, materialise, spill" }))+foreach ($p in @(@("map (clip)", $map), @("merge", $mrg), @("encode", $enc), @("append", $app))) {+ Write-Output (" {0,-24} {1,8:N1} s {2,5:N1}%" -f `+ $p[0], ($p[1] / 1000.0), (100.0 * $p[1] / 1000.0 / $sw.Elapsed.TotalSeconds))+}+Write-Output (" {0,-24} {1,8:N1} s" -f "TOTAL WALL", $sw.Elapsed.TotalSeconds)++# --- per zoom -------------------------------------------------------------+Write-Output ""+Write-Output "PER ZOOM"+Write-Output (" {0,-5}{1,12}{2,14}{3,16}{4,10}{5,9}{6,9}{7,9}" -f `+ "zoom", "tiles", "features", "body bytes", "map_s", "merge_s", "enc_s", "app_s")+foreach ($z in $r.zooms) {+ Write-Output (" z{0,-4}{1,12:N0}{2,14:N0}{3,16:N0}{4,10:N1}{5,9:N1}{6,9:N1}{7,9:N1}" -f `+ $z.zoom, $z.tiles, $z.features, $z.bytes,+ ($z.map_ms / 1000.0), ($z.merge_ms / 1000.0), ($z.encode_ms / 1000.0), ($z.append_ms / 1000.0))+}++# --- memory ---------------------------------------------------------------+Write-Output ""+Write-Output "PEAK MEMORY"+Write-Output (" {0,-24} {1} kernel high-water, cannot be missed" -f "resident", (Size $peakWs))+Write-Output (" {0,-24} {1}" -f "committed private", (Size $peakPriv))++# --- disk -----------------------------------------------------------------+# The input is read-only and pre-existing, so it is reported apart from what the build+# creates. Spill and archive do not peak together, so their sum is an upper bound.+Write-Output ""+Write-Output "DISK"+Write-Output (" {0,-24} {1} read-only input" -f "source .pbf", (Size (Get-Item $Pbf).Length))+Write-Output (" {0,-24} {1} scratch, deleted" -f "feature spill, peak", (Size $peakSpill))+if ($peakData -gt 0) {+ Write-Output (" {0,-24} {1} scratch, deleted" -f "tile scratch, peak", (Size $peakData))+}+Write-Output (" {0,-24} {1} the deliverable" -f "archive", (Size $archive))+Write-Output (" {0,-24} {1} upper bound; the scratches do not peak together" -f `+ "created, worst case", (Size ($peakSpill + $peakData + $archive)))++# --- the archive, by part -------------------------------------------------+$h = @{}+foreach ($line in (& $dump $Out --mode header)) {+ $f = $line -split "`t"+ if ($f.Count -ge 2) { $h[$f[0]] = $f[1] }+}+function Span([string] $key) {+ # `offset+length`, as the header mode prints it.+ if ($h.ContainsKey($key) -and $h[$key] -match '^(\d+)\+(\d+)$') { return [long]$Matches[2] }+ return 0L+}+Write-Output ""+Write-Output "ARCHIVE BY PART"+foreach ($part in @(+ @("header", 128, "fixed"),+ @("dictionary", (Span "dict"), "layer / kind / detail names"),+ @("root index", (Span "root"), "one entry per leaf, binary-searched"),+ @("leaf index", (Span "leaves"), "16 B per stored body"),+ @("tile bodies", (Span "data"), "the geometry, DEFLATE'd per body")+)) {+ $pct = if ($archive -gt 0) { 100.0 * $part[1] / $archive } else { 0 }+ Write-Output (" {0,-14}{1} {2,6:N2}% {3}" -f $part[0], (Size $part[1]), $pct, $part[2])+}+Write-Output (" {0,-14}{1} {2,6:N2}%" -f "TOTAL", (Size $archive), 100.0)++$bodyBytes = ($r.zooms | Measure-Object bytes -Sum).Sum+Write-Output ""+Write-Output (" tiles addressed {0,14:N0}" -f [long]$h["tiles_addressed"])+Write-Output (" bodies written {0,14:N0} dedup {1} — run-length plus content" -f [long]$h["bodies_written"], $h["dedup"])+Write-Output (" body bytes raw {0,14:N0} {1:N2}x compression into the archive" -f `+ $bodyBytes, ($bodyBytes / [Math]::Max(1, (Span "data"))))+Write-Output (" features {0,14:N0} from {1:N0} ways + {2:N0} relations" -f `+ $r.features, $r.ways_classified, $r.relations_classified)+if ($r.coalesced.line_features_before -gt $r.coalesced.line_features_after) {+ Write-Output (" coalesced {0,14:N0} -> {1:N0} line features ({2:N0}x), {3:N0} -> {4:N0} parts ({5:N1}x)" -f `+ $r.coalesced.line_features_before, $r.coalesced.line_features_after,+ ($r.coalesced.line_features_before / [Math]::Max(1, $r.coalesced.line_features_after)),+ $r.coalesced.parts_before, $r.coalesced.parts_after,+ ($r.coalesced.parts_before / [Math]::Max(1, $r.coalesced.parts_after)))+}+Write-Output (" build id {0,14}" -f $h["build_id"])+Write-Output (" sha256 {0}" -f (Get-FileHash $Out -Algorithm SHA256).Hash)++if (-not $Keep) {+ Remove-Item $Out -Force -ErrorAction SilentlyContinue+ Remove-Item $json -Force -ErrorAction SilentlyContinue+ Write-Output ""+ Write-Output " (archive removed; pass -Keep to keep it)"+}+Write-Output ""
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 b5c8d30c21..d02301443d 100644--- a/scripts/maps/osm_ingest/src/nodeloc.rs+++ b/scripts/maps/osm_ingest/src/nodeloc.rs@@ -153,9 +153,32 @@ struct IdIndex { len: usize, } +/// One `offsets` entry, or an error when `deltas` has outgrown a `u32`.+fn offset(at: usize) -> Result<u32> {+ u32::try_from(at).map_err(|_| {+ Error(format!("an id index's delta bytes ({at}) are past the {} it can address", u32::MAX))+ })+}+ impl IdIndex { /// Build from ids that are already sorted and unique.- fn build(ids: &[i64]) -> IdIndex {+ ///+ /// Errors rather than truncates on the two `u32` fields, because both are within reach at planet+ /// scale and both fail silently: a truncated `offsets` entry sends [`IdIndex::find`] scanning+ /// from the wrong place in `deltas`, and a truncated position sends a coordinate to the wrong+ /// node. Neither produces a wrong-looking value -- they produce a plausible one, which is worse.+ /// `deltas` runs about 1.1 bytes per id, so the 4.29 GB ceiling is roughly 3.9 G ids away; the+ /// crate's README already flags exactly this class of bug for `road_graph`.+ fn build(ids: &[i64]) -> Result<IdIndex> {+ // A position is returned as a `u32` by `find`, so the id count is capped by that and not by+ // the delta bytes.+ if ids.len() > u32::MAX as usize {+ return Err(Error(format!(+ "{} node ids is past the {} an id index can address",+ ids.len(),+ u32::MAX,+ )));+ } let blocks = ids.len().div_ceil(BLOCK); let mut index = IdIndex { bases: Vec::with_capacity(blocks),@@ -166,7 +189,7 @@ impl IdIndex { }; for block in ids.chunks(BLOCK) { index.bases.push(block[0]);- index.offsets.push(index.deltas.len() as u32);+ index.offsets.push(offset(index.deltas.len())?); let mut previous = block[0]; for &id in &block[1..] { // Non-negative because the input is sorted and unique, so the gap is at least one.@@ -174,9 +197,9 @@ impl IdIndex { previous = id; } }- index.offsets.push(index.deltas.len() as u32);+ index.offsets.push(offset(index.deltas.len())?); index.deltas.shrink_to_fit();- index+ Ok(index) } fn len(&self) -> usize {@@ -211,6 +234,107 @@ impl IdIndex { } None }++ /// A cursor for a run of **ascending** lookups.+ ///+ /// [`Self::find`] pays a binary search over `bases` per call. That is the right shape for a random+ /// lookup and the wrong one for the node pass, which asks about every node in a PBF block in+ /// ascending order: `bases` grew from 53 MB on a us-west extract to 290 MB on a north-america one,+ /// so each of those searches became about twenty-two cache misses plus the page walks to reach+ /// them. Measured, the pass spent 317.9 s of CPU searching against 5.1 s writing, and went 90x+ /// between those two extracts for 5.4x the nodes -- superlinear, because the array stopped+ /// fitting rather than because there was more work.+ ///+ /// A cursor searches once and then walks, which is one sequential sweep instead of thousands of+ /// scattered probes. Correct for any query order -- a query that goes backwards re-seeks -- so it+ /// does not depend on the PBF actually being sorted, only on it usually being sorted to be fast.+ fn cursor(&self) -> Cursor<'_> {+ Cursor { index: self, block: 0, at: 0, current: 0, position: 0, live: false }+ }+}++/// How many blocks a cursor will walk past before it gives up and searches instead.+///+/// Without a bound, a worker handed a distant blob would scan from wherever it happened to be, which+/// is the pathological case this whole change is meant to avoid. Sixty-four blocks is 4096 ids: past+/// that a binary search is cheaper than the walk.+const FORWARD_SCAN_BLOCKS: usize = 64;++/// A forward cursor into an [`IdIndex`]. See [`IdIndex::cursor`].+struct Cursor<'a> {+ index: &'a IdIndex,+ /// The block the cursor sits inside.+ block: usize,+ /// Offset into `deltas` just past `current`.+ at: usize,+ /// The id the cursor is on.+ current: i64,+ /// Position of `current` in the set.+ position: usize,+ /// False before the first lookup, when `current` means nothing.+ live: bool,+}++impl Cursor<'_> {+ /// The position of `id`, or `None` if it is not in the set.+ ///+ /// Answers exactly what [`IdIndex::find`] would, which a test asserts over thousands of cases in+ /// both ascending and shuffled order.+ fn find(&mut self, id: i64) -> Option<u32> {+ if !self.live || id < self.current || self.too_far(id) {+ let block = match self.index.bases.binary_search(&id) {+ Ok(block) => block,+ // Before the first id in the set. The cursor is left alone: a miss says nothing about+ // where the next hit will be.+ Err(0) => return None,+ Err(next) => next - 1,+ };+ self.enter(block);+ }+ while self.current < id {+ if !self.step() {+ return None;+ }+ }+ if self.current == id {+ Some(self.position as u32)+ } else {+ None+ }+ }++ /// Whether `id` is far enough ahead that walking to it would cost more than a search.+ fn too_far(&self, id: i64) -> bool {+ let ahead = self.block + FORWARD_SCAN_BLOCKS;+ ahead < self.index.bases.len() && self.index.bases[ahead] <= id+ }++ /// Sit on `block`'s first id.+ fn enter(&mut self, block: usize) {+ self.block = block;+ self.current = self.index.bases[block];+ self.at = self.index.offsets[block] as usize;+ self.position = block * BLOCK;+ self.live = true;+ }++ /// Move to the next id in the set. `false` at the end, leaving the cursor where it was.+ fn step(&mut self) -> bool {+ let end = self.index.offsets[self.block + 1] as usize;+ if self.at < end {+ let (gap, used) = get_uvarint(&self.index.deltas[self.at..]);+ self.at += used;+ self.current += gap as i64;+ self.position += 1;+ return true;+ }+ // The block is spent, and the next block's base is the next id.+ if self.block + 1 >= self.index.bases.len() {+ return false;+ }+ self.enter(self.block + 1);+ true+ } } /// LEB128, as the rest of this crate spells varints.@@ -244,7 +368,7 @@ impl NodeLocations { pub fn new(mut ids: Vec<i64>) -> Result<NodeLocations> { ids.sort_unstable(); ids.dedup();- let index = IdIndex::build(&ids);+ 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 mapped, so the two never peak together.@@ -283,6 +407,34 @@ impl NodeLocations { } } +/// Where the node pass's CPU goes, split between decoding blocks and writing coordinates.+///+/// Nanoseconds. `SCAN_NANOS` covers **both** the protobuf decode of a block and the id lookups for+/// its nodes, because it brackets the whole `visit_block` call -- timing the lookups alone would need+/// a clock read per node, and there are 2.3 billion of them on a north-america extract. An earlier+/// version of this comment called it "searching" and a conclusion was drawn from it about the id+/// index; that was wrong, and the number cannot tell those two apart. What it does bound is the+/// write side, which is the part that is serialised: `run_pass_sink` calls its sink under a lock.+///+/// Timed per CHUNK rather than per node -- a chunk is eight blobs, tens of thousands of nodes -- so+/// two `Instant::now()` calls and one atomic add cost nothing measurable. Off unless `MAPS_TIMING`+/// is set regardless, for the reason `mamaps_build`'s encode counters are: an instrument hit once per+/// item across 64 workers changes what it measures.+static SCAN_NANOS: atomic::AtomicU64 = atomic::AtomicU64::new(0);+static WRITE_NANOS: atomic::AtomicU64 = atomic::AtomicU64::new(0);++fn timing() -> bool {+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *ON.get_or_init(|| std::env::var_os("MAPS_TIMING").is_some())+}++/// The node pass's split in seconds of CPU: `(decode and look up, write)`. Zero without+/// `MAPS_TIMING`.+pub fn resolve_seconds() -> (f64, f64) {+ let s = |c: &atomic::AtomicU64| c.load(atomic::Ordering::Relaxed) as f64 / 1e9;+ (s(&SCAN_NANOS), s(&WRITE_NANOS))+}+ /// The node pass: fill in every coordinate the earlier passes asked for. /// /// Uses [`pbf::run_pass_sink`] rather than [`pbf::run_pass`], because `run_pass`'s contract is to@@ -305,6 +457,7 @@ pub fn resolve_nodes( if table.is_empty() { return Ok(table); }+ let on = timing(); // 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;@@ -316,21 +469,33 @@ pub fn resolve_nodes( label, Vec::<(u32, i32, i32)>::new, |state: &mut Vec<(u32, i32, i32)>, block| {+ let at = on.then(std::time::Instant::now); let mut kinds = 0u8;+ // One cursor per block, because that is the run of ascending ids: a PBF block's dense+ // nodes are delta-encoded and therefore sorted, so this pays one binary search here and+ // walks the rest.+ let mut cursor = ids.cursor(); visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| { if let Element::Node(n) = el {- if let Some(idx) = ids.find(n.id) {+ if let Some(idx) = cursor.find(n.id) { state.push((idx, n.lat_e7, n.lon_e7)); } } Ok(()) })?;+ if let Some(at) = at {+ SCAN_NANOS.fetch_add(at.elapsed().as_nanos() as u64, atomic::Ordering::Relaxed);+ } Ok(kinds) }, |chunk| {+ let at = on.then(std::time::Instant::now); for (idx, lat, lon) in chunk { locs.set(idx as usize, lat, lon); }+ if let Some(at) = at {+ WRITE_NANOS.fetch_add(at.elapsed().as_nanos() as u64, atomic::Ordering::Relaxed);+ } Ok(()) }, )?;@@ -340,6 +505,98 @@ pub fn resolve_nodes( #[cfg(test)] mod tests {+ /// **The test the cursor lives or dies by.** It has to answer exactly what [`IdIndex::find`] does+ /// for every id, in ascending order (its fast path), in shuffled order (where it must re-seek),+ /// and for ids that are absent — including ones below the first and above the last.+ ///+ /// Ascending alone would not catch it: the whole risk of a cursor is that it is correct while+ /// walking forwards and wrong the moment something asks out of order, and nothing in the PBF+ /// format actually promises sorted ids.+ #[test]+ fn the_cursor_answers_exactly_what_a_fresh_search_would() {+ let mut state = 0x9E37_79B9_7F4A_7C15u64;+ let mut next = || {+ state ^= state << 13;+ state ^= state >> 7;+ state ^= state << 17;+ state+ };+ // Spans several blocks, with gaps too large for a one-byte varint so the walk has to handle+ // multi-byte deltas, and a run of dense ids so it handles the cheap case too.+ let mut ids: Vec<i64> = Vec::new();+ let mut id = 5i64;+ for i in 0..1000 {+ id += if i % 7 == 0 { (next() % 300_000) as i64 + 1 } else { (next() % 4) as i64 + 1 };+ ids.push(id);+ }+ ids.sort_unstable();+ ids.dedup();+ let index = super::IdIndex::build(&ids).expect("an index that fits");++ // Every id, ascending: the path the node pass actually takes.+ let mut cursor = index.cursor();+ for &want in &ids {+ assert_eq!(cursor.find(want), index.find(want), "ascending, id {want}");+ }++ // Absent ids interleaved with present ones, still ascending.+ let mut cursor = index.cursor();+ for &want in &ids {+ assert_eq!(cursor.find(want - 1), index.find(want - 1), "ascending gap below {want}");+ assert_eq!(cursor.find(want), index.find(want), "ascending, id {want}");+ }++ // Shuffled, which forces a re-seek on most calls.+ let mut shuffled = ids.clone();+ for i in (1..shuffled.len()).rev() {+ shuffled.swap(i, (next() % (i as u64 + 1)) as usize);+ }+ let mut cursor = index.cursor();+ for &want in &shuffled {+ assert_eq!(cursor.find(want), index.find(want), "shuffled, id {want}");+ }++ // Strictly descending, the worst order for a forward cursor.+ let mut cursor = index.cursor();+ for &want in ids.iter().rev() {+ assert_eq!(cursor.find(want), index.find(want), "descending, id {want}");+ }++ // Outside the set at both ends, and far enough past the end to trip the scan bound.+ let first = ids[0];+ let last = ids[ids.len() - 1];+ let mut cursor = index.cursor();+ for want in [i64::MIN, first - 1, 0, last + 1, last + 10_000_000, i64::MAX] {+ assert_eq!(cursor.find(want), index.find(want), "outside, id {want}");+ }++ // A jump far ahead then far back, which is what work stealing does to a live cursor.+ let mut cursor = index.cursor();+ assert_eq!(cursor.find(ids[0]), index.find(ids[0]));+ assert_eq!(cursor.find(last), index.find(last));+ assert_eq!(cursor.find(ids[0]), index.find(ids[0]));+ assert_eq!(cursor.find(ids[ids.len() / 2]), index.find(ids[ids.len() / 2]));+ }++ /// The cursor must be right on a set small enough to have one partial block, where `position`+ /// arithmetic that assumed full blocks would still look plausible.+ #[test]+ fn the_cursor_is_right_on_a_set_smaller_than_one_block() {+ for count in [1usize, 2, 63, 64, 65, 129] {+ let ids: Vec<i64> = (0..count as i64).map(|i| i * 3 + 11).collect();+ let index = super::IdIndex::build(&ids).expect("an index that fits");+ let mut cursor = index.cursor();+ for &want in &ids {+ assert_eq!(cursor.find(want), index.find(want), "{count} id(s), id {want}");+ }+ let mut cursor = index.cursor();+ for &want in &ids {+ let miss = want + 1;+ assert_eq!(cursor.find(miss), index.find(miss), "{count} id(s), absent {miss}");+ }+ }+ }+ /// **The test the compressed index lives or dies by.** It has to answer exactly what a plain /// `binary_search` over the same ids would, for ids that are present and ids that are not, and it /// has to hold at block boundaries and across gaps too large for
Diff truncated.