contacts: remove old SIM row when an edit insert duplicates it (#936)
- Commit
36d6eae9cf4d6aaee22eb6dd34c339e456c871e7- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 18:23 UTC (1 day ago)
- Parents
4f9ebf2
Editing a physical SIM contact could leave the old row in place with the edited copy beside it, so the contact appeared twice with the new data not replacing the old. Root cause: a SIM edit is an update-by-search - the provider finds the row by its whole old record and replaces it, and the app treated a reported success as proof of replacement. When the search misses on a field the provider compares but does not expose to queries (for example an ANR on a card whose ADN cursor has no anrs column, so the app reads the row without it), the legacy provider reports failure, but the Android 16 modem phonebook cache inserts the new record instead and still reports success. The row count cannot distinguish "replaced" from "inserted alongside", and nothing re-checked, so the duplicate survived. An earlier change already made the update carry the full visible old record and made the delete-then-insert fallback conditional on the delete succeeding; this closes the remaining reported-success case. Fix: after a successful in-place update, the SIM save path re-reads the ADN rows for that subscription. If both the pre-edit row and the edited row are present, it deletes the pre-edit row by its full record; if that delete fails the save reports failure instead of leaving a duplicate (and does not fall through to another insert). A re-read showing only the old row is the known stale provider cache and is left alone, and a matched replace is untouched. Deliberately narrow: SimContacts.kt (the delimited-field normalisation and delete-selection work for the neighbouring SIM issues) is not modified, so this merges independently. Tests: new SimInsertOnMissEditTest runs the ViewModel SIM save path against a fake ICC provider that reproduces the Android 16 insert-on-miss update and hides ANRs from its cursor. Editing an emailed/ANR contact now leaves exactly the edited row (this test fails without the fix), and a provider-matched edit still replaces in place. Verification: ./gradlew :contacts:lint :contacts:lintVitalRelease green; new tests plus all SIM test classes green; full :contacts:testDevUnitTest run has only the two pre-existing InsertOrEdit number-display failures, reproduced identically on a clean tree at the same base without this change.
Diff
contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.ktindex 4579cfd8f4..0adc6f3b13 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt@@ -96,6 +96,15 @@ internal suspend fun ContactViewModel.updateExistingSimContact( if (canEditInPlace) { val updated = SimContactsDataSource.updateSimContact(app, oldSc, name, number, email, subId) if (updated) {+ // A provider whose update-by-search misses can still report+ // success: on Android 16 the modem phonebook cache inserts the+ // new record instead of replacing the old one (#936). The row+ // count cannot tell "replaced" from "inserted alongside", so+ // re-read and remove the old row when both are now present.+ if (!removeOldSimRowLeftByInsertingUpdate(app, oldSc, name, number, email)) {+ Log.error("ContactViewModel", "SIM edit aborted: could not remove the duplicated old SIM row")+ return false+ } syncFromSystem() scheduleSimConvergenceSync() return true@@ -113,6 +122,36 @@ internal suspend fun ContactViewModel.updateExistingSimContact( return null } +/**+ * Removes the pre-edit row when a provider update inserted the edited row+ * alongside it instead of replacing it (#936). The old-record search can+ * miss on a field the provider compares but does not expose to queries+ * (an ANR on a card whose ADN cursor has no `anrs` column is one), and an+ * inserting provider reports that miss as success, so the update's result+ * alone cannot be trusted. Only the both-rows-present case is acted on: a+ * re-read that still shows just the old row is the known stale-cache read+ * (see [scheduleSimConvergenceSync]) and must not delete the only copy.+ * Returns false only when both rows are present and the old one cannot be+ * removed; the caller then fails the save rather than leaving a duplicate.+ */+private fun ContactViewModel.removeOldSimRowLeftByInsertingUpdate(+ app: Application,+ oldSc: com.vayunmathur.contacts.data.SimContact,+ name: String,+ number: String,+ email: String?,+): Boolean {+ val rows = SimContactsDataSource.listSimContacts(app)+ .filter { it.subscriptionId == oldSc.subscriptionId }+ fun matches(row: com.vayunmathur.contacts.data.SimContact, n: String, num: String, mail: String?): Boolean =+ row.name == n && row.number == num && row.emails.orEmpty() == mail.orEmpty()+ val oldRow = rows.firstOrNull { matches(it, oldSc.name, oldSc.number, oldSc.emails) } ?: return true+ val newPresent = rows.any { matches(it, name, number, email) }+ val edited = oldSc.name != name || oldSc.number != number || oldSc.emails.orEmpty() != email.orEmpty()+ if (!newPresent || !edited) return true+ return SimContactsDataSource.deleteSimContact(app, oldRow)+}+ /** * Re-reads the SIM list once the ADN provider's read cache has had time to * converge on our write. Intermittently the immediate post-write
contacts/src/test/java/com/vayunmathur/contacts/data/SimInsertOnMissEditTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/data/SimInsertOnMissEditTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/data/SimInsertOnMissEditTest.ktnew file mode 100644index 0000000000..8096b37216--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/data/SimInsertOnMissEditTest.kt@@ -0,0 +1,199 @@+package com.vayunmathur.contacts.data++import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import androidx.core.net.toUri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.contacts.platform.ContactViewModel+import com.vayunmathur.contacts.platform.persistSimContact+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+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 #936 against a fake ICC provider modelling the Android 16 modem+ * phonebook behaviour the legacy cache did not have: update-by-search that+ * misses *inserts* the new record and still reports success, so the app+ * cannot tell "replaced" from "inserted alongside the old row" by the+ * update result. The modelled miss is a stored ANR the provider compares+ * but does not expose: its ADN cursor has no `anrs` column, so the app+ * reads the row without the ANR and its old record can never match.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class SimInsertOnMissEditTest {++ data class Row(+ val name: String,+ val number: String,+ val emails: List<String> = emptyList(),+ val anrs: List<String> = emptyList(),+ )++ class InsertOnMissIccProvider : ContentProvider() {+ override fun onCreate(): Boolean = true++ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): Cursor {+ // No "anrs" column: this provider never exposes ANRs to queries.+ val cursor = MatrixCursor(arrayOf("name", "number", "emails", "_id"))+ rows.forEachIndexed { index, row ->+ cursor.addRow(+ arrayOf<Any?>(+ row.name,+ row.number,+ row.emails.takeIf { it.isNotEmpty() }+ ?.joinToString("") { "$it," },+ index.toLong(),+ )+ )+ }+ return cursor+ }++ override fun insert(uri: Uri, values: ContentValues?): Uri {+ rows += values.toRow(newKeys = false)+ return "content://icc/adn/0".toUri()+ }++ override fun update(+ uri: Uri, values: ContentValues?, selection: String?,+ selectionArgs: Array<out String>?,+ ): Int {+ val index = rows.indexOf(values.toRow(newKeys = false))+ if (index == -1) {+ // Android 16 phonebook cache: an unmatched update inserts.+ rows += values.toRow(newKeys = true)+ } else {+ rows[index] = values.toRow(newKeys = true)+ }+ return 1+ }++ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {+ var name: String? = null+ var number: String? = null+ var emails: List<String>? = null+ selection.orEmpty().split(" AND ").forEach { param ->+ val pair = param.split("=", limit = 2)+ if (pair.size != 2) return@forEach+ val value = pair[1].trim().removeSurrounding("'")+ when (pair[0].trim()) {+ "tag", "name" -> name = value+ "number" -> number = value+ "emails" -> emails = split(value, ',')+ }+ }+ val index = rows.indexOfFirst { row ->+ (name == null || row.name == name) &&+ (number == null || row.number == number) &&+ (emails == null || row.emails == emails)+ }+ if (index == -1) return 0+ rows.removeAt(index)+ return 1+ }++ override fun getType(uri: Uri): String? = null++ companion object {+ val rows = mutableListOf<Row>()++ fun split(raw: String?, separator: Char): List<String> =+ raw?.split(separator)?.map { it.trim() }?.filter { it.isNotEmpty() }.orEmpty()++ fun reset(seed: List<Row>) {+ rows.clear()+ rows += seed+ }+ }+ }++ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()+ private val app get() = ApplicationProvider.getApplicationContext<Application>()++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ ShadowContentResolver.registerProviderInternal("icc", InsertOnMissIccProvider())+ InsertOnMissIccProvider.reset(+ listOf(Row("Aisha Rahman", "+14155550102", listOf("[email protected]"), listOf("+999")))+ )+ }++ @AfterTest+ fun tearDown() {+ Dispatchers.resetMain()+ }++ @Test+ fun editingASimContactWhoseOldRecordMissesLeavesOnlyTheEditedRow() {+ val vm = ContactViewModel(app)+ runBlocking { vm.syncFromSystem() }+ val projected = SimContactsDataSource.simContactsAsContacts(ctx).single()+ val edited = projected.copy(+ details = projected.details.copy(+ names = listOf(Name(0, "", "Aisha", "", "Khan", "")),+ phoneNumbers = listOf(PhoneNumber(0, "+222", CDKPhone.TYPE_MOBILE)),+ emails = listOf(Email(0, "[email protected]", CDKEmail.TYPE_HOME)),+ )+ )+ assertTrue(runBlocking { vm.persistSimContact(edited) })+ // The provider inserted the edit alongside the old row; the save+ // must have removed the old row instead of duplicating the contact.+ assertEquals(+ listOf(Row("Aisha Khan", "+222", listOf("[email protected]"))),+ InsertOnMissIccProvider.rows.toList(),+ )+ assertEquals(1, SimContactsDataSource.listSimContacts(ctx).size)+ }++ @Test+ fun editingASimContactTheProviderMatchesStillReplacesIt() {+ InsertOnMissIccProvider.reset(listOf(Row("Bob", "+111")))+ val vm = ContactViewModel(app)+ runBlocking { vm.syncFromSystem() }+ val projected = SimContactsDataSource.simContactsAsContacts(ctx).single()+ val edited = projected.copy(+ details = projected.details.copy(+ phoneNumbers = listOf(PhoneNumber(0, "+222", CDKPhone.TYPE_MOBILE)),+ )+ )+ assertTrue(runBlocking { vm.persistSimContact(edited) })+ assertEquals(+ listOf(Row("Bob", "+222")),+ InsertOnMissIccProvider.rows.toList(),+ )+ }+}++private fun ContentValues?.toRow(newKeys: Boolean): SimInsertOnMissEditTest.Row {+ fun key(new: String, old: String) = if (newKeys) new else old+ return SimInsertOnMissEditTest.Row(+ name = this?.getAsString(key("newTag", "tag")).orEmpty(),+ number = this?.getAsString(key("newNumber", "number")).orEmpty(),+ emails = SimInsertOnMissEditTest.InsertOnMissIccProvider.split(+ this?.getAsString(key("newEmails", "emails")), ','+ ),+ anrs = SimInsertOnMissEditTest.InsertOnMissIccProvider.split(+ this?.getAsString(key("newAnrs", "anrs")), ':'+ ),+ )+}