File size: 46,174 Bytes
9a46c96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
from __future__ import annotations

from contextlib import contextmanager
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import io
import json
from pathlib import Path
import sys
import threading
import types
from urllib.error import HTTPError

import pytest
import yaml

import dlb.checkpoints as checkpoints_module
from dlb.checkpoints import (
    CheckpointResource,
    DigestSpec,
    DirectSource,
    GDriveSource,
    HuggingFaceSource,
    ZenodoSource,
    build_hf_snapshot_kwargs,
    download_direct,
    fetch_resource,
    publish_partial,
    require_server_platform,
    safe_checkpoint_destination,
    safe_remote_path,
    select_zenodo_files,
    verify_checkpoint_lock,
    verify_published_file,
)


def write_single_resource_manifest(tmp_path: Path) -> Path:
    manifest = tmp_path / "artifacts" / "checkpoints.yaml"
    manifest.parent.mkdir(parents=True, exist_ok=True)
    manifest.write_text(
        yaml.safe_dump(
            {
                "schema_version": 1,
                "resources": {
                    "test_direct": {
                        "id": "test_direct",
                        "backend": "direct",
                        "provenance": "official",
                        "teacher_family": "masked_mdlm",
                        "destination": "official/test",
                        "license": "test",
                        "terms_url": "https://example.test/terms",
                        "digest": {"policy": "capture_after_download"},
                        "required_files": ["model.bin"],
                        "source": {
                            "url": "https://example.test/model.bin",
                            "filename": "model.bin",
                        },
                    }
                },
                "recipes": {},
                "coverage": [],
            },
            sort_keys=False,
        ),
        encoding="utf-8",
    )
    return manifest


def manifest_bound_lock(manifest: Path, file_path: str, payload: bytes) -> dict[str, object]:
    return {
        "schema_version": 1,
        "manifest_sha256": hashlib.sha256(manifest.read_bytes()).hexdigest(),
        "resources": {
            "test_direct": {
                "status": "downloaded",
                "backend": "direct",
                "provenance": "official",
                "teacher_family": "masked_mdlm",
                "destination": "checkpoints/official/test",
                "files": [
                    {
                        "path": file_path,
                        "size_bytes": len(payload),
                        "sha256": hashlib.sha256(payload).hexdigest(),
                    }
                ],
            }
        },
    }


@contextmanager
def ranged_http_server(payload: bytes):
    requests: list[str | None] = []

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            range_header = self.headers.get("Range")
            requests.append(range_header)
            start = int(range_header.removeprefix("bytes=").removesuffix("-")) if range_header else 0
            body = payload[start:]
            self.send_response(206 if range_header else 200)
            self.send_header("Content-Length", str(len(body)))
            if range_header:
                self.send_header("Content-Range", f"bytes {start}-{len(payload)-1}/{len(payload)}")
            self.end_headers()
            self.wfile.write(body)

        def log_message(self, format, *args):
            return

    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        yield f"http://127.0.0.1:{server.server_port}/checkpoint.bin", requests
    finally:
        server.shutdown()
        thread.join()


class FakeHTTPResponse(io.BytesIO):
    def __init__(self, payload: bytes, *, status: int, headers: dict[str, str]):
        super().__init__(payload)
        self.status = status
        self.headers = headers

    def getcode(self):
        return self.status

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()


def install_fake_http(monkeypatch, responses):
    requests = []
    queue = list(responses)

    def fake_urlopen(request):
        requests.append({key.lower(): value for key, value in request.header_items()})
        result = queue.pop(0)
        if isinstance(result, BaseException):
            raise result
        return result

    monkeypatch.setattr(checkpoints_module, "urlopen", fake_urlopen)
    return requests


def write_partial_resume_state(
    target: Path, payload: bytes, validator: str, total_size: int
) -> None:
    partial = target.with_name(target.name + ".partial")
    partial.write_bytes(payload)
    partial.with_name(partial.name + ".meta.json").write_text(
        json.dumps(
            {
                "url": "https://example.test/model.bin",
                "validator_header": "ETag",
                "validator_value": validator,
                "total_size": total_size,
            }
        ),
        encoding="utf-8",
    )


def test_direct_download_discards_unvalidated_partial_and_atomically_publishes(
    tmp_path, monkeypatch
):
    """Catch partial bytes without entity metadata being trusted for resume."""

    payload = b"checkpoint-payload-for-resume"
    digest = hashlib.sha256(payload).hexdigest()
    target = tmp_path / "model.bin"
    partial = target.with_name(target.name + ".partial")
    partial.write_bytes(payload[:11])
    monkeypatch.setenv("NO_PROXY", "127.0.0.1")
    monkeypatch.setenv("no_proxy", "127.0.0.1")

    with ranged_http_server(payload) as (url, requests):
        result = download_direct(
            DirectSource(url=url, filename="model.bin"),
            target,
            DigestSpec(policy="sha256", sha256=digest),
        )

    assert requests == [None]
    assert target.read_bytes() == payload
    assert not partial.exists()
    assert result["status"] == "downloaded"
    assert result["sha256"] == digest


