Modern Apps git

← Modern-Apps.git

contacts: slow contact sources still publish when they land (#926)

Commit
cb2c0d26bbc25c1f761d90739efde56ec1861424
Author
Vayun Mathur <[email protected]>
When
2026-12-04 18:22 UTC (1 day ago)
Parents
11e611f
Issue 926 (v2.6.11B, LineageOS on Galaxy S10): the app showed
only a loading animation and then no contacts at all under the
Contacts and Groups tabs, on every start; filtering contact
sources did not help, and v2.6.4 worked.

Root cause

The earlier per-source isolation bounded how long a sync waits
for each source, but it also discarded the timed-out source:
loadContacts cancelled the deferred and treated the source as
empty. That is right for a wedged provider (the LineageOS
IccProvider waiting on the radio for EF_ADN), but wrong for a
provider that is merely slow. The device source is a whole-book
query - every RawContact plus the full Data table, photo blobs
included - so on a cold start with a large book it can
legitimately run past the 5s timeout. Every sync then repeated
the same query, hit the same timeout, and threw the finished
result away: the book read as empty on every start, forever,
with no recovery short of a provider change event happening to
coincide with a faster run. Filtering sources could not help
because the discarded query is the unfiltered sync itself.

Fix

A timeout now only stops the wait, not the source. In
ContactSourceLoader.loadContacts the timed-out deferred is no
longer cancelled; a late-completion continuation on the loader
scope publishes the completed device+SIM merge when the source
eventually lands. The return value and the loading state are
unchanged - the wait still terminates on the timeout with
whatever has landed, a throwing source still reads as empty,
and a never-answering source simply never publishes (its Binder
thread stays abandoned on the IO pool, as before). A monotonic
load generation guards the late publish: if a newer sync has
started, the stale late result is dropped instead of
overwriting the fresher list. Loader close (ViewModel cleared)
cancels the late continuation. contacts/AGENTS.md updated to
document the semantics.

Regression tests

ContactSourceLoaderTest gains three tests driving the loader
with non-cancellable sleeps (a stuck/slow Binder call cannot be
cancelled): a slow device source past its timeout still
publishes device+SIM when it lands; a slow SIM source does the
same; and a late result from a superseded load does not
overwrite the newer load's list. The pre-existing throwing /
hanging / healthy loader tests and SimSourceIsolation926Test
still pass unchanged.

Verified in this worktree:
- Targeted: :contacts:testDevUnitTest for ContactSourceLoaderTest
  and SimSourceIsolation926Test - green.
- Full: :contacts:lint :contacts:lintVitalRelease green;
  :contacts:testDevUnitTest ran 605 tests with 3 failures, all
  unrelated to this change: DeepInteractionsPass2Test.
  insertOrEditShowsContactsAndCreateNewRoutes fails identically
  on the unmodified base (same '+14155550199' assertExists), and
  CropCanvasPass2Test / InsertOrEditIntentActivityPass2Test
  failed only in the loaded full run and pass in isolation -
  the known flaky Compose UI tests under load.

Local commit only; not pushed, issue not closed.

Diff

contacts/AGENTS.md
diff --git a/contacts/AGENTS.md b/contacts/AGENTS.mdindex 414f887847..b2f8bbc72e 100644--- a/contacts/AGENTS.md+++ b/contacts/AGENTS.md@@ -46,7 +46,7 @@ are no watch receivers in this module. - Watch state persists in `data/WearContactsStore` (`contacts_snapshot.json` + `contacts_manifest.json` in filesDir). - Watch listing screenshots are the `group = "wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt`, collected by `:contacts:metadata` into `metadata_data/photos/contacts/wear/`; phone shots use the `phone` bucket. **Gotchas:**-- Contact load is per-source isolated (`data/ContactSourceLoader`): device and SIM contacts publish independently under a per-source timeout, the loaded flag flips as soon as the contacts land, and the one-time migrations plus provider-accounts/default-account refresh run after that under the same timeout — a throwing or never-answering SIM/provider source reads as empty for that source only and never blanks the list or holds the loading state+- Contact load is per-source isolated (`data/ContactSourceLoader`): device and SIM contacts publish independently under a per-source timeout, the loaded flag flips as soon as the contacts land, and the one-time migrations plus provider-accounts/default-account refresh run after that under the same timeout — a throwing or never-answering SIM/provider source reads as empty for that source only and never blanks the list or holds the loading state. A timeout only stops the wait: a source that lands late still publishes the completed merge (a stale late result from a superseded load is dropped), so a slow-but-healthy provider never reads as a permanently empty book - `util/` is NOT a closed package root — don't add more files there - Write paths go through the contacts provider + account (`platform/`), not a local DB — account picker dialogs matter - `ImportActivity` + `ImportVcfScreen` handle VIEW intents; `ContactListPick`/`ContactItemPick` serve picker callers
contacts/src/main/java/com/vayunmathur/contacts/data/ContactSourceLoader.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/ContactSourceLoader.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/ContactSourceLoader.ktindex 35f0532be5..9364bdac4e 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/ContactSourceLoader.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/ContactSourceLoader.kt@@ -8,7 +8,9 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull+import java.util.concurrent.atomic.AtomicLong  /** Upper bound one contact source may take before it is abandoned as empty. */ internal const val CONTACT_SOURCE_TIMEOUT_MILLIS = 5_000L@@ -29,11 +31,25 @@ internal const val CONTACT_SOURCE_TIMEOUT_MILLIS = 5_000L  *  * Throwing sources are isolated the same way: the failure is logged  * and reads as an empty source, never as a failed whole load.+ *+ * A timeout only stops the *wait*, it does not discard the source: a+ * provider that is slow rather than wedged (a large address book's+ * whole-book Data query, photos included, can legitimately take+ * longer than [CONTACT_SOURCE_TIMEOUT_MILLIS] on a cold start) still+ * publishes when it eventually lands, via the late-completion path in+ * [loadContacts]. Before that, such a book read as empty on every+ * sync — each start re-ran the same query, timed it out at the same+ * point, and threw the finished result away, so the contacts never+ * showed at all. A late result from a superseded load is dropped so+ * it cannot overwrite a newer load's list.  */ internal class ContactSourceLoader(     private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO), ) { +    /** Generation of the newest [loadContacts] call; late results from older loads are dropped. */+    private val latestLoadGeneration = AtomicLong(0)+     /** Releases the detached scope; in-flight stuck calls are abandoned. */     fun close() {         scope.cancel()@@ -72,7 +88,9 @@ internal class ContactSourceLoader(      * [publish] as soon as the device source lands and again with the      * merged list once the SIM source lands (or times out / fails).      * Returns the merged list; a failed or hanging source contributes-     * no contacts.+     * no contacts to the return value, but a source that lands after+     * its timeout still publishes the completed merge (unless a newer+     * load has superseded this one).      */     // Broad catches are deliberate: each source crosses an OEM provider     // that throws undocumented RuntimeExceptions, and a failed source@@ -104,19 +122,43 @@ internal class ContactSourceLoader(                 emptyList()             }         }+        val generation = latestLoadGeneration.incrementAndGet()+        var deviceTimedOut = false+        var simTimedOut = false         val device = withTimeoutOrNull(timeoutMillis) { deviceDeferred.await() }             ?: emptyList<Contact>().also {+                deviceTimedOut = true                 Log.status(TAG, "Device contact source timed out after ${timeoutMillis}ms")-                deviceDeferred.cancel()             }         publish(device)         val sim = withTimeoutOrNull(timeoutMillis) { simDeferred.await() }             ?: emptyList<Contact>().also {+                simTimedOut = true                 Log.status(TAG, "SIM contact source timed out after ${timeoutMillis}ms")-                simDeferred.cancel()             }         val merged = device + sim         publish(merged)+        if (deviceTimedOut || simTimedOut) {+            // The timeout ended the wait so the loading state can+            // terminate and the other source can show, but the timed-out+            // source is not cancelled or discarded: when it eventually+            // lands, publish the completed merge. A source that never+            // lands simply never publishes (its Binder thread stays+            // abandoned on the IO pool, as before). A newer load+            // supersedes this one, so a stale late result is dropped+            // instead of overwriting the fresher list.+            scope.launch {+                try {+                    val lateDevice = if (deviceTimedOut) deviceDeferred.await() else device+                    val lateSim = if (simTimedOut) simDeferred.await() else sim+                    if (latestLoadGeneration.get() == generation) {+                        publish(lateDevice + lateSim)+                    }+                } catch (e: CancellationException) {+                    // Loader closed (ViewModel cleared) before the source landed.+                }+            }+        }         return merged     } 
contacts/src/test/java/com/vayunmathur/contacts/util/ContactSourceLoaderTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/util/ContactSourceLoaderTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/util/ContactSourceLoaderTest.ktindex 23aec5aaa2..1b7fdad119 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/util/ContactSourceLoaderTest.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/util/ContactSourceLoaderTest.kt@@ -117,6 +117,91 @@ class ContactSourceLoaderTest {         }     } +    @Test+    fun slowDeviceSourceBeyondTimeoutStillPublishesWhenItLands() = runBlocking {+        val loader = ContactSourceLoader()+        try {+            val device = listOf(contact(7, "Aisha"), contact(8, "Bob"))+            val sim = listOf(contact(-1, "Sim"))+            val published = mutableListOf<List<Contact>>()+            val started = System.nanoTime()+            val merged = withTimeout(10_000) {+                loader.loadContacts(+                    // Slow, not wedged: a non-cancellable sleep longer+                    // than the timeout, like a big book's provider query.+                    deviceLoader = { Thread.sleep(600); device },+                    simLoader = { sim },+                    timeoutMillis = 100,+                    publish = { published.add(it) },+                )+            }+            val elapsedMillis = (System.nanoTime() - started) / 1_000_000+            // The wait still terminates on the timeout with what has landed.+            assertEquals(sim, merged)+            assertTrue(elapsedMillis < 3_000, "load took ${elapsedMillis}ms despite the timeout")+            // And the finished device result is not thrown away: the+            // completed merge publishes when the source lands (#926 —+            // before this, every sync repeated the same timeout and the+            // book read as empty on every start).+            withTimeout(5_000) {+                while (published.lastOrNull() != device + sim) delay(25)+            }+        } finally {+            loader.close()+        }+    }++    @Test+    fun slowSimSourceBeyondTimeoutStillPublishesWhenItLands() = runBlocking {+        val loader = ContactSourceLoader()+        try {+            val device = listOf(contact(7, "Aisha"))+            val sim = listOf(contact(-1, "Sim"))+            val published = mutableListOf<List<Contact>>()+            val merged = withTimeout(10_000) {+                loader.loadContacts(+                    deviceLoader = { device },+                    simLoader = { Thread.sleep(600); sim },+                    timeoutMillis = 100,+                    publish = { published.add(it) },+                )+            }+            assertEquals(device, merged)+            withTimeout(5_000) {+                while (published.lastOrNull() != device + sim) delay(25)+            }+        } finally {+            loader.close()+        }+    }++    @Test+    fun lateResultFromSupersededLoadDoesNotOverwriteNewerList() = runBlocking {+        val loader = ContactSourceLoader()+        try {+            val stale = listOf(contact(1, "Stale"))+            val fresh = listOf(contact(2, "Fresh"))+            val published = mutableListOf<List<Contact>>()+            loader.loadContacts(+                deviceLoader = { Thread.sleep(600); stale },+                simLoader = { emptyList() },+                timeoutMillis = 100,+                publish = { published.add(it) },+            )+            loader.loadContacts(+                deviceLoader = { fresh },+                simLoader = { emptyList() },+                timeoutMillis = 2_000,+                publish = { published.add(it) },+            )+            // Give the first load's late completion time to land.+            delay(900)+            assertEquals(fresh, published.last())+        } finally {+            loader.close()+        }+    }+     @Test     fun singleSourceLoadIsolatesThrowAndHang() = runBlocking {         val loader = ContactSourceLoader()