okami.mom/strata

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

Niko1221test_download_integrity: a server that keeps serving the wrong file ends with the file kept as .bad (the dlsha behaviour: the new mismatch line, the file not deleted)5b1728358

main
18.2 KiB444 linesraw
1"""0.2.2: a model download never leaves wrong bytes behind, and a file with a wrong SHA-256 is repaired, not thrown away.
2
3A user's 39.8 GB shard arrived with the wrong SHA-256 on 0.2.1 (16 connections, several pieces per request).  These tests run
4setup.download() against a local HTTP server that misbehaves in each way a server, a CDN or a disk can: a 200 for a ranged
5request, a 206 for another range or another total, a body that ends early, another version of the file part-way, a changed
6ETag, a .part written from another mirror, no piece list, a full disk, a raw write that takes fewer bytes than given, and
7bytes that are wrong in the first download (the repair reads the file again and writes only the pieces that differ).
8Pieces are 64 KiB here instead of 32 MiB, so a few MiB stand for the 40 GB."""
9
10from __future__ import annotations
11
12import contextlib
13import hashlib
14import http.server
15import io
16import json
17import random
18import re
19import shutil
20import tempfile
21import threading
22import unittest
23from pathlib import Path
24from unittest import mock
25
26import setup
27from strata_control import transfer
28
29PIECE = 64 << 10
30SIZE = 40 * PIECE + 12345            # 41 pieces, the last one short
31DATA = random.Random(7).randbytes(SIZE)
32SHA = hashlib.sha256(DATA).hexdigest()
33
34
35class Behavior:
36    """What the server does with request number n (1 = the first).  `plan` returns overrides for that answer."""
37
38    def __init__(self, plan=None, data=DATA, etag='"v1"'):
39        self.plan = plan or (lambda n, start, end: {})
40        self.data = data
41        self.etag = etag
42        self.lock = threading.Lock()
43        self.count = 0
44        self.served = []                               # (start, end) of every ranged answer
45        self.once = set()
46
47    def next(self):
48        with self.lock:
49            self.count += 1
50            return self.count
51
52
53class Handler(http.server.BaseHTTPRequestHandler):
54    protocol_version = "HTTP/1.0"                      # one request per connection: ending a body early is a reset
55
56    def log_message(self, *a):
57        pass
58
59    def do_HEAD(self):
60        beh = self.server.beh
61        self.send_response(200)
62        self.send_header("Content-Length", str(len(beh.data)))
63        self.send_header("Accept-Ranges", "bytes")
64        self.end_headers()
65
66    def do_GET(self):
67        beh = self.server.beh
68        n = beh.next()
69        total = len(beh.data)
70        m = re.match(r"bytes=(\d+)-(\d*)", self.headers.get("Range") or "")
71        start = int(m.group(1)) if m else 0
72        end = min(int(m.group(2)), total - 1) if m and m.group(2) else total - 1
73        if start >= total:
74            self.send_response(416)
75            self.end_headers()
76            return
77        o = beh.plan(n, start, end) or {}
78        if o.get("status") == 404 or o.get("status") == 503:
79            self.send_response(o["status"])
80            self.send_header("Content-Length", "0")
81            self.end_headers()
82            return
83        status = o.get("status", 206 if m else 200)
84        b0, b1 = o.get("body", (start, end))
85        body = bytearray(beh.data if status == 200 else beh.data[b0:b1 + 1])
86        for off in o.get("corrupt", ()):
87            lo = 0 if status == 200 else b0
88            if lo <= off < lo + len(body):
89                body[off - lo] ^= 0xFF
90        self.send_response(status)
91        self.send_header("Content-Length", str(o.get("cl", len(body))))
92        if status == 206:
93            self.send_header("Content-Range", o.get("cr", f"bytes {start}-{end}/{total}"))
94        self.send_header("ETag", o.get("etag", beh.etag))
95        self.end_headers()
96        with beh.lock:
97            beh.served.append((start, end))
98        cut = o.get("cut")
99        try:
100            self.wfile.write(bytes(body[:cut] if cut is not None else body))
101        except OSError:
102            pass
103
104
105class Server(http.server.ThreadingHTTPServer):
106    daemon_threads = True
107
108    def handle_error(self, request, client_address):
109        pass
110
111
112class DownloadCase(unittest.TestCase):
113    def setUp(self):
114        self.tmp = Path(tempfile.mkdtemp(prefix="dlint"))
115        self.addCleanup(shutil.rmtree, self.tmp, True)
116        patches = [mock.patch.object(setup, "DL_CHUNK", PIECE), mock.patch.object(setup, "DL_MIN_PARALLEL", PIECE * 4),
117                   mock.patch.object(setup, "DL_BACKOFF", 0.0), mock.patch.object(setup, "DL_SAVE_EVERY", 0.0),
118                   mock.patch.object(setup, "DL_ROUNDS", 3), mock.patch.object(setup.time, "sleep", lambda s: None),
119                   mock.patch.object(setup, "file_pin", lambda url: (SIZE, SHA)),
120                   mock.patch.dict("os.environ", {"STRATA_DL_CONNECTIONS": "4", "STRATA_SOURCE": "huggingface"})]
121        for p in patches:
122            p.start()
123            self.addCleanup(p.stop)
124        self.dst = self.tmp / "model.gguf"
125        self.part = self.tmp / "model.gguf.part"
126
127    def serve(self, beh):
128        srv = Server(("127.0.0.1", 0), Handler)
129        srv.beh = beh
130        threading.Thread(target=srv.serve_forever, daemon=True).start()
131        self.addCleanup(srv.server_close)
132        self.addCleanup(srv.shutdown)
133        self.beh = beh
134        return f"http://127.0.0.1:{srv.server_address[1]}/m/model.gguf"
135
136    def run_download(self, url, expect_exit=False):
137        buf = io.StringIO()
138        with contextlib.redirect_stdout(buf):
139            if expect_exit:
140                with self.assertRaises(SystemExit):
141                    setup.download(url, self.dst)
142            else:
143                setup.download(url, self.dst)
144        self.out = buf.getvalue()
145        return self.out
146
147    def assertGood(self):
148        self.assertTrue(self.dst.is_file(), self.out)
149        self.assertEqual(hashlib.sha256(self.dst.read_bytes()).hexdigest(), SHA)
150        self.assertFalse(self.part.exists())
151        self.assertFalse(self.tmp.joinpath("model.gguf.part.chunks").exists())
152
153
154class Misbehaving(DownloadCase):
155    def test_clean_download(self):
156        self.run_download(self.serve(Behavior()))
157        self.assertGood()
158
159    def test_ranged_requests_answered_with_200_use_one_stream(self):
160        self.run_download(self.serve(Behavior(lambda n, s, e: {"status": 200})))
161        self.assertGood()
162
163    def test_ranges_stop_being_honoured_part_way(self):
164        # the probe and the first pieces are right; later requests get the whole file with a 200
165        self.run_download(self.serve(Behavior(lambda n, s, e: {"status": 200} if n > 6 else {})))
166        self.assertGood()
167
168    def test_206_for_another_range_is_not_written(self):
169        # Content-Range names a range that starts later than the one asked for, from the 5th request on
170        self.run_download(self.serve(Behavior(lambda n, s, e: {"cr": f"bytes {s + 7}-{e}/{SIZE}", "body": (s + 7, e)}
171                                              if n > 4 and s > 0 else {})))
172        self.assertGood()
173
174    def test_206_with_another_total_is_not_written(self):
175        self.run_download(self.serve(Behavior(lambda n, s, e: {"cr": f"bytes {s}-{e}/{SIZE + 1}"} if n > 4 else {})))
176        self.assertGood()
177
178    def test_206_with_a_longer_body_than_asked(self):
179        # Content-Length does not fit the range: tried again, then right
180        self.run_download(self.serve(Behavior(lambda n, s, e: {"cl": e - s + 5} if n in (4, 5, 9) else {})))
181        self.assertGood()
182
183    def test_connection_reset_in_the_middle_of_pieces(self):
184        # every 3rd answer ends after a random part of its body; the piece it broke in is written again from its start
185        rnd = random.Random(3)
186        self.run_download(self.serve(Behavior(lambda n, s, e: {"cut": rnd.randrange(1, max(2, e - s))} if n % 3 == 0 else {})))
187        self.assertGood()
188
189    def test_an_answer_cut_after_a_whole_number_of_blocks_still_ends_in_the_right_bytes(self):
190        self.run_download(self.serve(Behavior(lambda n, s, e: {"cut": PIECE + 17} if n in (3, 4, 5, 6) else {})))
191        self.assertGood()
192
193    def test_one_answer_from_another_version_is_asked_again(self):
194        self.run_download(self.serve(Behavior(lambda n, s, e: {"etag": '"v2"'} if n in (4, 7) else {})))
195        self.assertGood()
196
197    def test_another_version_for_good_stops_and_leaves_no_file(self):
198        out = self.run_download(self.serve(Behavior(lambda n, s, e: {"etag": '"v2"'} if n > 3 else {})), expect_exit=True)
199        self.assertFalse(self.dst.exists())
200
201    def test_the_file_changing_between_resolves_is_noticed(self):
202        src = setup._Source("http://x/y", SIZE)
203        src.etag = "aaa"
204
205        class R:
206            status = 206
207            headers = {"Content-Range": f"bytes 0-0/{SIZE}", "ETag": '"bbb"'}
208
209            def __enter__(self):
210                return self
211
212            def __exit__(self, *a):
213                return False
214
215            def read(self, n):
216                return b"x"
217
218            def geturl(self):
219                return "http://x/y"
220
221        with mock.patch.object(setup, "_urlopen", lambda *a, **k: R()):
222            with self.assertRaises(setup._Changed):
223                src.resolve()
224
225    def test_server_error_part_way_keeps_pieces_and_a_second_run_finishes(self):
226        url = self.serve(Behavior(lambda n, s, e: {"status": 503} if n > 12 else {}))
227        self.run_download(url, expect_exit=True)
228        self.assertTrue(self.part.exists())
229        self.assertTrue(self.tmp.joinpath("model.gguf.part.chunks").exists())
230        first_run = len(self.beh.served)
231        self.beh.plan = lambda n, s, e: {}                     # the same address, now answering
232        self.beh.served.clear()
233        self.run_download(url)
234        self.assertGood()
235        fetched = sum(e - s + 1 for s, e in self.beh.served if e > s)       # without the one-byte probes
236        self.assertLess(fetched, SIZE, "the second run took the whole file again instead of resuming")
237        self.assertGreater(first_run, 1)
238
239    def test_two_interrupted_runs_then_a_good_one(self):
240        url = self.serve(Behavior())
241        for limit in (6, 6):
242            self.beh.count = 0
243            self.beh.plan = lambda n, s, e, limit=limit: {"status": 503} if n > limit else {}
244            self.run_download(url, expect_exit=True)
245        self.beh.plan = lambda n, s, e: {}
246        self.run_download(url)
247        self.assertGood()
248
249    def test_a_part_written_from_another_mirror_is_dropped(self):
250        url = self.serve(Behavior())
251        self.part.write_bytes(b"\xaa" * (PIECE * 10))
252        self.tmp.joinpath("model.gguf.part.chunks").write_text(
253            json.dumps({"v": 1, "total": SIZE, "chunk": PIECE, "done": [[0, 10]]}), encoding="utf-8")
254        self.tmp.joinpath("model.gguf.part.src").write_text(
255            json.dumps({"url": "https://www.modelscope.cn/models/x/resolve/master/model.gguf", "etag": None}), encoding="utf-8")
256        self.run_download(url)
257        self.assertGood()                                      # the 0xaa pieces were not trusted
258
259    def test_a_part_of_another_version_is_dropped(self):
260        url = self.serve(Behavior())
261        self.part.write_bytes(b"\xaa" * (PIECE * 10))
262        self.tmp.joinpath("model.gguf.part.chunks").write_text(
263            json.dumps({"v": 1, "total": SIZE, "chunk": PIECE, "done": [[0, 10]]}), encoding="utf-8")
264        self.tmp.joinpath("model.gguf.part.src").write_text(json.dumps({"url": url, "etag": '"old"'}), encoding="utf-8")
265        self.run_download(url)
266        self.assertGood()
267
268    def test_without_a_writable_piece_list_the_file_is_not_written_in_parts(self):
269        url = self.serve(Behavior())
270        with mock.patch.object(setup, "_save_pieces", return_value=False):
271            self.run_download(url)
272        self.assertGood()
273
274    def test_a_stale_piece_list_never_names_bytes_the_part_lacks(self):
275        self.part.write_bytes(b"\x00" * (PIECE * 3))
276        self.tmp.joinpath("model.gguf.part.chunks").write_text(
277            json.dumps({"v": 1, "total": SIZE, "chunk": PIECE, "done": [[0, 30]]}), encoding="utf-8")
278        self.assertEqual(setup._load_pieces(self.part, SIZE), {0, 1, 2})
279
280    def test_full_disk_stops_with_a_plain_message_and_keeps_the_part(self):
281        url = self.serve(Behavior())
282
283        def full(f, pos, data):
284            raise OSError(28, "No space left on device")
285
286        with mock.patch.object(setup, "_write_all", full):
287            out = self.run_download(url, expect_exit=True)
288        self.assertIn("cannot write", out)
289        self.assertIn("free some disk space", out)
290        self.assertFalse(self.dst.exists())
291
292    def test_a_raw_write_that_takes_fewer_bytes_is_finished(self):
293        class Slow:
294            def __init__(self):
295                self.buf = bytearray(100)
296                self.pos = 0
297
298            def seek(self, p):
299                self.pos = p
300
301            def write(self, v):
302                n = min(7, len(v))
303                self.buf[self.pos:self.pos + n] = bytes(v[:n])
304                self.pos += n
305                return n
306
307        f = Slow()
308        setup._write_all(f, 10, bytes(range(60)))
309        self.assertEqual(bytes(f.buf[10:70]), bytes(range(60)))
310
311    def test_a_raw_write_that_takes_nothing_is_an_error(self):
312        class Zero:
313            def seek(self, p):
314                pass
315
316            def write(self, v):
317                return 0
318
319        with self.assertRaises(OSError):
320            setup._write_all(Zero(), 0, b"abc")
321
322    def test_single_stream_resume_ignores_a_206_from_the_wrong_offset(self):
323        url = self.serve(Behavior(lambda n, s, e: {"cr": f"bytes {s + 5}-{e}/{SIZE}", "body": (s + 5, e)} if s > 0 else {}))
324        self.part.write_bytes(DATA[:PIECE * 3])
325        with mock.patch.dict("os.environ", {"STRATA_DL_CONNECTIONS": "1"}):
326            self.run_download(url)
327        self.assertGood()
328
329    def test_single_stream_resume_ignores_a_200(self):
330        url = self.serve(Behavior(lambda n, s, e: {"status": 200}))
331        self.part.write_bytes(DATA[:PIECE * 3])
332        with mock.patch.dict("os.environ", {"STRATA_DL_CONNECTIONS": "1"}):
333            self.run_download(url)
334        self.assertGood()
335
336    def test_finished_file_without_a_mark_is_checked_not_marked(self):
337        self.dst.write_bytes(DATA[:-1] + b"\x00")
338        url = self.serve(Behavior())
339        self.run_download(url)
340        self.assertIn("Some parts of model.gguf were damaged", self.out)
341        self.assertGood()
342        self.assertTrue(self.tmp.joinpath("model.gguf.done").exists())
343
344
345class Repair(DownloadCase):
346    def test_wrong_bytes_in_two_pieces_are_found_and_only_those_rewritten(self):
347        bad = [5 * PIECE + 100, 30 * PIECE + 7]
348        seen = set()
349
350        def plan(n, s, e):
351            hit = [o for o in bad if s <= o <= e and o not in seen]
352            seen.update(hit)
353            return {"corrupt": hit} if hit else {}
354
355        out = self.run_download(self.serve(Behavior(plan)))
356        self.assertGood()
357        self.assertIn("Some parts of model.gguf were damaged; downloading only those parts again", out)
358        self.assertIn("2 of 41 parts were different", out)
359        self.assertTrue(self.tmp.joinpath("model.gguf.done").exists())
360
361    def test_one_flipped_byte_in_the_last_short_piece(self):
362        bad = [SIZE - 3]
363        seen = set()
364
365        def plan(n, s, e):
366            hit = [o for o in bad if s <= o <= e and o not in seen]
367            seen.update(hit)
368            return {"corrupt": hit} if hit else {}
369
370        out = self.run_download(self.serve(Behavior(plan)))
371        self.assertGood()
372        self.assertIn("1 of 41 parts were different", out)
373
374    def test_a_repair_that_loses_the_connection_part_way_still_ends_right(self):
375        bad = [3 * PIECE + 1]
376        seen = set()
377
378        def plan(n, s, e):
379            hit = [o for o in bad if s <= o <= e and o not in seen]
380            seen.update(hit)
381            o = {"corrupt": hit} if hit else {}
382            if seen and n % 4 == 0:
383                o["cut"] = 5000
384            return o
385
386        self.run_download(self.serve(Behavior(plan)))
387        self.assertGood()
388
389    def test_a_server_that_keeps_serving_the_wrong_file_ends_with_the_file_kept_as_bad(self):
390        wrong = bytearray(DATA)
391        wrong[1000] ^= 0xFF
392        url = self.serve(Behavior(data=bytes(wrong)))
393        out = self.run_download(url, expect_exit=True)
394        self.assertIn("does not match the pinned SHA-256", out)
395        self.assertFalse(self.dst.exists())
396        self.assertTrue(self.dst.with_name(self.dst.name + ".bad").is_file())   # kept, not deleted (f-0216-dlsha)
397        self.assertFalse(self.tmp.joinpath("model.gguf.done").exists())
398
399    def test_the_repair_is_off_for_a_file_the_person_owns(self):
400        self.dst.write_bytes(b"x" * SIZE)
401        called = []
402        with contextlib.redirect_stdout(io.StringIO()):
403            with self.assertRaises(SystemExit):
404                setup.verify_sha256(self.dst, SIZE, SHA, own=True, repair=lambda: called.append(1))
405        self.assertEqual(called, [])
406        self.assertTrue(self.dst.exists())
407
408
409class UpdateTransfer(unittest.TestCase):
410    """strata_control/transfer.py (update archives): a resumed answer is appended only when it starts at the byte asked for."""
411
412    def setUp(self):
413        self.tmp = Path(tempfile.mkdtemp(prefix="dlint"))
414        self.addCleanup(shutil.rmtree, self.tmp, True)
415
416    def test_resume_check(self):
417        class R:
418            def __init__(self, status, cr):
419                self.status = status
420                self.headers = {"Content-Range": cr} if cr else {}
421
422        self.assertTrue(transfer._resumes_at(R(206, "bytes 100-999/1000"), 100, 1000))
423        self.assertFalse(transfer._resumes_at(R(206, "bytes 0-999/1000"), 100, 1000))
424        self.assertFalse(transfer._resumes_at(R(206, "bytes 100-999/2000"), 100, 1000))
425        self.assertFalse(transfer._resumes_at(R(206, ""), 100, 1000))
426        self.assertFalse(transfer._resumes_at(R(200, "bytes 100-999/1000"), 100, 1000))
427
428    def test_a_206_from_the_wrong_offset_restarts_the_file(self):
429        data = DATA[:200000]
430        beh = Behavior(lambda n, s, e: {"cr": f"bytes {s + 9}-{e}/{len(data)}", "body": (s + 9, e)} if s > 0 else {}, data=data)
431        srv = Server(("127.0.0.1", 0), Handler)
432        srv.beh = beh
433        threading.Thread(target=srv.serve_forever, daemon=True).start()
434        self.addCleanup(srv.server_close)
435        self.addCleanup(srv.shutdown)
436        part = self.tmp / "a.part"
437        part.write_bytes(data[:50000])
438        got = transfer.download(f"http://127.0.0.1:{srv.server_address[1]}/a", part, size=len(data),
439                                sha256=hashlib.sha256(data).hexdigest())
440        self.assertEqual(got.read_bytes(), data)
441
442
443if __name__ == "__main__":
444    unittest.main()