Modern Apps git

← Modern-Apps.git

backup: SAF overwrite is staged so a failed write keeps the old blob

Commit
0bd6d53155ff3a6c09e36dee6fbb963d87435286
Author
Vayun Mathur <[email protected]>
When
2026-11-30 19:25 UTC (5 days ago)
Parents
ae96444
SafBackend.write opened the destination with mode 'wt' (truncate)
before running the writer, so any mid-write failure — a stream
dying during encryption, a full disk — destroyed the previous good
backup blob and left truncated ciphertext where it was. Callers
were written assuming the old blob survives a failed write (the
manifest keeps the previous entry precisely so it stays
restorable), so one failed run could silently lose app-data
backups or corrupt files/index.json and orphan every blob.
WebDAV and the test backend already buffered fully; SAF was the
outlier.

Writes now stage into a hidden .tmp- sibling and commit only once
the writer completes (renameDocument, with a copy fallback for
providers that cannot rename). A writer failure deletes staging
and rethrows with the previous blob byte-for-byte intact; list()
filters staging names so a kill-orphaned staging file is never
mistaken for a blob, and stale staging is cleared on the next
write to that path. Two regression tests cover failed-overwrite
preservation and failed-first-write cleanliness; the fake SAF
provider gained renameDocument so the commit path is exercised.
Verified: :backup:testDevUnitTest 73 tests pass; the one lint
error is pre-existing on untouched Route.kt.

Diff

