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.
This commit is contained in:
@@ -0,0 +1,478 @@
|
||||
"""Independent admission tests for vector editor topology, history and Worker replay."""
|
||||
|
||||
import ast
|
||||
import copy
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.simulation.ai_polygon import semantic_objects, semantic_vectors
|
||||
from k1link.simulation.ai_polygon.semantic_edits import apply_operations, paths
|
||||
|
||||
|
||||
def document():
|
||||
return {
|
||||
"schema_version": "missioncore.urban-map/v3",
|
||||
"source": {"world_sha256": "a" * 64},
|
||||
"features": [
|
||||
{
|
||||
"id": "road",
|
||||
"properties": {
|
||||
"class": "road_boundary",
|
||||
"authority": "observation-only",
|
||||
"route_permission": "unassigned",
|
||||
},
|
||||
"geometry": {
|
||||
"type": "Polygon",
|
||||
"coordinates": [
|
||||
[
|
||||
[0, 0, 2],
|
||||
[2, 0, 2],
|
||||
[4, 0, 2],
|
||||
[4, 4, 2],
|
||||
[2, 4, 2],
|
||||
[0, 4, 2],
|
||||
[0, 0, 2],
|
||||
]
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_group_delete_reconnects_closed_ring_and_is_atomic():
|
||||
base = document()
|
||||
before = copy.deepcopy(base)
|
||||
op = {
|
||||
"kind": "delete_vertices",
|
||||
"vertices": [{"feature_id": "road", "path": 0, "index": i} for i in (1, 2)],
|
||||
}
|
||||
result = apply_operations(base, [op])
|
||||
ring = paths(result["features"][0])[0]
|
||||
assert ring == [[0, 0, 2], [4, 4, 2], [2, 4, 2], [0, 4, 2], [0, 0, 2]]
|
||||
assert base == before
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base,
|
||||
[
|
||||
{
|
||||
"kind": "delete_vertices",
|
||||
"vertices": [
|
||||
{"feature_id": "road", "path": 0, "index": i} for i in (0, 1, 2, 3, 4)
|
||||
],
|
||||
}
|
||||
],
|
||||
)
|
||||
assert base == before
|
||||
|
||||
|
||||
def test_curve_and_vertical_axis_keep_provenance_and_validate_shape():
|
||||
base = document()
|
||||
op = dict(
|
||||
kind="curve", feature_id="road", path=0, index=1, incoming=[-0.6, -0.2], outgoing=[0.6, 0.2]
|
||||
)
|
||||
c = apply_operations(base, [op])
|
||||
assert c == apply_operations(copy.deepcopy(base), [op], verified_history=True)
|
||||
assert len(semantic_vectors.knots(c["features"][0], 0)) == 6
|
||||
moved = apply_operations(
|
||||
c,
|
||||
[
|
||||
dict(
|
||||
kind="translate",
|
||||
feature_id="road",
|
||||
vertices=[dict(feature_id="road", path=0, index=1)],
|
||||
axis="z",
|
||||
delta=[0, 0, 0.2],
|
||||
)
|
||||
],
|
||||
)
|
||||
assert semantic_vectors.knots(moved["features"][0], 0)[1]["point"] == [2, 0, 2.2]
|
||||
assert moved["features"][0]["properties"]["height_source"] == "human-axis-edit-unverified"
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
c, [dict(kind="move", feature_id="road", path=0, index=1, position=[2, 0, 3])]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
c,
|
||||
[
|
||||
dict(
|
||||
kind="curve",
|
||||
feature_id="road",
|
||||
path=0,
|
||||
index=1,
|
||||
incoming=[float("nan"), 0],
|
||||
outgoing=[0, 0],
|
||||
)
|
||||
],
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base, [dict(kind="move", feature_id="road", path=0, index=0, position=[5, 2, 2])]
|
||||
)
|
||||
|
||||
|
||||
def test_pedestrian_region_holes_are_still_checked():
|
||||
base = document()
|
||||
base["features"][0]["properties"]["class"] = "pedestrian_area"
|
||||
outer = paths(base["features"][0])[0]
|
||||
op = dict(
|
||||
kind="region",
|
||||
feature_id="road",
|
||||
token="abcdefghijklmnop",
|
||||
mode="union",
|
||||
brush=[[1, 1, 2], [3, 1, 2], [3, 3, 2], [1, 3, 2], [1, 1, 2]],
|
||||
polygons=[[outer]],
|
||||
)
|
||||
result = apply_operations(base, [op])
|
||||
assert result["features"][0]["properties"]["review_status"] == "unreviewed"
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base, [{**op, "polygons": [[outer, [[5, 5, 2], [6, 5, 2], [6, 6, 2], [5, 5, 2]]]]}]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base, [{**op, "polygons": [[[[0, 0, 2], [4, 4, 2], [0, 4, 2], [4, 0, 2], [0, 0, 2]]]]}]
|
||||
)
|
||||
|
||||
|
||||
def test_worker_replays_vector_history_exactly(monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [
|
||||
n
|
||||
for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
first = dict(
|
||||
kind="curve", feature_id="road", path=0, index=1, incoming=[-0.6, -0.2], outgoing=[0.6, 0.2]
|
||||
)
|
||||
second = dict(
|
||||
kind="translate",
|
||||
feature_id="road",
|
||||
vertices=[dict(feature_id="road", path=0, index=1)],
|
||||
axis="xz",
|
||||
delta=[0.1, 0, 0.2],
|
||||
)
|
||||
before, replayed, affected = scope["contexts"](
|
||||
dict(model=document(), revisions=[dict(operations=[first]), dict(operations=[second])])
|
||||
)
|
||||
expected = apply_operations(document(), [first, second])
|
||||
assert [f["geometry"] for f in replayed] == [f["geometry"] for f in expected["features"]]
|
||||
assert len(affected) == 1 and before[0]["geometry"] != replayed[0]["geometry"]
|
||||
|
||||
|
||||
def duplicate(index=1, delta=None, axis="x"):
|
||||
return dict(
|
||||
kind="duplicate_vertex",
|
||||
feature_id="road",
|
||||
path=0,
|
||||
index=index,
|
||||
delta=delta if delta is not None else [0.5, 0, 0],
|
||||
axis=axis,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"index,delta,slot", [(0, [-1, 0, 0], 0), (1, [1, 0, 0], 2), (2, [1, 0, 0], 3)]
|
||||
)
|
||||
def test_duplicate_extends_ends_and_inserts_interior_without_moving_source(index, delta, slot):
|
||||
base = document()
|
||||
base["features"][0]["geometry"] = dict(
|
||||
type="LineString", coordinates=[[0, 0, 2], [2, 0, 2], [4, 0, 2]]
|
||||
)
|
||||
original = copy.deepcopy(base)
|
||||
result = apply_operations(base, [duplicate(index, delta)])
|
||||
nodes = semantic_vectors.knots(result["features"][0], 0)
|
||||
assert nodes[slot]["point"] == [
|
||||
original["features"][0]["geometry"]["coordinates"][index][k] + delta[k] for k in range(3)
|
||||
]
|
||||
assert [n["point"] for i, n in enumerate(nodes) if i != slot] == original["features"][0][
|
||||
"geometry"
|
||||
]["coordinates"]
|
||||
assert base == original
|
||||
assert result == apply_operations(base, [duplicate(index, delta)], verified_history=True)
|
||||
assert apply_operations(base, [duplicate(index, [0, 0, 0])]) == base
|
||||
|
||||
|
||||
def test_duplicate_closed_ring_curves_and_invalid_geometry_remain_checked():
|
||||
base = apply_operations(
|
||||
document(),
|
||||
[
|
||||
dict(
|
||||
kind="curve",
|
||||
feature_id="road",
|
||||
path=0,
|
||||
index=1,
|
||||
incoming=[-0.2, 0],
|
||||
outgoing=[0.2, 0],
|
||||
)
|
||||
],
|
||||
)
|
||||
old = semantic_vectors.knots(base["features"][0], 0)
|
||||
result = apply_operations(base, [duplicate()])
|
||||
new = semantic_vectors.knots(result["features"][0], 0)
|
||||
assert new[1] == old[1] and new[2]["incoming"] == old[1]["incoming"]
|
||||
ring = paths(result["features"][0])[0]
|
||||
assert ring[0] == ring[-1]
|
||||
for op in [
|
||||
duplicate(delta=[2, 0, 0]),
|
||||
duplicate(delta=[0, 0, 1], axis="z"),
|
||||
duplicate(delta=[0, 1, 0]),
|
||||
duplicate(delta=[float("nan"), 0, 0]),
|
||||
duplicate(index=-1),
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(document(), [op])
|
||||
|
||||
|
||||
def test_strip_vertices_stretch_but_legacy_rigid_history_and_symbols_keep_their_meaning():
|
||||
base = document()
|
||||
f = base["features"][0]
|
||||
f["properties"].update({"class": "road_marking", "subtype": "linear_marking"})
|
||||
f["geometry"]["coordinates"] = [[[0, 0, 2], [4, 0, 2], [4, 0.2, 2], [0, 0.2, 2], [0, 0, 2]]]
|
||||
op = dict(
|
||||
kind="translate_vertices",
|
||||
feature_id="road",
|
||||
vertices=[dict(feature_id="road", path=0, index=i) for i in (1, 2)],
|
||||
axis="x",
|
||||
delta=[2, 0, 0],
|
||||
)
|
||||
result = apply_operations(base, [op])
|
||||
assert paths(result["features"][0])[0] == [
|
||||
[0, 0, 2],
|
||||
[6, 0, 2],
|
||||
[6, 0.2, 2],
|
||||
[0, 0.2, 2],
|
||||
[0, 0, 2],
|
||||
]
|
||||
legacy = apply_operations(base, [{**op, "kind": "translate"}], verified_history=True)
|
||||
assert paths(legacy["features"][0])[0][0] == [2, 0, 2]
|
||||
for subtype in (None, "letter_A", "straight_arrow", "bicycle", "crosswalk"):
|
||||
symbol = copy.deepcopy(base)
|
||||
symbol["features"][0]["properties"]["subtype"] = subtype
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(symbol, [op])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(symbol, [duplicate()])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [{**op, "delta": [-4, 0, 0]}])
|
||||
|
||||
|
||||
def test_duplicate_save_reload_and_worker_replay(monkeypatch, tmp_path):
|
||||
from test_semantic_edits import make_setup
|
||||
|
||||
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits
|
||||
|
||||
world, model, maps, store, sha = make_setup(tmp_path)
|
||||
op = {**duplicate(2, [1, 0, 0]), "feature_id": "curb-1"}
|
||||
body = dict(
|
||||
expected_revision=None, model_sha256=sha, request_id="shift-duplicate-0001", operations=[op]
|
||||
)
|
||||
saved = store.save(world, body)
|
||||
assert SemanticEdits(store.root.parents[1], maps).get(world) == saved
|
||||
assert store.save(world, body) == saved and maps.get(world) == model
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [
|
||||
n
|
||||
for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
_, replayed, affected = scope["contexts"](dict(model=model, revisions=[dict(operations=[op])]))
|
||||
assert replayed[0]["geometry"] == saved["edited"]["features"][0]["geometry"]
|
||||
assert affected == [("curb-1", [4.5, 1.0, 2.0])]
|
||||
with pytest.raises(ValueError, match="window"):
|
||||
scope["contexts"](
|
||||
dict(model=model, revisions=[dict(operations=[{**op, "delta": [9, 0, 0]}])])
|
||||
)
|
||||
|
||||
|
||||
def test_linear_placement_edit_copy_and_worker_replay(monkeypatch):
|
||||
from test_semantic_objects import document, place
|
||||
|
||||
base = document()
|
||||
placement = place("linear_marking")
|
||||
fid = placement["feature_id"]
|
||||
vertices = [dict(feature_id=fid, path=0, index=i) for i in (1, 2)]
|
||||
stretch = dict(
|
||||
kind="translate_vertices", feature_id=fid, vertices=vertices, axis="x", delta=[2, 0, 0]
|
||||
)
|
||||
copy_op = dict(
|
||||
kind="duplicate_marking",
|
||||
feature_id=fid,
|
||||
new_feature_id="user-copy-1234567890123456",
|
||||
axis="y",
|
||||
delta=[0, 2, 0],
|
||||
)
|
||||
ops = [placement, stretch, copy_op]
|
||||
result = apply_operations(base, ops)
|
||||
assert len(result["features"]) == 2
|
||||
assert result["features"][0]["properties"]["subtype"] == "linear_marking"
|
||||
assert "semantic_element_id" not in result["features"][1]["properties"]
|
||||
assert result["features"][1]["properties"]["height_source"] == "human-copy-unverified"
|
||||
assert base["features"] == []
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(result, [copy_op])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
result, [{**copy_op, "new_feature_id": "user-other-1234567890", "delta": [1, 2, 0]}]
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [
|
||||
n
|
||||
for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
before, replayed, affected = scope["contexts"](
|
||||
dict(model=base, revisions=[dict(operations=ops)])
|
||||
)
|
||||
assert before == [] and replayed == result["features"]
|
||||
assert len(affected) == 2 and affected[-1][0] == copy_op["new_feature_id"]
|
||||
# New editable curve metadata must move with the whole strip, then remain editable.
|
||||
curved = apply_operations(
|
||||
result, [dict(kind="curve", **vertices[0], incoming=[-0.2, 0], outgoing=[0, 0.01])]
|
||||
)
|
||||
original = copy.deepcopy(curved)
|
||||
moved = apply_operations(curved, [{**copy_op, "new_feature_id": "user-curved-1234567890"}])
|
||||
assert curved == original
|
||||
for a, b in zip(
|
||||
semantic_vectors.knots(curved["features"][0], 0),
|
||||
semantic_vectors.knots(moved["features"][-1], 0),
|
||||
strict=True,
|
||||
):
|
||||
assert b["point"] == [a["point"][0], a["point"][1] + 2, a["point"][2]]
|
||||
assert b["incoming"] == a["incoming"]
|
||||
|
||||
|
||||
def test_copy_rigid_group_is_new_group_and_does_not_modify_source():
|
||||
from test_semantic_objects import document, place
|
||||
|
||||
base = apply_operations(document(), [place()])
|
||||
original = copy.deepcopy(base)
|
||||
op = dict(
|
||||
kind="duplicate_marking",
|
||||
feature_id=base["features"][2]["id"],
|
||||
new_feature_id="user-zebra-1234567890123",
|
||||
delta=[0, 2, 0],
|
||||
axis="y",
|
||||
)
|
||||
result = apply_operations(base, [op])
|
||||
assert base == original and result["features"][:6] == base["features"]
|
||||
assert len(result["features"]) == 12
|
||||
assert {f["properties"]["semantic_element_id"] for f in result["features"][6:]} == {
|
||||
op["new_feature_id"]
|
||||
}
|
||||
for a, b in zip(base["features"], result["features"][6:], strict=True):
|
||||
for r, s in zip(semantic_objects.paths(a), semantic_objects.paths(b), strict=True):
|
||||
assert s == [[p[0], p[1] + 2, p[2]] for p in r]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case",
|
||||
json.loads((Path(__file__).parent / "fixtures/semantic_duplicate_direction.json").read_text()),
|
||||
ids=lambda c: c["name"],
|
||||
)
|
||||
def test_directional_duplicate_exact_order_and_legacy_compatibility(case):
|
||||
base = document()
|
||||
points = case["points"]
|
||||
base["features"][0]["geometry"] = (
|
||||
dict(type="Polygon", coordinates=[points + [points[0]]])
|
||||
if case["closed"] else dict(type="LineString", coordinates=points)
|
||||
)
|
||||
original = copy.deepcopy(base)
|
||||
op = duplicate(case["index"], case["delta"], "yz" if case["delta"][2] else "xy")
|
||||
op["side"] = case["side"]
|
||||
result = apply_operations(base, [op])
|
||||
slot = case["index"] + int(case["side"] == "after")
|
||||
expected = copy.deepcopy(points)
|
||||
expected.insert(slot, [v + case["delta"][k] for k, v in enumerate(points[case["index"]])])
|
||||
assert [n["point"] for n in semantic_vectors.knots(result["features"][0], 0)] == expected
|
||||
assert base == original
|
||||
assert result == apply_operations(copy.deepcopy(base), [op], verified_history=True)
|
||||
if case["closed"]:
|
||||
ring = paths(result["features"][0])[0]
|
||||
assert ring[0] == ring[-1]
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [{**op, "side": "guess"}])
|
||||
|
||||
|
||||
def test_directional_insert_still_rejects_backtracking():
|
||||
base = document()
|
||||
base["features"][0]["geometry"] = dict(
|
||||
type="LineString", coordinates=[[0, 0, 2], [4, 0, 2], [8, 0, 2]]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [{**duplicate(1, [-1, 0, 0]), "side": "after"}])
|
||||
assert apply_operations(base, [{**duplicate(1, [-1, 0, 0]), "side": "before"}])
|
||||
|
||||
|
||||
def test_worker_replays_explicit_side_and_legacy_chain(monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [n for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
base = document()
|
||||
base["features"][0]["geometry"] = dict(
|
||||
type="LineString", coordinates=[[0, 0, 2], [4, 0, 2], [8, 0, 2]]
|
||||
)
|
||||
legacy = duplicate(2, [1, 0, 0])
|
||||
new = {**duplicate(1, [-1, 0, 0]), "side": "before"}
|
||||
before, replayed, _ = scope["contexts"](
|
||||
dict(model=base, revisions=[dict(operations=[legacy]), dict(operations=[new])])
|
||||
)
|
||||
expected = apply_operations(base, [legacy, new])
|
||||
assert [f["geometry"] for f in replayed] == [f["geometry"] for f in expected["features"]]
|
||||
assert before[0]["geometry"]["coordinates"] == [[0, 0, 2], [4, 0, 2], [8, 0, 2], [9, 0, 2]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["translate_vertices", "delete_vertices"])
|
||||
def test_group_validation_does_not_copy_the_spline_for_every_selected_vertex(monkeypatch, kind):
|
||||
base = document()
|
||||
feature = base["features"][0]
|
||||
feature["geometry"] = dict(type="LineString", coordinates=[[i, 0, 2] for i in range(130)])
|
||||
feature = semantic_vectors.with_knots(feature, 0, semantic_vectors.knots(feature, 0))
|
||||
base["features"][0] = feature
|
||||
original = copy.deepcopy(base)
|
||||
references = [dict(feature_id="road", path=0, index=i) for i in range(1, 129)]
|
||||
op = dict(kind=kind, vertices=references)
|
||||
if kind == "translate_vertices":
|
||||
op.update(feature_id="road", delta=[0, 1, 0], axis="y")
|
||||
copied_points = 0
|
||||
real = semantic_vectors.knots
|
||||
|
||||
def count(*args):
|
||||
nonlocal copied_points
|
||||
nodes = real(*args)
|
||||
copied_points += len(nodes)
|
||||
return nodes
|
||||
|
||||
monkeypatch.setattr(semantic_vectors, "knots", count)
|
||||
result = apply_operations(base, [op])
|
||||
# Linear allocation budget: group validation must not be O(vertices * spline).
|
||||
assert copied_points <= 3 * 130
|
||||
expected = [[0, 0, 2], [129, 0, 2]] if kind == "delete_vertices" else (
|
||||
[[0, 0, 2]] + [[i, 1, 2] for i in range(1, 129)] + [[129, 0, 2]]
|
||||
)
|
||||
assert result["features"][0]["geometry"]["coordinates"] == expected
|
||||
invalid = copy.deepcopy(op)
|
||||
invalid["vertices"].append(dict(feature_id="road", path=0, index=130))
|
||||
with pytest.raises(ValueError, match="Точка не найдена"):
|
||||
apply_operations(base, [invalid])
|
||||
assert base == original
|
||||
Reference in New Issue
Block a user