Modern Apps git

← Modern-Apps.git

maps: index POI lookups by Morton key instead of scanning

Commit
74f6f961c666c69a1c48117fc4f267d87ff01b6c
Author
vayun-mathur <[email protected]>
When
2026-08-24 19:19 UTC (3 months ago)
Parents
d2ac272

Diff

maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex 8b336380ab..2b7b78e738 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -13,6 +13,9 @@ android {     defaultConfig {         applicationId = "com.vayunmathur.maps"     }+    // PoiIndexTest exercises the real side-file reader, which logs. Without this every+    // android.util.Log call throws "not mocked" and the test can only cover code that never logs.+    testOptions.unitTests.isReturnDefaultValues = true }  androidComponents {
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 3069c7b9e5..a5af22d271 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -2,6 +2,8 @@ package com.vayunmathur.maps.data  import com.vayunmathur.maps.util.PoiIndex import com.vayunmathur.maps.util.Wikidata+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonObject@@ -50,9 +52,21 @@ sealed interface SpecificFeature {  *  * Returns a bare place when the sidecar is absent or the point is not one of ours,  * which is the same thing every caller used to produce unconditionally.+ *+ * Suspending, and on [Dispatchers.IO], because [PoiIndex.attributesNear] reads a mapped side+ * file. Every one of this function's call sites used to be on the main thread — including the+ * one inside the tap gesture handler — so a cold 316 MB mmap page-faulted on the UI thread.+ * That is true even now the lookup is a binary search rather than a scan: the scan was what+ * made it an ANR, the mmap is what makes it I/O.  */-fun osmPlace(name: String, position: Position, poiType: Int? = null): SpecificFeature.GenericPlace {-    val attrs = PoiIndex.attributesNear(position.latitude, position.longitude, name)+suspend fun osmPlace(+    name: String,+    position: Position,+    poiType: Int? = null,+): SpecificFeature.GenericPlace {+    val attrs = withContext(Dispatchers.IO) {+        PoiIndex.attributesNear(position.latitude, position.longitude, name)+    }     return SpecificFeature.GenericPlace(         name = name,         phone = attrs?.phone,@@ -73,8 +87,8 @@ fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content /**  * Resolve a tapped basemap feature into a [SpecificFeature].  *- * Amenities are now Google-only (rendered on the custom overlay layer and tapped- * there — see GooglePoiLayer), so this no longer reads the amenities DB: it only+ * Amenities come from the baked `ma_pois` layer and are tapped there (see+ * [com.vayunmathur.maps.ui.toSelectedMaPoi]), so this no longer reads the amenities DB: it only  * handles the country/region/city admin labels (Wikidata-backed). Everything else  * returns null, since native POIs are suppressed in the style.  */
maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt b/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.ktindex c3ac0aea4d..db6c934363 100644--- a/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt@@ -74,8 +74,7 @@ object OrderLookupClient {     } } -/** Food categories worth checking for orderability (mirrors the food buckets of- *  GooglePoiLayer's category colouring). */+/** Food categories worth checking for orderability. */ private val FOOD_KEYWORDS = listOf(     "restaurant", "food", "dining", "pizza", "burger", "steak", "sushi",     "cafe", "coffee", "bakery", "tea", "dessert",
maps/src/main/java/com/vayunmathur/maps/ui/FamilyLocationLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/FamilyLocationLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/FamilyLocationLayer.ktindex c7ad46a8bd..0c0ee0b72c 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/FamilyLocationLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/FamilyLocationLayer.kt@@ -48,7 +48,7 @@ private val FAMILY_LOCATION_COLOR = Color(0xFF5E35B1)  * Live family-location overlay: a [GeoJsonSource] fed from the findfamily bound  * service (pushed while the map is open) plus a [CircleLayer] avatar dot, a  * centred initial and a name label, ported to maplibre-compose declarative- * layers exactly like [SavedPlacesLayer] / [GooglePoiLayer]. Tap the dot →+ * layers exactly like [SavedPlacesLayer] / [SearchResultLayer]. Tap the dot →  * details via [toSelectedFamilyMember], reusing [SpecificFeature.GenericPlace]  * so the existing place sheet + Directions/route path renders with no new code.  */
maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.ktdeleted file mode 100644index 64908a2245..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt+++ /dev/null@@ -1,171 +0,0 @@-package com.vayunmathur.maps.ui--import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.ImageBitmap-import androidx.compose.ui.graphics.asImageBitmap-import androidx.compose.ui.unit.dp-import com.vayunmathur.maps.data.Feature1-import com.vayunmathur.maps.data.SpecificFeature-import com.vayunmathur.maps.data.google.GooglePoiPin-import com.vayunmathur.maps.data.osmPlace-import com.vayunmathur.maps.data.string-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive-import kotlinx.serialization.json.doubleOrNull-import kotlinx.serialization.json.jsonPrimitive-import org.maplibre.compose.expressions.dsl.const-import org.maplibre.compose.expressions.dsl.convertToColor-import org.maplibre.compose.expressions.dsl.feature-import org.maplibre.compose.expressions.dsl.image-import org.maplibre.compose.expressions.dsl.interpolate-import org.maplibre.compose.expressions.dsl.linear-import org.maplibre.compose.expressions.dsl.zoom-import org.maplibre.compose.expressions.value.StringValue-import org.maplibre.compose.layers.CircleLayer-import org.maplibre.compose.layers.SymbolLayer-import org.maplibre.compose.sources.GeoJsonData-import org.maplibre.compose.sources.GeoJsonOptions-import org.maplibre.compose.sources.GeoJsonSource-import org.maplibre.compose.util.MaplibreComposable-import org.maplibre.spatialk.geojson.FeatureCollection-import org.maplibre.spatialk.geojson.Point-import org.maplibre.spatialk.geojson.Position--/** Symbol layer id — hit-tested first in MapPage.onMapClick so a Google pin tap- *  wins over basemap label features. */-const val GOOGLE_POI_LAYER_ID = "google-poi-pins"-private const val GOOGLE_POI_DOT_LAYER_ID = "google-poi-dots"-private const val GOOGLE_POI_SOURCE_ID = "google-poi-geojson"--/**- * Custom Google-POI overlay: a [GeoJsonSource] fed from the viewport scrape plus- * a category-coloured [CircleLayer] "dot" and a [SymbolLayer] marker on top- * (Vela's ambient dot + icon pattern, ported to maplibre-compose declarative- * layers). Native basemap POIs are suppressed (see MapPage.patchStyleForHybrid),- * so these are the only POI pins on the map.- *- * Icons are Compose-generated bitmaps (Decision D5): the marker glyph is drawn- * once with a [android.graphics.Canvas]; per-place colour is data-driven from- * each feature's `color` property (derived from its category).- */-@Composable-@MaplibreComposable-fun GooglePoiLayer(pins: List<GooglePoiPin>) {-    val marker = remember { generateMarkerBitmap() }-    var source by remember { mutableStateOf<GeoJsonSource?>(null) }--    LaunchedEffect(Unit) {-        source = GeoJsonSource(-            GOOGLE_POI_SOURCE_ID,-            GeoJsonData.Features(FeatureCollection(emptyList<Feature1>())),-            GeoJsonOptions(),-        )-    }--    source?.let { src ->-        LaunchedEffect(pins) {-            src.setData(GeoJsonData.Features(FeatureCollection(pins.map { it.toFeature() })))-        }--        // Category-coloured base dot (the pin body).-        CircleLayer(-            GOOGLE_POI_DOT_LAYER_ID,-            src,-            color = feature["color"].cast<StringValue>().convertToColor(),-            radius = interpolate(-                linear(), zoom(),-                11 to const(4.dp),-                14 to const(6.dp),-                17 to const(8.dp),-            ),-            strokeColor = const(Color.White),-            strokeWidth = const(1.5.dp),-        )--        // White centre glyph (generated bitmap) so the pin reads as a marker.-        SymbolLayer(-            GOOGLE_POI_LAYER_ID,-            src,-            iconImage = image(marker),-            iconSize = interpolate(-                linear(), zoom(),-                11 to const(0.35f),-                14 to const(0.5f),-                17 to const(0.65f),-            ),-        )-    }-}--/** Rebuild a pin as a GeoJSON point feature; category → display colour is baked- *  into `color` so the CircleLayer can style it data-driven, and name/lat/lng- *  ride along so onMapClick can re-select the place. */-private fun GooglePoiPin.toFeature(): Feature1 = Feature1(-    Point(Position(lng, lat)),-    JsonObject(-        mapOf(-            "id" to JsonPrimitive(id),-            "name" to JsonPrimitive(name),-            "lat" to JsonPrimitive(lat),-            "lng" to JsonPrimitive(lng),-            "category" to JsonPrimitive(category ?: ""),-            "color" to JsonPrimitive(colorForCategory(category)),-        )-    ),-)--/**- * Convert a hit-tested pin feature back into a selectable place. We reuse- * [SpecificFeature.GenericPlace] (name + position) so the existing- * `SelectedFeatureViewModel.currentPoiInfo` flow fetches the Google enrichment- * and `GooglePoiEnrichment` renders in the sheet — no new detail path needed.- */-fun Feature1.toSelectedGooglePoi(): SpecificFeature? {-    val props = properties ?: return null-    val name = props.string("name")?.ifBlank { null } ?: return null-    val lat = props["lat"]?.jsonPrimitive?.doubleOrNull ?: return null-    val lng = props["lng"]?.jsonPrimitive?.doubleOrNull ?: return null-    return osmPlace(name, Position(lng, lat))-}--/** Category → pin colour, mirroring Vela's `PoiIcons.colorFor(group)` grouping. */-private fun colorForCategory(category: String?): String {-    val c = category?.lowercase() ?: return "#EA4335"-    return when {-        listOf("restaurant", "food", "dining", "pizza", "burger", "steak", "sushi").any { it in c } -> "#EA4335"-        listOf("cafe", "coffee", "bakery", "tea", "dessert").any { it in c } -> "#F9AB00"-        listOf("bar", "pub", "night", "brew", "wine").any { it in c } -> "#A142F4"-        listOf("hotel", "lodging", "motel", "hostel", "resort").any { it in c } -> "#4285F4"-        listOf("store", "shop", "market", "mall", "grocery", "supermarket").any { it in c } -> "#1A73E8"-        listOf("gas", "fuel", "charging", "ev ").any { it in c } -> "#34A853"-        listOf("park", "garden", "trail", "recreation", "museum", "gallery").any { it in c } -> "#34A853"-        listOf("hospital", "clinic", "pharmacy", "doctor", "health", "dentist").any { it in c } -> "#D93025"-        listOf("bank", "atm", "finance").any { it in c } -> "#188038"-        listOf("school", "university", "college", "library").any { it in c } -> "#F29900"-        else -> "#5F6368"-    }-}--/** Draw the marker once: a white-ringed dot used as the SymbolLayer glyph on top- *  of the category-coloured base circle. */-private fun generateMarkerBitmap(): ImageBitmap {-    val size = 48-    val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)-    val canvas = android.graphics.Canvas(bmp)-    val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)-    val cx = size / 2f-    val cy = size / 2f-    paint.color = android.graphics.Color.WHITE-    canvas.drawCircle(cx, cy, size / 2f - 4f, paint)-    paint.color = android.graphics.Color.parseColor("#33000000")-    paint.style = android.graphics.Paint.Style.STROKE-    paint.strokeWidth = 3f-    canvas.drawCircle(cx, cy, size / 2f - 5f, paint)-    return bmp.asImageBitmap()-}
maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.ktindex 790d4fe6b2..05974022d8 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt@@ -131,9 +131,10 @@ fun MaPoisLayer(source: VectorSource, filterTypes: Set<Int>? = null) {  * and `GooglePoiEnrichment` renders in the sheet — no new detail path needed.  *  * [osmPlace] folds in the sidecar's hours / phone / website / address, so the sheet- * has something to show before (and without) any Google response.+ * has something to show before (and without) any Google response. That is a mapped-file+ * read, which is why this suspends.  */-fun Feature1.toSelectedMaPoi(): SpecificFeature? {+suspend fun Feature1.toSelectedMaPoi(): SpecificFeature? {     val props = properties ?: return null     val name = props.string("name")?.ifBlank { null } ?: return null     val pos = (geometry as? Point)?.coordinates ?: return null
maps/src/main/java/com/vayunmathur/maps/ui/ParkingLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/ParkingLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/ParkingLayer.ktindex b44385ae5d..cbb1a3af09 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/ParkingLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/ParkingLayer.kt@@ -42,7 +42,7 @@ private val PARKING_COLOR = Color(0xFF1967D2)  * Parking-pin overlay (P9): a [GeoJsonSource] holding the single active  * [ParkingSpot] plus a [CircleLayer] body and a [SymbolLayer] "P" glyph on top,  * ported to maplibre-compose declarative layers exactly like [SavedPlacesLayer]- * / [GooglePoiLayer]. Renders nothing when no spot is saved.+ * / [SearchResultLayer]. Renders nothing when no spot is saved.  */ @Composable @MaplibreComposable
maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesLayer.ktindex a11a69b9f6..6e2cd9dd8f 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesLayer.kt@@ -47,7 +47,7 @@ private val SAVED_PLACE_COLOR = Color(0xFF1A73E8)  * Saved-place overlay (Vela's `SavedPin`): a [GeoJsonSource] fed from the user's  * saved places (Home, Work and the starred list) plus a [CircleLayer] "dot" and  * a [SymbolLayer] bookmark glyph on top, ported to maplibre-compose declarative- * layers exactly like [GooglePoiLayer] / [SearchResultLayer]. Tap → details via+ * layers exactly like [SearchResultLayer]. Tap → details via  * [toSelectedSavedPlace], reusing [SpecificFeature.GenericPlace] so the existing  * enrichment + place sheet render with no new detail path.  */
maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.ktindex 0f20a69d99..efc002c891 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt@@ -25,6 +25,7 @@ import com.vayunmathur.library.ui.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment@@ -50,6 +51,7 @@ import com.vayunmathur.maps.util.SearchResult import com.vayunmathur.maps.util.SearchPhase import com.vayunmathur.maps.util.SearchUiState import com.vayunmathur.maps.util.SelectedFeatureViewModel+import kotlinx.coroutines.launch  /**  * Google-only search page (amenities.db removed, Decision D2): a text query@@ -88,6 +90,8 @@ fun SearchPage(         }     } +    val scope = rememberCoroutineScope()+     val actions = remember(nearLat, nearLon, idx) {         object : SearchActions {             override fun setQuery(query: String) {@@ -110,23 +114,29 @@ fun SearchPage(                 // Shared selection path: replace a route waypoint when picking a                 // stop (idx != null), otherwise set the selected feature. Then                 // leave the search page.-                val feature = searchViewModel.toFeature(result)-                if (idx != null) {-                    // The selection could have changed (e.g. user navigated away-                    // and back) between opening search and picking a result.-                    // Tolerate a non-Route current selection rather than crashing.-                    val current = viewModel.selectedFeature.value-                    if (current is SpecificFeature.Route) {-                        viewModel.set(current.copy(waypoints = current.waypoints.mapIndexed { idx2, it ->-                            if (idx2 == idx) feature else it-                        }))+                //+                // Launched because building the feature reads the POI attribute sidecar off the+                // main thread; the pop stays inside so the selection is in place before this+                // page goes away.+                scope.launch {+                    val feature = searchViewModel.toFeature(result)+                    if (idx != null) {+                        // The selection could have changed (e.g. user navigated away+                        // and back) between opening search and picking a result.+                        // Tolerate a non-Route current selection rather than crashing.+                        val current = viewModel.selectedFeature.value+                        if (current is SpecificFeature.Route) {+                            viewModel.set(current.copy(waypoints = current.waypoints.mapIndexed { idx2, it ->+                                if (idx2 == idx) feature else it+                            }))+                        } else {+                            viewModel.set(feature)+                        }                     } else {                         viewModel.set(feature)                     }-                } else {-                    viewModel.set(feature)+                    backStack.pop()                 }-                backStack.pop()             }              override fun pickContactAddress(address: String) {
maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.ktindex 74445ef1de..c33bdb50bb 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt@@ -44,7 +44,7 @@ private const val SEARCH_RESULT_SOURCE_ID = "search-result-geojson"  * Search-result pin overlay (Vela's `MARKERS_LAYER` analog): a [GeoJsonSource]  * fed from the Google search results plus a [CircleLayer] "dot" and a  * [SymbolLayer] marker glyph on top, ported to maplibre-compose declarative- * layers exactly like [GooglePoiLayer]. Distinct from the ambient POI overlay so+ * layers exactly like [SavedPlacesLayer]. Distinct from the ambient POI overlay so  * search pins read as "your results" (a single accent colour) rather than the  * category-coloured ambient POIs. Tap → details via [toSelectedSearchResult].  */
maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.ktindex a6b59941be..242bfdcbcd 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt@@ -53,9 +53,11 @@ fun interface FeatureSource {  * be read and asserted on rather than the shape of a hundred-line chain of `?:` and early  * `return`s.  *- * Not a composable and not suspending. It does no I/O — the admin-label branch used to make a- * Wikidata round-trip inside the gesture handler; that now belongs to the ViewModel, which is- * why [adminLabelIds] hits are returned as raw features for the caller to resolve.+ * Not a composable. [pickPin] suspends: resolving a POI hit reads the `poi_attrs.bin` sidecar,+ * so that one probe does I/O and does it on [kotlinx.coroutines.Dispatchers.IO]. The admin-label+ * branch is the opposite arrangement — it used to make a Wikidata round-trip inside the gesture+ * handler, and now belongs to the ViewModel, which is why [ADMIN_LABEL_LAYER_IDS] hits come back+ * as raw features for the caller to resolve.  */ class MapFeaturePicker(     private val source: FeatureSource,@@ -72,7 +74,7 @@ class MapFeaturePicker(     private class Probe(         val layerId: String,         val enabled: Boolean = true,-        val resolve: (List<Feature1>) -> MapHit?,+        val resolve: suspend (List<Feature1>) -> MapHit?,     )      private val probes: List<Probe> = listOf(@@ -103,7 +105,7 @@ class MapFeaturePicker(      * Every probe uses the same tolerance box so a tap NEAR a small glyph still counts; see      * [MapChromeMetrics.hitSlop].      */-    fun pickPin(offset: DpOffset): MapHit? {+    suspend fun pickPin(offset: DpOffset): MapHit? {         val box = hitBox(offset)         return probes.firstNotNullOfOrNull { probe ->             if (!probe.enabled) null else probe.resolve(source.query(box, setOf(probe.layerId)))
maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.ktindex a8815b83d4..91e2ebbc26 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt@@ -90,8 +90,7 @@ class GooglePoiMapViewModel(application: Application) : AndroidViewModel(applica      /**      * Publish ambient pins from the OFFLINE POI index (P29) for the-     * [north]..[south] × [west]..[east] box, feeding [GooglePoiLayer] (the proven-     * GeoJSON pin renderer). Debounced; views wider than [MAX_LAT_SPAN] and empty+     * [north]..[south] × [west]..[east] box. Debounced; views wider than [MAX_LAT_SPAN] and empty      * results KEEP the previous pins so a fast pan / wide zoom never blinks the      * overlay to nothing (P23 no-clear). The index query + name decode run on      * [Dispatchers.IO]; [PoiIndex.initialize] is idempotent so calling it here is@@ -180,7 +179,7 @@ class GooglePoiMapViewModel(application: Application) : AndroidViewModel(applica         }     } -    /** Map an offline index record to the pin model [GooglePoiLayer] renders; the+    /** Map an offline index record to the pin model [pins] publishes; the      *  category label drives its data-driven pin colour (P29). */     private fun PoiIndex.PoiRecord.toPin(): GooglePoiPin = GooglePoiPin(         id = "poi:$latE7:$lonE7",@@ -237,7 +236,7 @@ class GooglePoiMapViewModel(application: Application) : AndroidViewModel(applica         const val MAX_LAT_SPAN = 0.15          // Cap on ambient offline pins per viewport (P29) so a dense city box-        // stays bounded; matches GooglePoiLayer's close-zoom feel.+        // stays bounded; matches the ambient overlay's close-zoom feel.         const val OFFLINE_CAP = 300          // Degrees of latitude → metres, for turning the viewport's lat span into
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 7826ebdc11..689b3f6e4c 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -154,7 +154,7 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         query: String,         nearLat: Double,         nearLon: Double,-        onFirst: (SearchResult?) -> Unit,+        onFirst: suspend (SearchResult?) -> Unit,     ) {         _query.value = query         searchJob?.cancel()@@ -230,9 +230,9 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati      *      * The sidecar lookup matters most here: an offline result has no Google      * enrichment coming, so without it the sheet opens with a title and nothing-     * else.+     * else. It is also a mapped-file read, hence [osmPlace] and this suspend.      */-    fun toFeature(result: SearchResult): SpecificFeature.GenericPlace =+    suspend fun toFeature(result: SearchResult): SpecificFeature.GenericPlace =         osmPlace(name = result.title, position = Position(result.lon, result.lat))      /**
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 f00f4f088d..cf6e30db8d 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -19,7 +19,7 @@ import java.nio.channels.FileChannel  *  * `poi_index.bin` — a flat array of 14-byte little-endian records  *    `{ int32 lat_e7; int32 lon_e7; uint32 name_off; uint16 type }`,  *    `count = filesize / 14`, sorted ascending by the 64-bit Morton(lat,lon)- *    key (the key itself is not stored).+ *    key (the key itself is not stored — [spatialFromE7] recomputes it).  *  * `poi_attrs.bin` — OPTIONAL attribute sidecar (opening hours, phone,  *    website, address, cuisine, wheelchair), indexed by the ORDINAL of the  *    matching `poi_index.bin` record. See `scripts/maps/osm_ingest/src/poi_attrs.rs`@@ -31,6 +31,13 @@ import java.nio.channels.FileChannel  * from the same host as the graph); queries then return empty lists. The sidecar  * is separately optional: an install that has the index but not the attributes  * keeps working, and every attribute reads as null.+ *+ * **The spatial queries binary-search; they do not scan.** They used to walk all+ * `count` records, which was imperceptible over a California extract and ANR'd the+ * app on a planet-wide one — 22.6 M records on the main thread inside a tap+ * handler. `poi_index.bin` was already sorted by Morton key; this reader simply+ * never used it. See [Mapped.forEachInBbox] for the bound that replaced the scan,+ * and its caveat.  */ object PoiIndex {     private const val TAG = "PoiIndex"@@ -116,26 +123,112 @@ object PoiIndex {                 address == null && cuisine == null && wheelchair == null     } -    private var index: MappedByteBuffer? = null-    private var names: MappedByteBuffer? = null-    private var namesLen: Int = 0-    private var count: Int = 0-    private var loaded = false-    private var tried = false+    /**+     * One consistent set of mappings, published as a unit.+     *+     * Every query used to be `@Synchronized` on this object, which meant a lookup for a tapped+     * pin also blocked a background viewport refresh and vice versa — for the duration of a+     * full-file scan. The mapped state is immutable once built, so the queries need no lock at+     * all: they read [mapped] once into a local and work from that. Only [reload] mutates, and+     * a query already in flight keeps using the snapshot it started with rather than seeing the+     * buffers swapped underneath it.+     */+    private class Mapped(+        val index: MappedByteBuffer,+        val names: MappedByteBuffer,+        val namesLen: Int,+        val count: Int,+        /** The attribute sidecar, or null when it is absent or does not match. */+        val attrs: MappedByteBuffer?,+        /** Byte offset of the attribute blob, i.e. just past the offset array. */+        val attrsBlobStart: Int,+    ) {+        fun latE7(i: Int): Int = index.getInt(i * RECORD_BYTES)+        fun lonE7(i: Int): Int = index.getInt(i * RECORD_BYTES + 4)+        fun nameOff(i: Int): Int = index.getInt(i * RECORD_BYTES + 8)+        fun type(i: Int): Int = index.getShort(i * RECORD_BYTES + 12).toInt() and 0xFFFF++        /** The Morton key the file is sorted by, recomputed from the record's coordinate. */+        fun spatialAt(i: Int): Long = spatialFromE7(latE7(i), lonE7(i))++        fun record(i: Int): PoiRecord =+            PoiRecord(latE7(i), lonE7(i), type(i), nameAt(nameOff(i)) ?: "", i)++        /** Read the NUL-terminated UTF-8 name that starts at byte [off], or null. */+        fun nameAt(off: Int): String? {+            if (off < 0 || off >= namesLen) return null+            var end = off+            while (end < namesLen && names.get(end).toInt() != 0) end+++            val n = end - off+            if (n <= 0) return null+            val bytes = ByteArray(n)+            // Absolute bulk get keeps the shared buffer's position untouched.+            val dup = names.duplicate()+            dup.position(off)+            dup.get(bytes, 0, n)+            return String(bytes, Charsets.UTF_8)+        }++        /** Ordinal of the first record whose key is >= [key], or [count]. */+        fun lowerBound(key: Long): Int {+            var lo = 0+            var hi = count+            while (lo < hi) {+                val mid = (lo + hi) ushr 1+                // Unsigned: half the planet's keys have bit 63 set, and a signed compare here+                // walks off the front of the northern hemisphere.+                if (java.lang.Long.compareUnsigned(spatialAt(mid), key) < 0) lo = mid + 1 else hi = mid+            }+            return lo+        }++        /**+         * Visit every record inside the bbox in file order, stopping early when [onHit]+         * returns false.+         *+         * Cost is the box's Morton span — a binary search to its lower bound, then a walk to+         * its upper bound — rather than [count]. That span is not the box: a box straddling the+         * equator or the prime meridian flips a top-level Z-curve bit and covers most of the+         * key space, so those degenerate back toward a full walk. `poi_spatial.bin` makes the+         * lookup exactly cell-local; this is the bound available without a format change, and+         * it is what takes a POI tap from 22.6 M records to a local handful.+         */+        fun forEachInBbox(+            minLatE7: Int,+            maxLatE7: Int,+            minLonE7: Int,+            maxLonE7: Int,+            onHit: (ordinal: Int, latE7: Int, lonE7: Int) -> Boolean,+        ) {+            if (minLatE7 > maxLatE7 || minLonE7 > maxLonE7) return+            val (first, last) = spatialRangeForBbox(minLatE7, maxLatE7, minLonE7, maxLonE7)+            var i = lowerBound(first)+            while (i < count) {+                if (java.lang.Long.compareUnsigned(spatialAt(i), last) > 0) return+                val latE7 = latE7(i)+                val lonE7 = lonE7(i)+                if (latE7 in minLatE7..maxLatE7 && lonE7 in minLonE7..maxLonE7 &&+                    !onHit(i, latE7, lonE7)+                ) {+                    return+                }+                i+++            }+        }+    } -    /** The attribute sidecar, or null when it is absent or does not match. */-    private var attrs: MappedByteBuffer? = null-    /** Byte offset of the blob, i.e. just past the offset array. */-    private var attrsBlobStart: Int = 0+    @Volatile+    private var mapped: Mapped? = null+    private var tried = false      /** True once both side files were mapped successfully. */-    val available: Boolean get() = loaded+    val available: Boolean get() = mapped != null      /** True when the optional attribute sidecar is mapped and usable. */-    val attributesAvailable: Boolean get() = attrs != null+    val attributesAvailable: Boolean get() = mapped?.attrs != null      /** Number of POI records available offline (0 when not loaded). */-    val recordCount: Int get() = count+    val recordCount: Int get() = mapped?.count ?: 0      /**      * Map both side files from [Context.getExternalFilesDir]. Idempotent and@@ -145,10 +238,35 @@ object PoiIndex {      */     @Synchronized     fun initialize(context: Context): Boolean {-        if (loaded) return true+        if (mapped != null) return true         if (tried) return false         tried = true         val dir = context.getExternalFilesDir(null) ?: return false+        return open(dir)+    }++    /** Force a re-map after the side files finish downloading. */+    @Synchronized+    fun reload(context: Context): Boolean {+        val dir = context.getExternalFilesDir(null) ?: return false+        return reload(dir)+    }++    /**+     * Re-map from an explicit directory.+     *+     * Also the seam `PoiIndexTest` maps fixtures through: the production entry point needs a+     * `Context` only to find the directory, and a unit test has a temp dir and no Context.+     */+    @Synchronized+    internal fun reload(dir: File): Boolean {+        mapped = null+        tried = true+        return open(dir)+    }++    @Synchronized+    private fun open(dir: File): Boolean {         val indexFile = File(dir, INDEX_FILE)         val namesFile = File(dir, NAMES_FILE)         if (!indexFile.isFile || !namesFile.isFile) {@@ -156,59 +274,54 @@ object PoiIndex {             return false         }         return try {-            index = mapReadOnly(indexFile).also { it.order(ByteOrder.LITTLE_ENDIAN) }+            val indexBuf = mapReadOnly(indexFile).also { it.order(ByteOrder.LITTLE_ENDIAN) }             val namesBuf = mapReadOnly(namesFile)-            names = namesBuf-            namesLen = namesBuf.capacity()-            count = (indexFile.length() / RECORD_BYTES).toInt()-            loaded = true-            Log.d(TAG, "Loaded $count POI records, names=${namesLen}B")+            val count = (indexFile.length() / RECORD_BYTES).toInt()             // Separate and optional: a failure here leaves the index perfectly             // usable, just without attributes.-            openAttrs(File(dir, ATTRS_FILE))+            val attrs = openAttrs(File(dir, ATTRS_FILE), count)+            mapped = Mapped(+                index = indexBuf,+                names = namesBuf,+                namesLen = namesBuf.capacity(),+                count = count,+                attrs = attrs?.first,+                attrsBlobStart = attrs?.second ?: 0,+            )+            Log.d(TAG, "Loaded $count POI records, names=${namesBuf.capacity()}B")             true         } catch (e: Exception) {             Log.w(TAG, "Failed to map POI side files", e)-            index = null; names = null; loaded = false+            mapped = null             false         }     } -    /** Force a re-map after the side files finish downloading. */-    @Synchronized-    fun reload(context: Context): Boolean {-        loaded = false-        tried = false-        index = null-        names = null-        attrs = null-        return initialize(context)-    }-     /**-     * Map the attribute sidecar, leaving [attrs] null if anything is off.+     * Map the attribute sidecar, returning null (rather than throwing) if anything is off.      *      * The record-count check is the one that matters: the sidecar joins to the      * index purely by position, so a sidecar from a different build would hand      * every place someone else's phone number. Refusing the file is the only safe      * response, and there is no way to detect the mismatch later.+     *+     * @return the mapped buffer and the byte offset of the blob, or null.      */-    private fun openAttrs(file: File) {-        attrs = null+    private fun openAttrs(file: File, count: Int): Pair<MappedByteBuffer, Int>? {         if (!file.isFile) {             Log.d(TAG, "POI attribute sidecar absent")-            return+            return null         }         try {             val buf = mapReadOnly(file).also { it.order(ByteOrder.LITTLE_ENDIAN) }             if (buf.capacity() < ATTRS_HEADER_BYTES) {                 Log.w(TAG, "$ATTRS_FILE is truncated")-                return+                return null             }             for (i in ATTRS_MAGIC.indices) {                 if (buf.get(i) != ATTRS_MAGIC[i]) {                     Log.w(TAG, "$ATTRS_FILE has the wrong magic")-                    return+                    return null                 }             }             // Not a gate: the length prefixes let this reader step over a key added@@ -221,18 +334,18 @@ object PoiIndex {             val attrCount = buf.getInt(8)             if (attrCount != count) {                 Log.w(TAG, "$ATTRS_FILE has $attrCount slots but the index has $count; ignoring it")-                return+                return null             }             val blobStart = ATTRS_HEADER_BYTES + 4 * attrCount             if (blobStart > buf.capacity()) {                 Log.w(TAG, "$ATTRS_FILE offset array runs past the file")-                return+                return null             }-            attrsBlobStart = blobStart-            attrs = buf             Log.d(TAG, "Loaded POI attributes for $attrCount record(s)")+            return buf to blobStart         } catch (e: Exception) {             Log.w(TAG, "Failed to map $ATTRS_FILE", e)+            return null         }     } @@ -245,55 +358,32 @@ object PoiIndex {             }         } -    /** Read the NUL-terminated UTF-8 name that starts at byte [off], or null. */-    private fun nameAt(off: Int): String? {-        val buf = names ?: return null-        if (off < 0 || off >= namesLen) return null-        var end = off-        while (end < namesLen && buf.get(end).toInt() != 0) end++-        val n = end - off-        if (n <= 0) return null-        val bytes = ByteArray(n)-        // Absolute bulk get keeps the shared buffer's position untouched.-        val dup = buf.duplicate()-        dup.position(off)-        dup.get(bytes, 0, n)-        return String(bytes, Charsets.UTF_8)-    }--    private fun recLatE7(i: Int): Int = index!!.getInt(i * RECORD_BYTES)-    private fun recLonE7(i: Int): Int = index!!.getInt(i * RECORD_BYTES + 4)-    private fun recNameOff(i: Int): Int = index!!.getInt(i * RECORD_BYTES + 8)-    private fun recType(i: Int): Int = index!!.getShort(i * RECORD_BYTES + 12).toInt() and 0xFFFF-     /**      * Case-insensitive prefix/substring search over the deduped name pool,      * returning matching POIs ranked prefix-first then by distance to      * ([nearLat],[nearLon]). Returns an empty list when nothing matches or the      * index isn't loaded.      */-    @Synchronized     fun searchByName(         query: String,         nearLat: Double,         nearLon: Double,         limit: Int = 20,     ): List<PoiRecord> {-        if (!loaded) return emptyList()+        val m = mapped ?: return emptyList()         val q = query.trim().lowercase()         if (q.isEmpty()) return emptyList()          // Pass 1: walk the name pool once, recording matching offsets and their         // rank (0 = prefix match, 1 = substring). Decoding each unique name once         // is the dedup win the side-file layout is designed for.-        val buf = names ?: return emptyList()         val matchRank = HashMap<Int, Int>()         var pos = 0-        while (pos < namesLen) {+        while (pos < m.namesLen) {             var end = pos-            while (end < namesLen && buf.get(end).toInt() != 0) end+++            while (end < m.namesLen && m.names.get(end).toInt() != 0) end++             if (end > pos) {-                val name = nameAt(pos)+                val name = m.nameAt(pos)                 if (name != null) {                     val lower = name.lowercase()                     if (lower.startsWith(q)) matchRank[pos] = 0@@ -305,18 +395,17 @@ object PoiIndex {         if (matchRank.isEmpty()) return emptyList()          // Pass 2: scan records, keeping those whose name offset matched.-        val out = ArrayList<Ranked>(minOf(CANDIDATE_CAP, count))+        val out = ArrayList<Ranked>(minOf(CANDIDATE_CAP, m.count))         var i = 0-        while (i < count && out.size < CANDIDATE_CAP) {-            val off = recNameOff(i)+        while (i < m.count && out.size < CANDIDATE_CAP) {+            val off = m.nameOff(i)             val rank = matchRank[off]             if (rank != null) {-                val name = nameAt(off) ?: ""-                val latE7 = recLatE7(i)-                val lonE7 = recLonE7(i)+                val latE7 = m.latE7(i)+                val lonE7 = m.lonE7(i)                 out.add(                     Ranked(-                        PoiRecord(latE7, lonE7, recType(i), name, i),+                        PoiRecord(latE7, lonE7, m.type(i), m.nameAt(off) ?: "", i),                         rank,                         distanceSq(latE7 / 1e7, lonE7 / 1e7, nearLat, nearLon),                     )@@ -333,14 +422,13 @@ object PoiIndex {      * pre-filter + squared-distance sort). Names are decoded only for the      * returned winners. Empty when the index isn't loaded.      */-    @Synchronized     fun nearest(         lat: Double,         lon: Double,         limit: Int = 20,         maxMeters: Double = 250.0,     ): List<PoiRecord> {-        if (!loaded) return emptyList()+        val m = mapped ?: return emptyList()         val dLat = maxMeters / 111_320.0         val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(1e-6)         val dLon = maxMeters / (111_320.0 * cosLat)@@ -350,35 +438,22 @@ object PoiIndex {         val maxLonE7 = ((lon + dLon) * 1e7).toInt()          val hits = ArrayList<Hit>()-        var i = 0-        while (i < count) {-            val latE7 = recLatE7(i)-            val lonE7 = recLonE7(i)-            if (latE7 in minLatE7..maxLatE7 && lonE7 in minLonE7..maxLonE7) {-                hits.add(Hit(i, distanceSq(latE7 / 1e7, lonE7 / 1e7, lat, lon)))-            }-            i+++        m.forEachInBbox(minLatE7, maxLatE7, minLonE7, maxLonE7) { i, latE7, lonE7 ->+            hits.add(Hit(i, distanceSq(latE7 / 1e7, lonE7 / 1e7, lat, lon)))+            true         }+        // Stable, so records at an equal distance stay in file order — the tie-break the+        // scan this replaced had, and what the equivalence test pins.         hits.sortBy { it.distSq }-        return hits.take(limit).map { h ->-            PoiRecord(-                recLatE7(h.idx),-                recLonE7(h.idx),-                recType(h.idx),-                nameAt(recNameOff(h.idx)) ?: "",-                h.idx,-            )-        }+        return hits.take(limit).map { m.record(it.idx) }     }      /**      * All POIs whose coordinate falls inside the [west]..[east] × [south]..[north]-     * bounding box, capped at [cap] (a linear scan over the flat record array —-     * cheap even at ~283k records for a per-idle viewport refresh). Names are-     * decoded for each returned record. Empty when the index isn't loaded; used-     * to drive the ambient offline pin overlay (P29).+     * bounding box, capped at [cap]. Names are decoded for each returned record.+     * Empty when the index isn't loaded; used to drive the ambient offline pin+     * overlay (P29).      */-    @Synchronized     fun inViewport(         west: Double,         south: Double,@@ -386,20 +461,16 @@ object PoiIndex {         north: Double,         cap: Int = 300,     ): List<PoiRecord> {-        if (!loaded || cap <= 0) return emptyList()+        val m = mapped ?: return emptyList()+        if (cap <= 0) return emptyList()         val minLatE7 = (south * 1e7).toInt()         val maxLatE7 = (north * 1e7).toInt()         val minLonE7 = (west * 1e7).toInt()         val maxLonE7 = (east * 1e7).toInt()-        val out = ArrayList<PoiRecord>(minOf(cap, count))-        var i = 0-        while (i < count && out.size < cap) {-            val latE7 = recLatE7(i)-            val lonE7 = recLonE7(i)-            if (latE7 in minLatE7..maxLatE7 && lonE7 in minLonE7..maxLonE7) {-                out.add(PoiRecord(latE7, lonE7, recType(i), nameAt(recNameOff(i)) ?: "", i))-            }-            i+++        val out = ArrayList<PoiRecord>(minOf(cap, m.count))+        m.forEachInBbox(minLatE7, maxLatE7, minLonE7, maxLonE7) { i, _, _ ->+            out.add(m.record(i))+            out.size < cap         }         return out     }@@ -417,18 +488,18 @@ object PoiIndex {      * Every offset is treated as untrusted. The file arrives over the network and a      * truncated download must read as "no attributes", not throw out of a tap.      */-    @Synchronized     fun attributesAt(ordinal: Int): PoiAttributes? {-        val buf = attrs ?: return null-        if (ordinal < 0 || ordinal >= count) return null+        val m = mapped ?: return null+        val buf = m.attrs ?: return null+        if (ordinal < 0 || ordinal >= m.count) return null         val off = buf.getInt(ATTRS_HEADER_BYTES + 4 * ordinal)         if (off == NO_ATTRS || off < 0) return null         // Bounded before the add, not after: `attrsBlobStart + off` can wrap negative         // for a large positive off, and a negative index passes an `at + 2 > capacity`         // test on its way to an IndexOutOfBoundsException.-        val blobLen = buf.capacity() - attrsBlobStart+        val blobLen = buf.capacity() - m.attrsBlobStart         if (off > blobLen - 2) return null-        val at = attrsBlobStart + off+        val at = m.attrsBlobStart + off         val bodyLen = buf.getShort(at).toInt() and 0xFFFF         val body = at + 2         if (bodyLen > buf.capacity() - body) return null@@ -447,18 +518,16 @@ object PoiIndex {      * can share a coordinate to within a metre, and attaching one's phone number to      * the other is the kind of wrong that looks right.      *-     * Costs one [nearest] call, which is a linear scan of the whole record array —-     * the same cost model [inViewport] documents and runs per viewport idle. If that-     * ever stops being affordable it is a limitation of all three, not of this one.+     * Costs one [nearest] call, which is a binary search plus a walk of a 25 m box.+     * Still a file read against a cold mmap, so callers keep it off the main thread.      */-    @Synchronized     fun attributesNear(         lat: Double,         lon: Double,         name: String,         maxMeters: Double = 25.0,     ): PoiAttributes? {-        if (attrs == null || name.isBlank()) return null+        if (mapped?.attrs == null || name.isBlank()) return null         val match = nearest(lat, lon, limit = 8, maxMeters = maxMeters)             .firstOrNull { it.name == name }             ?: return null
maps/src/main/java/com/vayunmathur/maps/util/SpatialKey.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SpatialKey.kt b/maps/src/main/java/com/vayunmathur/maps/util/SpatialKey.ktnew file mode 100644index 0000000000..7d6c387c35--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/SpatialKey.kt@@ -0,0 +1,63 @@+package com.vayunmathur.maps.util++/**+ * The 64-bit Morton (Z-order) key that `poi_index.bin` and `nodes.bin` are sorted by.+ *+ * This is a bit-for-bit cross-language contract with `latlng_to_spatial` in+ * `scripts/maps/osm_ingest/src/spatial.rs` (the writer) and `Graph::latlng_to_spatial` in+ * `maps/src/main/rust/src/graph.rs`. The device binary-searches files the Rust tools wrote, so+ * a one-bit disagreement does not fail — it silently returns the wrong records. `SpatialKeyTest`+ * pins this against vectors generated from the Rust implementation rather than from expectation.+ *+ * Keys are `u64` held in a `Long` for their bits only. Everything north of the equator has bit+ * 63 set, so a signed comparison sorts the whole northern hemisphere *below* the southern one:+ * every comparison has to go through [java.lang.Long.compareUnsigned].+ */+fun latLngToSpatial(lat: Double, lon: Double): Long {+    val x = (lon + 180.0) / 360.0+    val y = (lat + 90.0) / 180.0+    val ix = toU32(x * 4_294_967_295.0)+    val iy = toU32(y * 4_294_967_295.0)+    var res = 0L+    for (i in 0 until 32) {+        res = res or (((ix ushr i) and 1).toLong() shl (2 * i))+        res = res or (((iy ushr i) and 1).toLong() shl (2 * i + 1))+    }+    return res+}++/** [latLngToSpatial] for a stored `lat_e7`/`lon_e7` pair, mirroring `spatial_from_e7`. */+fun spatialFromE7(latE7: Int, lonE7: Int): Long =+    // `* 1e-7`, not `/ 1e7`. The two disagree in the last bit for roughly a third of e7 values+    // (they are different operations, and 1e-7 is not exactly representable). No sampled+    // disagreement actually reached the key, but this is a bit-for-bit contract: matching the+    // writer's arithmetic is cheaper than arguing about which differences survive truncation.+    latLngToSpatial(latE7 * 1e-7, lonE7 * 1e-7)++/**+ * The smallest Morton interval that is guaranteed to contain every point of the+ * `minLatE7..maxLatE7` × `minLonE7..maxLonE7` box, as `(first, last)` inclusive.+ *+ * Bit interleaving is monotone in each axis independently — the highest differing key bit+ * belongs to either x or y, and a 1 there forces that coordinate to be larger — so the box's two+ * extreme corners bound every point inside it. The interval is a *superset*: it also contains+ * points outside the box, which is why callers still test the exact coordinates.+ *+ * The interval is as wide as the box's Z-curve span, not as the box. A box straddling the+ * equator or the prime meridian flips a top-level bit and spans most of the key space, which is+ * Z-order's known discontinuity (pinned in `spatial.rs`'s+ * `morton_jumps_a_whole_quadrant_at_a_quadrant_boundary`). `poi_spatial.bin` replaces this with+ * an exact cell lookup; this is the bound available without a format change.+ */+fun spatialRangeForBbox(minLatE7: Int, maxLatE7: Int, minLonE7: Int, maxLonE7: Int): Pair<Long, Long> =+    spatialFromE7(minLatE7, minLonE7) to spatialFromE7(maxLatE7, maxLonE7)++/**+ * Rust's `f64 as u32`, which *saturates*: below zero clamps to 0, above `u32::MAX` clamps to+ * `u32::MAX`, NaN is 0.+ *+ * Kotlin's `Double.toInt()` saturates at `Int.MAX_VALUE` instead — half the range — which would+ * fold every longitude east of the prime meridian onto the same key. Going via `Long` keeps the+ * full range; `Double.toLong()` already saturates and already maps NaN to 0.+ */+private fun toU32(v: Double): Int = v.toLong().coerceIn(0L, 0xFFFF_FFFFL).toInt()
maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.ktindex 355c1fedfe..cfbf812ad1 100644--- a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt@@ -11,6 +11,7 @@ import com.vayunmathur.maps.ui.SAVED_PLACE_LAYER_ID import com.vayunmathur.maps.ui.SEARCH_RESULT_LAYER_ID import com.vayunmathur.maps.ui.TRANSIT_STOP_LAYER_ID import com.vayunmathur.maps.ui.theme.MapChromeMetrics+import kotlinx.coroutines.runBlocking import org.maplibre.spatialk.geojson.Point import org.maplibre.spatialk.geojson.Position import kotlin.test.Test@@ -25,6 +26,10 @@ import kotlin.test.assertTrue  * accident of which `?:` came first.  *  * [FeatureSource] is the seam — no renderer, no composition, no device.+ *+ * [MapFeaturePicker.pickPin] suspends because the POI probe reads a sidecar file, so the tests+ * that call it run under [runBlocking]. Nothing here actually blocks: [FakeSource] answers from+ * a map, and no probe reaches real I/O.  */ class MapFeaturePickerTest { @@ -46,7 +51,7 @@ class MapFeaturePickerTest {     private val tap = DpOffset(100.dp, 200.dp)      @Test-    fun `probes run parking, stop, search, saved, family, poi in that order`() {+    fun `probes run parking, stop, search, saved, family, poi in that order`() = runBlocking {         val source = FakeSource(emptyMap())         MapFeaturePicker(source, transitEnabled = true).pickPin(tap) @@ -64,7 +69,7 @@ class MapFeaturePickerTest {     }      @Test-    fun `probeOrder matches what actually gets queried`() {+    fun `probeOrder matches what actually gets queried`() = runBlocking {         val source = FakeSource(emptyMap())         val picker = MapFeaturePicker(source, transitEnabled = true)         picker.pickPin(tap)@@ -73,7 +78,7 @@ class MapFeaturePickerTest {      /** Parking wins outright: a car spot on top of a POI is still the car spot. */     @Test-    fun `parking beats everything below it and stops the search`() {+    fun `parking beats everything below it and stops the search`() = runBlocking {         val source = FakeSource(             mapOf(                 PARKING_PIN_LAYER_ID to listOf(bareFeature()),@@ -88,7 +93,7 @@ class MapFeaturePickerTest {      /** The transit probe is skipped entirely when the layer is not drawn. */     @Test-    fun `a transit stop is not probed while the layer is off`() {+    fun `a transit stop is not probed while the layer is off`() = runBlocking {         val source = FakeSource(emptyMap())         MapFeaturePicker(source, transitEnabled = false).pickPin(tap)         assertTrue(@@ -109,7 +114,7 @@ class MapFeaturePickerTest {      * being hit and the hit being usable are different things.      */     @Test-    fun `an unresolvable feature falls through to the next probe`() {+    fun `an unresolvable feature falls through to the next probe`() = runBlocking {         val source = FakeSource(mapOf(SEARCH_RESULT_LAYER_ID to listOf(bareFeature())))         val hit = MapFeaturePicker(source, transitEnabled = false).pickPin(tap) @@ -121,13 +126,13 @@ class MapFeaturePickerTest {     }      @Test-    fun `no hits anywhere yields null`() {+    fun `no hits anywhere yields null`() = runBlocking {         assertNull(MapFeaturePicker(FakeSource(emptyMap()), transitEnabled = true).pickPin(tap))     }      /** The slop box is what makes tapping *near* a small glyph work. */     @Test-    fun `every pin probe uses the same hit slop box around the tap`() {+    fun `every pin probe uses the same hit slop box around the tap`() = runBlocking {         val source = FakeSource(emptyMap())         MapFeaturePicker(source, transitEnabled = true).pickPin(tap) 
maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.ktnew file mode 100644index 0000000000..0d0dc7745e--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt@@ -0,0 +1,354 @@+package com.vayunmathur.maps.util++import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.file.Files+import kotlin.random.Random+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins [PoiIndex]'s spatial lookups against the linear scans they replaced.+ *+ * `PoiIndex` had no tests at all while it grew three full-file scans, which is how a POI tap+ * came to walk 22.6 M records on the main thread. The interesting risk in replacing those scans+ * is not that the new code is slow, it is that a binary search over a key the reader recomputes+ * can stop one record early and drop a POI — for some coordinates only, without failing.+ *+ * So the oracle here is the OLD implementation, transcribed verbatim below, and the assertion is+ * that the indexed lookups return exactly what it returns. That pins today's behaviour rather+ * than the author's expectations of it, including the tie-breaks.+ */+class PoiIndexTest {++    private var temp: File? = null++    @AfterTest+    fun tearDown() {+        temp?.deleteRecursively()+        temp = null+    }++    // --- fixtures ----------------------------------------------------------++    /** One POI as the fixture writer sees it, before it knows its ordinal. */+    private class Poi(val latE7: Int, val lonE7: Int, val type: Int, val name: String)++    /**+     * The side files for [pois], written to a fresh temp dir and mapped.+     *+     * Records come out sorted by unsigned Morton key, because that is the only thing about+     * `poi_index.bin` the reader is allowed to assume. [returns] the records in file order, so a+     * list index is an ordinal.+     */+    private fun load(pois: List<Poi>, attrs: Map<Int, String> = emptyMap(), attrSlots: Int? = null): List<Poi> {+        val dir = Files.createTempDirectory("poiindex").toFile()+        temp = dir++        val sorted = pois.sortedWith { a, b ->+            java.lang.Long.compareUnsigned(+                spatialFromE7(a.latE7, a.lonE7),+                spatialFromE7(b.latE7, b.lonE7),+            )+        }++        // Name pool: each unique name once, NUL-terminated, in first-seen order.+        val nameOff = LinkedHashMap<String, Int>()+        val namesOut = java.io.ByteArrayOutputStream()+        for (p in sorted) {+            if (p.name !in nameOff) {+                nameOff[p.name] = namesOut.size()+                namesOut.write(p.name.toByteArray(Charsets.UTF_8))+                namesOut.write(0)+            }+        }+        File(dir, PoiIndex.NAMES_FILE).writeBytes(namesOut.toByteArray())++        val index = ByteBuffer.allocate(sorted.size * 14).order(ByteOrder.LITTLE_ENDIAN)+        for (p in sorted) {+            index.putInt(p.latE7)+            index.putInt(p.lonE7)+            index.putInt(nameOff.getValue(p.name))+            index.putShort(p.type.toShort())+        }+        File(dir, PoiIndex.INDEX_FILE).writeBytes(index.array())++        if (attrs.isNotEmpty() || attrSlots != null) {+            File(dir, PoiIndex.ATTRS_FILE)+                .writeBytes(attrsFile(attrSlots ?: sorted.size, attrs))+        }++        assertTrue(PoiIndex.reload(dir), "fixture did not map")+        return sorted+    }++    /**+     * A `poi_attrs.bin` carrying one phone number per entry of [phones], keyed by ordinal.+     *+     * [slots] is separate from `phones.size` so a test can write a sidecar whose record count+     * disagrees with the index — the mismatch the reader has to refuse, since the join is+     * positional and a stale sidecar would hand every place someone else's phone number.+     */+    private fun attrsFile(slots: Int, phones: Map<Int, String>): ByteArray {+        val blob = java.io.ByteArrayOutputStream()+        val offsets = IntArray(slots) { -1 }+        for (ordinal in 0 until slots) {+            val phone = phones[ordinal] ?: continue+            offsets[ordinal] = blob.size()+            val value = phone.toByteArray(Charsets.UTF_8)+            val body = ByteBuffer.allocate(3 + value.size).order(ByteOrder.LITTLE_ENDIAN)+            body.put(2)                        // KEY_PHONE+            body.putShort(value.size.toShort())+            body.put(value)+            blob.write(ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN)+                .putShort(body.capacity().toShort()).array())+            blob.write(body.array())+        }+        val out = ByteBuffer.allocate(12 + 4 * slots + blob.size()).order(ByteOrder.LITTLE_ENDIAN)+        out.put("MAPA".toByteArray(Charsets.US_ASCII))+        out.put(1)          // version+        out.put(0); out.put(0); out.put(0)+        out.putInt(slots)+        for (o in offsets) out.putInt(o)+        out.put(blob.toByteArray())+        return out.array()+    }++    /** A spread of POIs around ([lat],[lon]), plus a few far away to catch an unbounded walk. */+    private fun scatter(rng: Random, n: Int, lat: Double, lon: Double, spanDeg: Double): List<Poi> =+        List(n) { i ->+            Poi(+                latE7 = ((lat + rng.nextDouble(-spanDeg, spanDeg)) * 1e7).toInt(),+                lonE7 = ((lon + rng.nextDouble(-spanDeg, spanDeg)) * 1e7).toInt(),+                type = i % 40,+                // Deliberately not unique: shared names are the whole point of the name pool,+                // and attributesNear matches on name as well as distance.+                name = listOf("Cafe Roma", "Blue Bottle", "Safeway", "Kaiser", "Cafe Roma")[i % 5],+            )+        }++    // --- the oracle: the implementations these replaced ---------------------++    /** `nearest` before the Morton bound: a walk of every record. */+    private fun refNearest(+        recs: List<Poi>,+        lat: Double,+        lon: Double,+        limit: Int,+        maxMeters: Double,+    ): List<PoiIndex.PoiRecord> {+        val dLat = maxMeters / 111_320.0+        val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(1e-6)+        val dLon = maxMeters / (111_320.0 * cosLat)+        val minLatE7 = ((lat - dLat) * 1e7).toInt()+        val maxLatE7 = ((lat + dLat) * 1e7).toInt()+        val minLonE7 = ((lon - dLon) * 1e7).toInt()+        val maxLonE7 = ((lon + dLon) * 1e7).toInt()+        val hits = ArrayList<Pair<Int, Double>>()+        for (i in recs.indices) {+            val r = recs[i]+            if (r.latE7 in minLatE7..maxLatE7 && r.lonE7 in minLonE7..maxLonE7) {+                hits.add(i to distanceSq(r.latE7 / 1e7, r.lonE7 / 1e7, lat, lon))+            }+        }+        // sortedBy is stable, as ArrayList.sortBy was, so equal distances keep file order.+        return hits.sortedBy { it.second }.take(limit).map { (i, _) -> recs[i].asRecord(i) }+    }++    /** `inViewport` before the Morton bound: a walk of every record. */+    private fun refInViewport(+        recs: List<Poi>,+        west: Double,+        south: Double,+        east: Double,+        north: Double,+        cap: Int,+    ): List<PoiIndex.PoiRecord> {+        val minLatE7 = (south * 1e7).toInt()+        val maxLatE7 = (north * 1e7).toInt()+        val minLonE7 = (west * 1e7).toInt()+        val maxLonE7 = (east * 1e7).toInt()+        val out = ArrayList<PoiIndex.PoiRecord>()+        var i = 0+        while (i < recs.size && out.size < cap) {+            val r = recs[i]+            if (r.latE7 in minLatE7..maxLatE7 && r.lonE7 in minLonE7..maxLonE7) out.add(r.asRecord(i))+            i+++        }+        return out+    }++    private fun Poi.asRecord(ordinal: Int) = PoiIndex.PoiRecord(latE7, lonE7, type, name, ordinal)++    private fun distanceSq(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {+        val cosLat = Math.cos(Math.toRadians((aLat + bLat) / 2.0))+        val dLat = aLat - bLat+        val dLon = (aLon - bLon) * cosLat+        return dLat * dLat + dLon * dLon+    }++    // --- equivalence -------------------------------------------------------++    @Test+    fun `nearest returns exactly what the full scan returned`() {+        val rng = Random(1)+        val recs = load(scatter(rng, 4_000, 37.7749, -122.4194, 0.35))+        assertEquals(4_000, PoiIndex.recordCount)+        repeat(200) {+            val lat = 37.7749 + rng.nextDouble(-0.35, 0.35)+            val lon = -122.4194 + rng.nextDouble(-0.35, 0.35)+            val meters = rng.nextDouble(10.0, 2_000.0)+            val limit = rng.nextInt(1, 25)+            assertEquals(+                refNearest(recs, lat, lon, limit, meters),+                PoiIndex.nearest(lat, lon, limit = limit, maxMeters = meters),+                "nearest($lat, $lon, limit=$limit, maxMeters=$meters)",+            )+        }+    }++    @Test+    fun `inViewport returns exactly what the full scan returned, cap included`() {+        val rng = Random(2)+        val recs = load(scatter(rng, 4_000, 51.5074, -0.1278, 0.4))+        repeat(200) {+            val lat = 51.5074 + rng.nextDouble(-0.4, 0.4)+            val lon = -0.1278 + rng.nextDouble(-0.4, 0.4)+            val h = rng.nextDouble(0.001, 0.3)+            val w = rng.nextDouble(0.001, 0.3)+            val cap = rng.nextInt(1, 60)+            assertEquals(+                refInViewport(recs, lon - w, lat - h, lon + w, lat + h, cap),+                PoiIndex.inViewport(lon - w, lat - h, lon + w, lat + h, cap = cap),+                "inViewport around ($lat, $lon) +-($h, $w) cap=$cap",+            )+        }+    }++    /**+     * Z-order's discontinuity is a *performance* caveat, not a correctness one, and this is the+     * difference being asserted. A box containing the origin spans nearly the whole key space,+     * so the walk degenerates — but it must still return every record, which is exactly what+     * would break if the interval were computed from anything other than the two extreme corners.+     */+    @Test+    fun `a bbox straddling the equator and the prime meridian still finds everything`() {+        val rng = Random(3)+        val recs = load(scatter(rng, 2_000, 0.0, 0.0, 1.5))+        assertEquals(+            refInViewport(recs, -1.0, -1.0, 1.0, 1.0, 5_000),+            PoiIndex.inViewport(-1.0, -1.0, 1.0, 1.0, cap = 5_000),+        )+        assertEquals(+            refNearest(recs, 0.0, 0.0, 50, 50_000.0),+            PoiIndex.nearest(0.0, 0.0, limit = 50, maxMeters = 50_000.0),+        )+    }++    @Test+    fun `records outside the box are never returned however far the walk goes`() {+        val recs = load(+            listOf(+                Poi(377_749_000, -1_224_194_000, 1, "Near"),+                Poi(377_749_100, -1_224_194_100, 2, "Near"),+                Poi(-338_688_000, 1_512_093_000, 3, "Sydney"),+                Poi(515_074_000, -1_278_000, 4, "London"),+                Poi(356_762_000, 1_396_503_000, 5, "Tokyo"),+            )+        )+        val got = PoiIndex.nearest(37.7749, -122.4194, limit = 20, maxMeters = 100.0)+        assertEquals(listOf("Near", "Near"), got.map { it.name })+        assertEquals(refNearest(recs, 37.7749, -122.4194, 20, 100.0), got)+    }++    @Test+    fun `an empty index answers every query with an empty list`() {+        load(emptyList())+        assertEquals(0, PoiIndex.recordCount)+        assertTrue(PoiIndex.nearest(37.7749, -122.4194).isEmpty())+        assertTrue(PoiIndex.inViewport(-123.0, 37.0, -122.0, 38.0).isEmpty())+        assertTrue(PoiIndex.searchByName("cafe", 37.7749, -122.4194).isEmpty())+    }++    // --- names and attributes ---------------------------------------------++    @Test+    fun `searchByName ranks prefix matches before substring matches`() {+        load(+            listOf(+                Poi(377_749_000, -1_224_194_000, 1, "Blue Bottle"),+                Poi(377_749_100, -1_224_194_100, 2, "The Blue Door"),+            )+        )+        val got = PoiIndex.searchByName("blue", 37.7749, -122.4194)+        assertEquals(listOf("Blue Bottle", "The Blue Door"), got.map { it.name })+    }++    @Test+    fun `attributesNear joins on name as well as distance`() {+        // Two POIs a metre apart, as a cafe inside a mall is. Attaching the cafe's phone number+        // to the mall is the kind of wrong that looks right, so the name has to decide.+        val recs = load(+            listOf(+                Poi(377_749_000, -1_224_194_000, 1, "Mall"),+                Poi(377_749_050, -1_224_194_000, 2, "Cafe"),+            ),+            attrs = emptyMap(),+        )+        val mall = recs.indexOfFirst { it.name == "Mall" }+        val cafe = recs.indexOfFirst { it.name == "Cafe" }+        load(recs, attrs = mapOf(mall to "+1-555-MALL", cafe to "+1-555-CAFE"))++        assertTrue(PoiIndex.attributesAvailable)+        assertEquals(+            "+1-555-CAFE",+            PoiIndex.attributesNear(37.7749, -122.4194, "Cafe")?.phone,+        )+        assertEquals(+            "+1-555-MALL",+            PoiIndex.attributesNear(37.7749, -122.4194, "Mall")?.phone,+        )+        assertNull(+            PoiIndex.attributesNear(37.7749, -122.4194, "Nowhere"),+            "a name that is not there must not fall back to the nearest thing",+        )+    }++    @Test+    fun `a sidecar whose record count disagrees with the index is refused`() {+        load(+            listOf(+                Poi(377_749_000, -1_224_194_000, 1, "Mall"),+                Poi(377_749_050, -1_224_194_000, 2, "Cafe"),+            ),+            attrs = mapOf(0 to "+1-555-WRONG"),+            attrSlots = 7,+        )+        assertTrue(PoiIndex.available, "the index itself stays usable")+        assertFalse(PoiIndex.attributesAvailable)+        assertNull(PoiIndex.attributesNear(37.7749, -122.4194, "Cafe"))+    }++    @Test+    fun `an absent sidecar leaves the index working with no attributes`() {+        load(listOf(Poi(377_749_000, -1_224_194_000, 1, "Mall")))+        assertTrue(PoiIndex.available)+        assertFalse(PoiIndex.attributesAvailable)+        assertEquals(1, PoiIndex.nearest(37.7749, -122.4194, maxMeters = 50.0).size)+    }++    @Test+    fun `a missing index file leaves every query a no-op`() {+        val dir = Files.createTempDirectory("poiindex-empty").toFile()+        temp = dir+        assertFalse(PoiIndex.reload(dir))+        assertFalse(PoiIndex.available)+        assertEquals(0, PoiIndex.recordCount)+        assertTrue(PoiIndex.nearest(37.7749, -122.4194).isEmpty())+    }+}
maps/src/test/java/com/vayunmathur/maps/util/SpatialKeyTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/SpatialKeyTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/SpatialKeyTest.ktnew file mode 100644index 0000000000..c683865aa3--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/SpatialKeyTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.maps.util++import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Pins the Kotlin Morton key against the Rust one.+ *+ * `poi_index.bin` is sorted by a key the Rust writer computes and never stores, so the reader+ * recomputes it to binary-search the file. Nothing checks the two agree at runtime: a+ * disagreement does not throw, it silently returns records from the wrong part of the planet.+ * The expected values come from `latlng_to_spatial` in `scripts/maps/osm_ingest/src/spatial.rs`,+ * not from what this implementation happens to produce.+ */+class SpatialKeyTest {++    /**+     * Four of the seven exceed `Long.MAX_VALUE`, which is the point of including them: they are+     * ordinary northern-hemisphere coordinates, so anything comparing these keys signed is wrong+     * for over half the planet.+     */+    private val vectors = listOf(+        Vector(37.7749, -122.4194, 10260008668490545080uL),   // San Francisco+        Vector(0.0, 0.0, 4611686018427387903uL),              // null island+        Vector(-33.8688, 151.2093, 8426202144485016706uL),    // Sydney+        Vector(51.5074, -0.1278, 13103069469376416030uL),     // London+        Vector(-89.9999, -179.9999, 9594441uL),               // near the SW corner+        Vector(89.9999, 179.9999, 18446744073699957169uL),    // near the NE corner+        Vector(35.6762, 139.6503, 16000615434097125079uL),    // Tokyo+    )++    private class Vector(val lat: Double, val lon: Double, val key: ULong)++    @Test+    fun `matches the rust writer bit for bit`() {+        for (v in vectors) {+            assertEquals(v.key, latLngToSpatial(v.lat, v.lon).toULong(), "(${v.lat}, ${v.lon})")+        }+    }++    @Test+    fun `four of the vectors do not fit in a signed Long`() {+        val big = vectors.count { it.key > Long.MAX_VALUE.toULong() }+        assertEquals(4, big, "the unsigned cases are what make this suite worth having")+    }++    /**+     * `spatial_from_e7` is the form the writer actually sorts by, and it feeds the reader's+     * binary search one stored record at a time. It multiplies by `1e-7` rather than dividing by+     * `1e7`; these vectors were generated through that arithmetic.+     */+    @Test+    fun `agrees with the writer for stored e7 coordinates`() {+        assertEquals(10260008668490545080uL, spatialFromE7(377_749_000, -1_224_194_000).toULong())+        assertEquals(4611686018427387903uL, spatialFromE7(0, 0).toULong())+        assertEquals(8426202144485016706uL, spatialFromE7(-338_688_000, 1_512_093_000).toULong())+        assertEquals(13103069469376416030uL, spatialFromE7(515_074_000, -1_278_000).toULong())+    }++    /** The corners of the domain, where a saturating-cast mistake would show up first. */+    @Test+    fun `saturates at the corners instead of wrapping`() {+        assertEquals(0uL, latLngToSpatial(-90.0, -180.0).toULong())+        // Out of range in both axes: Rust's `f64 as u32` clamps, so this must not wrap to a+        // small key. Kotlin's Double.toInt() would have stopped at Int.MAX_VALUE.+        assertEquals(latLngToSpatial(90.0, 180.0), latLngToSpatial(1000.0, 1000.0))+        assertEquals(latLngToSpatial(-90.0, -180.0), latLngToSpatial(-1000.0, -1000.0))+    }++    @Test+    fun `is monotonic in each axis independently`() {+        val a = latLngToSpatial(37.0, -122.0)+        val b = latLngToSpatial(37.0, -121.0)+        assertTrue(+            java.lang.Long.compareUnsigned(a, b) < 0,+            "increasing longitude must increase the key",+        )+        val c = latLngToSpatial(38.0, -122.0)+        assertTrue(+            java.lang.Long.compareUnsigned(a, c) < 0,+            "increasing latitude must increase the key",+        )+    }++    /**+     * The containment property [spatialRangeForBbox] relies on, checked against random boxes+     * rather than asserted in a comment.+     *+     * Every point inside a box must have a key inside the box corners' key interval. If this+     * were ever false, `PoiIndex` would stop early and drop POIs — silently, and only for some+     * coordinates, which is the worst way for a spatial index to be wrong.+     */+    @Test+    fun `every point in a bbox has a key inside the corner interval`() {+        val rng = Random(20260824)+        repeat(20_000) {+            val lat0 = rng.nextInt(-900_000_000, 900_000_000)+            val lon0 = rng.nextInt(-1_800_000_000, 1_800_000_000)+            val minLatE7 = lat0+            val maxLatE7 = (lat0.toLong() + rng.nextInt(0, 10_000_000)).coerceAtMost(900_000_000L).toInt()+            val minLonE7 = lon0+            val maxLonE7 = (lon0.toLong() + rng.nextInt(0, 10_000_000)).coerceAtMost(1_800_000_000L).toInt()+            val (first, last) = spatialRangeForBbox(minLatE7, maxLatE7, minLonE7, maxLonE7)+            val latE7 = rng.nextInt(minLatE7, maxLatE7 + 1)+            val lonE7 = rng.nextInt(minLonE7, maxLonE7 + 1)+            val key = spatialFromE7(latE7, lonE7)+            assertTrue(+                java.lang.Long.compareUnsigned(first, key) <= 0 &&+                    java.lang.Long.compareUnsigned(key, last) <= 0,+                "($latE7, $lonE7) fell outside the interval for " ++                    "[$minLatE7..$maxLatE7] x [$minLonE7..$maxLonE7]",+            )+        }+    }+}