Modern Apps git

← Modern-Apps.git

email,photos: database upgrades from before v2.6.0 start fresh

Commit
4d4a39f76cb87c99edfe7bc407954abaa1621e9d
Author
Vayun Mathur <[email protected]>
When
2026-12-01 14:57 UTC (4 days ago)
Parents
9efba8a
Owner-approved upgrade floor (DB versions pinned exactly
from git tags): email floor DB v17 (app v2.6.0), photos
floor DB v12; VaultDatabase is v1 with no pre-floor
versions. Migrations 1->17 (email) and 1->12 (photos) are
removed, plus the one pre-floor schema file on disk
(photos v1.json; other schema files start at/after the
floors and stay).

Below-floor behaviour is explicit, not a crash-loop:
DatabaseMigrations gains destructiveMigrationFrom (default
empty, every other module unchanged), applied as
fallbackToDestructiveMigrationFrom ONLY when non-empty —
a pre-floor DB is recreated once on open; floor->current
migrates normally with data intact; no blanket destructive
fallback anywhere.

Migration tests rewritten to the policy: pre-floor chain
tests removed (behaviour removed-by-policy, listed in the
agent report), floor->current data-intact tests added for
both modules, and real-file pre-floor destructive-open
tests added. 432 gross lines removed here; the remaining
LOC-plan schema files did not exist on disk for these
modules. Verified: :email:testDevUnitTest 593,
:photos:testDevUnitTest 418, :library:room tests BUILD
SUCCESSFUL; lint errors pre-existing on untouched files.

Diff

