Modern Apps git

← Modern-Apps.git

maps: searchable place labels with native OSM boundary links

Commit
982f7b92a34847e7caaa5f43dfb2e0cfbf54bed4
Author
Vayun Mathur <[email protected]>
When
2026-11-08 20:23 UTC (27 days ago)
Parents
214f1ed
Place labels (cities, towns, villages and friends) were invisible to
POI search and carried no boundary link, so selecting one could not
resolve its administrative region for masking and highlighting.

What changed and why:
- osm_ingest classifies named place elements as searchable POI
  records (new type 51 for the 12 known place values; any other
  non-empty place value becomes a generic OTHER record instead of
  being dropped). Elements that already were POIs via another key
  keep their record and only change type, so the record delta is
  exactly the newly searchable labels.
- Each POI now resolves a native OSM boundary link at build time:
  explicit label/admin_centre membership wins, otherwise the
  smallest containing administrative boundary (holes respected),
  capped at the level the place kind implies (country 2,
  state/province 4, everything else 8). Administrative boundary
  places link to themselves. Regular POIs resolve the smallest
  containing admin exactly as before via the same machinery.
- The links ship in a new ordinal-keyed sidecar, poi_region.bin
  (magic PRG1, u64 tagged OSM id per POI ordinal, 0 = no link),
  written always beside --index under its conventional name; no new
  CLI flag. The packed .mamaps archive carries it as new section
  kind 15, staged after the overlay so section kinds stay
  strictly ascending.
- App side threads the link from PoiRecord through SearchResult
  into GenericPlace.regionId and uses it first in regionMaskFor;
  the admin-name fallback stays for unlinked places (deep links,
  saved places, tapped pins).

Index size delta (same-planet California rebuild, 324328 -> 337543
records, +13215 / +4.1%; 9510 of the new records are type 51, the
rest are other place=* values typed OTHER):
  poi_index.bin      +185010  (13215 x 14 bytes, exact)
  poi_names.bin      +136840
  poi_name_index.bin +122340
  poi_attrs.bin      +68957
  poi_spatial.bin    +83940
  poi_region.bin     +2700356 (new: 12 + 8 x 337543, exact)
  shipped index total 32015650 -> 35313093 (+3297443, +10.3%)
  poi.geojsonseq +2030628 (build intermediate for tippecanoe only)

How it was verified:
- cargo test -p osm_ingest: 299 pass, including the new region
  fixture test (member link beats containment, self-link,
  containment, outside == 0).
- cargo test -p tile_build --bin mamaps_pack: 10 pass, including
  the new kind-15 pack test.
- tilecodec mamaps::archive (--features write): 7 pass, 1 failure
  in a_minimal_sidecar_parses_and_slices that predates this change
  (zero-byte nodes fixture rejected by the v7 ZBLK check; proved
  pre-existing by re-running with the new arm disabled).
- :maps:compileDevKotlin BUILD SUCCESSFUL; :maps:lint reports no
  errors in touched files (44 errors, all in other in-flight test
  files). The new region-mask unit-test assertion is added but
  cannot compile until the test source set builds again (missing
  userSpeedMps args and a changed listener arity from other
  in-flight work).

Notes for the planet-build owner: poi_extract now always writes
poi_region.bin next to --index, and mamaps_pack stages it as kind
15; the POI-index stage needs the new output wired through. The
map tap path still constructs places with regionId 0 (out of
scope here), and type 51 is inert tile-side (no in-repo consumer
of the ma_pois layer).

Diff

