From 82daba5053dea2a15d8e7eed7c57dfd408f18119 Mon Sep 17 00:00:00 2001 From: firestar5683 <168790843+firestar5683@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:14:26 -0600 Subject: [PATCH] Fix Ford AOL receipt ordering and scope Volkswagen lookup --- openpilot/selfdrive/car/card.py | 3 +- .../aol/tests/test_ford_cancel_raw_health.py | 225 ++++++++++++++++++ .../aol/tests/test_ford_first_grant_join.py | 80 +++++++ openpilot/starpilot/aol/transport_pause.py | 37 ++- .../tests/test_card_initial_wait_brand.py | 28 +++ 5 files changed, 370 insertions(+), 3 deletions(-) create mode 100644 openpilot/starpilot/aol/tests/test_ford_cancel_raw_health.py create mode 100644 openpilot/starpilot/aol/tests/test_ford_first_grant_join.py create mode 100644 openpilot/starpilot/tests/test_card_initial_wait_brand.py diff --git a/openpilot/selfdrive/car/card.py b/openpilot/selfdrive/car/card.py index 44c7ec0070..d3fe1b7039 100644 --- a/openpilot/selfdrive/car/card.py +++ b/openpilot/selfdrive/car/card.py @@ -659,7 +659,8 @@ class Car: current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=self.aol_axis_session()), self.aol_transport_feedback, self.aol_card_intent, now_ns=now_ns, producer=self.slc_producer_session)) from openpilot.starpilot.car.volkswagen.aol import awaiting_initial_request as volkswagen_initial_request - volkswagen_initial_wait = volkswagen_initial_request(self.CP, CS, self.sm, + volkswagen_initial_wait = self.CP.brand == 'volkswagen' and volkswagen_initial_request( + self.CP, CS, self.sm, current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=self.aol_axis_session()), self.aol_transport_feedback, self.aol_card_intent, now_ns=now_ns, producer=getattr(self, 'slc_producer_session', '')) diff --git a/openpilot/starpilot/aol/tests/test_ford_cancel_raw_health.py b/openpilot/starpilot/aol/tests/test_ford_cancel_raw_health.py new file mode 100644 index 0000000000..cc1e71cfbe --- /dev/null +++ b/openpilot/starpilot/aol/tests/test_ford_cancel_raw_health.py @@ -0,0 +1,225 @@ +"""Ford FULL->LAT Cancel receipt ordering; controlled host/native wire regression.""" +from dataclasses import replace +from types import SimpleNamespace + +import pytest +from opendbc.car import structs +from openpilot.cereal import log +from openpilot.starpilot.aol.runtime import decide_axes +from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback +from openpilot.starpilot.aol.wire import PandaSlot, SafetyState, encode_safety + +NOW = 10_000_000_000 + + +class Peers: + def __init__(self, messages): + self.messages = {m.which(): m for m in messages} + self.logMonoTime = {k: m.logMonoTime for k, m in self.messages.items()} + self.seen = dict.fromkeys(self.messages, True) + self.valid = dict(self.seen) + self.alive = dict(self.seen) + + def __getitem__(self, name): + return getattr(self.messages[name], name) + + +def message(name, stamp, size=None): + m = log.Event.new_message(logMonoTime=stamp, valid=True) + m.init(name) if size is None else m.init(name, size) + return m + + +def sample(cp, stamp, sequence, native, *, combined, event=True, raw_controls=False): + w = message('aolSafetyWire', native.observedMonoTime, 0) + w.aolSafetyWire = encode_safety(native) + a = message('aolAxisState', stamp) + a.aolAxisState = {'sessionId': 'axis', 'faultSessionId': 'axis', 'sequence': sequence, 'qualified': True, + 'faultReason': 'none', 'observedMonoTime': stamp, 'sourceCarStateMonoTime': stamp, 'validUntilMonoTime': stamp+30_000_000, + 'intentProducerSessionId': 'producer', 'intentIntegrityEpoch': 1, 'faultEventMonoTime': stamp, + 'desiredLateral': True, 'lateralActive': True, 'desiredLongitudinal': combined, 'longitudinalActive': combined, + 'nativeAcknowledged': True, 'mode': 'combined' if combined else 'lateralOnly'} + p = message('pandaStates', stamp, 1) + p.pandaStates[0] = {'safetyModel': 'ford', 'safetyParam': 16387, 'alternativeExperience': 32, 'controlsAllowed': raw_controls} + e = message('onroadEvents', stamp, int(event)) + if event: + e.onroadEvents[0] = {'name': 'pcmDisable', 'userDisable': True} + return Peers([w.as_reader(), a.as_reader(), p.as_reader(), e.as_reader()]) + + +def fixture(): + cp = structs.CarParams(brand='ford', carFingerprint='FORD_MUSTANG_MACH_E_MK1', flags=3, + alternativeExperience=32, steerControlType='angle', transmissionType='automatic', + pcmCruise=True, openpilotLongitudinalControl=True, safetyConfigs=[{'safetyModel': 'ford', 'safetyParam': 16387}]) + cs = structs.CarState(canValid=True, vEgo=11., vEgoRaw=11., gearShifter='drive') + cs.cruiseState.available = cs.cruiseState.enabled = True + slot = PandaSlot(0, 'panda', 6, 16387, 32, True) + native = SafetyState(1, True, NOW, NOW+200_000_000, 6, 16387, True, True, True, True, + 'panda', 'axis', sourcePandaStatesMonoTime=NOW, pandaInventory=(slot,)) + f = TransportPauseFeedback(cp) + sm = sample(cp, NOW, 1, native, combined=True, event=False, raw_controls=True) + assert not f.observe(sm, cp, cs, NOW, latched=True, intent_producer_session='producer') + cs.cruiseState.enabled = False + stamp = NOW + 20_000_000 + sm = sample(cp, stamp, 2, native, combined=False) + return cp, cs, f, sm, native, stamp + 2_000_000 + + +def change(sm, name, fn): + m = sm.messages[name].as_builder() + fn(getattr(m, name)) + sm.messages[name] = m.as_reader() + + +def wire(sm, native): + m = sm.messages['aolSafetyWire'].as_builder() + m.logMonoTime = native.observedMonoTime + m.aolSafetyWire = encode_safety(native) + sm.messages['aolSafetyWire'] = m.as_reader() + sm.logMonoTime['aolSafetyWire'] = native.observedMonoTime + + +def invoke(cp, cs, f, sm, now, latched=True): + return f.observe(sm, cp, cs, now, latched=latched, intent_producer_session='producer') + + +def test_raw_cancel_before_native_echo_retains_lat_not_long_without_renewing_receipts(): + cp, cs, f, sm, native, now = fixture() + before = dict(sm.logMonoTime) + assert not invoke(cp, cs, f, sm, now) + assert sm.logMonoTime == before + assert sm['aolAxisState'].validUntilMonoTime == NOW+50_000_000 + intent = SimpleNamespace(allowedLatch=True, pauseLateral=False, pauseLongitudinal=False) + axes = decide_axes(standard_lateral=False, standard_longitudinal=False, intent=intent, native=native, + car_state=cs, initialized=True, model_ready=True, no_entry=False, immediate_disable=False, dm_lockout=False, pause_brake_mps=0.) + assert axes.lateral_active and not axes.longitudinal_active + intent.allowedLatch = False + axes = decide_axes(standard_lateral=False, standard_longitudinal=False, intent=intent, native=native, + car_state=cs, initialized=True, model_ready=True, no_entry=False, immediate_disable=False, dm_lockout=False, pause_brake_mps=0.) + assert not axes.lateral_active and not axes.longitudinal_active + + +def test_native_echo_first_is_unchanged(): + cp, cs, f, sm, native, now = fixture() + wire(sm, replace(native, observedMonoTime=NOW+20_000_000, validUntilMonoTime=NOW+220_000_000, + requestedLongitudinal=False, longitudinalAllowed=False, + pandaInventory=(replace(native.pandaInventory[0], controlsAllowed=False),))) + assert not invoke(cp, cs, f, sm, now) + + +@pytest.mark.parametrize('fault', ['lat_denied', 'missing_native', 'expired_native', 'source_stale', 'source_missing', + 'axis_stale', 'raw_missing', 'raw_fault', 'native_fault', 'event_stale', 'event_missing', 'event_wrong', + 'explicit_off', 'epoch', 'gas', 'can_invalid']) +def test_cancel_cannot_retain_unproven_lateral(fault): + cp, cs, f, sm, native, now = fixture() + latched = True + if fault == 'lat_denied': + wire(sm, replace(native, lateralAllowed=False)) + elif fault == 'missing_native': + sm.seen['aolSafetyWire'] = False + elif fault == 'expired_native': + wire(sm, replace(native, observedMonoTime=now-200_000_001, validUntilMonoTime=now-1)) + elif fault in ('source_stale', 'source_missing'): + change(sm, 'aolAxisState', lambda a: setattr(a, 'sourceCarStateMonoTime', now-30_000_001 if fault=='source_stale' else 0)) + elif fault == 'axis_stale': + now = NOW+50_000_001 + elif fault == 'raw_missing': + sm.seen['pandaStates'] = False + elif fault == 'raw_fault': + change(sm, 'pandaStates', lambda p: setattr(p[0], 'safetyRxChecksInvalid', True)) + elif fault == 'native_fault': + wire(sm, replace(native, pandaInventory=(replace(native.pandaInventory[0], faults=1),))) + elif fault == 'event_stale': + sm.logMonoTime['onroadEvents'] = now-30_000_001 + elif fault == 'event_missing': + sm.seen['onroadEvents'] = False + elif fault == 'event_wrong': + change(sm, 'onroadEvents', lambda e: setattr(e[0], 'name', 'pedalPressed')) + elif fault == 'explicit_off': + latched = False + elif fault == 'epoch': + change(sm, 'aolAxisState', lambda a: setattr(a, 'intentIntegrityEpoch', 2)) + elif fault == 'gas': + cs.gasPressed = True + elif fault == 'can_invalid': + cs.canValid = False + retained = f._native_long_withdrawal_lateral_current(sm, cp, cs, sm['aolAxisState'], now, latched=latched, producer='producer') + assert retained is None + + +def test_repeated_cancel_does_not_refresh_original_source_or_native_deadlines(): + cp, cs, f, sm, native, now = fixture() + for stamp in [now, now+5_000_000, now+10_000_000]: + assert not invoke(cp, cs, f, sm, stamp) + # A second raw Cancel event cannot revive the original expired axis proof. + sm.logMonoTime['onroadEvents'] = NOW+50_000_001 + change(sm, 'onroadEvents', lambda e: setattr(e[0], 'name', 'buttonCancel')) + assert invoke(cp, cs, f, sm, NOW+50_000_001) + assert sm['aolAxisState'].validUntilMonoTime == NOW+50_000_000 + assert native.validUntilMonoTime == NOW+200_000_000 + + +def test_fresh_native_receipts_allow_repeated_cancel_and_new_full_engagement(): + cp, cs, f, sm, native, now = fixture() + assert not invoke(cp, cs, f, sm, now) + sequence = 3 + for cycle in range(3): + stamp = NOW + (40 + cycle * 80) * 1_000_000 + # New native LAT-only receipt completes the previous withdrawal. + native = replace(native, observedMonoTime=stamp, validUntilMonoTime=stamp+200_000_000, + sourcePandaStatesMonoTime=stamp, requestedLongitudinal=False, longitudinalAllowed=False, + pandaInventory=(replace(native.pandaInventory[0], controlsAllowed=False),)) + sm = sample(cp, stamp, sequence, native, combined=False) + assert not invoke(cp, cs, f, sm, stamp+1_000_000) + assert f.lateral_only_baseline + # A fresh driver engagement and matching native FULL receipt, not Cancel, + # reestablish the combined axis baseline. + stamp += 20_000_000 + cs.cruiseState.enabled = True + native = replace(native, observedMonoTime=stamp, validUntilMonoTime=stamp+200_000_000, + sourcePandaStatesMonoTime=stamp, requestedLongitudinal=True, longitudinalAllowed=True, + pandaInventory=(replace(native.pandaInventory[0], controlsAllowed=True),)) + sm = sample(cp, stamp, sequence+1, native, combined=True, event=False, raw_controls=True) + assert not invoke(cp, cs, f, sm, stamp+1_000_000) + assert not f.lateral_only_baseline + # Second physical Cancel: newer raw LONG-off, previous FULL native receipt. + stamp += 20_000_000 + cs.cruiseState.enabled = False + sm = sample(cp, stamp, sequence+2, native, combined=False) + original_deadline = native.validUntilMonoTime + assert not invoke(cp, cs, f, sm, stamp+1_000_000) + assert native.validUntilMonoTime == original_deadline + sequence += 3 + + +def test_real_ford_intent_owner_cancel_does_not_rearm_explicit_lateral_off(): + from openpilot.starpilot.aol.intent import AOL_TOGGLE, AolSettings + from openpilot.starpilot.car.ford.aol import FordCardIntent + + cp, cs, _, _, _, now = fixture() + settings = AolSettings(True, 0., AOL_TOGGLE, 0, (0, 0, 0), (0, 0, 0)) + owner = FordCardIntent(cp, settings) + owner.update(cs, now_ns=now, fault_active=False) + owner.observe_full_engagement(cs, enabled=False, active=False, source_ns=now, + observation_valid=True, now_ns=now, fault_active=False) + owner.observe_full_engagement(cs, enabled=True, active=True, source_ns=now+1, + observation_valid=True, now_ns=now+1, fault_active=False) + assert owner.allowed_latch + cs.buttonEvents = [{'type': 'cancel', 'pressed': True}] + owner.update(cs, now_ns=now+2, fault_active=False) + assert owner.allowed_latch + cs.buttonEvents = [] + owner.update(cs, now_ns=now+3, fault_active=False) + cs.buttonEvents = [{'type': 'lkas', 'pressed': True}] + owner.update(cs, now_ns=now+4, fault_active=False) + assert not owner.allowed_latch and owner.pause_lateral + cs.buttonEvents = [{'type': 'lkas', 'pressed': False}] + owner.update(cs, now_ns=now+5, fault_active=False) + cs.buttonEvents = [{'type': 'cancel', 'pressed': True}] + owner.update(cs, now_ns=now+6, fault_active=False) + assert not owner.allowed_latch and owner.pause_lateral + cs.buttonEvents = [] + owner.update(cs, now_ns=now+7, fault_active=False) + cs.buttonEvents = [{'type': 'lkas', 'pressed': True}] + owner.update(cs, now_ns=now+8, fault_active=False) + assert owner.allowed_latch and not owner.pause_lateral diff --git a/openpilot/starpilot/aol/tests/test_ford_first_grant_join.py b/openpilot/starpilot/aol/tests/test_ford_first_grant_join.py new file mode 100644 index 0000000000..2e8d3f5967 --- /dev/null +++ b/openpilot/starpilot/aol/tests/test_ford_first_grant_join.py @@ -0,0 +1,80 @@ +"""First native grant may join only the exact previously validated axis lease.""" +import pytest +from openpilot.starpilot.tests.test_ford_first_gas_grant import first_grant +from openpilot.starpilot.tests.ford_alpha_test_support import NOW, PRODUCER, change, native_change + + +def pending_grant(): + cp, cs, feedback, sm, native = first_grant() + event = sm.messages['aolAxisState'].as_builder() + event.logMonoTime = NOW + 20_000_000 + event.aolAxisState.observedMonoTime = NOW + 20_000_000 + event.aolAxisState.validUntilMonoTime = NOW + 50_000_000 + event.aolAxisState.lateralActive = True + event.aolAxisState.mode = 'lateralOnly' + sm.messages['aolAxisState'] = event.as_reader() + sm.logMonoTime['aolAxisState'] = event.logMonoTime + native_change(sm, native, requestedLateral=False, lateralAllowed=False, requestedLongitudinal=False) + assert not feedback.observe(sm, cp, cs, NOW + 30_000_000, latched=True, intent_producer_session=PRODUCER) + assert not feedback.ever_lateral_active and not feedback.lateral_native_ns + native_change(sm, native, observedMonoTime=NOW + 40_000_000, validUntilMonoTime=NOW + 240_000_000) + return cp, cs, feedback, sm + + +@pytest.mark.parametrize('fault', [ + 'none', 'expired', 'source', 'sequence', 'publication', 'deadline', 'epoch', 'producer', 'session', + 'fault', 'off', 'no-prior', 'prior-stale', 'prior-active', 'prior-native', 'pending', 'retaining', + 'source-retaining', 'native-denied', 'native-expired', 'native-old', 'native-session', 'native-invalid', + 'brake', 'cancel', 'cancel-release', 'gas-off', 'cruise-off', 'can-invalid', 'eps', 'unlatched', +]) +def test_first_grant_only_joins_the_original_validated_source(fault): + cp, cs, feedback, sm = pending_grant() + now = NOW + 45_000_000 + axis = sm['aolAxisState'] + assert now - axis.sourceCarStateMonoTime > 30_000_000 + assert now < axis.validUntilMonoTime + if fault == 'expired': + now = axis.validUntilMonoTime + 1 + elif fault in ('source', 'sequence', 'publication', 'deadline', 'epoch', 'producer', 'session', 'fault', 'off'): + field, value = { + 'source': ('sourceCarStateMonoTime', axis.sourceCarStateMonoTime - 1), + 'sequence': ('sequence', axis.sequence + 1), 'publication': ('observedMonoTime', axis.observedMonoTime + 1), + 'deadline': ('validUntilMonoTime', axis.validUntilMonoTime + 1), 'epoch': ('intentIntegrityEpoch', 2), + 'producer': ('intentProducerSessionId', 'foreign'), 'session': ('sessionId', 'foreign'), + 'fault': ('faultReason', 'critical'), 'off': ('desiredLateral', False), + }[fault] + change(sm, 'aolAxisState', lambda a: setattr(a, field, value)) + elif fault in ('no-prior', 'prior-stale', 'prior-active', 'prior-native', 'pending', 'retaining', 'source-retaining'): + field, value = { + 'no-prior': ('signature', None), 'prior-stale': ('healthy_feedback_ns', axis.sourceCarStateMonoTime + 30_000_001), + 'prior-active': ('ever_lateral_active', True), 'prior-native': ('lateral_native_ns', NOW), + 'pending': ('pending_event', 1), 'retaining': ('retention_started_ns', NOW), + 'source-retaining': ('source_retention_started_ns', NOW), + }[fault] + setattr(feedback, field, value) + elif fault.startswith('native-'): + from openpilot.starpilot.aol.wire import decode_safety + native = decode_safety(sm['aolSafetyWire']) + field, value = { + 'native-denied': ('lateralAllowed', False), 'native-expired': ('validUntilMonoTime', now - 1), + 'native-old': ('observedMonoTime', feedback.healthy_native_ns), + 'native-session': ('axisSessionId', 'foreign'), 'native-invalid': ('compatible', False), + }[fault] + native_change(sm, native, **{field: value}) + elif fault in ('cancel', 'cancel-release'): + cs.buttonEvents = [{'type': 'cancel', 'pressed': fault == 'cancel'}] + elif fault == 'cruise-off': + cs.cruiseState.enabled = False + elif fault in ('brake', 'gas-off', 'can-invalid', 'eps'): + field, value = {'brake': ('brakePressed', True), 'gas-off': ('gasPressed', False), + 'can-invalid': ('canValid', False), 'eps': ('steerFaultTemporary', True)}[fault] + setattr(cs, field, value) + before = dict(vars(feedback)), dict(sm.logMonoTime), sm['aolAxisState'].to_dict() + result = feedback._first_ford_gas_lateral_grant(sm, cp, cs, sm['aolAxisState'], now, + latched=fault != 'unlatched', producer=PRODUCER) + assert (result is not None) == (fault == 'none') + assert before == (dict(vars(feedback)), dict(sm.logMonoTime), sm['aolAxisState'].to_dict()) + if result is not None: + assert result.lateralAllowed and not result.longitudinalAllowed + assert not feedback.observe(sm, cp, cs, now, latched=True, intent_producer_session=PRODUCER) + assert not feedback._same_validated_ford_first_source(sm['aolAxisState'], now + 1) diff --git a/openpilot/starpilot/aol/transport_pause.py b/openpilot/starpilot/aol/transport_pause.py index d52c3b13b1..6ef53c1e78 100644 --- a/openpilot/starpilot/aol/transport_pause.py +++ b/openpilot/starpilot/aol/transport_pause.py @@ -194,6 +194,26 @@ class TransportPauseFeedback: self.healthy_native_ns = 0 self.healthy_inventory = None + def _same_validated_ford_first_source(self, axis, now_ns): + """Join the first native grant to an already validated, still-leased axis. + + This retains intent only. It does not admit a new source, renew a lease, + or change any source/axis/native check used to transmit controls. + """ + p = self.signature + if not p or self.ever_lateral_active or self.lateral_native_ns: + return False + signature = (str(axis.sessionId), int(axis.sequence), int(axis.observedMonoTime), int(axis.observedMonoTime), + int(axis.validUntilMonoTime), str(axis.faultReason), int(axis.faultEventMonoTime), str(axis.faultSessionId), + int(axis.sourceCarStateMonoTime), bool(axis.lateralActive), bool(axis.longitudinalActive), + bool(axis.desiredLateral), bool(axis.desiredLongitudinal), bool(axis.nativeAcknowledged), + str(axis.intentProducerSessionId), int(axis.intentIntegrityEpoch)) + return bool(p == signature and + 0 < axis.sourceCarStateMonoTime <= axis.observedMonoTime <= self.healthy_feedback_ns < now_ns <= axis.validUntilMonoTime and + self.healthy_feedback_ns - axis.sourceCarStateMonoTime <= AXIS_MAX_AGE_NS and + axis.validUntilMonoTime == axis.observedMonoTime + AXIS_MAX_AGE_NS and + now_ns - self.healthy_feedback_ns <= AXIS_MAX_AGE_NS) + def _first_ford_gas_lateral_grant(self, sm, cp, cs, axis, now_ns, *, latched, producer): from opendbc.car import structs from opendbc.car.ford.aol import qualified as ford_qualified @@ -207,7 +227,8 @@ class TransportPauseFeedback: str(axis.faultReason) != 'none' or not (pending_ack or str(axis.mode) == 'lateralOnly' and axis.lateralActive) or not axis.nativeAcknowledged or not axis.desiredLateral or not axis.desiredLongitudinal or axis.longitudinalActive or not 0 < axis.sourceCarStateMonoTime <= axis.observedMonoTime <= now_ns <= axis.validUntilMonoTime or - now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or + (now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS and + (cs.buttonEvents or not self._same_validated_ford_first_source(axis, now_ns))) or not cs.gasPressed or cs.brakePressed or cs.regenBraking or not cs.cruiseState.available or not cs.cruiseState.enabled or not cs.canValid or cs.canTimeout or cs.steerFaultTemporary or cs.steerFaultPermanent or cs.accFaulted or cs.vehicleSensorsInvalid or cs.steeringDisengage or @@ -221,6 +242,7 @@ class TransportPauseFeedback: native = independent_lateral_health(sm, cp, cs, self.session, now_ns) # 10Hz LAT grant may precede waiting axis: intent only. if (native is None or native.observedMonoTime < max(self.healthy_native_ns, self.lateral_native_ns) or + (now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS and native.observedMonoTime <= self.healthy_native_ns) or not native.pandaInventory or not native.requestedLongitudinal or native.longitudinalAllowed or self.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))): return None @@ -287,7 +309,18 @@ class TransportPauseFeedback: native = independent_lateral_health(sm, cp, cs, self.session, now_ns) # Brake health may precede axis status. # Keep LAT intent only; physical pedal owns LONG. - brake_health = bool(((ford_withdrawal or classic_brake) and cs.brakePressed or volkswagen_withdrawal) and (not cs.gasPressed or volkswagen_withdrawal) and + # Cancel can withdraw raw Panda LONG before its next native axis receipt. + # Retain only the already acknowledged LAT-only axis, under the original + # source/native deadlines and a fresh matching cruise-withdrawal event. + ford_cancel_health = bool(ford_withdrawal and not cs.cruiseState.enabled and + not axis.desiredLongitudinal and not axis.longitudinalActive and + 0 < event_ns <= now_ns and now_ns - event_ns <= AXIS_MAX_AGE_NS and + any(event.userDisable and event.name in (log.OnroadEvent.EventName.buttonCancel, + log.OnroadEvent.EventName.pcmDisable) for event in sm['onroadEvents']) and + 0 < int(sm.logMonoTime['pandaStates']) <= now_ns and + now_ns - int(sm.logMonoTime['pandaStates']) <= SAFETY_MAX_AGE_NS) + brake_health = bool(((ford_withdrawal or classic_brake) and cs.brakePressed or volkswagen_withdrawal or + ford_cancel_health) and (not cs.gasPressed or volkswagen_withdrawal) and native is not None and native.sourcePandaStatesMonoTime > 0 and native.sourcePandaStatesMonoTime < int(sm.logMonoTime['pandaStates']) and all(not slot.controlsAllowed for slot, config in zip(sm['pandaStates'], cp.safetyConfigs, strict=True) diff --git a/openpilot/starpilot/tests/test_card_initial_wait_brand.py b/openpilot/starpilot/tests/test_card_initial_wait_brand.py new file mode 100644 index 0000000000..221608a2e3 --- /dev/null +++ b/openpilot/starpilot/tests/test_card_initial_wait_brand.py @@ -0,0 +1,28 @@ +"""The Card Volkswagen initial-wait lookup is never entered for other brands.""" +import ast +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + + +@pytest.mark.parametrize('brand', ['ford', 'hyundai', 'honda', 'toyota', 'gm', 'subaru', 'volkswagen']) +@pytest.mark.parametrize('waiting', [False, True]) +def test_card_initial_wait_lookup_is_brand_scoped(brand, waiting): + path = Path(__file__).resolve().parents[2] / 'selfdrive/car/card.py' + tree = ast.parse(path.read_text()) + expressions = [node.value for node in ast.walk(tree) if isinstance(node, ast.Assign) + and any(isinstance(target, ast.Name) and target.id == 'volkswagen_initial_wait' for target in node.targets)] + assert len(expressions) == 1 + expression = expressions[0] + lookup = next(node for node in ast.walk(expression) if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) and node.func.id == 'volkswagen_initial_request') + # Keep the actual production guard/execution; only replace arguments with sentinels. + lookup.args = [] + lookup.keywords = [] + probe = Mock(return_value=waiting) + code = compile(ast.fix_missing_locations(ast.Expression(expression)), str(path), 'eval') + result = eval(code, {'self': SimpleNamespace(CP=SimpleNamespace(brand=brand)), 'volkswagen_initial_request': probe}) + assert result == (brand == 'volkswagen' and waiting) + assert probe.call_count == int(brand == 'volkswagen')