def test_direct_download_reuses_a_nonempty_regular_target(tmp_path, monkeypatch):
    payload = b"existing-checkpoint"
    target = tmp_path / "model.bin"
    target.write_bytes(payload)
    requests = install_fake_http(monkeypatch, [])

    result = download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(payload).hexdigest()),
    )

    assert requests == []
    assert result["status"] == "reused"
    assert result["size_bytes"] == len(payload)
    assert target.read_bytes() == payload


def test_direct_download_quarantines_an_empty_matching_target_before_reuse(
    tmp_path, monkeypatch
):
    target = tmp_path / "checkpoints" / "official" / "model.bin"
    target.parent.mkdir(parents=True)
    target.write_bytes(b"")
    requests = install_fake_http(
        monkeypatch,
        [
            FakeHTTPResponse(
                b"replacement",
                status=200,
                headers={"Content-Length": "11", "ETag": '"v2"'},
            )
        ],
    )

    with pytest.raises(ValueError, match="download digest mismatch"):
        download_direct(
            DirectSource(
                url="https://example.test/model.bin", filename="model.bin"
            ),
            target,
            DigestSpec(
                policy="sha256", sha256=hashlib.sha256(b"").hexdigest()
            ),
            quarantine_root=tmp_path / "checkpoints" / "quarantine",
        )

    assert requests == [{}]
    assert not target.exists()
    quarantined = list(
        (tmp_path / "checkpoints" / "quarantine").glob(
            "*/official/model.bin"
        )
    )
    assert len(quarantined) == 1
    assert quarantined[0].is_file()
    assert quarantined[0].stat().st_size == 0


def test_direct_resume_sends_if_range_and_accepts_exact_validated_206(
    tmp_path, monkeypatch
):
    """Catch a valid partial resume that is not bound to its original HTTP entity."""

    payload = b"abcdefghij"
    target = tmp_path / "model.bin"
    write_partial_resume_state(target, payload[:4], '"v1"', len(payload))
    requests = install_fake_http(
        monkeypatch,
        [
            FakeHTTPResponse(
                payload[4:],
                status=206,
                headers={
                    "Content-Range": "bytes 4-9/10",
                    "Content-Length": "6",
                    "ETag": '"v1"',
                },
            )
        ],
    )

    download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(payload).hexdigest()),
    )

    assert requests == [{"range": "bytes=4-", "if-range": '"v1"'}]
    assert target.read_bytes() == payload
    assert not target.with_name("model.bin.partial.meta.json").exists()


def test_direct_resume_restarts_when_content_range_starts_at_wrong_offset(
    tmp_path, monkeypatch
):
    """Catch appending a 206 response that does not begin at the partial size."""

    payload = b"abcdefghij"
    target = tmp_path / "model.bin"
    write_partial_resume_state(target, payload[:4], '"v1"', len(payload))
    requests = install_fake_http(
        monkeypatch,
        [
            FakeHTTPResponse(
                payload[3:],
                status=206,
                headers={"Content-Range": "bytes 3-9/10", "ETag": '"v1"'},
            ),
            FakeHTTPResponse(
                payload,
                status=200,
                headers={"Content-Length": "10", "ETag": '"v1"'},
            ),
        ],
    )

    download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(payload).hexdigest()),
    )

    assert requests[0] == {"range": "bytes=4-", "if-range": '"v1"'}
    assert requests[1] == {}
    assert target.read_bytes() == payload


def test_direct_resume_uses_full_200_fallback_without_appending(tmp_path, monkeypatch):
    """Catch a server's full-response fallback being appended to old partial bytes."""

    payload = b"abcdefghij"
    target = tmp_path / "model.bin"
    write_partial_resume_state(target, b"old!", '"v1"', len(payload))
    requests = install_fake_http(
        monkeypatch,
        [
            FakeHTTPResponse(
                payload,
                status=200,
                headers={"Content-Length": "10", "ETag": '"v2"'},
            )
        ],
    )

    download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(payload).hexdigest()),
    )

    assert requests == [{"range": "bytes=4-", "if-range": '"v1"'}]
    assert target.read_bytes() == payload
    assert not target.with_name("model.bin.partial.meta.json").exists()


def test_direct_resume_restarts_when_entity_validator_changes(tmp_path, monkeypatch):
    """Catch combining old partial bytes with a different ETag's ranged response."""

    old_payload = b"abcdefghij"
    new_payload = b"1234567890"
    target = tmp_path / "model.bin"
    write_partial_resume_state(target, old_payload[:4], '"v1"', len(old_payload))
    requests = install_fake_http(
        monkeypatch,
        [
            FakeHTTPResponse(
                new_payload[4:],
                status=206,
                headers={"Content-Range": "bytes 4-9/10", "ETag": '"v2"'},
            ),
            FakeHTTPResponse(
                new_payload,
                status=200,
                headers={"Content-Length": "10", "ETag": '"v2"'},
            ),
        ],
    )

    download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(new_payload).hexdigest()),
    )

    assert requests[0] == {"range": "bytes=4-", "if-range": '"v1"'}
    assert requests[1] == {}
    assert target.read_bytes() == new_payload


