Modern Apps git

← Modern-Apps.git

maps: read only the coordinates and geometry stage A needs (#perf)

Commit
0c35f6991d94a066fd8e339e4548ece1bb2b2858
Author
Vayun Mathur <[email protected]>
When
2026-11-11 05:36 UTC (25 days ago)
Parents
d86b964
What:
- Lane inheritance (world builds): a way's coordinates are read
  lazily. NodeLocations::indices_if_complete() checks every ref
  resolves using only the in-memory id index and resolved bits;
  lanefill::prepare_lazy() then reads just what the join decides on:
  the bearings leaving each end for a donor, and for a recipient the
  running length until it passes 50 m (a prefix over the limit means
  the whole way is: the sum of non-negative segments only grows).
- Region fallback: Store::par_scan_where() pre-filters each spill
  record on its packed class and id flag, decoding geometry only for
  id-carrying boundary areas and places (NormalizedChunks::
  read_into_where decodes props first, geometry on demand).

Why: on the planet every coordinate read is a random read of an ~80
GB mapped table; lane inheritance read every coordinate of every
named road (134 s) though most are long roads decided after a few
nodes. The region fallback decoded all ~1.35 B features' geometry to
keep a few hundred thousand (71 s).

Byte-identity: prepare_lazy makes prepare()'s decisions in the same
order with the same arithmetic (test
lazy_preparation_matches_preparing_the_whole_line: 20k random ways,
donors/recipients, repeated vertices, closed and nameless ways,
record bytes compared). Region builds keep the full-line path (the
fringe test needs every vertex). The fallback's pre-filter accepts a
superset of what its filter keeps. CA / US West archives identical.

Diff

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 7bf119aac3..43d597805c 100644--- a/scripts/maps/mamaps_build/src/extract_fallback.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -412,7 +412,14 @@ pub fn extend_region_links_with(     // 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| {+    // Pre-filter on the packed class (no geometry decoded): only an id-carrying boundary area+    // or place can pass the filter below.+    let kept = store.par_scan_where(+        |class, has_id| {+            has_id+                && ((class.layer == LAYER_BOUNDARIES && class.area) || class.layer == LAYER_PLACES)+        },+        |feature| {         if feature.id == ID_NONE {             return None;         }
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 a93e55a7f0..ca97bc5e75 100644--- a/scripts/maps/mamaps_build/src/extract_part2.rs+++ b/scripts/maps/mamaps_build/src/extract_part2.rs@@ -374,6 +374,7 @@ fn inherit_lane_counts(         blocks,         |mut reader| -> Result<Vec<crate::lanefill::Prepared>> {             let mut refs: Vec<i64> = Vec::new();+            let mut indices: Vec<usize> = Vec::new();             let mut out = Vec::new();             while let Some((id, class, name, lane_count, _, _, _, _)) = reader.next(&mut refs)? {                 // Roads, and not slip roads. A ramp leaves a junction carrying its parent's name on@@ -385,6 +386,25 @@ fn inherit_lane_counts(                     continue;                 }                 let Some(name) = name else { continue };+                let oneway = class.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0;+                if fringe.is_none() {+                    // World build: no fringe to test, so read only the coordinates the join needs+                    // (`lanefill::prepare_lazy`). A way with an unresolved node is one `prepare`+                    // drops (its line would be shorter than its refs).+                    if table.indices_if_complete(&refs, &mut indices) {+                        if let Some(prepared) = crate::lanefill::prepare_lazy(+                            id,+                            &name,+                            lane_count,+                            oneway,+                            &refs,+                            |i| table.coord_at(indices[i]),+                        ) {+                            out.push(prepared);+                        }+                    }+                    continue;+                }                 let line = table.line(&refs);                 // A region build only joins the fringe: a recipient is at most 50 m long, so                 // a donor sharing an endpoint node with a kept recipient always touches the@@ -393,7 +413,6 @@ fn inherit_lane_counts(                 if !fringe_touches(fringe.as_ref(), &line) {                     continue;                 }-                let oneway = class.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0;                 if let Some(prepared) = crate::lanefill::prepare(&crate::lanefill::Segment {                     id,                     name: &name,
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 3c7e83ea35..2ab6df7b5c 100644--- a/scripts/maps/mamaps_build/src/lanefill.rs+++ b/scripts/maps/mamaps_build/src/lanefill.rs@@ -282,6 +282,66 @@ pub fn prepare(segment: &Segment) -> Option<Prepared> {     Some(Prepared([record(first, head, 0u8), record(last, tail, FLAG_LAST_END)])) } +/// [`prepare`] for a way whose coordinates are read on demand: `coord(i)` is node `i`'s+/// coordinate, valid for every `i < nodes.len()` (the caller has checked every node resolves --+/// `prepare`'s `nodes.len() == line.len()` test).+///+/// The same decisions on the same arithmetic, reading only the coordinates they need: a donor+/// (`lanes > 0`) needs only the bearings leaving its two ends, and a recipient's length test can+/// stop as soon as the running sum passes [`MAX_STUB_M`] -- the sum of non-negative segments only+/// grows, so a prefix over the limit means the whole way is. On the planet every coordinate read+/// is a random read of an ~80 GB table, and lane inheritance read every coordinate of every named+/// road (134 s); most of them are long and decided after a few nodes.+pub fn prepare_lazy(+    id: i64,+    name: &str,+    lanes: u8,+    oneway: bool,+    nodes: &[i64],+    coord: impl Fn(usize) -> (f64, f64),+) -> Option<Prepared> {+    if name.is_empty() || nodes.len() < 2 {+        return None;+    }+    let first = nodes[0];+    let last = nodes[nodes.len() - 1];+    if first == last {+        return None;+    }+    if lanes == 0 {+        // `polyline_length_m`, summed in the same order, stopping once it is decided.+        let mut length = -0.0f64;+        let mut previous = coord(0);+        for i in 1..nodes.len() {+            let p = coord(i);+            let north = (p.1 - previous.1) * METRES_PER_DEGREE;+            let east = (p.0 - previous.0) * METRES_PER_DEGREE * previous.1.to_radians().cos();+            length += (north * north + east * east).sqrt();+            if length > MAX_STUB_M {+                return None;+            }+            previous = p;+        }+    }+    // `leaving`, scanning from each end for the first coordinate that differs.+    let origin = coord(0);+    let head = bearing(origin, (1..nodes.len()).map(&coord).find(|p| *p != origin)?);+    let origin = coord(nodes.len() - 1);+    let tail = bearing(origin, (0..nodes.len() - 1).rev().map(&coord).find(|p| *p != origin)?);++    let name_hash = hash_name(name);+    let base = if oneway { FLAG_ONEWAY } else { 0 };+    let record = |node: i64, bearing: f64, end: u8| Record {+        node,+        way: id,+        name_hash,+        bearing: bearing as f32,+        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>>,@@ -484,4 +544,58 @@ fn deviation(a: f64, b: f64) -> f64 {     (180.0 - delta.abs()).abs() } -include!("lanefill_part1.rs");\ No newline at end of file+include!("lanefill_part1.rs");++#[cfg(test)]+mod lazy_tests {+    use super::*;++    /// `prepare_lazy` decides every way exactly as `prepare` on its full line does: same `None`s,+    /// same records, for donors and recipients, short and long, with repeated vertices at either+    /// end and degenerate ways.+    #[test]+    fn lazy_preparation_matches_preparing_the_whole_line() {+        let mut state = 0x2545_F491_4F6C_DD1Du64;+        let mut next = || {+            state ^= state << 13;+            state ^= state >> 7;+            state ^= state << 17;+            state+        };+        for case in 0..20_000i64 {+            let n = 2 + (next() % 12) as usize;+            let step = [1e-6, 1e-5, 1e-4, 3e-4][(next() % 4) as usize];+            let mut line = Vec::with_capacity(n);+            let (mut x, mut y) = (-122.3 + (next() % 1000) as f64 * 1e-3, 37.5);+            for _ in 0..n {+                if next() % 5 != 0 {+                    x += ((next() % 200) as f64 - 100.0) * step;+                    y += ((next() % 200) as f64 - 100.0) * step;+                }+                line.push((x, y));+            }+            let mut nodes: Vec<i64> = (0..n as i64).map(|k| 1000 + k).collect();+            if case % 9 == 0 {+                let last = nodes.len() - 1;+                nodes[last] = nodes[0];+            }+            let lanes = (next() % 3) as u8;+            let oneway = next() % 2 == 0;+            let name = if case % 13 == 0 { "" } else { "Main St" };+            let whole = prepare(&Segment { id: case, name, lanes, oneway, nodes: &nodes, line: &line });+            let lazy = prepare_lazy(case, name, lanes, oneway, &nodes, |i| line[i]);+            match (whole, lazy) {+                (None, None) => {}+                (Some(a), Some(b)) => {+                    for (ra, rb) in a.0.iter().zip(b.0.iter()) {+                        let (mut ba, mut bb) = (Vec::new(), Vec::new());+                        ra.write(&mut ba).unwrap();+                        rb.write(&mut bb).unwrap();+                        assert_eq!(ba, bb, "case {case}");+                    }+                }+                (a, b) => panic!("case {case}: whole {} lazy {}", a.is_some(), b.is_some()),+            }+        }+    }+}
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.rsindex 3e3e3e871d..cb02712e23 100644--- a/scripts/maps/mamaps_build/src/store_part6.rs+++ b/scripts/maps/mamaps_build/src/store_part6.rs@@ -688,6 +688,27 @@ impl Store {         T: Send,         F: Fn(Feature) -> Option<T> + Sync,     {+        self.par_scan_where(|_, _| true, keep)+    }++    /// [`par_scan`](Self::par_scan) with a cheap pre-filter on each record's packed class and+    /// whether it carries a feature id: records it rejects are never turned into features (their+    /// geometry is never decoded), so it must accept every record `keep` could keep.+    pub fn par_scan_where<T, P, F>(&self, pre: P, keep: F) -> Result<Vec<T>>+    where+        T: Send,+        P: Fn(&Class, bool) -> bool + Sync,+        F: Fn(Feature) -> Option<T> + Sync,+    {+        let pre = |props: &[(String, Value)]| -> bool {+            let class = props.iter().find_map(|(k, v)| match (k.as_str(), v) {+                (CLASS_KEY, Value::Uint(bits)) => Some(unpack(*bits)),+                _ => None,+            });+            // A record with no class is corrupt: let it through so `feature_of` reports it.+            let Some(class) = class else { return true };+            pre(&class, props.iter().any(|(k, _)| k == ID_KEY))+        };         use rayon::prelude::*;         let chunks = self.open_chunks()?;         let n = chunks.chunk_count();@@ -704,7 +725,7 @@ impl Store {                         || (Vec::new(), Vec::new()),                         |(scratch, records), i| -> Result<Vec<T>> {                             chunks-                                .read_into(i, scratch, records)+                                .read_into_where(i, scratch, records, &pre)                                 .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;                             let mut kept = Vec::new();                             for record in records.drain(..) {
scripts/maps/osm_ingest/src/nodeloc.rs
diff --git a/scripts/maps/osm_ingest/src/nodeloc.rs b/scripts/maps/osm_ingest/src/nodeloc.rsindex d57db8c88d..c9319b22f6 100644--- a/scripts/maps/osm_ingest/src/nodeloc.rs+++ b/scripts/maps/osm_ingest/src/nodeloc.rs@@ -110,6 +110,10 @@ impl Locs {         self.resolved[index / 64] |= 1 << (index % 64);     } +    fn is_resolved(&self, index: usize) -> bool {+        index < self.len && self.resolved[index / 64] & (1 << (index % 64)) != 0+    }+     fn get(&self, index: usize) -> Option<(i32, i32)> {         if index >= self.len || self.resolved[index / 64] & (1 << (index % 64)) == 0 {             return None;@@ -449,6 +453,28 @@ impl NodeLocations {         self.locs.get(self.index_of(id)? as usize)     } +    /// Every ref's table index into `out` (cleared first), `false` as soon as one ref has no+    /// coordinate -- exactly the refs [`Self::line`] would drop. Reads only the in-memory id index+    /// and resolved bits, never the coordinate array: a caller that needs only some of a way's+    /// coordinates (its ends, or a prefix) can then read just those with [`Self::coord_at`].+    pub fn indices_if_complete(&self, refs: &[i64], out: &mut Vec<usize>) -> bool {+        out.clear();+        for &id in refs {+            match self.index_of(id) {+                Some(i) if self.locs.is_resolved(i as usize) => out.push(i as usize),+                _ => return false,+            }+        }+        true+    }++    /// The coordinate at a table index [`Self::indices_if_complete`] returned, in the same+    /// `(lon, lat)` degrees [`Self::line`] produces.+    pub fn coord_at(&self, index: usize) -> Coord {+        let (lat_e7, lon_e7) = self.locs.get(index).expect("a resolved index");+        (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7)+    }+     /// A way's geometry in lon/lat order, with unresolved refs skipped.     ///     /// A ref can be unresolved for a legitimate reason: an extract cut through the
scripts/maps/tile_build/src/spill_part2.rs
diff --git a/scripts/maps/tile_build/src/spill_part2.rs b/scripts/maps/tile_build/src/spill_part2.rsindex 9704ceb90f..37dd79401c 100644--- a/scripts/maps/tile_build/src/spill_part2.rs+++ b/scripts/maps/tile_build/src/spill_part2.rs@@ -1136,6 +1136,70 @@ impl NormalizedChunks {     /// The chunk span covers one compressed frame: it is read whole, inflated, and decoded     /// with the same [`decode_chunk_records`] the sequential reader uses, so the two paths     /// cannot diverge on what they accept.+    /// [`read_into`](Self::read_into), keeping only the records whose properties pass `keep` --+    /// and decoding the geometry of those alone. For whole-spill scans that want a sliver of it+    /// (the region fallback keeps boundary shapes and place labels out of ~1.35 B planet+    /// features): the properties sit after the geometry in each record and are a few bytes, the+    /// geometry is most of the decode. Kept records come back exactly as `read_into` yields them.+    pub fn read_into_where(+        &self,+        i: usize,+        scratch: &mut Vec<u8>,+        out: &mut Vec<NormalizedFeature>,+        keep: &dyn Fn(&[(String, Value)]) -> bool,+    ) -> Result<()> {+        out.clear();+        let mut all = Vec::new();+        // Inflate through `read_into`'s own path, then walk the raw records here.+        let (Some(&start), Some(&end)) = (self.chunks.get(i), self.chunks.get(i + 1)) else {+            return self.read_into(i, scratch, &mut all);+        };+        if end < start {+            return self.read_into(i, scratch, &mut all);+        }+        scratch.clear();+        scratch.resize((end - start) as usize, 0);+        match (&self.file, &self.anon) {+            (Some(f), None) => crate::pmtiles::read_exact_at(f, scratch, start).map_err(|e| {+                Error(format!("reading normalized chunk {i} of {}: {e}", self.path.display()))+            })?,+            (None, Some(a)) => a.read_at(start, scratch).map_err(|e| {+                Error(format!("reading normalized chunk {i} of {}: {e}", self.path.display()))+            })?,+            _ => return err("a normalized chunk reader has no backend".to_string()),+        }+        let raw = inflate_frame(i, &self.path, scratch)?;+        let mut at = 0usize;+        while at < raw.len() {+            if raw.len() - at < NORM_HEADER_BYTES {+                return err(format!(+                    "normalized chunk {i} of {} ends inside a record header",+                    self.path.display()+                ));+            }+            let head: &[u8; NORM_HEADER_BYTES] =+                raw[at..at + NORM_HEADER_BYTES].try_into().expect("a header's worth of bytes");+            let (geom_len, props_len, kind) = norm_header(head)?;+            let body = at + NORM_HEADER_BYTES;+            let rec_end = body + geom_len + props_len;+            if rec_end > raw.len() {+                return err(format!(+                    "normalized chunk {i} of {} holds a record running past its end",+                    self.path.display()+                ));+            }+            let props = decode_props(&raw[body + geom_len..rec_end])?;+            if keep(&props) {+                out.push(NormalizedFeature {+                    geometry: decode_geometry(kind, &raw[body..body + geom_len])?,+                    props,+                });+            }+            at = rec_end;+        }+        Ok(())+    }+     pub fn read_into(         &self,         i: usize,