backup/AGENTS.md
diff --git a/backup/AGENTS.md b/backup/AGENTS.mdindex b2b21470f9..de01781b23 100644--- a/backup/AGENTS.md+++ b/backup/AGENTS.md@@ -22,6 +22,7 @@ _Install: ./install backup (dev by default)._ - Onboarding ends when the ViewModel has key + destination, not via navigation — the stack follows the flag - Media-permission grant funnels straight into `backupFilesNow()` - Internet is used only for WebDAV remotes; everything else is offline+- SAF blob writes are staged to a hidden `.tmp-` sibling and committed by rename (copy fallback when a provider cannot rename); a failed writer leaves the previous blob intact, and staging names never appear in `list()`  ## Why this is the reference (copy this, not others) **Copy-this checklist:**
backup/src/main/java/com/vayunmathur/backup/data/backend/SafBackend.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/data/backend/SafBackend.kt b/backup/src/main/java/com/vayunmathur/backup/data/backend/SafBackend.ktindex 66811d94a9..e9badab538 100644--- a/backup/src/main/java/com/vayunmathur/backup/data/backend/SafBackend.kt+++ b/backup/src/main/java/com/vayunmathur/backup/data/backend/SafBackend.kt@@ -16,6 +16,12 @@ import java.io.OutputStream  * `ACTION_OPEN_DOCUMENT_TREE` and persisted with a takePersistableUriPermission  * grant. Paths map to a directory/file hierarchy under the tree, addressed through  * [DocumentsContract] (no androidx.documentfile dependency).+ *+ * Writes are staged: the new blob is written to a hidden sibling staging file+ * and only then replaces the previous blob (rename, with a copy fallback for+ * providers without rename support). A writer that fails midway — a media+ * stream dying during encryption, a full disk — therefore leaves the previous+ * good blob intact instead of a truncated file the manifest still points at.  */ class SafBackend(     private val context: Context,@@ -39,17 +45,50 @@ class SafBackend(             val name = segments.last()             val parent = resolveDir(segments.dropLast(1), create = true)                 ?: throw IOException("cannot create parent of: $path")-            val existing = findChild(parent, name)-            val fileUri = if (existing != null) {-                docUri(existing.docId)-            } else {-                DocumentsContract.createDocument(resolver, docUri(parent), MIME_OCTET, name)-                    ?: throw IOException("cannot create file: $path")+            // Stage into a hidden sibling: opening the destination with "wt"+            // truncates it before the writer runs, so a mid-write failure+            // would destroy the previous good blob (the exact failure the+            // manifest-preservation logic in FileBackupManager assumes cannot+            // happen). The destination is only touched once staging is whole.+            val stagingName = stagingName(name)+            findChild(parent, stagingName)?.let { stale ->+                runCatching { DocumentsContract.deleteDocument(resolver, docUri(stale.docId)) }             }-            val out = openOutput(fileUri) ?: throw IOException("cannot open for write: $path")-            out.use { writer(it) }+            val stagingUri = DocumentsContract.createDocument(resolver, docUri(parent), MIME_OCTET, stagingName)+                ?: throw IOException("cannot create file: $path")+            val stagingDocId = DocumentsContract.getDocumentId(stagingUri)+            try {+                val out = openOutput(stagingUri) ?: throw IOException("cannot open for write: $path")+                out.use { writer(it) }+            } catch (t: Throwable) {+                runCatching { DocumentsContract.deleteDocument(resolver, docUri(stagingDocId)) }+                throw t+            }+            commitStaged(parent, name, stagingDocId, path)         } +    /** Replaces [name] under [parent] with the fully written staging file. */+    private fun commitStaged(parent: String, name: String, stagingDocId: String, path: String) {+        val renamed = runCatching {+            findChild(parent, name)?.let {+                DocumentsContract.deleteDocument(resolver, docUri(it.docId))+            }+            DocumentsContract.renameDocument(resolver, docUri(stagingDocId), name)+        }.getOrNull()+        if (renamed != null) return+        // Provider cannot rename (or refuses this name): the staged blob is+        // complete, so copy it over the destination and drop staging. This+        // still keeps writer failures from ever touching the destination.+        val destUri = findChild(parent, name)?.let { docUri(it.docId) }+            ?: DocumentsContract.createDocument(resolver, docUri(parent), MIME_OCTET, name)+            ?: throw IOException("cannot commit file: $path")+        val input = resolver.openInputStream(docUri(stagingDocId))+            ?: throw IOException("cannot read staged file: $path")+        val out = openOutput(destUri) ?: throw IOException("cannot open for write: $path")+        input.use { inp -> out.use { inp.copyTo(it) } }+        runCatching { DocumentsContract.deleteDocument(resolver, docUri(stagingDocId)) }+    }+     override suspend fun <T> read(path: String, reader: suspend (InputStream) -> T): T =         withContext(Dispatchers.IO) {             val docId = resolveFile(path) ?: throw FileNotFoundException(path)@@ -65,7 +104,13 @@ class SafBackend(                 childrenUri(parent),                 arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME),                 null, null, null,-            )?.use { c -> while (c.moveToNext()) add(c.getString(0)) }+            )?.use { c ->+                while (c.moveToNext()) {+                    val childName = c.getString(0)+                    // Staging files are an internal write detail, never blobs.+                    if (!isStagingName(childName)) add(childName)+                }+            }         }     } @@ -147,8 +192,13 @@ class SafBackend(     private fun segments(path: String): List<String> =         path.split('/').filter { it.isNotEmpty() } +    private fun stagingName(name: String): String = "$STAGING_PREFIX$name"++    private fun isStagingName(name: String): Boolean = name.startsWith(STAGING_PREFIX)+     /** MIME type used when creating backup blobs in the SAF tree. */     companion object {         private const val MIME_OCTET = "application/octet-stream"+        private const val STAGING_PREFIX = ".tmp-"     } }
backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.kt b/backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.ktindex 77541c14bd..4b440d91aa 100644--- a/backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.kt+++ b/backup/src/test/java/com/vayunmathur/backup/FakeDocumentsProvider.kt@@ -84,6 +84,14 @@ class FakeDocumentsProvider : DocumentsProvider() {         if (f.isDirectory) f.deleteRecursively() else f.delete()     } +    override fun renameDocument(documentId: String, displayName: String): String {+        val src = file(documentId)+        if (!src.exists()) throw FileNotFoundException(documentId)+        val dst = File(src.parentFile, displayName)+        check(src.renameTo(dst)) { "rename $documentId to $displayName failed" }+        return docId(dst)+    }+     override fun openDocument(documentId: String, mode: String, signal: CancellationSignal?): ParcelFileDescriptor {         val f = file(documentId)         if (!f.exists() && mode.contains("w")) { f.parentFile?.mkdirs(); f.createNewFile() }
backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.ktindex 7778f3ebd2..7d6e630949 100644--- a/backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.kt+++ b/backup/src/test/java/com/vayunmathur/backup/data/backend/SafBackendTest.kt@@ -88,6 +88,34 @@ class SafBackendTest {         assertEquals(3, File(root, "kv/com.example/k2").length().toInt())     } +    @Test fun failedOverwritePreservesPreviousBlob() = runBlocking<Unit> {+        backend.save("files/abc", "previous-good-blob".toByteArray())+        // A writer that emits partial bytes then fails (a media stream dying+        // during encryption, a full disk) must not truncate the blob the+        // manifest still points at.+        assertFailsWith<java.io.IOException> {+            backend.write("files/abc") {+                it.write("partial".toByteArray())+                throw java.io.IOException("simulated mid-write failure")+            }+        }+        assertEquals("previous-good-blob", backend.load("files/abc").decodeToString())+        assertEquals(listOf("abc"), backend.list("files"))+        assertFalse(File(root, "files/.tmp-abc").exists())+    }++    @Test fun failedFirstWriteLeavesNoBlobOrStaging() = runBlocking<Unit> {+        assertFailsWith<java.io.IOException> {+            backend.write("files/new") {+                it.write("partial".toByteArray())+                throw java.io.IOException("simulated mid-write failure")+            }+        }+        assertFalse(backend.exists("files/new"))+        assertEquals(emptyList(), backend.list("files"))+        assertFalse(File(root, "files/.tmp-new").exists())+    }+     @Test fun ensureDirBlockedByFile() = runBlocking<Unit> {         backend.save("blocker", "x".toByteArray())         assertFailsWith<Exception> { backend.ensureDir("blocker/sub") }