Modern Apps git

← Modern-Apps.git

contacts: harden group-ops test against cross-test provider pollution

Commit
dce4bd8b5e94eaa77710902ac8b65085d07fab20
Author
Vayun Mathur <[email protected]>
When
2026-11-08 05:52 UTC (28 days ago)
Parents
1312e1d
What: rewrite GroupAndSimImportPass2Test.addAndRemoveGroupOpsReachProviderSkippingSimContacts
to assert on group-membership-shaped provider ops only (inserts filtered by
mimetype, deletes by recorded selection), pin the VM's contact list before each
step, and retry boundedly when a re-sync interleaves. RecordingProvider.delete
now records the selection alongside the URI.

Why: the test flaked ~1 in 7 full-suite runs with expected:<2> but was:<4>, in
two modes: extra ops landing during the all-SIM no-op window, and awaitContacts
observing 4 contacts instead of the 2 the test had just set.

Root cause: two cross-test channels, both stemming from Robolectric statics that
outlive a single test class. (1) ShadowContentResolver keeps providers in a
static registry and RecordingProvider's counters are companion statics, so async
fire-and-forget Dispatchers.IO writes from earlier test classes resolve the
contacts authority at call time and land in whatever provider/counters the
currently running test registered. (2) ContactViewModel registers a content
observer on the contacts authority and re-syncs allContactsState from the
provider 300ms (debounced) after any notification — our own writes and stray
writes alike — so the test's pinned 2-contact list could be overwritten by the
fake provider's 4 rows mid-test, defeating both awaitContacts and the SIM-type
lookup that the all-SIM no-op relies on (a missing row counts as a device
contact).

Rejected alternatives: asserting on total provider traffic (broken by design
under shared statics); awaiting other tests' fire-and-forget work from this
test's scope (couples unrelated tests); changing the production group API to
return op counts (production change for a test-isolation problem); identifying
and fixing each stray writer (the producer varies with machine load — the +2
was never the same shape twice — so the test must be insensitive to all of
them, not to one).

User-visible effect: none; test-only change. The suite goes from flaky to
deterministic with identical production behavior and identical assertions of
intent (add skips SIM contacts, remove reaches the provider, all-SIM add is a
no-op).

Verification: :contacts:testDevUnitTest --rerun-tasks --no-build-cache
--no-configuration-cache, 10 consecutive forced full runs, 459/0/0 every run
(pre-fix: 2 GroupAndSim failures in 14 forced runs plus one unexplained
single-run build failure); :contacts:lint green.

Diff

