Modern Apps git

← Modern-Apps.git

library/downloadservice: a complete .part at a 416 finalizes instead of wedging forever

Commit
d479d877790ec6dc412b8675603c181d93420f2f
Author
Vayun Mathur <[email protected]>
When
2026-12-01 10:08 UTC (5 days ago)
Parents
e59c148
The resume path handled only 206 (append) and 200 (restart).
When a .part already held the whole body — size pinned but
the process died before verify/finalize, or the server file
shrank — the next run sent Range: bytes=L-, the server
correctly replied 416, and the code threw IOException. None
of the catches deletes that .part (they deliberately keep it
'for resume'), so every retry re-asked the same
unsatisfiable range: after the downloader's attempts and the
worker retries, only clearing app data could recover. No
path ever deleted or completed that .part.

streamToPart now interprets 416: if the .part already holds
the whole body (length equals the 416 Content-Range total
when present, plus the spec's pinned size and SHA-256
checks; no evidence means no), it returns and the caller's
verify-and-finalize promotes it; if oversized/corrupt/short
it deletes the .part and fails the attempt so the retry
restarts from offset 0. Three regression tests cover the
pinned-complete, unpinned-via-total, and oversized paths.
Cancellation, concurrency and integrity gates were audited
and cleared. Verified: :library:downloadservice:
testDebugUnitTest 61 tests pass; lint BUILD SUCCESSFUL.

Diff

