Preserve installed operator workspace before consolidation

Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 09:59:51 +03:00
parent 97614742bb
commit d0e5f90952
368 changed files with 129172 additions and 1856 deletions
+273
View File
@@ -0,0 +1,273 @@
"""Whole-body geometric admission, separate from the mission's point radius."""
import importlib
import math
from pathlib import Path
import numpy as np
import pytest
from k1link.simulation.ai_polygon.mission_policy import WaypointMission
from k1link.simulation.ai_polygon.robots import select_robot
@pytest.fixture
def monitor(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon/navigation"))
return importlib.import_module("footprint").Footprint(select_robot("dcd006-v020")["physics"])
def ground(xmax=2, ymax=2, slope=0):
return np.array(
[
[x, y, x * slope, 0]
for x in np.arange(-2, xmax + 0.001, 0.05)
for y in np.arange(-2, ymax + 0.001, 0.05)
]
)
def pose(x=0, y=0, yaw=0):
return [x, y, 0.37, 0, 0, math.sin(yaw / 2), math.cos(yaw / 2)]
def test_obstacle_absence_cannot_stand_in_for_observed_support(monitor):
empty = monitor.assess_pose([], pose(), 0.37)
assert empty["collision_free"] and not empty["support_known"] and not empty["admitted"]
full = monitor.assess_pose(ground(), pose(), 0.37)
assert full["admitted"] and full["support_samples"] == full["supported_samples"]
strip = ground()[np.abs(ground()[:, 1]) < 0.01]
assert not monitor.assess_pose(strip, pose(), 0.37)["support_known"]
def test_nearby_ground_cannot_extrapolate_support_over_a_ledge_or_hole(monitor):
platform = ground(ymax=0.5)
assert monitor.assess_pose(platform, pose(), 0.37)["admitted"]
# Nearest return is <15cm from the corner; it lies on only one side.
assert not monitor.assess_pose(platform, pose(y=0.15), 0.37)["admitted"]
p = ground()
hole = p[np.linalg.norm(p[:, :2] - [0.25, 0.1], axis=1) > 0.25]
assert not monitor.assess_pose(hole, pose(), 0.37)["admitted"]
def test_same_arrival_point_can_fit_one_heading_but_not_another(monitor):
lane = ground(ymax=0.5)
lane = lane[lane[:, 1] >= -0.5 - 1e-6]
assert monitor.assess_pose(lane, pose(), 0.37)["admitted"]
assert not monitor.assess_pose(lane, pose(yaw=math.pi / 2), 0.37)["admitted"]
obstacle = np.vstack((ground(), [[0.55, 0.42, 0.25, 0.25]]))
result = monitor.assess_pose(obstacle, pose(), 0.37)
assert result["support_known"] and not result["collision_free"] and not result["admitted"]
def test_supported_grade_uses_physical_slope_and_contact_height(monitor):
for degrees, expected in ((20, True), (28, False)):
a = math.radians(degrees)
inclined = [0, 0, 0.37 / math.cos(a), 0, -math.sin(a / 2), 0, math.cos(a / 2)]
assert (
monitor.assess_pose(ground(slope=math.tan(a)), inclined, 0.37)["admitted"] == expected
)
def test_arrival_requires_same_observation_and_does_not_expand_radius():
mission = WaypointMission([[0, 0]])
current = pose(x=0.399)
mission.update(current, 1, lambda *_: None)
assert mission.arrival_candidate(current) and mission.fault is None
for observed, seconds, index, admitted in (
(current, 0, 0, True),
(pose(x=0.3), 1, 0, True),
(current, 1, 1, True),
(current, 1, 0, False),
):
assert not mission.confirm_arrival(observed, seconds, index, admitted=admitted)
assert mission.confirm_arrival(current, 1, 0, admitted=True)
assert mission.fault == "goal-reached"
outside = WaypointMission([[0, 0]])
outside.update(pose(x=0.401), 1, lambda *_: None)
assert not outside.confirm_arrival(pose(x=0.401), 1, 0, admitted=True)
def test_rejected_body_receipts_do_not_reset_stall_or_advance_waypoints():
mission = WaypointMission([[0, 0], [3, 0]])
for t in range(34):
mission.update(pose(), t, lambda *_: None)
assert not mission.confirm_arrival(pose(), t, 0, admitted=False)
assert mission.index == 0 and mission.fault == "stuck"
@pytest.fixture
def arrival_adapter(monkeypatch):
from types import SimpleNamespace
from k1link.simulation.ai_polygon.run_inputs import sensor_rig
from k1link.simulation.ai_polygon.source_projection import PinholeSource
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
from navigation_client import ComposedInference
adapter = ComposedInference.__new__(ComposedInference)
robot = select_robot("dcd006-v020")
adapter.geometry = robot["physics"]
adapter.source = PinholeSource(sensor_rig(robot, 0.8))
adapter.mission = WaypointMission([[0, 0], [3, 0]])
adapter.inputs = {"sha256": "a" * 64}
adapter.max_speed = 0.2
adapter.environment = "park"
adapter.goal = None # A camera blind strip cannot bypass observed-body admission.
_, intent = adapter.mission.update(pose(), 1, lambda *_: None)
inputs = {
"source.lidar": ground()[:, :3],
"source.pose": pose(),
"source.simulation-time": 1,
"source.range-rays": {},
"source.camera.calibration": {
"origin": [0.38, 0, 0.8],
"rotation": np.eye(3).reshape(-1).tolist(),
"intrinsics": [533, 533, 400, 300],
"body_contact_height_m": 0.37,
},
"navigation.intent": intent,
"navigation.surface": np.ones((512, 512), dtype=bool),
"navigation.permissions": np.ones((512, 512), dtype=bool),
"detection.boxes": [],
}
replies, requests = [], []
def request(path, value):
assert path == "/plan"
requests.append(value)
return replies.pop(0)
adapter.navigation = SimpleNamespace(request=request)
return adapter, inputs, replies, requests
def arrival_reply(inputs):
return {
"status": "arrival-accepted",
"speed_mps": 0.2, # The mission transition must always produce a stop.
"yaw_rate_rps": 0.1,
"path": [],
"arrival": {
"admitted": True,
"observation": {
"pose": inputs["source.pose"].copy(),
"target_xy": [0, 0],
"simulation_time_seconds": inputs["source.simulation-time"],
"execution_inputs_sha256": "a" * 64,
},
},
}
def test_live_adapter_waits_for_body_receipt_then_stops_and_advances_once(arrival_adapter):
adapter, inputs, replies, requests = arrival_adapter
for status in ("waiting-for-plan", "blocked"):
replies.append({"status": status, "speed_mps": 0, "yaw_rate_rps": 0, "path": []})
assert adapter.navigate(inputs)["motion.command"]["speed_mps"] == 0
assert adapter.mission.index == 0
replies.append(arrival_reply(inputs))
command = adapter.navigate(inputs)["motion.command"]
assert command["speed_mps"] == command["yaw_rate_rps"] == 0
assert adapter.mission.index == 1 and adapter.mission.fault is None
assert all(r["arrival_target"] == [0, 0] for r in requests)
assert adapter.navigation_evidence["mission"]["waypoint"] == 1
@pytest.mark.parametrize("invalid", ["missing", "denied", "pose", "clock", "target", "inputs"])
def test_live_adapter_rejects_unbound_or_stale_receipt(arrival_adapter, invalid):
adapter, inputs, replies, _ = arrival_adapter
reply = arrival_reply(inputs)
if invalid == "missing":
reply.pop("arrival")
elif invalid == "denied":
reply["arrival"]["admitted"] = False
else:
key, value = {
"pose": ("pose", pose(x=0.1)),
"clock": ("simulation_time_seconds", 0),
"target": ("target_xy", [3, 0]),
"inputs": ("execution_inputs_sha256", "b" * 64),
}[invalid]
reply["arrival"]["observation"][key] = value
replies.append(reply)
with pytest.raises(ValueError, match="body arrival receipt"):
adapter.navigate(inputs)
assert adapter.mission.index == 0 and adapter.mission.fault is None
def test_arrival_region_can_offer_observed_body_pose_without_radius_relaxation(monitor):
# Initial under-body blind strip: the waypoint centre is unsupported, but
# an entire body fits farther ahead inside the same arrival circle.
platform = ground()
platform = platform[platform[:, 0] >= -0.25 - 1e-6]
assert not monitor.assess_pose(platform, pose(), 0.37)["admitted"]
selected = monitor.find_arrival_pose(platform, pose(x=-0.3), [0, 0], 0.37)
assert selected is not None and np.linalg.norm(selected[:2]) <= 0.4
assert selected[3:] == pose()[3:]
assert monitor.assess_pose(platform, selected, 0.37)["admitted"]
# No sampling or nearest-point extrapolation can create a destination
# when the whole admissible arrival region is unsupported.
assert monitor.find_arrival_pose([], pose(), [0, 0], 0.37) is None
assert monitor.find_arrival_pose(platform, pose(), [-1, 0], 0.37) is None
def test_body_support_requires_positive_unexpired_surface_permission(monitor, monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon/navigation"))
from semantic_surface import SemanticSurface
memory = SemanticSurface()
terrain = ground()
assert not monitor.assess_pose(
terrain, pose(), 0.37, support_terrain=memory.permitted_terrain(terrain, 0)
)["admitted"]
samples = terrain.copy()
samples[:, 3] = 1
memory.observe(samples, 1)
assert monitor.assess_pose(
terrain, pose(), 0.37, support_terrain=memory.permitted_terrain(terrain, 20)
)["admitted"]
assert not monitor.assess_pose(
terrain, pose(), 0.37, support_terrain=memory.permitted_terrain(terrain, 32)
)["admitted"]
# A newly forbidden cell cannot retain an older positive permit.
samples[:, 3] = 0
memory.observe(samples, 33)
assert len(memory.permitted_terrain(terrain, 33)) == 0
def test_near_goal_without_current_visual_candidate_only_asks_for_body_validation(arrival_adapter):
adapter, inputs, replies, requests = arrival_adapter
inputs["source.pose"] = pose(x=-0.65)
_, inputs["navigation.intent"] = adapter.mission.update(
inputs["source.pose"], 2, lambda *_: None
)
inputs["source.simulation-time"] = 2
inputs["navigation.surface"][:] = False
replies.append({"status": "blocked", "speed_mps": 0, "yaw_rate_rps": 0, "path": []})
assert adapter.navigate(inputs)["motion.command"]["speed_mps"] == 0
assert requests[0]["arrival_target"] == [0, 0]
assert requests[0]["semantic_points"] == [] # Low confidence cannot create positive permission.
assert adapter.mission.index == 0
replies.append(arrival_reply(inputs))
with pytest.raises(ValueError, match="mission observation"):
adapter.navigate(inputs) # A server cannot expand the unchanged arrival radius.
def test_body_goal_admission_keeps_task_identity_when_visual_candidates_reappear(arrival_adapter):
adapter, inputs, replies, requests = arrival_adapter
inputs["source.pose"] = pose(x=-0.65)
_, inputs["navigation.intent"] = adapter.mission.update(
inputs["source.pose"], 2, lambda *_: None
)
inputs["source.simulation-time"] = 2
replies.append({"status": "blocked", "speed_mps": 0, "yaw_rate_rps": 0, "path": []})
adapter.navigate(inputs)
# A newly visible intermediate candidate lies beyond the task region.
# CMU must continue receiving the bound task target for revalidation.
adapter.goal = [0.8, 0.6, 0]
replies.append({"status": "blocked", "speed_mps": 0, "yaw_rate_rps": 0, "path": []})
adapter.navigate(inputs)
assert requests[-1]["arrival_target"] == [0, 0]
assert adapter.mission.index == 0
+157
View File
@@ -0,0 +1,157 @@
"""Two contact strips, independent body collisions, and conservative sweep coverage."""
import importlib
import math
from pathlib import Path
import numpy as np
import pytest
from k1link.simulation.ai_polygon.robots import select_robot
from k1link.simulation.ai_polygon.run_inputs import robot_geometry
POSE = [0, 0, 0.37, 0, 0, 0, 1]
@pytest.fixture
def monitor(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
return importlib.import_module("navigation.footprint").Footprint(
robot_geometry(select_robot("dcd006-v020"))
)
def ground():
return np.array(
[[x, y, 0, 0] for x in np.arange(-2, 2.01, 0.05) for y in np.arange(-2, 2.01, 0.05)]
)
def test_centre_gap_does_not_replace_or_remove_track_support(monitor):
terrain = ground()
gap = terrain[np.abs(terrain[:, 1]) >= 0.12]
straight = monitor.assess_command_support(0.3, 0, gap, POSE, 0.37)
assert straight["admitted"] and straight["status"] == "observed-supported"
assert all(side["support_samples"] > 0 for side in straight["per_side"].values())
# The same gap beneath the left belt cannot be excused by a supported right belt.
missing_left = terrain[~((terrain[:, 0] > 0.58) & (terrain[:, 1] > 0.12))]
result = monitor.assess_command_support(0.3, 0, missing_left, POSE, 0.37)
assert not result["admitted"] and result["per_side"]["left"]["unknown_samples"] > 0
assert result["per_side"]["right"]["unknown_samples"] == 0
# The chassis still collides with an obstacle between its belts.
obstacle = np.vstack((gap, [[0.7, 0, 0.3, 0.3]]))
assert not monitor.command_footprint_clear(0.3, 0, obstacle, POSE)
def test_arrival_requires_both_contacts_and_full_body_collision_clearance(monitor):
terrain = ground()
gap = terrain[np.abs(terrain[:, 1]) >= 0.12]
stationary = monitor.assess_pose(gap, POSE, 0.37)
assert stationary["admitted"] and stationary["support_samples"] == 72
assert stationary["schema_version"] == "missioncore.body-clearance/v2"
assert not monitor.assess_pose(gap[gap[:, 1] < 0], POSE, 0.37)["admitted"]
blocked = np.vstack((gap, [[0, 0, 0.3, 0.3]]))
assert not monitor.assess_pose(blocked, POSE, 0.37)["admitted"]
assert not monitor.assess_pose([], POSE, 0.37)["admitted"]
def test_drop_under_one_belt_and_turn_outside_a_supported_lane(monitor):
terrain = ground()
terrain[(terrain[:, 0] >= 0.6) & (terrain[:, 1] > 0.12), 2] = -0.4
drop = monitor.assess_command_support(0.3, 0, terrain, POSE, 0.37)
assert drop["status"] == "observed-unsafe"
assert drop["per_side"]["left"]["unsafe_samples"] > 0
assert drop["per_side"]["right"]["unsafe_samples"] == 0
lane = ground()
lane = lane[np.abs(lane[:, 1]) <= 0.65 + 1e-8]
assert monitor.assess_command_support(0.3, 0, lane, POSE, 0.37)["admitted"]
turn = monitor.assess_command_support(0, 0.8, lane, POSE, 0.37)
assert not turn["admitted"] and turn["unknown_samples"] > 0
@pytest.mark.parametrize("v,w", [(0.3, 0), (-0.3, 0), (0, 0.8), (0.2, -0.35), (-0.2, 0.35)])
def test_partial_motion_and_contact_edges_fit_swept_cells(monitor, v, w):
bounds = monitor.command_bounds(v, w)
cells, _ = monitor.contacts.cells(bounds, w)
spacing = monitor.contacts.spacing_m
occupied = {tuple(x) for x in np.rint(cells / spacing).astype(int)}
# Independent kinematic trajectories: stall in translation or turning, or
# any partial response. Include band interiors and every edge/corner.
for vf in (0, 0.35, 1):
for wf in (0, 0.35, 1):
for t in np.linspace(0, bounds["horizon_seconds"], 17):
angle = w * wf * t
rotation = np.array(
[[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]]
)
centre = (
np.array([v * vf * t, 0])
if w * wf == 0
else v * vf / (w * wf) * np.array([math.sin(angle), 1 - math.cos(angle)])
)
for low, high in monitor.contacts.bands:
for x in np.linspace(low[0], high[0], 5):
for y in np.linspace(low[1], high[1], 3):
point = rotation @ [x, y] + centre
assert tuple(np.rint(point / spacing).astype(int)) in occupied
@pytest.mark.parametrize("v,w", [(0.3, 0), (0, -0.8), (0.2, 0.35), (-0.2, -0.35)])
def test_same_arc_reduction_removes_cells_without_moving_the_lattice(monitor, v, w):
previous = set()
for scale in (0.2, 0.4, 0.6, 0.8, 1):
cells, _ = monitor.contacts.cells(monitor.command_bounds(v * scale, w * scale), w * scale)
selected = {tuple(x) for x in np.rint(cells / monitor.contacts.spacing_m).astype(int)}
assert previous <= selected
previous = selected
def test_occlusion_hold_and_small_motion_are_distinct(monitor):
held = monitor.assess_command_support(0, 0, [], POSE, 0.37)
assert held["status"] == "hold" and held["unsupported_xy"] == []
small = monitor.assess_command_support(0.01, 0, [], POSE, 0.37)
assert small["status"] != "hold"
# A blind current footprint is excluded from diagnostics, never inserted into a map.
blind = monitor.assess_command_support(0.3, 0, [], POSE, 0.37)
assert blind["status"] == "unknown" and blind["current_body_excluded_samples"] > 0
assert all(
abs(x) > monitor.half_length or abs(y) > monitor.half_width
for x, y in blind["unsupported_xy"]
)
def test_contact_assessment_is_invariant_to_world_pose(monitor):
terrain = ground()
terrain = terrain[~((terrain[:, 0] > 0.6) & (terrain[:, 1] > 0))]
original = monitor.assess_command_support(0.3, -0.2, terrain, POSE, 0.37)
angle = 0.7
rotation = np.array([[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]])
terrain[:, :2] = terrain[:, :2] @ rotation.T + [20, -12]
pose = [20, -12, 0.37, 0, 0, math.sin(angle / 2), math.cos(angle / 2)]
transformed = monitor.assess_command_support(0.3, -0.2, terrain, pose, 0.37)
assert transformed["unknown_samples"] == original["unknown_samples"]
assert transformed["per_side"] == original["per_side"]
def test_native_trace_auditor_detects_unrequested_lateral_drift_and_requires_full_horizon(
monitor,
):
audit = importlib.import_module("qualify_contact_sweep")
robot = select_robot("dcd006-v020")
rows = [
{
"request": [0, 0],
"dt": 1 / 60,
"position": [0, 0, 0.37],
"quaternion_wxyz": [1, 0, 0, 0],
"pre_step": {"position": [0, 0, 0.37], "heading": 0},
}
for _ in range(78)
]
assert audit.phase_metrics(rows, robot)["passed"]
interleaved = [dict(row, case=case, phase="hold") for row in rows for case in ("a", "b")]
phases = audit.audit_rows(interleaved, {"a": robot, "b": robot})
assert len(phases) == 2 and all(p["passed"] and len(p["windows"]) == 1 for p in phases)
assert not audit.phase_metrics(rows[:-1], robot)["passed"]
rows[-1]["position"] = [0, 0.15, 0.37]
assert not audit.phase_metrics(rows, robot)["passed"]
+248
View File
@@ -0,0 +1,248 @@
"""Transfer failure, identity boundaries and local plan persistence without a Worker lease."""
import base64
import hashlib
import json
from types import SimpleNamespace
import pytest
from k1link.simulation.ai_polygon.editor_cache import EditorCache
from k1link.simulation.ai_polygon.plans import PlanStore
def fixture(tmp_path):
world = {
"world_id": "aiworld-" + "1" * 32,
"sha256": "a" * 64,
"status": "available",
"settings": {"prepared": True, "meters_per_unit": 1, "rotation_degrees": [90, 0, 0]},
}
store = EditorCache(tmp_path, SimpleNamespace(get=lambda _: world))
row = store.request(world["world_id"])
data = {"scene.sog": b"synthetic-ply", "collision.glb": b"synthetic-glb"}
files = {
n: {"sha256": hashlib.sha256(b).hexdigest(), "byte_length": len(b)} for n, b in data.items()
}
store.update(row["key"], {"action": "manifest", "files": files})
return store, row, data
def chunk(store, key, name, data, offset=0):
return store.update(
key,
{
"action": "chunk",
"name": name,
"offset": offset,
"data": base64.b64encode(data).decode(),
},
)
def test_resume_and_publish(tmp_path):
store, row, data = fixture(tmp_path)
key = row["key"]
name = "scene.sog"
chunk(store, key, name, data[name][:4])
store = EditorCache(tmp_path, store.worlds)
assert store.get(key)["files"][name]["uploaded_bytes"] == 4
with pytest.raises(RuntimeError, match="offset"):
chunk(store, key, name, data[name])
with pytest.raises(RuntimeError):
store.asset(key, name)
chunk(store, key, name, data[name][4:], 4)
chunk(store, key, "collision.glb", data["collision.glb"])
store.update(key, {"action": "complete"})
assert store.asset(key, name)[0].read_bytes() == data[name]
assert store.request(row["world"]["world_id"])["status"] == "ready"
assert store.pending() is None
assert store.update(key, {"action": "complete"})["status"] == "ready"
def test_checksum_and_path_boundaries(tmp_path):
store, row, data = fixture(tmp_path)
key = row["key"]
with pytest.raises(FileNotFoundError):
store.get("../../outside")
with pytest.raises(ValueError):
chunk(store, key, "../outside", b"x")
for name, payload in data.items():
chunk(store, key, name, b"x" * len(payload))
with pytest.raises(ValueError, match="checksum"):
store.update(key, {"action": "complete"})
assert store.get(key)["status"] != "ready"
path = store.directory(key) / "manifest.json"
doc = json.loads(path.read_text())
doc["identity"]["source_sha256"] = "b" * 64
path.write_text(json.dumps(doc))
with pytest.raises(ValueError, match="identity"):
store.get(key)
def test_local_plan_has_no_fake_run_and_is_idempotent(tmp_path):
store, row, data = fixture(tmp_path)
for name, payload in data.items():
chunk(store, row["key"], name, payload)
cache = store.update(row["key"], {"action": "complete"})
plans = PlanStore(tmp_path / "plans")
context = {
"run_id": None,
"world": row["world"],
"robot": {"robot_id": "robot", "sha256": "c" * 64},
}
points = [{"id": "a" * 16, "position": [1, 2, 3]}, {"id": "b" * 16, "position": [1, 4, 3]}]
kwargs = {
"draft_id": "d" * 32,
"cache_key": row["key"],
"editor_collider_sha256": cache["files"]["collision.glb"]["sha256"],
}
plan = plans.create(context, "Local", points, 1, **kwargs)
assert plans.create(context, "Local", points, 1, **kwargs) == plan
assert plan["source_run_id"] is None
assert plan["source"] == "operator-local-viewport"
assert plan["settings"]["heading_degrees"] == 90
assert plan["editor_collider_sha256"] == kwargs["editor_collider_sha256"]
def test_local_plan_api_works_without_worker_and_rejects_stale_calibration(tmp_path):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from test_ai_polygon import make_world
from k1link.simulation.ai_polygon.robots import robot_catalog
from k1link.simulation.ai_polygon.worlds import WorldStore, write_json
from k1link.web.ai_polygon_api import build_ai_polygon_router
worlds = WorldStore(tmp_path)
world = make_world(worlds)
editor = EditorCache(tmp_path, worlds)
row = editor.request(world["world_id"])
files = {
n: {"sha256": hashlib.sha256(b"fixture").hexdigest(), "byte_length": 7}
for n in ("scene.sog", "collision.glb")
}
editor.update(row["key"], {"action": "manifest", "files": files})
for name in files:
chunk(editor, row["key"], name, b"fixture")
editor.update(row["key"], {"action": "complete"})
app = FastAPI()
app.include_router(build_ai_polygon_router(tmp_path))
robot = robot_catalog()[0]
body = {
"cache_key": row["key"],
"robot_id": robot["robot_id"],
"robot_sha256": robot["sha256"],
"draft_id": "e" * 32,
"sequence": 1,
"name": "Local",
"points": [
{"id": "a" * 16, "position": [1, 2, 3]},
{"id": "b" * 16, "position": [1, 4, 3]},
],
}
with TestClient(app) as client:
assert client.post("/api/v1/ai-polygon/plans", json=body).status_code == 201
catalog = client.get("/api/v1/ai-polygon/catalog").json()
assert catalog["runtime"]["active_run"] is None and not catalog["runs"]
world["settings"]["meters_per_unit"] = 2
write_json(worlds.directory(world["world_id"]) / "world.json", world)
assert client.post("/api/v1/ai-polygon/plans", json=body).status_code == 409
def test_editor_preparation_uses_existing_gpu_exclusion(tmp_path):
from test_observatory_recorded_jobs import _definitions
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
queue = ObservatoryRecordedJobQueue(tmp_path, definitions=_definitions())
owner = "aicache-" + "b" * 64
queue.reserve_simulation(owner)
queue.reserve_simulation(owner)
with pytest.raises(RuntimeError):
queue.reserve_simulation("airun-" + "a" * 32)
with pytest.raises(RuntimeError):
queue.release_simulation("aicache-" + "c" * 64)
# The reservation survives Core restart and only its exact receipt releases it.
queue = ObservatoryRecordedJobQueue(tmp_path, definitions=_definitions())
with pytest.raises(RuntimeError):
queue.reserve_simulation("airun-" + "a" * 32)
queue.release_simulation(owner)
queue.reserve_simulation("airun-" + "a" * 32)
queue.release_simulation("airun-" + "a" * 32)
def preparation_module(monkeypatch):
import importlib.util
from pathlib import Path
root = Path(__file__).parents[1] / "simulation/ai-polygon"
monkeypatch.syspath_prepend(str(root))
spec = importlib.util.spec_from_file_location("editor_assets", root / "editor_assets.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize("count,bands,valid", [(123, 3, True), (100, 3, False), (123, 0, False)])
def test_sog_publication_preserves_density_and_harmonics(
tmp_path, monkeypatch, count, bands, valid
):
import zipfile
module = preparation_module(monkeypatch)
source, output = tmp_path / "source.ply", tmp_path / "scene.sog"
source.write_text(
"ply\nelement vertex 123\n"
+ "".join(f"property float f_rest_{i}\n" for i in range(45))
+ "end_header\n"
)
with zipfile.ZipFile(output, "w") as archive:
archive.writestr("meta.json", json.dumps({"count": count, "shN": {"bands": bands}}))
if valid:
assert module.verify_sog(source, output) == {"gaussian_count": 123, "sh_bands": 3}
else:
with pytest.raises(ValueError, match="retain"):
module.verify_sog(source, output)
def test_original_sog_reuse_is_byte_exact_and_rejects_changed_assets(tmp_path, monkeypatch):
import zipfile
module = preparation_module(monkeypatch)
archive = tmp_path / "source"
archive.mkdir()
data = {"meta.json": b'{"count":123}', "sh0.webp": b"original-colour-data"}
for name, payload in data.items():
(archive / name).write_bytes(payload)
manifest = archive / "source-manifest.json"
manifest.write_text(
json.dumps(
{
"source_url": "fixture",
"files": [
{"path": n, "byte_length": len(b), "sha256": hashlib.sha256(b).hexdigest()}
for n, b in data.items()
],
}
)
)
monkeypatch.setattr(module, "__file__", str(tmp_path / "editor_assets.py"))
(tmp_path / "editor-sources.json").write_text(
json.dumps(
{
"a" * 64: {
"manifest": "source/source-manifest.json",
"manifest_sha256": module.digest(manifest),
}
}
)
)
output = tmp_path / "scene.sog"
world = {"sha256": "a" * 64, "source_url": "fixture"}
assert module.reuse_sog_archive(tmp_path, world, output)
with zipfile.ZipFile(output) as bundled:
assert {n: bundled.read(n) for n in bundled.namelist()} == data
(archive / "sh0.webp").write_bytes(b"damaged")
with pytest.raises(ValueError, match="checksum"):
module.reuse_sog_archive(tmp_path, world, output)
+105 -2
View File
@@ -27,10 +27,12 @@ def test_chassis_jitter_cannot_hide_stall_and_retries_are_bounded():
def test_route_cursor_and_completion_survive_pause_without_restarting_task():
mission = WaypointMission([[1, 0], [3, 0]])
mission.update(pose(), 0, goal)
assert mission.update(pose(1), 6, goal)[1]["waypoint"] == 1
assert mission.update(pose(1), 6, goal)[1]["waypoint"] == 0
assert mission.confirm_arrival(pose(1), 6, 0, admitted=True)
mission.resume()
assert mission.update(pose(1), 6, goal)[1]["waypoint"] == 1
assert mission.update(pose(3), 18, goal)[1]["state"] == "goal-reached"
assert mission.update(pose(3), 18, goal)[1]["state"] != "goal-reached"
assert mission.confirm_arrival(pose(3), 18, 1, admitted=True)
mission.resume()
assert mission.update(pose(3), 18, goal)[1]["state"] == "goal-reached"
@@ -139,3 +141,104 @@ def test_rejected_observation_stops_but_does_not_forget_revalidated_goal():
assert calls == [observed]
# Memory alone never authorizes a command when the new frame is rejected.
assert mission.update(pose(1.3), 1.4, lambda *_: None)[0] is None
def test_temporary_barrier_replans_without_forgetting_observed_arrival_point():
mission = WaypointMission([[1.4, 0], [3, 0]])
observed = [1.4, 0, 0]
mission.update(pose(0.6), 0, lambda *_: observed)
assert mission.update(pose(0.6), 8, lambda *_: None)[0] is None
assert mission.attempts == 1 and mission.goal == observed
assert observed not in mission.failed_goals
def revalidate(target, prior, excluded):
assert target == [1.4, 0] and prior == observed and not excluded
return prior
assert mission.update(pose(0.6), 8.2, revalidate)[0] == observed
assert mission.update(pose(0.7), 9, lambda *_: None)[0] is None
mission.update(pose(1.1), 10, lambda target, prior, _: [*target, 0])
assert mission.index == 0
assert mission.confirm_arrival(pose(1.1), 10, 0, admitted=True)
mission.update(pose(1.1), 10.2, lambda target, prior, _: [*target, 0])
assert mission.index == 1 and mission.goal == [3, 0, 0]
def test_preserved_arrival_evidence_does_not_remove_stall_budget_or_allow_blind_motion():
mission = WaypointMission([[1.4, 0]])
observed = [1.4, 0, 0]
mission.update(pose(0.6), 0, lambda *_: observed)
for t in range(1, 34):
requested, intent = mission.update(pose(0.6), t, lambda *_: None)
assert requested is None
assert intent["state"] == "stuck" and mission.attempts == 4
def test_arrival_evidence_survives_completed_retreat_and_requires_revalidation():
mission = WaypointMission([[1.4, 0]])
observed = [1.4, 0, 0]
def retreat(prior):
return prior or [-0.05, 0, 0]
mission.update(pose(0.6), 0, lambda *_: observed, retreat)
assert mission.update(pose(0.6), 8, lambda *_: None, retreat)[1]["state"] == "reversing"
assert mission.update(pose(0.1), 10, lambda *_: None, retreat)[0] is None
assert mission.goal == observed and mission.recovery_goal is None
assert mission.update(pose(0.1), 10.2, lambda *_: None)[0] is None
assert mission.update(pose(0.1), 10.4, lambda target, prior, _: prior)[0] == observed
def yaw_pose(angle, x=0, y=0):
import math
return [x, y, 0.37, 0, 0, math.sin(angle / 2), math.cos(angle / 2)]
def test_slow_half_turn_is_progress_without_spurious_recovery():
import math
mission = WaypointMission([[-3, 0]])
def choose(target, *_):
return [*target, 0]
for seconds in np.arange(0, 21, 0.2):
_, intent = mission.update(yaw_pose(math.pi * min(seconds / 20, 1)), float(seconds), choose)
assert intent["recovery_attempt"] == 0
for seconds in np.arange(21, 50, 0.2):
current = yaw_pose(math.pi, x=-(seconds - 20) * 0.1)
mission.update(current, float(seconds), choose)
if mission.arrival_candidate(current):
mission.confirm_arrival(current, float(seconds), 0, admitted=True)
assert mission.state == "goal-reached"
def test_alignment_jitter_and_goal_changes_do_not_create_unbounded_budget():
mission = WaypointMission([[-8, 0]])
for seconds in np.arange(0, 90, 0.2):
angle = 0.3 * np.sin(seconds)
_, intent = mission.update(yaw_pose(angle), float(seconds), lambda target, *_: [*target, 0])
assert intent["state"] == "stuck"
mission = WaypointMission([[-8, 0]])
for seconds in np.arange(0, 90, 0.2):
_, intent = mission.update(
yaw_pose(seconds * 0.1),
float(seconds),
lambda *_, t=seconds: [2 * np.cos(t * 0.1 + 0.5), 2 * np.sin(t * 0.1 + 0.5), 0],
)
assert intent["state"] == "stuck"
def test_heading_credit_keeps_existing_retry_count_and_expires():
mission = WaypointMission([[-8, 0]])
def choose(target, *_):
return [*target, 0]
mission.update(yaw_pose(0), 0, choose)
mission.update(yaw_pose(0), 8, choose)
assert mission.attempts == 1
for seconds in range(9, 80):
mission.update(yaw_pose(min((seconds - 8) * 0.08, 3.14)), seconds, choose)
assert mission.fault == "stuck" and mission.attempts == 4
+196 -16
View File
@@ -1,18 +1,31 @@
"""The actuator may soften acceleration but must never prolong a safety command."""
"""Continuous two-track intent, source expiry, saturation and adapter parity."""
import importlib.util
import importlib
from pathlib import Path
import pytest
spec = importlib.util.spec_from_file_location(
"motion_control", Path(__file__).parents[1] / "simulation/ai-polygon/motion_control.py"
from k1link.fleet.differential_drive import (
DriveLimits,
SideSpeeds,
TwoSideDrive,
arcade_intent,
tank_intent,
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def test_slow_perception_keeps_continuous_physics_command():
@pytest.fixture
def module(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
return importlib.import_module("motion_control")
@pytest.fixture
def limits():
return DriveLimits(0.685, 0.3, 0.2, 0.4, 0.1)
def test_slow_perception_keeps_continuous_physics_command(module):
drive = module.DriveEnvelope()
rows = [drive.step(0.15, 0, 1 / 60)[0] for _ in range(180)]
assert rows[0] == pytest.approx(0.2 / 60)
@@ -20,21 +33,188 @@ def test_slow_perception_keeps_continuous_physics_command():
assert rows[44:] == pytest.approx([0.15] * 136)
def test_braking_and_deadman_bypass_ramp():
def test_zero_or_deadman_is_immediate_but_normal_reduction_is_smooth(module):
drive = module.DriveEnvelope()
for _ in range(60):
drive.step(0.15, 0, 1 / 60)
assert drive.step(0.03, 0, 1 / 60) == (0.03, 0)
assert drive.step(0.03, 0, 1 / 60)[0] == pytest.approx(0.15 - 0.4 / 60)
assert drive.step(0.15, 0.2, 1 / 60, stop=True) == (0, 0)
assert drive.wheels == (0, 0)
assert drive.step(0.15, 0, 1 / 60)[0] == pytest.approx(0.2 / 60)
assert drive.step(0, 0, 1 / 60) == (0, 0)
def test_curvature_and_direction_change():
def test_w_a_release_a_and_change_to_d_keep_moving_without_side_jumps(limits):
drive = TwoSideDrive(limits)
previous = drive.applied
finals = []
for steering in (0, 1, 0, -1, 0):
requested = arcade_intent(1, steering, limits, 0.35)
for _ in range(180):
value = drive.step(requested, 1 / 60)
assert min(value.left_mps, value.right_mps) > 0
assert max(value.left_mps, value.right_mps) <= 0.3
for a, b in zip(vars(previous).values(), vars(value).values(), strict=True):
assert abs(b - a) <= 0.4 / 60 + 1e-9
previous = value
finals.append(value.twist(limits.track_centres_m))
assert finals[0][1] == finals[2][1] == finals[4][1] == 0
assert finals[1][1] > 0 and finals[3][1] < 0
def test_tank_reversal_reaches_zero_without_stopping_other_side(limits):
drive = TwoSideDrive(limits)
for _ in range(120):
drive.step(tank_intent(1, 1, limits), 1 / 60)
values = [drive.step(tank_intent(-1, 1, limits), 1 / 60) for _ in range(180)]
assert all(value.right_mps == pytest.approx(0.3) for value in values)
first_reverse = next(i for i, value in enumerate(values) if value.left_mps < 0)
assert values[first_reverse - 1].left_mps == 0
assert values[-1].left_mps == pytest.approx(-0.3)
def test_twist_tank_and_arcade_share_direction_units_and_saturation(module, limits):
requested = SideSpeeds.from_twist(0.3, 0.35, 0.685)
bounded = requested.bounded(0.3)
assert bounded.right_mps == 0.3 and 0 < bounded.left_mps < bounded.right_mps
assert bounded.left_mps / bounded.right_mps == pytest.approx(
requested.left_mps / requested.right_mps
)
assert arcade_intent(1, 1, limits, 0.35) == bounded
drive = module.DriveEnvelope()
for _ in range(60):
speed, yaw = drive.step(0.15, 0.2, 1 / 60)
assert yaw / speed == pytest.approx(0.2 / 0.15)
speed, yaw = drive.step(-0.15, -0.2, 1 / 60)
assert speed < 0 and yaw < 0
assert max(map(abs, drive.wheels)) <= 0.2 / 60 + 1e-9
for _ in range(180):
v, w = drive.step(0.3, 0.35, 1 / 60)
assert (v, w) == pytest.approx(bounded.twist(0.685))
assert drive.wheels == pytest.approx((bounded.left_mps, bounded.right_mps))
assert SideSpeeds.from_twist(-0.2, -0.3, 0.685).twist(0.685) == pytest.approx((-0.2, -0.3))
def test_clock_gaps_and_invalid_values_cannot_create_unbounded_intent(limits):
drive = TwoSideDrive(limits)
assert drive.step(SideSpeeds(0.3, 0.3), 100).left_mps == pytest.approx(0.02)
prior = drive.applied
assert drive.step(SideSpeeds(0.3, 0.3), 0) == prior
for dt in (-1, float("nan"), float("inf")):
with pytest.raises(ValueError):
drive.step(SideSpeeds(0.3, 0.3), dt)
assert drive.applied == prior
for value in (float("nan"), float("inf")):
with pytest.raises(ValueError):
SideSpeeds(value, 0)
with pytest.raises(ValueError):
tank_intent(1.1, 0, limits)
with pytest.raises(ValueError):
DriveLimits(0, 0.3, 0.2, 0.4, 0.1)
def test_profile_mass_and_geometry_are_consumed_consistently(module):
profile = importlib.import_module("rover_profile")
chassis, wheel = profile.mass_distribution()
assert chassis + len(profile.PROFILE["wheel_names"]) * wheel == 100
assert profile.mass_distribution({**profile.PROFILE, "mass_kg": 110})[0] == chassis + 10
with pytest.raises(ValueError):
profile.mass_distribution({**profile.PROFILE, "mass_kg": 3})
robot = profile.ROBOT_DOCUMENT
assert (
module.DriveEnvelope().limits.track_centres_m == robot["visual"]["motion"]["track_width_m"]
)
assert robot["physics"]["track_width_m"] + robot["physics"]["wheel_width_m"] == pytest.approx(
robot["physics"]["width_m"]
)
assert (
robot["physics"]["zero_command_mode"] != robot["mechanics"]["vesc_adapter"]["zero_command"]
)
def test_chassis_feedback_accounts_for_pitch_without_setting_body_motion(module):
control = module.ChassisSpeedFeedback(
{"proportional_gain": 0.75, "max_correction_mps": 0.15}, 0.37, 0.685, 0.3
)
# A forward-pitching body can outrun its belt while the contact moves slowly.
nominal = control.step(0.15, 0.1, 0.15, 0)
descending = control.step(0.15, 0.1, 0.19, 0.2)
assert nominal == pytest.approx((0.15, 0.1))
assert 0 < descending[0] < 0.15 and descending[1] == pytest.approx(0.1)
assert control.step(-0.15, -0.1, -0.19, -0.2) == pytest.approx((-descending[0], -0.1))
# Safety zero cannot acquire translation from feedback.
assert control.step(0, 0, 0.2, 0.4) == (0, 0)
# A low-speed arc must not turn into an unrequested inner-side reversal.
v, w = control.step(0.07, 0.2, 0.2, 0.2)
assert v - w * 0.685 / 2 >= -1e-12 and v + w * 0.685 / 2 >= 0
v, w = control.step(0.1, 0.2 / 0.685, 0, -0.2)
assert v - w * 0.685 / 2 == pytest.approx(0) # Keep the intended held inner belt.
assert control.step(0.01, 0, 0.4, 0.5) == (0, 0) # No autonomous reversal.
v, w = control.step(0.3, 0.35, 0, -0.5)
assert max(abs(v - w * 0.685 / 2), abs(v + w * 0.685 / 2)) <= 0.3
with pytest.raises(ValueError):
control.step(0.15, 0, float("nan"), 0)
def test_pivot_corrects_body_drift_without_reversing_sides_or_overriding_stop(module):
control = module.ChassisSpeedFeedback(
{"proportional_gain": 0.75, "max_correction_mps": 0.15}, 0.37, 0.685, 0.3
)
assert control.step(0, 0.35, 0, 0) == pytest.approx((0, 0.35))
assert control.step(0, 0.35, 0.04, 0) == pytest.approx((-0.03, 0.35))
assert control.step(0, -0.35, -0.04, 0) == pytest.approx((0.03, -0.35))
for yaw in (-0.35, -0.01, 0.01, 0.35):
for measured in (-2, -0.04, 0.04, 2):
v, w = control.step(0, yaw, measured, 0.4)
left, right = v - w * 0.685 / 2, v + w * 0.685 / 2
assert left * yaw <= 1e-12 and right * yaw >= -1e-12
assert w == pytest.approx(yaw)
assert max(abs(left), abs(right)) <= 0.3
shared = module.RoverMotionControl(importlib.import_module("rover_profile").ROBOT_DOCUMENT, 0.3)
shared.step(0, 0.35, 1 / 60, 0.04, 0)
assert shared.step(0, 0.35, 1 / 60, 0.2, 0.4, stop=True) == (0, 0)
def test_speed_reserve_preserves_arc_reverse_pivot_and_zero(module):
reserve = module.reserve_chassis_speed
v, w = reserve(0.15, 0.2, 0.15, 0.03)
assert v == pytest.approx(0.12) and w / v == pytest.approx(0.2 / 0.15)
assert reserve(-0.15, -0.2, 0.15, 0.03) == pytest.approx((-v, -w))
assert reserve(0.05, 0.1, 0.15, 0.03) == (0.05, 0.1)
assert reserve(0, 0.2, 0.15, 0.03) == (0, 0.2)
assert reserve(0, 0, 0.15, 0.03) == (0, 0)
with pytest.raises(ValueError):
reserve(0.15, 0, 0.03, 0.03)
def test_shared_runtime_command_path_matches_explicit_components(module):
robot = importlib.import_module("rover_profile").ROBOT_DOCUMENT
shared = module.RoverMotionControl(robot, 0.3)
envelope = module.DriveEnvelope()
settings = robot["control"]["chassis_speed_feedback"]
feedback = module.ChassisSpeedFeedback(
settings, robot["tracked_contact"]["chassis_com_height_m"], 0.685, 0.3
)
# Explicit composition, with changing feedback, arcs, reversals and watchdog stops.
for v, w, stop in [
(0.3, 0, False),
(0.3, 0.2, False),
(0, 0.35, False),
(-0.1, -0.2, False),
(0.2, 0.2, True),
(0, 0, False),
]:
for i in range(90):
observed, pitch = (i % 7) * 0.025, (i % 5 - 2) * 0.03
expected = module.reserve_chassis_speed(
v, w, 0.3, 0.3 * settings["body_speed_reserve_fraction"]
)
expected = envelope.step(*expected, 1 / 60, stop=stop)
expected = feedback.step(*expected, observed, pitch)
assert shared.step(v, w, 1 / 60, observed, pitch, stop=stop) == pytest.approx(
expected, abs=1e-14
)
def test_explicit_control_profile_is_used_by_command_adapter(module):
import copy
robot = copy.deepcopy(importlib.import_module("rover_profile").ROBOT_DOCUMENT)
robot["control"]["acceleration_mps2"] = 0.1
robot["control"]["chassis_speed_feedback"]["enabled"] = False
control = module.RoverMotionControl(robot, 0.2)
assert control.step(0.2, 0, 1 / 60, 0, 0) == pytest.approx((0.1 / 60, 0))
+179 -6
View File
@@ -1,7 +1,9 @@
import importlib.util
import subprocess
import sys
from functools import partial
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pytest
@@ -13,24 +15,78 @@ from k1link.simulation.ai_polygon.terrain_contract import terrain_matches
ROOT = Path(__file__).resolve().parents[1] / "simulation/ai-polygon"
@pytest.fixture(autouse=True)
def runtime_imports(monkeypatch):
# Match the shipped adapter's script directory without depending on which
# other test happened to add it to sys.path first.
monkeypatch.syspath_prepend(str(ROOT))
def module(name):
spec = importlib.util.spec_from_file_location(name, ROOT / (name + ".py"))
spec = importlib.util.spec_from_file_location(name.replace("/", "."), ROOT / (name + ".py"))
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
from k1link.simulation.ai_polygon.robots import select_robot
from k1link.simulation.ai_polygon.run_inputs import sensor_rig
from k1link.simulation.ai_polygon.source_projection import PinholeSource
robot = select_robot("dcd006-v020")
geometry = robot["physics"]
if name == "navigation/footprint":
return result.Footprint(geometry)
if name == "navigation_client":
source = PinholeSource(sensor_rig(robot, 0.8))
return SimpleNamespace(
**{
**vars(result),
"project": partial(result.project, source=source),
"visual_goal": partial(result.visual_goal, source=source, geometry=geometry),
"recovery_goal": partial(result.recovery_goal, geometry=geometry),
}
)
if name == "navigation/terrain_costs":
return SimpleNamespace(
**{
**vars(result),
"underbody_support_costs": partial(
result.underbody_support_costs, geometry=geometry
),
}
)
return result
def test_grouped_semantic_barriers_preserve_per_return_expiry_and_boundaries():
memory = module("navigation/semantic_surface").SemanticSurface()
samples = np.array([[0, 0, 0, 0], [-0.001, 0, 0, 1], [0.201, 0, 0, 1], [0.202, 0, 1, 0]])
memory.observe(samples, 10)
rng = np.random.default_rng(20261003)
terrain = rng.uniform(-0.5, 0.5, (2000, 4))
original = terrain.copy()
for now in (10, 39.999, 40, 40.001):
expected = terrain.copy()
blocked = []
for point in terrain:
cell = tuple(np.floor(point[:2] / 0.2).astype(int))
permission, observed = memory.cells.get(cell, (1, now))
blocked.append(permission == 0 and observed >= now - 30)
expected[blocked, 3] = np.maximum(expected[blocked, 3], 1)
actual, count = memory.apply(terrain, now)
assert count == sum(blocked) and np.array_equal(expected, actual)
assert np.array_equal(original, terrain)
def test_simulation_composition_has_causal_dependencies_and_separate_authority():
graph = compose(ROOT)
assert graph.as_dict()["execution"]["mode"] == "worker-local-simulation"
motion = graph.nodes[-1]
assert motion.module.group == "motion"
assert dict(motion.inputs)["segmentation.surface"] == "simulation-segformer-ade"
assert dict(motion.inputs)["navigation.surface"] == "simulation-waypoint-mission"
assert dict(motion.inputs)["detection.boxes"] == "simulation-rf-detr"
assert motion.module.state_policy == "causal-reset-at-source-start"
selection = graph.selection_document()
selection["selections"] = [r for r in selection["selections"] if r["group"] != "segmentation"]
with pytest.raises(CompositionError, match="segmentation.surface"):
with pytest.raises(CompositionError, match="segmentation.labels"):
compose(ROOT, selection)
@@ -41,7 +97,8 @@ def test_surface_providers_are_interchangeable_in_the_shared_constructor():
if row["group"] == "segmentation":
row.update(module_id=reference.module_id, module_sha256=reference.sha256)
graph = compose(ROOT, selection)
assert dict(graph.nodes[-1].inputs)["segmentation.surface"] == reference.module_id
policy = next(n for n in graph.nodes if n.module.group == "policy")
assert dict(policy.inputs)["segmentation.surface"] == reference.module_id
def test_composition_rejects_stale_module_identity():
@@ -127,11 +184,24 @@ def test_observed_route_goal_keeps_task_position_and_cannot_run_away_from_it():
advanced = [1.5, 0, 0.37, 0, 0, 0, 1]
camera = {**calibration, "origin": [1.88, 0, 0.8]}
prior = [*target, 0]
# A rejected centre may select observed ground inside the arrival region;
# an unconstrained pixel median must never move it outside that region.
changed = surface.copy()
_, u, v, visible = module("navigation_client").project(np.asarray([prior]), calibration)
assert visible.all()
changed[int(v[0] * 512 / 600), int((u[0] - 100) * 512 / 600)] = False
alternative = choose(changed, points, pose, calibration, prior, target)
assert alternative is not None
assert np.linalg.norm(np.asarray(alternative[:2]) - target) <= 0.25
assert choose(surface, points, pose, calibration, prior, target) == prior
assert choose(surface, points + [1.5, 0, 0], advanced, camera, prior, target) == prior
# The actual camera loses nearby ground beyond the old hardcoded 0.8 m.
advanced = [1.1, 0, 0.37, 0, 0, 0, 1]
camera = {**calibration, "origin": [1.48, 0, 0.8]}
assert choose(surface, points + [1.1, 0, 0], advanced, camera, prior, target) == prior
assert (
choose(surface, points + [1.1, 0, 0], advanced, camera, alternative, target) == alternative
)
assert choose(np.zeros_like(surface), points, pose, calibration, target=target) is None
# Clear road ahead is not permission to drive away from a missed waypoint.
assert choose(surface, points, pose, calibration, target=[-1, 0]) is None
@@ -200,6 +270,59 @@ def test_command_monitor_covers_deadman_braking_distance_and_rotation():
assert not check(0, 0.8, [[0.7, 0, 0.5, 0.5]], pose)
def test_command_sweep_covers_recorded_understeer_and_retains_straight_corridor():
monitor = module("navigation/footprint")
pose = [0, 0, 0.37, 0, 0, 0, 1]
# Reconstructed body corner from v0.20-m130-mu0.80, left-arc at 1.9 s.
# The ideal .2 m/s, .2 rad/s arc previously admitted this virtual obstacle.
obstacle = [[0.8994258851, -0.3573475900, 0.5, 0.5]]
assert not monitor.command_footprint_clear(0.2, 0.2, obstacle, pose)
walls = [[x, y, 0.5, 0.5] for x in np.arange(-1, 2, 0.05) for y in (-0.52, 0.52)]
assert monitor.command_footprint_clear(0.2, 0, walls, pose)
assert not monitor.command_footprint_clear(0.2, 0.2, walls, pose)
assert not monitor.command_footprint_clear(0, 0.8, walls, pose)
# Turning error cannot excuse an obstacle within the initial true body.
assert not monitor.command_footprint_clear(0.2, 0.2, [[0, 0, 0.5, 0.5]], pose)
def test_command_envelope_contains_incomplete_responses_and_scales_monotonically():
monitor = module("navigation/footprint")
for speed in (-0.3, 0, 0.3):
for yaw in (-0.8, 0, 0.8):
b = monitor.command_bounds(speed, yaw)
lower, upper = np.array(b["lower_xy_m"]), np.array(b["upper_xy_m"])
for response_v in (0, 0.3, 1):
for response_w in (0, 0.2, 1):
t = np.linspace(0, b["horizon_seconds"], 101)
v, w = speed * response_v, yaw * response_w
a = w * t
x = v * np.sin(a) / w if w else v * t
y = v * (1 - np.cos(a)) / w if w else np.zeros_like(t)
for cx in (-monitor.half_length, monitor.half_length):
for cy in (-monitor.half_width, monitor.half_width):
points = np.column_stack(
(
x + cx * np.cos(a) - cy * np.sin(a),
y + cx * np.sin(a) + cy * np.cos(a),
)
)
assert np.all(points >= lower - 1e-9)
assert np.all(points <= upper + 1e-9)
for scale in (0.2, 0.5, 0.8):
small = monitor.command_bounds(speed * scale, yaw * scale)
assert np.all(np.array(small["lower_xy_m"]) >= lower - 1e-9)
assert np.all(np.array(small["upper_xy_m"]) <= upper + 1e-9)
assert np.all(np.array(small["discrepancy_xy_m"]) <= b["discrepancy_xy_m"])
@pytest.mark.parametrize("speed,yaw", [(float("nan"), 0), (0, float("inf"))])
def test_command_sweep_rejects_nonfinite_commands(speed, yaw):
with pytest.raises(ValueError):
module("navigation/footprint").command_footprint_clear(
speed, yaw, [], [0, 0, 0.37, 0, 0, 0, 1]
)
def test_smooth_slope_is_distinct_from_a_step_or_vertical_terrain():
costs = module("navigation/terrain_costs").supported_slope_costs
xy = np.array([[x, y] for x in np.arange(-1, 1.01, 0.1) for y in np.arange(-1, 1.01, 0.1)])
@@ -226,7 +349,7 @@ def test_underbody_support_does_not_clear_future_terrain_walls_or_drops():
terrain = np.array(
[
[-0.375, -0.28, 0.066, 0.103], # Low return already under the chassis.
[0.46, 0, 0.066, 0.103], # Inset excludes the leading edge.
[0.55, 0, 0.066, 0.103], # DCD-006 inset excludes the leading edge.
[0.75, 0, 0.066, 0.103], # Never change future terrain from body pose.
[0, 0, 0.12, 0.12], # A real step within the footprint remains blocked.
[0, 0, 0.5, 0.5],
@@ -349,7 +472,7 @@ def test_grade_fit_cannot_bridge_an_unobserved_gap():
def test_existing_reserve_overlap_only_allows_departure_not_approach_or_body_overlap():
check = module("navigation/footprint").command_footprint_clear
pose = [0, 0, 0.37, 0, 0, 0, 1]
behind = [[-0.53, 0, 0.5, 0.5]]
behind = [[-0.61, 0, 0.5, 0.5]]
assert check(0.15, 0, behind, pose)
assert not check(-0.1, 0, behind, pose)
assert not check(0, 0.35, behind, pose)
@@ -388,3 +511,53 @@ def test_velocity_regulation_keeps_the_selected_arc_and_its_braking_clearance():
reverse, _, scale = monitor.regulate_command(-0.1, 0, [[-0.68, 0, 0.2, 0.2]], pose)
assert 0.2 <= scale < 1 and reverse < 0
assert monitor.command_footprint_clear(reverse, 0, [[-0.68, 0, 0.2, 0.2]], pose)
def test_range_fan_rotation_preserves_both_mounts_and_first_hit_occlusion():
from types import SimpleNamespace
sensor = module("terrain").RangeSensor.__new__(module("terrain").RangeSensor)
sensor.directions = np.array([[1.0, 0, 0], [0, 1, 0], [0, 0, -1]])
sensor.rear_directions = np.array([[-1.0, 0, 0]])
calls = []
hits = iter(
[
{
"hit": True,
"rigidBody": "/World/Ground",
"collision": "/World/Ground",
"position": [1, 2, 3],
},
{"hit": True, "rigidBody": "/World/Rover/chassis", "position": [7, 7, 7]},
{"hit": False},
{
"hit": True,
"rigidBody": "/World/Obstacle",
"collision": "/World/Obstacle/Shape",
"position": [4, 5, 6],
},
]
)
def cast(origin, direction, distance, **kwargs):
calls.append((origin, direction, distance, kwargs))
return next(hits)
sensor.query = SimpleNamespace(raycast_closest=cast)
transform = np.array([[0, 1, 0, 0], [-1, 0, 0, 0], [0, 0, 1, 0], [9, 8, 7, 1]])
result = sensor.capture([1, 0, 0.8], transform, [-1, 0, 0.8])
assert result.tolist() == [[1, 2, 3], [4, 5, 6]]
assert sensor.hit_paths == {"/World/Ground": 1, "/World/Obstacle/Shape": 1}
# Exact per-beam mounts, max-range no-echo, and no ray behind self-occlusion.
assert sensor.rays["origins"][sensor.rays["origin_indices"]].tolist() == pytest.approx(
np.array([[1, 0, 0.8], [1, 0, 0.8], [-1, 0, 0.8]])
)
assert sensor.rays["ends"].tolist() == pytest.approx(
np.array([[1, 2, 3], [1, 0, -7.2], [4, 5, 6]])
)
assert [c[1] for c in calls] == [(0, 1, 0), (-1, 0, 0), (0, 0, -1), (0, -1, 0)]
assert [c[0] for c in calls] == [(1, 0, 0.8)] * 3 + [(-1, 0, 0.8)]
assert all(c[2:] == (8.0, {"bothSides": True}) for c in calls)
sensor.query = SimpleNamespace(raycast_closest=lambda *a, **k: {"hit": False})
assert len(sensor.capture([1, 0, 0.8], transform)) == 0
assert sensor.hit_paths == {}
+180
View File
@@ -0,0 +1,180 @@
"""Mission identity, edit acknowledgement and ground-constrained viewport picking."""
import importlib.util
import json
from pathlib import Path
import numpy as np
import pytest
from pydantic import ValidationError
from test_ai_polygon_realtime import realtime as _realtime
from test_ai_polygon_realtime import snapshot
from k1link.simulation.ai_polygon.contracts import PlanningCommand, PlanSave, RunCreate
realtime = _realtime
def point(identity, x, y=0, z=0):
return {"id": identity * 16, "position": [x, y, z]}
def test_plan_requires_worker_ack_and_is_immutable(realtime):
store, hello, row = realtime
row["request"]["purpose"] = "planning"
store._save(row)
key = row["run_id"]
with pytest.raises(RuntimeError, match="планирование"):
store.control(key, "play")
command = PlanningCommand(request_id="e" * 32, action="add")
assert store.planning_command(key, command)["planning_sequence"] == 1
assert store.planning_command(key, command)["planning_sequence"] == 1
with pytest.raises(RuntimeError, match="подтверждения"):
store.save_plan(key, PlanSave(name="Trail", sequence=1))
points = [point("a", 1, 2, 0.3), point("b", 1, 4, 0.5)]
store.snapshot(
key,
hello.instance_id,
snapshot(
planning={
"sequence": 1,
"view_revision": 0,
"points": points,
"can_undo": True,
}
),
)
plan = store.save_plan(key, PlanSave(name="Trail", sequence=1))
assert plan["settings"]["spawn_xy"] == [1, 2]
assert plan["settings"]["route_xy"] == [[1, 4]]
assert plan["settings"]["heading_degrees"] == 90
assert store.plans.get(plan["plan_id"]) == plan
assert store.worlds.get(row["world"]["world_id"])["settings"] == row["world"]["settings"]
store.control(key, "stop")
with pytest.raises(RuntimeError, match="завершается"):
store.save_plan(key, PlanSave(name="Trail", sequence=1))
altered = {**plan, "name": "tampered"}
(store.plans.root / (plan["plan_id"] + ".json")).write_text(json.dumps(altered))
with pytest.raises(ValueError, match="повреждено"):
store.plans.get(plan["plan_id"])
def test_plan_identity_and_no_edits_during_evaluation(realtime):
store, _, row = realtime
with pytest.raises(RuntimeError, match="планирования"):
store.planning_command(row["run_id"], PlanningCommand(request_id="f" * 32, action="clear"))
plan = store.plans.create(row, "Task", [point("a", 0), point("b", 1)], 0)
row["state"] = "stopped"
store._save(row)
store.active = None
store.queue.release_simulation(row["run_id"])
request = RunCreate(
world_id=row["world"]["world_id"],
clock="realtime",
start_paused=True,
plan_id=plan["plan_id"],
)
updated = store.worlds.get(row["world"]["world_id"])
updated["sha256"] = "f" * 64
from k1link.simulation.ai_polygon.worlds import write_json
write_json(store.worlds.directory(updated["world_id"]) / "world.json", updated)
with pytest.raises(ValueError, match="не соответствует"):
store.start(request, "wrong-scene-plan")
def test_snapshot_route_is_bounded():
with pytest.raises(ValidationError):
snapshot(
planning={
"sequence": 0,
"view_revision": 0,
"can_undo": False,
"points": [point("a", 0)] * 34,
}
)
with pytest.raises(ValidationError):
snapshot(
planning={
"sequence": 0,
"view_revision": 0,
"can_undo": False,
"points": [point("a", float("nan"))],
}
)
class TerrainQuery:
def raycast_all(self, origin, direction, distance, collect, bothSides):
if direction[2] >= 0:
return
# Synthetic sloping ground z = 0.1 x. A foreign collider cannot be picked.
t = (origin[2] - 0.1 * origin[0]) / (0.1 * direction[0] - direction[2])
p = np.asarray(origin) + t * np.asarray(direction)
collect({"collision": "/World/Rover", "normal": [0, 0, 1], "position": [0, 0, 2]})
if 0 <= t <= distance:
collect({"collision": "/World/Terrain", "normal": [-0.1, 0, 0.995], "position": p})
def test_projection_edit_axes_undo_and_stale_view():
source = Path(__file__).parents[1] / "simulation/ai-polygon/route_view.py"
spec = importlib.util.spec_from_file_location("route_view_test", source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
view = module.RouteView(
{
"request": {"purpose": "planning"},
"world": {
"settings": {
"spawn_xy": [0, 0],
"ground_z": 0,
"heading_degrees": 0,
"route_xy": [[100, 100]],
}
},
},
TerrainQuery(),
)
assert len(view.points) == 1 # No hidden legacy mission imported into a new plan.
view.matrix[3, 2] = -10
p = module.project_point([2, 3, 0], view.matrix, view.focal, view.aperture)
origin, direction = view.ray(*p)
assert np.allclose(origin + direction * (-origin[2] / direction[2]), [2, 3, 0])
identity = view.points[0]["id"]
command = PlanningCommand(
request_id="a" * 32, action="move", point_id=identity, x=0.6, y=0.6, axis="x"
).model_dump()
view.apply([{**command, "sequence": 1}])
moved = view.points[0]["position"]
assert moved[0] > 1 and moved[1] == 0 and moved[2] == pytest.approx(0.1 * moved[0])
view.apply([{**command, "sequence": 2, "action": "undo"}])
assert view.points[0]["position"] == [0, 0, 0]
view.apply([{**command, "sequence": 3, "view_revision": 99}])
assert "Обзор изменился" in view.error
assert view.points[0]["position"] == [0, 0, 0]
view.apply([{**command, "sequence": 4, "action": "zoom", "amount": 1000}])
assert np.linalg.norm(view.desired_eye - view.eye) == pytest.approx(3)
# Free-look keeps position; flight follows gaze, Q/E follows world vertical.
view.apply([{**command, "sequence": 5, "action": "home"}])
home = view.desired_eye.copy()
view.apply([{**command, "sequence": 6, "action": "orbit", "x": 0.4, "y": -1}])
assert np.allclose(view.desired_eye, home)
assert view.desired_angles[1] > 0 # Looking above the horizon is allowed.
forward, right, up = view.camera_axes(view.desired_angles)
assert abs(np.dot(forward, right)) < 1e-8 and np.linalg.norm(up) == pytest.approx(1)
view.apply([{**command, "sequence": 7, "action": "fly", "x": 0, "y": 0.5, "amount": 0}])
assert np.allclose(view.desired_eye - home, forward * 0.5)
flown = view.desired_eye.copy()
view.apply([{**command, "sequence": 8, "action": "fly", "x": 0, "y": 0, "amount": -1}])
assert np.allclose(view.desired_eye - flown, [0, 0, -1])
assert view.camera_moving
for _ in range(180):
view.advance_camera(1 / 30)
assert not view.camera_moving # No latched key or simulation time is needed to stop.
assert view.points[0]["position"] == [0, 0, 0]
view.apply([{**command, "sequence": 9, "action": "clip", "amount": 0, "enabled": True}])
assert view.clip_height == 0 # Zero/negative world heights are real clipping planes.
view.apply([{**command, "sequence": 10, "action": "clip", "amount": -2, "enabled": True}])
assert view.clip_height == -2
view.apply([{**command, "sequence": 11, "action": "clip", "enabled": False}])
assert view.clip_height is None
+107
View File
@@ -301,3 +301,110 @@ def test_windows_snapshot_sharing_retry_is_bounded(tmp_path, monkeypatch):
with pytest.raises(PermissionError):
module.sharing_retry(permanent)
assert len(attempts) == 8
def test_run_pins_selected_robot_and_rejects_report_from_another_world(
realtime, tmp_path, monkeypatch
):
import importlib
import json
from test_ai_polygon_reports import ADAPTERS, fixture_episode
from k1link.simulation.ai_polygon.contracts import SimulationReport
from k1link.simulation.ai_polygon.robots import select_robot
store, hello, row = realtime
robot = select_robot("dcd006-v020")
assert row["robot"] == robot
assert row["request"]["robot_id"] == robot["robot_id"]
monkeypatch.syspath_prepend(str(ADAPTERS))
fixture_episode(tmp_path)
original = json.loads((tmp_path / "run.json").read_text())
original.update(run_id=row["run_id"], world=row["world"], worker=row["worker"])
(tmp_path / "run.json").write_text(json.dumps(original))
report = SimulationReport.model_validate(
importlib.import_module("run_report").seal_episode(
tmp_path, {"mission_outcome": "operator-stop"}
)
)
with pytest.raises(ValueError, match="не соответствует"):
store.finish(
row["run_id"],
hello.instance_id,
"stopped",
"",
report.model_copy(update={"world_sha256": "f" * 64}),
)
assert store.active == row["run_id"]
done = store.finish(row["run_id"], hello.instance_id, "stopped", "", report)
assert done["report"]["manifest_sha256"] == report.manifest_sha256
assert store.finish(row["run_id"], hello.instance_id, "stopped", "", report) == done
with pytest.raises(ValueError, match="нельзя заменить"):
store.finish(
row["run_id"],
hello.instance_id,
"stopped",
"",
report.model_copy(update={"distance_m": 99}),
)
def test_stale_worker_robot_is_rejected_before_creating_or_reserving_run(realtime):
store, hello, row = realtime
store.finish(row["run_id"], hello.instance_id, "stopped", "")
store.register(hello.model_copy(update={"robots": {"dcd006-v020": "0" * 64}}))
prior = list(store.root.iterdir())
with pytest.raises(RuntimeError, match="ещё обновляется"):
store.start(
RunCreate(world_id=row["world"]["world_id"], clock="realtime"),
"test-stale-robot-01",
)
assert store.active is None
assert list(store.root.iterdir()) == prior
def test_operator_input_cannot_revert_camera_or_drive_and_ignores_duplicate_sequence(realtime):
from k1link.simulation.ai_polygon.contracts import ObserverInput
store, hello, row = realtime
value = ObserverInput(session="e" * 32, sequence=1, orbit=(0.1, 0.2), move=(0, 0, 0), zoom=0.5)
changed = store.view(row["run_id"], "follow", value)
assert changed["control"] == "pause"
assert changed["observer_input"]["sequence"] == 1
older = value.model_copy(update={"sequence": 0, "orbit": (0.8, 0.9)})
assert store.view(row["run_id"], "follow", older)["observer_input"]["orbit"] == [0.1, 0.2]
store.view(row["run_id"], "overview")
with pytest.raises(RuntimeError, match="изменён"):
store.view(row["run_id"], "follow", value)
def test_spatial_preview_is_bounded_run_owned_and_monotonic(realtime):
from k1link.simulation.ai_polygon.contracts import InferencePreview
store, hello, row = realtime
preview = InferencePreview(
frame_id=1,
simulation_time_ns=50,
composition_sha256="d" * 64,
environment="park",
layers=[
dict(
id="lidar",
label="LiDAR",
kind="points3d",
points=[[1, 0, 0]],
source_count=1,
frame="body-x-forward-y-left-z-up",
)
],
)
run_id = row["run_id"]
with pytest.raises((ValueError, RuntimeError)):
store.inference_preview(run_id, "f" * 32, preview)
assert store.inference_preview(run_id, hello.instance_id, preview) == {"accepted": True}
assert store.inference_preview(run_id)["layers"][0]["points"] == [(1, 0, 0)]
assert store.inference_preview(run_id, hello.instance_id, preview) == {"accepted": False}
store.active = None
with pytest.raises(RuntimeError, match="не запущена"):
store.inference_preview(run_id, hello.instance_id, preview)
+122
View File
@@ -0,0 +1,122 @@
"""Selected rover identity and compact, sealed Worker evidence contracts."""
import hashlib
import importlib
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from k1link.simulation.ai_polygon.contracts import SimulationReport
from k1link.simulation.ai_polygon.robots import robot_catalog, select_robot
ADAPTERS = Path(__file__).parents[1] / "simulation/ai-polygon"
def test_rover_uses_the_canonical_metric_asset():
robot = select_robot("dcd006-v020")
asset = ADAPTERS.parents[1] / robot["visual"]["source"]
assert hashlib.sha256(asset.read_bytes()).hexdigest() == robot["visual"]["sha256"]
assert robot["visual"]["dimensions_m"] == [1.163, 0.905, 0.734]
assert robot["physics"]["length_m"] == 1.163
assert robot["physics"]["width_m"] == 0.905
assert len(robot_catalog()) == 1
with pytest.raises(ValueError, match="изменился"):
select_robot("dcd006-v020", "0" * 64)
with pytest.raises(ValueError, match="не установлен"):
select_robot("../../other")
def fixture_episode(path):
def save(name, value):
target = path / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(value))
run_id = "airun-" + "a" * 32
save(
"run.json",
{
"run_id": run_id,
"robot": select_robot("dcd006-v020"),
"world": {"sha256": "b" * 64, "settings": {"route_xy": [[2, 0]]}},
"worker": {"runtime_sources": {"scene": "c" * 64}},
},
)
save("composition.json", {"sha256": "d" * 64})
rows = []
for x, command, reason in [
(0, 0, "stale-camera"),
(1, 0.1, "none"),
(1.5, 0, "no-road"),
(1.5, 0, "no-road"),
(2, 0.1, "none"),
]:
rows.append(
{
"pose": [x, 0, 0.37, 0, 0, 0, 1],
"dt": 0.1,
"command": [command, 0],
"stop_reason": "none" if reason == "no-road" else reason,
"decision_reason": reason,
}
)
(path / "physics-motion.jsonl").write_text("\n".join(json.dumps(r) for r in rows))
(path / "camera").mkdir()
(path / "camera/decisions.jsonl").write_text(
json.dumps(
{
"inference_ms": 150,
"mission": {"state": "tracking", "waypoint": 0, "waypoint_count": 1},
}
)
)
def test_report_does_not_confuse_timeout_with_success_and_seals_sources(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(ADAPTERS))
report_module = importlib.import_module("run_report")
fixture_episode(tmp_path)
report = report_module.seal_episode(tmp_path, {"mission_outcome": "time-limit"})
validated = SimulationReport.model_validate(report)
assert validated.mission_outcome == "time-limit" and validated.waypoints_reached == 0
assert validated.distance_m == 2 and validated.goal_error_m == 0
assert validated.simulation_seconds == pytest.approx(0.5)
assert validated.stops[0].model_dump() == {"reason": "no-road", "events": 1, "seconds": 0.2}
assert validated.collision_count is None
assert validated.inference_ms_p95 == 150
manifest = tmp_path / "evidence-manifest.json"
assert hashlib.sha256(manifest.read_bytes()).hexdigest() == validated.manifest_sha256
for item in json.loads(manifest.read_text())["files"]:
assert hashlib.sha256((tmp_path / item["path"]).read_bytes()).hexdigest() == item["sha256"]
with pytest.raises(FileExistsError):
report_module.seal_episode(tmp_path, {"mission_outcome": "goal-reached"})
def test_failed_preparation_has_missing_measurements_not_fabricated_zeros(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(ADAPTERS))
report_module = importlib.import_module("run_report")
fixture_episode(tmp_path)
(tmp_path / "physics-motion.jsonl").unlink()
(tmp_path / "camera/decisions.jsonl").unlink()
report = report_module.seal_episode(tmp_path, {"mission_outcome": "error"})
assert report["distance_m"] is report["simulation_seconds"] is report["goal_error_m"] is None
assert report["inference_ms_p50"] is None
def test_docker_desktop_readiness_retries_only_availability(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(ADAPTERS))
stack = importlib.import_module("model_stack")
responses = iter(
[
SimpleNamespace(returncode=1, stdout=""),
SimpleNamespace(returncode=0, stdout=""),
SimpleNamespace(returncode=0, stdout="27.0"),
]
)
calls = []
monkeypatch.setattr(stack, "docker", lambda *a, **k: next(responses))
stack.wait_for_docker(tmp_path / "status.json", sleep=calls.append)
assert calls == [3, 3]
assert json.loads((tmp_path / "status.json").read_text())["state"] == "waiting-docker"
+258
View File
@@ -0,0 +1,258 @@
"""Execution inputs: profile isolation, projection, admission and immutable evidence."""
import copy
import importlib.util
import os
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from test_ai_polygon_realtime import realtime as realtime
from k1link.simulation.ai_polygon.contracts import RunCreate, SimulationReport
from k1link.simulation.ai_polygon.robots import select_robot
from k1link.simulation.ai_polygon.run_inputs import (
LEGACY_SCHEMA,
SCHEMA,
digest,
legacy_run_inputs,
resolve_run_inputs,
robot_geometry,
sensor_rig,
validate_run_inputs,
)
from k1link.simulation.ai_polygon.source_projection import PinholeSource
ROOT = Path(__file__).parents[1]
ADAPTERS = ROOT / "simulation/ai-polygon"
def module(name):
spec = importlib.util.spec_from_file_location(name.replace("/", "."), ADAPTERS / (name + ".py"))
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
def legacy():
return {
"request": {},
"plan": None,
"world": {
"settings": {"camera_height_m": 0.8, "max_speed_mps": 0.15, "route_xy": [[2.0, 0.0]]}
},
}
def reseal(value):
value["sha256"] = digest({k: v for k, v in value.items() if k != "sha256"})
return value
def test_explicit_migration_is_nonmutating_and_new_runtime_uses_pinned_inputs():
robot, run = select_robot("dcd006-v020"), legacy()
before = copy.deepcopy(run)
inputs = resolve_run_inputs(run, robot)
assert run == before and inputs["migration"] == "world-plan-composition/v1"
run["execution_inputs"] = inputs
run["world"]["settings"].update(route_xy=[[999, 999]], max_speed_mps=0.3)
resolved = resolve_run_inputs(run, robot)
assert resolved["mission"]["route_xy"] == [[2.0, 0.0]]
assert resolved["behavior"]["max_speed_mps"] == 0.15
resolved["mission"]["route_xy"].clear()
assert inputs["mission"]["route_xy"] == [[2.0, 0.0]]
@pytest.mark.parametrize(
"mutate",
[
lambda v: v.update(schema_version="unknown"),
lambda v: v.update(extra=True),
lambda v: v["robot"]["geometry"].update(width_m=0.1),
lambda v: v["sensors"].update(source_adapter="guess-crop"),
lambda v: v["sensors"].update(provider_crop_xywh=[0, 0, 800, 600]),
lambda v: v["sensors"].update(image_size=[1920, 1080]),
lambda v: v["behavior"].update(max_speed_mps=True),
lambda v: v["behavior"].update(max_speed_mps=0.31),
lambda v: v["mission"].update(arrival_radius_m=1),
lambda v: v["localization"].update(mode="estimated"),
],
)
def test_unknown_incompatible_or_resealed_inputs_are_rejected(mutate):
robot = select_robot("dcd006-v020")
inputs = legacy_run_inputs(legacy(), robot)
mutate(inputs)
with pytest.raises(ValueError):
validate_run_inputs(reseal(inputs), robot)
def test_tamper_and_plan_mismatch_are_rejected():
robot, run = select_robot("dcd006-v020"), legacy()
run["execution_inputs"] = legacy_run_inputs(run, robot)
run["execution_inputs"]["behavior"]["max_speed_mps"] = 0.2
with pytest.raises(ValueError, match="identity"):
resolve_run_inputs(run, robot)
reseal(run["execution_inputs"])
run["plan"] = {"sha256": "a" * 64}
with pytest.raises(ValueError, match="mission identity"):
resolve_run_inputs(run, robot)
def test_contact_inputs_are_versioned_profile_bound_and_old_evidence_is_unchanged():
robot = select_robot("dcd006-v020")
current = legacy_run_inputs(legacy(), robot)
contact = current["robot"]["geometry"]["ground_contact"]
left, right = contact["bands"]
assert left["lower_xy_m"] == pytest.approx([-0.46090352840718773, 0.2325])
assert left["upper_xy_m"] == pytest.approx([0.25765496961256984, 0.4525])
assert right["upper_xy_m"][1] == pytest.approx(-0.2325)
changed = copy.deepcopy(current)
changed["robot"]["geometry"]["ground_contact"]["bands"][0]["upper_xy_m"][1] = 0.3
with pytest.raises(ValueError, match="geometry"):
validate_run_inputs(reseal(changed), robot)
old = copy.deepcopy(current)
old["schema_version"] = LEGACY_SCHEMA
old["robot"]["geometry"].pop("ground_contact")
reseal(old)
before = copy.deepcopy(old)
assert validate_run_inputs(old, robot) == before and old == before
bad = copy.deepcopy(robot)
bad["mechanics"]["inner_gap_m"] = 0.1
with pytest.raises(ValueError, match="contact geometry"):
robot_geometry(bad)
def test_two_sensor_resolutions_project_the_same_observation(monkeypatch):
monkeypatch.syspath_prepend(str(ADAPTERS))
nav = module("navigation_client")
a = select_robot("dcd006-v020")
b = {
**copy.deepcopy(a),
"robot_id": "synthetic-small",
"sha256": "b" * 64,
"sensor_image_size": [640, 480],
}
b["physics"].update(length_m=0.6, width_m=0.4)
sources = [PinholeSource(sensor_rig(r, 0.8)) for r in (a, b)]
points = np.array([[x, y, 0] for x in (1.5, 2.0, 3.0) for y in (-0.4, 0, 0.4)])
pixels = []
for source in sources:
focal = source.width * 14 / 36
calibration = {
"origin": [0.62, 0, 0.8],
"rotation": np.eye(3).ravel(),
"intrinsics": [focal, focal, source.width / 2, source.height / 2],
}
_, u, v, visible = nav.project(points, calibration, source)
pixels.append((visible, source.indices(u[visible], v[visible])))
assert np.array_equal(pixels[0][0], pixels[1][0])
assert np.array_equal(pixels[0][1], pixels[1][1])
original = np.zeros((600, 800, 3), dtype=np.uint8)
assert sources[0].model_rgb(original) is original # No new resample for baseline.
assert sources[1].model_rgb(np.full((480, 640, 3), 123, dtype=np.uint8)).shape == original.shape
with pytest.raises(ValueError, match="source camera"):
sources[1].model_rgb(original)
def test_two_robot_footprints_change_admission_without_global_cross_talk():
robot = select_robot("dcd006-v020")
narrow = {**robot["physics"], "length_m": 0.6, "width_m": 0.4}
Footprint = module("navigation/footprint").Footprint
baseline, small = Footprint(robot["physics"]), Footprint(narrow)
pose = [0, 0, 0.37, 0, 0, 0, 1]
obstacle = [[0, 0.35, 0.2, 0.2]]
assert not baseline.command_footprint_clear(0.1, 0, obstacle, pose)
assert small.command_footprint_clear(0.1, 0, obstacle, pose)
assert not baseline.command_footprint_clear(0.1, 0, obstacle, pose)
costs = module("navigation/terrain_costs")
terrain = np.array([[0, 0.3, 0, 0.2]])
assert costs.underbody_support_costs(terrain, pose, geometry=robot["physics"])[1] == 1
assert costs.underbody_support_costs(terrain, pose, geometry=narrow)[1] == 0
def test_two_profiles_change_full_width_visual_goal(monkeypatch):
monkeypatch.syspath_prepend(str(ADAPTERS))
nav = module("navigation_client")
robot = select_robot("dcd006-v020")
source = PinholeSource(sensor_rig(robot, 0.8))
geometry = robot["physics"]
points = np.array(
[[x, y, 0] for x in np.linspace(1.5, 3, 20) for y in np.linspace(-0.05, 0.05, 9)]
)
calibration = {
"origin": [0.38, 0, 0.8],
"rotation": np.eye(3).ravel(),
"intrinsics": [533.333, 533.333, 400, 300],
}
surface = np.zeros((512, 512), dtype=bool)
surface[:, 220:292] = True
pose = [0, 0, 0.37, 0, 0, 0, 1]
assert (
nav.visual_goal(surface, points, pose, calibration, source=source, geometry=geometry)
is None
)
assert (
nav.visual_goal(
surface, points, pose, calibration, source=source, geometry={**geometry, "width_m": 0.2}
)
is not None
)
def test_core_pins_inputs_only_for_capable_worker_and_checks_report_identity(realtime):
store, hello, old = realtime
assert "execution_inputs" not in old
store.finish(old["run_id"], hello.instance_id, "stopped", "")
store.register(hello.model_copy(update={"execution_inputs_versions": [SCHEMA]}))
run = store.start(
RunCreate(world_id=old["world"]["world_id"], clock="realtime"), "inputs-test-01"
)
assert run["execution_inputs"]["robot"]["sha256"] == run["robot"]["sha256"]
report = SimulationReport(
schema_version="missioncore.simulation-report/v2",
run_id=run["run_id"],
generated_at="2026-10-03T00:00:00Z",
mission_outcome="time-limit",
robot_id=run["robot"]["robot_id"],
robot_sha256=run["robot"]["sha256"],
world_sha256=run["world"]["sha256"],
runtime_sources=run["worker"]["runtime_sources"],
simulation_seconds=0,
distance_m=0,
goal_error_m=None,
waypoint_count=0,
waypoints_reached=0,
inference_ms_p50=None,
inference_ms_p95=None,
stops=[],
inference_count=0,
inference_errors=0,
report_sha256="a" * 64,
manifest_sha256="b" * 64,
evidence_files=1,
evidence_bytes=1,
)
with pytest.raises(ValueError, match="Отчёт"):
store.finish(run["run_id"], hello.instance_id, "completed", "", report)
correct = report.model_copy(
update={"execution_inputs_sha256": run["execution_inputs"]["sha256"]}
)
assert (
store.finish(run["run_id"], hello.instance_id, "completed", "", correct)["state"]
== "completed"
)
def test_coordinator_inputs_do_not_import_numpy_pydantic_or_core():
script = (
"from k1link.simulation.ai_polygon.run_inputs import sensor_rig; "
"from k1link.simulation.ai_polygon.robots import select_robot; "
"assert sensor_rig(select_robot('dcd006-v020'), .8)['image_size']==[800,600]"
)
subprocess.run(
[sys.executable, "-S", "-c", script],
env={**os.environ, "PYTHONPATH": str(ROOT / "src")},
check=True,
)
+18
View File
@@ -40,3 +40,21 @@ def test_clearance_tracks_translation_heading_and_support_slope():
points[:, :2] += [10, -3]
assert count(points, (10, -3), 45, (0.2, 0, 4)) == 1
assert count([[8, -5, 3.6], [12, -5, 4.4], [10, -1, 4]], (10, -3), 45, (0.2, 0, 4)) == 0
def test_rectangular_dcd006_front_and_rotated_corner_are_checked():
def rectangle(points, angle=0):
return MODULE.obstructing_triangles(
np.array(points),
np.array([[0, 1, 2]]),
(0, 0),
angle,
(0, 0, 0),
length=1.163,
width=0.905,
)
# New nose is beyond the former square; adjacent space remains available.
assert rectangle([[0.56, -0.02, 0.2], [0.56, 0.02, 0.2], [0.56, 0, 0.8]]) == 1
assert rectangle([[0, 0.47, 0.2], [0.02, 0.47, 0.2], [0, 0.47, 0.8]]) == 0
assert rectangle([[0, 0.56, 0.2], [0.02, 0.56, 0.2], [0, 0.56, 0.8]], 90) == 1
+117
View File
@@ -0,0 +1,117 @@
"""Ground support of intermediate motion, including unknown and measured hazards."""
import importlib
import math
from pathlib import Path
import numpy as np
import pytest
from k1link.simulation.ai_polygon.robots import select_robot
POSE = [0, 0, 0.37, 0, 0, 0, 1]
@pytest.fixture
def monitor(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
return importlib.import_module("navigation.footprint").Footprint(
select_robot("dcd006-v020")["physics"]
)
def ground():
return np.array(
[[x, y, 0, 0] for x in np.arange(-2, 2.01, 0.05) for y in np.arange(-2, 2.01, 0.05)]
)
def test_empty_or_one_sided_ground_is_unknown_not_a_free_motion_certificate(monitor):
assert monitor.command_footprint_clear(0.2, 0, [], POSE)
unknown = monitor.assess_command_support(0.2, 0, [], POSE, 0.37)
assert not unknown["admitted"] and unknown["status"] == "unknown"
assert unknown["unknown_samples"] == unknown["support_samples"]
assert unknown["unsafe_samples"] == 0
known = monitor.assess_command_support(0.2, 0, ground(), POSE, 0.37)
assert known["admitted"] and known["status"] == "observed-supported"
ledge = ground()[ground()[:, 0] <= 0.85]
result = monitor.assess_command_support(0.2, 0, ledge, POSE, 0.37)
assert not result["admitted"] and result["unknown_samples"] > 0
assert result["support_reasons"]["outside-observed-patch"] > 0
def test_supported_start_and_finish_do_not_hide_a_hole_between_them(monitor):
terrain = ground()
terrain = terrain[np.linalg.norm(terrain[:, :2] - [0.85, 0], axis=1) > 0.19]
assert monitor.assess_pose(terrain, POSE, 0.37)["admitted"]
finish = [1.7, 0, *POSE[2:]]
# The endpoint assertion uses the complete ground extent required by its body.
extension = ground() + [2, 0, 0, 0]
full = np.vstack((terrain, extension[extension[:, 0] > 2]))
assert monitor.assess_pose(full, finish, 0.37)["admitted"]
motion = monitor.assess_command_support(0.2, 0, full, POSE, 0.37)
assert not motion["admitted"] and motion["unknown_samples"] > 0
def test_straight_support_does_not_grant_room_to_rotate_body(monitor):
lane = ground()
lane = lane[np.abs(lane[:, 1]) <= 0.65 + 1e-8]
assert monitor.assess_command_support(0.2, 0, lane, POSE, 0.37)["admitted"]
turn = monitor.assess_command_support(0, 0.8, lane, POSE, 0.37)
assert not turn["admitted"] and turn["unknown_samples"] > 0
def test_measured_drop_is_distinct_from_missing_observations(monitor):
terrain = ground()
terrain[terrain[:, 0] > 0.7, 2] = -0.4
result = monitor.assess_command_support(0.2, 0, terrain, POSE, 0.37)
assert not result["admitted"] and result["unsafe_samples"] > 0
assert result["status"] == "observed-unsafe"
assert result["support_reasons"]["height-discontinuity"] > 0
def test_fixed_support_grid_remains_nested_and_world_rotation_does_not_grant_support(monitor):
terrain = ground()
terrain = terrain[np.linalg.norm(terrain[:, :2] - [0.9, -0.3], axis=1) > 0.18]
statuses = [
monitor.assess_command_support(0.2 * s, -0.25 * s, terrain, POSE, 0.37)
for s in (0.2, 0.4, 0.6, 0.8, 1)
]
assert [x["unknown_samples"] for x in statuses] == sorted(
x["unknown_samples"] for x in statuses
)
a = 1.1
rotation = np.array([[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]])
moved = terrain.copy()
moved[:, :2] = moved[:, :2] @ rotation.T + [20, -10]
pose = [20, -10, 0.37, 0, 0, math.sin(a / 2), math.cos(a / 2)]
result = monitor.assess_command_support(0.2, -0.25, moved, pose, 0.37)
assert result["admitted"] == statuses[-1]["admitted"]
assert result["unknown_samples"] == statuses[-1]["unknown_samples"]
def test_normal_underbody_occlusion_is_not_missing_future_ground(monitor):
terrain = ground()
inside = (np.abs(terrain[:, 0]) < monitor.half_length - 0.02) & (
np.abs(terrain[:, 1]) < monitor.half_width - 0.02
)
terrain = terrain[~inside]
assert not monitor.assess_pose(terrain, POSE, 0.37)["support_known"]
moving = monitor.assess_command_support(0.2, 0, terrain, POSE, 0.37)
assert moving["admitted"] and moving["current_body_excluded_samples"] > 0
# No invented under-body returns have been added to the caller's map.
assert not np.any((np.abs(terrain[:, 0]) < 0.3) & (np.abs(terrain[:, 1]) < 0.3))
hold = monitor.assess_command_support(0, 0, [], POSE, 0.37)
assert hold["admitted"] and hold["status"] == "hold" and hold["support_samples"] == 0
assert hold["unsupported_xy"] == []
def test_support_guard_reduces_same_arc_or_stops_before_unknown(monitor):
terrain = ground()
terrain = terrain[terrain[:, 0] <= 0.85 + 1e-8]
v, w, scale, support = monitor.regulate_supported_command(0.2, 0, terrain, POSE, 0.37)
assert 0.2 <= scale < 1 and v > 0 and w == 0 and support["admitted"]
v, w, scale, support = monitor.regulate_supported_command(0.2, 0, [], POSE, 0.37)
assert (v, w, scale) == (0, 0, 0) and not support["admitted"]
blocked = np.vstack((ground(), [[0, 0, 0.3, 0.3]]))
assert monitor.regulate_supported_command(0.2, 0, blocked, POSE, 0.37)[:3] == (0, 0, 0)
+79
View File
@@ -0,0 +1,79 @@
import importlib
import math
from pathlib import Path
import pytest
@pytest.fixture
def rig(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
return importlib.import_module("control_qualification")
def test_arrival_reference_point_does_not_guarantee_full_body_support(rig):
g = dict(length_m=1.163, width_m=0.905)
lane = [-2, -0.5, 2, 0.5]
assert rig.goal_body_supported([0, 0], 0, [0, 0], g, lane)
assert not rig.goal_body_supported([0, 0], math.pi / 2, [0, 0], g, lane)
assert not rig.goal_body_supported([0.2, 0], 0, [0, 0], g, [-0.6, -0.5, 0.6, 0.5])
assert not rig.goal_body_supported([0.401, 0], 0, [0, 0], g, [-2, -2, 2, 2])
assert rig.goal_body_supported([0.399, 0], math.pi / 3, [0, 0], g, [-2, -2, 2, 2])
def test_matrix_is_bounded_and_covers_speed_load_and_friction(rig):
cases = rig.specifications()
assert len(cases) == len({c["id"] for c in cases}) == 12
assert {c["speed_mps"] for c in cases} == {0.1, 0.2, 0.3}
assert {c["payload_kg"] for c in cases} == {0, 30}
assert {c["dynamic_friction"] for c in cases} == {0.35, 0.8}
assert sum(p[1] for p in rig.PHASES) < 70
def test_stationary_motor_targets_cannot_pass_a_sliding_body(rig):
rows = [
dict(
phase="stop",
phase_seconds=(i + 1) / 60,
dt=1 / 60,
request=[0, 0],
nominal=[0, 0],
distance_step_m=0.1 / 60,
turn_step_rad=0,
position=[i * 0.1 / 60, 0],
velocity=[0.1, 0, 0],
forward_mps=0.1,
yaw_rps=0,
acceleration_mps2=0,
held_sides=[True, True],
)
for i in range(180)
]
m = rig.phase_metrics(rows)
assert not m["passed"] and not m["checks"]["hold_speed"]
assert m["stopping_time_s"] is None and m["stopping_distance_m"] is None
def test_pivot_position_uses_excursion_not_accumulated_path(rig):
rows = [
dict(
phase="pivot",
phase_seconds=(i + 1) / 60,
dt=1 / 60,
request=[0, 0.35],
nominal=[0, 0.35],
distance_step_m=0.002,
turn_step_rad=0.35 / 60,
position=[0.1 * math.sin(i * 0.04), 0.1 * (1 - math.cos(i * 0.04))],
phase_origin=[0, 0],
velocity=[0.1, 0, 0],
forward_mps=0,
yaw_rps=0.35,
acceleration_mps2=0,
held_sides=[False, False],
)
for i in range(360)
]
result = rig.phase_metrics(rows)
assert result["distance_m"] > 0.3
assert result["maximum_displacement_m"] < 0.21 and result["checks"]["pivot_position"]
@@ -0,0 +1,97 @@
"""Candidate episodes must pin new identities without rewriting old evidence."""
import copy
import importlib
from pathlib import Path
import pytest
@pytest.fixture
def qualifier(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
return importlib.import_module("qualify_gaussian_episode")
def reference():
return {
"run_id": "airun-" + "b" * 32,
"world": {
"sha256": "c" * 64,
"collider_sha256": "d" * 64,
"settings": {
"heading_degrees": 90,
"spawn_xy": [20, 30],
"max_speed_mps": 0.3,
"camera_height_m": 0.8,
"route_xy": [[20, 50]],
},
},
"request": {
"composition": {
"schema_version": "missioncore.observatory-ai-composition/v1",
"selections": [
{
"group": group,
"module_id": module,
"module_sha256": "0" * 64,
"parameters": {"environment": "park"} if group == "policy" else {},
}
for group, module in (
("segmentation", "simulation-ddrnet-goose"),
("detection", "simulation-rf-detr"),
("policy", "simulation-waypoint-mission"),
("motion", "simulation-cmu-navigation"),
)
],
}
},
"worker": {"runtime_sources": {"scene": "old"}},
"plan": {"sha256": "old", "robot_sha256": "old"},
}
def test_candidate_pins_actual_robot_and_composition_without_mutating_reference(qualifier):
from k1link.simulation.ai_polygon.composition import compose
original = reference()
before = copy.deepcopy(original)
run = qualifier.prepare_run(original, "airun-" + "a" * 32, 180, 4.2, {"a": "b"})
assert original == before
assert run["robot"]["physics"]["contact_model"] == "tracks"
assert run["robot"]["sha256"] == run["request"]["robot_sha256"]
assert run["robot"]["sha256"] == run["plan"]["robot_sha256"]
assert run["plan"]["sha256"] != "old"
assert run["worker"]["runtime_sources"]["scene"] != "old"
graph = compose(qualifier.ROOT, run["request"]["composition"])
assert graph.sha256 == run["qualification"]["composition_sha256"]
assert run["world"]["settings"]["route_xy"][-1] == pytest.approx([20, 34.2])
assert run["world"]["settings"]["max_speed_mps"] == 0.15
@pytest.mark.parametrize(
"identity,seconds,length",
[
("old-run", 180, 4.2),
("airun-" + "a" * 32, 601, 4.2),
("airun-" + "a" * 32, 180, float("nan")),
("airun-" + "a" * 32, 180, 40),
],
)
def test_unbounded_or_ambiguous_episode_is_rejected(qualifier, identity, seconds, length):
with pytest.raises(ValueError):
qualifier.prepare_run(reference(), identity, seconds, length, {})
def test_challenge_is_pinned_separately_from_robot_world_and_model(qualifier):
original = reference()
before = copy.deepcopy(original)
base = qualifier.prepare_run(original, "airun-" + "a" * 32, 180, 4.2, {})
fault = qualifier.prepare_run(original, "airun-" + "c" * 32, 180, 4.2, {}, "observation-loss")
assert original == before
assert base["robot"] == fault["robot"] and base["world"] == fault["world"]
assert "scenario" not in base["qualification"]
assert fault["qualification"]["scenario"]["name"] == "observation-loss"
assert len(fault["qualification"]["scenario"]["sha256"]) == 64
with pytest.raises(ValueError):
qualifier.prepare_run(original, "airun-" + "a" * 32, 180, 4.2, {}, "unknown")
+51
View File
@@ -0,0 +1,51 @@
import importlib.util
import json
import math
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location(
"rover_motion", ROOT / "simulation/ai-polygon/rover_motion.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
MOTION = json.loads(
(ROOT / "apps/control-station/public/rover-scene/dcd006-v020-motion.json").read_text()
)
def test_independent_tracks_stop_reverse_and_pivot():
phase = module.TrackPhase(MOTION)
phase.step(0.1, 0.3, -0.3)
left, right = dict(phase.distances), dict(phase.wheel_angles)
phase.step(0.1, 0, 0)
assert phase.distances == left
assert phase.wheel_angles == right
phase.step(0.1, -0.3, 0.3)
for side in ("L", "R"):
assert min(phase.distances[side], MOTION["length_m"] - phase.distances[side]) < 1e-9
for angle in phase.wheel_angles.values():
assert abs(math.sin(angle)) < 1e-9
def test_motion_matches_exported_gltf_rest_pose():
import struct
data = (ROOT / "apps/control-station/public/rover-scene/dcd006-v020-motion.glb").read_bytes()
size = struct.unpack_from("<I", data, 12)[0]
gltf = json.loads(data[20 : 20 + size])
nodes = {n["name"]: n for n in gltf["nodes"]}
for side in ("L", "R"):
for i in range(44):
position, angle = module.belt_pose(MOTION, 0, side, i)
node = nodes[f"{side}_BELT_{i:02d}"]
assert position == pytest.approx(node["translation"], abs=1e-6)
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
assert x == pytest.approx(0, abs=1e-6)
assert y == pytest.approx(0, abs=1e-6)
assert math.sin(angle) == pytest.approx(2 * z * w, abs=1e-6)
assert math.cos(angle) == pytest.approx(1 - 2 * z * z, abs=1e-6)
for wheel in MOTION["wheels"]:
assert wheel["node"] in nodes
+157
View File
@@ -0,0 +1,157 @@
"""Library editing never rewrites a route or erases evidence/worker ownership."""
import json
import pytest
from test_ai_polygon_realtime import realtime as _realtime
from k1link.simulation.ai_polygon.contracts import RunCreate
from k1link.simulation.ai_polygon.library import LibraryMetadata
realtime = _realtime
def make_plan(store, row):
return store.plans.create(
row,
"Trail",
[
{"id": "a" * 16, "position": [0, 0, 0]},
{"id": "b" * 16, "position": [2, 0, 0]},
],
0,
)
def test_rename_remove_restore_preserves_immutable_plan(realtime):
store, _, row = realtime
plan = make_plan(store, row)
identity = plan["plan_id"]
path = store.plans.root / (identity + ".json")
before = path.read_bytes()
store.update_library("plans", identity, {"display_name": "New trail"})
assert store.plans.visible_list()[0]["display_name"] == "New trail"
store.update_library("plans", identity, {"removed": True})
assert store.plans.visible_list() == []
# Metadata survives a fresh reader, while evidence remains byte-identical.
assert LibraryMetadata(store.plans.library.root).get(identity)["removed"]
assert path.read_bytes() == before
assert store.plans.get(identity) == plan
store.update_library("plans", identity, {"removed": False})
assert store.plans.visible_list()[0]["display_name"] == "New trail"
def test_removal_cannot_hide_worker_owner_and_keeps_terminal_evidence(realtime):
store, _, row = realtime
identity = row["run_id"]
with pytest.raises(RuntimeError, match="завершите"):
store.update_library("runs", identity, {"removed": True})
row["state"] = "stopped"
store._save(row)
with pytest.raises(RuntimeError, match="освобождения"):
store.update_library("runs", identity, {"removed": True})
store.active = None
before = (store.directory(identity) / "run.json").read_bytes()
store.update_library("runs", identity, {"removed": True})
assert store.library.visible(store.list(), "run_id") == []
assert (store.directory(identity) / "run.json").read_bytes() == before
store.update_library("runs", identity, {"removed": False})
assert store.library.visible(store.list(), "run_id")[0]["run_id"] == identity
def test_removed_plan_is_not_launchable_or_deduplicated(realtime):
store, _, row = realtime
plan = make_plan(store, row)
store.update_library("plans", plan["plan_id"], {"removed": True})
replacement = make_plan(store, row)
assert replacement["plan_id"] != plan["plan_id"]
row["state"] = "stopped"
store._save(row)
store.active = None
store.queue.release_simulation(row["run_id"])
with pytest.raises(ValueError, match="удалено"):
store.start(
RunCreate(world_id=row["world"]["world_id"], clock="realtime", plan_id=plan["plan_id"]),
"removed-plan-check",
)
def test_library_rejects_paths_and_unknown_records(realtime, tmp_path):
store, _, _ = realtime
with pytest.raises(FileNotFoundError):
store.update_library("plans", "aiplan-" + "f" * 32, {"removed": True})
with pytest.raises(FileNotFoundError):
store.library.update("../run", {"removed": True})
target = tmp_path / "outside.json"
target.write_text(json.dumps({"private": True}))
identity = "airun-" + "f" * 32
(store.library.root / (identity + ".json")).symlink_to(target)
with pytest.raises(ValueError, match="regular"):
store.library.update(identity, {"removed": True})
assert json.loads(target.read_text()) == {"private": True}
def test_library_api_validation_catalog_and_restart(realtime, tmp_path):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.ai_polygon_api import build_ai_polygon_router
store, _, row = realtime
plan = make_plan(store, row)
row["state"] = "stopped"
store._save(row)
api = "/api/v1/ai-polygon"
for iteration in range(2):
app = FastAPI()
app.include_router(build_ai_polygon_router(tmp_path))
with TestClient(app) as client:
if iteration == 0:
for invalid in (
{"display_name": " "},
{"display_name": "x" * 121},
{"removed": "yes"},
{"sha256": "tampered"},
):
assert (
client.patch(f"{api}/plans/{plan['plan_id']}", json=invalid).status_code
== 422
)
assert (
client.patch(
f"{api}/plans/{plan['plan_id']}",
json={"display_name": "Renamed", "removed": True},
).status_code
== 200
)
assert (
client.patch(f"{api}/runs/{row['run_id']}", json={"removed": True}).status_code
== 200
)
catalog = client.get(f"{api}/catalog").json()
assert not catalog["plans"] and not catalog["runs"]
assert client.get(f"{api}/runs/{row['run_id']}").json()["run_id"] == row["run_id"]
if iteration == 1:
client.patch(f"{api}/plans/{plan['plan_id']}", json={"removed": False})
restored = client.get(f"{api}/catalog").json()["plans"][0]
assert (
restored["display_name"] == "Renamed" and restored["sha256"] == plan["sha256"]
)
def test_run_snapshots_current_task_label_without_changing_route(realtime):
store, _, row = realtime
plan = make_plan(store, row)
store.update_library("plans", plan["plan_id"], {"display_name": "Renamed trail"})
row["state"] = "stopped"
store._save(row)
store.active = None
store.queue.release_simulation(row["run_id"])
run = store.start(
RunCreate(world_id=row["world"]["world_id"], clock="realtime", plan_id=plan["plan_id"]),
"renamed-plan-check",
)
assert run["plan_display_name"] == "Renamed trail"
assert run["plan"] == plan
store.update_library("plans", plan["plan_id"], {"display_name": "Another name"})
assert store.get(run["run_id"])["plan_display_name"] == "Renamed trail"
+89
View File
@@ -0,0 +1,89 @@
"""One catalog and artifact identity for local driving and route planning."""
import hashlib
import pytest
from test_ai_polygon_realtime import realtime as _realtime
from k1link.simulation.ai_polygon.contracts import RunCreate
from k1link.simulation.ai_polygon.editor_cache import EditorCache
from k1link.simulation.ai_polygon.worlds import WorldStore
from k1link.simulation.projects import _world_manifest
realtime = _realtime
def project_fixture(tmp_path):
worlds = WorldStore(tmp_path)
store = worlds.projects.projects
project = store.create(
name="Synthetic scan",
scene_type="outdoor",
source_kind="archive",
files=[{"logical_path": "scan.zip", "byte_length": 8}],
)
pid = project["project_id"]
assets = []
for role, name, data in [
("stream-manifest", "streamed/lod-meta.json", b'{"version":1}'),
("collision-mesh", "collision/scene.glb", b"synthetic-mesh"),
]:
path = store.artifacts_root(pid) / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
assets.append(
dict(
role=role,
logical_path=name,
media_type="application/octet-stream",
byte_length=len(data),
sha256=hashlib.sha256(data).hexdigest(),
)
)
project = store.complete(
pid, result={}, artifacts=assets, world_manifest=_world_manifest(pid, assets)
)
return worlds, project
def test_project_is_listed_once_and_reuses_full_streamed_sog(tmp_path):
worlds, project = project_fixture(tmp_path)
world = worlds.list()[0]
assert world["world_id"] == project["project_id"].replace("sim-", "aiworld-")
assert worlds.get(world["world_id"]) == world
cache = EditorCache(tmp_path, worlds)
row = cache.request(world["world_id"])
assert row["status"] == "ready"
assert row["local_scene"]["visual_url"].endswith("streamed/lod-meta.json")
assert cache.pending() is None # No Worker lease/converter required for an existing SOG.
assert not (cache.directory(row["key"]) / "scene.sog").exists()
assert cache.get(row["key"])["files"] == row["files"]
assert len(worlds.list()) == 1
def test_calibration_or_artifact_revision_invalidates_plan_identity(tmp_path):
worlds, project = project_fixture(tmp_path)
before = worlds.list()[0]
settings = project["viewer_settings"]
settings["visual"]["rotation_degrees"]["x"] = 90
worlds.projects.projects.update_viewer_settings(project["project_id"], settings)
after = worlds.get(before["world_id"])
assert before["sha256"] != after["sha256"]
assert EditorCache.identity(before) != EditorCache.identity(after)
with pytest.raises(FileNotFoundError):
worlds.get("../outside")
def test_project_requires_capable_worker_and_saved_task_before_gpu_reservation(tmp_path, realtime):
store, hello, active = realtime
store.finish(active["run_id"], hello.instance_id, "stopped", "")
worlds, _ = project_fixture(tmp_path)
# Select the project, independently of original PLY entries in the fixture.
world = next(w for w in worlds.list() if w.get("local_scene"))
request = RunCreate(world_id=world["world_id"], clock="realtime", start_paused=True)
with pytest.raises(RuntimeError, match="поддерживает SOG"):
store.start(request, "project-old-worker")
store.register(hello.model_copy(update={"scene_formats": ["gaussian-ply", "project-sog"]}))
with pytest.raises(ValueError, match="сохраните маршрут"):
store.start(request, "project-no-task")
assert store.active is None
+221
View File
@@ -0,0 +1,221 @@
import importlib.util
import sys
from pathlib import Path
import numpy as np
import pytest
from k1link.simulation.ai_polygon.driving_profiles import permitted_surface
ROOT = Path(__file__).parents[1] / "simulation/ai-polygon"
sys.path.insert(0, str(ROOT))
from inference_preview import InferencePreview # noqa: E402 - Worker adapter source path above.
from observer_camera import ObserverCamera # noqa: E402
def test_operator_camera_never_mutates_sensor_and_free_view_does_not_follow_rover():
camera = ObserverCamera()
body = [1.0, 2.0, 0.4]
sensor = [1.4, 2.0, 1.0]
original = sensor.copy()
camera.update("follow", body, 0, sensor)
input = dict(session="a" * 32, sequence=1, orbit=[0.7, 0.2], move=[0, 0, 0], zoom=0)
first = camera.update("camera", body, 0, sensor, input)
again = camera.update("camera", body, 0, sensor, input)
assert first == again
assert first[0] == sensor and sensor == original
assert first[1][1] > 2 # Operator sees sideways, sensor input stays unchanged.
free = camera.update("overview", body, 0, sensor)
other = camera.update("overview", [100, 100, 0.4], 1, [100, 100, 1])
assert free == other
changed = camera.update(
"overview", body, 0, sensor, dict(input, session="b" * 32, move=[0, 3, 0])
)
assert changed[0] != free[0]
def test_coalesced_camera_totals_apply_once():
def run(sequences):
camera = ObserverCamera()
camera.update("follow", [0, 0, 0], 0, [0, 0, 1])
for seq in sequences:
result = camera.update(
"follow",
[0, 0, 0],
0,
[0, 0, 1],
dict(
session="a" * 32,
sequence=seq,
orbit=[seq * 0.1, 0],
move=[0, 0, 0],
zoom=seq * 0.01,
),
)
return result
assert np.allclose(run([1, 2, 3])[0], run([3, 3])[0])
def test_park_rejects_lawn_and_urban_rejects_carriageway_without_overriding_model_confidence():
labels = np.array([[6, 11, 52, 9, 13, 2]])
candidates = np.ones_like(labels, dtype=bool)
assert permitted_surface(
labels, candidates, "park", "simulation-segformer-ade", {}
).tolist() == [[True, True, True, False, True, False]]
assert permitted_surface(
labels, candidates, "urban", "simulation-segformer-ade", {}
).tolist() == [[False, True, True, False, False, False]]
candidates[0, 0] = False
assert not permitted_surface(labels, candidates, "park", "simulation-segformer-ade", {})[0, 0]
with pytest.raises(ValueError):
permitted_surface(labels, candidates, "unknown", "simulation-segformer-ade", {})
def test_semantic_barrier_survives_smooth_ground_and_expires():
spec = importlib.util.spec_from_file_location(
"semantic_surface", ROOT / "navigation/semantic_surface.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
memory = module.SemanticSurface()
terrain = np.array([[1.01, 2.01, 0.0, 0.0], [2.0, 3.0, 0.0, 0.5]])
memory.observe([[1.01, 2.01, 0, 0]], 0)
assert memory.apply(terrain, 1)[0][0, 3] == 1
assert memory.apply(terrain, 31)[0][0, 3] == 0
memory.observe([[1.01, 2.01, 0, 1]], 32)
assert memory.apply(terrain, 32)[0][0, 3] == 0
assert memory.apply(terrain, 32)[0][1, 3] == 0.5 # Never erase geometric hazards.
def test_uncertain_path_is_not_a_persistent_obstacle_but_cannot_supply_a_goal():
from types import SimpleNamespace
from navigation_client import ComposedInference
from k1link.simulation.ai_polygon.mission_policy import WaypointMission
adapter = ComposedInference.__new__(ComposedInference)
adapter.environment = "park"
adapter.segmenter_id = "simulation-segformer-ade"
adapter.models = SimpleNamespace(labels={})
adapter.mission = WaypointMission([[2, 0]])
labels = np.full((512, 512), 13, dtype=np.uint8)
labels[:, :100] = 9 # A lawn is still an explicit profile exclusion.
output = adapter.plan_mission(
{
"segmentation.labels": labels,
"segmentation.surface": np.zeros_like(labels, dtype=bool),
"source.lidar": np.array([[x, y, 0] for x in [1.5, 2, 2.5] for y in [-0.2, 0, 0.2]]),
"source.pose": [0, 0, 0.37, 0, 0, 0, 1],
"source.simulation-time": 0,
"source.camera.calibration": {
"origin": [0.38, 0, 0.8],
"rotation": np.eye(3).reshape(-1).tolist(),
"intrinsics": [533, 533, 400, 300],
},
}
)
assert output["navigation.goal"] is None
assert not output["navigation.surface"].any()
assert output["navigation.permissions"][:, 100:].all()
assert not output["navigation.permissions"][:, :100].any()
def test_preview_contains_only_real_outputs_with_shared_frame_and_bounded_images(tmp_path):
import base64
import io
import json
from types import SimpleNamespace
from PIL import Image
directory = tmp_path / "camera"
directory.mkdir()
node = SimpleNamespace(
module=SimpleNamespace(
provides=("segmentation.labels", "navigation.surface", "detection.boxes")
),
inputs=(),
)
producer = InferencePreview(directory, SimpleNamespace(sha256="a" * 64, nodes=[node]), "park")
rgb = np.zeros((600, 800, 3), dtype=np.uint8)
values = {
"segmentation.labels": np.full((512, 512), 6, dtype=np.uint8),
"navigation.surface": np.ones((512, 512), dtype=bool),
"detection.boxes": [],
}
producer.publish(rgb, values, {"simulation_time_ns": 123456}, 7)
preview = json.loads((tmp_path / "inference-preview.json").read_text())
assert preview["frame_id"] == 7 and preview["simulation_time_ns"] == 123456
assert [p["id"] for p in preview["layers"]] == ["segmentation", "surface", "detection"]
for layer in preview["layers"]:
raw = base64.b64decode(layer["jpeg"])
assert len(raw) < 75000
assert Image.open(io.BytesIO(raw)).size == (400, 300)
producer.publish(rgb, values, {"simulation_time_ns": 123457}, 8)
assert json.loads((tmp_path / "inference-preview.json").read_text())["frame_id"] == 7
def test_operator_smoothing_converges_and_view_switch_does_not_fly_through_world():
from observer_camera import SmoothView
smoother = SmoothView()
start = [[0, 0, 0], [1, 0, 0], [0, 0, 1]]
goal = [[0, 10, 0], [1, 10, 0], [0, 0, 1]]
assert smoother.update("follow", start, 0) == start
middle = smoother.update("follow", goal, 0.04)
assert 0 < middle[0][1] < 10
settled = smoother.update("follow", goal, 1)
assert settled[0][1] == pytest.approx(10, abs=0.001)
assert smoother.update("camera", start, 1.1) == start
def test_preview_ports_follow_composition_not_incidental_values(tmp_path):
from types import SimpleNamespace
from k1link.simulation.ai_polygon.contracts import InferencePreview as PreviewContract
# This graph consumes only range/pose. Incidental segmentation is not an output.
node = SimpleNamespace(
module=SimpleNamespace(provides=("motion.command",)),
inputs=(("source.lidar", "source"), ("source.pose", "source")),
)
graph = SimpleNamespace(sha256="b" * 64, nodes=[node])
directory = tmp_path / "camera"
directory.mkdir()
values = {
"source.lidar": np.array([[10, 21, 3], [10, 22, 3]]),
"source.pose": [10, 20, 3, 0, 0, 2**-0.5, 2**-0.5],
"segmentation.labels": np.ones((512, 512)),
}
InferencePreview(directory, graph, "park").publish(
np.zeros((600, 800, 3), dtype=np.uint8), values, {"simulation_time_ns": 5}, 1
)
payload = PreviewContract.model_validate_json((tmp_path / "inference-preview.json").read_text())
assert [layer.id for layer in payload.layers] == ["lidar"]
layer = payload.layers[0]
assert layer.points == [(1, 0, 0), (2, 0, 0)]
assert layer.source_count == 2
assert layer.frame == "body-x-forward-y-left-z-up"
raw = payload.model_dump()
raw["layers"].append(dict(raw["layers"][0]))
with pytest.raises(ValueError, match="unique"):
PreviewContract.model_validate(raw)
# A new image-producing module can use its own ID without a UI/API enum edit.
image = {"id": "depth-confidence", "kind": "image", "label": "Depth", "jpeg": "YWJj"}
raw["layers"] = [image]
assert PreviewContract.model_validate(raw).layers[0].id == "depth-confidence"
raw["layers"] = [dict(image, kind="points3d")]
with pytest.raises(ValueError, match="Spatial"):
PreviewContract.model_validate(raw)
def test_lidar_display_sampling_never_mutates_inference_inputs():
from inference_preview import lidar
points = np.arange(9000, dtype=float).reshape(-1, 3)
original = points.copy()
result = lidar(None, {"source.lidar": points, "source.pose": [0, 0, 0, 0, 0, 0, 1]}, {})
assert len(result["points"]) <= 2048 and result["source_count"] == 3000
np.testing.assert_array_equal(points, original)
+29
View File
@@ -0,0 +1,29 @@
import importlib
from pathlib import Path
def test_native_audit_includes_first_step_and_detects_translation_and_roll(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
audit = importlib.import_module("sweep_qualification")
geometry = dict(
length_m=1.163, width_m=0.905, height_m=0.734, max_step_m=0.1, max_slope_degrees=25
)
rows = [
dict(
phase="hold",
dt=1 / 60,
request=[0, 0],
pre_step=dict(position=[0, 0, 0], heading=0),
position=[0, 0, 0],
quaternion_wxyz=[1, 0, 0, 0],
)
for _ in range(180)
]
assert audit.phase_metrics(rows, geometry)["passed"]
rows[0]["position"] = [0.1, 0, 0]
result = audit.phase_metrics(rows, geometry)
assert not result["passed"] and not result["windows"][0]["passed"]
rows[0]["position"] = [0, 0, 0]
rows[0]["quaternion_wxyz"] = [0.9659258263, 0.2588190451, 0, 0]
assert not audit.phase_metrics(rows, geometry)["passed"]
assert not audit.phase_metrics(rows[:10], geometry)["passed"]
+289
View File
@@ -0,0 +1,289 @@
"""Physical invariants of the aggregate belts, separate from native Isaac rigs."""
import importlib
import json
from pathlib import Path
import numpy as np
import pytest
@pytest.fixture
def model(monkeypatch):
root = Path(__file__).parents[1] / "simulation/ai-polygon"
monkeypatch.syspath_prepend(str(root))
profile = json.loads((root / "robots/dcd006-v020.json").read_text())
return importlib.import_module("track_dynamics").TrackDynamics(profile["tracked_contact"], 100)
def support(friction=0.8):
return [
(side, np.array([x, y, -0.37]), np.array([0, 0, 1]), 981 / 10, friction)
for side, y in enumerate((0.3425, -0.3425))
for x in np.linspace(-0.35, 0.35, 5)
]
def advance(model, target, contacts, linear=(0, 0, 0), angular=(0, 0, 0), mode="drive"):
return model.step(target, contacts, np.eye(3), linear, angular, np.zeros(3), 1 / 60, mode)
def test_airborne_tracks_cannot_push_the_body(model):
for _ in range(300):
force, torque, row = advance(model, [0.3, -0.3], [])
assert np.array_equal(force, [0, 0, 0]) and np.array_equal(torque, [0, 0, 0])
assert model.belt_mps == pytest.approx([0.3, -0.3])
assert row["normal_load_n"] == [0, 0]
def test_zero_friction_removes_traction_even_with_power(model):
model.belt_mps[:] = [0.3, 0.1]
force, torque, _ = advance(model, [0.3, 0.1], support(0))
assert np.array_equal(force, [0, 0, 0]) and np.array_equal(torque, [0, 0, 0])
def test_predictor_gravity_and_support_are_not_applied_twice(model):
force, torque, _ = model.step(
[0.3, 0.3],
[],
np.eye(3),
np.zeros(3),
np.zeros(3),
np.zeros(3),
1 / 60,
external_wrench=[0, 0, -981, 0, 0, 0],
)
assert np.array_equal(force, [0, 0, 0]) and np.array_equal(torque, [0, 0, 0])
previous = model.belt_mps.copy()
with pytest.raises(ValueError, match="external predictor"):
model.step(
[0.3, 0.3],
[],
np.eye(3),
np.zeros(3),
np.zeros(3),
np.zeros(3),
1 / 60,
external_wrench=[0, 0, float("nan"), 0, 0, 0],
)
assert np.array_equal(model.belt_mps, previous)
def test_contact_is_passive_and_obeys_one_friction_circle(model):
model.belt_mps[:] = [0.4, -0.4]
force, torque, row = advance(model, [0, 0], support(), (0.1, 0.2, 0), (0, 0, 0.3), "coast")
assert row["motor_force_n"] == [0, 0]
assert row["motor_power_w"] == 0
assert row["slip_power_w"] <= 0
assert np.linalg.norm(force) <= 0.8 * 981 + 1e-8
assert np.isfinite(torque).all()
def test_motor_torque_and_power_caps_act_on_the_two_belts(model):
model.belt_mps[:] = [5, -5]
_, _, row = advance(model, [10, -10], [])
assert 0 < row["motor_power_w"] <= 1000 + 1e-8
maximum = (
model.profile["max_drive_torque_nm"] / model.profile["drive_sprocket_effective_radius_m"]
)
assert max(map(abs, row["motor_force_n"])) <= maximum
assert (
max(map(abs, row["motor_force_n"])) < maximum * 0.4
) # Power, not stall torque, limits it.
def test_brake_dissipates_rotating_belts_while_coast_preserves_airborne_momentum(model):
model.belt_mps[:] = [0.3, -0.3]
advance(model, [0, 0], [], mode="coast")
assert model.belt_mps == pytest.approx([0.3, -0.3])
for _ in range(60):
_, _, row = advance(model, [0, 0], [], mode="brake")
assert row["motor_power_w"] <= 0
assert max(abs(model.belt_mps)) < 1e-8
def test_symmetry_and_difference_produce_forces_without_a_yaw_setter(model):
model.belt_mps[:] = [0.3, 0.3]
force, torque, _ = advance(model, [0.3, 0.3], support())
assert force[0] > 0 and abs(torque[2]) < 1e-8
model.belt_mps[:] = [0.1, 0.3]
_, torque, _ = advance(model, [0.1, 0.3], support(), linear=(0.2, 0, 0))
assert torque[2] > 0
def test_unsupported_time_steps_fail_without_mutating_belts(model):
for dt in (0, -0.1, 1, float("nan")):
with pytest.raises(ValueError):
model.step([0.3, 0.3], [], np.eye(3), np.zeros(3), np.zeros(3), np.zeros(3), dt)
assert np.array_equal(model.belt_mps, [0, 0])
def test_speed_regulation_rejects_contact_load_without_unbounded_integral(model):
for _ in range(10000):
_, _, row = model.step(
[0.02, 0.02], support(), np.eye(3), np.zeros(3), np.zeros(3), np.zeros(3), 0.001
)
assert model.belt_mps == pytest.approx([0.02, 0.02], abs=1e-4)
assert min(row["motor_force_n"]) > 100
for _ in range(120):
advance(model, [50, 50], support())
cap = model.profile["max_drive_torque_nm"] / model.profile["drive_sprocket_effective_radius_m"]
assert max(abs(model.integral_force_n)) <= cap
_, _, row = advance(model, [0, 0], support(), mode="coast")
assert row["motor_force_n"] == [0, 0]
assert row["speed_integral_force_n"] == [0, 0]
def test_bad_rotation_and_contact_state_fail_before_changing_belts(model):
for rotation in (np.eye(2), np.diag([1, 1, -1]), np.eye(3) * 2):
with pytest.raises(ValueError):
model.step([0.3, 0.3], [], rotation, np.zeros(3), np.zeros(3), np.zeros(3), 1 / 60)
for point in ([0, 0], [0, float("nan"), 0]):
with pytest.raises(ValueError):
advance(model, [0.3, 0.3], [(0, point, [0, 0, 1], 100, 0.8)])
assert np.array_equal(model.belt_mps, [0, 0])
def test_native_query_callback_failure_is_not_reported_as_missing_support(monkeypatch):
from types import SimpleNamespace
root = Path(__file__).parents[1] / "simulation/ai-polygon"
monkeypatch.syspath_prepend(str(root))
cls = importlib.import_module("tracked_rover").TrackedDrive
drive = object.__new__(cls)
drive.root_path = "/World/Rover"
drive.query = SimpleNamespace(
raycast_all=lambda origin, direction, distance, callback, **kw: callback(object())
)
with pytest.raises(RuntimeError, match="Track support query failed"):
drive.ground_hit(np.zeros(3), np.array([0, 0, 1]))
def test_native_query_ignores_rover_and_copies_closest_surface(monkeypatch):
from types import SimpleNamespace
root = Path(__file__).parents[1] / "simulation/ai-polygon"
monkeypatch.syspath_prepend(str(root))
cls = importlib.import_module("tracked_rover").TrackedDrive
drive = object.__new__(cls)
drive.root_path = "/World/Rover"
def query(origin, direction, distance, callback, **kwargs):
for path, length in (
("/World/Rover/chassis/left_belt", 0),
("/World/Other", 0.03),
("/World/Ground", 0.02),
):
callback(
SimpleNamespace(
collision=path, distance=length, position=(0, 0, 0), normal=(0, 0, 1)
)
)
drive.query = SimpleNamespace(raycast_all=query)
assert drive.ground_hit(np.zeros(3), np.array([0, 0, 1]))["collision"] == "/World/Ground"
def test_turning_does_not_reclassify_previous_contact_as_chassis_gap(monkeypatch):
root = Path(__file__).parents[1] / "simulation/ai-polygon"
monkeypatch.syspath_prepend(str(root))
classify = importlib.import_module("tracked_rover").belt_contact_side
# Native frame: right belt's rear inner corner, exactly on the CAD edge.
point = np.array([-0.462, -0.2325, -0.37])
old_centre, old_rotation = np.zeros(3), np.eye(3)
yaw = 0.29 / 60
current_rotation = np.array(
[[np.cos(yaw), -np.sin(yaw), 0], [np.sin(yaw), np.cos(yaw), 0], [0, 0, 1]]
)
current_centre = np.array([0.036, -0.053, 0]) / 60
assert classify(point, current_centre, current_rotation, 0.465) is None
assert classify(point, old_centre, old_rotation, 0.465) == 1
assert classify(point * [1, -1, 1], old_centre, old_rotation, 0.465) == 0
assert classify(np.array([0, 0, -0.24]), old_centre, old_rotation, 0.465) is None
def test_held_belt_does_not_receive_second_custom_traction_force(model):
model.belt_mps[:] = [0.002, -0.002]
force, torque, row = model.step(
[0, 0],
support(),
np.eye(3),
[0.2, 0, 0],
[0, 0, 0.1],
np.zeros(3),
1 / 60,
"hold",
held_sides=[True, True],
)
assert row["belt_mps"] == [0, 0]
assert row["motor_force_n"] == [0, 0]
assert row["lock_capture_energy_j"] < 0.001
assert np.array_equal(force, [0, 0, 0]) and np.array_equal(torque, [0, 0, 0])
def test_held_side_does_not_stop_independent_driven_side(model):
for _ in range(120):
_, _, row = model.step(
[0, 0.2],
[],
np.eye(3),
np.zeros(3),
np.zeros(3),
np.zeros(3),
1 / 60,
held_sides=[True, False],
)
assert row["belt_mps"][0] == 0 and row["belt_mps"][1] > 0.19
before = model.belt_mps.copy()
with pytest.raises(ValueError, match="held side"):
model.step(
[0.2, 0.2],
[],
np.eye(3),
np.zeros(3),
np.zeros(3),
np.zeros(3),
1 / 60,
held_sides=[True, False],
)
assert np.array_equal(model.belt_mps, before)
def test_hold_material_has_finite_capacity_and_releases_when_driving(model):
coefficients = importlib.import_module("tracked_rover").hold_material_coefficients
assert coefficients(model.profile, 500, False) == (0, 0)
static, dynamic = coefficients(model.profile, 500, True)
assert static == 0.9 and dynamic == 0.8
static, dynamic = coefficients(model.profile, 5000, True)
assert 0 < dynamic <= static < 0.8
assert static * 5000 * model.profile["drive_sprocket_effective_radius_m"] == pytest.approx(50)
@pytest.mark.parametrize("sample_xs", [[], [0.2, 0.4]])
def test_irregular_support_keeps_native_loads_and_full_centre_of_pressure(model, sample_xs):
patch = importlib.import_module("tracked_rover").pressure_patch
normal = np.array([0, 0, 1.0])
records = [
(np.array([-0.3, 0.24, -0.36]), normal, 300.0, 0.7),
(np.array([0.3, 0.44, -0.34]), normal, 100.0, 0.8),
]
samples = [(x, np.array([x, 0.34, -0.35]), normal, 0.8) for x in sample_xs]
contacts, fallback = patch(0, records, samples, -0.15)
assert fallback
assert len(contacts) == len(records)
assert sum(c[3] for c in contacts) == 400
assert sum(c[1] * c[3] for c in contacts) / 400 == pytest.approx([-0.15, 0.29, -0.355])
for contact, record in zip(contacts, records, strict=True):
assert np.array_equal(contact[1], record[0])
assert contact[3:] == record[2:]
def test_resolved_pressure_line_still_preserves_measured_load_and_longitudinal_cop(model):
patch = importlib.import_module("tracked_rover").pressure_patch
normal = np.array([0, 0, 1.0])
records = [(np.array([0.1, 0.34, -0.37]), normal, 490.5, 0.8)]
samples = [(x, np.array([x, 0.34, -0.37]), normal, 0.8) for x in np.linspace(-0.3, 0.3, 9)]
contacts, fallback = patch(0, records, samples, 0.1)
assert not fallback
assert sum(c[3] for c in contacts) == pytest.approx(490.5)
assert sum(c[1][0] * c[3] for c in contacts) / 490.5 == pytest.approx(0.1, abs=1e-6)