Files
NODEDC_MISSION_CORE/tests/test_annotation_provenance.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

279 lines
10 KiB
Python

"""Provenance validates mechanics without changing labels or inventing evidence."""
import copy
import importlib.util
import json
import sys
from pathlib import Path
import pytest
from test_semantic_admission import admission as admission_fixture
from test_semantic_admission import corpus as corpus_fixture
from test_semantic_admission import dataset, decision, release
from test_semantic_corpus import group, opened, plan, refs
admission = admission_fixture
corpus = corpus_fixture
sys.path.insert(0, str(Path(__file__).parents[1] / "simulation/semantic-learning"))
import annotation_provenance as a # noqa: E402
import region_coverage as r # noqa: E402
def case():
old = bytearray([255]) * 48
old[0] = 0 # Outside ROI: earlier known background, not a new review.
old[18] = 1 # Inside automatic margin: preserve prior paint.
protected = bytearray(48)
protected[47] = 1 # Historical protected unknown, subtype unavailable.
packet = dict(
size=[8, 6],
roi=[1, 1, 7, 5],
view="top",
target_sha256=a.sha(old),
protected_sha256=a.sha(protected),
)
proposal = dict(
background_reviewed=True,
reason="synthetic complete ROI",
boundary_ignore_px=1,
paint_polygons=[[[2, 1], [6, 1], [6, 5], [2, 5]]],
unknown_polygons=[[[4, 2], [5, 2], [5, 3], [4, 3]]],
unknown_reason="synthetic source ambiguity",
)
record = r.raster_proposal(packet, proposal)
merged, stats = r.merge(packet, record, old, protected)
return packet, record, old, bytearray(merged), protected, stats
def check(values):
p, rec, old, merged, protected, stats = values
return a.audit_unit(p, rec, old, merged, protected, merged_sha256=stats["merged_sha256"])
def test_exact_partition_old_known_survives_and_outside_is_not_reviewed():
values = case()
snapshots = copy.deepcopy(values)
proof = check(values)
assert values == snapshots
assert proof["source_subtypes_known"] is True
assert proof["reviewed_pixels"] == 24
assert proof["categories"]["source_unknown"]["pixels"] == 1
assert proof["categories"]["source_unknown"]["remaining_unknown"] == 1
margin = proof["categories"]["automatic_margin"]
assert margin["retained_old_paint"] == 1
assert margin["remaining_unknown"] == margin["pixels"] - 1
assert proof["prior_protected_untyped"] == dict(
pixels=1, inside_roi=0, outside_roi=1, remaining_unknown=1
)
assert proof["outside_roi"] == dict(
pixels=24, prior_known=1, prior_protected_untyped=1, unassigned_unknown=22
)
assert proof["merged_sha256"] == a.sha(values[3])
def test_legacy_record_does_not_invent_source_or_margin_subtypes():
values = case()
del values[1]["source_unknown"]
proof = check(values)
assert proof["source_subtypes_known"] is False
assert proof["categories"]["source_unknown"]["pixels"] == 0
assert proof["categories"]["automatic_margin"]["pixels"] == 0
assert proof["categories"]["untyped_unknown"]["pixels"] > 0
@pytest.mark.parametrize("known", [0, 1])
def test_source_unknown_cannot_retain_prior_known(known):
p, rec, old, merged, protected, stats = case()
old[20] = merged[20] = known
p["target_sha256"] = a.sha(old)
stats["merged_sha256"] = a.sha(merged)
with pytest.raises(ValueError, match="Source unknown conflicts"):
check((p, rec, old, merged, protected, stats))
@pytest.mark.parametrize(
"change",
[
"target_sha",
"merged_sha",
"protected_sha",
"outside",
"old_known",
"source_known",
"missing",
"overlap",
"source_overlap",
"source_outside",
"view",
"protected_change",
],
)
def test_tamper_and_false_coverage_fail_closed(change):
p, rec, old, merged, protected, stats = case()
if change == "target_sha":
p["target_sha256"] = "0" * 64
elif change == "merged_sha":
stats["merged_sha256"] = "0" * 64
elif change == "protected_sha":
p["protected_sha256"] = "0" * 64
elif change == "outside":
merged[1] = 0
elif change == "old_known":
merged[18] = 255
elif change == "source_known":
merged[20] = 0
elif change == "missing":
rec["unknown"].pop()
elif change == "overlap":
rec["paint"] += [rec["paint"][0]]
rec["paint"].sort()
elif change == "source_overlap":
rec["source_unknown"] *= 2
elif change == "source_outside":
rec["source_unknown"] = [[0, 1, 2]]
elif change == "view":
rec["view"] = "other"
elif change == "protected_change":
merged[47] = 0
if change in {"outside", "old_known", "source_known", "protected_change"}:
stats["merged_sha256"] = a.sha(merged) # Valid checksum cannot hide invalid semantics.
with pytest.raises(ValueError):
check((p, rec, old, merged, protected, stats))
@pytest.fixture
def publication(admission, corpus, tmp_path, monkeypatch):
source = dataset(tmp_path, "source")
receipt = corpus.build(
tmp_path, plan(corpus, [source], [group("physical", "train", "a" * 64)]), "corpora/v1"
)
with opened(corpus, tmp_path, receipt) as reader:
ref = refs(reader)[0]
ptr, _ = release(admission, tmp_path, receipt, [ref], [decision(admission, ref)])
with admission.Supervision(tmp_path, ptr["path"], ptr["sha256"]) as reader:
entry = next(e for b in reader.training_batches("observed_paint") for e in b)
target = entry["targets"][0]
original = admission.pixel_target(target)
protected = bytearray(len(original))
for y, start, end in target["unknown"]:
protected[y * 8 + start : y * 8 + end] = bytes([1]) * (end - start)
payload = dict(
supervision=ptr,
sample_id=entry["sample_id"],
view="top",
size=[8, 6],
roi=[0, 0, 8, 2],
target_sha256=a.sha(original),
protected_sha256=a.sha(protected),
)
unit = dict(id="roi", physical_group="physical", split="train", payload=payload)
proposal = dict(
reason="reviewed synthetic stripe",
background_reviewed=True,
boundary_ignore_px=1,
paint_polygons=[[[1, 0], [6, 0], [6, 2], [1, 2]]],
unknown_polygons=[],
)
state = dict(
state="closed",
plan=dict(root_actor="root", units=[unit]),
root_review=dict(verdict="accepted", admitted_units=["roi"]),
tasks=[dict(unit="roi", stage="annotate", result=proposal)],
)
monkeypatch.setitem(sys.modules, "admission_store", admission)
spec = importlib.util.spec_from_file_location(
"provenance_publish_test",
Path(__file__).parents[1] / "simulation/semantic-learning/agent_admission.py",
)
pub = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pub)
class FakeCycle:
def __init__(self, *args):
pass
def status(self, identity):
return state
def close(self):
pass
monkeypatch.setattr(pub, "Cycle", FakeCycle)
identity = "c" * 64
result = pub.publish(tmp_path, identity, "supervision/published")
return pub, result, tmp_path / "agent-reviews" / identity, identity
@pytest.mark.parametrize("corrupt_legacy", [False, True])
def test_real_publication_legacy_retry_preserves_every_existing_byte(
publication, tmp_path, corrupt_legacy
):
pub, expected, journal, identity = publication
path = journal / "audit.json"
current = json.loads(path.read_bytes())
assert "provenance" in current["units"][0] # New publication includes proof.
legacy = copy.deepcopy(current)
for unit in legacy["units"]:
del unit["provenance"]
if corrupt_legacy:
legacy["units"][0]["coverage"]["paint"] += 1
# Model an actual historical audit, including different insignificant whitespace.
path.write_text(json.dumps(legacy, indent=4) + "\n")
saved = {
p: p.read_bytes()
for directory in (journal, tmp_path / "supervision/published")
for p in directory.rglob("*")
if p.is_file()
}
sidecar = journal / "audit-provenance-v1.json"
if corrupt_legacy:
with pytest.raises(ValueError, match="legacy audit differs"):
pub.publish(tmp_path, identity, "supervision/published")
assert not sidecar.exists()
else:
assert pub.publish(tmp_path, identity, "supervision/published") == expected
proof = json.loads(sidecar.read_bytes())
assert proof["legacy_audit_sha256"] == a.sha(saved[path])
assert proof["audit"] == current
exact_sidecar = sidecar.read_bytes()
assert pub.publish(tmp_path, identity, "supervision/published") == expected
assert sidecar.read_bytes() == exact_sidecar
# Existing sidecar is immutable too; even an otherwise valid legacy retry fails.
sidecar.write_text("{}\n")
with pytest.raises(ValueError, match="Published evidence changed"):
pub.publish(tmp_path, identity, "supervision/published")
assert sidecar.read_text() == "{}\n"
assert all(p.read_bytes() == before for p, before in saved.items())
@pytest.mark.parametrize("change", ["changed_to_current", "missing_audit"])
def test_existing_sidecar_blocks_audit_replacement_or_removal(publication, tmp_path, change):
pub, expected, journal, identity = publication
path = journal / "audit.json"
current_bytes = path.read_bytes()
legacy = json.loads(current_bytes)
for unit in legacy["units"]:
del unit["provenance"]
path.write_text(json.dumps(legacy, indent=4) + "\n")
assert pub.publish(tmp_path, identity, "supervision/published") == expected
sidecar = journal / "audit-provenance-v1.json"
sidecar_bytes = sidecar.read_bytes()
release_bytes = {
p: p.read_bytes() for p in (tmp_path / "supervision/published").rglob("*") if p.is_file()
}
if change == "changed_to_current":
path.write_bytes(current_bytes)
else:
path.unlink()
with pytest.raises(
ValueError, match="Published evidence changed|requires its original legacy audit"
):
pub.publish(tmp_path, identity, "supervision/published")
assert sidecar.read_bytes() == sidecar_bytes
assert all(p.read_bytes() == value for p, value in release_bytes.items())
if change == "changed_to_current":
assert path.read_bytes() == current_bytes
else:
assert not path.exists() # A rejected retry must not recreate audit.json.