kolibri icon indicating copy to clipboard operation
kolibri copied to clipboard

Resumed download livelocks when the server reports Content-Range with an unknown total length (`/*`)

Open namanjain24-sudo opened this issue 1 month ago • 2 comments

🙂 Looking for an issue? Welcome! This issue is open for contribution. If this is the first time you’re requesting an issue, please:

  • Read Contributing guidelines carefully. Pay extra attention to Using generative AI. Pull requests and comments that don’t follow the guidelines won’t be answered.
  • Confirm that you’ve read the guidelines in your comment.

Target branch: develop

Observed behavior

FileDownload._run_byte_range_download (kolibri/utils/file_transfer.py) decides whether a server honoured a Range request by comparing the response's Content-Range header against an exact expected string:

content_range = response.headers.get("content-range", "").lower()
expected_content_range = (
    f"bytes {start_byte}-{expected_end}/{self.total_size}"
)
range_response_supported = content_range == expected_content_range

RFC 7233 section 4.2 allows a server to report the total length as * when it doesn't know or doesn't want to disclose it, e.g. Content-Range: bytes 4096-10239/*. That is a perfectly valid, fully-honoured range response, but it never matches the hard-coded /{self.total_size} suffix above, so range_response_supported is False even though the server returned exactly the requested bytes.

When that happens, the else branch resets the destination and writes the (correctly-returned, but partial) response body as if it were the whole file:

else:
    self.dest_file_obj.reset()
    ...
    self.dest_file_obj.write_all(
        data_generator, progress_callback=progress_callback
    )

The next get_next_missing_range() call then computes a different resume offset from the (now wrong) bytes-written count, so the following Range request asks for a different sub-range, which the server again honours with /*, which again gets rejected, resets, and rewrites. The download livelocks: it keeps retrying forever and never converges, instead of completing.

I hit this while reviewing the TransferFile resume logic that #15533 just landed (the exact-string comparison itself predates that PR — it was introduced long ago in d8c5f033d8 — but TransferFile is the destination used by default for a fresh download, i.e. one with no pre-existing .chunks directory, and it only started retrying through this exact byte-range path once #15533 wired resume_offset() > 0 into byte_range_download. So this is now reachable from the default single-file download path, not just the chunked one).

Errors and logs

Instrumenting the Range header on each retry against a mock server that always honours the request but reports /* shows the resume offset oscillating forever instead of converging:

call #2: Range request start=4096
call #3: Range request start=6144
call #4: Range request start=4096
call #5: Range request start=6144
call #6: Range request start=4096

(content is 10240 bytes total; 4096 and 6144 are the two possible "bytes already written" counts produced by alternately discarding and rewriting from byte 0, so the retry loop bounces between them indefinitely).

Expected behavior

A Content-Range response whose returned start/end match what was requested should be accepted as "range supported" regardless of whether the total-length field is a concrete number or RFC 7233's *, so a resumed download actually converges instead of looping forever.

User-facing consequences

Any backend that reports Content-Range: bytes X-Y/* (some reverse proxies, CDNs, or object-storage gateways that can front Studio/remote content do this when they don't want to echo the full object size) will cause an interrupted content import or channel database download to never finish once it has to retry mid-stream: it keeps re-requesting different sub-ranges forever, burning bandwidth without making progress, instead of the resumed-download behaviour #15533 added.

Steps to reproduce

Add this test to kolibri/utils/tests/test_file_transfer.py::TestTransferFileRetryAfterPartialStream (it already has the imports it needs) and run pytest kolibri/utils/tests/test_file_transfer.py -k unknown_total_length:

def test_retry_resumes_when_server_reports_unknown_total_length(self):
    session = MagicMock()
    call_count = {"n": 0}

    def _get(url, headers=None, **kwargs):
        call_count["n"] += 1
        if call_count["n"] == 1:
            return self._response(self._partial_stream())
        if call_count["n"] > 6:
            raise AssertionError("GET called more than 6 times, loop does not converge")
        start = int(headers["Range"].replace("bytes=", "").split("-")[0])
        res = MagicMock()
        res.status_code = 206
        body = self.content[start:]
        res.headers = {
            "content-length": str(len(body)),
            "content-range": f"bytes {start}-{len(self.content) - 1}/*",
        }
        res.iter_content.return_value = iter([body])
        return res

    session.get.side_effect = _get

    with FileDownload(
        "http://example.com/test_file",
        self.dest,
        hashlib.md5(self.content).hexdigest(),
        session=session,
        retry_wait=0,
    ) as fd:
        fd.run()

    with open(self.dest, "rb") as f:
        self.assertEqual(f.read(), self.content)

Result on develop: the AssertionError guard fires — the download makes more than 6 GET requests without ever producing a file that matches self.content, confirming it never converges.

Context

Affects develop at 6cfad10c85 (post-#15533).

AI usage

Claude Code (acting on my instruction to review the latest develop pull and look for real bugs) found and reproduced this while reading through the TransferFile/ChunkedFile resume logic in file_transfer.py. It wrote the failing test above, ran it twice (once to confirm the livelock, once with an instrumented trace to confirm the oscillating offsets), and drafted this issue. I reviewed the reproduction, the RFC 7233 reasoning, and the scoping of "affects the default download path since #15533" before filing.

namanjain24-sudo avatar Oct 08 '26 23:10 namanjain24-sudo

/assign

namanjain24-sudo avatar Oct 08 '26 23:10 namanjain24-sudo

Hi! 👋

Thanks so much for your interest! This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues. If there are no unassigned 'help wanted' issues available, please wait until new ones are added.

We really appreciate your willingness to help. 😊

Are you preparing for Google Summer of Code? See our GSoC guidelines.

learning-equality-bot avatar Oct 08 '26 23:10 learning-equality-bot