"""Mixed admission rejects identity drift and preserves class mass across folds.""" import copy import hashlib import json import sys from pathlib import Path import numpy as np import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning")) import mixed_supervision as m def target_view(target): runs = {"paint": [], "background": [], "unknown": []} for row, col in np.ndindex(target.shape): label = int(target[row, col]) if label != 255: runs["paint" if label else "background"].append([row, col, col + 1]) return dict(view="top", size=list(target.shape[::-1]), **runs) def fixtures(): records, weights, entries = [], {}, {} for name, group, values in [ ("a", "g", [[1, 1, 0, 255], [255, 0, 255, 255]]), ("b", "g", [[1, 255, 0, 255], [255, 255, 255, 255]]), ("c", "h", [[1, 0, 255, 255], [255, 255, 255, 255]]), ]: t = np.array(values, dtype=np.uint8) image = dict( sample_id=name, view="top", camera={"size": [4, 2]}, rgb={"path": name + "/top.png", "sha256": name * 64}, ) r = dict(name=name, sample_id=name, group=group, split="train", input=image, target=t) records.append(r) weights[name] = np.where(t == 255, 0, 0.2 if name == "a" else 0.1).astype(np.float32) entries[name] = dict( sample_id=name, physical_group=group, split="train", task="observed_paint", source={"world_sha256": name * 64}, inputs=[copy.deepcopy(image)], targets=[target_view(t)], ) return records, weights, entries, copy.deepcopy(entries) def admission(records, new): a = records[0]["target"].copy() a[0, 1] = 255 a[1, 0] = 1 new["a"]["targets"] = [target_view(a)] b = records[1]["target"].copy() b[1, 0] = 0 new["b"]["targets"] = [target_view(b)] def proof(records, old): value = dict( schema="missioncore.mixed-withdrawals/v1", evidence=[dict(path="archive/review.json", sha256="e" * 64)], records={ "a": dict( source=old["a"]["source"], input=records[0]["input"], old_target_sha256=m._sha(records[0]["target"].tobytes()), runs=[[0, 1, 2]], ) }, ) return value def kwargs(value): payload = json.dumps(value, sort_keys=True).encode() return dict(withdrawal_bytes=payload, withdrawal_sha256=hashlib.sha256(payload).hexdigest()) def test_mixed_growth_with_exact_withdrawal_and_conserved_group_class_mass(): records, weights, old, new = fixtures() admission(records, new) original = copy.deepcopy((records, weights, old, new)) out, ww, audit = m.prepare_mixed(records, weights, old, new, **kwargs(proof(records, old))) assert out[0]["target"].tolist() == [[1, 255, 0, 255], [1, 0, 255, 255]] assert out[0]["mixed_added_paint"].sum() == 1 assert out[0]["mixed_withdrawn"].sum() == 1 assert out[1]["mixed_added_background"].sum() == 1 assert audit["records"][0]["withdrawn_paint"] == 1 for mass in audit["masses"]: assert mass["after"] == pytest.approx(mass["before"]) for label in (0, 1): group_rows = [r for r in out if r["group"] == "g"] amounts = [ww[r["name"]][r["target"] == label].sum() for r in group_rows] assert amounts[0] == pytest.approx(amounts[1]) np.testing.assert_array_equal(ww["c"], weights["c"]) for r, previous in zip(records, original[0], strict=True): np.testing.assert_array_equal(r["target"], previous["target"]) np.testing.assert_array_equal(weights[r["name"]], original[1][r["name"]]) assert old == original[2] and new == original[3] assert all(not ww[r["name"]][r["target"] == 255].any() for r in out) def test_identity_release_is_bit_exact_and_fold_can_use_global_proof(): records, weights, old, new = fixtures() out, ww, _ = m.prepare_mixed(records, weights, old, new) for r, n in zip(records, out, strict=True): np.testing.assert_array_equal(r["target"], n["target"]) np.testing.assert_array_equal(weights[r["name"]], ww[r["name"]]) _, fold_weights, _ = m.prepare_mixed( records[2:], {"c": weights["c"]}, {"c": old["c"]}, {"c": new["c"]}, **kwargs(proof(records, old)), ) np.testing.assert_array_equal(fold_weights["c"], weights["c"]) @pytest.mark.parametrize( "field", ["source", "physical_group", "split", "sample_id", "task", "inputs"] ) def test_release_identity_drift_is_rejected(field): records, weights, old, new = fixtures() new["a"][field] = "changed" with pytest.raises(ValueError, match="binding changed"): m.prepare_mixed(records, weights, old, new) @pytest.mark.parametrize( "fault", [ "missing_proof", "bad_hash", "wrong_source", "wrong_input", "old_hash", "extra", "missing", "duplicate", "outside", "no_evidence", "flip", "cached_target", "unknown_weight", "zero_weight", "nan", "wrong_record", "duplicate_id", ], ) def test_fail_closed_for_invalid_admission_or_provenance(fault): records, weights, old, new = fixtures() admission(records, new) doc = proof(records, old) p = doc["records"]["a"] if fault == "wrong_source": p["source"] = {} elif fault == "wrong_input": p["input"] = {} elif fault == "old_hash": p["old_target_sha256"] = "0" * 64 elif fault == "extra": p["runs"].append([0, 0, 1]) elif fault == "missing": p["runs"] = [] elif fault == "duplicate": p["runs"].append([0, 1, 2]) elif fault == "outside": p["runs"] = [[2, 0, 1]] elif fault == "no_evidence": doc["evidence"] = [] elif fault == "flip": t = records[1]["target"].copy() t[0, 0] = 0 new["b"]["targets"] = [target_view(t)] elif fault == "cached_target": records[1]["target"][0, 0] = 0 elif fault == "unknown_weight": weights["b"][0, 1] = 0.1 elif fault == "zero_weight": weights["b"][0, 0] = 0 elif fault == "nan": weights["b"][0, 0] = np.nan elif fault == "wrong_record": records[1]["group"] = "g-other" elif fault == "duplicate_id": records[1]["sample_id"] = "a" kw = kwargs(doc) if fault == "missing_proof": kw = {} elif fault == "bad_hash": kw["withdrawal_sha256"] = "0" * 64 with pytest.raises(ValueError): m.prepare_mixed(records, weights, old, new, **kw) def test_withdrawing_last_class_support_cannot_silently_discard_mass(): records, weights, old, new = fixtures() records, old, new = records[2:], {"c": old["c"]}, {"c": new["c"]} target = records[0]["target"].copy() target[0, 0] = 255 new["c"]["targets"] = [target_view(target)] doc = dict( schema="missioncore.mixed-withdrawals/v1", evidence=[dict(path="review.json", sha256="e" * 64)], records={ "c": dict( source=old["c"]["source"], input=records[0]["input"], old_target_sha256=m._sha(records[0]["target"].tobytes()), runs=[[0, 0, 1]], ) }, ) with pytest.raises(ValueError, match="baseline mass and final support"): m.prepare_mixed(records, {"c": weights["c"]}, old, new, **kwargs(doc)) def test_target_view_order_does_not_choose_context_view(): records, weights, old, new = fixtures() for entries in (old, new): for entry in entries.values(): view = copy.deepcopy(entry["targets"][0]) view["view"] = "oblique" entry["targets"].insert(0, view) out, _, _ = m.prepare_mixed(records, weights, old, new) for a, b in zip(records, out, strict=True): np.testing.assert_array_equal(a["target"], b["target"]) new["a"]["targets"][-1]["size"] = [8, 1] with pytest.raises(ValueError, match="dimensions differ"): m.prepare_mixed(records, weights, old, new) def test_new_class_without_baseline_mass_is_rejected(): records, weights, old, new = fixtures() records = records[2:] records[0]["target"][0, 0] = 0 old = {"c": old["c"]} old["c"]["targets"] = [target_view(records[0]["target"])] new = copy.deepcopy(old) target = records[0]["target"].copy() target[0, 2] = 1 new["c"]["targets"] = [target_view(target)] with pytest.raises(ValueError, match="baseline mass and final support"): m.prepare_mixed(records, {"c": weights["c"]}, old, new) def test_paint_only_addition_preserves_background_weights_exactly(): records, weights, old, new = fixtures() target = records[0]["target"].copy() target[1, 0] = 1 new["a"]["targets"] = [target_view(target)] out, ww, _ = m.prepare_mixed(records, weights, old, new) for original, updated in zip(records, out, strict=True): mask = updated["target"] == 0 np.testing.assert_array_equal(ww[original["name"]][mask], weights[original["name"]][mask])