def test_complete_partial_revalidates_unchanged_entity_without_redownload(
    tmp_path, monkeypatch
):
    """Catch complete partials issuing an invalid bytes=<total>- request."""

    payload = b"abcdefghij"
    target = tmp_path / "model.bin"
    write_partial_resume_state(target, payload, '"v1"', len(payload))
    requests = install_fake_http(
        monkeypatch,
        [
            FakeHTTPResponse(
                payload[:1],
                status=206,
                headers={
                    "Content-Range": "bytes 0-0/10",
                    "Content-Length": "1",
                    "ETag": '"v1"',
                },
            )
        ],
    )

    download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(payload).hexdigest()),
    )

    assert requests == [{"range": "bytes=0-0", "if-range": '"v1"'}]
    assert target.read_bytes() == payload


def test_complete_partial_overwrites_when_entity_changed(tmp_path, monkeypatch):
    """Catch a complete old entity being published after validator mismatch."""

    old_payload = b"abcdefghij"
    new_payload = b"1234567890"
    target = tmp_path / "model.bin"
    write_partial_resume_state(target, old_payload, '"v1"', len(old_payload))
    requests = install_fake_http(
        monkeypatch,
        [
            FakeHTTPResponse(
                new_payload,
                status=200,
                headers={"Content-Length": "10", "ETag": '"v2"'},
            )
        ],
    )

    download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(new_payload).hexdigest()),
    )

    assert requests == [{"range": "bytes=0-0", "if-range": '"v1"'}]
    assert target.read_bytes() == new_payload


def test_complete_partial_handles_416_once_then_restarts_without_range(
    tmp_path, monkeypatch
):
    """Catch identical Range retry loops after an HTTP 416 response."""

    payload = b"abcdefghij"
    target = tmp_path / "model.bin"
    write_partial_resume_state(target, payload, '"v1"', len(payload))
    error = HTTPError(
        "https://example.test/model.bin", 416, "Range Not Satisfiable", {}, None
    )
    requests = install_fake_http(
        monkeypatch,
        [
            error,
            FakeHTTPResponse(
                payload,
                status=200,
                headers={"Content-Length": "10", "ETag": '"v1"'},
            ),
        ],
    )

    download_direct(
        DirectSource(url="https://example.test/model.bin", filename="model.bin"),
        target,
        DigestSpec(policy="sha256", sha256=hashlib.sha256(payload).hexdigest()),
    )

    assert requests == [
        {"range": "bytes=0-0", "if-range": '"v1"'},
        {},
    ]
    assert target.read_bytes() == payload


def test_direct_download_rejects_a_symlinked_partial_before_writing(tmp_path, monkeypatch):
    """Catch resume writes following a sibling .partial symlink outside staging."""

    outside = tmp_path / "outside.bin"
    outside.write_bytes(b"sentinel")
    target = tmp_path / "checkpoints" / "model.bin"
    target.parent.mkdir()
    target.with_name("model.bin.partial").symlink_to(outside)
    monkeypatch.setenv("NO_PROXY", "127.0.0.1")
    monkeypatch.setenv("no_proxy", "127.0.0.1")

    with ranged_http_server(b"replacement") as (url, requests):
        with pytest.raises(ValueError, match="symlink"):
            download_direct(
                DirectSource(url=url, filename="model.bin"),
                target,
                DigestSpec(policy="capture_after_download"),
            )

    assert requests == []
    assert outside.read_bytes() == b"sentinel"


def test_huggingface_fetch_rejects_a_symlinked_staging_directory(tmp_path, monkeypatch):
    """Catch snapshot_download following an existing snapshot.partial symlink."""

    checkpoint_root = tmp_path / "checkpoints"
    outside = tmp_path / "outside"
    outside.mkdir()
    partial = checkpoint_root / "official" / "model.partial"
    partial.parent.mkdir(parents=True)
    partial.symlink_to(outside, target_is_directory=True)
    called = False

    def fake_snapshot_download(**kwargs):
        nonlocal called
        called = True

    monkeypatch.setitem(
        sys.modules,
        "huggingface_hub",
        types.SimpleNamespace(snapshot_download=fake_snapshot_download),
    )
    resource = CheckpointResource.model_validate(
        {
            "id": "test_hf",
            "backend": "huggingface",
            "provenance": "official",
            "teacher_family": "masked_mdlm",
            "destination": "official/model",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {"policy": "capture_after_download"},
            "required_files": ["model.safetensors"],
            "source": {
                "repo_id": "owner/model",
                "revision": "a" * 40,
                "allow_patterns": ["*.safetensors"],
            },
        }
    )

    with pytest.raises(ValueError, match="symlink"):
        fetch_resource(tmp_path, resource)

    assert called is False
    assert list(outside.iterdir()) == []


@pytest.mark.parametrize(
    "payload",
    [
        {},
        {"README.md": b"metadata", "config.json": b"{}"},
        {"config.json": b"{}", "model.safetensors": b""},
    ],
    ids=["empty", "metadata-only", "empty-primary"],
)
def test_huggingface_fetch_requires_primary_weight_before_publication(
    tmp_path, monkeypatch, payload
):
    """Catch empty or README/config-only snapshots being locked as models."""

    def fake_snapshot_download(**kwargs):
        staging = Path(kwargs["local_dir"])
        for name, content in payload.items():
            (staging / name).write_bytes(content)

    monkeypatch.setitem(
        sys.modules,
        "huggingface_hub",
        types.SimpleNamespace(snapshot_download=fake_snapshot_download),
    )
    resource = CheckpointResource.model_validate(
        {
            "id": "test_hf",
            "backend": "huggingface",
            "provenance": "official",
            "teacher_family": "masked_mdlm",
            "destination": "official/model",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {"policy": "capture_after_download"},
            "required_files": ["config.json", "model.safetensors"],
            "source": {
                "repo_id": "owner/model",
                "revision": "a" * 40,
                "allow_patterns": ["README.md", "config.json", "model.safetensors"],
            },
        }
    )

    with pytest.raises(FileNotFoundError, match="required checkpoint file"):
        fetch_resource(tmp_path, resource)

    assert not (tmp_path / "checkpoints" / "official" / "model").exists()


