diff --git a/openpilot/selfdrive/selfdrived/selfdrived.py b/openpilot/selfdrive/selfdrived/selfdrived.py index 6bdb06173d..ce4fa3a9ae 100755 --- a/openpilot/selfdrive/selfdrived/selfdrived.py +++ b/openpilot/selfdrive/selfdrived/selfdrived.py @@ -1394,12 +1394,19 @@ class SelfdriveD: now_ns - source_ns <= SAFETY_MAX_AGE_NS and CS.canValid and not CS.canTimeout and (getattr(self, 'conditional_car_state_valid', False) or getattr(self, 'aol_publication_retained_intent', None) is intent)) + from openpilot.starpilot.car.subaru.paused_intent import retain_stopped_source + stopped_intent = healthy_expiry and retain_stopped_source(self, CS, intent, source_ns, now_ns) self.aol_car_state_log_ns = 0 self.conditional_car_state_valid = False self.aol_expired_healthy_source = healthy_expiry previous = self.aol_axis_decision was_enabled = self.enabled self.aol_axis_decision = AxisDecision() + if stopped_intent: + self.aol_fault_reason = 'availabilityPause' + self.aol_publication_retained_intent = intent + self.events.add(EventName.commIssue) + return if healthy_expiry and not was_enabled and (self.cold_gm_main_readiness(CS, intent, now_ns) or self.cold_gm_main_readiness(CS, intent, now_ns, recovering=True)): self.aol_fault_reason = 'availabilityPause' @@ -1697,6 +1704,11 @@ class SelfdriveD: if not axis_deferred: self.aol_sequence = next_sequence self.pm.send('aolAxisState', axis_msg) + if source_clock_scoped and reason == 'none': + from openpilot.starpilot.car.subaru.paused_intent import record_stopped_intent + record_stopped_intent(self, CS, axis_msg, now_ns) + elif reason == 'critical': + self.aol_stopped_intent_proof = None # Bind critical history to the actual completed axis publication. The # working decision can change again during later source-expiry checks. self.aol_published_fault_proof = ((str(axis.sessionId), str(axis.faultReason), @@ -2229,6 +2241,10 @@ class SelfdriveD: hard_fault=bool(self.aol_selected_pair_future or self.aol_authority_lost or lost_active_aol or lost_companion and not publication_expiry or lost_permission or upgraded), healthy_native=self.aol_transport_pause.observed_native) + from openpilot.starpilot.car.subaru.paused_intent import retain_stopped_source + stopped_availability = bool(publication_expiry and retain_stopped_source( + self, CS, retained_intent, retained_intent.carStateLogMonoTime, now_ns)) + availability = availability or stopped_availability ordinary_availability = bool(not source_current and not lost_active_aol and not lost_permission and not upgraded and self.ordinary_source_availability(CS, now_ns, native)) if ordinary_availability: @@ -2328,7 +2344,7 @@ class SelfdriveD: if self.aol_ordinary_source_pause: self.aol_axis_decision = self.ordinary_source_withdrawal() elif availability: - self.aol_axis_decision = AxisDecision(desired_lateral=True, native_acknowledged=True) + self.aol_axis_decision = AxisDecision() if stopped_availability else AxisDecision(desired_lateral=True, native_acknowledged=True) elif getattr(self, 'aol_availability_long_inhibit', False): decision = self.aol_axis_decision self.aol_axis_decision = AxisDecision(desired_lateral=decision.desired_lateral, diff --git a/openpilot/starpilot/aol/transport_pause.py b/openpilot/starpilot/aol/transport_pause.py index c0f9133649..d52c3b13b1 100644 --- a/openpilot/starpilot/aol/transport_pause.py +++ b/openpilot/starpilot/aol/transport_pause.py @@ -1195,6 +1195,9 @@ class TransportPauseFeedback: (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))) def _inactive_source_pause_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer): + from openpilot.starpilot.car.subaru.paused_intent import retain_stopped_source_feedback + if retain_stopped_source_feedback(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=producer): + return True from opendbc.car import structs previous = self.signature if (not latched or self.failed or self.paused or self.pending_event or self.retention_started_ns or @@ -1447,6 +1450,12 @@ class TransportPauseFeedback: from openpilot.starpilot.car.ford.physical_pause import retain_physical_pause_intent if retain_physical_pause_intent(self, sm, cp, cs, axis, now_ns, latched=latched, producer=intent_producer_session): return False + if cp.brand == 'subaru' and current and continuity: + from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction + if retain_paused_restriction(self, sm, cp, cs, axis, stamp, now_ns, + latched=latched, producer=intent_producer_session): + self.sequence, self.signature = int(axis.sequence), signature + return False if current and continuity and self._temporary_steering_intent_current(sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session, signature=signature): self.sequence, self.signature = int(axis.sequence), signature diff --git a/openpilot/starpilot/car/subaru/paused_intent.py b/openpilot/starpilot/car/subaru/paused_intent.py new file mode 100644 index 0000000000..d2fa4246b0 --- /dev/null +++ b/openpilot/starpilot/car/subaru/paused_intent.py @@ -0,0 +1,167 @@ +"""Retain established Subaru OFF intent; this proof never grants a command.""" +from dataclasses import dataclass +from math import isfinite + +from opendbc.car import structs +from opendbc.car.subaru.stock_aol import qualified +from opendbc.car.subaru.values import CAR +from openpilot.cereal import log +from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS +from openpilot.starpilot.aol.wire import IntentState, SafetyState + + +@dataclass(frozen=True) +class StoppedIntentProof: + session: str + cp: tuple + epoch: int + intent: IntentState + state: object + native: SafetyState + + +def stopped_state(cp, state): + return bool(cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 and qualified(cp, marked_only=True) and + state.canValid and not state.canTimeout and state.standstill and state.brakePressed and + isfinite(state.vEgo) and isfinite(state.vEgoRaw) and + state.gearShifter == structs.CarState.GearShifter.drive and state.cruiseState.available and + not state.cruiseState.enabled and not state.gasPressed and not state.regenBraking and + not state.buttonEvents and not state.steerFaultTemporary and not state.steerFaultPermanent and + not state.accFaulted and not state.doorOpen and not state.seatbeltUnlatched and + not state.vehicleSensorsInvalid and not state.steeringDisengage) + + +def native_off(native): + return bool(native is not None and native.pandaInventory and not any((native.requestedLateral, + native.lateralAllowed, native.requestedLongitudinal, native.longitudinalAllowed))) + + +def record_stopped_intent(sd, state, message, now_ns): + from openpilot.starpilot.aol.transport_pause import _healthy_transport_native, cp_identity + sd.aol_stopped_intent_proof = None + axis = message.aolAxisState + intent = getattr(sd, 'aol_last_intent', None) + companion = getattr(sd, 'aol_intent_companion', None) + if (not stopped_state(sd.CP, state) or not getattr(sd, 'aol_ever_active', False) or sd.aol_authority_lost or sd.enabled or sd.active or + not message.valid or not axis.qualified or str(axis.faultReason) != 'none' or str(axis.mode) != 'off' or + str(axis.sessionId) != sd.aol_session_id or str(axis.faultSessionId) != sd.aol_session_id or + axis.observedMonoTime != now_ns or axis.validUntilMonoTime != now_ns + AXIS_MAX_AGE_NS or + any((axis.desiredLateral, axis.desiredLongitudinal, axis.lateralActive, axis.longitudinalActive)) or + not axis.nativeAcknowledged or intent is None or not intent.settingsQualified or + not intent.allowedLatch or not intent.lateralArmed or intent.pauseLongitudinal or + companion is None or not companion.last_drain_ok or companion.session != intent.producerSessionId or + axis.intentProducerSessionId != intent.producerSessionId or axis.intentIntegrityEpoch != companion.integrity_epoch or + not 0 < axis.sourceCarStateMonoTime == intent.carStateLogMonoTime <= now_ns or + now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS): + return + native = _healthy_transport_native(sd.sm, sd.CP, state, sd.aol_session_id, now_ns) + if native_off(native): + sd.aol_stopped_intent_proof = StoppedIntentProof(sd.aol_session_id, cp_identity(sd.CP), + companion.integrity_epoch, intent, state, native) + + +def retain_stopped_source(sd, state, intent, source_ns, now_ns): + from openpilot.selfdrive.selfdrived.events import ET + from openpilot.starpilot.aol.transport_pause import _healthy_transport_native, cp_identity, HOST_SOURCE_AVAILABILITY_EVENTS + proof = getattr(sd, 'aol_stopped_intent_proof', None) + companion = getattr(sd, 'aol_intent_companion', None) + decision = sd.aol_axis_decision + if (proof is None or not stopped_state(sd.CP, state) or state is not proof.state or intent != proof.intent or + sd.aol_session_id != proof.session or cp_identity(sd.CP) != proof.cp or not getattr(sd, 'aol_ever_active', False) or + sd.aol_authority_lost or sd.enabled or sd.active or + getattr(sd, 'aol_fault_reason', 'none') not in ('none', 'availabilityPause') or + any((decision.desired_lateral, decision.desired_longitudinal, decision.lateral_active, decision.longitudinal_active)) or + companion is None or not companion.last_drain_ok or companion.session != proof.intent.producerSessionId or + companion.integrity_epoch != proof.epoch or not getattr(sd, 'aol_step_intent_drain_ok', True) or + getattr(sd, 'car_state_queue_invalid', False) or getattr(sd, 'aol_selected_pair_future', False) or + not sd.sm.all_checks(['modelV2', 'extrinsicsCalibration', 'driverMonitoringState']) or + sd.sm['extrinsicsCalibration'].calStatus != log.ExtrinsicsCalibration.Status.calibrated or + sd.sm['driverMonitoringState'].lockout or sd.sm['driverMonitoringState'].alwaysOnLockout or + sd.sm['driverMonitoringState'].alertLevel == log.DriverMonitoringState.AlertLevel.three or + source_ns != proof.intent.carStateLogMonoTime or not 0 < source_ns <= now_ns <= proof.intent.validUntilMonoTime or + not AXIS_MAX_AGE_NS < now_ns - source_ns <= SAFETY_MAX_AGE_NS or + any(event.userDisable and event.name != log.OnroadEvent.EventName.pcmDisable or event.immediateDisable or + event.softDisable and event.name not in HOST_SOURCE_AVAILABILITY_EVENTS for event in sd.events.to_msg()) or + sd.events.contains(ET.ENABLE)): + return False + latest = companion.latest + raw = latest[2] if latest is not None and latest[1] else None + if (raw is None or raw.producerSessionId != proof.intent.producerSessionId or not raw.settingsQualified or + not raw.allowedLatch or not raw.lateralArmed or raw.pauseLongitudinal or + raw.pauseLateral != proof.intent.pauseLateral or not source_ns <= raw.carStateLogMonoTime <= now_ns or + not 0 < raw.observedMonoTime <= now_ns <= raw.validUntilMonoTime): + return False + for stamp, (value, epoch, producer) in companion.raw_projections.items(): + if stamp >= source_ns and (epoch != proof.epoch or producer != proof.intent.producerSessionId or value is None or + not value.settingsQualified or not value.allowedLatch or not value.lateralArmed or value.pauseLongitudinal or + value.pauseLateral != proof.intent.pauseLateral): + return False + native = _healthy_transport_native(sd.sm, sd.CP, state, proof.session, now_ns) + return bool(native_off(native) and native.observedMonoTime >= proof.native.observedMonoTime and + native.pandaSerial == proof.native.pandaSerial and + tuple(slot.hardwareSerial for slot in native.pandaInventory) == tuple(slot.hardwareSerial for slot in proof.native.pandaInventory)) + + +def retain_stopped_source_feedback(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer): + from openpilot.starpilot.aol.transport_pause import _healthy_transport_native, cp_identity, host_source_availability_only + previous = feedback.signature + if (not stopped_state(cp, state) or not latched or feedback.failed or feedback.paused or feedback.pending_event or + feedback.retention_started_ns or feedback.source_retention_started_ns or not feedback.ever_lateral_active or + previous is None or not feedback.session or cp_identity(cp) != feedback.cp or + previous[0] != feedback.session or previous[7] != feedback.session or previous[5] != 'none' or + any(previous[9:13]) or not previous[13] or not producer or previous[14] != producer or + not 0 < previous[8] <= previous[2] <= now_ns or not 0 < feedback.healthy_feedback_ns <= now_ns or + previous[2] - previous[8] > AXIS_MAX_AGE_NS or previous[4] != previous[2] + AXIS_MAX_AGE_NS or + now_ns - previous[8] > SAFETY_MAX_AGE_NS or + not sm.seen['aolAxisState'] or not sm.valid['aolAxisState'] or not sm.alive['aolAxisState'] or + not axis.qualified or str(axis.mode) != 'off' or str(axis.faultReason) != 'availabilityPause' or + axis.sourceCarStateMonoTime != 0 or any((axis.desiredLateral, axis.desiredLongitudinal, + axis.lateralActive, axis.longitudinalActive, axis.nativeAcknowledged)) or + str(axis.sessionId) != feedback.session or str(axis.faultSessionId) != feedback.session or + axis.intentProducerSessionId != producer or axis.intentIntegrityEpoch != previous[15] or + axis.sequence <= feedback.sequence or not previous[2] < stamp == axis.observedMonoTime <= now_ns <= axis.validUntilMonoTime or + axis.validUntilMonoTime - stamp != AXIS_MAX_AGE_NS): + return False + event_ns = int(sm.logMonoTime['onroadEvents']) + events = [e for e in sm['onroadEvents'] if not (e.name == log.OnroadEvent.EventName.pcmDisable and + e.userDisable and not e.softDisable and not e.immediateDisable)] + if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or + not 0 < event_ns == axis.faultEventMonoTime <= stamp or now_ns - event_ns > 1_500_000_000 or + not host_source_availability_only(events)): + return False + native = _healthy_transport_native(sm, cp, state, feedback.session, now_ns) + return bool(native_off(native) and native.observedMonoTime >= feedback.healthy_native_ns and + feedback.healthy_inventory == (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))) + + +def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer): + from openpilot.starpilot.aol.transport_pause import _configured_transport_native + previous = feedback.signature + if (cp.carFingerprint != CAR.SUBARU_IMPREZA_2020 or not qualified(cp, marked_only=True) or + not latched or feedback.failed or feedback.paused or feedback.pending_event or + feedback.retention_started_ns or feedback.source_retention_started_ns or not feedback.ever_lateral_active or + previous is None or not feedback.session or not producer or + previous[0] != previous[7] or previous[0] != feedback.session or previous[5] != 'none' or + any(previous[9:13]) or not previous[13] or previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or + axis.intentProducerSessionId != producer or str(axis.sessionId) != feedback.session or + str(axis.faultReason) != 'none' or str(axis.mode) != 'off' or not axis.nativeAcknowledged or + any((axis.desiredLateral, axis.lateralActive, axis.desiredLongitudinal, axis.longitudinalActive)) or + not 0 < previous[8] <= previous[2] <= now_ns <= previous[4] or now_ns - previous[8] > AXIS_MAX_AGE_NS or + not previous[8] <= axis.sourceCarStateMonoTime <= stamp <= now_ns or now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or + not state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or + state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or + state.steeringDisengage or state.buttonEvents or state.gasPressed or state.regenBraking or + state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or state.cruiseState.enabled or + not 0 < feedback.healthy_feedback_ns <= now_ns or not feedback.healthy_inventory): + return False + event_ns = int(sm.logMonoTime['onroadEvents']) + if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or + not 0 < axis.faultEventMonoTime == event_ns <= stamp or now_ns - event_ns > 1_500_000_000 or + any(event.immediateDisable or + event.softDisable and event.name != log.OnroadEvent.EventName.steerTempUnavailable or + event.userDisable and not (event.name == log.OnroadEvent.EventName.pcmDisable or + state.brakePressed and event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])): + return False + native = _configured_transport_native(sm, cp, feedback.session, now_ns, allow_restricted_lateral=True) + return bool(native_off(native) and native.observedMonoTime >= feedback.healthy_native_ns and + feedback.healthy_inventory == (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))) diff --git a/openpilot/starpilot/car/subaru/tests/test_paused_intent.py b/openpilot/starpilot/car/subaru/tests/test_paused_intent.py new file mode 100644 index 0000000000..8a7bdddab8 --- /dev/null +++ b/openpilot/starpilot/car/subaru/tests/test_paused_intent.py @@ -0,0 +1,201 @@ +"""Inactive intent cannot renew a source, an output deadline, or native authority.""" +from dataclasses import replace +from types import SimpleNamespace + +import pytest + +from openpilot.cereal import messaging +from openpilot.starpilot.aol.runtime import AxisDecision +from openpilot.starpilot.aol.wire import IntentState +from openpilot.starpilot.aol.tests.test_subaru_temporary_eps import stopped_feedback, leases +from openpilot.starpilot.tests.test_ford_reverse_intent import PRODUCER, SESSION, change, native_change, sample +from openpilot.starpilot.car.subaru.paused_intent import ( + record_stopped_intent, retain_stopped_source, retain_stopped_source_feedback, +) + + +def source_case(): + cp, state, feedback, sm, native, stamp = stopped_feedback() + for name in ('modelV2', 'extrinsicsCalibration', 'driverMonitoringState'): + event = messaging.new_message(name, valid=True, logMonoTime=stamp) + if name == 'extrinsicsCalibration': + event.extrinsicsCalibration.calStatus = 'calibrated' + sm.messages[name] = event.as_reader() + sm.logMonoTime[name] = stamp + sm.seen[name] = sm.valid[name] = sm.alive[name] = True + sm.all_checks = lambda names: all(sm.seen[n] and sm.valid[n] and sm.alive[n] for n in names) + intent = IntentState(PRODUCER, 2, stamp, stamp, stamp + 200_000_000, True, False, False, True, True) + companion = SimpleNamespace(session=PRODUCER, integrity_epoch=0, last_drain_ok=True, + latest=(stamp, True, intent), raw_projections={stamp: (intent, 0, PRODUCER)}) + sd = SimpleNamespace(CP=cp, sm=sm, aol_session_id=SESSION, aol_ever_active=True, + aol_authority_lost=False, enabled=False, active=False, aol_fault_reason='none', aol_last_intent=intent, + aol_intent_companion=companion, aol_axis_decision=AxisDecision(native_acknowledged=True), + events=SimpleNamespace(to_msg=lambda: sm['onroadEvents'], contains=lambda _kind: False)) + record_stopped_intent(sd, state, sm.messages['aolAxisState'], stamp) + assert sd.aol_stopped_intent_proof is not None + return sd, state, intent, stamp, feedback, native + + +def test_stopped_source_retains_original_intent_only_and_never_reanchors(): + sd, state, intent, stamp, feedback, _ = source_case() + proof = sd.aol_stopped_intent_proof + before = leases(feedback), feedback.signature, intent.validUntilMonoTime, sd.aol_axis_decision + for age in (30_000_001, 35_000_000, 100_000_000, 190_000_000): + assert retain_stopped_source(sd, state, intent, stamp, stamp + age) + assert sd.aol_stopped_intent_proof is proof + assert (leases(feedback), feedback.signature, intent.validUntilMonoTime, sd.aol_axis_decision) == before + assert not retain_stopped_source(sd, state, intent, stamp, stamp + 200_000_001) + assert not retain_stopped_source(sd, state, intent, stamp, stamp + 30_000_000) + + +@pytest.mark.parametrize('fault', ('moving', 'brake', 'main', 'acc', 'gas', 'regen', 'can', 'timeout', + 'eps', 'permanent', 'door', 'belt', 'sensors', 'driver_off', 'cancel', 'reverse', 'epoch', 'producer', + 'integrity', 'drain', 'future_pair', 'queue', 'critical', 'active_lat', 'desired_lat', 'active_long', + 'desired_long', 'enabled', 'authority_lost', 'new_state', 'off', 'settings', 'pause', 'raw_epoch', + 'model', 'calibration', 'dm', 'native_fault', 'native_stale', 'native_request', 'native_allow', + 'native_long', 'native_inventory', 'native_session', 'hard_event', 'user_off', 'no_history')) +def test_stopped_source_independent_vetoes_remain_authoritative(fault): + sd, state, intent, stamp, _, native = source_case() + physical = {'moving': ('standstill', False), 'brake': ('brakePressed', False), 'gas': ('gasPressed', True), + 'regen': ('regenBraking', True), 'can': ('canValid', False), 'timeout': ('canTimeout', True), + 'eps': ('steerFaultTemporary', True), 'permanent': ('steerFaultPermanent', True), 'door': ('doorOpen', True), + 'belt': ('seatbeltUnlatched', True), 'sensors': ('vehicleSensorsInvalid', True), 'driver_off': ('steeringDisengage', True)} + if fault in physical: + setattr(state, *physical[fault]) + elif fault in ('main', 'acc'): + setattr(state.cruiseState, 'available' if fault == 'main' else 'enabled', fault == 'acc') + elif fault == 'cancel': + state.buttonEvents = [{'type': 'cancel', 'pressed': True}] + elif fault == 'reverse': + state.gearShifter = 'reverse' + elif fault in ('epoch', 'producer', 'integrity'): + setattr(sd.aol_intent_companion, {'epoch': 'integrity_epoch', 'producer': 'session', 'integrity': 'last_drain_ok'}[fault], + {'epoch': 1, 'producer': 'other', 'integrity': False}[fault]) + elif fault in ('drain', 'future_pair', 'queue'): + setattr(sd, {'drain': 'aol_step_intent_drain_ok', 'future_pair': 'aol_selected_pair_future', + 'queue': 'car_state_queue_invalid'}[fault], fault != 'drain') + elif fault == 'critical': + sd.aol_fault_reason = 'critical' + elif fault in ('active_lat', 'desired_lat', 'active_long', 'desired_long'): + field = {'active_lat': 'lateral_active', 'desired_lat': 'desired_lateral', + 'active_long': 'longitudinal_active', 'desired_long': 'desired_longitudinal'}[fault] + sd.aol_axis_decision = replace(sd.aol_axis_decision, **{field: True}) + elif fault in ('enabled', 'authority_lost'): + setattr(sd, 'enabled' if fault == 'enabled' else 'aol_authority_lost', True) + elif fault == 'new_state': + state = state.as_reader().as_builder() + elif fault in ('off', 'settings', 'pause'): + raw = replace(intent, **{'off': {'allowedLatch': False}, 'settings': {'settingsQualified': False}, + 'pause': {'pauseLateral': True}}[fault]) + sd.aol_intent_companion.latest = (stamp, True, raw) + sd.aol_intent_companion.raw_projections[stamp] = (raw, 0, PRODUCER) + elif fault == 'raw_epoch': + sd.aol_intent_companion.raw_projections[stamp] = (intent, 1, PRODUCER) + elif fault == 'model': + sd.sm.valid['modelV2'] = False + elif fault == 'calibration': + change(sd.sm, 'extrinsicsCalibration', lambda c: setattr(c, 'calStatus', 'uncalibrated')) + elif fault == 'dm': + change(sd.sm, 'driverMonitoringState', lambda d: setattr(d, 'alwaysOnLockout', True)) + elif fault == 'native_fault': + native_change(sd.sm, native, pandaInventory=(replace(native.pandaInventory[0], faults=1),)) + elif fault == 'native_stale': + native_change(sd.sm, native, validUntilMonoTime=stamp) + elif fault in ('native_request', 'native_allow', 'native_long'): + native_change(sd.sm, native, **{{'native_request': 'requestedLateral', 'native_allow': 'lateralAllowed', + 'native_long': 'requestedLongitudinal'}[fault]: True}) + elif fault == 'native_inventory': + native_change(sd.sm, native, pandaSerial='other', pandaInventory=(replace(native.pandaInventory[0], hardwareSerial='other'),)) + elif fault == 'native_session': + native_change(sd.sm, native, axisSessionId='other') + elif fault in ('hard_event', 'user_off'): + change(sd.sm, 'onroadEvents', lambda e: setattr(e[0], 'immediateDisable' if fault == 'hard_event' else 'name', + True if fault == 'hard_event' else 'buttonCancel')) + elif fault == 'no_history': + sd.aol_stopped_intent_proof = None + else: + raise AssertionError(fault) + assert not retain_stopped_source(sd, state, intent, stamp, stamp + 35_000_000) + + +def test_stopped_source_zero_feedback_keeps_fixed_original_source_and_native_deadlines(): + cp, state, feedback, _, _, stamp = stopped_feedback() + before = leases(feedback), feedback.signature, feedback.sequence + now = stamp + 35_000_000 + sm, native = sample(cp, now, now, 3, active=False, requested=False, allowed=False, event_stamp=now) + change(sm, 'aolAxisState', lambda a: (setattr(a, 'sourceCarStateMonoTime', 0), + setattr(a, 'nativeAcknowledged', False), setattr(a, 'faultReason', 'availabilityPause'), setattr(a, 'intentIntegrityEpoch', 0))) + change(sm, 'onroadEvents', lambda e: (setattr(e[0], 'name', 'commIssue'), setattr(e[0], 'userDisable', False), setattr(e[0], 'softDisable', True))) + assert retain_stopped_source_feedback(feedback, sm, cp, state, sm['aolAxisState'], now, now, + latched=True, producer=PRODUCER) + assert not feedback.observe(sm, cp, state, now, latched=True, intent_producer_session=PRODUCER) + assert (leases(feedback), feedback.signature, feedback.sequence) == before + late = stamp + 200_000_001 + assert not retain_stopped_source_feedback(feedback, sm, cp, state, sm['aolAxisState'], now, late, + latched=True, producer=PRODUCER) + assert not native.requestedLateral and not native.lateralAllowed + + +def paused_case(): + cp, state, feedback, sm, native, stamp = stopped_feedback() + state.steerFaultTemporary = True + return cp, state, feedback, sm, native, stamp + + +def test_paused_restriction_keeps_only_intent_without_renewing_healthy_baselines(): + from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction + cp, state, feedback, sm, _, stamp = paused_case() + before = leases(feedback), feedback.healthy_feedback_ns, feedback.healthy_native_ns + assert retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp, + latched=True, producer=PRODUCER) + assert not feedback.observe(sm, cp, state, stamp, latched=True, intent_producer_session=PRODUCER) + assert (leases(feedback), feedback.healthy_feedback_ns, feedback.healthy_native_ns) == before + assert not retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp + 30_000_001, + latched=True, producer=PRODUCER) + + +@pytest.mark.parametrize('fault', ('permanent', 'can', 'timeout', 'main', 'acc', 'cancel', 'reverse', 'gas', + 'regen', 'door', 'belt', 'sensors', 'driver_off', 'long', 'lat', 'ack', 'epoch', 'producer', 'critical', + 'native_request', 'native_allow', 'native_long', 'native_fault', 'native_stale', 'native_inventory', + 'hard_event', 'user_off', 'soft_event', 'failed', 'no_history', 'off', 'other_car')) +def test_paused_restriction_preserves_independent_fault_user_and_authority_vetoes(fault): + from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction + cp, state, feedback, sm, native, stamp = paused_case() + physical = {'permanent': ('steerFaultPermanent', True), 'can': ('canValid', False), 'timeout': ('canTimeout', True), + 'gas': ('gasPressed', True), 'regen': ('regenBraking', True), 'door': ('doorOpen', True), + 'belt': ('seatbeltUnlatched', True), 'sensors': ('vehicleSensorsInvalid', True), 'driver_off': ('steeringDisengage', True)} + if fault in physical: + setattr(state, *physical[fault]) + elif fault in ('main', 'acc'): + setattr(state.cruiseState, 'available' if fault == 'main' else 'enabled', fault == 'acc') + elif fault == 'cancel': + state.buttonEvents = [{'type': 'cancel', 'pressed': True}] + elif fault == 'reverse': + state.gearShifter = 'reverse' + elif fault in ('long', 'lat', 'ack', 'epoch', 'producer', 'critical'): + field, value = {'long': ('desiredLongitudinal', True), 'lat': ('lateralActive', True), 'ack': ('nativeAcknowledged', False), + 'epoch': ('intentIntegrityEpoch', 1), 'producer': ('intentProducerSessionId', 'other'), 'critical': ('faultReason', 'critical')}[fault] + change(sm, 'aolAxisState', lambda a: setattr(a, field, value)) + elif fault in ('native_request', 'native_allow', 'native_long'): + native_change(sm, native, **{{'native_request': 'requestedLateral', 'native_allow': 'lateralAllowed', + 'native_long': 'longitudinalAllowed'}[fault]: True}) + elif fault == 'native_fault': + native_change(sm, native, pandaInventory=(replace(native.pandaInventory[0], faults=1),)) + elif fault == 'native_stale': + native_change(sm, native, validUntilMonoTime=stamp - 1) + elif fault == 'native_inventory': + native_change(sm, native, pandaSerial='other', pandaInventory=(replace(native.pandaInventory[0], hardwareSerial='other'),)) + elif fault in ('hard_event', 'user_off', 'soft_event'): + change(sm, 'onroadEvents', lambda e: (setattr(e[0], 'name', 'controlsMismatch' if fault == 'hard_event' else + 'buttonCancel' if fault == 'user_off' else 'commIssue'), setattr(e[0], + 'immediateDisable' if fault == 'hard_event' else 'userDisable' if fault == 'user_off' else 'softDisable', True))) + elif fault == 'failed': + feedback.failed = True + elif fault == 'no_history': + feedback.ever_lateral_active = False + elif fault == 'other_car': + cp.carFingerprint = 'SUBARU_OUTBACK' + elif fault != 'off': + raise AssertionError(fault) + assert not retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp, + latched=fault != 'off', producer=PRODUCER) diff --git a/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py b/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py index 3f9f414f45..cab58aee89 100644 --- a/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py +++ b/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py @@ -29,7 +29,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, source_outage=False, vm_angle_handoff=0, crawl=False, eps_brake_join=False, high_angle_guard=False, main_on_brake=False, guard_brake_release=False, stopped_feedback_gap=False, rearm_on_brake=0, main_during_eps=False, - angle_continuation=0): + angle_continuation=0, stopped_source_gap=False, paused_eps=0): angle_handoff = fixed_angle_handoff or vm_angle_handoff fw = firmware_records(candidate, FW_VERSIONS, 'subaru') if firmware is None else firmware rows = [] @@ -87,7 +87,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, if stopped_feedback_gap and elapsed >= 131: now += 3_919_864 cruise = not main_only and (30 <= tick < 110 or tick >= 410) - brake = (stopped_feedback_gap and 125 <= tick < 135 or 90 <= tick < 110 or eps_brake_join and 225 <= tick < 270 or + brake = ((stopped_feedback_gap or stopped_source_gap) and 125 <= tick < 135 or 90 <= tick < 110 or eps_brake_join and 225 <= tick < 270 or main_on_brake and 30 <= tick < 55 or guard_brake_release and 225 <= tick < 245 or rearm_on_brake and 345 <= tick < 365) brake = bool(brake or angle_continuation and 70 <= tick < 90) @@ -96,7 +96,14 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, main = not 310 <= tick < 350 and (tick >= 30 or not main_only) stopped = stop_resume and (125 <= tick < 135 if hard_stop_native_first or host_first_stop else 185 <= tick < 195) first_resume = 145 <= tick < 150 if hard_stop_native_first or host_first_stop else 125 <= tick < 145 + if paused_eps: + first_resume = False # Blinker debounce overlaps the later reverse pause. source_missing = bool(source_outage and 75 <= tick < 81) + if paused_eps: + brake = bool(paused_eps in (1, 3) and 90 <= tick < 115 or not 90 <= tick < 115 and brake) + stopped = bool(paused_eps in (1, 3) and 90 <= tick < 115 or stopped) + temporary = bool(paused_eps in (3, 4) and 95 <= tick < 111 or temporary) + values = { 'Throttle': {'Throttle_Pedal': 100 if source_outage and 60 <= tick < 90 else 0}, 'Steering_Torque': {'Steer_Warning': int(temporary), @@ -140,6 +147,13 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, if angle_continuation: values['Steering_2']['Steering_Angle'] = ci.CC.apply_angle_last if tick < 90 else 0 values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 17.28) + if paused_eps: + values['Dashlights'] = {'LEFT_BLINKER': int(90 <= tick < 115)} + values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 0 if stopped else 14.4) + values['Brake_Pedal'] = {'Speed': 0 if stopped else 14.4} + values['Steering_Torque']['Steer_Torque_Sensor'] = 119 if 90 <= tick <= 100 else 80 if 101 <= tick < 111 else 0 + if paused_eps in (1, 2): + values['Brake_Pressure_L_R'] = {'Steering_Angle': 101 if 95 <= tick < 111 else 0} incoming = stream.frames(values, tick=tick) if source_outage: pending_host_can.append((now, incoming)) @@ -227,7 +241,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, expired, _ = controls.state_control() assert not expired.latActive and not expired.longActive driven_new = selfdrive_step(sd, published, new_native, previous_controls, cp, safety, now, calibration='calibrated', - source_timeout=source_missing) + source_timeout=source_missing or stopped_source_gap and 130 <= elapsed <= 133) if deadline_gap and elapsed == gap_tick: current = driven_new['aolAxisState'].aolAxisState assert current.lateralActive and not sd.aol_authority_lost, 'SUBARU_FRESH_SUCCESSOR_LOST_LATERAL' @@ -355,11 +369,15 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, assert not command.latActive and not command.longActive and row['permission'] == 0, row assert row['fault'] == 'none' and 'controlsMismatch' not in row['events'], row if stopped: - assert not row['lat'] and row['cardLatch'] and row['permission'] == 0 and row['fault'] == 'none', ('SUBARU_STOP_LOST_ARMED_INTENT', row) + assert not row['lat'] and row['cardLatch'] and row['permission'] == 0 and row['fault'] in ( + ('none', 'availabilityPause') if stopped_source_gap else ('none',)), ('SUBARU_STOP_LOST_ARMED_INTENT', row) if source_outage and 78 <= tick < 81: assert not row['lat'] and not row['long'] and row['fault'] == 'availabilityPause', ('SUBARU_SOURCE_GAP_BECAME_CRITICAL', row) if source_outage and 84 <= tick < 90: assert row['lat'] and row['cardLatch'] and row['permission'] == 1 and not row['controls'], row + if paused_eps and 90 <= tick < 115: + assert row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'], ('SUBARU_PAUSED_EPS_LOST_INTENT', row) + assert all(not frame['request'] and frame['output'] == 0 and frame['nativeAccepted'] for frame in row['steering']), row assert not command.longActive, row if 10 <= tick < 30: assert not command.latActive and not bool(intent and intent.allowedLatch) and row['permission'] == 0, row @@ -597,3 +615,22 @@ def test_actual_jacobw_aol_continues_through_admission_angle(candidate, directio crossing = [frame for row in rows if 65 <= row['tick'] < 90 for frame in row['steering'] if abs(frame['output']) > 120] assert len(crossing) >= 10 assert all(frame['request'] and frame['nativeAccepted'] and abs(frame['output']) <= 190 for frame in crossing) + + +def test_actual_stopped_source_gap_retains_intent_without_renewing_output(subaru_native_pair, tmp_path): + test_actual_full_engage_brake_reverse_temporary_recovery_mainoff( + CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, + stop_resume=True, hard_stop_native_first=True, stopped_source_gap=True) + rows = json.loads((tmp_path / (str(CAR.SUBARU_IMPREZA_2020) + '-True-actual.json')).read_text()) + paused = [row for row in rows if 130 <= row['elapsed'] <= 134] + assert any(row['fault'] == 'availabilityPause' for row in paused) + assert all(row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'] and row['permission'] == 0 for row in paused) + assert all('controlsMismatch' not in row['events'] for row in rows) + + +@pytest.mark.parametrize('restriction', [1, 2, 3, 4], ids=('stopped-guard', 'moving-guard', 'stopped-eps', 'moving-eps')) +def test_actual_paused_subaru_restriction_keeps_armed_intent(subaru_native_pair, tmp_path, restriction): + preferences = {'PauseLateralOnSignal': True, 'PauseLateralSpeed': 100., 'LateralResumeDelay': 0.} + test_actual_full_engage_brake_reverse_temporary_recovery_mainoff( + CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, + preferences=preferences, paused_eps=restriction) diff --git a/prebuilt.json b/prebuilt.json index d51ea963ea..63172b6d24 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "bd066f25463a1a5f4a53a71e32270a07f76cc89451e6d29e249eaddca537313a", "schema_version": 1} +{"protected_inventory_sha256": "13bc1e36b30db7a66238e7b775751632641e32f30a505648287bcaaff37fa353", "schema_version": 1} diff --git a/tools/ci/run_vehicle_tests.py b/tools/ci/run_vehicle_tests.py index d559ff91e4..8fed4aee29 100644 --- a/tools/ci/run_vehicle_tests.py +++ b/tools/ci/run_vehicle_tests.py @@ -278,8 +278,11 @@ RELEASE_TARGETS = ( "openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_jacobw_aol_continues_through_admission_angle", "openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_main_during_temporary_eps_waits_for_clear", "openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_stopped_feedback_gap_retains_only_armed_intent", + "openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_stopped_source_gap_retains_intent_without_renewing_output", + "openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_paused_subaru_restriction_keeps_armed_intent", "openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_repeat_main_with_brake_and_signal_pause", "openpilot/starpilot/aol/tests/test_subaru_temporary_eps.py", + "openpilot/starpilot/car/subaru/tests/test_paused_intent.py", "opendbc_repo/opendbc/car/subaru/tests/test_jacobw_angle.py", "opendbc_repo/opendbc/car/rivian/tests/test_radar_reachability.py", "opendbc_repo/opendbc/car/tesla/tests/test_radar_pairs.py",