okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
38.2 KiB740 linesraw
1"""Tests for setup.py's parallel ranged downloads (0.2.0): a local threaded HTTP server that supports Range stands in
2for Hugging Face's CDN.  Covers the parallel path, a resume after a kill and after a failed round, a server without Range,
3a piece that fails once, a signed address that runs out, the SHA-256 pin, STRATA_DL_CONNECTIONS=1 and the progress line.
4
5    python -m unittest tools.test_setup_download
6"""
7from __future__ import annotations
8
9import contextlib
10import hashlib
11import http.server
12import io
13import json
14import os
15import re
16import subprocess
17import sys
18import tempfile
19import threading
20import time
21import unittest
22from pathlib import Path
23from unittest import mock
24
25ROOT = Path(__file__).resolve().parents[1]
26sys.path.insert(0, str(ROOT))
27sys.path.insert(0, str(ROOT / "tools"))
28import setup  # noqa: E402
29import strata_mcp  # noqa: E402
30
31CHUNK = 64 << 10                                       # the tests' piece size (setup uses 32 MiB)
32DATA = bytes((i * 7 + (i >> 8)) & 0xFF for i in range(CHUNK * 40 + 12345))       # 40 whole pieces and a short last one
33BIG = (bytes((i * 11 + (i >> 9)) & 0xFF for i in range(1 << 16)) * 170)[:(10 << 20) + 12345]     # 10 MiB and a bit: longer than the one-stream read
34NAME = "t.gguf"
35
36
37class Server:
38    """A threaded HTTP server for one file.  `faults(path, start, end, nth)` may answer a request with an error."""
39
40    def __init__(self, data=DATA, ranges=True, length=True, redirect=False, delay=0.002, faults=None, hold_from=None):
41        self.data, self.ranges, self.length, self.redirect, self.delay = data, ranges, length, redirect, delay
42        self.faults = faults
43        # hold_from: a body byte at this file offset or later is not sent until the "release" event is set (the headers and every byte before it are):
44        # a client is at a known place, with no timing in it, until the test lets go (a kill test; release.set() also frees the handlers)
45        self.hold_from, self.release = hold_from, threading.Event()
46        self.lock = threading.Lock()
47        self.gets, self.heads, self.redirects = [], 0, 0           # gets: (start, end) of every ranged GET
48        self.active = self.max_active = 0
49        self.streams = self.max_streams = 0                         # the same without setup's one-byte probes (Range: bytes=0-0)
50        self.nth = {}
51        outer = self
52
53        class Handler(http.server.BaseHTTPRequestHandler):
54            def log_message(self, *a):
55                pass
56
57            def do_HEAD(self):
58                outer.handle(self, head=True)
59
60            def do_GET(self):
61                outer.handle(self, head=False)
62
63        self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
64        self.httpd.daemon_threads = True
65        self.port = self.httpd.server_address[1]
66        self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)
67
68    @property
69    def url(self):
70        return f"http://127.0.0.1:{self.port}/{NAME}"
71
72    def __enter__(self):
73        self.thread.start()
74        return self
75
76    def __exit__(self, *exc):
77        self.httpd.shutdown()
78        self.httpd.server_close()
79
80    def handle(self, h, head):
81        path = h.path.split("?")[0]
82        if self.redirect and path == "/" + NAME:
83            with self.lock:
84                self.redirects += 1
85            h.send_response(302)
86            h.send_header("Location", f"http://127.0.0.1:{self.port}/cdn/{NAME}?Expires={int(time.time()) + 3600}&Signature=x")
87            h.send_header("Content-Length", "0")
88            h.end_headers()
89            return
90        size = len(self.data)
91        rng = h.headers.get("Range")
92        start, end = 0, size - 1
93        if rng and self.ranges:
94            m = re.match(r"bytes=(\d+)-(\d*)$", rng)
95            start = int(m.group(1))
96            end = min(int(m.group(2)), size - 1) if m.group(2) else size - 1
97        if head:
98            with self.lock:
99                self.heads += 1
100            h.send_response(200)
101            if self.length:
102                h.send_header("Content-Length", str(size))
103            h.send_header("Content-Type", "application/octet-stream")
104            h.end_headers()
105            return
106        with self.lock:
107            self.gets.append((start, end) if rng and self.ranges else (0, size - 1))
108            key = (start, end)
109            self.nth[key] = n = self.nth.get(key, 0) + 1
110            self.active += 1
111            self.max_active = max(self.max_active, self.active)
112            probe = rng == "bytes=0-0"
113            if not probe:
114                self.streams += 1
115                self.max_streams = max(self.max_streams, self.streams)
116        try:
117            fault = self.faults(path, start, end, n) if self.faults else None
118            if fault and fault[0] == "status":
119                h.send_response(fault[1])
120                h.send_header("Content-Length", "0")
121                h.end_headers()
122                return
123            body = self.data[start:end + 1]
124            if rng and self.ranges:
125                h.send_response(206)
126                h.send_header("Content-Range", f"bytes {start}-{end}/{size}")
127            else:
128                h.send_response(200)
129            h.send_header("Content-Length", str(len(body)))
130            h.end_headers()
131            cut = fault[1] if fault and fault[0] == "cut" else None
132            try:
133                for i in range(0, len(body), 16384):
134                    if self.hold_from is not None and start + i >= self.hold_from:
135                        self.release.wait(120)
136                    if cut is not None and i >= cut:
137                        h.connection.shutdown(2)           # the connection drops in the middle of the body
138                        return
139                    h.wfile.write(body[i:i + 16384])
140                    if self.delay:
141                        time.sleep(self.delay)
142            except OSError:
143                pass
144        finally:
145            with self.lock:
146                self.active -= 1
147                if not probe:
148                    self.streams -= 1
149
150
151def pin_of(data):
152    return len(data), hashlib.sha256(data).hexdigest()
153
154
155@contextlib.contextmanager
156def small_pieces(**extra):
157    """Setup's piece size, size floor and waits scaled down to the test file."""
158    consts = dict(DL_CHUNK=CHUNK, DL_RUN=1, DL_MIN_PARALLEL=0, DL_BACKOFF=0.0, DL_SAVE_EVERY=0.05, DL_CONNECTIONS=4)
159    consts.update(extra)
160    with contextlib.ExitStack() as st:
161        for k, v in consts.items():
162            st.enter_context(mock.patch.object(setup, k, v))
163        st.enter_context(mock.patch.object(setup.time, "sleep", lambda s: None))
164        env = {k: v for k, v in os.environ.items() if k not in ("STRATA_DL_CONNECTIONS", "STRATA_ALLOW_UNPINNED")}
165        env["STRATA_SOURCE"] = "huggingface"
166        st.enter_context(mock.patch.dict(os.environ, env, clear=True))
167        yield
168
169
170def run(server, d, pin="auto", name=NAME):
171    """setup.download() of the server's file into folder d; returns (exit code or None, stdout)."""
172    dst = Path(d) / name
173    want = pin_of(DATA) if pin == "auto" else pin
174    out = io.StringIO()
175    code = None
176    with mock.patch.object(setup, "file_pin", lambda u: want), contextlib.redirect_stdout(out):
177        try:
178            setup.download(server.url, dst, "the model")
179        except SystemExit as e:
180            code = e.code if e.code is not None else 0
181    return code, out.getvalue()
182
183
184def asked(srv):
185    """The pieces (indexes) the server was asked for, one entry per request; the one-byte probe is left out, and so is the
186    plain whole-file GET that Python before 3.13 sends when it follows the HEAD's redirect (urllib turns the redirected HEAD into
187    a GET and the download closes it at once); no piece is that big."""
188    whole = (0, len(srv.data) - 1)
189    return [s // CHUNK for s, e in srv.gets if (s, e) not in ((0, 0), whole)]
190
191
192def files(d):
193    return sorted(p.name for p in Path(d).iterdir())
194
195
196class ParallelDownload(unittest.TestCase):
197    def test_a_big_file_comes_over_several_connections(self):
198        with small_pieces(), Server(redirect=True) as srv, tempfile.TemporaryDirectory() as d:
199            code, out = run(srv, d)
200            self.assertIsNone(code, out)
201            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
202            self.assertEqual(files(d), [NAME, NAME + ".done"])             # no .part, no piece list left behind
203            self.assertIn("sha256 " + hashlib.sha256(DATA).hexdigest(), (Path(d) / (NAME + ".done")).read_text())
204            self.assertGreater(srv.max_active, 1)
205            self.assertLessEqual(srv.max_active, 4)
206            self.assertEqual(sorted(asked(srv)), list(range(41)))           # every piece once, none twice
207            self.assertEqual(srv.redirects, 2)                              # HEAD and the one probe: the pieces use the CDN address
208
209    def test_the_redirect_is_resolved_once(self):
210        with small_pieces(), Server(redirect=True) as srv, tempfile.TemporaryDirectory() as d:
211            code, out = run(srv, d)
212            self.assertIsNone(code, out)
213            self.assertLessEqual(srv.redirects, 2)
214
215    def test_a_small_file_is_one_stream(self):
216        with small_pieces(DL_MIN_PARALLEL=len(DATA) + 1), Server() as srv, tempfile.TemporaryDirectory() as d:
217            code, out = run(srv, d)
218            self.assertIsNone(code, out)
219            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
220            self.assertEqual(srv.max_streams, 1)   # (the one-byte probe can still be sending: not a stream)
221            self.assertEqual(len(srv.gets), 1)
222
223    def test_one_connection_variable_restores_one_stream(self):
224        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
225            with mock.patch.dict(os.environ, {"STRATA_DL_CONNECTIONS": "1"}):
226                code, out = run(srv, d)
227            self.assertIsNone(code, out)
228            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
229            self.assertEqual(srv.max_streams, 1)   # (the one-byte probe can still be sending: not a stream)
230            self.assertEqual(srv.gets, [(0, len(DATA) - 1)])                # one request for the whole file
231
232    def test_connection_count_variable(self):
233        with small_pieces():
234            self.assertEqual(setup.dl_connections(), 4)
235            for raw, want in (("16", 16), ("0", 1), ("-3", 1), ("99", 32), ("x", 4), ("", 4)):
236                with mock.patch.dict(os.environ, {"STRATA_DL_CONNECTIONS": raw}):
237                    self.assertEqual(setup.dl_connections(), want, raw)
238
239
240class NoRangeSupport(unittest.TestCase):
241    def test_a_server_that_ignores_range_is_read_in_one_stream(self):
242        with small_pieces(), Server(ranges=False) as srv, tempfile.TemporaryDirectory() as d:
243            code, out = run(srv, d)
244            self.assertIsNone(code, out)
245            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
246            self.assertEqual(srv.max_streams, 1)   # (the one-byte probe can still be sending: not a stream)
247            self.assertEqual(files(d), [NAME, NAME + ".done"])
248
249    def test_a_server_without_any_length_is_read_in_one_stream(self):
250        with small_pieces(), Server(length=False, ranges=False) as srv, tempfile.TemporaryDirectory() as d:
251            code, out = run(srv, d, pin=None)                                # no length, so nothing to check a pin against first
252            self.assertIsNone(code, out)
253            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
254            self.assertEqual(srv.max_streams, 1)   # (the one-byte probe can still be sending: not a stream)
255
256    def test_a_head_without_a_length_still_gets_the_connections(self):
257        """ModelScope's HEAD has no Content-Length (#1915): the length comes from a one-byte ranged GET, not 'unknown'."""
258        with small_pieces(), Server(length=False) as srv, tempfile.TemporaryDirectory() as d:
259            code, out = run(srv, d)
260            self.assertIsNone(code, out)
261            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
262            self.assertGreater(srv.max_active, 1)
263            self.assertEqual(sorted(asked(srv)), list(range(41)))
264            self.assertEqual(files(d), [NAME, NAME + ".done"])
265
266    def test_range_stopping_in_the_middle_falls_back_to_the_unbroken_start(self):
267        def faults(path, start, end, nth):
268            return None
269
270        with small_pieces(), Server(faults=faults) as srv, tempfile.TemporaryDirectory() as d:
271            real = setup._fetch_run
272            calls = []
273
274            def fetch(src, st, f, run):
275                calls.append(run)
276                if len(calls) == 6:
277                    raise setup._NoRange("HTTP 200")
278                return real(src, st, f, run)
279
280            with mock.patch.object(setup, "_fetch_run", fetch):
281                code, out = run(srv, d)
282            self.assertIsNone(code, out)
283            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)           # the pin check passed: no gaps were kept
284            self.assertEqual(files(d), [NAME, NAME + ".done"])
285
286
287class Resume(unittest.TestCase):
288    def test_a_failed_round_keeps_the_finished_pieces(self):
289        broken = {"on": True}
290
291        def faults(path, start, end, nth):
292            if broken["on"] and start >= 20 * CHUNK:
293                return ("status", 500)
294            return None
295
296        with small_pieces(DL_ROUNDS=1, DL_CHUNK_TRIES=1), Server(faults=faults) as srv, tempfile.TemporaryDirectory() as d:
297            code, out = run(srv, d)
298            self.assertEqual(code, 1)                                       # could not finish: setup stops with a message
299            self.assertIn("could not finish downloading", out)
300            part = Path(d) / (NAME + ".part")
301            side = Path(d) / (NAME + ".part.chunks")
302            self.assertTrue(part.exists() and side.exists())
303            saved = json.loads(side.read_text())
304            done = {i for a, b in saved["done"] for i in range(a, b)}
305            self.assertTrue(done and all(i < 20 for i in done), done)
306            srv.gets.clear()
307            broken["on"] = False
308            code, out = run(srv, d)
309            self.assertIsNone(code, out)
310            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
311            again = set(asked(srv))
312            self.assertFalse(again & done, "pieces that were finished are fetched again")
313            self.assertEqual(again | done, set(range(41)))
314            self.assertEqual(files(d), [NAME, NAME + ".done"])
315
316    def killed_download_continues(self, one_stream):
317        """Kill setup.download in a subprocess once 12 pieces are on disk, then run it again: it continues and fetches none of them again.
318        No timing decides this: the test server sends nothing from file offset HOLD on until the test has killed the runner (Server.hold_from), so the
319        runner is always found part-way, however slow or fast the machine is. one_stream: the range probe fails in the runner, so setup reads the
320        file in one stream (parallel_download returns False), whose .part is an unbroken run from the start."""
321        # The parallel path saves every finished piece, so 13 whole pieces may arrive and 12 are on disk before the kill. The one-stream path writes
322        # what it reads in blocks of 8 MiB (setup.download_single), so its file must be longer than that: 8 MiB land on disk, then the server holds.
323        data = BIG if one_stream else DATA
324        HOLD = 9 << 20 if one_stream else 13 * CHUNK
325        pin = (len(data), hashlib.sha256(data).hexdigest())
326        probe = "setup._probe_ranges = lambda *a, **k: False\n" if one_stream else ""
327        runner = (
328            "import sys; sys.path[:0] = [%r, %r]\n"
329            "import setup\n"
330            "setup.DL_CHUNK = %d; setup.DL_MIN_PARALLEL = 0; setup.DL_SAVE_EVERY = 0.05; setup.DL_CONNECTIONS = 4\n"
331            "%s"
332            "pin = (%d, %r)\n"
333            "setup.file_pin = lambda u: pin\n"
334            "setup.download(sys.argv[1], __import__('pathlib').Path(sys.argv[2]) / %r, 'the model')\n"
335            % (str(ROOT), str(ROOT / "tools"), CHUNK, probe, pin[0], pin[1], NAME))
336        with small_pieces(), Server(data=data, hold_from=HOLD) as srv, tempfile.TemporaryDirectory() as d:
337            self.addCleanup(srv.release.set)                    # never leave a handler thread waiting
338            env = dict(os.environ, STRATA_SOURCE="huggingface")
339            err = Path(d) / "runner.err"
340            with open(err, "wb") as err_file:
341                proc = subprocess.Popen([sys.executable, "-c", runner, srv.url, d], env=env,
342                                        stdout=subprocess.DEVNULL, stderr=err_file)
343            side = Path(d) / (NAME + ".part.chunks")
344            part = Path(d) / (NAME + ".part")
345            started = time.time()
346            deadline = started + 60
347            try:
348                while time.time() < deadline and proc.poll() is None:
349                    try:
350                        if side.is_file():
351                            if sum(b - a for a, b in json.loads(side.read_text())["done"]) >= 12:
352                                break
353                        elif part.is_file() and part.stat().st_size >= 12 * CHUNK:   # the one-stream fallback (below)
354                            break
355                    except (OSError, ValueError, KeyError):
356                        pass
357                    threading.Event().wait(0.02)                # (not time.sleep: small_pieces() makes that a no-op)
358            finally:
359                code = proc.poll()
360                proc.kill()
361                proc.wait()
362                srv.release.set()
363            state = "the runner %s after %.1f s; its stderr: %s" % (
364                "was still running" if code is None else "had already ended with exit code %s" % code, time.time() - started,
365                err.read_text(errors="replace")[-2000:] or "(empty)")
366            self.assertTrue(part.exists(), "the .part file is missing at the kill: " + state)
367            if side.exists():
368                saved = json.loads(side.read_text())
369                done = {i for a, b in saved["done"] for i in range(a, b)}
370            else:
371                # One failed range probe makes setup read the file in one stream (parallel_download returns False): its .part is an
372                # unbroken run from the start and has no piece list, which the next run reads as finished pieces (_load_pieces).
373                # Seen on GitHub's Linux and macOS runners (run 42699343686); both ways must continue without fetching them again.
374                done = set(range(part.stat().st_size // CHUNK))
375            self.assertGreaterEqual(len(done), 12, "%d pieces at the kill; %s" % (len(done), state))
376            srv.hold_from = None                                # the second run is not held
377            srv.gets.clear()
378            code, out = run(srv, d, pin=pin)
379            self.assertIsNone(code, out)
380            self.assertEqual((Path(d) / NAME).read_bytes(), data)
381            self.assertFalse(set(asked(srv)) & done, "pieces that were finished before the kill are fetched again")
382
383    def test_a_killed_download_continues(self):
384        self.killed_download_continues(one_stream=False)
385
386    def test_a_killed_one_stream_download_continues(self):
387        self.killed_download_continues(one_stream=True)
388
389    def test_a_part_from_one_stream_continues_after_its_last_whole_piece(self):
390        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
391            have = CHUNK * 10 + 777                                         # an older setup's .part: bytes from the start
392            (Path(d) / (NAME + ".part")).write_bytes(DATA[:have])
393            code, out = run(srv, d)
394            self.assertIsNone(code, out)
395            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
396            self.assertEqual(sorted(asked(srv)), list(range(10, 41)))       # pieces 0-9 were not asked for again
397
398    def test_one_stream_continues_a_parallel_part_from_its_unbroken_start(self):
399        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
400            part = Path(d) / (NAME + ".part")
401            junk = bytearray(DATA)
402            junk[8 * CHUNK:9 * CHUNK] = b"\0" * CHUNK                       # a gap behind the later pieces
403            part.write_bytes(bytes(junk[:20 * CHUNK]))
404            (Path(d) / (NAME + ".part.chunks")).write_text(json.dumps(
405                {"v": 1, "total": len(DATA), "chunk": CHUNK, "done": [[0, 8], [9, 20]]}))
406            with mock.patch.dict(os.environ, {"STRATA_DL_CONNECTIONS": "1"}):
407                code, out = run(srv, d)
408            self.assertIsNone(code, out)
409            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
410            self.assertEqual(srv.gets, [(8 * CHUNK, len(DATA) - 1)])        # resumed after piece 7, the gap refetched
411            self.assertEqual(files(d), [NAME, NAME + ".done"])
412
413    def test_a_piece_list_of_another_file_starts_over(self):
414        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
415            (Path(d) / (NAME + ".part")).write_bytes(b"x" * (CHUNK * 3))
416            (Path(d) / (NAME + ".part.chunks")).write_text(json.dumps(
417                {"v": 1, "total": 999, "chunk": CHUNK, "done": [[0, 3]]}))
418            code, out = run(srv, d)
419            self.assertIsNone(code, out)
420            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
421
422
423class Failures(unittest.TestCase):
424    def test_a_piece_that_fails_once_is_tried_again(self):
425        def faults(path, start, end, nth):
426            if start == 5 * CHUNK and nth == 1:
427                return ("status", 500)
428            if start == 9 * CHUNK and nth == 1:
429                return ("cut", CHUNK // 2)                                  # drops half way: continues from where it was
430            return None
431
432        with small_pieces(), Server(faults=faults) as srv, tempfile.TemporaryDirectory() as d:
433            code, out = run(srv, d)
434            self.assertIsNone(code, out)
435            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
436            self.assertEqual(sum(1 for s, _ in srv.gets if s == 5 * CHUNK), 2)
437            self.assertEqual(sum(1 for s, _ in srv.gets if s == 9 * CHUNK), 1)
438            resumed = [s for s, _ in srv.gets if 9 * CHUNK < s < 10 * CHUNK]
439            self.assertEqual(len(resumed), 1)                               # the rest of the piece, not all of it again
440            self.assertGreater(resumed[0], 9 * CHUNK)
441
442    def test_a_signed_address_that_ran_out_is_asked_for_again(self):
443        def faults(path, start, end, nth):
444            if path.startswith("/cdn/") and nth == 1 and start in (4 * CHUNK, 11 * CHUNK):
445                return ("status", 403)
446            return None
447
448        with small_pieces(), Server(redirect=True, faults=faults) as srv, tempfile.TemporaryDirectory() as d:
449            code, out = run(srv, d)
450            self.assertIsNone(code, out)
451            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
452            self.assertGreater(srv.redirects, 2)                            # HEAD + first probe + a new address after the 403
453
454    def test_a_pinned_hash_mismatch_keeps_the_file_as_bad_and_stops(self):
455        wrong = bytes(reversed(DATA))
456        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
457            code, out = run(srv, d, pin=pin_of(wrong))
458            self.assertEqual(code, 1)
459            self.assertEqual(files(d), [NAME + ".bad"])                     # no file, no .done, no .part, no piece list; the bytes are kept
460            self.assertEqual((Path(d) / (NAME + ".bad")).read_bytes(), DATA)
461
462    def test_a_pinned_hash_mismatch_with_the_same_size(self):
463        other = bytes((b ^ 0x55) for b in DATA)
464        with small_pieces(), Server(data=other) as srv, tempfile.TemporaryDirectory() as d:
465            code, out = run(srv, d)
466            self.assertEqual(code, 1)
467            self.assertIn("does not match the pinned SHA-256", out)
468            self.assertIn(NAME + ".bad", out)
469            self.assertIn("the server sends exactly the bytes you have", out)      # the repair compared every block: the server's file is this one
470            self.assertEqual(files(d), [NAME + ".bad"])
471
472    def test_a_kept_bad_file_is_taken_back_when_it_matches_the_pin_now(self):
473        """A false mismatch (a bad read, a pin that was wrong and is fixed) costs one hash, not the download: the .bad file is the file again."""
474        wrong = bytes(reversed(DATA))
475        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
476            code, _ = run(srv, d, pin=pin_of(wrong))
477            self.assertEqual(code, 1)
478            srv.gets.clear()
479            code, out = run(srv, d)                                        # the right pin now
480            self.assertIsNone(code, out)
481            self.assertEqual(srv.gets, [], "nothing was asked of the server")
482            self.assertEqual(files(d), [NAME, NAME + ".done"])
483            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
484
485    def test_a_kept_bad_file_is_removed_by_a_good_download(self):
486        other = bytes((b ^ 0x55) for b in DATA)
487        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
488            (Path(d) / (NAME + ".bad")).write_bytes(other)                  # kept by an earlier run; not the pinned bytes
489            code, out = run(srv, d)
490            self.assertIsNone(code, out)
491            self.assertEqual(files(d), [NAME, NAME + ".done"])
492            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
493
494    def test_a_kept_bad_file_is_removed_when_there_is_no_room_for_the_new_copy(self):
495        other = bytes((b ^ 0x55) for b in DATA)
496        usage = type("U", (), {"free": 1000, "total": 10 ** 6, "used": 0})()
497        seen = []
498
499        def faults(path, start, end, nth):
500            seen.append(files(self.d))
501            return None
502
503        with small_pieces(), Server(faults=faults) as srv, tempfile.TemporaryDirectory() as d,                 mock.patch.object(setup.shutil, "disk_usage", lambda p: usage):
504            self.d = d
505            (Path(d) / (NAME + ".bad")).write_bytes(other)
506            code, out = run(srv, d)
507            self.assertIsNone(code, out)
508            self.assertTrue(seen and NAME + ".bad" not in seen[0], seen[:1])   # gone before the first piece came down
509            self.assertEqual(files(d), [NAME, NAME + ".done"])
510
511    def test_a_kept_bad_file_stays_while_there_is_room(self):
512        other = bytes((b ^ 0x55) for b in DATA)
513        seen = []
514
515        def faults(path, start, end, nth):
516            seen.append(files(self.d))
517            return None
518
519        with small_pieces(), Server(faults=faults) as srv, tempfile.TemporaryDirectory() as d:
520            self.d = d
521            (Path(d) / (NAME + ".bad")).write_bytes(other)
522            code, out = run(srv, d)
523            self.assertIsNone(code, out)
524            self.assertTrue(seen and NAME + ".bad" in seen[0], "kept until the new copy is checked")
525            self.assertNotIn(NAME + ".bad", files(d))
526
527    def test_a_full_disk_stops_with_a_message(self):
528        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
529            real = setup._piece_worker
530
531            def worker(src, st, todo, part):
532                st.fatal = setup._DiskError("No space left on device")
533                st.stop.set()
534
535            with mock.patch.object(setup, "_piece_worker", worker):
536                code, out = run(srv, d)
537            self.assertEqual(code, 1)
538            self.assertIn("cannot write", out)
539
540    def test_the_file_is_not_preallocated(self):
541        """The app counts a .part's size as the bytes done, so it must not jump to the full size at the start."""
542        seen = []
543
544        def faults(path, start, end, nth):
545            if start == 30 * CHUNK:
546                p = Path(self.d) / (NAME + ".part")
547                seen.append(p.stat().st_size if p.exists() else None)
548            return None
549
550        with small_pieces(DL_CONNECTIONS=2), Server(faults=faults, delay=0.01) as srv, tempfile.TemporaryDirectory() as d:
551            self.d = d
552            code, out = run(srv, d)
553            self.assertIsNone(code, out)
554            # a preallocated file would already be the full size (len(DATA)) here; what the other connection has written ahead of piece 30 is
555            # thread timing (Windows put it at 34 and 39 pieces), so the check is only that the file has not been made full size
556            self.assertTrue(seen and seen[0] is not None and seen[0] < len(DATA), seen)
557
558
559class Progress(unittest.TestCase):
560    def test_the_progress_line_is_the_one_the_app_reads(self):
561        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d:
562            code, out = run(srv, d)
563            self.assertIsNone(code, out)
564            lines = [x for x in out.replace("\r", "\n").split("\n") if x.strip()]
565            bar = [x for x in lines if "GB (" in x]
566            self.assertTrue(bar)
567            for x in bar:
568                self.assertRegex(x, r"^  the model: +[\d.]+ / [\d.]+ GB \(\d+%\) +$")
569            parsed = strata_mcp.install_progress(bar)["download"]
570            self.assertEqual(parsed["file"], "the model")
571            self.assertEqual(parsed["percent"], 100)
572            self.assertEqual(parsed["total_gb"], round(len(DATA) / 1e9, 2))
573
574    def test_the_format_matches_the_one_stream_path(self):
575        with small_pieces(), Server() as srv, tempfile.TemporaryDirectory() as d1, tempfile.TemporaryDirectory() as d2:
576            _, par = run(srv, d1)
577            with mock.patch.dict(os.environ, {"STRATA_DL_CONNECTIONS": "1"}):
578                _, one = run(srv, d2)
579            def shape(out):
580                return {re.sub(r"[\d.]+", "N", x) for x in out.replace("\r", "\n").split("\n") if "GB (" in x}
581            self.assertEqual(shape(par), shape(one))
582
583
584class SignedAddress(unittest.TestCase):
585    def test_expiry_of_a_cdn_address(self):
586        now = time.time()
587        self.assertAlmostEqual(setup._url_ttl(f"https://cdn.example/f?Expires={int(now) + 600}&Signature=x"), 600, delta=3)
588        self.assertIsNone(setup._url_ttl("https://cdn.example/f"))
589        self.assertIsNone(setup._url_ttl(f"https://cdn.example/f?Expires={int(now) - 5}"))      # already out, or a wrong clock
590        self.assertIsNone(setup._url_ttl("https://cdn.example/f?Expires=soon"))
591        stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(now))
592        self.assertAlmostEqual(setup._url_ttl(f"https://cdn.example/f?X-Amz-Date={stamp}&X-Amz-Expires=900"), 900, delta=3)
593
594
595if __name__ == "__main__":
596    unittest.main()
597
598
599class Runs(unittest.TestCase):
600    """One request asks for several neighbouring pieces (DL_RUN): fewer connections to open, the same piece list."""
601
602    def test_a_request_covers_several_pieces(self):
603        with small_pieces(DL_RUN=4), Server() as srv, tempfile.TemporaryDirectory() as d:
604            code, out = run(srv, d)
605            self.assertIsNone(code, out)
606            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
607            self.assertEqual(files(d), [NAME, NAME + ".done"])
608            spans = [(s, e) for s, e in srv.gets if (s, e) != (0, 0)]
609            self.assertLess(len(spans), 41)                                 # fewer requests than pieces
610            self.assertTrue(any(e - s + 1 > CHUNK for s, e in spans), spans)
611            self.assertTrue(all(e - s + 1 <= 4 * CHUNK for s, e in spans), spans)
612            covered = sorted(i for s, e in spans for i in range(s // CHUNK, e // CHUNK + 1))
613            self.assertEqual(covered, list(range(41)))                       # every piece once, none twice
614
615    def test_the_last_pieces_are_asked_for_one_by_one(self):
616        st = setup._Pieces(CHUNK * 100, set(), conns=4)
617        todo = list(range(100))
618        self.assertEqual(setup._take_run(st, todo), [0, 1, 2, 3])
619        with mock.patch.object(setup, "DL_RUN", 4):
620            self.assertEqual(setup._take_run(st, list(range(60, 100))), [60, 61, 62, 63])
621            self.assertEqual(setup._take_run(st, list(range(93, 100))), [93])      # fewer than two rounds left
622            self.assertEqual(setup._take_run(st, [5, 9, 10]), [5])                  # only neighbours go together
623
624    def test_a_broken_run_continues_from_the_byte_it_reached(self):
625        cuts = []
626
627        def faults(path, start, end, nth):
628            if end - start + 1 > 2 * CHUNK and not cuts:
629                cuts.append(start)
630                return ("cut", int(2.5 * CHUNK))                           # drops inside the third piece of the run
631            return None
632
633        with small_pieces(DL_RUN=4, DL_CONNECTIONS=2), Server(faults=faults) as srv, tempfile.TemporaryDirectory() as d:
634            code, out = run(srv, d)
635            self.assertIsNone(code, out)
636            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
637            self.assertEqual(len(cuts), 1)
638            first = cuts[0]
639            again = [s for s, e in srv.gets if first < s < first + 4 * CHUNK]
640            self.assertEqual(len(again), 1)                                  # one more request: for the rest
641            self.assertGreaterEqual(again[0], first + 2 * CHUNK)              # the two whole pieces are not fetched again
642
643    def test_a_connection_that_keeps_moving_is_not_given_up_on(self):
644        """Seven breaks in a row (more than DL_CHUNK_TRIES) that each carried bytes forward do not end the request."""
645        count = [0]
646
647        def faults(path, start, end, nth):
648            if start < 4 * CHUNK and end - start + 1 > CHUNK // 2 and count[0] < 7:
649                count[0] += 1
650                return ("cut", CHUNK // 3)
651            return None
652
653        with small_pieces(DL_RUN=4, DL_CONNECTIONS=2, DL_ROUNDS=1), Server(faults=faults) as srv,                 tempfile.TemporaryDirectory() as d:
654            code, out = run(srv, d)
655            self.assertIsNone(code, out)
656            self.assertEqual((Path(d) / NAME).read_bytes(), DATA)
657            self.assertEqual(count[0], 7)
658
659    def test_a_request_without_progress_still_gives_up(self):
660        def faults(path, start, end, nth):
661            if start >= 4 * CHUNK:
662                return ("status", 500)
663            return None
664
665        with small_pieces(DL_RUN=4, DL_ROUNDS=1, DL_CHUNK_TRIES=2), Server(faults=faults) as srv,                 tempfile.TemporaryDirectory() as d:
666            code, out = run(srv, d)
667            self.assertEqual(code, 1)
668            self.assertIn("could not finish downloading", out)
669
670    def test_the_default_is_many_connections_and_runs(self):
671        self.assertGreaterEqual(setup.DL_CONNECTIONS, 8)
672        self.assertGreaterEqual(setup.DL_RUN, 2)
673        self.assertEqual(setup.DL_CHUNK, 32 << 20)                           # the piece list on disk names this size: resumes need it
674
675
676class WholeMarkNeedsThePin(unittest.TestCase):
677    """#4088: a full-length shard with no finish mark and a pinned SHA-256 must not be marked "whole" (the approach of PR #4318, written here).
678
679    A run killed between the rename of a finished .part and the end of its hash leaves exactly that state; the mark the next run wrote made done()
680    true, download() skipped the file, the pinned hash was never checked and a shard damaged by that crash stayed in place."""
681
682    def setUp(self):
683        self.tmp = tempfile.TemporaryDirectory()
684        self.addCleanup(self.tmp.cleanup)
685        self.folder = Path(self.tmp.name)
686        self.repo = next(r for r, files in setup.REPO_PINS.items() if files)
687        self.name = next(iter(setup.REPO_PINS[self.repo]))
688        self.hf = f"https://huggingface.co/{self.repo}/resolve/main/"
689        patch = mock.patch.object(setup, "whole_shard", return_value=True)       # the test is about the mark, not the GGUF header
690        patch.start()
691        self.addCleanup(patch.stop)
692
693    def test_a_pinned_shard_is_left_for_the_download_check(self):
694        shard = self.folder / self.name
695        shard.write_bytes(b"x")
696        self.assertIsNotNone(setup.file_pin(self.hf + self.name), "the file needs a pin for this test to mean anything")
697        setup.mark_whole_unless_pinned([shard], self.hf, own=False)
698        self.assertFalse(setup.done(shard), "no finish mark: download() hashes it and repairs it")
699        self.assertFalse(shard.with_name(shard.name + ".done").exists())
700
701    def test_a_file_without_a_pin_keeps_the_whole_mark(self):
702        shard = self.folder / "hand-copied.gguf"
703        shard.write_bytes(b"x")
704        self.assertIsNone(setup.file_pin(self.hf + shard.name))
705        setup.mark_whole_unless_pinned([shard], self.hf, own=False)
706        self.assertTrue(setup.done(shard))
707        self.assertIn("whole", shard.with_name(shard.name + ".done").read_text(encoding="utf-8"))
708
709    def test_the_persons_own_file_keeps_the_mark(self):
710        shard = self.folder / self.name
711        shard.write_bytes(b"x")
712        setup.mark_whole_unless_pinned([shard], self.hf, own=True)           # --gguf-dir: not a download
713        self.assertTrue(setup.done(shard))
714
715    def test_a_family_with_no_hf_folder_keeps_the_mark_and_does_not_raise(self):
716        """The NVFP4 families have no "hf" key (they download a file list): the helper must not need one (it raised KeyError in main())."""
717        shard = self.folder / self.name
718        shard.write_bytes(b"x")
719        setup.mark_whole_unless_pinned([shard], None, own=False)
720        self.assertTrue(setup.done(shard))
721        setup.mark_whole_unless_pinned([], None, own=False)
722
723    def test_a_marked_or_missing_file_is_not_touched(self):
724        shard = self.folder / "marked.gguf"
725        shard.write_bytes(b"x")
726        setup.mark(shard, "sha256 abc")
727        setup.mark_whole_unless_pinned([shard, self.folder / "absent.gguf"], self.hf, own=False)
728        self.assertEqual(shard.with_name(shard.name + ".done").read_text(encoding="utf-8").strip(), "sha256 abc")
729
730    def test_the_damaged_pinned_file_is_then_hashed_by_the_download(self):
731        """The whole path: full length, no mark, wrong bytes -> not marked -> download() takes its 'stopped before the check' branch and hashes it."""
732        shard = self.folder / self.name
733        shard.write_bytes(b"x" * 8)
734        pin = (8, "ab" * 32)                                                  # a pin of this file's size, so the "full length" branch is the one taken
735        calls = []
736        with mock.patch.dict(setup.REPO_PINS[self.repo], {self.name: pin}), mock.patch.object(setup, "range_total", return_value=8),                 mock.patch.object(setup, "_urlopen", lambda *a, **k: type("R", (), {"headers": {"Content-Length": "8"}, "__enter__": lambda s: s, "__exit__": lambda s, *e: False, "close": lambda s: None})()),                 mock.patch.object(setup, "verify_sha256", lambda *a, **k: calls.append(a)):
737            setup.mark_whole_unless_pinned([shard], self.hf, own=False)
738            self.assertFalse(setup.done(shard))
739            setup.download(self.hf + self.name, shard)
740        self.assertTrue(calls and calls[0][1:3] == pin, "the pinned hash was checked")