def test_direct_fetch_rejects_an_empty_required_file(tmp_path, monkeypatch):
    """Catch capture policy locking an empty direct-download payload as successful."""

    requests = install_fake_http(
        monkeypatch,
        [FakeHTTPResponse(b"", status=200, headers={"Content-Length": "0", "ETag": '"v1"'})],
    )
    resource = CheckpointResource.model_validate(
        {
            "id": "test_direct",
            "backend": "direct",
            "provenance": "official",
            "teacher_family": "masked_mdlm",
            "destination": "official/direct",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {"policy": "capture_after_download"},
            "required_files": ["model.bin"],
            "source": {
                "url": "https://example.test/model.bin",
                "filename": "model.bin",
            },
        }
    )

    with pytest.raises(FileNotFoundError, match="empty"):
        fetch_resource(tmp_path, resource)

    assert requests == [{}]


def test_huggingface_fetch_enforces_per_file_manifest_digests(tmp_path, monkeypatch):
    """Catch HF publication bypassing the resource's declared digest policy."""

    def fake_snapshot_download(**kwargs):
        staging = Path(kwargs["local_dir"])
        (staging / "config.json").write_bytes(b"config")
        (staging / "model.safetensors").write_bytes(b"weights")

    monkeypatch.setitem(
        sys.modules,
        "huggingface_hub",
        types.SimpleNamespace(snapshot_download=fake_snapshot_download),
    )
    resource = CheckpointResource.model_validate(
        {
            "id": "test_hf",
            "backend": "huggingface",
            "provenance": "official",
            "teacher_family": "masked_mdlm",
            "destination": "official/model",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {
                "policy": "sha256",
                "per_file_sha256": {
                    "config.json": hashlib.sha256(b"config").hexdigest(),
                    "model.safetensors": "0" * 64,
                },
            },
            "required_files": ["config.json", "model.safetensors"],
            "source": {
                "repo_id": "owner/model",
                "revision": "a" * 40,
                "allow_patterns": ["config.json", "model.safetensors"],
            },
        }
    )

    with pytest.raises(ValueError, match="download digest mismatch"):
        fetch_resource(tmp_path, resource)

    assert not (tmp_path / "checkpoints" / "official" / "model").exists()


def test_mismatch_is_quarantined_before_replacement(tmp_path):
    """Catch corrupt existing checkpoints being overwritten without audit evidence."""

    target = tmp_path / "official" / "model.bin"
    target.parent.mkdir(parents=True)
    target.write_bytes(b"corrupt")
    partial = target.with_name(target.name + ".partial")
    partial.write_bytes(b"correct")
    expected = hashlib.sha256(b"correct").hexdigest()

    result = publish_partial(
        partial,
        target,
        DigestSpec(policy="sha256", sha256=expected),
        quarantine_root=tmp_path / "quarantine",
        timestamp="20260729T120000Z",
    )

    assert target.read_bytes() == b"correct"
    quarantined = tmp_path / "quarantine" / "20260729T120000Z" / "official" / "model.bin"
    assert quarantined.read_bytes() == b"corrupt"
    assert result["quarantined"] == quarantined.as_posix()


@pytest.mark.parametrize(
    "name",
    ["../escape.ckpt", "/absolute.ckpt", "nested/../../escape", "", ".", "a\\b"],
)
def test_remote_filenames_cannot_escape_destination(name):
    """Catch provider-controlled filenames traversing outside the checkpoint root."""

    with pytest.raises(ValueError, match="unsafe remote path"):
        safe_remote_path(name)


def test_checkpoint_destination_rejects_a_symlinked_ancestor(tmp_path):
    """Catch downloads escaping through a pre-existing symlink under checkpoints."""

    checkpoint_root = tmp_path / "root" / "checkpoints"
    outside = tmp_path / "outside"
    checkpoint_root.mkdir(parents=True)
    outside.mkdir()
    (checkpoint_root / "official").symlink_to(outside, target_is_directory=True)

    with pytest.raises(ValueError, match="symlink"):
        safe_checkpoint_destination(checkpoint_root, "official/model/checkpoint.bin")


def test_huggingface_backend_pins_revision_and_allow_patterns(tmp_path):
    """Catch broad or moving Hugging Face snapshot requests."""

    source = HuggingFaceSource(
        repo_id="owner/model",
        revision="a" * 40,
        allow_patterns=["*.json", "*.safetensors"],
    )

    assert build_hf_snapshot_kwargs(source, tmp_path / "snapshot.partial") == {
        "repo_id": "owner/model",
        "revision": "a" * 40,
        "allow_patterns": ["*.json", "*.safetensors"],
        "local_dir": str(tmp_path / "snapshot.partial"),
        "resume_download": True,
    }


