File size: 37,084 Bytes
82df7d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bb3be3
 
82df7d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bb3be3
 
82df7d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bb3be3
 
82df7d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bb3be3
82df7d3
dc096c2
 
 
 
 
8bb3be3
 
 
82df7d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc096c2
 
 
 
 
 
 
 
 
 
 
 
82df7d3
dc096c2
 
 
 
 
82df7d3
8bb3be3
 
 
 
 
 
 
 
 
82df7d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc096c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82df7d3
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Unit tests for per-(dataset, plan-kind) annotation version resolution.

Every config loads the newest annotation published at or before the requested
version. The invariant under test:

    For every config x every pin, resolution either returns a version that is
    declared for that (dataset, plan-kind), or raises the "not published at this
    version" error. There is no third outcome -- in particular, never a path
    that does not exist.

Run:  python scripts/test_annotation_resolution.py
      python scripts/test_annotation_resolution.py --datasets-root /path/to/Datasets

Sections 1-4, 6 and 7 are pure and need no data on disk. Section 5 reconciles
_ANNOTATION_INDEX against a real Datasets/ tree and is skipped when none is given.

The repo has no test framework; this is a standalone script that exits non-zero
on any failure, matching scripts/test_tl_ack_gate.py.
"""
import argparse
import ast
import importlib.util
import inspect
import os
import re
import shutil
import sys
import tempfile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _medvision_test_support as _support  # noqa: E402

_MEDVISION_PY = _support.MEDVISION_PY
_INFO_CSV = _support.INFO_CSV

mv = _support.load_loader("medvision_res_test_")

PINS = ["1.0.0", "1.1.0", "1.1.1", "1.2.0", "1.2.1", "1.3.0", "latest"]
RELEASE = "1.3.0"

_results = []


def check(ok, desc, detail=""):
    _results.append(ok)
    print(f"[{'PASS' if ok else 'FAIL'}] {desc}" + (f"  {detail}" if detail else ""))


def section(title):
    print(f"\n--- {title} ---")


# ---------------------------------------------------------------- 1. helpers
section("1. Version helpers")

check(mv._version_tuple("1.1.0") == (1, 1, 0), "parses 1.1.0")
check(mv._version_tuple("1.2") == (1, 2, 0), "pads 1.2 -> (1,2,0)",
      "unpadded, (1,2) would sort BELOW (1,2,0)")
check(mv._version_tuple(True) == (1, 0, 0), "legacy boolean True -> v1.0.0 baseline")
check(mv._version_tuple(None) == (1, 0, 0), "None -> v1.0.0 baseline")
check(
    mv._version_tuple("1.0.0") < mv._version_tuple("1.1.0")
    < mv._version_tuple("1.1.1") < mv._version_tuple("1.2.0"),
    "release ordering is strictly increasing",
)
for good in ("1.0.0", "1.2.0", "10.20.30"):
    check(mv._is_version(good), f"_is_version accepts {good!r}")
for bad in ("vdraft", "", "1.2", "v1.1.1", "1.2.0-rc1", "latest"):
    check(not mv._is_version(bad), f"_is_version rejects {bad!r}")

# ------------------------------------------------------- 2. pin normalization
section("2. Pin normalization")


def _norm(raw):
    try:
        return mv._normalize_requested(raw, RELEASE)
    except EnvironmentError:
        return "RAISE"


check(_norm(None) == "RAISE", "unset -> EnvironmentError")
check(_norm("latest") == RELEASE, "latest -> release version")
check(_norm("LATEST") == RELEASE, "LATEST is case-insensitive")
check(_norm("  latest ") == RELEASE, "whitespace is stripped")
check(_norm("1.1.1") == "1.1.1", "explicit version passes through")
for bad in ("v1.1.1", "1.2", "", "  ", "1.2.0-rc1"):
    check(_norm(bad) == "RAISE", f"malformed pin {bad!r} -> EnvironmentError",
          "previously collapsed to v1.0.0 and could load silently")

# The accepted SET is derived from _ANNOTATION_INDEX, so a well-formed version
# that was never published is refused rather than silently resolved down.
check(mv._published_versions() ==
      tuple(sorted({v for ks in mv._ANNOTATION_INDEX.values() for vs in ks.values()
                    for v in vs}, key=mv._version_tuple)),
      "_published_versions is derived from _ANNOTATION_INDEX")
for v in mv._published_versions():
    check(_norm(v) == v, f"published version {v!r} is accepted")
# RE-BASED twice: 1.3.0 used to sit in this list until MSWAL published it.
for unknown in ("1.1.5", "1.0.1", "0.0.0", "1.2.2", "2.0.0", "999.999.999"):
    check(_norm(unknown) == "RAISE",
          f"unpublished version {unknown!r} -> EnvironmentError",
          "would otherwise resolve silently to an older annotation, or to nothing")

# The release version must stay acceptable even when nothing is published at it,
# or a version bump made before any regeneration would break `latest` outright.
check(mv._normalize_requested("latest", "1.3.0") == "1.3.0",
      "latest still works when the release is ahead of every published annotation")
check("1.3.0" in mv._acceptable_versions("1.3.0"),
      "the release version is always acceptable")
check(set(mv._acceptable_versions(RELEASE))
      == set(mv._published_versions()) | {RELEASE},
      "acceptable = published versions + the release")

# ------------------------------------------- 3. index / BUILDER_CONFIGS parity
section("3. Index covers every config (and nothing extra)")

configs = mv.MedVision.BUILDER_CONFIGS
needed = set()
for c in configs:
    kind = mv._PLAN_KIND_BY_TASKTYPE.get(c.taskType)
    if kind is None:
        check(False, f"taskType {c.taskType!r} missing from _PLAN_KIND_BY_TASKTYPE")
    else:
        needed.add((c.dataset_name, kind))

declared = {(ds, k) for ds, kinds in mv._ANNOTATION_INDEX.items() for k in kinds}

# The released config list is the oracle, not a hardcoded 922 -- that count also
# passes if a config is silently renamed.
_released = {ln.split(",")[0].strip()
             for ln in open(_INFO_CSV, encoding="utf-8") if ln.strip()}
_built = {c.name for c in configs}
check(_built == _released,
      f"BUILDER_CONFIGS matches {os.path.basename(_INFO_CSV)} exactly",
      f"only in code: {sorted(_built - _released)[:3]} | "
      f"only in csv: {sorted(_released - _built)[:3]}")
check(len(configs) == len(_released), f"{len(_released)} BUILDER_CONFIGS",
      f"got {len(configs)}")
check(len(needed) == 75, "75 (dataset, plan-kind) pairs", f"got {len(needed)}")
check(len({d for d, _ in needed}) == 31, "31 datasets",
      f"got {len({d for d, _ in needed})}")
check(not (needed - declared), "every config's pair is declared",
      f"missing: {sorted(needed - declared)}")
check(not (declared - needed), "no unreachable index entries",
      f"extra: {sorted(declared - needed)}")
for ds, kinds in mv._ANNOTATION_INDEX.items():
    for kind, versions in kinds.items():
        check(bool(versions) and all(mv._is_version(v) for v in versions),
              f"{ds}/{kind} declares well-formed versions", str(versions))
        check(list(versions) == sorted(versions, key=mv._version_tuple),
              f"{ds}/{kind} versions are ascending", str(versions))

# ------------------------------------------------- 4. biometry family hygiene
section("4. Biometry families are disjoint")

tl = {c.dataset_name for c in configs if c.taskType == "Tumor-Lesion-Size"}
lm = {c.dataset_name for c in configs if c.taskType.startswith("Biometrics-From-Landmarks")}
check(not (tl & lm), "no dataset carries both biometry families",
      f"overlap: {sorted(tl & lm)}")
check(tl | lm == set(mv._BIOMETRY_FAMILY), "_BIOMETRY_FAMILY covers exactly the biometry datasets",
      f"symmetric difference: {sorted((tl | lm) ^ set(mv._BIOMETRY_FAMILY))}")
for ds in tl:
    check(mv._BIOMETRY_FAMILY.get(ds) == "fromSeg", f"{ds} registered as fromSeg")
for ds in lm:
    check(mv._BIOMETRY_FAMILY.get(ds) == "landmark", f"{ds} registered as landmark")
# the guard itself
try:
    mv._check_biometry_family("KiTS23", "Biometrics-From-Landmarks")
    check(False, "family mismatch raises")
except RuntimeError:
    check(True, "family mismatch raises", "KiTS23 is fromSeg, asked as landmark")
try:
    mv._check_biometry_family("KiTS23", "Tumor-Lesion-Size")
    check(True, "matching family passes")
except RuntimeError as e:
    check(False, "matching family passes", str(e))

# ------------------------------------------------------- 5. index vs the disk
section("5. Index reconciles with a real Datasets/ tree")

ap = argparse.ArgumentParser()
ap.add_argument("--datasets-root", default=None)
args, _ = ap.parse_known_args()

if not args.datasets_root:
    print("[SKIP] no --datasets-root given")
else:
    root = args.datasets_root
    seen = 0
    for ds, kinds in sorted(mv._ANNOTATION_INDEX.items()):
        ddir = os.path.join(root, ds)
        if not os.path.isdir(ddir):
            continue
        for kind, want in kinds.items():
            got = mv._discover_versions(ddir, kind)
            if not got:
                print(f"[SKIP] {ds}/{kind}: not generated yet")
                continue
            seen += 1
            check(list(got) == list(want), f"{ds}/{kind} disk matches index",
                  f"disk={got} index={list(want)}")
    print(f"       reconciled {seen} pair(s)")

# ------------------------------------------------------------ 6. full sweep
section("6. Full sweep: 992 configs x every pin")

# 1.2.0 still resolves for every config: v1.2.0 stays DECLARED in the index
# (MAMA-MIA/PI-CAI are withheld by _PAUSED_ANNOTATIONS, not by de-listing),
# so resolution is unchanged and only the pause gate refuses those loads.
# 1.2.0 no longer covers the whole catalogue: MAMA-MIA and PI-CAI withdrew their
# v1.2.0 annotations, so their 36 configs have nothing at or below that pin.
EXPECTED = {"1.0.0": (820, 172), "1.1.0": (820, 172), "1.1.1": (820, 172),
            "1.2.0": (914, 78), "1.2.1": (950, 42), "1.3.0": (992, 0),
            "latest": (992, 0)}

for pin in PINS:
    requested = mv._normalize_requested(pin, RELEASE)
    resolved = unavailable = bad = 0
    for c in configs:
        kind = mv._PLAN_KIND_BY_TASKTYPE[c.taskType]
        decl = mv._declared_versions(c.dataset_name, kind)
        got = mv._resolve(decl, requested)
        if got is None:
            unavailable += 1
        elif got in decl and mv._version_tuple(got) <= mv._version_tuple(requested):
            resolved += 1
        else:
            bad += 1
    want_r, want_u = EXPECTED[pin]
    check(bad == 0, f"pin {pin}: no third outcome", f"invalid={bad}")
    check((resolved, unavailable) == (want_r, want_u),
          f"pin {pin}: {want_r} resolve / {want_u} unavailable",
          f"got {resolved}/{unavailable}")

# the headline regression: TL at latest used to hand a non-existent path to
# _generate_examples and crash at gzip.open()
for ds in ["BraTS24", "HNTSMRG24", "KiPA22", "KiTS23", "MSD", "autoPET-III"]:
    got = mv._resolve(mv._declared_versions(ds, "biometry"), RELEASE)
    check(got == "1.1.1", f"{ds} biometry at latest -> 1.1.1", f"got {got}")

# new datasets are unreachable below the version that introduced them, and that
# must be an explicit refusal rather than a silent slide to something older.
_INTRODUCED_120 = ["AFIDs", "DEEP-PSMA", "LIDC-IDRI", "LNQ2023", "PDDCA", "VerSe"]
# MAMA-MIA and PI-CAI shipped at 1.2.0 but that annotation was WITHDRAWN (it was
# recorded in the source orientation), so their earliest reachable version is
# 1.2.1 and a 1.2.0 pin now finds nothing for them at all.
_WITHDREW_120 = ["MAMA-MIA", "PI-CAI"]
for ds in _INTRODUCED_120 + _WITHDREW_120:
    earliest = "1.2.1" if ds in _WITHDREW_120 else "1.2.0"
    for kind in mv._ANNOTATION_INDEX[ds]:
        declared = mv._declared_versions(ds, kind)
        check(mv._resolve(declared, "1.1.1") is None,
              f"{ds}/{kind} unavailable at 1.1.1")
        want = None if ds in _WITHDREW_120 else "1.2.0"
        got = mv._resolve(declared, "1.2.0")
        check(got == want, f"{ds}/{kind} at pin 1.2.0 -> {want}", f"got {got}")
        check(mv._resolve(declared, earliest) == earliest,
              f"{ds}/{kind} resolves at {earliest}")

_INTRODUCED_130 = ["MSWAL"]
for ds in _INTRODUCED_130:
    for kind in mv._ANNOTATION_INDEX[ds]:
        declared = mv._declared_versions(ds, kind)
        check(mv._resolve(declared, "1.2.1") is None,
              f"{ds}/{kind} unavailable at 1.2.1")
        check(mv._resolve(declared, "1.3.0") == "1.3.0",
              f"{ds}/{kind} resolves at 1.3.0")

# ------------------------------------------------------- 7. download decision
section("7. Download decision")


def needs_download(declared, local_versions, requested, force=False, tracker="1.0.0"):
    """Drive the REAL predicate, mv._download_needed, not a copy of it.

    Only the two resolutions are done here, exactly as _split_generators does
    them. `tracker` is the `dataset_<name>` entry of .downloaded_datasets.json,
    written only after the images land; None means "no completed install".

    This used to re-implement the predicate, which meant every row below could
    stay green while the shipped decision was broken.
    """
    target = mv._resolve(declared, requested)
    local = mv._resolve(local_versions, requested)
    return mv._download_needed(force, tracker, local, target)


KITS_BIO = ("1.0.0", "1.1.0", "1.1.1")
ACDC_SEG = ("1.0.0",)

# (declared, on-disk, pin, force, tracker, expect_download, description)
DL_CASES = [
    (ACDC_SEG, (), "1.2.0", False, None, True, "first-time download"),
    (ACDC_SEG, ("1.0.0",), "1.2.0", False, "1.0.0", False,
     "unchanged dataset at latest -> SKIP (was a ~28 GiB re-download)"),
    (KITS_BIO, ("1.0.0",), "1.1.1", False, "1.0.0", True,
     "v1.0.0-era copy, pin 1.1.1 -> DOWNLOAD (glob-only would skip: regression guard)"),
    (KITS_BIO, KITS_BIO, "1.0.0", False, "1.1.1", False,
     "downgrade with cumulative zip on disk -> SKIP"),
    (KITS_BIO, KITS_BIO, "1.1.1", False, "1.1.1", False, "already current -> SKIP"),
    (KITS_BIO, ("1.0.0",), "1.0.0", False, "1.0.0", False,
     "pin matches what is on disk -> SKIP"),
    (ACDC_SEG, ("1.0.0",), "1.2.0", True, "1.0.0", True, "force_download_data overrides"),
    (KITS_BIO, (), "1.1.1", False, "1.1.1", True, "plans deleted -> DOWNLOAD"),
    # a tracker entry recording a version the dataset does not possess must not
    # suppress a download the disk says is needed
    (KITS_BIO, ("1.0.0",), "1.1.1", False, "1.2.0", True,
     "poisoned tracker entry cannot suppress a needed download (self-heal)"),
    (KITS_BIO + ("1.3.0",), KITS_BIO, "1.3.0", False, "1.1.1", True,
     "future regeneration -> DOWNLOAD"),
    # REGRESSION GUARD (audit finding 1, high): the annotation plans are extracted
    # at step 3.1, BEFORE the images (3.2) and the RAS+ reorientation (3.3). A run
    # that dies in between leaves plans with no images and no tracker entry. Judged
    # on the plans alone that state looks complete, the images are never fetched,
    # and the loader yields rows whose image paths do not exist.
    (KITS_BIO, KITS_BIO, "1.1.1", False, None, True,
     "plans present but install never completed -> DOWNLOAD (interrupted-download guard)"),
    (ACDC_SEG, ("1.0.0",), "1.0.0", False, None, True,
     "same, for a single-version dataset"),
    # legacy boolean entries mean a completed install under the old scheme
    (ACDC_SEG, ("1.0.0",), "1.2.0", False, True, False,
     "legacy boolean tracker entry counts as complete -> SKIP"),
]
for declared, local, pin, force, tracker, want, desc in DL_CASES:
    got = needs_download(declared, local, pin, force, tracker)
    check(got == want, desc, f"download={got}, expected={want}")

# ------------------------------------------- 8. glob robustness in the data dir
section("8. _discover_versions survives glob metacharacters in the path")

_probe = tempfile.mkdtemp(prefix="medvision_glob_probe_")
for tag in ["plain", "med[v2]", "st*ar", "que?ry", "a*b[c]?d"]:
    ddir = os.path.join(_probe, tag, "KiTS23")
    os.makedirs(ddir, exist_ok=True)
    for v in ("1.0.0", "1.1.0", "1.1.1"):
        open(os.path.join(ddir, f"benchmark_plan_biometry_v{v}.json.gz"), "w").close()
    open(os.path.join(ddir, "benchmark_plan_biometry_vdraft.json.gz"), "w").close()
    got = mv._discover_versions(ddir, "biometry")
    check(got == ["1.0.0", "1.1.0", "1.1.1"],
          f"data dir containing {tag!r} discovers all versions", f"got {got}")
shutil.rmtree(_probe, ignore_errors=True)

# ------------------------------------ 9. fingerprint token vs. what is loaded
section("9. create_config_id token matches the version actually loaded")

_by_name = {c.name: c for c in configs}


def _token(config_name, pin):
    """The fingerprint token MedVisionConfig hands to its parent.

    Intercepts BuilderConfig.create_config_id rather than reading the return
    value, so this works whether the real `datasets` is installed (the parent
    returns a hashed string) or the stub above is in use. Reading the return
    value only worked under the stub.
    """
    if pin is None:
        os.environ.pop("MedVision_PLANNER_VERSION", None)
    else:
        os.environ["MedVision_PLANNER_VERSION"] = pin
    cfg = _by_name[config_name]
    parent = type(cfg).__mro__[1]  # BuilderConfig
    orig = parent.create_config_id
    parent.create_config_id = (
        lambda self, config_kwargs, custom_features=None: dict(config_kwargs or {})
    )
    try:
        return cfg.create_config_id({})["planner_version"]
    finally:
        parent.create_config_id = orig


_KITS = "KiTS23_TumorLesionSize_Task01_Axial_Test"
_ACDC = "ACDC_MaskSize_Task01_Axial_Test"

# The token is "<resolved annotation version>-<8 hex of the canonical data root>".
# The version prefix must stay readable in the cache path; the root suffix is what
# stops two data roots from sharing one cache (see the guards further down).
def _ver(config_name, pin):
    return _token(config_name, pin).rsplit("-", 1)[0]


check(_ver(_ACDC, "1.0.0") == "1.0.0", "pin 1.0.0 -> resolved version in the token")
check(_ver(_ACDC, "latest") == "1.0.0", "latest on an unchanged dataset -> resolved version")
check(_ver(_KITS, "latest") == "1.1.1", "latest on a TL dataset -> resolved version")
check(_ver(_ACDC, None) == "unset", "unset is preserved as the version part")
check(_token(_ACDC, "1.1.1") == _token(_ACDC, "latest") == _token(_ACDC, "1.0.0"),
      "pins selecting the same plan share one cache key")
check(re.fullmatch(r"1\.0\.0-[0-9a-f]{8}", _token(_ACDC, "latest")) is not None,
      "token shape is <version>-<8 hex>", _token(_ACDC, "latest"))

# REGRESSION GUARD (audit finding 2): _normalize_requested strips whitespace, so a
# padded pin loads normally. If create_config_id does not strip identically, the
# token reverts to the raw request string -- the request-keyed fingerprint this
# change exists to remove -- and identical data lands in a second cache directory.
for pin, base in [("latest", _KITS), ("1.1.1", _KITS), ("1.2.0", _ACDC), ("1.0.0", _ACDC)]:
    plain = _token(base, pin)
    for padded in (f" {pin}", f"{pin} ", f"\t{pin}", f"{pin}\n"):
        got = _token(base, padded)
        check(got == plain, f"padded pin {padded!r} yields the same token as {pin!r}",
              f"got {got!r}, expected {plain!r}")
        # and the loader must agree it is the same request
        check(mv._normalize_requested(padded, RELEASE)
              == mv._normalize_requested(pin, RELEASE),
              f"_normalize_requested agrees for {padded!r}")
os.environ.pop("MedVision_PLANNER_VERSION", None)

# ------------------------------------ 10. step 3.2 cannot fake a completed install
section("10. Step 3.2 never swallows a failure into a completion marker")

# The tracker entry written at step 3.4 is the "install completed" marker that the
# download predicate tests for presence. It is only trustworthy if a failed image
# download (3.2) can never reach 3.4. These assertions are structural on purpose:
# they hold regardless of which exception a download script happens to raise.
_src = open(_MEDVISION_PY, encoding="utf-8").read()
_tree = ast.parse(_src)


def _dl_calls(node):
    return [
        n for n in ast.walk(node)
        if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
        and n.func.attr == "download_and_extract"
    ]


_tries = [t for t in ast.walk(_tree) if isinstance(t, ast.Try) and _dl_calls(t)]
check(bool(_tries), "found the step-3.2 try block")
_step32 = max(_tries, key=lambda t: t.end_lineno - t.lineno)

# A bare `except:` used to re-call download_and_extract, re-running a multi-GB
# transfer on ANY failure -- including a Ctrl-C, which it swallowed.
check(len(_dl_calls(_step32)) == 1,
      "download_and_extract is invoked exactly once (no blind retry)",
      f"found {len(_dl_calls(_step32))} call site(s)")

_broad = [
    ast.unparse(h.type) if h.type else "bare except"
    for t in ast.walk(_step32) if isinstance(t, ast.Try)
    for h in t.handlers
    if h.type is None
    or (isinstance(h.type, ast.Name) and h.type.id in ("BaseException", "Exception"))
]
check(not _broad, "nothing around step 3.2 catches BaseException (Ctrl-C aborts)",
      f"found {_broad}")

# Any except clause here would let a failed download fall through to 3.3/3.4 and
# stamp the completion marker onto a dataset with no images.
check(_step32.handlers == [],
      "step 3.2 has no except clause, so a failed download cannot reach the 3.4 marker",
      f"handlers: {[ast.unparse(h.type) if h.type else 'bare' for h in _step32.handlers]}")

# The signature pre-check must select kwargs correctly for both conventions, and
# must not wrap the transfer itself.
def _pick(fn):
    kw = {"max_workers": 4}
    try:
        inspect.signature(fn).bind("d", "n", **kw)
    except TypeError:
        kw = {}
    return kw


check(_pick(lambda dataset_dir, dataset_name, **kw: None) == {"max_workers": 4},
      "script accepting **kwargs is called WITH max_workers")
check(_pick(lambda dataset_dir, dataset_name, max_workers=1: None) == {"max_workers": 4},
      "script declaring max_workers explicitly is called WITH it")
check(_pick(lambda dataset_dir, dataset_name: None) == {},
      "legacy script without max_workers is called WITHOUT it")


def _raiser(dataset_dir, dataset_name, **kw):
    raise ConnectionError("simulated network drop mid-transfer")


try:
    _f = _raiser
    _kw = _pick(_f)
    _f("d", "n", **_kw)
    check(False, "a failing download propagates rather than being swallowed")
except ConnectionError:
    check(True, "a failing download propagates rather than being swallowed",
          "so 3.3/3.4 never run and no completion marker is written")

# --------------------------------- 11. the data root is part of the cache identity
section("11. Two data roots never share one Arrow cache")

# Every row's image_file/mask_file/landmark_file is os.path.join(dataset_dir, ...),
# rooted at MedVision_DATA_DIR, so the root changes what the rows SAY. Before it was
# folded into the token, two runs differing only in data root produced a byte-identical
# config_id -> cache hit -> _split_generators never ran -> nothing downloaded into the
# new root and the rows pointed into the old one.
_saved_root = os.environ.get("MedVision_DATA_DIR")


def _token_at(config_name, root, pin="latest"):
    os.environ["MedVision_DATA_DIR"] = root
    return _token(config_name, pin)


try:
    _tA = _token_at(_ACDC, "/tmp/mv-rootA")
    check(_tA != _token_at(_ACDC, "/tmp/mv-rootB"),
          "different data roots -> different cache ids", f"both {_tA}")
    check(_tA == _token_at(_ACDC, "/tmp/mv-rootA/") == _token_at(_ACDC, "/tmp/./mv-rootA"),
          "non-canonical spellings of one root share one cache id")
    check(_token_at(_KITS, "/tmp/mv-rootA", "1.1.1")
          == _token_at(_KITS, "/tmp/mv-rootA", "latest"),
          "for a fixed root, pins selecting the same plan still share one key")
    check(_tA.startswith("1.0.0-"), "resolved annotation version stays readable in the id", _tA)
finally:
    if _saved_root is None:
        os.environ.pop("MedVision_DATA_DIR", None)
    else:
        os.environ["MedVision_DATA_DIR"] = _saved_root
    os.environ.pop("MedVision_PLANNER_VERSION", None)

# ------------------------------- 12. a relative data root survives the download scripts
section("12. The data root is canonicalised before the download scripts see it")

# MedVision.py chdirs into dataset_dir, then hands that same path to the dataset's
# download script, which begins with its own os.chdir(dataset_dir). A relative root
# makes the second chdir resolve against the first one's result and fail -- for all
# 30 datasets, so nothing could be downloaded at all.
_saved_root, _cwd0 = os.environ.get("MedVision_DATA_DIR"), os.getcwd()
_probe = tempfile.mkdtemp(prefix="medvision_relroot_")
try:
    os.chdir(_probe)
    os.environ["MedVision_DATA_DIR"] = "relroot"
    check(os.path.isabs(mv._data_root()), "_data_root() is absolute for a relative env value",
          mv._data_root())
    _d = os.path.join(mv._data_root(), "Datasets", "PDDCA")
    os.makedirs(_d, exist_ok=True)
    os.chdir(_d)                      # what _split_generators does
    try:
        os.chdir(_d)                  # what the download script then does
        check(True, "dataset_dir survives the download script's own chdir(dataset_dir)")
    except FileNotFoundError as e:
        check(False, "dataset_dir survives the download script's own chdir(dataset_dir)", str(e))
    os.chdir(_probe)
    for blank in ("", "   "):
        os.environ["MedVision_DATA_DIR"] = blank
        try:
            mv._data_root()
            check(False, f"blank data root {blank!r} is rejected, not resolved to cwd")
        except ValueError:
            check(True, f"blank data root {blank!r} is rejected, not resolved to cwd")
        check(mv._data_root(strict=False) == "",
              f"strict=False returns empty for {blank!r} instead of raising")
    # structural: _split_generators must not read the env var raw again
    _sg = next(n for n in ast.walk(_tree)
               if isinstance(n, ast.FunctionDef) and n.name == "_split_generators")
    _asg = [ast.unparse(a) for a in ast.walk(_sg) if isinstance(a, ast.Assign)
            and any(isinstance(t, ast.Name) and t.id == "MedVision_data_dir" for t in a.targets)]
    check(_asg == ["MedVision_data_dir = _data_root()"],
          "_split_generators takes the data root from _data_root()", f"got {_asg}")
finally:
    os.chdir(_cwd0)
    if _saved_root is None:
        os.environ.pop("MedVision_DATA_DIR", None)
    else:
        os.environ["MedVision_DATA_DIR"] = _saved_root
    shutil.rmtree(_probe, ignore_errors=True)

# ------------------------- 13. the annotation zip has an owner across processes
section("13. Step 3.1 owns the shared annotation zip under a per-dataset lock")

# Datasets/<name>.zip is one shared path per dataset. HF's builder lock is per CONFIG
# (Train and Test of one task are two configs), so two concurrent preparations of the
# same dataset both downloaded, both extractall'd into one tree, and the second
# os.remove died with a bare FileNotFoundError.
_dl_block = next(
    n for n in ast.walk(_tree)
    if isinstance(n, ast.If)
    and isinstance(n.test, ast.Name) and n.test.id == "_needs_download"
)
_removes = [n for n in ast.walk(_dl_block)
            if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
            and n.func.attr == "remove"]
check(len(_removes) == 1, "exactly one os.remove of the zip", f"found {len(_removes)}")

_withs = [w for w in ast.walk(_dl_block) if isinstance(w, ast.With)]
_locked = [
    w for w in _withs
    if any(isinstance(i.context_expr, ast.Call)
           and isinstance(i.context_expr.func, ast.Name)
           and i.context_expr.func.id == "FileLock"
           for i in w.items)
]
check(bool(_locked), "the download block acquires a FileLock")
# the remove, the extract and the snapshot_download must all sit INSIDE that lock
_lock = _locked[0]
for attr, what in (("remove", "os.remove"), ("extractall", "extractall")):
    inside = [n for n in ast.walk(_lock)
              if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
              and n.func.attr == attr]
    check(bool(inside), f"{what} is inside the per-dataset lock")
_snap = [n for n in ast.walk(_lock)
         if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
         and n.func.id == "snapshot_download"]
check(bool(_snap), "snapshot_download is inside the per-dataset lock")
# and the lock must be re-checking, so the waiter skips instead of repeating the work
_resolves_in_lock = [n for n in ast.walk(_lock)
                     if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
                     and n.func.id == "_resolve"]
check(bool(_resolves_in_lock),
      "the lock re-checks resolution so a waiter skips the redundant download")

# REGRESSION GUARD: the in-lock re-check must not swallow force_download_data.
# A plan rewritten in place at the same version is already >= _target, so without
# this the documented remediation (MedVision_FORCE_DOWNLOAD_DATA=True to refresh a
# stale annotation) re-fetches the images and keeps the stale plan.
_lock_guard = next((n for n in ast.walk(_lock) if isinstance(n, ast.If)), None)
check(_lock_guard is not None, "the lock has a skip guard")
_guard_src = ast.unparse(_lock_guard.test) if _lock_guard is not None else ""
check("force_download_data" in _guard_src,
      "the in-lock skip guard honours force_download_data", _guard_src)

# --------------------------------------------- 14. paused annotations are refused
section("14. Paused annotations cannot be loaded")


class _StubBuilder:
    """Just enough of the builder for _info() — it only reads self.config."""

    def __init__(self, cfg):
        self.config = cfg


# Invariants on whatever is REALLY paused right now. The table is empty most of the
# time - a pause is an incident response, not a steady state - so this loop is
# usually a no-op and the mechanism itself is exercised synthetically below.
for ds, versions in mv._PAUSED_ANNOTATIONS.items():
    _decl = {v for vs in mv._ANNOTATION_INDEX.get(ds, {}).values() for v in vs}
    check(ds in mv._ANNOTATION_INDEX, f"{ds} is still declared in the index",
          "a PAUSED version is still published, so it must stay listed; a version "
          "deleted from the hub is WITHDRAWN and belongs in neither table")
    check(set(versions) <= _decl, f"{ds} pauses only versions the index declares",
          f"paused={sorted(versions)} declared={sorted(_decl)}")

_clean_cfgs = [c for c in configs if c.dataset_name not in mv._PAUSED_ANNOTATIONS]
_broke = []
for c in _clean_cfgs:
    try:
        mv.MedVision._info(_StubBuilder(c))
    except Exception as e:  # noqa: BLE001
        _broke.append((c.name, type(e).__name__))
check(not _broke, f"all {len(_clean_cfgs)} unpaused configs load through _info()",
      f"broke: {_broke[:3]}")

# ---- the mechanism itself, exercised on a SYNTHETIC pause ----
#
# Driven by a fabricated entry rather than by whatever happens to be paused today, so
# the gate stays under test when the table is empty. Pausing only ever happens in
# response to an incident, so a test that needs a live incident to run is a test that
# is silently absent exactly when it is about to be needed.
#
# ACDC is the subject: it publishes a single version, so pausing that version makes
# every one of its (dataset, kind) pairs FULLY paused, which is the state _info() gates
# on. try/finally because both globals are module-level - leaving a fabricated entry
# behind would poison every later section instead of failing here.
_SUBJECT = "ACDC"
_saved_index = dict(mv._ANNOTATION_INDEX[_SUBJECT])
_saved_paused = dict(mv._PAUSED_ANNOTATIONS)
_subject_cfgs = [c for c in configs if c.dataset_name == _SUBJECT]
_other_cfgs = [c for c in configs if c.dataset_name != _SUBJECT]
check(bool(_subject_cfgs), f"{len(_subject_cfgs)} {_SUBJECT} configs available to test the gate")
try:
    mv._PAUSED_ANNOTATIONS[_SUBJECT] = ("1.0.0",)

    check(mv._fully_paused(_SUBJECT, "segmentation"),
          "pausing a dataset's only version makes the pair fully paused")

    # _info() is the gate a warm Arrow cache still has to pass: datasets calls it from
    # DatasetBuilder.__init__, before the cache directory is consulted.
    _leaked = []
    for c in _subject_cfgs:
        _kind = mv._PLAN_KIND_BY_TASKTYPE.get(c.taskType)
        if _kind is None or not mv._fully_paused(c.dataset_name, _kind):
            continue
        try:
            mv.MedVision._info(_StubBuilder(c))
            _leaked.append(c.name)
        except RuntimeError:
            pass
    check(not _leaked, "every config of a fully paused (dataset, kind) is refused by _info()",
          f"loadable: {_leaked[:3]}")

    _collateral = []
    for c in _other_cfgs[:200]:
        try:
            mv.MedVision._info(_StubBuilder(c))
        except Exception as e:  # noqa: BLE001
            _collateral.append((c.name, type(e).__name__))
    check(not _collateral, "pausing one dataset does not affect the others",
          f"broke: {_collateral[:3]}")

    check(mv._resolve(mv._declared_versions(_SUBJECT, "detection"), "1.0.0") == "1.0.0",
          "a pin to the paused version still RESOLVES to it",
          "which is why _split_generators re-checks _target against the pause table")

    # Publishing a correction lifts the pause with no edit to the gate.
    mv._ANNOTATION_INDEX[_SUBJECT] = {k: v + ("1.3.0",) for k, v in _saved_index.items()}
    check(not mv._fully_paused(_SUBJECT, "segmentation"),
          "a corrected version lifts the pause automatically")
    try:
        mv.MedVision._info(_StubBuilder(_subject_cfgs[0]))
        check(True, "and _info() lets the dataset through again")
    except RuntimeError as e:
        check(False, "and _info() lets the dataset through again", str(e)[:60])
finally:
    mv._ANNOTATION_INDEX[_SUBJECT] = _saved_index
    mv._PAUSED_ANNOTATIONS.clear()
    mv._PAUSED_ANNOTATIONS.update(_saved_paused)

check(mv._PAUSED_ANNOTATIONS == _saved_paused, "the pause table is restored after the test")

_sg_node = next(n for n in ast.walk(_tree)
                if isinstance(n, ast.FunctionDef) and n.name == "_split_generators")
check(any(isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
          and n.func.id == "_annotation_paused_error" for n in ast.walk(_sg_node)),
      "_split_generators also refuses a withheld resolved version")

# ------------------------------------------- 15. withdrawn versions are named as such
section("15. A withdrawn version is reported as withdrawn, not as never-published")

# Invariant: a withdrawn version must NOT still be declared. The two states are
# mutually exclusive - if it is still in the index, it is published (or paused), and
# claiming it was deleted from the hub would be a lie the loader tells with a
# straight face.
for _ds, _entries in mv._WITHDRAWN_ANNOTATIONS.items():
    _decl = {v for vs in mv._ANNOTATION_INDEX.get(_ds, {}).values() for v in vs}
    check(not (set(_entries) & _decl),
          f"{_ds}: withdrawn versions are absent from the index",
          f"still declared: {sorted(set(_entries) & _decl)}")
    check(all(isinstance(r, str) and r for r in _entries.values()),
          f"{_ds}: every withdrawn version records why")

_task = next(c for c in configs if c.dataset_name == "MAMA-MIA").taskType

# Pinned AT the withdrawn version -> the withdrawal branch.
_msg = str(mv._annotation_unavailable_error(
    "MAMA-MIA", _task, "detection", "1.2.0",
    mv._declared_versions("MAMA-MIA", "detection")))
check("WITHDRAWN" in _msg, "a pin at the withdrawn version says WITHDRAWN")
check("did not exist yet" not in _msg,
      "and does NOT claim the annotations never existed",
      "that would send someone holding a v1.2.0 cache after the wrong problem")
check("1.2.0" in _msg and "RAS+" in _msg,
      "and names the withdrawn version and the reason")

# Pinned BELOW it -> the version was never reachable from that pin, so the
# never-published wording is the correct one and must be preserved.
_msg = str(mv._annotation_unavailable_error(
    "MAMA-MIA", _task, "detection", "1.1.1",
    mv._declared_versions("MAMA-MIA", "detection")))
check("did not exist yet" in _msg,
      "a pin BELOW the withdrawn version keeps the never-published wording",
      "1.2.0 sits above that pin, so it explains nothing")

# A dataset with no withdrawals is untouched by any of this.
_msg = str(mv._annotation_unavailable_error(
    "PDDCA", _task, "detection", "1.1.1",
    mv._declared_versions("PDDCA", "detection")))
check("WITHDRAWN" not in _msg and "did not exist yet" in _msg,
      "datasets with no withdrawn version keep the original banner")

# Withdrawing must never empty a dataset. If it did, every config of that dataset
# would be permanently unloadable while still advertised in BUILDER_CONFIGS - at
# which point the dataset itself should be de-listed, not just one of its versions.
for _ds in mv._WITHDRAWN_ANNOTATIONS:
    _kinds = mv._ANNOTATION_INDEX.get(_ds, {})
    check(bool(_kinds) and all(_kinds.values()),
          f"{_ds} still publishes something after the withdrawal",
          f"index entry: {_kinds}")
    check(mv._resolve(mv._declared_versions(_ds, "detection"), RELEASE) is not None,
          f"{_ds} still resolves at the current release")

# ------------------------------------------------------------------ summary
print()
failures = _results.count(False)
if failures:
    print(f"{failures} of {len(_results)} check(s) FAILED.")
    sys.exit(1)
print(f"All {len(_results)} checks passed.")