emergency: dead contacts are pruned from storage on load
- Commit
9901081d272b6c8d92dfae24596e7989ecc880cb- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 22:10 UTC (5 days ago)
- Parents
9146042
Deleting an emergency contact from the address book left its URI in storage forever: load() emptied the in-memory list but resolveAndPrune compared the already-filtered list against a re-read of itself, so the persist branch was dead code and the dead URI was re-queried (and re-failed) on every load. load() now captures the URIs exactly as persisted and compares against that. Crucially, pruning only persists on definitive deletions: reads produce a tri-state (Found/Deleted/Unknown) and readAllForPrune returns null if any URI was unreadable, so a transient permission/provider failure can never permanently erase live contacts — the naive fix would have been worse. Regression tests cover both branches. The 2 test failures and 2 lint errors are pre-existing scaffold-migration/screenshot fallout in untouched files. Verified: :emergency:testDevUnitTest 88/90 pass with only those pre-existing failures; zero lint findings in changed files.
Diff
emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.ktindex 9a87f23f76..a8dd72633e 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt@@ -42,8 +42,9 @@ class EmergencyRepository private constructor( val info: StateFlow<EmergencyInfo> = mutable.asStateFlow() suspend fun load() = withContext(Dispatchers.IO) {- val info = readStored()- val resolved = if (isUnlocked()) resolveAndPrune(info) else info+ val storedUris = storedContactUris()+ val info = readStored(storedUris)+ val resolved = if (isUnlocked()) resolveAndPrune(info, storedUris) else info mutable.value = resolved } @@ -94,7 +95,8 @@ class EmergencyRepository private constructor( updateSuggestionState() } - private fun readStored(): EmergencyInfo {+ /** The stored contact URIs exactly as persisted, before any resolution. */+ private fun storedContactUris(): List<Uri> { // Legacy guard (b/28194605): contacts were once a string set; a ClassCastException // means the stored value predates the `|` format and is ignored. val serialized = runCatching { prefs.getString(EmergencyKeys.CONTACTS, "") }@@ -102,7 +104,10 @@ class EmergencyRepository private constructor( Log.status(TAG, "ignoring legacy contact storage", it) "" }.orEmpty()- val uris = parseContactUris(serialized)+ return parseContactUris(serialized)+ }++ private fun readStored(uris: List<Uri>): EmergencyInfo { // Pre-unlock the contacts cannot be resolved; carry the URIs with blank snapshots. val contacts = if (isUnlocked()) { contacts.readAll(uris)@@ -122,11 +127,16 @@ class EmergencyRepository private constructor( /** * Re-validates stored URIs, dropping contacts deleted from the address book and * re-persisting when anything was pruned - GrapheneOS's `deserializeAndFilter`.+ *+ * The comparison runs against the URIs exactly as persisted ([storedUris]),+ * not against [info]'s contacts: [readStored] has already resolved (and+ * dropped dead URIs from) that list, so comparing against it could never+ * observe a prune and the stored list was never cleaned. An inconclusive+ * read (see [ContactReader.readAllForPrune]) leaves storage untouched. */- private fun resolveAndPrune(info: EmergencyInfo): EmergencyInfo {- val uris = info.contacts.map { it.phoneUri }- val resolved = contacts.readAll(uris)- if (resolved.size != uris.size) {+ private fun resolveAndPrune(info: EmergencyInfo, storedUris: List<Uri>): EmergencyInfo {+ val resolved = contacts.readAllForPrune(storedUris) ?: return info+ if (resolved.map { it.phoneUri } != storedUris) { persistUris(resolved.map { it.phoneUri }) return info.copy(contacts = resolved) }
emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.ktindex f4d48b4ddc..52b3350902 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt@@ -27,7 +27,45 @@ class ContactReader( ) { /** Reads one contact, or null when the URI no longer resolves or access is denied. */- fun read(phoneUri: Uri): EmergencyContact? {+ fun read(phoneUri: Uri): EmergencyContact? =+ (readOutcome(phoneUri) as? ReadOutcome.Found)?.contact++ /** Reads all URIs, silently dropping ones that no longer resolve. */+ fun readAll(uris: List<Uri>): List<EmergencyContact> = uris.mapNotNull { read(it) }++ /**+ * Reads all URIs for a persistence decision (pruning), or null when any+ * URI could not be read at all (query threw or returned no cursor - a+ * permission/provider failure, not a deletion). Callers must not persist+ * a pruned list from an inconclusive read: a transient failure would+ * permanently erase contacts that still exist. A URI whose query+ * succeeds but returns no usable row is definitively gone and is dropped.+ */+ fun readAllForPrune(uris: List<Uri>): List<EmergencyContact>? {+ val resolved = ArrayList<EmergencyContact>(uris.size)+ for (uri in uris) {+ when (val outcome = readOutcome(uri)) {+ is ReadOutcome.Found -> resolved += outcome.contact+ ReadOutcome.Deleted -> Unit // definitively gone; drop it+ ReadOutcome.Unknown -> return null+ }+ }+ return resolved+ }++ /** Outcome of one contact read: found, definitively gone, or unreadable. */+ private sealed interface ReadOutcome {+ /** The URI resolved to a displayable contact. */+ class Found(val contact: EmergencyContact) : ReadOutcome++ /** The query succeeded but the row (or its number) is gone. */+ data object Deleted : ReadOutcome++ /** The query itself failed; nothing is known about the contact. */+ data object Unknown : ReadOutcome+ }++ private fun readOutcome(phoneUri: Uri): ReadOutcome { val cursor = runCatching { resolver.query( phoneUri,@@ -42,24 +80,21 @@ class ContactReader( ) }.getOrElse { Log.status(TAG, "unable to read contact $phoneUri", it)- return null- } ?: return null+ return ReadOutcome.Unknown+ } ?: return ReadOutcome.Unknown cursor.use {- if (!it.moveToNext()) return null+ if (!it.moveToNext()) return ReadOutcome.Deleted val name = it.getString(0).orEmpty() val number = it.getString(1).orEmpty()- if (number.isBlank()) return null+ if (number.isBlank()) return ReadOutcome.Deleted val type = ContactsContract.CommonDataKinds.Phone.getTypeLabel( resources, it.getInt(2), it.getString(3), ).toString() val photo = readPhoto(it.getLong(4))- return EmergencyContact(phoneUri, name, number, type, photo)+ return ReadOutcome.Found(EmergencyContact(phoneUri, name, number, type, photo)) } } - /** Reads all URIs, silently dropping ones that no longer resolve. */- fun readAll(uris: List<Uri>): List<EmergencyContact> = uris.mapNotNull { read(it) }- /** True when [phoneUri] is non-null and still resolves to a number. */ fun isValid(phoneUri: Uri?): Boolean { if (phoneUri == null) return false
emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.ktindex 7ec2721462..e518b769ad 100644--- a/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt@@ -1,5 +1,7 @@ package com.vayunmathur.emergency.platform +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.app.Application import android.content.Context import android.content.Intent@@ -96,6 +98,56 @@ class RepositoryTest { assertTrue(repo.info.value.contacts.isEmpty()) Unit }++ // The repository singleton keeps the prefs it was created with; read that+ // exact store (a fresh Context here is a different Robolectric storage).+ private fun storedContacts(): String {+ val field = EmergencyRepository::class.java.getDeclaredField("prefs")+ field.isAccessible = true+ val prefs = field.get(EmergencyRepository.get(ctx)) as android.content.SharedPreferences+ return prefs.getString(+ com.vayunmathur.emergency.data.EmergencyKeys.CONTACTS, "",+ ).orEmpty()+ }++ @Test+ fun `repository removes dead contacts from storage on load`() = runBlocking {+ val repo = EmergencyRepository.get(ctx)+ repo.info.value.contacts.toList().forEach { repo.removeContact(it.phoneUri) }+ assertTrue(repo.addContact(phoneUri))+ assertTrue(storedContacts().contains(phoneUri.toString()))++ // The contact is deleted from the address book: load must drop it from+ // the stored list too, not just from the in-memory snapshot, so the+ // dead URI is not re-read (and re-failed) on every later load.+ FakeContactsProvider.phones.remove(phoneUri.toString())+ repo.load()+ assertTrue(repo.info.value.contacts.isEmpty())+ assertFalse(storedContacts().contains(phoneUri.toString()))+ assertEquals("", storedContacts())+ Unit+ }++ @Test+ fun `repository keeps stored contacts when a load cannot resolve them`() = runBlocking {+ val repo = EmergencyRepository.get(ctx)+ repo.info.value.contacts.toList().forEach { repo.removeContact(it.phoneUri) }+ assertTrue(repo.addContact(phoneUri))+ assertTrue(storedContacts().contains(phoneUri.toString()))++ // A read failure (permission revoked, provider unavailable) is not a+ // deletion: the stored URI must survive the failed load and resolve+ // again once reads work, or a transient failure would permanently+ // erase the user's emergency contacts.+ FakeContactsProvider.failUris += phoneUri.toString()+ repo.load()+ assertTrue(storedContacts().contains(phoneUri.toString()))++ FakeContactsProvider.failUris -= phoneUri.toString()+ repo.load()+ assertEquals(listOf(phoneUri), repo.info.value.contacts.map { it.phoneUri })+ Unit+ } } @RunWith(RobolectricTestRunner::class)