diff --git a/.github/workflows/flm-offroad.yaml b/.github/workflows/flm-offroad.yaml index 90c4c4cd77..56d7a99ccb 100644 --- a/.github/workflows/flm-offroad.yaml +++ b/.github/workflows/flm-offroad.yaml @@ -74,6 +74,7 @@ jobs: openpilot/starpilot/flm/tests/test_offroad_backend.py \ openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py \ openpilot/starpilot/flm/tests/test_offroad_retained_trials.py \ + openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py \ openpilot/starpilot/flm/tests/test_route_recording_clocks.py \ openpilot/starpilot/flm/tests/test_configured_route_recording.py \ openpilot/starpilot/flm/tests/test_observed_maneuvers.py \ diff --git a/openpilot/starpilot/flm/calibration_lifecycle.py b/openpilot/starpilot/flm/calibration_lifecycle.py index cba4e8fcaf..6190e8ad79 100644 --- a/openpilot/starpilot/flm/calibration_lifecycle.py +++ b/openpilot/starpilot/flm/calibration_lifecycle.py @@ -120,3 +120,16 @@ class ConsumerCalibrationLifecycle: generation in self.rejected): return False return self.capture(generation) + + +def configuration_calibration(sm, calibration_lifecycle, now): + # Calibration describes the vehicle frame, not a per-message command lease. + # Like torqued's PoseCalibrator, retain a valid calibrated transform between + # deliveries. Sample freshness and current native authority are checked + # independently when admitting physical observations and applying offers. + stamp = int(sm.logMonoTime['extrinsicsCalibration']) + receipt = int(round(sm.recv_time['extrinsicsCalibration'] * 1e9)) + if not (sm.seen['extrinsicsCalibration'] and sm.valid['extrinsicsCalibration'] and + 0 < stamp <= now and 0 < receipt <= now): + return calibration_lifecycle.observe(None, current=False) + return calibration_lifecycle.observe(sm['extrinsicsCalibration'], current=True) diff --git a/openpilot/starpilot/flm/offroad_analysis.py b/openpilot/starpilot/flm/offroad_analysis.py index 25e764fcfb..af37f9fe5a 100644 --- a/openpilot/starpilot/flm/offroad_analysis.py +++ b/openpilot/starpilot/flm/offroad_analysis.py @@ -5,7 +5,7 @@ import hashlib import json from openpilot.starpilot.flm.canonical_surface_adapter import NAMES -from openpilot.starpilot.flm.offroad_evidence import RouteWindow +from openpilot.starpilot.flm.offroad_evidence import RouteWindow, cohort from openpilot.starpilot.flm.offroad_tracking import estimate, suggest from openpilot.starpilot.flm.offroad_coordinate_policy import tracking_coordinate_candidates @@ -13,31 +13,6 @@ MAX_WINDOWS = 4096 MAX_COHORT_WINDOWS = 24 -def cohort(window): - """Classify only original reference and speed; never errors or response.""" - if type(window) is not RouteWindow or not window.valid(): - raise ValueError('Original complete tracking window required') - points = window.points - speed = tuple(p.speed_mps for p in points) - bands = {0 if v < 10 else 1 if v < 20 else 2 for v in speed} - if len(bands) != 1: - return None - floor = 0.03 if window.domain == 'lateral_acceleration' else 0.1 - signs = {1 if p.desired > floor else -1 if p.desired < -floor else 0 for p in points} - center_limit = 0.3 if window.domain == 'lateral_acceleration' else 3.0 - if len(signs) != 1 or 0 in signs: - if max(abs(p.desired) for p in points) <= center_limit: - return str(next(iter(bands))) + ':both:center' - return None - # A whole maneuver section is used; no error-based crop or sample matching. - start = sum(abs(p.desired) for p in points[:10]) / 10 - end = sum(abs(p.desired) for p in points[-10:]) / 10 - duration = (points[-1].mono_ns - points[0].mono_ns) / 1e9 - slope = (end - start) / duration - threshold = max(floor, 0.15 * max(start, end)) - phase = 'turn_in' if slope > threshold else 'unwind' if slope < -threshold else 'steady' - side = 'left' if next(iter(signs)) > 0 else 'right' - return str(next(iter(bands))) + ':' + side + ':' + phase def _spread(rows, count): diff --git a/openpilot/starpilot/flm/offroad_cache.py b/openpilot/starpilot/flm/offroad_cache.py index cf9b88d587..54db4202a1 100644 --- a/openpilot/starpilot/flm/offroad_cache.py +++ b/openpilot/starpilot/flm/offroad_cache.py @@ -261,3 +261,18 @@ class AssessmentCache: self._write('inputs.json', json.dumps(rows[-MAX_CHECKPOINTS:], sort_keys=True, separators=(',', ':'), allow_nan=False).encode()) self._write('latest.json', raw) + +def trial_origin(cache, digest): + for _ in range(8): + value = cache.get(digest) + if value.get('kind') == 'next_drive_trial': + return digest, value + if value.get('kind') != 'next_drive_outcome': + break + digest = value['trial_analysis_sha256'] + raise ValueError('Bounded original next-drive trial lineage required') + + +def trial_document(cache, digest): + return trial_origin(cache, digest)[1] + diff --git a/openpilot/starpilot/flm/offroad_daemon.py b/openpilot/starpilot/flm/offroad_daemon.py index ffb4b10f6f..3aaee7c130 100644 --- a/openpilot/starpilot/flm/offroad_daemon.py +++ b/openpilot/starpilot/flm/offroad_daemon.py @@ -4,6 +4,7 @@ import json import os from pathlib import Path import signal +import sys import tempfile import time import traceback @@ -12,8 +13,6 @@ from typing import Any from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog -from openpilot.starpilot.flm.offroad_route import RouteInputError -from openpilot.starpilot.flm.offroad_worker import OffroadWorker from openpilot.starpilot.flm.training_report import report_path, READ_MAX_BYTES, _report_bounded @@ -289,6 +288,8 @@ def wait_for_parked(sm, params, *, stopped=lambda: False, clock=time.monotonic): def run_parked_analysis(worker, report): """Advance promptly only after an unreadable input was durably skipped.""" + from openpilot.starpilot.flm.offroad_route import RouteInputError + try: report.set(worker.run_once()) except (ValueError, OSError, RuntimeError) as error: @@ -309,7 +310,7 @@ def run_parked_analysis(worker, report): return False -def main(): +def _run(): from openpilot.common.hardware.hw import Paths from openpilot.starpilot.flm.offroad_cache import directory_for_params from openpilot.starpilot.flm.offroad_source import record_drive @@ -321,8 +322,9 @@ def main(): nonlocal stopped stopped = True - previous = signal.signal(signal.SIGTERM, stop) + previous = {sig: signal.signal(sig, stop) for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)} sm = None + restart = False report = StatusReport() try: sm = messaging.SubMaster(['deviceState', 'pandaStates', 'peripheralState']) @@ -336,28 +338,13 @@ def main(): return okay cache = directory_for_params(params) - worker = OffroadWorker( - params, - Paths.log_root(), - cache, - permitted=permitted, - on_analysis=lambda: report.analyzing({'status': 'fitting', 'reason': 'analyzing_last_completed_drive'}), - on_assessment=lambda a: report.analyzing( - { - 'status': 'fitting', - 'reason': 'checking_recorded_steering_recommendations', - 'completed_route': a.receipt.route_id, - 'vehicle': str(a.cp.carFingerprint), - 'analysis_counts': dict(a.counts), - 'recorded_tracking': a.recorded_tracking, - } - ), - on_recommendations=lambda value: report.analyzing({**value, 'reason': 'checking_recorded_steering_recommendations'}), - ) - report.restore(worker.cache) + worker = None next_analysis = 0.0 while not stopped: if not params.get_bool('IsOffroad'): + if worker is not None: + restart = True + break report.set({'enabled': True, 'status': 'collecting', 'reason': 'recording_for_offroad_analysis'}) record_drive( params, @@ -377,6 +364,28 @@ def main(): ), ) elif parked() and time.monotonic() >= next_analysis: + if worker is None: + from openpilot.starpilot.flm.offroad_worker import OffroadWorker + + worker = OffroadWorker( + params, + Paths.log_root(), + cache, + permitted=permitted, + on_analysis=lambda: report.analyzing({'status': 'fitting', 'reason': 'analyzing_last_completed_drive'}), + on_assessment=lambda a: report.analyzing( + { + 'status': 'fitting', + 'reason': 'checking_recorded_steering_recommendations', + 'completed_route': a.receipt.route_id, + 'vehicle': str(a.cp.carFingerprint), + 'analysis_counts': dict(a.counts), + 'recorded_tracking': a.recorded_tracking, + } + ), + on_recommendations=lambda value: report.analyzing({**value, 'reason': 'checking_recorded_steering_recommendations'}), + ) + report.restore(worker.cache) next_analysis = time.monotonic() + 10.0 if run_parked_analysis(worker, report): next_analysis = time.monotonic() @@ -384,14 +393,35 @@ def main(): if not stopped: time.sleep(0.05) finally: - signal.signal(signal.SIGTERM, previous) - if sm is not None: - for sock in sm.sock.values(): - close = getattr(sock, 'close', None) - if close is not None: - close() + try: + if sm is not None: + for sock in sm.sock.values(): + close = getattr(sock, 'close', None) + if close is not None: + close() + finally: + for sig, handler in previous.items(): + signal.signal(sig, handler) + return restart and not stopped + + +_CLEAN_IMAGE = '--flm-clean-image' + + +def _clean_image(): + # Release both the manager's inherited heap and every parked allocation. + # Reuse its launcher to retain crash/logging setup and the tracked PID. + code = "from openpilot.system.manager.process import launcher; launcher('openpilot.starpilot.flm.offroad_daemon', 'steerlearnerd')" + os.execv(sys.executable, [sys.executable, '-c', code, _CLEAN_IMAGE]) + + +def main(): + if sys.argv[-1:] != [_CLEAN_IMAGE]: + _clean_image() + return + if _run(): + _clean_image() if __name__ == '__main__': main() - diff --git a/openpilot/starpilot/flm/offroad_evidence.py b/openpilot/starpilot/flm/offroad_evidence.py index f827a32bab..82368ec850 100644 --- a/openpilot/starpilot/flm/offroad_evidence.py +++ b/openpilot/starpilot/flm/offroad_evidence.py @@ -284,3 +284,50 @@ def compare_same_windows(windows, predicted_actual, *, minimum_windows=3, model_ 'no_overshoot_regression': all(row['no_overshoot_regression'] for row in metrics), 'no_peak_error_regression': all(row['no_peak_error_regression'] for row in metrics), } + + +def cohort(window): + """Classify only original reference and speed; never errors or response.""" + if type(window) is not RouteWindow or not window.valid(): + raise ValueError('Original complete tracking window required') + points = window.points + speed = tuple(p.speed_mps for p in points) + bands = {0 if v < 10 else 1 if v < 20 else 2 for v in speed} + if len(bands) != 1: + return None + floor = 0.03 if window.domain == 'lateral_acceleration' else 0.1 + signs = {1 if p.desired > floor else -1 if p.desired < -floor else 0 for p in points} + center_limit = 0.3 if window.domain == 'lateral_acceleration' else 3.0 + if len(signs) != 1 or 0 in signs: + if max(abs(p.desired) for p in points) <= center_limit: + return str(next(iter(bands))) + ':both:center' + return None + # A whole maneuver section is used; no error-based crop or sample matching. + start = sum(abs(p.desired) for p in points[:10]) / 10 + end = sum(abs(p.desired) for p in points[-10:]) / 10 + duration = (points[-1].mono_ns - points[0].mono_ns) / 1e9 + slope = (end - start) / duration + threshold = max(floor, 0.15 * max(start, end)) + phase = 'turn_in' if slope > threshold else 'unwind' if slope < -threshold else 'steady' + side = 'left' if next(iter(signs)) > 0 else 'right' + return str(next(iter(bands))) + ':' + side + ':' + phase + + +def window_demand(window): + import math + + points = window.points + rms = math.sqrt(sum(p.desired**2 for p in points) / len(points)) + return { + 'domain': window.domain, + 'duration_ns': points[-1].mono_ns - points[0].mono_ns, + 'speed_low': min(p.speed_mps for p in points), + 'speed_high': max(p.speed_mps for p in points), + 'goal_rms': rms, + 'goal_shape': [ + sum(p.desired for p in points[i * len(points) // 8 : (i + 1) * len(points) // 8]) / len(points[i * len(points) // 8 : (i + 1) * len(points) // 8]) / rms + if rms > 0 + else 0.0 + for i in range(8) + ], + } diff --git a/openpilot/starpilot/flm/offroad_processor.py b/openpilot/starpilot/flm/offroad_processor.py index 50148a3b01..6472eb4da4 100644 --- a/openpilot/starpilot/flm/offroad_processor.py +++ b/openpilot/starpilot/flm/offroad_processor.py @@ -8,7 +8,7 @@ from openpilot.starpilot.flm.offroad_analysis import analyze, MAX_WINDOWS, cohor from openpilot.starpilot.flm.offroad_baseline_windows import baseline_windows from openpilot.starpilot.flm.canonical_surface_adapter import NAMES as AMPLITUDE_NAMES from openpilot.starpilot.flm.offroad_residual import analyze_stable_windows -from openpilot.starpilot.flm.offroad_evidence import read_point, whole_windows, eligible_points, tracking_metrics +from openpilot.starpilot.flm.offroad_evidence import read_point, whole_windows, eligible_points, tracking_metrics, window_demand from openpilot.starpilot.flm.offroad_route import ( latest_route, walk_completed_route, RouteInputCancelled, RouteReceipt, SelectedSourceReceipt, PartialRouteReceipt, route_permission, ) @@ -57,24 +57,6 @@ class CompletedAssessment: } -def window_demand(window): - import math - - points = window.points - rms = math.sqrt(sum(p.desired**2 for p in points) / len(points)) - return { - 'domain': window.domain, - 'duration_ns': points[-1].mono_ns - points[0].mono_ns, - 'speed_low': min(p.speed_mps for p in points), - 'speed_high': max(p.speed_mps for p in points), - 'goal_rms': rms, - 'goal_shape': [ - sum(p.desired for p in points[i * len(points) // 8 : (i + 1) * len(points) // 8]) / len(points[i * len(points) // 8 : (i + 1) * len(points) // 8]) / rms - if rms > 0 - else 0.0 - for i in range(8) - ], - } def _separate_qualification(report, continuous, *, proposal_windows=None, route_order=None, role_windows=None): diff --git a/openpilot/starpilot/flm/offroad_quality.py b/openpilot/starpilot/flm/offroad_quality.py index 7cff03f524..3a53eef9ee 100644 --- a/openpilot/starpilot/flm/offroad_quality.py +++ b/openpilot/starpilot/flm/offroad_quality.py @@ -11,9 +11,7 @@ import math import os from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES as NAMES -from openpilot.starpilot.flm.offroad_analysis import cohort -from openpilot.starpilot.flm.offroad_evidence import read_point, RouteWindow, window_identity, tracking_metrics -from openpilot.starpilot.flm.offroad_processor import window_demand +from openpilot.starpilot.flm.offroad_evidence import cohort, read_point, RouteWindow, window_identity, tracking_metrics, window_demand from openpilot.starpilot.flm.offroad_surface import REVISION from openpilot.starpilot.flm.offroad_surface import stop_marker @@ -164,12 +162,16 @@ class TrialGuard: def from_configuration(cp, params, cache_directory, *, vehicle_session): - from openpilot.starpilot.flm.offroad_worker import _current_scope, trial_document - from openpilot.starpilot.flm.offroad_store import startup_row - from openpilot.starpilot.flm.offroad_cache import AssessmentCache + from openpilot.starpilot.flm.offroad_runtime import current_scope + from openpilot.starpilot.flm.offroad_store import startup_row, KEY, MAX_BYTES + from openpilot.starpilot.flm.offroad_cache import AssessmentCache, trial_document + from openpilot.starpilot.saved_source import read_saved try: - scope = _current_scope(cp, params) + raw, readable = read_saved(params, KEY, MAX_BYTES) + if not readable or raw is None: + return None + scope = current_scope(cp, params) row, _ = startup_row(params, scope) except (OSError, KeyError, TypeError, ValueError, AttributeError, OverflowError): return None diff --git a/openpilot/starpilot/flm/offroad_runtime.py b/openpilot/starpilot/flm/offroad_runtime.py index 27983281da..e0ad083397 100644 --- a/openpilot/starpilot/flm/offroad_runtime.py +++ b/openpilot/starpilot/flm/offroad_runtime.py @@ -285,3 +285,28 @@ def configure(cp, ci, controller, params, *, manual_status): return RouteEffects(scope, values, numeric, previous=previous, fixed_numeric=fixed), 'configured_pending_actual_stage' except (AttributeError, KeyError, TypeError, ValueError, UnicodeError, OSError, OverflowError): return None, 'configuration_unavailable' + + +def current_configuration(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 + from openpilot.starpilot.flm.pid_controller_replay import PidControllerFactory + from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences + + startup = VehicleStartupPreferences.read(params, enabled=params.get_bool('OpenpilotEnabledToggle')) + mode = 'native' if cp.lateralTuning.which() == 'pid' else str(read_selection(params, cp).mode) + 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) + from openpilot.starpilot.flm.runtime_adapter_registry import selected_descriptor + + scope, numeric = configuration_scope(cp, ci, controller, params, manual_status='not_configured') + descriptor = selected_descriptor(cp, ci, controller) + if descriptor is None: + raise ValueError('Current registered controller required') + return scope, descriptor, numeric + + +def current_scope(cp, params): + return current_configuration(cp, params)[0] diff --git a/openpilot/starpilot/flm/offroad_source.py b/openpilot/starpilot/flm/offroad_source.py index e7ee60ece4..9c1efaeed9 100644 --- a/openpilot/starpilot/flm/offroad_source.py +++ b/openpilot/starpilot/flm/offroad_source.py @@ -15,7 +15,7 @@ def record_drive(params, *, stopped, on_status=None): from openpilot.starpilot.flm.calibration_lifecycle import ProducerCalibrationLifecycle from openpilot.starpilot.flm.runtime_adapter_registry import read_source, car_params_digest from openpilot.starpilot.flm.learning_wire import result_message, write_source_receipt - from openpilot.starpilot.flm.steerlearnerd import _configuration_calibration + from openpilot.starpilot.flm.calibration_lifecycle import configuration_calibration as _configuration_calibration cp_raw = params.get('CarParams') if not cp_raw or stopped() or params.get_bool('IsOffroad'): @@ -52,9 +52,12 @@ def record_drive(params, *, stopped, on_status=None): sm.update(50) now = time.monotonic_ns() quality_header = int(sm.logMonoTime['controlsState']) + control = None + control_decoded = False if guard is not None and guard.stopped is None and sm.updated['controlsState'] and quality_header - last_quality_header >= 25_000_000: last_quality_header = quality_header packet = sm.original.get('starpilotLateralState') + control_decoded = True try: control = None if packet is None else read_control(packet) except (ValueError, KeyError, TypeError, AttributeError, OverflowError): @@ -86,10 +89,13 @@ def record_drive(params, *, stopped, on_status=None): pm.send('autoSteeringLearning', message) if on_status is not None: packet = sm.original.get('starpilotLateralState') - try: - actual = None if packet is None else read_control(packet) - except (ValueError, KeyError, TypeError, AttributeError, OverflowError): - actual = None + if control_decoded: + actual = control + else: + try: + actual = None if packet is None else read_control(packet) + except (ValueError, KeyError, TypeError, AttributeError, OverflowError): + actual = None if ( actual is None or not actual.valid diff --git a/openpilot/starpilot/flm/offroad_worker.py b/openpilot/starpilot/flm/offroad_worker.py index 527b595c09..54875d7ea5 100644 --- a/openpilot/starpilot/flm/offroad_worker.py +++ b/openpilot/starpilot/flm/offroad_worker.py @@ -14,11 +14,11 @@ from typing import Any from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES as NAMES from openpilot.starpilot.flm.learned_lifecycle import decode -from openpilot.starpilot.flm.offroad_cache import AssessmentCache, MAX_CHECKPOINTS +from openpilot.starpilot.flm.offroad_cache import AssessmentCache, MAX_CHECKPOINTS, trial_origin, trial_document from openpilot.starpilot.flm.offroad_checks import qualify from openpilot.starpilot.flm.offroad_processor import analyze_latest, CompletedAssessment from openpilot.starpilot.flm.offroad_route import latest_route, logger_marker, route_inventory, source_revisions, RouteInputError, LOCAL_ID -from openpilot.starpilot.flm.offroad_runtime import configuration_scope +from openpilot.starpilot.flm.offroad_runtime import current_configuration as _current_configuration from openpilot.starpilot.flm.offroad_store import RouteScope, RouteStorage, KEY, MAX_BYTES, MAX_ROUTE_STEP, NAMESPACE from openpilot.starpilot.flm.offroad_surface import REVISION from openpilot.starpilot.flm.offroad_tracking import TrackingEstimate, compare_observed @@ -78,25 +78,6 @@ def _assessment_source_revision(): return _digest((hashes, native_identity(), binding)) -def _current_configuration(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 - from openpilot.starpilot.flm.pid_controller_replay import PidControllerFactory - from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences - - startup = VehicleStartupPreferences.read(params, enabled=params.get_bool('OpenpilotEnabledToggle')) - mode = 'native' if cp.lateralTuning.which() == 'pid' else str(read_selection(params, cp).mode) - 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) - from openpilot.starpilot.flm.runtime_adapter_registry import selected_descriptor - - scope, numeric = configuration_scope(cp, ci, controller, params, manual_status='not_configured') - descriptor = selected_descriptor(cp, ci, controller) - if descriptor is None: - raise ValueError('Current registered controller required') - return scope, descriptor, numeric def _current_scope(cp, params): @@ -160,19 +141,8 @@ def _est(value): return TrackingEstimate(**value) -def trial_origin(cache, digest): - for _ in range(8): - value = cache.get(digest) - if value.get('kind') == 'next_drive_trial': - return digest, value - if value.get('kind') != 'next_drive_outcome': - break - digest = value['trial_analysis_sha256'] - raise ValueError('Bounded original next-drive trial lineage required') -def trial_document(cache, digest): - return trial_origin(cache, digest)[1] def rejected_trial_change(cache, row, proposal): diff --git a/openpilot/starpilot/flm/runtime_adapter_registry.py b/openpilot/starpilot/flm/runtime_adapter_registry.py index 4e2b264174..899b6379be 100644 --- a/openpilot/starpilot/flm/runtime_adapter_registry.py +++ b/openpilot/starpilot/flm/runtime_adapter_registry.py @@ -10,7 +10,6 @@ import time from functools import cache from pathlib import Path import importlib -from opendbc.car.car_helpers import interfaces from openpilot.starpilot.lateral.learning_preferences import read_preference, KEY as PREFERENCE_KEY from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, LEGACY_KEYS, MAX_DOCUMENT_BYTES, parse_document, interpret_legacy from openpilot.starpilot.saved_source import read_saved @@ -396,6 +395,7 @@ class ControllerDescriptor: def selected_descriptor(cp, ci, controller): """Use the registered constructor plus the object actually selected by Controls.""" + from opendbc.car.car_helpers import interfaces from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle from openpilot.selfdrive.controls.lib.latcontrol_curvature import LatControlCurvature @@ -468,6 +468,7 @@ def selected_identity(descriptor, source_epoch, baseline=""): def ford_downstream(cp): # The BluePilot lateral library owns Ford steering when its bit is in the final admitted CP safety word; # no settings read or generic angle-output inference establishes this role. + from opendbc.car.car_helpers import interfaces from opendbc.car.ford.aol import BP_LATERAL, aol_safety_config config = aol_safety_config(cp) if cp.brand == 'ford' else None diff --git a/openpilot/starpilot/flm/steerlearnerd.py b/openpilot/starpilot/flm/steerlearnerd.py index 592de685a9..8e2824d66b 100644 --- a/openpilot/starpilot/flm/steerlearnerd.py +++ b/openpilot/starpilot/flm/steerlearnerd.py @@ -19,6 +19,7 @@ from openpilot.common.params import Params from openpilot.starpilot.flm.fullrate_collector import FullrateCollector, PairedDrainState, drain_pair, ControlEvidence, AppliedEvidence from openpilot.starpilot.flm.learning_wire import read_control, read_applied, result_message, write_source_receipt from openpilot.starpilot.flm.runtime_adapter_registry import SOURCE_LEASE_NS +from openpilot.starpilot.flm.calibration_lifecycle import configuration_calibration as _configuration_calibration class _SourceDelivery: @@ -150,17 +151,6 @@ def _collect_applied_output(collector, applied, sm, cp, now_ns): return collector.output(applied, now_ns) -def _configuration_calibration(sm, calibration_lifecycle, now): - # Calibration describes the vehicle frame, not a per-message command lease. - # Like torqued's PoseCalibrator, retain a valid calibrated transform between - # deliveries. Sample freshness and current native authority are checked - # independently when admitting physical observations and applying offers. - stamp = int(sm.logMonoTime['extrinsicsCalibration']) - receipt = int(round(sm.recv_time['extrinsicsCalibration'] * 1e9)) - if not (sm.seen['extrinsicsCalibration'] and sm.valid['extrinsicsCalibration'] and - 0 < stamp <= now and 0 < receipt <= now): - return calibration_lifecycle.observe(None, current=False) - return calibration_lifecycle.observe(sm['extrinsicsCalibration'], current=True) def _source_config_binding(source): return (source.cp_sha256, source.source_epoch, source.reset, source.calibration_generation, diff --git a/openpilot/starpilot/flm/tests/test_offroad_backend.py b/openpilot/starpilot/flm/tests/test_offroad_backend.py index d9f767ddab..0c0aa8a44c 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_backend.py +++ b/openpilot/starpilot/flm/tests/test_offroad_backend.py @@ -117,7 +117,8 @@ class TestOffroadCache(unittest.TestCase): def test_restart_withdraws_trial_and_accepted_rows_do_not_claim(self): row = {'state': 'ready_for_next_drive', 'values': values(0.01), 'analysis_sha256': self.cache.put(trial())} with ( - patch('openpilot.starpilot.flm.offroad_worker._current_scope', return_value=scope()), + patch('openpilot.starpilot.flm.offroad_runtime.current_scope', return_value=scope()), + patch('openpilot.starpilot.saved_source.read_saved', return_value=(b'declared-present-row', True)), patch('openpilot.starpilot.flm.offroad_store.startup_row', return_value=(row, 'loaded')), ): first = from_configuration(None, None, self.cache.directory, vehicle_session='a' * 32) diff --git a/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py b/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py index d2501cd320..bdd62e6dd3 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py +++ b/openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py @@ -1080,7 +1080,7 @@ class TestBoundedInconclusiveTrialLifecycle(unittest.TestCase): self.assertNotEqual(saved['analysis_sha256'], digest) self.assertEqual(record['trial_analysis_sha256'], first_digest, 'Retained trials keep constant-depth provenance') self.assertFalse((cache.directory / ('trial-' + saved['analysis_sha256'] + '.json')).exists()) - with patch.object(module, '_current_scope', return_value=scope()): + with patch('openpilot.starpilot.flm.offroad_runtime.current_scope', return_value=scope()): guard = from_configuration(None, params, cache.directory, vehicle_session='f' * 32) self.assertIsNotNone(guard) assert guard is not None diff --git a/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py b/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py new file mode 100644 index 0000000000..718a0d051d --- /dev/null +++ b/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py @@ -0,0 +1,302 @@ +"""Process-mode regressions; declared lifecycle/heap, no vehicle or actuator.""" +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +from openpilot.common.params import Params +from openpilot.starpilot.flm import offroad_daemon as daemon +from openpilot.starpilot.flm.offroad_store import KEY + + +class TestParkedProcessLifetime(unittest.TestCase): + def test_driving_imports_do_not_load_the_parked_optimizer(self): + code = ''' +import sys +from openpilot.starpilot.flm import offroad_daemon, offroad_quality, offroad_source +from openpilot.starpilot.flm.calibration_lifecycle import configuration_calibration +from openpilot.starpilot.flm.runtime_adapter_registry import read_source +for name in ('offroad_worker', 'offroad_processor', 'offroad_stable_bridge', 'steerlearnerd', 'controller_replay', 'pid_controller_replay'): + assert 'openpilot.starpilot.flm.' + name not in sys.modules, name +assert 'opendbc.car.car_helpers' not in sys.modules +''' + result = subprocess.run([sys.executable, '-B', '-c', code], capture_output=True, text=True, timeout=15) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_no_saved_tune_does_not_construct_controllers_for_a_guard(self): + from openpilot.starpilot.flm.offroad_quality import from_configuration + with tempfile.TemporaryDirectory() as root: + params = Params(root) + with patch('openpilot.starpilot.flm.offroad_runtime.current_scope', side_effect=AssertionError('No saved map')): + self.assertIsNone(from_configuration(None, params, Path(root) / 'cache', vehicle_session='a' * 32)) + + def test_a_quality_and_status_tick_decode_the_same_original_packet_once(self): + from openpilot.starpilot.flm.offroad_source import record_drive + + for malformed in (False, True): + with self.subTest(malformed=malformed): + now, finished, reports = 1_000_000_000, [], [] + packet = object() + control = SimpleNamespace(valid=True, active=True, manual=False, override=False, fault=False, limited=False, + control_ns=now, route_applied_coordinates=(('declared', .01),)) + guard = SimpleNamespace(stopped=None, marker=None, observe=Mock()) + + class Receiver: + def __init__(self, services, packet=packet, now=now): + self.original = {'starpilotLateralState': packet, 'controlsState': object()} + self.logMonoTime = {'controlsState': now} + self.updated = {'controlsState': True} + self.sock = {} + + def update(self, timeout): + pass + + pm = SimpleNamespace(sock={}, send=lambda *args, finished=finished: finished.append(True)) + message = SimpleNamespace(autoSteeringLearning=SimpleNamespace(learning=SimpleNamespace(reason=''))) + params = SimpleNamespace(get=lambda key: b'declared-cp', get_bool=lambda key: False) + source = SimpleNamespace(enabled=True, observed_ns=now, expires_ns=now + 500_000_000) + with patch('openpilot.starpilot.flm.offroad_source.messaging.SubMaster', Receiver), \ + patch('openpilot.starpilot.flm.offroad_source.messaging.PubMaster', return_value=pm), \ + patch('openpilot.starpilot.flm.offroad_source.messaging.log_from_bytes', return_value=object()), \ + patch('openpilot.starpilot.flm.offroad_source.time.monotonic_ns', return_value=now), \ + patch('openpilot.starpilot.flm.runtime_adapter_registry.car_params_digest', return_value='a' * 64), \ + patch('openpilot.starpilot.flm.runtime_adapter_registry.read_source', return_value=source), \ + patch('openpilot.starpilot.flm.calibration_lifecycle.configuration_calibration', return_value=None), \ + patch('openpilot.starpilot.flm.offroad_cache.directory_for_params', return_value=Path('/declared-cache')), \ + patch('openpilot.starpilot.flm.offroad_quality.from_configuration', return_value=guard), \ + patch('openpilot.starpilot.flm.learning_wire.result_message', return_value=message), \ + patch('openpilot.starpilot.flm.learning_wire.write_source_receipt'), \ + patch('openpilot.starpilot.flm.learning_wire.read_control', side_effect=ValueError('malformed') if malformed else None, + return_value=control) as decode: + record_drive(params, stopped=lambda finished=finished: bool(finished), on_status=lambda *args, reports=reports: reports.append(args)) + decode.assert_called_once_with(packet) + self.assertIs(guard.observe.call_args.args[2], None if malformed else control) + self.assertIs(reports[0][1], None if malformed else control) + + def exercise_transition(self, *, starts_parked, interrupted=None, cancel_on_cleanup=False): + events = [] + prior_signals = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)} + with tempfile.TemporaryDirectory() as root: + params = Params(root) + params.put_bool('IsOffroad', starts_parked, block=True) + params.put(KEY, b'declared-existing-saved-tune') + def close_socket(i): + events.append(('closed', i)) + if cancel_on_cleanup and i == 0: + handler = signal.getsignal(signal.SIGTERM) + if not callable(handler): + raise AssertionError('Cleanup cancellation handler missing') + handler(signal.SIGTERM, None) + + sockets = {str(i): SimpleNamespace(close=lambda i=i: close_socket(i)) for i in range(3)} + sm = SimpleNamespace(sock=sockets) + + class Worker: + def __init__(self, *args, permitted, **kwargs): + events.append('parked-worker') + self.permitted = permitted + self.cache = object() + + def run_once(self): + child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']) + try: + if interrupted is None: + params.put_bool('IsOffroad', False, block=True) + else: + handler = signal.getsignal(interrupted) + if not callable(handler): + raise AssertionError("Cancellation handler missing") + handler(interrupted, None) + self_cancelled = not self.permitted() + events.append(('cancelled', self_cancelled)) + if not self_cancelled: + raise AssertionError('Cancellation must reach the original worker') + raise ValueError('Declared interrupted analysis') + finally: + child.terminate() + child.wait(timeout=3) + events.append('child-reaped') + + def record_failure(self, error): + return {'status': 'collecting', 'reason': 'declared-cancelled'} + + def drive(*args, **kwargs): + events.append('driving-source') + self.assertNotIn('parked-worker', events, 'A cold driving start must not construct the optimizer') + params.put_bool('IsOffroad', True, block=True) + + report = SimpleNamespace(restore=lambda cache: events.append('history-restored'), set=lambda value: None, + publish=lambda: None, analyzing=lambda value: None) + with patch.object(daemon, 'Params', return_value=params), patch.object(daemon.messaging, 'SubMaster', return_value=sm), \ + patch.object(daemon, 'StatusReport', return_value=report), \ + patch.object(daemon, 'wait_for_parked', side_effect=lambda *a, stopped, **k: not stopped() and params.get_bool('IsOffroad')), \ + patch.dict(sys.modules, {'openpilot.starpilot.flm.offroad_worker': SimpleNamespace(OffroadWorker=Worker)}), \ + patch('openpilot.starpilot.flm.offroad_source.record_drive', side_effect=drive): + restart = daemon._run() + self.assertEqual(params.get(KEY), b'declared-existing-saved-tune') + self.assertIn(('cancelled', True), events) + self.assertIn('child-reaped', events) + self.assertEqual(sum(isinstance(e, tuple) and e[0] == 'closed' for e in events), 3) + self.assertEqual({s: signal.getsignal(s) for s in prior_signals}, prior_signals) + return restart, events + + def test_ignition_cancels_reaps_and_requests_a_clean_driving_image(self): + restart, events = self.exercise_transition(starts_parked=True) + self.assertTrue(restart) + self.assertNotIn('driving-source', events, 'The analysis image must never enter driving collection') + + def test_driving_to_parked_starts_a_new_worker_and_restores_history(self): + restart, events = self.exercise_transition(starts_parked=False) + self.assertTrue(restart) + self.assertLess(events.index('driving-source'), events.index('parked-worker')) + self.assertEqual(events.count('history-restored'), 1) + + def test_term_int_and_hup_cancel_without_reexec_or_losing_saved_tunes(self): + for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + with self.subTest(signal=sig): + restart, _ = self.exercise_transition(starts_parked=True, interrupted=sig) + self.assertFalse(restart) + + def test_shutdown_during_cleanup_cancels_an_already_requested_restart(self): + restart, events = self.exercise_transition(starts_parked=True, cancel_on_cleanup=True) + self.assertFalse(restart) + self.assertIn('child-reaped', events) + + def test_reexec_uses_the_existing_manager_launcher(self): + with patch.object(sys, 'argv', ['-c', daemon._CLEAN_IMAGE]), \ + patch.object(daemon, '_run', return_value=True), patch.object(daemon.os, 'execv') as execute: + daemon.main() + executable, argv = execute.call_args.args + self.assertEqual(executable, sys.executable) + self.assertEqual(argv[:2], [sys.executable, '-c']) + self.assertEqual(argv[-1], daemon._CLEAN_IMAGE) + self.assertIn("launcher('openpilot.starpilot.flm.offroad_daemon', 'steerlearnerd')", argv[2]) + with patch.object(sys, 'argv', ['-c', daemon._CLEAN_IMAGE]), \ + patch.object(daemon, '_run', return_value=None), patch.object(daemon.os, 'execv') as execute: + daemon.main() + execute.assert_not_called() + + def test_cold_manager_fork_is_replaced_before_loading_either_mode(self): + with patch.object(sys, 'argv', ['manager.py']), patch.object(daemon, '_run') as run, patch.object(daemon.os, 'execv') as execute: + daemon.main() + run.assert_not_called() + self.assertEqual(execute.call_count, 1) + self.assertEqual(execute.call_args.args[1][-1], daemon._CLEAN_IMAGE) + + def test_exec_failure_does_not_fall_back_to_collecting_in_the_parked_image(self): + with patch.object(sys, 'argv', ['-c', daemon._CLEAN_IMAGE]), patch.object(daemon, '_run', return_value=True) as run, \ + patch.object(daemon.os, 'execv', side_effect=OSError('declared exec failure')): + with self.assertRaises(OSError): + daemon.main() + run.assert_called_once() + + @unittest.skipUnless(sys.platform == 'linux', 'Actual manager/process/IPC lifecycle') + def test_manager_tracks_the_same_pid_and_can_stop_the_exec_replaced_child(self): + from openpilot.system.manager.process import PythonProcess + + with tempfile.TemporaryDirectory() as root, tempfile.TemporaryDirectory(prefix='msgq_flm-manager-', dir='/dev/shm') as ipc: + prefix = Path(ipc).name.removeprefix('msgq_') + report = Path('/dev/shm') / ('starpilot-flm-training-' + prefix + '.json') + with patch.dict(os.environ, {'OPENPILOT_PREFIX': prefix, 'PARAMS_ROOT': root}): + params = Params(root) + params.put_bool('IsOffroad', False, block=True) + params.put(KEY, b'declared-preserved-manager-store') + process = PythonProcess('steerlearnerd', 'openpilot.starpilot.flm.offroad_daemon', lambda *args: True, restart_on_exit=True) + process.start() + child = process.proc + self.assertIsNotNone(child) + assert child is not None + pid = child.pid + try: + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + self.assertTrue(child.is_alive(), 'Manager lost its child during exec') + try: + state = json.loads(report.read_text()) + except (OSError, ValueError): + state = {} + if state.get('current', {}).get('reason') == 'recording_for_offroad_analysis': + break + time.sleep(.02) + else: + self.fail('Manager-launched driving image did not become ready') + self.assertTrue(process.recover()) + self.assertIs(process.proc, child) + self.assertEqual(process.proc.pid, pid) + self.assertIsNone(child.exitcode) + self.assertEqual(params.get(KEY), b'declared-preserved-manager-store') + finally: + process.stop(sig=signal.SIGTERM) + report.unlink(missing_ok=True) + self.assertEqual(child.exitcode, 0) + self.assertIsNone(process.proc) + + @unittest.skipUnless(sys.platform == 'linux', 'Real Linux exec/RSS/IPC lifecycle') + def test_actual_exec_releases_a_declared_parked_heap_and_preserves_pid_and_store(self): + # A deliberate heap demonstrates allocator/data release, independently of + # any claim about an EV6's actual analysis size or driving CPU workload. + with tempfile.TemporaryDirectory() as root, tempfile.TemporaryDirectory(prefix='msgq_flm-exec-', dir='/dev/shm') as ipc: + prefix = Path(ipc).name.removeprefix('msgq_') + with patch.dict(os.environ, {'OPENPILOT_PREFIX': prefix}): + params = Params(root) + params.put_bool('IsOffroad', True, block=True) + params.put(KEY, b'declared-retained-store') + report = Path('/dev/shm') / ('starpilot-flm-training-' + prefix + '.json') + environment = dict(os.environ, PARAMS_ROOT=root, OPENPILOT_PREFIX=prefix) + code = ''' +import json,sys +from types import SimpleNamespace +from unittest.mock import Mock, patch +from openpilot.common.params import Params +from openpilot.starpilot.flm import offroad_daemon as daemon +params=Params() +sys.argv.append(daemon._CLEAN_IMAGE) # The declared heap belongs to an already-clean parked image. +class Worker: + def __init__(self,*args,**kwargs): + self.cache=object(); self.heap=bytearray(160*1024*1024) + def run_once(self): + rss=int(next(s for s in open('/proc/self/status') if s.startswith('VmRSS:')).split()[1]) + print(json.dumps({'before_kib':rss}),flush=True) + params.put_bool('IsOffroad',False,block=True) + return {'status':'collecting','reason':'declared-transition'} +sm=SimpleNamespace(sock={}) +with patch.object(daemon.messaging,'SubMaster',return_value=sm), patch.object(daemon,'wait_for_parked',return_value=True), \\ + patch.object(daemon.StatusReport,'restore',return_value=None), \\ + patch.dict(sys.modules,{'openpilot.starpilot.flm.offroad_worker':SimpleNamespace(OffroadWorker=Worker)}): + daemon.main() +''' + child = subprocess.Popen([sys.executable, '-B', '-c', code], env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + if child.poll() is not None: + self.fail('Lifecycle child exited early: ' + child.stderr.read()[-2000:]) + try: + state = json.loads(report.read_text()) + except (OSError, ValueError): + state = {} + if state.get('current', {}).get('reason') == 'recording_for_offroad_analysis': + break + time.sleep(.02) + else: + self.fail('Fresh driving image did not publish its status') + after = int(next(s for s in Path(f'/proc/{child.pid}/status').read_text().splitlines() if s.startswith('VmRSS:')).split()[1]) + self.assertEqual(params.get(KEY), b'declared-retained-store') + finally: + child.terminate() + try: + output, error = child.communicate(timeout=5) + except subprocess.TimeoutExpired: + child.kill() + output, error = child.communicate(timeout=3) + report.unlink(missing_ok=True) + self.assertEqual(child.returncode, 0, error[-2000:]) + before = next(json.loads(line)['before_kib'] for line in output.splitlines() if line.startswith('{"before_kib"')) + self.assertGreater(before - after, 96 * 1024, f'Parked heap retained: before={before}KiB after={after}KiB') diff --git a/openpilot/starpilot/flm/tests/test_offroad_retained_trials.py b/openpilot/starpilot/flm/tests/test_offroad_retained_trials.py index d5a1159a12..17d918fc10 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_retained_trials.py +++ b/openpilot/starpilot/flm/tests/test_offroad_retained_trials.py @@ -230,7 +230,7 @@ class TestRetainedTrialSources(unittest.TestCase): owner, _ = configure(None, None, SimpleNamespace(), params, manual_status='not_configured') self.assertIsNotNone(owner) self.assertFalse(owner.frame_allowed, 'A retained store still cannot supply actual frame permission') - with patch.object(worker, '_current_scope', return_value=scope()): + with patch('openpilot.starpilot.flm.offroad_runtime.current_scope', return_value=scope()): guard = from_configuration(None, params, cache.directory, vehicle_session='f' * 32) self.assertIsNone(guard.stopped) self.assertEqual(guard.baseline, tuple(original['gross_baseline']), 'The original gross-regression guard remains') diff --git a/prebuilt.json b/prebuilt.json index 361e82c4f8..d29d3d4f82 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "cc38a87c963b357f568aa5fa1d7a78030963a20b09f38786b68ef242d69e9d8a", "schema_version": 1} +{"protected_inventory_sha256": "81c6d968514769a6cb46b5e356e14f554679a279525c7dd7e287f53c63fe2c67", "schema_version": 1}