Files
NODEDC_MISSION_CORE/tests/test_urban_maps.py
T

216 lines
7.9 KiB
Python

"""Infrastructure observations cannot silently migrate between scene revisions."""
import copy
import json
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from test_ai_polygon import make_world
from k1link.simulation.ai_polygon.runs import RunStore
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore, validate_map
from k1link.simulation.ai_polygon.worlds import WorldStore
from k1link.web.ai_polygon_api import build_ai_polygon_router
def document(world):
return {
"schema_version": "missioncore.urban-map/v1",
"type": "FeatureCollection",
"coordinate_system": {
"frame": "scene-local",
"units": "metres",
"up": "Z",
"georeferenced": False,
},
"source": {
"world_sha256": world["sha256"],
"collider_sha256": world.get("collider_sha256"),
},
"coverage": {"cell_m": 0.1, "accepted_cells": 100},
"features": [
{
"type": "Feature",
"properties": {
"class": "sidewalk",
"authority": "observation-only",
"route_permission": "unassigned",
},
"geometry": {
"type": "Polygon",
"coordinates": [[[0, 0, 2], [1, 0, 2], [1, 1, 2], [0, 0, 2]]],
},
}
],
}
def test_revision_binding_and_integrity(tmp_path):
world = {"sha256": "a" * 64, "collider_sha256": "b" * 64}
data = document(world)
store = UrbanMapStore(tmp_path)
receipt = store.save(world, data)
assert store.get(world) == data
with pytest.raises(ValueError):
validate_map(data, {**world, "collider_sha256": "c" * 64})
with pytest.raises(FileNotFoundError):
store.get({**world, "sha256": "c" * 64})
path = store.directory(world) / (receipt["sha256"] + ".json")
data["features"] = []
path.write_text(json.dumps(data))
with pytest.raises(ValueError, match="changed"):
store.get(world)
@pytest.mark.parametrize(
"bad",
[
None,
{},
{"properties": None},
{"type": "Feature", "properties": {"class": []}},
{
"type": "Feature",
"properties": {
"class": "sidewalk",
"authority": "observation-only",
"route_permission": "unassigned",
},
"geometry": {"type": "Polygon", "coordinates": [None]},
},
],
)
def test_malformed_features_rejected(bad):
world = {"sha256": "a" * 64}
data = document(world)
data["features"] = [bad]
with pytest.raises(ValueError):
validate_map(data, world)
def test_permission_and_geometry_rejected():
world = {"sha256": "a" * 64}
data = document(world)
for mutate in [
lambda d: d["features"][0]["properties"].update(route_permission="allowed"),
lambda d: d["features"][0]["geometry"].update(
coordinates=[[[0, 0, 0], [1, 0, 0], [1, 1, 0]]]
),
lambda d: d["features"][0]["geometry"].update(coordinates=[[[0, 0, float("nan")]]] * 4),
]:
value = copy.deepcopy(data)
mutate(value)
with pytest.raises(ValueError):
validate_map(value, world)
def test_worker_api_auth_and_publish(tmp_path):
worlds = WorldStore(tmp_path)
world = make_world(worlds)
runs = RunStore(worlds)
app = FastAPI()
app.include_router(build_ai_polygon_router(tmp_path))
client = TestClient(app)
suffix = f"/worlds/{world['world_id']}/urban-map"
worker = "/api/v1/ai-polygon/worker" + suffix
read = "/api/v1/ai-polygon" + suffix
assert client.get(read).status_code == 404
assert client.post(worker, json=document(world)).status_code == 401
headers = {"Authorization": f"Bearer {runs.token}"}
assert client.post(worker, json=[], headers=headers).status_code == 400
assert client.post(worker, json=document(world), headers=headers).status_code == 200
assert client.get(read).json() == document(world)
def test_vector_lines_roundtrip_and_admission(tmp_path):
world = {"sha256": "a" * 64, "collider_sha256": "b" * 64}
data = document(world)
data["schema_version"] = "missioncore.urban-map/v2"
f = data["features"][0]
f["id"] = "curb-1"
f["properties"].update(confidence=0.8, review_status="unreviewed", **{"class": "curb"})
f["geometry"] = {"type": "LineString", "coordinates": [[1, 2, 3], [2, 3, 4]]}
store = UrbanMapStore(tmp_path)
store.save(world, data)
assert store.get(world) == data
for change in [
lambda d: d["features"].append(copy.deepcopy(d["features"][0])),
lambda d: d["features"][0]["properties"].update(confidence=float("nan")),
lambda d: d["features"][0]["geometry"].update(coordinates=[[1, 2, 3]]),
lambda d: d["features"][0]["geometry"].update(
coordinates=[[1, 2, 3], [1, 2, float("inf")]]
),
]:
bad = copy.deepcopy(data)
change(bad)
with pytest.raises(ValueError):
validate_map(bad, world)
def test_map_budget_is_global_and_preserves_existing_versions(tmp_path, monkeypatch):
from k1link import cache_budget
world = {"sha256": "a" * 64}
other = {"sha256": "b" * 64}
store = UrbanMapStore(tmp_path)
first = store.save(world, document(world))
before = {p.relative_to(store.root).as_posix(): p.read_bytes()
for p in store.root.rglob('*.json')}
monkeypatch.setitem(cache_budget.LIMITS, "urban-maps", 1)
assert store.save(world, document(world)) == first # Exact retry at capacity.
assert store.get(world) == document(world)
with pytest.raises(cache_budget.CacheCapacityError):
store.save(other, document(other))
after = {p.relative_to(store.root).as_posix(): p.read_bytes()
for p in store.root.rglob('*.json')}
assert after == before
def test_pair_budget_checks_both_maps_before_first_write(tmp_path, monkeypatch):
from k1link import cache_budget
world = {"sha256": "a" * 64}
store = UrbanMapStore(tmp_path)
store.save(world, document(world))
raw, auto = document(world), document(world)
raw['semantic_stage'], auto['semantic_stage'] = 'raw', 'algorithmic'
before = {p.relative_to(store.root).as_posix(): p.read_bytes()
for p in store.root.rglob('*.json')}
# There is room for raw alone, not the complete atomic publication.
used = cache_budget.usage(store.root)[0]
monkeypatch.setitem(cache_budget.LIMITS, "urban-maps", used + len(json.dumps(raw).encode()) + 1)
with pytest.raises(cache_budget.CacheCapacityError):
store.publish_pair(world, raw, auto)
assert {p.relative_to(store.root).as_posix(): p.read_bytes()
for p in store.root.rglob('*.json')} == before
def test_concurrent_identical_publications_recheck_reserved_bytes(tmp_path, monkeypatch):
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from threading import Barrier
from k1link import cache_budget
from k1link.simulation.ai_polygon import urban_maps
world = {"sha256": "a" * 64}
store = UrbanMapStore(tmp_path)
data, sha, size = store._prepare(world, document(world))
monkeypatch.setitem(cache_budget.LIMITS, "urban-maps", size + len(json.dumps({'sha256': sha})))
barrier = Barrier(2)
publish = urban_maps.cache_publication
@contextmanager
def together(*args, **kwargs):
barrier.wait(timeout=2) # Both callers observed missing files before locking.
with publish(*args, **kwargs):
yield
monkeypatch.setattr(urban_maps, "cache_publication", together)
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda _: store.save(world, data), range(2)))
assert results[0] == results[1]
assert store.get(world) == data
assert len(list(store.root.rglob('*.json'))) == 2