From 33818c84eba29ff27a0918e1a3bcb9a5e85f672c Mon Sep 17 00:00:00 2001 From: firestar5683 <168790843+firestar5683@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:47:54 -0600 Subject: [PATCH] Preserve compatible FLM tunes and scan larger drive libraries --- openpilot/selfdrive/controls/controlsd.py | 3 +- openpilot/starpilot/flm/manual_coordinates.py | 69 ++++++-- openpilot/starpilot/flm/offroad_cache.py | 2 +- openpilot/starpilot/flm/offroad_processor.py | 11 +- openpilot/starpilot/flm/offroad_route.py | 6 +- openpilot/starpilot/flm/offroad_runtime.py | 14 +- openpilot/starpilot/flm/offroad_store.py | 5 +- .../starpilot/flm/runtime_adapter_registry.py | 48 +++--- .../starpilot/flm/steering_compatibility.py | 54 +++++++ .../flm/tests/test_offroad_backend.py | 2 +- .../flm/tests/test_offroad_cache_retention.py | 13 +- .../tests/test_offroad_coordinate_policy.py | 10 +- .../flm/tests/test_offroad_fault_isolation.py | 15 ++ .../tests/test_offroad_process_lifecycle.py | 3 +- .../flm/tests/test_steering_compatibility.py | 75 +++++++++ openpilot/starpilot/galaxy/drive_history.py | 7 +- openpilot/starpilot/galaxy/flm_backup.py | 149 ++++++++++++++++-- .../galaxy/tests/test_drive_history.py | 13 ++ .../starpilot/galaxy/tests/test_flm_backup.py | 111 ++++++++++++- .../galaxy/tests/test_flm_review.mjs | 2 +- .../galaxy/tests/test_flm_ux_browser.mjs | 37 ++++- .../starpilot/galaxy/web/js/flm-backup.js | 13 +- openpilot/starpilot/galaxy/web/js/flm.js | 10 +- openpilot/starpilot/ui/torque_feature.py | 26 ++- prebuilt.json | 2 +- 25 files changed, 604 insertions(+), 96 deletions(-) create mode 100644 openpilot/starpilot/flm/steering_compatibility.py create mode 100644 openpilot/starpilot/flm/tests/test_steering_compatibility.py diff --git a/openpilot/selfdrive/controls/controlsd.py b/openpilot/selfdrive/controls/controlsd.py index f39af5c25b..5dae5dc1ea 100755 --- a/openpilot/selfdrive/controls/controlsd.py +++ b/openpilot/selfdrive/controls/controlsd.py @@ -152,7 +152,8 @@ class Controls: ) if isinstance(self.LaC, LatControlTorque): # Only the actual startup owner reads configuration; replay clones stay pure. - if manual_effects is not None and manual_effects.profile.context[1] != str(self.LaC.controller_mode): + if manual_effects is not None and (manual_effects.profile.context[1] != str(self.LaC.controller_mode) or + not manual_effects.compatible(self.CP, self.CI, self.LaC, self.params)): manual_effects, manual_status = None, 'context_changed' self.LaC.manual_flm_effects, self.LaC.manual_flm_status = manual_effects, manual_status self.lateral_gain_owner = create_gain_owner(self.params, self.CP, self.LaC) diff --git a/openpilot/starpilot/flm/manual_coordinates.py b/openpilot/starpilot/flm/manual_coordinates.py index 4dc88bdace..6dd2ffde7a 100644 --- a/openpilot/starpilot/flm/manual_coordinates.py +++ b/openpilot/starpilot/flm/manual_coordinates.py @@ -9,53 +9,82 @@ import time from openpilot.starpilot.flm.canonical_surface_adapter import NAMES, MANIFEST_SHA256, coordinate_bounds -def context(cp, controller): +def context(cp, controller, *, recovered=False): from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest from openpilot.starpilot.lateral.controller_selection import ControllerMode if (str(cp.steerControlType) != 'torque' or cp.lateralTuning.which() != 'torque' or cp.passive or cp.notCar or cp.dashcamOnly): raise ValueError('Manual coordinates require an active torque controller') - return car_params_digest(cp), str(ControllerMode(controller)), MANIFEST_SHA256 + from openpilot.starpilot.flm.offroad_surface import ROUTE_MANIFEST_SHA256 + return car_params_digest(cp), str(ControllerMode(controller)), ROUTE_MANIFEST_SHA256 if recovered else MANIFEST_SHA256 + + +def baseline_settings(cp, params): + """Selected scalar/gain/geometry policy, excluding the recovered coordinates.""" + from dataclasses import replace + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, MAX_DOCUMENT_BYTES, parse_document, serialize_document, PlatformProfile, FieldChoice + from openpilot.starpilot.saved_source import read_saved + raw, readable = read_saved(params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) + if not readable: + raise ValueError('Readable selected baseline settings required') + tune = cp.lateralTuning.torque + basis = (float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction)) + fingerprint = str(cp.carFingerprint) + profiles = {} if raw is None else parse_document(raw) + profile = profiles.get(fingerprint, PlatformProfile(basis, FieldChoice(), FieldChoice())) + return hashlib.sha256(serialize_document({fingerprint: replace(profile, manual_coordinates=None)})).hexdigest() @dataclass(frozen=True) class ManualCoordinates: context: tuple[str, str, str] values: tuple[tuple[str, float], ...] + compatibility: str = '' def validate(self): + from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES, route_bounds, RouteSurfaceEffects + recovered = bool(self.compatibility) + names = ROUTE_NAMES if recovered else NAMES + if recovered and (type(self.compatibility) is not str or len(self.compatibility) != 64 or self.compatibility.strip('0123456789abcdef')): + raise ValueError('Recovered manual tune needs its selected steering identity') if (type(self.context) is not tuple or len(self.context) != 3 or any(type(v) is not str for v in self.context) or any(len(self.context[i]) != 64 or self.context[i].strip('0123456789abcdef') for i in (0, 2)) or not self.context[1] or len(self.context[1]) > 32 or not self.context[1].isascii() - or type(self.values) is not tuple or len(self.values) != len(NAMES)): + or type(self.values) is not tuple or len(self.values) != len(names)): raise ValueError('Invalid manual coordinate context') from openpilot.starpilot.lateral.controller_selection import ControllerMode ControllerMode(self.context[1]) - for name, row in zip(NAMES, self.values, strict=True): + for name, row in zip(names, self.values, strict=True): if type(row) is not tuple or len(row) != 2 or row[0] != name: raise ValueError('Exactly thirty ordered manual coordinates required') - low, high = coordinate_bounds(name) + low, high = route_bounds(name) if recovered else coordinate_bounds(name) if type(row[1]) not in (int, float) or not math.isfinite(row[1]) or not low <= row[1] <= high: raise ValueError('Manual coordinate outside the selected envelope') # Validate the complete composed surface as well as each individual value. from openpilot.starpilot.flm.canonical_surface_adapter import CanonicalSurfaceEffects - CanonicalSurfaceEffects(dict(self.values[:1]), self.digest(), accumulated=dict(self.values)) + effects = RouteSurfaceEffects if recovered else CanonicalSurfaceEffects + effects(dict(self.values[:1]), self.digest(), accumulated=dict(self.values)) return self def digest(self): - return hashlib.sha256(json.dumps((self.context, self.values), separators=(',', ':'), allow_nan=False).encode()).hexdigest() + payload = (self.context, self.values, self.compatibility) if self.compatibility else (self.context, self.values) + return hashlib.sha256(json.dumps(payload, separators=(',', ':'), allow_nan=False).encode()).hexdigest() def document(self): self.validate() - return {'context': list(self.context), 'values': dict(self.values)} + return dict(context=list(self.context), values=dict(self.values), **({'compatibility': self.compatibility} if self.compatibility else {})) @classmethod def from_document(cls, value): - if (type(value) is not dict or set(value) != {'context', 'values'} or type(value['context']) is not list - or type(value['values']) is not dict or set(value['values']) != set(NAMES)): + if (type(value) is not dict or set(value) not in ({'context', 'values'}, {'context', 'values', 'compatibility'}) or type(value['context']) is not list + or type(value['values']) is not dict): raise ValueError('Invalid manual coordinate document') - return cls(tuple(value['context']), tuple((n, value['values'][n]) for n in NAMES)).validate() + from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES + names = ROUTE_NAMES if value.get('compatibility') else NAMES + if set(value['values']) != set(names): + raise ValueError('Complete manual coordinates required') + return cls(tuple(value['context']), tuple((n, value['values'][n]) for n in names), value.get('compatibility', '')).validate() class ManualEffects: @@ -67,9 +96,23 @@ class ManualEffects: raise ValueError('Typed manual coordinates required') profile.validate() self.profile = profile - self.source = CanonicalSurfaceEffects(dict(profile.values[:1]), profile.digest(), accumulated=dict(profile.values)) + from openpilot.starpilot.flm.offroad_surface import RouteSurfaceEffects + effects = RouteSurfaceEffects if profile.compatibility else CanonicalSurfaceEffects + self.source = effects(dict(profile.values[:1]), profile.digest(), accumulated=dict(profile.values)) self.original_effect_anchor = self.source.original_effect_anchor + def compatible(self, cp, ci, controller, params=None): + if not self.profile.compatibility: + return True + from openpilot.starpilot.flm.runtime_adapter_registry import compatibility_for, digest + try: + if params is None: + return False + value = dict(compatibility_for(cp, ci, controller), settings_sha256=baseline_settings(cp, params)) + return self.profile.compatibility == digest(value) + except (OSError, ValueError, TypeError, AttributeError, KeyError): + return False + def begin_frame(self): self.source.begin_frame(time.monotonic_ns()) @@ -104,7 +147,7 @@ def load(cp, controller, params=None): return None, 'not_configured' tune = cp.lateralTuning.torque if (profile.basis != (float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction)) - or profile.flm is not None or manual.context != context(cp, controller)): + or profile.flm is not None or manual.context != context(cp, controller, recovered=bool(manual.compatibility))): return None, 'context_changed' return ManualEffects(manual), 'configured' except (AttributeError, KeyError, TypeError, ValueError, OverflowError, UnicodeError): diff --git a/openpilot/starpilot/flm/offroad_cache.py b/openpilot/starpilot/flm/offroad_cache.py index 54db4202a1..fac26c9d36 100644 --- a/openpilot/starpilot/flm/offroad_cache.py +++ b/openpilot/starpilot/flm/offroad_cache.py @@ -7,7 +7,7 @@ from pathlib import Path import stat import tempfile -MAX_DOCUMENT = 1024 * 1024 +MAX_DOCUMENT = 4 * 1024 * 1024 MAX_FILES = 128 MAX_TOTAL = 64 * 1024 * 1024 MAX_CHECKPOINTS = 8 diff --git a/openpilot/starpilot/flm/offroad_processor.py b/openpilot/starpilot/flm/offroad_processor.py index 6472eb4da4..ffca3b59bc 100644 --- a/openpilot/starpilot/flm/offroad_processor.py +++ b/openpilot/starpilot/flm/offroad_processor.py @@ -420,14 +420,7 @@ def collect_latest_steering_inputs(params, root, *, permitted, selected_route=No def allowed(): return permitted() and time.monotonic() - started <= MAX_ANALYSIS_SECONDS - def walk(actual_root, original_route, *, permitted, consume): - if len(original_route.get('segments', ())) <= 30: - return walk_completed_route(actual_root, original_route, permitted=permitted, consume=consume) - from openpilot.starpilot.flm.offroad_prior_inputs import _selected_sources - - return _selected_sources(actual_root, original_route, permitted=permitted, consume=consume, cp_sha256=None) - - collected = collect_route_inputs(root, route, permitted=allowed, walker=walk) + collected = collect_route_inputs(root, route, permitted=allowed) current_cp = collected.receipt.cp_sha256 skipped = 0 @@ -452,7 +445,7 @@ def collect_latest_steering_inputs(params, root, *, permitted, selected_route=No from openpilot.starpilot.flm.offroad_route import RouteInputError try: - earlier = collect_route_inputs(root, candidate, permitted=allowed, walker=walk) + earlier = collect_route_inputs(root, candidate, permitted=allowed) except RouteInputError as error: import logging diff --git a/openpilot/starpilot/flm/offroad_route.py b/openpilot/starpilot/flm/offroad_route.py index b44ed9cc05..53f65e288b 100644 --- a/openpilot/starpilot/flm/offroad_route.py +++ b/openpilot/starpilot/flm/offroad_route.py @@ -99,9 +99,9 @@ def route_inventory(root): from openpilot.starpilot.galaxy.drive_history import MAX_ROOT_ENTRIES try: - # Match the existing root scan budget. A 513th segment in another drive - # must not invalidate every otherwise complete route in that bounded scan. - inventory = DriveHistory(Path(root), max_segments_per_route=MAX_SEGMENTS, max_segments=MAX_ROOT_ENTRIES).snapshot(isolate_route_errors=True) + # FLM reviews the bounded local library, beyond the route browser's first page. + inventory = DriveHistory(Path(root), max_segments_per_route=MAX_SEGMENTS, + max_segments=MAX_ROOT_ENTRIES, max_routes=MAX_ROOT_ENTRIES).snapshot(isolate_route_errors=True) except DriveHistoryUnavailable as error: raise ValueError('Local drive inventory is unavailable') from error if inventory['scanIncomplete']: diff --git a/openpilot/starpilot/flm/offroad_runtime.py b/openpilot/starpilot/flm/offroad_runtime.py index e0ad083397..8c52d26cfb 100644 --- a/openpilot/starpilot/flm/offroad_runtime.py +++ b/openpilot/starpilot/flm/offroad_runtime.py @@ -287,7 +287,7 @@ def configure(cp, ci, controller, params, *, manual_status): return None, 'configuration_unavailable' -def current_configuration(cp, params): +def _current_controller(cp, params): from opendbc.car.car_helpers import interfaces from openpilot.starpilot.lateral.controller_selection import read_selection from openpilot.starpilot.flm.controller_replay import SelectedControllerFactory @@ -299,6 +299,18 @@ def current_configuration(cp, params): factory = PidControllerFactory(cp, mode) if cp.lateralTuning.which() == 'pid' else SelectedControllerFactory(cp, mode, turn_assist=startup.turn_assist) controller, _ = factory.create() ci = interfaces[str(cp.carFingerprint)](cp) + return ci, controller + + +def current_compatibility(cp, params): + from openpilot.starpilot.flm.runtime_adapter_registry import compatibility_for + from openpilot.starpilot.flm.manual_coordinates import baseline_settings + ci, controller = _current_controller(cp, params) + return dict(compatibility_for(cp, ci, controller), settings_sha256=baseline_settings(cp, params)) + + +def current_configuration(cp, params): + ci, controller = _current_controller(cp, params) from openpilot.starpilot.flm.runtime_adapter_registry import selected_descriptor scope, numeric = configuration_scope(cp, ci, controller, params, manual_status='not_configured') diff --git a/openpilot/starpilot/flm/offroad_store.py b/openpilot/starpilot/flm/offroad_store.py index 531f85e0bc..e1be2ea8a4 100644 --- a/openpilot/starpilot/flm/offroad_store.py +++ b/openpilot/starpilot/flm/offroad_store.py @@ -274,8 +274,11 @@ def startup_row(params, scope): if not readable: return None, 'unreadable' try: - row = decode(raw).get(NAMESPACE, {}).get(scope.key()) + rows = decode(raw).get(NAMESPACE, {}) + row = rows.get(scope.key()) if row is None: + if any(value['scope']['cp_sha256'] == scope.cp_sha256 and any(value['values'].values()) for value in rows.values()): + return None, 'saved_tune_requires_controller_compatibility_review' return None, 'not_configured' if validate_row(row) != scope: return None, 'context_changed' diff --git a/openpilot/starpilot/flm/runtime_adapter_registry.py b/openpilot/starpilot/flm/runtime_adapter_registry.py index 899b6379be..13ed9ba596 100644 --- a/openpilot/starpilot/flm/runtime_adapter_registry.py +++ b/openpilot/starpilot/flm/runtime_adapter_registry.py @@ -19,37 +19,15 @@ REVISION = 'actual-controller-registry-v2' @cache def implementation_revision(controller_type, interface_type): - """Startup/optional-process source identity; never invoked by Controls.tick. - - Bind shaping and conversion implementation changes as well as numeric CP - values. Formatting changes conservatively discard stored priors too. - """ - here = Path(__file__).resolve().parent - controller_root = Path(cast(str, importlib.import_module(controller_type.__module__).__file__)).resolve().parent - brand_root = Path(cast(str, importlib.import_module(interface_type.__module__).__file__)).resolve().parent - common_root = here.parents[1] / 'common' - inherited_roots = tuple( - Path(cast(str, importlib.import_module(base.__module__).__file__)).resolve().parent - for base in controller_type.__mro__ - if base.__module__.startswith('openpilot.') - ) - roots = (here, here.parent / 'lateral', controller_root, brand_root, brand_root.parent, common_root, *inherited_roots) - files = tuple(sorted({path for root in roots for path in root.glob('*.py')})) - if not files or len(files) > 512: - raise ValueError('controller implementation identity bound') - result = hashlib.sha256() - result.update((controller_type.__module__ + '.' + controller_type.__qualname__).encode('utf-8')) - result.update((interface_type.__module__ + '.' + interface_type.__qualname__).encode('utf-8')) - for path in files: - data = path.read_bytes() - if len(data) > 2 * 1024 * 1024: - raise ValueError('implementation source bound') - result.update(path.name.encode('utf-8')) - result.update(hashlib.sha256(data).digest()) + """Selected steering semantics; startup only, never Controls.tick.""" from openpilot.starpilot.flm.native_primitives import native_identity + from openpilot.starpilot.flm.steering_compatibility import revision - result.update(native_identity().encode('utf-8')) - return REVISION + ':' + result.hexdigest() + here = Path(__file__).resolve().parent + controller = Path(cast(str, importlib.import_module(controller_type.__module__).__file__)).resolve() + interface = Path(cast(str, importlib.import_module(interface_type.__module__).__file__)).resolve() + names = (controller_type.__module__ + '.' + controller_type.__qualname__, interface_type.__module__ + '.' + interface_type.__qualname__) + return revision(here.parents[2], controller, interface, names, native_identity()) SOURCE_LEASE_NS = 500_000_000 @@ -459,6 +437,18 @@ def baseline_revision(descriptor, values): return hashlib.sha256(repr((descriptor, tuple(values))).encode('ascii')).hexdigest() +def compatibility_for(cp, ci, controller): + """Actual selected semantics for explicit recovery; not learned qualification.""" + from openpilot.starpilot.flm.offroad_surface import ROUTE_MANIFEST_SHA256 + descriptor = selected_descriptor(cp, ci, controller) + if descriptor is None: + raise ValueError('Actual registered steering controller required') + return {'cp_sha256': descriptor.cp_sha256, 'controller_revision': descriptor.controller_revision, + 'baseline_revision': baseline_revision(descriptor, baseline_values(controller)), + 'controller_mode': descriptor.controller_mode, 'controller_domain': descriptor.domain, + 'manifest_sha256': ROUTE_MANIFEST_SHA256} + + def selected_identity(descriptor, source_epoch, baseline=""): if len(source_epoch) != 64: raise ValueError('source epoch') diff --git a/openpilot/starpilot/flm/steering_compatibility.py b/openpilot/starpilot/flm/steering_compatibility.py new file mode 100644 index 0000000000..6e8fca05e2 --- /dev/null +++ b/openpilot/starpilot/flm/steering_compatibility.py @@ -0,0 +1,54 @@ +"""Declared selected-steering closure, not the platform discovery/fitter tree. + +CP, the actual selected types, baseline and persistent settings remain separate +scope fields. Brand-local sources are deliberately conservative: an encoder or +vehicle-interface change requires review even if a particular branch was idle. +""" +from pathlib import Path +import hashlib + +REVISION = 'selected-steering-compatibility-v1' +FLM = ( + 'steering_compatibility', 'runtime_adapter_registry', 'canonical_surface_adapter', 'offroad_surface', + 'offroad_runtime', 'offroad_store', 'torque_stages', 'pid_stages', 'selected_effects', 'manual_coordinates', + 'live', 'torque_surface', 'global_runtime', 'adaptive_profile', 'torque_adapter', 'learning_wire', 'native_refinement_wire', +) +COMMON = ('constants', 'filter_simple', 'pid', 'realtime') + + +def source_paths(root, controller_file, brand_file): + root = Path(root) + brand = Path(brand_file).parent + controller = Path(controller_file).parent + paths = {Path(controller_file), Path(brand_file)} + paths.update(root / 'openpilot/starpilot/flm' / (name + '.py') for name in FLM) + paths.update(root / 'openpilot/common' / (name + '.py') for name in COMMON) + paths.update(p for p in controller.glob('*.py') if p.name.startswith(('latcontrol', 'vehicle_model', 'drive_helpers'))) + paths.update((root / 'openpilot/starpilot/lateral').glob('*.py')) + paths.update(brand.glob('*.py')) + paths.update((brand.parent / name) for name in ('__init__.py', 'interfaces.py', 'lateral.py', 'structs.py', 'vehicle_model.py')) + paths.update((brand.parent / 'common').glob('*.py')) + dbc = root / 'opendbc_repo/opendbc/dbc' + paths.update((dbc / 'generator' / brand.name).rglob('*.dbc')) + paths.update(p for p in dbc.glob(brand.name + '*.dbc') if not p.is_symlink()) + safety = root / 'opendbc_repo/opendbc/safety' + paths.update(safety.glob('*.h')) + paths.update((safety / 'modes').glob(brand.name + '*.h')) + # Source data used by conversion/policy code, never other brands' discovery. + paths.update(p for directory in (brand, root / 'openpilot/starpilot/lateral') + for suffix in ('*.json', '*.toml') for p in directory.glob(suffix)) + return tuple(sorted(paths)) + + +def revision(root, controller_file, brand_file, names, native): + root = Path(root).resolve() + paths = source_paths(root, controller_file, brand_file) + if not 10 <= len(paths) <= 512: + raise ValueError('Selected steering source closure bound') + result = hashlib.sha256(repr((REVISION, names, native)).encode()) + for path in paths: + if path.is_symlink() or not path.is_file() or not 0 <= path.stat().st_size <= 2 * 1024 * 1024: + raise ValueError('Selected steering source unavailable: ' + str(path.relative_to(root))) + result.update(str(path.relative_to(root)).encode()) + result.update(hashlib.sha256(path.read_bytes()).digest()) + return REVISION + ':' + result.hexdigest() diff --git a/openpilot/starpilot/flm/tests/test_offroad_backend.py b/openpilot/starpilot/flm/tests/test_offroad_backend.py index 0c0aa8a44c..248652bd6f 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_backend.py +++ b/openpilot/starpilot/flm/tests/test_offroad_backend.py @@ -214,7 +214,7 @@ class TestOffroadCache(unittest.TestCase): def collect(root, route, *, permitted, walker=None): self.assertTrue(permitted()) - self.assertTrue(callable(walker)) + self.assertIsNone(walker, 'Use the default complete route reader') calls.append(route['routeId']) return parked if route is latest else driving diff --git a/openpilot/starpilot/flm/tests/test_offroad_cache_retention.py b/openpilot/starpilot/flm/tests/test_offroad_cache_retention.py index b17bc18ef1..cbb7f9b61d 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_cache_retention.py +++ b/openpilot/starpilot/flm/tests/test_offroad_cache_retention.py @@ -6,7 +6,7 @@ import tempfile import unittest from unittest.mock import patch -from openpilot.starpilot.flm.offroad_cache import AssessmentCache, MAX_FILES +from openpilot.starpilot.flm.offroad_cache import AssessmentCache, MAX_DOCUMENT, MAX_FILES, MAX_TOTAL class TestCacheRetention(unittest.TestCase): @@ -18,6 +18,17 @@ class TestCacheRetention(unittest.TestCase): def fill(self): return [self.cache.put({'kind': 'completed_assessment', 'unit': index}) for index in range(MAX_FILES)] + def test_full_drive_document_survives_restart_and_oversized_write_preserves_it(self): + document = {'kind': 'declared-large-assessment', 'data': 'x' * (2 * 1024 * 1024)} + digest = self.cache.put(document) + self.assertEqual(AssessmentCache(self.cache.directory).get(digest), document) + before = set(self.cache.directory.iterdir()) + with self.assertRaisesRegex(ValueError, 'Assessment document bound'): + self.cache.put({'data': 'x' * MAX_DOCUMENT}) + self.assertEqual(set(self.cache.directory.iterdir()), before) + self.assertEqual(self.cache.get(digest), document) + self.assertEqual((MAX_DOCUMENT, MAX_FILES, MAX_TOTAL), (4 * 1024 * 1024, 128, 64 * 1024 * 1024)) + def test_full_cache_releases_room_preserving_saved_proof_dependency_and_checkpoints(self): linked = self.cache.put({'kind': 'next_drive_trial'}) saved = self.cache.put({'kind': 'next_drive_outcome', 'trial_analysis_sha256': linked}) diff --git a/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py b/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py index bdd62e6dd3..5c7de3d7d5 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py +++ b/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py @@ -1417,7 +1417,7 @@ class TestSelectedCurrentDriveInputs(unittest.TestCase): with self.subTest(invalid=invalid), self.assertRaises(ValueError): self.selected_source(**invalid) - def test_primary_long_drive_reuses_selected_reader_without_a_full_scan(self): + def test_primary_long_drive_reviews_every_original_segment(self): from types import SimpleNamespace from openpilot.starpilot.flm import offroad_processor as processor from openpilot.starpilot.flm import offroad_prior_inputs as inputs @@ -1429,20 +1429,22 @@ class TestSelectedCurrentDriveInputs(unittest.TestCase): 'recorded_lateral_request_rows': 100, 'active_lateral_request_rows': 90, 'invalid_lateral_request_rows': 0, }, quality_stops=[]) - def collect(root, actual, *, permitted, walker): + def collect(root, actual, *, permitted, walker=None): + walker = processor.walk_completed_route if walker is None else walker self.assertEqual(walker(root, actual, permitted=permitted, consume=lambda *args: None), receipt) return collected with ( patch.object(processor, 'latest_route', return_value=route), patch.object(processor, 'collect_route_inputs', side_effect=collect), - patch.object(processor, 'walk_completed_route', side_effect=AssertionError('Long drive must not start a full scan')), + patch.object(processor, 'walk_completed_route', return_value=receipt) as complete, patch.object(inputs, '_selected_sources', return_value=receipt) as selected, ): actual, result = processor.collect_latest_steering_inputs(None, '.', permitted=lambda: True) self.assertEqual(actual, route) self.assertIs(result, collected) - self.assertIsNone(selected.call_args.kwargs['cp_sha256']) + complete.assert_called_once() + selected.assert_not_called() diff --git a/openpilot/starpilot/flm/tests/test_offroad_fault_isolation.py b/openpilot/starpilot/flm/tests/test_offroad_fault_isolation.py index d68435f541..c776b1a3ef 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_fault_isolation.py +++ b/openpilot/starpilot/flm/tests/test_offroad_fault_isolation.py @@ -74,6 +74,21 @@ def zstd_recording(root, counter, *, fault=None, **kwargs): class TestRouteFaultIsolation(unittest.TestCase): + def test_many_short_drives_do_not_invalidate_the_flm_inventory(self): + # Inventory-only fixture; these bytes are never admitted as learning evidence. + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for counter in range(673): + for segment in range(3 if counter < 39 else 2): + path = root / f'{counter:08x}--aaaaaaaaaa--{segment}' + path.mkdir() + (path / 'rlog.zst').write_bytes(b'inventory only') + self.assertTrue(DriveHistory(root, max_segments=2048).snapshot()['scanIncomplete']) + actual = route_inventory(root) + self.assertFalse(actual['scanIncomplete']) + self.assertEqual(len(actual['routes']), 673) + self.assertEqual(sum(row['segmentCount'] for row in actual['routes']), 1385) + def test_total_inventory_matches_bounded_root_scan_without_raising_per_drive_limit(self): # Metadata-only fixtures: file presence never establishes valid log data. with tempfile.TemporaryDirectory() as directory: diff --git a/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py b/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py index 718a0d051d..41285d08bf 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py +++ b/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py @@ -86,7 +86,8 @@ assert 'opendbc.car.car_helpers' not in sys.modules with tempfile.TemporaryDirectory() as root: params = Params(root) params.put_bool('IsOffroad', starts_parked, block=True) - params.put(KEY, b'declared-existing-saved-tune') + params.put(KEY, b'declared-existing-saved-tune', block=True) + self.assertEqual(params.get(KEY), b'declared-existing-saved-tune') def close_socket(i): events.append(('closed', i)) if cancel_on_cleanup and i == 0: diff --git a/openpilot/starpilot/flm/tests/test_steering_compatibility.py b/openpilot/starpilot/flm/tests/test_steering_compatibility.py new file mode 100644 index 0000000000..041720da93 --- /dev/null +++ b/openpilot/starpilot/flm/tests/test_steering_compatibility.py @@ -0,0 +1,75 @@ +"""Compatibility follows steering consumers, not unrelated platform discovery.""" +from dataclasses import replace +from types import SimpleNamespace + +import pytest +from openpilot.starpilot.flm.steering_compatibility import source_paths, revision +from openpilot.starpilot.flm.offroad_store import RouteScope, startup_row, NAMESPACE, KEY +from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES +from openpilot.starpilot.flm.learned_lifecycle import encode + + +@pytest.fixture +def closure(tmp_path): + control = tmp_path / 'openpilot/selfdrive/controls/lib/latcontrol_torque.py' + brand = tmp_path / 'opendbc_repo/opendbc/car/hyundai/interface.py' + seed = [control, brand, brand.with_name('hyundaicanfd.py'), + tmp_path / 'openpilot/starpilot/lateral/model_turn_assist.py', + tmp_path / 'opendbc_repo/opendbc/safety/modes/hyundai_canfd.h'] + for path in seed: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('declared baseline\n') + for path in source_paths(tmp_path, control, brand): + path.parent.mkdir(parents=True, exist_ok=True) + if not path.exists(): + path.write_text('declared baseline\n') + def token(native='native-one'): + return revision(tmp_path, control, brand, ('LatControlTorque', 'HyundaiInterface'), native) + return tmp_path, control, brand, token + + +@pytest.mark.parametrize('state', ['ready_for_next_drive', 'accepted_after_drive', 'retained_after_drive', 'rolled_back']) +def test_unrelated_updates_preserve_queued_accepted_and_rollback_selection(closure, state): + root, _, _, token = closure + before = token() + for name in ('opendbc_repo/opendbc/car/car_helpers.py', 'opendbc_repo/opendbc/car/chrysler/discovery.py', + 'openpilot/starpilot/galaxy/server.py', 'openpilot/starpilot/flm/offroad_worker.py'): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('unrelated changed implementation\n') + assert token() == before + scope = RouteScope('a' * 64, before, 'b' * 64, 'c' * 64, '0', 'native', 'torque') + values = dict.fromkeys(ROUTE_NAMES, 0.) + values['friction_threshold_mid'] = .0036 + row = {'scope': scope.document(), 'values': values, 'previous': dict.fromkeys(ROUTE_NAMES, 0.), + 'route_sha256s': ['d' * 64], 'source_start_ns': 1, 'source_end_ns': 2, 'analysis_sha256': 'e' * 64, + 'completed_wall_ns': 1794777785171179957, 'sequence': 1, 'state': state} + store = root / KEY + store.write_bytes(encode({'version': 3, 'profiles': {}, 'fullSurfaces': {}, NAMESPACE: {scope.key(): row}})) + params = SimpleNamespace(get_param_path=lambda _: str(store)) + assert startup_row(params, scope) == (row, 'route_tune_loaded') + legacy = replace(scope, controller_revision='actual-controller-registry-v2:' + 'f' * 64) + assert startup_row(params, legacy) == (None, 'saved_tune_requires_controller_compatibility_review') + + +@pytest.mark.parametrize('name', [ + 'openpilot/selfdrive/controls/lib/latcontrol_torque.py', + 'opendbc_repo/opendbc/car/hyundai/hyundaicanfd.py', + 'openpilot/starpilot/lateral/model_turn_assist.py', + 'opendbc_repo/opendbc/safety/modes/hyundai_canfd.h', + 'openpilot/starpilot/flm/offroad_surface.py', + 'opendbc_repo/opendbc/car/vehicle_model.py', +]) +def test_relevant_controller_encoder_model_safety_and_bounds_changes_invalidate(closure, name): + root, _, _, token = closure + before = token() + (root / name).write_text('relevant steering changed\n') + assert token() != before + + +def test_missing_semantics_or_changed_native_cannot_reuse_identity(closure): + root, _, _, token = closure + assert token('native-one') != token('native-two') + (root / 'openpilot/starpilot/flm/offroad_surface.py').unlink() + with pytest.raises(ValueError, match='source unavailable'): + token() diff --git a/openpilot/starpilot/galaxy/drive_history.py b/openpilot/starpilot/galaxy/drive_history.py index 3ec6fdf6c5..9ab24ca882 100644 --- a/openpilot/starpilot/galaxy/drive_history.py +++ b/openpilot/starpilot/galaxy/drive_history.py @@ -97,14 +97,17 @@ def _segment_files(root_fd: int, name: str) -> tuple[dict[str, bool] | None, boo class DriveHistory: def __init__(self, root: Path | None = None, *, max_segments_per_route: int = MAX_SEGMENTS_PER_ROUTE, - max_segments: int = MAX_SEGMENTS): + max_segments: int = MAX_SEGMENTS, max_routes: int = MAX_ROUTES): if type(max_segments_per_route) is not int or not 1 <= max_segments_per_route <= MAX_STATS_SEGMENTS_PER_ROUTE: raise ValueError('Invalid route segment limit') if type(max_segments) is not int or not max_segments_per_route <= max_segments <= MAX_ROOT_ENTRIES: raise ValueError('Invalid total segment limit') + if type(max_routes) is not int or not 1 <= max_routes <= MAX_ROOT_ENTRIES: + raise ValueError('Invalid route limit') self.root = root if root is not None else Path(Paths.log_root()) self.max_segments_per_route = max_segments_per_route self.max_segments = max_segments + self.max_routes = max_routes def delete_videos(self, name: object) -> dict: return delete_segment_videos(self.root, name) @@ -160,7 +163,7 @@ class DriveHistory: if isolate_route_errors and route_id in route_errors: continue number = int(number_text) - if route_id not in routes and len(routes) >= MAX_ROUTES: + if route_id not in routes and len(routes) >= self.max_routes: result['scanIncomplete'] = True continue existing = routes.get(route_id) diff --git a/openpilot/starpilot/galaxy/flm_backup.py b/openpilot/starpilot/galaxy/flm_backup.py index 096dd638b1..ba099165c0 100644 --- a/openpilot/starpilot/galaxy/flm_backup.py +++ b/openpilot/starpilot/galaxy/flm_backup.py @@ -13,9 +13,9 @@ from openpilot.starpilot.analytics.settings import _eligible, _value from openpilot.starpilot.flm.canonical_surface_adapter import NAMES from openpilot.starpilot.flm.learned_lifecycle import decode, encode from openpilot.starpilot.flm.offroad_cache import AssessmentCache, directory_for_params -from openpilot.starpilot.flm.offroad_runtime import current_scope +from openpilot.starpilot.flm.offroad_runtime import current_scope, current_compatibility from openpilot.starpilot.flm.offroad_saved_history import SavedHistory -from openpilot.starpilot.flm.offroad_store import KEY, MAX_BYTES as STORE_MAX, MAX_SCOPES, NAMESPACE, validate_rows +from openpilot.starpilot.flm.offroad_store import RouteScope, KEY, MAX_BYTES as STORE_MAX, MAX_SCOPES, NAMESPACE, validate_rows from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest from openpilot.starpilot.galaxy.settings import SettingsChanged from openpilot.starpilot.galaxy.toggle_backup import ToggleBackup @@ -58,6 +58,27 @@ class FlmBackup: raise BackupRefused('The saved controller selection is unreadable. Nothing was restored.') return str(selected.mode) + def _recovery(self, ctx, learned): + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, MAX_DOCUMENT_BYTES, parse_document + raw, readable = read_saved(self.settings.params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) + if not readable: + raise BackupRefused('Manual tuning is unreadable. Nothing was changed.') + profile = None if raw is None else parse_document(raw).get(str(ctx.cp.carFingerprint)) + manual = None if profile is None else profile.manual_coordinates + try: + compatibility = current_compatibility(ctx.cp, self.settings.params) + except (OSError, ValueError, TypeError, AttributeError): + compatibility = None + try: + scope_key = current_scope(ctx.cp, self.settings.params).key() + except (OSError, ValueError, TypeError, AttributeError): + scope_key = None + selected = scope_key if scope_key in learned else None + return {'compatibility': compatibility, 'setup': selected, 'manualProfile': None if manual is None or not manual.compatibility else + json.dumps(manual.document(), sort_keys=True, separators=(',', ':'), allow_nan=False), + 'trials': {key: os.path.lexists(directory_for_params(self.settings.params) / ('trial-' + row['analysis_sha256'] + '.json')) + for key, row in learned.items()}} + def export(self): ctx = self.settings.context.sample() if ctx.cp is None or ctx.cp.notCar: @@ -75,9 +96,12 @@ class FlmBackup: if (fresh.cp_raw != ctx.cp_raw or fresh.metric != ctx.metric or self._mode(fresh.cp) != mode or self._manual(fresh) != manual or read_saved(self.settings.params, KEY, STORE_MAX) != (raw, readable)): raise SettingsChanged('Settings changed while preparing the backup. Try again.') - body = {'format': FORMAT, 'version': 1, 'createdAt': datetime.now(UTC).isoformat(), 'vehicle': str(ctx.cp.carFingerprint), + recovery = self._recovery(ctx, learned) + body = {'format': FORMAT, 'version': 2, 'createdAt': datetime.now(UTC).isoformat(), 'vehicle': str(ctx.cp.carFingerprint), 'controllerMode': mode, - 'cpSha256': identity, 'metric': ctx.metric, 'manual': manual, 'learned': learned} + 'cpSha256': identity, 'metric': ctx.metric, 'manual': manual, 'learned': learned, 'recovery': recovery} + if self._recovery(fresh, learned) != recovery: + raise SettingsChanged('Recovery state changed while preparing the backup. Try again.') result = dict(body, checksum=digest(body)) if len(json.dumps(result, allow_nan=False).encode()) > MAX_BYTES: raise BackupRefused('This tune exceeds the backup size limit.') @@ -85,8 +109,9 @@ class FlmBackup: def _validate(self, backup): fields = {'format', 'version', 'createdAt', 'vehicle', 'controllerMode', 'cpSha256', 'metric', 'manual', 'learned', 'checksum'} - if (type(backup) is not dict or set(backup) != fields or backup['format'] != FORMAT or - type(backup['version']) is not int or backup['version'] != 1 or type(backup['metric']) is not bool or + if (type(backup) is not dict or set(backup) not in (fields, fields | {'recovery'}) or backup['format'] != FORMAT or + type(backup['version']) is not int or backup['version'] not in (1, 2) or + ('recovery' in backup) != (backup['version'] == 2) or type(backup['metric']) is not bool or type(backup['createdAt']) is not str or len(backup['createdAt']) > 64 or type(backup['vehicle']) is not str or len(backup['vehicle']) > 128 or type(backup['controllerMode']) is not str or not 1 <= len(backup['controllerMode']) <= 32 or @@ -120,11 +145,36 @@ class FlmBackup: seen.add(row['key']) if any(row['scope']['cp_sha256'] != backup['cpSha256'] for row in learned.values()): raise BackupRefused('The backup mixes different vehicle configurations.') + if backup['version'] == 2: + recovery = backup['recovery'] + if (type(recovery) is not dict or set(recovery) != {'compatibility', 'setup', 'manualProfile', 'trials'} or + type(recovery['trials']) is not dict or set(recovery['trials']) != set(learned) or + any(type(v) is not bool for v in recovery['trials'].values())): + raise BackupRefused('The backup lifecycle record is invalid.') + try: + if recovery['setup'] is not None and recovery['setup'] not in learned: + raise ValueError('Recovery setup is missing') + if recovery['compatibility'] is not None: + fields = {'cp_sha256', 'controller_revision', 'baseline_revision', 'controller_mode', 'controller_domain', 'manifest_sha256', 'settings_sha256'} + if type(recovery['compatibility']) is not dict or set(recovery['compatibility']) != fields: + raise ValueError('Exact compatible steering context required') + settings = recovery['compatibility']['settings_sha256'] + if type(settings) is not str or len(settings) != 64 or settings.strip('0123456789abcdef'): + raise ValueError('Exact baseline settings required') + RouteScope(**{key: value for key, value in recovery['compatibility'].items() if key != 'settings_sha256'}, + persistent_source_epoch='0' * 64, reset_generation='0').validate() + if recovery['manualProfile'] is not None: + from openpilot.starpilot.flm.manual_coordinates import ManualCoordinates + if type(recovery['manualProfile']) is not str or len(recovery['manualProfile']) > 16384: + raise ValueError('Bounded manual recovery required') + ManualCoordinates.from_document(json.loads(recovery['manualProfile'])) + except (ValueError, TypeError, KeyError) as error: + raise BackupRefused('The backup compatibility record is invalid.') from error return learned def _plan(self, backup, mode, identity, authorized): learned = self._validate(backup) - if mode not in ('manual', 'learned'): + if mode not in ('manual', 'learned', 'recovery'): raise BackupRefused('Choose manual settings or an Auto Learn setup.') ctx = self.settings.context.sample() if (not authorized() or not ctx.parked or ctx.cp is None or type(ctx.cp_raw) is not bytes or @@ -141,6 +191,8 @@ class FlmBackup: raise BackupRefused('The existing saved tune is unreadable. It will not be overwritten.') doc = decode(raw) changes = [] + if mode == 'recovery': + return self._manual_recovery(backup, learned, ctx, raw, doc, authorized) if mode == 'manual': available = {row.key: row for row in self.settings._state('tuning', ctx).rows if row.available} helper = ToggleBackup(self.settings, None) @@ -190,6 +242,65 @@ class FlmBackup: raise SettingsChanged('The vehicle or saved tune changed. Review the backup again.') return {'mode': mode, 'cp': hashlib.sha256(ctx.cp_raw).hexdigest(), 'expected': raw, 'desired': desired, 'changes': changes} + def _manual_recovery(self, backup, learned, ctx, raw, doc, authorized): + from dataclasses import replace + from openpilot.starpilot.flm.manual_coordinates import ManualCoordinates, context + from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, MAX_DOCUMENT_BYTES, parse_document, serialize_document, PlatformProfile, FieldChoice + if backup['version'] != 2: + raise BackupRefused('This older backup has no compatible manual recovery record. Its manual sliders can still be reviewed.') + recovery = backup['recovery'] + from openpilot.starpilot.flm.runtime_adapter_registry import implementation_revision + from openpilot.starpilot.flm.native_primitives import native_identity + implementation_revision.cache_clear() + native_identity.cache_clear() + compatible = current_compatibility(ctx.cp, self.settings.params) + if recovery['compatibility'] != compatible: + raise BackupRefused('No saved setup matches the current steering implementation and baseline. Nothing was changed.') + token = digest(compatible) + if recovery['manualProfile'] is not None: + known = [doc, *(decode(text.encode()) for text in SavedHistory(self.settings.params).read().values())] + local = [row for saved in known for row in saved.get(NAMESPACE, {}).values() + if all(row['scope'].get(name) == value for name, value in compatible.items() if name != 'settings_sha256')] + newest = max(local, key=lambda row: (row['completed_wall_ns'], row['sequence'], row['state'] == 'rolled_back'), default=None) + if newest is not None and newest['state'] == 'rolled_back': + raise BackupRefused('The latest compatible local setup was rolled back. Review that outcome before manual recovery.') + manual = ManualCoordinates.from_document(json.loads(recovery['manualProfile'])) + else: + selected = learned.get(recovery['setup']) + if selected is None or any(selected['scope'].get(name) != value for name, value in compatible.items() if name != 'settings_sha256'): + raise BackupRefused('No compatible setup was exported. Its earlier values remain in the backup for review.') + if selected['state'] == 'rolled_back': + raise BackupRefused('This setup was rolled back. It cannot be recovered as a new manual tune.') + known = [doc, *(decode(text.encode()) for text in SavedHistory(self.settings.params).read().values())] + for saved in known: + local = saved.get(NAMESPACE, {}).get(recovery['setup']) + if local is not None and (local['sequence'], local['completed_wall_ns']) >= (selected['sequence'], selected['completed_wall_ns']): + if local['state'] == 'rolled_back' or local['values'] != selected['values']: + raise BackupRefused('A newer local outcome supersedes this backup. Existing rollback history was preserved.') + manual = ManualCoordinates(context(ctx.cp, self._mode(ctx.cp), recovered=True), + tuple((name, selected['values'][name]) for name in ROUTE_NAMES), token).validate() + if manual.compatibility != token or manual.context != context(ctx.cp, self._mode(ctx.cp), recovered=True): + raise BackupRefused('The recovered manual tune needs a different controller or vehicle. Nothing was changed.') + expected, readable = read_saved(self.settings.params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) + if not readable: + raise BackupRefused('Existing manual settings are unreadable. Nothing was changed.') + profiles = {} if expected is None else parse_document(expected) + tune = ctx.cp.lateralTuning.torque + basis = (float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction)) + previous = profiles.get(str(ctx.cp.carFingerprint), PlatformProfile(basis, FieldChoice(), FieldChoice())) + if previous.basis != basis or previous.flm is not None: + raise BackupRefused('The existing manual baseline differs. Review it before recovering a tune.') + prior = {} if previous.manual_coordinates is None else dict(previous.manual_coordinates.values) + changes = [[name, prior.get(name, 0), value] for name, value in manual.values if value != prior.get(name, 0)] + if not changes and previous.manual_coordinates != manual and any(value for _, value in manual.values): + changes = [['Manual tune configuration', 'existing manual settings', 'reviewed backup settings']] + profiles[str(ctx.cp.carFingerprint)] = replace(previous, manual_coordinates=manual) + if not authorized() or not self.settings.context.sample().parked: + raise SettingsChanged('Park before recovering a tune.') + return {'mode': 'recovery', 'cp': hashlib.sha256(ctx.cp_raw).hexdigest(), 'expected': expected, + 'desired': serialize_document(profiles), 'changes': changes, 'automatic_expected': raw} + def preview(self, backup, mode, identity, *, authorized): plan = self._plan(backup, mode, identity, authorized) with self.lock: @@ -199,7 +310,8 @@ class FlmBackup: intent = secrets.token_urlsafe(24) self.pending[intent] = {'backup': backup, 'mode': mode, 'identity': identity, 'expires': self.clock() + 90, 'plan': plan} return {'intent': intent, 'mode': mode, 'changes': plan['changes'], 'count': len(plan['changes']), - 'question': 'Restore these manual slider values? Manual overrides pause Auto Learn.' if mode == 'manual' else + 'question': 'Recover these values as your manual tune? Auto Learn pauses until you reset the manual tune.' if mode == 'recovery' else + 'Restore these manual slider values? Manual overrides pause Auto Learn.' if mode == 'manual' else 'Restore this locally verified Auto Learn setup? Current use is still confirmed by the controller while driving.'} def confirm(self, intent, identity, *, authorized): @@ -214,7 +326,16 @@ class FlmBackup: if not plan['changes']: return {'complete': True, 'restored': 0, 'unchanged': len(pending['backup']['manual']) if plan['mode'] == 'manual' else 1, 'skipped': []} directory = directory_for_params(self.settings.params) - AssessmentCache(directory.with_name(directory.name + '-backups')).put({'kind': 'before_user_restore', 'backup': self.export()}) + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, MAX_DOCUMENT_BYTES + manual_raw, readable = read_saved(self.settings.params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) + if not readable: + raise SettingsChanged('Existing manual tuning could not be backed up. Nothing was restored.') + automatic_raw, readable = read_saved(self.settings.params, KEY, STORE_MAX) + if not readable: + raise SettingsChanged('Existing automatic tuning could not be backed up. Nothing was restored.') + AssessmentCache(directory.with_name(directory.name + '-backups')).put({'kind': 'before_user_restore', 'backup': self.export(), + 'manualDocument': None if manual_raw is None else manual_raw.decode(), + 'automaticDocument': None if automatic_raw is None else automatic_raw.decode()}) if plan['mode'] == 'manual': backup = pending['backup'] @@ -230,6 +351,16 @@ class FlmBackup: return ToggleBackup(self.settings, None).restore({'format': 'galaxy-toggles', 'version': 1, 'createdAt': backup['createdAt'], 'metric': backup['metric'], 'vehicle': backup['vehicle'], 'settings': backup['manual'], 'layout': None}, identity, authorized=permitted_manual) + if plan['mode'] == 'recovery': + cache = AssessmentCache(directory.with_name(directory.name + '-backups')) + cache.put({'kind': 'user_reviewed_manual_recovery', 'backup': pending['backup']}) + def permitted_recovery(): + return authorized() and self._plan(pending['backup'], 'recovery', identity, authorized) == plan + result = commit_exact(self.settings.params, key=DOCUMENT_KEY, max_bytes=MAX_DOCUMENT_BYTES, + raw=plan['desired'], expected=plan['expected'], authorized=permitted_recovery, temp_prefix='.flm-recovery-') + if not result.committed or not result.verified: + raise SettingsChanged('Manual recovery was not confirmed. Existing automatic history was left unchanged.') + return {'complete': True, 'restored': len(plan['changes']), 'manual': True, 'unchanged': 0, 'skipped': []} SavedHistory(self.settings.params).preserve(plan['expected'] or encode(decode(None))) def permitted(): diff --git a/openpilot/starpilot/galaxy/tests/test_drive_history.py b/openpilot/starpilot/galaxy/tests/test_drive_history.py index 59f41070ee..ffcfe6ac91 100644 --- a/openpilot/starpilot/galaxy/tests/test_drive_history.py +++ b/openpilot/starpilot/galaxy/tests/test_drive_history.py @@ -135,6 +135,19 @@ class DriveHistoryTest(unittest.TestCase): with self.assertRaises(ValueError): drive_history.DriveHistory(self.root, max_segments_per_route=512, max_segments=invalid) + def test_explicit_route_budget_preserves_default_and_rejects_invalid_limits(self): + for counter in range(101): + self.segment(f'{counter:08x}--aaaaaaaaaa--0', 'rlog.zst') + ordinary = self.reader.snapshot() + self.assertTrue(ordinary['scanIncomplete']) + self.assertEqual(len(ordinary['routes']), 100) + expanded = drive_history.DriveHistory(self.root, max_routes=2048).snapshot() + self.assertFalse(expanded['scanIncomplete']) + self.assertEqual(len(expanded['routes']), 101) + for invalid in (True, 0, -1, 2049): + with self.assertRaises(ValueError): + drive_history.DriveHistory(self.root, max_routes=invalid) + def test_missing_root_is_empty_but_root_symlink_is_unavailable(self): self.assertEqual(drive_history.DriveHistory(self.root / 'missing').snapshot()['routes'], []) link = Path(self.temp.name) / 'linked' diff --git a/openpilot/starpilot/galaxy/tests/test_flm_backup.py b/openpilot/starpilot/galaxy/tests/test_flm_backup.py index cf7507b8c5..0b3365251a 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_backup.py +++ b/openpilot/starpilot/galaxy/tests/test_flm_backup.py @@ -36,7 +36,7 @@ class FlmBackupTest(unittest.TestCase): self.gateway = self.fixture.gateway self.identity = self.fixture.session, self.fixture.generation self.owner = FlmBackup(self.gateway) - self.scope = RouteScope(car_params_digest(cp), 'declared-backup-controller', 'a' * 64, 'b' * 64, '0', + self.scope = RouteScope(car_params_digest(cp), 'selected-steering-compatibility-v1:' + 'a' * 64, 'a' * 64, 'b' * 64, '0', self.owner._mode(cp), 'torque') zero = dict.fromkeys(ROUTE_NAMES, 0.0) self.row: dict[str, Any] = {'scope': self.scope.document(), 'values': dict(zero, friction_threshold_mid=.0036, @@ -47,6 +47,12 @@ class FlmBackupTest(unittest.TestCase): self.params.put(KEY, self.raw, block=True) self.scope_patch = patch('openpilot.starpilot.galaxy.flm_backup.current_scope', return_value=self.scope) self.scope_patch.start() + self.compatibility = {key: value for key, value in self.scope.document().items() if key not in ('persistent_source_epoch', 'reset_generation')} + from openpilot.starpilot.flm.manual_coordinates import baseline_settings + self.compatibility['settings_sha256'] = baseline_settings(cp, self.params) + self.compat_patch = patch('openpilot.starpilot.galaxy.flm_backup.current_compatibility', return_value=self.compatibility) + self.compat_patch.start() + self.addCleanup(self.compat_patch.stop) self.addCleanup(self.scope_patch.stop) def preview(self, backup=None, mode='learned', authorized=lambda: True): @@ -215,6 +221,109 @@ class FlmBackupTest(unittest.TestCase): self.preview(self.seal(changed), 'manual') self.assertEqual(self.stored(), self.raw) + def test_earlier_manual_definition_stays_readable_and_resettable_without_application(self): + from openpilot.starpilot.flm.manual_coordinates import ManualCoordinates, load + from openpilot.starpilot.flm.canonical_surface_adapter import NAMES + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, PlatformProfile, FieldChoice, serialize_document + cp = self.fixture.context.value.cp + context = (car_params_digest(cp), self.scope.controller_mode, '0' * 64) + values = dict.fromkeys(NAMES, 0.) + values['ff_gain_left'] = .01 + prior = ManualCoordinates(context, tuple(values.items())).validate() + tune = cp.lateralTuning.torque + profile = PlatformProfile((float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction)), + FieldChoice(), FieldChoice(), manual_coordinates=prior) + self.params.put(DOCUMENT_KEY, json.loads(serialize_document({str(cp.carFingerprint): profile})), block=True) + self.assertEqual(load(cp, self.scope.controller_mode, self.params), (None, 'context_changed')) + page = self.gateway.page('tuning', *self.identity) + self.assertTrue(any(row['confirm'] and row['available'] for row in page['rows'])) + self.assertEqual(self.stored(), self.raw) + + def test_empty_device_recovers_all_values_as_manual_without_auto_qualification(self): + from openpilot.starpilot.flm.manual_coordinates import load + from openpilot.starpilot.flm.torque_stages import StageFrame + backup = self.owner.export() + self.assertEqual(backup['version'], 2) + self.assertFalse(backup['recovery']['trials'][self.scope.key()]) + empty = encode(decode(None)) + self.params.put(KEY, empty, block=True) + preview = self.preview(backup, 'recovery') + self.assertIn('manual tune', preview['question']) + self.assertEqual(preview['count'], 3) + self.assertEqual(self.stored(), empty) + result = self.confirm(preview) + self.assertTrue(result['manual']) + self.assertEqual(self.stored(), empty, 'Manual recovery must never manufacture learned qualification') + cp = self.fixture.context.value.cp + effect, status = load(cp, self.scope.controller_mode, self.params) + self.assertEqual(status, 'configured') + self.assertIsNotNone(effect) + self.assertEqual(dict(effect.profile.values), self.row['values']) + frame = StageFrame(25., .3, 0., .3, .3, True, False, False) + effect.begin_frame() + ff, threshold = effect.selected_stage(frame, original_anchor=effect.original_effect_anchor) + self.assertEqual(ff, .3) + self.assertAlmostEqual(threshold, .3 * 1.0048) + original_context = {key: value for key, value in self.compatibility.items() if key != 'settings_sha256'} + with patch('openpilot.starpilot.flm.runtime_adapter_registry.compatibility_for', return_value=original_context): + self.assertTrue(effect.compatible(cp, None, None, self.params)) + with patch('openpilot.starpilot.flm.runtime_adapter_registry.compatibility_for', return_value=dict(self.compatibility, controller_revision='changed')): + self.assertFalse(effect.compatible(cp, None, None, self.params)) + + def test_recovered_manual_profile_exports_and_restores_again_without_history(self): + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, parse_document + backup = self.owner.export() + self.params.put(KEY, encode(decode(None)), block=True) + self.assertTrue(self.confirm(self.preview(backup, 'recovery'))['manual']) + original = Path(self.params.get_param_path(DOCUMENT_KEY)).read_bytes() + second = self.owner.export() + self.assertIsInstance(second['recovery']['manualProfile'], str) + self.assertIsNone(second['recovery']['setup']) + Path(self.params.get_param_path(DOCUMENT_KEY)).unlink() + self.assertTrue(self.confirm(self.preview(second, 'recovery'))['manual']) + self.assertEqual(Path(self.params.get_param_path(DOCUMENT_KEY)).read_bytes(), original) + with patch('openpilot.starpilot.flm.offroad_runtime.current_compatibility', return_value=self.compatibility): + page = self.gateway.page('tuning', *self.identity) + curves = [row for row in page['rows'] if row.get('coordinate', '').startswith('friction_threshold_')] + self.assertEqual(len(curves), 5) + self.assertFalse(any(row['available'] for row in curves)) + index = next(i for i, row in enumerate(page['rows']) if row.get('coordinate') == 'ff_gain_left') + intent = self.gateway.preview(page['view'], index, 0, *self.identity, value=.5) + self.assertTrue(self.gateway.confirm(intent['intent'], *self.identity)) + profile = parse_document(Path(self.params.get_param_path(DOCUMENT_KEY)).read_bytes())[str(self.fixture.context.value.cp.carFingerprint)] + self.assertEqual(dict(profile.manual_coordinates.values)['friction_threshold_mid'], .0036) + self.assertEqual(dict(profile.manual_coordinates.values)['ff_gain_left'], .005) + self.assertEqual(decode(self.stored()).get(NAMESPACE, {}), {}) + + def test_manual_recovery_retains_trial_and_rollback_provenance_and_refuses_regression(self): + cache = AssessmentCache(directory_for_params(self.params)) + self.assertTrue(cache.claim_trial(self.row['analysis_sha256'], 'a' * 32)) + backup = self.owner.export() + self.assertTrue(backup['recovery']['trials'][self.scope.key()]) + rolled = deepcopy(self.row) + rolled.update(state='rolled_back', values=dict(rolled['previous'])) + self.params.put(KEY, encode({'version': 3, 'profiles': {}, 'fullSurfaces': {}, NAMESPACE: {self.scope.key(): rolled}}), block=True) + with self.assertRaisesRegex(BackupRefused, 'rollback'): + self.preview(backup, 'recovery') + self.assertTrue((cache.directory / ('trial-' + self.row['analysis_sha256'] + '.json')).exists()) + self.assertEqual(decode(self.stored())[NAMESPACE][self.scope.key()]['state'], 'rolled_back') + + def test_manual_recovery_interruption_and_incompatible_source_do_not_change_saved_data(self): + from types import SimpleNamespace + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY + backup = self.owner.export() + self.params.put(KEY, encode(decode(None)), block=True) + before = self.stored() + with patch('openpilot.starpilot.galaxy.flm_backup.current_compatibility', return_value=dict(self.compatibility, controller_revision='different')): + with self.assertRaisesRegex(BackupRefused, 'matches the current steering'): + self.preview(backup, 'recovery') + preview = self.preview(backup, 'recovery') + with patch('openpilot.starpilot.galaxy.flm_backup.commit_exact', return_value=SimpleNamespace(committed=False, verified=False)): + with self.assertRaisesRegex(SettingsChanged, 'not confirmed'): + self.confirm(preview) + self.assertEqual(self.stored(), before) + self.assertFalse(Path(self.params.get_param_path(DOCUMENT_KEY)).exists()) + def test_authenticated_http_download_preview_restore_origin_and_size_guards(self): access = GalaxyAccessOwner(Path(self.params.get_param_path(KEY)).parent.parent / 'backup-access') self.assertTrue(access.configure('password123', lambda: True)) diff --git a/openpilot/starpilot/galaxy/tests/test_flm_review.mjs b/openpilot/starpilot/galaxy/tests/test_flm_review.mjs index f3b9c26bc8..d01dcc435f 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_review.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_review.mjs @@ -89,7 +89,7 @@ assert(emptyText.includes('Saved tune not reported')) assert(!emptyText.includes('Earlier report'), 'No-report state must not pretend an earlier report exists') const tuneFile = { format: 'starpilot-flm-tune', version: 1, vehicle: 'DECLARED_UI_CAR', manual: [], learned: {} } assert.deepEqual(parseTune(JSON.stringify(tuneFile)), tuneFile) -for (const invalid of ['{', 'x'.repeat(65537), JSON.stringify({ ...tuneFile, version: 2 }), JSON.stringify({ ...tuneFile, learned: [] })]) +for (const invalid of ['{', 'x'.repeat(65537), JSON.stringify({ ...tuneFile, version: 3 }), JSON.stringify({ ...tuneFile, learned: [] })]) assert.throws(() => parseTune(invalid)) const transfer = { ...FlmBackup.data(), parked: true, bluetooth: false, unauthorized() {}, $emit() {} } for (const [name, fn] of Object.entries(FlmBackup.methods)) transfer[name] = fn.bind(transfer) diff --git a/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs b/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs index c3a6734306..abff606483 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs @@ -17,7 +17,7 @@ const targetIndex = SURFACE_NAMES.indexOf('highway_center_taper_max') const running = child => child.exitCode === null && child.signalCode === null assert.equal(running({ exitCode: null, signalCode: 'SIGTERM' }), false, 'A signal-reaped child must not be awaited for a second exit') let scenario = 'ideas', parked = true, saveError = false, reportError = false, pending = null -let backupReject = false +let backupReject = false, backupRecovery = false, manualRecovered = false const tuneBackup = { format: 'starpilot-flm-tune', version: 1, vehicle: 'DECLARED_UI_CAR', metric: false, controllerMode: 'starpilot', cpSha256: 'a'.repeat(64), createdAt: '2026-11-16T03:00:00Z', checksum: 'declared-ui-checksum', manual: [{ page: 'tuning', key: 'torque:surface:highway_center_taper_max', value: '0.5' }], learned: {} } @@ -102,6 +102,9 @@ function settings() { 'Shapes small steering corrections at this stage. Higher and lower values change the controller response. Parked only. Manual overrides pause Auto Learn.', value: manual[coordinate].toFixed(4), minimum: -25, maximum: 25, step: .25, unit: '%', defaultValue: 0, resetAvailable: parked, available: parked, action: true })), + ...(manualRecovered ? ['crawl','low','mid','fast','highway'].map((speed, index) => ({ coordinate: 'friction_threshold_' + speed, + label: 'Recovered speed correction', value: [0,0,.36,.48,.48][index].toFixed(4), unit: '%', available: false, action: false, + reason: 'Saved by explicit manual recovery. Auto Learn is paused.' })) : []), { label: 'Reset all manual overrides', reason: 'Remove the thirty manual overrides.', value: 'Reset', confirm: true, available: parked, action: true }] } } const stylesheetLinks = [...(await readFile(join(root, 'index.html'), 'utf8')).matchAll(/]*rel="stylesheet"[^>]*>/g)].map(row => row[0].replaceAll('href="./', 'href="/')).join('\n') @@ -130,13 +133,18 @@ const server = createServer(async (req, res) => { let raw = ''; for await (const chunk of req) raw += chunk const body = JSON.parse(raw); requests.push({ path: pathname, body }) if (!parked || saveError) return json({ error: 'Declared save refusal' }, 503) - if (pathname === '/api/settings/flm-backup/preview') return backupReject ? json({ error: 'No Auto Learn setup matches the current controller.' }, 409) : - json({ intent: 'declared-backup-intent', question: 'Restore these manual slider values? Manual overrides pause Auto Learn.', count: 1, - changes: [['Highway center taper', '0', '0.5']] }) + if (pathname === '/api/settings/flm-backup/preview') { + backupRecovery = body.mode === 'recovery' + return backupReject ? json({ error: 'No Auto Learn setup matches the current controller.' }, 409) : + json({ intent: 'declared-backup-intent', question: backupRecovery ? 'Recover these values as your manual tune? Auto Learn pauses until you reset the manual tune.' : + 'Restore these manual slider values? Manual overrides pause Auto Learn.', count: 1, + changes: [['Highway center taper', '0', '0.5']] }) + } if (pathname === '/api/settings/flm-backup/confirm') { assert.equal(body.intent, 'declared-backup-intent');assert.equal(body.confirmed, true) manual.highway_center_taper_max = .5 - return json({ complete: true, restored: 1, unchanged: 0, skipped: [] }) + if (backupRecovery) manualRecovered = true + return json({ complete: true, restored: 1, manual: backupRecovery, unchanged: 0, skipped: [] }) } if (pathname.endsWith('/preview') || pathname.endsWith('/reset-default')) { pending = { intent: 'declared-intent-' + requests.length, row: body.row, value: pathname.endsWith('/reset-default') ? 0 : body.value } @@ -523,6 +531,25 @@ try { await until(() => execute('return document.querySelector("dialog[open]").textContent.includes("No Auto Learn setup matches")')) assert(!await execute('return !!document.querySelector("#flm-restore-title")'), 'Incompatible backup never reaches confirmation') await capture('backup-incompatible');await click('dialog[aria-labelledby=flm-import-title] .gx-actions button:first-child') + backupReject = false + await viewport(416) + await execute(`const input=document.querySelector('[data-role=flm-backup] input[type=file]'),files=new DataTransfer(); + files.items.add(new File([arguments[0]],'tune-v2.json',{type:'application/json'}));input.files=files.files;input.dispatchEvent(new Event('change',{bubbles:true}))`, + JSON.stringify({ ...tuneBackup, version: 2, recovery: { compatibility: null, setup: null, manualProfile: null, trials: {} } })) + await until(() => execute('return !!document.querySelector("#flm-import-title")')) + await click('dialog[aria-labelledby=flm-import-title] input[value=recovery]') + await click('dialog[aria-labelledby=flm-import-title] .gx-actions button:last-child') + await until(() => execute('return !!document.querySelector("#flm-restore-title")')) + assert.equal(requests.at(-1).body.mode, 'recovery') + assert(await execute('return document.querySelector("dialog[open]").textContent.includes("your manual tune")')) + await layout('backup/manual-recovery');await capture('backup-manual-recovery') + await click('dialog[aria-labelledby=flm-restore-title] .gx-actions button:last-child') + await until(() => execute('return !document.querySelector("dialog[open]")')) + await until(() => execute('return document.querySelector("[data-role=flm-backup]").textContent.includes("Auto Learn is paused")')) + await until(() => execute('return !!document.querySelector("#tuner-recovered-title")')) + await show('#tuner-recovered-title');await layout('backup/recovered-manual-values');await capture('backup-recovered-manual-values') + assert(await execute('return document.querySelector("#tuner-recovered-title").parentElement.textContent.includes("Auto Learn paused")')) + checks.push('backup/explicit-manual-recovery-without-auto-qualification') await change('applied', { parked: false });await click('#tuner-tab-tune') await click('[data-role=flm-backup] summary') assert(await execute('return document.querySelector("[data-role=flm-backup] .gx-actions button:last-of-type").disabled')) diff --git a/openpilot/starpilot/galaxy/web/js/flm-backup.js b/openpilot/starpilot/galaxy/web/js/flm-backup.js index 07dca20c04..67dfe4a9ea 100644 --- a/openpilot/starpilot/galaxy/web/js/flm-backup.js +++ b/openpilot/starpilot/galaxy/web/js/flm-backup.js @@ -7,7 +7,7 @@ export function parseTune(text) { if (new TextEncoder().encode(text).length > MAX_TUNE_BYTES) throw new Error('Tune backup is too large.') let value try { value = JSON.parse(text) } catch { throw new Error('Choose a valid JSON tune backup.') } - if (value?.format !== 'starpilot-flm-tune' || value.version !== 1 || !Array.isArray(value.manual) || value.manual.length > 30 || + if (value?.format !== 'starpilot-flm-tune' || ![1, 2].includes(value.version) || !Array.isArray(value.manual) || value.manual.length > 30 || !value.learned || typeof value.learned !== 'object' || Array.isArray(value.learned) || Object.keys(value.learned).length > 8 || typeof value.vehicle !== 'string' || value.vehicle.length > 128) throw new Error('Choose a supported FLM tune backup.') return value @@ -28,7 +28,7 @@ export const FlmBackup = { if (this.busy || this.bluetooth) return this.busy = true;this.error = this.notice = '' try { - const text = JSON.stringify(await this.request('./api/flm/backup'), null, 2) + const text = JSON.stringify(await this.request('./api/flm/backup')) parseTune(text) const file = new File([text], 'starpilot-flm-tune.json', { type: 'application/json' }) if (share && navigator.canShare?.({ files: [file] })) { @@ -68,7 +68,7 @@ export const FlmBackup = { try { const result = await this.request('./api/settings/flm-backup/confirm', { intent, confirmed: true }) if (result.complete !== true) throw new Error(result.error || 'Restore stopped. Refresh your tune before retrying.') - this.pending = this.draft = null;this.notice = result.restored ? `${result.restored} ${result.restored === 1 ? 'setting' : 'settings'} restored. Current application is shown separately.` : 'Your saved settings already match this backup.' + this.pending = this.draft = null;this.notice = result.manual ? 'Manual tune recovered. Auto Learn is paused; your learning history is preserved.' : result.restored ? `${result.restored} ${result.restored === 1 ? 'setting' : 'settings'} restored. Current application is shown separately.` : 'Your saved settings already match this backup.' this.$emit('restored') } catch (error) { this.pending = null;this.error = error.message || 'Could not confirm the restore. Refresh your tune before retrying.';this.$emit('restored') } finally { this.busy = false } @@ -84,10 +84,11 @@ export const FlmBackup = {
Park and switch off the vehicle to restore settings.
Working…
{{ draft.vehicle.replaceAll('_', ' ') }} · {{ draft.manual.length }} manual settings · {{ Object.keys(draft.learned).length }} Auto Learn setups
+{{ draft.vehicle.replaceAll('_', ' ') }} · {{ draft.manual.length }} manual {{ draft.manual.length === 1 ? 'setting' : 'settings' }} · {{ Object.keys(draft.learned).length }} Auto Learn setups
Auto Learn restore requires the matching controller, vehicle and this device’s retained qualification history. Manual overrides pause Auto Learn.
+ + +Auto Learn setup restores a setup this comma already knows. On a wiped or replacement comma, choose Recover as manual tune. Manual recovery pauses Auto Learn.
Saved manual settings · Auto Learn paused
+These speed adjustments came from your reviewed backup. Applied state is reported separately.
+Reset manual tune to remove the recovered settings.
+Choose an area below. Amber labels show findings from your drive.
{{ group === 'friction' ? 'MANAGED BY AUTO LEARN' : 'YOUR MANUAL CONTROLS' }}
{{ selectedGroup.description }}
Moving a slider saves a manual override for your next drive and pauses Auto Learn. Zero removes the override. Reviewing a finding does neither.