Modern Apps git

← Modern-Apps.git

maps: parallelize poi_extract's serial stages, 17.9s -> 1.6s on CA (#perf)

Commit
a00077575496f4a6cf9b5af3514975748e90ff98
Author
Vayun Mathur <[email protected]>
When
2026-11-10 19:11 UTC (25 days ago)
Parents
cecc075
What: poi_extract spent ~90% of a California run on one thread. The
three PBF passes were already parallel; everything after them was not.
This makes every post-pass stage parallel (or overlapped) on the
crate's own rayon pool (par::install, so --threads/MAPS_THREADS still
govern it) without changing a single output byte.

Root cause, measured with new per-stage TIMING subphases on CA
(192 threads, baseline-bin poi_extract, 17.9 s wall):
  - regions-stamp 11.93 s: the admin-boundary containment test ran
    rings::point_in_ring over EVERY vertex of every candidate ring
    (state/county rings are 1e4-1e5 vertices) for every POI, serially.
  - review table load 2.06 s: 400 MB TSV parsed serially in main,
    in front of the passes, though it is not needed until after them.
  - write-nameidx 1.40 s: the name-index sort comparator re-split
    both names with word_at() on every comparison, serially.
  - write-main 0.33 s, centroids 0.29 s, sort 0.03 s: serial.

Changes (all POI-specific code; no shared module touched):
  - poi_build_part3.rs (new, include!d): RingIndex, a latitude-band
    CSR of edges per ring. A probe walks only edges whose y-span
    covers its latitude. Exact: an edge can toggle the ray-cast parity
    only if min(y1,y2) <= y < max(y1,y2); band() is monotone in y, so
    such an edge is always filed under band(y), and the toggle test is
    the original expression operand for operand (parity is an XOR, so
    visiting a subset in another order gives the same bit). A property
    test pins it to rings::point_in_ring on 30k probes incl. probes on
    vertex latitudes. Stamping runs per-POI in parallel chunks; the
    three conjuncts are reordered cheapest-first (all pure). Boundary
    assembly runs per boundary in parallel, collected in id order.
  - poi_reviews.rs: parallel line-aligned chunk parse; global line
    numbers and first-error semantics preserved; storage is now a
    sorted Vec deduped keep-last (== HashMap insert in file order).
    Tests pin it to the old serial HashMap parse for many chunk sizes.
  - poi_extract.rs / poi_build.rs: build_with_review_loader joins a
    loader thread right before reviews apply; a failed load is
    noticed between passes so a bad table still fails early.
    build_with / build_with_reviews keep their signatures (mamaps_build
    --build-poi-to calls build_with; behaviour unchanged).
  - poi_side.rs: name index entries carry their word's byte range, so
    the (still total-order) comparator compares slices; parallel
    unstable sort (keys unique => identical order). Spatial pairs sort
    in parallel. Both files written from one buffer.
  - poi_build_part1.rs: the 7 output files are written by 6 concurrent
    tasks (each file by exactly one task, all from the same sorted
    slice); geojson lines are formatted in parallel batches and written
    in order through 8 MiB buffers. Centroids, apply_reviews, the
    needed/outer_wanted dedups and the Morton sort (par_sort_by_key is
    stable, like sort_by_key) are parallel.

Verified (California, --region california, planet reviews TSV):
  - sha256 of all 7 outputs identical to ~/planet-opt/baseline-bin/
    poi_extract, at --threads 1, 8, 192 and MAPS_THREADS=8.
  - wall 17.9 s -> 1.55 s median of 5 (11.5x); regions-stamp
    11.93 s -> 0.008 s (0.45 s even at --threads 1); nameidx
    1.40 s -> folded into a 0.16 s concurrent write.
  - peak RSS 1.42 GB -> ~1.65 GB (review table held during passes,
    band index, 16 B name-index entries).
  - cargo test --release -p osm_ingest: 301 + 2 pass.

Diff

