Subaru SNG: accept any counter advance for captured source validity

capture() stores only the CANParser's newest accepted sample per batch,
so when pandad batches two Throttle frames (100 Hz) into one packet the
stored counter advances by 2 and the strict previously-stored + 1
validity check flaps False for a tick. Each flap hard-resets StopAndGo's
standstill clock, which needs 51 consecutive ready frames, so the 3 kph
hold pulse never fires and EyeSight's standstill timeout drops ACC --
on essentially every SNG standstill. Replay of the 2026-11-24 incident
segment through the real interface/controller: the counter check was the
only failing gate (71/544 stop ticks) and the clock peaked at 24/51.

Validity now means the stored sample is the parser's current accepted,
checksum-verified sample whose counter advanced from the previously
stored one. A counter that does not advance is still never stored or
validated, and the sender's freshness gates still retire stale
samples. The panda keeps enforcing the strict +1 sequence on the raw
bus, where it sees every frame, before passing any modified frame.

Tests: capture() unit tests for batched delivery (including wraparound
and stalled counters), and a caller-level test with jittered Throttle
batching that reaches the hold pulse -- a delivery pattern the existing
caller harness cannot represent, since it feeds exactly one frame per
message per tick. With this change the incident replay produces hold
pulses (speed=True on 45 calls, clock peak 55, 17 spoofed frames)
instead of none.
This commit is contained in:
Sam Yau
2026-11-25 12:49:58 -08:00
parent b022663e6e
commit 3670055c6b
3 changed files with 251 additions and 1 deletions
@@ -26,5 +26,5 @@ def capture(interface, packets):
and data[0] == ((address & 255) + (address >> 8) + sum(data[1:])) & 255
and (previous is None or source_ns > previous[0] and data[1] & 15 != previous[1][1] & 15)
):
state.sng_source_valid[address] = previous is not None and data[1] & 15 == ((previous[1][1] + 1) & 15)
state.sng_source_valid[address] = previous is not None and data[1] & 15 != previous[1][1] & 15
state.sng_sources[address] = (source_ns, bytes(data))
@@ -0,0 +1,127 @@
"""SNG hold pulse through the real interface/controller callers, with batched CAN delivery.
The full-stack caller harness (test_sng_callers) delivers exactly one frame per
message per tick, so the stored Throttle counter always advances by exactly one
and the 2026-11-24 standstill failure is unrepresentable in it. Here the
100 Hz Throttle source is delivered pandad-style: every fifth tick the packet
carries two Throttle frames, the CANParser accepts both, and capture() can only
store the newest -- the stored counter jumps by 2. The StopAndGo ready clock
must still reach 51 consecutive frames and emit the 3 kph hold pulse.
"""
import time as time_module
from types import SimpleNamespace
from unittest.mock import patch
from opendbc.car import Bus, gen_empty_fingerprint
from opendbc.car.subaru.interface import CarInterface
from opendbc.car.subaru.sng import prepare, selected
from opendbc.car.subaru.values import CAR
from openpilot.cereal import messaging
from openpilot.starpilot.car.subaru.sng_caller import update as sng_caller_update
from openpilot.starpilot.car.subaru.tests.caller_helpers import CompleteCan
_real_clock_gettime_ns = time_module.clock_gettime_ns
_ADDED_BOOTTIME = not hasattr(time_module, 'CLOCK_BOOTTIME')
if _ADDED_BOOTTIME:
time_module.CLOCK_BOOTTIME = 7 # Linux value; absent on macOS
_BOOTTIME = time_module.CLOCK_BOOTTIME
_virtual = {'ns': 0}
def _fake_clock_gettime_ns(clk):
if clk == _BOOTTIME:
return _virtual['ns']
return _real_clock_gettime_ns(clk)
class FakeSubMaster:
"""The three publications sng_caller gates on, always seen/valid/alive/fresh."""
SERVICES = ('carControl', 'selfdriveState', 'longitudinalPlan')
def __init__(self):
self.seen = dict.fromkeys(self.SERVICES, True)
self.valid = dict.fromkeys(self.SERVICES, True)
self.alive = dict.fromkeys(self.SERVICES, True)
self.logMonoTime = dict.fromkeys(self.SERVICES, 0)
self.recv_time = dict.fromkeys(self.SERVICES, 0.0)
def update(self, now_ns):
for name in self.SERVICES:
self.logMonoTime[name] = now_ns
self.recv_time[name] = (now_ns - 1000) / 1e9
def test_sng_hold_pulse_with_batched_throttle_delivery():
cp = CarInterface.get_params(CAR.SUBARU_IMPREZA_2020, gen_empty_fingerprint(), [], False, False, False)
prepare(cp, True)
assert selected(cp)
try:
with patch.object(time_module, 'clock_gettime_ns', _fake_clock_gettime_ns):
ci = CarInterface(cp)
stream = CompleteCan(ci)
sm = FakeSubMaster()
card = SimpleNamespace(CI=ci, CP=cp, sm=sm)
# A capnp reader, as production card passes to CI.apply (CC.update calls
# actuators.as_builder(), which the opendbc structs wrapper lacks).
control_msg = messaging.new_message('carControl', valid=True)
control_msg.carControl.enabled = True
control_msg.carControl.hudControl.leadVisible = True
cc = messaging.log_from_bytes(control_msg.to_bytes()).carControl
values = {
"Steering_Torque": {"Steer_Warning": 0},
"Steering_2": {"Steering_Angle": 0},
"Wheel_Speeds": dict.fromkeys(("FL", "FR", "RL", "RR"), 0),
"Throttle": {"Signal1": 9, "Engine_RPM": 1234, "Neutral": 1, "Signal3": 7, "Off_Accel": 3},
"Brake_Pedal": {"Brake_Pedal": 0, "Signal1": 7, "Signal2": 31, "Signal3": 1, "Signal4": 0xABCD},
"ES_Distance": {"Car_Follow": 1, "Close_Distance": 2.0},
"Brake_Status": {"Brake": 0},
"CruiseControl": {"Cruise_On": 1, "Cruise_Activated": 1},
"ES_Status": {"Cruise_Activated": 1},
"ES_DashStatus": {"Cruise_On": 1, "Cruise_Set_Speed": 60},
"Transmission": {"Gear": 121},
"Cruise_Buttons": {"Resume": 0, "Signal1": 0x12345, "Signal2": 0x12345},
}
pt_bus = ci.can_parsers[Bus.pt].bus
base_ns = 1_000_000_000_000
pulses = []
throttle_taps = []
ready_ticks = []
max_duration = 0
for tick in range(200):
now = base_ns + tick * 10_000_000
_virtual['ns'] = now
frames = []
if tick % 5 == 4:
# Packed first, so this is the older of the two Throttle frames the
# parser accepts from this tick's packet; frames() packs the newer.
frames.append(stream.packers[Bus.pt].make_can_msg('Throttle', pt_bus, values["Throttle"]))
frames.extend(stream.frames(values, tick=tick, omit=((Bus.pt, 'Brake_Pedal'),) if tick % 2 else ()))
ci.update([(now, frames)])
assert ci.CS.out.standstill
sm.update(now)
sng_caller_update(card, ci.CS.out, cc, now)
_, sends = ci.apply(cc, now)
if tick >= 20:
ready_ticks.append(bool(ci.CS.sng_lead_ready))
max_duration = max(max_duration, ci.CC.frame - ci.CC.sng_owner.last_standstill_frame)
for address, data, _bus in sends:
if address == 0x139 and data[2] == 53 and (data[3] & 15) == 0:
pulses.append(tick)
if address == 0x40 and data[4] == 5:
throttle_taps.append(tick)
# The batched ticks must not flap the lead-ready health signal...
assert sum(ready_ticks) >= 0.95 * len(ready_ticks), ready_ticks
# ...the standstill clock must run past the 51 consecutive frames the
# hold pulse requires (it peaked at 24 in the 2026-11-24 incident)...
assert max_duration > 50, max_duration
# ...and the spoofed 3 kph Brake_Pedal hold pulse must reach the wire,
# on roughly the designed 0.55 s cadence (two pulses in 2 s).
assert len(pulses) >= 2, pulses
# The departure tap must not fire: Close_Distance never enters 3.0-4.5 m.
assert not throttle_taps, throttle_taps
finally:
if _ADDED_BOOTTIME:
del time_module.CLOCK_BOOTTIME
@@ -0,0 +1,123 @@
"""capture() source validity when pandad batches a 100 Hz source message.
capture() stores at most one sample per CAN batch -- the CANParser's newest
accepted frame. When a batch carries two Throttle frames, the stored counter
therefore advances by 2, and validity must mean "the counter advanced", not
"advanced by exactly one" (the 2026-11-24 SNG standstill failure). The panda
still enforces the strict +1 sequence on the raw bus; this flag is only the
host-side health signal for the StopAndGo state machine.
"""
from types import SimpleNamespace
import pytest
from opendbc.car import Bus
from opendbc.car.subaru.sng_source import NAMES, capture
def frame(address, counter):
data = bytearray(8)
data[1] = counter & 15
data[0] = ((address & 255) + (address >> 8) + sum(data[1:])) & 255
return bytes(data)
class FakeParser:
"""Stand-in for the CANParser acceptance capture() keys on.
vl/ts_nanos always hold the newest accepted sample per message, exactly as
the real parser leaves them after consuming a batch.
"""
def __init__(self):
self.vl = {name: {'COUNTER': 0} for name in NAMES.values()}
self.ts_nanos = {name: {'COUNTER': 0} for name in NAMES.values()}
def update(self, packets):
for timestamp, frames in packets:
for address, data, bus in frames:
if address in NAMES and bus == 0:
name = NAMES[address]
self.vl[name] = {'COUNTER': data[1] & 15}
self.ts_nanos[name] = {'COUNTER': timestamp}
class Harness:
def __init__(self):
self.parser = FakeParser()
self.interface = SimpleNamespace(CS=SimpleNamespace(), can_parsers={Bus.pt: self.parser})
def feed_counters(self, timestamp, address, counters):
packets = [(timestamp, [(address, frame(address, counter), 0) for counter in counters])]
self.parser.update(packets) # production order: the parser consumes the batch first
capture(self.interface, packets)
def stored(self, address):
return self.interface.CS.sng_sources[address]
def valid(self, address):
return self.interface.CS.sng_source_valid[address]
@pytest.mark.parametrize('address', [0x40, 0x139])
def test_first_sample_is_not_valid(address):
h = Harness()
h.feed_counters(1_000_000, address, [5])
assert h.stored(address)[1][1] & 15 == 5
assert h.valid(address) is False
@pytest.mark.parametrize('address', [0x40, 0x139])
def test_sequential_advance_is_valid(address):
h = Harness()
h.feed_counters(1_000_000, address, [5])
h.feed_counters(2_000_000, address, [6])
assert h.valid(address) is True
@pytest.mark.parametrize('address', [0x40, 0x139])
def test_two_frames_in_one_batch_stay_valid(address):
# One batch carries counters 6 and 7: the parser accepts both, capture can
# only store the newest, and the stored counter jumps by 2.
h = Harness()
h.feed_counters(1_000_000, address, [5])
h.feed_counters(2_000_000, address, [6, 7])
assert h.stored(address)[1][1] & 15 == 7
assert h.valid(address) is True
h.feed_counters(3_000_000, address, [8, 9])
assert h.stored(address)[1][1] & 15 == 9
assert h.valid(address) is True
def test_stalled_counter_never_becomes_valid():
h = Harness()
h.feed_counters(1_000_000, 0x40, [5])
first = h.stored(0x40)
for timestamp in (2_000_000, 3_000_000, 4_000_000):
h.feed_counters(timestamp, 0x40, [5])
# No advance: nothing new is stored, so the sample's timestamp keeps aging
# and the sender's freshness gate retires it; it never reads valid.
assert h.stored(0x40) == first
assert h.valid(0x40) is False
def test_stalled_counter_does_not_refresh_a_valid_source():
h = Harness()
h.feed_counters(1_000_000, 0x40, [5])
h.feed_counters(2_000_000, 0x40, [6])
assert h.valid(0x40) is True
stored = h.stored(0x40)
h.feed_counters(3_000_000, 0x40, [6])
assert h.stored(0x40) == stored
def test_counter_wraparound():
h = Harness()
h.feed_counters(1_000_000, 0x40, [14])
h.feed_counters(2_000_000, 0x40, [15])
h.feed_counters(3_000_000, 0x40, [0]) # 15 -> 0 is an ordinary +1 step modulo 16
assert h.valid(0x40) is True
h.feed_counters(4_000_000, 0x40, [1, 2]) # batched across the wrap: stored counter jumps 0 -> 2
assert h.stored(0x40)[1][1] & 15 == 2
assert h.valid(0x40) is True