diff --git a/openpilot/starpilot/flm/offroad_checks.py b/openpilot/starpilot/flm/offroad_checks.py index 299c5b7362..d0a90d4e4c 100644 --- a/openpilot/starpilot/flm/offroad_checks.py +++ b/openpilot/starpilot/flm/offroad_checks.py @@ -338,12 +338,13 @@ def _read_original_results(assessment, original, ids, values, root, *, permitted original_outputs = tuple(outputs) numerical = check_candidate(assessment.cp, block, values, score_start_ns=start, score_end_ns=end, require_change=False, original_outputs=original_outputs) commands = numerical.pop('commands', ()) + unchanged_inhibited = numerical.pop('unchanged_inhibited_commands', ()) native = None if numerical['qualified']: stamps = {r[0] for r in commands} scored = tuple(c for c in block if c.control_ns in stamps) emissions = tuple(o for o in outputs if o.control_ns in stamps) - native = check_original_native(assessment.cp, scored, emissions, commands, require_change=False) + native = check_original_native(assessment.cp, scored, emissions, commands, require_change=False, unchanged_inhibited=unchanged_inhibited) okay = bool(numerical['qualified'] and native is not None and native['qualified']) results.append({'window': wid, 'qualified': okay, 'numerical': numerical, 'registered_encoder': native}) # Retain only one original segment of pre-roll for the following segment. diff --git a/openpilot/starpilot/flm/offroad_controller_checks.py b/openpilot/starpilot/flm/offroad_controller_checks.py index 02e56a3a9c..d42c565287 100644 --- a/openpilot/starpilot/flm/offroad_controller_checks.py +++ b/openpilot/starpilot/flm/offroad_controller_checks.py @@ -167,6 +167,7 @@ def check_candidate(cp, controls, values, *, score_start_ns=0, score_end_ns=2**6 verified = scored = changed = checkpoints = inhibited_frames = clipped_frames = nonemitted_frames = 0 minimum = maximum = 0.0 commands = [] + unchanged_inhibited = [] last_ns = last_sequence = 0 for evidence in controls: if ( @@ -223,12 +224,17 @@ def check_candidate(cp, controls, values, *, score_start_ns=0, score_end_ns=2**6 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: - return {'qualified': False, 'reason': 'actual_controller_output_bound', 'verified_frames': verified} reference = frame.actual_lac_command if reference is None: return {'qualified': False, 'reason': 'original_full_precision_controller_output_missing', 'verified_frames': verified} + if not math.isfinite(candidate): + return {'qualified': False, 'reason': 'actual_controller_output_bound', 'verified_frames': verified} + if abs(candidate) > probe.steer_max + 1e-12: + # An unchanged, inhibited original is context only. The native replay + # must also reproduce its bounded output if Card consumed the command. + if not (inhibited and candidate == reference and (delivery_context == 'clipped_context' or nonemitted)): + return {'qualified': False, 'reason': 'actual_controller_output_bound', 'verified_frames': verified} + unchanged_inhibited.append(frame.control_ns) # Compare the same Float32 actuator field, never raw double versus Float32. from openpilot.starpilot.flm.controller_replay import final_command @@ -264,6 +270,7 @@ def check_candidate(cp, controls, values, *, score_start_ns=0, score_end_ns=2**6 'minimum_command_delta': minimum, 'maximum_command_delta': maximum, 'commands': tuple(commands), + 'unchanged_inhibited_commands': tuple(unchanged_inhibited), 'counterfactual_rollout_proven': False, 'physical_improvement_proven': False, 'native_encoder_application_proven': False, @@ -271,7 +278,7 @@ def check_candidate(cp, controls, values, *, score_start_ns=0, score_end_ns=2**6 } -def check_original_native(cp, controls, outputs, commands, *, require_change=True): +def check_original_native(cp, controls, outputs, commands, *, require_change=True, unchanged_inhibited=()): """Decode originals then replay the registered encoder; no new native grant.""" from dataclasses import replace from opendbc.car.steering_projection import TorqueProjection @@ -327,6 +334,9 @@ def check_original_native(cp, controls, outputs, commands, *, require_change=Tru after = history.rollout(candidate, start, end, allow_unclipped_equal_output=True) except (AttributeError, KeyError, TypeError, ValueError, OverflowError) as error: return {'qualified': False, 'reason': 'original_encoder_or_candidate_quality_refused', 'detail': str(error)[:160]} + unchanged = set(unchanged_inhibited) + if any(before[stamp] != after[stamp] and output.control_ns in unchanged for stamp, output in originals.items()): + return {'qualified': False, 'reason': 'candidate_changed_inhibited_native_output'} changed = sum(before[k] != after[k] for k in before) return { 'qualified': bool(changed or not require_change), diff --git a/openpilot/starpilot/flm/offroad_processor.py b/openpilot/starpilot/flm/offroad_processor.py index 79a9247ef1..56ff59ce12 100644 --- a/openpilot/starpilot/flm/offroad_processor.py +++ b/openpilot/starpilot/flm/offroad_processor.py @@ -597,11 +597,20 @@ def _assess_inputs(route, collected, previous, *, permitted, sources=None, route } return None + stable_count = 0 for key, values in sorted(stable_windows.items()): + if not permitted(): + raise RouteInputCancelled('Parked analysis cancelled') + grade = stable_grades.get(key, 'continuous_original_control_metadata') + references = {w.identity: gross_reference(w) for w in values} + if grade != 'bookended_zero_route_tracking': + # Freeze input-only eligibility before partitioning. A trial needs a + # comparable two-second revocation reference for every selected parent. + values = [w for w in values if references[w.identity] is not None] if not values: continue + stable_count += len(values) report = analyze_stable_windows(tuple(values), permitted=permitted, route_order=route_order, comparison=comparisons.get(key)) - grade = stable_grades.get(key, 'continuous_original_control_metadata') report['tracking_source_grade'] = grade if grade == 'bookended_zero_route_tracking': _separate_qualification(report, windows.get(key, ()), proposal_windows=values, route_order=route_order) @@ -618,7 +627,7 @@ def _assess_inputs(route, collected, previous, *, permitted, sources=None, route 'end_ns': w.points[-1].mono_ns, 'metrics': tracking_metrics(w.points), 'demand': window_demand(w), - 'gross_reference': gross_reference(w), + 'gross_reference': references[w.identity], 'categorical_bookends_original_ns': bookends.get(w.identity, ()), } for w in values @@ -630,7 +639,7 @@ def _assess_inputs(route, collected, previous, *, permitted, sources=None, route bind_original_contexts(report, [*values, *windows.get(key, ())], comparisons[key]) stable.append(report) - counts['stable_qualified_whole_windows'] = sum(map(len, stable_windows.values())) + counts['stable_qualified_whole_windows'] = stable_count diagnostic = [] from openpilot.starpilot.flm.offroad_observed import merge_sources diff --git a/openpilot/starpilot/flm/offroad_stable_bridge.py b/openpilot/starpilot/flm/offroad_stable_bridge.py index 63a5fcb2ca..de49d97393 100644 --- a/openpilot/starpilot/flm/offroad_stable_bridge.py +++ b/openpilot/starpilot/flm/offroad_stable_bridge.py @@ -9,6 +9,7 @@ import hashlib import math from pathlib import Path from statistics import fmean +from typing import cast from openpilot.starpilot.flm.offroad_stable_policy import ( FLMSample, @@ -345,7 +346,8 @@ class StableRouteSelector: recommended = next((p for p in profiles if p['label'] == 'Recommended'), None) if recommended is not None: recommended['frictionCurveUnits'] = 'relative_actual_selected_threshold' - report = {'original_windows': windows, 'supported_dimensions': len(selected), 'unavailable_dimensions': unavailable, 'profile': recommended} + report = {'original_windows': windows, 'supported_dimensions': len(selected), 'unavailable_dimensions': unavailable, 'profile': recommended, + 'notchy_mid_curve_observed': any(row['bucket'] == 'notchy_mid_curve' for _, row in observations)} report['coordinate_candidates'] = coordinate_candidates(observations, self.previous) if observations_only: report['coordinate_observations'] = observations @@ -406,9 +408,9 @@ class StableRouteSelector: return None, {'reason': 'original_stable_input_fields_missing', 'original_windows': all_ids} training, training_report = self.profile(ids['training'], cohort['cohort']) selection = 'training_values_only_no_heldout_resizing' - if training is not None: - from openpilot.starpilot.flm.offroad_surface import CURVE_NAMES + from openpilot.starpilot.flm.offroad_surface import CURVE_NAMES + if training is not None: if any(training['values'][name] != self.previous[name] for name in CURVE_NAMES): # Quieting is one trial; unrelated turn changes need their own evidence. values = dict(self.previous) @@ -451,8 +453,14 @@ class StableRouteSelector: if not agrees: return None, proof assert training is not None + training_values = cast(dict[str, float], training['values']) + notchy_curve_quieting = ( + training_report.get('notchy_mid_curve_observed') is True and heldout_report.get('notchy_mid_curve_observed') is True + and all(name in CURVE_NAMES and training_values[name] > self.previous[name] for name in training['changed_parameters']) + ) return { 'parameter': 'stable:' + ','.join(training['changed_parameters']), + 'notchy_curve_quieting': notchy_curve_quieting, 'delta': training['maximum_coordinate_step'], 'values': training['values'], 'policy': 'original_stable_recommended_bounded_route_v1', diff --git a/openpilot/starpilot/flm/offroad_worker.py b/openpilot/starpilot/flm/offroad_worker.py index e92e6fe7ab..8b3c2aaf7d 100644 --- a/openpilot/starpilot/flm/offroad_worker.py +++ b/openpilot/starpilot/flm/offroad_worker.py @@ -492,6 +492,57 @@ def input_coverage(cohort): return cohort['whole_windows'] * min(references) ** 2 +def _candidate_order(choice): + group, cohort, proposal = choice + # Prefer a direct correction when independent sections both show notchy + # curves. Use original coverage to order the remaining choices. + return (proposal.get('notchy_curve_quieting') is not True, -input_coverage(cohort), -cohort['whole_windows'], + cohort['cohort'], group['original_context_sha256']) + + +def _save_route_trial(params, cp, trial, *, expected, authorized): + storage = RouteStorage(params) + from openpilot.starpilot.flm.offroad_store import MAX_SCOPES, validate_row + + scope = validate_row(trial) + document = decode(expected) + rows = document.get(NAMESPACE, {}) + if scope.key() in rows or not any(trial['previous'].values()): + return storage.save(trial, expected=expected, authorized=authorized) + # Derive the first rollback map from the actual saved settings, not the trial. + if trial['state'] != 'ready_for_next_drive' or trial['sequence'] != 1: + return False + + from openpilot.starpilot.flm.learned_lifecycle import encode + from openpilot.starpilot.flm.manual_coordinates import selected_manual + from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest + from openpilot.starpilot.saved_document import commit_exact + + if car_params_digest(cp) != scope.cp_sha256: + return False + manual = selected_manual(cp, params) + if (manual is None or trial['previous'] != (ZERO | manual.starting_values) + or any(trial['values'][name] != trial['previous'][name] for name in manual.locked)): + return False + + def permitted(): + return (storage.directory == Path(params.get_param_path(KEY)).parent.resolve() + and storage.directory.stat().st_uid == os.geteuid() and authorized() and selected_manual(cp, params) == manual) + + if not permitted() or read_saved(params, KEY, MAX_BYTES) != (expected, True): + return False + if len(rows) >= MAX_SCOPES: + from openpilot.starpilot.flm.offroad_saved_history import SavedHistory + + SavedHistory(params).preserve(expected) + del rows[min(rows, key=lambda key: (rows[key]['completed_wall_ns'], key))] + rows[scope.key()] = trial + desired = encode(dict(document, version=3, fullSurfaces=document.get('fullSurfaces', {}), routeSurfaces=rows)) + result = commit_exact(params, key=KEY, max_bytes=MAX_BYTES, raw=desired, expected=expected, + authorized=permitted, temp_prefix='.route-steering-') + return result.committed and result.verified + + def _input_spans(group, cohort, ids): name = 'qualification_original_windows' if 'qualification_roles' in cohort else 'selected_original_windows' return { @@ -1259,7 +1310,7 @@ class OffroadWorker: reason = outcome['reason'] else: # Freeze input-only ranking; training may select a candidate, validation may not. - choices.sort(key=lambda v: (-input_coverage(v[1]), -v[1]['whole_windows'], v[1]['cohort'], v[0]['original_context_sha256'])) + choices.sort(key=_candidate_order) recommendations_ready() training_seen = set() training_spans = set() @@ -1397,7 +1448,7 @@ class OffroadWorker: inventory = route_inventory(self.root) return not inventory['scanIncomplete'] and all(sum(r == source for r in inventory['routes']) == 1 for source in required) - saved = RouteStorage(self.params).save(new, expected=expected, authorized=original_sources_current) + saved = _save_route_trial(self.params, assessment.cp, new, expected=expected, authorized=original_sources_current) if not saved: raise ValueError('Next-drive tune compare-and-swap refused') status = 'ready_for_next_drive' diff --git a/openpilot/starpilot/flm/tests/test_coordinate_locks.py b/openpilot/starpilot/flm/tests/test_coordinate_locks.py index 747de67c56..25be50565b 100644 --- a/openpilot/starpilot/flm/tests/test_coordinate_locks.py +++ b/openpilot/starpilot/flm/tests/test_coordinate_locks.py @@ -263,3 +263,30 @@ def test_actual_runtime_applies_an_unlocked_adjustment_and_quality_rollback_keep drive.frame() assert controls.global_learning.eligible and owner.frame_allowed assert owner.source.values['center_taper_max'] == .01 + + +def test_first_automatic_trial_uses_the_confirmed_settings_as_its_exact_rollback(tmp_path, cp): + from openpilot.starpilot.flm.manual_coordinates import context + from openpilot.starpilot.flm.offroad_store import KEY, MAX_BYTES, RouteScope, RouteStorage, startup_row + from openpilot.starpilot.flm.offroad_worker import _save_route_trial + + params = PrivateParams(tmp_path) + prior = dict.fromkeys(ROUTE_NAMES, 0.) | {'ff_gain_left': .005, 'center_taper_max': .01} + selected = ManualCoordinates(context(cp, 'starpilot', recovered=True), tuple(prior.items()), automatic=('ff_gain_left',)).validate() + original = save(params, cp, selected) + scope = RouteScope(selected.context[0], 'selected-controller', 'a' * 64, 'b' * 64, '0', 'starpilot', 'torque') + row = {'scope': scope.document(), 'previous': prior, 'values': dict(prior, friction_threshold_highway=.005), + 'route_sha256s': ['c' * 64], 'source_start_ns': 1, 'source_end_ns': 2, 'completed_wall_ns': 3, + 'analysis_sha256': 'd' * 64, 'sequence': 1, 'state': 'ready_for_next_drive'} + altered = dict(row, previous=dict(prior, ff_gain_left=.004)) + locked = dict(row, values=dict(row['values'], center_taper_max=.011)) + assert not _save_route_trial(params, cp, altered, expected=None, authorized=lambda: True) + assert not _save_route_trial(params, cp, locked, expected=None, authorized=lambda: True) + assert not _save_route_trial(params, cp, row, expected=None, authorized=lambda: False) + assert read_saved(params, KEY, MAX_BYTES) == (None, True) + assert _save_route_trial(params, cp, row, expected=None, authorized=lambda: True) + assert startup_row(params, scope)[0] == row + stored, readable = read_saved(params, KEY, MAX_BYTES) + assert readable and RouteStorage(params).rollback(scope=scope, expected=stored, authorized=lambda: True) + assert startup_row(params, scope)[0]['values'] == prior + assert read_saved(params, DOCUMENT_KEY, 16384) == (original, True) diff --git a/openpilot/starpilot/flm/tests/test_offroad_nonemitted_controls.py b/openpilot/starpilot/flm/tests/test_offroad_nonemitted_controls.py index ef3040b56f..d4cbd266ec 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_nonemitted_controls.py +++ b/openpilot/starpilot/flm/tests/test_offroad_nonemitted_controls.py @@ -173,3 +173,25 @@ def test_sparse_numerical_credit_never_replaces_real_native_emissions(native_his assert not result['qualified'] and result['reason'] == 'insufficient_original_native_delivery' unchanged = check_original_native(cp, controls, chain, commands, require_change=True) assert not unchanged['qualified'], 'A complete unchanged history cannot earn a changed tune' + + +def test_native_replay_preserves_a_required_inhibited_emission(native_history): + cp, controls, chain, commands = native_history + stamp = chain[0].control_ns + altered = tuple((ns, before, after + .004 if ns == stamp else after) for ns, before, after in commands) + changed = check_original_native(cp, controls, chain, altered) + assert changed['qualified'] and changed['candidate_changed_emissions'] > 0 + refused = check_original_native(cp, controls, chain, altered, unchanged_inhibited=(stamp,)) + assert not refused['qualified'] and refused['reason'] == 'candidate_changed_inhibited_native_output' + unchanged = check_original_native(cp, controls, chain, commands, require_change=False, unchanged_inhibited=(stamp,)) + assert unchanged['qualified'] and unchanged['candidate_changed_emissions'] == 0 + + +def test_replicated_curve_quieting_precedes_generic_gain_with_more_windows(): + from openpilot.starpilot.flm.offroad_worker import _candidate_order + + group = {'original_context_sha256': 'a' * 64} + gain = group, {'whole_windows': 41, 'cohort': '2:right:steady'}, {} + quieting = group, {'whole_windows': 15, 'cohort': '2:right:steady'}, {'notchy_curve_quieting': True} + assert _candidate_order(quieting) < _candidate_order(gain) + assert _candidate_order((*quieting[:2], {'notchy_curve_quieting': False})) > _candidate_order(gain) diff --git a/prebuilt.json b/prebuilt.json index 888dc3b13d..708085f7d0 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "c260d1d070482207be9ff251611e2d869e5ed8673f90e7355df4cacbec18641e", "schema_version": 1} +{"protected_inventory_sha256": "fc856d30347f32f773ce6ff3230dcc19449de8b99248cd1efc92bbfe67f709d6", "schema_version": 1}