Modern Apps git

← Modern-Apps.git

maps: parallelise mamaps_build's serial stage-A and tiler stages (#perf)

Commit
239147dcecda51067453a49bda0e50190929dfdb
Author
Vayun Mathur <[email protected]>
When
2026-11-10 21:07 UTC (25 days ago)
Parents
b54e047
What: every stage of mamaps_build that the live Nov 10 planet build
(Phase 4, 192 vCPU Genoa) showed running far below the box was moved
onto the pool or pipelined, without changing a byte of the archive.
Measured with a read-only sampler (/proc stat + log) on the live run:
pass 1 4m44s @4.6 cores, lane inheritance 6m12s @8, materialise ways
32m48s @8, materialise relations 4m @8.5, graph load 1m40s @1.3,
junctions 4m41s @28, region fallback 18 min @1.2, tiler map phases
z0-z14 ~35 min @3-11 (reader-bound), merge+encode ~12 min @6-14.

Root causes and fixes:
- Pass 1: the ways spill was encoded record by record in
  run_pass_sink's drain, which runs under the lock every worker also
  takes to deposit and claim. Workers now encode their chunk into
  WayBlocks (same record bytes, first id varint left open); the drain
  only patches that varint, appends, and sets the needed-node bitset
  from per-block sorted/deduped refs. The stream is byte-identical
  (unit test) and gains a block index (WayBlockLoc).
- Lane inheritance / materialise ways: both read the spill through
  one cursor. They now decode blocks across the pool
  (for_each_way_block -> pipeline_ordered: group k+1 computes while
  group k drains in order). lanefill::prepare builds endpoint records
  on the pool; PreRecord builds whole spill records (props, header,
  geometry) on the pool so the drain only appends.
- Feature spill writer (tile_build NormalizedWriter): frames are
  queued and DEFLATEd in batches of 4096 on the pool, staged in order
  with the chunk index recorded at write time (same offsets), as one
  multi-MB write per batch. The File-plan spill is created NOCOW
  (already-DEFLATEd frames, so compress-force zstd was pure waste).
- Relations and junctions: pipeline_ordered with PreRecords instead of
  4096/32Ki barriers plus serial encode; conventions.add stays serial
  and ordered.
- Graph v7 ZBLK inflate (junction load and the preflight check):
  blocks inflate in parallel, appended in order.
- Region fallback: Store::par_scan decodes the whole store across the
  pool (file order kept) instead of one cursor over ~1.35 B features.
- DEM load: HashMap of ~76 M Vec<u16> replaced by a sorted id column
  plus one contiguous sample column, both built on the pool; repeated
  ids keep the last record exactly as HashMap::insert did (test).
- Tiler map reader: the old reader decoded through one 4-lane
  ZoomReader behind three partitions it could not consume, and moved
  every feature through one thread. Now threads/3 (4..=64) dedicated
  decode threads claim spill chunks, a per-slot reorder ring hands
  blocks back in order, and the sequencer only sums vertex counts and
  moves whole blocks (chunks become lists of blocks; same cuts, same
  indices).
- Giant features: subdivide_par descends huge lines/polygons on the
  pool, returning tiles in exactly subdivide's emit order.
- Merge: ranges drained strictly in order with a 32-tile queue each,
  so only one range merged at a time. Later ranges now run ahead into
  queues under a shared 2 GiB estimated-bytes allowance (the current
  range keeps the 32-tile bound and is never budget-blocked, so the
  drain cannot deadlock); the coordinator drains in bulk and only
  notifies parked threads.
- Encode/append: append of batch k overlaps merge+encode of k+1, and
  up to 16 merge batches share one encode pass; each batch keeps its
  own cut and its own prune_barren_subtree, so pruning is unchanged.
- tilecodec finish: level-9 leaf compression ran on one thread (~4.3
  GB of leaf entries on a planet); now on Options::threads threads,
  frames laid down in leaf order.

Tried and dropped (measured slower): worker-side Pass 3 coordinate
stores into the mmap (page-fault contention, 1.3 s -> 4.6-5.6 s on
California); parallel Douglas-Peucker annotate; more merge range
workers (16/32: no change).

Verification (California, frozen baseline-bin road_graph graph,
baseline transit_shapes routes, read-only coastline.shp + world.mdem,
--region california, MAPS_ANON_SPILL=1):
- archive sha256 94cb7eef4c760742...a9a3 for baseline-bin at
  MAPS_THREADS=192 and 8, and for this build at 192, 8 and 1.
- Phase TIMING wall 163.8 s -> ~52-55 s (192 threads, shared box):
  pass1 4.4->2.3, lane-inherit 3.9->0.2, materialise-ways 26.6->2.5,
  junctions 5.1->1.1, region-fallback 14.7->0.5, dem-load 12-24->0.5,
  map 47.8->25, merge+encode+append+finish 32->~11.
- cargo test --release: mamaps_build 286, tile_build 197, osm_ingest
  300 passed. tilecodec --features write: 181 passed, 4 failing tests
  are pre-existing and in untouched code (version-byte-7 and blocked
  writer assertions).

Diff

