import importlib.util import sys from pathlib import Path import pytest SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning" sys.path.insert(0, str(SRC)) spec = importlib.util.spec_from_file_location("street_probe", SRC / "street_holdout_probe.py") probe = importlib.util.module_from_spec(spec) spec.loader.exec_module(probe) sys.path.remove(str(SRC)) def record(group, name, split="train", rgb=None): return dict( group=group, name=name, sample_id=name, split=split, input={"rgb": {"sha256": rgb or name}} ) def test_physical_street_is_excluded_together_and_controls_never_enter_folds(): records = [ record("a", "a1"), record("a", "a2"), record("b", "b"), record("c", "c"), record("r", "r", "regression"), ] ff = list(probe.folds(records)) assert len(ff) == 3 for group, learn, held in ff: assert all(r["group"] != group and r["split"] == "train" for r in learn) assert all(r["group"] == group and r["split"] == "train" for r in held) assert {r["name"] for r in ff[0][2]} == {"a1", "a2"} with pytest.raises(ValueError, match="Identical RGB"): list( probe.folds( [record("a", "a", rgb="same"), record("b", "b", rgb="same"), record("c", "c")] ) ) def result(candidate, errors): return [ dict( phase="development", candidate=candidate, held_out=str(i), converged=True, metrics=dict(recall=1 - e, fpr=e), ) for i, e in enumerate(errors) ] def test_selection_checks_worst_street_and_missing_folds_and_rejects_controls(): rows = ( result("base", [0.1, 0.2, 0.3]) + result("good", [0.1, 0.1, 0.2]) + result("bad", [0, 0, 0.31]) ) assert probe.select_candidate(rows, "base")["selected"] == "good" with pytest.raises(ValueError, match="Missing"): probe.select_candidate(rows[:-1], "base") with pytest.raises(ValueError, match="Development"): probe.select_candidate([dict(rows[0], phase="regression")] + rows[1:], "base") worse = result("base", [0.1, 0.2, 0.3]) + result("bad", [0, 0, 0.31]) assert probe.select_candidate(worse, "base")["selected"] == "base" def test_held_out_group_cannot_fit_even_if_original_split_was_train(): with pytest.raises(ValueError, match="Held-out street"): probe.fit_candidate( [dict(group="a", split="train")], dict(head="linear", l2=0.01), held_out="a" )