Modern Apps git

← Modern-Apps.git

maps: link member-less place labels to boundaries by containment

Commit
a30c00400dc5c8e1233f85752f81533a49ec8a07
Author
vayun-mathur <[email protected]>
When
2026-09-22 02:56 UTC (2 months ago)
Parents
b3896cc

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.rsnew file mode 100644index 0000000000..0ddda82244--- /dev/null+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -0,0 +1,383 @@+//! Build-time containment fallback for place-label -> boundary links.+//!+//! Tapping a place label should outline its exact admin boundary. The authoritative half of that+//! link is membership: a boundary relation points at its own label node via an `admin_centre` or+//! `label` member, and stage A records that node -> relation pair into `region_links`+//! (`extract_part1.rs`). This module is the second half: for every place label that membership did+//! not link, pick the boundary that contains its centroid.+//!+//! # Matching order: members first, containment second+//!+//! The member map is never overwritten here. Fallback only inserts entries for place tagged-IDs+//! still missing from `region_links`, keyed the same way the tiler looks them up (the place's own+//! tagged node/way/relation id), so the two halves agree and `tiler_part5.rs` needs no change.+//!+//! # Where this runs+//!+//! Called from `main_part1.rs` between `extract()` returning and `tiler::Settings` construction,+//! with the finished [`Store`](crate::store::Store) and the member-built map. The store holds+//! whole lon/lat polygons (pre-tiler, pre-clip), which is the only place a containment test is+//! meaningful — at tiler encode time the geometry is tile-local clipped fragments. Two sequential+//! reads of the spill: one to collect boundary shapes, one to stream places and link them. No new+//! spills, no resident feature table.+//!+//! # Level bands+//!+//! A place kind only matches the admin levels it can actually name:+//!+//! | place kind | admin levels |+//! |---|---|+//! | `country` | 1–2 |+//! | `region` | 3–4 |+//! | `locality` | 7–12 |+//!+//! Levels 5–6 (county) intentionally match nothing. Those boundaries only link via relation+//! members; anything else masks nothing rather than the wrong county. `neighbourhood` and+//! `macrohood` places likewise match nothing — a suburb centroid inside a city boundary must not+//! outline the city.+//!+//! # `REGION_NONE` rules: when in doubt, mask nothing+//!+//! A missing link leaves the tiler's `REGION_NONE` path (mask nothing), so every uncertain case+//! emits nothing: zero in-band candidates, an ambiguous pick (two containers' areas within ~1% of+//! each other), or the place sitting on a ring edge (where ray-casting is a coin flip). Ambiguity+//! favors no-mask over wrong-mask.+//!+//! # Cost cap+//!+//! Boundaries are partitioned by band (a place only ever tests its own band) behind a coarse+//! 4-degree grid, with a bbox reject before any point-in-polygon test, in a single pass per read.+//! Per-place work is then a handful of candidates, not the whole boundary set. If profiling ever+//! shows this dominating, the documented escape hatch is a rank-based skip (only attempt fallback+//! for places above a population-rank floor) — not yet implemented, and the per-kind counts in+//! [`FallbackStats`] are the numbers that would size it.++use std::collections::HashMap;++use osm_ingest::proto::Result;+use osm_ingest::rings::{point_in_ring, ring_area, Polygon};+use tile_build::geom::Geometry;+use tilecodec::mamaps::body::ID_NONE;+use tilecodec::mamaps::dict::{KINDS, LAYER_BOUNDARIES, LAYER_PLACES};++/// What a run of the fallback did, for the build report.+#[derive(Debug, Default, Clone)]+pub struct FallbackStats {+    /// Linkable `places` features seen (tagged id, non-empty point, known kind).+    pub places_total: u64,+    /// Of those, already linked by relation members before fallback ran.+    pub member_linked: u64,+    /// Of those, newly linked by containment here.+    pub fallback_linked: u64,+    /// Of those, still unlinked after both halves (`total - member - fallback`).+    pub fallback_missed: u64,+    /// `(kind, total, linked)` per place kind, sorted by kind. `linked` counts both halves;+    /// the ratio is the per-kind hit rate the build log prints.+    pub per_kind: Vec<(String, u64, u64)>,+}++/// Which admin-level band a place or a boundary belongs to.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Band {+    Country,+    Region,+    Locality,+}++/// The admin levels a place kind may link to. `None` means the kind never links by containment+/// (county levels and sub-locality places — see the module docs).+fn band_for_place_kind(kind: &str) -> Option<Band> {+    match kind {+        "country" => Some(Band::Country),+        "region" => Some(Band::Region),+        "locality" => Some(Band::Locality),+        _ => None,+    }+}++/// The band an admin level belongs to. Levels 5–6 deliberately belong to no band.+fn band_for_level(level: u16) -> Option<Band> {+    match level {+        1..=2 => Some(Band::Country),+        3..=4 => Some(Band::Region),+        7..=12 => Some(Band::Locality),+        _ => None,+    }+}++/// A boundary candidate: one `region_area` shape with everything the selector needs precomputed.+struct Boundary {+    /// Tagged relation id, the link value the tiler stamps.+    id: u64,+    /// `admin_level` from the region shape's class (`kind_detail`).+    level: u16,+    /// Sum of `|ring_area|` over the shape's exterior rings — the same metric `RegionMesh`+    /// compares on device (a consistent planar measure, not ground area; only ever compared).+    area: f64,+    /// `(min_lon, min_lat, max_lon, max_lat)` over the shape, for the prefilter. `None` when the+    /// shape holds no vertices at all.+    bbox: Option<(f64, f64, f64, f64)>,+    /// Assembled polygons, exterior first then holes, lon/lat.+    polygons: Vec<Polygon>,+}++impl Boundary {+    fn new(id: u64, level: u16, polygons: Vec<Polygon>) -> Boundary {+        let area: f64 =+            polygons.iter().filter_map(|poly| poly.first()).map(|ext| ring_area(ext).abs()).sum();+        let mut bbox: Option<(f64, f64, f64, f64)> = None;+        for ring in polygons.iter().flatten() {+            for &(lon, lat) in ring {+                bbox = Some(match bbox {+                    None => (lon, lat, lon, lat),+                    Some((x0, y0, x1, y1)) => {+                        (x0.min(lon), y0.min(lat), x1.max(lon), y1.max(lat))+                    }+                });+            }+        }+        Boundary { id, level, area, bbox, polygons }+    }+}++/// A place kind name from its interned `Class.kind` (1-based into [`KINDS`]).+fn place_kind_name(kind: u16) -> Option<&'static str> {+    if kind == 0 {+        return None;+    }+    KINDS.get(kind as usize - 1).copied()+}++/// Grid cells are 4 degrees square: 90 over lon, 45 over lat.+const GRID_NX: usize = 90;+const GRID_NY: usize = 45;+/// A boundary covering more cells than this goes on the overflow list, tested for every place.+/// 4-degree cells make even Russia (~250 cells) indexable; this only catches degenerate bboxes.+const MAX_CELLS_PER_BOUNDARY: usize = 1024;++/// Boundaries partitioned spatially so one place tests a cellful, not the planet.+struct Grid {+    cells: Vec<Vec<usize>>,+    overflow: Vec<usize>,+}++fn cell_of(lon: f64, lat: f64) -> usize {+    let ix = (((lon + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1) as usize;+    let iy = (((lat + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1) as usize;+    iy * GRID_NX + ix+}++impl Grid {+    fn build(boundaries: &[Boundary]) -> Grid {+        let mut grid = Grid { cells: vec![Vec::new(); GRID_NX * GRID_NY], overflow: Vec::new() };+        for (i, b) in boundaries.iter().enumerate() {+            let Some((x0, y0, x1, y1)) = b.bbox else {+                continue;+            };+            let (cx0, cy0) = (+                (((x0 + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1),+                (((y0 + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1),+            );+            let (cx1, cy1) = (+                (((x1 + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1),+                (((y1 + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1),+            );+            let count = (cx1 - cx0 + 1) as usize * (cy1 - cy0 + 1) as usize;+            if count > MAX_CELLS_PER_BOUNDARY {+                grid.overflow.push(i);+                continue;+            }+            for cy in cy0..=cy1 {+                for cx in cx0..=cx1 {+                    grid.cells[cy as usize * GRID_NX + cx as usize].push(i);+                }+            }+        }+        grid+    }++    /// Boundary indices that may contain `point`: its cell plus the overflow list.+    fn candidates_for(&self, point: (f64, f64)) -> impl Iterator<Item = usize> + '_ {+        self.cells[cell_of(point.0, point.1)]+            .iter()+            .copied()+            .chain(self.overflow.iter().copied())+    }+}++/// Is `point` inside `polygons`? Inside some exterior and in none of its holes.+fn point_in_boundary(point: (f64, f64), polygons: &[Polygon]) -> bool {+    polygons.iter().any(|poly| {+        let Some((exterior, holes)) = poly.split_first() else {+            return false;+        };+        point_in_ring(point, exterior) && !holes.iter().any(|hole| point_in_ring(point, hole))+    })+}++/// Point-to-segment distance at or below one e7 grid step (~1 cm) counts as on the edge.+///+/// e7-quantised coordinates snap to a 1e-7 grid, so anything closer than that is+/// indistinguishable from exactly on the line — and ray-casting there is a coin flip.+fn point_on_segment(point: (f64, f64), a: (f64, f64), b: (f64, f64)) -> bool {+    const EPS: f64 = 1e-7;+    let (px, py) = point;+    let dx = b.0 - a.0;+    let dy = b.1 - a.1;+    let len2 = dx * dx + dy * dy;+    if len2 == 0.0 {+        return (px - a.0).abs() <= EPS && (py - a.1).abs() <= EPS;+    }+    // Perpendicular distance, scale-aware: |cross| / |segment|.+    let cross = dx * (py - a.1) - dy * (px - a.0);+    if (cross / len2.sqrt()).abs() > EPS {+        return false;+    }+    px >= a.0.min(b.0) - EPS+        && px <= a.0.max(b.0) + EPS+        && py >= a.1.min(b.1) - EPS+        && py <= a.1.max(b.1) + EPS+}++/// Is `point` on any ring edge of `polygons`? Rings are explicitly closed, but the wrap edge is+/// checked too so an unclosed ring cannot hide one.+fn point_on_boundary_edge(point: (f64, f64), polygons: &[Polygon]) -> bool {+    polygons.iter().flat_map(|poly| poly.iter()).any(|ring| {+        if ring.len() < 2 {+            return false;+        }+        (0..ring.len()).any(|i| point_on_segment(point, ring[i], ring[(i + 1) % ring.len()]))+    })+}++/// Pick the link for one place: smallest in-band container wins, ties and edges link nothing.+fn select_link(point: (f64, f64), band: Band, candidates: &[&Boundary]) -> Option<u64> {+    // In-band, bbox-passing candidates only — the bbox is what keeps this off the PIP path.+    let mut passing: Vec<&Boundary> = Vec::new();+    for b in candidates {+        if band_for_level(b.level) != Some(band) {+            continue;+        }+        let Some((x0, y0, x1, y1)) = b.bbox else {+            continue;+        };+        if point.0 < x0 || point.0 > x1 || point.1 < y0 || point.1 > y1 {+            continue;+        }+        passing.push(*b);+    }+    // On any in-band edge the ray cast cannot be trusted — mask nothing.+    if passing.iter().any(|b| point_on_boundary_edge(point, &b.polygons)) {+        return None;+    }+    let mut best: Option<&Boundary> = None;+    let mut second = f64::INFINITY;+    for b in passing {+        if b.area <= 0.0 || !point_in_boundary(point, &b.polygons) {+            continue;+        }+        match best {+            None => best = Some(b),+            Some(cur) if b.area < cur.area => {+                second = cur.area;+                best = Some(b);+            }+            Some(_) => {+                second = second.min(b.area);+            }+        }+    }+    let best = best?;+    // Two containers within ~1% of each other is a coin flip (overlapping claims, duplicate+    // relations) — mask nothing rather than the wrong one.+    if second.is_finite() && (second - best.area) / best.area < 0.01 {+        return None;+    }+    Some(best.id)+}++/// Extend `region_links` with containment fallback links for member-less place labels.+///+/// Reads the finished store twice (boundaries, then places), inserts only keys still missing so+/// member links always win, and returns the counts the build log reports. The tiler reads the+/// extended map unchanged.+pub fn extend_region_links(+    store: &crate::store::Store,+    region_links: &mut HashMap<u64, u64>,+) -> Result<FallbackStats> {+    // Pass 1: boundary shapes. Only `region_area` areas (the mask's own shapes, carrying the+    // admin level in `kind_detail`); border lines enclose nothing.+    let mut boundaries: Vec<Boundary> = Vec::new();+    let mut reader = store.reader()?;+    while let Some(feature) = reader.next()? {+        if feature.class.layer != LAYER_BOUNDARIES || !feature.class.area {+            continue;+        }+        if feature.id == ID_NONE {+            continue;+        }+        let Geometry::Polygons(polygons) = feature.geometry else {+            continue;+        };+        if polygons.is_empty() {+            continue;+        }+        boundaries.push(Boundary::new(feature.id, feature.class.kind_detail, polygons));+    }+    boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0);+    let grid = Grid::build(&boundaries);++    // Pass 2: places. Positional, so node, way-centroided and relation-centroided labels all+    // link by the tagged id they already carry — the only path that can link non-node places,+    // since the member map is node-keyed.+    let mut stats = FallbackStats::default();+    let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new();+    let mut buf: Vec<&Boundary> = Vec::new();+    let mut reader = store.reader()?;+    while let Some(feature) = reader.next()? {+        if feature.class.layer != LAYER_PLACES {+            continue;+        }+        if feature.id == ID_NONE {+            continue;+        }+        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;+        };+        stats.places_total += 1;+        let entry = per_kind.entry(kind_name.to_string()).or_insert((0, 0));+        entry.0 += 1;+        if region_links.contains_key(&feature.id) {+            stats.member_linked += 1;+            entry.1 += 1;+            continue;+        }+        let Some(band) = band_for_place_kind(kind_name) else {+            continue;+        };+        buf.clear();+        buf.extend(grid.candidates_for(point).map(|i| &boundaries[i]));+        if let Some(target) = select_link(point, band, &buf) {+            region_links.insert(feature.id, target);+            stats.fallback_linked += 1;+            entry.1 += 1;+        }+    }+    stats.fallback_missed =+        stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked);+    let mut kinds: Vec<(String, u64, u64)> = per_kind+        .into_iter()+        .map(|(kind, (total, linked))| (kind, total, linked))+        .collect();+    kinds.sort_by(|a, b| a.0.cmp(&b.0));+    stats.per_kind = kinds;+    Ok(stats)+}++include!("extract_fallback_part1.rs");
scripts/maps/mamaps_build/src/extract_fallback_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_fallback_part1.rs b/scripts/maps/mamaps_build/src/extract_fallback_part1.rsnew file mode 100644index 0000000000..f32a2b897c--- /dev/null+++ b/scripts/maps/mamaps_build/src/extract_fallback_part1.rs@@ -0,0 +1,190 @@+#[cfg(test)]+mod tests {+    use super::*;++    /// A closed square ring, `min..max` in both axes.+    fn square(min: f64, max: f64) -> Polygon {+        vec![vec![(min, min), (max, min), (max, max), (min, max), (min, min)]]+    }++    fn boundary(id: u64, level: u16, polygons: Vec<Polygon>) -> Boundary {+        Boundary::new(id, level, polygons)+    }++    #[test]+    fn nested_shapes_link_each_place_kind_to_its_own_level() {+        // Country 0..100 (level 2), region 10..50 (level 4), locality 20..30 (level 8).+        let country = boundary(1, 2, vec![square(0.0, 100.0)]);+        let region = boundary(2, 4, vec![square(10.0, 50.0)]);+        let locality = boundary(3, 8, vec![square(20.0, 30.0)]);+        let all = [&country, &region, &locality];+        // A country label inside all three still links the country: bands isolate levels.+        assert_eq!(select_link((25.0, 25.0), Band::Country, &all), Some(1));+        assert_eq!(select_link((25.0, 25.0), Band::Region, &all), Some(2));+        assert_eq!(select_link((25.0, 25.0), Band::Locality, &all), Some(3));+        // A region label outside the region links nothing, not the country it sits in —+        // bands never fall back across levels.+        assert_eq!(select_link((5.0, 5.0), Band::Region, &all), None);+        assert_eq!(select_link((5.0, 5.0), Band::Country, &all), Some(1));+    }++    #[test]+    fn smallest_in_band_container_wins() {+        // Two localities nested: the tighter one wins.+        let big = boundary(1, 8, vec![square(20.0, 40.0)]);+        let small = boundary(2, 8, vec![square(25.0, 35.0)]);+        let both = [&big, &small];+        assert_eq!(select_link((30.0, 30.0), Band::Locality, &both), Some(2));+        // Order-independent.+        let swapped = [&small, &big];+        assert_eq!(select_link((30.0, 30.0), Band::Locality, &swapped), Some(2));+    }++    #[test]+    fn county_levels_match_nothing() {+        // Levels 5–6 are the documented gap: a place inside only a county links nowhere.+        let county = boundary(1, 6, vec![square(0.0, 100.0)]);+        let only = [&county];+        assert_eq!(select_link((50.0, 50.0), Band::Country, &only), None);+        assert_eq!(select_link((50.0, 50.0), Band::Region, &only), None);+        assert_eq!(select_link((50.0, 50.0), Band::Locality, &only), None);+        // A county boundary never steals a pick even when it is the tightest container.+        let country = boundary(2, 2, vec![square(0.0, 100.0)]);+        let mixed = [&county, &country];+        assert_eq!(select_link((50.0, 50.0), Band::Country, &mixed), Some(2));+    }++    #[test]+    fn near_tie_links_nothing() {+        // Two identical claims: areas equal, diff 0% — ambiguous.+        let first = boundary(1, 8, vec![square(0.0, 10.0)]);+        let second = boundary(2, 8, vec![square(0.0, 10.0)]);+        assert_eq!(select_link((5.0, 5.0), Band::Locality, &[&first, &second]), None);+        // Areas within 1% (10.0 vs 10.04 wide — 0.8% area diff) still ambiguous.+        let narrow = boundary(3, 8, vec![square(0.0, 10.0)]);+        let wide = boundary(4, 8, vec![square(0.0, 10.04)]);+        assert_eq!(select_link((5.0, 5.0), Band::Locality, &[&narrow, &wide]), None);+        // A clear 2x nesting is not a tie.+        let big = boundary(5, 8, vec![square(0.0, 20.0)]);+        assert_eq!(select_link((5.0, 5.0), Band::Locality, &[&narrow, &big]), Some(3));+    }++    #[test]+    fn a_point_on_a_ring_edge_links_nothing() {+        let square8 = boundary(1, 8, vec![square(0.0, 10.0)]);+        let only = [&square8];+        // On the west edge: ray-casting is a coin flip, so this is a deliberate miss.+        assert_eq!(select_link((0.0, 5.0), Band::Locality, &only), None);+        // Just inside still links.+        assert_eq!(select_link((0.5, 5.0), Band::Locality, &only), Some(1));+    }++    #[test]+    fn holes_punch_out() {+        // A locality donut: exterior 0..10 with a 4..6 hole. A place in the hole is not inside.+        let donut = boundary(1, 8, vec![vec![+            vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)],+            vec![(4.0, 4.0), (6.0, 4.0), (6.0, 6.0), (4.0, 6.0), (4.0, 4.0)],+        ]]);+        let only = [&donut];+        assert_eq!(select_link((2.0, 2.0), Band::Locality, &only), Some(1));+        assert_eq!(select_link((5.0, 5.0), Band::Locality, &only), None);+    }++    #[test]+    fn sub_locality_places_never_link() {+        assert_eq!(band_for_place_kind("neighbourhood"), None);+        assert_eq!(band_for_place_kind("macrohood"), None);+        assert_eq!(band_for_place_kind("country"), Some(Band::Country));+        assert_eq!(band_for_place_kind("region"), Some(Band::Region));+        assert_eq!(band_for_place_kind("locality"), Some(Band::Locality));+    }++    /// End to end over a spilled store: member links win, member-less places gain links+    /// (including a way-id place the node-keyed member map could never reach), and the county+    /// gap still misses.+    #[test]+    fn member_links_win_and_member_less_places_gain_links() {+        use crate::extract::{tagged_id, Feature, ELEMENT_NODE, ELEMENT_RELATION, ELEMENT_WAY};++        fn place(id: u64, place_tag: &str, point: (f64, f64)) -> Feature {+            let class = crate::schema::places::classify(+                &[("place", place_tag), ("name", "Test")] as &[(&str, &str)],+            )+            .expect("classified");+            Feature {+                class,+                geometry: Geometry::Points(vec![point]),+                name: Some("Test".to_string()),+                id,+                transit_color: 0,+                transit_ordinal: 0,+                transit_lanes: 0,+                transit_taper: 0,+                lane_count: 0,+                turn_fwd: Vec::new(),+                turn_bwd: Vec::new(),+                carriageway: tilecodec::mamaps::body::Carriageway::default(),+                building: None,+            }+        }++        fn shape(id: u64, level: &str, ring: Polygon) -> Feature {+            let class = crate::schema::boundaries::region_area(+                &[("boundary", "administrative"), ("admin_level", level)] as &[(&str, &str)],+                false,+            )+            .expect("region shape");+            Feature {+                class,+                geometry: Geometry::Polygons(vec![ring]),+                name: None,+                id,+                transit_color: 0,+                transit_ordinal: 0,+                transit_lanes: 0,+                transit_taper: 0,+                lane_count: 0,+                turn_fwd: Vec::new(),+                turn_bwd: Vec::new(),+                carriageway: tilecodec::mamaps::body::Carriageway::default(),+                building: None,+            }+        }++        // A city boundary (level 8) 20..30 and a county boundary (level 6) 0..100.+        let city_id = tagged_id(201, ELEMENT_RELATION);+        let county_id = tagged_id(202, ELEMENT_RELATION);+        let member_target = tagged_id(203, ELEMENT_RELATION);+        // A member-linked town: fallback would pick the city, the member must win.+        let linked_town = tagged_id(101, ELEMENT_NODE);+        // A member-less town (node) and a member-less village mapped as a way.+        let bare_town = tagged_id(102, ELEMENT_NODE);+        let way_village = tagged_id(103, ELEMENT_WAY);+        // A country label sitting where only the county covers it: must stay unlinked.+        let bare_country = tagged_id(104, ELEMENT_NODE);+        let features = vec![+            shape(city_id, "8", square(20.0, 30.0)),+            shape(county_id, "6", square(0.0, 100.0)),+            place(linked_town, "town", (25.0, 25.0)),+            place(bare_town, "town", (26.0, 26.0)),+            place(way_village, "village", (27.0, 27.0)),+            place(bare_country, "country", (50.0, 50.0)),+        ];+        let store = crate::store::Store::of(&features).expect("spilled");++        let mut links: HashMap<u64, u64> = HashMap::new();+        links.insert(linked_town, member_target);+        let stats = extend_region_links(&store, &mut links).expect("fallback");++        assert_eq!(links.get(&linked_town), Some(&member_target), "member wins over fallback");+        assert_eq!(links.get(&bare_town), Some(&city_id), "member-less town gains the city");+        assert_eq!(links.get(&way_village), Some(&city_id), "way-id place links by position");+        assert!(!links.contains_key(&bare_country), "county gap: no link for the country label");++        assert_eq!(stats.places_total, 4);+        assert_eq!(stats.member_linked, 1);+        assert_eq!(stats.fallback_linked, 2);+        assert_eq!(stats.fallback_missed, 1);+    }+}
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex 8884ea656e..f34563d0d7 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -43,6 +43,7 @@ mod coalesce_extra; mod corridor; mod dem; mod extract;+mod extract_fallback; mod lanefill; mod rings; mod shapefile;
scripts/maps/mamaps_build/src/main_part1.rs
diff --git a/scripts/maps/mamaps_build/src/main_part1.rs b/scripts/maps/mamaps_build/src/main_part1.rsindex a0fd9ca26d..37010cbe69 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -55,7 +55,7 @@ fn run(     // an empty graph dir with no `metadata.bin`, paid for in full.     check_graph_dir(&graph_dir, run.region)?; -    let (store, stats, region_links) = extract::extract(+    let (store, stats, mut region_links) = extract::extract(         input,         layers,         &run.coastline,@@ -65,6 +65,27 @@ fn run(         run.region.bbox(),     )     .map_err(|e| format!("{}: {e}", input.display()))?;+    // The containment fallback: member-less place labels gain links from the whole-polygon+    // shapes above, never overwriting a member link. Runs here — after the store is sealed+    // and before the tiler reads the map — because only whole rings answer containment.+    match crate::extract_fallback::extend_region_links(&store, &mut region_links) {+        Ok(fallback) => {+            if fallback.places_total > 0 {+                println!(+                    "  place-label -> boundary links: {} place(s), {} member-linked, {} fallback-linked, {} missed",+                    fallback.places_total,+                    fallback.member_linked,+                    fallback.fallback_linked,+                    fallback.fallback_missed,+                );+                for (kind, total, linked) in &fallback.per_kind {+                    let rate = *linked as f64 / (*total).max(1) as f64 * 100.0;+                    println!("    {kind}: {linked}/{total} ({rate:.0}%)");+                }+            }+        }+        Err(e) => return Err(format!("region fallback: {e}")),+    }     println!(         "classified {} way(s), {} relation(s) and {} node(s) -> {} feature(s), {} node(s) resolved",         stats.ways_classified,@@ -108,9 +129,6 @@ fn run(             stats.lanes_inherited,         );     }-    if !region_links.is_empty() {-        println!("  including {} place-label -> boundary link(s)", region_links.len());-    }      // The build id identifies the *data*: change the input and every reader has to drop its     // cache. Derived rather than asked for, so a forgotten input cannot silently republish