Files
NODEDC_MISSION_CORE/tests/test_semantic_snapshot.py
T
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

223 lines
8.2 KiB
Python

"""Final geometry coverage and portable sharding never turn unknown into negatives."""
import copy
import importlib.util
import sys
from pathlib import Path
import pytest
from test_semantic_delivery import draft, ds
from k1link.simulation.ai_polygon import semantic_objects, semantic_vectors
@pytest.fixture
def snapshot(monkeypatch):
for key, value in {
"dataset_store": ds,
"semantic_objects": semantic_objects,
"semantic_vectors": semantic_vectors,
}.items():
monkeypatch.setitem(sys.modules, key, value)
spec = importlib.util.spec_from_file_location(
"final_snapshot",
Path(__file__).parents[1] / "simulation/semantic-learning/final_snapshot.py",
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def feature(points, kind="road_boundary", id="road"):
return dict(
id=id,
properties={"class": kind, "review_status": "unreviewed"},
geometry=dict(type="LineString", coordinates=points),
)
def package(features):
return dict(
model={"features": copy.deepcopy(features)},
edited={"features": copy.deepcopy(features)},
revisions=[],
revision="a" * 64,
world_sha256="b" * 64,
)
def test_long_edges_cover_every_grid_cell_without_changing_vertices(snapshot):
p = package([feature([[1, 2, 3], [91, 2, 12]])])
original = copy.deepcopy(p)
result = snapshot.plan(p, ["road_boundary"])
assert len(result["windows"]) == 10 and p == original
assert all(w["features"] == ["road"] for w in result["windows"])
split = package([feature([[1, 2, 3], [36, 2, 6.5], [91, 2, 12]])])
assert snapshot.plan(split, ["road_boundary"])["windows"] == result["windows"]
def test_large_edit_uses_final_geometry_and_keeps_other_classes_ignored(snapshot):
p = package(
[
feature([[1, 2, 3], [91, 2, 12]]),
feature([[1, 100, 3], [91, 100, 12]], "building_facade", "house"),
]
)
p["revisions"] = [
dict(
operations=[dict(kind="move", feature_id="road", path=0, index=0, position=[1, 32, 3])]
)
]
p["edited"]["features"][0]["geometry"]["coordinates"][0] = [1, 32, 3]
result = snapshot.plan(p, ["road_boundary"])
assert len(result["windows"]) > 10
assert all(w["features"] == ["road"] for w in result["windows"])
assert not result["training_eligible"]
p["edited"]["features"][0]["geometry"]["coordinates"][0][0] += 1
with pytest.raises(ValueError, match="Replayed"):
snapshot.plan(p, ["road_boundary"])
def test_collection_portable_integrity_and_policy(tmp_path):
root = tmp_path / "collection"
root.mkdir()
draft(root / "part-000")
result = ds.verify(root / "part-000")
ds.write(
root / "dataset.json",
dict(
schema_version="missioncore.semantic-collection/v1",
shards={"part-000": result},
files={},
training_eligible=False,
),
)
verified = ds.verify(root)
moved = tmp_path / "renamed"
root.rename(moved)
assert ds.verify(moved) == verified
(moved / "part-000/labels.json").write_text("{}")
with pytest.raises(ValueError):
ds.verify(moved)
def test_batched_crops_preserve_float_sampling_and_source_order(monkeypatch):
import ast
import types
import numpy as np
source = Path(__file__).parents[1] / "simulation/urban-mapping/mapping.py"
tree = ast.parse(source.read_text())
fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "prepare_crops")
rng = np.random.default_rng(42)
data = np.zeros(1001, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("identity", "i4")])
for k in ["x", "y", "z"]:
data[k] = rng.uniform(-80, 80, len(data))
data["x"][:4] = [-21, 21, -21.00001, 21.00001]
data["y"][:4] = 0
data["identity"] = np.arange(len(data))
class Ply:
@staticmethod
def read(*args, **kwargs):
return {"vertex": types.SimpleNamespace(data=data)}
monkeypatch.setitem(sys.modules, "plyfile", types.SimpleNamespace(PlyData=Ply))
ns = dict(np=np, Path=Path)
exec(compile(ast.Module(body=[fn], type_ignores=[]), str(source), "exec"), ns)
transform = np.eye(4)
jobs = [
dict(
source=dict(ply="synthetic.ply", source_to_world=transform.tolist()),
bounds_xy=[[x - 6, -6], [x + 6, 6]],
halo_m=15,
)
for x in [0, 10, 20, 30]
]
got = list(ns["prepare_crops"](jobs))
xyz = np.column_stack([data[n] for n in ["x", "y", "z"]])
world = xyz @ transform[:3, :3].T + transform[:3, 3]
for job, rows in zip(jobs, got, strict=True):
bounds = np.asarray(job["bounds_xy"], dtype=float)
mask = ((world[:, :2] >= bounds[0] - 15) & (world[:, :2] <= bounds[1] + 15)).all(axis=1)
assert rows.tobytes() == data[mask].tobytes()
with pytest.raises(ValueError):
list(ns["prepare_crops"](jobs + jobs))
def test_worker_resumes_verified_parts_without_rebuilding_them(tmp_path, monkeypatch, snapshot):
import json
import types
from test_semantic_delivery import fixture
monkeypatch.setitem(sys.modules, "final_snapshot", snapshot)
monkeypatch.setitem(sys.modules, "core_client", types.SimpleNamespace(CoreClient=object))
monkeypatch.setitem(
sys.modules,
"infrastructure_gaussian_sources",
types.SimpleNamespace(resolve_gaussian_entry=lambda *args: None),
)
path = Path(__file__).parents[1] / "simulation/semantic-learning/worker.py"
spec = importlib.util.spec_from_file_location("snapshot_worker", path)
worker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(worker)
release = tmp_path / "release"
release.mkdir()
ds.write(release / "release.json", {"id": "original-builder"})
(release / "dataset_store.py").write_text("# portable verifier fixture\n")
monkeypatch.setattr(worker, "HERE", release)
_, _, _, _, env = fixture(tmp_path / "fixture")
store = ds.Store(tmp_path / "worker", reserve=0)
key = store.accept(env)
assert store.next() == key
monkeypatch.setattr(
worker,
"plan",
lambda _: dict(windows=[{}] * 8, classes=["road_boundary"], world_sha256="b" * 64),
)
monkeypatch.setattr(worker, "source_for", lambda *args: (tmp_path, {}))
monkeypatch.setattr(
worker.subprocess, "run", lambda *args, **kwargs: types.SimpleNamespace(returncode=1)
)
monkeypatch.setattr(
worker, "docker", lambda *args, **kwargs: types.SimpleNamespace(stdout=b"[]")
)
called = []
interrupt = True
def render(*args):
batch = ds.read(store.root / "work" / key / "batch.json")
called.append(batch["name"])
part = store.root / "work" / key / "dataset" / batch["name"]
if interrupt and batch["name"] == "part-001":
part.mkdir()
(part / "incomplete").write_text("interrupted")
raise InterruptedError("priority job")
draft(part)
monkeypatch.setattr(worker, "run_shard", render)
with pytest.raises(InterruptedError):
worker.build(key, store, tmp_path / "state")
part0 = store.root / "work" / key / "dataset/part-000"
preserved = {p.name: p.read_bytes() for p in part0.iterdir()}
# A different builder must not silently mix with the completed part.
ds.write(release / "release.json", {"id": "different-builder"})
with pytest.raises(ValueError, match="original builder"):
worker.build(key, store, tmp_path / "state")
assert called == ["part-000", "part-001"]
ds.write(release / "release.json", {"id": "original-builder"})
interrupt = False
result = worker.build(key, store, tmp_path / "state")
assert called == ["part-000", "part-001", "part-001"]
published = store.root / "datasets" / key
assert {p.name: p.read_bytes() for p in (published / "part-000").iterdir()} == preserved
assert not (published / "part-001/incomplete").exists()
assert result["sample_count"] == 2 and ds.verify(published)["sample_count"] == 2
assert not (store.root / "work" / key).exists()
assert (
json.loads(store.db.execute("SELECT receipt FROM jobs").fetchone()[0])["state"]
== "draft-ready"
)