fix(downloader): correct truncation, ranged sizing, and session carry

Check a sequential download against the complete length whenever one is known, and settle the unknown-total case on the 416. An empty body of unknown length, a 206 with no complete length, and a 206 starting past the resume offset all passed the size checks before and were renamed into place. Four restart paths spent no attempt, so a host that always answered the same way cycled forever.
This commit is contained in:
imSp4rky
2026-09-06 20:03:08 -06:00
parent dffb8b27e3
commit 22cc739e83
13 changed files with 1895 additions and 121 deletions
+214
View File
@@ -0,0 +1,214 @@
"""``probe_ranged`` cost and fidelity.
The probe asks for one byte to learn the complete length and whether the host honours
ranges. It runs once for every single-URL download and once per tail-boost candidate,
so what it costs and what it sends both matter:
- it must leave the connection reusable. A streamed response whose body is never read
cannot go back in the pool. Every probe would then tear down a socket, and the next
request would pay a fresh handshake.
- it must ask for an unencoded body like ``download()`` does. A CDN that answers a
probe with a Content-Encoding makes the probe decline, and the ranged-parallel path
is silently lost for a file that supports it.
- it must carry the URL item's own request options. Without them a host that needs an
auth header answers the probe with a 4xx, and the download falls back to one
connection even though the ranges were there.
The drain is bounded by the declared Content-Length, not by the status code. A host
that ignores Range may answer 200 with the whole resource, and one that answers 206
with the whole resource is just as possible. Reading either would download the file
only to decide not to use it.
"""
import importlib
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from requests import Session
from unshackle.core.constants import DOWNLOAD_CANCELLED
# the package re-exports the `requests` function, shadowing the module of the same name
dl = importlib.import_module("unshackle.core.downloaders.requests")
PAYLOAD = bytes((i * 11 + 3) % 256 for i in range(32 * 1024))
BIG = bytes(8 * 1024 * 1024) # larger than any socket buffer, so a full drain is visible
PROBES = 6
AUTH = "let-me-in"
class _ProbeServer(ThreadingHTTPServer):
allow_reuse_address = True
daemon_threads = True
def __init__(self):
self.lock = threading.Lock()
self.requests: list = [] # (Range, Accept-Encoding, X-Auth)
self.connections = 0
self.mode = "range"
self.written = 0
self.broke = False
super().__init__(("127.0.0.1", 0), _ProbeHandler)
def handle_error(self, request, client_address): # the client hanging up is expected here
pass
class _ProbeHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def setup(self):
super().setup()
with self.server.lock:
self.server.connections += 1
def do_GET(self):
srv = self.server
rng = self.headers.get("Range")
with srv.lock:
srv.requests.append((rng, self.headers.get("Accept-Encoding"), self.headers.get("X-Auth")))
if srv.mode == "needs_auth" and self.headers.get("X-Auth") != AUTH:
self.send_response(403)
self.send_header("Content-Length", "0")
self.end_headers()
return
if srv.mode == "ignores_range":
self.send_response(200)
self.send_header("Content-Length", str(len(BIG)))
self.end_headers()
self._write_slowly(BIG)
return
if srv.mode == "fat_206":
# a 206 status on a whole-resource body: the status alone cannot bound the drain
self.send_response(206)
self.send_header("Content-Range", f"bytes 0-{len(BIG) - 1}/{len(BIG)}")
self.send_header("Content-Length", str(len(BIG)))
self.end_headers()
self._write_slowly(BIG)
return
if not rng:
self.send_response(200)
self.send_header("Content-Length", str(len(PAYLOAD)))
self.end_headers()
self.wfile.write(PAYLOAD)
return
start_s, _, end_s = rng.removeprefix("bytes=").partition("-")
start = int(start_s)
end = int(end_s) if end_s else len(PAYLOAD) - 1
body = PAYLOAD[start : end + 1]
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(PAYLOAD)}")
self.send_header("Content-Length", str(len(body)))
if srv.mode == "encode_unless_identity" and self.headers.get("Accept-Encoding") != "identity":
self.send_header("Content-Encoding", "gzip")
self.end_headers()
self.wfile.write(body)
def _write_slowly(self, body):
# chunked writes so the count records how far the client actually read
srv = self.server
try:
for at in range(0, len(body), 64 * 1024):
self.wfile.write(body[at : at + 64 * 1024])
with srv.lock:
srv.written += len(body[at : at + 64 * 1024])
except OSError:
with srv.lock:
srv.broke = True
self.close_connection = True
@pytest.fixture
def server(monkeypatch):
DOWNLOAD_CANCELLED.clear()
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
srv = _ProbeServer()
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
srv.server_close()
DOWNLOAD_CANCELLED.clear()
def url(srv, path="/payload.bin"):
return f"http://127.0.0.1:{srv.server_address[1]}{path}"
def test_probe_reuses_the_pooled_connection(server):
session = Session()
for _ in range(PROBES):
assert dl.probe_ranged(url(server), session) == (len(PAYLOAD), True)
assert server.connections == 1
def test_probe_does_not_drain_a_200_body(server):
server.mode = "ignores_range"
session = Session()
assert dl.probe_ranged(url(server), session) == (0, False)
for _ in range(50):
with server.lock:
if server.broke or server.written >= len(BIG):
break
time.sleep(0.1)
with server.lock:
assert server.written < len(BIG)
def test_probe_asks_for_identity_encoding(server):
server.mode = "encode_unless_identity"
session = Session()
assert dl.probe_ranged(url(server), session) == (len(PAYLOAD), True)
assert server.requests[-1][1] == "identity"
# a caller that names its own encoding still wins
assert dl.probe_ranged(url(server), session, headers={"Accept-Encoding": "gzip"}) == (0, False)
assert server.requests[-1][1] == "gzip"
def test_probe_uses_the_url_items_headers(server, tmp_path, monkeypatch):
server.mode = "needs_auth"
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_SIZE", 8 * 1024)
item = {"url": url(server), "headers": {"X-Auth": AUTH}}
for _ in dl.requests([item], output_dir=tmp_path, filename="seg_{i:04}.bin", max_workers=4):
pass
save_path = tmp_path / "seg_0000.bin"
assert save_path.read_bytes() == PAYLOAD
probes = [r for r in server.requests if r[0] == "bytes=0-0"]
assert probes and all(r[2] == AUTH for r in probes)
# the probe was answered, so the ranged path ran instead of one sequential connection
assert [r for r in server.requests if r[0] and r[0] != "bytes=0-0"]
def test_probe_does_not_drain_a_fat_206_body(server):
"""A 206 carrying the whole resource must not be read to decide whether to use ranges."""
server.mode = "fat_206"
session = Session()
assert dl.probe_ranged(url(server), session) == (len(BIG), True)
for _ in range(50):
with server.lock:
if server.broke or server.written >= len(BIG):
break
time.sleep(0.1)
with server.lock:
assert server.written < len(BIG)
+110 -4
View File
@@ -13,7 +13,9 @@ Pins the byte-range fan-out that splits one large file across parts:
or a content-encoded 206;
- the public single-URL path falls back to a sequential download only when the
server does not really support ranges, and re-raises a 4xx instead of paying
MAX_ATTEMPTS a second time from byte 0.
MAX_ATTEMPTS a second time from byte 0;
- the split plan is worker-driven: every worker gets a part, down to a 4 MiB floor
that stops a large worker count cutting a file into slivers.
Tests 2/3 exercise ``dispatch_parts`` directly: the public path swallows a
range-support failure and falls back, so the raise that the invariant guarantees
@@ -118,7 +120,7 @@ def run(srv, tmp_path, urls, **kwargs):
def test_ranged_parallel_merges_byte_identical(server, tmp_path, monkeypatch):
# shrink the thresholds so a 32 KiB payload splits into several parts
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_SIZE", 8 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_PART_SIZE", 2 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 2 * 1024)
files = run(server, tmp_path, [{"url": url(server)}], max_workers=4)
assert len(files) == 1
assert files[0].read_bytes() == PAYLOAD
@@ -182,7 +184,7 @@ def test_permanent_part_failure_is_not_retried_sequentially(server, tmp_path, mo
server.mode = "deny_parts"
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_SIZE", 8 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_PART_SIZE", 8 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 8 * 1024)
with pytest.raises(HTTPError):
run(server, tmp_path, [{"url": url(server)}], max_workers=4)
# a sequential fallback would issue a plain unranged GET; only the probe and the
@@ -198,7 +200,7 @@ def test_range_unsupported_falls_back_to_sequential(server, tmp_path, monkeypatc
server.mode = "probe_only_206"
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_SIZE", 8 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_PART_SIZE", 8 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 8 * 1024)
files = run(server, tmp_path, [{"url": url(server)}], max_workers=4)
assert len(files) == 1
assert files[0].read_bytes() == PAYLOAD
@@ -214,3 +216,107 @@ def test_permanent_status_unwraps_causes():
wrapped = RuntimeError("max retries")
wrapped.__cause__ = HTTPError(response=_Resp(404))
assert dl.permanent_status(wrapped) == 404
BIG = bytes((i * 13 + 7) % 256 for i in range(8 * 1024 * 1024))
class _BigHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self):
srv = self.server
rng = self.headers.get("Range")
with srv.lock:
srv.requests.append(rng)
if not rng:
self.send_response(200)
self.send_header("Content-Length", str(len(BIG)))
self.end_headers()
self.wfile.write(BIG)
return
start_s, _, end_s = rng.removeprefix("bytes=").partition("-")
start = int(start_s)
end = int(end_s) if end_s else len(BIG) - 1
body = BIG[start : end + 1]
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BIG)}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
@pytest.fixture
def big_server():
srv = ThreadingHTTPServer(("127.0.0.1", 0), _BigHandler)
srv.lock = threading.Lock()
srv.requests = []
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
_REAL_SPLIT = dl.split_ranges
class _SplitStop(Exception):
"""Ends dispatch_parts once the split plan is known, before any request is made."""
def plan_split(monkeypatch, tmp_path, total_size, max_workers):
"""The (size, max_parts, part_target, parts) that dispatch_parts asks split_ranges for."""
record: list = []
def spy(size, max_parts, part_target):
# _REAL_SPLIT, not dl.split_ranges: a second call in one test would otherwise
# chain through the previous spy and raise before recording
record.append((size, max_parts, part_target, _REAL_SPLIT(size, max_parts, part_target)))
raise _SplitStop
monkeypatch.setattr(dl, "split_ranges", spy)
gen = dl.dispatch_parts(
url="http://127.0.0.1:1/unreachable",
save_path=tmp_path / "planned.bin",
session=Session(),
total_size=total_size,
max_workers=max_workers,
)
with pytest.raises(_SplitStop):
next(gen)
return record[0]
def test_part_count_matches_worker_count(tmp_path, monkeypatch):
_, _, _, parts = plan_split(monkeypatch, tmp_path, 64 * 1024 * 1024, 16)
assert len(parts) == 16
_, _, _, parts = plan_split(monkeypatch, tmp_path, 16 * 1024 * 1024, 4)
assert len(parts) == 4
def test_part_floor_caps_sliver_count(tmp_path, monkeypatch):
# below the 4 MiB floor a part's handshake costs more than its transfer
_, _, target, parts = plan_split(monkeypatch, tmp_path, 16 * 1024 * 1024, 64)
assert target == 4 * 1024 * 1024
assert len(parts) == 4
def test_worker_driven_parts_merge_byte_identical(big_server, tmp_path):
save_path = tmp_path / "big.bin"
for _ in dl.dispatch_parts(
url=url(big_server, "/big.bin"),
save_path=save_path,
session=Session(),
total_size=len(BIG),
max_workers=2,
):
pass
assert save_path.read_bytes() == BIG
assert len({r for r in big_server.requests if r}) == 2
assert not save_path.with_name(save_path.name + ".!dev").exists()
@@ -0,0 +1,273 @@
"""Completeness of a sequential download that the server serves in short pieces.
``download()`` renames its ``.!dev`` partial into place and reports ``file_downloaded``
only when the resource is whole. A host that caps every range answers an open-ended
resume (``Range: bytes=N-``) with an honest short 206: the body matches the response's
own ``Content-Length``, so the short-read check is satisfied while the file is still
truncated. These tests pin the completeness decision on the three paths that reach it:
- a resume with a known complete length must continue from the served end until the
complete length is on disk;
- a resume with an unknown complete length (``Content-Range: bytes N-M/*``) has no
number to compare against, so the only proof of the end is the server refusing the
next range with a 416;
- a first request that carries no Range at all, which a host may still answer with a
short 206. Its Content-Range names the complete length, so the decision has a number
to compare against even though nothing was resumed.
The guards beside them pin what the decision must not change: an unknown-length body
with no partial on disk still finalizes, a stale oversized partial is still discarded
on a 416, a resume that arrives whole costs no extra request, and an empty resume body
still raises instead of repeating the same request forever.
"""
import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from requests import Session
from unshackle.core.constants import DOWNLOAD_CANCELLED
# the package re-exports the `requests` function, shadowing the module of the same name
dl = importlib.import_module("unshackle.core.downloaders.requests")
TOTAL = 256 * 1024
PAYLOAD = bytes((i * 37 + 5) % 256 for i in range(TOTAL))
SEED = 64 * 1024 # bytes a prior run left in the .!dev partial
CAP = 32 * 1024 # most the capped server serves for one range
OPEN_CAP = 16 * 1024 # most the halving server serves for an open-ended range
CUT = 96 * 1024 # where the halving server cuts the unranged body
class _ShortServer(ThreadingHTTPServer):
allow_reuse_address = True
daemon_threads = True
def __init__(self):
self.lock = threading.Lock()
self.requests: list = []
self.mode = "cap"
super().__init__(("127.0.0.1", 0), _ShortHandler)
def handle_error(self, request, client_address): # the client hanging up is expected here
pass
class _ShortHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def do_GET(self):
srv = self.server
header = self.headers.get("Range")
with srv.lock:
srv.requests.append(header)
mode = srv.mode
if header is None:
if mode == "fresh206":
# a 206 to an un-Ranged request: the complete length is only in Content-Range
body = PAYLOAD[:CAP]
self.send_response(206)
self.send_header("Content-Range", f"bytes 0-{CAP - 1}/{TOTAL}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
if mode == "chunked200":
# no Content-Length: an unknown-length body the downloader cannot size
self.send_response(200)
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
self.wfile.write(b"%x\r\n" % len(PAYLOAD) + PAYLOAD + b"\r\n0\r\n\r\n")
return
self.send_response(200)
self.send_header("Content-Length", str(TOTAL))
self.end_headers()
if mode == "halving":
# honest length, then cut: download() credits a resume and bounds the next request
self.wfile.write(PAYLOAD[:CUT])
self.close_connection = True
return
self.wfile.write(PAYLOAD)
return
start_s, _, end_s = header.removeprefix("bytes=").partition("-")
start = int(start_s)
want_end = int(end_s) if end_s else None
if start >= TOTAL:
self.send_response(416)
self.send_header("Content-Range", f"bytes */{TOTAL}")
self.send_header("Content-Length", "0")
self.end_headers()
return
if mode == "empty206":
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{TOTAL - 1}/{TOTAL}")
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
self.wfile.write(b"0\r\n\r\n")
return
if want_end is not None:
end = min(TOTAL - 1, want_end) # a bounded sub-range is always served whole
elif mode == "whole_remainder":
end = TOTAL - 1
elif mode == "halving":
end = min(TOTAL - 1, start + OPEN_CAP - 1)
else:
end = min(TOTAL - 1, start + CAP - 1)
body = PAYLOAD[start : end + 1]
total = "*" if mode == "cap_star" else str(TOTAL)
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{total}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
@pytest.fixture
def server(monkeypatch):
DOWNLOAD_CANCELLED.clear()
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
srv = _ShortServer()
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
srv.server_close()
DOWNLOAD_CANCELLED.clear()
def url(srv):
return f"http://127.0.0.1:{srv.server_address[1]}/seg.mp4"
def run(srv, save_path):
return list(dl.download(url=url(srv), save_path=save_path, session=Session(), segmented=True))
def assert_complete(save_path):
# size first: a truncation failure then names the byte counts instead of diffing blobs
assert save_path.stat().st_size == TOTAL
assert save_path.read_bytes() == PAYLOAD
def finalized(events):
return [event["written"] for event in events if "file_downloaded" in event]
def seed_partial(save_path, size):
tmp_file = save_path.with_name(f"{save_path.name}.!dev")
tmp_file.write_bytes(PAYLOAD[:size])
return tmp_file
def test_capped_open_ended_resume_finishes_the_file(server, tmp_path):
server.mode = "cap"
save_path = tmp_path / "seg.mp4"
tmp_file = seed_partial(save_path, SEED)
events = run(server, save_path)
assert_complete(save_path)
assert finalized(events) == [TOTAL]
assert not tmp_file.exists()
def test_short_tail_after_chunk_halving_finishes_the_file(server, tmp_path, monkeypatch):
server.mode = "halving"
monkeypatch.setattr(dl, "REQUEST_CHUNK_SIZE", 64 * 1024)
monkeypatch.setattr(dl, "MIN_REQUEST_CHUNK", 8 * 1024)
monkeypatch.setattr(dl, "MIN_RESUME_PROGRESS", 1024)
save_path = tmp_path / "seg.mp4"
events = run(server, save_path)
assert_complete(save_path)
assert finalized(events) == [TOTAL]
# the bounded sub-ranges in the middle were each served whole and continued
bounded = [r for r in server.requests if r and r.split("-")[-1]]
assert len(bounded) >= 2
def test_zero_byte_resume_body_raises_instead_of_spinning(server, tmp_path):
server.mode = "empty206"
save_path = tmp_path / "seg.mp4"
seed_partial(save_path, SEED)
with pytest.raises(IOError):
run(server, save_path)
assert not save_path.exists()
# an empty body must spend an attempt, not repeat the same request with no bound
assert len(server.requests) <= dl.MAX_ATTEMPTS
def test_unknown_total_resume_finalizes_on_416(server, tmp_path):
server.mode = "cap_star"
save_path = tmp_path / "seg.mp4"
tmp_file = seed_partial(save_path, SEED)
events = run(server, save_path)
assert_complete(save_path)
assert finalized(events) == [TOTAL]
assert not tmp_file.exists()
def test_stale_partial_416_still_restarts_clean(server, tmp_path):
server.mode = "cap"
save_path = tmp_path / "seg.mp4"
tmp_file = save_path.with_name(f"{save_path.name}.!dev")
tmp_file.write_bytes(b"\x00" * (TOTAL + 4096))
events = run(server, save_path)
assert_complete(save_path)
assert finalized(events) == [TOTAL]
assert None in server.requests # restarted from byte 0 with an unranged GET
assert not tmp_file.exists()
def test_unknown_length_body_still_finalizes(server, tmp_path):
server.mode = "chunked200"
save_path = tmp_path / "seg.mp4"
events = run(server, save_path)
assert_complete(save_path)
assert finalized(events) == [TOTAL]
def test_complete_resume_finalizes_without_an_extra_request(server, tmp_path):
server.mode = "whole_remainder"
save_path = tmp_path / "seg.mp4"
seed_partial(save_path, SEED)
events = run(server, save_path)
assert_complete(save_path)
assert finalized(events) == [TOTAL]
# a known complete length that the first response satisfies costs no confirming request
assert len(server.requests) == 1
def test_short_206_to_an_unranged_first_request_finishes_the_file(server, tmp_path):
"""No resume, so the only complete length is the one the 206's Content-Range names."""
server.mode = "fresh206"
save_path = tmp_path / "seg.mp4"
events = run(server, save_path)
assert_complete(save_path)
assert finalized(events) == [TOTAL]
+54 -7
View File
@@ -11,7 +11,9 @@ target, finalized by the last part worker via os.replace. The invariants:
- finalize is last-part-wins: on success save_path exists and the ``.tp.!dev`` target
is gone;
- a permanently failing part fails the batch and the boosted segment is never
os.replace'd into place (no corrupt finalized segment).
os.replace'd into place (no corrupt finalized segment);
- a part that fails for a reason a retry could fix puts its segment back on the normal
single-worker path, without aborting the sibling segments or the track.
Determinism: with ``max_workers`` < segment count <= 2*max_workers and adaptive=True,
the leading ``max_workers`` segments submit upfront and the trailing few stay in
@@ -50,9 +52,16 @@ class _Handler(BaseHTTPRequestHandler):
start_s, _, end_s = rng[len("bytes=") :].partition("-")
start = int(start_s)
end = int(end_s) if end_s else len(BODY) - 1
if server.deny_offset_ranges and start > 0:
# every non-leading window is refused for good (expired token, geo block)
self.send_response(403)
self.send_header("Content-Length", "0")
self.end_headers()
return
if server.break_offset_ranges and start > 0:
# misbehave for every non-leading window: send the whole body as 200 so
# part-mode's 206 check fails permanently for that part
# every non-leading window answers 200 with the whole body: part-mode's 206
# check fails, but 200 is not permanent, so the segment goes back on the
# normal single-worker path
self.send_response(200)
self.send_header("Content-Length", str(len(BODY)))
self.end_headers()
@@ -80,6 +89,7 @@ def server():
srv.lock = threading.Lock()
srv.requests = []
srv.break_offset_ranges = False
srv.deny_offset_ranges = False
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
@@ -160,15 +170,52 @@ def test_tail_boost_finalize_last_part_wins(server, tmp_path):
assert not save_path.with_name(f"{save_path.name}.tp.!dev").exists()
def test_tail_boost_part_failure_fails_batch_but_keeps_siblings_files_clean(server, tmp_path, monkeypatch):
server.break_offset_ranges = True # every non-leading part window 200s -> permanent 206 failure
def test_tail_boost_part_failure_falls_back_to_normal_path(server, tmp_path, monkeypatch):
server.break_offset_ranges = True # every part window past the first fails, but not for good
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
files, advances = run(server, tmp_path, seg_urls(server))
assert boost_engaged(server), "tail boost never engaged; the fallback path is untested"
# a transient part failure returns the segment to the normal path instead of killing the track
assert len(files) == SEG_COUNT
assert all(f.read_bytes() == BODY for f in files)
# one advance per segment: a requeued segment must not be counted twice
assert advances == SEG_COUNT
assert not dl.DOWNLOAD_CANCELLED.is_set()
assert not list(tmp_path.glob("*.!dev"))
assert not list(tmp_path.glob("*.tp.!dev"))
def test_tail_boost_failure_does_not_abort_sibling_segments(server, tmp_path, monkeypatch):
server.break_offset_ranges = True
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
files, _ = run(server, tmp_path, seg_urls(server))
assert boost_engaged(server), "tail boost never engaged; the fallback path is untested"
# the parts of one segment share an abort of their own: setting the batch-wide one would
# strand every other in-flight worker and end the batch with segments missing
assert len(files) == SEG_COUNT
with server.lock:
reqs = list(server.requests)
boosted_paths = {path for path, rng in reqs if rng and rng != "bytes=0-0"}
assert boosted_paths
# each boosted segment went back on the normal path: a plain unranged GET for it
plain = {path for path, rng in reqs if rng is None}
assert boosted_paths <= plain
def test_tail_boost_permanent_part_failure_still_fails_the_batch(server, tmp_path, monkeypatch):
server.deny_offset_ranges = True # every part window past the first is a 403
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
with pytest.raises(Exception):
run(server, tmp_path, seg_urls(server))
# the boosted tail segments (6, 7) hit the failing windows: no part run reaches parts_left==0
# cleanly, so neither is finalized. sibling leaders that did finalize must be uncorrupted.
assert boost_engaged(server), "tail boost never engaged; the permanent-failure rule is untested"
# a 4xx will not get better on the normal path either, so the boosted tail segments
# (6, 7) are never finalized and the batch fails instead of paying a second full attempt
for i in (6, 7):
assert not (tmp_path / f"seg_{i:04}.bin").exists()
for f in tmp_path.glob("seg_*.bin"):