Modern Apps git

← Modern-Apps.git

maps: spill the ways table, and tile on every core

Commit
7ad6fa443379548b05bb799ae9b8bc500afe8285
Author
vayun-mathur <[email protected]>
When
2026-08-28 04:50 UTC (3 months ago)
Parents
cc11506

Diff

scripts/maps/mamaps_build/Cargo.lock
diff --git a/scripts/maps/mamaps_build/Cargo.lock b/scripts/maps/mamaps_build/Cargo.lockindex a1fb989653..b94bccd67e 100644--- a/scripts/maps/mamaps_build/Cargo.lock+++ b/scripts/maps/mamaps_build/Cargo.lock@@ -44,6 +44,7 @@ name = "mamaps_build" version = "0.1.0" dependencies = [  "osm_ingest",+ "rayon",  "tile_build",  "tilecodec", ]
scripts/maps/mamaps_build/Cargo.toml
diff --git a/scripts/maps/mamaps_build/Cargo.toml b/scripts/maps/mamaps_build/Cargo.tomlindex 9896650d78..ed8cc1dff4 100644--- a/scripts/maps/mamaps_build/Cargo.toml+++ b/scripts/maps/mamaps_build/Cargo.toml@@ -32,6 +32,10 @@ path = "src/main.rs" tilecodec = { path = "../../../library/tilecodec/src/main/rust", features = ["write"] } tile_build = { path = "../tile_build" } osm_ingest = { path = "../osm_ingest" }+# Already in this lockfile through both `tile_build` and `osm_ingest`, so this adds+# 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"  [profile.release] opt-level = 3
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 c8da727a0b..df59635f37 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -3,11 +3,12 @@ //! Three passes, because a PBF is ordered nodes-then-ways-then-relations and a way's geometry needs //! coordinates that arrived before its tags did: //!-//! 1. **ways + relations.** Classify tags. Keep the node refs of every classified way and the member-//!    way ids of every classified relation. Node blobs are skipped outright.-//! 2. **ways again**, keeping the refs of the ways that turned out to be relation members. A second-//!    pass rather than keeping every untagged way's refs from the first, because "every untagged way-//!    in California" is 40 M node ids and the members are a few thousand.+//! 1. **ways + relations.** Classify tags. Spill the node refs of every classified way to a+//!    sequential file and keep the member way ids of every classified relation. Node blobs are+//!    skipped outright.+//! 2. **ways again**, keeping the refs of the ways some relation lists as a member. A second pass+//!    rather than keeping every untagged way's refs from the first, because "every untagged way in+//!    California" is 40 M node ids and the members are a few hundred thousand. //! 3. **nodes.** Fill coordinates for exactly the ids the first two passes asked for, at 16 bytes //!    per needed node. //!@@ -15,8 +16,16 @@ //! `O(needed)`; `graph_build`'s bitset costs 2.5 GB keyed by raw OSM node id whatever the extract, //! and peaks near 10 GB on California. A water-and-buildings build needs a few million nodes, so it //! pays tens of megabytes.+//!+//! # Nothing large is resident across the passes+//!+//! Neither of the two big tables this stage produces is held in memory. Features go to+//! [`Store`]; classified ways go to [`WaySink`], exploiting the fact that pass 1 already sees them+//! in ascending id order so no sort is needed to read them back in the order the archive wants.+//! What stays resident is the set a sequential file cannot serve: the refs of the ways that some+//! relation lists as a member, because a relation reaches those by id in its own order. -use std::collections::{HashMap, HashSet};+use std::collections::HashMap; use std::path::Path;  use osm_ingest::nodeloc::{resolve_nodes, NodeLocations};@@ -28,7 +37,7 @@ use osm_ingest::select::Select; use tile_build::geom::Geometry;  use crate::schema::{self, Class, Layers};-use crate::store::{Sink, Store};+use crate::store::{Sink, Store, WayCounts, WayReader, WaySink};  /// One classified feature, in lon/lat, ready to tile. pub struct Feature {@@ -51,7 +60,7 @@ pub struct Stats {     pub rings: RingStats, } -/// A classified way, held between passes.+/// A classified way, held only from the blob it was decoded in until its chunk reaches [`WaySink`]. struct Way {     class: Class,     refs: Vec<i64>,@@ -72,7 +81,8 @@ struct Relation { /// Read `input` and spill every feature the schema classifies to `spill_path`. /// /// Features go to disk rather than into a `Vec`, because holding them was 4.9 GB of a measured-/// 10.03 GB California peak and nothing reads them until the tiler does. See [`crate::store`].+/// 10.03 GB California peak and nothing reads them until the tiler does. Classified ways go to a+/// scratch file beside it for the same reason. See [`crate::store`]. pub fn extract(     input: &Path,     layers: Layers,@@ -82,12 +92,23 @@ pub fn extract(     let blobs = pbf::scan_blobs(input)?;     let select = Select::parse(&schema::filters(layers))?;     let mut stats = Stats::default();+    // Scratch for this function alone: written in pass 1, read twice below, and removed as soon as+    // the last read is done. Beside the feature spill, so a build directed at a writable output+    // directory needs nothing else to be writable.+    let ways_path = spill_path.with_extension("ways.tmp");      // --- pass 1: ways and relations -------------------------------------------------------     //+    // `run_pass_sink` rather than `run_pass`, because `run_pass`'s contract is to hand back every+    // chunk at once and these chunks hold the node refs of every classified way — the 2.7 GB this+    // spill exists to be rid of. Here a chunk is appended to the file and freed while its+    // neighbours are still decoding.+    //     // `blob_kinds` comes back from this pass and lets the later ones skip whole blobs, which on a     // planet extract is most of the file.-    let (chunks, blob_kinds) = pbf::run_pass(+    let mut ways = WaySink::create(&ways_path)?;+    let mut relations: Vec<Relation> = Vec::new();+    let blob_kinds = pbf::run_pass_sink(         input,         &blobs,         None,@@ -139,23 +160,32 @@ pub fn extract(             })?;             Ok(kinds)         },+        |(chunk_ways, chunk_relations)| {+            // Chunks arrive in file order and a PBF's ways are sorted by id, so appending here+            // leaves the file in ascending id order. `WaySink::push` refuses an id that does not+            // advance rather than letting an unsorted file reorder the archive silently.+            for (id, way) in chunk_ways {+                ways.push(id, &way.class, &way.refs)?;+            }+            relations.extend(chunk_relations);+            Ok(())+        },     )?;--    let mut ways: HashMap<i64, Way> = HashMap::new();-    let mut relations: Vec<Relation> = Vec::new();-    for (chunk_ways, chunk_relations) in chunks {-        ways.extend(chunk_ways);-        relations.extend(chunk_relations);-    }-    stats.ways_classified = ways.len() as u64;+    let WayCounts { ways: ways_classified, refs: way_refs } = ways.finish()?;+    stats.ways_classified = ways_classified;     stats.relations_classified = relations.len() as u64; -    // --- pass 2: the member ways pass 1 did not keep --------------------------------------+    // --- pass 2: the refs of every relation member way ------------------------------------+    //+    // **Every** member, not just the ones pass 1 did not classify. A relation reaches its members by+    // id, in the order it lists them, which is the one random access in this stage and the one thing+    // a sequential spill file cannot serve. So the members — and only the members — stay resident,+    // and that is what lets the other several million classified ways go to disk. California has+    // 63 156 relations, so this table is small next to the one it replaces.     let wanted: Vec<i64> = {         let mut wanted: Vec<i64> = relations             .iter()             .flat_map(|r| r.members.iter().map(|(id, _)| *id))-            .filter(|id| !ways.contains_key(id))             .collect();         wanted.sort_unstable();         wanted.dedup();@@ -189,62 +219,57 @@ pub fn extract(     }      // --- pass 3: the coordinates those two asked for ---------------------------------------    let mut needed: Vec<i64> = Vec::new();-    for way in ways.values() {-        needed.extend_from_slice(&way.refs);+    //+    // The classified ways are read off disk instead of walked in memory. Order does not matter here+    // — `NodeLocations::new` sorts and dedups — so this is a plain streaming pass over the spill.+    //+    // Sized exactly rather than grown into. This is ~200 M ids on California, and a `Vec` that+    // doubles its way there holds the old and the new allocation at once across the last realloc:+    // 1.1 GB plus 2.1 GB, for a length both passes already know.+    let member_refs: usize = members.values().map(|refs| refs.len()).sum();+    let mut needed: Vec<i64> = Vec::with_capacity(way_refs as usize + member_refs);+    {+        let mut reader = WayReader::open(&ways_path)?;+        let mut refs: Vec<i64> = Vec::new();+        while reader.next(&mut refs)?.is_some() {+            needed.extend_from_slice(&refs);+        }     }+    // A member way that pass 1 also classified already contributed its refs above; `members` adds+    // the ones — the great majority, since a multipolygon's rings usually carry no tags of their+    // own — that nothing else asked for.     for refs in members.values() {         needed.extend_from_slice(refs);     }-    for relation in &relations {-        for (id, _) in &relation.members {-            if let Some(way) = ways.get(id) {-                needed.extend_from_slice(&way.refs);-            }-        }-    }     let table = NodeLocations::new(needed);     stats.nodes_needed = table.len() as u64;     let table = resolve_nodes(input, &blobs, &blob_kinds, "Pass 3: nodes", table)?;      // --- materialise ----------------------------------------------------------------------     //-    // Ways in **id order**, not hash order, because the output has to be reproducible and a-    // `HashMap`'s iteration is not. The one place in this pipeline where that is a real risk.+    // Ways in **id order**, which is the order the spill file is already in. It used to be a sort of+    // a `HashMap`'s keys, for the same reason: the output has to be reproducible and hash order is+    // not. The one place in this pipeline where that was a real risk, and now it is a property of+    // the file rather than a step that could be forgotten.     let mut sink = Sink::create(spill_path)?;---    // Which ways a relation still needs. Everything else can have its refs freed the moment its own-    // geometry is built, which is what keeps the refs heap from staying resident for the whole pass-    // -- 1.4 GB of the California peak.-    let mut needed_by_relations: HashSet<i64> = HashSet::new();-    for relation in &relations {-        needed_by_relations.extend(relation.members.iter().map(|(id, _)| *id));-    }--    let mut ids: Vec<i64> = ways.keys().copied().collect();-    ids.sort_unstable();-    for id in ids {-        let way = &ways[&id];-        let line = table.line(&way.refs);-        let (class, area) = (way.class, way.class.area);-        match way_geometry(&line, area) {+    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;             }             None => stats.geometry_failed += 1,         }-        // Freed now rather than at the end of the pass. A way no relation refers to is finished with-        // the moment its geometry exists.-        if !needed_by_relations.contains(&id) {-            if let Some(way) = ways.get_mut(&id) {-                way.refs = Vec::new();-            }-        }     }+    // 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);+     for relation in &relations {-        let refs_of = |id: &i64| ways.get(id).map(|w| &w.refs).or_else(|| members.get(id));         // 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.@@ -252,7 +277,7 @@ pub fn extract(             let lines: Vec<Vec<(f64, f64)>> = relation                 .members                 .iter()-                .filter_map(|(id, _)| refs_of(id))+                .filter_map(|(id, _)| members.get(id))                 .map(|refs| table.line(refs))                 .filter(|line| line.len() >= 2)                 .collect();@@ -268,7 +293,7 @@ pub fn extract(             .members             .iter()             .filter_map(|(id, inner)| {-                Some(MemberWay { refs: refs_of(id)?.clone(), outer: !inner })+                Some(MemberWay { refs: members.get(id)?.clone(), outer: !inner })             })             .collect();         let polygons = rings::assemble(&member_ways, |id| locate(&table, id), &mut stats.rings);
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 44fd05a114..f502ef3245 100644--- a/scripts/maps/mamaps_build/src/store.rs+++ b/scripts/maps/mamaps_build/src/store.rs@@ -23,10 +23,19 @@ //! already round-tripped, and already handles every geometry kind — and it costs one small //! indirection: the [`Class`] is packed into a single integer property. That is the plan's own //! suggestion, and it is why `spill.rs` needed no change.+//!+//! # The second table: classified ways+//!+//! [`WaySink`] and [`WayReader`] do the same for the ~2.7 GB row of that table, for the same reason+//! and by a different route: a way's record is a handful of integers rather than a geometry, and it+//! is read back in the order it was written, so it gets a format of its own rather than+//! `NormalizedWriter`'s. See [`WaySink`] for why no sort is needed on the way back. +use std::fs::File;+use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; -use osm_ingest::proto::{err, Result};+use osm_ingest::proto::{err, zigzag, Error, Result}; use tile_build::geom::Geometry; use tile_build::mvt::Value; use tile_build::spill::{NormalizedReader, NormalizedWriter};@@ -243,6 +252,228 @@ impl Reader {     } } +/// Classified ways on disk: the second row of the table above, and the second thing stage A no+/// longer holds.+///+/// # Why a file rather than the `HashMap<i64, Way>` this replaces+///+/// The map cost ~2.7 GB on California, nearly all of it node refs, and every read of it was+/// sequential in ascending id order — [`crate::extract`] sorted the keys precisely so the archive+/// would not depend on hash order. It was a map only because a relation reaches its member ways by+/// id, in whatever order it lists them, and that one random access is served far more cheaply by+/// keeping *only* the relation members resident: California has 63 156 relations against several+/// million classified ways.+///+/// # Why nothing has to be sorted on the way back+///+/// A `.osm.pbf` stores ways sorted by id, and [`osm_ingest::pbf::run_pass_sink`] hands finished+/// chunks to its sink in file order. Appending as pass 1 goes therefore produces a file already in+/// the order materialisation wants, and the sort disappears along with the map.+///+/// [`push`] **enforces** that ordering rather than trusting it. An id that does not advance would+/// silently reorder the archive, and a byte-identical rebuild is the only evidence this pipeline has+/// that a change to stage A preserved its meaning — so a file that is not sorted is an error here,+/// where it is one line of output, rather than a diff in a 655 MB archive.+///+/// # The encoding+///+/// One record per way, every field a varint, nothing aligned:+///+/// | field | encoding |+/// |---|---|+/// | id | zigzag varint of the gap from the previous record's id |+/// | class | unsigned varint of [`pack`]'s integer |+/// | ref count | unsigned varint |+/// | refs | zigzag varint of each ref's gap from the one before it, the first from zero |+///+/// Delta coding earns its keep rather than being a flourish. The refs are ~150 M ids on California+/// and the file is read twice — once to collect the node ids pass 3 must resolve, once to build+/// geometry — so a flat 8 bytes each would be 1.2 GB read twice. Consecutive nodes of a way were+/// almost always created in one editing session and so have near-consecutive ids, which is exactly+/// what a delta collapses to one or two bytes.+///+/// [`push`]: WaySink::push+pub struct WaySink {+    out: BufWriter<File>,+    /// One record's bytes, reused. Several million records, so a `Vec` per record would be several+    /// million allocations for a buffer that is dead a line later.+    record: Vec<u8>,+    last_id: i64,+    count: u64,+    refs: u64,+}++impl WaySink {+    pub fn create(path: &Path) -> Result<WaySink> {+        let file = File::create(path)+            .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;+        Ok(WaySink {+            // A megabyte, because the writes are a few dozen bytes each and there are millions.+            out: BufWriter::with_capacity(1 << 20, file),+            record: Vec::new(),+            last_id: 0,+            count: 0,+            refs: 0,+        })+    }++    /// Append one classified way. `id` must be greater than the previous call's.+    pub fn push(&mut self, id: i64, class: &Class, refs: &[i64]) -> Result<()> {+        if self.count > 0 && id <= self.last_id {+            return err(format!(+                "way {id} arrived after way {}, so this PBF is not sorted by way id and the \+                 sequential ways spill cannot be used for it",+                self.last_id,+            ));+        }+        self.record.clear();+        put_svarint(&mut self.record, id.wrapping_sub(self.last_id));+        put_uvarint(&mut self.record, pack(class)?);+        put_uvarint(&mut self.record, refs.len() as u64);+        let mut previous: i64 = 0;+        for &node in refs {+            put_svarint(&mut self.record, node.wrapping_sub(previous));+            previous = node;+        }+        self.out+            .write_all(&self.record)+            .map_err(|e| Error(format!("cannot write the ways spill: {e}")))?;+        self.last_id = id;+        self.count += 1;+        self.refs += refs.len() as u64;+        Ok(())+    }++    /// Flush, and report how many ways were written and how many node refs they hold between them.+    ///+    /// The ref count is not a statistic. [`crate::extract`] reads this file back to collect the node+    /// ids pass 3 must resolve, and that vector is ~200 M ids on California: grown by extension it+    /// doubles into 2.1 GB of capacity, and the realloc that gets it there holds the old and new+    /// allocations at once. Knowing the exact length first turns that into one allocation of exactly+    /// the right size.+    pub fn finish(mut self) -> Result<WayCounts> {+        self.out.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?;+        Ok(WayCounts { ways: self.count, refs: self.refs })+    }+}++/// What a finished [`WaySink`] holds.+pub struct WayCounts {+    pub ways: u64,+    /// Node refs summed over every way, duplicates included — a capacity, not a cardinality.+    pub refs: u64,+}++/// Reads back what a [`WaySink`] wrote, in the order it was written.+pub struct WayReader {+    inner: BufReader<File>,+    last_id: i64,+    seen: u64,+}++impl WayReader {+    pub fn open(path: &Path) -> Result<WayReader> {+        let file = File::open(path)+            .map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;+        Ok(WayReader {+            inner: BufReader::with_capacity(1 << 20, file),+            last_id: 0,+            seen: 0,+        })+    }++    /// The next way's id and class, with its node refs written into `refs`.+    ///+    /// `refs` belongs to the caller and is cleared here, so one allocation serves the whole file.+    /// Returning a fresh `Vec` instead would be one allocation per classified way, several million+    /// of them, for a buffer whose contents are dead by the next call — the same reasoning as+    /// [`WaySink::record`].+    ///+    /// A record that ends mid-varint or claims more refs than the file holds is a corrupt spill+    /// rather than a way to skip: this file was written by [`WaySink`] moments ago in the same+    /// process, so anything unreadable means it is not the file we wrote.+    pub fn next(&mut self, refs: &mut Vec<i64>) -> Result<Option<(i64, Class)>> {+        refs.clear();+        let Some(delta) = self.uvarint_or_end()? else {+            return Ok(None);+        };+        let id = self.last_id.wrapping_add(zigzag(delta));+        self.last_id = id;+        self.seen += 1;+        let class = unpack(self.uvarint()?);+        let count = self.uvarint()?;+        // No `reserve` on `count`: it comes off disk, and a corrupt one would be an allocation+        // request rather than the error this returns for every other kind of damage. The buffer is+        // the caller's and is reused across the whole file, so after the first few records it is+        // already as large as any way needs.+        let mut previous: i64 = 0;+        for _ in 0..count {+            previous = previous.wrapping_add(zigzag(self.uvarint()?));+            refs.push(previous);+        }+        Ok(Some((id, class)))+    }++    /// One varint, or `None` if the file ended cleanly on a record boundary.+    fn uvarint_or_end(&mut self) -> Result<Option<u64>> {+        let mut value: u64 = 0;+        let mut shift: u32 = 0;+        loop {+            let buf = self+                .inner+                .fill_buf()+                .map_err(|e| Error(format!("cannot read the ways spill: {e}")))?;+            if buf.is_empty() {+                if shift == 0 {+                    return Ok(None);+                }+                return err(format!("the ways spill ends mid-varint after {} way(s)", self.seen));+            }+            // Consumed in one go per buffer fill rather than a byte at a time: a varint almost+            // always lies wholly inside the buffer, and there are hundreds of millions of them.+            let mut used = 0usize;+            for &byte in buf {+                used += 1;+                if shift >= 64 {+                    return err("a ways spill varint is longer than 64 bits".to_string());+                }+                value |= ((byte & 0x7f) as u64) << shift;+                shift += 7;+                if byte & 0x80 == 0 {+                    self.inner.consume(used);+                    return Ok(Some(value));+                }+            }+            self.inner.consume(used);+        }+    }++    fn uvarint(&mut self) -> Result<u64> {+        match self.uvarint_or_end()? {+            Some(value) => Ok(value),+            None => err(format!("the ways spill ends mid-record after {} way(s)", self.seen)),+        }+    }+}++fn put_uvarint(out: &mut Vec<u8>, mut value: u64) {+    loop {+        let byte = (value & 0x7f) as u8;+        value >>= 7;+        if value == 0 {+            out.push(byte);+            return;+        }+        out.push(byte | 0x80);+    }+}++/// Zigzagged, so a gap that happens to run backwards costs one bit rather than ten bytes.+/// [`zigzag`] is the decoder, already in `osm_ingest` because the PBF itself is encoded this way.+fn put_svarint(out: &mut Vec<u8>, value: i64) {+    put_uvarint(out, ((value << 1) ^ (value >> 63)) as u64);+}+ #[cfg(test)] mod tests {     use super::*;@@ -348,4 +579,92 @@ mod tests {         assert_eq!(again.next().expect("read").expect("a feature").class, lake);         let _ = std::fs::remove_file(&path);     }++    /// Ids, classes and refs all come back exactly, in the order they went in. The one thing the+    /// ways spill has to guarantee, because the archive's feature order is this file's record order.+    #[test]+    fn spilled_ways_come_back_in_the_order_and_with_the_refs_they_went_in_with() {+        let path = temp("ways_roundtrip");+        let lake = Class::area(dict::LAYER_WATER, schema::kind("lake"), 6);+        let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);+        // Refs chosen to exercise the delta coding: a large first id, a run of neighbours, a jump+        // backwards, and a way with none at all.+        let cases: Vec<(i64, Class, Vec<i64>)> = vec![+            (1, lake, vec![10_000_000_001, 10_000_000_002, 10_000_000_003, 9_000_000_000]),+            (2, road, vec![]),+            (i64::MAX, lake, vec![-5, 0, 5, i64::MAX, i64::MIN]),+        ];+        let mut sink = WaySink::create(&path).expect("create");+        for (id, class, refs) in &cases {+            sink.push(*id, class, refs).expect("push");+        }+        let counts = sink.finish().expect("finish");+        assert_eq!(counts.ways, 3, "one record per push");+        assert_eq!(counts.refs, 9, "refs summed over every way, so `needed` can be sized once");++        let mut reader = WayReader::open(&path).expect("open");+        let mut refs: Vec<i64> = Vec::new();+        for (id, class, expected) in &cases {+            let (got_id, got_class) = reader.next(&mut refs).expect("read").expect("a way");+            assert_eq!(got_id, *id);+            assert_eq!(got_class, *class);+            assert_eq!(&refs, expected);+        }+        assert!(reader.next(&mut refs).expect("read").is_none(), "and then the end");+        assert!(refs.is_empty(), "the caller's buffer is cleared even at the end");+        let _ = std::fs::remove_file(&path);+    }++    /// The spill's whole premise is that a PBF's ways arrive sorted, so materialisation can stream+    /// the file instead of sorting a map's keys. An input that breaks the premise has to say so:+    /// accepting it would reorder the archive, and a reordered archive is only visible as a+    /// different hash of 655 MB.+    #[test]+    fn a_way_id_that_does_not_advance_is_refused_rather_than_reordering_the_archive() {+        let path = temp("ways_unsorted");+        let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);+        let mut sink = WaySink::create(&path).expect("create");+        sink.push(100, &class, &[1, 2]).expect("push");+        assert!(sink.push(99, &class, &[3]).is_err(), "an id going backwards");+        assert!(sink.push(100, &class, &[3]).is_err(), "and the same id twice");+        sink.push(101, &class, &[3]).expect("but forwards is fine");+        let _ = std::fs::remove_file(&path);+    }++    /// A truncated spill is a corrupt file, not a short one. It was written by `WaySink` in this+    /// same process moments earlier, so a record that will not parse means the file is not ours.+    #[test]+    fn a_truncated_ways_spill_is_an_error_rather_than_a_silently_short_read() {+        let path = temp("ways_truncated");+        let class = Class::area(dict::LAYER_WATER, schema::kind("lake"), 6);+        let mut sink = WaySink::create(&path).expect("create");+        sink.push(1, &class, &[7, 8, 9]).expect("push");+        sink.push(2, &class, &[11, 12, 13]).expect("push");+        sink.finish().expect("finish");++        let whole = std::fs::read(&path).expect("read");+        // Cut the second record short, leaving it claiming refs the file does not hold.+        std::fs::write(&path, &whole[..whole.len() - 2]).expect("truncate");+        let mut reader = WayReader::open(&path).expect("open");+        let mut refs: Vec<i64> = Vec::new();+        assert!(reader.next(&mut refs).expect("read").is_some(), "the first record survives");+        assert!(reader.next(&mut refs).is_err(), "the cut one does not");+        let _ = std::fs::remove_file(&path);+    }++    /// Delta coding is the reason the file can be read twice without the I/O mattering. Worth+    /// pinning: a regression to fixed-width would be invisible except as a slower build.+    #[test]+    fn near_consecutive_refs_cost_about_a_byte_each() {+        let path = temp("ways_size");+        let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);+        let refs: Vec<i64> = (0..1000).map(|i| 10_000_000_000 + i).collect();+        let mut sink = WaySink::create(&path).expect("create");+        sink.push(1, &class, &refs).expect("push");+        sink.finish().expect("finish");+        let bytes = std::fs::metadata(&path).expect("metadata").len();+        // The first ref is a full-width id; every one after it is a delta of 1, one byte.+        assert!(bytes < 1100, "{bytes} bytes for 1000 refs, against 8000 fixed-width");+        let _ = std::fs::remove_file(&path);+    } }
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 6f13d6b089..93544aff58 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -26,10 +26,56 @@ //! disk through `tile_build::spill` and will need to for a planet build; a California //! water-and-buildings run is a few hundred megabytes, so this does not yet. The shape is the same //! either way — the writer already streams — so the change is local when it is needed.+//!+//! # Parallelism, and why the bytes do not move+//!+//! Tiling was 301 s of a 355 s California build, on one of 64 cores, and z14 alone is 68% of it+//! (180.7 M of 263 M output points) — so the split that matters is *within* a zoom, not across+//! them. A zoom is therefore a map/reduce:+//!+//! 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.+//! 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.+//!+//! 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+//! of the thread count but of *where the chunk boundaries fall*. Both halves are asserted, in+//! `the_archive_is_identical_at_every_thread_count` and+//! `the_archive_is_identical_however_the_features_are_chunked`.+//!+//! What would break it, and what this module is shaped to avoid:+//!+//! * A `HashMap` anywhere a tile, a layer or a feature is emitted from. Both maps here are+//!   `BTreeMap`s, and the only hash map in the path is the writer's dedup bucket table, which is+//!   probed and never walked.+//! * A reduce that folds partial results as they *complete* — a `reduce`, a `fold`, a channel of+//!   finished work. A layer's feature order would then follow the scheduler, and the damage would+//!   be a different feature *ordering* within a tile rather than a different picture: every pixel+//!   would still be right and every byte would be wrong.+//! * Emitting from the workers. Tile ids must ascend for [`StreamWriter`], so the append stays on+//!   one thread and only the pure work fans out.+//!+//! Memory is what this costs. All of a zoom's chunks are live at the end of the map phase, holding+//! the same coordinates the sequential map held plus one `BodyLayer` header per `(chunk, tile,+//! layer)` for each tile more than one chunk touches; the merge then frees each chunk's nodes as it+//! consumes them. In flight on top of that are at most `2 * threads` chunks of raw features. That+//! duplication is why [`CHUNK_VERTICES`] is as large as it is: smaller chunks balance the pool+//! better and duplicate more headers. -use std::collections::BTreeMap;+use std::cmp::Reverse;+use std::collections::{btree_map, BTreeMap, BinaryHeap};+use std::sync::atomic::{AtomicUsize, Ordering};+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 tilecodec::mamaps::body::{     Body, Feature as BodyFeature, Layer as BodyLayer, Part, GEOM_LINE, GEOM_POLYGON, WINDING_HOLE,@@ -48,6 +94,67 @@ pub const EXTENT: u32 = 4096; /// How aggressively to simplify, as a multiple of `tile_build`'s per-zoom tolerance. pub const DEFAULT_SIMPLIFICATION: f64 = 1.0; +/// Input vertices per chunk handed to one worker.+///+/// By **vertex** rather than by feature, because feature cost spans four orders of magnitude in the+/// same file: a building is five points and a state boundary is hundreds of thousands, so a chunk of+/// *n* features is not a unit of work at all. A feature bigger than this on its own becomes its own+/// chunk, which is the right answer for a coastline.+///+/// The size trades two costs against each other. Smaller chunks balance the pool better and give the+/// reader less to get through before a worker can start; larger chunks duplicate fewer `BodyLayer`+/// headers across chunks that touch the same tile, which is the whole of this design's memory+/// overhead. 64 Ki vertices is about a megabyte of `f64` pairs per chunk in flight and leaves a few+/// hundred chunks at California z14 — several tasks per core on a 64-core box.+const CHUNK_VERTICES: usize = 64 * 1024;++/// Worker stack, matching [`par`]'s pool and what the toolchain gives `main` on Windows.+///+/// The geometry called below is iterative, so 2 MiB would very likely do — but "very likely" is not+/// what you want from a stack, and getting it wrong aborts partway through a build instead of+/// returning an error.+const WORKER_STACK: usize = 8 * 1024 * 1024;++/// Set only by tests, which build the same archive at several chunk sizes to show the output does+/// not depend on where the boundaries fall. Zero means [`CHUNK_VERTICES`].+static CHUNK_OVERRIDE: AtomicUsize = AtomicUsize::new(0);++fn chunk_vertices() -> usize {+    match CHUNK_OVERRIDE.load(Ordering::Relaxed) {+        0 => CHUNK_VERTICES,+        n => n,+    }+}++#[cfg(test)]+fn set_chunk_vertices(n: usize) {+    CHUNK_OVERRIDE.store(n, Ordering::Relaxed);+}++/// Adopt `RAYON_NUM_THREADS` when nothing else has set the thread budget.+///+/// [`par::threads`] answers to `--threads` and then `MAPS_THREADS`, spelled that way so that one+/// export governs a whole multi-tool build, and it deliberately ignores rayon's own variable because+/// it builds its own pool. But `RAYON_NUM_THREADS` is the knob anyone reaches for to pin a Rust+/// program to one thread — including whoever is checking that this archive is identical at one+/// thread and at sixty-four — and ignoring it would make that check assert nothing. So it is+/// honoured, below `MAPS_THREADS` rather than above it, once per process.+fn adopt_thread_budget() {+    static ONCE: std::sync::Once = std::sync::Once::new();+    ONCE.call_once(|| {+        if std::env::var_os("MAPS_THREADS").is_some() {+            return;+        }+        let wanted = std::env::var("RAYON_NUM_THREADS")+            .ok()+            .and_then(|raw| raw.trim().parse::<usize>().ok())+            .filter(|n| *n > 0);+        if let Some(n) = wanted {+            par::set_threads(n);+        }+    });+}+ /// Per-zoom counts for the build report. #[derive(Debug, Default, Clone, Copy)] pub struct ZoomStats {@@ -69,6 +176,38 @@ pub struct Settings {     pub build_id: u64, } +/// One chunk's share of a zoom, keyed on `(tile id, layer id)`.+///+/// Keyed on the **tile id**, not on `(x, y)`. Those are different orders: `tile_id` walks a Hilbert+/// curve, so row-major `(x, y)` ascends through it out of sequence and the writer rejects the+/// archive. Cheap to get wrong and caught only by an ordering check, which is why the writer has+/// one.+///+/// Flat rather than `tile -> layer -> layer`. A nested map pays a whole inner `BTreeMap` node —+/// eleven `BodyLayer` slots, most of a kilobyte — for every tile, and nearly every tile carries one+/// or two layers; with a chunk map per chunk that overhead is multiplied by the chunk count.+/// Flattening puts eleven *entries* in a node instead, and changes no order: `(tile, layer)`+/// ascending is tile-major with layers in id order inside it, which is what the nested form yielded+/// and what the writer needs.+type Chunk = BTreeMap<(u64, u8), BodyLayer>;++/// What one chunk contributed to a zoom's counters. Only ever summed, so the order they are summed+/// in cannot change the answer.+#[derive(Debug, Default, Clone, Copy)]+struct Tally {+    features: u64,+    points: u64,+    dropped: u64,+}++impl Tally {+    fn add(&mut self, other: Tally) {+        self.features += other.features;+        self.points += other.points;+        self.dropped += other.dropped;+    }+}+ /// Tile every feature and write the archive. /// Tile every feature in `store` into a `.mamaps` archive. ///@@ -76,6 +215,7 @@ pub struct Settings { /// sequential passes over a file cost seconds on any modern disk; holding the features cost 4.9 GB of /// a measured 10.03 GB California peak. pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> {+    adopt_thread_budget();     let bbox = store.bbox();     let mut writer = StreamWriter::new(Options {         min_zoom: settings.min_zoom,@@ -96,79 +236,386 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta     let mut per_zoom = Vec::new();     for z in settings.min_zoom..=settings.max_zoom {         let mut stats = ZoomStats { zoom: z, ..ZoomStats::default() };-        // Keyed on the **tile id**, not on `(x, y)`. Those are different orders: `tile_id` walks a-        // Hilbert curve, so row-major `(x, y)` ascends through it out of sequence and the writer-        // rejects the archive. Cheap to get wrong and caught only by an ordering check, which is-        // why the writer has one.-        let mut tiles: BTreeMap<u64, BTreeMap<u8, BodyLayer>> = BTreeMap::new();         let tolerance = simplify::tolerance_for(z, settings.max_zoom, settings.simplification);         let buffer = geom::buffer_for(EXTENT);-        let mut touched: Vec<(u64, u64)> = Vec::new(); -        // The store speaks osm_ingest's error type and the tiler tile_build's; both wrap a string.-        let mut reader = store.reader().map_err(|e| tile_build::proto::Error(e.to_string()))?;-        while let Some(feature) = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))? {-            if z < feature.class.min_zoom {-                continue;+        let (chunks, tally) = map_zoom(store, z, tolerance, buffer)?;+        stats.features = tally.features;+        stats.points = tally.points;+        stats.dropped = tally.dropped;++        // Ascending by tile id because the merge makes it so, not because a sort step was+        // remembered. A `BTreeMap` per chunk and a heap across them is the same guarantee the+        // single-threaded `BTreeMap` gave.+        let mut merged = merge(chunks);+        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+            // zoom at once because the batch is what bounds the encoded bytes held before the+            // writer takes them.+            let batch: Vec<(u64, Vec<BodyLayer>)> =+                merged.by_ref().take(par::batch_len()).collect();+            if batch.is_empty() {+                break;             }-            let mut projected = geom::project_geometry(&feature.geometry, z, EXTENT);-            // Significance first, then filter: computed on the whole geometry so a vertex's fate-            // does not depend on which tile it lands in.-            simplify::annotate(&mut projected);-            let thinned = simplify::filter(&projected, tolerance);-            if is_empty(&thinned) {-                stats.dropped += 1;-                continue;+            for (id, encoded, rings) in encode_batch(batch)? {+                stats.rings.add(rings);+                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)?;             }-            geom::tiles_touched(&thinned, z, EXTENT, buffer, &mut touched);-            for &(tx, ty) in &touched {-                let rect = geom::tile_rect(tx, ty, EXTENT, buffer);-                let clipped = clip::clip_geometry(&thinned, &rect);-                if is_empty(&clipped) {-                    continue;+        }+        per_zoom.push(stats);+    }++    let bytes = writer.finish()?;+    Ok((bytes, per_zoom))+}++/// The map half of one zoom: every feature in the store, clipped into per-chunk tile maps.+///+/// Returns the chunks **in read order**, which is the only order the reduce may use them in.+///+/// The reader gets a thread of its own rather than a task on the pool, and that is not a+/// preference. A producer that blocks on a full channel from inside the pool it feeds deadlocks when+/// the pool has one thread: the single worker *is* the producer, so nothing can drain what it is+/// waiting to write. Off the pool, one thread is merely slow — which matters, because one thread is+/// a configuration this has to stay byte-identical at.+fn map_zoom(store: &Store, z: u8, tolerance: f64, buffer: f64) -> Result<(Vec<Chunk>, Tally)> {+    let workers = par::threads().max(1);+    // Bounded, because this is the one place the parallel tiler holds features the sequential one+    // did not: `2 * threads` chunks of about `chunk_vertices()` vertices, and no more however far+    // ahead of the workers the reader gets.+    let (send, receive) = std::sync::mpsc::sync_channel::<(usize, Vec<Feature>)>(workers * 2);+    let receive = Mutex::new(receive);+    let done: Mutex<Vec<(usize, Chunk, Tally)>> = Mutex::new(Vec::new());+    let failed = std::sync::atomic::AtomicBool::new(false);++    std::thread::scope(|scope| -> Result<()> {+        let reader = std::thread::Builder::new()+            .name("mamaps-read".to_string())+            .spawn_scoped(scope, move || read_chunks(store, z, send))+            .map_err(|e| tile_build::proto::Error(format!("cannot start the store reader: {e}")))?;++        // One worker runs on this thread whatever happens, so a machine that will not give us+        // threads is slow rather than a build hung on a channel nobody is draining.+        let mut spawned = Vec::new();+        for i in 1..workers {+            let worker = std::thread::Builder::new()+                .name(format!("mamaps-tile-{i}"))+                .stack_size(WORKER_STACK)+                .spawn_scoped(scope, || {+                    tile_chunks(&receive, &done, &failed, z, tolerance, buffer)+                });+            match worker {+                Ok(handle) => spawned.push(handle),+                Err(e) => {+                    eprintln!("WARNING: cannot start tiling thread {i} ({e}); continuing without");+                    break;                 }-                let local = geom::to_tile(&clipped, tx, ty, EXTENT);-                let layer = tiles-                    .entry(tile_id(z, tx, ty))-                    .or_default()-                    .entry(feature.class.layer)-                    .or_insert_with(|| BodyLayer::new(feature.class.layer));-                let added = push(layer, &feature, &local);-                stats.features += added.0;-                stats.points += added.1;             }         }+        tile_chunks(&receive, &done, &failed, z, tolerance, buffer);+        for handle in spawned {+            handle.join().map_err(|_| {+                tile_build::proto::Error("a tiling thread panicked".to_string())+            })?;+        }+        reader.join().map_err(|_| {+            tile_build::proto::Error("the store reader thread panicked".to_string())+        })?+    })?;++    if failed.load(Ordering::Relaxed) {+        // Refused rather than published. A skipped chunk is a handful of features missing from a+        // handful of tiles: no error on device, no visibly broken tile, just an archive that is+        // quietly not the one the report describes.+        return err(format!("a chunk of z{z} panicked while being tiled; see the message above"));+    }++    let mut chunks = done.into_inner().expect("the chunk list outlives its workers");+    // **The reduce order.** By the index a chunk was read at, never by the order it finished in.+    // This one line is what keeps the archive independent of the thread count.+    chunks.sort_by_key(|(index, _, _)| *index);+    let mut tally = Tally::default();+    for (_, _, chunk_tally) in &chunks {+        tally.add(*chunk_tally);+    }+    Ok((chunks.into_iter().map(|(_, chunk, _)| chunk).collect(), tally))+}++/// Cut the store into chunks of roughly [`chunk_vertices`] input vertices and send them on.+///+/// The cut is a function of the feature stream alone — not of the thread count, not of how fast the+/// workers drain — so two runs chunk identically even before the merge makes the boundaries+/// invisible.+///+/// A feature below the zoom's own floor is dropped here rather than sent. It costs nothing to+/// recognise, and at z0 shipping them would be shipping the whole store.+fn read_chunks(+    store: &Store,+    z: u8,+    send: std::sync::mpsc::SyncSender<(usize, Vec<Feature>)>,+) -> Result<()> {+    // The store speaks osm_ingest's error type and the tiler tile_build's; both wrap a string.+    let mut reader = store.reader().map_err(|e| tile_build::proto::Error(e.to_string()))?;+    let want = chunk_vertices();+    let mut chunk: Vec<Feature> = Vec::new();+    let mut vertices = 0usize;+    let mut index = 0usize;+    while let Some(feature) = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))? {+        if z < feature.class.min_zoom {+            continue;+        }+        vertices += vertex_count(&feature.geometry);+        chunk.push(feature);+        if vertices >= want {+            // A closed receiver means every worker is already gone, which only happens on a panic+            // that is being reported anyway. Stopping quietly beats a second, vaguer error.+            if send.send((index, std::mem::take(&mut chunk))).is_err() {+                return Ok(());+            }+            index += 1;+            vertices = 0;+        }+    }+    if !chunk.is_empty() {+        let _ = send.send((index, chunk));+    }+    Ok(())+} -        // A `BTreeMap` keyed on the tile id, so the emit order **is** the writer's required order-        // and no sort step can be forgotten. A `HashMap` here is the single easiest way to lose-        // byte-identical rebuilds.-        for (id, layers) in tiles {-            // **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 layers: Vec<BodyLayer> = layers.into_values().collect();-            for layer in &mut layers {-                stats.rings.add(crate::rings::normalise(layer));+/// Take chunks until the reader is finished, tiling each into a map of its own.+///+/// A panic inside one chunk is **caught and recorded** rather than allowed to unwind, and the loop+/// keeps draining. That is not defensiveness about a bug that should not happen, it is about the+/// shape of the failure: a worker that dies with a bounded channel full behind it leaves the reader+/// blocked on a send nobody will ever take, and at one worker there is nobody else to drain it. So+/// the bug's symptom would be a 64-core box sitting at 0% forever in the middle of a five-minute+/// stage, instead of an error naming the zoom. `map_zoom` fails the build on the flag.+fn tile_chunks(+    receive: &Mutex<std::sync::mpsc::Receiver<(usize, Vec<Feature>)>>,+    done: &Mutex<Vec<(usize, Chunk, Tally)>>,+    failed: &std::sync::atomic::AtomicBool,+    z: u8,+    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.+        let tiled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            tile_chunk(&features, z, tolerance, buffer, &mut touched)+        }));+        match tiled {+            Ok((chunk, tally)) => done.lock().expect("the chunk list").push((index, chunk, tally)),+            Err(_) => {+                eprintln!("ERROR: chunk {index} of z{z} panicked while being tiled");+                failed.store(true, Ordering::Relaxed);             }-            // 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.-            let layers: Vec<BodyLayer> =-                layers.into_iter().filter(|l| !l.features.is_empty()).collect();-            if layers.is_empty() {+        }+    }+}++/// Project, simplify, bisect 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) {+    let mut tiles: Chunk = BTreeMap::new();+    let mut tally = Tally::default();+    for feature in features {+        let mut projected = geom::project_geometry(&feature.geometry, z, EXTENT);+        // Significance first, then filter: computed on the whole geometry so a vertex's fate+        // does not depend on which tile it lands in.+        simplify::annotate(&mut projected);+        let thinned = simplify::filter(&projected, tolerance);+        if is_empty(&thinned) {+            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;             }-            let body = Body { extent: EXTENT as u16, layers };-            let encoded = tilecodec::mamaps::body::serialize(&body)?;-            stats.bytes += encoded.len() as u64;-            stats.tiles += 1;-            writer.append_encoded(id, &encoded)?;+            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;         }-        per_zoom.push(stats);     }+    (tiles, tally)+} -    let bytes = writer.finish()?;-    Ok((bytes, per_zoom))+/// Input vertices in a geometry, for chunking. Counted rather than estimated, because it is the+/// number that decides how long a chunk takes.+fn vertex_count(geometry: &Geometry) -> usize {+    match geometry {+        Geometry::Points(points) => points.len(),+        Geometry::Lines(lines) => lines.iter().map(Vec::len).sum(),+        Geometry::Polygons(polygons) => polygons.iter().flatten().map(Vec::len).sum(),+    }+}++/// K-way merge one zoom's chunks into ascending tiles, each carrying its layers in id order.+///+/// This is the reduce, and its ordering is the whole correctness argument. Keying the heap on+/// `(tile, layer, chunk index)` makes the entries for one tile arrive layer-major and, within a+/// layer, in **chunk order** — so appending them as they arrive lays a layer's features down in the+/// order the store yielded them. That is not merely *a* deterministic order; it is the order the+/// single-threaded tiler produced, which is why the archive did not move.+///+/// Streamed rather than merged into one map first, so a chunk's `BTreeMap` nodes are freed as they+/// are consumed instead of every chunk and a merged copy of it being live at once.+fn merge(chunks: Vec<Chunk>) -> Merged {+    let mut chunks: Vec<btree_map::IntoIter<(u64, u8), BodyLayer>> =+        chunks.into_iter().map(BTreeMap::into_iter).collect();+    let mut front: Vec<Option<((u64, u8), BodyLayer)>> = Vec::with_capacity(chunks.len());+    let mut next = BinaryHeap::with_capacity(chunks.len());+    for (index, chunk) in chunks.iter_mut().enumerate() {+        let head = chunk.next();+        if let Some(((tile, layer), _)) = &head {+            next.push(Reverse((*tile, *layer, index)));+        }+        front.push(head);+    }+    Merged { chunks, front, next }+}++/// A merge in progress: one held entry per chunk, and a heap over their keys. `Reverse`, because+/// `BinaryHeap` is a max-heap and the writer wants ascending ids.+struct Merged {+    chunks: Vec<btree_map::IntoIter<(u64, u8), BodyLayer>>,+    front: Vec<Option<((u64, u8), BodyLayer)>>,+    next: BinaryHeap<Reverse<(u64, u8, usize)>>,+}++impl Iterator for Merged {+    type Item = (u64, Vec<BodyLayer>);++    fn next(&mut self) -> Option<(u64, Vec<BodyLayer>)> {+        let Reverse((tile, _, _)) = *self.next.peek()?;+        let mut layers: Vec<BodyLayer> = Vec::new();+        while let Some(&Reverse((at, layer_id, index))) = self.next.peek() {+            if at != tile {+                break;+            }+            self.next.pop();+            let (_, layer) = self.front[index].take().expect("a heap key without its entry");+            // Entries for one layer are adjacent, because the key sorts the layer before the chunk.+            // So the accumulator only ever has to look at the layer it started last.+            match layers.last_mut() {+                Some(last) if last.layer_id == layer_id => concatenate(last, layer),+                _ => layers.push(layer),+            }+            let head = self.chunks[index].next();+            if let Some(((tile, layer_id), _)) = &head {+                self.next.push(Reverse((*tile, *layer_id, index)));+            }+            self.front[index] = head;+        }+        Some((tile, layers))+    }+}++/// Append one chunk's share of a layer onto another chunk's.+///+/// Rebased, not rebuilt: a `BodyLayer` is three parallel arenas and a feature addresses its parts by+/// index, so concatenating them means shifting `parts_offset` by the parts already there and+/// `coord_start` by the coordinates. The result is byte for byte what [`push`] would have produced+/// had both chunks' features gone into one layer in this order, which is the claim the whole design+/// rests on and what `concatenating_two_chunks_of_a_layer_is_one_layer` holds it to.+fn concatenate(into: &mut BodyLayer, from: BodyLayer) {+    let parts_base = into.parts.len() as u32;+    let coords_base = into.coords.len() as u32;+    into.features.extend(from.features.into_iter().map(|mut feature| {+        feature.parts_offset += parts_base;+        feature+    }));+    into.parts.extend(from.parts.into_iter().map(|mut part| {+        part.coord_start += coords_base;+        part+    }));+    into.coords.extend_from_slice(&from.coords);+}++/// Stage C and body encoding for a batch of merged tiles, in parallel, results in tile order.+///+/// Both halves are pure functions of a single tile, which is the only reason this can fan out at+/// all: [`crate::rings::normalise`] rewrites one layer's own arenas and nothing else, and+/// [`tilecodec::mamaps::body::serialize`] only reads. `map(..).collect()` preserves the input's+/// order — rayon's collect is positional, not completion-ordered — so the caller appends in+/// ascending tile id with no sort of its own.+///+/// A tile whose layers all emptied out comes back as `None` rather than being dropped here, because+/// its stage C counters still belong in the build report.+#[allow(clippy::type_complexity)]+/// Stage C, serialise and **compress** one batch of merged tiles, in parallel.+///+/// Compression belongs here rather than in the writer's append. DEFLATE at level nine is the single+/// most expensive step per tile and the one least able to be stolen: left in `append_encoded` it ran+/// on the appending thread, downstream of this whole parallel phase, and on a California z14 it was+/// ~900 MB through one core while sixty-three sat idle. That is why a 64-thread build was *slower*+/// than the sequential one it replaced.+///+/// 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)>> {+    let min_len = par::min_task_len(batch.len());+    par::install(|| {+        batch+            .into_par_iter()+            .with_min_len(min_len)+            .map(|(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(&encoded);+                Ok((id, Some((stored, raw_len)), rings))+            })+            .collect()+    }) }  /// Append one feature's tile-local geometry to a layer. Returns `(features, points)` added.@@ -333,6 +780,30 @@ mod tests {         Settings { min_zoom, max_zoom, simplification: DEFAULT_SIMPLIFICATION, build_id: 7 }     } +    /// The thread budget and the chunk size are process-wide, and `cargo test` runs these tests in+    /// one process on several threads. The tests that set either take this lock against each other —+    /// not for safety, an `AtomicUsize` is safe, but so that a test asserting "this is what one+    /// thread produces" really is running on one thread when it says so.+    ///+    /// A poisoned lock is taken anyway: poisoning means another test panicked, and *its* failure is+    /// the one worth reading rather than a cascade of lock errors on top of it.+    static BUDGET: Mutex<()> = Mutex::new(());++    fn budget() -> std::sync::MutexGuard<'static, ()> {+        let guard = BUDGET.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+        // Trip the once-only environment adoption here, *before* the test sets its own count. Left+        // to `build`, the first call would run it after `set_threads(1)` and could quietly put+        // `RAYON_NUM_THREADS` back — leaving a test that says "one thread" asserting nothing.+        adopt_thread_budget();+        guard+    }++    /// `par::clear_threads` is `#[cfg(test)]` *inside* `tile_build`, so it does not exist from here.+    /// Putting the box's own count back is the same thing for a test process.+    fn release_threads() {+        par::set_threads(std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4));+    }+     #[test]     fn a_lake_tiles_and_reads_back_out_of_the_archive() {         let features = vec![lake(-120.0, 35.0, 0.5, 0)];@@ -434,4 +905,191 @@ mod tests {         let at = |z: u8| stats.iter().find(|s| s.zoom == z).expect("zoom").points;         assert!(at(6) < at(14), "z6 has {} points, z14 has {}", at(6), at(14));     }++    /// Enough features, spread over enough tiles, that every zoom has several chunks to merge and+    /// several tiles per chunk. A single-tile fixture would pass any merge, correct or not.+    fn a_crowd() -> Vec<Feature> {+        let mut features = Vec::new();+        for i in 0..60 {+            let (row, column) = (i / 10, i % 10);+            let (lon, lat) = (-120.0 + column as f64 * 0.03, 35.0 + row as f64 * 0.03);+            features.push(lake(lon, lat, 0.02, 0));+            features.push(Feature {+                class: Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 0),+                geometry: square(lon + 0.004, lat + 0.004, 0.004),+            });+            // A line as well, so the merge has to rebase a `GEOM_LINE` feature's parts too, and a+            // long one so it crosses tiles rather than sitting inside one.+            features.push(Feature {+                class: Class::line(dict::LAYER_WATER, crate::schema::kind("river"), 0),+                geometry: Geometry::Lines(vec![(0..40)+                    .map(|k| (lon + k as f64 * 0.002, lat + (k % 5) as f64 * 0.001))+                    .collect()]),+            });+        }+        features+    }++    /// **The property the parallel tiler exists to keep.** The archive is a function of the input,+    /// not of the thread count.+    ///+    /// One thread is not a formality: it is the configuration where the reader and the single worker+    /// share one queue, and it is the configuration a producer running on the pool would deadlock+    /// in. Three is the awkward one, where chunks outnumber threads unevenly and completion order+    /// is guaranteed not to be read order.+    #[test]+    fn the_archive_is_identical_at_every_thread_count() {+        let _budget = budget();+        let store = spilled(&a_crowd());+        // Small enough that the crowd above becomes many chunks, so the merge is doing real work at+        // every thread count rather than folding one chunk into itself.+        set_chunk_vertices(64);+        par::set_threads(1);+        let (one, first_stats) = build(&store, &settings(0, 12)).expect("one thread");+        for threads in [2usize, 3, 8, 17] {+            par::set_threads(threads);+            let (bytes, stats) = build(&store, &settings(0, 12)).expect("many threads");+            assert_eq!(bytes.len(), one.len(), "{threads} threads changed the archive length");+            assert_eq!(bytes, one, "{threads} threads changed the archive bytes");+            // The report is published beside the archive and diffed too, so it has to agree as+            // well: a counter summed in completion order would still be right, and one accumulated+            // per chunk into a shared total would not.+            for (a, b) in first_stats.iter().zip(&stats) {+                assert_eq!(+                    (a.zoom, a.tiles, a.features, a.points, a.dropped, a.bytes),+                    (b.zoom, b.tiles, b.features, b.points, b.dropped, b.bytes),+                    "{threads} threads changed the z{} counters",+                    a.zoom,+                );+                assert_eq!(a.rings, b.rings, "{threads} threads changed z{} stage C", a.zoom);+            }+        }+        set_chunk_vertices(0);+        release_threads();+    }++    /// The stronger claim, and the one that makes the thread count irrelevant rather than merely+    /// tested: concatenating a partition of the feature stream in partition order reproduces the+    /// stream, so **where** the chunk boundaries fall cannot matter either.+    ///+    /// A chunk of one vertex means one chunk per feature — every tile in the merge is then assembled+    /// from as many pieces as it has features, which is the worst case for [`concatenate`] and the+    /// one where a wrong `parts_offset` could not hide.+    #[test]+    fn the_archive_is_identical_however_the_features_are_chunked() {+        let _budget = budget();+        let store = spilled(&a_crowd());+        par::set_threads(4);+        set_chunk_vertices(1);+        let one_per_feature = build(&store, &settings(0, 12)).expect("tiny chunks").0;+        for size in [7usize, 64, 4096, 1 << 20] {+            set_chunk_vertices(size);+            let bytes = build(&store, &settings(0, 12)).expect("build").0;+            assert_eq!(bytes, one_per_feature, "a chunk of {size} vertices changed the archive");+        }+        set_chunk_vertices(0);+        release_threads();+    }++    /// Feature order **within a tile layer** is the store's order, asserted rather than assumed.+    ///+    /// This is the failure the whole module is arranged around, and it is invisible from outside: a+    /// merge that folded chunks in completion order would still put every feature in the right tile,+    /// still draw the right picture, and still write different bytes every run. So each feature+    /// carries a `kind_detail` counting up in store order, and the decoded archive has to count up+    /// too.+    #[test]+    fn feature_order_within_a_tile_layer_is_the_store_order() {+        let _budget = budget();+        // All in one small patch so they pile into the same handful of z14 tiles, each labelled with+        // its position in the store.+        let features: Vec<Feature> = (0..40u16)+            .map(|i| Feature {+                class: Class {+                    kind_detail: i,+                    ..Class::area(dict::LAYER_WATER, crate::schema::kind("lake"), 0)+                },+                geometry: square(-120.0 + i as f64 * 0.00005, 35.0, 0.004),+            })+            .collect();+        let store = spilled(&features);+        set_chunk_vertices(1);+        par::set_threads(8);+        let (bytes, _) = build(&store, &settings(14, 14)).expect("build");+        set_chunk_vertices(0);+        release_threads();++        let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");+        let mut widest = 0usize;+        for (id, _, body) in &entries {+            let body = Body::parse(body).expect("parse");+            let Some(layer) = body.layer(dict::LAYER_WATER) else { continue };+            let order: Vec<u16> = layer.features.iter().map(|f| f.kind_detail).collect();+            let mut ascending = order.clone();+            ascending.sort_unstable();+            assert_eq!(order, ascending, "tile {id} holds its features out of store order");+            widest = widest.max(order.len());+        }+        // And that assertion has to have had something to bite on: a tile carrying one feature is+        // in order however badly the merge behaves.+        assert!(widest >= 20, "no tile gathered enough features to order (widest was {widest})");+    }++    /// [`concatenate`] against the thing it claims to equal: one layer built by pushing both+    /// features in one go. Not "the offsets look plausible" but "the layer is the same layer".+    #[test]+    fn concatenating_two_chunks_of_a_layer_is_one_layer() {+        let class = Class::area(dict::LAYER_WATER, crate::schema::kind("lake"), 0);+        let feature = Feature { class, geometry: square(0.0, 0.0, 1.0) };+        // Tile-local already, so the fixture is about the arenas rather than about projection, and+        // big enough that no minimum-area floor can drop it.+        let box_at = |x: i32| {+            IntGeometry::Polygons(vec![vec![vec![+                (x, 0),+                (x + 500, 0),+                (x + 500, 500),+                (x, 500),+                (x, 0),+            ]]])+        };++        let mut together = BodyLayer::new(dict::LAYER_WATER);+        assert_eq!(push(&mut together, &feature, &box_at(0)), (1, 5));+        push(&mut together, &feature, &box_at(1000));++        let mut first = BodyLayer::new(dict::LAYER_WATER);+        push(&mut first, &feature, &box_at(0));+        let mut second = BodyLayer::new(dict::LAYER_WATER);+        push(&mut second, &feature, &box_at(1000));+        concatenate(&mut first, second);++        assert_eq!(first, together, "two chunks concatenated are not the one-pass layer");+        // Spelled out as well, because `assert_eq` on the whole layer would also pass if both were+        // empty, and an arena its parts do not tile exactly is what the encoder rejects.+        assert_eq!(first.features.len(), 2);+        assert_eq!(first.features[1].parts_offset, 1);+        assert_eq!(first.parts[1].coord_start, first.parts[0].point_count);+        assert_eq!(first.coords.len(), 10);+    }++    /// The merge's contract on its own, without a build around it: ascending tiles, and layers in id+    /// order within a tile, with same-layer contributions from several chunks collapsed into one.+    #[test]+    fn the_merge_yields_ascending_tiles_with_their_layers_in_id_order() {+        let mut early: Chunk = BTreeMap::new();+        early.insert((10, 3), BodyLayer::new(3));+        early.insert((30, 1), BodyLayer::new(1));+        let mut middle: Chunk = BTreeMap::new();+        middle.insert((10, 1), BodyLayer::new(1));+        middle.insert((20, 2), BodyLayer::new(2));+        let mut late: Chunk = BTreeMap::new();+        late.insert((10, 3), BodyLayer::new(3));++        let merged: Vec<(u64, Vec<u8>)> = merge(vec![early, middle, late])+            .map(|(id, layers)| (id, layers.iter().map(|l| l.layer_id).collect()))+            .collect();+        // Tile 10 carries layer 1 before layer 3 even though layer 3 was read first, and its two+        // separate layer-3 pieces arrive as one layer rather than two.+        assert_eq!(merged, vec![(10, vec![1, 3]), (20, vec![2]), (30, vec![1])]);+    } }
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 f162096218..9c25758515 100644--- a/scripts/maps/osm_ingest/src/nodeloc.rs+++ b/scripts/maps/osm_ingest/src/nodeloc.rs@@ -73,6 +73,17 @@ impl NodeLocations { }  /// 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+/// hand every chunk's accumulator back at once and these accumulators are the largest thing this+/// pass touches. On California they are 154 M nodes at 12 bytes -- about 1.8 GB -- and they would be+/// alive next to the 2.5 GB table they are about to be folded into, so the two peak together. Here a+/// chunk is folded and freed while its neighbours are still decoding, which also overlaps the merge+/// with the I/O. `pbf.rs` names this exact hazard in `run_pass_sink`'s own doc comment.+///+/// The merge order is unchanged: `run_pass_sink` calls its sink in chunk order, which is the order+/// `run_pass` returned chunks in, so two blocks reporting the same node still resolve to the same+/// coordinate. pub fn resolve_nodes(     input: &Path,     blobs: &[pbf::BlobLoc],@@ -83,8 +94,10 @@ pub fn resolve_nodes(     if table.is_empty() {         return Ok(table);     }+    // Moved out so the workers can search it while the sink writes to `locs`; put back below.     let ids = std::mem::take(&mut table.ids);-    let (chunks, _) = pbf::run_pass(+    let locs = &mut table.locs;+    pbf::run_pass_sink(         input,         blobs,         Some(blob_kinds),@@ -103,13 +116,14 @@ pub fn resolve_nodes(             })?;             Ok(kinds)         },+        |chunk| {+            for (idx, lat, lon) in chunk {+                locs[idx as usize] = (lat, lon);+            }+            Ok(())+        },     )?;     table.ids = ids;-    for chunk in chunks {-        for (idx, lat, lon) in chunk {-            table.locs[idx as usize] = (lat, lon);-        }-    }     Ok(table) }