diff --git a/openpilot/selfdrive/controls/controlsd.py b/openpilot/selfdrive/controls/controlsd.py index bd81d689d9..2f88f3af04 100644 --- a/openpilot/selfdrive/controls/controlsd.py +++ b/openpilot/selfdrive/controls/controlsd.py @@ -224,7 +224,7 @@ class Controls: manual_effects, manual_status = load_manual_coordinates(self.CP, self.lateral_controller_selection.mode, self.params) self.torque_learning_allowed = bool( - manual_status == 'not_configured' and learning_allowed(self.params, self.CP, selection=self.lateral_controller_selection) + manual_status in ('not_configured', 'configured') and learning_allowed(self.params, self.CP, selection=self.lateral_controller_selection) ) return manual_effects, manual_status diff --git a/openpilot/starpilot/flm/controller_replay.py b/openpilot/starpilot/flm/controller_replay.py index 22d3af1a5e..8679617445 100644 --- a/openpilot/starpilot/flm/controller_replay.py +++ b/openpilot/starpilot/flm/controller_replay.py @@ -755,14 +755,14 @@ class ControllerReplay: trace = None _verify_only = True if frame.route_effect_revision: - from openpilot.starpilot.flm.offroad_surface import REVISION as ROUTE_REVISION, replay_source + from openpilot.starpilot.flm.offroad_surface import current_revision, replay_source from openpilot.starpilot.flm.route_recording import _valid - if frame.route_effect_revision != ROUTE_REVISION or recorded_effect is not None or frame.live_applied_coordinates: + if not current_revision(frame.route_effect_revision) or recorded_effect is not None or frame.live_applied_coordinates: raise ValueError('Distinct explicit route replay policy required') - _valid(frame.route_applied_coordinates, frame.route_configuration_scope) + _valid(frame.route_applied_coordinates, frame.route_configuration_scope, frame.route_effect_revision) if any(value for _, value in frame.route_applied_coordinates): - recorded_effect = replay_source(dict(frame.route_applied_coordinates), self.baseline_revision) + recorded_effect = replay_source(dict(frame.route_applied_coordinates), self.baseline_revision, revision=frame.route_effect_revision) _verify_only = True actual, _ = _run( self.actual, diff --git a/openpilot/starpilot/flm/global_runtime.py b/openpilot/starpilot/flm/global_runtime.py index fc3111d8e7..7a819d5fd8 100644 --- a/openpilot/starpilot/flm/global_runtime.py +++ b/openpilot/starpilot/flm/global_runtime.py @@ -255,7 +255,7 @@ class GlobalRuntime: policy = getattr(getattr(self.controller, 'starpilot_extension', None), 'policy', None) self.live_manual = bool( manual_current - or getattr(self.controller, 'manual_flm_effects', None) is not None + or (getattr(self.controller, 'manual_flm_effects', None) is not None and getattr(self.controller, 'route_flm_effects', None) is None) or getattr(self.controller, 'manual_flm_status', 'not_configured') not in ('configured', 'not_configured') or getattr(self.controller, 'flm_surface', None) is not None or getattr(policy, 'surface', None) is not None diff --git a/openpilot/starpilot/flm/learner_factory.py b/openpilot/starpilot/flm/learner_factory.py index 3fbddf8de6..e906ad7123 100644 --- a/openpilot/starpilot/flm/learner_factory.py +++ b/openpilot/starpilot/flm/learner_factory.py @@ -74,15 +74,16 @@ def collection_keys(evidence): def _frame(evidence): if getattr(evidence, 'route_effect_revision', ''): from dataclasses import replace - from openpilot.starpilot.flm.route_recording import SCHEMAS, _valid - from openpilot.starpilot.flm.offroad_surface import REVISION as ROUTE_REVISION + from openpilot.starpilot.flm.route_recording import schema_base, _valid + from openpilot.starpilot.flm.offroad_surface import current_revision - if evidence.stage_schema_revision not in SCHEMAS or evidence.route_effect_revision != ROUTE_REVISION: + base = schema_base(evidence.stage_schema_revision) + if base is None or not current_revision(evidence.route_effect_revision): raise ValueError('Explicit route recording schema required') - _valid(evidence.route_applied_coordinates, evidence.route_configuration_scope) + _valid(evidence.route_applied_coordinates, evidence.route_configuration_scope, evidence.route_effect_revision) original = replace( evidence, - stage_schema_revision=SCHEMAS[evidence.stage_schema_revision], + stage_schema_revision=base, route_applied_coordinates=(), route_effect_revision='', route_configuration_scope='', diff --git a/openpilot/starpilot/flm/learning_wire.py b/openpilot/starpilot/flm/learning_wire.py index 272c089c88..b4bd88d68e 100644 --- a/openpilot/starpilot/flm/learning_wire.py +++ b/openpilot/starpilot/flm/learning_wire.py @@ -278,7 +278,7 @@ def _read_fields(row, schema): def read_control(event): - from openpilot.starpilot.flm.route_recording import decode_configuration, configuration_values, SCHEMAS, MAX_ROUTE_STAGE_VALUES + from openpilot.starpilot.flm.route_recording import decode_configuration, configuration_values, schema_base, MAX_ROUTE_STAGE_VALUES if not event.valid: raise ValueError('invalid envelope') @@ -287,7 +287,7 @@ def read_control(event): row.version != VERSION or len(row.features) > MAX_FIELDS or len(row.appliedCoordinates) > MAX_FIELDS - or len(row.stageValues) > (MAX_ROUTE_STAGE_VALUES if str(row.stageSchemaRevision) in SCHEMAS else 40) + or len(row.stageValues) > (MAX_ROUTE_STAGE_VALUES if schema_base(str(row.stageSchemaRevision)) is not None else 40) or len(row.baselineValues) > 32 or len(row.appliedParameterNames) > 8 or len(row.liveAppliedCoordinates) not in (0, 30) diff --git a/openpilot/starpilot/flm/manual_coordinates.py b/openpilot/starpilot/flm/manual_coordinates.py index 6dd2ffde7a..3e015c3860 100644 --- a/openpilot/starpilot/flm/manual_coordinates.py +++ b/openpilot/starpilot/flm/manual_coordinates.py @@ -40,13 +40,30 @@ class ManualCoordinates: context: tuple[str, str, str] values: tuple[tuple[str, float], ...] compatibility: str = '' + automatic: tuple[str, ...] | None = None + + @property + def route_format(self): + return bool(self.compatibility) or self.automatic is not None + + @property + def locked(self): + # Zero has always meant Default in the editor, including older documents. + return tuple(name for name, value in self.values if value != 0 and name not in (self.automatic or ())) + + @property + def starting_values(self): + return {name: value for name, value in self.values if value != 0} def validate(self): from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES, route_bounds, RouteSurfaceEffects - recovered = bool(self.compatibility) + recovered = self.route_format 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')): + if type(self.compatibility) is not str or self.compatibility and (len(self.compatibility) != 64 or self.compatibility.strip('0123456789abcdef')): raise ValueError('Recovered manual tune needs its selected steering identity') + if self.automatic is not None and (type(self.automatic) is not tuple or + self.automatic != tuple(name for name in ROUTE_NAMES if name in self.automatic)): + raise ValueError('Accepted findings need unique ordered route coordinates') 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)) @@ -64,27 +81,38 @@ class ManualCoordinates: # Validate the complete composed surface as well as each individual value. from openpilot.starpilot.flm.canonical_surface_adapter import CanonicalSurfaceEffects effects = RouteSurfaceEffects if recovered else CanonicalSurfaceEffects - effects(dict(self.values[:1]), self.digest(), accumulated=dict(self.values)) + kwargs = {} + if self.automatic is not None: + from openpilot.starpilot.flm.offroad_surface import revision_for_manual + kwargs['revision'] = revision_for_manual(self) + effects(dict(self.values[:1]), self.digest(), accumulated=dict(self.values), **kwargs) return self def digest(self): payload = (self.context, self.values, self.compatibility) if self.compatibility else (self.context, self.values) + if self.automatic is not None: + payload = (payload, self.automatic) return hashlib.sha256(json.dumps(payload, separators=(',', ':'), allow_nan=False).encode()).hexdigest() def document(self): self.validate() - return dict(context=list(self.context), values=dict(self.values), **({'compatibility': self.compatibility} if self.compatibility else {})) + return dict(context=list(self.context), values=dict(self.values), **({'compatibility': self.compatibility} if self.compatibility else {}), + **({'automatic': list(self.automatic)} if self.automatic is not None else {})) @classmethod def from_document(cls, value): - if (type(value) is not dict or set(value) not in ({'context', 'values'}, {'context', 'values', 'compatibility'}) or type(value['context']) is not list + if (type(value) is not dict or not {'context', 'values'} <= set(value) <= {'context', 'values', 'compatibility', 'automatic'} + or type(value['context']) is not list or type(value['values']) is not dict): raise ValueError('Invalid manual coordinate document') from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES - names = ROUTE_NAMES if value.get('compatibility') else NAMES + if 'automatic' in value and type(value['automatic']) is not list: + raise ValueError('Accepted finding coordinates must be a list') + names = ROUTE_NAMES if value.get('compatibility') or 'automatic' in value 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() + automatic = tuple(value['automatic']) if 'automatic' in value else None + return cls(tuple(value['context']), tuple((n, value['values'][n]) for n in names), value.get('compatibility', ''), automatic).validate() class ManualEffects: @@ -97,8 +125,12 @@ class ManualEffects: profile.validate() self.profile = profile 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)) + effects = RouteSurfaceEffects if profile.route_format else CanonicalSurfaceEffects + kwargs = {} + if profile.automatic is not None: + from openpilot.starpilot.flm.offroad_surface import revision_for_manual + kwargs['revision'] = revision_for_manual(profile) + self.source = effects(dict(profile.values[:1]), profile.digest(), accumulated=dict(profile.values), **kwargs) self.original_effect_anchor = self.source.original_effect_anchor def compatible(self, cp, ci, controller, params=None): @@ -147,8 +179,27 @@ 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, recovered=bool(manual.compatibility))): + or profile.flm is not None or manual.context != context(cp, controller, recovered=manual.route_format)): return None, 'context_changed' return ManualEffects(manual), 'configured' except (AttributeError, KeyError, TypeError, ValueError, OverflowError, UnicodeError): return None, 'invalid' + + +def selected_manual(cp, params): + from openpilot.starpilot.lateral.controller_selection import read_selection + from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, MAX_DOCUMENT_BYTES, parse_document + from openpilot.starpilot.saved_source import read_saved + + raw, readable = read_saved(params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) + if not readable: + raise ValueError('Unreadable manual coordinate settings') + if raw is None: + return None + profile = parse_document(raw).get(str(cp.carFingerprint)) + if profile is None or profile.manual_coordinates is None: + return None + owner, status = load(cp, read_selection(params, cp).mode, params) + if status not in ('configured', 'not_configured'): + raise ValueError('Manual coordinate settings require review: ' + status) + return None if owner is None else owner.profile diff --git a/openpilot/starpilot/flm/offroad_control_metadata.py b/openpilot/starpilot/flm/offroad_control_metadata.py index 06c93fdb8f..3ffa52d419 100644 --- a/openpilot/starpilot/flm/offroad_control_metadata.py +++ b/openpilot/starpilot/flm/offroad_control_metadata.py @@ -7,7 +7,7 @@ replay vectors or assert that they are valid. from dataclasses import dataclass import math -from openpilot.starpilot.flm.route_recording import SCHEMAS, CONFIGURED_SCHEMAS, decode_configuration, configuration_values +from openpilot.starpilot.flm.route_recording import schema_base, configured_schema, decode_configuration, configuration_values @dataclass(frozen=True) @@ -43,7 +43,7 @@ class RecordedControlMetadata: def _inhibited_inputs(row, schema): # Only two original flags are needed here; full replay stays a separate check. - configured = schema in CONFIGURED_SCHEMAS + configured = configured_schema(schema) if not configured and (not row.limited or schema.split('@', 1)[0] != 'torque-selected-stage-snapshot-v1'): return () from openpilot.starpilot.flm.native_refinement_wire import EXTENDED_INPUTS @@ -85,7 +85,7 @@ def read_control_metadata(event): ): raise ValueError('Finite original controller context required') schema = str(row.stageSchemaRevision) - if schema in SCHEMAS: + if schema_base(schema) is not None: _, coordinates, route_revision, scope, configured = decode_configuration(schema, tuple((str(v.name), float(v.value)) for v in row.stageValues)) else: if '@route-' in schema or len(row.stageValues) > 40 or any(str(v.name).startswith('route.') for v in row.stageValues): diff --git a/openpilot/starpilot/flm/offroad_controller_checks.py b/openpilot/starpilot/flm/offroad_controller_checks.py index 733041c363..d19865eded 100644 --- a/openpilot/starpilot/flm/offroad_controller_checks.py +++ b/openpilot/starpilot/flm/offroad_controller_checks.py @@ -7,10 +7,10 @@ from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES as NAMES, RouteS def original_delivery_context(control, outputs): from dataclasses import replace from opendbc.car.steering_projection import TorqueProjection - from openpilot.starpilot.flm.route_recording import SCHEMAS + from openpilot.starpilot.flm.route_recording import schema_base from openpilot.starpilot.flm.torque_eligibility import exact_unclipped_pair, bounded_context_output, consumed_sources_current - schema = SCHEMAS.get(control.stage_schema_revision, control.stage_schema_revision) + schema = schema_base(control.stage_schema_revision) or control.stage_schema_revision if schema != 'torque-selected-stage-snapshot-v1' or not outputs: return None original = replace(control, stage_schema_revision=schema) @@ -214,7 +214,14 @@ def check_candidate(cp, controls, values, *, score_start_ns=0, score_end_ns=2**6 'failed_original_ns': frame.control_ns, } restore_snapshot(probe, probe_vm, before) - trial = replay_source(values, baseline) + from openpilot.starpilot.flm.offroad_surface import REVISION, revision_locks + revision = evidence.route_effect_revision or REVISION + locks, _ = revision_locks(revision) + from openpilot.starpilot.flm.route_recording import configuration_values + configured = dict(configuration_values(evidence.route_applied_coordinates, evidence.route_configured_coordinates, evidence.replay_inputs)) + if any(values[name] != configured.get(name) for name in locks): + return {'qualified': False, 'reason': 'candidate_changes_manually_locked_coordinate', 'verified_frames': verified} + trial = replay_source(values, baseline, revision=revision) candidate, _ = _run(probe, probe_vm, frame.inputs, actual.objective, (0.0,) * len(frame.applied_coordinates), frame.torque_values, effect_trial=trial) # Existing selected source checks retain per-stage sign/envelopes and limits. if not math.isfinite(candidate) or abs(candidate) > probe.steer_max + 1e-12: diff --git a/openpilot/starpilot/flm/offroad_daemon.py b/openpilot/starpilot/flm/offroad_daemon.py index 4f2364c6fa..052416fc20 100644 --- a/openpilot/starpilot/flm/offroad_daemon.py +++ b/openpilot/starpilot/flm/offroad_daemon.py @@ -202,7 +202,7 @@ class StatusReport: details['Actual route control timestamp'] = value['actual_control_ns'] details['Native delivery is not asserted by this status'] = True from openpilot.starpilot.flm.fullrate_collector import ControlEvidence - from openpilot.starpilot.flm.offroad_surface import REVISION + from openpilot.starpilot.flm.offroad_surface import current_revision control = value.get('actual_control') applied = False @@ -214,7 +214,7 @@ class StatusReport: and control.active and not (control.manual or control.override or control.fault or control.limited or control.saturated) and 0 < control.control_ns <= now <= control.control_ns + 100_000_000 - and control.route_effect_revision == REVISION + and current_revision(control.route_effect_revision) and len(control.route_configuration_scope) == 64 and not control.route_configuration_scope.strip('0123456789abcdef') ): diff --git a/openpilot/starpilot/flm/offroad_observed.py b/openpilot/starpilot/flm/offroad_observed.py index e527b77edb..902c9273f6 100644 --- a/openpilot/starpilot/flm/offroad_observed.py +++ b/openpilot/starpilot/flm/offroad_observed.py @@ -3,7 +3,7 @@ from bisect import bisect_left, bisect_right import hashlib from statistics import median -from openpilot.starpilot.flm.offroad_surface import REVISION, ROUTE_NAMES +from openpilot.starpilot.flm.offroad_surface import current_revision, ROUTE_NAMES def observed_sources(windows, timeline, metadata_for): @@ -26,7 +26,7 @@ def observed_sources(windows, timeline, metadata_for): metadata = metadata_for(control, window.domain) values = metadata.pop('route_values') revision = metadata.pop('route_revision') - if revision != REVISION or tuple(name for name, _ in values) != ROUTE_NAMES or context is not None and context != metadata: + if not current_revision(revision) or tuple(name for name, _ in values) != ROUTE_NAMES or context is not None and context != metadata: break context = metadata for name, value in values: diff --git a/openpilot/starpilot/flm/offroad_processor.py b/openpilot/starpilot/flm/offroad_processor.py index ffca3b59bc..5aa76b98c0 100644 --- a/openpilot/starpilot/flm/offroad_processor.py +++ b/openpilot/starpilot/flm/offroad_processor.py @@ -172,10 +172,11 @@ def _control_reconstructible(control, stamp): if not control.limited: return True inputs = dict(getattr(control, 'replay_inputs', ())) - from openpilot.starpilot.flm.route_recording import SCHEMAS + from openpilot.starpilot.flm.route_recording import schema_base schema = getattr(control, 'stage_schema_revision', '') - return bool(SCHEMAS.get(schema, schema) == 'torque-selected-stage-snapshot-v1' and inputs.get('active') == 1.0 and inputs.get('safety_limited') in (0.0, 1.0)) + return bool((schema_base(schema) or schema) == 'torque-selected-stage-snapshot-v1' + and inputs.get('active') == 1.0 and inputs.get('safety_limited') in (0.0, 1.0)) def continuous_control_window(window, timeline, metadata_for, expected): diff --git a/openpilot/starpilot/flm/offroad_quality.py b/openpilot/starpilot/flm/offroad_quality.py index 3a53eef9ee..bd641b5f0b 100644 --- a/openpilot/starpilot/flm/offroad_quality.py +++ b/openpilot/starpilot/flm/offroad_quality.py @@ -12,7 +12,7 @@ import os from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES as NAMES 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 current_revision from openpilot.starpilot.flm.offroad_surface import stop_marker @@ -101,7 +101,7 @@ class TrialGuard: or control.limited or control.saturated or abs(control.control_ns - stamp) > 30_000_000 - or control.route_effect_revision != REVISION + or not current_revision(control.route_effect_revision) or control.route_configuration_scope != self.scope_key or dict(control.route_applied_coordinates) != self.values ): diff --git a/openpilot/starpilot/flm/offroad_runtime.py b/openpilot/starpilot/flm/offroad_runtime.py index 646afc81ae..e4f4a39821 100644 --- a/openpilot/starpilot/flm/offroad_runtime.py +++ b/openpilot/starpilot/flm/offroad_runtime.py @@ -24,8 +24,8 @@ def configuration_data(cp, ci, controller, params, *, manual_status): 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 - if manual_status != 'not_configured' or not is_valid_vin(str(cp.carVin)) or str(cp.carVin) == VIN_UNKNOWN: - raise ValueError('Known vehicle and no manual coordinates required') + if manual_status not in ('not_configured', 'configured') or not is_valid_vin(str(cp.carVin)) or str(cp.carVin) == VIN_UNKNOWN: + raise ValueError('Known vehicle and valid manual coordinate settings required') descriptor = selected_descriptor(cp, ci, controller) if descriptor is None or descriptor.domain not in ('torque', 'torque_pid'): raise ValueError('Actual registered torque controller required') @@ -64,8 +64,11 @@ def configuration_data(cp, ci, controller, params, *, manual_status): if document is not None: profile = parse_document(document).get(str(cp.carFingerprint)) if profile is not None: - if profile.flm is not None or profile.manual_coordinates is not None or profile.geometry is not None and profile.geometry.learning == 'force_off': + if profile.flm is not None or profile.geometry is not None and profile.geometry.learning == 'force_off': raise ValueError('Manual or explicitly disabled tuning selected') + if profile.manual_coordinates is not None: + from openpilot.starpilot.flm.manual_coordinates import selected_manual + selected_manual(cp, params) if cp.lateralTuning.which() == 'torque': tune = cp.lateralTuning.torque if profile.basis != (float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction)): @@ -147,7 +150,7 @@ def fixed_manual_numeric(controller, values): class RouteEffects: """Exact cold-start configuration, guarded by existing per-frame stages.""" - def __init__(self, scope, values, numeric, *, previous=None, fixed_numeric=None): + def __init__(self, scope, values, numeric, *, previous=None, fixed_numeric=None, revision=None): scope.validate() if type(values) is not tuple or tuple(name for name, _ in values) != tuple(NAMES): raise ValueError('Ordered full route map required') @@ -158,7 +161,9 @@ class RouteEffects: raise ValueError('Full previous route map required') self.quality_stopped = False self.quality_markers = frozenset(stop_marker(scope.key(), dict(values), r) for r in STOP_REASONS) - self.source = RouteSurfaceEffects(dict(values[:1]), scope.baseline_revision, accumulated=dict(values)) + from openpilot.starpilot.flm.offroad_surface import REVISION + self.revision = REVISION if revision is None else revision + self.source = RouteSurfaceEffects(dict(values[:1]), scope.baseline_revision, accumulated=dict(values), revision=self.revision) self.original_effect_anchor = self.source.original_effect_anchor self.enabled = True self.frame_allowed = False @@ -176,7 +181,7 @@ class RouteEffects: self.frame_allowed = False self.quality_stopped = True self.values = self.previous - self.source = RouteSurfaceEffects(dict(self.values[:1]), self.scope.baseline_revision, accumulated=dict(self.values)) + self.source = RouteSurfaceEffects(dict(self.values[:1]), self.scope.baseline_revision, accumulated=dict(self.values), revision=self.revision) self.original_effect_anchor = self.source.original_effect_anchor self.status = 'quality_guard_returned_to_prior_accepted_map' @@ -277,18 +282,29 @@ def configure(cp, ci, controller, params, *, manual_status): controller.route_flm_scope = scope controller.route_flm_scope_key = scope.key() row, status = startup_row(params, scope) - if row is None: + from openpilot.starpilot.flm.manual_coordinates import selected_manual + from openpilot.starpilot.flm.offroad_surface import revision_for_manual + manual = selected_manual(cp, params) + locked = {} if manual is None else {name: value for name, value in manual.values if name in manual.locked} + starting = {} if manual is None else manual.starting_values + if row is None and not starting: return None, status - if row['state'] == 'ready_for_next_drive': + if row is not None and row['state'] == 'ready_for_next_drive': from openpilot.starpilot.flm.offroad_cache import directory_for_params if os.path.lexists(directory_for_params(params) / ('trial-' + row['analysis_sha256'] + '.json')): return None, 'provisional_trial_already_started' - values = tuple((n, float(row['values'][n])) for n in NAMES) - previous = tuple((n, float(row['previous'][n])) for n in NAMES) + current = dict.fromkeys(NAMES, 0.0) | starting if row is None else dict(row['values']) + prior = current if row is None else dict(row['previous']) + if any(current[name] != value or prior[name] != value for name, value in locked.items()): + raise ValueError('Automatic configuration conflicts with a manually locked coordinate') + values = tuple((n, float(current[n])) for n in NAMES) + previous = tuple((n, float(prior[n])) for n in NAMES) fixed = None if not fixed_manual else fixed_manual_numeric(controller, fixed_manual) - return RouteEffects(scope, values, numeric, previous=previous, fixed_numeric=fixed), 'configured_pending_actual_stage' + return RouteEffects(scope, values, numeric, previous=previous, fixed_numeric=fixed, revision=revision_for_manual(manual)), 'configured_pending_actual_stage' except (AttributeError, KeyError, TypeError, ValueError, UnicodeError, OSError, OverflowError): + controller.route_flm_scope = None + controller.route_flm_scope_key = '' return None, 'configuration_unavailable' diff --git a/openpilot/starpilot/flm/offroad_surface.py b/openpilot/starpilot/flm/offroad_surface.py index 7175c0a394..bfb11537aa 100644 --- a/openpilot/starpilot/flm/offroad_surface.py +++ b/openpilot/starpilot/flm/offroad_surface.py @@ -7,6 +7,7 @@ per-coordinate bounds, sign and 25% stage envelopes remain authoritative. import hashlib import math +import re from openpilot.starpilot.flm.canonical_surface_adapter import CanonicalSurfaceEffects, MANIFEST_SHA256, NAMES LEGACY_REVISION = 'route-reference-relative-v2' @@ -20,6 +21,33 @@ ROUTE_MANIFEST_SHA256 = hashlib.sha256( ).hexdigest() +def revision_for_manual(manual): + if manual is None or not manual.locked: + return REVISION + mask = sum(1 << ROUTE_NAMES.index(name) for name in manual.locked) + return f'route-coordinate-locks-v1-{"r" if manual.compatibility else "c"}-{mask:09x}' + + +def revision_locks(revision): + if revision == REVISION: + return (), False + matched = re.fullmatch(r'route-coordinate-locks-v1-([cr])-([0-9a-f]{9})', revision) if type(revision) is str else None + if matched is None or not 0 < int(matched[2], 16) < 1 << len(ROUTE_NAMES): + raise ValueError('Unknown route coordinate-lock revision') + names = tuple(name for i, name in enumerate(ROUTE_NAMES) if int(matched[2], 16) & (1 << i)) + if matched[1] == 'c' and any(name not in NAMES for name in names): + raise ValueError('Canonical manual settings have thirty coordinates') + return names, matched[1] == 'c' + + +def current_revision(revision): + try: + revision_locks(revision) + return True + except ValueError: + return False + + def route_bounds(name): if name in CURVE_NAMES: return -0.25, 0.25 @@ -42,7 +70,9 @@ def route_values(values, *, legacy_allowed=False): class RouteSurfaceEffects(CanonicalSurfaceEffects): - def __init__(self, coordinates, baseline_revision, *, accumulated): + def __init__(self, coordinates, baseline_revision, *, accumulated, revision=REVISION): + self.revision = revision + locks, canonical_manual = revision_locks(revision) values = route_values(accumulated, legacy_allowed=True) if type(coordinates) is not dict or any(name not in NAMES for name in coordinates): raise ValueError('Original canonical frame anchor required') @@ -50,6 +80,25 @@ class RouteSurfaceEffects(CanonicalSurfaceEffects): self.route_values = {name: self.values[name] if name in NAMES else values[name] for name in ROUTE_NAMES} self.curve_values = tuple(values[name] for name in CURVE_NAMES) self.full_profile_sha256 = hashlib.sha256(repr((ROUTE_MANIFEST_SHA256, self.full_profile_sha256, self.curve_values)).encode()).hexdigest() + self.manual_surface = None + self.automatic_surface = self.surface + self.relative_values = self.values + if locks: + if any(values[name] == 0 for name in locks): + raise ValueError('A locked coordinate must have an explicit nondefault value') + self.full_profile_sha256 = hashlib.sha256(repr((revision, self.full_profile_sha256)).encode()).hexdigest() + if canonical_manual: + from openpilot.starpilot.flm.canonical_surface_adapter import WINDOWS + raw = dict(self.math._GM_NEUTRAL) + for name in WINDOWS: + raw[name] *= 1 + self.values[name] + manual, automatic = dict(raw), dict(raw) + for name in NAMES: + if name not in WINDOWS: + (manual if name in locks else automatic)[name] = self.values[name] + self.manual_surface = self.math.GmSurface('torque_universal', manual) + self.automatic_surface = self.math.GmSurface('torque_universal', automatic) + self.relative_values = {name: 0.0 if name in locks else value for name, value in self.values.items()} # Original threshold phase weights are in [0,1], with an existing .82..1.18 # clamp. Refuse a profile whose curve could breach the composed 25% bound # at ANY phase, before admitting it to a real controller. @@ -77,16 +126,23 @@ class RouteSurfaceEffects(CanonicalSurfaceEffects): def _scale(self, frame): if frame.setpoint == 0.0: - return 1.0 + if self.manual_surface is None: + return 1.0 + return self.math._gm_get_flm_full_surface_center_taper_scale(self.manual_surface, self.manual_surface.profile, 0.0, frame.speed, True) m = self.math phase = m._gm__flm_full_surface_transition_phase(self.surface, frame.setpoint, frame.jerk) side = 'left' if frame.setpoint >= 0 else 'right' # These are relative settings of the ACTUAL selected FF, not an added # legacy FF term gated by an unrelated amplitude's onset/cutoff. relative = ( - 1.0 + self.values['ff_gain_' + side] + self.values['turn_in_boost_' + side] * max(phase, 0.0) - self.values['unwind_taper_' + side] * max(-phase, 0.0) + 1.0 + self.relative_values['ff_gain_' + side] + self.relative_values['turn_in_boost_' + side] * max(phase, 0.0) + - self.relative_values['unwind_taper_' + side] * max(-phase, 0.0) ) - remaining = m._gm_get_flm_full_surface_ff_scale(self.surface, self.surface.profile, frame.setpoint, frame.jerk, frame.speed, False) + automatic = self.automatic_surface + remaining = m._gm_get_flm_full_surface_ff_scale(automatic, automatic.profile, frame.setpoint, frame.jerk, frame.speed, False) + if self.manual_surface is not None: + manual = self.manual_surface + remaining *= m._gm_get_flm_full_surface_ff_scale(manual, manual.profile, frame.setpoint, frame.jerk, frame.speed, True) center = m._gm_get_flm_full_surface_center_taper_scale(self.surface, self.surface.profile, frame.setpoint, frame.speed, True) return relative * remaining * center @@ -132,13 +188,13 @@ class RouteSurfaceEffects(CanonicalSurfaceEffects): return self._ff(frame) -def replay_source(values, baseline_revision): +def replay_source(values, baseline_revision, *, revision=REVISION): """Child-only numeric probe; never builds a live envelope or authority.""" from openpilot.starpilot.flm.selected_effects import EffectReplaySource complete = route_values(values, legacy_allowed=True) obj = EffectReplaySource.from_coordinates({NAMES[0]: complete[NAMES[0]]}, baseline_revision, accumulated={name: complete[name] for name in NAMES}) - obj.source = RouteSurfaceEffects({NAMES[0]: complete[NAMES[0]]}, baseline_revision, accumulated=complete) + obj.source = RouteSurfaceEffects({NAMES[0]: complete[NAMES[0]]}, baseline_revision, accumulated=complete, revision=revision) obj.original_effect_anchor = obj.source.original_effect_anchor obj.applied_coordinates = obj.source.applied_coordinates return obj diff --git a/openpilot/starpilot/flm/offroad_worker.py b/openpilot/starpilot/flm/offroad_worker.py index 58652ad397..3c1764503a 100644 --- a/openpilot/starpilot/flm/offroad_worker.py +++ b/openpilot/starpilot/flm/offroad_worker.py @@ -20,7 +20,7 @@ from openpilot.starpilot.flm.offroad_processor import analyze_latest, CompletedA 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 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_surface import REVISION, current_revision, revision_for_manual from openpilot.starpilot.flm.offroad_tracking import TrackingEstimate, compare_observed from openpilot.starpilot.saved_source import read_saved from openpilot.starpilot.flm.log_decode import LogDecodeCancelled @@ -85,6 +85,11 @@ def _current_scope(cp, params): def recorded_source_contract(cp, metadata, scope, params): + from openpilot.starpilot.flm.manual_coordinates import selected_manual + expected_revision = revision_for_manual(selected_manual(cp, params)) + recorded_revision = metadata.get('route_revision', '') + if (recorded_revision and recorded_revision != expected_revision) or (not recorded_revision and expected_revision != REVISION): + return None if metadata['route_scope'] == scope.key(): return {'kind': 'same_recorded_scope', 'current_scope': scope.key()} if not metadata['route_scope']: @@ -122,7 +127,7 @@ def _recorded_values(metadata): pairs = metadata['route_values'] if not pairs: return dict(ZERO) if not metadata['route_revision'] else None - if metadata['route_revision'] != REVISION or tuple(n for n, _ in pairs) != tuple(NAMES): + if not current_revision(metadata['route_revision']) or tuple(n for n, _ in pairs) != tuple(NAMES): return None return dict(pairs) @@ -571,7 +576,8 @@ def recent_findings(cache, results, display): if type(row) is not dict: continue name = row.get('parameter') - if (name not in NAMES or type(row.get('baseline')) not in (int, float) or row['baseline'] != current[name] + if (name not in NAMES or name in latest.get('manual_locked_parameters', ()) + or type(row.get('baseline')) not in (int, float) or row['baseline'] != current[name] or type(row.get('reason')) is not str or len(row['reason']) > 240): continue target = row.get('target') @@ -806,7 +812,15 @@ class OffroadWorker: raise ValueError('Unreadable automatic tuning history') row = decode(raw).get(NAMESPACE, {}).get(scope.key()) state.update(scope=scope, raw=raw, row=row) - return dict(ZERO) if row is None else dict(row['values']) + from openpilot.starpilot.flm.manual_coordinates import selected_manual + manual = selected_manual(cp, self.params) + locked = {} if manual is None else {name: value for name, value in manual.values if name in manual.locked} + state['locked'] = locked + state['starting'] = {} if manual is None else manual.starting_values + current = dict(ZERO) | state['starting'] if row is None else dict(row['values']) + if any(current[name] != value for name, value in locked.items()): + raise ValueError('Saved automatic map conflicts with manually locked coordinates') + return current if self.on_analysis is not None: self.on_analysis() @@ -872,7 +886,8 @@ class OffroadWorker: omitted_segments=[list(row) for row in assessment.receipt.omitted_segments]) report = assessment.report() report.update(policy=POLICY, current_scope=scope.document(), road_improvement_confirmed=False) - current = dict(ZERO) if row is None else dict(row['values']) + locked = state.get('locked', {}) + current = dict(ZERO) | state.get('starting', {}) if row is None else dict(row['values']) recorded['recommendations'] = recorded_recommendations(assessment, current, report) choices = [] @@ -1006,7 +1021,8 @@ class OffroadWorker: def recommendations_ready(): - recorded['recommendations'] = recorded_recommendations(assessment, current, report) + recorded['recommendations'] = [r for r in recorded_recommendations(assessment, current, report) if r['parameter'] not in locked] + recorded['manual_locked_parameters'] = list(locked) if partial: for recommendation in recorded['recommendations']: if recommendation['target'] is not None: @@ -1015,6 +1031,8 @@ class OffroadWorker: self.on_recommendations(dict(recorded)) recommendations_ready() + choices = [(group, cohort, proposal) for group, cohort, proposal in choices + if all(proposal['values'][name] == value for name, value in locked.items())] if partial: recommendations = recorded['recommendations'] result = {**recorded, 'status': 'collecting', 'reason': 'partial_drive_provisional_only', @@ -1348,7 +1366,8 @@ class OffroadWorker: 'recorded_tracking': report.get('recorded_tracking'), 'skipped_routes': [*self.skipped_routes, *getattr(assessment, 'route_skips', ())][:16], 'suggestion_count': len(diagnostics) + len(profile_suggestions), - 'recommendations': recorded_recommendations(assessment, current, report), + 'recommendations': [r for r in recorded_recommendations(assessment, current, report) if r['parameter'] not in locked], + 'manual_locked_parameters': list(locked), 'suggestions': profile_suggestions + [ {'parameter': v['parameter'], 'delta': v['delta'], 'whole_windows': c['whole_windows'], 'qualification': 'controller_native_checks_not_passed'} diff --git a/openpilot/starpilot/flm/producer_clock_equivalence.py b/openpilot/starpilot/flm/producer_clock_equivalence.py index d0a3538a17..a9e87159db 100644 --- a/openpilot/starpilot/flm/producer_clock_equivalence.py +++ b/openpilot/starpilot/flm/producer_clock_equivalence.py @@ -18,8 +18,9 @@ PRODUCER_SOURCE_HASHES = ( ('openpilot', 'system/camerad/cameras/spectra.cc', '4fa26c17f0fb792a4ab6815657beccddee1d641faa2fd02e5aa7393f717a2f3a'), ('openpilot', 'system/camerad/cameras/camera_qcom2.cc', 'b34c24c9984a0ac086f7b961cb7ff09d0501231da50aaad0e676bb3dc3f2edd9'), ('openpilot', 'system/camerad/cameras/camera_common.cc', 'bd9a416a6ee21047b4deec6df04276d8717cd92fe14de43f3e9daff86b62bb8f'), - ('openpilot', 'selfdrive/modeld/modeld.py', '7a0eaf1f854c8f290f157d860691bb3e2c00c7421fbf9f1f8a092683757988ee'), + ('openpilot', 'selfdrive/modeld/modeld.py', '1b8d96ca9f7ac267d180732a6646b128bcbaec9ac79f80814030ec84197fd9d5'), ('openpilot', 'starpilot/car/volkswagen/model_smoothing.py', 'dd5d0ddaf77fe05960b673557b1b9f649d303ddfdad77a5185c7b3156fc6bbd2'), + ('openpilot', 'starpilot/car/hyundai/model_smoothing.py', '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243'), ('openpilot', 'selfdrive/modeld/fill_model_msg.py', 'b3916c34d1073d0c26a7a8adc51e7b148f63a1ac68b388226170fd0f8b8b56b4'), ('openpilot', 'system/sensord/sensord.py', '7c79ab07d775622a43001e5a9b9ccc9a7bafb065940185849b33eefc2fd26420'), ('openpilot', 'system/sensord/sensors/lsm6ds3_gyro.py', '3e561f3d8572e1477c9b4b810c7570837d51e81c5672fe21ec67a68cae00dd92'), diff --git a/openpilot/starpilot/flm/route_recording.py b/openpilot/starpilot/flm/route_recording.py index e9497cb9af..8a09a3ce50 100644 --- a/openpilot/starpilot/flm/route_recording.py +++ b/openpilot/starpilot/flm/route_recording.py @@ -13,6 +13,7 @@ from openpilot.starpilot.flm.offroad_surface import ( LEGACY_REVISION, ROUTE_NAMES, route_bounds, + current_revision, ) BASES = ('torque-selected-stage-snapshot-v1', 'pid-selected-stage-snapshot-v2') @@ -25,8 +26,30 @@ SCOPE_PREFIX = 'route.scope.' MAX_ROUTE_STAGE_VALUES = 40 + 2 * len(ROUTE_NAMES) + 8 +def schema_parts(schema): + if schema in SCHEMAS: + configured = schema in CONFIGURED_SCHEMAS + revision = REVISION if configured else schema.rsplit('@', 1)[1] + return SCHEMAS[schema], revision, configured + if type(schema) is str and schema.endswith('+configured-v1') and schema.count('@') == 1: + base, revision = schema.removesuffix('+configured-v1').split('@') + if base in BASES and current_revision(revision): + return base, revision, True + return None + + +def schema_base(schema): + parts = schema_parts(schema) + return None if parts is None else parts[0] + + +def configured_schema(schema): + parts = schema_parts(schema) + return parts is not None and parts[2] + + def _valid(values, scope, revision=REVISION): - if revision not in (REVISION, LEGACY_REVISION): + if revision != LEGACY_REVISION and not current_revision(revision): raise ValueError('Unknown route revision') names = NAMES if revision == LEGACY_REVISION else ROUTE_NAMES if type(values) is not tuple or tuple(n for n, _ in values) != tuple(names) or type(scope) is not str or len(scope) != 64 or scope.strip('0123456789abcdef'): @@ -41,9 +64,10 @@ def encode(evidence): if evidence.route_effect_revision: revision = evidence.route_effect_revision schema = evidence.stage_schema_revision - suffix = '+configured-v1' if schema in CONFIGURED_SCHEMAS else '' - if revision not in (REVISION, LEGACY_REVISION) or schema not in SCHEMAS or schema != SCHEMAS[schema] + '@' + revision + suffix: + parts = schema_parts(schema) + if parts is None or parts[1] != revision: raise ValueError('Explicit matching route revision required') + suffix = parts[2] if evidence.live_applied_coordinates or evidence.effect_trace is not None: raise ValueError('Route and live trial metadata remain distinct') _valid(evidence.route_applied_coordinates, evidence.route_configuration_scope, revision) @@ -60,7 +84,7 @@ def encode(evidence): return evidence.stage_values + tuple((PREFIX + n, v) for n, v in evidence.route_applied_coordinates) + settings + words if ( evidence.route_applied_coordinates or evidence.route_configuration_scope - or evidence.route_configured_coordinates or evidence.stage_schema_revision in SCHEMAS + or evidence.route_configured_coordinates or schema_base(evidence.stage_schema_revision) is not None ): raise ValueError('Route metadata cannot omit revision') return evidence.stage_values @@ -72,12 +96,12 @@ def decode(schema, pairs): def decode_configuration(schema, pairs): - if schema not in SCHEMAS: + parts = schema_parts(schema) + if parts is None: if any(n.startswith('route.') for n, _ in pairs): raise ValueError('Unknown route stage schema') return pairs, (), '', '', () - configured_version = schema in CONFIGURED_SCHEMAS - revision = REVISION if configured_version else schema.rsplit('@', 1)[1] + _, revision, configured_version = parts names = NAMES if revision == LEGACY_REVISION else ROUTE_NAMES tail = len(names) * (2 if configured_version else 1) + 8 if not tail <= len(pairs) <= 40 + tail: @@ -136,6 +160,8 @@ def with_actual_route(evidence, controller): and evidence.valid and not (evidence.manual or evidence.override or evidence.fault) ) + if not current and getattr(controller, 'manual_flm_effects', None) is not None: + raise ValueError('Manual locks require their actual current route-stage witness') if current: configured = owner.values source = owner.source @@ -158,12 +184,13 @@ def with_actual_route(evidence, controller): inhibited = inputs.get('active') == 1.0 and any(inputs.get(name) == 1.0 for name in ('safety_limited', 'curvature_limited')) if any(calls) or not inhibited: raise ValueError('Partial route execution cannot be recorded as applied') - _valid(values, getattr(controller, 'route_flm_scope_key', '')) + revision = REVISION if owner is None else owner.source.revision + _valid(values, getattr(controller, 'route_flm_scope_key', ''), revision) return replace( evidence, - stage_schema_revision=evidence.stage_schema_revision + '@' + REVISION + '+configured-v1', + stage_schema_revision=evidence.stage_schema_revision + '@' + revision + '+configured-v1', route_applied_coordinates=values, route_configured_coordinates=configured, - route_effect_revision=REVISION, + route_effect_revision=revision, route_configuration_scope=getattr(controller, 'route_flm_scope_key', ''), ) diff --git a/openpilot/starpilot/flm/selected_effects.py b/openpilot/starpilot/flm/selected_effects.py index c43da9cfb3..4c29fde74a 100644 --- a/openpilot/starpilot/flm/selected_effects.py +++ b/openpilot/starpilot/flm/selected_effects.py @@ -345,7 +345,10 @@ def _selected_source(parent): policy = getattr(getattr(parent, 'starpilot_extension', None), 'policy', None) if getattr(parent, 'flm_surface', None) is not None or getattr(policy, 'surface', None) is not None: return None - return source if type(source) is ManualEffects else None + if type(source) is not ManualEffects: + return None + from openpilot.starpilot.flm.offroad_runtime import selected_route + return selected_route(parent) or source if getattr(parent, 'route_flm_effects', None) is not None: from openpilot.starpilot.flm.offroad_runtime import selected_route @@ -354,9 +357,11 @@ def _selected_source(parent): def manual(parent): + from openpilot.starpilot.flm.manual_coordinates import ManualEffects policy = getattr(getattr(parent, 'starpilot_extension', None), 'policy', None) return ( - getattr(parent, 'manual_flm_effects', None) is not None or getattr(parent, 'flm_surface', None) is not None or getattr(policy, 'surface', None) is not None + (getattr(parent, 'manual_flm_effects', None) is not None and type(parent.manual_flm_effects) is not ManualEffects) + or getattr(parent, 'flm_surface', None) is not None or getattr(policy, 'surface', None) is not None ) diff --git a/openpilot/starpilot/flm/tests/test_coordinate_locks.py b/openpilot/starpilot/flm/tests/test_coordinate_locks.py new file mode 100644 index 0000000000..bbce838b2a --- /dev/null +++ b/openpilot/starpilot/flm/tests/test_coordinate_locks.py @@ -0,0 +1,228 @@ +"""Manual choices remain fixed while other coordinates retain automatic ownership.""" +from dataclasses import replace +from contextlib import contextmanager +import json +from unittest.mock import patch + +import pytest + +from openpilot.starpilot.flm.canonical_surface_adapter import NAMES, CanonicalSurfaceEffects +from openpilot.starpilot.flm.manual_coordinates import ManualCoordinates, selected_manual +from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES, RouteSurfaceEffects, revision_for_manual, revision_locks +from openpilot.starpilot.flm.tests.test_manual_coordinates import cp as cp, manual, PrivateParams, save, feature, request, saved_profile +from openpilot.starpilot.flm.tests.test_configured_route_recording import control, wire +from openpilot.starpilot.flm.learning_wire import read_control +from openpilot.starpilot.flm.offroad_control_metadata import read_control_metadata +from openpilot.starpilot.flm.torque_stages import StageFrame +from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, parse_document, serialize_document +from openpilot.starpilot.saved_source import read_saved + + +def configure_controls_manual(controls, *, automatic=None, **changes): + from openpilot.starpilot.flm.manual_coordinates import context + from openpilot.selfdrive.controls.controlsd import Controls + + cp = controls.CP.as_builder() + cp.carVin = 'KMHM34AA0NA000001' # Declared unit vehicle, never an identity supplied to a real recording. + controls.params.put('CarParams', cp.to_bytes(), block=True) + values = dict.fromkeys(NAMES if automatic is None else ROUTE_NAMES, 0.) | changes + selected = ManualCoordinates(context(cp, controls.lateral_controller_selection.mode, recovered=automatic is not None), tuple(values.items()), + automatic=automatic).validate() + raw, readable = read_saved(controls.params, DOCUMENT_KEY, 16384) + assert readable and raw is not None + profiles = parse_document(raw) + fingerprint = str(controls.CP.carFingerprint) + profiles[fingerprint] = replace(profiles[fingerprint], manual_coordinates=selected) + controls.params.put(DOCUMENT_KEY, json.loads(serialize_document(profiles)), block=True) + return Controls(), selected + + +@contextmanager +def lock_drive(controls): + from openpilot.starpilot.flm.tests import test_registered_controls_global as packets + from openpilot.starpilot.flm.tests import test_live_trial_global_runtime as live + from openpilot.starpilot.flm.runtime_adapter_registry import read_source + + def source_packet(controls, now, tick, calibration, result=None, validation=None): + source = read_source(controls.CP, controls.params, now_ns=now, calibration=calibration, + calibration_generation=live.GENERATION, vehicle_session='declared-lock-fixture') + event = packets.result_message(result, 'declared-lock-fixture', tick + 1, now, replay_validation=validation) + packets.write_source_receipt(event, source) + return packets.messaging.log_from_bytes(event.to_bytes()) + with patch.object(packets, 'source_packet', source_packet), patch.object(live, 'source_packet', source_packet): + yield live.LiveControls(controls) + + +@pytest.mark.parametrize('name', NAMES) +def test_old_documents_lock_only_nondefault_values_without_rewriting_them(tmp_path, cp, name): + params = PrivateParams(tmp_path) + original = save(params, cp, manual(cp, **{name: .01})) + restored = selected_manual(cp, params) + assert restored.locked == (name,) + assert restored.document() == ManualCoordinates.from_document(restored.document()).document() + assert (tmp_path / 'd' / 'TorqueOverrideDocument').read_bytes() == original + assert revision_locks(revision_for_manual(restored)) == ((name,), True) + + +def test_edit_unchanged_save_restart_and_individual_default_preserve_other_locks(tmp_path, cp): + params = PrivateParams(tmp_path) + save(params, cp, manual(cp, center_taper_max=.01, unwind_taper_right=.02)) + state = {'parked': True} + editor, capability = feature(cp, params, state) + def row(name): + return replace(next(r for r in editor.manual_rows(capability, True) if r.key.endswith(':' + name)), vehicle_fingerprint=str(cp.carFingerprint)) + assert editor.apply(request(row('center_taper_max'), 1.)) + assert selected_manual(cp, params).locked == ('unwind_taper_right', 'center_taper_max') + assert editor.apply(request(row('center_taper_max'), 0.)) + assert selected_manual(cp, params).locked == ('unwind_taper_right',) + assert dict(saved_profile(params, cp).manual_coordinates.values)['unwind_taper_right'] == .02 + restarted, restarted_capability = feature(cp, params, state) + assert next(r for r in restarted.manual_rows(restarted_capability, True) if r.key.endswith(':unwind_taper_right')).value == '2.0000' + + +def test_editing_an_accepted_finding_locks_only_that_value_and_default_releases_it(tmp_path, cp): + from openpilot.starpilot.flm.manual_coordinates import context + from openpilot.starpilot.galaxy.setting_descriptions import purpose + from openpilot.starpilot.galaxy.settings import _projection + + params = PrivateParams(tmp_path) + values = dict.fromkeys(ROUTE_NAMES, 0.) | {'ff_gain_left': .005, 'center_taper_max': .01, 'friction_threshold_mid': .003} + selected = ManualCoordinates(context(cp, 'starpilot', recovered=True), tuple(values.items()), + automatic=('ff_gain_left', 'friction_threshold_mid')).validate() + save(params, cp, selected) + editor, capability = feature(cp, params, {'parked': True}) + def row(name): + return replace(next(r for r in editor.manual_rows(capability, True) if r.key.endswith(':' + name)), vehicle_fingerprint=str(cp.carFingerprint)) + assert all(purpose(r) for r in editor.manual_rows(capability, True)) + assert _projection(row('ff_gain_left'))['acceptedFindingValue'] == .005 + assert editor.apply(request(row('ff_gain_left'), .5)) + assert 'acceptedFindingValue' not in _projection(row('ff_gain_left')) + restored = selected_manual(cp, params) + assert restored.locked == ('ff_gain_left', 'center_taper_max') + assert restored.automatic == ('friction_threshold_mid',) + assert editor.apply(request(row('ff_gain_left'), 0.)) + restored = selected_manual(cp, params) + assert restored.locked == ('center_taper_max',) + assert restored.automatic == ('friction_threshold_mid',) + assert dict(restored.values)['friction_threshold_mid'] == .003 + assert _projection(row('friction_threshold_mid'))['acceptedFindingValue'] == .003 + assert ManualCoordinates.from_document(restored.document()) == restored + + +@pytest.mark.parametrize('name', NAMES) +@pytest.mark.parametrize('setpoint,jerk,speed', [(0., 0., 15.), (.5, 1., 5.), (-1., 1., 25.)]) +def test_locked_manual_math_matches_existing_controller_math_when_no_auto_values_are_present(cp, name, setpoint, jerk, speed): + selected = manual(cp, **{name: .01}) + baseline = 'a' * 64 + before = CanonicalSurfaceEffects({NAMES[0]: dict(selected.values)[NAMES[0]]}, baseline, accumulated=dict(selected.values)) + values = dict.fromkeys(ROUTE_NAMES, 0.) | dict(selected.values) + after = RouteSurfaceEffects({NAMES[0]: values[NAMES[0]]}, baseline, accumulated=values, revision=revision_for_manual(selected)) + frame = StageFrame(speed, setpoint, jerk, .4, .3, True, False, False) + for source in (before, after): + source.begin_frame(1) + expected = before.selected_stage(frame, original_anchor=before.original_effect_anchor) + assert after.selected_stage(frame, original_anchor=after.original_effect_anchor) == expected + + +def test_an_unlocked_automatic_coordinate_changes_output_without_changing_the_manual_value(cp): + selected = manual(cp, center_taper_max=.01) + original = dict.fromkeys(ROUTE_NAMES, 0.) | dict(selected.values) + candidate = dict(original, ff_gain_left=.005) + sources = [RouteSurfaceEffects({NAMES[0]: v[NAMES[0]]}, 'a' * 64, accumulated=v, revision=revision_for_manual(selected)) for v in (original, candidate)] + frame = StageFrame(20., .3, .1, .4, .3, True, False, False) + results = [] + for source in sources: + source.begin_frame(1) + results.append(source.selected_stage(frame, original_anchor=source.original_effect_anchor)) + assert source.values['center_taper_max'] == .01 + assert results[0] != results[1] + assert selected.locked == ('center_taper_max',) + + +@pytest.mark.parametrize('inhibited', [False, True]) +def test_original_wire_retains_locked_identity_and_does_not_invent_an_application_on_a_limited_tick(cp, inhibited): + selected = manual(cp, center_taper_max=.01) + revision = revision_for_manual(selected) + original = control(inhibited=inhibited) + configured = dict(original.route_configured_coordinates, center_taper_max=.01) + actual = dict.fromkeys(ROUTE_NAMES, 0.) if inhibited else configured + original = replace(original, stage_schema_revision='torque-selected-stage-snapshot-v1@' + revision + '+configured-v1', + route_effect_revision=revision, route_configured_coordinates=tuple(configured.items()), route_applied_coordinates=tuple(actual.items())) + packet = wire(original) + for read in (read_control, read_control_metadata): + restored = read(packet) + assert restored.route_effect_revision == revision + assert restored.route_applied_coordinates == original.route_applied_coordinates + assert restored.route_configured_coordinates == original.route_configured_coordinates + + +@pytest.mark.parametrize('revision', ['route-coordinate-locks-v1-c-000000000', 'route-coordinate-locks-v1-c-800000000', + 'route-coordinate-locks-v1-c-100000000', 'route-coordinate-locks-v1-x-000000001']) +def test_invalid_or_out_of_manifest_locks_refuse(revision): + with pytest.raises(ValueError): + revision_locks(revision) + + +@pytest.mark.parametrize('accepted', [False, True]) +def test_actual_controls_keep_collecting_and_reconstruct_user_selected_values(accepted): + from openpilot.starpilot.flm.tests.test_fixed_manual_baseline import fixed_controls + from openpilot.starpilot.flm.learner_factory import _frame + from openpilot.starpilot.flm.controller_replay import ControllerReplay, SelectedControllerFactory, snapshot_from_values + from openpilot.starpilot.flm.torque_adapter import Objective + + with fixed_controls(factor=False, friction=False) as (initial, _): + controls, selected = configure_controls_manual(initial, center_taper_max=.01, automatic=('center_taper_max',) if accepted else None) + raw = read_saved(controls.params, DOCUMENT_KEY, 16384) + assert controls.LaC.manual_flm_effects.profile == selected + assert controls.LaC.route_flm_effects is not None, controls.route_flm_status + captured = None + with lock_drive(controls) as drive: + for tick in range(151): + now, _ = drive.frame() + runtime = controls.global_learning + if tick > 100 and runtime.eligible and runtime.snapshot: + captured = runtime.capture_evidence(control_ns=now + 1, state_ns=int(controls.sm.logMonoTime['selfdriveState']), active=True, limited=False) + if captured is not None: + break + assert captured is not None, controls.global_learning.reason + assert not captured.manual and dict(captured.route_applied_coordinates)['center_taper_max'] == .01 + assert revision_locks(captured.route_effect_revision)[0] == (() if accepted else ('center_taper_max',)) + factory = SelectedControllerFactory(controls.CP, captured.controller_mode, turn_assist=captured.turn_assist) + replay = ControllerReplay(factory, Objective('feedforward', 'high', 'steady'), identity=captured.identity, + baseline_revision=captured.baseline_revision, model_revision='declared-unit-reconstruction') + original_frame = _frame(captured) + replay.checkpoint(original_frame.control_ns, snapshot_from_values(captured.replay_snapshot)) + replay.raw_mode = True + reconstructed = replay.normalize(original_frame, _verify_only=True) + assert reconstructed is not None and reconstructed.verified + assert read_saved(controls.params, DOCUMENT_KEY, 16384) == raw + + +def test_actual_runtime_applies_an_unlocked_adjustment_and_quality_rollback_keeps_the_manual_value(): + from openpilot.starpilot.flm.tests.test_fixed_manual_baseline import fixed_controls + from openpilot.starpilot.flm.offroad_runtime import RouteEffects + from openpilot.starpilot.flm.offroad_surface import stop_marker + + # Declared saved-row values exercise runtime application, not a claim of road qualification. + with fixed_controls(factor=False, friction=False) as (initial, _): + controls, selected = configure_controls_manual(initial, center_taper_max=.01) + original = controls.LaC.route_flm_effects + assert original is not None, controls.route_flm_status + target = dict(original.values, ff_gain_left=.005) + owner = RouteEffects(original.scope, tuple(target.items()), original.numeric, previous=original.values, + fixed_numeric=original.fixed_numeric, revision=revision_for_manual(selected)) + controls.LaC.route_flm_effects = owner + with lock_drive(controls) as drive: + for _ in range(151): + drive.frame() + assert controls.global_learning.eligible + assert owner.calls and owner.frame_allowed + assert owner.source.values['center_taper_max'] == .01 and owner.source.values['ff_gain_left'] == .005 + owner.observe_current_status(stop_marker(owner.scope.key(), target, 'gross_tracking_or_oscillation_worse')) + assert owner.quality_stopped + assert dict(owner.values)['center_taper_max'] == .01 + assert dict(owner.values)['ff_gain_left'] == 0. + for _ in range(5): + drive.frame() + assert controls.global_learning.eligible and owner.frame_allowed + assert owner.source.values['center_taper_max'] == .01 diff --git a/openpilot/starpilot/flm/tests/test_manual_coordinates.py b/openpilot/starpilot/flm/tests/test_manual_coordinates.py index bdd6c07b81..9abc4519e7 100644 --- a/openpilot/starpilot/flm/tests/test_manual_coordinates.py +++ b/openpilot/starpilot/flm/tests/test_manual_coordinates.py @@ -274,8 +274,8 @@ def test_next_startup_loads_new_saved_values_without_mutating_running_profile(tm assert dict(following.profile.values)['center_taper_max'] == .02 -@pytest.mark.parametrize('saved,expected', [(False, True), (True, False)]) -def test_actual_controls_startup_holds_native_learning_only_for_manual_tune(tmp_path, cp, monkeypatch, saved, expected): +@pytest.mark.parametrize('saved', [False, True]) +def test_actual_controls_startup_keeps_learning_with_individual_manual_settings(tmp_path, cp, monkeypatch, saved): from openpilot.selfdrive.controls import controlsd params = PrivateParams(tmp_path) if saved: @@ -287,7 +287,7 @@ def test_actual_controls_startup_holds_native_learning_only_for_manual_tune(tmp_ monkeypatch.setattr(owner, 'params', params, raising=False) owner.lateral_controller_selection = default_selection(cp) effects, status = owner._configure_manual_tune() - assert owner.torque_learning_allowed is expected + assert owner.torque_learning_allowed assert (effects is not None) is saved assert status == ('configured' if saved else 'not_configured') assert (tmp_path / 'd' / 'ForceAutoTuneOff').read_bytes() == b'0' diff --git a/openpilot/starpilot/flm/tests/test_upstream_producer_transport.py b/openpilot/starpilot/flm/tests/test_upstream_producer_transport.py index d3dd7234ad..d7459647f3 100644 --- a/openpilot/starpilot/flm/tests/test_upstream_producer_transport.py +++ b/openpilot/starpilot/flm/tests/test_upstream_producer_transport.py @@ -10,7 +10,8 @@ from openpilot.starpilot.flm import producer_clock_equivalence as clock APPROVED = { 'starpilot/car/volkswagen/model_smoothing.py': 'dd5d0ddaf77fe05960b673557b1b9f649d303ddfdad77a5185c7b3156fc6bbd2', - 'selfdrive/modeld/modeld.py': '7a0eaf1f854c8f290f157d860691bb3e2c00c7421fbf9f1f8a092683757988ee', + 'selfdrive/modeld/modeld.py': '1b8d96ca9f7ac267d180732a6646b128bcbaec9ac79f80814030ec84197fd9d5', + 'starpilot/car/hyundai/model_smoothing.py': '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243', 'visionipc/visionipc_py.cc': '6c131c4f5eccb9f822f1aaae63733f26b1427c52340b61c9cdaf6cd4aee2f89d', 'visionipc/visionipc_server.cc': 'a4325a5171eacb931eb271d06a992d2f27216040df113d92099f62cdfa67d81a', 'visionipc/visionipc_client.cc': 'd142cd60eedabfc581e9770fcd6f0ca81b762ba9dbc608b54dd20a27a317a52d', @@ -19,7 +20,7 @@ APPROVED = { def test_exact_installed_upstream_closure_is_checked_before_contract(): contract = clock.pinned_default_contract() - assert len(clock.PRODUCER_SOURCE_HASHES) == 20 + assert len(clock.PRODUCER_SOURCE_HASHES) == 21 assert {relative: expected for _, relative, expected in clock.PRODUCER_SOURCE_HASHES if relative in APPROVED} == APPROVED assert contract.producer_revision == clock.CLOSURE_SHA256 assert contract.proof_sha256 == clock.CLOSURE_SHA256 diff --git a/openpilot/starpilot/galaxy/flm_acceptance.py b/openpilot/starpilot/galaxy/flm_acceptance.py new file mode 100644 index 0000000000..2df3b36c21 --- /dev/null +++ b/openpilot/starpilot/galaxy/flm_acceptance.py @@ -0,0 +1,101 @@ +"""Explicit parked acceptance is a user starting value, never automatic qualification.""" +from dataclasses import replace +import math +import re + +from openpilot.starpilot.flm.manual_coordinates import ManualCoordinates, context, selected_manual +from openpilot.starpilot.flm.offroad_cache import AssessmentCache, directory_for_params +from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES +from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest +from openpilot.starpilot.lateral.controller_selection import read_selection, DOCUMENT_KEY as CONTROLLER_KEY +from openpilot.starpilot.lateral.learning_preferences import read_preference, KEY as LEARNING_KEY +from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, MAX_DOCUMENT_BYTES, FieldChoice, PlatformProfile, parse_document, serialize_document +from openpilot.starpilot.saved_document import commit_exact +from openpilot.starpilot.saved_source import read_saved + + +def _finding(report, parameter, target, assessment): + current = report.get('current') or {} + details = current.get('details') or {} + if current.get('fresh') is not True or details.get('Offroad assessment hash') != assessment: + raise ValueError('Refresh the drive findings before accepting this change.') + rows = details.get('Recorded coordinate recommendations', ()) + matches = [row for row in rows if type(row) is list and len(row) == 5 and row[0] == parameter and row[2] == target + and type(row[3]) is int and row[3] > 0 and row[4] not in ( + 'conflicting_recorded_candidates', 'heldout_profile_does_not_support_training_step', 'controller_checks_did_not_support_change')] + if len(matches) != 1: + raise ValueError('This finding is no longer available. Refresh the drive review.') + return report.get('vehicle'), details.get('Original completed route hash'), tuple(matches[0]) + + +def accept_finding(settings, reports, payload, *, authorized): + if (type(payload) is not dict or set(payload) != {'parameter', 'target', 'assessment'} or payload['parameter'] not in ROUTE_NAMES + or type(payload['target']) not in (int, float) or not math.isfinite(payload['target']) or + type(payload['assessment']) is not str or re.fullmatch('[0-9a-f]{64}', payload['assessment']) is None): + raise ValueError('Select a current finding to accept.') + parameter, target, assessment = payload['parameter'], payload['target'], payload['assessment'] + with settings.lock: + ctx = settings.context.sample() + owner = settings._owner(ctx, live=True, session_valid=authorized) + if ctx.cp is None or not ctx.parked or ctx.editing_saved_vehicle or not owner.authority('torque') or not authorized(): + raise ValueError('Park with the current vehicle connected before accepting a finding.') + cp = ctx.cp + dependencies = {key: read_saved(settings.params, key, MAX_DOCUMENT_BYTES) for key in (CONTROLLER_KEY, LEARNING_KEY, 'ForceAutoTuneOff')} + if not all(value[1] for value in dependencies.values()): + raise ValueError('The saved learning settings are unreadable.') + selection = read_selection(settings.params, cp) + if selection.source == 'invalid': + raise ValueError('The selected steering controller is unavailable.') + identity = context(cp, selection.mode, recovered=True) + preference = read_preference(settings.params, cp, preference_snapshot=dependencies[LEARNING_KEY], legacy_snapshot=dependencies['ForceAutoTuneOff']) + if not preference.valid or not preference.enabled: + raise ValueError('Enable Auto Learn before accepting a finding for continued learning.') + found = _finding(reports.snapshot(), parameter, target, assessment) + # The canonical reader omits the report envelope's vehicle; the original + # cached assessment's exact CarParams digest below is mandatory either way. + if found[0] not in (None, str(cp.carFingerprint)): + raise ValueError('This finding belongs to a different vehicle.') + directory = directory_for_params(settings.params) + if not directory.exists(): + raise ValueError('The original drive review is unavailable. Refresh the findings.') + document = AssessmentCache(directory).get(assessment) + route = document['assessment']['route'] + if (document.get('kind') not in ('completed_assessment', 'partial_assessment') or + route['cp_sha256'] != car_params_digest(cp) or route['source_sha256'] != found[1]): + raise ValueError('The original drive review does not match this vehicle.') + raw, readable = read_saved(settings.params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) + if not readable: + raise ValueError('Saved steering settings are unreadable. Nothing was changed.') + baseline = cp.lateralTuning.torque + basis = (float(baseline.latAccelFactor), float(baseline.latAccelOffset), float(baseline.friction)) + profiles = {} if raw is None else parse_document(raw) + fingerprint = str(cp.carFingerprint) + profile = profiles.get(fingerprint, PlatformProfile(basis, FieldChoice(), FieldChoice())) + if profile.basis != basis or profile.flm is not None: + raise ValueError('Review the existing manual tune before accepting this finding.') + previous = selected_manual(cp, settings.params) + if previous is not None and previous.compatibility: + from openpilot.starpilot.flm.offroad_runtime import current_compatibility + from openpilot.starpilot.flm.runtime_adapter_registry import digest + if previous.compatibility != digest(current_compatibility(cp, settings.params)): + raise ValueError('Review the recovered tune before accepting this finding.') + values = dict.fromkeys(ROUTE_NAMES, 0.) | ({} if previous is None else dict(previous.values)) + values[parameter] = target + automatic = set(() if previous is None else previous.automatic or ()) | {parameter} + accepted = ManualCoordinates(identity, tuple(values.items()), '' if previous is None else previous.compatibility, + tuple(name for name in ROUTE_NAMES if name in automatic)).validate() + profiles[fingerprint] = replace(profile, manual_coordinates=accepted) + desired = serialize_document(profiles) + def permitted(): + fresh = settings.context.sample() + return (authorized() and fresh.parked and fresh.cp_raw == ctx.cp_raw and owner.authority('parked_preferences') + and owner.authority('torque') and _finding(reports.snapshot(), parameter, target, assessment) == found + and all(read_saved(settings.params, key, MAX_DOCUMENT_BYTES) == value for key, value in dependencies.items())) + + if not permitted(): + raise ValueError('The vehicle or finding changed. Review it again.') + saved = commit_exact(settings.params, key=DOCUMENT_KEY, max_bytes=MAX_DOCUMENT_BYTES, raw=desired, + expected=raw, authorized=permitted, temp_prefix='.accepted-steering-') + if not saved.committed or not saved.verified: + raise ValueError('Could not confirm that the finding was saved. Refresh the saved settings.') + return {'status': 'saved', 'parameter': parameter, 'value': target, 'learning': 'automatic', 'for_next_drive': True} diff --git a/openpilot/starpilot/galaxy/flm_backup.py b/openpilot/starpilot/galaxy/flm_backup.py index ba099165c0..c789bca9c2 100644 --- a/openpilot/starpilot/galaxy/flm_backup.py +++ b/openpilot/starpilot/galaxy/flm_backup.py @@ -74,7 +74,7 @@ class FlmBackup: 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 + return {'compatibility': compatibility, 'setup': selected, 'manualProfile': None if manual is None or not manual.route_format 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()}} @@ -194,6 +194,11 @@ class FlmBackup: if mode == 'recovery': return self._manual_recovery(backup, learned, ctx, raw, doc, authorized) if mode == 'manual': + retained = backup.get('recovery', {}).get('manualProfile') + if retained is not None: + from openpilot.starpilot.flm.manual_coordinates import ManualCoordinates + if ManualCoordinates.from_document(json.loads(retained)).automatic is not None: + return self._manual_recovery(backup, learned, ctx, raw, doc, authorized) available = {row.key: row for row in self.settings._state('tuning', ctx).rows if row.available} helper = ToggleBackup(self.settings, None) for row in backup['manual']: @@ -280,7 +285,8 @@ class FlmBackup: 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): + if (manual.compatibility != token and not (manual.automatic is not None and manual.compatibility == '') + 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: @@ -311,7 +317,7 @@ class FlmBackup: 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': '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 these manual slider values? Changed values stay locked; other settings can 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): diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index eff2d80f7e..e0e69dd2f0 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -1723,6 +1723,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe '/api/connect/proxy', '/api/connect/provider', '/api/auth/login', '/api/auth/logout', '/api/settings/preview', '/api/settings/confirm', '/api/settings/recovery/preview', '/api/settings/recovery/confirm', '/api/settings/flm-backup/preview', '/api/settings/flm-backup/confirm', + '/api/settings/flm-finding/accept', '/api/settings/reset-default', '/api/settings/restore', '/api/recordings/action', '/api/replay/start', '/api/replay/control', '/api/replay/stop', '/api/replay/export-start', @@ -1803,6 +1804,24 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe else: self.json(200 if authorized() else 401, result if authorized() else {'error': 'Sign in to Galaxy'}) return + if path == '/api/settings/flm-finding/accept': + identity = self.settings_session() + if identity is None: + self.json(401, {'error': 'Sign in to Galaxy'}) + return + from openpilot.starpilot.galaxy.flm_acceptance import accept_finding + def authorized(): + return self.settings_session() == identity + try: + with effect_lock: + result = accept_finding(feature_settings(), training_results_source, payload, authorized=authorized) + except (ValueError, SettingsChanged) as error: + self.json(409 if authorized() else 401, {'error': str(error) if authorized() else 'Sign in to Galaxy'}) + except (SettingsUnavailable, OSError, RuntimeError, TypeError, KeyError): + self.json(503, {'error': 'Could not confirm this finding was saved. Refresh the saved settings before trying again.'}) + else: + self.json(200 if authorized() else 401, result if authorized() else {'error': 'Sign in to Galaxy'}) + return if path.startswith('/api/replay/'): replay_api.post(self, path, payload) return diff --git a/openpilot/starpilot/galaxy/setting_descriptions.py b/openpilot/starpilot/galaxy/setting_descriptions.py index 635ddb645d..1188fcb881 100644 --- a/openpilot/starpilot/galaxy/setting_descriptions.py +++ b/openpilot/starpilot/galaxy/setting_descriptions.py @@ -54,7 +54,7 @@ DESCRIPTIONS = { 'TurnAssist': 'Uses steering-angle feedback to assist rolling low-speed turns above the vehicle minimum steering speed.', 'LateralControllerSelection': 'Chooses the stock steering controller or the vehicle-specific StarPilot controller.', 'ForceAutoTuneOff': ('StarPilot’s FLM tuning will attempt to automatically correct torque profiles as you drive. ' + - 'On allows automatic learning; Off disables it. Nonzero manual FLM overrides pause Auto Learn.'), + 'On allows automatic learning; Off disables it. Manual FLM overrides lock only the settings you change.'), 'torque_prepare_firestar': 'Prepares steering settings for a tuning-request recording. Turning it off restores the previous settings.', 'SteerLatAccel': 'Sets the legacy lateral-acceleration-to-torque conversion. Review the vehicle-specific tuning profile before applying it.', 'SteerFriction': 'Sets legacy steering friction compensation. Review the vehicle-specific tuning profile before applying it.', @@ -354,6 +354,13 @@ FLM_DESCRIPTIONS = { 'Higher fades it more; lower keeps more. The fade can be limited by Curvy unwind floor relief. No effect with ' + 'FF gain at zero.'), } +FLM_DESCRIPTIONS.update({ + 'friction_threshold_' + speed: ( + 'Shapes small steering corrections at ' + label + '. Higher makes compensation build more gradually; ' + + 'lower makes it respond sooner. Auto Learn can refine an accepted finding.') + for speed, label in (('crawl', 'crawling speeds'), ('low', 'low speeds'), ('mid', 'medium speeds'), + ('fast', 'higher speeds'), ('highway', 'highway speeds')) +}) def purpose(row): diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py index c95b5642f5..3085d430f1 100644 --- a/openpilot/starpilot/galaxy/settings.py +++ b/openpilot/starpilot/galaxy/settings.py @@ -417,6 +417,7 @@ def _projection(row: FeatureRow) -> dict: "repairValue": row.repair_value, "defaultValue": row.default_value, "resetAvailable": row_default(row) is not None, "displayScale": "lane-strength" if row.key == "LaneCenteringStrength" else None, **({"coordinate": row.key.removeprefix("torque:surface:")} if row.key.startswith("torque:surface:") and row.key != "torque:surface:reset" else {}), + **({"acceptedFindingValue": row.accepted_finding_value} if row.accepted_finding_value is not None else {}), "heading": is_heading(row.key), "collapsed": bool(row.collapsed), **({"previewSound": row.key} if row.key in SOUND_SPECS else {})} diff --git a/openpilot/starpilot/galaxy/tests/description-key-inventory.json b/openpilot/starpilot/galaxy/tests/description-key-inventory.json index 2d4c7c5eb0..10853d6d0a 100644 --- a/openpilot/starpilot/galaxy/tests/description-key-inventory.json +++ b/openpilot/starpilot/galaxy/tests/description-key-inventory.json @@ -407,6 +407,11 @@ "torque:learning:value", "torque:ratio:mode", "torque:ratio:value", + "torque:surface:friction_threshold_crawl", + "torque:surface:friction_threshold_fast", + "torque:surface:friction_threshold_highway", + "torque:surface:friction_threshold_low", + "torque:surface:friction_threshold_mid", "torque_prepare_firestar", "vasm:annotation", "vasm:confidence", diff --git a/openpilot/starpilot/galaxy/tests/test_flm.mjs b/openpilot/starpilot/galaxy/tests/test_flm.mjs index aebad771ff..8583873057 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm.mjs @@ -151,3 +151,44 @@ assert.doesNotMatch(FlmPage.template, /Steering settings|One change\. A fair com assert.match(FlmPage.template, /

Your steering<\/h2>/) assert.match(FlmPage.template, /]+:active="view === 'plots'"[^>]+embedded/) assert.doesNotMatch(FlmPage.template, /gx-tuner__plots-link/) + +// An explicit acceptance uses its own endpoint; slider editing remains manual. +const acceptanceContext = { mode: 'local', preference: { valid: true, enabled: true, parked: true, controller: 'torque' }, + current: { fresh: true }, error: '', manualBusy: false } +assert.equal(FlmPage.computed.canAcceptFindings.call(acceptanceContext), true) +for (const change of [{ manualBusy: true }, { current: { fresh: false } }, { mode: 'remote' }, + ...['parked', 'enabled', 'valid'].map(key => ({ preference: { ...acceptanceContext.preference, [key]: false } })), + { preference: { ...acceptanceContext.preference, controller: 'pid' } }]) + assert.equal(FlmPage.computed.canAcceptFindings.call({ ...acceptanceContext, ...change }), false) +const acceptanceFetch = globalThis.fetch +try { + const idea = { parameter: 'ff_gain_left', target: .005 } + const vm = { ...FlmPage.data(), canAcceptFindings: true, review: { findings: [idea] }, + current: { details: { 'Offroad assessment hash': 'a'.repeat(64) } }, + manualFeed: { active: false }, parameterLabel: name => name, unauthorized: () => {} } + vm.reviewFinding = FlmPage.methods.reviewFinding.bind(vm) + vm.acceptFinding = FlmPage.methods.acceptFinding.bind(vm) + const calls = [] + globalThis.fetch = async (url, options) => { + calls.push({ url, options }) + return { ok: true, json: async () => ({ status: 'saved', parameter: idea.parameter, value: idea.target, learning: 'automatic', for_next_drive: true }) } + } + vm.reviewFinding(idea) + assert.equal(calls.length, 0, 'Reviewing acceptance never writes') + await vm.acceptFinding() + assert.equal(calls.length, 1) + assert.equal(calls[0].url, './api/settings/flm-finding/accept') + assert.deepEqual(JSON.parse(calls[0].options.body), { parameter: idea.parameter, target: idea.target, assessment: 'a'.repeat(64) }) + assert.equal(vm.findingDraft, null) + assert.match(vm.findingNotice, /Auto Learn stays on/) + vm.reviewFinding(idea) + globalThis.fetch = async () => { calls.push('failed');throw new TypeError('offline') } + await vm.acceptFinding() + assert.equal(calls.length, 2, 'An unknown write outcome is not retried automatically') + assert.equal(vm.findingNotice, '') + assert.match(vm.findingError, /Could not confirm/) + vm.canAcceptFindings = false + vm.reviewFinding(idea) + assert.equal(vm.findingDraft, null) +} finally { globalThis.fetch = acceptanceFetch } +console.log('Accept finding keeps learning enabled, requires parked authority, and preserves uncertain write outcomes') diff --git a/openpilot/starpilot/galaxy/tests/test_flm_acceptance.py b/openpilot/starpilot/galaxy/tests/test_flm_acceptance.py new file mode 100644 index 0000000000..142a183d02 --- /dev/null +++ b/openpilot/starpilot/galaxy/tests/test_flm_acceptance.py @@ -0,0 +1,180 @@ +"""Accepting a finding saves explicit user intent without freezing its learner.""" +from copy import deepcopy +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace +from typing import Any +import http.client +import json +import threading +import unittest +from unittest.mock import patch + +from openpilot.starpilot.flm.manual_coordinates import selected_manual +from openpilot.starpilot.flm.offroad_cache import AssessmentCache, directory_for_params +from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES +from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest +from openpilot.starpilot.galaxy.flm_acceptance import accept_finding +from openpilot.starpilot.galaxy.tests import test_flm_backup as fixtures +from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY +from openpilot.starpilot.saved_source import read_saved + + +class TestFindingAcceptance(unittest.TestCase): + def setUp(self): + self.fixture = fixtures.FlmBackupTest() + self.fixture.setUp() + self.addCleanup(self.fixture.doCleanups) + self.settings, self.params = self.fixture.gateway, self.fixture.params + self.cp = self.fixture.fixture.context.value.cp + self.cache = AssessmentCache(directory_for_params(self.params)) + self.source = 'c' * 64 + self.assessment = self.cache.put({'kind': 'completed_assessment', 'assessment': { + 'route': {'cp_sha256': car_params_digest(self.cp), 'source_sha256': self.source}}}) + self.report: dict[str, Any] = {'vehicle': str(self.cp.carFingerprint), 'current': {'fresh': True, 'details': { + 'Original completed route hash': self.source, 'Offroad assessment hash': self.assessment, + 'Recorded coordinate recommendations': [['ff_gain_left', 0., .005, 6, 'recorded_provisional_suggestion']]}}} + self.reports = SimpleNamespace(snapshot=lambda: deepcopy(self.report)) + + def accept(self, name='ff_gain_left', target=.005, **kwargs): + return accept_finding(self.settings, self.reports, {'parameter': name, 'target': target, 'assessment': self.assessment}, + authorized=kwargs.get('authorized', lambda: True)) + + def raw(self): + return read_saved(self.params, DOCUMENT_KEY, 16384)[0] + + def test_every_supported_coordinate_can_be_accepted_without_locking_it(self): + for name in ROUTE_NAMES: + with self.subTest(name=name): + self.report['current']['details']['Recorded coordinate recommendations'] = [[name, 0., .001, 6, 'recorded_provisional_suggestion']] + result = self.accept(name, .001) + self.assertEqual(result['learning'], 'automatic') + selected = selected_manual(self.cp, self.params) + self.assertIn(name, selected.automatic) + self.assertNotIn(name, selected.locked) + self.assertEqual(dict(selected.values)[name], .001) + + def test_acceptance_preserves_other_values_learning_history_and_repeated_readback(self): + before = self.fixture.stored() + first = self.accept() + raw = self.raw() + self.assertEqual(self.accept(), first) + self.assertEqual(self.raw(), raw) + self.assertEqual(self.fixture.stored(), before) + self.assertTrue(first['for_next_drive']) + self.assertNotIn('qualified', first) + self.assertEqual(selected_manual(self.cp, self.params).locked, ()) + + def test_canonical_report_without_envelope_identity_uses_exact_original_car_params(self): + self.report.pop('vehicle') + self.assertEqual(self.accept()['learning'], 'automatic') + + def test_refuses_changed_target_conflicts_missing_review_and_nonfinite_values_without_writes(self): + for change in ('target', 'conflict', 'stale', 'missing_cache', 'wrong_vehicle', 'wrong_cp', 'disabled', 'nonfinite', 'onroad'): + with self.subTest(change=change): + original = deepcopy(self.report) + context = self.fixture.fixture.context.value + preference = self.params.get('SteeringLearningPreferences') + raw = self.raw() + target = .005 + if change == 'target': + target = .006 + elif change == 'conflict': + self.report['current']['details']['Recorded coordinate recommendations'][0][4] = 'conflicting_recorded_candidates' + elif change == 'stale': + self.report['current']['fresh'] = False + elif change == 'missing_cache': + (self.cache.directory / (self.assessment + '.json')).rename(self.cache.directory / 'held.json') + elif change == 'wrong_vehicle': + self.report['vehicle'] = 'other' + elif change == 'wrong_cp': + cp = self.cp.as_reader().as_builder() + cp.mass += 1 + self.fixture.fixture.context.value = replace(context, cp=cp, cp_raw=cp.to_bytes()) + elif change == 'disabled': + from openpilot.starpilot.lateral.learning_preferences import replace_preference + self.params.put('SteeringLearningPreferences', replace_preference(None, self.cp, False), block=True) + elif change == 'nonfinite': + target = float('nan') + else: + self.fixture.fixture.context.value = replace(context, parked=False) + try: + with self.assertRaises((ValueError, OSError)): + self.accept(target=target) + self.assertEqual(self.raw(), raw) + finally: + self.report = original + self.fixture.fixture.context.value = context + if change == 'missing_cache': + (self.cache.directory / 'held.json').rename(self.cache.directory / (self.assessment + '.json')) + if preference is None: + self.params.remove('SteeringLearningPreferences') + else: + self.params.put('SteeringLearningPreferences', preference, block=True) + + def test_session_or_parked_authority_lost_during_commit_preserves_original(self): + before = self.raw() + calls = [] + def authorized(): + calls.append(True) + return len(calls) < 4 + with self.assertRaises(ValueError): + self.accept(authorized=authorized) + self.assertEqual(self.raw(), before) + + def test_interrupted_replace_preserves_original_and_reports_unconfirmed(self): + before = self.raw() + with patch('openpilot.starpilot.saved_document.os.replace', side_effect=OSError('interrupted')): + with self.assertRaisesRegex(ValueError, 'confirm'): + self.accept() + self.assertEqual(self.raw(), before) + root = Path(self.params.get_param_path(DOCUMENT_KEY)).parent.parent + self.assertEqual(list(root.glob('.accepted-steering-*')), []) + + def test_backup_roundtrip_preserves_acceptance_and_does_not_turn_it_into_a_manual_lock(self): + self.accept() + backup = self.fixture.owner.export() + selected = selected_manual(self.cp, self.params) + self.assertEqual(selected.automatic, ('ff_gain_left',)) + self.params.remove(DOCUMENT_KEY) + preview = self.fixture.preview(backup, mode='manual') + result = self.fixture.confirm(preview) + self.assertTrue(result['manual']) + restored = selected_manual(self.cp, self.params) + self.assertEqual(restored, selected) + self.assertEqual(restored.locked, ()) + + def test_http_requires_session_same_origin_and_parked_state_before_saving(self): + from openpilot.starpilot.galaxy.access import GalaxyAccessOwner + from openpilot.starpilot.galaxy.server import make_server + access = GalaxyAccessOwner(Path(self.params.get_param_path(DOCUMENT_KEY)).parent.parent / 'accept-access') + self.assertTrue(access.configure('password123', lambda: True)) + server = make_server(port=0, owner=access, settings=self.settings, training_results=self.reports) + worker = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': .01}, daemon=True) + worker.start() + def close(): + server.shutdown() + worker.join(timeout=2) + server.server_close() + self.addCleanup(close) + def post(path, body, cookie='', origin=None): + connection = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=5) + try: + connection.request('POST', path, body=json.dumps(body), headers={'Cookie': cookie, 'Content-Type': 'application/json', + 'Origin': origin or f'http://127.0.0.1:{server.server_port}'}) + response = connection.getresponse() + return response.status, dict(response.headers), json.loads(response.read()) + finally: + connection.close() + endpoint = '/api/settings/flm-finding/accept' + body = {'parameter': 'ff_gain_left', 'target': .005, 'assessment': self.assessment} + before = self.raw() + self.assertEqual(post(endpoint, body)[0], 401) + _, headers, _ = post('/api/auth/login', {'password': 'password123'}) + cookie = headers['Set-Cookie'].split(';')[0] + self.assertEqual(post(endpoint, body, cookie, 'https://wrong.invalid')[0], 403) + self.assertEqual(self.raw(), before) + status, _, saved = post(endpoint, body, cookie) + self.assertEqual(status, 200) + self.assertEqual(saved['learning'], 'automatic') + self.assertNotIn('ff_gain_left', selected_manual(self.cp, self.params).locked) diff --git a/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs b/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs index 69fb7ed975..8bb8e3e601 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs @@ -22,6 +22,7 @@ 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: {} } +const acceptedFindings = new Set() const manual = Object.fromEntries(SURFACE_NAMES.map(name => [name, 0])) const hints = [['highway_center_taper_max', .005], ['friction_threshold_low', .002], ['friction_threshold_mid', .004], ['friction_threshold_fast', .005], ['friction_threshold_highway', .006]] @@ -36,7 +37,7 @@ function report() { current: { fresh: true, ageSeconds: 0, enabled: application, status: 'collecting', reason: 'no_new_native_feasible_training_step', progress: { samples: 71357, blocks: 197, requiredBlocks: 6 }, fit: null, application: { applied: application, reason: application ? 'current_controller_application' : 'saved_configuration_is_not_current_application' }, - details: { 'Completed drive analyzed': 'declared-ui-drive', 'Recorded steering observations': 71357, + details: { 'Completed drive analyzed': 'declared-ui-drive', 'Recorded steering observations': 71357, 'Offroad assessment hash': 'a'.repeat(64), 'Original completed route hash': 'b'.repeat(64), 'Analysis decision': scenario === 'saved' ? 'bounded_trial_configured_for_next_drive' : 'no_new_native_feasible_training_step', 'Automatic configuration changed': saved, 'Saved route adjustment count': saved ? 1 : 0, 'Recorded coordinate recommendations': scenario === 'none' ? [] : hints.map(([name, target], index) => [name, 0, @@ -99,13 +100,14 @@ function settings() { return { page: 'tuning', title: 'Manual tuning', view: 'declared-ui-view', parked, rows: [...SURFACE_NAMES.map(coordinate => ({ coordinate, label: coordinate, // This highlighted dial uses the published help; other fixture rows stay generic. - reason: coordinate === 'highway_center_taper_max' ? 'Adds straight-ahead softening at highway speeds. Higher softens small corrections more; lower keeps more steering response. This changes steering feel, not your target position in the lane. Parked only. Manual overrides pause Auto Learn.' : - 'Shapes small steering corrections at this stage. Higher and lower values change the controller response. Parked only. Manual overrides pause Auto Learn.', + reason: coordinate === 'highway_center_taper_max' ? 'Adds straight-ahead softening at highway speeds. Higher softens small corrections more; lower keeps more steering response. This changes steering feel, not your target position in the lane. Parked only. Manual overrides lock only the changed setting.' : + 'Shapes small steering corrections at this stage. Higher and lower values change the controller response. Parked only. Manual overrides lock only the changed setting.', + ...(acceptedFindings.has(coordinate) ? {acceptedFindingValue: manual[coordinate] / 100} : {}), 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.' })) : []), + reason: 'Saved by explicit manual recovery. These values stay locked.' })) : []), { 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') @@ -134,11 +136,17 @@ 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-finding/accept') { + const hint = hints.find(([name, target]) => body.parameter === name && body.target === target) + if (!hint || body.assessment !== 'a'.repeat(64)) return json({ error: 'Finding changed' }, 409) + acceptedFindings.add(body.parameter);manual[body.parameter] = body.target * 100 + return json({ status: 'saved', parameter: body.parameter, value: body.target, learning: 'automatic', for_next_drive: true }) + } 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, + json({ intent: 'declared-backup-intent', question: backupRecovery ? 'Recover these values as your manual tune? Other settings can keep learning.' : + 'Restore these manual slider values? Manual overrides lock only the changed setting.', count: 1, changes: [['Highway center taper', '0', '0.5']] }) } if (pathname === '/api/settings/flm-backup/confirm') { @@ -309,7 +317,7 @@ try { await show('.gx-tuner__idea-grid');await capture(`${theme}-${width}-finding`) await show('.gx-tuner__groups');await capture(`${theme}-${width}-categories`) } - await click('.gx-tuner__idea-grid .gx-btn') + await click('.gx-tuner__idea-grid .gx-btn--tonal') assert.equal(await execute('return document.activeElement.id'), 'tuner-dial-highway_center_taper_max') assert.equal(await execute('return document.querySelector("#tuner-dial-highway_center_taper_max input").value'), '0') await layout(`${width}/${theme}/dial`) @@ -567,10 +575,10 @@ try { 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("[data-role=flm-backup]").textContent.includes("Manual values stay locked")')) 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")')) + assert(await execute('return document.querySelector("#tuner-recovered-title").parentElement.textContent.includes("Manually selected values stay locked")')) 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') @@ -578,6 +586,49 @@ try { await capture('backup-driving-locked') checks.push('backup/real-download/local-file/preview/confirmed-restore/incompatible/driving-lockout') assert.deepEqual(errors, []) + manualRecovered = false + await viewport(416);await change('ideas');await click('#tuner-tab-tune') + await until(() => execute('return window.flm.canAcceptFindings')) + const beforeAcceptance = requests.length + await click('[data-action=accept-finding]') + await until(() => execute('return !!document.querySelector("#accept-finding-title")')) + assert.equal(requests.length, beforeAcceptance, 'Opening the finding review does not save it') + assert(await execute('return document.querySelector("[role=dialog]").contains(document.activeElement)')) + await layout('finding/accept-review-mobile');await capture('finding-accept-review-mobile') + await click('dialog[aria-labelledby=accept-finding-title] .gx-dialog__actions button:first-child') + assert.equal(requests.length, beforeAcceptance, 'Cancel leaves the tune unchanged') + await click('[data-action=accept-finding]') + await click('dialog[aria-labelledby=accept-finding-title] .gx-dialog__actions button:last-child') + await until(() => execute('return !!window.flm.findingNotice && !window.flm.findingBusy')) + assert.equal(requests.at(-1).path, '/api/settings/flm-finding/accept') + assert.equal(requests.at(-1).body.parameter, 'highway_center_taper_max') + assert(acceptedFindings.has('highway_center_taper_max')) + assert.equal(await execute('return window.flm.offroad.saved'), false, 'User acceptance does not fabricate an automatic save') + assert(await execute('return document.querySelector("[data-action=accept-finding]").disabled')) + assert(await execute('return document.querySelector("[data-coordinate=highway_center_taper_max]").textContent.includes("Accepted for next drive")')) + await execute('window.flm.acceptedFindingNames=[]') + assert(await execute('return window.flm.findingAccepted(window.flm.review.manual[0])'), 'Saved acceptance survives clearing local UI state') + await layout('finding/accepted-learning-on');await capture('finding-accepted-learning-on') + await click('.gx-tuner__curve-summary > details > summary') + await click('[data-coordinate=friction_threshold_mid] [data-action=accept-finding]') + saveError = true + const beforeFailure = requests.length + await click('dialog[aria-labelledby=accept-finding-title] .gx-dialog__actions button:last-child') + await until(() => execute('return !!window.flm.findingError && !window.flm.findingBusy')) + assert.equal(requests.length, beforeFailure + 1, 'A failed or unknown write is not retried') + assert(!acceptedFindings.has('friction_threshold_mid')) + await show('[data-role=finding-error]');await capture('finding-accept-error') + await change('ideas', { parked: false });await click('#tuner-tab-tune') + assert(await execute('return [...document.querySelectorAll("[data-action=accept-finding]")].every(e=>e.disabled)')) + await capture('finding-driving-locked') + await viewport(1280, 900);await change('ideas');await click('#tuner-tab-tune') + await execute('window.flm.findingError=""') + await click('.gx-tuner__curve-summary > details > summary') + await click('[data-coordinate=friction_threshold_low] [data-action=accept-finding]') + await layout('finding/accept-review-desktop');await capture('finding-accept-review-desktop') + await click('dialog[aria-labelledby=accept-finding-title] .gx-dialog__actions button:first-child') + checks.push('finding/explicit-accept/cancel/learning-on/no-auto-qualification/error/no-retry/driving-lockout') + console.log(`Real Chromium FLM UI: ${checks.length} responsive/theme/state checks, 5 findings/7 destinations, parked save/reset, driving lockout, errors and retained evidence passed`) } catch (error) { failure = error.stack diff --git a/openpilot/starpilot/galaxy/tests/test_setting_descriptions.py b/openpilot/starpilot/galaxy/tests/test_setting_descriptions.py index 589935964d..24004d044b 100644 --- a/openpilot/starpilot/galaxy/tests/test_setting_descriptions.py +++ b/openpilot/starpilot/galaxy/tests/test_setting_descriptions.py @@ -131,10 +131,11 @@ def test_actual_owner_projections_have_no_uncovered_setting(tmp_path): def test_manual_coordinate_purposes_preserve_startup_and_context_warnings(): from openpilot.starpilot.flm.canonical_surface_adapter import NAMES - startup = "Parked only. Saved for the next drive; zero restores this stage's original baseline. Manual overrides pause Auto Learn." + from openpilot.starpilot.flm.offroad_surface import ROUTE_NAMES + startup = "Parked only. Saved for the next drive; zero restores this stage's original baseline. Only changed settings are locked." changed = "Vehicle tune, controller or effect definition changed. Reset this manual tune before editing." - assert set(FLM_DESCRIPTIONS) == set(NAMES) - assert len(set(FLM_DESCRIPTIONS.values())) == len(NAMES) + assert set(FLM_DESCRIPTIONS) == set(ROUTE_NAMES) + assert len(set(FLM_DESCRIPTIONS.values())) == len(ROUTE_NAMES) for name in NAMES: row = FeatureRow('torque:surface:' + name, 'Manual correction', '0', reason=startup) assert 'higher' in purpose(row).lower() and 'lower' in purpose(row).lower() diff --git a/openpilot/starpilot/galaxy/web/js/flm-backup.js b/openpilot/starpilot/galaxy/web/js/flm-backup.js index 67dfe4a9ea..b4e831b877 100644 --- a/openpilot/starpilot/galaxy/web/js/flm-backup.js +++ b/openpilot/starpilot/galaxy/web/js/flm-backup.js @@ -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.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.pending = this.draft = null;this.notice = result.manual ? 'Tune recovered. Manual values stay locked; other settings can keep learning.' : 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 } @@ -88,7 +88,7 @@ export const FlmBackup = {
-

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.

+

Auto Learn setup restores a setup this comma already knows. On a wiped or replacement comma, choose Recover as manual tune. Recovered manual values stay locked; accepted findings can keep learning.

{{ error }}

Restore this tune?

diff --git a/openpilot/starpilot/galaxy/web/js/flm.js b/openpilot/starpilot/galaxy/web/js/flm.js index c5d497ec95..ec24a0a026 100644 --- a/openpilot/starpilot/galaxy/web/js/flm.js +++ b/openpilot/starpilot/galaxy/web/js/flm.js @@ -49,6 +49,7 @@ export const FlmPage = { go: { type: Function, default: path => { window.location.hash = path } } }, data: () => ({ report: null, error: "", loading: false, request: null, receivedAt: 0, now: 0, bluetooth: bluetoothConnection(), manualState: { status: "idle", data: null, pending: null, error: "" }, manualResetRequested: false, manualWrite: null, + findingDraft: null, findingBusy: false, findingError: '', findingNotice: '', acceptedFindingNames: [], headerOffset: 88, view: "overview", group: "balance", showAllHistory: false, groups: SURFACE_GROUPS }), watch: { initialView(view) { this.selectView(view) }, mode() { this.syncManualControls() }, @@ -85,6 +86,8 @@ export const FlmPage = { document.removeEventListener("visibilitychange", this.visibility) }, computed: { + canAcceptFindings() { return this.mode === 'local' && this.preference?.valid === true && this.preference.enabled === true && + this.preference.parked === true && this.preference.controller === 'torque' && this.current?.fresh === true && !this.error && !this.manualBusy }, manualRows() { return (this.manualState.data?.rows || []).map((row, index) => ({ row, index })).filter(({ row }) => this.selectedGroup.names.includes(row.coordinate)) }, recoveredManualCurve() { return (this.manualState.data?.rows || []).filter(row => FRICTION_NAMES.includes(row.coordinate)) }, manualActions() { return (this.manualState.data?.rows || []).map((row, index) => ({ row, index })).filter(({ row }) => row.confirm) }, @@ -180,12 +183,42 @@ export const FlmPage = { }, }, methods: { + reviewFinding(idea) { + if (!this.canAcceptFindings || this.findingBusy || !Number.isFinite(idea.target) || + !this.review.findings.some(row => row.parameter === idea.parameter && row.target === idea.target)) return + const assessment = this.current?.details?.['Offroad assessment hash'] + if (!/^[0-9a-f]{64}$/.test(assessment || '')) { this.findingError = 'Refresh the drive review before accepting a finding.'; return } + this.findingError = '';this.findingDraft = { parameter: idea.parameter, target: idea.target, assessment } + }, + async acceptFinding() { + if (!this.findingDraft || this.findingBusy || !this.canAcceptFindings) return + const draft = { ...this.findingDraft } + this.findingBusy = true;this.findingError = '';this.findingNotice = '' + try { + const result = await requestJson('./api/settings/flm-finding/accept', { request: { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(draft) } }) + if (result.status !== 'saved' || result.parameter !== draft.parameter || result.value !== draft.target || result.learning !== 'automatic') + throw new Error('Could not confirm this finding was saved. Refresh the saved settings.') + this.acceptedFindingNames = [...this.acceptedFindingNames, draft.parameter] + this.findingNotice = `${this.parameterLabel(draft.parameter)} accepted for your next drive. Auto Learn stays on for this setting.` + this.findingDraft = null + if (this.manualFeed?.active) await this.manualFeed.load('tuning') + } catch (error) { + if (error.status === 401) this.unauthorized() + this.findingError = error.status ? error.message : 'Could not confirm this finding was saved. Refresh the saved settings before trying again.' + this.findingDraft = null + } finally { this.findingBusy = false } + }, backupRestored() { this.manualWrite = null;this.manualResetRequested = false;this.manualFeed?.load('tuning');return this.load() }, dialPercent, ideaStatus, ideaValue, ideaHeading, curvePointLabel, ideaDetails, readable, detailText, coordinateText, measurementText, sourceSeconds, learningReason, historyTitle, recommendationText, - ideaExplanation(idea) { return idea.reason?.startsWith('observed_') ? learningReason(idea.reason) : ideaExplanation(idea) }, + findingAccepted(idea) { return this.acceptedFindingNames.includes(idea.parameter) || + this.manualState.data?.rows?.some(row => row.coordinate === idea.parameter && row.acceptedFindingValue === idea.target) }, + ideaExplanation(idea) { return this.findingAccepted(idea) ? 'This value is saved for your next drive. Auto Learn can keep refining it.' : + idea.reason?.startsWith('observed_') ? learningReason(idea.reason) : ideaExplanation(idea) }, manualEvidence(name, unit) { return offroadCoordinateEvidence(this.report, name, this.live, unit) }, beginManualWrite(requests) { const valid = requests.filter(([name, value]) => typeof name === 'string' && Number.isFinite(value)) + this.acceptedFindingNames = this.acceptedFindingNames.filter(name => !valid.some(([coordinate]) => coordinate === name)) this.manualWrite = valid.length ? { requests: valid, status: 'saving', values: null } : null }, publishManual(update) { @@ -299,6 +332,7 @@ export const FlmPage = { const value = await requestJson("./api/flm/training-results", { request: { signal: controller.signal } }) if (this.request !== controller || !this.activePage) return if (!validTrainingResults(value)) throw new Error("The device returned an unsupported training report.") + if (this.report?.current?.details?.['Offroad assessment hash'] !== value.current?.details?.['Offroad assessment hash']) this.acceptedFindingNames = [] this.report = value; this.error = ""; this.receivedAt = this.now = Date.now() clearTimeout(this.freshnessTimer) const age = value.current?.fresh ? value.current.ageSeconds * 1000 : 0 @@ -318,6 +352,12 @@ export const FlmPage = {