def test_gdrive_backend_addresses_each_expected_file_by_immutable_id(tmp_path):
    """Catch mutable folder-name discovery replacing manifest-pinned file IDs."""

    source = GDriveSource(
        folder_id="folder123",
        expected_files={"LM1B/checkpoint.pth": "fileA", "LM1B/config.yaml": "fileB"},
    )
    staging = tmp_path / "rdlm.partial"

    assert checkpoints_module.build_gdrive_commands(source, staging) == [
        [
            "gdown",
            "--continue",
            "fileA",
            "--output",
            str(staging / ".objects" / "fileA.partial"),
        ],
        [
            "gdown",
            "--continue",
            "fileB",
            "--output",
            str(staging / ".objects" / "fileB.partial"),
        ],
    ]


def test_gdrive_fetch_replaces_same_name_staging_from_pinned_file_ids(tmp_path, monkeypatch):
    """Catch a stale same-name file passing without acquisition by its declared ID."""

    resource = CheckpointResource.model_validate(
        {
            "id": "test_drive",
            "backend": "gdrive",
            "provenance": "official",
            "teacher_family": "continuous_rdlm",
            "destination": "official/rdlm",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {"policy": "capture_after_download"},
            "required_files": ["LM1B/checkpoint.pth", "LM1B/config.yaml"],
            "source": {
                "folder_id": "folder123",
                "expected_files": {
                    "LM1B/checkpoint.pth": "fileA",
                    "LM1B/config.yaml": "fileB",
                },
            },
        }
    )
    staging = tmp_path / "checkpoints" / "official" / "rdlm.partial"
    stale = staging / "LM1B" / "checkpoint.pth"
    stale.parent.mkdir(parents=True)
    stale.write_bytes(b"wrong-same-name")
    calls = []

    def fake_run(command, check):
        assert check is True
        calls.append(command)
        assert "--id" not in command
        file_id = command[2]
        output = Path(command[command.index("--output") + 1])
        assert output.parent.is_dir()
        output.write_bytes({"fileA": b"weights", "fileB": b"config"}[file_id])
        return types.SimpleNamespace(returncode=0)

    monkeypatch.setattr(checkpoints_module.subprocess, "run", fake_run)

    record = fetch_resource(tmp_path, resource)

    destination = tmp_path / "checkpoints" / "official" / "rdlm" / "LM1B"
    assert (destination / "checkpoint.pth").read_bytes() == b"weights"
    assert (destination / "config.yaml").read_bytes() == b"config"
    assert [command[2] for command in calls] == ["fileA", "fileB"]
    assert record["status"] == "downloaded"


def test_gdrive_fetch_enforces_per_file_manifest_digests(tmp_path, monkeypatch):
    """Catch Drive ID downloads bypassing the resource's declared digest policy."""

    resource = CheckpointResource.model_validate(
        {
            "id": "test_drive",
            "backend": "gdrive",
            "provenance": "official",
            "teacher_family": "continuous_rdlm",
            "destination": "official/rdlm",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {
                "policy": "sha256",
                "per_file_sha256": {
                    "checkpoint.pth": "0" * 64,
                    "config.yaml": hashlib.sha256(b"config").hexdigest(),
                },
            },
            "required_files": ["checkpoint.pth", "config.yaml"],
            "source": {
                "folder_id": "folder123",
                "expected_files": {"checkpoint.pth": "fileA", "config.yaml": "fileB"},
            },
        }
    )

    def fake_run(command, check):
        assert "--id" not in command
        file_id = command[2]
        output = Path(command[command.index("--output") + 1])
        output.write_bytes({"fileA": b"weights", "fileB": b"config"}[file_id])
        return types.SimpleNamespace(returncode=0)

    monkeypatch.setattr(checkpoints_module.subprocess, "run", fake_run)

    with pytest.raises(ValueError, match="download digest mismatch"):
        fetch_resource(tmp_path, resource)

    assert not (tmp_path / "checkpoints" / "official" / "rdlm").exists()


def test_gdrive_stale_partial_is_quarantined_and_rerun_succeeds(
    tmp_path, monkeypatch
):
    """Catch unexpected staging files causing every Drive rerun to fail forever."""

    resource = CheckpointResource.model_validate(
        {
            "id": "test_drive",
            "backend": "gdrive",
            "provenance": "official",
            "teacher_family": "continuous_rdlm",
            "destination": "official/rdlm",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {"policy": "capture_after_download"},
            "required_files": ["checkpoint.pth", "config.yaml"],
            "source": {
                "folder_id": "folder123",
                "expected_files": {"checkpoint.pth": "fileA", "config.yaml": "fileB"},
            },
        }
    )
    staging = tmp_path / "checkpoints" / "official" / "rdlm.partial"
    object_path = staging / ".objects" / "fileA.partial"
    object_path.parent.mkdir(parents=True)
    object_path.write_bytes(b"resume-prefix")
    (staging / "unexpected.bin").write_bytes(b"stale")

    def interrupted_run(command, check):
        raise checkpoints_module.subprocess.CalledProcessError(1, command)

    monkeypatch.setattr(checkpoints_module.subprocess, "run", interrupted_run)
    with pytest.raises(checkpoints_module.subprocess.CalledProcessError):
        fetch_resource(tmp_path, resource)

    assert object_path.read_bytes() == b"resume-prefix"
    assert not (staging / "unexpected.bin").exists()
    quarantined = list(
        (tmp_path / "checkpoints" / "quarantine").glob(
            "*/official/rdlm.partial/unexpected.bin"
        )
    )
    assert len(quarantined) == 1
    assert quarantined[0].read_bytes() == b"stale"

    def successful_run(command, check):
        assert "--id" not in command
        file_id = command[2]
        output = Path(command[command.index("--output") + 1])
        output.write_bytes({"fileA": b"weights", "fileB": b"config"}[file_id])
        return types.SimpleNamespace(returncode=0)

    monkeypatch.setattr(checkpoints_module.subprocess, "run", successful_run)
    record = fetch_resource(tmp_path, resource)

    assert record["status"] == "downloaded"
    destination = tmp_path / "checkpoints" / "official" / "rdlm"
    assert (destination / "checkpoint.pth").read_bytes() == b"weights"
    assert (destination / "config.yaml").read_bytes() == b"config"


