diff --git a/openpilot/starpilot/flm/offroad_observed.py b/openpilot/starpilot/flm/offroad_observed.py index fe01fc7a5c..e527b77edb 100644 --- a/openpilot/starpilot/flm/offroad_observed.py +++ b/openpilot/starpilot/flm/offroad_observed.py @@ -1,6 +1,7 @@ """Source-bound provisional symptoms; these spans never supply native roles.""" from bisect import bisect_left, bisect_right import hashlib +from statistics import median from openpilot.starpilot.flm.offroad_surface import REVISION, ROUTE_NAMES @@ -62,3 +63,46 @@ def merge_sources(sources): name: value for name, value in group['coordinate_baselines'].items() if source['coordinate_baselines'].get(name) == value } return list(groups.values()) + + +def curve_candidates(profiles, previous): + """Keep the original policy's curve steps only at observed speed points.""" + from openpilot.starpilot.flm.offroad_surface import CURVE_NAMES, CURVE_SPEEDS, route_bounds + from openpilot.starpilot.flm.offroad_store import MAX_ROUTE_STEP + + votes, symptoms = {}, {} + for proposed, observations in profiles: + if proposed is None: + continue + for index, name in enumerate(CURVE_NAMES): + delta = proposed['values'][name] - previous[name] + if not delta: + continue + for window, observation in observations: + bucket, speed = observation['bucket'], observation['speed_mps'] + if (delta > 0 and bucket not in ('center_chatter', 'notchy_mid_curve') + or delta < 0 and bucket != 'low_speed_unwillingness'): + continue + supported = ( + index == 0 and speed < CURVE_SPEEDS[1] or index == 4 and speed > CURVE_SPEEDS[3] + or 0 < index < 4 and CURVE_SPEEDS[index - 1] < speed < CURVE_SPEEDS[index + 1] + ) + if supported: + votes.setdefault(name, {}).setdefault(window, []).append(delta) + symptoms.setdefault(name, set()).add((bucket, observation['direction'])) + candidates = [] + for name, windows in votes.items(): + steps = [value for values in windows.values() for value in values] + if len(windows) < 3 or min(steps) * max(steps) <= 0: + continue + delta = median(median(values) for values in windows.values()) + target = round(previous[name] + delta, 12) + low, high = route_bounds(name) + if not low <= target <= high or not 1e-12 < abs(target - previous[name]) <= MAX_ROUTE_STEP + 1e-12: + continue + candidates.append({ + 'parameter': 'stable:' + name, 'delta': target - previous[name], 'values': dict(previous, **{name: target}), + 'original_windows': sorted(windows), 'symptoms': [list(row) for row in sorted(symptoms[name])], + 'coordinate_policy': 'observed_original_threshold_curve_v1', 'automatic_application_allowed': False, + }) + return candidates diff --git a/openpilot/starpilot/flm/offroad_stable_bridge.py b/openpilot/starpilot/flm/offroad_stable_bridge.py index 1989ed416a..63a5fcb2ca 100644 --- a/openpilot/starpilot/flm/offroad_stable_bridge.py +++ b/openpilot/starpilot/flm/offroad_stable_bridge.py @@ -362,6 +362,7 @@ class StableRouteSelector: def observe(self, windows): """Pool original symptoms across maneuvers without granting native fit credit.""" from openpilot.starpilot.flm.offroad_coordinate_policy import coordinate_candidates + from openpilot.starpilot.flm.offroad_observed import curve_candidates if not 1 <= len(windows) <= 4096 or len(set(windows)) != len(windows) or any(key not in self.spans for key in windows): raise ValueError('Bounded unique original observations required') @@ -372,15 +373,19 @@ class StableRouteSelector: available = [key for key in ordered if self.rows.get(key) is not None] available_ids = set(available) observations = [] - for start in range(0, len(available), 12): + profiles = [] + # Four seconds of shared original context preserve the existing 3.6 s + # curve detector at batch edges. Votes still count each source window once. + for start in range(0, len(available), 10): if not self.permitted(): raise ValueError('Parked observation analysis cancelled') - _, proof = self.profile(tuple(available[start:start + 12]), 'observed_maneuvers', observations_only=True) + mapped, proof = self.profile(tuple(available[start:start + 12]), 'observed_maneuvers', observations_only=True) observations.extend(proof['coordinate_observations']) + profiles.append((mapped, proof['coordinate_observations'])) return { 'original_windows': ordered, 'unavailable_original_windows': [key for key in ordered if key not in available_ids], - 'coordinate_candidates': coordinate_candidates(observations, self.previous), + 'coordinate_candidates': coordinate_candidates(observations, self.previous) + curve_candidates(profiles, self.previous), 'automatic_application_allowed': False, } diff --git a/openpilot/starpilot/flm/tests/test_observed_maneuvers.py b/openpilot/starpilot/flm/tests/test_observed_maneuvers.py index ac84976cae..82075ad2a2 100644 --- a/openpilot/starpilot/flm/tests/test_observed_maneuvers.py +++ b/openpilot/starpilot/flm/tests/test_observed_maneuvers.py @@ -9,11 +9,11 @@ from openpilot.starpilot.flm.offroad_processor import CompletedAssessment, _asse from openpilot.starpilot.flm.offroad_stable_bridge import StableRouteSelector from openpilot.starpilot.flm.offroad_stable_policy import FLMSample from openpilot.starpilot.flm.tests.test_offroad_backend import scope, values -from openpilot.starpilot.flm.tests.test_offroad_coordinate_policy import TestCrossDriveEvidence as CrossDriveFixture +from openpilot.starpilot.flm.tests import test_offroad_coordinate_policy as fixtures def mixed_drive(number): - collected, inventory = CrossDriveFixture.inputs(number) + collected, inventory = fixtures.TestCrossDriveEvidence.inputs(number) for key, windows in collected.windows.items(): changed = [] for original in windows: @@ -110,7 +110,7 @@ def test_partial_metadata_preserves_only_observed_consistent_coordinate_baseline from openpilot.starpilot.flm.offroad_control_metadata import read_control_metadata from openpilot.starpilot.flm.tests.test_configured_route_recording import control, wire - inputs, _ = CrossDriveFixture.inputs(1) + inputs, _ = fixtures.TestCrossDriveEvidence.inputs(1) context, windows = next(iter(inputs.windows.items())) metadata = inputs.context_metadata[context] template = read_control_metadata(wire(control(legacy=True))) @@ -141,3 +141,39 @@ def test_partial_metadata_preserves_only_observed_consistent_coordinate_baseline assert not observed_sources(windows[:1], timeline[30:], original), 'Missing source bookends remain unavailable' with pytest.raises(ValueError, match='counted twice'): merge_sources([source, source]) + + +def test_notchy_curve_advice_reaches_only_speed_points_with_three_original_windows(): + import math + + reader, ids = selector(3) + for key in ids: + original = reader.rows[key] + assert original is not None + # Six source seconds retain the classifier's original edge exclusions + # and long notchy-curve window; no sample-count threshold is shortened. + reader.spans[key]['end_ns'] = 7 * 10**9 + reader.rows[key] = [replace(original[0], t=1 + tick / 100, desired_la=.8, desired_jerk=0., + actual_la=.8 + .16 * math.sin(4 * math.pi * (1 + tick / 100)), + error=.16 * math.sin(4 * math.pi * (1 + tick / 100))) for tick in range(601)] + proof = reader.observe(ids) + curve = [candidate for candidate in proof['coordinate_candidates'] if 'friction_threshold_' in candidate['parameter']] + assert {candidate['parameter'] for candidate in curve} == {'stable:friction_threshold_fast', 'stable:friction_threshold_highway'} + assert all(len(candidate['original_windows']) == 3 and 0 < candidate['delta'] <= .01 for candidate in curve) + assert not proof['automatic_application_allowed'] + assert not [candidate for candidate in reader.observe(ids[:2])['coordinate_candidates'] if 'friction_threshold_' in candidate['parameter']] + + +def test_many_events_in_one_window_and_conflicting_curve_steps_do_not_inflate_support(): + from openpilot.starpilot.flm.offroad_observed import curve_candidates + + previous = values() + proposed = {'values': dict(previous, friction_threshold_highway=.005)} + observation = {'bucket': 'notchy_mid_curve', 'direction': 'left', 'speed_mps': 30., 'severity': 1.} + assert not curve_candidates([(proposed, [('one-window', observation)] * 30)], previous) + positive = [(str(i), observation) for i in range(3)] + rows = curve_candidates([(proposed, positive)], previous) + assert len(rows) == 1 and len(rows[0]['original_windows']) == 3 + reduction = {'values': dict(previous, friction_threshold_highway=-.005)} + negative = [(str(i + 3), dict(observation, bucket='low_speed_unwillingness')) for i in range(3)] + assert not curve_candidates([(proposed, positive), (reduction, negative)], previous) diff --git a/prebuilt.json b/prebuilt.json index 4b3fa8347e..75af503e7b 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "074cb75f6c811570fcb456c0995f40e514f0b16611f1aad3e74ca8337529b42b", "schema_version": 1} +{"protected_inventory_sha256": "2fa9d14e5695587fb58d6e2094c031d23a2bb9f8ced580c7c957ae8095f7b6db", "schema_version": 1}