Modern Apps git

← Modern-Apps.git

translate: safe platform backup via BackupAgent rekeying

Commit
3b4fd57380c867f92377759b3577361f1005c574
Author
Vayun Mathur <[email protected]>
When
2026-12-04 22:04 UTC (1 day ago)
Parents
c345a93
Translate's platform backup rules copied the raw SQLCipher database in
both the cloud and device-transfer channels. That database is encrypted
under a passphrase wrapped by a non-exportable AndroidKeyStore key, so a
restored copy on a new device cannot be opened: the builder mints a
fresh key, the encrypt-existing check skips the ciphertext, and the
first open throws instead of starting clean.

Fix by data kind:
- History/favourites and language settings are user data. The app now
  declares platform/AppBackupAgent over the library BaseBackupAgent
  with SqlCipherDbCodec, mirroring weather: the DB is exported to
  plaintext inside the backup payload and re-encrypted under the new
  device's key on restore. The agent also carries the
  translate_settings datastore, since declaring a BackupAgent moves
  cloud backup to the key/value path and the cloud-backup rules are
  then no longer consulted.
- data/translateDbConfigs pairs the DB name with the live passphrase.
  On a fresh restore target no passphrase exists yet, so reading the
  config mints one exactly as the database builder does; the import
  then encrypts under a passphrase the new device can open.
- The downloaded model packs (nllb600 617 MB, madlad400 1 GB, plus the
  retired small100 files) are re-derivable and are now excluded from
  both channels; InitialModelDownloadChecker re-fetches the active pack
  on first launch. The raw translate-db (+wal/shm/journal) and
  secure_prefs.xml are excluded from both channels so the broken raw
  copy can never land ahead of the codec payload.

Tests: BackupWiringTest is host-strongest. It pins the manifest
(allowBackup + BackupAgent name), the agent wiring (SqlCipherDbCodec,
translate_settings), translateDbConfigs against the live passphrase
including the fresh-target mint, and that both extraction-rules
sections exclude the raw DB, its sidecars, secure_prefs and every
model pack. The round-trip drives production configs through
BaseBackupAgent with a plaintext codec stand-in because SqlCipher is
native-only on a host JVM; the codec's own host contracts remain
pinned in SqlCipherDbCodecTest, and the native codec round-trip still
needs a device run.

Verified: ./gradlew :translate:lint :translate:lintVitalRelease
:translate:testDevUnitTest --max-workers=128 (173 tests, 0 failures).
One DbBackedPagesTest picker assertion failed once during the first
full parallel run; it passes isolated both at the base commit and with
this change, and the final full run is green.

Diff

