Modern Apps git

← Modern-Apps.git

maps: cancel superseded searches, one search lane, 50 ms debounce (#mapsearch)

Commit
397a3d0d66e9637fabc74a66f1e05745f0b9d365
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:09 UTC (22 days ago)
Parents
1436617
Symptom: searching for a place "takes forever".

Two costs sat in MapsSearchViewModel before the index was ever asked:

* A fixed 250 ms debounce on every keystroke. It existed because the
  lookup was slow enough that one search per character stacked up, so
  every character paid a quarter second of dead time up front.
* `searchJob?.cancel()` was the only brake, and it cannot stop a
  blocking lookup: the mapped-file walk never looked at cancellation.
  Each superseded keystroke kept reading the archive to completion on
  its own Dispatchers.IO thread, in parallel with (and competing for
  flash with) the search the user was waiting on. Typing "pizza" could
  leave three or four planet-wide walks running at once.

Change:

* PoiIndex.searchByName takes a `cancelled` poll (default never). The
  word-index path checks it between phases and returns empty early;
  the ViewModel passes `!coroutineContext.isActive`, so a cancelled
  keystroke stops at its next checkpoint. (The rewritten candidate
  engine in the following commit polls inside its scans too.)
* Searches run on a single-lane dispatcher
  (Dispatchers.IO.limitedParallelism(1)), so a superseded search that
  is still unwinding never runs beside its successor.
* Debounce 250 ms -> 50 ms: with cancellation real there is nothing
  left to protect; the window only merges IME bursts (autocorrect,
  paste).
* The two copies of the index call (setQuery, searchAndSelectFirst)
  share one helper. The search bias/limit/boost travel as an internal
  SearchBias to keep parameter lists within detekt's limit.

User-visible effect: the first results of a keystroke start ~200 ms
sooner, and fast typing no longer slows the final search down.

Verified: existing ViewModel tests (searching flag set before the
launch, reset, searchAndSelectFirst with no index) unchanged; compiled
the POI sources standalone against the real planet archive; module
build/tests in the container.

Diff

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 094f4721b3..3b3048f821 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -7,9 +7,12 @@ import com.vayunmathur.maps.data.RecentSearchStore import com.vayunmathur.maps.data.SavedPlaceStore import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.osmPlace+import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job+import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow@@ -105,10 +108,30 @@ private fun PoiIndex.PoiRecord.toSearchResult() = SearchResult( class MapsSearchViewModel(application: Application) : AndroidViewModel(application) {      companion object {-        /** Keystroke debounce (ms) before a query hits the network. */-        private const val SEARCH_DEBOUNCE_MS = 250L+        /**+         * Keystroke coalescing (ms) before a query hits the offline index.+         *+         * Was 250 ms, which on its own was a quarter second of dead time on every character:+         * the search was slow enough that stacking one per keystroke hurt, so typing paid for+         * it up front. With superseded searches cancelled cooperatively and serialised on+         * [searchLane] there is nothing left to protect, and the window only has to merge+         * the bursts an IME delivers (autocorrect replacing a word, a paste).+         */+        private const val SEARCH_DEBOUNCE_MS = 50L     } +    /**+     * One lane for index searches.+     *+     * `searchJob?.cancel()` used to be the only brake, and it does not stop a blocking+     * lookup: the mapped-file walk ignored cancellation, so every superseded keystroke kept+     * reading the archive on its own `Dispatchers.IO` thread, in parallel with โ€” and+     * competing for flash with โ€” the search the user was actually waiting on. Now a+     * superseded search notices it was cancelled at its next checkpoint (see the `cancelled`+     * parameter of [PoiIndex.searchByName]) and the next one never runs beside it.+     */+    private val searchLane: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1)+     private val recentStore = RecentSearchStore.get(application)      private val _query = MutableStateFlow("")@@ -142,8 +165,8 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati      * offline OSM POI index, biased toward [nearLat],[nearLon] (the map centre).      * Queries shorter than two characters clear the results without searching.      *-     * Debounced ~250 ms (Decision D7) so fast typists don't stack a search per-     * keystroke; the previous job is cancelled on every call.+     * Coalesced over [SEARCH_DEBOUNCE_MS] (Decision D7, shortened); the previous job is+     * cancelled on every call and stops at its next checkpoint.      */     fun setQuery(query: String, nearLat: Double, nearLon: Double) {         _query.value = query@@ -178,13 +201,7 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati                 // Offline OSM POI index only (P27). Addresses are not carried by                 // the index, so they resolve to empty. Any offline failure                 // (unmapped/poisoned index, decode error) is swallowed to empty.-                val app = getApplication<Application>()-                val offline = withContext(Dispatchers.IO) {-                    runCatching {-                        PoiIndex.initialize(app)-                        PoiIndex.searchByName(query, nearLat, nearLon, limit = 20, boost = app.searchBoost())-                    }.getOrDefault(emptyList())-                }+                val offline = withContext(searchLane) { offlineSearch(query, nearLat, nearLon) }                 _results.value = offline.map { it.toSearchResult() }             } finally {                 // `finally` because cancellation is the normal exit: every keystroke cancels@@ -214,13 +231,8 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         _query.value = query         searchJob?.cancel()         searchJob = viewModelScope.launch {-            val app = getApplication<Application>()-            val results = withContext(Dispatchers.IO) {-                runCatching {-                    PoiIndex.initialize(app)-                    PoiIndex.searchByName(query, nearLat, nearLon, limit = 20, boost = app.searchBoost())-                }.getOrDefault(emptyList())-            }.map { it.toSearchResult() }+            val results = withContext(searchLane) { offlineSearch(query, nearLat, nearLon) }+                .map { it.toSearchResult() }             _results.value = results             onFirst(results.firstOrNull())         }@@ -267,6 +279,26 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         }     } +    /**+     * The offline index search, run on [searchLane]. Any offline failure (unmapped/poisoned+     * index, decode error) is swallowed to empty; a cancelled caller makes it return early.+     */+    private suspend fun offlineSearch(+        query: String,+        nearLat: Double,+        nearLon: Double,+    ): List<PoiIndex.PoiRecord> {+        val app = getApplication<Application>()+        val context = currentCoroutineContext()+        return runCatching {+            PoiIndex.initialize(app)+            PoiIndex.searchByName(+                query, nearLat, nearLon, limit = 20, boost = app.searchBoost(),+                cancelled = { !context.isActive },+            )+        }.getOrDefault(emptyList())+    }+     /** Resets the search state (keeps recents). */     fun reset() {         searchJob?.cancel()
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 66bfb774bc..9d69d147ff 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -647,20 +647,26 @@ object PoiIndex {      * queries matched nothing before); tokens within one edit of a word match      * too, ranked below exact ones; [boost] (recents + saved places) only      * breaks ties within a rank โ€” it never resurrects a non-match.+     *+     * [cancelled] is polled between phases: a caller whose result is no longer wanted (the+     * user typed another character) gets an empty list back early instead of the lookup+     * running to completion beside its successor.      */+    @Suppress("LongParameterList") // query + bias point + limit + ranking signal + cancel token     fun searchByName(         query: String,         nearLat: Double,         nearLon: Double,         limit: Int = 20,         boost: Map<String, Double> = emptyMap(),+        cancelled: () -> Boolean = { false },     ): List<PoiRecord> {         val m = mapped ?: return emptyList()         if (query.isBlank()) return emptyList()         // Fully-qualified: the package-level search lives in PoiIndexWords.kt.         if (m.nameIdx != null) {             return com.vayunmathur.maps.util.searchByWordIndex(-                m, query, nearLat, nearLon, limit, CANDIDATE_CAP, boost,+                m, query, SearchBias(nearLat, nearLon, limit, boost), CANDIDATE_CAP, cancelled,             )         }         return searchByScan(m, query, nearLat, nearLon, limit, boost)
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 fc87cfbfda..a99ebd1ac4 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt@@ -150,6 +150,17 @@ private fun PoiIndex.Mapped.matchesAt(i: Int, key: ByteArray): Boolean {     return wordStartsWith(w, key) } +/**+ * Where and how a name search ranks: the bias point, how many results, and the+ * caller's recency/favorites signal (lowercased name -> weight).+ */+internal class SearchBias(+    val lat: Double,+    val lon: Double,+    val limit: Int,+    val boost: Map<String, Double> = emptyMap(),+)+ private class WordRanked(     val record: PoiIndex.PoiRecord,     val boost: Double,@@ -344,12 +355,14 @@ private fun scanMatchAt( internal fun searchByWordIndex(     m: PoiIndex.Mapped,     query: String,-    nearLat: Double,-    nearLon: Double,-    limit: Int,+    bias: SearchBias,     candidateCap: Int,-    boost: Map<String, Double> = emptyMap(),+    cancelled: () -> Boolean = { false }, ): List<PoiIndex.PoiRecord> {+    val nearLat = bias.lat+    val nearLon = bias.lon+    val limit = bias.limit+    val boost = bias.boost     val tokens = splitTokens(query.trim())     if (tokens.isEmpty()) return emptyList()     val keys = tokens.map { poiQueryKey(it) }@@ -371,11 +384,14 @@ internal fun searchByWordIndex(             m.wordPrefixMatches(key, FUZZY_EXACT_SEED_CAP).associate { it[0] to it[1] }         }     }+    if (cancelled()) return emptyList()     val local = m.localWordMatches(keys, nearLat, nearLon, limit)+    if (cancelled()) return emptyList()     val ordinals: Set<Int> = exactRanks.keys + local.keys     fun isPhrasePrefix(o: Int): Boolean = (exactRanks[o] ?: local[o]) == 0      val fuzzy = fuzzyMatches(m, tokens, exact, ordinals, candidateCap)+    if (cancelled()) return emptyList()     val shortlist = m.shortlist(         ordinals.map { it to if (isPhrasePrefix(it)) 0 else 1 } + fuzzy.toList(),         nearLat,