Skip to content

I believe simultaneous Wi-Fi + mobile data downloads are unreliable on Android. #682

Open

Description

@niggetron

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 INTERNET and ACCESS_NETWORK_STATE; CHANGE_NETWORK_STATE is absent:
    <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 requestNetwork or NetworkRequest for TRANSPORT_CELLULAR anywhere. The engine states that it does not retain networks and leaves that to the app:
    * 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.
    and #L29
  • The service wires the engine with no request:
    val httpEngine = KtorHttpEngine.withNetworkInterfaces(
    getSystemService(ConnectivityManager::class.java)
    )
    . The only callback is a default-network observer for upload metering:
  • 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

F3. Network IDs rotate; nothing rebinds

F4. Selection is not persisted

F5. Dispatch is speed-blind round-robin shared by all requests

  • nextEngine() is a global atomic round-robin (
    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]
    }
    }
    ). HEAD and probe requests take turns too (#L34-L46).
  • Docs: "balances requests, not speed" (
    - **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 ( ;
    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,
    )
    }
    ;
    maxSegments = if (serverInfo.supportsResume) config.maxConnectionsPerDownload else 1,
    ). Result: two requests per link regardless of link speed.

F6. Stolen tails and retries are not pinned to their link

  • The ledger measures per-lane rates and steals slow tails (
    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)
    }
    and #L320-L340).
  • A stolen tail is a new request. runConnection calls downloadSegment(lane) again (
    } 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
    and #L309-L317). That reaches SegmentDownloader.kt#L44, then MultiNetworkHttpEngine.download (
    override suspend fun download(
    url: String,
    range: LongRange?,
    headers: Map<String, String>,
    onData: suspend (ByteArray) -> Unit,
    ) {
    nextEngine().download(url, range, headers, onData)
    }
    ), which is round-robin. A fast-link connection can be handed a slow-link range, and its rate is measured on the wrong network.
  • keepFor (SegmentLane.kt#L320-L333) assumes the thief keeps its own link's speed, which this breaks.

F7. No failover or circuit breaker

F8. Connection count ignores how many networks are selected

  • Connections come from maxConnections or the default of 4 (
    fun effectiveConnections(requested: Int): Int =
    if (requested > 0) requested else config.maxConnectionsPerDownload
    ; HttpDownloadSource.kt#L494-L506).
  • 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 (
    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)
    }
    }
    , PAC branch at #L54-L55).
  • forNetwork(...) without a ConnectivityManager returns Direct (AndroidTransports.kt#L52;
    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 (
    /** 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() {}
    }
    ). 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.
  • Proxy DNS resolves only on the bound link (
    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

Reproduction (code-level; device run pending)

  1. Enable Wi-Fi and mobile data; leave Wi-Fi as the default network.
  2. Settings → Network: check whether "Mobile data" is listed (F1, F2).
  3. Select Wi-Fi and Mobile data. Start a range-supporting HTTPS download of at least 100 MB with default connections.
  4. Check per-interface traffic: adb shell dumpsys netstats detail | grep -A30 "uid=<ketch-uid>". Expect roughly equal request counts regardless of link speed (F5).
  5. 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).
  6. Force-stop the app and reopen it. The selection is gone (F4).
  7. 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 (

    Ketch/README.md

    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

  1. Add CHANGE_NETWORK_STATE. While a selection includes mobile data, hold a requestNetwork(TRANSPORT_CELLULAR + NET_CAPABILITY_INTERNET) callback; unregister on deselect or service destroy.
  2. Discover via registerNetworkCallback; require NET_CAPABILITY_VALIDATED; key selections by transport and interface instead of raw handle; rebuild the generation on onAvailable and onLost.
  3. Persist the selection and re-apply it on service start, or change the UI copy to match the docs.
  4. Pin stolen and retried lanes to their engine; add a per-network circuit breaker; consider weighting by measured throughput.
  5. Scale connections per selected network; warn instead of silently going direct on PAC networks; allow per-network proxy overrides.
  6. 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

  1. changed the title [-]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.[/+] on Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions