email: defer database build out of startup construction (#939)
- Commit
dabe7d651a4de4fbeb8604fdd81fd88024798334- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 18:12 UTC (1 day ago)
- Parents
7e2c429
The reported crash (Add Account gate visible for a second, then the app exits on every launch, Android 15, months-long) was traced to database construction throwing synchronously during startup. Most startup paths were already guarded for collection-time failures (StartupGuard isolation, the accounts flow catch, guarded backfills and IDLE start), but construction itself still threw: EmailRepository handed the RoomRepository lazy database to its four stores in its constructor, so merely obtaining the singleton resolved the SQLCipher passphrase (AndroidKeyStore-backed decryption in the shared Room layer). EmailViewModel then resolved DAOs eagerly in property initializers (draftsActions and the accounts/outbox/drafts/ blockedSenders flow sources). On a device whose AndroidKeyStore key has been invalidated by an OS upgrade, lock-screen change or data restore, passphrase decryption throws before any flow catch exists, escaping viewModel() inside composition and killing the process before the Add Account gate can stay up. Fix, at the cause: constructing the repository and the ViewModel no longer builds the database. The four repository stores become lazy delegates (first actual use still builds, unchanged), draftsActions is lazy, and the eagerly created DAO flows are acquired through a guard that logs and falls back to an empty flow when construction throws; outbox/drafts/blockedSenders also gain the same collection-time catch accounts already had (and report loaded, so their screens do not spin forever). Cancellation is always rethrown. No library/room change: recovery of an invalidated key remains a separate decision, unchanged by this commit. User-visible effect: on an affected device the app now stays open at the Add Account gate instead of exiting on launch. New regression test EmailViewModelStartupTest poisons the stored passphrase (GCM tampering via FakeAndroidKeyStore) so the next database build throws AEADBadTagException, then asserts the repository and ViewModel construct and all gate flows degrade to empty. It fails on the pre-fix code with that exact exception. Verified in the worktree: ./gradlew :email:lint :email:lintVitalRelease :email:testDevUnitTest green (601 tests). One transient failure in EmailViewModelNetworkTest during the first full run (ConcurrentModificationException iterating the fake IMAP server's unsynchronized received-commands list) is unrelated to this change: it passes standalone and in the full-suite re-run.
Diff
email/AGENTS.md
diff --git a/email/AGENTS.md b/email/AGENTS.mdindex 2b798f749b..a16826eb17 100644--- a/email/AGENTS.md+++ b/email/AGENTS.md@@ -23,7 +23,7 @@ _Install: ./install email (dev by default)._ - `NetworkClient.init(this, TrustBundle.SYSTEM)` must stay first in `onCreateBeforeContent` — mail servers need system CAs, not the first-party bundle - `DateMillisBackfill`/`PeekContentBackfill` are one-time migrations gated on `runIfNeeded`; skipping them breaks sort order and snippet previews - IDLE push is foreground-gated via `AppLifecycleTracker` — background delivery goes through the hourly worker + notifications, not the socket-- Startup background work never crashes the first screen: every `MainActivity.onCreateBeforeContent` step runs in isolation via `platform/StartupGuard` (catches `Throwable`, rethrows only cancellation), the backfills and IDLE start guard their own database access, and `EmailViewModel.accounts` degrades to an empty list (the Add Account gate) when the database will not open on the device+- Startup never crashes the first screen: constructing `EmailRepository` and `EmailViewModel` never builds the database (stores and `draftsActions` are lazy, DAO flows are acquired via a guard that falls back to an empty flow), `MainActivity.onCreateBeforeContent` steps run in isolation via `platform/StartupGuard` (catches `Throwable`, rethrows only cancellation), the backfills and IDLE start guard their own database access, and `EmailViewModel.accounts` degrades to an empty list (the Add Account gate) when the database will not build or open on the device - `network/imap/TrustAll.kt` exists for debug only; never widen its use - Upgrades from app versions before v2.6.0 start with a fresh local database (supported upgrade floor: Email DB v17; DB versions 1–16 open destructively, v17 onward migrates normally)
email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt b/email/src/main/java/com/vayunmathur/email/data/EmailRepository.ktindex 7997d1b7be..43d485ea5e 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt@@ -13,10 +13,17 @@ import com.vayunmathur.library.room.RoomRepository class EmailRepository private constructor(context: Context) : RoomRepository<EmailDatabase>(context, EmailDatabase::class, "email-db") { - val accounts: EmailAccountStore = EmailAccountStore(db)- val messages: EmailMessageStore = EmailMessageStore(db)- val queries: EmailQueryStore = EmailQueryStore(db)- val outbox: EmailOutboxStore = EmailOutboxStore(db)+ // Lazy: handing `db` to the stores eagerly here would resolve the+ // SQLCipher passphrase inside this constructor, so merely obtaining the+ // repository would throw on a device whose AndroidKeyStore key has been+ // invalidated (OS upgrade / lock-screen change / restore, #939). With the+ // build deferred to first actual use, singleton creation never touches+ // the database; the failure surfaces at query time, where the startup+ // guards (StartupGuard / EmailViewModel flow guards) already contain it.+ val accounts: EmailAccountStore by lazy { EmailAccountStore(db) }+ val messages: EmailMessageStore by lazy { EmailMessageStore(db) }+ val queries: EmailQueryStore by lazy { EmailQueryStore(db) }+ val outbox: EmailOutboxStore by lazy { EmailOutboxStore(db) } // Expose the underlying database for DAO-level access fun getDatabase(): EmailDatabase = db
email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.ktindex 309407a9ce..3fb49c64f9 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt@@ -50,7 +50,32 @@ class EmailViewModel(application: Application) : private val emailManager = EmailManager() private val appContext = application.applicationContext - val draftsActions = EmailDraftActions(viewModelScope, repository.getDatabase().outboxDao())+ /**+ * Acquires a DAO-backed list flow for a property initializer without+ * letting database *construction* throw out of this constructor (#939).+ * Resolving a DAO builds the Room database — SQLCipher passphrase+ * decryption in the shared Room layer — which throws synchronously on a+ * device whose AndroidKeyStore key has been invalidated (OS upgrade /+ * lock-screen change / data restore), before any flow `.catch` could be+ * attached. Inside `viewModel()` that escaped composition and exited the+ * app at startup. Construction failure now degrades to the same empty+ * list as an open failure at collection time.+ */+ private fun <T> dbFlowOrEmpty(step: String, source: () -> Flow<List<T>>): Flow<List<T>> =+ try {+ source()+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ throw cancelled+ } catch (failure: Throwable) {+ Log.status("EmailViewModel", "$step unavailable; database failed to build", failure)+ flowOf(emptyList())+ }++ // Lazy for the same #939 reason as [dbFlowOrEmpty]: resolving the outbox+ // DAO at construction time builds the database synchronously.+ val draftsActions: EmailDraftActions by lazy {+ EmailDraftActions(viewModelScope, repository.getDatabase().outboxDao())+ } val send = EmailSendActions(viewModelScope, appContext, emailManager) val aiSummaryHelper = AiSummaryHelper(appContext) @@ -60,7 +85,7 @@ class EmailViewModel(application: Application) : // gate — instead of escaping viewModelScope and crashing the process // a second after that gate first composes from the initial emptyList. val accounts: StateFlow<List<EmailAccount>> =- accountsDao.getAccountsFlow()+ dbFlowOrEmpty("Accounts") { accountsDao.getAccountsFlow() } .catch { failure -> if (failure is kotlinx.coroutines.CancellationException) throw failure Log.status("EmailViewModel", "Accounts unavailable; database failed to open", failure)@@ -80,10 +105,23 @@ class EmailViewModel(application: Application) : /** Flips true once the drafts DAO emits at least once; the list starts empty. */ val hasLoadedDrafts: kotlinx.coroutines.flow.StateFlow<Boolean> = _hasLoadedDrafts - val outbox: Flow<List<OutboxEntry>> = outboxDao.getOutboxFlow()+ val outbox: Flow<List<OutboxEntry>> = dbFlowOrEmpty("Outbox") { outboxDao.getOutboxFlow() } .onEach { _hasLoadedOutbox.value = true }- val drafts: Flow<List<com.vayunmathur.email.data.DraftEntry>> = outboxDao.getDraftsFlow()- .onEach { _hasLoadedDrafts.value = true }+ .catch { failure ->+ if (failure is kotlinx.coroutines.CancellationException) throw failure+ Log.status("EmailViewModel", "Outbox unavailable; database failed to open", failure)+ _hasLoadedOutbox.value = true+ emit(emptyList())+ }+ val drafts: Flow<List<com.vayunmathur.email.data.DraftEntry>> =+ dbFlowOrEmpty("Drafts") { outboxDao.getDraftsFlow() }+ .onEach { _hasLoadedDrafts.value = true }+ .catch { failure ->+ if (failure is kotlinx.coroutines.CancellationException) throw failure+ Log.status("EmailViewModel", "Drafts unavailable; database failed to open", failure)+ _hasLoadedDrafts.value = true+ emit(emptyList())+ } /** Block a sender (matched by email address) so their mail is hidden from the inbox. */ override fun blockSender(from: String) {@@ -149,7 +187,13 @@ class EmailViewModel(application: Application) : } } - val blockedSenders: Flow<List<com.vayunmathur.email.data.BlockedSender>> = accountsDao.getBlockedSendersFlow()+ val blockedSenders: Flow<List<com.vayunmathur.email.data.BlockedSender>> =+ dbFlowOrEmpty("Blocked senders") { accountsDao.getBlockedSendersFlow() }+ .catch { failure ->+ if (failure is kotlinx.coroutines.CancellationException) throw failure+ Log.status("EmailViewModel", "Blocked senders unavailable; database failed to open", failure)+ emit(emptyList())+ } // Hide messages from blocked senders (matched by email address substring). val messages: Flow<List<EmailPreview>> = combine(messagesRaw, blockedSenders) { msgs, blocked ->
email/src/test/java/com/vayunmathur/email/platform/EmailViewModelStartupTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/platform/EmailViewModelStartupTest.kt b/email/src/test/java/com/vayunmathur/email/platform/EmailViewModelStartupTest.ktnew file mode 100644index 0000000000..134b46a7f1--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/platform/EmailViewModelStartupTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.email.platform++import android.app.Application+import android.content.Context+import android.util.Base64+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.email.data.EmailDatabase+import com.vayunmathur.email.data.EmailRepository+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.library.util.databases+import com.vayunmathur.testsupport.FakeAndroidKeyStore+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Regression tests for the remaining #939 startup crash: the earlier guard+ * covered failures while *collecting* the accounts flow and running+ * background startup steps, but database *construction* still threw+ * synchronously during start. `EmailRepository` handed the (lazy) database+ * to its four stores in its constructor and `EmailViewModel` resolved DAOs+ * in property initializers, so merely obtaining the repository/ViewModel+ * ran SQLCipher passphrase decryption — which throws when the device's+ * AndroidKeyStore key has been invalidated (OS upgrade, lock-screen+ * change, data restore, as on the reporter's Android 15 device) — and the+ * exception escaped `viewModel()` inside composition, exiting the app+ * before the Add Account gate could stay on screen.+ *+ * These tests poison the stored database passphrase so the next database+ * build fails GCM authentication, then pin that the repository and the+ * ViewModel still construct and every eagerly-created list flow degrades+ * to its empty value instead of throwing.+ */+@RunWith(RobolectricTestRunner::class)+class EmailViewModelStartupTest {++ private val context: Application+ get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun poisonDatabasePassphrase() {+ FakeAndroidKeyStore.install()+ FakeAndroidKeyStore.clear()+ resetRepositorySingleton()+ databases.remove(EmailDatabase::class)++ // A valid passphrase first (key generated + ciphertext stored)...+ DatabaseHelper(context).storePassphrase("startup-test-passphrase")+ // ...then corrupt the stored ciphertext, as a device whose+ // AndroidKeyStore-rotated key makes decryption fail equivalently.+ val prefs = context.getSharedPreferences(SECURE_PREFS, Context.MODE_PRIVATE)+ val stored = prefs.getString(PASSPHRASE_KEY, null)!!+ val bytes = Base64.decode(stored, Base64.NO_WRAP)+ bytes[0] = (bytes[0] + 1).toByte()+ prefs.edit()+ .putString(PASSPHRASE_KEY, Base64.encodeToString(bytes, Base64.NO_WRAP))+ .commit()+ }++ @AfterTest+ fun reset() {+ databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ @Test+ fun `repository and view model survive a database that cannot be built`() {+ // Construction itself is the regression: both used to throw here.+ EmailRepository.get(context)+ val viewModel = EmailViewModel(context)++ // The gate-critical flows degrade to empty instead of crashing.+ assertTrue(viewModel.accounts.value.isEmpty())+ runBlocking {+ assertEquals(emptyList(), viewModel.outbox.first())+ assertEquals(emptyList(), viewModel.drafts.first())+ assertEquals(emptyList(), viewModel.blockedSenders.first())+ }+ // The failure-empties count as loaded so the screens do not spin+ // forever behind a database that will never open on this device.+ assertTrue(viewModel.hasLoadedOutbox.value)+ assertTrue(viewModel.hasLoadedDrafts.value)+ }++ @Test+ fun `view model still constructs against a working database`() {+ val db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ databases[EmailDatabase::class] = db+ try {+ val viewModel = EmailViewModel(context)+ assertTrue(viewModel.accounts.value.isEmpty()) // no accounts yet+ runBlocking {+ assertEquals(emptyList(), EmailRepository.get(context).getAccounts())+ }+ } finally {+ databases.remove(EmailDatabase::class)+ runCatching { db.close() }+ }+ }++ /** SharedPreferences contract owned by the library [DatabaseHelper]. */+ private companion object {+ const val SECURE_PREFS = "secure_prefs"+ const val PASSPHRASE_KEY = "encrypted_passphrase_no_auth"+ }+}