scripts/maps/osm_ingest/src/bin/poi_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/poi_extract.rs b/scripts/maps/osm_ingest/src/bin/poi_extract.rsindex 811ae7707a..b19f26f014 100644--- a/scripts/maps/osm_ingest/src/bin/poi_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/poi_extract.rs@@ -22,30 +22,49 @@ fn main() -> ExitCode {         osm_ingest::par::set_threads(n);     } -    let reviews = match args.reviews.as_deref().map(osm_ingest::poi_reviews::ReviewTable::load) {-        Some(Ok(table)) => {-            println!("Loaded {} review row(s)", table.len());-            Some(table)-        }-        Some(Err(e)) => {-            eprintln!("ERROR: {e}");-            return ExitCode::FAILURE;-        }-        None => None,+    // The review table is parsed on its own thread while the PBF passes run;+    // `build_with_review_loader` joins it right before the reviews are applied.+    let loader = args.reviews.clone().map(|path| {+        std::thread::spawn(move || {+            let t = std::time::Instant::now();+            let table = osm_ingest::poi_reviews::ReviewTable::load(&path);+            eprintln!("[poi] review table loaded in {:.3}s", t.elapsed().as_secs_f64());+            table+        })+    });+    let have_reviews = loader.is_some();+    let on_loaded = |table: &osm_ingest::poi_reviews::ReviewTable| {+        println!("Loaded {} review row(s)", table.len());     }; -    match osm_ingest::poi_build::build_with_reviews(-        &args.input,-        &args.geojson,-        &args.names,-        &args.index,-        &args.attrs,-        &args.spatial,-        &args.name_index,-        &args.region,-        args.bbox,-        reviews.as_ref(),-    ) {+    let result = match loader {+        Some(loader) => osm_ingest::poi_build::build_with_review_loader(+            &args.input,+            &args.geojson,+            &args.names,+            &args.index,+            &args.attrs,+            &args.spatial,+            &args.name_index,+            &args.region,+            args.bbox,+            loader,+            &on_loaded,+        ),+        None => osm_ingest::poi_build::build_with_reviews(+            &args.input,+            &args.geojson,+            &args.names,+            &args.index,+            &args.attrs,+            &args.spatial,+            &args.name_index,+            &args.region,+            args.bbox,+            None,+        ),+    };+    match result {         Ok(stats) => {             println!(                 "{} POI(s) ({} node, {} closed-way, {} relation), {} unique name(s) \@@ -61,7 +80,7 @@ fn main() -> ExitCode {                 "{} POI(s) with attributes, {} unique record(s), {} sidecar byte(s)",                 stats.with_attrs, stats.unique_attrs, stats.attr_bytes             );-            if reviews.is_some() {+            if have_reviews {                 println!("{} POI(s) with review data", stats.with_reviews);             }             println!(
scripts/maps/osm_ingest/src/poi_build.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build.rs b/scripts/maps/osm_ingest/src/poi_build.rsindex 0c3f9dcf84..b385fbb2da 100644--- a/scripts/maps/osm_ingest/src/poi_build.rs+++ b/scripts/maps/osm_ingest/src/poi_build.rs@@ -212,6 +212,120 @@ pub fn build_with_reviews(     region: &Path,     bbox: Option<crate::bbox::BBox>,     reviews: Option<&ReviewTable>,+) -> Result<Stats> {+    build_inner(+        input,+        geojson,+        names,+        index,+        attrs,+        spatial,+        name_index,+        region,+        bbox,+        match reviews {+            Some(t) => Reviews::Ready(t),+            None => Reviews::None,+        },+    )+}++/// A review table still being loaded on another thread; see+/// [`build_with_review_loader`].+pub type ReviewLoader = std::thread::JoinHandle<Result<ReviewTable>>;++/// [`build_with_reviews`], with the table still loading on `loader`'s thread.+///+/// The table is ~400 MB of TSV on a planet build and is not needed until after+/// the three PBF passes, so loading it up front serialised a second-scale parse+/// in front of the whole run. The join happens right before the reviews are+/// applied; a loader that has already failed is noticed between passes, so a bad+/// table still fails the run early rather than after the node pass.+///+/// `on_loaded` runs once with the joined table (the binary prints its row+/// count there).+#[allow(clippy::too_many_arguments)]+pub fn build_with_review_loader(+    input: &Path,+    geojson: &Path,+    names: &Path,+    index: &Path,+    attrs: &Path,+    spatial: &Path,+    name_index: &Path,+    region: &Path,+    bbox: Option<crate::bbox::BBox>,+    loader: ReviewLoader,+    on_loaded: &dyn Fn(&ReviewTable),+) -> Result<Stats> {+    build_inner(+        input,+        geojson,+        names,+        index,+        attrs,+        spatial,+        name_index,+        region,+        bbox,+        Reviews::Loading(Some(loader), on_loaded, None),+    )+}++/// Where the review table comes from.+enum Reviews<'a> {+    None,+    Ready(&'a ReviewTable),+    /// The loader (until joined), the joined-callback, and the joined table.+    Loading(Option<ReviewLoader>, &'a dyn Fn(&ReviewTable), Option<ReviewTable>),+}++impl Reviews<'_> {+    /// Join the loader if it has already finished, so a failed load surfaces now.+    fn poll(&mut self) -> Result<()> {+        if let Reviews::Loading(h, _, _) = self {+            if h.as_ref().is_some_and(|h| h.is_finished()) {+                return self.join();+            }+        }+        Ok(())+    }++    /// Block until the table is loaded (no-op unless loading).+    fn join(&mut self) -> Result<()> {+        if let Reviews::Loading(h, cb, table) = self {+            if let Some(h) = h.take() {+                let t = h+                    .join()+                    .map_err(|_| Error("the review loader panicked".into()))??;+                cb(&t);+                *table = Some(t);+            }+        }+        Ok(())+    }++    fn table(&self) -> Option<&ReviewTable> {+        match self {+            Reviews::None => None,+            Reviews::Ready(t) => Some(t),+            Reviews::Loading(_, _, t) => t.as_ref(),+        }+    }+}++#[allow(clippy::too_many_arguments)]+fn build_inner(+    input: &Path,+    geojson: &Path,+    names: &Path,+    index: &Path,+    attrs: &Path,+    spatial: &Path,+    name_index: &Path,+    region: &Path,+    bbox: Option<crate::bbox::BBox>,+    mut reviews: Reviews<'_>, ) -> Result<Stats> {     // Fail before the three passes rather than after them if an output path is     // unwritable.@@ -248,9 +362,9 @@ pub fn build_with_reviews(         .flat_map(|a| a.outer_ways.iter().copied())         .chain(boundaries.iter().flat_map(|b| b.member_ways.iter().map(|(w, _)| *w)))         .collect();-    outer_wanted.sort_unstable();-    outer_wanted.dedup();+    par_sort_dedup(&mut outer_wanted);     println!("{} POI relation(s)", rel_areas.len());+    reviews.poll()?;      timer.switch("ways");     // --- Pass 2: closed-way areas + the relations' outer ways ----------------@@ -276,14 +390,14 @@ pub fn build_with_reviews(         .flat_map(|a| a.refs.iter().copied())         .chain(outer_refs.values().flat_map(|r| r.iter().copied()))         .collect();-    needed.sort_unstable();-    needed.dedup();+    par_sort_dedup(&mut needed);     println!(         "{} closed-way area(s), {} node location(s) needed",         way_areas.len(),         needed.len()     ); +    reviews.poll()?;     timer.switch("nodes");     // --- Pass 3: node POIs + the node locations areas need -------------------     let (chunks, _) = pbf::run_pass(@@ -324,55 +438,69 @@ pub fn build_with_reviews(      timer.switch("centroids");     // --- Area centroids -------------------------------------------------------    for area in &way_areas {-        if !touches(&mut area.refs.iter().copied()) {-            continue;-        }-        // A closed way's ring is its own node list minus the repeated closing-        // node.-        if let Some(poi) = ring_centroid(area.refs[..area.refs.len() - 1].iter().copied(), &location)-        {-            pois.push(make_poi(-                poi,-                area.type_,-                area.id,-                &area.name,-                area.attrs.clone(),-                area.self_region,-                area.place_cap,-            ));-        }-    }+    // Each area's POI depends on that area alone; `collect` keeps area order, so+    // `pois` comes out exactly as the serial loop pushed it.+    use rayon::prelude::*;+    let way_pois: Vec<Option<Poi>> = crate::par::install(|| {+        way_areas+            .par_iter()+            .with_min_len(256)+            .map(|area| {+                if !touches(&mut area.refs.iter().copied()) {+                    return None;+                }+                // A closed way's ring is its own node list minus the repeated+                // closing node.+                let poi = ring_centroid(area.refs[..area.refs.len() - 1].iter().copied(), &location)?;+                Some(make_poi(+                    poi,+                    area.type_,+                    area.id,+                    &area.name,+                    area.attrs.clone(),+                    area.self_region,+                    area.place_cap,+                ))+            })+            .collect()+    });+    pois.extend(way_pois.into_iter().flatten());     let from_ways = pois.len() - from_nodes; -    for area in &rel_areas {-        // libosmium assembled a true ring from the member ways; we cannot, so-        // deduplicate the member node ids instead. That is exact when the outer-        // ring is a single closed way, and drops the endpoints shared between-        // consecutive ways when it is split across several.-        let mut refs: Vec<i64> = area-            .outer_ways-            .iter()-            .filter_map(|w| outer_refs.get(w))-            .flat_map(|r| r.iter().copied())-            .collect();-        refs.sort_unstable();-        refs.dedup();-        if !touches(&mut refs.iter().copied()) {-            continue;-        }-        if let Some(poi) = ring_centroid(refs.iter().copied(), &location) {-            pois.push(make_poi(-                poi,-                area.type_,-                -area.id,-                &area.name,-                area.attrs.clone(),-                area.self_region,-                area.place_cap,-            ));-        }-    }+    let rel_pois: Vec<Option<Poi>> = crate::par::install(|| {+        rel_areas+            .par_iter()+            .with_max_len(16)+            .map(|area| {+                // libosmium assembled a true ring from the member ways; we cannot,+                // so deduplicate the member node ids instead. That is exact when+                // the outer ring is a single closed way, and drops the endpoints+                // shared between consecutive ways when it is split across several.+                let mut refs: Vec<i64> = area+                    .outer_ways+                    .iter()+                    .filter_map(|w| outer_refs.get(w))+                    .flat_map(|r| r.iter().copied())+                    .collect();+                refs.sort_unstable();+                refs.dedup();+                if !touches(&mut refs.iter().copied()) {+                    return None;+                }+                let poi = ring_centroid(refs.iter().copied(), &location)?;+                Some(make_poi(+                    poi,+                    area.type_,+                    -area.id,+                    &area.name,+                    area.attrs.clone(),+                    area.self_region,+                    area.place_cap,+                ))+            })+            .collect()+    });+    pois.extend(rel_pois.into_iter().flatten());     let from_relations = pois.len() - from_nodes - from_ways;     println!(         "Extracted {} POI(s): {from_nodes} node, {from_ways} closed-way, {from_relations} relation",@@ -381,7 +509,10 @@ pub fn build_with_reviews(      // Before the sort: `pois` is still nodes, then ways, then relations, which is     // the only place the OSM element type is known.-    let with_reviews = match reviews {+    timer.switch("reviews-wait");+    reviews.join()?;+    timer.switch("reviews");+    let with_reviews = match reviews.table() {         Some(table) => {             let n = apply_reviews(&mut pois, from_nodes, from_ways, table);             println!("{n} POI(s) with review data ({} review row(s) loaded)", table.len());@@ -394,7 +525,10 @@ pub fn build_with_reviews(     // the only place the OSM element type is known. Region links resolve here     // for the same reason reviews do — and the stamped ids ride the Morton sort     // on the `Poi` struct, so `poi_region.bin` joins by ordinal afterwards.-    let with_region = resolve_regions(&mut pois, from_nodes, &boundaries, &outer_refs, &location);+    timer.switch("regions-assemble");+    let assembled = assemble_boundaries(&boundaries, &outer_refs, &location);+    timer.switch("regions-stamp");+    let with_region = stamp_regions(&mut pois, from_nodes, &boundaries, &assembled);     if with_region > 0 {         println!("{with_region} POI(s) with a boundary link");     }@@ -402,10 +536,11 @@ pub fn build_with_reviews(     // Morton order, ties broken by osm_id, so both poi_index.bin and the geojson     // are stable across runs.     timer.switch("sort");-    pois.sort_by_key(|p| (p.morton, p.osm_id));+    // `par_sort_by_key` is stable like `sort_by_key`, so equal keys keep the+    // pre-sort (nodes, ways, relations) order exactly as before.+    crate::par::install(|| pois.par_sort_by_key(|p| (p.morton, p.osm_id))); -    timer.switch("write");-    let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index, region)?;+    let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index, region, &mut timer)?;     timer.finish();     Ok(Stats {         records: written.records,@@ -428,163 +563,40 @@ pub fn build_with_reviews( /// count. `pois[..from_nodes]` are nodes, the next `from_ways` closed ways, the /// rest relations (whose `osm_id` is stored negated). fn apply_reviews(pois: &mut [Poi], from_nodes: usize, from_ways: usize, table: &ReviewTable) -> usize {-    let mut matched = 0;-    for (i, p) in pois.iter_mut().enumerate() {-        let (element, id) = if i < from_nodes {-            (ELEMENT_NODE, p.osm_id)-        } else if i < from_nodes + from_ways {-            (ELEMENT_WAY, p.osm_id)-        } else {-            (ELEMENT_RELATION, -p.osm_id)-        };-        if let Some(review) = table.get(element, id) {-            p.attrs = crate::poi_attrs::append(std::mem::take(&mut p.attrs), &review.fields());-            matched += 1;-        }-    }-    matched-}--/// One assembled boundary: its polygons, each exterior ring's absolute area-/// (smallest-wins needs no sign), its bbox, and its tagged link.-struct BoundaryPoly {-    tagged: u64,-    admin_level: u8,-    polys: Vec<rings::Polygon>,-    areas: Vec<f64>,-    min_lon: f64,-    min_lat: f64,-    max_lon: f64,-    max_lat: f64,-}--/// Stamp every POI's [`Poi::region`]: self-links are already set, a node carried-/// as a boundary's `label`/`admin_centre` member takes that boundary's tagged id,-/// otherwise the smallest-area containing admin at or above the POI's-/// place-implied cap wins. Returns the stamped count.-///-/// `pois[..from_nodes]` are nodes, which is the only slice the member-link map-/// can hit — node ids and way/relation ids share a namespace per element type,-/// and a way id equal to a label node id is a different object.-///-/// Containment runs through a coarse 1°-cell grid over boundary bboxes, so a-/// planet build tests each POI only against the boundaries whose bbox covers it-/// instead of every admin relation on earth.-fn resolve_regions<L>(-    pois: &mut [Poi],-    from_nodes: usize,-    boundaries: &[BoundaryRel],-    outer_refs: &HashMap<i64, Vec<i64>>,-    location: &L,-) -> usize-where-    L: Fn(i64) -> Option<(i32, i32)>,-{-    // Deterministic on double-labelling: the lowest boundary id wins.-    let mut ordered: Vec<&BoundaryRel> = boundaries.iter().collect();-    ordered.sort_by_key(|b| b.id);-    let mut labels: HashMap<i64, u64> = HashMap::new();-    for b in &ordered {-        let tagged = poi_side::tag_relation(b.id);-        for n in &b.label_nodes {-            labels.entry(*n).or_insert(tagged);-        }-    }--    let locate = |id: i64| -> Option<Coord> {-        location(id).map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7))-    };-    let mut assembled: Vec<BoundaryPoly> = Vec::new();-    let mut ring_stats = RingStats::default();-    for b in &ordered {-        let members: Vec<MemberWay> = b-            .member_ways-            .iter()-            .map(|(w, outer)| MemberWay {-                refs: outer_refs.get(w).cloned().unwrap_or_default(),-                outer: *outer,-            })-            .collect();-        let polys = rings::assemble(&members, &locate, &mut ring_stats);-        if polys.is_empty() {-            continue;-        }-        let (mut min_lon, mut min_lat) = (f64::INFINITY, f64::INFINITY);-        let (mut max_lon, mut max_lat) = (f64::NEG_INFINITY, f64::NEG_INFINITY);-        let mut areas = Vec::with_capacity(polys.len());-        for poly in &polys {-            areas.push(rings::ring_area(&poly[0]).abs());-            for ring in poly {-                for &(lon, lat) in ring {-                    min_lon = min_lon.min(lon);-                    min_lat = min_lat.min(lat);-                    max_lon = max_lon.max(lon);-                    max_lat = max_lat.max(lat);+    use rayon::prelude::*;+    // Per-POI and independent, so chunking cannot change any POI's body.+    crate::par::install(|| {+        pois.par_iter_mut()+            .enumerate()+            .with_min_len(4096)+            .map(|(i, p)| {+                let (element, id) = if i < from_nodes {+                    (ELEMENT_NODE, p.osm_id)+                } else if i < from_nodes + from_ways {+                    (ELEMENT_WAY, p.osm_id)+                } else {+                    (ELEMENT_RELATION, -p.osm_id)+                };+                match table.get(element, id) {+                    Some(review) => {+                        p.attrs =+                            crate::poi_attrs::append(std::mem::take(&mut p.attrs), &review.fields());+                        true+                    }+                    None => false,                 }-            }-        }-        assembled.push(BoundaryPoly {-            tagged: poi_side::tag_relation(b.id),-            admin_level: b.admin_level,-            polys,-            areas,-            min_lon,-            min_lat,-            max_lon,-            max_lat,-        });-    }--    let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();-    for (i, b) in assembled.iter().enumerate() {-        for cx in b.min_lon.floor() as i32..=b.max_lon.floor() as i32 {-            for cy in b.min_lat.floor() as i32..=b.max_lat.floor() as i32 {-                grid.entry((cx, cy)).or_default().push(i);-            }-        }-    }+            })+            .filter(|hit| *hit)+            .count()+    })+} -    let mut matched = 0;-    for (i, p) in pois.iter_mut().enumerate() {-        if p.region != poi_side::REGION_NONE {-            matched += 1;-            continue;-        }-        // Member links win over containment.-        if i < from_nodes {-            if let Some(tagged) = labels.get(&p.osm_id) {-                p.region = *tagged;-                matched += 1;-                continue;-            }-        }-        let lon = p.lon_e7 as f64 * 1e-7;-        let lat = p.lat_e7 as f64 * 1e-7;-        let Some(cands) = grid.get(&(lon.floor() as i32, lat.floor() as i32)) else {-            continue;-        };-        let mut best: Option<(f64, u64)> = None;-        for bi in cands {-            let b = &assembled[*bi];-            if b.admin_level > p.place_cap {-                continue;-            }-            for (poly, area) in b.polys.iter().zip(&b.areas) {-                // Holes excluded: inside an inner ring is not inside the admin.-                if rings::point_in_ring((lon, lat), &poly[0])-                    && !poly[1..].iter().any(|h| rings::point_in_ring((lon, lat), h))-                    && best.is_none_or(|(a, _)| *area < a)-                {-                    best = Some((*area, b.tagged));-                }-            }-        }-        if let Some((_, tagged)) = best {-            p.region = tagged;-            matched += 1;-        }-    }-    matched+/// Sort ascending and drop duplicates. The values are plain integers, so an+/// unstable parallel sort yields exactly the serial `sort_unstable` + `dedup`.+fn par_sort_dedup(v: &mut Vec<i64>) {+    use rayon::prelude::*;+    crate::par::install(|| v.par_sort_unstable());+    v.dedup(); }  fn poi_tags<'a>(t: &osm::Tags<'_, 'a>) -> PoiTags<'a> {@@ -820,4 +832,5 @@ where }  include!("poi_build_part1.rs");-include!("poi_build_part2.rs");\ No newline at end of file+include!("poi_build_part2.rs");+include!("poi_build_part3.rs");\ No newline at end of file
scripts/maps/osm_ingest/src/poi_build_part1.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build_part1.rs b/scripts/maps/osm_ingest/src/poi_build_part1.rsindex 4f520e49e4..0fcd1f2cb1 100644--- a/scripts/maps/osm_ingest/src/poi_build_part1.rs+++ b/scripts/maps/osm_ingest/src/poi_build_part1.rs@@ -37,6 +37,17 @@ struct Written {     name_entries: usize, } +/// Output buffer size. Large sequential writes: the build box's root is btrfs+/// with `compress-force=zstd`, which pays per extent, and a default 8 KiB+/// `BufWriter` turns a multi-GB geojson into a million small writes.+const WRITE_BUF: usize = 8 << 20;++/// POIs formatted per parallel geojson batch. Bounds the formatted text held at+/// once (~0.3 KB a line) while giving every thread plenty of chunks.+const GEOJSON_BATCH: usize = 1 << 18;+const GEOJSON_CHUNK: usize = 2048;++#[allow(clippy::too_many_arguments)] fn write_outputs(     pois: &[Poi],     geojson: &Path,@@ -46,66 +57,65 @@ fn write_outputs(     spatial: &Path,     name_index: &Path,     region: &Path,+    timer: &mut crate::timing::PhaseTimer, ) -> Result<Written> {-    let mut pool = NamePool::new(BufWriter::new(create(names)?));-    let mut index_out = BufWriter::new(create(index)?);-    let mut geojson_out = BufWriter::new(create(geojson)?);-    // The sidecar is indexed by record ordinal, so it is filled in this same loop-    // over the same Morton-sorted vector. Any second pass over `pois` would be an-    // opportunity for the two files to disagree.-    let mut attr_pool = AttrPool::new();-    let mut line: Vec<u8> = Vec::new();--    for p in pois {-        let off = pool.intern(&p.name).map_err(io_err)?;-        index_out.write_all(&p.lat_e7.to_le_bytes()).map_err(io_err)?;-        index_out.write_all(&p.lon_e7.to_le_bytes()).map_err(io_err)?;-        index_out.write_all(&off.to_le_bytes()).map_err(io_err)?;-        index_out.write_all(&p.type_.to_le_bytes()).map_err(io_err)?;-        attr_pool.push(&p.attrs).map_err(io_err)?;--        line.clear();-        write!(-            line,-            "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"Point\",\"coordinates\":[{:.7},{:.7}]}},\"properties\":{{\"name\":\"",-            p.lon, p.lat+    // All seven files are pure functions of the Morton-sorted `pois`, and each is+    // written by exactly one task, so running the tasks side by side cannot change a+    // byte of any of them. They still join by record ordinal because every one of+    // them walks the same slice in the same order — the property the single serial+    // loop used to guarantee.+    timer.switch("write");+    let (r_names, r_geojson, r_attrs, r_spatial, r_name_index, r_region) = {+        let mut r_names = None;+        let mut r_geojson = None;+        let mut r_attrs = None;+        let mut r_spatial = None;+        let mut r_name_index = None;+        let mut r_region = None;+        crate::par::install(|| {+            rayon::scope(|sc| {+                sc.spawn(|_| r_names = Some(write_names_and_index(pois, names, index)));+                sc.spawn(|_| r_geojson = Some(write_geojson(pois, geojson)));+                sc.spawn(|_| r_attrs = Some(write_attrs(pois, attrs)));+                sc.spawn(|_| {+                    r_spatial = Some(write_with(spatial, |out| {+                        let coords: Vec<(i32, i32)> =+                            pois.iter().map(|p| (p.lat_e7, p.lon_e7)).collect();+                        poi_side::write_spatial(out, &coords)+                    }))+                });+                sc.spawn(|_| {+                    r_name_index = Some(write_with(name_index, |out| {+                        let name_slices: Vec<&[u8]> = pois.iter().map(|p| p.name.as_slice()).collect();+                        poi_side::write_name_index(out, &name_slices)+                    }))+                });+                sc.spawn(|_| {+                    r_region = Some(write_with(region, |out| {+                        let region_ids: Vec<u64> = pois.iter().map(|p| p.region).collect();+                        poi_side::write_region(out, &region_ids)+                    }))+                });+            })+        });+        let done = "every write task ran";+        (+            r_names.expect(done),+            r_geojson.expect(done),+            r_attrs.expect(done),+            r_spatial.expect(done),+            r_name_index.expect(done),+            r_region.expect(done),         )-        .map_err(io_err)?;-        json_escape(&p.name, &mut line);-        writeln!(line, "\",\"type\":{},\"osm_id\":{}}}}}", p.type_, p.osm_id).map_err(io_err)?;-        geojson_out.write_all(&line).map_err(io_err)?;-    }--    let mut attrs_out = BufWriter::new(create(attrs)?);-    attr_pool.write(&mut attrs_out).map_err(io_err)?;-    attrs_out.flush().map_err(io_err)?;--    // Both side files are derived from the same Morton-sorted vector as the index, in-    // the same function, for the same reason the sidecar is: they join by record-    // ordinal, and any second pass over `pois` is an opportunity to disagree.-    let coords: Vec<(i32, i32)> = pois.iter().map(|p| (p.lat_e7, p.lon_e7)).collect();-    let mut spatial_out = BufWriter::new(create(spatial)?);-    let spatial_cells = poi_side::write_spatial(&mut spatial_out, &coords).map_err(io_err)?;-    spatial_out.flush().map_err(io_err)?;+    };+    // Errors surface in the order the serial writer would have hit them.+    let (unique, bytes) = r_names?;+    r_geojson?;+    let attr_pool = r_attrs?;+    let spatial_cells = r_spatial?;+    let name_entries = r_name_index?;+    r_region?; -    let name_slices: Vec<&[u8]> = pois.iter().map(|p| p.name.as_slice()).collect();-    let mut name_index_out = BufWriter::new(create(name_index)?);-    let name_entries =-        poi_side::write_name_index(&mut name_index_out, &name_slices).map_err(io_err)?;-    name_index_out.flush().map_err(io_err)?;--    // The region sidecar joins by the same ordinal, in the same function, for the-    // same reason as the two above.-    let region_ids: Vec<u64> = pois.iter().map(|p| p.region).collect();-    let mut region_out = BufWriter::new(create(region)?);-    poi_side::write_region(&mut region_out, &region_ids).map_err(io_err)?;-    region_out.flush().map_err(io_err)?;--    index_out.flush().map_err(io_err)?;-    geojson_out.flush().map_err(io_err)?;-    let unique = pool.unique_count();-    let bytes = pool.byte_len();-    pool.finish().map_err(io_err)?;     println!(         "Wrote {} record(s), {unique} unique name(s), {bytes} name byte(s)",         pois.len()@@ -131,6 +141,81 @@ fn write_outputs(     }) } +/// Create `path`, hand `f` a large buffered writer over it, flush.+fn write_with<T>(path: &Path, f: impl FnOnce(&mut BufWriter<File>) -> std::io::Result<T>) -> Result<T> {+    let mut out = BufWriter::with_capacity(WRITE_BUF, create(path)?);+    let v = f(&mut out).map_err(io_err)?;+    out.flush().map_err(io_err)?;+    Ok(v)+}++/// `poi_names.bin` + `poi_index.bin`. Serial on purpose: a name's offset is the+/// pool size when it is first seen in record order (see `names.rs`).+fn write_names_and_index(pois: &[Poi], names: &Path, index: &Path) -> Result<(usize, u32)> {+    let mut pool = NamePool::new(BufWriter::with_capacity(WRITE_BUF, create(names)?));+    let mut index_out = BufWriter::with_capacity(WRITE_BUF, create(index)?);+    for p in pois {+        let off = pool.intern(&p.name).map_err(io_err)?;+        let mut rec = [0u8; 14];+        rec[0..4].copy_from_slice(&p.lat_e7.to_le_bytes());+        rec[4..8].copy_from_slice(&p.lon_e7.to_le_bytes());+        rec[8..12].copy_from_slice(&off.to_le_bytes());+        rec[12..14].copy_from_slice(&p.type_.to_le_bytes());+        index_out.write_all(&rec).map_err(io_err)?;+    }+    index_out.flush().map_err(io_err)?;+    let unique = pool.unique_count();+    let bytes = pool.byte_len();+    pool.finish().map_err(io_err)?;+    Ok((unique, bytes))+}++/// The geojsonseq, formatted in parallel batches and written in record order.+/// Each line is a function of its own POI only, so the bytes are the serial+/// loop's.+fn write_geojson(pois: &[Poi], geojson: &Path) -> Result<()> {+    use rayon::prelude::*;+    let mut out = BufWriter::with_capacity(WRITE_BUF, create(geojson)?);+    for batch in pois.chunks(GEOJSON_BATCH) {+        let texts: Vec<Vec<u8>> = batch+            .par_chunks(GEOJSON_CHUNK)+            .map(|chunk| {+                let mut buf: Vec<u8> = Vec::with_capacity(chunk.len() * 192);+                for p in chunk {+                    geojson_line(p, &mut buf);+                }+                buf+            })+            .collect();+        for t in &texts {+            out.write_all(t).map_err(io_err)?;+        }+    }+    out.flush().map_err(io_err)+}++/// One geojsonseq feature line, appended to `line`.+fn geojson_line(p: &Poi, line: &mut Vec<u8>) {+    // Writes into a Vec cannot fail.+    let _ = write!(+        line,+        "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"Point\",\"coordinates\":[{:.7},{:.7}]}},\"properties\":{{\"name\":\"",+        p.lon, p.lat+    );+    json_escape(&p.name, line);+    let _ = writeln!(line, "\",\"type\":{},\"osm_id\":{}}}}}", p.type_, p.osm_id);+}++/// `poi_attrs.bin`, deduplicated in record order (offsets are first-seen).+fn write_attrs(pois: &[Poi], attrs: &Path) -> Result<AttrPool> {+    let mut attr_pool = AttrPool::new();+    for p in pois {+        attr_pool.push(&p.attrs).map_err(io_err)?;+    }+    write_with(attrs, |out| attr_pool.write(out))?;+    Ok(attr_pool)+}+ fn create(path: &Path) -> Result<File> {     File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) }
scripts/maps/osm_ingest/src/poi_build_part3.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build_part3.rs b/scripts/maps/osm_ingest/src/poi_build_part3.rsnew file mode 100644index 0000000000..04c9466035--- /dev/null+++ b/scripts/maps/osm_ingest/src/poi_build_part3.rs@@ -0,0 +1,392 @@+// ---- Region links: boundary assembly and per-POI containment ---------------+//+// Both halves run on the crate pool (`par::install`), and both are+// byte-neutral by construction:+//+// * `assemble_boundaries` maps each boundary independently and collects in the+//   same id order the serial loop walked, so `assembled[i]` — and therefore+//   every grid cell's candidate list — is unchanged.+// * `stamp_regions` decides each POI from that POI and read-only shared state+//   only, so splitting `pois` into chunks cannot change any POI's answer.+//+// The containment test itself is `rings::point_in_ring`'s ray cast, restricted+// to the edges that can straddle the probe's latitude ([`RingIndex`]). The+// crossing parity is an XOR over edges, so visiting a subset in a different+// order gives the same bit as long as the skipped edges could never toggle it —+// which is exactly what the band assignment guarantees.++/// One assembled boundary: its polygons, each exterior ring's absolute area+/// (smallest-wins needs no sign), its bbox, and its tagged link.+struct BoundaryPoly {+    tagged: u64,+    admin_level: u8,+    polys: Vec<rings::Polygon>,+    /// `index[p][r]` accelerates `polys[p][r]`.+    index: Vec<Vec<RingIndex>>,+    areas: Vec<f64>,+    min_lon: f64,+    min_lat: f64,+    max_lon: f64,+    max_lat: f64,+}++/// Latitude-band edge index over one closed ring, so a containment probe walks+/// only the edges whose latitude span covers the probe instead of all of them.+///+/// Admin rings run to 10^5 vertices (a coastline-hugging state or country), and+/// the serial ray cast walked every one of them for every POI in the 1° cell —+/// 80% of a California run.+///+/// Exactness: edge `i` can toggle the ray-cast parity only when+/// `(y1 > y) != (y2 > y)`, i.e. `min(y1, y2) <= y < max(y1, y2)`. `band()` is a+/// monotone non-decreasing function of `y` (an IEEE subtract and a multiply by a+/// positive constant both round monotonically, as do `floor` and the clamp), so+/// for any such `y`, `band(min) <= band(y) <= band(max)` — and the edge is filed+/// under every band in that closed range. No edge that could toggle is ever+/// skipped; the toggle test on the edges visited is the original expression,+/// operand for operand.+struct RingIndex {+    min_y: f64,+    max_y: f64,+    inv: f64,+    bands: usize,+    /// CSR: edges of band `b` are `edges[offs[b]..offs[b + 1]]`.+    offs: Vec<u32>,+    edges: Vec<u32>,+}++/// Edges per band the index aims for. Smaller is faster to probe and bigger to+/// store; four keeps the index well under the ring's own 16 bytes a vertex.+const EDGES_PER_BAND: usize = 4;+/// Upper bound on bands per ring, so a pathological ring cannot blow up memory.+const MAX_BANDS: usize = 1 << 16;++impl RingIndex {+    fn new(ring: &[Coord]) -> RingIndex {+        let n = ring.len();+        let (mut min_y, mut max_y) = (f64::INFINITY, f64::NEG_INFINITY);+        for &(_, y) in ring {+            min_y = min_y.min(y);+            max_y = max_y.max(y);+        }+        let span = max_y - min_y;+        let bands = if n < 3 || !(span > 0.0) {+            1+        } else {+            (n / EDGES_PER_BAND).clamp(1, MAX_BANDS)+        };+        let inv = if span > 0.0 { bands as f64 / span } else { 0.0 };+        let mut idx = RingIndex {+            min_y,+            max_y,+            inv,+            bands,+            offs: Vec::new(),+            edges: Vec::new(),+        };+        if n < 3 {+            idx.offs = vec![0; bands + 1];+            return idx;+        }+        // Two passes (count, then fill) so the CSR is allocated exactly once.+        let mut counts = vec![0u32; bands + 1];+        let span_of = |i: usize| -> Option<(usize, usize)> {+            let (_, y1) = ring[i];+            let (_, y2) = ring[(i + 1) % n];+            // A horizontal edge never satisfies `(y1 > y) != (y2 > y)`.+            if y1 == y2 {+                return None;+            }+            Some((idx.band(y1.min(y2)), idx.band(y1.max(y2))))+        };+        for i in 0..n {+            if let Some((lo, hi)) = span_of(i) {+                for c in &mut counts[lo..=hi] {+                    *c += 1;+                }+            }+        }+        let mut offs = vec![0u32; bands + 1];+        for b in 0..bands {+            offs[b + 1] = offs[b] + counts[b];+        }+        let mut fill = offs.clone();+        let mut edges = vec![0u32; offs[bands] as usize];+        for i in 0..n {+            if let Some((lo, hi)) = span_of(i) {+                for f in &mut fill[lo..=hi] {+                    edges[*f as usize] = i as u32;+                    *f += 1;+                }+            }+        }+        idx.offs = offs;+        idx.edges = edges;+        idx+    }++    #[inline]+    fn band(&self, y: f64) -> usize {+        let b = ((y - self.min_y) * self.inv).floor();+        // `as usize` saturates a negative to 0; clamp the top edge.+        (b as usize).min(self.bands - 1)+    }++    /// `rings::point_in_ring((x, y), ring)`, bit for bit.+    #[inline]+    fn contains(&self, (x, y): Coord, ring: &[Coord]) -> bool {+        let n = ring.len();+        if n < 3 {+            return false;+        }+        // No edge has `min <= y < max` outside this range, so no toggle.+        if !(y >= self.min_y && y < self.max_y) {+            return false;+        }+        let b = self.band(y);+        let mut inside = false;+        for &i in &self.edges[self.offs[b] as usize..self.offs[b + 1] as usize] {+            let i = i as usize;+            let (x1, y1) = ring[i];+            let (x2, y2) = ring[(i + 1) % n];+            if (y1 > y) != (y2 > y) {+                let t = (y - y1) / (y2 - y1);+                if x < x1 + t * (x2 - x1) {+                    inside = !inside;+                }+            }+        }+        inside+    }+}++/// Assemble every boundary's polygons (in boundary-id order) and index their+/// rings for [`stamp_regions`]. Boundaries that close nothing are dropped.+fn assemble_boundaries<L>(+    boundaries: &[BoundaryRel],+    outer_refs: &HashMap<i64, Vec<i64>>,+    location: &L,+) -> Vec<BoundaryPoly>+where+    L: Fn(i64) -> Option<(i32, i32)> + Sync,+{+    use rayon::prelude::*;+    let mut ordered: Vec<&BoundaryRel> = boundaries.iter().collect();+    ordered.sort_by_key(|b| b.id);+    let locate = |id: i64| -> Option<Coord> {+        location(id).map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7))+    };+    let one = |b: &BoundaryRel| -> Option<BoundaryPoly> {+        let members: Vec<MemberWay> = b+            .member_ways+            .iter()+            .map(|(w, outer)| MemberWay {+                refs: outer_refs.get(w).cloned().unwrap_or_default(),+                outer: *outer,+            })+            .collect();+        // The stats are a per-call report nobody reads on this path.+        let polys = rings::assemble(&members, &locate, &mut RingStats::default());+        if polys.is_empty() {+            return None;+        }+        let (mut min_lon, mut min_lat) = (f64::INFINITY, f64::INFINITY);+        let (mut max_lon, mut max_lat) = (f64::NEG_INFINITY, f64::NEG_INFINITY);+        let mut areas = Vec::with_capacity(polys.len());+        for poly in &polys {+            areas.push(rings::ring_area(&poly[0]).abs());+            for ring in poly {+                for &(lon, lat) in ring {+                    min_lon = min_lon.min(lon);+                    min_lat = min_lat.min(lat);+                    max_lon = max_lon.max(lon);+                    max_lat = max_lat.max(lat);+                }+            }+        }+        let index = polys+            .iter()+            .map(|poly| poly.iter().map(|r| RingIndex::new(r)).collect())+            .collect();+        Some(BoundaryPoly {+            tagged: poi_side::tag_relation(b.id),+            admin_level: b.admin_level,+            polys,+            index,+            areas,+            min_lon,+            min_lat,+            max_lon,+            max_lat,+        })+    };+    // `with_max_len(1)`: a handful of country-sized boundaries dominate, so let+    // each be stolen on its own. `collect` keeps the input (id) order.+    let out: Vec<Option<BoundaryPoly>> = crate::par::install(|| {+        ordered.par_iter().with_max_len(1).map(|b| one(b)).collect()+    });+    out.into_iter().flatten().collect()+}++/// POIs per containment work unit.+const STAMP_CHUNK: usize = 1024;++/// Stamp every POI's [`Poi::region`]: self-links are already set, a node carried+/// as a boundary's `label`/`admin_centre` member takes that boundary's tagged id,+/// otherwise the smallest-area containing admin at or above the POI's+/// place-implied cap wins. Returns the stamped count.+///+/// `pois[..from_nodes]` are nodes, which is the only slice the member-link map+/// can hit — node ids and way/relation ids share a namespace per element type,+/// and a way id equal to a label node id is a different object.+///+/// Containment runs through a coarse 1°-cell grid over boundary bboxes, so a+/// planet build tests each POI only against the boundaries whose bbox covers it+/// instead of every admin relation on earth.+fn stamp_regions(+    pois: &mut [Poi],+    from_nodes: usize,+    boundaries: &[BoundaryRel],+    assembled: &[BoundaryPoly],+) -> usize {+    use rayon::prelude::*;+    // Deterministic on double-labelling: the lowest boundary id wins.+    let mut ordered: Vec<&BoundaryRel> = boundaries.iter().collect();+    ordered.sort_by_key(|b| b.id);+    let mut labels: HashMap<i64, u64> = HashMap::new();+    for b in &ordered {+        let tagged = poi_side::tag_relation(b.id);+        for n in &b.label_nodes {+            labels.entry(*n).or_insert(tagged);+        }+    }++    let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();+    for (i, b) in assembled.iter().enumerate() {+        for cx in b.min_lon.floor() as i32..=b.max_lon.floor() as i32 {+            for cy in b.min_lat.floor() as i32..=b.max_lat.floor() as i32 {+                grid.entry((cx, cy)).or_default().push(i);+            }+        }+    }++    // One POI's answer, from that POI and read-only state alone.+    let stamp = |i: usize, p: &mut Poi| -> bool {+        if p.region != poi_side::REGION_NONE {+            return true;+        }+        // Member links win over containment.+        if i < from_nodes {+            if let Some(tagged) = labels.get(&p.osm_id) {+                p.region = *tagged;+                return true;+            }+        }+        let lon = p.lon_e7 as f64 * 1e-7;+        let lat = p.lat_e7 as f64 * 1e-7;+        let Some(cands) = grid.get(&(lon.floor() as i32, lat.floor() as i32)) else {+            return false;+        };+        let mut best: Option<(f64, u64)> = None;+        for bi in cands {+            let b = &assembled[*bi];+            if b.admin_level > p.place_cap {+                continue;+            }+            for ((poly, idx), area) in b.polys.iter().zip(&b.index).zip(&b.areas) {+                // The serial loop's three conjuncts, cheapest first. All three are+                // pure, so their order cannot change whether `best` moves.+                if best.is_none_or(|(a, _)| *area < a)+                    && idx[0].contains((lon, lat), &poly[0])+                    // Holes excluded: inside an inner ring is not inside the admin.+                    && !poly[1..]+                        .iter()+                        .zip(&idx[1..])+                        .any(|(h, hi)| hi.contains((lon, lat), h))+                {+                    best = Some((*area, b.tagged));+                }+            }+        }+        match best {+            Some((_, tagged)) => {+                p.region = tagged;+                true+            }+            None => false,+        }+    };++    crate::par::install(|| {+        pois.par_chunks_mut(STAMP_CHUNK)+            .enumerate()+            .map(|(c, chunk)| {+                let base = c * STAMP_CHUNK;+                chunk+                    .iter_mut()+                    .enumerate()+                    .map(|(j, p)| stamp(base + j, p))+                    .filter(|hit| *hit)+                    .count()+            })+            .sum()+    })+}++#[cfg(test)]+mod region_index_tests {+    use super::*;++    /// A deterministic xorshift, so the property test needs no crate.+    fn rng(seed: &mut u64) -> f64 {+        *seed ^= *seed << 13;+        *seed ^= *seed >> 7;+        *seed ^= *seed << 17;+        (*seed >> 11) as f64 / (1u64 << 53) as f64+    }++    /// The banded probe must agree with `rings::point_in_ring` on every point,+    /// including probes exactly on vertex latitudes and outside the bbox.+    #[test]+    fn the_banded_probe_matches_the_full_ray_cast() {+        let mut seed = 0x9E37_79B9_7F4A_7C15u64;+        for n in [3usize, 4, 5, 17, 64, 1000, 5000] {+            // A star-shaped (very concave) closed ring around (10, 50).+            let mut ring: Vec<Coord> = (0..n)+                .map(|k| {+                    let a = k as f64 / n as f64 * std::f64::consts::TAU;+                    let r = 0.2 + rng(&mut seed);+                    (10.0 + r * a.cos(), 50.0 + r * a.sin())+                })+                .collect();+            ring.push(ring[0]);+            let idx = RingIndex::new(&ring);+            let mut probes: Vec<Coord> = (0..4000)+                .map(|_| (8.5 + 3.0 * rng(&mut seed), 48.5 + 3.0 * rng(&mut seed)))+                .collect();+            // Exactly on vertex latitudes and on vertices themselves.+            for &(vx, vy) in ring.iter().take(200) {+                probes.push((vx, vy));+                probes.push((vx - 0.01, vy));+                probes.push((10.0, vy));+            }+            for p in probes {+                assert_eq!(+                    idx.contains(p, &ring),+                    rings::point_in_ring(p, &ring),+                    "n={n} p={p:?}"+                );+            }+        }+    }++    #[test]+    fn degenerate_rings_contain_nothing() {+        let flat = vec![(0.0, 1.0), (1.0, 1.0), (2.0, 1.0), (0.0, 1.0)];+        let idx = RingIndex::new(&flat);+        assert!(!idx.contains((1.0, 1.0), &flat));+        assert_eq!(rings::point_in_ring((1.0, 1.0), &flat), false);+        let tiny = vec![(0.0, 0.0), (1.0, 1.0)];+        assert!(!RingIndex::new(&tiny).contains((0.5, 0.5), &tiny));+    }+}
scripts/maps/osm_ingest/src/poi_reviews.rs
diff --git a/scripts/maps/osm_ingest/src/poi_reviews.rs b/scripts/maps/osm_ingest/src/poi_reviews.rsindex 105f4ec6b2..40ae7f7360 100644--- a/scripts/maps/osm_ingest/src/poi_reviews.rs+++ b/scripts/maps/osm_ingest/src/poi_reviews.rs@@ -14,7 +14,6 @@ //! The join key has to be the OSM element because `poi_index.bin` and //! `poi_attrs.bin` carry no OSM id, so this is the last point where one exists. -use std::collections::HashMap; use std::path::Path;  use crate::poi_attrs::{KEY_RATING, KEY_REVIEW_COUNT, KEY_REVIEW_SUMMARY};@@ -54,9 +53,19 @@ impl Review {  #[derive(Debug, Default)] pub struct ReviewTable {-    map: HashMap<(u8, i64), Review>,+    /// Sorted by key, one entry per key (the LAST row for that key wins, as the+    /// `HashMap::insert` this replaced did). A sorted `Vec` rather than a map so+    /// the 2.7M-row planet table can be built and ordered in parallel.+    rows: Vec<((u8, i64), Review)>, } +/// One parsed row, or `(line index within its chunk, why)` for the first bad one.+type ChunkRows = std::result::Result<Vec<((u8, i64), Review)>, (usize, String)>;++/// Smallest parse chunk. The table is ~400 MB on a planet build; below a few MiB a+/// chunk is not worth a task.+const MIN_PARSE_CHUNK: usize = 4 << 20;+ impl ReviewTable {     pub fn load(path: &Path) -> Result<Self> {         let text = std::fs::read_to_string(path)@@ -64,64 +73,148 @@ impl ReviewTable {         Self::parse(&text).map_err(|e| Error(format!("{}: {}", path.display(), e.0)))     } +    /// Parse the whole table.+    ///+    /// Parallel, and identical to the serial parse it replaced: the text is cut+    /// only immediately after a `\n`, so the chunks' `lines()` concatenate to the+    /// whole text's `lines()`; each chunk reports its line count, so an error+    /// carries the same global line number; the first failing chunk in text order+    /// supplies the error, and within a chunk parsing stops at its first bad line,+    /// so the reported error is the first bad line of the file. Rows are then+    /// stable-sorted by key and deduplicated keeping the last, which is what+    /// repeated `HashMap::insert` in file order did.     pub fn parse(text: &str) -> Result<Self> {-        let mut map = HashMap::new();-        for (n, line) in text.lines().enumerate() {-            let line = line.trim_end_matches('\r');-            if line.trim().is_empty() || line.starts_with('#') {-                continue;-            }-            let bad = |why: &str| Error(format!("line {}: {why}", n + 1));-            let cols: Vec<&str> = line.split('\t').collect();-            if cols.len() != 5 {-                return Err(bad(&format!("expected 5 tab-separated columns, found {}", cols.len())));-            }-            let element = match cols[0] {-                "node" => ELEMENT_NODE,-                "way" => ELEMENT_WAY,-                "relation" => ELEMENT_RELATION,-                other => return Err(bad(&format!("unknown element `{other}`"))),-            };-            let id: i64 = cols[1].parse().map_err(|_| bad("id is not an integer"))?;-            if id <= 0 {-                return Err(bad("id must be positive"));+        let target = (text.len() / (crate::par::threads() * 4).max(1)).max(MIN_PARSE_CHUNK);+        Self::parse_chunked(text, target)+    }++    /// [`ReviewTable::parse`] with an explicit chunk size, so tests can force+    /// many chunks on a tiny table.+    fn parse_chunked(text: &str, target: usize) -> Result<Self> {+        use rayon::prelude::*;+        let target = target.max(1);+        let bytes = text.as_bytes();+        let mut chunks: Vec<&str> = Vec::new();+        let mut pos = 0;+        while pos < bytes.len() {+            let mut end = (pos + target).min(bytes.len());+            if end < bytes.len() {+                end = match bytes[end..].iter().position(|b| *b == b'\n') {+                    Some(k) => end + k + 1,+                    None => bytes.len(),+                };             }-            let rating = match cols[2].trim() {-                "" => None,-                r => {-                    let v: f32 = r.parse().map_err(|_| bad("rating is not a number"))?;-                    if !(1.0..=5.0).contains(&v) {-                        return Err(bad("rating must be between 1 and 5"));-                    }-                    Some(format!("{v:.1}"))-                }-            };-            let review_count = match cols[3].trim() {-                "" => None,-                c => {-                    let v: u32 = c.parse().map_err(|_| bad("review_count is not a positive integer"))?;-                    (v > 0).then(|| v.to_string())+            // `end` is just past an ASCII `\n` or the end, so a char boundary.+            chunks.push(&text[pos..end]);+            pos = end;+        }++        let parsed: Vec<(usize, ChunkRows)> = crate::par::install(|| {+            chunks.par_iter().map(|c| parse_chunk(c)).collect()+        });++        let mut first_line = 0usize;+        let mut total = 0usize;+        for (lines, rows) in &parsed {+            match rows {+                Ok(r) => total += r.len(),+                Err((n, why)) => {+                    return Err(Error(format!("line {}: {why}", first_line + n + 1)));                 }-            };-            let summary = Some(cols[4].trim())-                .filter(|s| !s.is_empty() && s.len() <= MAX_SUMMARY_BYTES)-                .map(str::to_string);-            map.insert((element, id), Review { rating, review_count, summary });+            }+            first_line += lines;+        }+        let mut rows: Vec<((u8, i64), Review)> = Vec::with_capacity(total);+        for (_, r) in parsed {+            rows.extend(r.expect("errors returned above"));         }-        Ok(Self { map })+        crate::par::install(|| rows.par_sort_by_key(|r| r.0));+        // `dedup_by` hands (later, kept); swapping first leaves the later row kept.+        rows.dedup_by(|later, kept| {+            if later.0 == kept.0 {+                std::mem::swap(later, kept);+                true+            } else {+                false+            }+        });+        Ok(Self { rows })     }      pub fn get(&self, element: u8, id: i64) -> Option<&Review> {-        self.map.get(&(element, id))+        self.rows+            .binary_search_by_key(&(element, id), |r| r.0)+            .ok()+            .map(|i| &self.rows[i].1)     }      pub fn len(&self) -> usize {-        self.map.len()+        self.rows.len()     }      pub fn is_empty(&self) -> bool {-        self.map.is_empty()+        self.rows.is_empty()+    }+}++/// Parse one line-aligned chunk: `(lines in the chunk, rows or first error)`.+fn parse_chunk(text: &str) -> (usize, ChunkRows) {+    let mut out = Vec::new();+    let mut lines = 0usize;+    for (n, line) in text.lines().enumerate() {+        lines = n + 1;+        match parse_line(line) {+            Ok(Some(row)) => out.push(row),+            Ok(None) => {}+            Err(why) => return (lines, Err((n, why))),+        }+    }+    (lines, Ok(out))+}++/// One table line: `Ok(None)` for a blank or comment line.+fn parse_line(line: &str) -> std::result::Result<Option<((u8, i64), Review)>, String> {+    let line = line.trim_end_matches('\r');+    if line.trim().is_empty() || line.starts_with('#') {+        return Ok(None);+    }+    let cols: Vec<&str> = line.split('\t').collect();+    if cols.len() != 5 {+        return Err(format!("expected 5 tab-separated columns, found {}", cols.len()));+    }+    let element = match cols[0] {+        "node" => ELEMENT_NODE,+        "way" => ELEMENT_WAY,+        "relation" => ELEMENT_RELATION,+        other => return Err(format!("unknown element `{other}`")),+    };+    let id: i64 = cols[1].parse().map_err(|_| "id is not an integer".to_string())?;+    if id <= 0 {+        return Err("id must be positive".into());     }+    let rating = match cols[2].trim() {+        "" => None,+        r => {+            let v: f32 = r.parse().map_err(|_| "rating is not a number".to_string())?;+            if !(1.0..=5.0).contains(&v) {+                return Err("rating must be between 1 and 5".into());+            }+            Some(format!("{v:.1}"))+        }+    };+    let review_count = match cols[3].trim() {+        "" => None,+        c => {+            let v: u32 = c+                .parse()+                .map_err(|_| "review_count is not a positive integer".to_string())?;+            (v > 0).then(|| v.to_string())+        }+    };+    let summary = Some(cols[4].trim())+        .filter(|s| !s.is_empty() && s.len() <= MAX_SUMMARY_BYTES)+        .map(str::to_string);+    Ok(Some(((element, id), Review { rating, review_count, summary }))) }  #[cfg(test)]@@ -171,4 +264,61 @@ mod tests {         let t = ReviewTable::parse(&format!("node\t1\t4.0\t10\t{}\n", "x".repeat(MAX_SUMMARY_BYTES + 1))).unwrap();         assert_eq!(t.get(ELEMENT_NODE, 1).unwrap().fields().len(), 2);     }++    /// Serial reference: the `HashMap` parse this module used before it went+    /// parallel, kept here to pin the parallel one to it.+    fn reference(text: &str) -> std::result::Result<std::collections::HashMap<(u8, i64), Review>, String> {+        let mut map = std::collections::HashMap::new();+        for (n, line) in text.lines().enumerate() {+            match parse_line(line) {+                Ok(Some((k, v))) => {+                    map.insert(k, v);+                }+                Ok(None) => {}+                Err(why) => return Err(format!("line {}: {why}", n + 1)),+            }+        }+        Ok(map)+    }++    fn sample(rows: usize, bad_at: Option<usize>) -> String {+        let mut s = String::from("# header\n");+        for i in 0..rows {+            if Some(i) == bad_at {+                s.push_str("node\tnope\t1\t1\tx\n");+                continue;+            }+            // Ids repeat, so later rows must overwrite earlier ones.+            let el = ["node", "way", "relation"][i % 3];+            s.push_str(&format!("{el}\t{}\t{}.0\t{i}\tsummary {i}\r\n", 1 + i % 37, 1 + i % 5));+            if i % 11 == 0 {+                s.push('\n');+            }+        }+        s+    }++    #[test]+    fn chunked_parse_matches_the_serial_map_for_every_chunk_size() {+        let text = sample(500, None);+        let want = reference(&text).unwrap();+        for target in [1usize, 2, 7, 64, 333, 4096, 1 << 20] {+            let got = ReviewTable::parse_chunked(&text, target).unwrap();+            assert_eq!(got.len(), want.len(), "target {target}");+            for (k, v) in &want {+                assert_eq!(got.get(k.0, k.1), Some(v), "target {target} key {k:?}");+            }+        }+    }++    #[test]+    fn chunked_parse_reports_the_first_bad_line_globally() {+        let mut text = sample(300, Some(123));+        text.push_str("way\tx\t\t\t\n");+        let want = reference(&text).unwrap_err();+        for target in [1usize, 5, 50, 999, 1 << 20] {+            let got = ReviewTable::parse_chunked(&text, target).unwrap_err().0;+            assert_eq!(got, want, "target {target}");+        }+    } }
scripts/maps/osm_ingest/src/poi_side.rs
diff --git a/scripts/maps/osm_ingest/src/poi_side.rs b/scripts/maps/osm_ingest/src/poi_side.rsindex 04a9807c93..1474060a25 100644--- a/scripts/maps/osm_ingest/src/poi_side.rs+++ b/scripts/maps/osm_ingest/src/poi_side.rs@@ -206,21 +206,26 @@ fn cell_axis(value: i32, origin: i32) -> u32 { /// Returns the number of populated cells. Writes a valid, empty grid for no records /// rather than refusing, so the file's presence never depends on the extract. pub fn write_spatial<W: Write>(out: &mut W, coords: &[(i32, i32)]) -> io::Result<usize> {+    use rayon::prelude::*;     let grid = Grid::fit(coords);     let (lat0, lon0, cols) = match &grid {         Some(g) => (g.lat0_e7, g.lon0_e7, g.cols),         None => (0, 0, 0),     }; -    // (cell, ordinal), sorted so equal cells are adjacent and ordinals ascend within-    // one — the order the CSR encodes, and the order a reader walks.-    let mut pairs: Vec<(u32, u32)> = Vec::with_capacity(coords.len());-    if let Some(g) = &grid {-        for (ordinal, &(lat, lon)) in coords.iter().enumerate() {-            pairs.push((g.cell(lat, lon), ordinal as u32));-        }-    }-    pairs.sort_unstable();+    // `(cell, ordinal)` pairs are unique (the ordinal is), so the parallel+    // unstable sort orders them exactly as the serial one did.+    let mut pairs: Vec<(u32, u32)> = match &grid {+        Some(g) => crate::par::install(|| {+            coords+                .par_iter()+                .enumerate()+                .map(|(ordinal, &(lat, lon))| (g.cell(lat, lon), ordinal as u32))+                .collect()+        }),+        None => Vec::new(),+    };+    crate::par::install(|| pairs.par_sort_unstable());      let mut cell_ids: Vec<u32> = Vec::new();     let mut cell_off: Vec<u32> = Vec::new();@@ -232,56 +237,90 @@ pub fn write_spatial<W: Write>(out: &mut W, coords: &[(i32, i32)]) -> io::Result     }     cell_off.push(pairs.len() as u32); -    out.write_all(SPATIAL_MAGIC)?;-    out.write_all(&SPATIAL_VERSION.to_le_bytes())?;-    out.write_all(&(coords.len() as u32).to_le_bytes())?;-    out.write_all(&(cell_ids.len() as u32).to_le_bytes())?;-    out.write_all(&lat0.to_le_bytes())?;-    out.write_all(&lon0.to_le_bytes())?;-    out.write_all(&CELL_E7.to_le_bytes())?;-    out.write_all(&cols.to_le_bytes())?;+    // One buffer, one write: the file is a few hundred MB on a planet, and+    // 4-byte `write_all`s through a default `BufWriter` cost more than the sort.+    let mut buf: Vec<u8> =+        Vec::with_capacity(SPATIAL_HEADER_BYTES + 4 * (2 * cell_ids.len() + 1 + pairs.len()));+    buf.extend_from_slice(SPATIAL_MAGIC);+    buf.extend_from_slice(&SPATIAL_VERSION.to_le_bytes());+    buf.extend_from_slice(&(coords.len() as u32).to_le_bytes());+    buf.extend_from_slice(&(cell_ids.len() as u32).to_le_bytes());+    buf.extend_from_slice(&lat0.to_le_bytes());+    buf.extend_from_slice(&lon0.to_le_bytes());+    buf.extend_from_slice(&CELL_E7.to_le_bytes());+    buf.extend_from_slice(&cols.to_le_bytes());     for id in &cell_ids {-        out.write_all(&id.to_le_bytes())?;+        buf.extend_from_slice(&id.to_le_bytes());     }     for off in &cell_off {-        out.write_all(&off.to_le_bytes())?;+        buf.extend_from_slice(&off.to_le_bytes());     }     for &(_, ordinal) in &pairs {-        out.write_all(&ordinal.to_le_bytes())?;+        buf.extend_from_slice(&ordinal.to_le_bytes());     }+    out.write_all(&buf)?;     Ok(cell_ids.len()) }  /// Write `poi_name_index.bin` for records whose names are `names[ordinal]`. ///-/// Returns the number of entries. The sort resolves each entry's word out of `names`-/// rather than materialising it, which keeps the working set to 8 bytes per entry-/// instead of that plus a copy of every word.+/// Returns the number of entries.+///+/// Each entry carries its word's byte range inside its name, so the sort compares+/// slices directly. The serial version re-split the name with [`word_at`] on every+/// comparison — O(name) work inside an O(n log n) sort, on one thread — which was+/// 1.4 s of a 14 s California run and the largest serial stage after the region+/// stamp. 16 bytes an entry instead of 8; on a planet's ~10^8 entries that is+/// ~0.8 GB more, at a stage whose peak is otherwise just the POI vector.+///+/// Same order, bit for bit: the key is still `cmp_word(word, word)` then+/// `(ordinal, word_idx)`, a total order (the pair is unique), so the parallel+/// unstable sort cannot order equal keys differently from the serial one. pub fn write_name_index<W: Write>(out: &mut W, names: &[&[u8]]) -> io::Result<usize> {-    let mut entries: Vec<(u32, u8)> = Vec::new();-    for (ordinal, name) in names.iter().enumerate() {-        for (word_idx, _) in words(name) {-            entries.push((ordinal as u32, word_idx));-        }+    use rayon::prelude::*;+    /// `(ordinal, word start, word end, word_idx)`.+    type Entry = (u32, u32, u32, u8);+    let per_name: Vec<Vec<Entry>> = crate::par::install(|| {+        names+            .par_iter()+            .enumerate()+            .with_min_len(4096)+            .map(|(ordinal, name)| {+                let base = name.as_ptr() as usize;+                words(name)+                    .map(|(word_idx, w)| {+                        let start = (w.as_ptr() as usize - base) as u32;+                        (ordinal as u32, start, start + w.len() as u32, word_idx)+                    })+                    .collect()+            })+            .collect()+    });+    let mut entries: Vec<Entry> = Vec::with_capacity(per_name.iter().map(Vec::len).sum());+    for v in per_name {+        entries.extend(v);     }+    let word = |e: &Entry| &names[e.0 as usize][e.1 as usize..e.2 as usize];     // Ordinal breaks ties so the file is reproducible: two runs over the same input     // must be byte-identical, which an unstable sort only gives on a total order.-    entries.sort_unstable_by(|a, b| {-        let wa = word_at(names[a.0 as usize], a.1).unwrap_or_default();-        let wb = word_at(names[b.0 as usize], b.1).unwrap_or_default();-        cmp_word(wa, wb).then(a.cmp(b))+    crate::par::install(|| {+        entries.par_sort_unstable_by(|a, b| {+            cmp_word(word(a), word(b)).then((a.0, a.3).cmp(&(b.0, b.3)))+        })     }); -    out.write_all(NAME_MAGIC)?;-    out.write_all(&NAME_VERSION.to_le_bytes())?;-    out.write_all(&(names.len() as u32).to_le_bytes())?;-    out.write_all(&(entries.len() as u32).to_le_bytes())?;-    for &(ordinal, _) in &entries {-        out.write_all(&ordinal.to_le_bytes())?;+    let mut buf: Vec<u8> = Vec::with_capacity(NAME_HEADER_BYTES + 5 * entries.len());+    buf.extend_from_slice(NAME_MAGIC);+    buf.extend_from_slice(&NAME_VERSION.to_le_bytes());+    buf.extend_from_slice(&(names.len() as u32).to_le_bytes());+    buf.extend_from_slice(&(entries.len() as u32).to_le_bytes());+    for e in &entries {+        buf.extend_from_slice(&e.0.to_le_bytes());     }-    for &(_, word_idx) in &entries {-        out.write_all(&[word_idx])?;+    for e in &entries {+        buf.push(e.3);     }+    out.write_all(&buf)?;     Ok(entries.len()) }