Keep safety mutation runs isolated and bounded

This commit is contained in:
firestar5683
2026-11-12 02:42:07 -06:00
parent 7e6d08187b
commit b47f8b6133
4 changed files with 74 additions and 20 deletions
@@ -11,7 +11,7 @@ from opendbc.safety import LEN_TO_DLC
libsafety_dir = os.path.dirname(os.path.abspath(__file__))
def _build_libsafety(release: bool = False) -> str:
def _build_libsafety(release: bool = False, output_dir: str | Path | None = None) -> str:
"""Compile libsafety.so to a temp file and return its path."""
root = str(Path(libsafety_dir).parents[3])
safety_c = os.path.join(libsafety_dir, "safety.c")
@@ -30,13 +30,20 @@ def _build_libsafety(release: bool = False) -> str:
if not release:
cflags += ['-DALLOW_DEBUG']
fd, safety_os = tempfile.mkstemp(suffix='.os', dir=libsafety_dir)
fd, safety_os = tempfile.mkstemp(suffix='.os', dir=output_dir or libsafety_dir)
os.close(fd)
fd, libsafety_so = tempfile.mkstemp(suffix='.so')
os.close(fd)
subprocess.check_call(['cc', '-fPIC', *cflags, '-I', root, '-c', safety_c, '-o', safety_os])
subprocess.check_call(['cc', '-shared', safety_os, '-o', libsafety_so, *ldflags])
libsafety_so = None
try:
fd, libsafety_so = tempfile.mkstemp(suffix='.so', dir=output_dir)
os.close(fd)
subprocess.check_call(['cc', '-fPIC', *cflags, '-I', root, '-c', safety_c, '-o', safety_os])
subprocess.check_call(['cc', '-shared', safety_os, '-o', libsafety_so, *ldflags])
except BaseException:
if libsafety_so is not None:
Path(libsafety_so).unlink(missing_ok=True)
raise
finally:
Path(safety_os).unlink(missing_ok=True)
return libsafety_so
+16 -6
View File
@@ -476,7 +476,11 @@ def build_priority_tests(site, catalog, core_tests):
family_modules = [name for name in sorted(catalog) if name == f"test_{family}.py" or name.startswith(f"test_{family}_") or
(family == "ford" and name == "test_angle_native.py")]
if family_modules:
return [test_id for name in family_modules for test_id in catalog[name]]
targets = [test_id for name in family_modules for test_id in catalog[name]]
if family == "honda":
targets.sort(key=lambda target: not target.endswith((".test_all_stock_honda_rx_callbacks_finish_without_native_memory_faults",
".test_all_zero_commands_finish_without_native_memory_faults")))
return targets
# Unmapped mode files still exercise the full safety suite rather than receive zero targets.
return [test_id for name in sorted(catalog) for test_id in catalog[name]]
return core_tests
@@ -607,18 +611,23 @@ def _run_pytest(targets):
debug_root = None
debug_libraries = []
release_template = None
native_copy_count = 0
def fixture_native(release=False):
if release:
return build_native(release=True)
nonlocal release_template, native_copy_count
if native is None or native_path is None or debug_root is None:
raise RuntimeError("pytest Debug mutation context is unavailable")
if native.mutation_get_active_mutant() != active_mutant:
raise RuntimeError("pytest fixture changed the active Debug mutant")
path = debug_root / f"debug-{len(debug_libraries)}.so"
shutil.copyfile(native_path, path)
if release and release_template is None:
release_template = build_native(release=True, output_dir=debug_root)
path = debug_root / f"{'release' if release else 'debug'}-{native_copy_count}.so"
native_copy_count += 1
shutil.copyfile(release_template if release else native_path, path)
library = libsafety_py.ffi.dlopen(str(path))
library.mutation_set_active_mutant(active_mutant)
if not release:
library.mutation_set_active_mutant(active_mutant)
debug_libraries.append(library)
return str(path)
@@ -648,6 +657,7 @@ def run_unittest(targets, lib_path, mutant_id, verbose):
unittest_targets = [target for target in targets if not target.startswith("pytest:")]
pytest_targets = [target for target in targets if target.startswith("pytest:")]
class LazyTargets(unittest.TestSuite):
_cleanup = False
_result: unittest.TestResult | None = None
@@ -89,7 +89,7 @@ class TestMutationInfrastructureAccounting(unittest.TestCase):
source = """import pytest
from opendbc.car import structs
from opendbc.safety.tests.libsafety import libsafety_py
@pytest.fixture(params=(False, False, True), ids=('DEBUG_A', 'DEBUG_B', 'RELEASE'))
@pytest.fixture(params=(False, False, True, True), ids=('DEBUG_A', 'DEBUG_B', 'RELEASE_A', 'RELEASE_B'))
def native_variant(request):
previous = libsafety_py.libpath
libsafety_py.load(libsafety_py._build_libsafety(release=request.param))
@@ -98,18 +98,18 @@ def native_variant(request):
finally:
libsafety_py.load(previous)
def test_native_variant(native_variant):
assert not libsafety_py.libsafety.get_controls_allowed()
libsafety_py.libsafety.set_controls_allowed(True)
if native_variant:
assert libsafety_py.libsafety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) != 0
with pytest.raises(AttributeError):
libsafety_py.libsafety.mutation_get_active_mutant()
else:
assert libsafety_py.libsafety.mutation_get_active_mutant() == 73
assert not libsafety_py.libsafety.get_controls_allowed()
libsafety_py.libsafety.set_controls_allowed(True)
"""
release = libsafety_py._build_libsafety(release=True)
with TemporaryDirectory() as directory, patch.dict(libsafety_py.__dict__):
root = Path(directory)
release = libsafety_py._build_libsafety(release=True, output_dir=root)
debug = root / "instrumented.so"
fixture_source = "\n".join(("#include <stdbool.h>", "static bool fixture_controls;",
"void set_controls_allowed(bool value) { fixture_controls = value; }",
@@ -121,20 +121,57 @@ def test_native_variant(native_variant):
target = root / "test_native_variant.py"
target.write_text(source)
builds = []
build_roots = []
def build_variant(release=False):
def build_variant(release=False, output_dir=None):
self.assertIsNotNone(output_dir)
self.assertTrue(release, "active Debug library must not be rebuilt")
builds.append(release)
build_roots.append(Path(output_dir))
return release_library
release_library = release
with patch.object(libsafety_py, "_build_libsafety", side_effect=build_variant):
result = mutation._run_pytest(["pytest:" + str(target)])
self.assertEqual((result.ran, result.skipped, result.failures, result.errors), (3, 0, (), ()), result.output_tail)
self.assertEqual((result.ran, result.skipped, result.failures, result.errors), (4, 0, (), ()), result.output_tail)
self.assertEqual(builds, [True])
self.assertTrue(all(not path.exists() for path in build_roots))
self.assertTrue(Path(release).is_file())
self.assertEqual(libsafety_py.libsafety.mutation_get_active_mutant(), 73)
self.assertTrue(libsafety_py.libsafety.get_controls_allowed())
def test_native_build_removes_objects_and_failed_outputs(self):
with TemporaryDirectory() as directory:
root = Path(directory)
library = Path(libsafety_py._build_libsafety(release=True, output_dir=root))
self.assertEqual(list(root.iterdir()), [library])
library.unlink()
for calls in ((RuntimeError("compiler failed"),), (None, RuntimeError("compiler failed"))):
with self.subTest(calls=len(calls)), patch.object(libsafety_py.subprocess, "check_call", side_effect=calls):
with self.assertRaisesRegex(RuntimeError, "compiler failed"):
libsafety_py._build_libsafety(output_dir=root)
self.assertEqual(list(root.iterdir()), [])
make_temp = libsafety_py.tempfile.mkstemp
def fail_shared_output(*args, **kwargs):
if kwargs.get("suffix") == ".so":
raise OSError("output allocation failed")
return make_temp(*args, **kwargs)
with patch.object(libsafety_py.tempfile, "mkstemp", side_effect=fail_shared_output):
with self.assertRaisesRegex(OSError, "output allocation failed"):
libsafety_py._build_libsafety(output_dir=root)
self.assertEqual(list(root.iterdir()), [])
def test_honda_callback_probes_precede_in_process_native_calls(self):
site = mutation.MutationSite(1, 0, 1, 0, 1, 1, "==", "!=", "comparison", mutation.SAFETY_DIR / "modes/honda.h", 1)
probe = "test_honda_interceptor.TestHondaInterceptor.test_all_stock_honda_rx_callbacks_finish_without_native_memory_faults"
catalog = {"test_honda.py": ["test_honda.TestHonda.test_rx_hook"], "test_honda_interceptor.py": [probe]}
expected = [target for targets in catalog.values() for target in targets]
ordered = mutation.build_priority_tests(site, catalog, expected)
self.assertEqual(Counter(ordered), Counter(expected))
self.assertEqual(ordered[0], probe)
def test_worker_crash_is_infrastructure_error(self):
site = self.site()
future = Future()
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "4aa43fd77d78ff9853fe2e08ff057da2ef47b2eb731593c09703d27c2961fa38", "schema_version": 1}
{"protected_inventory_sha256": "d66a99fa44445564a35b15c26a219b62a01a182b536705529878767576ec1d75", "schema_version": 1}