translate/AGENTS.md
diff --git a/translate/AGENTS.md b/translate/AGENTS.mdindex aa3c28fd53..9e727f609c 100644--- a/translate/AGENTS.md+++ b/translate/AGENTS.md@@ -15,7 +15,7 @@ _Install: ./install translate (dev by default)._ **Key features:** - Text translation over the on-device NLLB engine (`NllbTranslator` + `NllbModel`); language catalog, recents, and Auto source-language detection (`detectLanguageCode`, English fallback when it finds no trusted evidence) in `domain/` - Camera mode: `CameraPreviewLayer` + `CameraOverlay` over `:library:ocr`; speech in via `SpeechRecognizerEngine`, spoken output via `TtsSpeaker`-- History + persistent settings (`data/TranslateSettings`); translation available from the system selection menu+- History + persistent settings (`data/TranslateSettings`); translation available from the system selection menu. Platform backup carries history/favourites + language settings through `platform/AppBackupAgent` (SqlCipherDbCodec plaintext export/re-encrypt); the raw SQLCipher DB, `secure_prefs` and the downloaded model packs are excluded from both backup channels in `res/xml/data_extraction_rules.xml` - OpenAssistant `translate_text` via `intents/TranslateIntent`: input truncated at 1,000 chars with a flag, output capped at 2,000 chars, source/target codes validated against `domain/Languages` (target never `auto`); a missing model returns the typed `MODEL_NOT_DOWNLOADED` error in `library.intents.translate.TranslateResultData` **Architecture / data-flow:** `ui/` text/camera/language pages → `platform/TranslateViewModel` (+ `TranslateUiContract`) → `domain/TranslationEngine` → `platform/NllbTranslator` on the `:library:ml` runtime; models fetched once via `:library:downloadservice` and hash-verified before first use. Translator loading is a terminal state machine (`platform/TranslatorLoader` + `TranslatorLoadState`): the ViewModel is created before the download gate passes, so the text/camera/image pages re-attempt the load on entry, and every attempt ends in Ready or a Failed error with retry (Retry action / scaffold pull-to-refresh) — never an endless loading state. **Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/TextTranslateScreen.kt` → `platform/TranslateViewModel.kt` → `domain/TranslationEngine.kt` → `platform/NllbTranslator.kt`.@@ -30,6 +30,8 @@ _Install: ./install translate (dev by default)._ - com/vayunmathur/translate/Navigation.kt - com/vayunmathur/translate/Route.kt ### data/ + domain/ — settings, languages, engine contract+- com/vayunmathur/translate/data/TranslateDatabase.kt — `TranslationRecord`/`TranslationDao` + `translateDbConfigs` for the BackupAgent+- com/vayunmathur/translate/data/TranslateRepository.kt - com/vayunmathur/translate/data/TranslateSettings.kt - com/vayunmathur/translate/domain/TranslationEngine.kt - com/vayunmathur/translate/domain/TranslationChunks.kt@@ -37,6 +39,7 @@ _Install: ./install translate (dev by default)._ - com/vayunmathur/translate/domain/Languages.kt - com/vayunmathur/translate/domain/RecentLanguages.kt ### platform/ — ViewModel, NLLB, speech, TTS+- com/vayunmathur/translate/platform/AppBackupAgent.kt - com/vayunmathur/translate/platform/TranslateViewModel.kt - com/vayunmathur/translate/platform/TranslateUiContract.kt - com/vayunmathur/translate/platform/TranslatorLoader.kt
translate/build.gradle.kts
diff --git a/translate/build.gradle.kts b/translate/build.gradle.ktsindex 832f0a2c68..5e75c4d7f3 100644--- a/translate/build.gradle.kts+++ b/translate/build.gradle.kts@@ -49,6 +49,7 @@ rustNativeTests {         listOf(             "com.vayunmathur.translate.data.DataLayerTest",             "com.vayunmathur.translate.data.DbBackedRepositoryTest",+            "com.vayunmathur.translate.platform.BackupWiringTest",             "com.vayunmathur.translate.platform.SharedImageIntentTest",             "com.vayunmathur.translate.platform.ViewModelAndPagesTest",             "com.vayunmathur.translate.ui.CameraScreenProbeTest",
translate/src/main/AndroidManifest.xml
diff --git a/translate/src/main/AndroidManifest.xml b/translate/src/main/AndroidManifest.xmlindex e79996baf5..e0f1c4fc28 100644--- a/translate/src/main/AndroidManifest.xml+++ b/translate/src/main/AndroidManifest.xml@@ -31,6 +31,7 @@      <application         android:allowBackup="true"+        android:backupAgent=".platform.AppBackupAgent"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"
translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.kt b/translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.ktindex fb95fc317f..4edbb2dcdf 100644--- a/translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.kt+++ b/translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.kt@@ -1,5 +1,6 @@ package com.vayunmathur.translate.data +import android.content.Context import androidx.room3.Dao import androidx.room3.Database import androidx.room3.Delete@@ -8,10 +9,36 @@ import androidx.room3.PrimaryKey import androidx.room3.Query import androidx.room3.RoomDatabase import androidx.room3.Upsert+import com.vayunmathur.library.util.DatabaseHelper import kotlinx.coroutines.flow.Flow  const val TRANSLATE_DB_NAME = "translate-db" +/**+ * Backup config for the platform BackupAgent: the encrypted DB name paired+ * with the live SQLCipher passphrase. The codec exports the DB to plaintext+ * inside the backup payload and re-encrypts it under the new device's key,+ * so the raw encrypted file and its keystore-wrapped passphrase never have+ * to travel (see res/xml/data_extraction_rules.xml).+ *+ * On a restore target the passphrase does not exist yet — the key is+ * mint-on-first-use in the database builder — so reading the config mints it+ * the same way the builder does; the import side then encrypts under a+ * passphrase this device can open afterwards.+ */+fun translateDbConfigs(context: Context): List<Pair<String, String>> =+    listOf(TRANSLATE_DB_NAME to translateDbPassphrase(context))++/** The SQLCipher passphrase for [TRANSLATE_DB_NAME], minting it on first use. */+internal fun translateDbPassphrase(context: Context): String {+    val helper = DatabaseHelper(context.applicationContext)+    if (!helper.isKeyGenerated()) {+        helper.generateKey()+        return helper.createAndStorePassphrase(helper.getCipherForEncryption())+    }+    return helper.getPassphrase()+}+ /**  * One saved translation: the source text, its translation, and the language pair.  *
translate/src/main/java/com/vayunmathur/translate/platform/AppBackupAgent.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/AppBackupAgent.kt b/translate/src/main/java/com/vayunmathur/translate/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..1e7ff57fe6--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/platform/AppBackupAgent.kt@@ -0,0 +1,21 @@+package com.vayunmathur.translate.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.translate.data.translateDbConfigs++/** Platform backup agent: history/favourites + language settings; model packs stay excluded. */+class AppBackupAgent : BaseBackupAgent() {+    override val dbCodec = SqlCipherDbCodec++    override val dbConfigs: List<Pair<String, String>>+        get() = translateDbConfigs(this)++    /**+     * Language preferences ride the same agent as the DB: with a custom+     * BackupAgent declared, the OS takes the key/value path and the+     * cloud-backup rules are not consulted, so without this list the+     * last-used pair and recents would not reach a new device from cloud.+     */+    override val datastoreNames: List<String> = listOf("translate_settings")+}
translate/src/main/res/xml/data_extraction_rules.xml
diff --git a/translate/src/main/res/xml/data_extraction_rules.xml b/translate/src/main/res/xml/data_extraction_rules.xmlindex a8366226b5..d770d3eb2e 100644--- a/translate/src/main/res/xml/data_extraction_rules.xml+++ b/translate/src/main/res/xml/data_extraction_rules.xml@@ -1,46 +1,85 @@ <?xml version="1.0" encoding="utf-8"?> <!--   Translate. Audited state:-    * externalFilesDir/nllb600/ — the NLLB-200-distilled-600M translation model:-      nllb600.maml and tokenizer.bin (NllbModel.FILES). An earlier version stored-      SMaLL-100 under externalFilesDir/small100/; NllbModel.deleteRetired removes-      those files on first run, so no exclude is needed for them.-    * filesDir/datastore/translate_settings.preferences_pb — last used source and-      target language (TranslateSettings).-    * filesDir/datastore_default.preferences_pb — per-file download progress.+    * databases/translate-db — Room DB holding translation history and+      favourites (TranslationRecord). Genuinely user data, worth restoring.+    * files/datastore/translate_settings.preferences_pb — last used source and+      target language plus per-direction recents (TranslateSettings).+    * files/datastore_default.preferences_pb — per-file model download progress+      (DataStoreUtils). Tiny, portable, and re-derived by the download gate,+      so carrying it needs no codec and costs nothing.+    * secure_prefs.xml — SQLCipher passphrase for translate-db, wrapped by a+      non-exportable AndroidKeyStore key.+    * externalFilesDir/nllb600/ and madlad400/ — downloaded language models+      (617 MB + 1,015 MB). NllbModel.deleteRetired additionally removes the+      retired SMaLL-100 files under small100/ on first run. -  The model is excluded from cloud backup: the weights are far past the-  ~25 MB Auto Backup quota, and exceeding that quota fails the backup for the-  whole app, which would take the language preferences down with it. It is also-  fully regenerable — NllbModel downloads it mirror-only from-  data.maproj.org with SHA-256 pinning, and InitialModelDownloadChecker in-  MainActivity re-fetches it automatically on first launch.+  translate-db is excluded from both sections: it is SQLCipher-encrypted+  under a passphrase wrapped by a non-exportable AndroidKeyStore key, which+  never leaves the device, so a restored copy of the raw file cannot be+  opened — the database builder mints a fresh key and passphrase, the+  encrypt-existing check skips the already-encrypted file, and Room throws+  SQLiteNotADatabaseException. Shipping it would trade a clean first launch+  for a crash. -  It is kept for device transfer. D2D has no quota and runs over a direct local-  link, so carrying the already-downloaded model across saves the user a-  multi-hundred-megabyte re-download on a brand new phone. This matches the-  approach already taken in maps for its offline map data.+  History/favourites still migrate: translate declares its own BackupAgent+  (platform/AppBackupAgent), which uses SqlCipherDbCodec to export the DB to+  plaintext inside the backup payload and re-encrypt it under the new+  device's key on restore. The agent also carries the translate_settings+  datastore. That path is the one that works; the raw file copy would only+  get in its way. -  Language preferences are tiny and back up in both directions.+  The model packs are excluded from both channels. They are re-derivable:+  NllbModel/MadladModel fetch them mirror-only from data.maproj.org with+  SHA-256 pinning, and InitialModelDownloadChecker in MainActivity+  re-fetches the active pack automatically on first launch. Carrying them+  over device transfer saved one re-download but moved over a gigabyte+  across for data that is not the user's.++  SCOPE: translate declares android:backupAgent=".platform.AppBackupAgent"+  and does NOT set android:fullBackupOnly, so Android uses key/value backup+  here and the <cloud-backup> section below is NOT consulted. Cloud content+  is exactly AppBackupAgent's translateDbConfigs(this) plus the+  translate_settings datastore — translate-db, exported to plaintext by+  SqlCipherDbCodec and re-encrypted on restore. That is the path that+  carries history/favourites across, and it works. The rules below govern+  <device-transfer>, and are the correct control if the backupAgent is ever+  removed. --> <data-extraction-rules>-    <cloud-backup>+    <!-- Not consulted while android:backupAgent is declared; see SCOPE above. -->+    <cloud-backup disableIfNoEncryptionCapabilities="true">         <include domain="root" path="." />         <include domain="file" path="." />         <include domain="database" path="." />+        <exclude domain="database" path="translate-db" />+        <exclude domain="database" path="translate-db-wal" />+        <exclude domain="database" path="translate-db-shm" />+        <exclude domain="database" path="translate-db-journal" />         <include domain="sharedpref" path="." />+        <exclude domain="sharedpref" path="secure_prefs.xml" />         <include domain="external" path="." />-        <!-- Downloaded NLLB-200 weights: over the cloud quota and re-fetchable+        <!-- Downloaded model packs: past the cloud quota and re-fetchable              with hash pinning. -->         <exclude domain="external" path="nllb600" />+        <exclude domain="external" path="madlad400" />+        <exclude domain="external" path="small100" />     </cloud-backup>     <device-transfer>         <include domain="root" path="." />         <include domain="file" path="." />         <include domain="database" path="." />+        <exclude domain="database" path="translate-db" />+        <exclude domain="database" path="translate-db-wal" />+        <exclude domain="database" path="translate-db-shm" />+        <exclude domain="database" path="translate-db-journal" />         <include domain="sharedpref" path="." />-        <!-- Model included: no quota on D2D, and it spares the user a large-             re-download. -->+        <exclude domain="sharedpref" path="secure_prefs.xml" />         <include domain="external" path="." />+        <!-- Model packs re-download on first launch; do not move ~1.6 GB+             across the transfer for re-derivable weights. -->+        <exclude domain="external" path="nllb600" />+        <exclude domain="external" path="madlad400" />+        <exclude domain="external" path="small100" />     </device-transfer> </data-extraction-rules>
translate/src/test/java/com/vayunmathur/translate/platform/BackupWiringTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/platform/BackupWiringTest.kt b/translate/src/test/java/com/vayunmathur/translate/platform/BackupWiringTest.ktnew file mode 100644index 0000000000..fa026a2090--- /dev/null+++ b/translate/src/test/java/com/vayunmathur/translate/platform/BackupWiringTest.kt@@ -0,0 +1,312 @@+package com.vayunmathur.translate.platform++import android.content.Context+import android.content.pm.ApplicationInfo+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.library.util.DbBackupCodec+import com.vayunmathur.library.util.databases+import com.vayunmathur.testsupport.FakeAndroidKeyStore+import com.vayunmathur.translate.data.PlainSqlCipherDriverShadow+import com.vayunmathur.translate.data.TRANSLATE_DB_NAME+import com.vayunmathur.translate.data.TranslateDatabase+import com.vayunmathur.translate.data.TranslateRepository+import com.vayunmathur.translate.data.TranslateSettings+import com.vayunmathur.translate.data.pollDb+import com.vayunmathur.translate.data.runDb+import com.vayunmathur.translate.data.translateDbConfigs+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.BeforeClass+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.BackupDataEntity+import org.robolectric.shadows.BackupDataInputBuilder+import org.robolectric.shadows.BackupDataOutputFactory+import org.w3c.dom.Element+import java.io.ByteArrayInputStream+import java.io.File+import java.util.zip.ZipInputStream+import javax.xml.parsers.DocumentBuilderFactory+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Host-strongest backup checks. The production codec is SQLCipher-native and+ * cannot load on a host JVM, so the round-trip drives the production agent+ * contract (translateDbConfigs + translation-settings datastore through+ * [BaseBackupAgent]) with a plaintext codec stand-in instead: on the host the+ * shadowed driver stores plaintext SQLite, so a byte copy is exactly what+ * sqlcipher_export produces on device. The production codec's own host+ * contracts are pinned in SqlCipherDbCodecTest; its native round-trip still+ * needs a device.+ */+@RunWith(RobolectricTestRunner::class)+@Config(shadows = [PlainSqlCipherDriverShadow::class])+class BackupWiringTest {+    /** Host stand-in for the native codec (see class doc). */+    private object HostPlaintextCodec : DbBackupCodec {+        override fun exportDatabase(+            context: Context,+            dbName: String,+            password: String,+            outputFile: File,+        ) {+            val source = context.getDatabasePath(dbName)+            if (!source.exists()) return+            outputFile.parentFile?.mkdirs()+            source.copyTo(outputFile, overwrite = true)+        }++        override fun importDatabase(+            context: Context,+            dbName: String,+            password: String,+            inputFile: File,+        ) {+            val target = context.getDatabasePath(dbName)+            target.parentFile?.mkdirs()+            inputFile.copyTo(target, overwrite = true)+            File("${target.path}-wal").delete()+            File("${target.path}-shm").delete()+            File("${target.path}-journal").delete()+        }+    }++    private class HostAgent : BaseBackupAgent() {+        override val dbCodec = HostPlaintextCodec+        override val dbConfigs: List<Pair<String, String>>+            get() = translateDbConfigs(attached)+        override val datastoreNames = listOf("translate_settings")++        lateinit var attached: Context++        fun attach(ctx: Context) {+            attached = ctx+            attachBaseContext(ctx)+        }+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun pfd(file: File): ParcelFileDescriptor {+        if (!file.exists()) file.writeBytes(ByteArray(0))+        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE)+    }++    /**+     * Closes the Room database and drops the cached singleton, so the next+     * [TranslateRepository.get] rebuilds against whatever file is live —+     * the host mirror of the process restart a real restore implies.+     */+    private fun closeAndResetRepository() {+        databases[TranslateDatabase::class]?.close()+        databases.remove(TranslateDatabase::class)+        val instanceField = TranslateRepository::class.java.getDeclaredField("instance")+        instanceField.isAccessible = true+        instanceField.set(null, null)+    }++    private fun rulesFile(): File {+        val moduleRelative = File("src/main/res/xml/data_extraction_rules.xml")+        if (moduleRelative.isFile) return moduleRelative+        val repoRelative = File("translate/src/main/res/xml/data_extraction_rules.xml")+        if (repoRelative.isFile) return repoRelative+        error("data_extraction_rules.xml not found from ${File(".").absolutePath}")+    }++    private fun sectionRules(+        rules: Element,+        section: String,+    ): Set<Pair<String, String>> {+        val result = mutableSetOf<Pair<String, String>>()+        val sections = rules.getElementsByTagName(section)+        for (i in 0 until sections.length) {+            val node = sections.item(i) as Element+            val children = node.childNodes+            for (j in 0 until children.length) {+                val child = children.item(j)+                if (child is Element) {+                    result += child.tagName to "${child.getAttribute("domain")}/${child.getAttribute("path")}"+                }+            }+        }+        return result+    }++    @Test+    fun `manifest allows backup and declares the codec agent`() {+        val info = context.packageManager.getApplicationInfo(context.packageName, 0)+        assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0)+        assertEquals(+            "com.vayunmathur.translate.platform.AppBackupAgent",+            info.backupAgentName,+        )++        val agent = AppBackupAgent()+        assertTrue(agent.dbCodec === SqlCipherDbCodec)+        assertEquals(listOf("translate_settings"), agent.datastoreNames)+    }++    @Test+    fun `db configs pair the translate database with its live passphrase`() {+        val repo = TranslateRepository.get(context)+        runDb { repo.record("wiring-check", "revisar", "en", "es") }++        val configs = translateDbConfigs(context)+        assertEquals(1, configs.size)+        assertEquals(TRANSLATE_DB_NAME, configs.single().first)+        assertEquals(DatabaseHelper(context).getPassphrase(), configs.single().second)++        // Restore target: no key minted yet, so reading the config must mint+        // one the fresh database can actually be encrypted under.+        DatabaseHelper(context).deleteKey()+        val minted = translateDbConfigs(context)+        assertTrue(minted.single().second.isNotBlank())+        assertEquals(DatabaseHelper(context).getPassphrase(), minted.single().second)+    }++    @Test+    fun `extraction rules never carry the raw database key or models`() {+        val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rulesFile())+        val root = document.documentElement++        for (section in listOf("cloud-backup", "device-transfer")) {+            val rules = sectionRules(root, section)+            for (suffix in listOf("", "-wal", "-shm", "-journal")) {+                assertTrue(+                    "exclude" to "database/translate-db$suffix" in rules,+                    "$section must exclude translate-db$suffix: $rules",+                )+            }+            assertTrue("exclude" to "sharedpref/secure_prefs.xml" in rules, "$section: $rules")+            for (modelDir in listOf("nllb600", "madlad400", "small100")) {+                assertTrue(+                    "exclude" to "external/$modelDir" in rules,+                    "$section must exclude $modelDir: $rules",+                )+            }+            assertTrue("include" to "file/." in rules, "$section carries settings files: $rules")+            assertTrue(+                (rules.none { it == "include" to "database/translate-db" }),+                "$section must not include the raw DB: $rules",+            )+        }+        val cloud = root.getElementsByTagName("cloud-backup").item(0) as Element+        assertEquals("true", cloud.getAttribute("disableIfNoEncryptionCapabilities"))+    }++    @Test+    fun `agent round trip preserves history favourites and settings`() {+        // Robolectric sandboxes are per method but the repository singleton+        // is static, so an earlier method in this class may have left one+        // bound to its own sandbox. Drop it and seed through a fresh one.+        closeAndResetRepository()+        val repo = TranslateRepository.get(context)+        runDb {+            repo.clearHistory()+            repo.record("hello", "hola", "en", "es")+            repo.record("goodbye", "adios", "en", "es")+        }+        val seeded =+            pollDb({ repo.history.first() }) { rows ->+                rows.any { it.sourceText == "hello" } && rows.any { it.sourceText == "goodbye" }+            }+        val hello = seeded.single { it.sourceText == "hello" }+        runDb { repo.setFavorite(hello.id, true) }+        runBlocking {+            val settings = TranslateSettings(context)+            settings.setSource("fr")+            settings.setTarget("de")+        }+        val settingsFile = File(context.filesDir, "datastore/translate_settings.preferences_pb")+        assertTrue(settingsFile.isFile)+        val settingsBytes = settingsFile.readBytes()++        // The codec contract requires the live DB closed before import/export.+        closeAndResetRepository()++        val agent = HostAgent().apply { attach(context) }+        val output = BackupDataOutputFactory.newInstance()+        val backupState = File(context.cacheDir, "translate-backup-state.bin").apply { delete() }+        agent.onBackup(null, output, pfd(backupState))+        val entities = Shadows.shadowOf(output).entities+        assertEquals(1, entities.size)+        val entity = entities.single()+        assertEquals("full_backup", entity.key())++        val entryNames =+            ZipInputStream(ByteArrayInputStream(entity.data())).use { zip ->+                buildList {+                    var entry = zip.nextEntry+                    while (entry != null) {+                        add(entry.name)+                        entry = zip.nextEntry+                    }+                }+            }+        assertTrue("translate-db.db" in entryNames, "backup zip entries: $entryNames")+        assertTrue("translate_settings.preferences_pb" in entryNames, "backup zip entries: $entryNames")++        // Wipe everything the backup is supposed to bring back.+        val dbFile = context.getDatabasePath(TRANSLATE_DB_NAME)+        dbFile.delete()+        File("${dbFile.path}-wal").delete()+        File("${dbFile.path}-shm").delete()+        File("${dbFile.path}-journal").delete()+        settingsFile.delete()+        assertTrue(!dbFile.exists() && !settingsFile.exists())++        val input =+            BackupDataInputBuilder+                .newBuilder()+                .addEntity(BackupDataEntity.create("unrelated_key", "junk"))+                .addEntity(entity)+                .build()+        val restoreState = File(context.cacheDir, "translate-restore-state.bin").apply { delete() }+        agent.onRestore(input, 1, pfd(restoreState))++        assertTrue(dbFile.isFile)+        assertTrue(settingsFile.isFile)+        assertTrue(settingsBytes.contentEquals(settingsFile.readBytes()))++        // The production import leaves an encrypted DB the repository opens+        // natively; the host stand-in leaves the plaintext bytes the shadow+        // driver wrote, so rows are read back with plain SQLite here instead+        // of rebuilding the repository (whose encrypt-existing step is the+        // native hop this host cannot run).+        assertTrue(dbFile.isFile && dbFile.length() > 0)+        val rows =+            android.database.sqlite.SQLiteDatabase+                .openDatabase(dbFile.path, null, android.database.sqlite.SQLiteDatabase.OPEN_READONLY)+            .use { sqlite ->+                sqlite.rawQuery(+                    "SELECT sourceText, translatedText, isFavorite FROM TranslationRecord",+                    null,+                ).use { cursor ->+                    buildList {+                        while (cursor.moveToNext()) {+                            add(Triple(cursor.getString(0), cursor.getString(1), cursor.getInt(2)))+                        }+                    }+                }+            }+        val restoredHello = rows.single { it.first == "hello" }+        assertEquals("hola", restoredHello.second)+        assertEquals(1, restoredHello.third)+        assertNotNull(rows.singleOrNull { it.first == "goodbye" })+    }++    companion object {+        @BeforeClass+        @JvmStatic+        fun installFakeKeyStore() = FakeAndroidKeyStore.install()+    }+}