contacts: ancillary sync work can't hold the list on loading (#926)
- Commit
504d964007e3b6a72d4300d0007dbee9b7c0b2b4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-28 06:31 UTC (8 days ago)
- Parents
0c94f95
The reported device/SIM merge was already isolated (parallel load, 5s timeout, device-first publish), but the loading gate still waited for everything around it: one-time migrations (contacts-provider queries + applyBatch, calendar sync with a second full load) ran unbounded BEFORE the load, and the accounts query + default-account resolution (RawContacts, SimContacts.getSimAccounts) ran unbounded after it, the accounts query catching only three exception types so an OEM RuntimeException aborted the whole refresh. A hanging or throwing ancillary source therefore kept both tabs on the loading spinner forever (and source filtering couldn't help — the SIM work ran before any filter). Now hasLoaded flips immediately after loadContacts publishes, the migrations run after the load inside the same per-source timeout (abandoned on timeout, retried next sync since their flag stays unset), and both the provider-accounts query and default-account resolution go through contactSourceLoader with generic exception containment. SIM behaviours from #934-936 are untouched (SimContacts.kt unchanged). New SimSourceIsolation926Test: hanging SIM default-account query, throwing default-account query, and hanging RawContacts accounts query each still complete loading with device contacts. Verified: :contacts:testDevUnitTest 580/582 pass — the 2 failures (InsertOrEdit scaffold-search tests) fail identically with this change reverse-applied, pre-existing; :contacts:lint passes with no contacts findings.
Diff
contacts/AGENTS.md
diff --git a/contacts/AGENTS.md b/contacts/AGENTS.mdindex 0d250cc86f..398104e5df 100644--- a/contacts/AGENTS.md+++ b/contacts/AGENTS.md@@ -5,7 +5,7 @@ _Install: ./install contacts (dev by default)._ - Gradle: :contacts / dir: contacts/ - Package roots present: ui, data, intents, auth-- Entry files: MainActivity.kt (no Route.kt — list/detail/edit flow with dialogs + pick activities)+- Entry files: MainActivity.kt, Route.kt, Navigation.kt - Deps: (none — contacts provider + account framework only) - Metadata: metadata_data/contacts.md (present) - Rust: no / screenshotTest: yes@@ -19,6 +19,7 @@ _Install: ./install contacts (dev by default)._ **Architecture / data-flow:** `ui/` list/detail/edit pages (+ `ui/dialogs/`) → `util/ContactViewModel` (+ split `Accounts`/`Draft` helpers, `ContactsUiContract`) → `data/` models over the system contacts provider (`Contact`/`ContactGroup`, `ContactPrefill`, `SimContacts`); persistence is the provider, not Room — there is no database here. **Entry points + reading order:** `MainActivity.kt` → `ui/ContactListScreen.kt` → `ui/ContactDetailsPage.kt` → `ui/EditContactPage.kt` → `util/ContactViewModel.kt` → `data/Contact.kt`. **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 - `util/` is NOT a closed package root — don't add more files there - Write paths go through the contacts provider + account (`auth/`), not a local DB — account picker dialogs matter - `ImportActivity` + `ImportVcfScreen` handle VIEW intents; `ContactListPick`/`ContactItemPick` serve picker callers@@ -80,6 +81,9 @@ _Install: ./install contacts (dev by default)._ - com/vayunmathur/contacts/ui/dialogs/AddToGroupDialog.kt - com/vayunmathur/contacts/ui/dialogs/EventDatePickerDialog.kt - com/vayunmathur/contacts/ui/dialogs/EventDeleteConfirmDialog.kt+- com/vayunmathur/contacts/ui/dialogs/AddGroupDialog.kt+- com/vayunmathur/contacts/ui/dialogs/DeleteGroupDialog.kt+- com/vayunmathur/contacts/ui/dialogs/DeleteSelectedContactsDialog.kt ### intents/ — assistant IPC - com/vayunmathur/contacts/intents/GetIntent.kt - com/vayunmathur/contacts/intents/InsertIntent.kt
contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModel.ktindex 4dc6d53657..1b311148fb 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModel.kt@@ -433,8 +433,6 @@ class ContactViewModel internal constructor( private suspend fun refreshContactsFromSystem() { val app = getApplication<Application>()- migrateNoYearEventDates()- migrateBirthdayCalendarToUtc() // 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@@ -448,6 +446,23 @@ class ContactViewModel internal constructor( timeoutMillis = contactSourceTimeoutMillis, publish = { allContactsState.value = it }, )+ // Loading resolves as soon as the contacts themselves land. The+ // one-time migrations and the account refresh below are ancillary:+ // they query the same providers (and the calendar provider), so a+ // wedged one must not hold the loaded flag — and with it both+ // tabs' loading state — hostage after the list has published.+ _hasLoadedContacts.value = true+ // Best-effort one-time migrations, isolated like every other+ // provider call: a hanging migration is abandoned (its DataStore+ // flag stays unset, so a later sync retries it) instead of+ // blocking the load it used to precede.+ contactSourceLoader.load(+ sourceName = "contact-migrations",+ timeoutMillis = contactSourceTimeoutMillis,+ ) {+ migrateNoYearEventDates()+ migrateBirthdayCalendarToUtc()+ } // 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
contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelAccounts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelAccounts.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelAccounts.ktindex a6a0bc3ebc..b779b09ff5 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelAccounts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelAccounts.kt@@ -10,6 +10,7 @@ import com.vayunmathur.contacts.R import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.data.LOCAL_ACCOUNT_TYPE import com.vayunmathur.contacts.data.NewContactAccountPolicy+import com.vayunmathur.contacts.data.NewContactRestriction import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isDefaultLocalAccount@@ -88,7 +89,15 @@ internal suspend fun ContactViewModel.loadAccountsInternal( simInfos: List<SimContactsDataSource.SimSubscriptionInfo>? = null, ) { val app = getApplication<Application>()- val accountSet = queryProviderAccounts(app)+ // The provider-accounts query is the same contacts-provider Binder+ // call as the contact load, so it gets the same isolation (issue+ // 926): a throwing or never-answering provider reads as "no provider+ // accounts" instead of aborting — or wedging — the account refresh+ // that the contact sync's loading state used to wait on.+ val accountSet = contactSourceLoader.load(+ sourceName = "provider-accounts",+ timeoutMillis = contactSourceTimeoutMillis,+ ) { queryProviderAccounts(app) } ?: mutableSetOf() migrateLegacyAccounts() val savedAccounts = loadSavedAccounts() migrateHiddenAccountKeys()@@ -101,7 +110,14 @@ internal suspend fun ContactViewModel.loadAccountsInternal( timeoutMillis = contactSourceTimeoutMillis, ) { SimContactsDataSource.getSimSubscriptionInfos(app) } ?: emptyList() refreshSimAccounts(infos)- val restriction = NewContactAccountPolicy.resolve(defaultAccountSource)+ // The default-account facts are provider/SIM queries too (including+ // SimContacts.getSimAccounts on Android 16+): isolate them the same+ // way, so a wedged query reads as "no restriction" instead of+ // aborting the accounts list after the contacts have published.+ val restriction: NewContactRestriction? = contactSourceLoader.load(+ sourceName = "default-account",+ timeoutMillis = contactSourceTimeoutMillis,+ ) { 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).@@ -147,6 +163,10 @@ internal fun ContactViewModel.newContactDefaultAccount(): ContactAccount { return ContactAccount(restriction.cloudAccount.name, restriction.cloudAccount.type) } +// Broad catch is deliberate: OEM contacts providers throw undocumented+// RuntimeExceptions beyond SQLException/SecurityException, and a failed+// accounts query must read as "no provider accounts" (issue 926).+@Suppress("TooGenericExceptionCaught") private suspend fun ContactViewModel.queryProviderAccounts( app: Application, ): MutableSet<ContactAccount> {@@ -171,11 +191,7 @@ private suspend fun ContactViewModel.queryProviderAccounts( accountSet.add(ContactAccount(name, type)) } }- } catch (e: android.database.SQLException) {- Log.error("ContactViewModel", "Error querying raw contacts for accounts", e)- } catch (e: SecurityException) {- Log.error("ContactViewModel", "Error querying raw contacts for accounts", e)- } catch (e: IllegalArgumentException) {+ } catch (e: Exception) { Log.error("ContactViewModel", "Error querying raw contacts for accounts", e) } return accountSet
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.ktindex de0ea2535b..3d52aa2f65 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/util/SimSourceIsolation926Test.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/util/SimSourceIsolation926Test.kt@@ -9,10 +9,12 @@ import android.database.MatrixCursor import android.net.Uri import android.provider.ContactsContract import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.contacts.data.DefaultAccountKind 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.platform.ContactAccount import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.data.SimProviderPass2Test import kotlinx.coroutines.Dispatchers@@ -52,6 +54,52 @@ class SimSourceIsolation926Test { override fun providerSimAccounts(): List<ProviderAccount> = emptyList() } + /** Cloud default whose SIM-accounts query never answers (stuck Binder call). */+ private class HangingSimAccountsSource : DefaultAccountSource {+ override fun defaultAccountForNewContacts(): DefaultAccountSnapshot =+ DefaultAccountSnapshot(DefaultAccountKind.CLOUD, ProviderAccount("cloud@x", "com.cloud"))+ override fun customLocalAccount(): ProviderAccount? = null+ override fun providerSimAccounts(): List<ProviderAccount> {+ Thread.sleep(5_000)+ return emptyList()+ }+ }++ /** Cloud default whose SIM-accounts query throws an undocumented RuntimeException. */+ private class ThrowingSimAccountsSource : DefaultAccountSource {+ override fun defaultAccountForNewContacts(): DefaultAccountSnapshot =+ DefaultAccountSnapshot(DefaultAccountKind.CLOUD, ProviderAccount("cloud@x", "com.cloud"))+ override fun customLocalAccount(): ProviderAccount? = null+ override fun providerSimAccounts(): List<ProviderAccount> =+ throw IllegalStateException("sim accounts wedged")+ }++ /**+ * Contacts provider that delegates to the healthy fake except for the+ * two-column RawContacts accounts query, which never answers.+ */+ class HangingAccountsProvider : ContentProvider() {+ private val delegate = FakeProviderPass2Test.FakeContactsProvider()+ override fun onCreate() = true+ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): Cursor {+ if (uri.toString().contains("raw_contacts") && projection?.size == 2) {+ Thread.sleep(5_000)+ }+ return delegate.query(uri, projection, selection, selectionArgs, sortOrder)+ }+ override fun insert(uri: Uri, values: ContentValues?): Uri =+ delegate.insert(uri, values)+ override fun update(+ uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+ ): Int = delegate.update(uri, values, selection, selectionArgs)+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int =+ delegate.delete(uri, selection, selectionArgs)+ override fun getType(uri: Uri): String? = null+ }+ /** ICC provider whose every query throws, as on a wedged SIM stack. */ class ThrowingIccProvider : ContentProvider() { override fun onCreate() = true@@ -131,6 +179,50 @@ class SimSourceIsolation926Test { assertTrue(elapsedMillis < 10_000, "sync took ${elapsedMillis}ms despite the source timeout") } + @Test+ fun hangingDefaultAccountQueryStillCompletesLoadingAndKeepsAccounts() {+ ShadowContentResolver.registerProviderInternal("icc", ThrowingIccProvider())+ val vm = ContactViewModel(app, HangingSimAccountsSource(), 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 default-account query hangs")+ assertEquals(setOf(7L, 8L), vm.allContactsState.value.map { it.id }.toSet())+ assertTrue(+ ContactAccount("[email protected]", "com.google") in vm.accountsState.value,+ "provider accounts must survive a wedged default-account query: ${vm.accountsState.value}",+ )+ assertTrue(elapsedMillis < 4_000, "sync took ${elapsedMillis}ms despite the source timeout")+ }++ @Test+ fun throwingDefaultAccountQueryDoesNotAbortAccountLoad() {+ ShadowContentResolver.registerProviderInternal("icc", ThrowingIccProvider())+ val vm = ContactViewModel(app, ThrowingSimAccountsSource(), 500)+ runBlocking { withTimeout(15_000) { vm.syncFromSystem() } }+ assertTrue(vm.hasLoadedContacts.value)+ assertEquals(setOf(7L, 8L), vm.allContactsState.value.map { it.id }.toSet())+ assertTrue(+ ContactAccount("[email protected]", "com.google") in vm.accountsState.value,+ "accounts must still load when the default-account query throws: ${vm.accountsState.value}",+ )+ }++ @Test+ fun hangingProviderAccountsQueryStillCompletesLoading() {+ ShadowContentResolver.registerProviderInternal(+ ContactsContract.AUTHORITY, HangingAccountsProvider(),+ )+ ShadowContentResolver.registerProviderInternal("icc", ThrowingIccProvider())+ 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 accounts query hangs")+ assertEquals(setOf(7L, 8L), vm.allContactsState.value.map { it.id }.toSet())+ assertTrue(elapsedMillis < 4_000, "sync took ${elapsedMillis}ms despite the source timeout")+ }+ @Test fun healthySimSourceStillMergesIntoTheList() { ShadowContentResolver.registerProviderInternal("icc", SimProviderPass2Test.FakeIccProvider())