contacts: isolate SIM source so a wedged SIM cannot hang the list
- Commit
9a6f5b64dfb7653f254526497d1d6ed9a95da160- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 02:15 UTC (19 days ago)
- Parents
6aaeb30
Fixes issue 926 (v2.6.11B, LineageOS on Galaxy S10): the contacts
app showed only a loading animation forever, with no contacts
under the Contacts or Groups tabs and no crash. Unchecking
contact sources did not help. v2.6.4 worked.
Root cause
SIM contacts arrived after v2.6.4: 51850bd64 added SIM support
and 037333303 made each SIM a virtual contact account whose
ADN rows were merged into the unified list inside
syncFromSystem(). That merge was strictly sequential and
publish-once:
val device = Contact.getAllContacts(app)
val sim = SimContactsDataSource.simContactsAsContacts(app)
allContactsState.value = device + sim
Both tabs gate their loading spinner on hasLoadedContacts
(ContactList: isLoading = !hasLoadedContacts; GroupsPage the
same), and that flag flips only in the finally block after the
merge above. So one slow source held the device contacts --
already loaded -- hostage and kept the flag down forever.
On the reported device the SIM half is what never answers.
simContactsAsContacts() issues a synchronous Binder query to
content://icc/adn/subId/<subId>, served by the platform
IccProvider, which loads EF_ADN from the card through the
radio. On LineageOS builds that query can block waiting on
the telephony stack instead of returning or throwing, so the
existing catch blocks (which already contained throwing
providers) never run. A physical SIM is required to take this
path at all -- without one there are no per-subId URIs to
query -- which is why the reporter ties it to the physical
SIM newly appearing as a listed source, why filtering sources
cannot help (the query runs before any filter is applied, on
the unfiltered sync), and why v2.6.4, whose sync was a single
getAllContacts() call with no SIM query, never hit it. The
same unbounded pattern repeated in the accounts path:
getSimSubscriptionInfos() was called three times per sync
(once for labels, twice more inside loadAccountsInternal)
with no timeout on any of them.
Fix
- New ContactSourceLoader loads each source on a detached
supervisor scope and only waits for it with a timeout
(5s per source). A Binder call that never answers cannot
be interrupted by coroutine cancellation, so timing out
abandons the wait, logs the source, and treats it as
empty; a throwing source is isolated the same way.
- syncFromSystem() now loads device and SIM in parallel and
publishes the device list as soon as it lands, then the
merged list once the SIM lands or is abandoned. SIM
contacts still load whenever the device answers normally.
- The subscription enumeration gets the same isolation and
its single result is reused for the account labels and the
accounts list instead of being queried three times.
- fetchGroups() now catches provider failures as "no groups"
instead of killing the groups flow.
- hasLoadedContacts still flips in syncFromSystem()'s
finally, which is now guaranteed to be reached: every
blocking call inside the sync is behind the loader timeout.
Regression tests (fake seam)
- ContactSourceLoaderTest drives the loader with fake source
lambdas: throwing SIM (device still publishes), hanging SIM
and hanging device (non-cancellable Thread.sleep, like a
stuck Binder call; the other source still publishes and the
load returns promptly), healthy merge, and single-source
isolation.
- SimSourceIsolation926Test puts throwing and hanging fake
ICC providers behind the real SIM seam next to the fake
device provider: device contacts (ids 7, 8) still render,
hasLoadedContacts flips, and a healthy fake SIM still
merges into the list.
Verified: :contacts:compileDevKotlin and
:contacts:testDevUnitTest green (565 tests, 0 failures).
:contacts:detekt reports only the two pre-existing
MainActivity findings from the tabs-as-routes change, which
this change does not touch.
No push, per instructions.Diff
contacts/src/main/java/com/vayunmathur/contacts/util/ContactSourceLoader.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactSourceLoader.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactSourceLoader.ktnew file mode 100644index 0000000000..ad95581b09--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactSourceLoader.kt@@ -0,0 +1,126 @@+package com.vayunmathur.contacts.util++import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.async+import kotlinx.coroutines.cancel+import kotlinx.coroutines.withTimeoutOrNull++/** Upper bound one contact source may take before it is abandoned as empty. */+internal const val CONTACT_SOURCE_TIMEOUT_MILLIS = 5_000L++/**+ * Loads every contact source independently so one bad source cannot wedge+ * the whole address book (issue 926).+ *+ * The system contacts provider and the ICC ADN provider+ * (`content://icc/adn/subId/<subId>`) are both synchronous Binder calls:+ * a provider that never answers cannot be interrupted by coroutine+ * cancellation. Each source therefore runs on this loader's own+ * supervisor scope, detached from the caller, and the caller only+ * *waits* for it with [withTimeoutOrNull]. Timing out abandons the+ * wait (the stuck Binder thread is left on the IO pool) and surfaces+ * that source as empty; every other source still publishes and the+ * caller's loading state still terminates.+ *+ * Throwing sources are isolated the same way: the failure is logged+ * and reads as an empty source, never as a failed whole load.+ */+internal class ContactSourceLoader(+ private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),+) {++ /** Releases the detached scope; in-flight stuck calls are abandoned. */+ fun close() {+ scope.cancel()+ }++ /**+ * Runs [block] as one isolated source, returning null when it throws+ * or does not answer within [timeoutMillis].+ */+ @Suppress("TooGenericExceptionCaught")+ suspend fun <T> load(+ sourceName: String,+ timeoutMillis: Long = CONTACT_SOURCE_TIMEOUT_MILLIS,+ block: suspend () -> T,+ ): T? {+ val deferred = scope.async {+ try {+ block()+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.status(TAG, "Contact source $sourceName failed; treating it as empty", e)+ null+ }+ }+ val result = withTimeoutOrNull(timeoutMillis) { deferred.await() }+ if (result == null && !deferred.isCompleted) {+ Log.status(TAG, "Contact source $sourceName timed out after ${timeoutMillis}ms; treating it as empty")+ deferred.cancel()+ }+ return result+ }++ /**+ * Loads device and SIM contacts in parallel, publishing through+ * [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.+ */+ // Broad catches are deliberate: each source crosses an OEM provider+ // that throws undocumented RuntimeExceptions, and a failed source+ // must read as empty rather than fail the merged load.+ @Suppress("TooGenericExceptionCaught")+ suspend fun loadContacts(+ deviceLoader: suspend () -> List<Contact>,+ simLoader: suspend () -> List<Contact>,+ timeoutMillis: Long = CONTACT_SOURCE_TIMEOUT_MILLIS,+ publish: (List<Contact>) -> Unit = {},+ ): List<Contact> {+ val deviceDeferred = scope.async {+ try {+ deviceLoader()+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.status(TAG, "Device contact source failed; treating it as empty", e)+ emptyList()+ }+ }+ val simDeferred = scope.async {+ try {+ simLoader()+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.status(TAG, "SIM contact source failed; treating it as empty", e)+ emptyList()+ }+ }+ val device = withTimeoutOrNull(timeoutMillis) { deviceDeferred.await() }+ ?: emptyList<Contact>().also {+ Log.status(TAG, "Device contact source timed out after ${timeoutMillis}ms")+ deviceDeferred.cancel()+ }+ publish(device)+ val sim = withTimeoutOrNull(timeoutMillis) { simDeferred.await() }+ ?: emptyList<Contact>().also {+ Log.status(TAG, "SIM contact source timed out after ${timeoutMillis}ms")+ simDeferred.cancel()+ }+ val merged = device + sim+ publish(merged)+ return merged+ }++ private companion object {+ const val TAG = "ContactSourceLoader"+ }+}
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex 9ea49ad6b7..b76c349ee0 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -95,9 +95,17 @@ class ContactViewModel internal constructor( application: Application, /** Where the provider's default-account facts come from (#916); tests pass a fake. */ internal val defaultAccountSource: DefaultAccountSource,+ /** Per-source load timeout (issue 926); tests shrink it so a hanging fake answers fast. */+ internal val contactSourceTimeoutMillis: Long = CONTACT_SOURCE_TIMEOUT_MILLIS, ) : AndroidViewModel(application), ContactsActions { - constructor(application: Application) : this(application, SystemDefaultAccountSource(application))+ constructor(application: Application) : this(+ application,+ SystemDefaultAccountSource(application),+ )++ /** Isolated per-source loading (issue 926); see [ContactSourceLoader]. */+ internal val contactSourceLoader = ContactSourceLoader() internal val dataStore = DataStoreUtils.getInstance(application) @@ -194,6 +202,9 @@ class ContactViewModel internal constructor( }.flowOn(Dispatchers.IO) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(SUBSCRIBE_TIMEOUT), emptyList()) + // Broad catch is deliberate: a failing groups query must read as "no+ // groups", not kill the groups flow while the contacts list is fine.+ @Suppress("TooGenericExceptionCaught") private fun fetchGroups(): List<ContactGroup> { val resolver = getApplication<Application>().contentResolver val uri = ContactsContract.Groups.CONTENT_URI@@ -201,13 +212,17 @@ class ContactViewModel internal constructor( val list = mutableListOf<ContactGroup>() val selection = "${ContactsContract.Groups.GROUP_VISIBLE} = 1 AND ${ContactsContract.Groups.DELETED} = 0"- resolver.query(uri, projection, selection, null, null)?.use { cursor ->- val idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Groups._ID)- val titleIdx = cursor.getColumnIndexOrThrow(ContactsContract.Groups.TITLE)- while (cursor.moveToNext()) {- val title = cursor.getString(titleIdx) ?: "Unnamed"- list.add(ContactGroup(cursor.getLong(idIdx), title))+ try {+ resolver.query(uri, projection, selection, null, null)?.use { cursor ->+ val idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Groups._ID)+ val titleIdx = cursor.getColumnIndexOrThrow(ContactsContract.Groups.TITLE)+ while (cursor.moveToNext()) {+ val title = cursor.getString(titleIdx) ?: "Unnamed"+ list.add(ContactGroup(cursor.getLong(idIdx), title))+ } }+ } catch (e: Exception) {+ Log.status("ContactViewModel", "Error loading groups; treating as empty", e) } return list.sortedByNameLocale { it.name } }@@ -331,6 +346,7 @@ class ContactViewModel internal constructor( } override fun onCleared() {+ contactSourceLoader.close() getApplication<Application>().contentResolver.unregisterContentObserver(contactsObserver) getApplication<Application>().contentResolver.unregisterContentObserver(simObserver) // Broad catch is deliberate: must not throw out of onCleared.@@ -414,11 +430,27 @@ class ContactViewModel internal constructor( val app = getApplication<Application>() migrateNoYearEventDates() migrateBirthdayCalendarToUtc()- val device = com.vayunmathur.contacts.data.Contact.getAllContacts(app)- val sim = SimContactsDataSource.simContactsAsContacts(app)- allContactsState.value = device + sim- // Refresh SIM account labels for UI (type|name -> display)- val infos = SimContactsDataSource.getSimSubscriptionInfos(app)+ // Issue 926: device and SIM are independent sources. Before this,+ // the two ran sequentially and only the merged list was published,+ // so a SIM query that never answered (the LineageOS IccProvider+ // waiting on the radio for EF_ADN) blocked the device contacts+ // too and _hasLoadedContacts never flipped — both tabs spun+ // forever. The loader publishes the device list as soon as it+ // lands and abandons a throwing/hanging SIM source as empty.+ contactSourceLoader.loadContacts(+ deviceLoader = { com.vayunmathur.contacts.data.Contact.getAllContacts(app) },+ simLoader = { SimContactsDataSource.simContactsAsContacts(app) },+ timeoutMillis = contactSourceTimeoutMillis,+ publish = { allContactsState.value = it },+ )+ // Refresh SIM account labels for UI (type|name -> display). The+ // subscription enumeration is itself a telephony Binder call, so+ // it gets the same isolation/timeout, and its result is reused+ // for the accounts list instead of being queried twice more.+ val infos = contactSourceLoader.load(+ sourceName = "sim-subscriptions",+ timeoutMillis = contactSourceTimeoutMillis,+ ) { SimContactsDataSource.getSimSubscriptionInfos(app) } ?: emptyList() val labels = infos.associate { info -> val acc = ContactAccount(SimContactsDataSource.accountNameFor(info), SIM_ACCOUNT_TYPE) "${acc.type}|${acc.name}" to@@ -426,14 +458,9 @@ class ContactViewModel internal constructor( } simAccountLabelsState.value = labels simSlotLabelsState.value = simSlotLabelsFor(infos)- // Also refresh the accounts list to include current SIM accounts (in case SIM inserted/removed)- // Do it by launching loadAccounts() if needed; but we can update accountsState directly- // to avoid double query. However loadAccounts() also merges DataStore saved accounts,- // so we trigger it.- // Use a direct call to avoid extra launch overhead: we are already on IO, but- // loadAccounts() launches its own coroutine, so just trigger it.- // To keep accounts in sync, refresh directly: already on IO via syncFromSystem().- loadAccountsInternal()+ // Also refresh the accounts list to include current SIM accounts+ // (in case a SIM was inserted/removed), reusing [infos].+ loadAccountsInternal(simInfos = infos) } fun getContact(contactId: Long): Contact? {
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.ktindex 54e4b45e79..453e465d8d 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt@@ -83,19 +83,29 @@ internal fun decodeHiddenKeyClean(entry: String): Pair<String, String>? { return type to name } -internal suspend fun ContactViewModel.loadAccountsInternal() {+internal suspend fun ContactViewModel.loadAccountsInternal(+ simInfos: List<SimContactsDataSource.SimSubscriptionInfo>? = null,+) { val app = getApplication<Application>() val accountSet = queryProviderAccounts(app) migrateLegacyAccounts() val savedAccounts = loadSavedAccounts() migrateHiddenAccountKeys()- refreshSimAccounts(app)+ // Reuse the caller's enumeration when it already fetched one (the+ // contact sync does); otherwise fetch it under the same per-source+ // timeout as the contact load (issue 926) — this telephony Binder+ // call used to be made three times per sync with no bound at all.+ val infos = simInfos ?: contactSourceLoader.load(+ sourceName = "sim-subscriptions",+ timeoutMillis = contactSourceTimeoutMillis,+ ) { SimContactsDataSource.getSimSubscriptionInfos(app) } ?: emptyList()+ refreshSimAccounts(infos) val restriction = NewContactAccountPolicy.resolve(defaultAccountSource) newContactRestrictionState.value = restriction // The cloud default is where new contacts now go, so offer it even when it holds // no contacts yet (it would otherwise be missing from every account picker). val cloud = restriction?.cloudAccount?.let { ContactAccount(it.name, it.type) }- sortAccountsIntoState((accountSet + savedAccounts + simAccountsOf(app) + listOfNotNull(cloud)).toList())+ sortAccountsIntoState((accountSet + savedAccounts + simAccountsOf(infos) + listOfNotNull(cloud)).toList()) } /**@@ -171,8 +181,10 @@ private suspend fun ContactViewModel.queryProviderAccounts( } // Virtual SIM accounts-private suspend fun ContactViewModel.refreshSimAccounts(app: Application) {- val simInfos = SimContactsDataSource.getSimSubscriptionInfos(app)+private fun ContactViewModel.refreshSimAccounts(+ simInfos: List<SimContactsDataSource.SimSubscriptionInfo>,+) {+ val app = getApplication<Application>() val simLabels = simInfos.associate { info -> val acc = ContactAccount(SimContactsDataSource.accountNameFor(info), SIM_ACCOUNT_TYPE) "${acc.type}|${acc.name}" to SimContactsDataSource.getSimAccountDisplayLabel(app, info)@@ -181,11 +193,10 @@ private suspend fun ContactViewModel.refreshSimAccounts(app: Application) { simSlotLabelsState.value = simSlotLabelsFor(simInfos) } -private fun simAccountsOf(app: Application): List<ContactAccount> {- val simInfos = SimContactsDataSource.getSimSubscriptionInfos(app)- return simInfos.map { info ->- ContactAccount(SimContactsDataSource.accountNameFor(info), SIM_ACCOUNT_TYPE)- }+private fun simAccountsOf(+ simInfos: List<SimContactsDataSource.SimSubscriptionInfo>,+): List<ContactAccount> = simInfos.map { info ->+ ContactAccount(SimContactsDataSource.accountNameFor(info), SIM_ACCOUNT_TYPE) } private fun ContactViewModel.sortAccountsIntoState(all: List<ContactAccount>) {
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.ktnew file mode 100644index 0000000000..72b4ea40af--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/util/ContactSourceLoaderTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.contacts.util++import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.data.ContactDetails+import com.vayunmathur.contacts.data.Name+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Issue 926 regression: one contact source must never wedge the whole+ * load. These drive [ContactSourceLoader] with fake source seams —+ * throwing, hanging (non-cancellable sleep, like a stuck Binder call+ * into the ICC provider) and healthy — and prove the other source+ * still publishes and the merged load always returns.+ */+@RunWith(RobolectricTestRunner::class)+class ContactSourceLoaderTest {++ private fun contact(id: Long, first: String) = Contact(+ id = id,+ accountType = null,+ accountName = null,+ isFavorite = false,+ details = ContactDetails.empty().copy(+ names = listOf(Name(0, "", first, "", "Lee", "")),+ ),+ )++ @Test+ fun throwingSimSourceLeavesDeviceContactsAndCompletes() = runBlocking {+ val loader = ContactSourceLoader()+ try {+ val device = listOf(contact(7, "Aisha"), contact(8, "Bob"))+ val published = mutableListOf<List<Contact>>()+ val merged = withTimeout(10_000) {+ loader.loadContacts(+ deviceLoader = { device },+ simLoader = { throw IllegalStateException("icc wedged") },+ timeoutMillis = 1_000,+ publish = { published.add(it) },+ )+ }+ assertEquals(device, merged)+ // Device contacts were published on their own before the merge.+ assertEquals(device, published.first())+ } finally {+ loader.close()+ }+ }++ @Test+ fun hangingSimSourceTimesOutAndDeviceContactsStillPublish() = runBlocking {+ val loader = ContactSourceLoader()+ try {+ val device = listOf(contact(7, "Aisha"))+ val published = mutableListOf<List<Contact>>()+ val started = System.nanoTime()+ val merged = withTimeout(10_000) {+ loader.loadContacts(+ deviceLoader = { device },+ // A stuck Binder query cannot be cancelled; sleep+ // simulates exactly that (delay() would cancel).+ simLoader = { Thread.sleep(5_000); listOf(contact(9, "Sim")) },+ timeoutMillis = 150,+ publish = { published.add(it) },+ )+ }+ val elapsedMillis = (System.nanoTime() - started) / 1_000_000+ assertEquals(device, merged)+ assertEquals(device, published.first())+ assertTrue(elapsedMillis < 4_000, "load took ${elapsedMillis}ms despite the timeout")+ } finally {+ loader.close()+ }+ }++ @Test+ fun hangingDeviceSourceLeavesSimContactsAndCompletes() = runBlocking {+ val loader = ContactSourceLoader()+ try {+ val sim = listOf(contact(-1, "Sim"))+ val merged = withTimeout(10_000) {+ loader.loadContacts(+ deviceLoader = { Thread.sleep(5_000); listOf(contact(7, "Aisha")) },+ simLoader = { sim },+ timeoutMillis = 150,+ )+ }+ assertEquals(sim, merged)+ } finally {+ loader.close()+ }+ }++ @Test+ fun healthySourcesMergeAndSlowSourceWithinTimeoutIsKept() = runBlocking {+ val loader = ContactSourceLoader()+ try {+ val device = listOf(contact(7, "Aisha"))+ val sim = listOf(contact(-1, "Sim"))+ val merged = loader.loadContacts(+ deviceLoader = { device },+ simLoader = { delay(50); sim },+ timeoutMillis = 2_000,+ )+ assertEquals(device + sim, merged)+ } finally {+ loader.close()+ }+ }++ @Test+ fun singleSourceLoadIsolatesThrowAndHang() = runBlocking {+ val loader = ContactSourceLoader()+ try {+ assertEquals("ok", loader.load("healthy", 1_000) { "ok" })+ assertNull(loader.load<String>("throwing", 1_000) {+ throw SecurityException("no sim permission")+ })+ assertNull(loader.load<String>("hanging", 150) {+ Thread.sleep(5_000)+ "never"+ })+ } finally {+ loader.close()+ }+ }+}
contacts/src/test/java/com/vayunmathur/contacts/util/SimSourceIsolation926Test.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/util/SimSourceIsolation926Test.kt b/contacts/src/test/java/com/vayunmathur/contacts/util/SimSourceIsolation926Test.ktnew file mode 100644index 0000000000..ba96def9cc--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/util/SimSourceIsolation926Test.kt@@ -0,0 +1,146 @@+package com.vayunmathur.contacts.util++import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.provider.ContactsContract+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.contacts.data.DefaultAccountSource+import com.vayunmathur.contacts.data.DefaultAccountSnapshot+import com.vayunmathur.contacts.data.FakeProviderPass2Test+import com.vayunmathur.contacts.data.ProviderAccount+import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE+import com.vayunmathur.contacts.data.SimProviderPass2Test+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Issue 926 (v2.6.11, LineageOS/Galaxy S10): the contacts app spun+ * forever on both tabs when the physical SIM appeared as a source.+ * The SIM ADN query and the device query were merged sequentially+ * before anything was published, so a throwing or never-answering+ * ICC provider blocked the device contacts and the loaded flag.+ *+ * These tests put a throwing, then a hanging, fake ICC provider+ * behind the real SIM source seam and prove the device contacts+ * still render and loading completes; a healthy SIM still merges.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class SimSourceIsolation926Test {+ private val app get() = ApplicationProvider.getApplicationContext<Application>()++ private class FakeSource : DefaultAccountSource {+ override fun defaultAccountForNewContacts(): DefaultAccountSnapshot? = null+ override fun customLocalAccount(): ProviderAccount? = null+ override fun providerSimAccounts(): List<ProviderAccount> = emptyList()+ }++ /** ICC provider whose every query throws, as on a wedged SIM stack. */+ class ThrowingIccProvider : ContentProvider() {+ override fun onCreate() = true+ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): Cursor = throw IllegalStateException("icc wedged")+ override fun insert(uri: Uri, values: ContentValues?): Uri =+ throw IllegalStateException("icc wedged")+ override fun update(+ uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+ ): Int = throw IllegalStateException("icc wedged")+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int =+ throw IllegalStateException("icc wedged")+ override fun getType(uri: Uri): String? = null+ }++ /** ICC provider whose query never answers within the test window. */+ class HangingIccProvider : ContentProvider() {+ override fun onCreate() = true+ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): Cursor {+ // Non-cancellable block, like a Binder call waiting on the+ // radio to load EF_ADN; coroutine cancellation cannot stop it.+ Thread.sleep(3_000)+ return MatrixCursor(arrayOf("name", "number", "emails", "_id"))+ }+ override fun insert(uri: Uri, values: ContentValues?): Uri =+ throw IllegalStateException("icc wedged")+ override fun update(+ uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+ ): Int = throw IllegalStateException("icc wedged")+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int =+ throw IllegalStateException("icc wedged")+ override fun getType(uri: Uri): String? = null+ }++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ ShadowContentResolver.registerProviderInternal(+ ContactsContract.AUTHORITY,+ FakeProviderPass2Test.FakeContactsProvider(),+ )+ }++ @AfterTest+ fun tearDown() {+ Dispatchers.resetMain()+ }++ private fun vm(timeoutMillis: Long = 500): ContactViewModel =+ ContactViewModel(app, FakeSource(), timeoutMillis)++ @Test+ fun throwingSimSourceStillRendersDeviceContactsAndCompletesLoading() {+ ShadowContentResolver.registerProviderInternal("icc", ThrowingIccProvider())+ val vm = vm()+ runBlocking { withTimeout(15_000) { vm.syncFromSystem() } }+ assertTrue(vm.hasLoadedContacts.value, "loading must terminate when the SIM source throws")+ // The fake device provider's two contacts survive a dead SIM source.+ assertEquals(setOf(7L, 8L), vm.allContactsState.value.map { it.id }.toSet())+ assertTrue(vm.allContactsState.value.none { it.accountType == SIM_ACCOUNT_TYPE })+ }++ @Test+ fun hangingSimSourceStillRendersDeviceContactsAndCompletesLoading() {+ ShadowContentResolver.registerProviderInternal("icc", HangingIccProvider())+ val vm = vm(timeoutMillis = 200)+ val started = System.nanoTime()+ runBlocking { withTimeout(15_000) { vm.syncFromSystem() } }+ val elapsedMillis = (System.nanoTime() - started) / 1_000_000+ assertTrue(vm.hasLoadedContacts.value, "loading must terminate when the SIM source hangs")+ assertEquals(setOf(7L, 8L), vm.allContactsState.value.map { it.id }.toSet())+ assertTrue(elapsedMillis < 10_000, "sync took ${elapsedMillis}ms despite the source timeout")+ }++ @Test+ fun healthySimSourceStillMergesIntoTheList() {+ ShadowContentResolver.registerProviderInternal("icc", SimProviderPass2Test.FakeIccProvider())+ val vm = vm()+ runBlocking { withTimeout(15_000) { vm.syncFromSystem() } }+ assertTrue(vm.hasLoadedContacts.value)+ val ids = vm.allContactsState.value.map { it.id }.toSet()+ assertTrue(7L in ids && 8L in ids, "device contacts missing: $ids")+ assertTrue(+ vm.allContactsState.value.any { it.accountType == SIM_ACCOUNT_TYPE },+ "healthy SIM contacts must still load",+ )+ }+}