email/AGENTS.md
diff --git a/email/AGENTS.md b/email/AGENTS.mdindex 9cbb8741c6..c0aef7657d 100644--- a/email/AGENTS.md+++ b/email/AGENTS.md@@ -25,6 +25,7 @@ _Install: ./install email (dev by default)._ - 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+- 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)  ## Key files ### Root — entry + navigation
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex 70e9bd72c5..0b9152e56b 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -42,177 +42,6 @@ abstract class EmailDatabase : RoomDatabase() {         @Volatile         private var instance: EmailDatabase? = null -        /**-         * v1 → v2 (reconstructed; see below): multi-account keys.-         *-         * History: v1 (f554d13d6, "email: more comprehensive inbox") had only-         * EmailFolder(fullName PK, name, parentFullName, delimiter) and-         * EmailMessage(id+folderName PK, subject, from, date, body, isHtml).-         * The next commit touching the DB, 742082c48 ("email: make loading-         * faster"), jumped straight to version = 3 — version 2 was never-         * committed or shipped, so no device carries a "v2 schema" to match.-         * This step therefore takes the first half of that 1→3 diff: both-         * tables are recreated with `accountEmail` in their primary keys and-         * EmailFolder gains `holdsMessages`. Primary keys cannot be altered,-         * so the tables are rebuilt and rows copied; v1 had no account-         * concept, so existing rows are stamped with the empty account,-         * which matches no account and is repopulated per-account on sync-         * (the 1→3 build of the day wiped these rows via destructive-         * fallback, so preserving them at all is strictly better).-         */-        private val MIGRATION_1_2 = Migration(1, 2) {-            it.execSQL(-                """-                CREATE TABLE IF NOT EXISTS `EmailFolder_new` (-                    `accountEmail` TEXT NOT NULL,-                    `fullName` TEXT NOT NULL,-                    `name` TEXT NOT NULL,-                    `parentFullName` TEXT,-                    `holdsMessages` INTEGER NOT NULL,-                    `delimiter` TEXT NOT NULL,-                    PRIMARY KEY(`accountEmail`, `fullName`)-                )-                """.trimIndent()-            )-            it.execSQL(-                "INSERT INTO `EmailFolder_new` (`accountEmail`, `fullName`, `name`, `parentFullName`, `holdsMessages`, `delimiter`) " +-                    "SELECT '', `fullName`, `name`, `parentFullName`, 1, `delimiter` FROM `EmailFolder`"-            )-            it.execSQL("DROP TABLE IF EXISTS `EmailFolder`")-            it.execSQL("ALTER TABLE `EmailFolder_new` RENAME TO `EmailFolder`")-            it.execSQL(-                """-                CREATE TABLE IF NOT EXISTS `EmailMessage_new` (-                    `accountEmail` TEXT NOT NULL,-                    `folderName` TEXT NOT NULL,-                    `id` INTEGER NOT NULL,-                    `subject` TEXT NOT NULL,-                    `from` TEXT NOT NULL,-                    `date` TEXT NOT NULL,-                    `body` TEXT,-                    `isHtml` INTEGER NOT NULL,-                    PRIMARY KEY(`accountEmail`, `folderName`, `id`)-                )-                """.trimIndent()-            )-            it.execSQL(-                "INSERT INTO `EmailMessage_new` (`accountEmail`, `folderName`, `id`, `subject`, `from`, `date`, `body`, `isHtml`) " +-                    "SELECT '', `folderName`, `id`, `subject`, `from`, `date`, `body`, `isHtml` FROM `EmailMessage`"-            )-            it.execSQL("DROP TABLE IF EXISTS `EmailMessage`")-            it.execSQL("ALTER TABLE `EmailMessage_new` RENAME TO `EmailMessage`")-        }--        /**-         * v2 → v3 (reconstructed): the EmailAccount table, the second half-         * of 742082c48's 1→3 diff (EmailAccount(email PK, accessToken,-         * refreshToken, expiresAt)). Creates the table empty: a v1 install-         * held its single Gmail OAuth identity outside Room, and the tokens-         * are re-established by signing in again.-         */-        private val MIGRATION_2_3 = Migration(2, 3) {-            it.execSQL(-                """-                CREATE TABLE IF NOT EXISTS `EmailAccount` (-                    `email` TEXT NOT NULL,-                    `accessToken` TEXT NOT NULL,-                    `refreshToken` TEXT,-                    `expiresAt` INTEGER NOT NULL,-                    PRIMARY KEY(`email`)-                )-                """.trimIndent()-            )-        }--        /**-         * v3 → v4 (reconstructed): a18f75606 ("email: sending emails", the-         * commit that raised version 3 → 4) added Attachment and the-         * EmailMessage columns serverId, threadId, to, cc, references and-         * hasAttachments; a3f7b10dd then added isRead without a version-         * bump, so every shipped v4 database carries it and MIGRATION_4_5-         * already assumes it. Attachment is created exactly as at v4.-         */-        private val MIGRATION_3_4 = Migration(3, 4) {-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN serverId TEXT")-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN threadId TEXT")-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN `to` TEXT")-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN cc TEXT")-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN `references` TEXT")-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN hasAttachments INTEGER NOT NULL DEFAULT 0")-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN isRead INTEGER NOT NULL DEFAULT 0")-            it.execSQL(-                """-                CREATE TABLE IF NOT EXISTS `Attachment` (-                    `accountEmail` TEXT NOT NULL,-                    `folderName` TEXT NOT NULL,-                    `messageId` INTEGER NOT NULL,-                    `partId` TEXT NOT NULL,-                    `fileName` TEXT NOT NULL,-                    `mimeType` TEXT NOT NULL,-                    `size` INTEGER NOT NULL,-                    `localUri` TEXT,-                    PRIMARY KEY(`accountEmail`, `messageId`, `partId`)-                )-                """.trimIndent()-            )-        }--        private val MIGRATION_4_5 = Migration(4, 5) {-            it.execSQL(-                """-                CREATE TABLE IF NOT EXISTS `OutboxEntry` (-                    `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,-                    `accountEmail` TEXT NOT NULL,-                    `to` TEXT NOT NULL,-                    `cc` TEXT,-                    `subject` TEXT NOT NULL,-                    `body` TEXT NOT NULL,-                    `attachmentLocalPaths` TEXT NOT NULL DEFAULT '[]',-                    `inReplyTo` TEXT,-                    `references` TEXT,-                    `createdAt` INTEGER NOT NULL DEFAULT 0,-                    `lastError` TEXT,-                    `attemptCount` INTEGER NOT NULL DEFAULT 0,-                    `lastAttemptAt` INTEGER NOT NULL DEFAULT 0-                )-                """.trimIndent()-            )-        }--        private val MIGRATION_11_12 = Migration(11, 12) {-            it.execSQL("ALTER TABLE OutboxEntry ADD COLUMN scheduledAt INTEGER NOT NULL DEFAULT 0")-        }--        private val MIGRATION_12_13 = Migration(12, 13) {-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN snoozedUntil INTEGER NOT NULL DEFAULT 0")-        }--        private val MIGRATION_13_14 = Migration(13, 14) {-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN listUnsubscribe TEXT")-            it.execSQL("CREATE TABLE IF NOT EXISTS `BlockedSender` (`address` TEXT NOT NULL, PRIMARY KEY(`address`))")-        }--        private val MIGRATION_14_15 = Migration(14, 15) {-            it.execSQL("ALTER TABLE OutboxEntry ADD COLUMN isHtml INTEGER NOT NULL DEFAULT 0")-        }--        private val MIGRATION_15_16 = Migration(15, 16) {-            it.execSQL(-                """-                CREATE TABLE IF NOT EXISTS `DeletedUid` (-                    `accountEmail` TEXT NOT NULL,-                    `folderName` TEXT NOT NULL,-                    `uid` INTEGER NOT NULL,-                    PRIMARY KEY(`accountEmail`, `folderName`, `uid`)-                )-                """.trimIndent()-            )-        }--        private val MIGRATION_16_17 = Migration(16, 17) {-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN listUnsubscribePost TEXT")-        }-         private val MIGRATION_17_18 = Migration(17, 18) {             it.execSQL("ALTER TABLE OutboxEntry ADD COLUMN inlineImageJson TEXT NOT NULL DEFAULT '[]'")             it.execSQL("ALTER TABLE DraftEntry ADD COLUMN inlineImageJson TEXT NOT NULL DEFAULT '[]'")@@ -255,53 +84,6 @@ abstract class EmailDatabase : RoomDatabase() {             )         } -        private val MIGRATION_5_6 = Migration(5, 6) {-            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN dateMillis INTEGER NOT NULL DEFAULT 0")-        }--        private val MIGRATION_6_7 = Migration(6, 7) {-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN provider TEXT NOT NULL DEFAULT 'gmail'")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN imapHost TEXT NOT NULL DEFAULT 'imap.gmail.com'")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN imapPort INTEGER NOT NULL DEFAULT 993")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN imapUseSsl INTEGER NOT NULL DEFAULT 1")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN smtpHost TEXT NOT NULL DEFAULT 'smtp.gmail.com'")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN smtpPort INTEGER NOT NULL DEFAULT 465")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN smtpUseSsl INTEGER NOT NULL DEFAULT 1")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN authType TEXT NOT NULL DEFAULT 'oauth2'")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN passwordEncrypted BLOB")-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN passwordIv BLOB")-        }--        private val MIGRATION_7_8 = Migration(7, 8) {-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN username TEXT NOT NULL DEFAULT ''")-            it.execSQL("UPDATE EmailAccount SET username = email")-        }--        private val MIGRATION_8_9 = Migration(8, 9) {-            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN signature TEXT NOT NULL DEFAULT ''")-        }--        private val MIGRATION_9_10 = Migration(9, 10) {-            it.execSQL("ALTER TABLE OutboxEntry ADD COLUMN bcc TEXT")-        }--        private val MIGRATION_10_11 = Migration(10, 11) {-            it.execSQL(-                """-                CREATE TABLE IF NOT EXISTS `DraftEntry` (-                    `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,-                    `accountEmail` TEXT NOT NULL,-                    `to` TEXT NOT NULL,-                    `cc` TEXT NOT NULL,-                    `bcc` TEXT NOT NULL,-                    `subject` TEXT NOT NULL,-                    `body` TEXT NOT NULL,-                    `updatedAt` INTEGER NOT NULL-                )-                """.trimIndent()-            )-        }-         /**          * Adds the stored `peekContent` snippet column (see [EmailMessage.peekContent]).          * Purely additive: existing rows get `''` and are backfilled from their body on@@ -362,28 +144,11 @@ abstract class EmailDatabase : RoomDatabase() {             it.execSQL("ALTER TABLE OutboxEntry ADD COLUMN messageId TEXT")         } -        /**-         * Every migration for this database, registered with the Room builder via the-         * [DatabaseMigrations] reflection hook in `openRoomDatabase`. Order is-         * irrelevant to Room; kept numeric here for readability.-         */+        /** Database versions before the supported floor (DB v17): opening one starts fresh. */+        override val destructiveMigrationFrom: Set<Int> = (1..16).toSet()++        /** Every supported migration (DB v17 onward), registered via [DatabaseMigrations]. */         override val migrations: List<Migration> = listOf(-            MIGRATION_1_2,-            MIGRATION_2_3,-            MIGRATION_3_4,-            MIGRATION_4_5,-            MIGRATION_5_6,-            MIGRATION_6_7,-            MIGRATION_7_8,-            MIGRATION_8_9,-            MIGRATION_9_10,-            MIGRATION_10_11,-            MIGRATION_11_12,-            MIGRATION_12_13,-            MIGRATION_13_14,-            MIGRATION_14_15,-            MIGRATION_15_16,-            MIGRATION_16_17,             MIGRATION_17_18,             MIGRATION_18_19,             MIGRATION_19_20,
email/src/main/java/com/vayunmathur/email/data/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/data/EmailModels.ktindex 52fa2aa8dc..3140379771 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt@@ -146,14 +146,13 @@ data class EmailAccount(      * account-picker UIs.      *      * `@ColumnInfo(defaultValue = ...)` is required so the schema generated-     * from this entity matches `MIGRATION_6_7`, which `ALTER TABLE`s these-     * columns in with a SQL default. Without it Room would throw-     * `IllegalStateException: Migration didn't properly handle: EmailAccount`-     * at startup for users upgrading from v6.+     * from this entity matches the migrated schema, whose columns carry SQL+     * defaults. Without it Room throws `IllegalStateException: Migration+     * didn't properly handle: EmailAccount` at startup on upgrade.      */     @ColumnInfo(defaultValue = "gmail")     val provider: String = "gmail",-    /** IMAP hostname this account fetches from. Hard-coded to Gmail's pre-multi-provider migration. */+    /** IMAP hostname this account fetches from; Gmail's host is the default. */     @ColumnInfo(defaultValue = "imap.gmail.com")     val imapHost: String = "imap.gmail.com",     @ColumnInfo(defaultValue = "993")
email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.ktindex 816749d8dd..c8927b1c81 100644--- a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt+++ b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt@@ -1,49 +1,42 @@ package com.vayunmathur.email.data +import android.content.Context+import androidx.room3.Room import androidx.sqlite.SQLiteConnection import androidx.sqlite.driver.AndroidSQLiteDriver import androidx.sqlite.execSQL+import androidx.test.core.app.ApplicationProvider+import java.io.File import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking -/** W5: the full EmailDatabase migration chain over v1- and v4-shaped databases. */+/** The supported EmailDatabase migration chain (DB v17 floor) and the pre-floor fresh start. */ @org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) @org.robolectric.annotation.Config(sdk = [34]) class EmailMigrationsW5Test { +    private val context: Context = ApplicationProvider.getApplicationContext()+     /**-     * The v1 schema exactly as f554d13d6 shipped it: EmailFolder keyed by-     * fullName alone and EmailMessage keyed by (id, folderName), no account-     * concept anywhere.+     * A minimal v17-shaped database: the tables/columns the v17-onward+     * migrations alter or index, with one account and one message whose+     * data must survive the floor-to-current upgrade.      */-    private fun openV1(): SQLiteConnection {-        val conn = AndroidSQLiteDriver().open(":memory:")-        conn.execSQL(-            "CREATE TABLE EmailFolder (`fullName` TEXT NOT NULL, `name` TEXT NOT NULL, " +-                "`parentFullName` TEXT, `delimiter` TEXT NOT NULL, PRIMARY KEY(`fullName`))"-        )-        conn.execSQL(-            "CREATE TABLE EmailMessage (`id` INTEGER NOT NULL, `folderName` TEXT NOT NULL, " +-                "`subject` TEXT NOT NULL, `from` TEXT NOT NULL, `date` TEXT NOT NULL, `body` TEXT, " +-                "`isHtml` INTEGER NOT NULL, PRIMARY KEY(`id`, `folderName`))"-        )-        conn.execSQL("INSERT INTO EmailFolder (fullName, name, delimiter) VALUES ('INBOX', 'Inbox', '/')")-        conn.execSQL(-            "INSERT INTO EmailMessage (id, folderName, subject, `from`, date, body, isHtml) " +-                "VALUES (7, 'INBOX', 'Quarterly report', '[email protected]', '2026-01-01', 'numbers', 0)"-        )-        return conn-    }--    private fun openV4(): SQLiteConnection {+    private fun openV17(): SQLiteConnection {         val conn = AndroidSQLiteDriver().open(":memory:")-        conn.execSQL("CREATE TABLE EmailMessage (accountEmail TEXT NOT NULL, folderName TEXT NOT NULL, id INTEGER NOT NULL, threadId TEXT, subject TEXT, `from` TEXT, body TEXT)")-        conn.execSQL("CREATE TABLE EmailAccount (email TEXT NOT NULL PRIMARY KEY)")-        conn.execSQL("CREATE TABLE EmailFolder (accountEmail TEXT NOT NULL, fullName TEXT NOT NULL, parentFullName TEXT)")-        conn.execSQL("CREATE TABLE Attachment (accountEmail TEXT NOT NULL, folderName TEXT NOT NULL, messageId INTEGER NOT NULL)")-        conn.execSQL("INSERT INTO EmailAccount (email) VALUES ('[email protected]')")+        conn.execSQL("CREATE TABLE EmailFolder (accountEmail TEXT NOT NULL, fullName TEXT NOT NULL, name TEXT NOT NULL, parentFullName TEXT, holdsMessages INTEGER NOT NULL DEFAULT 1, delimiter TEXT NOT NULL DEFAULT '/', PRIMARY KEY(accountEmail, fullName))")+        conn.execSQL("CREATE TABLE EmailMessage (accountEmail TEXT NOT NULL, folderName TEXT NOT NULL, id INTEGER NOT NULL, serverId TEXT, threadId TEXT, subject TEXT NOT NULL, `from` TEXT NOT NULL, `to` TEXT, cc TEXT, `references` TEXT, date TEXT NOT NULL, dateMillis INTEGER NOT NULL DEFAULT 0, snoozedUntil INTEGER NOT NULL DEFAULT 0, listUnsubscribe TEXT, listUnsubscribePost TEXT, body TEXT, isHtml INTEGER NOT NULL DEFAULT 0, isRead INTEGER NOT NULL DEFAULT 0, hasAttachments INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(accountEmail, folderName, id))")+        conn.execSQL("CREATE TABLE EmailAccount (email TEXT NOT NULL PRIMARY KEY, accessToken TEXT NOT NULL DEFAULT '', refreshToken TEXT, expiresAt INTEGER NOT NULL DEFAULT 0, provider TEXT NOT NULL DEFAULT 'gmail', imapHost TEXT NOT NULL DEFAULT 'imap.gmail.com', imapPort INTEGER NOT NULL DEFAULT 993, imapUseSsl INTEGER NOT NULL DEFAULT 1, smtpHost TEXT NOT NULL DEFAULT 'smtp.gmail.com', smtpPort INTEGER NOT NULL DEFAULT 465, smtpUseSsl INTEGER NOT NULL DEFAULT 1, authType TEXT NOT NULL DEFAULT 'oauth2', passwordEncrypted BLOB, passwordIv BLOB, username TEXT NOT NULL DEFAULT '', signature TEXT NOT NULL DEFAULT '')")+        conn.execSQL("CREATE TABLE Attachment (accountEmail TEXT NOT NULL, folderName TEXT NOT NULL, messageId INTEGER NOT NULL, partId TEXT NOT NULL DEFAULT '', fileName TEXT NOT NULL DEFAULT '', mimeType TEXT NOT NULL DEFAULT '', size INTEGER NOT NULL DEFAULT 0, localUri TEXT, PRIMARY KEY(accountEmail, messageId, partId))")+        conn.execSQL("CREATE TABLE OutboxEntry (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, accountEmail TEXT NOT NULL, `to` TEXT NOT NULL, cc TEXT, bcc TEXT, subject TEXT NOT NULL, body TEXT NOT NULL, attachmentLocalPaths TEXT NOT NULL DEFAULT '[]', inReplyTo TEXT, `references` TEXT, createdAt INTEGER NOT NULL DEFAULT 0, lastError TEXT, attemptCount INTEGER NOT NULL DEFAULT 0, lastAttemptAt INTEGER NOT NULL DEFAULT 0, scheduledAt INTEGER NOT NULL DEFAULT 0, isHtml INTEGER NOT NULL DEFAULT 0)")+        conn.execSQL("CREATE TABLE DraftEntry (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, accountEmail TEXT NOT NULL, `to` TEXT NOT NULL, cc TEXT NOT NULL, bcc TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, updatedAt INTEGER NOT NULL DEFAULT 0)")+        conn.execSQL("CREATE TABLE BlockedSender (address TEXT NOT NULL PRIMARY KEY)")+        conn.execSQL("CREATE TABLE DeletedUid (accountEmail TEXT NOT NULL, folderName TEXT NOT NULL, uid INTEGER NOT NULL, PRIMARY KEY(accountEmail, folderName, uid))")+        conn.execSQL("INSERT INTO EmailAccount (email, username) VALUES ('[email protected]', '[email protected]')")+        conn.execSQL("INSERT INTO EmailFolder (accountEmail, fullName, name) VALUES ('[email protected]', 'INBOX', 'Inbox')")+        conn.execSQL("INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, date, body) VALUES ('[email protected]', 'INBOX', 7, 'Quarterly report', '[email protected]', '2026-01-01', 'numbers')")         return conn     } @@ -78,40 +71,16 @@ class EmailMigrationsW5Test {     @Test     fun migrationChainIsCompleteAndOrdered() {         assertEquals(-            (1..23).map { it to it + 1 },+            (17..23).map { it to it + 1 },             EmailDatabase.migrations.map { it.startVersion to it.endVersion }.sortedBy { it.first },         )+        assertEquals((1..16).toSet(), EmailDatabase.destructiveMigrationFrom)     }      @Test-    fun v1DatabaseReachesV4ShapeThroughReconstructedMigrations() {-        val conn = openV1()-        migrate(conn, 1, until = 4)-        // v3 half: account table exists, folder/message keys carry the account.-        assertTrue(tableExists(conn, "EmailAccount"))-        assertTrue(columns(conn, "EmailFolder").containsAll(setOf("accountEmail", "holdsMessages")))-        assertTrue(columns(conn, "EmailMessage").contains("accountEmail"))-        // v4 half (a18f75606 + a3f7b10dd's unversioned isRead): threading-        // columns and Attachment, but nothing the 4->... chain adds later.-        assertTrue(-            columns(conn, "EmailMessage").containsAll(-                setOf("serverId", "threadId", "to", "cc", "references", "hasAttachments", "isRead")-            ),-            columns(conn, "EmailMessage").toString(),-        )-        assertTrue(tableExists(conn, "Attachment"))-        assertTrue(!columns(conn, "EmailMessage").contains("dateMillis"))-        // Rows survive the primary-key rebuild, stamped with the empty account.-        assertEquals(listOf("INBOX"), strings(conn, "SELECT fullName FROM EmailFolder"))-        assertEquals(listOf("Quarterly report"), strings(conn, "SELECT subject FROM EmailMessage"))-        assertEquals(listOf(""), strings(conn, "SELECT accountEmail FROM EmailMessage"))-        conn.close()-    }--    @Test-    fun v1DatabaseUpgradesAllTheWayToV24Shape() {-        val conn = openV1()-        migrate(conn, 1)+    fun v17DatabaseUpgradesAllTheWayToV24ShapeWithDataIntact() {+        val conn = openV17()+        migrate(conn, 17)         assertTrue(tableExists(conn, "OutboxEntry"))         assertTrue(tableExists(conn, "DraftEntry"))         assertTrue(tableExists(conn, "BlockedSender"))@@ -120,7 +89,7 @@ class EmailMigrationsW5Test {         assertTrue(tableExists(conn, "Attachment"))         assertTrue(             columns(conn, "EmailMessage").containsAll(-                setOf("serverId", "dateMillis", "snoozedUntil", "listUnsubscribe", "peekContent")+                setOf("serverId", "dateMillis", "snoozedUntil", "listUnsubscribe", "listUnsubscribePost", "peekContent")             ),             columns(conn, "EmailMessage").toString(),         )@@ -128,25 +97,28 @@ class EmailMigrationsW5Test {             columns(conn, "EmailAccount").containsAll(setOf("provider", "username", "allowInsecureCertificates")),             columns(conn, "EmailAccount").toString(),         )+        assertTrue(columns(conn, "OutboxEntry").containsAll(setOf("inlineImageJson", "messageId")), columns(conn, "OutboxEntry").toString())+        assertTrue(columns(conn, "DraftEntry").contains("inlineImageJson"))         assertEquals(listOf("Quarterly report"), strings(conn, "SELECT subject FROM EmailMessage"))+        assertEquals(listOf("[email protected]"), strings(conn, "SELECT username FROM EmailAccount"))         conn.close()     }      @Test     fun migration21To22CreatesFtsIndexOverExistingMessages() {-        val conn = openV4()-        migrate(conn, 4, until = 21)+        val conn = openV17()+        migrate(conn, 17, until = 21)+        conn.execSQL("DELETE FROM EmailMessage")         conn.execSQL(-            "INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, body) " +-                "VALUES ('[email protected]', 'INBOX', 1, 'Quarterly report', '[email protected]', 'numbers inside')",+            "INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, date, body) " ++                "VALUES ('[email protected]', 'INBOX', 1, 'Quarterly report', '[email protected]', '2026-01-01', 'numbers inside')",         )         conn.execSQL(-            "INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, body) " +-                "VALUES ('[email protected]', 'INBOX', 2, 'Hello', '[email protected]', 'dinner plans')",+            "INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, date, body) " ++                "VALUES ('[email protected]', 'INBOX', 2, 'Hello', '[email protected]', '2026-01-02', 'dinner plans')",         )         migrate(conn, 21)         assertTrue(tableExists(conn, "EmailMessageFts"))-        // The rebuild indexed rows that existed before the migration.         assertEquals(             listOf("1"),             strings(conn, "SELECT docid FROM EmailMessageFts WHERE EmailMessageFts MATCH '\"quarter*\"'"),@@ -158,47 +130,53 @@ class EmailMigrationsW5Test {         conn.close()     } -    @Test-    fun v4DatabaseUpgradesToV24Shape() {-        val conn = openV4()-        migrate(conn, 4)-        assertTrue(tableExists(conn, "OutboxEntry"))-        assertTrue(tableExists(conn, "DraftEntry"))-        assertTrue(tableExists(conn, "BlockedSender"))-        assertTrue(tableExists(conn, "DeletedUid"))-        assertTrue(tableExists(conn, "EmailMessageFts"))-        assertTrue(columns(conn, "EmailMessage").containsAll(setOf("dateMillis", "snoozedUntil", "listUnsubscribe", "listUnsubscribePost", "peekContent")), columns(conn, "EmailMessage").toString())-        assertTrue(columns(conn, "EmailAccount").containsAll(setOf("provider", "imapHost", "smtpHost", "authType", "username", "signature", "allowInsecureCertificates")), columns(conn, "EmailAccount").toString())-        assertTrue(columns(conn, "OutboxEntry").containsAll(setOf("scheduledAt", "isHtml", "bcc", "inlineImageJson", "messageId")), columns(conn, "OutboxEntry").toString())-        assertTrue(columns(conn, "DraftEntry").contains("inlineImageJson"))-        // The 6→7 backfill copies email into the new username column.-        assertEquals(listOf("[email protected]"), strings(conn, "SELECT username FROM EmailAccount"))-        conn.close()-    }-     @Test     fun migration18To19CanonicalizesInboxCasing() {-        val conn = openV4()-        migrate(conn, 4, until = 18)-        conn.execSQL("INSERT INTO EmailMessage (accountEmail, folderName, id) VALUES ('[email protected]', 'Inbox', 1)")-        conn.execSQL("INSERT INTO EmailMessage (accountEmail, folderName, id) VALUES ('[email protected]', 'inbox/Receipts', 2)")-        conn.execSQL("INSERT INTO EmailMessage (accountEmail, folderName, id) VALUES ('[email protected]', 'Sent', 3)")-        conn.execSQL("INSERT INTO EmailFolder (accountEmail, fullName, parentFullName) VALUES ('[email protected]', 'Inbox', NULL)")-        conn.execSQL("INSERT INTO EmailFolder (accountEmail, fullName, parentFullName) VALUES ('[email protected]', 'Inbox.Receipts', 'Inbox')")+        val conn = openV17()+        migrate(conn, 17, until = 18)+        conn.execSQL("INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, date) VALUES ('[email protected]', 'Inbox', 1, 's', '[email protected]', 'd')")+        conn.execSQL("INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, date) VALUES ('[email protected]', 'inbox/Receipts', 2, 's', '[email protected]', 'd')")+        conn.execSQL("INSERT INTO EmailMessage (accountEmail, folderName, id, subject, `from`, date) VALUES ('[email protected]', 'Sent', 3, 's', '[email protected]', 'd')")+        conn.execSQL("INSERT INTO EmailFolder (accountEmail, fullName, name) VALUES ('[email protected]', 'Inbox', 'Inbox')")+        conn.execSQL("INSERT INTO EmailFolder (accountEmail, fullName, name, parentFullName) VALUES ('[email protected]', 'Inbox.Receipts', 'Receipts', 'Inbox')")         conn.execSQL("INSERT INTO Attachment (accountEmail, folderName, messageId) VALUES ('[email protected]', 'INBOX', 1)")         conn.execSQL("INSERT INTO DeletedUid (accountEmail, folderName, uid) VALUES ('[email protected]', 'inbox', 9)")          migrate(conn, 18)         assertEquals(             listOf("INBOX", "INBOX/Receipts", "Sent"),-            strings(conn, "SELECT folderName FROM EmailMessage ORDER BY id"),+            strings(conn, "SELECT folderName FROM EmailMessage WHERE id IN (1, 2, 3) ORDER BY id"),         )         assertEquals(             listOf("INBOX", "INBOX.Receipts"),-            strings(conn, "SELECT fullName FROM EmailFolder ORDER BY fullName"),+            strings(conn, "SELECT fullName FROM EmailFolder WHERE fullName LIKE 'Inbox%' OR fullName LIKE 'INBOX%' ORDER BY fullName"),         )         assertEquals(listOf("INBOX"), strings(conn, "SELECT parentFullName FROM EmailFolder WHERE parentFullName IS NOT NULL"))         assertEquals(listOf("INBOX"), strings(conn, "SELECT folderName FROM DeletedUid"))         conn.close()     }++    @Test+    fun preFloorDatabaseOpensDestructivelyWithoutCrashing() = runBlocking {+        val file = File(context.cacheDir, "email-prefloor-test.db")+        file.delete(); File(file.path + "-wal").delete(); File(file.path + "-shm").delete()+        AndroidSQLiteDriver().open(file.absolutePath).use { conn ->+            conn.execSQL("CREATE TABLE EmailMessage (id INTEGER PRIMARY KEY, subject TEXT)")+            conn.execSQL("INSERT INTO EmailMessage (id, subject) VALUES (1, 'old mail')")+            conn.execSQL("PRAGMA user_version = 16")+        }+        val db = Room.databaseBuilder(context, EmailDatabase::class.java, file.absolutePath)+            .setDriver(AndroidSQLiteDriver())+            .addMigrations(*EmailDatabase.migrations.toTypedArray())+            .fallbackToDestructiveMigrationFrom(true, *EmailDatabase.destructiveMigrationFrom.toIntArray())+            .allowMainThreadQueries()+            .build()+        try {+            // Opening succeeds and the pre-floor rows are gone (fresh database).+            assertEquals(emptyList(), db.accountDao().getAccounts())+        } finally {+            db.close()+            file.delete()+        }+    } }
library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt
diff --git a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.ktindex 827fd5aa65..0c94f12b21 100644--- a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt+++ b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt@@ -96,15 +96,18 @@ private fun <T : RoomDatabase> Context.openRoomDatabase(      // Resolve migrations: explicit arg wins; otherwise read from the     // database's companion object if it implements [DatabaseMigrations].-    val resolvedMigrations: List<Migration> = migrations ?: run {-        val companionField = try {-            dbClass.getDeclaredField("Companion").apply { isAccessible = true }-        } catch (_: NoSuchFieldException) {-            null-        }-        val companionInstance = companionField?.get(null)-        (companionInstance as? DatabaseMigrations)?.migrations ?: emptyList()+    val companionInstance = try {+        dbClass.getDeclaredField("Companion").apply { isAccessible = true }.get(null)+    } catch (_: NoSuchFieldException) {+        null+    } catch (_: IllegalAccessException) {+        null     }+    val resolvedMigrations: List<Migration> = migrations+        ?: (companionInstance as? DatabaseMigrations)?.migrations+        ?: emptyList()+    val destructiveFrom: Set<Int> =+        (companionInstance as? DatabaseMigrations)?.destructiveMigrationFrom ?: emptySet()      val targetContext = if (useDeviceProtectedStorage) {         val deviceContext = this.createDeviceProtectedStorageContext()@@ -142,6 +145,9 @@ private fun <T : RoomDatabase> Context.openRoomDatabase(         dbClass,         dbName     ).addMigrations(*resolvedMigrations.toTypedArray())+    if (destructiveFrom.isNotEmpty()) {+        builder.fallbackToDestructiveMigrationFrom(true, *destructiveFrom.toIntArray())+    }      builder.setDriver(SQLCipherDriver(password.toByteArray(Charsets.UTF_8), null, null)) 
library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.ktindex 3363498a48..b328bb7cd5 100644--- a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt+++ b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt@@ -101,6 +101,13 @@ inline fun <reified T : RoomDatabase> closeCachedDatabase() {  */ interface DatabaseMigrations {     val migrations: List<Migration>++    /**+     * Database versions with no supported upgrade path: opening a database+     * at one of these versions destroys and recreates it instead of failing.+     * Empty (the default) means every version needs a migration.+     */+    val destructiveMigrationFrom: Set<Int> get() = emptySet() }  /** Room type converters for instants, durations and JSON-encoded lists. */
photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex 29545817a1..2827bf15d9 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -25,6 +25,7 @@ _Install: ./install photos (dev by default)._ - `MaFragmentActivity` (not `MaActivity`) — biometric + fragment-hosting requirement - Widget code is flat in `widget/` (widget + receiver in one file); ViewModels/ML/compositing live in `platform/`, pure helpers in `domain/` - MediaStore sync writes already-known rows by column (`PhotoDao.updateSyncFields`), never as rebuilt-row upserts: the sync projection excludes the OCR/CLIP payload columns, so an upsert of a changed row would null its OCR text/geometry and CLIP embedding while leaving the scanned flags set+- Upgrades from app versions before v2.6.0 start with a fresh local database (supported upgrade floor: Photo DB v12 and Vault DB v1; Photo DB versions 1–11 open destructively, v12 onward migrates normally; Vault DB has no pre-floor versions)  ## Key files ### Root — entry + inline navigation
photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.json
diff --git a/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.json b/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.jsondeleted file mode 100644index e8674cbb1c..0000000000--- a/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/1.json+++ /dev/null@@ -1,82 +0,0 @@-{-  "formatVersion": 1,-  "database": {-    "version": 1,-    "identityHash": "59f63f3c4bb06096d148596664d488c0",-    "entities": [-      {-        "tableName": "Photo",-        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `date` INTEGER NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `exifSet` INTEGER NOT NULL, `lat` REAL, `long` REAL, `duration` INTEGER)",-        "fields": [-          {-            "fieldPath": "id",-            "columnName": "id",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "name",-            "columnName": "name",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "uri",-            "columnName": "uri",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "date",-            "columnName": "date",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "width",-            "columnName": "width",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "height",-            "columnName": "height",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "exifSet",-            "columnName": "exifSet",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "lat",-            "columnName": "lat",-            "affinity": "REAL"-          },-          {-            "fieldPath": "long",-            "columnName": "long",-            "affinity": "REAL"-          },-          {-            "fieldPath": "videoData.duration",-            "columnName": "duration",-            "affinity": "INTEGER"-          }-        ],-        "primaryKey": {-          "autoGenerate": true,-          "columnNames": [-            "id"-          ]-        }-      }-    ],-    "setupQueries": [-      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",-      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '59f63f3c4bb06096d148596664d488c0')"-    ]-  }-}\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex 3181372479..25ad617e0e 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -449,10 +449,10 @@ abstract class PhotoDatabase : RoomDatabase() {      /** Shared constants and helpers for PhotoDatabase. */     companion object : com.vayunmathur.library.util.DatabaseMigrations {+        override val destructiveMigrationFrom: Set<Int> = (1..11).toSet()+         override val migrations: List<Migration> = listOf(-            MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6,-            MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11,-            MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,+            MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,             MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,             MIGRATION_21_22, MIGRATION_22_23,         )@@ -476,7 +476,7 @@ val MIGRATION_21_22 = Migration(21, 22) { }  val MIGRATION_20_21 = Migration(20, 21) {-    // Restore full-text search (dropped by MIGRATION_8_9 for plain LIKE):+    // Restore full-text search (OCR text lives on the Photo row):     // an FTS4 virtual table over OCR text and file name, backed by Photo     // as its content table (unicode61, diacritics removed). Room generates     // and maintains the room_fts_content_sync_* triggers itself, so this@@ -490,68 +490,6 @@ val MIGRATION_20_21 = Migration(20, 21) {     it.execSQL("INSERT INTO `PhotoFts`(`PhotoFts`) VALUES('rebuild')") } -val MIGRATION_1_2 = Migration(1, 2) {-    it.execSQL("CREATE INDEX IF NOT EXISTS `index_Photo_date` ON `Photo` (`date`)")-}--val MIGRATION_2_3 = Migration(2, 3) {-    it.execSQL("ALTER TABLE Photo ADD COLUMN dateModified INTEGER NOT NULL DEFAULT 0")-}--val MIGRATION_3_4 = Migration(3, 4) {-    it.execSQL("ALTER TABLE Photo ADD COLUMN isTrashed INTEGER NOT NULL DEFAULT 0")-}--val MIGRATION_4_5 = Migration(4, 5) {-    it.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS `PhotoOCR` USING FTS4(`ocrText` TEXT)")-}--val MIGRATION_5_6 = Migration(5, 6) {-    // Recreate FTS table with new schema including description field-    it.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS `PhotoOCR_new` USING FTS4(`ocrText` TEXT, `description` TEXT)")-    it.execSQL("INSERT INTO PhotoOCR_new(rowid, ocrText, description) SELECT rowid, ocrText, '' FROM PhotoOCR")-    it.execSQL("DROP TABLE PhotoOCR")-    it.execSQL("ALTER TABLE PhotoOCR_new RENAME TO PhotoOCR")-}--val MIGRATION_6_7 = Migration(6, 7) {-    // Optional on-device face recognition: track scanned photos and store face-    // templates for contacts and library photos. SQL mirrors Room's generated-    // schema exactly so schema validation passes.-    it.execSQL("ALTER TABLE Photo ADD COLUMN faceScanned INTEGER NOT NULL DEFAULT 0")-    it.execSQL(-        "CREATE TABLE IF NOT EXISTS `ContactFace` (`contactKey` TEXT NOT NULL, `name` TEXT NOT NULL, " +-            "`embedding` BLOB NOT NULL, `photoUri` TEXT NOT NULL, PRIMARY KEY(`contactKey`))"-    )-    it.execSQL(-        "CREATE TABLE IF NOT EXISTS `PhotoFace` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +-            "`photoId` INTEGER NOT NULL, `embedding` BLOB NOT NULL, `contactKey` TEXT, `contactName` TEXT)"-    )-    it.execSQL("CREATE INDEX IF NOT EXISTS `index_PhotoFace_photoId` ON `PhotoFace` (`photoId`)")-}--val MIGRATION_7_8 = Migration(7, 8) {-    // Move from contact-matched faces to unsupervised, unnamed face clustering.-    // Drop the contact table and the old face rows (which carried contact-    // columns), recreate Person (clusters) + PhotoFace (with clusterId), and-    // reset faceScanned so existing photos get re-detected and clustered.-    // Photo data itself is untouched. SQL mirrors Room's generated schema.-    it.execSQL("DROP TABLE IF EXISTS ContactFace")-    it.execSQL("DROP TABLE IF EXISTS PhotoFace")-    it.execSQL(-        "CREATE TABLE IF NOT EXISTS `Person` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +-            "`centroid` BLOB NOT NULL, `faceCount` INTEGER NOT NULL, `repPhotoId` INTEGER NOT NULL, " +-            "`repLeft` REAL NOT NULL, `repTop` REAL NOT NULL, `repRight` REAL NOT NULL, `repBottom` REAL NOT NULL)"-    )-    it.execSQL(-        "CREATE TABLE IF NOT EXISTS `PhotoFace` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +-            "`photoId` INTEGER NOT NULL, `clusterId` INTEGER NOT NULL, `embedding` BLOB NOT NULL)"-    )-    it.execSQL("CREATE INDEX IF NOT EXISTS `index_PhotoFace_photoId` ON `PhotoFace` (`photoId`)")-    it.execSQL("CREATE INDEX IF NOT EXISTS `index_PhotoFace_clusterId` ON `PhotoFace` (`clusterId`)")-    it.execSQL("UPDATE Photo SET faceScanned = 0")-}- val MIGRATION_16_17 = Migration(16, 17) {     // Index the predicate every progress count and every getUnscannedFor* query     // shares (`isTrashed = 0 AND duration IS NULL`). The only index before this@@ -601,50 +539,6 @@ val MIGRATION_19_20 = Migration(19, 20) {     it.execSQL("ALTER TABLE Photo ADD COLUMN isFavorite INTEGER NOT NULL DEFAULT 0") } -val MIGRATION_8_9 = Migration(8, 9) {-    // Move OCR text off the FTS side-table and onto the Photo row so search is a-    // plain case-insensitive LIKE (no external inference service). ocrScanned-    // mirrors faceScanned so the OCR worker only processes new photos. Photo data-    // itself is untouched. SQL mirrors Room's generated schema exactly.-    it.execSQL("ALTER TABLE Photo ADD COLUMN ocrText TEXT")-    it.execSQL("ALTER TABLE Photo ADD COLUMN ocrScanned INTEGER NOT NULL DEFAULT 0")-    it.execSQL("DROP TABLE IF EXISTS PhotoOCR")-}--val MIGRATION_9_10 = Migration(9, 10) {-    // Add semantic-search columns: store each photo's L2-normalised image-    // embedding (BLOB) plus a clipScanned flag that mirrors ocrScanned so the-    // worker only embeds new photos. OCR text and faces are untouched.-    // SQL mirrors Room's generated schema exactly so schema validation passes.-    it.execSQL("ALTER TABLE Photo ADD COLUMN clipEmbedding BLOB")-    it.execSQL("ALTER TABLE Photo ADD COLUMN clipScanned INTEGER NOT NULL DEFAULT 0")-}--val MIGRATION_10_11 = Migration(10, 11) {-    // Add GPano panorama geometry columns (@Embedded PanoData, all nullable).-    // Reset exifSet so existing photos get re-scanned for GPano XMP on next-    // sync (follows the faceScanned reset precedent in MIGRATION_7_8). Column-    // names mirror Room's generated schema for the embedded fields exactly.-    it.execSQL("ALTER TABLE Photo ADD COLUMN fullWidth INTEGER")-    it.execSQL("ALTER TABLE Photo ADD COLUMN fullHeight INTEGER")-    it.execSQL("ALTER TABLE Photo ADD COLUMN croppedWidth INTEGER")-    it.execSQL("ALTER TABLE Photo ADD COLUMN croppedHeight INTEGER")-    it.execSQL("ALTER TABLE Photo ADD COLUMN croppedLeft INTEGER")-    it.execSQL("ALTER TABLE Photo ADD COLUMN croppedTop INTEGER")-    it.execSQL("UPDATE Photo SET exifSet = 0")-}--val MIGRATION_11_12 = Migration(11, 12) {-    // Add the PanoData.projectionType column so flat (cylindrical) panoramas can-    // be told apart from equirectangular 360 spheres. Existing pano rows (v11-    // only accepted equirectangular) are back-filled as such. Reset exifSet so-    // photos are re-scanned — cylindrical panoramas were previously rejected by-    // the parser and now need to be picked up.-    it.execSQL("ALTER TABLE Photo ADD COLUMN projectionType TEXT")-    it.execSQL("UPDATE Photo SET projectionType = 'equirectangular' WHERE fullWidth IS NOT NULL")-    it.execSQL("UPDATE Photo SET exifSet = 0")-}- val MIGRATION_12_13 = Migration(12, 13) {     // Add MediaStore's MIME_TYPE, which tells animated GIFs apart from stills.     // Existing rows stay NULL until the next sync backfills them; see@@ -678,7 +572,7 @@ val MIGRATION_15_16 = Migration(15, 16) {     // Person drops its single representative face and gains a user-chosen name.     // Existing face rows have no geometry to backfill, so both tables are     // dropped, recreated and re-derived by the background indexer — the same-    // drop-recreate-reset MIGRATION_7_8 did, for the same reason. Photo, OCR and+    // drop-recreate-reset an earlier face rebuild did, for the same reason. Photo, OCR and     // CLIP data are untouched. Nothing is lost: no names exist before this.     //     // Names live on the cluster row, so a future FaceRecognizer.EMBEDDER_VERSION
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.ktindex f813fa10ea..e2d39f3dfc 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt@@ -13,8 +13,6 @@ import androidx.work.Configuration import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.testing.WorkManagerTestInitHelper-import com.vayunmathur.photos.data.MIGRATION_10_11-import com.vayunmathur.photos.data.MIGRATION_11_12 import com.vayunmathur.photos.data.MIGRATION_12_13 import com.vayunmathur.photos.data.MIGRATION_13_14 import com.vayunmathur.photos.data.MIGRATION_14_15@@ -26,15 +24,6 @@ import com.vayunmathur.photos.data.MIGRATION_19_20 import com.vayunmathur.photos.data.MIGRATION_20_21 import com.vayunmathur.photos.data.MIGRATION_21_22 import com.vayunmathur.photos.data.MIGRATION_22_23-import com.vayunmathur.photos.data.MIGRATION_1_2-import com.vayunmathur.photos.data.MIGRATION_2_3-import com.vayunmathur.photos.data.MIGRATION_3_4-import com.vayunmathur.photos.data.MIGRATION_4_5-import com.vayunmathur.photos.data.MIGRATION_5_6-import com.vayunmathur.photos.data.MIGRATION_6_7-import com.vayunmathur.photos.data.MIGRATION_7_8-import com.vayunmathur.photos.data.MIGRATION_8_9-import com.vayunmathur.photos.data.MIGRATION_9_10 import com.vayunmathur.photos.data.PhotoDatabase import kotlin.test.Test import kotlin.test.assertEquals@@ -78,28 +67,33 @@ class PhotosSlice1WorkersTest {         throw AssertionError("no work enqueued under $name")     } -    // ---- Migration chain v1 -> v21 ----+    // ---- Migration chain v12 -> v23 (supported floor) ----      @Test-    fun fullMigrationChainUpgradesV1Schema() = runBlocking<Unit> {+    fun fullMigrationChainUpgradesV12Schema() = runBlocking<Unit> {         val connection = androidx.sqlite.driver.bundled.BundledSQLiteDriver()             .open(":memory:")         try {-            // Minimal v1 Photo table: the columns the early migrations index-            // or update, before any ALTER ran.+            // Minimal v12 Photo table: every column the v12-onward migrations+            // alter, index or read, before any of them ran.             connection.execSQL(                 "CREATE TABLE Photo (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL DEFAULT '', uri TEXT NOT NULL DEFAULT '', " +-                    "date INTEGER NOT NULL, exifSet INTEGER NOT NULL DEFAULT 0, duration INTEGER)",+                    "date INTEGER NOT NULL, width INTEGER NOT NULL DEFAULT 0, height INTEGER NOT NULL DEFAULT 0, " ++                    "dateModified INTEGER NOT NULL DEFAULT 0, exifSet INTEGER NOT NULL DEFAULT 0, lat REAL, `long` REAL, duration INTEGER, " ++                    "fullWidth INTEGER, fullHeight INTEGER, croppedWidth INTEGER, croppedHeight INTEGER, croppedLeft INTEGER, croppedTop INTEGER, " ++                    "projectionType TEXT, isTrashed INTEGER NOT NULL DEFAULT 0, faceScanned INTEGER NOT NULL DEFAULT 0, " ++                    "ocrText TEXT, ocrScanned INTEGER NOT NULL DEFAULT 0, clipEmbedding BLOB, clipScanned INTEGER NOT NULL DEFAULT 0)",             )-            connection.execSQL("INSERT INTO Photo (id, date) VALUES (1, 1000), (2, 2000)")+            connection.execSQL("CREATE TABLE Person (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, centroid BLOB NOT NULL, faceCount INTEGER NOT NULL, repPhotoId INTEGER NOT NULL, repLeft REAL NOT NULL, repTop REAL NOT NULL, repRight REAL NOT NULL, repBottom REAL NOT NULL)")+            connection.execSQL("CREATE TABLE PhotoFace (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, photoId INTEGER NOT NULL, clusterId INTEGER NOT NULL, embedding BLOB NOT NULL)")+            connection.execSQL("INSERT INTO Photo (id, date, name, ocrText) VALUES (1, 1000, 'a', 'hello'), (2, 2000, 'b', NULL)")             val migrations = listOf(-                MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6,-                MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11,-                MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,+                MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,                 MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,                 MIGRATION_21_22, MIGRATION_22_23,             )-            assertEquals(22, PhotoDatabase.migrations.size)+            assertEquals(11, PhotoDatabase.migrations.size)+            assertEquals((1..11).toSet(), PhotoDatabase.destructiveMigrationFrom)             for (migration in migrations) migration.migrate(connection)              fun queryStrings(sql: String): List<String> = connection.prepare(sql).use { statement ->@@ -149,9 +143,32 @@ class PhotosSlice1WorkersTest {     }      @Test-    fun migrationListIsContiguousFrom1To23() {+    fun migrationListIsContiguousFrom12To23() {         val versions = PhotoDatabase.migrations.map { it.startVersion to it.endVersion }-        assertEquals((1..22).map { it to it + 1 }, versions)+        assertEquals((12..22).map { it to it + 1 }, versions)+    }++    @Test+    fun preFloorDatabaseOpensDestructivelyWithoutCrashing() = runBlocking<Unit> {+        val file = java.io.File(context.cacheDir, "photos-prefloor-test.db")+        file.delete(); java.io.File(file.path + "-wal").delete(); java.io.File(file.path + "-shm").delete()+        androidx.sqlite.driver.bundled.BundledSQLiteDriver().open(file.absolutePath).use { conn ->+            conn.execSQL("CREATE TABLE Photo (id INTEGER PRIMARY KEY, name TEXT)")+            conn.execSQL("INSERT INTO Photo (id, name) VALUES (1, 'old')")+            conn.execSQL("PRAGMA user_version = 11")+        }+        val db = androidx.room3.Room.databaseBuilder(context, PhotoDatabase::class.java, file.absolutePath)+            .setDriver(androidx.sqlite.driver.bundled.BundledSQLiteDriver())+            .addMigrations(*PhotoDatabase.migrations.toTypedArray())+            .fallbackToDestructiveMigrationFrom(true, *PhotoDatabase.destructiveMigrationFrom.toIntArray())+            .allowMainThreadQueries()+            .build()+        try {+            assertEquals(emptyList(), db.photoDao().getAll())+        } finally {+            db.close()+            file.delete()+        }     }      // ---- Worker scheduling ----