Repository navigation
Description
Before you submit
- This isn't a request to support a specific video or social media site, or to bypass DRM.
Issue type
Bug report
Description
I believe simultaneous Wi-Fi + mobile data downloads are unreliable on Android(tried on Android 16 hyper os). I used Claude to review the code for root causes; the findings are from static analysis and still need verification.
Wi-Fi + Mobile Data multi-network downloads are unreliable on Android (cellular not retained, stale network IDs, speed-blind dispatch)
Summary
Selecting Wi-Fi and Mobile data in Settings → Network does not reliably spread one download over both links. Static review of ca3b660 shows that the Android app never asks Android to keep a cellular network up, discovery is a one-time snapshot keyed by networkHandle, nothing rebinds after a reconnect, and dispatch is a speed-blind round-robin. Device reproduction is still pending.
Environment
- Android 16 (API 36); HyperOS 3 also reported (not verified in code)
- Ketch commit
ca3b6601a137dc35b4e1b2a8c52354042273dc75 - Phone with Wi-Fi (2.4 GHz) and 5G mobile data
- Ketch app version:
Findings
F1. Cellular is never requested or retained
- The manifest declares only
INTERNETandACCESS_NETWORK_STATE;CHANGE_NETWORK_STATEis absent:Ketch/app/android/src/main/AndroidManifest.xml
Lines 4 to 22 in ca3b660
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /> <!-- Android 16 gates the local network with this one; Android 17 with ACCESS_LOCAL_NETWORK. --> <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:maxSdkVersion="36" /> <!-- Other devices, sharing and mDNS on the LAN; downloads from LAN hosts too. --> <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- Android 16 shows a single download as a progress chip in the status bar. --> <uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" /> - There is no
requestNetworkorNetworkRequestforTRANSPORT_CELLULARanywhere. The engine states that it does not retain networks and leaves that to the app:and #L29Ketch/library/ktor/src/androidMain/kotlin/com/linroid/ketch/engine/ConfigurableNetworks.android.kt
Lines 14 to 15 in ca3b660
* Requires INTERNET and ACCESS_NETWORK_STATE permissions. Does not request or retain networks; * the app owns ConnectivityManager callbacks when keeping a non-default network alive is needed. - The service wires the engine with no request: . The only callback is a default-network observer for upload metering:
Ketch/app/android/src/main/kotlin/com/linroid/ketch/app/android/KetchService.kt
Lines 211 to 213 in ca3b660
val httpEngine = KtorHttpEngine.withNetworkInterfaces( getSystemService(ConnectivityManager::class.java) ) Ketch/app/shared/src/androidMain/kotlin/com/linroid/ketch/app/instance/UnmeteredNetwork.android.kt
Line 33 in ca3b660
connectivity.registerDefaultNetworkCallback(callback) - Expected effect: "Mobile data" is missing from Settings while Wi-Fi is the default, or selection succeeds and then the link is unusable.
F2. Discovery is a one-time snapshot with weak filtering
manager.allNetworks(deprecated since API 31):and #L38Ketch/library/ktor/src/androidMain/kotlin/com/linroid/ketch/engine/ConfigurableNetworks.android.kt
Line 30 in ca3b660
@Suppress("DEPRECATION") - Filtered only on
NET_CAPABILITY_INTERNET(#L40).NET_CAPABILITY_VALIDATEDis never checked (see also #L63-L65), so captive or no-internet Wi-Fi can be selected. - Refreshed only when Settings opens: . No
Ketch/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/settings/NetworkSettings.kt
Line 42 in ca3b660
LaunchedEffect(controller) { controller.loadNetworks() } NetworkCallbackfeeds the list.
F3. Network IDs rotate; nothing rebinds
- ID =
network.networkHandle.toString()(), which the KDoc says is valid only for the network's lifetime (#L16).Ketch/library/ktor/src/androidMain/kotlin/com/linroid/ketch/engine/ConfigurableNetworks.android.kt
Line 45 in ca3b660
id = network.networkHandle.toString(), - Each engine is bound to one fixed
Network(). The generation is replaced only by select or close (Ketch/library/ktor/src/androidMain/kotlin/com/linroid/ketch/engine/AndroidTransports.kt
Lines 67 to 75 in ca3b660
private class NetworkBinding(private val network: Network) : SocketBinding { override val socketFactory: SocketFactory = network.socketFactory override fun prepare(socket: Socket) { network.bindSocket(socket) } override fun lookup(host: String): List<InetAddress> = network.getAllByName(host).toList() } , #L42-L73, #L110-L121).Lines 25 to 29 in ca3b660
class ConfigurableNetworkHttpEngine(private val provider: NetworkInterfaceProvider) : HttpEngine { private val updates = Mutex() private val current = AtomicReference<Generation?>( Generation(provider.createDefaultEngine(), NetworkInterfaceConfig()) ) - After a reconnect, requests on that engine fail, and re-selecting the old ID fails with "Unknown or unavailable interface" (ConfigurableNetworkHttpEngine.kt#L48-L50; ConfigurableNetworks.android.kt#L57-L59).
- Stale chips stay in the UI, named by the raw handle (;
Ketch/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/settings/NetworkSettings.kt
Lines 60 to 62 in ca3b660
// Keep selected interfaces that went away visible so they can be unticked. val missing = selected.filter { it !in available } .map { NetworkInterfaceInfo(id = it, name = it, addresses = emptyList()) } ). Recovery requires manual untick and re-tick.Ketch/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/devices/DeviceText.kt
Line 213 in ca3b660
val selected = networks.config.interfaceIds.map { names[it] ?: it } - Adding a new cellular ID while the old one is still selected also fails, because every selected ID is validated (ConfigurableNetworkHttpEngine.kt#L48-L50).
F4. Selection is not persisted
- Runtime-only per and
Line 1992 in ca3b660
The network selection is runtime-only and never saved. BitTorrent settings go through Ketch/docs/multiple-networks.md
Line 16 in ca3b660
- The selection is not saved: it resets when the device's Ketch restarts. - The service loads no network config (KetchService.kt#L211-L213); the engine starts from an empty config (ConfigurableNetworkHttpEngine.kt#L27-L29). The service is
START_STICKY(), so a restart silently returns to system-default routing.return START_STICKY - The UI copy says the choice "lasts until the device restarts" (), while the docs say it resets when Ketch restarts. These should match.
Ketch/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/settings/NetworkSettings.kt
Lines 33 to 36 in ca3b660
/** * The networks [device] spreads its HTTP requests over, as chips: the system's default * connection, or any set of its interfaces. The choice applies at once and lasts until the * device restarts. Below them, the proxy those requests go through ([ProxySettings]).
F5. Dispatch is speed-blind round-robin shared by all requests
nextEngine()is a global atomic round-robin (). HEAD and probe requests take turns too (#L34-L46).Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/engine/MultiNetworkHttpEngine.kt
Lines 68 to 75 in ca3b660
private fun nextEngine(): HttpEngine { while (true) { val index = nextIndex.load() check(index >= 0) { "Network engines are closed" } val next = if (index == engines.lastIndex) 0 else index + 1 if (nextIndex.compareAndSet(index, next)) return engines[index] } } - Docs: "balances requests, not speed" ().
Ketch/docs/multiple-networks.md
Lines 24 to 25 in ca3b660
- **It balances requests, not speed.** Requests are spread round-robin across all downloads and the metadata requests before them. Ketch does not bond connections or measure each network's speed. - Byte ranges are split equally with 4 default connections (;
val maxConnectionsPerDownload: Int = 4, ;Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/segment/SegmentCalculator.kt
Lines 17 to 41 in ca3b660
fun calculateSegments(totalBytes: Long, connections: Int): List<Segment> { require(totalBytes > 0) { "totalBytes must be positive" } require(connections > 0) { "connections must be positive" } val effectiveConnections = minOf(connections.toLong(), totalBytes.coerceAtLeast(1)).toInt() log.d { "Calculating segments: totalBytes=$totalBytes," + " connections=$connections, effective=$effectiveConnections" } val segmentSize = totalBytes / effectiveConnections val remainder = totalBytes % effectiveConnections return (0 until effectiveConnections).map { index -> val start = index * segmentSize + minOf(index.toLong(), remainder) val extraByte = if (index < remainder) 1L else 0L val end = start + segmentSize - 1 + extraByte Segment( index = index, start = start, end = end, downloadedBytes = 0, ) } ). Result: two requests per link regardless of link speed.Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/engine/HttpDownloadSource.kt
Line 86 in ca3b660
maxSegments = if (serverInfo.supportsResume) config.maxConnectionsPerDownload else 1,
F6. Stolen tails and retries are not pinned to their link
- The ledger measures per-lane rates and steals slow tails (and #L320-L340).
Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/segment/SegmentLane.kt
Lines 255 to 306 in ca3b660
private fun takeOver(thief: SegmentLane, thiefRate: Double?): Steal? { // A lane nobody started goes to the first connection free, whatever it received last, as no // other connection would start it. lanes.firstOrNull { it.waiting }?.let { lane -> lane.waiting = false restart(lane) return Steal(lane, lane, victimIdle = false) } // A connection that received nothing in its last lane takes nothing, not even a failed // connection's bytes, which then wait for their own connection to retry. if (thiefRate != null && thiefRate <= 0.0) return null lanes.firstOrNull { it.released }?.let { orphan -> // A failed connection's bytes go whole to the first connection free to take them. val lane = SegmentLane(this, orphan.cursor, orphan.cursor, orphan.limit, timeSource.markNow()) orphan.released = false orphan.limit = orphan.cursor // Nothing written: the new lane replaces it rather than leave an empty range. if (orphan.cursor == orphan.start) lanes.remove(orphan) lanes += lane return Steal(lane, orphan, victimIdle = false) } if (minSplitBytes == Long.MAX_VALUE) return null val candidates = lanes.filter { it !== thief && it.limit - it.admitted >= minSplitBytes } if (candidates.isEmpty()) return null val rates = candidates.associateWith { rateOf(it) } val known = rates.values.filterNotNull().sorted() val typical = thiefRate ?: known.getOrNull(known.size / 2) // Expected time to finish, or bytes left while no rate is known. val ordered = candidates.sortedByDescending { lane -> val left = (lane.limit - lane.admitted).toDouble() val rate = rates[lane] ?: typical when { rate == null -> left rate <= 0.0 -> Double.POSITIVE_INFINITY else -> left / rate } } for (victim in ordered) { val left = victim.limit - victim.admitted val keep = keepFor(left, rates[victim], thiefRate) ?: continue if (left - keep < minSplitBytes) continue val split = victim.admitted + keep val lane = SegmentLane(this, split, split, victim.limit, timeSource.markNow()) victim.limit = split victim.cut = true // A victim left with no byte at all is replaced rather than kept as an empty range, which // would be saved as a segment ending before it starts. if (split == victim.start) lanes -= victim lanes += lane val idle = victim.cursor == victim.admitted && victim.cursor >= victim.limit return Steal(lane, victim, idle) } - A stolen tail is a new request.
runConnectioncallsdownloadSegment(lane)again (and #L309-L317). That reachesKetch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/segment/SegmentedDownloadHelper.kt
Lines 263 to 288 in ca3b660
} catch (e: KetchError) { if (!retriesAlone || !e.isRetryable || (e is KetchError.Http && e.code == 429)) throw e if (lane.laneBytes > 0) retries = 0 // Read before the release: a connection may take the released bytes, finish them and end // before this one reads the count again. val ended = ledger.ended.value if (!policy.allows(retries) || !ledger.release(lane)) throw e retries++ val delayMs = policy.delayMs(retries) log.w { "Range ${lane.offset}..${lane.end} failed for taskId=${context.taskId}, " + "retrying the connection in ${delayMs}ms: ${e.describeCauses()}" } context.segments.value = ledger.snapshot() // Stop waiting once another connection took this lane and one ended for lack of work: // none is left for this one. withTimeoutOrNull(delayMs) { ledger.ended.first { it > ended && !lane.released } } val steal = ledger.rejoin(lane) ?: return if (steal.victimIdle) steal.victim.transfer?.cancel(LaneDrainedException()) if (steal.lane !== lane) { log.d { "Taking over ${steal.lane.start}..${steal.lane.end} instead of the range at " + "${lane.start} for taskId=${context.taskId}" } } lane = steal.lane SegmentDownloader.kt#L44, thenMultiNetworkHttpEngine.download(), which is round-robin. A fast-link connection can be handed a slow-link range, and its rate is measured on the wrong network.Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/engine/MultiNetworkHttpEngine.kt
Lines 54 to 61 in ca3b660
override suspend fun download( url: String, range: LongRange?, headers: Map<String, String>, onData: suspend (ByteArray) -> Unit, ) { nextEngine().download(url, range, headers, onData) } keepFor(SegmentLane.kt#L320-L333) assumes the thief keeps its own link's speed, which this breaks.
F7. No failover or circuit breaker
- Failed requests are not replayed inside the engine (MultiNetworkHttpEngine.kt#L13). A dead link keeps receiving about half the requests until the user re-selects (docs L27–L29).
- Retries default to 3 (); give-up path at
val retryCount: Int = 3, . Stalled transfers trip the 60 s idle watchdog (DownloadConfig.kt#L46;Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/engine/DownloadExecution.kt
Lines 1001 to 1008 in ca3b660
if (!error.isRetryable || !policy.allows(retryCount)) { // DownloadCoordinator logs the failure itself, an unknown one with its stack trace. log.i { if (error.isRetryable) "Giving up on taskId=$taskId after $retryCount retries" else "Not retrying taskId=$taskId: ${error::class.simpleName} is not retryable" } throw error } ).Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/engine/TransferWatchdog.kt
Lines 94 to 96 in ca3b660
if (idleTimeout.isPositive() && idle >= idleTimeout) { throw TransferStalledException("No data received for $idleTimeout") }
F8. Connection count ignores how many networks are selected
- Connections come from
maxConnectionsor the default of 4 (; HttpDownloadSource.kt#L494-L506).Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/engine/DownloadContext.kt
Lines 137 to 138 in ca3b660
fun effectiveConnections(requested: Int): Int = if (requested > 0) requested else config.maxConnectionsPerDownload - With one connection, only engine index 0 is used (MultiNetworkHttpEngine.kt#L68-L72). Index 0 is the first selected network (ConfigurableNetworkHttpEngine.kt#L48-L56), so the other link is never used.
F9. Proxy handling
- Per-network proxy comes from LinkProperties. A PAC URL silently returns Direct (, PAC branch at #L54-L55).
Ketch/library/ktor/src/androidMain/kotlin/com/linroid/ketch/engine/AndroidTransports.kt
Lines 51 to 63 in ca3b660
private fun networkRoute(network: Network, url: Url): ProxyRoute { val info = connectivity?.getLinkProperties(network)?.httpProxy ?: return ProxyRoute.Direct val host = info.host if (info.pacFileUrl != Uri.EMPTY || host.isNullOrEmpty() || info.port <= 0) { return ProxyRoute.Direct } val bypass = info.exclusionList.filter(ProxyBypass::isValid) return if (ProxyBypass.bypasses(bypass, url.host)) { ProxyRoute.Direct } else { ProxyRoute.Http(host, info.port) } } forNetwork(...)without a ConnectivityManager returns Direct (AndroidTransports.kt#L52;).Ketch/library/ktor/src/androidMain/kotlin/com/linroid/ketch/engine/NetworkHttpEngine.kt
Lines 24 to 30 in ca3b660
fun KtorHttpEngine.Companion.forNetwork( network: Network, logRequests: Boolean = true, userAgent: String? = KtorHttpEngine.DEFAULT_USER_AGENT, connectivityManager: ConnectivityManager? = null, ): KtorHttpEngine = KtorHttpEngine(AndroidTransports(network, connectivityManager), logRequests, userAgent) - The download proxy is applied to every selected network (). Docs say it must be reachable from each network (docs/multiple-networks.md#L33-L34), so a LAN-only proxy cannot be used over cellular.
Ketch/library/core/src/commonMain/kotlin/com/linroid/ketch/core/engine/MultiNetworkHttpEngine.kt
Lines 93 to 131 in ca3b660
/** These networks, each reaching servers as [proxy] says; closing it does nothing. */ private inner class Proxied(private val proxy: Proxy) : HttpEngine { override suspend fun head(url: String, headers: Map<String, String>): ServerInfo = nextEngine().withProxy(proxy).head(url, headers) override suspend fun probe(url: String, headers: Map<String, String>): ServerInfo = nextEngine().withProxy(proxy).probe(url, headers) override suspend fun request( method: String, url: String, headers: Map<String, String>, body: HttpBody?, maxBodyBytes: Int, ): HttpReply = nextEngine().withProxy(proxy).request(method, url, headers, body, maxBodyBytes) override suspend fun downloadResource( url: String, headers: Map<String, String>, onData: suspend (ByteArray) -> Unit, ): String = nextEngine().withProxy(proxy).downloadResource(url, headers, onData) override suspend fun download( url: String, range: LongRange?, headers: Map<String, String>, onData: suspend (ByteArray) -> Unit, ) { nextEngine().withProxy(proxy).download(url, range, headers, onData) } override val supportsProxies: Boolean get() = this@MultiNetworkHttpEngine.supportsProxies override fun withProxy(proxy: Proxy): HttpEngine = this@MultiNetworkHttpEngine.withProxy(proxy) override fun close() {} } - Proxy DNS resolves only on the bound link ().
Ketch/library/ktor/src/jvmAndAndroidMain/kotlin/com/linroid/ketch/engine/OkHttpTransports.kt
Lines 53 to 57 in ca3b660
when (route) { is ProxyRoute.Http -> { proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(route.host, route.port))) socketFactory(binding.socketFactory) dns(Dns { binding.lookup(it) })
F10. Test gaps
androidHostTestcontains onlyAndroidNetworkNamesTest.ktandAndroidTransportsTest.kt(https://github.com/linroid/Ketch/tree/ca3b6601a137dc35b4e1b2a8c52354042273dc75/library/ktor/src/androidHostTest). Nothing covers cellular while Wi-Fi is default, network loss mid-download, handle rotation across reconnects, or unequal-link dispatch.
Reproduction (code-level; device run pending)
- Enable Wi-Fi and mobile data; leave Wi-Fi as the default network.
- Settings → Network: check whether "Mobile data" is listed (F1, F2).
- Select Wi-Fi and Mobile data. Start a range-supporting HTTPS download of at least 100 MB with default connections.
- Check per-interface traffic:
adb shell dumpsys netstats detail | grep -A30 "uid=<ketch-uid>". Expect roughly equal request counts regardless of link speed (F5). - Toggle Wi-Fi off and on. Expect segments on the old link to fail, its chip to show as gone, and re-selecting the same set to fail with "Unknown or unavailable interface" (F3, F7).
- Force-stop the app and reopen it. The selection is gone (F4).
- Set max connections to 1 with both networks selected. Only one link carries traffic (F8).
Attach: adb shell dumpsys connectivity | grep -i -B2 -A8 cellular; adb shell dumpsys package com.linroid.ketch | grep -E "CHANGE_NETWORK_STATE|ACCESS_NETWORK_STATE"; adb logcat -v time | grep -iE "ketch|Unknown or unavailable|SocketException|Taking over".
Expected
- Both selected links carry bytes for the same download, as the README advertises ().
Lines 103 to 104 in ca3b660
- **Several networks at once** — Spread one download over Wi-Fi, Ethernet and, on Android, cellular data ([how it works](docs/multiple-networks.md)). - Mobile data is listed and stays up while Wi-Fi is the default.
- A Wi-Fi reconnect or cellular handover does not kill the download; Ketch rebinds to the current
Network. - With 2.4 GHz Wi-Fi and 5G, throughput approaches the sum of the links.
- A failing link is circuit-broken rather than retried into.
- The selection survives an app restart, or the UI says it does not.
- Holding cellular costs mobile data and battery; the UI should make that trade-off clear.
Suggested fixes
- Add
CHANGE_NETWORK_STATE. While a selection includes mobile data, hold arequestNetwork(TRANSPORT_CELLULAR + NET_CAPABILITY_INTERNET)callback; unregister on deselect or service destroy. - Discover via
registerNetworkCallback; requireNET_CAPABILITY_VALIDATED; key selections by transport and interface instead of raw handle; rebuild the generation ononAvailableandonLost. - Persist the selection and re-apply it on service start, or change the UI copy to match the docs.
- Pin stolen and retried lanes to their engine; add a per-network circuit breaker; consider weighting by measured throughput.
- Scale connections per selected network; warn instead of silently going direct on PAC networks; allow per-network proxy overrides.
- Add tests for the scenarios in F10.
This could be split into an app-integration issue (F1–F4) and a scheduler issue (F5–F8) if you prefer.
Platform
Android
Ketch version
0.10.5
Logs
No response
Activity
[-]I believe simultaneous Wi-Fi + mobile data downloads are unreliable on Android. I used Claude to review the code for root causes; the findings are from static analysis and still need verification[/-][+]I believe simultaneous Wi-Fi + mobile data downloads are unreliable on Android.[/+]