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
+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 == {}