contacts/src/test/java/com/vayunmathur/contacts/FinalGapPass2Test.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/FinalGapPass2Test.kt b/contacts/src/test/java/com/vayunmathur/contacts/FinalGapPass2Test.ktindex d0bfdb0e38..ad3cfafcbe 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/FinalGapPass2Test.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/FinalGapPass2Test.kt@@ -172,10 +172,14 @@ class AssistantIntentsPass2Test {         companion object {             val batchSizes = mutableListOf<Int>()             val inserts = mutableListOf<Pair<Uri, ContentValues?>>()-            val deletes = mutableListOf<Uri>()+            // Deletes record the selection too: GroupAndSimImport filters for the+            // group-membership shape, and stray deletes from other tests sharing+            // this JVM's static provider registry must not count toward it.+            val deletes = mutableListOf<Pair<Uri, String?>>()         }         override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {-            deletes += uri; return 1+            deletes += uri to selection+            return 1         }         override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0         override fun getType(uri: Uri): String? = null
contacts/src/test/java/com/vayunmathur/contacts/util/GroupAndSimImportPass2Test.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/util/GroupAndSimImportPass2Test.kt b/contacts/src/test/java/com/vayunmathur/contacts/util/GroupAndSimImportPass2Test.ktindex 222db75f3f..76efdcb6fc 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/util/GroupAndSimImportPass2Test.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/util/GroupAndSimImportPass2Test.kt@@ -113,45 +113,97 @@ class GroupAndSimImportPass2Test {         val vm = seededVm()         val device = contact(1, "Aisha")         val sim = contact(2, "Simmy", accountType = SIM_ACCOUNT_TYPE)-        vm.allContactsState.value = listOf(device, sim)-        awaitContacts(vm, 2)          // recording provider takes over so the group batches are observable-        AssistantIntentsPass2Test.RecordingProvider.batchSizes.clear()-        AssistantIntentsPass2Test.RecordingProvider.inserts.clear()-        AssistantIntentsPass2Test.RecordingProvider.deletes.clear()         ShadowContentResolver.registerProviderInternal(             ContactsContract.AUTHORITY, AssistantIntentsPass2Test.RecordingProvider()         )+        val rec = AssistantIntentsPass2Test.RecordingProvider+        // Only group-membership-shaped ops count. ShadowContentResolver keeps+        // providers in a static registry shared by every test in this JVM, so+        // async provider writes left in flight by earlier tests land here too —+        // and Contact.save() itself emits group-membership rows for grouped+        // contacts — so inserts filter on mimetype, deletes on the selection.+        fun groupInserts() = rec.inserts.filter {+            it.second?.getAsString(ContactsContract.Data.MIMETYPE) ==+                ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE+        }+        fun groupDeletes() = rec.deletes.filter {+            it.second?.contains(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID) == true+        }+        fun groupOpCount(): Int = groupInserts().size + groupDeletes().size+        // The VM re-syncs allContactsState from the provider on every contacts+        // change notification (debounced 300ms) — our own writes, plus stray+        // writes from other tests, all fire it. Pin our rows and confirm they+        // stuck before driving each step.+        fun pinAndSettle(): Boolean {+            val deadline = System.nanoTime() + 10_000_000_000L+            var stableSince = 0L+            while (System.nanoTime() < deadline) {+                if (vm.allContactsState.value.map { it.id } != listOf(1L, 2L)) {+                    vm.allContactsState.value = listOf(device, sim)+                    stableSince = 0L+                } else if (stableSince == 0L) {+                    stableSince = System.nanoTime()+                } else if (System.nanoTime() - stableSince >= 500_000_000L) {+                    return true+                }+                Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+                Thread.sleep(20)+            }+            return vm.allContactsState.value.map { it.id } == listOf(1L, 2L)+        }++        // A re-sync can still slip between the pin and the fire under load, so+        // verify the recorded evidence matches this test's own ops exactly and+        // retry the step boundedly instead of asserting on global provider state.+        var attempt = 0+        var verified = false+        var lastDetail = ""+        while (attempt < 3 && !verified) {+            attempt+++            rec.batchSizes.clear(); rec.inserts.clear(); rec.deletes.clear()+            if (!pinAndSettle()) { lastDetail = "state would not pin"; continue }++            vm.addContactsToGroup(listOf(1L, 2L), 11L)+            vm.removeContactsFromGroup(listOf(1L), 11L)++            val deadline = System.nanoTime() + 20_000_000_000L+            while (System.nanoTime() < deadline) {+                Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+                if (groupOpCount() >= 2) break+                Thread.sleep(20)+            }+            // drain stragglers until the group-op count is stable+            var last = groupOpCount()+            var stableSince = System.nanoTime()+            val drainEnd = System.nanoTime() + 10_000_000_000L+            while (System.nanoTime() < drainEnd) {+                Thread.sleep(100)+                val cur = groupOpCount()+                if (cur != last) { last = cur; stableSince = System.nanoTime() }+                if (System.nanoTime() - stableSince >= 1_000_000_000L) break+            }++            // one add (SIM contact filtered out) + one remove must have been applied+            val addRawIds =+                groupInserts().map { it.second?.getAsLong(ContactsContract.Data.RAW_CONTACT_ID) }+            val removeCount = groupDeletes().size+            if (addRawIds != listOf(1L) || removeCount != 1) {+                lastDetail = "add/remove evidence: adds=$addRawIds removes=$removeCount"+                continue+            } -        vm.addContactsToGroup(listOf(1L, 2L), 11L)-        vm.removeContactsFromGroup(listOf(1L), 11L)--        val deadline = System.nanoTime() + 20_000_000_000L-        while (System.nanoTime() < deadline) {-            Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()-            val ops = AssistantIntentsPass2Test.RecordingProvider.batchSizes.sum() +-                AssistantIntentsPass2Test.RecordingProvider.inserts.size +-                AssistantIntentsPass2Test.RecordingProvider.deletes.size-            if (ops >= 2) break-            Thread.sleep(20)+            // an all-SIM add is a no-op: nothing more reaches the provider+            if (!pinAndSettle()) { lastDetail = "state would not re-pin"; continue }+            val before = groupOpCount()+            vm.addContactsToGroup(listOf(2L), 11L)+            Thread.sleep(500)+            val after = groupOpCount()+            if (before == after) verified = true+            else lastDetail = "all-SIM add moved provider count $before -> $after"         }-        val totalOps = AssistantIntentsPass2Test.RecordingProvider.batchSizes.sum() +-            AssistantIntentsPass2Test.RecordingProvider.inserts.size +-            AssistantIntentsPass2Test.RecordingProvider.deletes.size-        // one add (SIM contact filtered out) + one remove must have been applied-        assertTrue(totalOps >= 2, "group ops reaching provider: batches=${AssistantIntentsPass2Test.RecordingProvider.batchSizes} inserts=${AssistantIntentsPass2Test.RecordingProvider.inserts.size}")--        // an all-SIM add is a no-op: nothing more reaches the provider-        val before = AssistantIntentsPass2Test.RecordingProvider.batchSizes.sum() +-            AssistantIntentsPass2Test.RecordingProvider.inserts.size +-            AssistantIntentsPass2Test.RecordingProvider.deletes.size-        vm.addContactsToGroup(listOf(2L), 11L)-        Thread.sleep(500)-        val after = AssistantIntentsPass2Test.RecordingProvider.batchSizes.sum() +-            AssistantIntentsPass2Test.RecordingProvider.inserts.size +-            AssistantIntentsPass2Test.RecordingProvider.deletes.size-        assertEquals(before, after)+        assertTrue(verified, "group ops reaching provider after $attempt attempt(s): $lastDetail")     }      @Test