def test_gdrive_quarantines_a_symlinked_object_partial_before_successful_rerun(
    tmp_path, monkeypatch
):
    resource = CheckpointResource.model_validate(
        {
            "id": "test_drive",
            "backend": "gdrive",
            "provenance": "official",
            "teacher_family": "continuous_rdlm",
            "destination": "official/rdlm",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {"policy": "capture_after_download"},
            "required_files": ["checkpoint.pth", "config.yaml"],
            "source": {
                "folder_id": "folder123",
                "expected_files": {"checkpoint.pth": "fileA", "config.yaml": "fileB"},
            },
        }
    )
    outside = tmp_path / "outside.bin"
    outside.write_bytes(b"sentinel")
    object_path = (
        tmp_path
        / "checkpoints"
        / "official"
        / "rdlm.partial"
        / ".objects"
        / "fileA.partial"
    )
    object_path.parent.mkdir(parents=True)
    object_path.symlink_to(outside)

    def successful_run(command, check):
        assert "--id" not in command
        file_id = command[2]
        output = Path(command[command.index("--output") + 1])
        output.write_bytes({"fileA": b"weights", "fileB": b"config"}[file_id])
        return types.SimpleNamespace(returncode=0)

    monkeypatch.setattr(checkpoints_module.subprocess, "run", successful_run)
    record = fetch_resource(tmp_path, resource)

    assert record["status"] == "downloaded"
    assert outside.read_bytes() == b"sentinel"
    destination = tmp_path / "checkpoints" / "official" / "rdlm"
    assert (destination / "checkpoint.pth").read_bytes() == b"weights"
    assert (destination / "config.yaml").read_bytes() == b"config"
    quarantined = list(
        (tmp_path / "checkpoints" / "quarantine").glob(
            "*/official/rdlm.partial/.objects/fileA.partial"
        )
    )
    assert len(quarantined) == 1
    assert quarantined[0].is_symlink()
    assert quarantined[0].readlink() == outside


def test_real_downloads_positively_require_linux():
    """Catch accidental acquisition on any unapproved operating system."""

    for system_name in ("Darwin", "Windows", "FreeBSD", ""):
        with pytest.raises(RuntimeError, match="Linux server-only"):
            require_server_platform(system_name)
    require_server_platform("Linux")


def test_zenodo_record_selects_named_files_and_rejects_traversal():
    """Catch downloading unrelated Zenodo files or trusting unsafe record filenames."""

    metadata = {
        "files": [
            {
                "key": "sdtt7-di4c2.ckpt",
                "size": 17,
                "checksum": "md5:b55b961b1f0d7f2ed55539452875ec15",
                "links": {"content": "https://zenodo.example/sdtt7"},
            },
            {
                "key": "other.bin",
                "size": 3,
                "checksum": "md5:abc",
                "links": {"content": "https://zenodo.example/other"},
            },
        ]
    }
    source = ZenodoSource(record_id=15124163, files=["sdtt7-di4c2.ckpt"])

    assert select_zenodo_files(metadata, source) == [
        {
            "filename": "sdtt7-di4c2.ckpt",
            "url": "https://zenodo.example/sdtt7",
            "size_bytes": 17,
            "published_checksum": "md5:b55b961b1f0d7f2ed55539452875ec15",
        }
    ]

    metadata["files"][0]["key"] = "../escape.ckpt"
    with pytest.raises(ValueError, match="unsafe remote path"):
        select_zenodo_files(metadata, ZenodoSource(record_id=15124163, files=["../escape.ckpt"]))


def test_zenodo_published_size_and_checksum_are_enforced(tmp_path):
    """Catch capturing a new SHA-256 for content that differs from Zenodo metadata."""

    target = tmp_path / "checkpoint.bin"
    target.write_bytes(b"zenodo")
    verify_published_file(
        target,
        size_bytes=6,
        checksum="md5:aa4386efabed44fe87a07a77480593a2",
    )
    with pytest.raises(ValueError, match="published size mismatch"):
        verify_published_file(target, size_bytes=7, checksum=None)
    with pytest.raises(ValueError, match="published checksum mismatch"):
        verify_published_file(target, size_bytes=6, checksum="md5:" + "0" * 32)


