Add vector infrastructure maps and persistent location experience
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.simulation.ai_polygon.spatial_experience import LocationExperience, read, save, validate
|
||||
|
||||
SOURCE = dict(world_sha256="a" * 64, collider_sha256="b" * 64, robot_sha256="c" * 64)
|
||||
POSE = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
|
||||
|
||||
|
||||
def feed(memory, t, xyz=(0.0, 0.0, 0.0), goal=(1.0, 0.0, 0.0), failure="footprint", bound=True):
|
||||
pose = [*xyz[:2], xyz[2] + 1, 0.0, 0.0, 0.0, 1.0]
|
||||
result = dict(
|
||||
status="blocked",
|
||||
speed_mps=0.0,
|
||||
yaw_rate_rps=0.0,
|
||||
diagnostic={"failure": failure},
|
||||
route_observation={
|
||||
"observation": dict(
|
||||
pose=pose, simulation_time_seconds=t, execution_inputs_sha256="exec"
|
||||
)
|
||||
}
|
||||
if bound
|
||||
else {},
|
||||
)
|
||||
memory.observe(
|
||||
list(xyz), list(goal), result, t, 100 + t, "airun-test", "packet-" + str(t), "exec", pose
|
||||
)
|
||||
|
||||
|
||||
def test_restart_revisit_and_directions(tmp_path):
|
||||
m = LocationExperience(SOURCE)
|
||||
feed(m, 0)
|
||||
feed(m, 0.6)
|
||||
feed(m, 0.7)
|
||||
assert len(m.attempts) == 1 and next(iter(m.attempts.values()))["count"] == 1
|
||||
path = tmp_path / "memory.json"
|
||||
save(path, m.document())
|
||||
n = LocationExperience(SOURCE, read(path, SOURCE))
|
||||
assert n.costs([0, 0], [[1, 0], [0, 1], [-1, 0]], 102) == pytest.approx([1.995333333, 0, 0])
|
||||
assert n.costs([2, 0], [[1, 0]], 102) == [0] # opposite approach
|
||||
assert n.costs([0, 0], [[1, 0]], 800) == [0] # evidence retained; temporary cost expires
|
||||
n.observe([0.5, 0, 0], None, {}, 2, 103, "r", "o", "exec", POSE)
|
||||
n.observe([1, 0, 0], None, {}, 3, 104, "r", "o", "exec", POSE)
|
||||
assert next(iter(n.attempts.values()))["status"] == "revisited-successfully"
|
||||
assert n.costs([0, 0], [[1, 0]], 105) == [0]
|
||||
with pytest.raises(ValueError):
|
||||
read(path, {**SOURCE, "collider_sha256": "d" * 64})
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure,bound", [("timeout", True), ("footprint", False), ("stale-range", True)]
|
||||
)
|
||||
def test_no_invented_obstacles(failure, bound):
|
||||
m = LocationExperience(SOURCE)
|
||||
feed(m, 0, failure=failure, bound=bound)
|
||||
feed(m, 10, failure=failure, bound=bound)
|
||||
assert not m.attempts
|
||||
|
||||
|
||||
def test_pose_teleport_does_not_connect_cells_or_mark_passed():
|
||||
m = LocationExperience(SOURCE)
|
||||
feed(m, 0)
|
||||
feed(m, 1)
|
||||
feed(m, 2, xyz=(20.0, 0.0, 0.0))
|
||||
assert len(m.visits) == 2 and next(iter(m.attempts.values()))["status"] == "unresolved"
|
||||
|
||||
|
||||
def test_invalid_summaries():
|
||||
m = LocationExperience(SOURCE)
|
||||
feed(m, 0)
|
||||
doc = m.document()
|
||||
for mutation in [
|
||||
lambda d: d["visits"][0].update(xyz=[0, 0, float("nan")]),
|
||||
lambda d: d.update(authority="motion"),
|
||||
lambda d: d["visits"][0].update(count=-1),
|
||||
lambda d: d["source"].update(world_sha256="../escape"),
|
||||
lambda d: d.update(source=None),
|
||||
]:
|
||||
bad = copy.deepcopy(doc)
|
||||
mutation(bad)
|
||||
with pytest.raises(ValueError):
|
||||
validate(bad)
|
||||
|
||||
|
||||
def test_api_auth_revision_and_reload(tmp_path):
|
||||
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.worlds import WorldStore
|
||||
from k1link.web.ai_polygon_api import build_ai_polygon_router
|
||||
|
||||
worlds = WorldStore(tmp_path)
|
||||
world = make_world(worlds)
|
||||
runs = RunStore(worlds)
|
||||
world["collider_sha256"] = "b" * 64
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
write_json(worlds.directory(world["world_id"]) / "world.json", world)
|
||||
source = {
|
||||
**SOURCE,
|
||||
"world_sha256": world["sha256"],
|
||||
"collider_sha256": world["collider_sha256"],
|
||||
}
|
||||
memory = LocationExperience(source)
|
||||
feed(memory, 0)
|
||||
feed(memory, 1)
|
||||
app = FastAPI()
|
||||
app.include_router(build_ai_polygon_router(tmp_path))
|
||||
client = TestClient(app)
|
||||
suffix = "/worlds/" + world["world_id"] + "/spatial-experience"
|
||||
write = "/api/v1/ai-polygon/worker" + suffix
|
||||
url = "/api/v1/ai-polygon" + suffix
|
||||
assert client.get(url).status_code == 404
|
||||
assert client.post(write, json=memory.document()).status_code == 401
|
||||
assert (
|
||||
client.post(
|
||||
write, json=memory.document(), headers={"Authorization": "Bearer " + runs.token}
|
||||
).status_code
|
||||
== 200
|
||||
)
|
||||
assert client.get(url).json() == memory.document()
|
||||
wrong = memory.document()
|
||||
wrong["source"] = {**source, "collider_sha256": "d" * 64}
|
||||
assert (
|
||||
client.post(
|
||||
write, json=wrong, headers={"Authorization": "Bearer " + runs.token}
|
||||
).status_code
|
||||
== 400
|
||||
)
|
||||
|
||||
|
||||
def test_surface_uncertainty_is_a_note_without_geometry_permission():
|
||||
m = LocationExperience(SOURCE)
|
||||
feed(m, 0, goal=(0.0, 0.0, 0.0), failure="no-permitted-goal")
|
||||
feed(m, 1, goal=(0.0, 0.0, 0.0), failure="no-permitted-goal")
|
||||
assert len(m.attempts) == 1
|
||||
assert m.costs([0, 0], [[1, 0], [0, 1]], 102) == [0, 0]
|
||||
|
||||
|
||||
def test_worker_adapter_survives_process_restart(tmp_path, monkeypatch):
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
|
||||
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
|
||||
adapter = importlib.import_module("experience_adapter").ExperienceAdapter
|
||||
run = dict(
|
||||
run_id="airun-evidence",
|
||||
world=dict(sha256="a" * 64, collider_sha256="b" * 64),
|
||||
_spatial_experience_root=str(tmp_path / "persistent"),
|
||||
)
|
||||
inputs = dict(
|
||||
sha256="exec", robot=dict(sha256="c" * 64, geometry=dict(body_contact_height_m=1))
|
||||
)
|
||||
camera = tmp_path / "run" / "camera"
|
||||
camera.mkdir(parents=True)
|
||||
a = adapter(run, inputs, camera)
|
||||
feed(a.memory, 0)
|
||||
feed(a.memory, 1)
|
||||
a.close()
|
||||
b = adapter(run, inputs, camera)
|
||||
assert b.memory.document() == a.memory.document()
|
||||
b.close()
|
||||
assert read(camera.parent / "spatial-experience.json") == a.memory.document()
|
||||
|
||||
|
||||
def test_final_worker_sync_includes_latest_flushed_summary(tmp_path, monkeypatch):
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
|
||||
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
|
||||
sync = importlib.import_module("realtime_worker").publish_experience
|
||||
m = LocationExperience(SOURCE)
|
||||
feed(m, 0)
|
||||
feed(m, 1)
|
||||
save(tmp_path / "spatial-experience.json", m.document())
|
||||
sent = []
|
||||
|
||||
class Client:
|
||||
def request(self, path, body):
|
||||
sent.append((path, body))
|
||||
|
||||
sync(Client(), tmp_path, "aiworld-test")
|
||||
assert sent == [("/worker/worlds/aiworld-test/spatial-experience", m.document())]
|
||||
@@ -0,0 +1,148 @@
|
||||
"""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)
|
||||
Reference in New Issue
Block a user