Restore replay execution and align CI fixtures with current settings

This commit is contained in:
firestar5683
2026-11-27 23:56:18 -06:00
parent df7d67c39f
commit b7953cf4a0
17 changed files with 61 additions and 51 deletions
View File
@@ -94,7 +94,7 @@ class TestActualSettingsOwners(unittest.TestCase):
self.assertNotIn("setting_data_ShareUsageStats", large)
self.assertNotIn("default_data_ShareUsageStats", large)
self.assertTrue(large["setting_lane_LaneCentering"])
self.assertTrue(large["default_lane_LaneCentering"])
self.assertFalse(large["default_lane_LaneCentering"])
self.assertFalse(compact["setting_appearance_StockConfidenceBallWidget"])
self.assertTrue(compact["default_appearance_StockConfidenceBallWidget"])
self.assertEqual(large["default_display_ScreenTimeoutOnroad"], 10.0)
@@ -1,4 +1,6 @@
"""Cruise MAIN assigned to Adopt speed limit is not also the Hyundai physical lateral toggle."""
from pathlib import Path
import pytest
from opendbc.car import structs
from openpilot.starpilot.aol.intent import AolCardIntent, AolSettings, read_settings
@@ -54,8 +56,9 @@ def test_main_toggle_is_unchanged_without_independent_cruise_buttons():
class SavedParams:
def __init__(self, values):
def __init__(self, values, root=Path("/nonexistent")):
self.values = values
self.root = root
def get(self, key, return_default=False):
return self.values.get(key)
@@ -64,7 +67,7 @@ class SavedParams:
return self.values.get(key) == b'1'
def get_param_path(self, key):
return f'/nonexistent/{key}'
return str(self.root / key)
@pytest.mark.parametrize('lkas,main,main_wheel', [(b'0', b'10', True), (b'0', b'9', False), (b'10', b'0', False), (b'0', b'8', False)])
@@ -117,9 +120,8 @@ def test_mixed_palisade_lkas_bookmark_owns_only_the_wheel_action(tmp_path, topol
cp.alphaLongitudinalAvailable = True
cp.safetyConfigs[0].safetyParam |= 4
assert (qualified_alpha if alpha_long else qualified)(cp, marked_only=True)
saved = SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': str(action).encode(), 'MainCruiseButtonControl': b'0'})
saved = SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': str(action).encode(), 'MainCruiseButtonControl': b'0'}, tmp_path)
(tmp_path/'LKASButtonControl').write_bytes(saved.get('LKASButtonControl'))
saved.get_param_path = lambda key: str(tmp_path/key)
owner = create_intent(cp, read_settings(saved))
cs = structs.CarState(canValid=True, gearShifter='drive', cruiseState={'available': True, 'enabled': True})
now = 3_000_000_000
@@ -189,8 +191,7 @@ def test_lkas_pause_mapping_only_pauses_the_selected_axis(action):
def test_live_lkas_remap_does_not_also_toggle_default_aol(tmp_path, saved_action):
from openpilot.starpilot.aol.intent import claim_remapped_lkas
saved = SavedParams({'AlwaysOnLateral': b'1'})
saved.get_param_path = lambda key: str(tmp_path/key)
saved = SavedParams({'AlwaysOnLateral': b'1'}, tmp_path)
settings = read_settings(saved)
owner = AolCardIntent(settings, explicit_latch=True)
cs = armed(owner)
@@ -1,5 +1,4 @@
from dataclasses import replace
from types import SimpleNamespace
import pytest
@@ -11,6 +10,7 @@ from openpilot.selfdrive.selfdrived.events import Events
from openpilot.selfdrive.selfdrived.selfdrived import EventName, SelfdriveD
from openpilot.selfdrive.selfdrived.state import StateMachine
from openpilot.starpilot.aol.intent import AolSettings
from openpilot.starpilot.aol.intent_companion import IntentCompanion
from openpilot.starpilot.aol.runtime import AxisDecision, current_native
from openpilot.starpilot.aol.tests.test_gm_held_native import Peers
from openpilot.starpilot.aol.wire import IntentState, PandaSlot, SafetyState, encode_safety
@@ -45,7 +45,7 @@ def native_health(cp, stamp, session):
@pytest.mark.parametrize('fault', ('none', 'assigned', 'missing_edge', 'stale', 'native_denial', 'native_fault',
'hard_fault', 'main_off', 'other_user', 'no_prior_lat'))
def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault, monkeypatch):
# Route 5e: the prior axis expires during processing, 28 ms after a fresh physical Cancel.
edge = 10_000_000_000
now = edge + 28_173_000
@@ -58,7 +58,8 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
sd.aol_car_state_log_ns = source = edge - (3_000_000 if fault == 'stale' else 0)
sd.conditional_car_state_valid = True
sd.aol_last_intent = IntentState('mqb-card', 2, source, source, source + 200_000_000, True, False, False, True, True)
sd.aol_intent_companion = SimpleNamespace(integrity_epoch=44)
sd.aol_intent_companion = IntentCompanion(None)
sd.aol_intent_companion.integrity_epoch = 44
sd.aol_published_input_proof = (sd.aol_session_id, edge - 11_623_000, edge - 5_618_000,
edge + 24_382_000, 'mqb-card', 44, True, True, fault != 'no_prior_lat', True)
sd.aol_authority_lost = sd.enabled = sd.active = False
@@ -75,7 +76,8 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
if fault != 'missing_edge':
cs.buttonEvents = [structs.CarState.ButtonEvent(type='cancel', pressed=True)]
slot, native, wire, panda = native_health(cp, edge - 29_808_000, sd.aol_session_id)
sd.sm = Peers([wire.as_reader(), panda.as_reader()])
peers = Peers([wire.as_reader(), panda.as_reader()])
monkeypatch.setattr(sd, "sm", peers, raising=False)
sd.aol_published_input_native = current_native(sd.sm, cp, now_ns=now, axis_session_id=sd.aol_session_id)
assert sd.aol_published_input_native is not None
if fault in ('native_denial', 'native_fault'):
@@ -84,7 +86,7 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
else:
native = replace(native, pandaInventory=(replace(slot, safetyRxChecksInvalid=True),))
wire.aolSafetyWire = encode_safety(native)
sd.sm.messages['aolSafetyWire'] = wire.as_reader()
peers.messages['aolSafetyWire'] = wire.as_reader()
result = sd._expire_axis_continuity(cs, now)
assert result == (fault != 'none')
assert sd.aol_axis_decision.lateral_active == (fault == 'none')
@@ -94,7 +96,6 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
@pytest.mark.parametrize('fault', ('none', 'unverified', 'mutated', 'session', 'revoked', 'old', 'hard_fault', 'native_denial'))
def test_mqb_armed_source_gap_handles_split_recovery(fault):
from openpilot.starpilot.aol.intent_companion import IntentCompanion
from openpilot.starpilot.aol.transport_pause import AvailabilityPause, _healthy_transport_native
from openpilot.starpilot.aol.wire import encode_intent
@@ -1,7 +1,6 @@
"""Shared declared-context HTTP fixture; no physical vehicle evidence."""
from pathlib import Path
from types import SimpleNamespace
import http.client
import json
import tempfile
@@ -30,12 +29,10 @@ class SettingsHttpFixture(unittest.TestCase):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.params = Params(temporary.name)
native = ToyotaInterface.get_non_essential_params(ToyotaCar.TOYOTA_COROLLA_TSS2)
cp = SimpleNamespace(carFingerprint="TOYOTA_COROLLA_TSS2", openpilotLongitudinalControl=True,
pcmCruise=False, notCar=False, dashcamOnly=False, passive=False,
brand="toyota", steerControlType=native.steerControlType, carVin="",
lateralTuning=native.lateralTuning, minSteerSpeed=native.minSteerSpeed, safetyConfigs=native.safetyConfigs,
transmissionType=car.CarParams.TransmissionType.automatic)
cp = ToyotaInterface.get_non_essential_params(ToyotaCar.TOYOTA_COROLLA_TSS2)
cp.openpilotLongitudinalControl = True
cp.pcmCruise = False
cp.transmissionType = car.CarParams.TransmissionType.automatic
self.context = MutableContext(cp)
self.gateway = SettingsGateway(self.params, self.context)
self.access = GalaxyAccessOwner(Path(temporary.name) / "access")
@@ -274,8 +274,8 @@ class SettingsGatewayTest(unittest.TestCase):
self.assertNotEqual(first["view"], second["view"])
self.assertEqual(first["rows"], second["rows"])
first_row = first["rows"][0]
self.assertEqual(first_row["value"], "On")
self.params.put_bool("LaneCentering", True, block=True)
self.assertEqual(first_row["value"], "Off")
self.params.put_bool("LaneCentering", False, block=True)
row = self.page("lane")["rows"][0]
self.assertEqual(first_row["value"], row["value"])
self.assertNotEqual(first_row["revision"], row["revision"])
@@ -1,4 +1,5 @@
from types import SimpleNamespace
from typing import cast
import pytest
@@ -25,7 +26,7 @@ def test_invalid_and_unauthorized_requests_do_not_write(tmp_path):
params = params_at(tmp_path)
for mode in ("developer", "", True, None, {}):
with pytest.raises(ValueError):
save_mode(params, mode, authorized=lambda: True)
save_mode(params, cast(str, mode), authorized=lambda: True)
with pytest.raises(RuntimeError):
save_mode(params, "advanced", authorized=lambda: False)
assert not (tmp_path / "d" / KEY).exists()
@@ -23,13 +23,11 @@ class TestBoltVehicleModel(unittest.TestCase):
CAR.CHEVROLET_BOLT_ACC_2022_2023_PEDAL, CAR.CHEVROLET_BOLT_EUV)
for identity in identities:
for mode in ('starpilot', 'standard'):
if identity == CAR.CHEVROLET_BOLT_EUV and mode == 'starpilot':
continue
with self.subTest(identity=identity, mode=mode), OpenpilotPrefix(), patch.dict(os.environ, {'SIMULATION': '1'}):
cp = params(identity, alpha=True)
settings = Params()
settings.put('CarParams', cp.to_bytes(), block=True)
if mode == 'standard' and identity != CAR.CHEVROLET_BOLT_EUV:
if mode == 'standard':
document = {'version': 1, 'vehicles': {str(identity): {'brand': 'gm', 'mode': 'standard'}}}
settings.put('LateralControllerSelection', document, block=True)
controls = Controls()
@@ -85,7 +85,8 @@ class HKGHighwayFrictionTests(unittest.TestCase):
def test_kona_se_uses_highway_friction_with_ordinary_torque_controller(self):
cp, controller = controller_for(CAR.HYUNDAI_KONA_EV_2023_NON_SCC, dashcamOnly=False)
self.assertEqual(controller.controller_mode, ControllerMode.STANDARD)
self.assertEqual(controller.controller_mode, ControllerMode.STARPILOT)
self.assertEqual(controller.controller_policy, "generic")
self.assertFalse(cp.flags & HyundaiFlags.CANFD)
cs = SimpleNamespace(vEgo=65 * CV.MPH_TO_MS, steeringPressed=False)
self.assertLess(abs(controller.friction(.1, 0., .2, cs, .1)),
@@ -100,12 +100,12 @@ def test_elantra_fast_takeoffs_settle_only_during_clear_cruise(case, monkeypatch
sm['modelV2'].action.desiredAcceleration = 1.
sm['radarState'].leadOne.present = case == 'lead one'
sm['radarState'].leadTwo.present = case == 'lead two'
kwargs = {'faster_lead_takeoff': case != 'faster disabled', 'now_ns': now, 'drive_id': DRIVE,
'cruise_ceiling': CruiseCeiling(19.9, ACTIVE) if case == 'speed ceiling' else None}
candidate.update(sm, **kwargs)
faster = case != 'faster disabled'
ceiling = CruiseCeiling(19.9, ACTIVE) if case == 'speed ceiling' else None
candidate.update(sm, faster_lead_takeoff=faster, now_ns=now, drive_id=DRIVE, cruise_ceiling=ceiling)
with monkeypatch.context() as restore:
restore.setattr(lp, 'get_cruise_accel', previous)
original.update(sm, **kwargs)
original.update(sm, faster_lead_takeoff=faster, now_ns=now, drive_id=DRIVE, cruise_ceiling=ceiling)
assert candidate.mpc.solution_status == original.mpc.solution_status == 0
assert candidate.output_should_stop == original.output_should_stop
if case != 'settling':
@@ -1,7 +1,7 @@
"""Synthetic serialized cabin planes and fail-closed observation lifecycle."""
from pathlib import Path
from unittest.mock import patch
from unittest.mock import Mock, patch
from openpilot.common.params import Params
from openpilot.starpilot.spot_monitor.inference import VASMInference
@@ -82,7 +82,7 @@ class Model(VASMInference):
def test_diagnostics_share_a_budget_and_summarize_healthy_operation():
runtime = VASMRuntime(None, None, Client, lambda _event: None)
runtime = VASMRuntime(Mock(spec=Params), None, Client, lambda _event: None)
with patch("openpilot.starpilot.spot_monitor.runtime.cloudlog.event") as log:
runtime._diagnostic(1_000_000_000, "unavailable", "model_load", detail="unsupported model")
for second in range(2, 31):
+2 -2
View File
@@ -290,12 +290,12 @@ class PathMarkers:
if not self._paint:
return
stop = self._stop_point
if stop.box is not None:
if stop.box is not None and stop.strip is not None:
alpha = stop.fade_filter.x if stop.committed else stop.fade_filter.x * STOP_OPACITY
base = COLOR_FORCE_STOP if stop.committed else rl.WHITE
draw_polygon(self._rect, stop.strip, rl.Color(base.r, base.g, base.b, int(255 * alpha)))
lead = self._lead
if lead.box is None:
if lead.box is None or lead.strip is None:
return
alpha = lead.fade_filter.x
color = lead_marker_color(self.road_style, alpha)
@@ -75,7 +75,7 @@ class TestControllerFeature(unittest.TestCase):
self.cp = interfaces[HONDA.HONDA_FIT_4G].get_non_essential_params(HONDA.HONDA_FIT_4G)
self.assertEqual(self.cp.lateralTuning.which(), 'torque')
self.assertEqual(self.require_row().choices, ('Stock Controller', 'StarPilot Controller'))
self.assertEqual(self.require_row().value, 'Stock Controller')
self.assertEqual(self.require_row().value, 'StarPilot Controller')
learning = self.require_row('ForceAutoTuneOff')
self.assertEqual(learning.label, 'Use StarPilot Auto Learn')
self.assertEqual(learning.value, 'On')
@@ -398,17 +398,17 @@ class FeatureSettingsOwnerTests(unittest.TestCase):
self.assertTrue(self.owner.apply(required_change(self._row("torque", "TurnAssist"))))
self.assertTrue(VehicleStartupPreferences.read(self.params, enabled=True).turn_assist)
def test_lane_centering_default_and_saved_off_are_distinct(self):
def test_lane_centering_default_and_saved_on_are_distinct(self):
self.assertIsNone(self.params.get("LaneCentering"))
row = self._row("lane", "LaneCentering")
self.assertEqual(row.value, "On")
self.assertEqual(row.default_value, "On")
self.assertIsNone(self.params.get("LaneCentering"))
self.params.put_bool("LaneCentering", False, block=True)
row = self._row("lane", "LaneCentering")
self.assertEqual(row.value, "Off")
self.assertEqual(row.default_value, "On")
self.assertFalse(self.params.get_bool("LaneCentering"))
self.assertEqual(row.default_value, "Off")
self.assertIsNone(self.params.get("LaneCentering"))
self.params.put_bool("LaneCentering", True, block=True)
row = self._row("lane", "LaneCentering")
self.assertEqual(row.value, "On")
self.assertEqual(row.default_value, "Off")
self.assertTrue(self.params.get_bool("LaneCentering"))
def test_live_lane_owner_maps_only_explicit_keys(self):
self.params.put_bool("LaneCentering", False, block=True)
+3 -3
View File
@@ -159,7 +159,7 @@ class TestModelManager(unittest.TestCase):
self.assertTrue(model_action_allowed({**self.data, "activeBigModel": ""}, "delete", self.big))
self.assertFalse(model_action_allowed({**self.data, "capabilities": {}}, "active", self.small, "small"))
moving = {**self.data, "isOnroad": True, "downloading": False,
"capabilities": self.data["capabilities"] | {"download": False, "downloadAll": False, "refresh": False}}
"capabilities": cast(dict, self.data["capabilities"]) | {"download": False, "downloadAll": False, "refresh": False}}
self.assertTrue(model_action_allowed(moving, "active", self.small, "small"))
self.assertTrue(model_action_allowed(moving, "active", self.big, "big"))
self.assertFalse(model_action_allowed(moving | {"jetlinkBig": True}, "active", self.big, "big"))
@@ -198,7 +198,7 @@ class TestModelManager(unittest.TestCase):
("Delete", "delete", "big", ""))
self.assertEqual(model_row_intent(self.data, "models:pick:big", "model:", 0), ("Use", "active", "", "big"))
self.assertEqual(catalog.rows[0].key, "models:downloads")
self.assertEqual(catalog.rows[0].actions, (("Refresh", False), ("Get All", True))) # the fixture grants no refresh capability
self.assertEqual(catalog.rows[0].actions, (("Refresh", True), ("Get All", True)))
self.assertEqual(model_row_intent(self.data, "models:catalog", "models:downloads", 1), ("Get All", "download_all", "", ""))
self.assertEqual(model_row_intent(self.data | {"downloading": True}, "models:catalog", "models:downloads", 0),
("Cancel", "cancel", "", ""))
@@ -326,7 +326,7 @@ class TestModelManager(unittest.TestCase):
session.model_manager_action.assert_not_called()
callback = confirm.call_args.args[2]
session.model_manager_snapshot.return_value = {**self.data, "isOnroad": True,
"capabilities": self.data["capabilities"] | {"download": False}}
"capabilities": cast(dict, self.data["capabilities"]) | {"download": False}}
callback()
session.model_manager_action.assert_not_called()
@@ -2,6 +2,7 @@
from collections import defaultdict
from dataclasses import replace
from types import SimpleNamespace as NS
from typing import cast
from unittest.mock import Mock
import numpy as np
@@ -113,10 +114,13 @@ def test_e2e_lead_labels_and_stale_speed():
sm.valid['radarState'] = False
sm['modelV2'].leadsV3 = [NS(prob=.9, x=[30.], y=[-.2], v=[12.]), NS(prob=.9, x=[60.], y=[0.], v=[12.])]
sm['carState'].vEgo = 14.
distance, info = renderer._lead_source(sm)
result = renderer._lead_source(sm)
assert result is not None
distance, info = result
assert distance == 30. and info.dRel == 30. - pm.RADAR_TO_CAMERA and info.vRel == -2.
sm.valid['carState'] = False
assert renderer._lead_source(sm)[1].vRel is None
result = renderer._lead_source(sm)
assert result is not None and result[1].vRel is None
@pytest.mark.parametrize('field,value', [('dRel', float('nan')), ('yRel', float('inf')), ('vRel', 'bad'), ('dRel', -1.)])
@@ -132,6 +136,7 @@ def test_lead_line_is_a_painted_strip_that_stays_thin_on_screen_and_never_spans_
renderer = Renderer()
run(renderer, messages(lead(d)))
strip, box = renderer._lead.strip, renderer._lead.box
assert strip is not None and box is not None
assert 4 - 1e-3 <= box.height <= 16 + 1e-3, 'perspective depth, clamped so it never thins out or becomes a block'
assert box.width <= 0.3 * W + 1e-3
assert box.y + box.height <= H - 16 + 1e-3
@@ -144,12 +149,15 @@ def test_strips_wind_like_the_path_ribbon_so_raylib_does_not_cull_them():
renderer = Renderer(curve=.002)
renderer._clip_region = rl.Rectangle(-500, -500, W + 1000, H + 1000)
path = renderer._path.raw_points
ribbon = large_model.ModelRenderer._map_lines_to_polygons(renderer, [path], [.9], renderer._path_offset_z, len(path) - 1, 100.)[0]
ribbon = large_model.ModelRenderer._map_lines_to_polygons(
cast(large_model.ModelRenderer, renderer), [path], [.9], renderer._path_offset_z, len(path) - 1, 100.,
)[0]
run(renderer, messages(lead(25.)))
def winding(points):
a, b, c = triangulate(points)[:3]
return np.sign((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))
assert renderer._lead.strip is not None
assert winding(renderer._lead.strip) == winding(ribbon) != 0
@@ -190,6 +198,7 @@ def test_line_stays_on_the_path_while_the_lead_drifts_in_its_lane():
for y in (-.8, 0., .8, -1.5):
sm['radarState'].leadOne = lead(25., y=y)
run(renderer, sm)
assert renderer._lead.strip is not None
centers.append(float(renderer._lead.strip[[1, 2], 0].mean()))
d = 25. + pm.RADAR_TO_CAMERA
assert len(set(centers)) == 1, 'the car drifting in its lane never moves the line sideways'
@@ -254,6 +263,7 @@ def test_stop_line_shows_for_e2e_plans_and_turns_red_when_committed():
renderer = Renderer()
box = stop_box(renderer, messages(source=pm.E2E, stop_m=28.))
strip = renderer._stop_point.strip
assert strip is not None
assert box is not None and 4 - 1e-3 <= box.height <= 16 + 1e-3 and renderer._stop_point.committed is False
assert abs(strip[2, 0] - strip[1, 0]) == pytest.approx(3.6 * F / (renderer._stop_point.d + pm.RADAR_TO_CAMERA), rel=1e-2), 'spans the lane'
stop_box(renderer, messages(source=pm.E2E, stop_m=28.), markers=pm.PathMarkerInput(indicator=True, stop_committed=True), frames=1)
@@ -296,6 +306,7 @@ def test_stop_line_is_centered_on_the_path_on_a_curve():
stop_box(renderer, messages(source=pm.E2E, stop_m=28.))
d = renderer._stop_point.d + pm.RADAR_TO_CAMERA
on_path = renderer.screen_x(d, .004 * d * d)
assert renderer._stop_point.strip is not None
assert float(renderer._stop_point.strip[[1, 2], 0].mean()) == pytest.approx(on_path, abs=2)
assert abs(on_path - CX) > 100, 'upstream centered it on the straight-ahead line instead'
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "fcfca2f5a163409f010d2f0ae2111487ec19f8856cb8036b8f75265758b3b9e1", "schema_version": 1}
{"protected_inventory_sha256": "310ca436c65d7d0a93b9efa2ffa555196be020ed89a934987eeb244ae83008ec", "schema_version": 1}