Files
NODEDC_MISSION_CORE/tests/test_semantic_admission.py
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00

540 lines
21 KiB
Python

"""Task-specific evidence, unchanged labels, context isolation and sparse ignore masks."""
import copy
import importlib.util
import json
import subprocess
import sys
from pathlib import Path
import pytest
from test_semantic_corpus import corpus as corpus_fixture
from test_semantic_corpus import group, opened, plan, refs
from test_semantic_delivery import ds
corpus = corpus_fixture
@pytest.fixture
def admission(corpus, monkeypatch):
monkeypatch.setitem(sys.modules, "corpus_store", corpus)
spec = importlib.util.spec_from_file_location(
"admission_store_test",
Path(__file__).parents[1] / "simulation/semantic-learning/admission_store.py",
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def dataset(root, name, world="a" * 64, revision="b" * 64):
folder = root / "datasets" / name / "window"
folder.mkdir(parents=True)
# Synthetic media bytes: admission checks identity, not image interpretation.
for view in ("top", "oblique"):
(folder / f"{view}.png").write_bytes(b"synthetic-raw-view-" + view.encode())
ds.write(
folder / "cameras.json",
dict(
views=[
dict(
id=v,
size=[8, 6],
projection="ortho",
eye=[0, 0, 10],
target=[0, 0, 0],
up=[0, 1, 0],
width_m=8,
)
for v in ("top", "oblique")
],
coordinates="scene-local XYZ, metres, Z up",
pixel_convention="pixel centres",
),
)
geometry = dict(
type="LineString",
coordinates=[
[0.0, 0.0, 0.1234567890123],
[4.0, 0.0, 0.1234567890123],
[8.0, 0.0, 0.1234567890123],
],
)
features = [
dict(
id="road",
properties=dict(**{"class": "road_boundary"}, review_status="accepted"),
geometry=geometry,
),
dict(
id="deleted",
properties=dict(**{"class": "road_boundary"}, review_status="rejected"),
geometry=geometry,
),
]
ds.write(
folder / "labels.json",
dict(
original_element=copy.deepcopy(features),
proposed_element=features,
projections={
v: [
dict(feature_id=f["id"], uv=[[0, 0], [4, 0], [8, 0]], in_front=[True] * 3)
for f in features
]
for v in ("top", "oblique")
},
),
)
parent = folder.parent
ds.write(
folder / "sample.json",
dict(
members=[p.relative_to(parent).as_posix() for p in sorted(folder.iterdir())],
revision=revision,
split_group=world,
training_eligible=False,
complete_regions=[],
),
)
ds.write(
parent / "dataset.json",
dict(
schema_version=ds.SCHEMA,
world_sha256=world,
revision=revision,
annotation_sha256="c" * 64,
split_group=world,
samples=["window/sample.json"],
training_eligible=False,
files={
p.relative_to(parent).as_posix(): dict(
sha256=ds.checksum(p), bytes=p.stat().st_size
)
for p in parent.rglob("*")
if p.is_file()
},
),
)
return dict(
path=parent.relative_to(root).as_posix(), sha256=ds.checksum(parent / "dataset.json")
)
def identity(reference):
return {k: reference["source"][k] for k in ("world_sha256", "revision", "annotation_sha256")}
def input_view(reference, view="top"):
return dict(sample_id=reference["id"], view=view)
def decision(admission, reference):
geometry = dict(
type="LineString",
coordinates=[
[0.0, 0.0, 0.1234567890123],
[4.0, 0.0, 0.1234567890123],
[8.0, 0.0, 0.1234567890123],
],
)
return dict(
schema_version=admission.DECISION_SCHEMA,
sample_id=reference["id"],
reviewer=dict(id="synthetic-reviewer", kind="assistant"),
reviewed_utc="2026-10-23T12:00:00+00:00",
reason="Synthetic test evidence",
inputs=[input_view(reference), input_view(reference, "oblique")],
observed_paint=[
dict(view="top", paint=[[1, 2, 5]], background=[[4, 1, 7]], unknown=[[2, 2, 5]])
],
contextual_map=[
dict(
feature_id="road",
geometry_sha256=ds.digest(geometry),
ranges=[[0, 0, 0.25, 0.75]],
state="confirmed",
evidence="context",
support=[input_view(reference, "oblique")],
reason="Synthetic surrounding view supports this interval",
)
],
)
@pytest.fixture
def sample(admission, corpus, tmp_path):
a = dataset(tmp_path, "source")
receipt = corpus.build(
tmp_path, plan(corpus, [a], [group("physical-a", "train", "a" * 64)]), "corpora/v1"
)
with opened(corpus, tmp_path, receipt) as reader:
reference = refs(reader)[0]
return receipt, reference, decision(admission, reference)
def release(admission, root, receipt, references, decisions, destination="supervision/v1"):
(root / "reviews").mkdir(exist_ok=True)
entries = []
for i, d in enumerate(decisions):
path = root / "reviews" / f"{destination.replace('/', '-')}-{i}.json"
ds.write(path, d)
entries.append(dict(path=path.relative_to(root).as_posix(), sha256=ds.checksum(path)))
revisions = {r["source"]["world_sha256"]: identity(r) for r in references}
p = dict(
schema_version=admission.PLAN_SCHEMA,
corpus=receipt,
revisions=list(revisions.values()),
decisions=entries,
)
return admission.build(root, p, destination), p
def records(reader, task="observed_paint", split="train"):
return [r for b in reader.batches(task, split) for r in b]
def test_sparse_pixels_preserve_unknown_and_context_is_a_separate_target(
admission, corpus, tmp_path, sample
):
receipt, reference, d = sample
with opened(corpus, tmp_path, receipt) as c:
value = admission.compile_decision(c, d, admission.revision_policy([identity(reference)]))
pixels = admission.pixel_target(value["observed_paint"][0])
assert len(pixels) == 48 and pixels.count(1) == 3 and pixels.count(0) == 6
assert pixels.count(255) == 39 and pixels[2 * 8 + 3] == 255
# No automatic conversion of reconstructed geometry to a visible-paint mask.
assert value["contextual_map"][0]["fragments"] == [
[[1.0, 0.0, 0.1234567890123], [3.0, 0.0, 0.1234567890123]]
]
assert value["contextual_map"][0]["completeness"] == "reviewed-ranges-only"
assert not value["background_from_absence"]
@pytest.mark.parametrize(
"change",
["pixel-conflict", "unknown-conflict", "bounds", "float", "duplicate-view", "missing-view"],
)
def test_ambiguous_pixel_supervision_fails(admission, corpus, tmp_path, sample, change):
receipt, r, d = sample
v = d["observed_paint"][0]
if change == "pixel-conflict":
v["background"] = [[1, 4, 6]]
elif change == "unknown-conflict":
v["unknown"] = [[1, 3, 4]]
elif change == "bounds":
v["paint"] = [[6, 1, 2]]
elif change == "float":
v["paint"] = [[1, 1.2, 2.2]]
elif change == "duplicate-view":
d["observed_paint"].append(copy.deepcopy(v))
else:
d["inputs"] = [input_view(r, "oblique")]
with opened(corpus, tmp_path, receipt) as c, pytest.raises(ValueError):
admission.compile_decision(c, d, admission.revision_policy([identity(r)]))
@pytest.mark.parametrize(
"change",
[
"rule",
"no-support",
"hidden-support",
"deleted",
"geometry",
"range",
"overlap",
"no-reviewer",
"time",
],
)
def test_unsafe_vector_admission_fails(admission, corpus, tmp_path, sample, change):
receipt, r, d = sample
v = d["contextual_map"][0]
if change == "rule":
v["evidence"] = "rule"
elif change == "no-support":
v["support"] = []
elif change == "hidden-support":
d["inputs"] = [input_view(r)]
elif change == "deleted":
v["feature_id"] = "deleted"
elif change == "geometry":
v["geometry_sha256"] = "0" * 64
elif change == "range":
v["ranges"] = [[0, 2, 0, 1]]
elif change == "overlap":
d["contextual_map"].append(copy.deepcopy(v))
elif change == "no-reviewer":
d["reviewer"]["kind"] = "rule"
else:
d["reviewed_utc"] = "2026-10-23T12:00:00"
with opened(corpus, tmp_path, receipt) as c, pytest.raises(ValueError):
admission.compile_decision(c, d, admission.revision_policy([identity(r)]))
def test_weak_and_unknown_are_retained_but_never_training_targets(
admission, corpus, tmp_path, sample
):
receipt, r, d = sample
d["observed_paint"][0]["paint"] = []
d["observed_paint"][0]["background"] = []
d["contextual_map"][0].update(state="weak", evidence="rule", support=[])
unknown = copy.deepcopy(d["contextual_map"][0])
unknown.update(state="unknown", evidence="unknown", ranges=[[0, 1, 0, 1]])
d["contextual_map"].append(unknown)
with opened(corpus, tmp_path, receipt) as c:
compiled = admission.compile_decision(c, d, admission.revision_policy([identity(r)]))
assert len(compiled["excluded_vectors"]) == 2 and not compiled["contextual_map"]
assert set(admission.pixel_target(compiled["observed_paint"][0])) == {255}
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
assert records(reader) == records(reader, "contextual_map") == []
def test_release_uses_exact_revisions_and_does_not_modify_sources(
admission, corpus, tmp_path, sample
):
receipt, r, d = sample
source = tmp_path / "datasets/source"
before = {p.relative_to(source): p.read_bytes() for p in source.rglob("*") if p.is_file()}
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
paint = records(reader)[0]
geometry = records(reader, "contextual_map")[0]
assert paint["task"] == "observed_paint" and len(paint["targets"]) == 1
assert "fragments" not in paint["targets"][0]
assert geometry["targets"][0]["evidence"] == "context"
assert geometry["supervision_scope"] == "reviewed-vector-ranges-only"
assert not geometry["background_from_absence"]
assert geometry["targets"][0]["supervised_axes"] == ["x", "y"]
assert not geometry["targets"][0]["z_supervision"]
assert len(geometry["inputs"]) == 2
assert all("labels" not in i for i in geometry["inputs"])
assert len(list(reader.training_batches("observed_paint"))) == 1
assert before == {
p.relative_to(source): p.read_bytes() for p in source.rglob("*") if p.is_file()
}
with opened(corpus, tmp_path, receipt) as c:
wrong = identity(r)
wrong["revision"] = "d" * 64
with pytest.raises(ValueError, match="selected annotation"):
admission.compile_decision(c, d, admission.revision_policy([wrong]))
with pytest.raises(ValueError, match="exactly one"):
admission.revision_policy([identity(r), wrong])
def test_context_from_neighbors_must_be_present_and_cannot_cross_controls(
admission, corpus, tmp_path
):
a = dataset(tmp_path, "a")
neighbor = dataset(tmp_path, "neighbor")
# Distinct export identity, still same frozen world/annotation coordinate frame.
manifest = tmp_path / neighbor["path"] / "dataset.json"
data = ds.read(manifest)
data["description"] = "adjacent window fixture"
ds.write(manifest, data)
neighbor["sha256"] = ds.checksum(manifest)
b = dataset(tmp_path, "b", world="f" * 64)
receipt = corpus.build(
tmp_path,
plan(
corpus, [a, neighbor, b], [group("a", "train", "a" * 64), group("b", "test", "f" * 64)]
),
"corpora/v1",
)
with opened(corpus, tmp_path, receipt) as c:
aa = refs(c)
rr = refs(c, "test")[0]
d = decision(admission, aa[0])
d["inputs"].append(input_view(aa[1]))
d["contextual_map"][0]["support"] = [input_view(aa[1])]
policy = admission.revision_policy([identity(aa[0]), identity(rr)])
assert len(admission.compile_decision(c, d, policy)["inputs"]) == 3
d["inputs"].append(input_view(rr))
with pytest.raises(ValueError, match="Context must share"):
admission.compile_decision(c, d, policy)
d = decision(admission, aa[0])
control = decision(admission, rr)
frozen, _ = release(admission, tmp_path, receipt, [aa[0], rr], [d, control])
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
train = [r for batch in reader.training_batches("contextual_map") for r in batch]
assert {v["sample_id"] for v in train} == {aa[0]["id"]}
test = records(reader, "contextual_map", "test")
assert len(test) == 1 and not test[0]["training_eligible"]
def test_pinned_reviews_media_and_corpus_are_verified(admission, tmp_path, sample):
receipt, r, d = sample
frozen, p = release(admission, tmp_path, receipt, [r], [d])
# Editing a draft decision does not change the already published release.
ds.write(tmp_path / p["decisions"][0]["path"], {})
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
assert len(records(reader)) == 1
with pytest.raises(ValueError, match="decision changed"):
admission.build(tmp_path, p, "supervision/v2")
(tmp_path / r["dataset"] / "window/top.png").write_bytes(b"corrupted")
with pytest.raises(ValueError, match="member changed"):
release(admission, tmp_path, receipt, [r], [d], "supervision/v3")
assert not (tmp_path / "supervision/v3").exists()
assert not list((tmp_path / "supervision").glob(".supervision-*"))
manifest = ds.read(tmp_path / frozen["path"] / "supervision.json")
member = next(v["path"] for v in manifest["records"].values())
ds.write(tmp_path / frozen["path"] / member, {})
with pytest.raises(ValueError, match="member changed"):
admission.Supervision(tmp_path, frozen["path"], frozen["sha256"])
def test_reader_is_lazy_and_portable_with_a_bounded_batch(admission, tmp_path, sample, monkeypatch):
receipt, r, d = sample
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
original = Path.open
def no_media(path, *a, **kw):
if path.suffix == ".png":
pytest.fail("metadata iteration opened RGB")
return original(path, *a, **kw)
with monkeypatch.context() as scoped:
scoped.setattr(Path, "open", no_media)
assert len(records(reader)) == 1
moved = tmp_path.with_name(tmp_path.name + "-moved")
tmp_path.rename(moved)
result = subprocess.run(
[
sys.executable,
"-B",
str(moved / frozen["path"] / "admission_store.py"),
"inspect",
str(moved),
frozen["path"],
frozen["sha256"],
],
check=True,
capture_output=True,
text=True,
)
assert json.loads(result.stdout)["counts"]["train"]["contextual_map"] == 1
with admission.Supervision(moved, frozen["path"], frozen["sha256"]) as reader:
with pytest.raises(ValueError):
list(reader.training_batches("all"))
with pytest.raises(ValueError):
list(reader.training_batches("contextual_map", 129))
moved.rename(tmp_path)
def test_overwrite_duplicate_and_budget_failure_preserve_old_release(
admission, tmp_path, sample, monkeypatch
):
receipt, r, d = sample
frozen, p = release(admission, tmp_path, receipt, [r], [d])
with pytest.raises(ValueError, match="already exists"):
admission.build(tmp_path, p, frozen["path"])
duplicate = copy.deepcopy(p)
duplicate["decisions"] *= 2
with pytest.raises(ValueError, match="Conflicting decisions"):
admission.build(tmp_path, duplicate, "supervision/duplicate")
for path in ("../escape", "datasets/source/inside", "corpora/v1/inside", "reviews"):
with pytest.raises(ValueError):
admission.build(tmp_path, p, path)
monkeypatch.setattr(admission, "MAX_RELEASE", 10)
with pytest.raises(ValueError, match="byte budget"):
admission.build(tmp_path, p, "supervision/v2")
assert not list((tmp_path / "supervision").glob(".supervision-*"))
assert ds.checksum(tmp_path / frozen["path"] / "supervision.json") == frozen["sha256"]
def test_ranges_never_silently_flatten_curves_or_fill_polygons(admission):
f = dict(
geometry=dict(type="Polygon", coordinates=[[[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 0, 0]]]),
properties={},
)
assert admission.fragments(f, [[0, 0, 0, 1]]) == [[[0, 0, 0], [1, 0, 0]]]
f["properties"]["editor_curves"] = {"0": {"mode": "curved"}}
with pytest.raises(ValueError, match="curve-aware"):
admission.fragments(f, [[0, 0, 0, 1]])
def test_one_object_cannot_have_conflicting_geometry_in_one_selected_revision(
admission, corpus, tmp_path
):
a = dataset(tmp_path, "a")
b = dataset(tmp_path, "b")
root = tmp_path / b["path"]
labels = ds.read(root / "window/labels.json")
labels["proposed_element"][0]["geometry"]["coordinates"][0][0] = 1.0
ds.write(root / "window/labels.json", labels)
manifest = ds.read(root / "dataset.json")
manifest["files"]["window/labels.json"] = dict(
sha256=ds.checksum(root / "window/labels.json"),
bytes=(root / "window/labels.json").stat().st_size,
)
ds.write(root / "dataset.json", manifest)
b["sha256"] = ds.checksum(root / "dataset.json")
receipt = corpus.build(
tmp_path, plan(corpus, [a, b], [group("a", "train", "a" * 64)]), "corpora/v1"
)
with opened(corpus, tmp_path, receipt) as c:
references = refs(c)
decisions = [decision(admission, r) for r in references]
for d, r in zip(decisions, references, strict=True):
d["contextual_map"][0]["geometry_sha256"] = ds.digest(
c.review(r)["active_candidates"][0]["geometry"]
)
with pytest.raises(ValueError, match="Conflicting source geometry"):
release(admission, tmp_path, receipt, references, decisions)
assert not (tmp_path / "supervision/v1").exists()
def test_unknown_only_views_are_not_empty_loss_targets_and_media_is_rechecked(
admission, tmp_path, sample
):
receipt, r, d = sample
d["observed_paint"].append(dict(view="oblique", paint=[], background=[], unknown=[[0, 0, 8]]))
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
example = records(reader)[0]
assert len(example["targets"]) == 1 and len(example["inputs"]) == 2
value = example["inputs"][0]
with reader.open_image(value) as stream:
assert stream.read() == b"synthetic-raw-view-top"
assert stream.closed
fake = copy.deepcopy(value)
fake["rgb"]["name"] = "window/labels.json"
with pytest.raises(ValueError, match="bound raw RGB"):
reader.open_image(fake)
(tmp_path / r["dataset"] / value["rgb"]["name"]).write_bytes(b"changed")
with pytest.raises(ValueError, match="member changed"), reader.open_image(value):
pass
def test_multiple_reviewed_windows_use_bounded_batches(admission, corpus, tmp_path):
inputs = []
for i in range(3):
entry = dataset(tmp_path, str(i))
path = tmp_path / entry["path"] / "dataset.json"
manifest = ds.read(path)
manifest["window_identity"] = i
ds.write(path, manifest)
entry["sha256"] = ds.checksum(path)
inputs.append(entry)
receipt = corpus.build(
tmp_path, plan(corpus, inputs, [group("area-a", "train", "a" * 64)]), "corpora/v1"
)
with opened(corpus, tmp_path, receipt) as c:
references = refs(c)
frozen, _ = release(
admission, tmp_path, receipt, references, [decision(admission, r) for r in references]
)
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
assert [len(b) for b in reader.training_batches("contextual_map", 2)] == [2, 1]
def test_unverified_vertical_height_is_not_a_planar_target(admission):
feature = dict(
geometry=dict(type="LineString", coordinates=[[1, 2, 3], [1, 2, 4]]), properties={}
)
with pytest.raises(ValueError, match="planar"):
admission.fragments(feature, [[0, 0, 0, 1]])