def test_zenodo_fetch_preserves_the_manifest_digest_policy(tmp_path, monkeypatch):
    """Catch Zenodo replacing a declared SHA-256 policy with capture-after-download."""

    payload = b"zenodo"
    expected_sha = hashlib.sha256(payload).hexdigest()
    metadata = {
        "files": [
            {
                "key": "model.ckpt",
                "size": len(payload),
                "checksum": "md5:" + hashlib.md5(payload, usedforsecurity=False).hexdigest(),
                "links": {"content": "https://zenodo.example/model"},
            }
        ]
    }

    class MetadataResponse(io.BytesIO):
        def __enter__(self):
            return self

        def __exit__(self, *args):
            self.close()

    monkeypatch.setattr(
        checkpoints_module,
        "urlopen",
        lambda request: MetadataResponse(json.dumps(metadata).encode("utf-8")),
    )
    seen = []

    def fake_download(source, target, digest, **kwargs):
        seen.append(digest)
        target.write_bytes(payload)
        return {"status": "downloaded", "quarantined": None}

    monkeypatch.setattr(checkpoints_module, "download_direct", fake_download)
    resource = CheckpointResource.model_validate(
        {
            "id": "test_zenodo",
            "backend": "zenodo",
            "provenance": "official",
            "teacher_family": "masked_mdlm",
            "destination": "official/zenodo",
            "license": "test",
            "terms_url": "https://example.test/terms",
            "digest": {"policy": "sha256", "sha256": expected_sha},
            "required_files": ["model.ckpt"],
            "source": {"record_id": 1, "files": ["model.ckpt"]},
        }
    )

    fetch_resource(tmp_path, resource)

    assert len(seen) == 1
    assert seen[0].policy == "sha256"
    assert seen[0].sha256 == expected_sha


def test_lock_verification_reports_missing_mismatch_and_verified(tmp_path):
    """Catch verification treating absent or changed files as successful."""

    present = tmp_path / "checkpoints" / "official" / "ok.bin"
    changed = tmp_path / "checkpoints" / "official" / "changed.bin"
    present.parent.mkdir(parents=True)
    present.write_bytes(b"ok")
    changed.write_bytes(b"changed")
    lock = {
        "schema_version": 1,
        "resources": {
            "ok": {
                "status": "downloaded",
                "files": [
                    {
                        "path": "checkpoints/official/ok.bin",
                        "size_bytes": 2,
                        "sha256": hashlib.sha256(b"ok").hexdigest(),
                    }
                ],
            },
            "changed": {
                "status": "downloaded",
                "files": [
                    {
                        "path": "checkpoints/official/changed.bin",
                        "size_bytes": 7,
                        "sha256": "0" * 64,
                    }
                ],
            },
            "missing": {
                "status": "unavailable",
                "files": [],
                "error": {"type": "FileNotFoundError", "message": "not published"},
            },
        },
    }

    report = verify_checkpoint_lock(tmp_path, lock)

    assert report["resources"]["ok"]["status"] == "verified"
    assert report["resources"]["changed"]["status"] == "mismatch"
    assert report["resources"]["missing"]["status"] == "unavailable"
    assert report["ok"] is False


def test_lock_verification_rejects_path_traversal(tmp_path):
    """Catch a tampered lock reading files outside the project checkpoint tree."""

    outside = tmp_path.parent / "outside.bin"
    outside.write_bytes(b"outside")
    lock = {
        "schema_version": 1,
        "resources": {
            "tampered": {
                "status": "downloaded",
                "files": [
                    {
                        "path": "../outside.bin",
                        "size_bytes": 7,
                        "sha256": hashlib.sha256(b"outside").hexdigest(),
                    }
                ],
            }
        },
    }

    report = verify_checkpoint_lock(tmp_path, lock)

    assert report["resources"]["tampered"]["status"] == "invalid"
    assert report["ok"] is False


def test_lock_verification_rejects_manifest_drift(tmp_path):
    """Catch verification against a lock produced from a different checkpoint manifest."""

    manifest = tmp_path / "artifacts" / "checkpoints.yaml"
    manifest.parent.mkdir()
    manifest.write_text("schema_version: 1\n", encoding="utf-8")
    lock = {"schema_version": 1, "manifest_sha256": "0" * 64, "resources": {}}

    report = verify_checkpoint_lock(tmp_path, lock, manifest_path=manifest)

    assert report["manifest_status"] == "mismatch"
    assert report["ok"] is False


def test_lock_verification_rejects_a_downloaded_resource_without_files(tmp_path):
    """Catch an empty provider response being recorded as a successful download."""

    lock = {
        "schema_version": 1,
        "resources": {"empty": {"status": "downloaded", "files": []}},
    }

    report = verify_checkpoint_lock(tmp_path, lock)

    assert report["resources"]["empty"]["status"] == "invalid"
    assert report["ok"] is False


@pytest.mark.parametrize("malformed", [[], "not-a-record", None])
def test_lock_verification_structures_nonmapping_resource_records(
    tmp_path, malformed
):
    """Catch malformed lock values reaching dict.get and raising AttributeError."""

    report = verify_checkpoint_lock(
        tmp_path,
        {"schema_version": 1, "resources": {"broken_resource": malformed}},
    )

    record = report["resources"]["broken_resource"]
    assert record["status"] == "invalid"
    assert record["error"]["type"] == "InvalidResourceRecord"
    assert "broken_resource" in record["error"]["message"]
    assert report["ok"] is False


