email: guard startup steps so one failure can't kill launch (#939)
- Commit
0c94f9599d9388d580eaf366c2e4bc7f8c17ccb3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-28 06:28 UTC (8 days ago)
- Parents
581b1a9
Report: Add Account screen shows ~1s, then the app exits, always, on Android 15 (months-long, not a regression; fine on an older device). Static trace: the Add Account gate is pure-static and composes immediately, while every DB/startup touch ran in unguarded launch blocks ~1s later — matching SQLCipher's ~1s key derivation — so any failure (most likely AndroidKeyStore/SQLCipher DB open on a device whose keystore state changed; Room migration and an API-35 widget-enqueue throw are the ranked alternates) escaped as an uncaught coroutine exception and killed the process. 16KB page size was ruled out (shipped libsqlcipher LOAD segments are 16KB-aligned). New platform/StartupGuard runs each startup step in isolation, catches Throwable (the old catch(Exception) missed Errors like UnsatisfiedLinkError), logs the exact failing step, and continues; MainActivity's six steps, both backfills, ImapIdleService, BootReceiver, and the widget now go through it, and EmailViewModel.accounts catches to the empty gate instead of crashing. On the affected device the app now stays usable at the gate and the log names the failing step for a follow-up shared-library (library/room) fix — deliberately not regenerated there, since recreating an invalidated DB key would destroy data. New StartupGuardTest (5 tests: containment, Error containment, cancellation not swallowed, backfills survive a broken DB). Verified: :email:testDevUnitTest 586 tests, 0 failures; lint findings are pre-existing detector errors in untouched files.
Diff
email/AGENTS.md
diff --git a/email/AGENTS.md b/email/AGENTS.mdindex 814412b0b2..9cbb8741c6 100644--- a/email/AGENTS.md+++ b/email/AGENTS.md@@ -23,6 +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 - `network/imap/TrustAll.kt` exists for debug only; never widen its use ## Key files@@ -69,6 +70,7 @@ _Install: ./install email (dev by default)._ - com/vayunmathur/email/network/smtp/MimeBuilder.kt ### platform/ — ViewModel, actions, notifications, lifecycle - com/vayunmathur/email/platform/EmailViewModel.kt+- com/vayunmathur/email/platform/StartupGuard.kt — isolated best-effort startup steps (#939) - com/vayunmathur/email/platform/EmailManager.kt - com/vayunmathur/email/platform/EmailUiContract.kt - com/vayunmathur/email/platform/EmailClientFlag.kt
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex f3aef79df5..f12ebc703c 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -13,6 +13,7 @@ import com.vayunmathur.email.data.ImapIdleService import com.vayunmathur.email.data.OutboxSendWorker import com.vayunmathur.email.platform.AppLifecycleTracker import com.vayunmathur.email.platform.EmailViewModel+import com.vayunmathur.email.platform.StartupGuard import com.vayunmathur.email.platform.IntentState import com.vayunmathur.email.ui.MainContent import com.vayunmathur.email.widget.EmailWidgetReceiver@@ -37,13 +38,29 @@ class MainActivity : MaActivity() { // launch on Dispatchers.IO themselves; calling them from here keeps // one startup site. Order preserved: hourly sync, outbox, IDLE, // then the one-time backfills.+ //+ // Every step runs through StartupGuard in isolation (#939): none of+ // this background work may crash the process after the first frame.+ // An unguarded failure here (WorkManager / foreground-service start+ // refusal, or a database that will not open on this device) used to+ // escape this launch and exit the app ~1s after the Add Account+ // gate first composed. lifecycleScope.launch(Dispatchers.IO) {- [email protected](EmailWidgetReceiver::class)- EmailSyncWorker.scheduleHourlyNonInboxSync(this@MainActivity)- OutboxSendWorker.runNow(this@MainActivity)- ImapIdleService.start(this@MainActivity)- DateMillisBackfill.runIfNeeded(lifecycleScope, this@MainActivity)- PeekContentBackfill.runIfNeeded(lifecycleScope, this@MainActivity)+ val context = this@MainActivity+ StartupGuard.runStep("widget previews") {+ context.updateWidgetPreviews(EmailWidgetReceiver::class)+ }+ StartupGuard.runStep("hourly sync schedule") {+ EmailSyncWorker.scheduleHourlyNonInboxSync(context)+ }+ StartupGuard.runStep("outbox flush") { OutboxSendWorker.runNow(context) }+ StartupGuard.runStep("IDLE start") { ImapIdleService.start(context) }+ StartupGuard.runStep("date backfill") {+ DateMillisBackfill.runIfNeeded(lifecycleScope, context)+ }+ StartupGuard.runStep("peek backfill") {+ PeekContentBackfill.runIfNeeded(lifecycleScope, context)+ } } } @@ -146,8 +163,18 @@ class MainActivity : MaActivity() { // is appended here, as the composer would for a fresh compose, // because a draft-resume does not append it again. lifecycleScope.launch(Dispatchers.IO) {+ // A database that will not open on this device (#939) must not+ // crash a share either: fall back to the plain composer route,+ // exactly as the no-account case below does.+ val account = try {+ EmailRepository.get(this@MainActivity).getAccounts().firstOrNull()+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ throw cancelled+ } catch (_: Throwable) {+ IntentState.navigationRoute = Route.Composer(to = to, subject = subject, body = body)+ return@launch+ } val repository = EmailRepository.get(this@MainActivity)- val account = repository.getAccounts().firstOrNull() if (account == null) { // No account to own a draft yet: keep the pre-existing flow // (the add-account gate runs first, then this route is read).
email/src/main/java/com/vayunmathur/email/data/DateMillisBackfill.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/DateMillisBackfill.kt b/email/src/main/java/com/vayunmathur/email/data/DateMillisBackfill.ktindex 7ccb21a1ee..c7720b8aa7 100644--- a/email/src/main/java/com/vayunmathur/email/data/DateMillisBackfill.kt+++ b/email/src/main/java/com/vayunmathur/email/data/DateMillisBackfill.kt@@ -18,23 +18,35 @@ object DateMillisBackfill { fun runIfNeeded(scope: CoroutineScope, context: Context) { scope.launch(Dispatchers.IO) {- val dao = EmailRepository.get(context).getDatabase().queryDao()- // Java's `Date.toString()` format, e.g. "Wed Nov 27 14:30:00 PST 2024".- val fmt = SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US)- var batch = dao.getRowsWithZeroDateMillis()- var fixed = 0- while (batch.isNotEmpty()) {- for (row in batch) {- val parsed = try { fmt.parse(row.date)?.time } catch (_: Exception) { null }- // Use 1 instead of 0 for unparseable dates so they don't keep getting- // re-processed forever (they'll sort to the bottom but won't loop).- val value = parsed?.takeIf { it > 0L } ?: 1L- dao.updateDateMillis(row.accountEmail, row.folderName, row.id, value)- fixed++- }- batch = dao.getRowsWithZeroDateMillis()+ // Best-effort one-time migration: a database that will not open+ // on this device (#939) must not crash the process from here.+ try {+ runBackfill(context)+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ throw cancelled+ } catch (failure: Throwable) {+ Log.status("DateMillisBackfill", "Backfill skipped; database unavailable", failure) }- if (fixed > 0) Log.dev("DateMillisBackfill", "Backfilled $fixed row(s)") } }++ private suspend fun runBackfill(context: Context) {+ val dao = EmailRepository.get(context).getDatabase().queryDao()+ // Java's `Date.toString()` format, e.g. "Wed Nov 27 14:30:00 PST 2024".+ val fmt = SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US)+ var batch = dao.getRowsWithZeroDateMillis()+ var fixed = 0+ while (batch.isNotEmpty()) {+ for (row in batch) {+ val parsed = try { fmt.parse(row.date)?.time } catch (_: Exception) { null }+ // Use 1 instead of 0 for unparseable dates so they don't keep getting+ // re-processed forever (they'll sort to the bottom but won't loop).+ val value = parsed?.takeIf { it > 0L } ?: 1L+ dao.updateDateMillis(row.accountEmail, row.folderName, row.id, value)+ fixed+++ }+ batch = dao.getRowsWithZeroDateMillis()+ }+ if (fixed > 0) Log.dev("DateMillisBackfill", "Backfilled $fixed row(s)")+ } }
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex 91627d796e..7f590d900d 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -71,8 +71,18 @@ class ImapIdleService : Service() { override fun onDestroy() { scope.cancel(); super.onDestroy() } private suspend fun startIdleLoops() {- val dao = EmailRepository.get(applicationContext).getDatabase().accountDao()- val accounts = dao.getAccounts()+ // A database that will not open on this device (#939) must not+ // crash the process from this SupervisorJob scope: log and stop,+ // exactly as the no-accounts case below already does.+ val accounts = try {+ EmailRepository.get(applicationContext).getDatabase().accountDao().getAccounts()+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ throw cancelled+ } catch (failure: Throwable) {+ Log.status(TAG, "IDLE start skipped; database unavailable", failure)+ stopSelf()+ return+ } if (accounts.isEmpty()) { stopSelf(); return } try { EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext) } catch (_: Exception) {} val current = accounts.map { it.email }.toSet()
email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.kt b/email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.ktindex 3c918da72b..7326ebe755 100644--- a/email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.kt+++ b/email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.kt@@ -2,6 +2,7 @@ package com.vayunmathur.email.data import android.content.Context import com.vayunmathur.library.log.Log+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch@@ -17,26 +18,38 @@ object PeekContentBackfill { fun runIfNeeded(scope: CoroutineScope, context: Context) { scope.launch(Dispatchers.IO) {- val dao = EmailRepository.get(context).getDatabase().queryDao()- var batch = dao.getRowsWithEmptyPeek()- var fixed = 0- while (batch.isNotEmpty()) {- for (row in batch) {- val peek = row.previewText(PEEK_LEN)- // Guard against an all-whitespace/empty preview: writing '' would- // leave the row eligible again and loop forever. Fall back to a- // single space so the row is marked done.- dao.updatePeekContent(- row.accountEmail,- row.folderName,- row.id,- peek.ifEmpty { " " },- )- fixed++- }- batch = dao.getRowsWithEmptyPeek()+ // Best-effort one-time migration: a database that will not open+ // on this device (#939) must not crash the process from here.+ try {+ runBackfill(context)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (failure: Throwable) {+ Log.status("PeekContentBackfill", "Backfill skipped; database unavailable", failure) }- if (fixed > 0) Log.dev("PeekContentBackfill", "Backfilled $fixed row(s)") } }++ private suspend fun runBackfill(context: Context) {+ val dao = EmailRepository.get(context).getDatabase().queryDao()+ var batch = dao.getRowsWithEmptyPeek()+ var fixed = 0+ while (batch.isNotEmpty()) {+ for (row in batch) {+ val peek = row.previewText(PEEK_LEN)+ // Guard against an all-whitespace/empty preview: writing '' would+ // leave the row eligible again and loop forever. Fall back to a+ // single space so the row is marked done.+ dao.updatePeekContent(+ row.accountEmail,+ row.folderName,+ row.id,+ peek.ifEmpty { " " },+ )+ fixed+++ }+ batch = dao.getRowsWithEmptyPeek()+ }+ if (fixed > 0) Log.dev("PeekContentBackfill", "Backfilled $fixed row(s)")+ } }
email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt b/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.ktindex 28baec9423..9267f2cfd5 100644--- a/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt@@ -47,9 +47,13 @@ class BootReceiver : BroadcastReceiver() { appContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) .edit { putBoolean(KEY_PENDING, true) } Log.debug(TAG, "Boot: deferred IDLE start, set $KEY_PENDING=true")- } catch (t: SecurityException) {- Log.status(TAG, "BootReceiver failed: ${t.message}", t)- } catch (t: IllegalStateException) {+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ throw cancelled+ } catch (t: Throwable) {+ // WorkManager scheduling / deferred-start writes are+ // best-effort at boot; none may crash the process+ // (#939: Security/IllegalState were only the known+ // foreground-service cases). Log.status(TAG, "BootReceiver failed: ${t.message}", t) } finally { pending.finish()
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 11bd1f459c..e6ff22ce43 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt@@ -20,6 +20,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.onEach@@ -53,8 +54,19 @@ class EmailViewModel(application: Application) : val send = EmailSendActions(viewModelScope, appContext, emailManager) val aiSummaryHelper = AiSummaryHelper(appContext) + // If the database will not open on this device (#939: SQLCipher+ // passphrase / Keystore / migration failure in the shared Room layer),+ // the accounts flow must degrade to "no accounts" — the Add Account+ // 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().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+ accountsDao.getAccountsFlow()+ .catch { failure ->+ if (failure is kotlinx.coroutines.CancellationException) throw failure+ Log.status("EmailViewModel", "Accounts unavailable; database failed to open", failure)+ emit(emptyList())+ }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) /** Active sync state — drives the linear progress bar at the top of the inbox. */ val isSyncing: StateFlow<Boolean> = EmailSyncState.isSyncing@@ -148,8 +160,17 @@ class EmailViewModel(application: Application) : init { viewModelScope.launch {- accountsDao.getAccounts().firstOrNull()?.let {- _selectedAccountEmail.value = it.email+ // Same #939 guard as the accounts flow: a database-open failure+ // leaves no selected account (Add Account gate) rather than an+ // uncaught exception that exits the app after the first frame.+ try {+ accountsDao.getAccounts().firstOrNull()?.let {+ _selectedAccountEmail.value = it.email+ }+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ throw cancelled+ } catch (failure: Throwable) {+ Log.status("EmailViewModel", "Initial account load failed; database unavailable", failure) } } }
email/src/main/java/com/vayunmathur/email/platform/StartupGuard.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/StartupGuard.kt b/email/src/main/java/com/vayunmathur/email/platform/StartupGuard.ktnew file mode 100644index 0000000000..88b6a6530e--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/platform/StartupGuard.kt@@ -0,0 +1,44 @@+package com.vayunmathur.email.platform++import com.vayunmathur.library.log.Log+import kotlinx.coroutines.CancellationException++/**+ * Runs one best-effort startup step without letting its failure kill the+ * process (GitHub #939).+ *+ * Every step launched from `MainActivity.onCreateBeforeContent` — widget+ * previews (an Android 15+ only WorkManager enqueue), hourly-sync / outbox+ * scheduling, the IMAP IDLE foreground service, and the one-time backfills —+ * is fire-and-forget background work that must never gate or crash the first+ * screen. They used to run unguarded inside plain `launch` blocks, so any+ * failure in them (a WorkManager enqueue refusal, a foreground-service start+ * refusal, or — most importantly — a database that fails to open on this+ * device, e.g. its SQLCipher passphrase can no longer be decrypted by the+ * Android Keystore after an OS upgrade or a data restore) escaped as an+ * uncaught coroutine exception about a second after the Add Account gate+ * composed from the accounts flow's initial empty value, and the app exited+ * on every launch.+ *+ * Each step is therefore run in isolation: a failure is logged and reported+ * as `false`, and the remaining steps still run. [CancellationException] is+ * the one exception rethrown — it means the owning scope is going away, not+ * that the step failed.+ */+object StartupGuard {++ private const val TAG = "EmailStartup"++ /** Runs [step] in isolation; returns false (and logs) if it threw. */+ suspend fun runStep(name: String, step: suspend () -> Unit): Boolean {+ return try {+ step()+ true+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (failure: Throwable) {+ Log.status(TAG, "Startup step '$name' failed; continuing without it", failure)+ false+ }+ }+}
email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt
diff --git a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.ktindex 84be688129..f96645fa68 100644--- a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt+++ b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt@@ -62,7 +62,12 @@ class EmailWidget : MaWidget<List<EmailPreview>>() { return withContext(Dispatchers.IO) { try { EmailRepository.get(context).getDatabase().queryDao().getRecentUnifiedPreview()- } catch (ignored: Exception) {+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ throw cancelled+ } catch (ignored: Throwable) {+ // Widened from Exception (#939): a native/database Error+ // (e.g. UnsatisfiedLinkError) must also degrade to an+ // empty widget, never crash the host process. Log.error("EmailWidget", "DB fail", ignored) emptyList() }
email/src/test/java/com/vayunmathur/email/platform/StartupGuardTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/platform/StartupGuardTest.kt b/email/src/test/java/com/vayunmathur/email/platform/StartupGuardTest.ktnew file mode 100644index 0000000000..1a8eaa469f--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/platform/StartupGuardTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.email.platform++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.email.data.DateMillisBackfill+import com.vayunmathur.email.data.EmailDatabase+import com.vayunmathur.email.data.EmailRepository+import com.vayunmathur.email.data.PeekContentBackfill+import java.util.concurrent.atomic.AtomicReference+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineExceptionHandler+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Regression tests for #939 ("crashes on startup", Android 15 device):+ * the Add Account gate composes from the accounts flow's initial empty+ * value, then every background startup step that touches the database or+ * WorkManager completes asynchronously. Before the fix those steps ran in+ * unguarded `launch` blocks, so a single failure — a RuntimeException or,+ * critically, an [Error] such as UnsatisfiedLinkError from a database that+ * will not open on that device — escaped as an uncaught coroutine+ * exception and exited the app about a second after the first frame.+ *+ * These tests pin the contract that now prevents that: startup steps are+ * isolated, `Throwable` (not just `Exception`) is contained, later steps+ * still run, and the one-time backfills survive a broken database.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class StartupGuardTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase++ @BeforeTest+ fun open() {+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ }++ @AfterTest+ fun close() {+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ runCatching { db.close() }+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ @Test+ fun `a failing startup step is contained and later steps still run`() = runBlocking {+ var laterStepRan = false+ val failed = StartupGuard.runStep("broken database") {+ throw IllegalStateException("database failed to open")+ }+ val succeeded = StartupGuard.runStep("later step") { laterStepRan = true }+ assertFalse(failed)+ assertTrue(succeeded)+ assertTrue(laterStepRan)+ }++ @Test+ fun `an Error from a startup step does not escape`() = runBlocking {+ // The pre-fix failure mode: native/database failures surface as+ // Error, which every catch (Exception) in the old code missed.+ val result = StartupGuard.runStep("native load") {+ throw UnsatisfiedLinkError("libsqlcipher.so not loaded")+ }+ assertFalse(result)+ }++ @Test+ fun `a successful startup step reports true`() = runBlocking {+ assertTrue(StartupGuard.runStep("ok") { })+ }++ @Test+ fun `cancellation is not swallowed by the guard`() {+ assertFailsWith<CancellationException> {+ runBlocking { StartupGuard.runStep("cancelled") { throw CancellationException() } }+ }+ }++ @Test+ fun `backfills survive a database that will not open`() {+ // Point the repository at a closed database so every DAO call+ // throws, then run both backfills on a scope that records any+ // uncaught exception instead of crashing the process.+ db.close()+ val uncaught = AtomicReference<Throwable?>(null)+ val scope = CoroutineScope(+ Dispatchers.IO + CoroutineExceptionHandler { _, failure -> uncaught.set(failure) },+ )+ DateMillisBackfill.runIfNeeded(scope, context)+ PeekContentBackfill.runIfNeeded(scope, context)+ runBlocking { delay(2_000) }+ assertNull(uncaught.get(), "backfill failure escaped as uncaught: ${uncaught.get()}")+ assertEquals(+ null, uncaught.get(),+ "backfills must contain database failures, not crash startup (#939)",+ )+ }+}