| |
| """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 |
|
|
| _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} ---") |
|
|
|
|
| |
| 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}") |
|
|
| |
| 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") |
|
|
| |
| |
| 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") |
| |
| 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") |
|
|
| |
| |
| 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") |
|
|
| |
| 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} |
|
|
| |
| |
| _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)) |
|
|
| |
| 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") |
| |
| 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)) |
|
|
| |
| 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)") |
|
|
| |
| section("6. Full sweep: 992 configs x every 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}") |
|
|
| |
| |
| 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}") |
|
|
| |
| |
| _INTRODUCED_120 = ["AFIDs", "DEEP-PSMA", "LIDC-IDRI", "LNQ2023", "PDDCA", "VerSe"] |
| |
| |
| |
| _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") |
|
|
| |
| 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",) |
|
|
| |
| 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"), |
| |
| |
| (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"), |
| |
| |
| |
| |
| |
| (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"), |
| |
| (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}") |
|
|
| |
| 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) |
|
|
| |
| 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] |
| 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" |
|
|
| |
| |
| |
| 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")) |
|
|
| |
| |
| |
| |
| 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}") |
| |
| 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) |
|
|
| |
| section("10. Step 3.2 never swallows a failure into a completion marker") |
|
|
| |
| |
| |
| |
| _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) |
|
|
| |
| |
| 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}") |
|
|
| |
| |
| 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]}") |
|
|
| |
| |
| 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") |
|
|
| |
| section("11. Two data roots never share one Arrow cache") |
|
|
| |
| |
| |
| |
| |
| _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) |
|
|
| |
| section("12. The data root is canonicalised before the download scripts see it") |
|
|
| |
| |
| |
| |
| _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) |
| try: |
| os.chdir(_d) |
| 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") |
| |
| _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) |
|
|
| |
| section("13. Step 3.1 owns the shared annotation zip under a per-dataset lock") |
|
|
| |
| |
| |
| |
| _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") |
| |
| _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") |
| |
| _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") |
|
|
| |
| |
| |
| |
| _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) |
|
|
| |
| 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 |
|
|
|
|
| |
| |
| |
| 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: |
| _broke.append((c.name, type(e).__name__)) |
| check(not _broke, f"all {len(_clean_cfgs)} unpaused configs load through _info()", |
| f"broke: {_broke[:3]}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| _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") |
|
|
| |
| |
| _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: |
| _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") |
|
|
| |
| 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") |
|
|
| |
| section("15. A withdrawn version is reported as withdrawn, not as never-published") |
|
|
| |
| |
| |
| |
| 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 |
|
|
| |
| _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") |
|
|
| |
| |
| _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") |
|
|
| |
| _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") |
|
|
| |
| |
| |
| 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") |
|
|
| |
| 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.") |
|
|