import ast from functools import lru_cache import hashlib import json import math import os from pathlib import Path import shlex import subprocess import tempfile import types import numpy as np APP = Path(os.environ.get("TBENCH_APP_ROOT", "/app")) TEST_ROOT = Path(os.environ.get("TBENCH_TEST_ROOT", "/tests")) PROJECT = APP / "vendor/robotics-toolbox-python" IK_PATH = PROJECT / "src/roboticstoolbox/robot/IK.py" CPP_PATH = PROJECT / "src/roboticstoolbox/ets/cpp-extensions/ik.cpp" ARTIFACT = APP / "output.json" @lru_cache(maxsize=1) def load_solver_class(): tree = ast.parse(IK_PATH.read_text()) solver = next( node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "IKSolver" ) imports = [ ast.parse("import numpy as np").body[0], ast.parse("from abc import ABC, abstractmethod").body[0], ] namespace = { "__name__": "submitted_ik", "rtb": types.SimpleNamespace(), "SE3": object, "IKSolution": object, "Tuple": tuple, "cast": lambda _, value: value, "ArrayLike": object, "NDArray": np.ndarray, } exec( compile( ast.Module(body=imports + [solver], type_ignores=[]), str(IK_PATH), "exec", ), namespace, ) solver_class = namespace["IKSolver"] solver_class.__abstractmethods__ = frozenset() return solver_class class CountingRng: def __init__(self, seed): self.generator = np.random.default_rng(seed) self.calls = 0 def uniform(self, *args, **kwargs): self.calls += 1 return self.generator.uniform(*args, **kwargs) def sha256(path): return hashlib.sha256(path.read_bytes()).hexdigest() def submitted_rand_q_source(): source = CPP_PATH.read_text() signature = "void _rand_q(" start = source.index(signature) opening = source.index("{", start) depth = 0 for index in range(opening, len(source)): if source[index] == "{": depth += 1 elif source[index] == "}": depth -= 1 if depth == 0: return source[start : index + 1] raise AssertionError("unable to isolate submitted _rand_q definition") def test_gate_artifact_schema_and_hashes(): assert ARTIFACT.is_file() data = json.loads(ARTIFACT.read_text()) assert data["schema_version"] == "robotics.ik_restart_validation.v1" assert set(data) == {"schema_version", "python", "native_cpp", "source_sha256"} assert data["source_sha256"] == { "src/roboticstoolbox/robot/IK.py": sha256(IK_PATH), "src/roboticstoolbox/ets/cpp-extensions/ik.cpp": sha256(CPP_PATH), } def test_gate_protected_source_assets(): expected = json.loads((TEST_ROOT / "fixtures/immutable_hashes.json").read_text()) for relative, digest in expected.items(): path = APP / relative assert path.is_file(), relative assert sha256(path) == digest, relative def test_core_python_seeded_sampling_matches_independent_recompute(): solver_class = load_solver_class() solver = object.__new__(solver_class) solver._private_random = CountingRng(9137) qlim = np.array([[-2.5, 0.125, 4.0, -8.0], [1.5, 0.125, 9.0, -3.0]]) ets = types.SimpleNamespace(n=4, qlim=qlim) actual = solver._random_q(ets, 11) reference_rng = np.random.default_rng(9137) expected = np.zeros((11, 4)) for row in range(11): for joint in range(4): expected[row, joint] = reference_rng.uniform( qlim[0, joint], qlim[1, joint] ) assert actual.shape == (11, 4) assert np.isfinite(actual).all() assert np.all(actual >= qlim[0]) and np.all(actual <= qlim[1]) assert np.all(actual[:, 1] == 0.125) assert np.allclose(actual, expected, rtol=0.0, atol=1e-14) def test_core_python_rejects_all_nonfinite_endpoints_before_rng(): solver_class = load_solver_class() cases = [ (np.array([[-1.0, math.inf], [1.0, 2.0]]), "1"), (np.array([[-math.inf, 0.0], [1.0, 2.0]]), "0"), (np.array([[-1.0, 0.0], [math.nan, 2.0]]), "0"), ] for qlim, joint_text in cases: solver = object.__new__(solver_class) solver._private_random = CountingRng(44) ets = types.SimpleNamespace(n=2, qlim=qlim) try: solver._random_q(ets, 5) except ValueError as error: message = str(error).lower() assert "joint" in message assert "limit" in message assert "finite" in message assert joint_text in message else: raise AssertionError("non-finite qlim was accepted") assert solver._private_random.calls == 0 def test_core_native_cpp_sampler_compiles_and_runs(): fixture = TEST_ROOT / "fixtures/native_guard_probe.cpp" with tempfile.TemporaryDirectory(prefix="native-ik-verifier-") as directory: directory_path = Path(directory) executable = directory_path / "native_guard_probe" marker = "// __RAND_Q_FUNCTION__" template = fixture.read_text() assert marker in template generated_source = directory_path / "native_guard_probe.cpp" generated_source.write_text( template.replace(marker, submitted_rand_q_source(), 1) ) includes = shlex.split( subprocess.check_output(["python3-config", "--includes"], text=True) ) ldflags = shlex.split( subprocess.check_output( ["python3-config", "--embed", "--ldflags"], text=True ) ) command = [ os.environ.get("CXX", "g++"), "-std=c++17", "-O0", "-ffunction-sections", "-fdata-sections", f"-I{PROJECT / 'src/roboticstoolbox/ets/cpp-extensions'}", *includes, str(generated_source), "-Wl,--gc-sections", *ldflags, "-o", str(executable), ] subprocess.run(command, cwd=PROJECT, check=True, timeout=90) result = subprocess.run( [str(executable)], check=True, capture_output=True, text=True, timeout=15 ) assert result.stdout.strip() == "native-guard-ok" def test_edge_multiple_invalid_python_joints_are_diagnostic(): solver_class = load_solver_class() solver = object.__new__(solver_class) solver._private_random = CountingRng(7) ets = types.SimpleNamespace( n=4, qlim=np.array( [[-1.0, -math.inf, 2.0, 3.0], [1.0, 4.0, math.nan, math.inf]] ), ) try: solver._random_q(ets, 1) except ValueError as error: message = str(error).lower() assert "1" in message and "2" in message and "3" in message assert "inf" in message and "nan" in message else: raise AssertionError("multiple invalid joints were accepted") assert solver._private_random.calls == 0 def test_edge_artifact_reports_executed_integration_results(): data = json.loads(ARTIFACT.read_text()) assert data["python"] == { "shape": [9, 3], "finite": True, "bounded": True, "zero_width_preserved": True, "invalid_rejected_before_rng": True, } assert data["native_cpp"] == { "finite": True, "bounded": True, "zero_width": True, "invalid_rejected_before_rng": True, }