"""Human revisions never mutate inference; test failures before/after durable commit.""" import copy import json from concurrent.futures import ThreadPoolExecutor import pytest from test_urban_maps import document from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, apply_operations from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore def make_setup(tmp_path): world = {"sha256": "a" * 64, "collider_sha256": "b" * 64} model = document(world) model["schema_version"] = "missioncore.urban-map/v3" model["source"].update(gaussian_only=True, artifact_sha256="c" * 64) model["features"] = [ { "type": "Feature", "id": "curb-1", "properties": { "class": "curb", "authority": "observation-only", "route_permission": "unassigned", "confidence": 0.9, "review_status": "accepted", }, "geometry": {"type": "LineString", "coordinates": [[0, 0, 2], [2, 0, 2], [4, 1, 2]]}, }, { "type": "Feature", "id": "facade-1", "properties": { "class": "building_facade", "authority": "observation-only", "route_permission": "unassigned", "confidence": 0.8, "review_status": "accepted", }, "geometry": {"type": "LineString", "coordinates": [[0, 5, 2], [4, 5, 2]]}, }, ] maps = UrbanMapStore(tmp_path) receipt = maps.save(world, model) store = SemanticEdits(tmp_path, maps) return world, model, maps, store, receipt["sha256"] @pytest.fixture def setup(tmp_path): return make_setup(tmp_path) def change(sha, *, request="first-request-0001", parent=None): return { "expected_revision": parent, "model_sha256": sha, "request_id": request, "operations": [ {"kind": "move", "feature_id": "curb-1", "path": 0, "index": 1, "position": [2, 0.5, 2]} ], } def test_save_restart_repeat_and_source_immutability(setup): world, model, maps, store, sha = setup saved = store.save(world, change(sha)) assert maps.get(world) == model assert saved["model"] == model assert saved["edited"]["features"][1] == model["features"][1] assert saved["edited"]["schema_version"] == "missioncore.urban-edit/v1" assert "gaussian_only" not in saved["edited"]["source"] assert not saved["learning"]["dataset_ready"] restarted = SemanticEdits(store.root.parents[1], maps) assert restarted.get(world) == saved assert restarted.save(world, change(sha)) == saved assert len(json.loads(store._path(world).read_text())["revisions"]) == 1 altered = change(sha) altered["operations"][0]["position"][0] = 3 with pytest.raises(RuntimeError, match="идентификатор|Идентификатор"): store.save(world, altered) def test_frozen_model_survives_new_analysis_and_conflict(setup): world, model, maps, store, sha = setup first = store.save(world, change(sha)) newer = copy.deepcopy(model) newer["features"][0]["geometry"]["coordinates"][1] = [2, -0.5, 2] maps.save(world, newer) view = store.get(world) assert view["model"] == model assert view["latest_model_sha256"] != sha with pytest.raises(RuntimeError, match="другом окне"): store.save(world, change(sha, request="second-request-0002")) second = change(sha, request="second-request-0002", parent=first["revision"]) second["operations"] = [ {"kind": "insert", "feature_id": "curb-1", "path": 0, "index": 0, "t": 0.5} ] assert len(store.save(world, second)["history"]) == 2 assert maps.get(world) == newer def test_concurrent_save_has_one_winner(setup): world, _, _, store, sha = setup def save(i): try: return store.save(world, change(sha, request=f"concurrent-request-{i:04}")) except RuntimeError: return None with ThreadPoolExecutor(max_workers=2) as pool: results = list(pool.map(save, (1, 2))) assert sum(r is not None for r in results) == 1 assert len(store.get(world)["history"]) == 1 def test_no_approximation_insert_and_delete_roundtrip(setup): _, model, _, _, _ = setup inserted = apply_operations( model, [{"kind": "insert", "feature_id": "curb-1", "path": 0, "index": 0, "t": 0.25}] ) assert inserted["features"][0]["geometry"]["coordinates"] == [ [0, 0, 2], [0.5, 0, 2], [2, 0, 2], [4, 1, 2], ] restored = apply_operations( inserted, [{"kind": "delete", "feature_id": "curb-1", "path": 0, "index": 1}] ) assert restored["features"][0]["geometry"] == model["features"][0]["geometry"] def test_no_op_preserves_evidence_and_does_not_create_revision(setup): world, model, _, store, sha = setup body = change(sha) body["operations"][0]["position"] = [2, 0, 2] assert apply_operations(model, body["operations"]) == model with pytest.raises(ValueError, match="Нет изменений"): store.save(world, body) assert store.get(world)["revision"] is None @pytest.mark.parametrize("position", [[2, 0, 3], [0, 0, 2], [float("nan"), 0, 2], [True, 0, 2]]) def test_invalid_save_never_commits(setup, position): world, _, _, store, sha = setup body = change(sha) body["operations"][0]["position"] = position with pytest.raises(ValueError): store.save(world, body) assert store.get(world)["revision"] is None def test_polygon_closure_and_crossing_rejection(setup): _, model, _, _, _ = setup model["features"][0]["geometry"] = { "type": "Polygon", "coordinates": [[[0, 0, 2], [2, 0, 2], [2, 2, 2], [0, 2, 2], [0, 0, 2]]], } moved = apply_operations( model, [{"kind": "move", "feature_id": "curb-1", "path": 0, "index": 0, "position": [-0.5, 0, 2]}], ) ring = moved["features"][0]["geometry"]["coordinates"][0] assert ring[0] == ring[-1] == [-0.5, 0, 2] with pytest.raises(ValueError, match="самопересечение"): apply_operations( model, [ { "kind": "move", "feature_id": "curb-1", "path": 0, "index": 1, "position": [1, 3, 2], } ], ) def test_corrupt_history_refused_and_budget_preserves_state(setup, monkeypatch): world, _, _, store, sha = setup monkeypatch.setattr("k1link.simulation.ai_polygon.semantic_edits.MAX_STATE", 1) with pytest.raises(ValueError, match="Лимит"): store.save(world, change(sha)) assert not store._path(world).exists() monkeypatch.undo() store.save(world, change(sha)) state = json.loads(store._path(world).read_text()) state["revisions"][0]["operations"][0]["position"][0] = 9 store._path(world).write_text(json.dumps(state)) with pytest.raises(ValueError, match="целостность"): store.get(world) def test_directional_duplicate_persists_without_reinterpreting_prior_history(setup): world, model, maps, store, sha = setup first = store.save(world, change(sha)) request = change(sha, request="directional-copy-0002", parent=first["revision"]) request["operations"] = [{ "kind": "duplicate_vertex", "feature_id": "curb-1", "path": 0, "index": 1, "delta": [-0.5, 0, 0], "axis": "x", "side": "before", }] saved = store.save(world, request) assert saved["edited"]["features"][0]["geometry"]["coordinates"] == [ [0, 0, 2], [1.5, 0.5, 2], [2, 0.5, 2], [4, 1, 2], ] assert SemanticEdits(store.root.parents[1], maps).get(world) == saved assert store.export(world, first["revision"])["package"]["edited"] == first["edited"] assert maps.get(world) == model def test_save_returns_admitted_geometry_without_a_second_history_replay(setup, monkeypatch): from k1link.simulation.ai_polygon import semantic_edits world, _, maps, store, sha = setup first = store.save(world, change(sha)) request = change(sha, request="admitted-save-0002", parent=first["revision"]) request["origin"] = "agent-proposal" request["operations"] = [dict(kind="duplicate_vertex", feature_id="curb-1", path=0, index=2, delta=[1, 0, 0], axis="x", side="after")] real = semantic_edits.apply_operations admitted = [] replayed = [] def track(*args, **kwargs): result = real(*args, **kwargs) (replayed if kwargs.get("verified_history") else admitted).append(result) return result monkeypatch.setattr(semantic_edits, "apply_operations", track) saved = store.save(world, request) assert len(replayed) == len(first["history"]) assert len(admitted) == 1 and saved["edited"] is admitted[0] assert saved["edited"]["features"][0]["properties"]["annotation_origin"] == "agent-proposal" assert SemanticEdits(store.root.parents[1], maps).get(world) == saved assert store.save(world, request) == saved