Modern Apps git

← Modern-Apps.git

mamaps_build: split oversized Rust files under the 500-line limit

Commit
0cf2e81dc5aed5a93eae20b80e85c1a4dd8680c8
Author
Vayun Mathur <[email protected]>
When
2026-12-01 20:26 UTC (4 days ago)
Parents
9bb3a82
Twenty files exceeded the 500-line rustFileLength limit, the
worst tiler_part3.rs at 1370 lines, landtype.rs at 875 and
tiler_part1.rs at 840.

Split each along module lines using the established include! part
pattern: whole top-level items (and, for the three files that are
a single test module, whole test items inside that module) move
verbatim into *_sN.rs files spliced into the same module, so
every item, visibility and call path is identical and no public
or crate-internal surface changes.

Verified: cargo fmt -p mamaps_build -- --check clean and
cargo test -p mamaps_build --locked green (293 passed).

Diff

scripts/maps/mamaps_build/src/dem.rs
diff --git a/scripts/maps/mamaps_build/src/dem.rs b/scripts/maps/mamaps_build/src/dem.rsindex ca541a9a63..e09fc12964 100644--- a/scripts/maps/mamaps_build/src/dem.rs+++ b/scripts/maps/mamaps_build/src/dem.rs@@ -295,413 +295,4 @@ impl Grids {     } } -impl Dem {-    /// Read and parse a `.mdem` dataset from disk.-    ///-    /// Mapped, not read: the 13 GB world file would otherwise cost a-    /// single-threaded `fs::read` plus a full copy before parsing starts.-    /// The mapping faults pages in on the pool's 64 threads during the-    /// parallel parse below, and the bytes are never copied — each tile's-    /// samples land directly in its grid `Vec`. The mapping drops on return;-    /// the `Dem` owns its grids.-    pub fn load(path: &Path) -> Result<Dem> {-        let mapped = osm_ingest::mem::Mapped::open(path).map_err(Error)?;-        Dem::parse(&mapped)-    }--    /// Parse a `.mdem` dataset: a 12-byte header (`MDEM`, version, out_zoom, `dim` u16, tile count-    /// u32), then per tile a `u64` tile id and its `dim * dim` `u16` samples, little-endian.-    ///-    /// Tiles parse on the pool: records are fixed-stride (`8 + cells * 2` bytes), so tile `i`-    /// starts at `12 + i * stride` with no dependency on any other tile. Each worker decodes a-    /// contiguous run into owned `(id, samples)` pairs; the single-threaded fold inserts them in-    /// file order. Same pairs as the serial loop — the map holds the same contents, and nothing-    /// ever iterates it (only `heightmap_for`'s `.get`), so no byte can move. The 13 GB world-    /// dataset's per-sample `u16::from_le_bytes` + per-tile alloc + hash insert runs ~50 s-    /// serially on every build regardless of region; fanning out the decode leaves only the-    /// `fs::read` and the inserts.-    fn parse(bytes: &[u8]) -> Result<Dem> {-        if bytes.len() < 12 {-            return err("a .mdem dataset is shorter than its 12-byte header");-        }-        if &bytes[0..4] != MAGIC {-            return err("not a .mdem dataset (bad magic)");-        }-        if bytes[4] != VERSION {-            return err(format!(-                "unsupported .mdem version {} (this build reads {VERSION})",-                bytes[4]-            ));-        }-        let out_zoom = bytes[5];-        let dim = u16::from_le_bytes([bytes[6], bytes[7]]);-        if dim < 2 {-            return err("a .mdem grid dimension is less than 2");-        }-        let count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;-        let cells = dim as usize * dim as usize;-        // One tile: an 8-byte id then `cells` little-endian u16 samples.-        let stride = 8 + cells * 2;-        if bytes.len() < 12 + count.saturating_mul(stride) {-            return err("a .mdem dataset ends before its tile count");-        }-        // Both columns on the pool (see [`Grids`]): the ids straight off their fixed-stride-        // offsets, then each grid decoded into its slot of one contiguous sample array.-        let keys: Vec<(u64, usize)> = par::install(|| {-            (0..count)-                .into_par_iter()-                .map(|i| {-                    let at = 12 + i * stride;-                    (u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")), i)-                })-                .collect()-        });-        let grids = par::install(|| {-            Grids::build(keys, cells, |i, grid| {-                let at = 12 + i * stride + 8;-                for (c, out) in grid.iter_mut().enumerate() {-                    let o = at + c * 2;-                    *out = u16::from_le_bytes([bytes[o], bytes[o + 1]]);-                }-            })-        });-        Ok(Dem { out_zoom, dim, grids })-    }--    /// The heightmap for one output tile, or `None` when no DEM covers it (so the tile omits the-    /// section and stays 16-byte).-    ///-    /// A tile at the dataset's own zoom is a verbatim copy of its grid — byte for byte what the-    /// ingest sampled, independent of neighbour coverage. Any other zoom is resampled onto this-    /// tile's grid.-    ///-    /// A grid that is **entirely sea level** yields `None` whatever the zoom: an all-ocean tile-    /// carries no relief, and emitting a flat sea-level heightmap makes the renderer draw its-    /// earth-coloured terrain grid over what should be open water (the renderer's contract is-    /// "no heightmap over ocean" — see `library/map`'s `terrain.rs`). Dropping it here is the-    /// backstop for a `.mdem` built without `dem_ingest --skip-flat`. A flat *land* tile at exactly-    /// sea level loses nothing visible: its flat `earth` fill draws the same ground the flat grid-    /// would have, and its features sit at 0 m either way.-    pub fn heightmap_for(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {-        if z == self.out_zoom {-            let samples = self.grids.get(&tile_id(z, x, y))?;-            if all_sea_level(samples) {-                return None;-            }-            // A flat tile's grid is mostly repetition: coarsen it. Steep-            // tiles keep the full grid.-            return Some(finish_grid(z, y, samples, self.dim));-        }-        self.resample(z, x, y)-    }--    /// Resample the dataset's grids onto one tile's `dim * dim` grid, sampling `dim * dim` points-    /// across the tile's own extent from its top-left — the same slippy walk `dem_ingest` runs over-    /// the terrarium grid, sourced from the loaded grids instead of PNGs.-    fn resample(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {-        let dim = self.dim as usize;-        let mut samples = Vec::with_capacity(dim * dim);-        let mut any = false;-        for row in 0..dim {-            let fy = y as f64 + row as f64 / (self.dim as f64 - 1.0);-            let lat = tile_y_to_lat(fy, z);-            for col in 0..dim {-                let fx = x as f64 + col as f64 / (self.dim as f64 - 1.0);-                let lon = tile_x_to_lon(fx, z);-                match self.sample_at(lon, lat) {-                    Some(v) => {-                        any = true;-                        samples.push(v);-                    }-                    // No DEM here: sea level, as `dem_ingest` fills a missing terrarium pixel. A-                    // tile entirely over missing DEM is dropped below.-                    None => samples.push(SEA_LEVEL),-                }-            }-        }-        // A tile whose every sample is sea level carries no relief: drop it so the renderer paints-        // open water rather than a flat earth-coloured terrain grid (see `heightmap_for`).-        if !any || all_sea_level(&samples) {-            return None;-        }-        // Same flat-tile coarsening as the verbatim path: the resampled grid-        // is full resolution, so relief is measured on it directly.-        Some(finish_grid(z, y, &samples, self.dim))-    }--    /// Build a dataset directly from grids, for tests that inject a synthetic DEM into the tiler-    /// rather than round-tripping bytes through disk.-    #[cfg(test)]-    pub(crate) fn from_grids(out_zoom: u8, dim: u16, grids: Vec<(u64, Vec<u16>)>) -> Dem {-        let cells = dim as usize * dim as usize;-        let keys: Vec<(u64, usize)> =-            grids.iter().enumerate().map(|(i, (id, _))| (*id, i)).collect();-        let grids = Grids::build(keys, cells, |i, grid| grid.copy_from_slice(&grids[i].1));-        Dem { out_zoom, dim, grids }-    }--    /// The elevation at one lon/lat, bilinearly interpolated within the dataset grid that covers it,-    /// or `None` when that grid was not fetched.-    fn sample_at(&self, lon: f64, lat: f64) -> Option<u16> {-        let n = (1u64 << self.out_zoom) as f64;-        // The fractional tile position at the dataset zoom. Clamped so a point exactly on the-        // world's right/bottom edge lands in the last tile rather than one past it.-        let tx = lon_to_tile_x(lon, self.out_zoom).clamp(0.0, n - f64::EPSILON);-        let ty = lat_to_tile_y(lat, self.out_zoom).clamp(0.0, n - f64::EPSILON);-        let ix = tx.floor() as u64;-        let iy = ty.floor() as u64;-        let grid = self.grids.get(&tile_id(self.out_zoom, ix, iy))?;-        let last = self.dim as usize - 1;-        // The point's position within the tile's grid: the fraction across the tile scaled onto the-        // `dim - 1` cells between the grid's edge samples.-        let gx = (tx - ix as f64) * last as f64;-        let gy = (ty - iy as f64) * last as f64;-        let x0 = gx.floor() as usize;-        let y0 = gy.floor() as usize;-        let x1 = (x0 + 1).min(last);-        let y1 = (y0 + 1).min(last);-        let fx = gx - x0 as f64;-        let fy = gy - y0 as f64;-        let d = self.dim as usize;-        let at = |cx: usize, cy: usize| grid[cy * d + cx] as f64;-        let top = at(x0, y0) * (1.0 - fx) + at(x1, y0) * fx;-        let bot = at(x0, y1) * (1.0 - fx) + at(x1, y1) * fx;-        let v = top * (1.0 - fy) + bot * fy;-        Some(v.round().clamp(0.0, u16::MAX as f64) as u16)-    }-}--// --- slippy / web-mercator tile math, matching `dem_ingest` so a resample lands where the ingest-// would have sampled -----fn lon_to_tile_x(lon: f64, z: u8) -> f64 {-    (lon + 180.0) / 360.0 * (1u64 << z) as f64-}--fn lat_to_tile_y(lat: f64, z: u8) -> f64 {-    let r = lat.clamp(-85.05112878, 85.05112878).to_radians();-    (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64-}--fn tile_x_to_lon(x: f64, z: u8) -> f64 {-    x / (1u64 << z) as f64 * 360.0 - 180.0-}--fn tile_y_to_lat(y: f64, z: u8) -> f64 {-    let n = PI * (1.0 - 2.0 * y / (1u64 << z) as f64);-    n.sinh().atan().to_degrees()-}--#[cfg(test)]-mod tests {-    use super::*;--    /// `--dem-max-error`: a plane collapses to 2x2 (bilinear reproduces it exactly), a spike keeps-    /// the full grid, and every emitted grid stays within the bound against the full grid.-    #[test]-    fn adaptive_grids_respect_their_error_bound() {-        let full = |f: &dyn Fn(usize, usize) -> i32| Heightmap {-            dim: 9,-            samples: (0..81).map(|i| (f(i / 9, i % 9) + SEA_LEVEL as i32) as u16).collect(),-        };-        let plane = full(&|r, c| 100 + 3 * r as i32 + 2 * c as i32);-        assert_eq!(adapt_grid(&plane, 1.0).dim, 2, "a plane is exactly bilinear");-        let spike = full(&|r, c| if r == 4 && c == 4 { 500 } else { 100 });-        assert_eq!(adapt_grid(&spike, 2.0).dim, 9, "a spike keeps full resolution");-        for tol in [1.0, 2.0, 5.0, 10.0] {-            for g in [&plane, &spike, &full(&|r, c| ((r * 37 + c * 11) % 23) as i32 * 7)] {-                let out = adapt_grid(g, tol);-                assert!(-                    grid_error(g, &out).0 <= tol + 1e-9,-                    "tol {tol}: {}",-                    grid_error(g, &out).0-                );-            }-        }-    }--    /// The sorted-column grids answer exactly what the old `HashMap` built by inserting in file-    /// order answered -- for ascending files, unsorted ones, and ones repeating an id (last wins).-    #[test]-    fn grids_answer_what_a_file_order_hash_map_did() {-        let dim = 3u16;-        let cells = 9usize;-        let grid = |v: u16| vec![v; cells];-        let cases: Vec<Vec<(u64, Vec<u16>)>> = vec![-            vec![(1, grid(1)), (5, grid(5)), (9, grid(9))],-            vec![-                (9, grid(1)),-                (1, grid(2)),-                (5, grid(3)),-                (1, grid(4)),-                (7, grid(5)),-                (9, grid(6)),-            ],-            vec![],-        ];-        for tiles in cases {-            let dem = Dem::parse(&dataset(10, dim, &tiles)).expect("parse");-            let mut map = std::collections::HashMap::new();-            for (id, g) in &tiles {-                map.insert(*id, g.clone());-            }-            for id in 0..12u64 {-                assert_eq!(-                    dem.grids.get(&id).map(<[u16]>::to_vec),-                    map.get(&id).cloned(),-                    "id {id}"-                );-            }-        }-    }--    /// Serialise a synthetic `.mdem` dataset the way `dem_ingest` does, for the parser to read back.-    fn dataset(out_zoom: u8, dim: u16, tiles: &[(u64, Vec<u16>)]) -> Vec<u8> {-        let mut out = Vec::new();-        out.extend_from_slice(MAGIC);-        out.push(VERSION);-        out.push(out_zoom);-        out.extend_from_slice(&dim.to_le_bytes());-        out.extend_from_slice(&(tiles.len() as u32).to_le_bytes());-        for (id, grid) in tiles {-            out.extend_from_slice(&id.to_le_bytes());-            for &s in grid {-                out.extend_from_slice(&s.to_le_bytes());-            }-        }-        out-    }--    /// A ramp grid whose sample at `(col, row)` is `32768 + row * 10 + col`, so a read-back can name-    /// which cell it got.-    fn ramp(dim: u16) -> Vec<u16> {-        let d = dim as usize;-        let mut g = Vec::with_capacity(d * d);-        for row in 0..d {-            for col in 0..d {-                g.push(SEA_LEVEL + (row * 10 + col) as u16);-            }-        }-        g-    }--    #[test]-    fn a_tile_at_the_datasets_zoom_is_a_verbatim_copy() {-        let (z, dim) = (14u8, 17u16);-        let (x, y) = (2730u64, 6335u64);-        let grid = ramp(dim);-        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), grid.clone())])).expect("parse");-        let hm = dem.heightmap_for(z, x, y).expect("a heightmap for the covered tile");-        assert_eq!(hm.dim, dim);-        assert_eq!(hm.samples, grid, "the grid is copied byte for byte at the dataset's own zoom");-        // And it reads back through the wire type's own accessor.-        assert_eq!(hm.sample(0, 0), Some(SEA_LEVEL));-        assert_eq!(hm.sample(3, 2), Some(SEA_LEVEL + 23));-        assert_eq!(Heightmap::metres(hm.sample(3, 2).unwrap()), 23);-        assert_eq!(hm.sample(dim, 0), None, "out of range");-    }--    #[test]-    fn a_tile_off_coverage_has_no_heightmap() {-        let (z, dim) = (14u8, 17u16);-        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, 10, 10), ramp(dim))])).expect("parse");-        assert!(dem.heightmap_for(z, 999, 999).is_none(), "an uncovered tile omits the section");-    }--    #[test]-    fn an_all_sea_level_tile_has_no_heightmap() {-        let (z, dim) = (14u8, 17u16);-        let (x, y) = (2730u64, 6335u64);-        let sea = vec![SEA_LEVEL; dim as usize * dim as usize];-        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), sea)])).expect("parse");-        assert!(-            dem.heightmap_for(z, x, y).is_none(),-            "an all-ocean tile drops its heightmap so the renderer paints open water",-        );-    }--    #[test]-    fn a_resampled_all_sea_level_tile_has_no_heightmap() {-        let (oz, dim) = (14u8, 17u16);-        // Cover the whole z13 block so every resample point hits coverage, yet all at sea level.-        let sea: Vec<u16> = vec![SEA_LEVEL; dim as usize * dim as usize];-        let mut tiles = Vec::new();-        for cx in 2730..=2732u64 {-            for cy in 6334..=6336u64 {-                tiles.push((tile_id(oz, cx, cy), sea.clone()));-            }-        }-        let dem = Dem::parse(&dataset(oz, dim, &tiles)).expect("parse");-        assert!(-            dem.heightmap_for(13, 1365, 3167).is_none(),-            "a resampled all-sea-level tile drops its heightmap too",-        );-    }--    /// A coarser tile resamples from the covering grids. Sampled over a tile whose whole extent is-    /// covered, a flat field must come back flat and non-empty.-    #[test]-    fn a_coarser_tile_resamples_within_range() {-        let (oz, dim) = (14u8, 17u16);-        // A z13 tile's dim*dim points span its three edge columns/rows of z14 tiles: x in-        // 2730..=2732 and y in 6334..=6336 for z13 (1365, 3167). Cover that whole 3x3 block so no-        // sample point falls off coverage (which would read as sea level).-        let flat: Vec<u16> = vec![SEA_LEVEL + 100; dim as usize * dim as usize];-        let mut tiles = Vec::new();-        for cx in 2730..=2732u64 {-            for cy in 6334..=6336u64 {-                tiles.push((tile_id(oz, cx, cy), flat.clone()));-            }-        }-        let dem = Dem::parse(&dataset(oz, dim, &tiles)).expect("parse");-        let hm = dem.heightmap_for(13, 1365, 3167).expect("a resampled heightmap");-        // A perfectly flat field coarsens: 5x5 of 100 m everywhere.-        assert_eq!(hm.dim, FLAT_DIM, "a flat resampled tile coarsens");-        assert_eq!(hm.samples.len(), FLAT_DIM as usize * FLAT_DIM as usize);-        assert!(-            hm.samples.iter().all(|&s| s == SEA_LEVEL + 100),-            "resampling a flat 100 m field is still 100 m everywhere",-        );-    }--    #[test]-    fn a_short_dataset_is_refused() {-        assert!(Dem::parse(b"MDE").is_err(), "shorter than the header");-        assert!(Dem::parse(b"XXXX\x01\x0e\x11\x00\x00\x00\x00\x00").is_err(), "bad magic");-        // A header claiming one tile with no tile bytes behind it.-        let mut short = dataset(14, 17, &[]);-        short[8] = 1; // claim one tile-        assert!(Dem::parse(&short).is_err(), "a claimed tile past the end is refused");-    }--    /// A flat tile (relief under `FLAT_RELIEF_M`) coarsens to `FLAT_DIM`:-    /// corners survive so tile edges agree with full-resolution neighbours.-    #[test]-    fn a_flat_tile_coarsens_and_a_steep_tile_does_not() {-        let (z, dim) = (14u8, 9u16);-        let (x, y) = (2730u64, 6335u64);-        // Relief 8 m: flat farmland. Corners pinned to distinct values so the-        // test can tell nearest-pick from averaging.-        let mut flat = vec![SEA_LEVEL + 100; dim as usize * dim as usize];-        flat[0] = SEA_LEVEL + 96;-        flat[8] = SEA_LEVEL + 104;-        flat[72] = SEA_LEVEL + 97;-        flat[80] = SEA_LEVEL + 103;-        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), flat)])).expect("parse");-        let hm = dem.heightmap_for(z, x, y).expect("a heightmap");-        assert_eq!(hm.dim, FLAT_DIM, "a flat tile coarsens");-        assert_eq!(hm.samples.len(), FLAT_DIM as usize * FLAT_DIM as usize);-        assert_eq!(hm.samples[0], SEA_LEVEL + 96, "top-left corner survives");-        assert_eq!(hm.samples[4], SEA_LEVEL + 104, "top-right corner survives");-        assert_eq!(hm.samples[20], SEA_LEVEL + 97, "bottom-left corner survives");-        assert_eq!(hm.samples[24], SEA_LEVEL + 103, "bottom-right corner survives");-        // A steep tile (relief over the threshold) keeps the full grid.-        let steep = ramp(dim);-        assert!(relief(&steep) > FLAT_RELIEF_M, "the ramp is steep: {}", relief(&steep));-        let dem =-            Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), steep.clone())])).expect("parse");-        let hm = dem.heightmap_for(z, x, y).expect("a heightmap");-        assert_eq!(hm.dim, dim, "a steep tile keeps full resolution");-        assert_eq!(hm.samples, steep);-    }-}+include!("dem_s1.rs");
scripts/maps/mamaps_build/src/dem_s1.rs
diff --git a/scripts/maps/mamaps_build/src/dem_s1.rs b/scripts/maps/mamaps_build/src/dem_s1.rsnew file mode 100644index 0000000000..f008ea8e06--- /dev/null+++ b/scripts/maps/mamaps_build/src/dem_s1.rs@@ -0,0 +1,410 @@+impl Dem {+    /// Read and parse a `.mdem` dataset from disk.+    ///+    /// Mapped, not read: the 13 GB world file would otherwise cost a+    /// single-threaded `fs::read` plus a full copy before parsing starts.+    /// The mapping faults pages in on the pool's 64 threads during the+    /// parallel parse below, and the bytes are never copied — each tile's+    /// samples land directly in its grid `Vec`. The mapping drops on return;+    /// the `Dem` owns its grids.+    pub fn load(path: &Path) -> Result<Dem> {+        let mapped = osm_ingest::mem::Mapped::open(path).map_err(Error)?;+        Dem::parse(&mapped)+    }++    /// Parse a `.mdem` dataset: a 12-byte header (`MDEM`, version, out_zoom, `dim` u16, tile count+    /// u32), then per tile a `u64` tile id and its `dim * dim` `u16` samples, little-endian.+    ///+    /// Tiles parse on the pool: records are fixed-stride (`8 + cells * 2` bytes), so tile `i`+    /// starts at `12 + i * stride` with no dependency on any other tile. Each worker decodes a+    /// contiguous run into owned `(id, samples)` pairs; the single-threaded fold inserts them in+    /// file order. Same pairs as the serial loop — the map holds the same contents, and nothing+    /// ever iterates it (only `heightmap_for`'s `.get`), so no byte can move. The 13 GB world+    /// dataset's per-sample `u16::from_le_bytes` + per-tile alloc + hash insert runs ~50 s+    /// serially on every build regardless of region; fanning out the decode leaves only the+    /// `fs::read` and the inserts.+    fn parse(bytes: &[u8]) -> Result<Dem> {+        if bytes.len() < 12 {+            return err("a .mdem dataset is shorter than its 12-byte header");+        }+        if &bytes[0..4] != MAGIC {+            return err("not a .mdem dataset (bad magic)");+        }+        if bytes[4] != VERSION {+            return err(format!(+                "unsupported .mdem version {} (this build reads {VERSION})",+                bytes[4]+            ));+        }+        let out_zoom = bytes[5];+        let dim = u16::from_le_bytes([bytes[6], bytes[7]]);+        if dim < 2 {+            return err("a .mdem grid dimension is less than 2");+        }+        let count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;+        let cells = dim as usize * dim as usize;+        // One tile: an 8-byte id then `cells` little-endian u16 samples.+        let stride = 8 + cells * 2;+        if bytes.len() < 12 + count.saturating_mul(stride) {+            return err("a .mdem dataset ends before its tile count");+        }+        // Both columns on the pool (see [`Grids`]): the ids straight off their fixed-stride+        // offsets, then each grid decoded into its slot of one contiguous sample array.+        let keys: Vec<(u64, usize)> = par::install(|| {+            (0..count)+                .into_par_iter()+                .map(|i| {+                    let at = 12 + i * stride;+                    (u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")), i)+                })+                .collect()+        });+        let grids = par::install(|| {+            Grids::build(keys, cells, |i, grid| {+                let at = 12 + i * stride + 8;+                for (c, out) in grid.iter_mut().enumerate() {+                    let o = at + c * 2;+                    *out = u16::from_le_bytes([bytes[o], bytes[o + 1]]);+                }+            })+        });+        Ok(Dem { out_zoom, dim, grids })+    }++    /// The heightmap for one output tile, or `None` when no DEM covers it (so the tile omits the+    /// section and stays 16-byte).+    ///+    /// A tile at the dataset's own zoom is a verbatim copy of its grid — byte for byte what the+    /// ingest sampled, independent of neighbour coverage. Any other zoom is resampled onto this+    /// tile's grid.+    ///+    /// A grid that is **entirely sea level** yields `None` whatever the zoom: an all-ocean tile+    /// carries no relief, and emitting a flat sea-level heightmap makes the renderer draw its+    /// earth-coloured terrain grid over what should be open water (the renderer's contract is+    /// "no heightmap over ocean" — see `library/map`'s `terrain.rs`). Dropping it here is the+    /// backstop for a `.mdem` built without `dem_ingest --skip-flat`. A flat *land* tile at exactly+    /// sea level loses nothing visible: its flat `earth` fill draws the same ground the flat grid+    /// would have, and its features sit at 0 m either way.+    pub fn heightmap_for(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {+        if z == self.out_zoom {+            let samples = self.grids.get(&tile_id(z, x, y))?;+            if all_sea_level(samples) {+                return None;+            }+            // A flat tile's grid is mostly repetition: coarsen it. Steep+            // tiles keep the full grid.+            return Some(finish_grid(z, y, samples, self.dim));+        }+        self.resample(z, x, y)+    }++    /// Resample the dataset's grids onto one tile's `dim * dim` grid, sampling `dim * dim` points+    /// across the tile's own extent from its top-left — the same slippy walk `dem_ingest` runs over+    /// the terrarium grid, sourced from the loaded grids instead of PNGs.+    fn resample(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {+        let dim = self.dim as usize;+        let mut samples = Vec::with_capacity(dim * dim);+        let mut any = false;+        for row in 0..dim {+            let fy = y as f64 + row as f64 / (self.dim as f64 - 1.0);+            let lat = tile_y_to_lat(fy, z);+            for col in 0..dim {+                let fx = x as f64 + col as f64 / (self.dim as f64 - 1.0);+                let lon = tile_x_to_lon(fx, z);+                match self.sample_at(lon, lat) {+                    Some(v) => {+                        any = true;+                        samples.push(v);+                    }+                    // No DEM here: sea level, as `dem_ingest` fills a missing terrarium pixel. A+                    // tile entirely over missing DEM is dropped below.+                    None => samples.push(SEA_LEVEL),+                }+            }+        }+        // A tile whose every sample is sea level carries no relief: drop it so the renderer paints+        // open water rather than a flat earth-coloured terrain grid (see `heightmap_for`).+        if !any || all_sea_level(&samples) {+            return None;+        }+        // Same flat-tile coarsening as the verbatim path: the resampled grid+        // is full resolution, so relief is measured on it directly.+        Some(finish_grid(z, y, &samples, self.dim))+    }++    /// Build a dataset directly from grids, for tests that inject a synthetic DEM into the tiler+    /// rather than round-tripping bytes through disk.+    #[cfg(test)]+    pub(crate) fn from_grids(out_zoom: u8, dim: u16, grids: Vec<(u64, Vec<u16>)>) -> Dem {+        let cells = dim as usize * dim as usize;+        let keys: Vec<(u64, usize)> =+            grids.iter().enumerate().map(|(i, (id, _))| (*id, i)).collect();+        let grids = Grids::build(keys, cells, |i, grid| grid.copy_from_slice(&grids[i].1));+        Dem { out_zoom, dim, grids }+    }++    /// The elevation at one lon/lat, bilinearly interpolated within the dataset grid that covers it,+    /// or `None` when that grid was not fetched.+    fn sample_at(&self, lon: f64, lat: f64) -> Option<u16> {+        let n = (1u64 << self.out_zoom) as f64;+        // The fractional tile position at the dataset zoom. Clamped so a point exactly on the+        // world's right/bottom edge lands in the last tile rather than one past it.+        let tx = lon_to_tile_x(lon, self.out_zoom).clamp(0.0, n - f64::EPSILON);+        let ty = lat_to_tile_y(lat, self.out_zoom).clamp(0.0, n - f64::EPSILON);+        let ix = tx.floor() as u64;+        let iy = ty.floor() as u64;+        let grid = self.grids.get(&tile_id(self.out_zoom, ix, iy))?;+        let last = self.dim as usize - 1;+        // The point's position within the tile's grid: the fraction across the tile scaled onto the+        // `dim - 1` cells between the grid's edge samples.+        let gx = (tx - ix as f64) * last as f64;+        let gy = (ty - iy as f64) * last as f64;+        let x0 = gx.floor() as usize;+        let y0 = gy.floor() as usize;+        let x1 = (x0 + 1).min(last);+        let y1 = (y0 + 1).min(last);+        let fx = gx - x0 as f64;+        let fy = gy - y0 as f64;+        let d = self.dim as usize;+        let at = |cx: usize, cy: usize| grid[cy * d + cx] as f64;+        let top = at(x0, y0) * (1.0 - fx) + at(x1, y0) * fx;+        let bot = at(x0, y1) * (1.0 - fx) + at(x1, y1) * fx;+        let v = top * (1.0 - fy) + bot * fy;+        Some(v.round().clamp(0.0, u16::MAX as f64) as u16)+    }+}++// --- slippy / web-mercator tile math, matching `dem_ingest` so a resample lands where the ingest+// would have sampled ---++fn lon_to_tile_x(lon: f64, z: u8) -> f64 {+    (lon + 180.0) / 360.0 * (1u64 << z) as f64+}++fn lat_to_tile_y(lat: f64, z: u8) -> f64 {+    let r = lat.clamp(-85.05112878, 85.05112878).to_radians();+    (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64+}++fn tile_x_to_lon(x: f64, z: u8) -> f64 {+    x / (1u64 << z) as f64 * 360.0 - 180.0+}++fn tile_y_to_lat(y: f64, z: u8) -> f64 {+    let n = PI * (1.0 - 2.0 * y / (1u64 << z) as f64);+    n.sinh().atan().to_degrees()+}++#[cfg(test)]+mod tests {+    use super::*;++    /// `--dem-max-error`: a plane collapses to 2x2 (bilinear reproduces it exactly), a spike keeps+    /// the full grid, and every emitted grid stays within the bound against the full grid.+    #[test]+    fn adaptive_grids_respect_their_error_bound() {+        let full = |f: &dyn Fn(usize, usize) -> i32| Heightmap {+            dim: 9,+            samples: (0..81).map(|i| (f(i / 9, i % 9) + SEA_LEVEL as i32) as u16).collect(),+        };+        let plane = full(&|r, c| 100 + 3 * r as i32 + 2 * c as i32);+        assert_eq!(adapt_grid(&plane, 1.0).dim, 2, "a plane is exactly bilinear");+        let spike = full(&|r, c| if r == 4 && c == 4 { 500 } else { 100 });+        assert_eq!(adapt_grid(&spike, 2.0).dim, 9, "a spike keeps full resolution");+        for tol in [1.0, 2.0, 5.0, 10.0] {+            for g in [&plane, &spike, &full(&|r, c| ((r * 37 + c * 11) % 23) as i32 * 7)] {+                let out = adapt_grid(g, tol);+                assert!(+                    grid_error(g, &out).0 <= tol + 1e-9,+                    "tol {tol}: {}",+                    grid_error(g, &out).0+                );+            }+        }+    }++    /// The sorted-column grids answer exactly what the old `HashMap` built by inserting in file+    /// order answered -- for ascending files, unsorted ones, and ones repeating an id (last wins).+    #[test]+    fn grids_answer_what_a_file_order_hash_map_did() {+        let dim = 3u16;+        let cells = 9usize;+        let grid = |v: u16| vec![v; cells];+        let cases: Vec<Vec<(u64, Vec<u16>)>> = vec![+            vec![(1, grid(1)), (5, grid(5)), (9, grid(9))],+            vec![+                (9, grid(1)),+                (1, grid(2)),+                (5, grid(3)),+                (1, grid(4)),+                (7, grid(5)),+                (9, grid(6)),+            ],+            vec![],+        ];+        for tiles in cases {+            let dem = Dem::parse(&dataset(10, dim, &tiles)).expect("parse");+            let mut map = std::collections::HashMap::new();+            for (id, g) in &tiles {+                map.insert(*id, g.clone());+            }+            for id in 0..12u64 {+                assert_eq!(+                    dem.grids.get(&id).map(<[u16]>::to_vec),+                    map.get(&id).cloned(),+                    "id {id}"+                );+            }+        }+    }++    /// Serialise a synthetic `.mdem` dataset the way `dem_ingest` does, for the parser to read back.+    fn dataset(out_zoom: u8, dim: u16, tiles: &[(u64, Vec<u16>)]) -> Vec<u8> {+        let mut out = Vec::new();+        out.extend_from_slice(MAGIC);+        out.push(VERSION);+        out.push(out_zoom);+        out.extend_from_slice(&dim.to_le_bytes());+        out.extend_from_slice(&(tiles.len() as u32).to_le_bytes());+        for (id, grid) in tiles {+            out.extend_from_slice(&id.to_le_bytes());+            for &s in grid {+                out.extend_from_slice(&s.to_le_bytes());+            }+        }+        out+    }++    /// A ramp grid whose sample at `(col, row)` is `32768 + row * 10 + col`, so a read-back can name+    /// which cell it got.+    fn ramp(dim: u16) -> Vec<u16> {+        let d = dim as usize;+        let mut g = Vec::with_capacity(d * d);+        for row in 0..d {+            for col in 0..d {+                g.push(SEA_LEVEL + (row * 10 + col) as u16);+            }+        }+        g+    }++    #[test]+    fn a_tile_at_the_datasets_zoom_is_a_verbatim_copy() {+        let (z, dim) = (14u8, 17u16);+        let (x, y) = (2730u64, 6335u64);+        let grid = ramp(dim);+        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), grid.clone())])).expect("parse");+        let hm = dem.heightmap_for(z, x, y).expect("a heightmap for the covered tile");+        assert_eq!(hm.dim, dim);+        assert_eq!(hm.samples, grid, "the grid is copied byte for byte at the dataset's own zoom");+        // And it reads back through the wire type's own accessor.+        assert_eq!(hm.sample(0, 0), Some(SEA_LEVEL));+        assert_eq!(hm.sample(3, 2), Some(SEA_LEVEL + 23));+        assert_eq!(Heightmap::metres(hm.sample(3, 2).unwrap()), 23);+        assert_eq!(hm.sample(dim, 0), None, "out of range");+    }++    #[test]+    fn a_tile_off_coverage_has_no_heightmap() {+        let (z, dim) = (14u8, 17u16);+        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, 10, 10), ramp(dim))])).expect("parse");+        assert!(dem.heightmap_for(z, 999, 999).is_none(), "an uncovered tile omits the section");+    }++    #[test]+    fn an_all_sea_level_tile_has_no_heightmap() {+        let (z, dim) = (14u8, 17u16);+        let (x, y) = (2730u64, 6335u64);+        let sea = vec![SEA_LEVEL; dim as usize * dim as usize];+        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), sea)])).expect("parse");+        assert!(+            dem.heightmap_for(z, x, y).is_none(),+            "an all-ocean tile drops its heightmap so the renderer paints open water",+        );+    }++    #[test]+    fn a_resampled_all_sea_level_tile_has_no_heightmap() {+        let (oz, dim) = (14u8, 17u16);+        // Cover the whole z13 block so every resample point hits coverage, yet all at sea level.+        let sea: Vec<u16> = vec![SEA_LEVEL; dim as usize * dim as usize];+        let mut tiles = Vec::new();+        for cx in 2730..=2732u64 {+            for cy in 6334..=6336u64 {+                tiles.push((tile_id(oz, cx, cy), sea.clone()));+            }+        }+        let dem = Dem::parse(&dataset(oz, dim, &tiles)).expect("parse");+        assert!(+            dem.heightmap_for(13, 1365, 3167).is_none(),+            "a resampled all-sea-level tile drops its heightmap too",+        );+    }++    /// A coarser tile resamples from the covering grids. Sampled over a tile whose whole extent is+    /// covered, a flat field must come back flat and non-empty.+    #[test]+    fn a_coarser_tile_resamples_within_range() {+        let (oz, dim) = (14u8, 17u16);+        // A z13 tile's dim*dim points span its three edge columns/rows of z14 tiles: x in+        // 2730..=2732 and y in 6334..=6336 for z13 (1365, 3167). Cover that whole 3x3 block so no+        // sample point falls off coverage (which would read as sea level).+        let flat: Vec<u16> = vec![SEA_LEVEL + 100; dim as usize * dim as usize];+        let mut tiles = Vec::new();+        for cx in 2730..=2732u64 {+            for cy in 6334..=6336u64 {+                tiles.push((tile_id(oz, cx, cy), flat.clone()));+            }+        }+        let dem = Dem::parse(&dataset(oz, dim, &tiles)).expect("parse");+        let hm = dem.heightmap_for(13, 1365, 3167).expect("a resampled heightmap");+        // A perfectly flat field coarsens: 5x5 of 100 m everywhere.+        assert_eq!(hm.dim, FLAT_DIM, "a flat resampled tile coarsens");+        assert_eq!(hm.samples.len(), FLAT_DIM as usize * FLAT_DIM as usize);+        assert!(+            hm.samples.iter().all(|&s| s == SEA_LEVEL + 100),+            "resampling a flat 100 m field is still 100 m everywhere",+        );+    }++    #[test]+    fn a_short_dataset_is_refused() {+        assert!(Dem::parse(b"MDE").is_err(), "shorter than the header");+        assert!(Dem::parse(b"XXXX\x01\x0e\x11\x00\x00\x00\x00\x00").is_err(), "bad magic");+        // A header claiming one tile with no tile bytes behind it.+        let mut short = dataset(14, 17, &[]);+        short[8] = 1; // claim one tile+        assert!(Dem::parse(&short).is_err(), "a claimed tile past the end is refused");+    }++    /// A flat tile (relief under `FLAT_RELIEF_M`) coarsens to `FLAT_DIM`:+    /// corners survive so tile edges agree with full-resolution neighbours.+    #[test]+    fn a_flat_tile_coarsens_and_a_steep_tile_does_not() {+        let (z, dim) = (14u8, 9u16);+        let (x, y) = (2730u64, 6335u64);+        // Relief 8 m: flat farmland. Corners pinned to distinct values so the+        // test can tell nearest-pick from averaging.+        let mut flat = vec![SEA_LEVEL + 100; dim as usize * dim as usize];+        flat[0] = SEA_LEVEL + 96;+        flat[8] = SEA_LEVEL + 104;+        flat[72] = SEA_LEVEL + 97;+        flat[80] = SEA_LEVEL + 103;+        let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), flat)])).expect("parse");+        let hm = dem.heightmap_for(z, x, y).expect("a heightmap");+        assert_eq!(hm.dim, FLAT_DIM, "a flat tile coarsens");+        assert_eq!(hm.samples.len(), FLAT_DIM as usize * FLAT_DIM as usize);+        assert_eq!(hm.samples[0], SEA_LEVEL + 96, "top-left corner survives");+        assert_eq!(hm.samples[4], SEA_LEVEL + 104, "top-right corner survives");+        assert_eq!(hm.samples[20], SEA_LEVEL + 97, "bottom-left corner survives");+        assert_eq!(hm.samples[24], SEA_LEVEL + 103, "bottom-right corner survives");+        // A steep tile (relief over the threshold) keeps the full grid.+        let steep = ramp(dim);+        assert!(relief(&steep) > FLAT_RELIEF_M, "the ramp is steep: {}", relief(&steep));+        let dem =+            Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), steep.clone())])).expect("parse");+        let hm = dem.heightmap_for(z, x, y).expect("a heightmap");+        assert_eq!(hm.dim, dim, "a steep tile keeps full resolution");+        assert_eq!(hm.samples, steep);+    }+}
scripts/maps/mamaps_build/src/extract_fallback.rs
diff --git a/scripts/maps/mamaps_build/src/extract_fallback.rs b/scripts/maps/mamaps_build/src/extract_fallback.rsindex 46c33f9e3e..c69284a2dc 100644--- a/scripts/maps/mamaps_build/src/extract_fallback.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -373,209 +373,5 @@ pub fn extend_region_links(     extend_region_links_with(store, region_links, &mut HashMap::new(), &HashMap::new()) } -/// [`extend_region_links`], also filling `country_zooms`: place tagged id → label start-/// zoom for `country` places, from each country's ground footprint and headcount (see-/// [`country_zoom`]). `populations` maps place tagged id → `population` tag headcount-/// (relation places; node/way countries are absent and score as unpopulated — the area-/// term still separates Russia from Nauru). The caller hands both maps to the tiler-/// beside `region_links`.-pub fn extend_region_links_with(-    store: &crate::store::Store,-    region_links: &mut HashMap<u64, u64>,-    country_zooms: &mut HashMap<u64, u8>,-    populations: &HashMap<u64, u64>,-) -> Result<FallbackStats> {-    // Pass 1: boundary shapes AND places, in one scan. Only `region_area`-    // areas (the mask's own shapes, carrying the admin level in `kind_detail`);-    // border lines enclose nothing. Places are positional, so node,-    // way-centroided and relation-centroided labels all link by the tagged id-    // they already carry.-    //-    // One scan, not two: the store reader is one sequential cursor over tens-    // of GB of spill, and both passes filtered it by layer. Collecting both-    // vectors in a single streaming pass deletes a full decode. Peak is-    // unchanged — boundaries already lived through place collection.-    struct PlacePoint {-        id: u64,-        point: (f64, f64),-        kind: Band,-        kind_name: String,-    }-    enum Kept {-        Boundary(Boundary),-        Place(PlacePoint),-    }-    // The scan decodes the whole store across the pool (`Store::par_scan_where`, file order kept), and-    // the per-feature filter -- including `Boundary::new`'s area and bbox walk -- runs there too.-    // The split into the two vectors below is in file order, so both are exactly what the-    // one-cursor loop built.-    // Pre-filter on the packed class (no geometry decoded): only an id-carrying boundary area-    // or place can pass the filter below.-    let kept = store.par_scan_where(-        |class, has_id| {-            has_id-                && ((class.layer == LAYER_BOUNDARIES && class.area) || class.layer == LAYER_PLACES)-        },-        |feature| {-            if feature.id == ID_NONE {-                return None;-            }-            if feature.class.layer == LAYER_BOUNDARIES && feature.class.area {-                let Geometry::Polygons(polygons) = feature.geometry else {-                    return None;-                };-                if polygons.is_empty() {-                    return None;-                }-                Some(Kept::Boundary(Boundary::new(feature.id, feature.class.kind_detail, polygons)))-            } else if feature.class.layer == LAYER_PLACES {-                let Geometry::Points(points) = feature.geometry else {-                    return None;-                };-                let &point = points.first()?;-                let kind_name = place_kind_name(feature.class.kind)?;-                let band = band_for_place_kind(kind_name)?;-                Some(Kept::Place(PlacePoint {-                    id: feature.id,-                    point,-                    kind: band,-                    kind_name: kind_name.to_string(),-                }))-            } else {-                None-            }-        },-    )?;-    let mut boundaries: Vec<Boundary> = Vec::new();-    let mut places: Vec<PlacePoint> = Vec::new();-    for item in kept {-        match item {-            Kept::Boundary(b) => boundaries.push(b),-            Kept::Place(p) => places.push(p),-        }-    }-    boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0);-    let grid = Grid::build(&boundaries);-    // The `country_zoom` lookup below used to walk `boundaries` linearly per-    // linked country; indexed by id so it is a hash lookup instead. Built-    // once — the vec never moves again after this.-    let boundary_by_id: HashMap<u64, usize> =-        boundaries.iter().enumerate().map(|(i, b)| (b.id, i)).collect();--    // Pass 2: places. Positional, so node, way-centroided and relation-centroided labels all-    // link by the tagged id they already carry — the only path that can link non-node places,-    // since the member map is node-keyed. Country labels also gain their area+population-    // start zoom here (see `country_zoom`): the linked boundary's footprint is in hand,-    // so no third pass is needed. The headcount comes from `populations` (relation-    // places, filled by the caller while tags were in hand); absent entries score as-    // unpopulated — Antarctica's case — never as missing.-    //-    // Collected serially first — the store reader is one sequential cursor —-    // then linked on the pool: `select_link` is pure per-place work over the-    // shared grid, and the drain inserts in collection order with member-    // links winning, exactly as the serial loop did. `select_link` returns-    // at most one target per place, so the drain cannot double-insert and-    // the map bytes are identical.-    //-    // NOTE: `places` now arrives from the fused pass-1 scan above (same-    // reader, same filter, same spill order), not from a second scan. What-    // follows is unchanged: drain order — and therefore every inserted key,-    // value, stat and country zoom — is identical.-    let mut stats = FallbackStats::default();-    let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new();-    // Member links always win: counted exactly as the serial loop did,-    // and skipped in the link pass so nothing contends on the map.-    for place in &places {-        stats.places_total += 1;-        let entry = per_kind.entry(place.kind_name.clone()).or_insert((0, 0));-        entry.0 += 1;-        if region_links.contains_key(&place.id) {-            stats.member_linked += 1;-            entry.1 += 1;-        }-    }-    // Parallel link: one candidate-set build + `select_link` per-    // member-less place, on the pool; the drain inserts in collection-    // order, so the map — and the stats — are identical at every thread-    // count. `select_link` returns at most one target per place, so the-    // drain cannot double-insert. The bar ticks in the drain per place, so-    // it spans the whole pass even though the expensive half runs on the-    // pool.-    let mut bar = Progress::new("Fallback: places".to_string(), places.len(), "place(s)", true);-    const FALLBACK_BATCH: usize = 16 * 1024;-    let mut batch: Vec<usize> = Vec::with_capacity(FALLBACK_BATCH);-    let mut built: Vec<Option<u64>> = Vec::with_capacity(FALLBACK_BATCH);-    let mut at = 0usize;-    while at < places.len() {-        batch.clear();-        while at < places.len() && batch.len() < FALLBACK_BATCH {-            if region_links.contains_key(&places[at].id) {-                // Member-linked: counted above, nothing to compute. The tick-                // keeps the bar spanning every place, not just computed ones.-                bar.tick("place(s)");-                at += 1;-                continue;-            }-            batch.push(at);-            at += 1;-        }-        if batch.is_empty() {-            continue;-        }-        built.clear();-        par::install(|| {-            batch-                .par_iter()-                .map(|&pi| {-                    let place = &places[pi];-                    let candidates: Vec<&Boundary> =-                        grid.candidates_for(place.point).map(|i| &boundaries[i]).collect();-                    select_link(place.point, place.kind, &candidates)-                })-                .collect_into_vec(&mut built)-        });-        for (&pi, target) in batch.iter().zip(built.drain(..)) {-            let place = &places[pi];-            if let Some(target) = target {-                region_links.insert(place.id, target);-                stats.fallback_linked += 1;-                if let Some(entry) = per_kind.get_mut(&place.kind_name) {-                    entry.1 += 1;-                }-            }-            // A country label starts at the zoom its footprint earns. The-            // linked boundary (member half inserted before this pass,-            // fallback half just above — both visible in `region_links`-            // now) carries the ground area; the headcount comes from-            // `populations` (relation places, filled by the caller while-            // tags were in hand); absent entries score as unpopulated —-            // Antarctica's case — never as missing. Unlinked countries keep-            // the schema floor (z0): a missing link must never hide a-            // country.-            if place.kind_name == "country" {-                if let Some(target) = region_links.get(&place.id) {-                    if let Some(&bi) = boundary_by_id.get(target) {-                        let boundary = &boundaries[bi];-                        let mid_lat =-                            boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0);-                        let population = populations.get(&place.id).copied().unwrap_or(0);-                        country_zooms-                            .insert(place.id, country_zoom(boundary.area, mid_lat, population));-                        stats.country_zooms += 1;-                    }-                }-            }-            bar.tick("place(s)");-        }-    }-    bar.finish("place(s)");-    stats.fallback_missed =-        stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked);-    let mut kinds: Vec<(String, u64, u64)> =-        per_kind.into_iter().map(|(kind, (total, linked))| (kind, total, linked)).collect();-    kinds.sort_by(|a, b| a.0.cmp(&b.0));-    stats.per_kind = kinds;-    Ok(stats)-}-+include!("extract_fallback_s1.rs"); include!("extract_fallback_part1.rs");
scripts/maps/mamaps_build/src/extract_fallback_s1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_fallback_s1.rs b/scripts/maps/mamaps_build/src/extract_fallback_s1.rsnew file mode 100644index 0000000000..1302a9f4a6--- /dev/null+++ b/scripts/maps/mamaps_build/src/extract_fallback_s1.rs@@ -0,0 +1,205 @@+/// [`extend_region_links`], also filling `country_zooms`: place tagged id → label start+/// zoom for `country` places, from each country's ground footprint and headcount (see+/// [`country_zoom`]). `populations` maps place tagged id → `population` tag headcount+/// (relation places; node/way countries are absent and score as unpopulated — the area+/// term still separates Russia from Nauru). The caller hands both maps to the tiler+/// beside `region_links`.+pub fn extend_region_links_with(+    store: &crate::store::Store,+    region_links: &mut HashMap<u64, u64>,+    country_zooms: &mut HashMap<u64, u8>,+    populations: &HashMap<u64, u64>,+) -> Result<FallbackStats> {+    // Pass 1: boundary shapes AND places, in one scan. Only `region_area`+    // areas (the mask's own shapes, carrying the admin level in `kind_detail`);+    // border lines enclose nothing. Places are positional, so node,+    // way-centroided and relation-centroided labels all link by the tagged id+    // they already carry.+    //+    // One scan, not two: the store reader is one sequential cursor over tens+    // of GB of spill, and both passes filtered it by layer. Collecting both+    // vectors in a single streaming pass deletes a full decode. Peak is+    // unchanged — boundaries already lived through place collection.+    struct PlacePoint {+        id: u64,+        point: (f64, f64),+        kind: Band,+        kind_name: String,+    }+    enum Kept {+        Boundary(Boundary),+        Place(PlacePoint),+    }+    // The scan decodes the whole store across the pool (`Store::par_scan_where`, file order kept), and+    // the per-feature filter -- including `Boundary::new`'s area and bbox walk -- runs there too.+    // The split into the two vectors below is in file order, so both are exactly what the+    // one-cursor loop built.+    // Pre-filter on the packed class (no geometry decoded): only an id-carrying boundary area+    // or place can pass the filter below.+    let kept = store.par_scan_where(+        |class, has_id| {+            has_id+                && ((class.layer == LAYER_BOUNDARIES && class.area) || class.layer == LAYER_PLACES)+        },+        |feature| {+            if feature.id == ID_NONE {+                return None;+            }+            if feature.class.layer == LAYER_BOUNDARIES && feature.class.area {+                let Geometry::Polygons(polygons) = feature.geometry else {+                    return None;+                };+                if polygons.is_empty() {+                    return None;+                }+                Some(Kept::Boundary(Boundary::new(feature.id, feature.class.kind_detail, polygons)))+            } else if feature.class.layer == LAYER_PLACES {+                let Geometry::Points(points) = feature.geometry else {+                    return None;+                };+                let &point = points.first()?;+                let kind_name = place_kind_name(feature.class.kind)?;+                let band = band_for_place_kind(kind_name)?;+                Some(Kept::Place(PlacePoint {+                    id: feature.id,+                    point,+                    kind: band,+                    kind_name: kind_name.to_string(),+                }))+            } else {+                None+            }+        },+    )?;+    let mut boundaries: Vec<Boundary> = Vec::new();+    let mut places: Vec<PlacePoint> = Vec::new();+    for item in kept {+        match item {+            Kept::Boundary(b) => boundaries.push(b),+            Kept::Place(p) => places.push(p),+        }+    }+    boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0);+    let grid = Grid::build(&boundaries);+    // The `country_zoom` lookup below used to walk `boundaries` linearly per+    // linked country; indexed by id so it is a hash lookup instead. Built+    // once — the vec never moves again after this.+    let boundary_by_id: HashMap<u64, usize> =+        boundaries.iter().enumerate().map(|(i, b)| (b.id, i)).collect();++    // Pass 2: places. Positional, so node, way-centroided and relation-centroided labels all+    // link by the tagged id they already carry — the only path that can link non-node places,+    // since the member map is node-keyed. Country labels also gain their area+population+    // start zoom here (see `country_zoom`): the linked boundary's footprint is in hand,+    // so no third pass is needed. The headcount comes from `populations` (relation+    // places, filled by the caller while tags were in hand); absent entries score as+    // unpopulated — Antarctica's case — never as missing.+    //+    // Collected serially first — the store reader is one sequential cursor —+    // then linked on the pool: `select_link` is pure per-place work over the+    // shared grid, and the drain inserts in collection order with member+    // links winning, exactly as the serial loop did. `select_link` returns+    // at most one target per place, so the drain cannot double-insert and+    // the map bytes are identical.+    //+    // NOTE: `places` now arrives from the fused pass-1 scan above (same+    // reader, same filter, same spill order), not from a second scan. What+    // follows is unchanged: drain order — and therefore every inserted key,+    // value, stat and country zoom — is identical.+    let mut stats = FallbackStats::default();+    let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new();+    // Member links always win: counted exactly as the serial loop did,+    // and skipped in the link pass so nothing contends on the map.+    for place in &places {+        stats.places_total += 1;+        let entry = per_kind.entry(place.kind_name.clone()).or_insert((0, 0));+        entry.0 += 1;+        if region_links.contains_key(&place.id) {+            stats.member_linked += 1;+            entry.1 += 1;+        }+    }+    // Parallel link: one candidate-set build + `select_link` per+    // member-less place, on the pool; the drain inserts in collection+    // order, so the map — and the stats — are identical at every thread+    // count. `select_link` returns at most one target per place, so the+    // drain cannot double-insert. The bar ticks in the drain per place, so+    // it spans the whole pass even though the expensive half runs on the+    // pool.+    let mut bar = Progress::new("Fallback: places".to_string(), places.len(), "place(s)", true);+    const FALLBACK_BATCH: usize = 16 * 1024;+    let mut batch: Vec<usize> = Vec::with_capacity(FALLBACK_BATCH);+    let mut built: Vec<Option<u64>> = Vec::with_capacity(FALLBACK_BATCH);+    let mut at = 0usize;+    while at < places.len() {+        batch.clear();+        while at < places.len() && batch.len() < FALLBACK_BATCH {+            if region_links.contains_key(&places[at].id) {+                // Member-linked: counted above, nothing to compute. The tick+                // keeps the bar spanning every place, not just computed ones.+                bar.tick("place(s)");+                at += 1;+                continue;+            }+            batch.push(at);+            at += 1;+        }+        if batch.is_empty() {+            continue;+        }+        built.clear();+        par::install(|| {+            batch+                .par_iter()+                .map(|&pi| {+                    let place = &places[pi];+                    let candidates: Vec<&Boundary> =+                        grid.candidates_for(place.point).map(|i| &boundaries[i]).collect();+                    select_link(place.point, place.kind, &candidates)+                })+                .collect_into_vec(&mut built)+        });+        for (&pi, target) in batch.iter().zip(built.drain(..)) {+            let place = &places[pi];+            if let Some(target) = target {+                region_links.insert(place.id, target);+                stats.fallback_linked += 1;+                if let Some(entry) = per_kind.get_mut(&place.kind_name) {+                    entry.1 += 1;+                }+            }+            // A country label starts at the zoom its footprint earns. The+            // linked boundary (member half inserted before this pass,+            // fallback half just above — both visible in `region_links`+            // now) carries the ground area; the headcount comes from+            // `populations` (relation places, filled by the caller while+            // tags were in hand); absent entries score as unpopulated —+            // Antarctica's case — never as missing. Unlinked countries keep+            // the schema floor (z0): a missing link must never hide a+            // country.+            if place.kind_name == "country" {+                if let Some(target) = region_links.get(&place.id) {+                    if let Some(&bi) = boundary_by_id.get(target) {+                        let boundary = &boundaries[bi];+                        let mid_lat =+                            boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0);+                        let population = populations.get(&place.id).copied().unwrap_or(0);+                        country_zooms+                            .insert(place.id, country_zoom(boundary.area, mid_lat, population));+                        stats.country_zooms += 1;+                    }+                }+            }+            bar.tick("place(s)");+        }+    }+    bar.finish("place(s)");+    stats.fallback_missed =+        stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked);+    let mut kinds: Vec<(String, u64, u64)> =+        per_kind.into_iter().map(|(kind, (total, linked))| (kind, total, linked)).collect();+    kinds.sort_by(|a, b| a.0.cmp(&b.0));+    stats.per_kind = kinds;+    Ok(stats)+}+
scripts/maps/mamaps_build/src/extract_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1.rs b/scripts/maps/mamaps_build/src/extract_part1.rsindex 9df762734f..bf58af3bc4 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -393,295 +393,4 @@ struct Pass1Out {     needed: NeededBits, } -/// Pass 1 (ways + relations) plus the corridor promotion. Moved whole from-/// `extract` so part files can cut at fn boundaries; behavior identical.-///-/// `blob_kinds_in` is an optional pre-computed mask (the graph sidecar) that lets this pass skip-/// node blobs; `None` means scan the whole file. Either way the mask it returns is complete.-///-/// `spill_plan` is the budget gate's backend choice: the ways spill stages anonymously or through-/// the `.tmp` at `ways_path`. Decided by the caller from pass-0 counts, not here, because this-/// pass cannot know the graph size that shares its peak.-#[allow(clippy::too_many_arguments)]-fn run_pass1(-    input: &Path,-    blobs: &[pbf::BlobLoc],-    blob_kinds_in: Option<&[u8]>,-    select: &Select,-    layers: Layers,-    ways_path: &Path,-    spill_plan: osm_ingest::mem::SpillPlan,-    stats: &mut Stats,-    timer: &mut crate::timing::PhaseTimer,-) -> Result<Pass1Out> {-    // --- 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 mut ways = WaySink::create_planned(ways_path, spill_plan)?;-    let mut relations: Vec<Relation> = Vec::new();-    // The needed-node bitset, fused into this pass: every classified way sets-    // its refs here in the drain below, so pass 3 never re-reads the ways-    // spill to collect them. Grows on demand (the maximum is not known until-    // the last push); member refs join after the drain.-    let mut needed = NeededBits::new_growable();-    // `admin_centre`/`label` node member -> boundary relation id (raw), gathered as region shapes-    // are classified below. See [`Pass1Out::region_label_nodes`].-    let mut region_label_nodes: HashMap<i64, i64> = HashMap::new();-    // Road ways carrying a `ref`, for the corridor pass below. A small minority of ways,-    // and the only thing pass 1 keeps in memory besides the relations.-    let mut corridors: Vec<crate::corridor::Segment> = Vec::new();-    let blob_kinds = pbf::run_pass_sink(-        input,-        blobs,-        pbf::PassSpec {-            blob_kinds: blob_kinds_in,-            want: KIND_WAYS | KIND_RELATIONS,-            label: "Pass 1: ways and relations",-        },-        || {-            (-                Vec::<WayBlock>::new(),-                Vec::<Relation>::new(),-                Vec::<crate::corridor::Segment>::new(),-                Vec::<(i64, i64)>::new(),-                Vec::<i64>::new(),-            )-        },-        |state, block| {-            let mut kinds = 0u8;-            // This block's refs land past here; sorted and deduped below, so the drain sets-            // the needed bitset in ascending runs instead of chasing every ref.-            let refs_from = state.4.len();-            visit_block(block, KIND_WAYS | KIND_RELATIONS, &mut kinds, &mut |el| {-                match el {-                    Element::Way(way) => {-                        if !select.matches(|k| way.tags.get_str(k)) {-                            return Ok(());-                        }-                        if let Some(class) = schema::classify(&way.tags, true, layers) {-                            // A numbered road's `min_zoom` is decided per corridor, not per-                            // way, so that a route does not vanish where its class changes.-                            // Slip roads are left out: they carry the parent's `ref` and-                            // would be promoted into junction stubs at world zoom.-                            if class.layer == tilecodec::mamaps::dict::LAYER_ROADS-                                && class.flags & tilecodec::mamaps::body::FLAG_IS_LINK == 0-                                && way.refs.len() >= 2-                            {-                                if let Some(route) = crate::corridor::route_key(&way.tags) {-                                    state.2.push(crate::corridor::Segment {-                                        way_id: way.id,-                                        route,-                                        first_node: way.refs[0],-                                        last_node: way.refs[way.refs.len() - 1],-                                        min_zoom: class.min_zoom,-                                    });-                                }-                            }-                            let name = schema::display_name(&way.tags, class.layer);-                            // A road's carriageway lane count, per-lane turn masks and directional-                            // split, baked so the renderer can draw the lanes individually, place-                            // turn arrows and put the centre line where the traffic divides. Zero,-                            // empty and default for every other layer.-                            let is_road =-                                class.layer == tilecodec::mamaps::dict::LAYER_ROADS;-                            let lane_count = if is_road {-                                schema::roads::lane_count(&way.tags)-                            } else {-                                0-                            };-                            let (turn_fwd, turn_bwd) = if is_road {-                                schema::roads::turn_masks(&way.tags)-                            } else {-                                (Vec::new(), Vec::new())-                            };-                            let carriageway = if is_road {-                                schema::roads::carriageway(&way.tags)-                            } else {-                                Carriageway::default()-                            };-                            // A building's S3DB attributes, parsed once here beside its class.-                            // Zero-cost for the overwhelming majority of ways, which are not-                            // buildings.-                            let building = if class.layer == LAYER_BUILDINGS {-                                Some(schema::buildings::attrs(&way.tags))-                            } else {-                                None-                            };-                            // Encoded HERE, on the worker, into the chunk's ways-spill blocks: the-                            // drain only patches each block's first id and appends it. This was-                            // the serial drain's record-by-record encode, which held pass 1 to ~4-                            // of 192 cores on the planet (4m40s). Same bytes; see `WayBlock`.-                            if state.0.last().is_none_or(|b| b.len() >= WAY_BLOCK_WAYS) {-                                state.0.push(WayBlock::new());-                            }-                            let refs: &[i64] = way.refs;-                            state.0.last_mut().expect("pushed above").push(-                                way.id,-                                &class,-                                refs,-                                name.as_deref(),-                                lane_count,-                                &turn_fwd,-                                &turn_bwd,-                                carriageway,-                                building,-                            )?;-                            state.4.extend_from_slice(refs);-                        }-                    }-                    Element::Relation(relation) => {-                        // Two relation types carry a shape. Anything else — a site, a-                        // public_transport — does not.-                        if !matches!(-                            relation.tags.get_str("type"),-                            Some("multipolygon" | "boundary")-                        ) {-                            return Ok(());-                        }-                        if !select.matches(|k| relation.tags.get_str(k)) {-                            return Ok(());-                        }-                        if let Some(class) = schema::classify(&relation.tags, false, layers) {-                            let members: Vec<_> = relation-                                .members-                                .iter()-                                .filter(|m| m.kind == MEMBER_WAY)-                                .map(|m| (m.id, m.role == b"inner"))-                                .collect();-                            // **The schema decides**, not the relation's `type` tag. Both an-                            // administrative border and a protected area are `type=boundary`, and-                            // one is a line while the other is a shape — which is exactly the-                            // distinction `Class::area` exists to make.-                            let area = class.area;-                            let name = schema::display_name(&relation.tags, class.layer);-                            // A multipolygon building (a footprint with a courtyard) carries S3DB-                            // attributes just as a building way does.-                            let building = if class.layer == LAYER_BUILDINGS {-                                Some(schema::buildings::attrs(&relation.tags))-                            } else {-                                None-                            };-                            // A country's code, kept so the region shape below can stamp its-                            // driving side and centre-line colour onto the tiles it covers.-                            let iso = schema::boundaries::country_code(&relation.tags)-                                .map(str::to_string);-                            // An administrative relation yields *two* features: the border, which-                            // is a line and is what the basemap draws, and the region's shape,-                            // which nothing draws and the region mask reads. They cannot be one-                            // feature — a clipped polygon grows tile-edge segments and the border-                            // layer strokes them into a grid. See `schema::boundaries`.-                            if let Some(shape) =-                                schema::boundaries::region_area(&relation.tags, false)-                            {-                                // The boundary points at its own label/centre node directly: record-                                // that node -> this relation so the place label it becomes can carry-                                // the id. `label` overwrites `admin_centre` (the label node is the-                                // one that renders; admin_centre is the capital, a different node).-                                for m in relation.members.iter() {-                                    if m.kind == MEMBER_NODE && m.role == b"admin_centre" {-                                        state.3.push((m.id, relation.id));-                                    }-                                }-                                for m in relation.members.iter() {-                                    if m.kind == MEMBER_NODE && m.role == b"label" {-                                        state.3.push((m.id, relation.id));-                                    }-                                }-                                state.1.push(Relation {-                                    class: shape,-                                    members: members.clone(),-                                    area: true,-                                    name: name.clone(),-                                    id: relation.id,-                                    building: None,-                                    population: None,-                                    iso: iso.clone(),-                                });-                            }-                            state.1.push(Relation {-                                class,-                                members,-                                area,-                                name,-                                id: relation.id,-                                building,-                                population: Some(schema::places::population_of(&relation.tags)),-                                iso: None,-                            });-                        }-                    }-                    Element::Node(_) => {}-                }-                Ok(())-            })?;-            sort_dedup_tail(&mut state.4, refs_from);-            Ok(kinds)-        },-        |(chunk_ways, chunk_relations, chunk_corridors, chunk_label_nodes, chunk_refs)| {-            // 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_block` refuses an id that does-            // not advance rather than letting an unsorted file reorder the archive silently.-            for block in &chunk_ways {-                ways.push_block(block)?;-            }-            // Fused ref collection: the refs were decoded on the worker, so the bitset takes-            // them now instead of a later pass re-reading the spill to find them again. A bitset-            // is order- and duplicate-blind, so the per-block sort/dedup changes no bit.-            for &node in &chunk_refs {-                needed.set_growable(node)?;-            }-            relations.extend(chunk_relations);-            corridors.extend(chunk_corridors);-            // `label` was pushed after `admin_centre`, so inserting in order lets the label win.-            for (node_id, rel_id) in chunk_label_nodes {-                region_label_nodes.insert(node_id, rel_id);-            }-            Ok(())-        },-    )?;-    let (counts, store) = ways.finish_either()?;-    stats.ways_classified = counts.ways;-    let (ways, way_refs, way_max_ref, ways_anon, way_blocks) =-        (counts.ways, counts.refs, counts.max_ref, store.map(std::sync::Arc::new), counts.blocks);-    stats.relations_classified = relations.len() as u64;--    // A numbered road changes class along its length, so deciding `min_zoom` per way chops-    // a corridor into stubs at the zooms where only its motorway parts survive. Promote-    // each connected same-`ref` run to the shallowest zoom any of its ways asks for, then-    // drop the segments: only the (way id, zoom) overrides are needed from here.-    timer.switch("corridors");-    let promoted = crate::corridor::promote(&corridors);-    stats.corridor_promotions = promoted.len() as u64;-    drop(corridors);--    Ok(Pass1Out {-        relations,-        promoted,-        blob_kinds,-        ways,-        way_refs,-        way_max_ref,-        ways_anon,-        way_blocks,-        region_label_nodes,-        needed,-    })-}-/// Sort and dedup `v[from..]` in place, leaving `v[..from]` untouched.-fn sort_dedup_tail(v: &mut Vec<i64>, from: usize) {-    v[from..].sort_unstable();-    let mut write = from;-    for read in from..v.len() {-        if write == from || v[read] != v[write - 1] {-            v[write] = v[read];-            write += 1;-        }-    }-    v.truncate(write);-}+include!("extract_part1_s1.rs");
scripts/maps/mamaps_build/src/extract_part1_s1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1_s1.rs b/scripts/maps/mamaps_build/src/extract_part1_s1.rsnew file mode 100644index 0000000000..3b081416c5--- /dev/null+++ b/scripts/maps/mamaps_build/src/extract_part1_s1.rs@@ -0,0 +1,292 @@+/// Pass 1 (ways + relations) plus the corridor promotion. Moved whole from+/// `extract` so part files can cut at fn boundaries; behavior identical.+///+/// `blob_kinds_in` is an optional pre-computed mask (the graph sidecar) that lets this pass skip+/// node blobs; `None` means scan the whole file. Either way the mask it returns is complete.+///+/// `spill_plan` is the budget gate's backend choice: the ways spill stages anonymously or through+/// the `.tmp` at `ways_path`. Decided by the caller from pass-0 counts, not here, because this+/// pass cannot know the graph size that shares its peak.+#[allow(clippy::too_many_arguments)]+fn run_pass1(+    input: &Path,+    blobs: &[pbf::BlobLoc],+    blob_kinds_in: Option<&[u8]>,+    select: &Select,+    layers: Layers,+    ways_path: &Path,+    spill_plan: osm_ingest::mem::SpillPlan,+    stats: &mut Stats,+    timer: &mut crate::timing::PhaseTimer,+) -> Result<Pass1Out> {+    // --- 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 mut ways = WaySink::create_planned(ways_path, spill_plan)?;+    let mut relations: Vec<Relation> = Vec::new();+    // The needed-node bitset, fused into this pass: every classified way sets+    // its refs here in the drain below, so pass 3 never re-reads the ways+    // spill to collect them. Grows on demand (the maximum is not known until+    // the last push); member refs join after the drain.+    let mut needed = NeededBits::new_growable();+    // `admin_centre`/`label` node member -> boundary relation id (raw), gathered as region shapes+    // are classified below. See [`Pass1Out::region_label_nodes`].+    let mut region_label_nodes: HashMap<i64, i64> = HashMap::new();+    // Road ways carrying a `ref`, for the corridor pass below. A small minority of ways,+    // and the only thing pass 1 keeps in memory besides the relations.+    let mut corridors: Vec<crate::corridor::Segment> = Vec::new();+    let blob_kinds = pbf::run_pass_sink(+        input,+        blobs,+        pbf::PassSpec {+            blob_kinds: blob_kinds_in,+            want: KIND_WAYS | KIND_RELATIONS,+            label: "Pass 1: ways and relations",+        },+        || {+            (+                Vec::<WayBlock>::new(),+                Vec::<Relation>::new(),+                Vec::<crate::corridor::Segment>::new(),+                Vec::<(i64, i64)>::new(),+                Vec::<i64>::new(),+            )+        },+        |state, block| {+            let mut kinds = 0u8;+            // This block's refs land past here; sorted and deduped below, so the drain sets+            // the needed bitset in ascending runs instead of chasing every ref.+            let refs_from = state.4.len();+            visit_block(block, KIND_WAYS | KIND_RELATIONS, &mut kinds, &mut |el| {+                match el {+                    Element::Way(way) => {+                        if !select.matches(|k| way.tags.get_str(k)) {+                            return Ok(());+                        }+                        if let Some(class) = schema::classify(&way.tags, true, layers) {+                            // A numbered road's `min_zoom` is decided per corridor, not per+                            // way, so that a route does not vanish where its class changes.+                            // Slip roads are left out: they carry the parent's `ref` and+                            // would be promoted into junction stubs at world zoom.+                            if class.layer == tilecodec::mamaps::dict::LAYER_ROADS+                                && class.flags & tilecodec::mamaps::body::FLAG_IS_LINK == 0+                                && way.refs.len() >= 2+                            {+                                if let Some(route) = crate::corridor::route_key(&way.tags) {+                                    state.2.push(crate::corridor::Segment {+                                        way_id: way.id,+                                        route,+                                        first_node: way.refs[0],+                                        last_node: way.refs[way.refs.len() - 1],+                                        min_zoom: class.min_zoom,+                                    });+                                }+                            }+                            let name = schema::display_name(&way.tags, class.layer);+                            // A road's carriageway lane count, per-lane turn masks and directional+                            // split, baked so the renderer can draw the lanes individually, place+                            // turn arrows and put the centre line where the traffic divides. Zero,+                            // empty and default for every other layer.+                            let is_road =+                                class.layer == tilecodec::mamaps::dict::LAYER_ROADS;+                            let lane_count = if is_road {+                                schema::roads::lane_count(&way.tags)+                            } else {+                                0+                            };+                            let (turn_fwd, turn_bwd) = if is_road {+                                schema::roads::turn_masks(&way.tags)+                            } else {+                                (Vec::new(), Vec::new())+                            };+                            let carriageway = if is_road {+                                schema::roads::carriageway(&way.tags)+                            } else {+                                Carriageway::default()+                            };+                            // A building's S3DB attributes, parsed once here beside its class.+                            // Zero-cost for the overwhelming majority of ways, which are not+                            // buildings.+                            let building = if class.layer == LAYER_BUILDINGS {+                                Some(schema::buildings::attrs(&way.tags))+                            } else {+                                None+                            };+                            // Encoded HERE, on the worker, into the chunk's ways-spill blocks: the+                            // drain only patches each block's first id and appends it. This was+                            // the serial drain's record-by-record encode, which held pass 1 to ~4+                            // of 192 cores on the planet (4m40s). Same bytes; see `WayBlock`.+                            if state.0.last().is_none_or(|b| b.len() >= WAY_BLOCK_WAYS) {+                                state.0.push(WayBlock::new());+                            }+                            let refs: &[i64] = way.refs;+                            state.0.last_mut().expect("pushed above").push(+                                way.id,+                                &class,+                                refs,+                                name.as_deref(),+                                lane_count,+                                &turn_fwd,+                                &turn_bwd,+                                carriageway,+                                building,+                            )?;+                            state.4.extend_from_slice(refs);+                        }+                    }+                    Element::Relation(relation) => {+                        // Two relation types carry a shape. Anything else — a site, a+                        // public_transport — does not.+                        if !matches!(+                            relation.tags.get_str("type"),+                            Some("multipolygon" | "boundary")+                        ) {+                            return Ok(());+                        }+                        if !select.matches(|k| relation.tags.get_str(k)) {+                            return Ok(());+                        }+                        if let Some(class) = schema::classify(&relation.tags, false, layers) {+                            let members: Vec<_> = relation+                                .members+                                .iter()+                                .filter(|m| m.kind == MEMBER_WAY)+                                .map(|m| (m.id, m.role == b"inner"))+                                .collect();+                            // **The schema decides**, not the relation's `type` tag. Both an+                            // administrative border and a protected area are `type=boundary`, and+                            // one is a line while the other is a shape — which is exactly the+                            // distinction `Class::area` exists to make.+                            let area = class.area;+                            let name = schema::display_name(&relation.tags, class.layer);+                            // A multipolygon building (a footprint with a courtyard) carries S3DB+                            // attributes just as a building way does.+                            let building = if class.layer == LAYER_BUILDINGS {+                                Some(schema::buildings::attrs(&relation.tags))+                            } else {+                                None+                            };+                            // A country's code, kept so the region shape below can stamp its+                            // driving side and centre-line colour onto the tiles it covers.+                            let iso = schema::boundaries::country_code(&relation.tags)+                                .map(str::to_string);+                            // An administrative relation yields *two* features: the border, which+                            // is a line and is what the basemap draws, and the region's shape,+                            // which nothing draws and the region mask reads. They cannot be one+                            // feature — a clipped polygon grows tile-edge segments and the border+                            // layer strokes them into a grid. See `schema::boundaries`.+                            if let Some(shape) =+                                schema::boundaries::region_area(&relation.tags, false)+                            {+                                // The boundary points at its own label/centre node directly: record+                                // that node -> this relation so the place label it becomes can carry+                                // the id. `label` overwrites `admin_centre` (the label node is the+                                // one that renders; admin_centre is the capital, a different node).+                                for m in relation.members.iter() {+                                    if m.kind == MEMBER_NODE && m.role == b"admin_centre" {+                                        state.3.push((m.id, relation.id));+                                    }+                                }+                                for m in relation.members.iter() {+                                    if m.kind == MEMBER_NODE && m.role == b"label" {+                                        state.3.push((m.id, relation.id));+                                    }+                                }+                                state.1.push(Relation {+                                    class: shape,+                                    members: members.clone(),+                                    area: true,+                                    name: name.clone(),+                                    id: relation.id,+                                    building: None,+                                    population: None,+                                    iso: iso.clone(),+                                });+                            }+                            state.1.push(Relation {+                                class,+                                members,+                                area,+                                name,+                                id: relation.id,+                                building,+                                population: Some(schema::places::population_of(&relation.tags)),+                                iso: None,+                            });+                        }+                    }+                    Element::Node(_) => {}+                }+                Ok(())+            })?;+            sort_dedup_tail(&mut state.4, refs_from);+            Ok(kinds)+        },+        |(chunk_ways, chunk_relations, chunk_corridors, chunk_label_nodes, chunk_refs)| {+            // 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_block` refuses an id that does+            // not advance rather than letting an unsorted file reorder the archive silently.+            for block in &chunk_ways {+                ways.push_block(block)?;+            }+            // Fused ref collection: the refs were decoded on the worker, so the bitset takes+            // them now instead of a later pass re-reading the spill to find them again. A bitset+            // is order- and duplicate-blind, so the per-block sort/dedup changes no bit.+            for &node in &chunk_refs {+                needed.set_growable(node)?;+            }+            relations.extend(chunk_relations);+            corridors.extend(chunk_corridors);+            // `label` was pushed after `admin_centre`, so inserting in order lets the label win.+            for (node_id, rel_id) in chunk_label_nodes {+                region_label_nodes.insert(node_id, rel_id);+            }+            Ok(())+        },+    )?;+    let (counts, store) = ways.finish_either()?;+    stats.ways_classified = counts.ways;+    let (ways, way_refs, way_max_ref, ways_anon, way_blocks) =+        (counts.ways, counts.refs, counts.max_ref, store.map(std::sync::Arc::new), counts.blocks);+    stats.relations_classified = relations.len() as u64;++    // A numbered road changes class along its length, so deciding `min_zoom` per way chops+    // a corridor into stubs at the zooms where only its motorway parts survive. Promote+    // each connected same-`ref` run to the shallowest zoom any of its ways asks for, then+    // drop the segments: only the (way id, zoom) overrides are needed from here.+    timer.switch("corridors");+    let promoted = crate::corridor::promote(&corridors);+    stats.corridor_promotions = promoted.len() as u64;+    drop(corridors);++    Ok(Pass1Out {+        relations,+        promoted,+        blob_kinds,+        ways,+        way_refs,+        way_max_ref,+        ways_anon,+        way_blocks,+        region_label_nodes,+        needed,+    })+}+/// Sort and dedup `v[from..]` in place, leaving `v[..from]` untouched.+fn sort_dedup_tail(v: &mut Vec<i64>, from: usize) {+    v[from..].sort_unstable();+    let mut write = from;+    for read in from..v.len() {+        if write == from || v[read] != v[write - 1] {+            v[write] = v[read];+            write += 1;+        }+    }+    v.truncate(write);+}
scripts/maps/mamaps_build/src/extract_part2.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part2.rs b/scripts/maps/mamaps_build/src/extract_part2.rsindex e6e4fd06e1..14bdcff117 100644--- a/scripts/maps/mamaps_build/src/extract_part2.rs+++ b/scripts/maps/mamaps_build/src/extract_part2.rs@@ -332,369 +332,4 @@ mod fringe_tests {     } } -/// Lane inheritance over the ways spill. Moved whole from `extract`.-///-/// The scan is batched: the expensive per-way work (coordinate lookup through the node-/// table — a rank-bitset search plus a mapped-file read per node) runs on the pool, while-/// the collector push stays serial in spill order. `table.line` is shared-read-only (the-/// materialise pass already calls it from `par_iter`), and the collector's output order-/// never reaches the archive — `finish` sorts every partition — so the bytes are identical.-/// What this buys: the scan is ~1.1 B sequential ways on a planet input, each paying ~10-/// node lookups; serially that is tens of minutes of mapped-file random reads.-///-/// `region` limits the join to the ways that can pair with a materialised way (see-/// [`fringe_touches`]): on a `--region` build over a larger input, the ways outside the-/// fringe can never share an endpoint node with a kept recipient, so resolving them would-/// be pure waste. `None` (world) disables the filter entirely.-fn inherit_lane_counts(-    spill_path: &Path,-    blocks: &WayBlocks,-    table: &NodeLocations,-    ways_classified: usize,-    region: Option<&osm_ingest::bbox::BBox>,-) -> Result<Vec<(i64, u8)>> {-    // --- lane inheritance --------------------------------------------------------------------    //-    // A junction stub OSM left untagged takes a lane count from the road it interrupts, instead of-    // the renderer's flat `oneway ? 1 : 2`. See [`crate::lanefill`] for the conditions and the-    // measurements behind each of them. It runs here rather than in pass 1 because the conditions-    // are geometric — a length and a turn angle — and coordinates are only resolved above.-    //-    // Block-parallel: every ways-spill block is decoded, filtered, resolved and turned into its-    // endpoint records on the pool ([`for_each_way_block`]); only the fixed-width record writes-    // stay serial, in block order -- which is spill order, so the partition files hold the same-    // bytes the one-cursor scan wrote. On the planet the one-cursor scan was 6 min at ~4 cores.-    let fringe = region.map(expanded_fringe);-    let mut collector = crate::lanefill::Collector::create(spill_path)?;-    let mut bar = Progress::new(-        "Lane inheritance: scan".to_string(),-        ways_classified,-        "way(s)",-        true,-    );-    for_each_way_block(-        blocks,-        |mut reader| -> Result<Vec<crate::lanefill::Prepared>> {-            let mut refs: Vec<i64> = Vec::new();-            let mut indices: Vec<usize> = Vec::new();-            let mut out = Vec::new();-            while let Some((id, class, name, lane_count, _, _, _, _)) = reader.next(&mut refs)? {-                // Roads, and not slip roads. A ramp leaves a junction carrying its parent's name on-                // very nearly its parent's heading, so it would inherit the mainline's width onto a-                // single-lane ramp; `corridor` leaves links out of a corridor for the same reason.-                if class.layer != tilecodec::mamaps::dict::LAYER_ROADS-                    || class.flags & tilecodec::mamaps::body::FLAG_IS_LINK != 0-                {-                    continue;-                }-                let Some(name) = name else { continue };-                let oneway = class.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0;-                if fringe.is_none() {-                    // World build: no fringe to test, so read only the coordinates the join needs-                    // (`lanefill::prepare_lazy`). A way with an unresolved node is one `prepare`-                    // drops (its line would be shorter than its refs).-                    if table.indices_if_complete(&refs, &mut indices) {-                        if let Some(prepared) = crate::lanefill::prepare_lazy(-                            id,-                            &name,-                            lane_count,-                            oneway,-                            &refs,-                            |i| table.coord_at(indices[i]),-                        ) {-                            out.push(prepared);-                        }-                    }-                    continue;-                }-                let line = table.line(&refs);-                // A region build only joins the fringe: a recipient is at most 50 m long, so-                // a donor sharing an endpoint node with a kept recipient always touches the-                // expanded box (see `expanded_fringe`). Anything else can pair only with-                // ways materialise drops — work with no reader.-                if !fringe_touches(fringe.as_ref(), &line) {-                    continue;-                }-                if let Some(prepared) = crate::lanefill::prepare(&crate::lanefill::Segment {-                    id,-                    name: &name,-                    lanes: lane_count,-                    oneway,-                    nodes: &refs,-                    line: &line,-                }) {-                    out.push(prepared);-                }-            }-            Ok(out)-        },-        |ways, prepared| {-            for p in &prepared {-                collector.push_prepared(p)?;-            }-            bar.tick_n(ways as usize, "way(s)");-            Ok(())-        },-    )?;-    bar.finish("way(s)");-    collector.finish()-}--/// Ways-spill blocks decoded per pool hand-off, per thread. Each block is at most-/// [`WAY_BLOCK_WAYS`] ways, so a group is ~1.5 M ways on 192 threads: enough to keep every core-/// busy with even load, and a bounded amount of finished work (endpoint records, spill records)-/// held while the previous group drains.-const BLOCKS_PER_THREAD: usize = 2;--/// Run `work` over every block of the ways spill on the pool and hand each block's result to-/// `drain` **in block order**, which is spill order.-///-/// Pipelined: while `drain` consumes group `k` on one thread, the pool computes group `k + 1`.-/// `work` gets a fresh cursor over its block; `drain` gets the block's way count (for progress)-/// and its result. The first error in block order wins, exactly as a one-cursor loop would-/// report it; work already computed past it is discarded.-fn for_each_way_block<T, W, D>(blocks: &WayBlocks, work: W, mut drain: D) -> Result<()>-where-    T: Send,-    W: Fn(WayReader) -> Result<T> + Sync,-    D: FnMut(u64, T) -> Result<()> + Send,-{-    let locs = blocks.locs();-    let group = (par::threads() * BLOCKS_PER_THREAD).max(1);-    pipeline_ordered(-        locs.len(),-        group,-        |i| blocks.reader(i).and_then(&work),-        |i, result| drain(locs[i].ways(), result?),-    )-}--/// Run `work(i)` for every `i in 0..len` on the pool, `group` items per hand-off, and hand each-/// result to `drain` **in index order**. While `drain` consumes one group on one thread, the pool-/// computes the next, so the serial drain overlaps the parallel work instead of alternating with-/// it -- and a slow item delays only its own group's drain, not a barrier every few thousand-/// items. The first error `drain` returns stops the loop; work already computed past it is-/// discarded.-pub(crate) fn pipeline_ordered<T, W, D>(len: usize, group: usize, work: W, mut drain: D) -> Result<()>-where-    T: Send,-    W: Fn(usize) -> T + Sync,-    D: FnMut(usize, T) -> Result<()> + Send,-{-    let group = group.max(1);-    par::install(|| {-        let mut start = 0usize;-        let mut pending: Option<(usize, Vec<T>)> = None;-        loop {-            let end = (start + group).min(len);-            let (drained, next) = rayon::join(-                || -> Result<()> {-                    if let Some((first, results)) = pending.take() {-                        for (k, result) in results.into_iter().enumerate() {-                            drain(first + k, result)?;-                        }-                    }-                    Ok(())-                },-                || {-                    if start < end {-                        Some((start..end).into_par_iter().map(&work).collect::<Vec<T>>())-                    } else {-                        None-                    }-                },-            );-            drained?;-            match next {-                Some(results) => pending = Some((start, results)),-                None => return Ok(()),-            }-            start = end;-        }-    })-}--/// One materialised way, decided on the pool: the serial drain only appends.-///-/// `Failed` (no geometry) counts `geometry_failed`; `Dropped` (region-filtered)-/// counts nothing — exactly the two non-pushed paths the inline drain had.-/// `Kept` carries the finished spill record ([`PreRecord`]), so the drain neither walks vertices-/// nor encodes.-enum BuiltWay {-    Failed,-    Dropped,-    Kept(PreRecord),-}--/// Resolve one way's fate: geometry, region keep/drop, and its spill record.-///-/// Pure over shared tables (`table`, `region`): safe across the pool. The record is built with-/// the same choice of shape the serial drain made -- a building carries its S3DB attributes, a-/// road with lane data carries those, everything else (a plain road included) goes the plain,-/// named way -- so `Sink::push_pre` stages exactly what `push_building` / `push_road` /-/// `push_named` would have.-#[allow(clippy::too_many_arguments)]-fn build_way(-    class: &Class,-    geometry: Option<Geometry>,-    region: Option<&osm_ingest::bbox::BBox>,-    name: Option<&str>,-    id: u64,-    lane_count: u8,-    turn_fwd: &[u16],-    turn_bwd: &[u16],-    carriageway: Carriageway,-    building: Option<BuildingAttrs>,-) -> Result<BuiltWay> {-    let Some(geometry) = geometry else {-        return Ok(BuiltWay::Failed);-    };-    // Region filter: roads, pois and buildings outside the bbox are dropped.-    // The geometry is resolved by now, so this is a direct touches-box test-    // on the line the way produced (a centroided point for labels).-    if is_region_filtered(class.layer) && !geometry_touches(&geometry, region) {-        return Ok(BuiltWay::Dropped);-    }-    let encoded = crate::store::EncodedGeom::live(&geometry)?;-    let record = if let Some(b) = building {-        PreRecord::building(class, &encoded, name, b)?-    } else if lane_count > 0 || !turn_fwd.is_empty() || !turn_bwd.is_empty() || !carriageway.is_empty() {-        PreRecord::road(class, &encoded, name, lane_count, turn_fwd, turn_bwd, carriageway)?-    } else {-        PreRecord::named(class, &encoded, name, id)?-    };-    Ok(BuiltWay::Kept(record))-}--/// Materialise classified ways off disk, in id order. Moved whole from `extract`.-///-/// `region` filters the built layers (`roads`, `poi`, `buildings`): a way in-/// one of those layers whose resolved line touches no bbox point is dropped.-/// Every other layer is always kept. Kept whole, never clipped — the tiler-/// clips per tile later.-///-/// Consumes `blocks`: it is the spill's last reader, and the handle must be closed before the-/// file is removed (Windows refuses to delete an open file).-#[allow(clippy::too_many_arguments)]-fn materialise_ways(-    ways_path: &Path,-    blocks: WayBlocks,-    promoted: &[(i64, u8)],-    inherited_lanes: &[(i64, u8)],-    table: &NodeLocations,-    region: Option<&osm_ingest::bbox::BBox>,-    sink: &mut Sink,-    stats: &mut Stats,-) -> Result<()> {-    // 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,-    );-    // Block-parallel end to end: decoding the spill, the coordinate lookups (`table.line`, an id-    // search plus a random read of a mapped file per node), ring closing, the region test and the-    // spill record itself all run on the pool, per block; the sink then appends the finished-    // records **in block order** -- spill order -- which is what keeps the archive byte-identical:-    // the spill's feature order is the archive's. Measured before this on California: decode-    // (`fill`) 5.5 s and record encode + DEFLATE (`push`) 19.0 s of 26.6 s were serial.-    let mut drain_wall = std::time::Duration::ZERO;-    let wall = std::time::Instant::now();-    let (mut failed, mut kept) = (0u64, 0u64);-    for_each_way_block(-        &blocks,-        |mut reader| -> Result<(RecordRun, u64)> {-            let mut refs: Vec<i64> = Vec::new();-            // The block's kept records go straight into one run (`Sink::push_run`); the first-            // failure in the block ends it with that error, which the in-order drain reports as-            // the first in spill order -- as the record-by-record drain did.-            let mut run = RecordRun::default();-            let mut block_failed = 0u64;-            while let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) =-                reader.next(&mut refs)?-            {-                let mut class = class;-                // The corridor's zoom, where it is shallower than this way's own. Corridors-                // are built from numbered roads alone, so a non-road way can never have an-                // entry — searching for one is ~17 wasted compares per boundary, building-                // and waterway on a region build.-                if class.layer == tilecodec::mamaps::dict::LAYER_ROADS {-                    if let Ok(at) = promoted.binary_search_by_key(&id, |(id, _)| *id) {-                        class.min_zoom = promoted[at].1;-                    }-                }-                // A neighbour's lane count, where OSM tagged none on this way. Only ever consulted-                // for a way that has none of its own, so a tag is never overridden.-                let lane_count = if lane_count == 0 {-                    inherited_lanes-                        .binary_search_by_key(&id, |(id, _)| *id)-                        .map_or(0, |at| inherited_lanes[at].1)-                } else {-                    lane_count-                };-                // Only a label way carries its id onward. A road or a building is merged with its-                // neighbours by `coalesce`, which leaves the survivor's id arbitrary, and the id-                // table exists for `poi` and `places` alone.-                let id = if is_label(class.layer) {-                    tagged_id(id, ELEMENT_WAY)-                } else {-                    tilecodec::mamaps::body::ID_NONE-                };-                let line = table.line(&refs);-                // A label layer's ways are centroided to points: a town mapped as an area-                // is still one label, not a loop. Everything else keeps its geometry.-                let geometry = if is_label(class.layer) {-                    centroid(&line).map(|point| Geometry::Points(vec![point]))-                } else {-                    way_geometry(&line, class.area)-                };-                match build_way(-                    &class,-                    geometry,-                    region,-                    name.as_deref(),-                    id,-                    lane_count,-                    &turn_fwd,-                    &turn_bwd,-                    carriageway,-                    building,-                )? {-                    BuiltWay::Failed => block_failed += 1,-                    BuiltWay::Dropped => {}-                    BuiltWay::Kept(record) => run.add(record),-                }-            }-            Ok((run, block_failed))-        },-        |ways, built| {-            let t = std::time::Instant::now();-            let (run, block_failed) = built;-            failed += block_failed;-            kept += run.len() as u64;-            sink.push_run(run)?;-            bar.tick_n(ways as usize, "way(s)");-            drain_wall += t.elapsed();-            Ok(())-        },-    )?;-    stats.geometry_failed += failed;-    stats.features += kept;-    // TEMP-PROFILE: the serial drain's share of the phase wall. Removed with the other probes.-    eprintln!(-        "  [profile] materialise-ways wall={:.1}s drain={:.1}s spill={:.2}GB",-        wall.elapsed().as_secs_f64(),-        drain_wall.as_secs_f64(),-        sink.staged_bytes() as f64 / 1e9-    );-    bar.finish("way(s)");-    // Nothing reads the ways spill after this: the relations below reach their members through-    // `members`, which is why that table is kept at all. The file backend's `.tmp` is removed-    // (after its handle closes); the anon backend's segments unmap with the last `Arc`.-    drop(blocks);-    let _ = std::fs::remove_file(ways_path);--    Ok(())-}+include!("extract_part2_s1.rs");
scripts/maps/mamaps_build/src/extract_part2_s1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part2_s1.rs b/scripts/maps/mamaps_build/src/extract_part2_s1.rsnew file mode 100644index 0000000000..196f0e1a51--- /dev/null+++ b/scripts/maps/mamaps_build/src/extract_part2_s1.rs@@ -0,0 +1,366 @@+/// Lane inheritance over the ways spill. Moved whole from `extract`.+///+/// The scan is batched: the expensive per-way work (coordinate lookup through the node+/// table — a rank-bitset search plus a mapped-file read per node) runs on the pool, while+/// the collector push stays serial in spill order. `table.line` is shared-read-only (the+/// materialise pass already calls it from `par_iter`), and the collector's output order+/// never reaches the archive — `finish` sorts every partition — so the bytes are identical.+/// What this buys: the scan is ~1.1 B sequential ways on a planet input, each paying ~10+/// node lookups; serially that is tens of minutes of mapped-file random reads.+///+/// `region` limits the join to the ways that can pair with a materialised way (see+/// [`fringe_touches`]): on a `--region` build over a larger input, the ways outside the+/// fringe can never share an endpoint node with a kept recipient, so resolving them would+/// be pure waste. `None` (world) disables the filter entirely.+fn inherit_lane_counts(+    spill_path: &Path,+    blocks: &WayBlocks,+    table: &NodeLocations,+    ways_classified: usize,+    region: Option<&osm_ingest::bbox::BBox>,+) -> Result<Vec<(i64, u8)>> {+    // --- lane inheritance -------------------------------------------------------------------+    //+    // A junction stub OSM left untagged takes a lane count from the road it interrupts, instead of+    // the renderer's flat `oneway ? 1 : 2`. See [`crate::lanefill`] for the conditions and the+    // measurements behind each of them. It runs here rather than in pass 1 because the conditions+    // are geometric — a length and a turn angle — and coordinates are only resolved above.+    //+    // Block-parallel: every ways-spill block is decoded, filtered, resolved and turned into its+    // endpoint records on the pool ([`for_each_way_block`]); only the fixed-width record writes+    // stay serial, in block order -- which is spill order, so the partition files hold the same+    // bytes the one-cursor scan wrote. On the planet the one-cursor scan was 6 min at ~4 cores.+    let fringe = region.map(expanded_fringe);+    let mut collector = crate::lanefill::Collector::create(spill_path)?;+    let mut bar = Progress::new(+        "Lane inheritance: scan".to_string(),+        ways_classified,+        "way(s)",+        true,+    );+    for_each_way_block(+        blocks,+        |mut reader| -> Result<Vec<crate::lanefill::Prepared>> {+            let mut refs: Vec<i64> = Vec::new();+            let mut indices: Vec<usize> = Vec::new();+            let mut out = Vec::new();+            while let Some((id, class, name, lane_count, _, _, _, _)) = reader.next(&mut refs)? {+                // Roads, and not slip roads. A ramp leaves a junction carrying its parent's name on+                // very nearly its parent's heading, so it would inherit the mainline's width onto a+                // single-lane ramp; `corridor` leaves links out of a corridor for the same reason.+                if class.layer != tilecodec::mamaps::dict::LAYER_ROADS+                    || class.flags & tilecodec::mamaps::body::FLAG_IS_LINK != 0+                {+                    continue;+                }+                let Some(name) = name else { continue };+                let oneway = class.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0;+                if fringe.is_none() {+                    // World build: no fringe to test, so read only the coordinates the join needs+                    // (`lanefill::prepare_lazy`). A way with an unresolved node is one `prepare`+                    // drops (its line would be shorter than its refs).+                    if table.indices_if_complete(&refs, &mut indices) {+                        if let Some(prepared) = crate::lanefill::prepare_lazy(+                            id,+                            &name,+                            lane_count,+                            oneway,+                            &refs,+                            |i| table.coord_at(indices[i]),+                        ) {+                            out.push(prepared);+                        }+                    }+                    continue;+                }+                let line = table.line(&refs);+                // A region build only joins the fringe: a recipient is at most 50 m long, so+                // a donor sharing an endpoint node with a kept recipient always touches the+                // expanded box (see `expanded_fringe`). Anything else can pair only with+                // ways materialise drops — work with no reader.+                if !fringe_touches(fringe.as_ref(), &line) {+                    continue;+                }+                if let Some(prepared) = crate::lanefill::prepare(&crate::lanefill::Segment {+                    id,+                    name: &name,+                    lanes: lane_count,+                    oneway,+                    nodes: &refs,+                    line: &line,+                }) {+                    out.push(prepared);+                }+            }+            Ok(out)+        },+        |ways, prepared| {+            for p in &prepared {+                collector.push_prepared(p)?;+            }+            bar.tick_n(ways as usize, "way(s)");+            Ok(())+        },+    )?;+    bar.finish("way(s)");+    collector.finish()+}++/// Ways-spill blocks decoded per pool hand-off, per thread. Each block is at most+/// [`WAY_BLOCK_WAYS`] ways, so a group is ~1.5 M ways on 192 threads: enough to keep every core+/// busy with even load, and a bounded amount of finished work (endpoint records, spill records)+/// held while the previous group drains.+const BLOCKS_PER_THREAD: usize = 2;++/// Run `work` over every block of the ways spill on the pool and hand each block's result to+/// `drain` **in block order**, which is spill order.+///+/// Pipelined: while `drain` consumes group `k` on one thread, the pool computes group `k + 1`.+/// `work` gets a fresh cursor over its block; `drain` gets the block's way count (for progress)+/// and its result. The first error in block order wins, exactly as a one-cursor loop would+/// report it; work already computed past it is discarded.+fn for_each_way_block<T, W, D>(blocks: &WayBlocks, work: W, mut drain: D) -> Result<()>+where+    T: Send,+    W: Fn(WayReader) -> Result<T> + Sync,+    D: FnMut(u64, T) -> Result<()> + Send,+{+    let locs = blocks.locs();+    let group = (par::threads() * BLOCKS_PER_THREAD).max(1);+    pipeline_ordered(+        locs.len(),+        group,+        |i| blocks.reader(i).and_then(&work),+        |i, result| drain(locs[i].ways(), result?),+    )+}++/// Run `work(i)` for every `i in 0..len` on the pool, `group` items per hand-off, and hand each+/// result to `drain` **in index order**. While `drain` consumes one group on one thread, the pool+/// computes the next, so the serial drain overlaps the parallel work instead of alternating with+/// it -- and a slow item delays only its own group's drain, not a barrier every few thousand+/// items. The first error `drain` returns stops the loop; work already computed past it is+/// discarded.+pub(crate) fn pipeline_ordered<T, W, D>(len: usize, group: usize, work: W, mut drain: D) -> Result<()>+where+    T: Send,+    W: Fn(usize) -> T + Sync,+    D: FnMut(usize, T) -> Result<()> + Send,+{+    let group = group.max(1);+    par::install(|| {+        let mut start = 0usize;+        let mut pending: Option<(usize, Vec<T>)> = None;+        loop {+            let end = (start + group).min(len);+            let (drained, next) = rayon::join(+                || -> Result<()> {+                    if let Some((first, results)) = pending.take() {+                        for (k, result) in results.into_iter().enumerate() {+                            drain(first + k, result)?;+                        }+                    }+                    Ok(())+                },+                || {+                    if start < end {+                        Some((start..end).into_par_iter().map(&work).collect::<Vec<T>>())+                    } else {+                        None+                    }+                },+            );+            drained?;+            match next {+                Some(results) => pending = Some((start, results)),+                None => return Ok(()),+            }+            start = end;+        }+    })+}++/// One materialised way, decided on the pool: the serial drain only appends.+///+/// `Failed` (no geometry) counts `geometry_failed`; `Dropped` (region-filtered)+/// counts nothing — exactly the two non-pushed paths the inline drain had.+/// `Kept` carries the finished spill record ([`PreRecord`]), so the drain neither walks vertices+/// nor encodes.+enum BuiltWay {+    Failed,+    Dropped,+    Kept(PreRecord),+}++/// Resolve one way's fate: geometry, region keep/drop, and its spill record.+///+/// Pure over shared tables (`table`, `region`): safe across the pool. The record is built with+/// the same choice of shape the serial drain made -- a building carries its S3DB attributes, a+/// road with lane data carries those, everything else (a plain road included) goes the plain,+/// named way -- so `Sink::push_pre` stages exactly what `push_building` / `push_road` /+/// `push_named` would have.+#[allow(clippy::too_many_arguments)]+fn build_way(+    class: &Class,+    geometry: Option<Geometry>,+    region: Option<&osm_ingest::bbox::BBox>,+    name: Option<&str>,+    id: u64,+    lane_count: u8,+    turn_fwd: &[u16],+    turn_bwd: &[u16],+    carriageway: Carriageway,+    building: Option<BuildingAttrs>,+) -> Result<BuiltWay> {+    let Some(geometry) = geometry else {+        return Ok(BuiltWay::Failed);+    };+    // Region filter: roads, pois and buildings outside the bbox are dropped.+    // The geometry is resolved by now, so this is a direct touches-box test+    // on the line the way produced (a centroided point for labels).+    if is_region_filtered(class.layer) && !geometry_touches(&geometry, region) {+        return Ok(BuiltWay::Dropped);+    }+    let encoded = crate::store::EncodedGeom::live(&geometry)?;+    let record = if let Some(b) = building {+        PreRecord::building(class, &encoded, name, b)?+    } else if lane_count > 0 || !turn_fwd.is_empty() || !turn_bwd.is_empty() || !carriageway.is_empty() {+        PreRecord::road(class, &encoded, name, lane_count, turn_fwd, turn_bwd, carriageway)?+    } else {+        PreRecord::named(class, &encoded, name, id)?+    };+    Ok(BuiltWay::Kept(record))+}++/// Materialise classified ways off disk, in id order. Moved whole from `extract`.+///+/// `region` filters the built layers (`roads`, `poi`, `buildings`): a way in+/// one of those layers whose resolved line touches no bbox point is dropped.+/// Every other layer is always kept. Kept whole, never clipped — the tiler+/// clips per tile later.+///+/// Consumes `blocks`: it is the spill's last reader, and the handle must be closed before the+/// file is removed (Windows refuses to delete an open file).+#[allow(clippy::too_many_arguments)]+fn materialise_ways(+    ways_path: &Path,+    blocks: WayBlocks,+    promoted: &[(i64, u8)],+    inherited_lanes: &[(i64, u8)],+    table: &NodeLocations,+    region: Option<&osm_ingest::bbox::BBox>,+    sink: &mut Sink,+    stats: &mut Stats,+) -> Result<()> {+    // 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,+    );+    // Block-parallel end to end: decoding the spill, the coordinate lookups (`table.line`, an id+    // search plus a random read of a mapped file per node), ring closing, the region test and the+    // spill record itself all run on the pool, per block; the sink then appends the finished+    // records **in block order** -- spill order -- which is what keeps the archive byte-identical:+    // the spill's feature order is the archive's. Measured before this on California: decode+    // (`fill`) 5.5 s and record encode + DEFLATE (`push`) 19.0 s of 26.6 s were serial.+    let mut drain_wall = std::time::Duration::ZERO;+    let wall = std::time::Instant::now();+    let (mut failed, mut kept) = (0u64, 0u64);+    for_each_way_block(+        &blocks,+        |mut reader| -> Result<(RecordRun, u64)> {+            let mut refs: Vec<i64> = Vec::new();+            // The block's kept records go straight into one run (`Sink::push_run`); the first+            // failure in the block ends it with that error, which the in-order drain reports as+            // the first in spill order -- as the record-by-record drain did.+            let mut run = RecordRun::default();+            let mut block_failed = 0u64;+            while let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) =+                reader.next(&mut refs)?+            {+                let mut class = class;+                // The corridor's zoom, where it is shallower than this way's own. Corridors+                // are built from numbered roads alone, so a non-road way can never have an+                // entry — searching for one is ~17 wasted compares per boundary, building+                // and waterway on a region build.+                if class.layer == tilecodec::mamaps::dict::LAYER_ROADS {+                    if let Ok(at) = promoted.binary_search_by_key(&id, |(id, _)| *id) {+                        class.min_zoom = promoted[at].1;+                    }+                }+                // A neighbour's lane count, where OSM tagged none on this way. Only ever consulted+                // for a way that has none of its own, so a tag is never overridden.+                let lane_count = if lane_count == 0 {+                    inherited_lanes+                        .binary_search_by_key(&id, |(id, _)| *id)+                        .map_or(0, |at| inherited_lanes[at].1)+                } else {+                    lane_count+                };+                // Only a label way carries its id onward. A road or a building is merged with its+                // neighbours by `coalesce`, which leaves the survivor's id arbitrary, and the id+                // table exists for `poi` and `places` alone.+                let id = if is_label(class.layer) {+                    tagged_id(id, ELEMENT_WAY)+                } else {+                    tilecodec::mamaps::body::ID_NONE+                };+                let line = table.line(&refs);+                // A label layer's ways are centroided to points: a town mapped as an area+                // is still one label, not a loop. Everything else keeps its geometry.+                let geometry = if is_label(class.layer) {+                    centroid(&line).map(|point| Geometry::Points(vec![point]))+                } else {+                    way_geometry(&line, class.area)+                };+                match build_way(+                    &class,+                    geometry,+                    region,+                    name.as_deref(),+                    id,+                    lane_count,+                    &turn_fwd,+                    &turn_bwd,+                    carriageway,+                    building,+                )? {+                    BuiltWay::Failed => block_failed += 1,+                    BuiltWay::Dropped => {}+                    BuiltWay::Kept(record) => run.add(record),+                }+            }+            Ok((run, block_failed))+        },+        |ways, built| {+            let t = std::time::Instant::now();+            let (run, block_failed) = built;+            failed += block_failed;+            kept += run.len() as u64;+            sink.push_run(run)?;+            bar.tick_n(ways as usize, "way(s)");+            drain_wall += t.elapsed();+            Ok(())+        },+    )?;+    stats.geometry_failed += failed;+    stats.features += kept;+    // TEMP-PROFILE: the serial drain's share of the phase wall. Removed with the other probes.+    eprintln!(+        "  [profile] materialise-ways wall={:.1}s drain={:.1}s spill={:.2}GB",+        wall.elapsed().as_secs_f64(),+        drain_wall.as_secs_f64(),+        sink.staged_bytes() as f64 / 1e9+    );+    bar.finish("way(s)");+    // Nothing reads the ways spill after this: the relations below reach their members through+    // `members`, which is why that table is kept at all. The file backend's `.tmp` is removed+    // (after its handle closes); the anon backend's segments unmap with the last `Arc`.+    drop(blocks);+    let _ = std::fs::remove_file(ways_path);++    Ok(())+}
scripts/maps/mamaps_build/src/lanefill.rs
diff --git a/scripts/maps/mamaps_build/src/lanefill.rs b/scripts/maps/mamaps_build/src/lanefill.rsindex 06e43044a4..e188b624fe 100644--- a/scripts/maps/mamaps_build/src/lanefill.rs+++ b/scripts/maps/mamaps_build/src/lanefill.rs@@ -351,305 +351,4 @@ pub struct Collector {     unlinked: bool, } -impl Collector {-    /// Open the partition files. `stem` is a scratch path; each partition appends to it.-    pub fn create(stem: &Path) -> Result<Collector> {-        let mut files = Vec::with_capacity(PARTITIONS);-        let mut paths = Vec::with_capacity(PARTITIONS);-        for i in 0..PARTITIONS {-            let path = stem.with_extension(format!("lanefill{i:03}.tmp"));-            // Read and write on one handle, so `finish` reads the partition back through it and-            // the name can be unlinked straight away: a build killed mid-scan leaves nothing.-            let file = std::fs::OpenOptions::new()-                .read(true)-                .write(true)-                .create(true)-                .truncate(true)-                .open(&path)-                .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;-            // Small buffers: there are `PARTITIONS` of them held open at once, and each takes a-            // steady trickle rather than a burst.-            files.push(BufWriter::with_capacity(1 << 14, file));-            paths.push(path);-        }-        let mut unlinked = true;-        for path in &paths {-            unlinked &= osm_ingest::mem::unlink_open_scratch(path);-        }-        Ok(Collector { files, paths, unlinked })-    }--    /// Offer one way to the join. Ways that cannot take part are dropped here.-    #[cfg_attr(not(test), allow(dead_code))]-    pub fn push(&mut self, segment: &Segment) -> Result<()> {-        match prepare(segment) {-            Some(prepared) => self.push_prepared(&prepared),-            None => Ok(()),-        }-    }--    /// Write the two endpoint records [`prepare`] built, in the order `push` always wrote them-    /// (first end, then last end). Split from `push` so the geometry -- length, bearings, name-    /// hash -- runs on the pool and only these two fixed-width writes stay serial.-    pub fn push_prepared(&mut self, prepared: &Prepared) -> Result<()> {-        for record in prepared.0 {-            record.write(&mut self.files[partition_of(record.node)])?;-        }-        Ok(())-    }--    /// Resolve every partition and return `(way id, inherited lane count)` for the ways that-    /// actually change, ascending by way id so the materialise pass can binary-search it.-    ///-    /// Ways whose inherited count equals the default they would have had anyway are left out, the-    /// same way [`crate::corridor::promote`] leaves out ways its corridor does not move.-    pub fn finish(mut self) -> Result<Vec<(i64, u8)>> {-        let mut files: Vec<File> = Vec::with_capacity(self.files.len());-        for file in std::mem::take(&mut self.files) {-            files.push(-                file.into_inner()-                    .map_err(|e| Error(format!("cannot flush a lanefill partition: {e}")))?,-            );-        }--        // `(way, end, donor lanes, one-way)`. The only state that outlives a partition, because a-        // way's two endpoints hash to two different files and the "donor at both ends" condition-        // cannot be decided until both have been seen.-        //-        // The 256 partitions are independent — every record for a node lives in exactly the one-        // partition `partition_of` sends it to — so each is read, sorted and paired on its own-        // thread and the per-partition pairs concatenated. `found` is globally sorted below, so the-        // 

Diff truncated.