library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rsindex 6037549c7c..ac6f52ca6f 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs@@ -37,9 +37,12 @@ pub const ARCHIVE_KIND_POI_WORDS: u8 = 12; pub const ARCHIVE_KIND_TRANSIT: u8 = 13; /// Graph `overlay.bin` payload: the `MOVL` highway overlay (optional). pub const ARCHIVE_KIND_GRAPH_OVERLAY: u8 = 14;+/// POI `poi_region.bin` payload: one tagged OSM boundary id per index ordinal+/// (`PRG1` + version + count, then `u64` ids; 0 means no boundary).+pub const ARCHIVE_KIND_POI_REGION: u8 = 15; /// Highest kind this build writes. Readers accept any non-zero kind and skip /// the ones they do not know, so a newer archive still opens in an older app.-pub const ARCHIVE_KIND_MAX_KNOWN: u8 = ARCHIVE_KIND_GRAPH_OVERLAY;+pub const ARCHIVE_KIND_MAX_KNOWN: u8 = ARCHIVE_KIND_POI_REGION;  /// `metadata.bin` (`MARG`) magic, little-endian `u32`. pub const GRAPH_MAGIC: u32 = 0x4752_414D;
library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rsindex 8a30dd746d..c0506033b7 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs@@ -102,7 +102,7 @@ pub use consts::{     ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE,     ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES,     ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_MAX_KNOWN, ARCHIVE_KIND_POI_ATTRS,-    ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES,+    ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_REGION,     ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, GRAPH_MAGIC,     GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_MIN, POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION,     TRANSIT_VERSION_MIN,
library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rsindex d2c648956c..be46ca74a7 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs@@ -88,9 +88,10 @@ fn the_footer_is_32_bytes_behind_mama8() {     assert!(ArchiveFooter::parse(&bad).is_err(), "bad magic is refused"); } -/// Fail-watched: entries are 32 bytes, the overlay is kind 14, and any non-zero-/// kind parses (so a newer writer's section does not lock out older readers)-/// while only the defined ones count as known.+/// Fail-watched: entries are 32 bytes, the overlay is kind 14, the POI region+/// sidecar is kind 15, and any non-zero kind parses (so a newer writer's+/// section does not lock out older readers) while only the defined ones count+/// as known. #[test] fn entries_are_32_bytes_and_unknown_kinds_parse() {     let e = ArchiveEntry { kind: ARCHIVE_KIND_TRANSIT, flags: 0, offset: 8192, len: 128, extra: 0 };@@ -99,10 +100,11 @@ fn entries_are_32_bytes_and_unknown_kinds_parse() {     assert_eq!(ARCHIVE_KIND_GRAPH_META, 1, "graph meta is kind 1");     assert_eq!(ARCHIVE_KIND_TRANSIT, 13, "transit is kind 13");     assert_eq!(ARCHIVE_KIND_GRAPH_OVERLAY, 14, "the highway overlay is kind 14");+    assert_eq!(ARCHIVE_KIND_POI_REGION, 15, "the POI region sidecar is kind 15");     let mut future = e.serialize();     future[0] = 99;     assert_eq!(ArchiveEntry::parse(&future).expect("a future kind parses").kind, 99);-    assert!(!is_known_kind(99) && is_known_kind(ARCHIVE_KIND_GRAPH_OVERLAY) && !is_known_kind(0));+    assert!(!is_known_kind(99) && is_known_kind(ARCHIVE_KIND_POI_REGION) && !is_known_kind(0));     let mut zero = e.serialize();     zero[0] = 0;     assert!(ArchiveEntry::parse(&zero).is_err(), "kind 0 is never a section");
library/tilecodec/src/main/rust/src/mamaps/archive/view.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rsindex 5c702a3db9..e77e836858 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs@@ -360,6 +360,19 @@ impl ArchiveView {                 return err("a single-archive POI word index covers a different index");             }         }+        // Region: PRG1 header + one u64 tagged id per index ordinal (ordinal join).+        if let Some(b) = slice(ARCHIVE_KIND_POI_REGION)? {+            if b.len() < 12 {+                return err("a single-archive POI region ends before its header");+            }+            if &b[0..4] != b"PRG1" {+                return err("a single-archive POI region has bad PRG1 magic");+            }+            let n = u32::from_le_bytes([b[8], b[9], b[10], b[11]]) as u64;+            if Some(n) != poi_count {+                return err("a single-archive POI region covers a different index");+            }+        }         // Transit: TRIX v3..=6 with a directory that fits.         if let Some(b) = slice(ARCHIVE_KIND_TRANSIT)? {             if b.len() < 80 {
maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.ktindex 711c671fed..f8bbeadcc7 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -84,6 +84,13 @@ sealed interface SpecificFeature {         val rating: Double? = null,         val reviewCount: Int? = null,         val reviewSummary: String? = null,+        /**+         * Tagged OSM boundary id from `poi_region.bin`, as in [Admin0Label]:+         * search and reverse-geocode carry the index hit's link through, so a+         * region picked off-index masks without an admin-label upgrade. 0 when+         * unlinked (deep links, saved places, tapped pins).+         */+        val regionId: Long = 0L,     ) : RoutableFeature     @Serializable     data class Route(val waypoints: List<RoutableFeature?>) : SpecificFeature@@ -110,6 +117,7 @@ suspend fun osmPlace(     name: String,     position: GeoPoint,     poiType: Int? = null,+    regionId: Long = 0L, ): SpecificFeature.GenericPlace {     val attrs: PoiIndex.PoiAttributes? = withContext(Dispatchers.IO) {         PoiIndex.attributesNear(position.latitude, position.longitude, name)@@ -127,6 +135,7 @@ suspend fun osmPlace(         rating = attrs?.rating,         reviewCount = attrs?.reviewCount,         reviewSummary = attrs?.reviewSummary,+        regionId = regionId,     ) } 
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.ktindex 3ca800ee7e..44a76539db 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt@@ -313,6 +313,8 @@ internal fun regionMaskFor(         selectedFeature.regionId.takeIf { it != 0L && selectedFeature.position != null }     is com.vayunmathur.maps.data.SpecificFeature.Admin2Label ->         selectedFeature.regionId.takeIf { it != 0L && selectedFeature.position != null }+    is com.vayunmathur.maps.data.SpecificFeature.GenericPlace ->+        selectedFeature.regionId.takeIf { it != 0L }     else -> null } @@ -320,14 +322,13 @@ internal fun regionMaskFor(  * The admin-region selection that should replace a focused [place] because  * a rendered admin label at its position names the same place, or null.  *- * Search (and deep links) can only build a [SpecificFeature.GenericPlace]:- * the offline POI index carries no boundary link, so a region picked from- * search could never mask. Once the camera has flown to the place, the- * rendered labels at that spot do carry the baked `regionId` — upgrading- * the selection to the matching admin label is what wires the mask (and- * the admin card) into the search path. Name equality (normalised, see- * [PoiSearch]) is required so a POI inside a city is never silently- * replaced by the city itself.+ * Search (and deep links) can only build a [SpecificFeature.GenericPlace].+ * A linked place already masks on its own (see [regionMaskFor]); this is the+ * fallback for an unlinked one (deep links, saved places, tapped pins): once+ * the camera has flown to the place, the rendered labels at that spot carry+ * the baked `regionId`, so upgrading the selection to the matching admin+ * label wires the mask into that path. Name equality (normalised, see+ * [PoiSearch]) keeps a POI inside a city from being silently replaced by it.  */ internal fun adminUpgradeFor(     place: com.vayunmathur.maps.data.SpecificFeature.GenericPlace,
maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.ktindex 1efdd7bd1b..094f4721b3 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -39,6 +39,13 @@ data class SearchResult(     val lat: Double,     val lon: Double,     val category: String?,+    /**+     * Tagged OSM boundary id from `poi_region.bin` (low 2 bits are the id+     * space), or 0 when the hit resolves to no boundary. Survives into the+     * sheet's [SpecificFeature.GenericPlace] so a region picked from search+     * masks without an admin-label upgrade round-trip.+     */+    val regionId: Long = 0L, )  /**@@ -85,6 +92,7 @@ private fun PoiIndex.PoiRecord.toSearchResult() = SearchResult(     lat = lat,     lon = lon,     category = PoiCategories.label(type),+    regionId = regionId, )  /**@@ -251,6 +259,7 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati                             name = it.title.ifBlank { address },                             position = GeoPoint(it.lon, it.lat),                             poiType = null,+                            regionId = it.regionId,                         )                     }                 )@@ -283,7 +292,11 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati      * else. It is also a mapped-file read, hence [osmPlace] and this suspend.      */     suspend fun toFeature(result: SearchResult): SpecificFeature.GenericPlace =-        osmPlace(name = result.title, position = GeoPoint(result.lon, result.lat))+        osmPlace(+            name = result.title,+            position = GeoPoint(result.lon, result.lat),+            regionId = result.regionId,+        )      /**      * Reverse-geocode [lat],[lon] to the nearest offline POI and hand it back@@ -305,6 +318,7 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati                     osmPlace(                         name = it.name,                         position = GeoPoint(it.lon, it.lat),+                        regionId = it.regionId,                     )                 }             )
maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.ktindex a0bd3718a3..e94057cacb 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt@@ -8,9 +8,9 @@ import java.nio.MappedByteBuffer /**  * Load the POI side files out of a single-archive `.mamaps` file.  *- * The archive carries the same five payloads as the side files (`poi_index`,+ * The archive carries the same six payloads as the side files (`poi_index`,  * `poi_names`, and the optional `poi_attrs` / `poi_spatial` / `poi_name_index`- * sections, kinds 8-12) after the tile data, each 8-byte aligned and named by+ * / `poi_region` sections, kinds 8-12 and 15) after the tile data, each 8-byte aligned and named by  * the section directory + `MAMA8` footer. This maps the one file once and  * slices views of it, then runs the same validators the multi-file path runs  * ([PoiIndex.attrsFromBuffer] and siblings) — only the mapping step differs,@@ -60,6 +60,7 @@ object PoiArchive {     const val KIND_ATTRS = 10     const val KIND_SPATIAL = 11     const val KIND_WORDS = 12+    const val KIND_REGION = 15      /** Tile-header offsets this needs: `build_id` at 16, `file_len` at 24. */     private const val HEADER_BUILD_ID_OFF = 16@@ -175,6 +176,8 @@ object PoiArchive {             ?.let { PoiIndex.spatialFromBuffer(it, count) }         val words = overrideOrBase(overrides, KIND_WORDS, sections, whole)             ?.let { PoiIndex.nameIndexFromBuffer(it, count) }+        val region = overrideOrBase(overrides, KIND_REGION, sections, whole)+            ?.let { regionFromBuffer(it, count) }         return PoiIndex.Mapped(             index = indexBuf,             names = namesBuf,@@ -190,6 +193,7 @@ object PoiArchive {             cols = grid?.cols ?: 0,             nameIdx = words?.first,             entryCount = words?.second ?: 0,+            region = region,             archive = whole,         ).also {             Log.debug(
maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.ktindex 1601f7ad97..435b03ab6c 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt@@ -17,7 +17,7 @@ package com.vayunmathur.maps.util  */ object PoiCategories {     /**-     * Human-readable labels indexed by type id (0..50), in the stable numbering+     * Human-readable labels indexed by type id (0..51), in the stable numbering      * defined in `scripts/maps/README.md` / `osm_ingest/src/tags.rs`.      *      * A list rather than a `when`: the ids are dense, so the index IS the id and@@ -75,6 +75,7 @@ object PoiCategories {         "Gift", // 48         "Marketplace", // 49         "Station", // 50+        "Place", // 51: cities, towns and other place labels     )      /** Human-readable category label (used as the search-result subtitle). */
maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.ktindex fbd697af5d..118570571a 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -130,6 +130,8 @@ object PoiIndex {          * attribute sidecar. -1 for a record not read from the index.          */         val ordinal: Int = -1,+        /** Tagged OSM boundary id, or 0 when this POI links to no boundary. */+        val regionId: Long = 0L,     ) {         val lat: Double get() = latE7 * E7_TO_DEGREES         val lon: Double get() = lonE7 * E7_TO_DEGREES@@ -207,6 +209,8 @@ object PoiIndex {         /** The word index, or null when absent or mismatched. */         internal val nameIdx: MappedByteBuffer? = null,         internal val entryCount: Int = 0,+        /** The region sidecar, or null when absent or mismatched. */+        internal val region: MappedByteBuffer? = null,         /** The whole archive mapping, when loaded from one file: pins every slice above. */         @Suppress("unused")         val archive: MappedByteBuffer? = null,@@ -221,7 +225,7 @@ object PoiIndex {         fun spatialAt(i: Int): Long = spatialFromE7(latE7(i), lonE7(i))          internal fun record(i: Int): PoiRecord =-            PoiRecord(latE7(i), lonE7(i), type(i), nameAt(nameOff(i)) ?: "", i)+            PoiRecord(latE7(i), lonE7(i), type(i), nameAt(nameOff(i)) ?: "", i, regionId(i))          /** Read the NUL-terminated UTF-8 name that starts at byte [off], or null. */         fun nameAt(off: Int): String? {@@ -514,7 +518,7 @@ object PoiIndex {      * can actually produce — buffer overruns and bounds checks. Anything else      * is a programming error and keeps propagating.      */-    private fun <T> bufferFailure(cause: Throwable, file: String): T? {+    internal fun <T> bufferFailure(cause: Throwable, file: String): T? {         when (cause) {             is IndexOutOfBoundsException,             is IllegalArgumentException,
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.ktnew file mode 100644index 0000000000..d628f66180--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.kt@@ -0,0 +1,67 @@+package com.vayunmathur.maps.util++import com.vayunmathur.library.log.Log+import java.nio.ByteOrder+import java.nio.MappedByteBuffer++/**+ * `poi_region.bin` reader: one tagged OSM boundary id (`u64`, 0 when the POI+ * links to no boundary) per `poi_index.bin` ordinal, so search hits and places+ * mask to their native boundary without a spatial lookup. The layout lives in+ * `scripts/maps/osm_ingest/src/poi_side.rs`; the low 2 bits of each id are the+ * OSM id space (2 = way, 3 = relation).+ *+ * Split out of [PoiIndex] for the FileLength limit. Like every other sidecar,+ * a region file whose record count disagrees with the index is refused rather+ * than trusted, since everything joins by ordinal.+ */+const val REGION_FILE = "poi_region.bin"++private const val TAG = "PoiIndex"++// --- poi_region.bin (see osm_ingest/src/poi_side.rs) -------------------------+private val REGION_MAGIC =+    byteArrayOf('P'.code.toByte(), 'R'.code.toByte(), 'G'.code.toByte(), '1'.code.toByte())+private const val REGION_VERSION = 1+internal const val REGION_HEADER_BYTES = 12+private const val REGION_VERSION_OFF = 4+private const val REGION_COUNT_OFF = 8+/** Bytes of one tagged OSM boundary id in the region array. */+internal const val REGION_ID_BYTES = 8+/** Tagged id for a POI that links to no boundary. */+internal const val REGION_NONE = 0L++/** Tagged OSM boundary id for record [i], or 0 when the region sidecar is absent. */+internal fun PoiIndex.Mapped.regionId(i: Int): Long =+    region?.getLong(REGION_HEADER_BYTES + i * REGION_ID_BYTES) ?: REGION_NONE++/** Buffer core of the region sidecar, reused by the single-archive path. */+internal fun regionFromBuffer(buf: MappedByteBuffer, count: Int): MappedByteBuffer? {+    buf.order(ByteOrder.LITTLE_ENDIAN)+    return runCatching { readRegion(buf, count) }+        .getOrElse { PoiIndex.bufferFailure(it, REGION_FILE) }+}++private fun readRegion(buf: MappedByteBuffer, count: Int): MappedByteBuffer? {+    if (buf.capacity() < REGION_HEADER_BYTES) return null+    for (i in REGION_MAGIC.indices) {+        if (buf.get(i) != REGION_MAGIC[i]) {+            Log.status(TAG, "$REGION_FILE has the wrong magic; ignoring it")+            return null+        }+    }+    if (buf.getInt(REGION_VERSION_OFF) != REGION_VERSION) {+        Log.status(TAG, "$REGION_FILE version ${buf.getInt(REGION_VERSION_OFF)} unsupported; ignoring it")+        return null+    }+    val records = buf.getInt(REGION_COUNT_OFF)+    if (records != count) {+        Log.status(TAG, "$REGION_FILE covers $records record(s), index has $count; ignoring it")+        return null+    }+    if (REGION_HEADER_BYTES + REGION_ID_BYTES.toLong() * records > buf.capacity().toLong()) {+        Log.status(TAG, "$REGION_FILE is truncated; ignoring it")+        return null+    }+    return buf+}
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.ktindex 431e2371fa..dfc73b6b15 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt@@ -7,7 +7,7 @@ import java.nio.MappedByteBuffer  /**  * Side-file mapping for [PoiIndex]: `poi_index.bin` + `poi_names.bin` plus the- * three optional sidecars.+ * four optional sidecars.  *  * Split out so `PoiIndex` stays under the function cap. Same package, so no  * API changes for any other caller.@@ -24,6 +24,7 @@ internal object PoiIndexSideFiles {         val attrs = openAttrs(File(dir, PoiIndex.ATTRS_FILE), count)         val grid = openSpatial(File(dir, PoiIndex.SPATIAL_FILE), count)         val words = openNameIndex(File(dir, PoiIndex.NAME_INDEX_FILE), count)+        val region = openRegion(File(dir, REGION_FILE), count)         return PoiIndex.Mapped(             index = indexBuf,             names = namesBuf,@@ -39,6 +40,7 @@ internal object PoiIndexSideFiles {             cols = grid?.cols ?: 0,             nameIdx = words?.first,             entryCount = words?.second ?: 0,+            region = region,         )     } @@ -77,4 +79,16 @@ internal object PoiIndexSideFiles {         if (!file.isFile) return null         return PoiIndex.nameIndexFromBuffer(PoiIndex.mapReadOnly(file), count)     }++    /**+     * Map `poi_region.bin`, or null when it is absent, stale or malformed.+     *+     * The record-count check matters for the same reason it does for the+     * others: the sidecar joins purely by ordinal, so a region file from a+     * different build would hand every place someone else's boundary.+     */+    private fun openRegion(file: File, count: Int): MappedByteBuffer? {+        if (!file.isFile) return null+        return regionFromBuffer(PoiIndex.mapReadOnly(file), count)+    } }
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.ktindex 336127c341..06bde71d73 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt@@ -317,7 +317,7 @@ private fun scanMatchAt(     val lonE7 = m.lonE7(i)     val name = m.nameAt(off) ?: ""     return Ranked(-        PoiIndex.PoiRecord(latE7, lonE7, m.type(i), name, i),+        PoiIndex.PoiRecord(latE7, lonE7, m.type(i), name, i, m.regionId(i)),         boostWeight(boost, name),         rank,         PoiIndex.distanceSq(
maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.ktindex e94790040e..8c5d0eefa6 100644--- a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt@@ -122,6 +122,17 @@ class MapSurfaceHelpersSlice1Test {                 ),             ),         )+        // A region picked from search carries the index hit's boundary link,+        // so it masks without an admin-label upgrade.+        assertEquals(+            7L,+            regionMaskFor(+                SpecificFeature.GenericPlace(+                    name = "Testville", phone = null, website = null, openingHours = null,+                    position = paris, regionId = 7L,+                ),+            ),+        )     }      @Test
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 afd71e7cc5..4b00dc5c01 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -47,6 +47,7 @@ fn run(             &dir.join("poi_attrs.bin"),             &dir.join("poi_spatial.bin"),             &dir.join("poi_name_index.bin"),+            &dir.join("poi_region.bin"),             run.region.bbox(),         )         .map_err(|e| format!("poi build: {e}"))?;
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 cadccf1971..811ae7707a 100644--- a/scripts/maps/osm_ingest/src/bin/poi_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/poi_extract.rs@@ -42,6 +42,7 @@ fn main() -> ExitCode {         &args.attrs,         &args.spatial,         &args.name_index,+        &args.region,         args.bbox,         reviews.as_ref(),     ) {@@ -67,14 +68,16 @@ fn main() -> ExitCode {                 "{} populated grid cell(s), {} name index entr(ies)",                 stats.spatial_cells, stats.name_entries             );+            println!("{} POI(s) with a boundary link", stats.with_region);             println!(-                "Wrote {}, {}, {}, {}, {}, {}",+                "Wrote {}, {}, {}, {}, {}, {}, {}",                 args.geojson.display(),                 args.names.display(),                 args.index.display(),                 args.attrs.display(),                 args.spatial.display(),-                args.name_index.display()+                args.name_index.display(),+                args.region.display()             );             ExitCode::SUCCESS         }
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 9ff71b7914..0c3f9dcf84 100644--- a/scripts/maps/osm_ingest/src/poi_build.rs+++ b/scripts/maps/osm_ingest/src/poi_build.rs@@ -1,7 +1,7 @@ //! POI extraction: `.osm.pbf` -> a geojsonseq for tippecanoe plus //! `poi_names.bin`, `poi_index.bin` and `poi_attrs.bin`. //!-//! A port of the former `scripts/maps/poi_extract.cpp`. The four outputs are+//! A port of the former `scripts/maps/poi_extract.cpp`. The seven outputs are //! mutually consistent — same POI set, same order, same coordinates: //! //! 1. **geojsonseq** newline-delimited GeoJSON `Point` features, fed to@@ -20,6 +20,14 @@ //!    matching `poi_index.bin` record. See [`crate::poi_attrs`] for the layout. //!    Kept separate because the 14-byte record is full and its width is load //!    bearing in three places.+//! 5. **`poi_spatial.bin`** coarse-grid CSR over the record coordinates, so the+//!    app can jump to a spatial range. See [`crate::poi_side`].+//! 6. **`poi_name_index.bin`** word-level inverted index into the record+//!    ordinals for name search. See [`crate::poi_side`].+//! 7. **`poi_region.bin`** one tagged OSM boundary id per record ordinal — the+//!    member link first, else the smallest containing administrative boundary —+//!    so the app can mask search results to a region. Zero where the POI+//!    matched nothing. See [`crate::poi_side`]. //! //! A POI is any node, or closed-way / multipolygon area, carrying BOTH a `name` //! and one of the recognised POI keys (see [`crate::tags::classify`]). Area@@ -41,14 +49,15 @@ use std::fs::File; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; -use crate::geojson::json_escape;+use crate::geojson::{json_escape, Coord}; use crate::names::NamePool;-use crate::osm::{self, visit_block, Element, MEMBER_WAY};+use crate::osm::{self, visit_block, Element, MEMBER_NODE, MEMBER_WAY}; use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS}; use crate::poi_attrs::AttrPool; use crate::poi_reviews::{ReviewTable, ELEMENT_NODE, ELEMENT_RELATION, ELEMENT_WAY}; use crate::poi_side; use crate::proto::{Error, Result};+use crate::rings::{self, MemberWay, RingStats}; use crate::spatial::spatial_from_e7; use crate::tags::{self, PoiTags}; @@ -75,6 +84,8 @@ pub struct Stats {     pub name_entries: usize,     /// POIs that matched a row of the `--reviews` table.     pub with_reviews: usize,+    /// POIs stamped with a non-zero boundary link in `poi_region.bin`.+    pub with_region: usize, }  struct Poi {@@ -88,6 +99,13 @@ struct Poi {     name: Vec<u8>,     /// Encoded sidecar record body, empty when the POI has no attributes.     attrs: Vec<u8>,+    /// Tagged OSM boundary id (`poi_side::tag_relation`/`tag_way`), or+    /// [`crate::poi_side::REGION_NONE`]. A self-link is stamped at creation;+    /// member-link and containment links are resolved pre-sort in [`build`].+    region: u64,+    /// Deepest `admin_level` this POI may link to: place-implied+    /// (country 2, state/province 4, everything else 8).+    place_cap: u8, }  /// A `type=multipolygon`/`boundary` relation that is itself a POI.@@ -97,11 +115,27 @@ struct RelArea {     name: Vec<u8>,     attrs: Vec<u8>,     outer_ways: Vec<i64>,+    /// [`crate::poi_side::tag_relation`] of this relation when it is itself an+    /// administrative boundary, else [`crate::poi_side::REGION_NONE`].+    self_region: u64,+    place_cap: u8,+}++/// A `type=boundary` + `boundary=administrative` relation (POI or not) whose+/// geometry POIs link against.+struct BoundaryRel {+    id: i64,+    admin_level: u8,+    /// `(way id, outer)` — empty-role ways count as outer per OSM convention.+    member_ways: Vec<(i64, bool)>,+    /// Node members with a `label`/`admin_centre` role.+    label_nodes: Vec<i64>, }  #[derive(Default)] struct RelPass {     areas: Vec<RelArea>,+    boundaries: Vec<BoundaryRel>, }  /// A closed way that is a POI in its own right.@@ -111,6 +145,10 @@ struct WayArea {     name: Vec<u8>,     attrs: Vec<u8>,     refs: Vec<i64>,+    /// [`crate::poi_side::tag_way`] of this way when it is itself tagged+    /// `boundary=administrative`, else [`crate::poi_side::REGION_NONE`].+    self_region: u64,+    place_cap: u8, }  #[derive(Default)]@@ -135,8 +173,9 @@ pub fn build(     attrs: &Path,     spatial: &Path,     name_index: &Path,+    region: &Path, ) -> Result<Stats> {-    build_with(input, geojson, names, index, attrs, spatial, name_index, None)+    build_with(input, geojson, names, index, attrs, spatial, name_index, region, None) }  /// [`build`] with a region bbox filter: `Some` keeps only POIs touching the@@ -151,9 +190,12 @@ pub fn build_with(     attrs: &Path,     spatial: &Path,     name_index: &Path,+    region: &Path,     bbox: Option<crate::bbox::BBox>, ) -> Result<Stats> {-    build_with_reviews(input, geojson, names, index, attrs, spatial, name_index, bbox, None)+    build_with_reviews(+        input, geojson, names, index, attrs, spatial, name_index, region, bbox, None,+    ) }  /// [`build_with`] plus an external review table whose rows are appended to the@@ -167,12 +209,13 @@ pub fn build_with_reviews(     attrs: &Path,     spatial: &Path,     name_index: &Path,+    region: &Path,     bbox: Option<crate::bbox::BBox>,     reviews: Option<&ReviewTable>, ) -> Result<Stats> {     // Fail before the three passes rather than after them if an output path is     // unwritable.-    for path in [geojson, names, index, attrs, spatial, name_index] {+    for path in [geojson, names, index, attrs, spatial, name_index, region] {         if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {             std::fs::create_dir_all(parent)                 .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?;@@ -195,12 +238,15 @@ pub fn build_with_reviews(         relation_blob,     )?;     let mut rel_areas: Vec<RelArea> = Vec::new();+    let mut boundaries: Vec<BoundaryRel> = Vec::new();     for chunk in chunks {         rel_areas.extend(chunk.areas);+        boundaries.extend(chunk.boundaries);     }     let mut outer_wanted: Vec<i64> = rel_areas         .iter()         .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();@@ -286,7 +332,15 @@ pub fn build_with_reviews(         // 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()));+            pois.push(make_poi(+                poi,+                area.type_,+                area.id,+                &area.name,+                area.attrs.clone(),+                area.self_region,+                area.place_cap,+            ));         }     }     let from_ways = pois.len() - from_nodes;@@ -308,7 +362,15 @@ pub fn build_with_reviews(             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()));+            pois.push(make_poi(+                poi,+                area.type_,+                -area.id,+                &area.name,+                area.attrs.clone(),+                area.self_region,+                area.place_cap,+            ));         }     }     let from_relations = pois.len() - from_nodes - from_ways;@@ -328,13 +390,22 @@ pub fn build_with_reviews(         None => 0,     }; +    // Before the sort: `pois` is still nodes, then ways, then relations, which is+    // 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);+    if with_region > 0 {+        println!("{with_region} POI(s) with a boundary link");+    }+     // 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));      timer.switch("write");-    let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index)?;+    let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index, region)?;     timer.finish();     Ok(Stats {         records: written.records,@@ -349,6 +420,7 @@ pub fn build_with_reviews(         spatial_cells: written.spatial_cells,         name_entries: written.name_entries,         with_reviews,+        with_region,     }) } @@ -373,6 +445,148 @@ fn apply_reviews(pois: &mut [Poi], from_nodes: usize, from_ways: usize, table: &     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);+                }+            }+        }+        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);+            }+        }+    }++    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+}+ fn poi_tags<'a>(t: &osm::Tags<'_, 'a>) -> PoiTags<'a> {     PoiTags {         railway: t.get_str("railway"),@@ -383,6 +597,19 @@ fn poi_tags<'a>(t: &osm::Tags<'_, 'a>) -> PoiTags<'a> {         leisure: t.get_str("leisure"),         healthcare: t.get_str("healthcare"),         office: t.get_str("office"),+        place: t.get_str("place"),+    }+}++/// Deepest `admin_level` a place POI may link to, from its `place` value:+/// a country links at level 2, a state/province at 4, everything else (cities+/// down to neighbourhoods) at 8. Non-place POIs link at any level.+fn place_level_cap(place: Option<&str>) -> u8 {+    match place {+        Some("country") => 2,+        Some("state" | "province") => 4,+        Some(_) => 8,+        None => 8,     } } @@ -390,6 +617,46 @@ fn relation_blob(state: &mut RelPass, block: &pbf::PrimitiveBlock) -> Result<u8>     let mut kinds = 0u8;     visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el: Element| {         if let Element::Relation(r) = el {+            // Boundary relations feed the region-link geometry whether or not they+            // are POIs themselves. A `boundary=administrative` relation is+            // linkable when it carries an `admin_level`; `type=boundary` without+            // one still assembles but links at the deepest level.+            if r.tags.get_str("type") == Some("boundary")+                && r.tags.get_str("boundary") == Some("administrative")+            {+                let admin_level: u8 = r+                    .tags+                    .get_str("admin_level")+                    .and_then(|v| v.parse().ok())+                    .unwrap_or(8);+                state.boundaries.push(BoundaryRel {+                    id: r.id,+                    admin_level,+                    member_ways: r+                        .members+                        .iter()+                        .filter(|m| {+                            m.kind == MEMBER_WAY+                                && (m.role == b"outer"+                                    || m.role == b"inner"+                                    || m.role.is_empty())+                        })+                        .map(|m| (m.id, m.role != b"inner"))+                        .collect(),+                    label_nodes: r+                        .members+                        .iter()+                        .filter(|m| {+                            m.kind == MEMBER_NODE+                                && (m.role == b"label" || m.role == b"admin_centre")+                        })+                        .map(|m| m.id)+                        .collect(),+                    });+                // A boundary relation with a name and POI tags is still a POI in its+                // own right (a national park on the relation, a `place` label on the+                // boundary). Fall through to the area path below.+            }             let is_area = r                 .tags                 .get_str("type")@@ -402,6 +669,11 @@ fn relation_blob(state: &mut RelPass, block: &pbf::PrimitiveBlock) -> Result<u8>                 _ => return Ok(()),             };             if let Some(type_) = tags::classify(&poi_tags(&r.tags)) {+                let self_region = if r.tags.get_str("boundary") == Some("administrative") {+                    poi_side::tag_relation(r.id)+                } else {+                    poi_side::REGION_NONE+                };                 state.areas.push(RelArea {                     id: r.id,                     type_,@@ -413,6 +685,8 @@ fn relation_blob(state: &mut RelPass, block: &pbf::PrimitiveBlock) -> Result<u8>                         .filter(|m| m.kind == MEMBER_WAY && (m.role == b"outer" || m.role.is_empty()))                         .map(|m| m.id)                         .collect(),+                    self_region,+                    place_cap: place_level_cap(r.tags.get_str("place")),                 });             }         }@@ -448,12 +722,19 @@ fn way_blob(                 _ => return Ok(()),             };             if let Some(type_) = tags::classify(&poi_tags(&w.tags)) {+                let self_region = if w.tags.get_str("boundary") == Some("administrative") {+                    poi_side::tag_way(w.id)+                } else {+                    poi_side::REGION_NONE+                };                 state.areas.push(WayArea {                     id: w.id,                     type_,                     name: name.to_vec(),                     attrs: crate::poi_attrs::encode(|k| w.tags.get(k)),                     refs: w.refs.to_vec(),+                    self_region,+                    place_cap: place_level_cap(w.tags.get_str("place")),                 });             }         }@@ -493,6 +774,8 @@ fn node_blob(                     n.id,                     name,                     crate::poi_attrs::encode(|k| n.tags.get(k)),+                    poi_side::REGION_NONE,+                    place_level_cap(n.tags.get_str("place")),                 ));             }         }
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 0ca5f7b997..4f520e49e4 100644--- a/scripts/maps/osm_ingest/src/poi_build_part1.rs+++ b/scripts/maps/osm_ingest/src/poi_build_part1.rs@@ -4,6 +4,8 @@ fn make_poi(     osm_id: i64,     name: &[u8],     attrs: Vec<u8>,+    region: u64,+    place_cap: u8, ) -> Poi {     let lat_e7 = (lat * 1e7).round() as i32;     let lon_e7 = (lon * 1e7).round() as i32;@@ -19,6 +21,8 @@ fn make_poi(         osm_id,         name: name.to_vec(),         attrs,+        region,+        place_cap,     } } @@ -41,6 +45,7 @@ fn write_outputs(     attrs: &Path,     spatial: &Path,     name_index: &Path,+    region: &Path, ) -> Result<Written> {     let mut pool = NamePool::new(BufWriter::new(create(names)?));     let mut index_out = BufWriter::new(create(index)?);@@ -89,6 +94,13 @@ fn write_outputs(         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();@@ -135,6 +147,8 @@ pub struct Args {     pub attrs: PathBuf,     pub spatial: PathBuf,     pub name_index: PathBuf,+    /// Tagged boundary ids per POI ordinal. Defaults beside `--index`.+    pub region: PathBuf,     /// Region bbox filter. `None` (world) keeps everything.     pub bbox: Option<crate::bbox::BBox>,     /// `None` leaves the pool at whatever `par::threads()` decides.@@ -214,6 +228,7 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {     let attrs = attrs.unwrap_or_else(|| index.with_file_name("poi_attrs.bin"));     let spatial = spatial.unwrap_or_else(|| index.with_file_name("poi_spatial.bin"));     let name_index = name_index.unwrap_or_else(|| index.with_file_name("poi_name_index.bin"));+    let region_ids = index.with_file_name("poi_region.bin");     Ok(Args {         input,         geojson,@@ -222,6 +237,7 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {         attrs,         spatial,         name_index,+        region: region_ids,         bbox: region.and_then(|r| r.bbox()),         threads,         reviews,
scripts/maps/osm_ingest/src/poi_build_part2.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build_part2.rs b/scripts/maps/osm_ingest/src/poi_build_part2.rsindex 9cf455ae8c..072dfc3717 100644--- a/scripts/maps/osm_ingest/src/poi_build_part2.rs+++ b/scripts/maps/osm_ingest/src/poi_build_part2.rs@@ -66,6 +66,25 @@ mod tests {             .collect()     } +    /// Decode `poi_region.bin` the way [`crate::poi_side`] documents it: one+    /// tagged OSM boundary id per record ordinal, `0` where the POI matched+    /// nothing.+    fn read_regions(dir: &Path) -> Vec<u64> {+        use crate::poi_side::{REGION_HEADER_BYTES, REGION_MAGIC, REGION_VERSION};+        let bytes = std::fs::read(dir.join("poi_region.bin")).unwrap();+        assert_eq!(&bytes[0..4], REGION_MAGIC);+        assert_eq!(+            u32::from_le_bytes(bytes[4..8].try_into().unwrap()),+            REGION_VERSION+        );+        let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;+        assert_eq!(bytes.len(), REGION_HEADER_BYTES + 8 * count);+        bytes[REGION_HEADER_BYTES..]+            .chunks_exact(8)+            .map(|r| u64::from_le_bytes(r.try_into().unwrap()))+            .collect()+    }+     fn build_sample(tag: &str) -> (Stats, PathBuf) {         let (pbf_path, dir) = testpbf::write_sample(tag);         let stats = build(@@ -76,6 +95,7 @@ mod tests {             &dir.join("poi_attrs.bin"),             &dir.join("poi_spatial.bin"),             &dir.join("poi_name_index.bin"),+            &dir.join("poi_region.bin"),         )         .unwrap();         (stats, dir)@@ -191,6 +211,7 @@ mod tests {                 &dir.join(format!("attrs{suffix}.bin")),                 &dir.join(format!("spatial{suffix}.bin")),                 &dir.join(format!("nameidx{suffix}.bin")),+                &dir.join(format!("region{suffix}.bin")),             )             .unwrap();         };@@ -203,6 +224,7 @@ mod tests {             ("attrsa.bin", "attrsb.bin"),             ("spatiala.bin", "spatialb.bin"),             ("nameidxa.bin", "nameidxb.bin"),+            ("regiona.bin", "regionb.bin"),         ] {             assert_eq!(                 std::fs::read(dir.join(a)).unwrap(),@@ -258,6 +280,45 @@ mod tests {         assert_eq!(index.len(), stats.records * 14);     } +    /// Member links win, containment covers the rest, misses stay zero: the+    /// town label is a `label` member of the boundary relation (stamped even+    /// though it sits outside the ring), the inside cafe resolves by+    /// containment, the outside cafe matches nothing.+    #[test]+    fn boundary_links_resolve_member_first_then_containment() {+        let (pbf_path, dir) = testpbf::write_region_sample("poi_region");+        let stats = build(+            &pbf_path,+            &dir.join("pois.geojsonseq"),+            &dir.join("poi_names.bin"),+            &dir.join("poi_index.bin"),+            &dir.join("poi_attrs.bin"),+            &dir.join("poi_spatial.bin"),+            &dir.join("poi_name_index.bin"),+            &dir.join("poi_region.bin"),+        )+        .unwrap();+        let (records, _) = read_records(&dir);+        assert_eq!(records.len(), 4);+        assert_eq!(stats.with_region, 3);++        let regions = read_regions(&dir);+        assert_eq!(regions.len(), records.len());+        let of = |n: &str| regions[records.iter().position(|r| r.name == n).unwrap()];++        // Tagged ids carry the OSM id space in the low 2 bits: relation 300 is+        // `(300 << 2) | 3`.+        let boundary = (testpbf::REGION_BOUNDARY_ID as u64) << 2 | 3;+        // The town label is type 51 and resolves through the member link alone.+        let town = records.iter().find(|r| r.name == "Testville").unwrap();+        assert_eq!(town.type_, 51);+        assert_eq!(of("Testville"), boundary);+        // The boundary relation is itself a park POI and links to itself.+        assert_eq!(of("Green Boundary"), boundary);+        assert_eq!(of("Inside Cafe"), boundary);+        assert_eq!(of("Outside Cafe"), 0);+    }+     /// Review rows join on (element, OSM id) before the Morton sort, and land on the     /// right ordinal after it. The relation row uses the plain id even though the     /// POI stores it negated.@@ -284,6 +345,7 @@ mod tests {             &dir.join("poi_attrs.bin"),             &dir.join("poi_spatial.bin"),             &dir.join("poi_name_index.bin"),+            &dir.join("poi_region.bin"),             None,             Some(&table),         )@@ -331,6 +393,7 @@ mod tests {         // Defaulted beside the index, so a caller written before the sidecar existed         // still emits one rather than silently skipping it.         assert_eq!(ok.attrs, PathBuf::from("out/poi_attrs.bin"));+        assert_eq!(ok.region, PathBuf::from("out/poi_region.bin"));         assert!(ok.threads.is_none(), "the pool defaults to the box");         assert!(parse_args(&["in.pbf".into()]).is_err());         assert!(parse_args(&["in.pbf".into(), "--geojson".into()]).is_err());
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 8c2812a207..04a9807c93 100644--- a/scripts/maps/osm_ingest/src/poi_side.rs+++ b/scripts/maps/osm_ingest/src/poi_side.rs@@ -34,6 +34,19 @@ //! u8  word_idx[entry_count]   which word of that record's name //! ``` //!+//! **`poi_region.bin`** — one tagged OSM boundary id per POI ordinal:+//!+//! ```text+//! magic "PRG1" | u32 version | u32 record_count  (12-byte header)+//! u64 tagged_ids[record_count]  native OSM label-member link first,+//!                               smallest containing admin fallback, else 0+//! ```+//!+//! The tagged id packs the OSM id space in the low 2 bits (0 none / 1 node /+//! 2 way / 3 relation): `tagged = (osm_id << 2) | space`. Boundary relations+//! use space 3, boundary ways space 2. `0` (`REGION_NONE`) stamps nothing, so+//! the reader masks nothing and the app's name-match fallback still applies.+//! //! Parallel arrays rather than a packed struct, so an entry costs 5 bytes and not the 8 //! that alignment would round it up to. It is still the largest of the POI files: //! indexing *every* word, not just the name's first, means the entry count is roughly@@ -57,6 +70,19 @@ //! //! The Kotlin reader is `PoiIndex.kt`; [`tests`] pins the ordering from this side. +/// Tagged-OSM-id space bits packed into the low 2 bits of a region link.+pub const REGION_NONE: u64 = 0;++/// Tag an OSM relation id as a region link.+pub fn tag_relation(id: i64) -> u64 {+    ((id as u64) << 2) | 3+}++/// Tag an OSM way id as a region link.+pub fn tag_way(id: i64) -> u64 {+    ((id as u64) << 2) | 2+}+ use std::cmp::Ordering; use std::io::{self, Write}; @@ -68,6 +94,10 @@ pub const NAME_MAGIC: &[u8; 4] = b"PNI1"; pub const NAME_VERSION: u32 = 1; pub const NAME_HEADER_BYTES: usize = 16; +pub const REGION_MAGIC: &[u8; 4] = b"PRG1";+pub const REGION_VERSION: u32 = 1;+pub const REGION_HEADER_BYTES: usize = 12;+ /// Grid cell size in 1e-7 degrees: 0.02°, the same as the transit pack's. pub const CELL_E7: u32 = 200_000; @@ -255,6 +285,20 @@ pub fn write_name_index<W: Write>(out: &mut W, names: &[&[u8]]) -> io::Result<us     Ok(entries.len()) } +/// Write `poi_region.bin`: one tagged OSM boundary id per record ordinal, in+/// the same Morton-sorted order as `poi_index.bin`. Same count-refused+/// convention as the other side files: the reader joins by ordinal only when+/// the counts agree.+pub fn write_region<W: Write>(out: &mut W, region_ids: &[u64]) -> io::Result<()> {+    out.write_all(REGION_MAGIC)?;+    out.write_all(&REGION_VERSION.to_le_bytes())?;+    out.write_all(&(region_ids.len() as u32).to_le_bytes())?;+    for id in region_ids {+        out.write_all(&id.to_le_bytes())?;+    }+    Ok(())+}+ #[cfg(test)] mod tests {     use super::*;
scripts/maps/osm_ingest/src/tags.rs
diff --git a/scripts/maps/osm_ingest/src/tags.rs b/scripts/maps/osm_ingest/src/tags.rsindex f369af65e3..963d2b0d4a 100644--- a/scripts/maps/osm_ingest/src/tags.rs+++ b/scripts/maps/osm_ingest/src/tags.rs@@ -179,6 +179,10 @@ pub fn is_stop_node(highway: Option<&str>, railway: Option<&str>, public_transpo /// Catch-all bucket for a recognised POI key with an unmapped value. pub const TYPE_OTHER: u16 = 255; +/// Place labels (cities, towns, …) are searchable POI-index records. Appended —+/// never renumber — like every other POI type number.+pub const TYPE_PLACE: u16 = 51;+ fn amenity_type(v: &str) -> Option<u16> {     Some(match v {         "restaurant" | "food_court" => 0,@@ -267,6 +271,18 @@ fn healthcare_type(v: &str) -> Option<u16> {     }) } +/// Named administrative places worth searching: countries down to city+/// neighbourhoods. Deliberately not every `place=*` value — counties are+/// covered by their boundary relations, and islands/islets/seas are not+/// searchable settlements.+fn place_type(v: &str) -> Option<u16> {+    match v {+        "country" | "state" | "province" | "city" | "town" | "village" | "hamlet" | "suburb"+        | "borough" | "neighbourhood" | "quarter" | "macrohood" => Some(TYPE_PLACE),+        _ => None,+    }+}+ /// The tags a POI classification needs, so the classifier is testable without a /// PBF block behind it. pub struct PoiTags<'a> {@@ -278,6 +294,7 @@ pub struct PoiTags<'a> {     pub leisure: Option<&'a str>,     pub healthcare: Option<&'a str>,     pub office: Option<&'a str>,+    pub place: Option<&'a str>, }  /// A POI key's tag value paired with the value -> type-number map for that key.@@ -288,8 +305,8 @@ type KeyedMap<'a> = (Option<&'a str>, fn(&str) -> Option<u16>); /// Station-like `railway`/`public_transport` values win outright (type 50). /// Bare transit values — tracks, signals, bus poles, platforms — are explicitly /// *not* POIs and must not reach the generic "recognised key -> other" path, or-/// they flood the map. Otherwise precedence is amenity, shop, tourism, leisure,-/// healthcare, then `office=*`.+/// they flood the map. Otherwise precedence is place, amenity, shop, tourism,+/// leisure, healthcare, then `office=*`. pub fn classify(t: &PoiTags) -> Option<u16> {     if matches!(t.railway, Some("station" | "halt" | "tram_stop"))         || matches!(t.public_transport, Some("station"))@@ -297,6 +314,15 @@ pub fn classify(t: &PoiTags) -> Option<u16> {         return Some(50);     } +    if let Some(p) = t.place {+        if !p.is_empty() && p != "no" {+            if let Some(ty) = place_type(p) {+                return Some(ty);+            }+            return Some(TYPE_OTHER);+        }+    }+     let order: [KeyedMap; 5] = [         (t.amenity, amenity_type),         (t.shop, shop_type),@@ -441,6 +467,7 @@ mod tests {             leisure: get("leisure"),             healthcare: get("healthcare"),             office: get("office"),+            place: get("place"),         }     } @@ -487,9 +514,41 @@ mod tests {     fn classify_unmapped_but_recognised_key_is_other() {         assert_eq!(classify(&tags(&[("amenity", "bbq")])), Some(TYPE_OTHER));         assert_eq!(classify(&tags(&[("shop", "anime")])), Some(TYPE_OTHER));+        assert_eq!(classify(&tags(&[("place", "island")])), Some(TYPE_OTHER));         // `no` and empty values do not count as recognised.         assert_eq!(classify(&tags(&[("amenity", "no")])), None);         assert_eq!(classify(&tags(&[("shop", "")])), None);+        assert_eq!(classify(&tags(&[("place", "no")])), None);         assert_eq!(classify(&tags(&[])), None);     }++    #[test]+    fn classify_place_labels_are_type_51() {+        for v in [+            "country",+            "state",+            "province",+            "city",+            "town",+            "village",+            "hamlet",+            "suburb",+            "borough",+            "neighbourhood",+            "quarter",+            "macrohood",+        ] {+            assert_eq!(classify(&tags(&[("place", v)])), Some(TYPE_PLACE), "place {v:?}");+        }+        assert_eq!(classify(&tags(&[("place", "city")])), Some(51));+        // Stations still win over place; place wins over amenity.+        assert_eq!(+            classify(&tags(&[("railway", "station"), ("place", "town")])),+            Some(50)+        );+        assert_eq!(+            classify(&tags(&[("place", "town"), ("amenity", "cafe")])),+            Some(TYPE_PLACE)+        );+    } }
scripts/maps/osm_ingest/src/testpbf.rs
diff --git a/scripts/maps/osm_ingest/src/testpbf.rs b/scripts/maps/osm_ingest/src/testpbf.rsindex 6bf384cff2..0b1090cfca 100644--- a/scripts/maps/osm_ingest/src/testpbf.rs+++ b/scripts/maps/osm_ingest/src/testpbf.rs@@ -363,6 +363,116 @@ fn write_pbf(tag: &str, bytes: &[u8]) -> (std::path::PathBuf, std::path::PathBuf     (path, dir) } +// ---- the POI region-link fixture -------------------------------------------+//+// A FOURTH fixture, for `poi_build`'s boundary links. The road-graph, vector and+// POI tests assert exact counts against the fixtures above, so this one is+// separate: a `type=boundary` + `boundary=administrative` relation that is+// itself a POI (`leisure=park` gives it a type, so it self-links), a+// `place=town` label carried as a `label` member OUTSIDE the ring (only the+// member link, never containment, can stamp it), one cafe inside the ring+// (containment) and one outside it (unstamped).++/// `type=boundary` + `boundary=administrative` + `admin_level=8`, itself a park+/// POI.+pub const REGION_BOUNDARY_ID: i64 = 300;+/// The boundary's single closed outer ring.+pub const REGION_RING_WAY_ID: i64 = 400;+/// `amenity=cafe` inside the ring.+pub const REGION_INSIDE_CAFE_ID: i64 = 15;+/// `amenity=cafe` outside the ring.+pub const REGION_OUTSIDE_CAFE_ID: i64 = 16;+/// `place=town` carried as a `label` member, deliberately outside the ring.+pub const REGION_TOWN_NODE_ID: i64 = 17;++/// `(id, lat_e7, lon_e7)` of the ring corners plus the POI nodes: a+/// 0.04-degree square, with the cafes and the town on its middle parallel.+pub const REGION_NODES: [(i64, i32, i32); 7] = [+    (11, 371_000_000, -1_221_000_000),+    (12, 371_000_000, -1_220_600_000),+    (13, 371_040_000, -1_220_600_000),+    (14, 371_040_000, -1_221_000_000),+    (REGION_INSIDE_CAFE_ID, 371_020_000, -1_220_800_000),+    (REGION_OUTSIDE_CAFE_ID, 371_100_000, -1_220_800_000),+    (REGION_TOWN_NODE_ID, 371_120_000, -1_220_850_000),+];++fn region_block() -> Vec<u8> {+    let mut st = StringTable::new();+    let k_amenity = st.id("amenity");+    let v_cafe = st.id("cafe");+    let k_name = st.id("name");+    let v_inside = st.id("Inside Cafe");+    let v_outside = st.id("Outside Cafe");+    let k_place = st.id("place");+    let v_town = st.id("town");+    let v_testville = st.id("Testville");+    let k_type = st.id("type");+    let k_boundary = st.id("boundary"); // also the value of `type=*`+    let v_admin = st.id("administrative");+    let k_admin_level = st.id("admin_level");+    let v_eight = st.id("8");+    let v_green = st.id("Green Boundary");+    let k_leisure = st.id("leisure");+    let v_park = st.id("park");+    let role_outer = st.id("outer");+    let role_label = st.id("label");++    let nodes: Vec<FixtureNode> = REGION_NODES+        .iter()+        .map(|(id, lat, lon)| {+            let tags = match *id {+                REGION_INSIDE_CAFE_ID => vec![(k_amenity, v_cafe), (k_name, v_inside)],+                REGION_OUTSIDE_CAFE_ID => vec![(k_amenity, v_cafe), (k_name, v_outside)],+                REGION_TOWN_NODE_ID => vec![(k_place, v_town), (k_name, v_testville)],+                _ => Vec::new(),+            };+            (*id, *lat, *lon, tags)+        })+        .collect();+    let dense = dense_group(&nodes);+    let ways = [way(REGION_RING_WAY_ID, &[], &[11, 12, 13, 14, 11])];+    let rels = [relation(+        REGION_BOUNDARY_ID,+        &[+            (k_type, k_boundary),+            (k_boundary, v_admin),+            (k_admin_level, v_eight),+            (k_name, v_green),+            (k_leisure, v_park),+        ],+        // Ascending, so the delta encoding stays small.+        &[+            (REGION_TOWN_NODE_ID, role_label, 0),+            (REGION_RING_WAY_ID, role_outer, 1),+        ],+    )];++    let mut node_group = Vec::new();+    bytes_field(2, &dense, &mut node_group);+    let mut way_group = Vec::new();+    for w in &ways {+        bytes_field(3, w, &mut way_group);+    }+    let mut rel_group = Vec::new();+    for r in &rels {+        bytes_field(4, r, &mut rel_group);+    }++    let mut block = Vec::new();+    bytes_field(1, &st.encode(), &mut block);+    bytes_field(2, &node_group, &mut block);+    bytes_field(2, &way_group, &mut block);+    bytes_field(2, &rel_group, &mut block);+    varint_field(17, 100, &mut block); // granularity+    block+}++/// Write the region-link fixture to a unique temp directory.+pub fn write_region_sample(tag: &str) -> (std::path::PathBuf, std::path::PathBuf) {+    write_pbf(tag, &pbf_from_block(&region_block()))+}+ // ---- the vector-layer fixture -------------------------------------------- // // A SECOND fixture rather than more features in the one above. The road-graph and
scripts/maps/tile_build/src/bin/mamaps_pack.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_pack.rs b/scripts/maps/tile_build/src/bin/mamaps_pack.rsindex 0c014d8a7a..ac91db36c1 100644--- a/scripts/maps/tile_build/src/bin/mamaps_pack.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_pack.rs@@ -19,7 +19,7 @@ //!   graph: metadata.bin nodes.bin edges.bin intermediate.bin road_names.bin //!          lanes.bin elevation.bin //!   poi:   poi_index.bin poi_names.bin poi_attrs.bin poi_spatial.bin-//!          poi_name_index.bin+//!          poi_name_index.bin poi_region.bin //!   transit: world.transit (one TRIX pack; `<feed>.transit` naming is a //!            delivery rename, the bytes are what matter) use std::io::{Read, Seek, SeekFrom, Write};@@ -30,7 +30,7 @@ use tile_build::mamaps::archive::{     ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE,     ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES,     ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_INDEX,-    ARCHIVE_KIND_POI_NAMES,+    ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_REGION,     ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, }; use tile_build::mamaps::header::Header;@@ -210,6 +210,17 @@ fn load_sidecars_impl(         Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}         Err(e) => return Err(format!("cannot stat {}: {e}", overlay.display())),     }+    // The POI region sidecar (`poi_region.bin`) is optional and sorts last: kind 15+    // comes after the overlay's 14, and `ArchiveView::parse` requires ascending kinds.+    let poi_region = poi.join("poi_region.bin");+    match std::fs::metadata(&poi_region) {+        Ok(m) if m.len() > 0 => {+            staged.push(Staged::whole(ARCHIVE_KIND_POI_REGION, poi_region, m.len()))+        }+        Ok(_) => {}+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+        Err(e) => return Err(format!("cannot stat {}: {e}", poi_region.display())),+    }     // Validate every sidecar's magic/version/count BEFORE anything is written: each section's     // check is the same one its loader runs, and a mismatch fails closed with a non-zero exit     // and no partial output. Only the small files are read whole; the large graph payloads@@ -407,13 +418,14 @@ fn validate_sidecars(     if poi_names.is_empty() && poi_count > 0 {         return Err("poi carries an index but no names".to_string());     }-    for name in ["poi_attrs.bin", "poi_spatial.bin", "poi_name_index.bin"] {+    for name in ["poi_attrs.bin", "poi_spatial.bin", "poi_name_index.bin", "poi_region.bin"] {         let path = poi.join(name);         if path.exists() {             let b = read_file(&path)?;             let (magic, want, kind) = match name {                 "poi_attrs.bin" => (&b"MAPA"[..], 12usize, "attrs"),                 "poi_spatial.bin" => (&b"PSP1"[..], 32usize, "grid"),+                "poi_region.bin" => (&b"PRG1"[..], 12usize, "region"),                 _ => (&b"PNI1"[..], 16usize, "word index"),             };             if b.len() < want {@@ -990,6 +1002,33 @@ mod tests {         assert_eq!(view.section(&packed, ARCHIVE_KIND_GRAPH_OVERLAY), Some(&overlay[..]));         let _ = std::fs::remove_dir_all(&dir);     }+    fn region_payload(tagged: u64) -> Vec<u8> {+        // `poi_region.bin`: PRG1 + version + one u64 tagged id per index ordinal.+        // The round-trip fixture's POI dir stages one index record.+        let mut out = Vec::new();+        out.extend_from_slice(b"PRG1");+        out.extend_from_slice(&1u32.to_le_bytes());+        out.extend_from_slice(&1u32.to_le_bytes());+        out.extend_from_slice(&tagged.to_le_bytes());+        out+    }+    #[test]+    fn a_region_sidecar_packs_after_the_overlay() {+        let (dir, poi) = overlay_fixture("region");+        let region = region_payload((300u64 << 2) | 3);+        std::fs::write(poi.join("poi_region.bin"), &region).expect("fixture region");+        let validated = load_sidecars(&dir, &poi, None).expect("stage fixtures");+        assert_eq!(validated.staged.last().map(|s| s.kind), Some(ARCHIVE_KIND_POI_REGION));+        let out = dir.join("packed.mamaps");+        pack_streaming(&dir.join("tiles.mamaps"), &validated, 0xBEEF, &out).expect("pack");+        let packed = std::fs::read(&out).expect("read packed");+        let header = Header::parse(&packed).expect("packed header");+        // `ArchiveView::parse` requires ascending kinds, so this open also proves+        // kind 15 stages after the overlay's 14.+        let view = ArchiveView::parse(&packed, &header).expect("packed archive opens");+        assert_eq!(view.section(&packed, ARCHIVE_KIND_POI_REGION), Some(&region[..]));+        let _ = std::fs::remove_dir_all(&dir);+    }     #[test]     fn a_stale_overlay_fails_the_pack() {         let (dir, poi) = overlay_fixture("stale_overlay");
scripts/maps/tile_build/src/bin/mamaps_probe.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_probe.rs b/scripts/maps/tile_build/src/bin/mamaps_probe.rsindex eb310d9f6c..e238d62ad0 100644--- a/scripts/maps/tile_build/src/bin/mamaps_probe.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_probe.rs@@ -430,6 +430,7 @@ fn sidecars(path: &str) -> ExitCode {             11 => "poi_spatial (poi_spatial.bin: PSP1 spatial grid)",             12 => "poi_words (poi_name_index.bin: PNI1 full-text word index)",             13 => "transit (world.transit: TRIX pack of routes/shapes)",+            15 => "poi_region (poi_region.bin: PRG1 region-id sidecar)",             _ => "unknown",         }     }
scripts/maps/tile_build/src/bin/mamaps_sizes.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_sizes.rs b/scripts/maps/tile_build/src/bin/mamaps_sizes.rsindex 79f6be9c98..3fc61cc892 100644--- a/scripts/maps/tile_build/src/bin/mamaps_sizes.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_sizes.rs@@ -30,11 +30,11 @@ use tile_build::mamaps::dict::Dictionary; use tile_build::mamaps::header::Header; use tile_build::mamaps::index::{decompress_leaf, parse_leaf, parse_root, LEAF_ENTRY_LEN, ROOT_ENTRY_LEN}; -const KIND_NAMES: [(u8, &str); 13] = [+const KIND_NAMES: [(u8, &str); 14] = [     (1, "graph_meta"), (2, "graph_nodes"), (3, "graph_edges"), (4, "graph_intermediate"),     (5, "graph_names"), (6, "graph_lanes"), (7, "graph_elevation"), (8, "poi_index"),     (9, "poi_names"), (10, "poi_attrs"), (11, "poi_spatial"), (12, "poi_words"),-    (13, "transit"),+    (13, "transit"), (15, "poi_region"), ];  fn gb(n: u64) -> f64 {