library/tilecodec/src/main/rust/src/mamaps/write/options.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs b/library/tilecodec/src/main/rust/src/mamaps/write/options.rsindex 2cdae7852c..4db2e3e919 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/options.rs@@ -37,6 +37,10 @@ pub struct Options {     pub min_lat_e7: i32,     pub max_lon_e7: i32,     pub max_lat_e7: i32,+    /// Threads `finish` may use to compress leaves; `0` means the machine's available+    /// parallelism. Speed only: every leaf's frame is a pure function of the leaf, so the+    /// archive is the same at any count.+    pub threads: usize, }  impl Default for Options {@@ -54,6 +58,7 @@ impl Default for Options {             min_lat_e7: -850_511_287,             max_lon_e7: 1_800_000_000,             max_lat_e7: 850_511_287,+            threads: 0,         }     } }
library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rsindex 33a9a243fd..e7b2101712 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs@@ -68,15 +68,44 @@ impl StreamWriter {         // grow its leaf is stored raw instead (`stored_len` zero), so this never costs a byte;         // with `compress_leaves` off every leaf stores raw and the file is the legacy layout         // bit for bit.-        let mut leaf_bytes = Vec::new();-        for (entry, leaf) in root.iter_mut().zip(leaves.iter()) {+        //+        // The frames are built on `options.threads` threads (a group of leaves at a time, each+        // thread a contiguous run) and laid down in leaf order: same frames, same order, same+        // bytes. Serially this was level-9 DEFLATE over every leaf on one thread -- ~4.3 GB of+        // entries on a planet, minutes of a 192-core box at one core.+        let compress_leaves = self.options.compress_leaves;+        let stored_for = |leaf: &Vec<index::LeafEntry>| -> Vec<u8> {             let raw = index::serialize_leaf(leaf);-            let stored = if self.options.compress_leaves {+            if compress_leaves {                 let frame = index::compress_leaf(&raw);                 if frame.len() < raw.len() { frame } else { raw }             } else {                 raw-            };+            }+        };+        let threads = match self.options.threads {+            0 => std::thread::available_parallelism().map_or(1, |n| n.get()),+            n => n,+        };+        const LEAF_GROUP: usize = 2048;+        let mut stored_leaves: Vec<Vec<u8>> = Vec::with_capacity(leaves.len());+        for group in leaves.chunks(LEAF_GROUP) {+            if threads <= 1 || group.len() <= 1 {+                stored_leaves.extend(group.iter().map(&stored_for));+                continue;+            }+            let per = group.len().div_ceil(threads.min(group.len()));+            let parts: Vec<Vec<Vec<u8>>> = std::thread::scope(|scope| {+                let handles: Vec<_> = group+                    .chunks(per)+                    .map(|run| scope.spawn(|| run.iter().map(&stored_for).collect::<Vec<_>>()))+                    .collect();+                handles.into_iter().map(|h| h.join().expect("a leaf compression thread")).collect()+            });+            stored_leaves.extend(parts.into_iter().flatten());+        }+        let mut leaf_bytes = Vec::new();+        for ((entry, leaf), stored) in root.iter_mut().zip(leaves.iter()).zip(stored_leaves) {             entry.leaf_offset = leaf_bytes.len() as u64;             entry.stored_len = if stored.len() == leaf.len() * index::LEAF_ENTRY_LEN {                 0
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 3cfadf7570..8d03aed112 100644--- a/scripts/maps/mamaps_build/src/dem.rs+++ b/scripts/maps/mamaps_build/src/dem.rs@@ -16,7 +16,6 @@ //! level yields `None` the same way, whatever the zoom: it carries no relief, and a flat sea-level //! grid would make the renderer draw earth-coloured terrain over open water (see [`Dem::heightmap_for`]). -use std::collections::HashMap; use std::f64::consts::PI; use std::path::Path; @@ -88,7 +87,60 @@ pub struct Dem {     /// The grid side length, so every grid is `dim * dim` samples. Shared by every tile.     dim: u16,     /// `tile_id(out_zoom, x, y)` -> the tile's `dim * dim` samples, row-major from its top-left.-    grids: HashMap<u64, Vec<u16>>,+    grids: Grids,+}++/// The dataset's grids as one sorted id column and one contiguous sample column.+///+/// Was a `HashMap<u64, Vec<u16>>`: on the 13 GB world dataset that is ~76 M allocations and a+/// single-threaded fold of ~76 M inserts on every build regardless of region (the bulk of a+/// 12-24 s `dem-load` at ~5 cores), plus the map's own slack. Here both columns are built on the+/// pool and a lookup is a binary search. Same answers as the map for every id, including a file+/// that repeats one: the map kept the **last** insert, and so does [`Grids::build`].+struct Grids {+    /// Tile ids, strictly ascending.+    ids: Vec<u64>,+    /// `ids.len() * cells` samples; tile `i`'s grid is `samples[i * cells..][..cells]`.+    samples: Vec<u16>,+    cells: usize,+}++impl Grids {+    /// From `(id, file index)` for every record and a way to fill a grid from a record index.+    /// Ids are sorted (already ascending in a `dem_ingest` file, which is checked rather than+    /// assumed) and a repeated id keeps its last record, as `HashMap::insert` in file order did.+    fn build<F>(mut keys: Vec<(u64, usize)>, cells: usize, fill: F) -> Grids+    where+        F: Fn(usize, &mut [u16]) + Sync,+    {+        let ascending = keys.par_windows(2).all(|w| w[0].0 < w[1].0);+        if !ascending {+            // (id, index) is a total order with unique keys, so the sort is deterministic; the+            // last of each id's run is its last record in the file.+            keys.par_sort_unstable();+            let mut kept: Vec<(u64, usize)> = Vec::with_capacity(keys.len());+            for k in keys {+                match kept.last_mut() {+                    Some(last) if last.0 == k.0 => *last = k,+                    _ => kept.push(k),+                }+            }+            keys = kept;+        }+        let mut samples = vec![0u16; keys.len() * cells];+        if cells > 0 {+            samples+                .par_chunks_mut(cells)+                .zip(keys.par_iter())+                .for_each(|(grid, &(_, index))| fill(index, grid));+        }+        Grids { ids: keys.into_iter().map(|(id, _)| id).collect(), samples, cells }+    }++    fn get(&self, id: &u64) -> Option<&[u16]> {+        let i = self.ids.binary_search(id).ok()?;+        Some(&self.samples[i * self.cells..(i + 1) * self.cells])+    } }  impl Dem {@@ -138,41 +190,26 @@ impl Dem {         if bytes.len() < 12 + count.saturating_mul(stride) {             return err("a .mdem dataset ends before its tile count");         }-        // Decoded tile indices, not tiles: the byte slices borrow `bytes`, so the-        // pool maps indices to owned pairs and the fold inserts in file order.-        // Chunks of 1024 tiles balance scheduling against per-task overhead-        // (~170 KB of samples per chunk at dim 9 — L2-resident working set).-        const PARSE_CHUNK_TILES: usize = 1024;-        let chunks = count.div_ceil(PARSE_CHUNK_TILES);-        let mut pairs: Vec<Vec<(u64, Vec<u16>)>> = Vec::with_capacity(chunks);-        par::install(|| {-            (0..chunks)+        // 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(|chunk| {-                    let lo = chunk * PARSE_CHUNK_TILES;-                    let hi = (lo + PARSE_CHUNK_TILES).min(count);-                    let mut out = Vec::with_capacity(hi - lo);-                    for i in lo..hi {-                        let at = 12 + i * stride;-                        let id =-                            u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"));-                        let mut samples = Vec::with_capacity(cells);-                        for c in 0..cells {-                            let o = at + 8 + c * 2;-                            samples.push(u16::from_le_bytes([bytes[o], bytes[o + 1]]));-                        }-                        out.push((id, samples));-                    }-                    out+                .map(|i| {+                    let at = 12 + i * stride;+                    (u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")), i)                 })-                .collect_into_vec(&mut pairs);+                .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]]);+                }+            })         });-        let mut grids = HashMap::with_capacity(count);-        for chunk in pairs.drain(..) {-            for (id, samples) in chunk {-                grids.insert(id, samples);-            }-        }         Ok(Dem { out_zoom, dim, grids })     } @@ -201,7 +238,7 @@ impl Dem {             if relief(samples) <= FLAT_RELIEF_M && self.dim >= FLAT_DIM {                 return Some(Heightmap { dim: FLAT_DIM, samples: coarsen(samples, self.dim as usize) });             }-            return Some(Heightmap { dim: self.dim, samples: samples.clone() });+            return Some(Heightmap { dim: self.dim, samples: samples.to_vec() });         }         self.resample(z, x, y)     }@@ -247,7 +284,10 @@ impl Dem {     /// 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 {-        Dem { out_zoom, dim, grids: grids.into_iter().collect() }+        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,@@ -306,6 +346,30 @@ fn tile_y_to_lat(y: f64, z: u8) -> f64 { mod tests {     use super::*; +    /// 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();
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex c544eba736..772d029297 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -67,7 +67,10 @@ use tile_build::progress::Progress; use rayon::prelude::*;  use crate::schema::{self, Class, Layers};-use crate::store::{Sink, Store, WayCounts, WayReader, WaySink};+use crate::store::{+    PreRecord, Sink, Store, WayBlock, WayBlockLoc, WayBlocks, WayCounts, WayReader, WaySink,+    WAY_BLOCK_WAYS,+}; use tilecodec::mamaps::body::{BuildingAttrs, Carriageway}; use tilecodec::mamaps::dict::LAYER_BUILDINGS; @@ -159,27 +162,6 @@ pub struct Stats {     pub rings: RingStats, } -/// A classified way, held only from the blob it was decoded in until its chunk reaches [`WaySink`].-struct Way {-    class: Class,-    refs: Vec<i64>,-    /// The display label for `places`/`poi` ways, `None` for every other layer.-    name: Option<String>,-    /// A road's carriageway lane count, zero for every other layer and for a road with no `lanes`-    /// tag. See [`crate::schema::roads::lane_count`].-    lane_count: u8,-    /// A road's per-lane turn masks `(forward, backward)`; empty otherwise. See-    /// [`crate::schema::roads::turn_masks`].-    turn_fwd: Vec<u16>,-    turn_bwd: Vec<u16>,-    /// A road's directional lane split and solid dividers; default otherwise. See-    /// [`crate::schema::roads::carriageway`].-    carriageway: Carriageway,-    /// A building's S3DB attributes, `None` for every non-building. See-    /// [`crate::schema::buildings::attrs`].-    building: Option<BuildingAttrs>,-}- /// A classified relation, held between passes. struct Relation {     class: Class,
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 b20fcbe997..7bf119aac3 100644--- a/scripts/maps/mamaps_build/src/extract_fallback.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -404,42 +404,49 @@ pub fn extend_region_links_with(         kind: Band,         kind_name: String,     }+    enum Kept {+        Boundary(Boundary),+        Place(PlacePoint),+    }+    // The scan decodes the whole store across the pool (`Store::par_scan`, 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.+    let kept = store.par_scan(|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();-    {-        let mut reader = store.reader()?;-        while let Some(feature) = reader.next()? {-            if feature.id == ID_NONE {-                continue;-            }-            if feature.class.layer == LAYER_BOUNDARIES && feature.class.area {-                let Geometry::Polygons(polygons) = feature.geometry else {-                    continue;-                };-                if polygons.is_empty() {-                    continue;-                }-                boundaries.push(Boundary::new(feature.id, feature.class.kind_detail, polygons));-            } else if feature.class.layer == LAYER_PLACES {-                let Geometry::Points(points) = feature.geometry else {-                    continue;-                };-                let Some(&point) = points.first() else {-                    continue;-                };-                let Some(kind_name) = place_kind_name(feature.class.kind) else {-                    continue;-                };-                let Some(band) = band_for_place_kind(kind_name) else {-                    continue;-                };-                places.push(PlacePoint {-                    id: feature.id,-                    point,-                    kind: band,-                    kind_name: kind_name.to_string(),-                });-            }+    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);
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 d8c4ded8e8..28f7746698 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -82,6 +82,7 @@ pub fn extract(         way_refs,         way_max_ref,         ways_anon,+        way_blocks,         region_label_nodes,         mut needed,     } = pass1;@@ -113,10 +114,10 @@ pub fn extract(     // so the next large allocation cannot sit beside a dead one.     drop(blob_kinds);     timer.switch("lane-inherit");+    let way_blocks = WayBlocks::open(&ways_path, &ways_anon, way_blocks)?;     let inherited_lanes = inherit_lane_counts(         spill_path,-        &ways_path,-        &ways_anon,+        &way_blocks,         &table,         stats.ways_classified as usize,         region.as_ref(),@@ -131,7 +132,7 @@ pub fn extract(     timer.switch("materialise-ways");     materialise_ways(         &ways_path,-        &ways_anon,+        way_blocks,         &promoted,         &inherited_lanes,         &table,@@ -349,6 +350,8 @@ struct Pass1Out {     /// The sealed ways spill, shared by refcount with every later reader; `None` on the file     /// plan, where readers open `ways_path` instead.     ways_anon: Option<std::sync::Arc<tile_build::anon::AnonStore>>,+    /// The block index over the ways spill (either backend), for the parallel readers.+    way_blocks: Vec<WayBlockLoc>,     /// `admin_centre`/`label` node member -> its boundary relation id, both raw OSM ids, for every     /// relation that carries a region shape. The authoritative half of the place->boundary link:     /// OSM points a boundary relation at its own label node directly, so no geometry test is needed.@@ -412,14 +415,18 @@ fn run_pass1(         "Pass 1: ways and relations",         || {             (-                Vec::<(i64, Way)>::new(),+                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) => {@@ -475,19 +482,26 @@ fn run_pass1(                             } else {                                 None                             };-                            state.0.push((+                            // 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,-                                Way {-                                    class,-                                    refs: way.refs.to_vec(),-                                    name,-                                    lane_count,-                                    turn_fwd,-                                    turn_bwd,-                                    carriageway,-                                    building,-                                },-                            ));+                                &class,+                                refs,+                                name.as_deref(),+                                lane_count,+                                &turn_fwd,+                                &turn_bwd,+                                carriageway,+                                building,+                            )?;+                            state.4.extend_from_slice(refs);                         }                     }                     Element::Relation(relation) => {@@ -575,30 +589,21 @@ fn run_pass1(                 }                 Ok(())             })?;+            sort_dedup_tail(&mut state.4, refs_from);             Ok(kinds)         },-        |(chunk_ways, chunk_relations, chunk_corridors, chunk_label_nodes)| {+        |(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` refuses an id that does not-            // advance rather than letting an unsorted file reorder the archive silently.-            for (id, way) in chunk_ways {-                // Fused ref collection: the refs are decoded and in hand here,-                // so the bitset takes them now instead of a later pass-                // re-reading the spill to find them again.-                for &node in &way.refs {-                    needed.set_growable(node)?;-                }-                ways.push(-                    id,-                    &way.class,-                    &way.refs,-                    way.name.as_deref(),-                    way.lane_count,-                    &way.turn_fwd,-                    &way.turn_bwd,-                    way.carriageway,-                    way.building,-                )?;+            // 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);@@ -611,8 +616,8 @@ fn run_pass1(     )?;     let (counts, store) = ways.finish_either()?;     stats.ways_classified = counts.ways;-    let (ways, way_refs, way_max_ref, ways_anon) =-        (counts.ways, counts.refs, counts.max_ref, store.map(std::sync::Arc::new));+    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@@ -632,7 +637,20 @@ fn run_pass1(         way_refs,         way_max_ref,         ways_anon,+        way_blocks,         region_label_nodes,         needed,     })-}\ No newline at end of file+}+/// 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 6d32283723..5b619d4e37 100644--- a/scripts/maps/mamaps_build/src/extract_part2.rs+++ b/scripts/maps/mamaps_build/src/extract_part2.rs@@ -234,30 +234,6 @@ fn build_resolved_table(     Ok(table) } -/// Open the ways spill for sequential reading, from whichever backend the budget gate chose:-/// the shared anonymous store when present, else the file at `ways_path`. One helper so the four-/// readers (two ref collectors, lanefill scan, materialise) share one backend.-fn open_ways_reader(-    ways_path: &Path,-    ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,-) -> Result<WayReader> {-    WayReader::open_either(ways_path, ways_anon)-}--/// One named, non-link road way held for parallel coordinate resolve.-///-/// Owns its refs and name: the spill cursor cannot be re-read, so a batch row carries-/// everything the serial push needs after the parallel phase hands the geometry back.-struct LaneRow {-    id: i64,-    /// The class flags: the link test already passed, but the one-way bit rides here for-    /// the segment the push builds.-    flags: u8,-    name: String,-    lanes: u8,-    refs: Vec<i64>,-}- /// The region bbox expanded for the lane join, in degrees. /// /// A recipient is at most 50 m long (`lanefill::MAX_STUB_M`, enforced again in `push`),@@ -370,8 +346,7 @@ mod fringe_tests { /// be pure waste. `None` (world) disables the filter entirely. fn inherit_lane_counts(     spill_path: &Path,-    ways_path: &Path,-    ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,+    blocks: &WayBlocks,     table: &NodeLocations,     ways_classified: usize,     region: Option<&osm_ingest::bbox::BBox>,@@ -382,35 +357,25 @@ fn inherit_lane_counts(     // 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 inherited_lanes = {-        let mut collector = crate::lanefill::Collector::create(spill_path)?;-        let mut reader = open_ways_reader(ways_path, &ways_anon)?;-        let mut refs: Vec<i64> = Vec::new();-        let mut bar = Progress::new(-            "Lane inheritance: scan".to_string(),-            ways_classified,-            "way(s)",-            true,-        );-        // One batch of spill rows at a time: 64 Ki ways at ~10 nodes each is a few tens of-        // MB of geometry in flight, the same budget the materialise pass uses.-        const LANE_BATCH: usize = 64 * 1024;-        let mut batch: Vec<LaneRow> = Vec::with_capacity(LANE_BATCH);-        let mut lines: Vec<Vec<(f64, f64)>> = Vec::with_capacity(LANE_BATCH);-        let mut exhausted = false;-        loop {-            batch.clear();-            // Serial fill: the spill is a sequential varint stream — one cursor, no seeking.-            // The bar ticks here, per way read, so it still spans the whole spill exactly as-            // before — the batching below must not move the tick or the count drifts.-            while batch.len() < LANE_BATCH {-                let Some((id, class, name, lane_count, _, _, _, _)) = reader.next(&mut refs)?-                else {-                    exhausted = true;-                    break;-                };-                bar.tick("way(s)");+    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 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.@@ -420,30 +385,7 @@ fn inherit_lane_counts(                     continue;                 }                 let Some(name) = name else { continue };-                batch.push(LaneRow {-                    id,-                    flags: class.flags,-                    name,-                    lanes: lane_count,-                    refs: std::mem::take(&mut refs),-                });-            }-            if batch.is_empty() {-                debug_assert!(exhausted, "an empty batch means the spill is done");-                break;-            }-            // Parallel resolve: the dominant cost, shared-read-only.-            lines.clear();-            par::install(|| {-                batch-                    .par_iter()-                    .map(|row| table.line(&row.refs))-                    .collect_into_vec(&mut lines)-            });-            // Serial push, in spill order: the collector's file order never reaches the-            // archive (`finish` sorts), but keeping it ordered keeps the temp bytes — and-            // any future debugging of them — deterministic.-            for (row, line) in batch.iter().zip(lines.drain(..)) {+                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@@ -451,50 +393,137 @@ fn inherit_lane_counts(                 if !fringe_touches(fringe.as_ref(), &line) {                     continue;                 }-                let oneway =-                    row.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0;-                collector.push(&crate::lanefill::Segment {-                    id: row.id,-                    name: &row.name,-                    lanes: row.lanes,+                let oneway = class.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0;+                if let Some(prepared) = crate::lanefill::prepare(&crate::lanefill::Segment {+                    id,+                    name: &name,+                    lanes: lane_count,                     oneway,-                    nodes: &row.refs,+                    nodes: &refs,                     line: &line,-                })?;+                }) {+                    out.push(prepared);+                }             }-            if exhausted {-                break;+            Ok(out)+        },+        |ways, prepared| {+            for p in &prepared {+                collector.push_prepared(p)?;             }-        }-        bar.finish("way(s)");-        collector.finish()?-    };+            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; -    Ok(inherited_lanes)+/// 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 spill record's geometry bytes plus the facts the spill-/// derives, so the drain does no vertex walk.+/// `Kept` carries the finished spill record ([`PreRecord`]), so the drain neither walks vertices+/// nor encodes. enum BuiltWay {     Failed,     Dropped,-    Kept(crate::store::EncodedGeom),+    Kept(PreRecord), } -/// Resolve one batch item's fate: geometry, region keep/drop, spill encoding.+/// Resolve one way's fate: geometry, region keep/drop, and its spill record. ///-/// Pure over shared tables (`table`, `region`): safe across the pool. The-/// region test runs here rather than in the drain — it walks every vertex-/// (`geometry_touches`), and the drain must not. Order-independent: one slot-/// per batch item, drained positionally.+/// 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);@@ -505,7 +534,15 @@ fn build_way(     if is_region_filtered(class.layer) && !geometry_touches(&geometry, region) {         return Ok(BuiltWay::Dropped);     }-    Ok(BuiltWay::Kept(crate::store::EncodedGeom::live(&geometry)?))+    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`.@@ -514,9 +551,13 @@ fn build_way( /// 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,-    ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,+    blocks: WayBlocks,     promoted: &[(i64, u8)],     inherited_lanes: &[(i64, u8)],     table: &NodeLocations,@@ -524,8 +565,6 @@ fn materialise_ways(     sink: &mut Sink,     stats: &mut Stats, ) -> Result<()> {-    let mut reader = open_ways_reader(ways_path, ways_anon)?;-    let mut refs: Vec<i64> = Vec::new();     // 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(@@ -534,169 +573,107 @@ fn materialise_ways(         "way(s)",         true,     );-    // Batched, because the expensive part of a way is embarrassingly parallel and the cheap part-    // cannot be. `table.line` is a coordinate lookup per node -- an id search plus a random read of a-    // mapped file -- and `way_geometry` closes and winds rings; neither touches shared mutable state,-    // so a batch of them goes as wide as the pool. The sink then takes the results **in order**,-    // which is what keeps the archive byte-identical: the spill's feature order is the archive's.-    //-    // 64 Ki ways at ~10 nodes each is a few tens of MB of geometry in flight, against a build that-    // peaks near 7 GB.-    const MATERIALISE_BATCH: usize = 64 * 1024;-    #[allow(clippy::type_complexity)]-    let mut batch: Vec<(-        Class,-        Option<String>,-        Vec<i64>,-        u64,-        u8,-        Vec<u16>,-        Vec<u16>,-        Carriageway,-        Option<BuildingAttrs>,-    )> = Vec::with_capacity(MATERIALISE_BATCH);-    let mut built: Vec<Result<BuiltWay>> = Vec::with_capacity(MATERIALISE_BATCH);-    // TEMP-PROFILE: split the batch loop into fill / resolve / drain walls.-    // Removed once the split is measured (naonly run).-    let mut t_fill = std::time::Duration::ZERO;-    let mut t_resolve = std::time::Duration::ZERO;-    let mut t_push = std::time::Duration::ZERO;-    let mut t_rest = std::time::Duration::ZERO;-    let mut t0 = std::time::Instant::now();-    loop {-        let more = reader.next(&mut refs)?;-        // Moved out of `more` by value below, so named ways cost no `String` clone and-        // turn-mask vectors move rather than copy: over ~1 B ways the allocator traffic-        // of cloning is minutes, and the batch owns every field anyway.-        let done = more.is_none();-        if let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) =-            more-        {-            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;+    // 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<Vec<Result<BuiltWay>>> {+            let mut refs: Vec<i64> = Vec::new();+            let mut out = Vec::new();+            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)+                };+                out.push(build_way(+                    &class,+                    geometry,+                    region,+                    name.as_deref(),+                    id,+                    lane_count,+                    &turn_fwd,+                    &turn_bwd,+                    carriageway,+                    building,+                ));             }-            // 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-            };-            batch.push((-                class,-                name,-                std::mem::take(&mut refs),-                id,-                lane_count,-                turn_fwd,-                turn_bwd,-                carriageway,-                building,-            ));-        }-        // Flushed when full, and once more at the end with whatever is left.-        if batch.len() >= MATERIALISE_BATCH || (done && !batch.is_empty()) {-            t_fill += t0.elapsed();-            let t1 = std::time::Instant::now();-            built.clear();-            par::install(|| {-                batch-                    .par_iter()-                    .map(|(class, _, refs, _, _, _, _, _, _)| {-                        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)-                        };-                        build_way(class, geometry, region)-                    })-                    .collect_into_vec(&mut built);-            });-            t_resolve += t1.elapsed();-            let t2 = std::time::Instant::now();-            let push_before = t_push;-            for (-                (class, name, _, id, lane_count, turn_fwd, turn_bwd, carriageway, building),-                built,-            ) in batch.iter().zip(built.drain(..))-            {+            Ok(out)+        },+        |ways, built| {+            let t = std::time::Instant::now();+            for built in built {                 // `?` in spill order: the first encode failure in feature order,                 // exactly as inline encoding would report it.-                let tp0 = std::time::Instant::now();                 match built? {-                    BuiltWay::Failed => stats.geometry_failed += 1,+                    BuiltWay::Failed => failed += 1,                     BuiltWay::Dropped => {}-                    BuiltWay::Kept(encoded) => {-                        // A building carries its S3DB attributes; a road with lane data carries-                        // those; everything else — and a plain road — goes the plain, named way.-                        if let Some(b) = building {-                            sink.push_building(class, &encoded, name.as_deref(), *b)?;-                        } else if *lane_count > 0-                            || !turn_fwd.is_empty()-                            || !turn_bwd.is_empty()-                            || !carriageway.is_empty()-                        {-                            sink.push_road(-                                class,-                                &encoded,-                                name.as_deref(),-                                *lane_count,-                                turn_fwd,-                                turn_bwd,-                                *carriageway,-                            )?;-                        } else {-                            sink.push_named(class, &encoded, name.as_deref(), *id)?;-                        }-                        stats.features += 1;+                    BuiltWay::Kept(record) => {+                        sink.push_pre(&record)?;+                        kept += 1;                     }                 }-                t_push += tp0.elapsed();-                bar.tick("way(s)");             }-            batch.clear();-            // Drain wall minus the sink pushes: match + stats + tick + drops.-            t_rest += t2.elapsed() - (t_push - push_before);-            t0 = std::time::Instant::now();-        }-        if done {-            break;-        }-    }+            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 fill={:.1}s resolve={:.1}s push={:.1}s rest={:.1}s spill={:.2}GB",-        t_fill.as_secs_f64(),-        t_resolve.as_secs_f64(),-        t_push.as_secs_f64(),-        t_rest.as_secs_f64(),+        "  [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;-    // the anon backend's segments unmap with the last `Arc`.-    drop(reader);-    let _ = std::fs::remove_file(&ways_path);+    // `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/extract_part3.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part3.rs b/scripts/maps/mamaps_build/src/extract_part3.rsindex 29d2c501ea..ef301379f7 100644--- a/scripts/maps/mamaps_build/src/extract_part3.rs+++ b/scripts/maps/mamaps_build/src/extract_part3.rs@@ -1,43 +1,37 @@-/// One relation's geometry, built off the shared tables with nothing mutable touched, so a batch of-/// them fans out across the pool exactly as [`materialise_ways`] does. The sink and the conventions-/// grid are fed from these **in relation order** in the serial drain, which is what keeps the-/// archive byte-identical: the drain order is the spill order is the archive's.-///-/// Geometry arrives spill-encoded ([`EncodedGeom`](crate::store::EncodedGeom)): the pool walks-/// vertices, the drain appends bytes. The region keep/drop decision is precomputed alongside-/// (pure per-relation work over the resolved shape), so the drain's only vertex touch is-/// `conventions.add`'s grid stamp — which must stay serial and ordered anyway (precedence).-enum BuiltRelation {-    /// A label relation centroided to a point, `None` when it had no locatable members.-    Label(Option<(f64, f64)>),-    /// A border relation's member lines, spill-encoded, already filtered to those with two or-    /// more points. Borders are never region-filtered (region shapes are always kept), so no-    /// keep flag rides along. `empty` is the pre-encode shape test (`lines.is_empty()`): an-    /// encoded empty still carries count bytes, so the drain cannot tell it from content by-    /// looking at the bytes — and the old drain counted it `geometry_failed` rather than-    /// pushing an empty record.-    Border { encoded: Result<crate::store::EncodedGeom>, empty: bool },-    /// An area relation's stitched rings and the ring stats that stitching produced. The stats are-    /// per-relation here and summed into [`Stats::rings`] serially — they are four additive counts,-    /// so the sum is the same in any order. `encoded` is the assembled polygons, spill-ready;-    /// `polygons` travels alongside for `conventions.add`, which needs rings rather than bytes.-    /// `empty` is the pre-encode shape test (`polygons.is_empty()`), for the same reason as-    /// [`BuiltRelation::Border`]'s.-    Area {-        polygons: Vec<rings::Polygon>,-        encoded: Result<crate::store::EncodedGeom>,-        empty: bool,-        keep: bool,-        rings: RingStats,-    },+/// What one relation contributes, decided on the pool. See [`BuiltRelation`].+enum RelationOutcome {+    /// Region-filtered (a `poi` label outside the bbox, a building outside it): counts nothing.+    Skip,+    /// No geometry: counts `geometry_failed`.+    Failed,+    /// A finished spill record: counts a feature.+    Kept(PreRecord), } -/// Build one relation's geometry. Reads only the shared `members` map and the resolved `table`,-/// both immutable, so it is safe to call across the pool. See [`BuiltRelation`].+/// One relation's geometry and spill record, built off the shared tables with nothing mutable+/// touched, so relations fan out across the pool exactly as [`materialise_ways`]' blocks do. The+/// sink and the conventions grid are fed from these **in relation order** by the serial drain,+/// which is what keeps the archive byte-identical: the drain order is the spill order is the+/// archive's. ///-/// `region` joins the pool inputs (shared ref): the buildings-area keep/drop test walks every-/// vertex (`polygons_touch`), and the drain must not. Labels keep their O(1) `point_touches`-/// in the drain — no walk to move.+/// The record itself ([`PreRecord`]) is built here too -- props, header, geometry bytes -- so the+/// drain only appends; it used to encode every relation (and DEFLATE its frames) on the one+/// serial thread, between pool batches of 4096 that each waited on their slowest relation. On+/// the planet that phase ran 4 minutes at ~8 cores.+struct BuiltRelation {+    /// An area relation's ring stats, summed into [`Stats::rings`] whether or not the stitch+    /// produced anything -- four additive counts, so the order cannot show.+    rings: Option<RingStats>,+    outcome: Result<RelationOutcome>,+    /// A kept country shape's assembled rings, for `conventions.add` -- which has precedence rules+    /// (an interior claim outranks a border one) and so stays serial and in relation order.+    conventions: Option<Vec<rings::Polygon>>,+}++/// Build one relation's geometry and record. Reads only the shared `members` map and the+/// resolved `table`, both immutable, so it is safe to call across the pool. The decisions --+/// label point or member lines or stitched rings, region keep/drop, record shape -- are the ones+/// the serial drain used to make, in the same order. fn build_relation(     relation: &Relation,     members: &MemberWays,@@ -53,7 +47,27 @@ fn build_relation(             .filter_map(|(id, _)| members.get(*id))             .flat_map(|refs| table.line(refs))             .collect();-        return BuiltRelation::Label(centroid(&line));+        let outcome = match centroid(&line) {+            None => Ok(RelationOutcome::Failed),+            // `poi` labels are region-filtered; `places` always kept. O(1) point test.+            Some(point)+                if relation.class.layer == tilecodec::mamaps::dict::LAYER_POI+                    && !point_touches(&point, region) =>+            {+                Ok(RelationOutcome::Skip)+            }+            Some(point) => crate::store::EncodedGeom::live(&Geometry::Points(vec![point]))+                .and_then(|encoded| {+                    PreRecord::named(+                        &relation.class,+                        &encoded,+                        relation.name.as_deref(),+                        tagged_id(relation.id, ELEMENT_RELATION),+                    )+                })+                .map(RelationOutcome::Kept),+        };+        return BuiltRelation { rings: None, outcome, conventions: None };     }     // A boundary relation's members are the border. Each is emitted as its own line rather than     // stitched: the renderer strokes them, and a gap between two member ways is invisible in a@@ -66,12 +80,18 @@ fn build_relation(             .map(|refs| table.line(refs))             .filter(|line| line.len() >= 2)             .collect();-        // Captured, not `?`: encode counts cannot overflow on real ways, but a-        // pool panic would abort the build where a channelled error fails it in-        // spill order. The drain reports the first failure in relation order.+        // `empty` is the pre-encode shape test: an encoded empty still carries count bytes, and+        // an empty border counts `geometry_failed` rather than pushing an empty record.         let empty = lines.is_empty();-        let encoded = crate::store::EncodedGeom::live(&Geometry::Lines(lines));-        return BuiltRelation::Border { encoded, empty };+        let outcome = crate::store::EncodedGeom::live(&Geometry::Lines(lines)).and_then(|encoded| {+            if empty {+                Ok(RelationOutcome::Failed)+            } else {+                PreRecord::named(&relation.class, &encoded, None, tilecodec::mamaps::body::ID_NONE)+                    .map(RelationOutcome::Kept)+            }+        });+        return BuiltRelation { rings: None, outcome, conventions: None };     }     let member_ways: Vec<MemberWay> = relation         .members@@ -80,27 +100,52 @@ fn build_relation(             Some(MemberWay { refs: members.get(*id)?.clone(), outer: !inner })         })         .collect();-    let mut rings = RingStats::default();-    let polygons = rings::assemble(&member_ways, |id| locate(table, id), &mut rings);+    let mut ring_stats = RingStats::default();+    let polygons = rings::assemble(&member_ways, |id| locate(table, id), &mut ring_stats);     // Buildings are region-filtered; every other area layer is always kept.-    // Decided here, on the assembled rings, so the drain never walks vertices.     let keep = relation.class.layer != tilecodec::mamaps::dict::LAYER_BUILDINGS         || polygons_touch(&polygons, region);+    let empty = polygons.is_empty();     let geometry = Geometry::Polygons(polygons);-    let empty = match &geometry {-        Geometry::Polygons(polygons) => polygons.is_empty(),-        // Unreachable: built as Polygons two lines up. The match (rather than-        // reading `polygons` before the move) keeps the emptiness test next to-        // the value the drain decides on.-        _ => unreachable!("just built as Polygons"),-    };     let encoded = crate::store::EncodedGeom::live(&geometry);     let Geometry::Polygons(polygons) = geometry else {         unreachable!("just built as Polygons");     };-    BuiltRelation::Area { polygons, encoded, empty, keep, rings }+    let mut conventions = None;+    let outcome = encoded.and_then(|encoded| {+        if empty {+            return Ok(RelationOutcome::Failed);+        }+        if !keep {+            return Ok(RelationOutcome::Skip);+        }+        // A multipolygon building carries its S3DB attributes into the building side table, just+        // as a building way does.+        if let Some(building) = relation.building {+            return PreRecord::building(&relation.class, &encoded, None, building).map(RelationOutcome::Kept);+        }+        // The id is what lets the mask gather a region's tile-clipped pieces back together.+        let id = if tracks_ids(&relation.class) {+            tagged_id(relation.id, ELEMENT_RELATION)+        } else {+            tilecodec::mamaps::body::ID_NONE+        };+        let record = PreRecord::named(&relation.class, &encoded, None, id)?;+        // The country's own shape is also what says how its roads are marked: stamped by the+        // drain, from these assembled rings, so the grid and the border line agree.+        if relation.iso.is_some() {+            conventions = Some(polygons);+        }+        Ok(RelationOutcome::Kept(record))+    });+    BuiltRelation { rings: Some(ring_stats), outcome, conventions } } +/// Relations per pool hand-off in [`materialise_relations`]. Large, because one country-sized+/// multipolygon can take seconds to stitch and a group's drain waits for its slowest relation;+/// with the next group computing while this one drains, that wait is mostly hidden.+const RELATIONS_PER_GROUP: usize = 32 * 1024;+ /// Materialise relations; returns the driving-side conventions. /// /// `region` filters the built layers (`roads`, `poi`, `buildings`) the same@@ -124,103 +169,34 @@ fn materialise_relations(     // Which driving side and centre-line colour applies where, accumulated as the country shapes     // go past.     let mut conventions = schema::boundaries::Conventions::default();-    // Batched, the [`materialise_ways`] pattern: `rings::assemble`, `centroid` and `table.line` are-    // the heavy per-relation work, are independent, and touch no shared mutable state, so a batch of-    // them goes as wide as the pool. The sink and the conventions grid then take the results **in-    // relation order**, which keeps the archive byte-identical. `conventions.add` in particular has-    // precedence rules (an interior claim outranks a border one), so it must stay serial and in-    // order.-    const MATERIALISE_RELATIONS_BATCH: usize = 4096;-    let mut built: Vec<BuiltRelation> = Vec::with_capacity(MATERIALISE_RELATIONS_BATCH);-    for batch in relations.chunks(MATERIALISE_RELATIONS_BATCH) {-        built.clear();-        par::install(|| {-            batch-                .par_iter()-                .map(|relation| build_relation(relation, members, table, region))-                .collect_into_vec(&mut built);-        });-        for (relation, built) in batch.iter().zip(built.drain(..)) {-            // `?` in spill order: the first encode failure in relation order,-            // exactly as inline encoding would report it.-            match built {-                BuiltRelation::Label(Some(point)) => {-                    // `poi` labels are region-filtered; `places` always kept.-                    // O(1) point test, no vertex walk — stays in the drain.-                    if relation.class.layer == tilecodec::mamaps::dict::LAYER_POI-                        && !point_touches(&point, region)-                    {-                        bar.tick("relation(s)");-                        continue;+    pipeline_ordered(+        relations.len(),+        RELATIONS_PER_GROUP,+        |i| build_relation(&relations[i], members, table, region),+        |i, built| {+            if let Some(r) = built.rings {+                stats.rings.outer_rings += r.outer_rings;+                stats.rings.inner_rings += r.inner_rings;+                stats.rings.unclosed += r.unclosed;+                stats.rings.orphan_inner += r.orphan_inner;+            }+            // `?` in spill order: the first failure in relation order, exactly as inline encoding+            // would report it.+            match built.outcome? {+                RelationOutcome::Skip => {}+                RelationOutcome::Failed => stats.geometry_failed += 1,+                RelationOutcome::Kept(record) => {+                    if let (Some(polygons), Some(iso)) = (&built.conventions, &relations[i].iso) {+                        conventions.add(iso, polygons);                     }-                    sink.push_named(-                        &relation.class,-                        &crate::store::EncodedGeom::live(&Geometry::Points(vec![point]))?,-                        relation.name.as_deref(),-                        tagged_id(relation.id, ELEMENT_RELATION),-                    )?;+                    sink.push_pre(&record)?;                     stats.features += 1;                 }-                BuiltRelation::Label(None) => stats.geometry_failed += 1,-                BuiltRelation::Border { encoded, empty } => {-                    let encoded = encoded?;-                    if empty {-                        stats.geometry_failed += 1;-                    } else {-                        sink.push_named(-                            &relation.class,-                            &encoded,-                            None,-                            tilecodec::mamaps::body::ID_NONE,-                        )?;-                        stats.features += 1;-                    }-                }-                BuiltRelation::Area { polygons, encoded, empty, keep, rings } => {-                    // Accumulated whether or not the stitch produced anything, exactly as the-                    // in-place `&mut stats.rings` did: a failed stitch still counted its unclosed-                    // and orphan rings.-                    stats.rings.outer_rings += rings.outer_rings;-                    stats.rings.inner_rings += rings.inner_rings;-                    stats.rings.unclosed += rings.unclosed;-                    stats.rings.orphan_inner += rings.orphan_inner;-                    let encoded = encoded?;-                    if empty {-                        stats.geometry_failed += 1;-                    } else {-                        // The buildings keep/drop was decided on the pool; every-                        // other area layer is always kept.-                        if !keep {-                            bar.tick("relation(s)");-                            continue;-                        }-                        // The id is what lets the mask gather a region's tile-clipped pieces back-                        // together.-                        let id = if tracks_ids(&relation.class) {-                            tagged_id(relation.id, ELEMENT_RELATION)-                        } else {-                            tilecodec::mamaps::body::ID_NONE-                        };-                        // A multipolygon building carries its S3DB attributes into the building side-                        // table, just as a building way does.-                        if let Some(building) = relation.building {-                            sink.push_building(&relation.class, &encoded, None, building)?;-                        } else {-                            // The country's own shape is also what says how its roads are marked.-                            // Stamped before the shape is moved into the sink, from the assembled-                            // rings, so the grid and the border line agree about where it is.-                            if let Some(iso) = &relation.iso {-                                conventions.add(iso, &polygons);-                            }-                            sink.push_named(&relation.class, &encoded, None, id)?;-                        }-                        stats.features += 1;-                    }-                }             }             bar.tick("relation(s)");-        }-    }+            Ok(())+        },+    )?;     bar.finish("relation(s)");      Ok(conventions)
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 5d7445d7c1..3c7e83ea35 100644--- a/scripts/maps/mamaps_build/src/lanefill.rs+++ b/scripts/maps/mamaps_build/src/lanefill.rs@@ -237,6 +237,51 @@ impl Record {     } } +/// A way's two endpoint records, built off the serial path. See [`Collector::push_prepared`].+pub struct Prepared([Record; 2]);++/// What [`Collector::push`] writes for `segment`, or `None` where it writes nothing.+///+/// Pure over the segment: the same checks, in the same order, with the same arithmetic as the+/// inline body this was lifted out of, so a pool-built `Prepared` is bit-for-bit the record pair+/// the serial path produced.+pub fn prepare(segment: &Segment) -> Option<Prepared> {+    if segment.name.is_empty() || segment.nodes.len() < 2 {+        return None;+    }+    if segment.nodes.len() != segment.line.len() {+        return None;+    }+    let first = segment.nodes[0];+    let last = segment.nodes[segment.nodes.len() - 1];+    // A closed way has one endpoint, not two, so it can never have a donor at "both" ends and+    // is not a junction stub in any case.+    if first == last {+        return None;+    }+    // An untagged way is never a donor, so one too long to be a recipient cannot affect+    // anything. Dropping it here rather than at resolve time is what keeps the spill small.+    if segment.lanes == 0 && polyline_length_m(segment.line) > MAX_STUB_M {+        return None;+    }+    // The bearing leaving each end, skipping repeated coordinates: a duplicated vertex has no+    // direction, and the graph does contain them where a way was split at a coincident point.+    let head = leaving(segment.line, true)?;+    let tail = leaving(segment.line, false)?;++    let name_hash = hash_name(segment.name);+    let base = if segment.oneway { FLAG_ONEWAY } else { 0 };+    let record = |node: i64, bearing: f64, end: u8| Record {+        node,+        way: segment.id,+        name_hash,+        bearing: bearing as f32,+        lanes: segment.lanes,+        flags: base | end,+    };+    Some(Prepared([record(first, head, 0u8), record(last, tail, FLAG_LAST_END)]))+}+ /// Accumulates endpoint records, then resolves them into the ways whose lane count changes. pub struct Collector {     files: Vec<BufWriter<File>>,@@ -261,42 +306,20 @@ impl Collector {     }      /// 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<()> {-        if segment.name.is_empty() || segment.nodes.len() < 2 {-            return Ok(());-        }-        if segment.nodes.len() != segment.line.len() {-            return Ok(());-        }-        let first = segment.nodes[0];-        let last = segment.nodes[segment.nodes.len() - 1];-        // A closed way has one endpoint, not two, so it can never have a donor at "both" ends and-        // is not a junction stub in any case.-        if first == last {-            return Ok(());+        match prepare(segment) {+            Some(prepared) => self.push_prepared(&prepared),+            None => Ok(()),         }-        // An untagged way is never a donor, so one too long to be a recipient cannot affect-        // anything. Dropping it here rather than at resolve time is what keeps the spill small.-        if segment.lanes == 0 && polyline_length_m(segment.line) > MAX_STUB_M {-            return Ok(());-        }-        // The bearing leaving each end, skipping repeated coordinates: a duplicated vertex has no-        // direction, and the graph does contain them where a way was split at a coincident point.-        let Some(head) = leaving(segment.line, true) else { return Ok(()) };-        let Some(tail) = leaving(segment.line, false) else { return Ok(()) };--        let name_hash = hash_name(segment.name);-        let base = if segment.oneway { FLAG_ONEWAY } else { 0 };-        for (node, bearing, end) in [(first, head, 0u8), (last, tail, FLAG_LAST_END)] {-            let record = Record {-                node,-                way: segment.id,-                name_hash,-                bearing: bearing as f32,-                lanes: segment.lanes,-                flags: base | end,-            };-            record.write(&mut self.files[partition_of(node)])?;+    }++    /// 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(())     }
scripts/maps/mamaps_build/src/main_part2.rs
diff --git a/scripts/maps/mamaps_build/src/main_part2.rs b/scripts/maps/mamaps_build/src/main_part2.rsindex c35a199bcc..e0caf6007d 100644--- a/scripts/maps/mamaps_build/src/main_part2.rs+++ b/scripts/maps/mamaps_build/src/main_part2.rs@@ -80,20 +80,10 @@ fn check_graph_dir(dir: &std::path::Path, region: osm_ingest::region::Region) ->     // Under v7 the record arrays are ZBLK sections: unpack at the boundary     // (this is a preflight check, not the hot path, so whole-section inflate     // is fine).+    // Block-parallel (see `schema::traffic::inflate_all`): the planet's 5 GB node table used to+    // inflate on one thread here, in the preflight, before stage A could start.     fn inflate_all(v: &tilecodec::blocked::Blocked) -> Result<Vec<u8>, String> {-        let mut cache = tilecodec::blocked::BlockCache::new(0);-        let mut out = Vec::with_capacity(v.unpacked_len() as usize);-        for b in 0..v.block_count() {-            out.extend_from_slice(-                cache-                    .get(v, b)-                    .map_err(|e| format!("blocked inflate failed: {e}"))?,-            );-        }-        if out.len() as u64 != v.unpacked_len() {-            return Err("blocked inflate came up short".to_string());-        }-        Ok(out)+        crate::schema::traffic::inflate_all(v).map_err(|e| format!("blocked inflate failed: {}", e.0))     }     let want_nodes = (node_count + 1)         .checked_mul(12)
scripts/maps/mamaps_build/src/schema/junction_part2.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part2.rs b/scripts/maps/mamaps_build/src/schema/junction_part2.rsindex 0578524f47..e7259cc8c3 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part2.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part2.rs@@ -232,49 +232,43 @@ pub fn stream_junctions(dir: &Path, conventions: &Conventions, sink: &mut Sink)     let class = junction_class();     let mut emitted = 0u64; -    // Batched, the `materialise_ways` pattern: `junctions_for_node` is pure-    // per-node work over shared-read-only tables, so a batch of node ids goes-    // as wide as the pool while the drain pushes **in `n` order**, which is-    // what keeps the spill — and therefore the archive — byte-identical at-    // every thread count. The bar ticks in the drain, per node, so it spans-    // the whole graph and this phase is never silent again.+    // Pipelined, the `materialise_ways` pattern: `junctions_for_node` is pure per-node work over+    // shared-read-only tables, and so is building each connector's spill record, so both run on+    // the pool while the drain only appends **in `n` order** -- which is what keeps the spill, and+    // therefore the archive, byte-identical at every thread count. The bar ticks in the drain, per+    // node, so it spans the whole graph and this phase is never silent.     //-    // 32 Ki node ids is a few hundred KB of ids in flight; junctions are-    // sparse, so the geometry coming back is far smaller than a ways batch of-    // the same count.-    const JUNCTION_BATCH: usize = 32 * 1024;+    // Was batches of 32 Ki nodes with the records encoded in the drain: on the planet (440 M+    // nodes, 177 M connectors) that ran 4m40s at ~28 cores, the drain and the per-batch barrier+    // being the limit.+    const JUNCTION_GROUP: usize = 256 * 1024;     let mut bar = Progress::new(         "Junctions".to_string(),         graph.node_count as usize,         "node(s)",         true,     );-    let mut ids: Vec<u64> = Vec::with_capacity(JUNCTION_BATCH);-    let mut built: Vec<Vec<Vec<(f64, f64)>>> = Vec::with_capacity(JUNCTION_BATCH);-    let mut next = 0u64;-    loop {-        ids.clear();-        while ids.len() < JUNCTION_BATCH && next < graph.node_count {-            ids.push(next);-            next += 1;-        }-        if ids.is_empty() {-            break;-        }-        built.clear();-        par::install(|| {-            ids.par_iter()-                .map(|&n| junctions_for_node(n, &graph, lanes.as_ref(), &incoming, conventions))-                .collect_into_vec(&mut built)-        });-        for node_geoms in built.drain(..) {-            for points in node_geoms {-                sink.push(&class, &crate::store::EncodedGeom::live(&Geometry::Lines(vec![points]))?)?;+    crate::extract::pipeline_ordered(+        graph.node_count as usize,+        JUNCTION_GROUP,+        |n| -> Result<Vec<crate::store::PreRecord>> {+            junctions_for_node(n as u64, &graph, lanes.as_ref(), &incoming, conventions)+                .into_iter()+                .map(|points| {+                    let encoded = crate::store::EncodedGeom::live(&Geometry::Lines(vec![points]))?;+                    crate::store::PreRecord::named(&class, &encoded, None, tilecodec::mamaps::body::ID_NONE)+                })+                .collect()+        },+        |_, records| {+            for record in records? {+                sink.push_pre(&record)?;                 emitted += 1;             }             bar.tick("node(s)");-        }-    }+            Ok(())+        },+    )?;     bar.finish("node(s)");     Ok(emitted) }
scripts/maps/mamaps_build/src/schema/traffic.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic.rs b/scripts/maps/mamaps_build/src/schema/traffic.rsindex abc6e2d931..9123e42ea2 100644--- a/scripts/maps/mamaps_build/src/schema/traffic.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -146,14 +146,24 @@ fn align_up8(n: usize) -> usize { /// Batch-tool path (traffic/junction stream whole tables), so one pass beats /// per-block caching. The device inflates lazily instead — see /// `maps/.../graph_part1.rs::BlockedView`.-fn inflate_all(view: &tilecodec::blocked::Blocked) -> Result<Vec<u8>> {-    let mut cache = tilecodec::blocked::BlockCache::new(0);+pub(crate) fn inflate_all(view: &tilecodec::blocked::Blocked) -> Result<Vec<u8>> {+    // Blocks inflate independently (`Blocked::block` is `&self` and pure), so they go across the+    // pool a group at a time and are appended in block order: the same bytes the one-block-at-a-+    // time loop produced. On the planet graph this was ~13 GB of nodes + edge records inflated on+    // one thread, the 1m40s at ~1.3 cores before the junction layer's first connector.+    use rayon::prelude::*;+    const GROUP: usize = 4096;     let mut out = Vec::with_capacity(view.unpacked_len() as usize);-    for b in 0..view.block_count() {-        let block = cache-            .get(view, b)-            .map_err(|e| osm_ingest::proto::Error(e.0))?;-        out.extend_from_slice(block);+    let n = view.block_count();+    let mut start = 0usize;+    while start < n {+        let end = (start + GROUP).min(n);+        let blocks: Vec<std::result::Result<Vec<u8>, _>> =+            tile_build::par::install(|| (start..end).into_par_iter().map(|b| view.block(b)).collect());+        for block in blocks {+            out.extend_from_slice(&block.map_err(|e| osm_ingest::proto::Error(e.0))?);+        }+        start = end;     }     if out.len() as u64 != view.unpacked_len() {         return err("a blocked section inflated short of its unpacked length".to_string());
scripts/maps/mamaps_build/src/store.rs
diff --git a/scripts/maps/mamaps_build/src/store.rs b/scripts/maps/mamaps_build/src/store.rsindex 3eeaf960f9..ce57ef4cf9 100644--- a/scripts/maps/mamaps_build/src/store.rs+++ b/scripts/maps/mamaps_build/src/store.rs@@ -329,4 +329,5 @@ include!("store_part1.rs"); include!("store_part2.rs"); include!("store_part3.rs"); include!("store_part4.rs");-include!("store_part5.rs");\ No newline at end of file+include!("store_part5.rs");+include!("store_part6.rs");\ No newline at end of file
scripts/maps/mamaps_build/src/store_part1.rs
diff --git a/scripts/maps/mamaps_build/src/store_part1.rs b/scripts/maps/mamaps_build/src/store_part1.rsindex 900bae2d88..01743d7d8c 100644--- a/scripts/maps/mamaps_build/src/store_part1.rs+++ b/scripts/maps/mamaps_build/src/store_part1.rs@@ -20,6 +20,13 @@ impl Sink {             }             osm_ingest::mem::SpillPlan::File => {                 eprintln!("  [stage A] feature spill -> {} (file backend: commit budget)", path.display());+                // Created empty and marked uncompressed first (`create` below truncates the same+                // inode, keeping the flag): the frames are already DEFLATE, so `compress-force`+                // spends a zstd attempt per 128 KiB extent at writeback on bytes that will not+                // shrink -- 289 GB of them on the planet. Best effort; the bytes are the same.+                if let Ok(file) = std::fs::File::create(path) {+                    osm_ingest::mem::mark_scratch_uncompressed(&file);+                }                 NormalizedWriter::create(path)                     .map_err(|e| osm_ingest::proto::Error(e.to_string()))?             }@@ -85,20 +92,7 @@ impl Sink {         name: Option<&str>,         id: u64,     ) -> Result<()> {-        self.props[0].1 = Value::Uint(pack(class)?);-        self.props.truncate(1);-        if let Some(name) = name.filter(|n| !n.is_empty()) {-            self.props.push((NAME_KEY.to_string(), Value::String(name.to_string())));-        }-        if id != tilecodec::mamaps::body::ID_NONE {-            if !crate::extract::tracks_ids(class) {-                return err(format!(-                    "layer {} carries a feature id, which only places, poi and a boundaries region shape may",-                    class.layer,-                ));-            }-            self.props.push((ID_KEY.to_string(), Value::Uint(id)));-        }+        fill_named(&mut self.props, class, name, id)?;         self.write_record(class, geometry)     } @@ -118,34 +112,7 @@ impl Sink {         turn_bwd: &[u16],         carriageway: Carriageway,     ) -> Result<()> {-        if name.is_none()-            && lane_count == 0-            && turn_fwd.is_empty()-            && turn_bwd.is_empty()-            && carriageway.is_empty()-        {-            return err("a road pushed with no lane data".to_string());-        }-        self.props[0].1 = Value::Uint(pack(class)?);-        self.props.truncate(1);-        if let Some(name) = name.filter(|n| !n.is_empty()) {-            self.props.push((NAME_KEY.to_string(), Value::String(name.to_string())));-        }-        if lane_count > 0 {-            self.props.push((LANE_COUNT_KEY.to_string(), Value::Uint(lane_count as u64)));-        }-        if !turn_fwd.is_empty() {-            self.props-                .push((TURN_FWD_KEY.to_string(), Value::String(osm_ingest::roads::pack_lanes(turn_fwd))));-        }-        if !turn_bwd.is_empty() {-            self.props-                .push((TURN_BWD_KEY.to_string(), Value::String(osm_ingest::roads::pack_lanes(turn_bwd))));-        }-        if !carriageway.is_empty() {-            self.props-                .push((CARRIAGEWAY_KEY.to_string(), Value::Uint(pack_carriageway(carriageway))));-        }+        fill_road(&mut self.props, class, name, lane_count, turn_fwd, turn_bwd, carriageway)?;         self.write_record(class, geometry)     } @@ -161,15 +128,7 @@ impl Sink {         name: Option<&str>,         attrs: BuildingAttrs,     ) -> Result<()> {-        self.props[0].1 = Value::Uint(pack(class)?);-        self.props.truncate(1);-        if let Some(name) = name.filter(|n| !n.is_empty()) {-            self.props.push((NAME_KEY.to_string(), Value::String(name.to_string())));-        }-        let (a, b, c) = pack_building(&attrs);-        self.props.push((BLD_A_KEY.to_string(), Value::Uint(a)));-        self.props.push((BLD_B_KEY.to_string(), Value::Uint(b)));-        self.props.push((BLD_C_KEY.to_string(), Value::Uint(c)));+        fill_building(&mut self.props, class, name, attrs)?;         self.write_record(class, geometry)     } 
scripts/maps/mamaps_build/src/store_part2.rs
diff --git a/scripts/maps/mamaps_build/src/store_part2.rs b/scripts/maps/mamaps_build/src/store_part2.rsindex bcf23c28da..74171b55f4 100644--- a/scripts/maps/mamaps_build/src/store_part2.rs+++ b/scripts/maps/mamaps_build/src/store_part2.rs@@ -15,6 +15,7 @@ impl Store {     /// A chunk whose shallowest `min_zoom` is deeper than `z` holds nothing this zoom draws, so it is     /// skipped outright — not read, not parsed. Order is unchanged, because the chunks that survive     /// are still visited in file order, and that is what keeps the archive byte-identical.+#[cfg_attr(not(test), allow(dead_code))]     pub fn reader_for_zoom(&self, z: u8) -> Result<ZoomReader> {         let wanted: Vec<usize> = self             .chunk_mins@@ -35,29 +36,6 @@ impl Store {             .collect()     } -    pub fn wanted_len_for_zoom(&self, z: u8) -> usize {-        self.chunk_mins.iter().filter(|min| **min <= z).count()-    }--    pub fn path(&self) -> &PathBuf {-        &self.path-    }--    /// The shared anonymous spill store. Cloned (refcount bump, never bytes)-    /// into per-lane store views so decode threads read the same memory.-    /// `None` on the file plan, where lanes open the file at `path` instead.-    pub fn anon_store(&self) -> Option<std::sync::Arc<tile_build::anon::AnonStore>> {-        self.anon.clone()-    }--    pub fn raw_chunks(&self) -> &[u64] {-        &self.chunks-    }--    pub fn chunk_mins_cloned(&self) -> Vec<u8> {-        self.chunk_mins.clone()-    }-     pub fn from_parts(path: PathBuf, chunks: Vec<u64>, chunk_mins: Vec<u8>) -> Self {         Self {             path,@@ -70,28 +48,6 @@ impl Store {         }     } -    /// A view over the same staged bytes: `store` is the shared anonymous-    /// spill (cloned Arc, never bytes) or `None` on the file plan, where the view reads the file-    /// at `path`. `chunks`/`chunk_mins` the same index either way.-    /// Used by per-lane decode threads, which need a `Store` to open readers-    /// from but must not copy the spill.-    pub fn view_over(-        path: PathBuf,-        chunks: Vec<u64>,-        chunk_mins: Vec<u8>,-        store: Option<std::sync::Arc<tile_build::anon::AnonStore>>,-    ) -> Self {-        Self {-            path,-            anon: store,-            chunks,-            chunk_mins,-            count: 0,-            bbox: (0, 0, 0, 0),-            conventions: crate::schema::boundaries::Conventions::default(),-        }-    }-     /// Open the staged bytes for chunked reading, anonymous or file according to the plan the     /// sink was created with. One helper so the three reader constructors agree.     fn open_chunks(&self) -> Result<NormalizedChunks> {@@ -319,6 +275,7 @@ fn feature_of(record: tile_build::spill::NormalizedFeature) -> Result<Feature> { /// lookup and the move are free; what is not is dropping the `props` the decoder built — a `Vec` and /// an owned key `String` per feature, freed one at a time on the one thread the whole map phase /// waits on. Converting in the lane puts that on the lane.+#[cfg_attr(not(test), allow(dead_code))] type Decoded = Result<Vec<Feature>>;  /// Threads decoding spill chunks ahead of the tiler.@@ -345,6 +302,7 @@ type Decoded = Result<Vec<Feature>>; /// continent wants. Removing the need for the knob means removing the re-decode it is compensating /// for: the spill is read once per zoom, which is ~1.06 billion feature decodes to deliver /// 199.7 M distinct features on north-america, and no lane count makes redundant work cheap.+#[cfg_attr(not(test), allow(dead_code))] pub fn prefetch_lanes() -> usize {     static LANES: std::sync::OnceLock<usize> = std::sync::OnceLock::new();     *LANES.get_or_init(|| {
scripts/maps/mamaps_build/src/store_part3.rs
diff --git a/scripts/maps/mamaps_build/src/store_part3.rs b/scripts/maps/mamaps_build/src/store_part3.rsindex a0da5f8041..2fb293f3b2 100644--- a/scripts/maps/mamaps_build/src/store_part3.rs+++ b/scripts/maps/mamaps_build/src/store_part3.rs@@ -11,6 +11,7 @@ /// reader was not waiting on disk, it was busy discarding features (see [`ZoomReader::spawn`]). Kept /// as a named constant of 1 rather than deleted, because the shape of the partition is worth being /// explicit about and because the next person to look at a 643 MB/s number will have the same idea.+#[cfg_attr(not(test), allow(dead_code))] const PREFETCH_RUN: usize = 1;  /// Chunks one lane may run ahead by.@@ -18,9 +19,11 @@ const PREFETCH_RUN: usize = 1; /// Bounds the prefetch at `prefetch_lanes() * (PREFETCH_DEPTH + 1) * 64` features — about 34 K at /// constants above, which is small against the 512 Ki *vertices* the tiler batches immediately /// downstream. Depth is here to absorb a slow chunk, not to buffer.+#[cfg_attr(not(test), allow(dead_code))] const PREFETCH_DEPTH: usize = 32;  /// Reads the chunks one zoom needs and seeks past the rest.+#[cfg_attr(not(test), allow(dead_code))] pub struct ZoomReader {     /// One receiver per lane. Wanted-chunk `k` is decoded by lane `(k / PREFETCH_RUN) % lanes.len()`,     /// so walking the lanes a run at a time reproduces file order exactly. Empty when there is@@ -47,6 +50,7 @@ impl Drop for ZoomReader {     } } +#[cfg_attr(not(test), allow(dead_code))] impl ZoomReader {     /// Start a lane per [`prefetch_lanes`] over `wanted`, dealt round-robin.     ///@@ -176,6 +180,7 @@ impl ZoomReader {     ///     /// Exposed so the tiler can show progress: the map phase is the longest in the build and was     /// silent for all of it, which on a continent is forty minutes of no output at all.+    #[allow(dead_code)]     pub fn chunks(&self) -> (usize, usize) {         (self.at.min(self.total), self.total)     }@@ -280,6 +285,10 @@ pub struct WaySink {     count: u64,     refs: u64,     max_ref: i64,+    /// Bytes staged so far: the next record's offset, for the block index.+    at: u64,+    /// The block index over the stream. See [`WayBlockLoc`].+    blocks: Vec<WayBlockLoc>, }  /// Where a [`WaySink`] stages its bytes: a file, or anonymous memory.@@ -300,6 +309,8 @@ impl WaySink {             count: 0,             refs: 0,             max_ref: 0,+            at: 0,+            blocks: Vec::new(),         })     } @@ -334,6 +345,8 @@ impl WaySink {             count: 0,             refs: 0,             max_ref: 0,+            at: 0,+            blocks: Vec::new(),         })     } @@ -359,54 +372,22 @@ impl WaySink {         building: Option<BuildingAttrs>,     ) -> Result<()> {         if self.count > 0 && id <= self.last_id {-            return err(format!(-                "way {id} arrived after way {}, so this PBF is not sorted by way id and the \-                 sequential ways spill cannot be used for it",-                self.last_id,-            ));+            return err(unsorted_ways(id, self.last_id));         }         self.record.clear();         put_svarint(&mut self.record, id.wrapping_sub(self.last_id));-        put_uvarint(&mut self.record, pack(class)?);-        put_uvarint(&mut self.record, refs.len() as u64);-        let mut previous: i64 = 0;-        for &node in refs {-            put_svarint(&mut self.record, node.wrapping_sub(previous));-            previous = node;-            self.max_ref = self.max_ref.max(node);-        }-        match name.filter(|n| !n.is_empty()) {-            Some(name) => {-                put_uvarint(&mut self.record, name.len() as u64);-                self.record.extend_from_slice(name.as_bytes());-            }-            None => put_uvarint(&mut self.record, 0),-        }-        put_uvarint(&mut self.record, lane_count as u64);-        // The turn masks: a count then each u16, forward then backward. Zero counts for the-        // overwhelming majority, which cost one byte each.-        for masks in [turn_fwd, turn_bwd] {-            put_uvarint(&mut self.record, masks.len() as u64);-            for &m in masks {-                put_uvarint(&mut self.record, m as u64);-            }-        }-        // The directional split, as one packed varint. Zero — one byte — for the roads whose-        // division was never surveyed, which is most of them.-        put_uvarint(&mut self.record, pack_carriageway(carriageway));-        // The building attributes: a presence byte, then the three packed words when present. A-        // non-building writes one zero byte; a building — even one with no S3DB tags — writes its-        // (usually all-zero) words so the tiler's side table stays dense-parallel to the layer.-        match building {-            Some(attrs) => {-                put_uvarint(&mut self.record, 1);-                let (a, b, c) = pack_building(&attrs);-                put_uvarint(&mut self.record, a);-                put_uvarint(&mut self.record, b);-                put_uvarint(&mut self.record, c);-            }-            None => put_uvarint(&mut self.record, 0),-        }+        let max_ref = encode_way_tail(+            &mut self.record,+            class,+            refs,+            name,+            lane_count,+            turn_fwd,+            turn_bwd,+            carriageway,+            building,+        )?;+        self.max_ref = self.max_ref.max(max_ref);         // Moved out rather than cloned: `out_write` takes `&mut self`, so `&self.record`         // cannot borrow across the call, and a per-way clone is a memcpy per record over         // millions of records. The buffer is restored below with its capacity intact, so the@@ -415,14 +396,64 @@ impl WaySink {         let result = self.out_write(&record).map_err(|e| {             Error(format!("cannot write the ways spill: {e}"))         });+        let len = record.len() as u64;         self.record = record;         result?;+        self.note_block(len, 1);         self.last_id = id;         self.count += 1;         self.refs += refs.len() as u64;         Ok(())     } +    /// Append a run of ways a worker encoded ([`WayBlock`]). Writes exactly what `push` would+    /// have written for those ways one at a time: the block's first id varint is re-encoded+    /// against the last id this sink saw, the rest is copied verbatim. The ordering rule is+    /// enforced across the block boundary just as `push` enforces it between records.+    pub fn push_block(&mut self, block: &WayBlock) -> Result<()> {+        if block.count == 0 {+            return Ok(());+        }+        if self.count > 0 && block.first_id <= self.last_id {+            return err(unsorted_ways(block.first_id, self.last_id));+        }+        self.record.clear();+        put_svarint(&mut self.record, block.first_id.wrapping_sub(self.last_id));+        let head = std::mem::take(&mut self.record);+        let wrote = self+            .out_write(&head)+            .and_then(|()| self.out_write(&block.bytes[block.head_len..]));+        let len = (head.len() + block.bytes.len() - block.head_len) as u64;+        self.record = head;+        wrote?;+        self.note_block(len, block.count);+        self.last_id = block.last_id;+        self.count += block.count;+        self.refs += block.refs;+        self.max_ref = self.max_ref.max(block.max_ref);+        Ok(())+    }++    /// Index `len` bytes / `ways` records just written at `self.at`, whose first delta is taken+    /// from `self.last_id` (still the pre-write value). Coalesced into the previous entry while+    /// that stays within [`WAY_BLOCK_WAYS`]: a run of consecutive records decodes from the first+    /// one's base however it was written, so merging entries changes nothing but the index size.+    fn note_block(&mut self, len: u64, ways: u64) {+        match self.blocks.last_mut() {+            Some(last) if last.offset + last.len == self.at && last.ways + ways <= WAY_BLOCK_WAYS => {+                last.len += len;+                last.ways += ways;+            }+            _ => self.blocks.push(WayBlockLoc {+                offset: self.at,+                len,+                start_last_id: self.last_id,+                ways,+            }),+        }+        self.at += len;+    }+     fn out_write(&mut self, bytes: &[u8]) -> Result<()> {         match &mut self.out {             WayOut::File(f) => f.write_all(bytes).map_err(|e| {@@ -448,7 +479,12 @@ impl WaySink {             WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?,             WayOut::Anon(a) => a.finish(),         }-        Ok(WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref })+        Ok(WayCounts {+            ways: self.count,+            refs: self.refs,+            max_ref: self.max_ref,+            blocks: std::mem::take(&mut self.blocks),+        })     }      /// Anonymous twin of [`finish`](Self::finish): seals the pagefile-backed@@ -461,7 +497,12 @@ impl WaySink {             }             WayOut::Anon(a) => a.finish(),         }-        let counts = WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref };+        let counts = WayCounts {+            ways: self.count,+            refs: self.refs,+            max_ref: self.max_ref,+            blocks: std::mem::take(&mut self.blocks),+        };         match self.out {             WayOut::Anon(a) => Ok((counts, a)),             WayOut::File(_) => unreachable!("checked above"),@@ -477,7 +518,12 @@ impl WaySink {             WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?,             WayOut::Anon(a) => a.finish(),         }-        let counts = WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref };+        let counts = WayCounts {+            ways: self.count,+            refs: self.refs,+            max_ref: self.max_ref,+            blocks: std::mem::take(&mut self.blocks),+        };         match self.out {             WayOut::Anon(a) => Ok((counts, Some(a))),             WayOut::File(_) => Ok((counts, None)),@@ -493,6 +539,8 @@ pub struct WayCounts {     /// The largest node ref written, or zero if none were. What a bitset over the id space is sized     /// from.     pub max_ref: i64,+    /// The block index over the stream, in stream order: what [`WayBlocks`] decodes from.+    pub blocks: Vec<WayBlockLoc>, }  /// Reads back what a [`WaySink`] wrote, in the order it was written.@@ -508,6 +556,7 @@ pub struct WayReader {  /// Where a [`WayReader`] reads from. enum WayIn {+#[cfg_attr(not(test), allow(dead_code))]     File(BufReader<File>),     Anon {         store: std::sync::Arc<tile_build::anon::AnonStore>,@@ -515,4 +564,6 @@ enum WayIn {         buf: Vec<u8>,         used: usize,     },+    /// One block of the stream, read whole ([`WayBlocks::reader`]).+    Slice { buf: Vec<u8>, used: usize }, }
scripts/maps/mamaps_build/src/store_part4.rs
diff --git a/scripts/maps/mamaps_build/src/store_part4.rs b/scripts/maps/mamaps_build/src/store_part4.rsindex b0412d5121..e5c8510af6 100644--- a/scripts/maps/mamaps_build/src/store_part4.rs+++ b/scripts/maps/mamaps_build/src/store_part4.rs@@ -1,4 +1,5 @@ impl WayReader {+#[cfg_attr(not(test), allow(dead_code))]     pub fn open(path: &Path) -> Result<WayReader> {         let file = File::open(path)             .map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;@@ -193,6 +194,7 @@ impl WayReader {                 }                 Ok(&buf[*used..])             }+            WayIn::Slice { buf, used } => Ok(&buf[*used..]),         }     } @@ -200,6 +202,7 @@ impl WayReader {         match &mut self.inner {             WayIn::File(f) => f.consume(n),             WayIn::Anon { used, .. } => *used += n,+            WayIn::Slice { used, .. } => *used += n,         }     } 
scripts/maps/mamaps_build/src/store_part6.rs
diff --git a/scripts/maps/mamaps_build/src/store_part6.rs b/scripts/maps/mamaps_build/src/store_part6.rsnew file mode 100644index 0000000000..36d3c56c1d--- /dev/null+++ b/scripts/maps/mamaps_build/src/store_part6.rs@@ -0,0 +1,647 @@+// --- pool-built records ------------------------------------------------------------------------+//+// The materialise drains used to build every spill record on the one serial thread: the props+// list (a `String` per key), `encode_props`, the record header, and -- per 64 features -- a DEFLATE+// frame. On California that was 19.0 s of a 26.6 s `materialise-ways`; on the planet, ~1.1 B ways,+// it was the bulk of a 30-40 minute single-core phase. Everything up to the record bytes is a pure+// function of one feature, so it now runs on the pool ([`PreRecord`]) and the serial thread only+// appends ([`Sink::push_pre`]); the frames compress in batches on the pool inside the writer.+//+// The props builders below are the bodies `push_named` / `push_road` / `push_building` always had,+// moved out so both paths run the very same code. Same props, same `encode_props`, same header:+// the same bytes.++/// `push_named`'s props: the packed class, then the name and the tagged id when present.+fn fill_named(+    props: &mut Vec<(String, Value)>,+    class: &Class,+    name: Option<&str>,+    id: u64,+) -> Result<()> {+    props[0].1 = Value::Uint(pack(class)?);+    props.truncate(1);+    if let Some(name) = name.filter(|n| !n.is_empty()) {+        props.push((NAME_KEY.to_string(), Value::String(name.to_string())));+    }+    if id != tilecodec::mamaps::body::ID_NONE {+        if !crate::extract::tracks_ids(class) {+            return err(format!(+                "layer {} carries a feature id, which only places, poi and a boundaries region shape may",+                class.layer,+            ));+        }+        props.push((ID_KEY.to_string(), Value::Uint(id)));+    }+    Ok(())+}++/// `push_road`'s props, including its refusal of a road with nothing to carry.+fn fill_road(+    props: &mut Vec<(String, Value)>,+    class: &Class,+    name: Option<&str>,+    lane_count: u8,+    turn_fwd: &[u16],+    turn_bwd: &[u16],+    carriageway: Carriageway,+) -> Result<()> {+    if name.is_none()+        && lane_count == 0+        && turn_fwd.is_empty()+        && turn_bwd.is_empty()+        && carriageway.is_empty()+    {+        return err("a road pushed with no lane data".to_string());+    }+    props[0].1 = Value::Uint(pack(class)?);+    props.truncate(1);+    if let Some(name) = name.filter(|n| !n.is_empty()) {+        props.push((NAME_KEY.to_string(), Value::String(name.to_string())));+    }+    if lane_count > 0 {+        props.push((LANE_COUNT_KEY.to_string(), Value::Uint(lane_count as u64)));+    }+    if !turn_fwd.is_empty() {+        props.push((TURN_FWD_KEY.to_string(), Value::String(osm_ingest::roads::pack_lanes(turn_fwd))));+    }+    if !turn_bwd.is_empty() {+        props.push((TURN_BWD_KEY.to_string(), Value::String(osm_ingest::roads::pack_lanes(turn_bwd))));+    }+    if !carriageway.is_empty() {+        props.push((CARRIAGEWAY_KEY.to_string(), Value::Uint(pack_carriageway(carriageway))));+    }+    Ok(())+}++/// `push_building`'s props: class, optional name, then the three packed S3DB words.+fn fill_building(+    props: &mut Vec<(String, Value)>,+    class: &Class,+    name: Option<&str>,+    attrs: BuildingAttrs,+) -> Result<()> {+    props[0].1 = Value::Uint(pack(class)?);+    props.truncate(1);+    if let Some(name) = name.filter(|n| !n.is_empty()) {+        props.push((NAME_KEY.to_string(), Value::String(name.to_string())));+    }+    let (a, b, c) = pack_building(&attrs);+    props.push((BLD_A_KEY.to_string(), Value::Uint(a)));+    props.push((BLD_B_KEY.to_string(), Value::Uint(b)));+    props.push((BLD_C_KEY.to_string(), Value::Uint(c)));+    Ok(())+}++/// One feature's spill record, built off the serial thread.+///+/// Carries what [`Sink::write_record`] needs beyond the bytes -- the geometry kind and bounds for+/// the writer's summary, the e7 box for the sink's bbox, the class's `min_zoom` for the chunk+/// index -- so [`Sink::push_pre`] repeats `write_record`'s bookkeeping exactly.+pub struct PreRecord {+    rec: Vec<u8>,+    kind: GeomKind,+    bounds: Option<Rect>,+    ebbx: Option<(i32, i32, i32, i32)>,+    min_zoom: u8,+}++impl PreRecord {+    /// What [`Sink::push_named`] would stage.+    pub fn named(+        class: &Class,+        geometry: &EncodedGeom,+        name: Option<&str>,+        id: u64,+    ) -> Result<PreRecord> {+        let mut props = vec![(CLASS_KEY.to_string(), Value::Uint(0))];+        fill_named(&mut props, class, name, id)?;+        Self::build(class, geometry, &props)+    }++    /// What [`Sink::push_road`] would stage.+    #[allow(clippy::too_many_arguments)]+    pub fn road(+        class: &Class,+        geometry: &EncodedGeom,+        name: Option<&str>,+        lane_count: u8,+        turn_fwd: &[u16],+        turn_bwd: &[u16],+        carriageway: Carriageway,+    ) -> Result<PreRecord> {+        let mut props = vec![(CLASS_KEY.to_string(), Value::Uint(0))];+        fill_road(&mut props, class, name, lane_count, turn_fwd, turn_bwd, carriageway)?;+        Self::build(class, geometry, &props)+    }++    /// What [`Sink::push_building`] would stage.+    pub fn building(+        class: &Class,+        geometry: &EncodedGeom,+        name: Option<&str>,+        attrs: BuildingAttrs,+    ) -> Result<PreRecord> {+        let mut props = vec![(CLASS_KEY.to_string(), Value::Uint(0))];+        fill_building(&mut props, class, name, attrs)?;+        Self::build(class, geometry, &props)+    }++    fn build(class: &Class, geometry: &EncodedGeom, props: &[(String, Value)]) -> Result<PreRecord> {+        let mut rec = Vec::with_capacity(64 + geometry.bytes.len());+        tile_build::spill::encode_normalized_record(geometry.kind, &geometry.bytes, props, &mut rec)+            .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+        Ok(PreRecord {+            rec,+            kind: geometry.kind,+            bounds: geometry.bounds,+            ebbx: geometry.ebbx,+            min_zoom: class.min_zoom,+        })+    }+}++impl Sink {+    /// Append a pool-built record: [`write_record`](Self::write_record) with the encoding already+    /// done. Same writer call, same chunk-min, count and bbox bookkeeping, in the same order.+    pub fn push_pre(&mut self, record: &PreRecord) -> Result<()> {+        self.writer+            .push_record(record.kind, &record.rec, record.bounds)+            .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+        self.filling = self.filling.min(record.min_zoom);+        self.count += 1;+        if self.count % NORM_CHUNK_FEATURES == 0 {+            self.chunk_mins.push(self.filling);+            self.filling = u8::MAX;+        }+        self.grow_bounds(record.ebbx);+        Ok(())+    }+}++// --- the ways spill, in blocks ---------------------------------------------------------------------+//+// The ways spill is one varint stream whose ids are delta-coded from record to record, so it could+// only ever be read by one cursor -- and it is read twice (lane inheritance, materialise), 1.1 B+// records on the planet, with every way decoded on one thread: 6 min and 30-40 min phases running+// at 4-6 of 192 cores. And it was *written* by pass 1's serial drain, record by record, which is+// what held pass 1 to ~4 cores for 4m40s.+//+// The stream is unchanged, byte for byte. What is new is an index over it: every+// [`WAY_BLOCK_WAYS`]-ish run of records is a [`WayBlockLoc`] -- its byte range plus the id the+// first record's delta is taken from -- so any run decodes on its own. Pass 1's workers encode+// their chunk's ways into [`WayBlock`]s (the record bytes with the first id left open), the drain+// only patches that one varint and appends, and the two readers decode blocks across the pool+// ([`WayBlocks`]) and consume them in block order, which is spill order.++/// Ways per index entry, at most. Small enough that a planet pass decodes ~280 k blocks across the+/// pool with even load; large enough that the index is a few MB.+pub const WAY_BLOCK_WAYS: u64 = 4096;++/// One run of the ways spill that decodes on its own.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct WayBlockLoc {+    /// Byte offset of the run's first record in the spill.+    offset: u64,+    /// Bytes in the run.+    len: u64,+    /// The id the first record's delta is taken from: the previous record's id, or zero.+    start_last_id: i64,+    /// Records in the run.+    ways: u64,+}++impl WayBlockLoc {+    pub fn ways(&self) -> u64 {+        self.ways+    }+}++/// A run of way records encoded off the serial thread, for [`WaySink::push_block`].+///+/// Exactly the bytes [`WaySink::push`] would write for the same ways, except that the first+/// record's id delta is left open (it is relative to whatever the sink saw last, which a worker+/// cannot know): the block stores that varint as the absolute id and remembers its length, and the+/// sink re-encodes just that varint.+pub struct WayBlock {+    bytes: Vec<u8>,+    /// Length of the first record's id varint at the head of `bytes`.+    head_len: usize,+    first_id: i64,+    last_id: i64,+    count: u64,+    refs: u64,+    max_ref: i64,+}++impl Default for WayBlock {+    fn default() -> Self {+        Self::new()+    }+}++impl WayBlock {+    pub fn new() -> WayBlock {+        WayBlock { bytes: Vec::new(), head_len: 0, first_id: 0, last_id: 0, count: 0, refs: 0, max_ref: 0 }+    }++    /// Ways encoded so far.+    pub fn len(&self) -> u64 {+        self.count+    }++    #[allow(dead_code)]+    pub fn is_empty(&self) -> bool {+        self.count == 0+    }++    /// Encode one way. Same arguments, same ordering rule and same record bytes as+    /// [`WaySink::push`].+    #[allow(clippy::too_many_arguments)]+    pub fn push(+        &mut self,+        id: i64,+        class: &Class,+        refs: &[i64],+        name: Option<&str>,+        lane_count: u8,+        turn_fwd: &[u16],+        turn_bwd: &[u16],+        carriageway: Carriageway,+        building: Option<BuildingAttrs>,+    ) -> Result<()> {+        if self.count > 0 && id <= self.last_id {+            return err(unsorted_ways(id, self.last_id));+        }+        if self.count == 0 {+            put_svarint(&mut self.bytes, id);+            self.head_len = self.bytes.len();+            self.first_id = id;+        } else {+            put_svarint(&mut self.bytes, id.wrapping_sub(self.last_id));+        }+        let max_ref = encode_way_tail(+            &mut self.bytes,+            class,+            refs,+            name,+            lane_count,+            turn_fwd,+            turn_bwd,+            carriageway,+            building,+        )?;+        self.max_ref = self.max_ref.max(max_ref);+        self.last_id = id;+        self.count += 1;+        self.refs += refs.len() as u64;+        Ok(())+    }+}++/// The error a non-advancing way id gets, from the sink and from a block alike.+fn unsorted_ways(id: i64, last_id: i64) -> String {+    format!(+        "way {id} arrived after way {last_id}, so this PBF is not sorted by way id and the \+         sequential ways spill cannot be used for it",+    )+}++/// Everything in a way record after its id varint (see [`WaySink`]'s table), appended to `out`.+/// Returns the largest ref, or zero for none -- the fold `WaySink` keeps.+#[allow(clippy::too_many_arguments)]+fn encode_way_tail(+    out: &mut Vec<u8>,+    class: &Class,+    refs: &[i64],+    name: Option<&str>,+    lane_count: u8,+    turn_fwd: &[u16],+    turn_bwd: &[u16],+    carriageway: Carriageway,+    building: Option<BuildingAttrs>,+) -> Result<i64> {+    put_uvarint(out, pack(class)?);+    put_uvarint(out, refs.len() as u64);+    let mut previous: i64 = 0;+    let mut max_ref: i64 = 0;+    for &node in refs {+        put_svarint(out, node.wrapping_sub(previous));+        previous = node;+        max_ref = max_ref.max(node);+    }+    match name.filter(|n| !n.is_empty()) {+        Some(name) => {+            put_uvarint(out, name.len() as u64);+            out.extend_from_slice(name.as_bytes());+        }+        None => put_uvarint(out, 0),+    }+    put_uvarint(out, lane_count as u64);+    // The turn masks: a count then each u16, forward then backward. Zero counts for the+    // overwhelming majority, which cost one byte each.+    for masks in [turn_fwd, turn_bwd] {+        put_uvarint(out, masks.len() as u64);+        for &m in masks {+            put_uvarint(out, m as u64);+        }+    }+    // The directional split, as one packed varint. Zero -- one byte -- when never surveyed.+    put_uvarint(out, pack_carriageway(carriageway));+    // The building attributes: a presence byte, then the three packed words when present. A+    // non-building writes one zero byte; a building -- even one with no S3DB tags -- writes its+    // (usually all-zero) words so the tiler's side table stays dense-parallel to the layer.+    match building {+        Some(attrs) => {+            put_uvarint(out, 1);+            let (a, b, c) = pack_building(&attrs);+            put_uvarint(out, a);+            put_uvarint(out, b);+            put_uvarint(out, c);+        }+        None => put_uvarint(out, 0),+    }+    Ok(max_ref)+}++/// The sealed ways spill as independently decodable blocks. Shared read-only across the pool:+/// every [`reader`](Self::reader) call is a positional read of one block.+pub struct WayBlocks {+    file: Option<File>,+    anon: Option<std::sync::Arc<tile_build::anon::AnonStore>>,+    locs: Vec<WayBlockLoc>,+}++impl WayBlocks {+    /// Open whichever backend the sink sealed -- the shared anon store when present, else the+    /// file at `path` -- with the index [`WaySink`] returned in its [`WayCounts`].+    pub fn open(+        path: &Path,+        anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,+        locs: Vec<WayBlockLoc>,+    ) -> Result<WayBlocks> {+        let file = match anon {+            Some(_) => None,+            None => Some(+                File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?,+            ),+        };+        Ok(WayBlocks { file, anon: anon.clone(), locs })+    }++    pub fn locs(&self) -> &[WayBlockLoc] {+        &self.locs+    }++    /// A cursor over block `i` alone, positioned on its first record with the id its first delta+    /// is taken from. Yields exactly the records [`WayReader::open`] yields over that byte range.+    pub fn reader(&self, i: usize) -> Result<WayReader> {+        let loc = self.locs[i];+        let len = usize::try_from(loc.len)+            .map_err(|_| Error("a ways spill block does not fit in memory".to_string()))?;+        let mut buf = vec![0u8; len];+        match (&self.anon, &self.file) {+            (Some(anon), _) => anon+                .read_at(loc.offset, &mut buf)+                .map_err(|e| Error(format!("cannot read the anon ways spill: {e}")))?,+            (None, Some(file)) => read_exact_at(file, &mut buf, loc.offset)+                .map_err(|e| Error(format!("cannot read the ways spill: {e}")))?,+            (None, None) => return err("a ways spill with no backend".to_string()),+        }+        Ok(WayReader {+            inner: WayIn::Slice { buf, used: 0 },+            last_id: loc.start_last_id,+            seen: 0,+        })+    }+}++/// Positional read of exactly `buf.len()` bytes, safe to call from many threads on one `File`.+fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> {+    while !buf.is_empty() {+        #[cfg(windows)]+        let n = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?;+        #[cfg(unix)]+        let n = std::os::unix::fs::FileExt::read_at(file, buf, offset)?;+        if n == 0 {+            return Err(std::io::Error::new(+                std::io::ErrorKind::UnexpectedEof,+                "the ways spill ended inside a block",+            ));+        }+        buf = &mut buf[n..];+        offset += n as u64;+    }+    Ok(())+}++#[cfg(test)]+mod way_block_tests {+    use super::*;++    fn class(layer: u8, kind: u16) -> Class {+        Class { layer, kind, kind_detail: 0, flags: 0, area: false, min_zoom: 12, min_area_px: 0.0 }+    }++    /// Pushing ways one at a time and pushing the same ways as worker-built blocks must write the+    /// same bytes, report the same counts, and read back the same records both through the+    /// sequential cursor and block by block -- on both backends.+    #[test]+    fn blocks_write_the_same_stream_and_read_back_block_by_block() {+        let dir = std::env::temp_dir().join(format!("mamaps_wayblock_{}", std::process::id()));+        let _ = std::fs::remove_dir_all(&dir);+        std::fs::create_dir_all(&dir).unwrap();+        let mut ways: Vec<(i64, Vec<i64>, Option<String>, u8, Vec<u16>)> = Vec::new();+        let mut id = 7i64;+        for i in 0..10_000i64 {+            id += 1 + (i % 5) * 1000;+            let refs: Vec<i64> = (0..(2 + i % 9)).map(|k| 1_000_000 + i * 3 + k * 17).collect();+            let name = (i % 7 == 0).then(|| format!("Road {i}"));+            ways.push((id, refs, name, (i % 4) as u8, if i % 11 == 0 { vec![1, 4] } else { vec![] }));+        }+        let c = class(tilecodec::mamaps::dict::LAYER_ROADS, 3);+        for anon in [false, true] {+            let one_path = dir.join(format!("one{anon}.tmp"));+            let blk_path = dir.join(format!("blk{anon}.tmp"));+            let plan = if anon { osm_ingest::mem::SpillPlan::Anon } else { osm_ingest::mem::SpillPlan::File };+            let mut one = WaySink::create_planned(&one_path, plan).unwrap();+            let mut blk = WaySink::create_planned(&blk_path, plan).unwrap();+            let mut block = WayBlock::new();+            for (n, (id, refs, name, lanes, turns)) in ways.iter().enumerate() {+                one.push(*id, &c, refs, name.as_deref(), *lanes, turns, &[], Carriageway::default(), None)+                    .unwrap();+                block+                    .push(*id, &c, refs, name.as_deref(), *lanes, turns, &[], Carriageway::default(), None)+                    .unwrap();+                // Uneven block sizes, including one-way blocks, to exercise coalescing.+                if n % 1237 == 0 || block.len() >= 3000 {+                    blk.push_block(&std::mem::take(&mut block)).unwrap();+                }+            }+            blk.push_block(&block).unwrap();+            let (c1, s1) = one.finish_either().unwrap();+            let (c2, s2) = blk.finish_either().unwrap();+            assert_eq!((c1.ways, c1.refs, c1.max_ref), (c2.ways, c2.refs, c2.max_ref));+            let bytes = |path: &Path, s: Option<&tile_build::anon::AnonStore>| -> Vec<u8> {+                match s {+                    Some(a) => {+                        let mut v = vec![0u8; a.len() as usize];+                        a.read_at(0, &mut v).unwrap();+                        v+                    }+                    None => std::fs::read(path).unwrap(),+                }+            };+            let s2 = s2.map(std::sync::Arc::new);+            let b1 = bytes(&one_path, s1.as_ref());+            let b2 = bytes(&blk_path, s2.as_deref());+            assert_eq!(b1, b2, "the block path must write the per-way stream byte for byte");+            for counts in [&c1, &c2] {+                assert!(counts.blocks.iter().all(|l| l.ways <= WAY_BLOCK_WAYS));+                assert_eq!(counts.blocks.iter().map(|l| l.ways).sum::<u64>(), ways.len() as u64);+            }+            // Block-by-block decode equals the sequential cursor, record for record.+            let blocks = WayBlocks::open(&blk_path, &s2, c2.blocks.clone()).unwrap();+            let mut seq = WayReader::open_either(&blk_path, &s2).unwrap();+            let (mut r1, mut r2) = (Vec::new(), Vec::new());+            for i in 0..blocks.locs().len() {+                let mut reader = blocks.reader(i).unwrap();+                let mut n = 0u64;+                while let Some(a) = reader.next(&mut r1).unwrap() {+                    let b = seq.next(&mut r2).unwrap().expect("sequential has as many records");+                    assert_eq!(a.0, b.0);+                    assert_eq!(a.2, b.2);+                    assert_eq!(a.3, b.3);+                    assert_eq!(a.4, b.4);+                    assert_eq!(r1, r2);+                    n += 1;+                }+                assert_eq!(n, blocks.locs()[i].ways);+            }+            assert!(seq.next(&mut r2).unwrap().is_none());+        }+        let _ = std::fs::remove_dir_all(&dir);+    }++    /// The ordering rule holds across a block boundary, not only inside one.+    #[test]+    fn a_block_that_does_not_advance_is_refused() {+        let path = std::env::temp_dir().join(format!("mamaps_wayblock_order_{}.tmp", std::process::id()));+        let c = class(tilecodec::mamaps::dict::LAYER_ROADS, 3);+        let mut sink = WaySink::create_planned(&path, osm_ingest::mem::SpillPlan::Anon).unwrap();+        let mut a = WayBlock::new();+        a.push(10, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).unwrap();+        sink.push_block(&a).unwrap();+        let mut b = WayBlock::new();+        b.push(10, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).unwrap();+        assert!(sink.push_block(&b).is_err());+        assert!(a.push(9, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).is_err());+    }+}++// --- zoom decode for the parallel map reader --------------------------------------------------------++/// The staged features opened for positional, many-thread decoding: one handle shared by every+/// decode thread of [`crate::tiler`]'s map reader.+pub struct ZoomChunks {+    inner: NormalizedChunks,+}++impl Store {+    /// Open the staged bytes for [`ZoomChunks::decode`]. Same backend choice as every other reader.+    pub fn zoom_chunks(&self) -> Result<ZoomChunks> {+        Ok(ZoomChunks { inner: self.open_chunks()? })+    }+}++impl ZoomChunks {+    /// Spill chunk `chunk`'s features that zoom `z` draws, in file order, plus each one's vertex+    /// count. Exactly what a [`ZoomReader`] lane yields for that chunk -- the same `read_into`, the+    /// same `feature_of`, the same zoom window -- so a reader that concatenates these in wanted+    /// order sees the stream `reader_for_zoom` delivers.+    pub fn decode(+        &self,+        chunk: usize,+        z: u8,+        scratch: &mut Vec<u8>,+        records: &mut Vec<tile_build::spill::NormalizedFeature>,+    ) -> Result<(Vec<Feature>, Vec<usize>)> {+        self.inner+            .read_into(chunk, scratch, records)+            .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+        let mut features = Vec::with_capacity(records.len());+        let mut counts = Vec::with_capacity(records.len());+        for record in records.drain(..) {+            let feature = feature_of(record)?;+            // The zoom window: floor is the feature's own `min_zoom`, ceiling the layer cap+            // (`MAX_ZOOM_PER_LAYER`). The same test `ZoomReader`'s lanes apply.+            if z >= feature.class.min_zoom+                && z <= crate::schema::max_zoom_for_layer(feature.class.layer)+            {+                counts.push(geometry_vertices(&feature.geometry));+                features.push(feature);+            }+        }+        Ok((features, counts))+    }+}++/// Every vertex in a geometry, all parts and rings: the measure the map reader cuts chunks by.+pub fn geometry_vertices(geometry: &Geometry) -> usize {+    match geometry {+        Geometry::Points(points) => points.len(),+        Geometry::Lines(lines) => lines.iter().map(Vec::len).sum(),+        Geometry::Polygons(polygons) => polygons.iter().flatten().map(Vec::len).sum(),+    }+}++impl Store {+    /// Every feature in the store, in file order, passed through `keep` on the pool; the kept+    /// values come back in file order.+    ///+    /// The same features [`reader`](Self::reader)'s one sequential cursor yields -- spill chunk by+    /// spill chunk, each read with the same `read_into` and decoded with the same `feature_of` --+    /// but decoded across the pool. For whole-store scans that keep a sliver (the region+    /// fallback's boundary shapes and place labels): on the planet the one-cursor version decoded+    /// 1.35 B features on one thread for 8+ minutes.+    pub fn par_scan<T, F>(&self, keep: F) -> Result<Vec<T>>+    where+        T: Send,+        F: Fn(Feature) -> Option<T> + Sync,+    {+        use rayon::prelude::*;+        let chunks = self.open_chunks()?;+        let n = chunks.chunk_count();+        // Groups bound what is in flight (one `Vec` header per chunk) on a 21 M-chunk planet.+        const GROUP: usize = 1 << 16;+        let mut out = Vec::new();+        let mut start = 0usize;+        while start < n {+            let end = (start + GROUP).min(n);+            let results: Vec<Result<Vec<T>>> = tile_build::par::install(|| {+                (start..end)+                    .into_par_iter()+                    .map_init(+                        || (Vec::new(), Vec::new()),+                        |(scratch, records), i| -> Result<Vec<T>> {+                            chunks+                                .read_into(i, scratch, records)+                                .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+                            let mut kept = Vec::new();+                            for record in records.drain(..) {+                                if let Some(v) = keep(feature_of(record)?) {+                                    kept.push(v);+                                }+                            }+                            Ok(kept)+                        },+                    )+                    .collect()+            });+            for r in results {+                out.extend(r?);+            }+            start = end;+        }+        Ok(out)+    }+}
scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex d6040ac99e..8561f28715 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -62,6 +62,8 @@ fn writer_for(store: &Store, settings: &Settings) -> Result<StreamWriter> {         max_lon_e7: bbox.2,         max_lat_e7: bbox.3,         spill_dir: settings.scratch.parent().map(std::path::Path::to_path_buf),+        // Leaf compression at finish runs on the build's own thread budget.+        threads: par::threads(),         ..Options::default()     }) }@@ -166,15 +168,13 @@ fn tile_zooms(                     .sum::<u64>(),             );             std::thread::scope(|s| -> Result<()> {-                let mut receivers = Vec::with_capacity(merge_workers);+                let queues = crate::tiler::RangeQueues::new(merge_workers);                 // Shared refs are `Copy`: each spawned closure gets its own                 // copy rather than moving `chunks`/`spill` on first use.                 let chunks_ref = &chunks;                 let spill_ref = &spill;                 for r in 0..merge_workers {-                    let (tx, rx) =-                        std::sync::mpsc::sync_channel(crate::tiler::RANGE_QUEUE_BOUND);-                    receivers.push(rx);+                    let tx = queues.sender(r);                     let range_plan = &plan;                     s.spawn(move || {                         crate::tiler::merge_range_into(@@ -188,7 +188,7 @@ fn tile_zooms(                 }                 let mut stream =                     crate::tiler::

Diff truncated.