library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.ktindex 748be0b967..8d9461e9ac 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt@@ -301,6 +301,9 @@ private const val BITS_PER_BYTE = 8.0 private const val CONNECT_TIMEOUT_MS = 30_000 private const val READ_TIMEOUT_MS = 30_000 +/** Range unsatisfiable: the requested offset is at or past the body's end. */+private const val HTTP_RANGE_NOT_SATISFIABLE = 416+ private const val TAG = "ModelDownload"  /**@@ -427,7 +430,12 @@ private suspend fun downloadSpec( /**  * Streams [spec] from the network into [partFile]. Resumes an existing partial  * with a `Range` request, appending on HTTP 206 and restarting (truncating) on- * 200. Publishes throttled `progress_*` / `speed_*` while streaming.+ * 200. A 416 means the offset is at or past the body's end: a partial that+ * already holds the whole body (a run stopped after the last byte but before+ * finalizing) is left for the caller's verify-and-finalize, while any other+ * partial is discarded so the retry restarts from scratch instead of asking+ * for the same unsatisfiable range forever. Publishes throttled+ * `progress_*` / `speed_*` while streaming.  */ @Suppress("CyclomaticComplexMethod", "LongMethod", "NestedBlockDepth") private suspend fun streamToPart(@@ -456,6 +464,16 @@ private suspend fun streamToPart(                 startOffset = 0L                 false             }+            HTTP_RANGE_NOT_SATISFIABLE -> {+                // The resume offset is at/past the end of the body. If the+                // partial already holds the whole body (and verifies), there+                // is nothing to stream: return so the caller finalizes it.+                // Otherwise it can never satisfy a Range request again, so+                // drop it and fail this attempt; the retry restarts clean.+                if (partAlreadyComplete(conn, spec, partFile)) return+                partFile.delete()+                throw IOException("Range not satisfiable for ${spec.url}; partial discarded")+            }             else -> throw IOException("Unexpected HTTP $code for ${spec.url}")         }         // contentLengthLong is the *remaining* bytes; add the resume offset for the total.@@ -475,6 +493,26 @@ private suspend fun streamToPart(     } } +/**+ * True when a 416'd [partFile] already holds the server's whole body: its+ * length matches the total in the 416's `Content-Range` header+ * (when the server sends one) and it passes the spec's pinned size/SHA-256+ * checks. With neither a server total nor any pin there is no evidence the+ * partial is exactly the body, so this returns false and the caller drops+ * the partial and refetches.+ */+private fun partAlreadyComplete(+    conn: HttpURLConnection,+    spec: DownloadSpec,+    partFile: File,+): Boolean {+    val rangeTotal = conn.getHeaderField("Content-Range")+        ?.substringAfterLast('/')?.trim()?.toLongOrNull()+    if (rangeTotal != null && partFile.length() != rangeTotal) return false+    if (rangeTotal == null && spec.expectedBytes == null && spec.sha256 == null) return false+    return sizeOk(partFile, spec.expectedBytes) && checksumOk(partFile, spec.sha256)+}+ /** Publishes the resume offset as initial progress before streaming starts. */ private suspend fun publishInitialProgress(     ds: DataStoreUtils,
library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.kt
diff --git a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.kt b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.ktindex ab343a0437..29040d2239 100644--- a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.kt+++ b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.kt@@ -176,4 +176,99 @@ class DownloadEdgeTest {             server.stop(0)         }     }++    /** RFC 7233 server: 416 (with the total) for a range starting at/past the end. */+    private fun rangeStrictServer(payload: ByteArray, hits: AtomicInteger): HttpServer {+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange ->+            hits.incrementAndGet()+            val range = exchange.requestHeaders.getFirst("Range")+            val start = range?.removePrefix("bytes=")?.removeSuffix("-")?.toIntOrNull()+            when {+                start != null && start >= payload.size -> {+                    exchange.responseHeaders.set("Content-Range", "bytes */${payload.size}")+                    exchange.sendResponseHeaders(416, -1)+                    exchange.close()+                }+                start != null -> {+                    val rest = payload.copyOfRange(start, payload.size)+                    exchange.responseHeaders.set(+                        "Content-Range",+                        "bytes $start-${payload.size - 1}/${payload.size}",+                    )+                    exchange.sendResponseHeaders(206, rest.size.toLong())+                    exchange.responseBody.use { it.write(rest) }+                }+                else -> {+                    exchange.sendResponseHeaders(200, payload.size.toLong())+                    exchange.responseBody.use { it.write(payload) }+                }+            }+        }+        server.start()+        return server+    }++    @Test+    fun completePartSurvives416AndFinalizes() = runBlocking<Unit> {+        val payload = ByteArray(3_000) { (it % 251).toByte() }+        val hits = AtomicInteger(0)+        val server = rangeStrictServer(payload, hits)+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_416_done").toFile()+            // A run stopped after the last byte but before finalize left this.+            File(dir, "done.bin.part").writeBytes(payload)+            val spec = DownloadSpec(+                fileName = "done.bin", description = "Done",+                url = "http://127.0.0.1:${server.address.port}/done.bin",+                sha256 = sha256(payload), expectedBytes = payload.size.toLong(),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "done.bin").readBytes().contentEquals(payload))+            assertEquals(1, hits.get())+        } finally {+            server.stop(0)+        }+    }++    @Test+    fun unpinnedCompletePartUses416Total() = runBlocking<Unit> {+        val payload = "whole-body".toByteArray()+        val hits = AtomicInteger(0)+        val server = rangeStrictServer(payload, hits)+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_416_unpinned").toFile()+            File(dir, "plain.bin.part").writeBytes(payload)+            val spec = DownloadSpec(+                fileName = "plain.bin", description = "Plain",+                url = "http://127.0.0.1:${server.address.port}/plain.bin",+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "plain.bin").readBytes().contentEquals(payload))+            assertEquals(1, hits.get())+        } finally {+            server.stop(0)+        }+    }++    @Test+    fun oversizedPartIsDiscardedAfter416AndRedownloaded() = runBlocking<Unit> {+        val payload = "right-sized".toByteArray()+        val hits = AtomicInteger(0)+        val server = rangeStrictServer(payload, hits)+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_416_over").toFile()+            File(dir, "over.bin.part").writeBytes(payload + "junk".toByteArray())+            val spec = DownloadSpec(+                fileName = "over.bin", description = "Over",+                url = "http://127.0.0.1:${server.address.port}/over.bin",+                sha256 = sha256(payload), expectedBytes = payload.size.toLong(),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "over.bin").readBytes().contentEquals(payload))+            assertEquals(2, hits.get())+        } finally {+            server.stop(0)+        }+    } }