def test_lock_verification_rejects_an_empty_resource_set(tmp_path):
    """Catch an empty lock being accepted as complete verification."""

    report = verify_checkpoint_lock(tmp_path, {"schema_version": 1, "resources": {}})

    assert report["resource_set_status"] == "invalid"
    assert report["ok"] is False


def test_lock_verification_cross_checks_manifest_resource_ids(tmp_path):
    """Catch a nonempty lock that silently omits resources from the pinned manifest."""

    manifest = Path(__file__).parents[1] / "artifacts" / "checkpoints.yaml"
    lock = {
        "schema_version": 1,
        "manifest_sha256": hashlib.sha256(manifest.read_bytes()).hexdigest(),
        "resources": {
            "flm_lm1b_hf": {
                "status": "unavailable",
                "files": [],
                "error": {"type": "HTTPError", "message": "test"},
            }
        },
    }

    report = verify_checkpoint_lock(tmp_path, lock, manifest_path=manifest)

    assert report["resource_set_status"] == "mismatch"
    assert report["ok"] is False


@pytest.mark.parametrize("schema_version", [2, True, 1.0, "1", None])
def test_lock_verification_requires_exact_schema_version(tmp_path, schema_version):
    """Catch a future or malformed lock schema being interpreted as schema 1."""

    report = verify_checkpoint_lock(
        tmp_path,
        {
            "schema_version": schema_version,
            "resources": {"x": {"status": "unavailable", "files": []}},
        },
    )

    assert report["schema_status"] == "invalid"
    assert report["ok"] is False


def test_lock_verification_rejects_a_missing_schema_version(tmp_path):
    report = verify_checkpoint_lock(
        tmp_path,
        {"resources": {"x": {"status": "unavailable", "files": []}}},
    )

    assert report["schema_status"] == "invalid"
    assert report["ok"] is False


@pytest.mark.parametrize(
    ("field", "rewritten"),
    [
        ("backend", "huggingface"),
        ("provenance", "reference_reproduction"),
        ("destination", "checkpoints/official/other"),
    ],
)
def test_lock_verification_binds_resource_metadata_to_manifest(tmp_path, field, rewritten):
    """Catch a lock record being relabeled independently of its manifest resource."""

    manifest = write_single_resource_manifest(tmp_path)
    payload = b"weights"
    model = tmp_path / "checkpoints" / "official" / "test" / "model.bin"
    model.parent.mkdir(parents=True)
    model.write_bytes(payload)
    lock = manifest_bound_lock(
        manifest, "checkpoints/official/test/model.bin", payload
    )
    lock["resources"]["test_direct"][field] = rewritten

    report = verify_checkpoint_lock(tmp_path, lock, manifest_path=manifest)

    assert report["resources"]["test_direct"]["status"] == "invalid"
    assert report["ok"] is False


def test_lock_verification_rejects_a_file_outside_its_resource_destination(tmp_path):
    """Catch one resource claiming a regular checkpoint owned by another resource."""

    manifest = write_single_resource_manifest(tmp_path)
    payload = b"swapped"
    swapped = tmp_path / "checkpoints" / "official" / "other" / "model.bin"
    swapped.parent.mkdir(parents=True)
    swapped.write_bytes(payload)
    lock = manifest_bound_lock(
        manifest, "checkpoints/official/other/model.bin", payload
    )

    report = verify_checkpoint_lock(tmp_path, lock, manifest_path=manifest)

    assert report["resources"]["test_direct"]["status"] == "invalid"
    assert report["ok"] is False


@pytest.mark.parametrize("symlink_level", ["root", "destination", "file"])
def test_lock_verification_lstats_every_checkpoint_path_component(tmp_path, symlink_level):
    """Catch symlinked roots, destination ancestors, and final files in lock verification."""

    manifest = write_single_resource_manifest(tmp_path)
    payload = b"linked"
    outside = tmp_path / "outside"
    outside.mkdir()
    outside_file = outside / "model.bin"
    outside_file.write_bytes(payload)
    checkpoint_root = tmp_path / "checkpoints"
    if symlink_level == "root":
        nested = outside / "official" / "test" / "model.bin"
        nested.parent.mkdir(parents=True)
        nested.write_bytes(payload)
        checkpoint_root.symlink_to(outside, target_is_directory=True)
        file_path = "checkpoints/official/test/model.bin"
    elif symlink_level == "destination":
        checkpoint_root.mkdir()
        (checkpoint_root / "official").mkdir()
        (checkpoint_root / "official" / "test").symlink_to(
            outside, target_is_directory=True
        )
        file_path = "checkpoints/official/test/model.bin"
    else:
        target = checkpoint_root / "official" / "test" / "model.bin"
        target.parent.mkdir(parents=True)
        target.symlink_to(outside_file)
        file_path = "checkpoints/official/test/model.bin"
    lock = manifest_bound_lock(manifest, file_path, payload)

    report = verify_checkpoint_lock(tmp_path, lock, manifest_path=manifest)

    assert report["resources"]["test_direct"]["status"] == "invalid"
    assert report["ok"] is False