mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 02:43:40 +08:00
Remove temporary sampling from the Card control loop
This commit is contained in:
@@ -507,18 +507,13 @@ class Car:
|
||||
def state_update(self, *, defer_radar=False) -> tuple[car.CarState, structs.RadarDataT | None]:
|
||||
"""carState update loop, driven by can"""
|
||||
|
||||
timing = getattr(self, '_cycle_timing', None)
|
||||
can_strs = messaging.drain_sock_raw(self.can_sock, wait_for_one=True)
|
||||
can_received_ns = time.monotonic_ns()
|
||||
if timing is not None:
|
||||
timing.mark('can_receive')
|
||||
can_list = can_capnp_to_list(can_strs)
|
||||
|
||||
# Update carState from CAN
|
||||
observe_controller_can(self.CI, can_list)
|
||||
CS = self.CI.update(can_list)
|
||||
if timing is not None:
|
||||
timing.mark('can_parse')
|
||||
from openpilot.starpilot.car.gm.aol import f1_conventional_lateral_owner
|
||||
cancel_boot_ns = (time.clock_gettime_ns(time.CLOCK_BOOTTIME)
|
||||
if (getattr(self.CI.CS, 'ev6_aol_source_healthy', False) or
|
||||
@@ -538,8 +533,6 @@ class Car:
|
||||
RD = None if defer_radar else self.radar_update(can_list)
|
||||
|
||||
self.sm.update(0)
|
||||
if timing is not None:
|
||||
timing.mark('service_update')
|
||||
|
||||
self.update_vehicle_state_context(CS)
|
||||
|
||||
@@ -1022,35 +1015,21 @@ class Car:
|
||||
self.pm.send('carParams', cp_send)
|
||||
self.car_params_published = True
|
||||
|
||||
timing = getattr(self, '_cycle_timing', None)
|
||||
if timing is not None:
|
||||
timing.publication_mark('begin')
|
||||
|
||||
# publish new carOutput
|
||||
co_send = messaging.new_message('carOutput')
|
||||
co_send.valid = self.sm.all_checks(['carControl'])
|
||||
co_send.carOutput.actuatorsOutput = self.last_actuators_output
|
||||
self.learning_feedback_publication = None
|
||||
if timing is not None:
|
||||
timing.publication_mark('car_output_create')
|
||||
capture = self._feedback_capture(int(co_send.logMonoTime))
|
||||
if timing is not None:
|
||||
timing.publication_mark('feedback_capture')
|
||||
if capture is not None:
|
||||
try:
|
||||
self.learning_feedback_publication = capture.publication(co_send)
|
||||
except Exception:
|
||||
capture.invalidate() # Optional observation cannot affect the original CO.
|
||||
if timing is not None:
|
||||
timing.publication_mark('feedback_publication')
|
||||
self.pm.send('carOutput', co_send)
|
||||
if timing is not None:
|
||||
timing.publication_mark('car_output_send')
|
||||
|
||||
# kick off controlsd step while we actuate the latest carControl packet
|
||||
cs_send = messaging.new_message('carState')
|
||||
if timing is not None:
|
||||
timing.publication_mark('car_state_create')
|
||||
if (self.slc_replay or self.curve_replay or getattr(self, 'conditional_replay', False)) and REPLAY and hasattr(self, 'can_log_mono_time'):
|
||||
cs_send.logMonoTime = int(self.can_log_mono_time)
|
||||
cs_send.valid = CS.canValid
|
||||
@@ -1839,16 +1818,11 @@ class Car:
|
||||
self.CC_prev = CC
|
||||
|
||||
def step(self):
|
||||
timing = getattr(self, '_cycle_timing', None)
|
||||
CS, RD = self.state_update(defer_radar=True)
|
||||
if timing is not None:
|
||||
timing.mark('state_decision')
|
||||
|
||||
if self.vehicle_startup.owner is not None:
|
||||
self.vehicle_startup.maintain(configured=self.startup_panda_configured())
|
||||
self.state_publish(CS, RD)
|
||||
if timing is not None:
|
||||
timing.mark('publish_state')
|
||||
|
||||
initialized = (not any(e.name == EventName.selfdriveInitializing for e in self.sm['onroadEvents']) and
|
||||
self.sm.seen['onroadEvents'])
|
||||
@@ -1862,13 +1836,9 @@ class Car:
|
||||
self.classic_startup_keepalive() or self.torque_ev_startup_keepalive() or self.mixed_startup_keepalive())):
|
||||
self.controls_update(CS, self.sm['carControl'], initialize_only=True)
|
||||
|
||||
if timing is not None:
|
||||
timing.mark('apply_control')
|
||||
radar_can = self._deferred_radar_can
|
||||
self._deferred_radar_can = None
|
||||
self.radar_publish(self.radar_update(radar_can))
|
||||
if timing is not None:
|
||||
timing.mark('radar')
|
||||
self.initialized_prev = initialized
|
||||
self.CS_prev = CS
|
||||
|
||||
@@ -1907,29 +1877,16 @@ class Car:
|
||||
time.sleep(0.1)
|
||||
|
||||
def card_thread(self):
|
||||
from openpilot.starpilot.diagnostics.card_timing import CardTiming
|
||||
self._cycle_timing = CardTiming(cloudlog.event)
|
||||
self.configure_conditional_settings_worker()
|
||||
e = threading.Event()
|
||||
t = threading.Thread(target=self.params_thread, args=(e, ))
|
||||
try:
|
||||
t.start()
|
||||
while True:
|
||||
timing = self._cycle_timing
|
||||
if timing is not None:
|
||||
timing.begin()
|
||||
self.vehicle_startup.check()
|
||||
if timing is not None:
|
||||
timing.mark('startup')
|
||||
self.step()
|
||||
if timing is not None:
|
||||
timing.finish()
|
||||
if not timing.enabled:
|
||||
self._cycle_timing = None
|
||||
self.rk.monitor_time()
|
||||
finally:
|
||||
if self._cycle_timing is not None:
|
||||
self._cycle_timing.close()
|
||||
e.set()
|
||||
t.join()
|
||||
if self.ioniq6_keepalive is not None:
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from types import SimpleNamespace
|
||||
from typing import cast
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
|
||||
|
||||
def test_control_loop_avoids_temporary_sampling_and_preserves_shutdown():
|
||||
calls = []
|
||||
stop = RuntimeError('stop private loop')
|
||||
keepalive = Mock()
|
||||
startup = SimpleNamespace(check=lambda: calls.append('startup'))
|
||||
def monitor():
|
||||
calls.append('monitor')
|
||||
raise stop
|
||||
owner = SimpleNamespace(configure_conditional_settings_worker=lambda: calls.append('configure'),
|
||||
params_thread=Mock(), vehicle_startup=startup,
|
||||
step=lambda: calls.append('step'), rk=SimpleNamespace(monitor_time=monitor),
|
||||
ioniq6_keepalive=keepalive, ioniq6_long_lost=False)
|
||||
with patch('openpilot.selfdrive.car.card.threading.Thread') as thread, \
|
||||
patch.dict('sys.modules', {'openpilot.starpilot.diagnostics.card_timing':
|
||||
SimpleNamespace(CardTiming=Mock(side_effect=AssertionError('realtime sampling')))}):
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
Car.card_thread(cast(Car, owner))
|
||||
assert error.value is stop
|
||||
assert calls == ['configure', 'startup', 'step', 'monitor']
|
||||
event = thread.call_args.kwargs['args'][0]
|
||||
assert event.is_set()
|
||||
thread.return_value.start.assert_called_once_with()
|
||||
thread.return_value.join.assert_called_once_with()
|
||||
assert owner.ioniq6_long_lost
|
||||
keepalive.stop.assert_called_once_with()
|
||||
@@ -1,158 +0,0 @@
|
||||
"""Temporary bounded Card phase diagnostics; never changes control policy or scheduling."""
|
||||
|
||||
import os
|
||||
import resource
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
PHASES = ("startup", "can_receive", "can_parse", "service_update", "state_decision", "publish_state", "apply_control", "radar")
|
||||
SLOW_NS = 20_000_000
|
||||
REPORT_INTERVAL_NS = 1_000_000_000
|
||||
CAPTURE_NS = 3_600_000_000_000
|
||||
MAX_REPORTS = 60
|
||||
PUBLICATION_PHASES = ("car_output_create", "feedback_capture", "feedback_publication", "car_output_send", "car_state_create")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Sample:
|
||||
wall: int
|
||||
cpu: int
|
||||
runqueue: int | None
|
||||
voluntary: int | None
|
||||
involuntary: int | None
|
||||
|
||||
|
||||
class CardTiming:
|
||||
def __init__(self, emit: Callable, sample: Callable[[], Sample] | None = None):
|
||||
self.emit = emit
|
||||
self.sample = sample or self._sample
|
||||
self.owner = threading.get_ident()
|
||||
self.fd: int | None = None
|
||||
self.schedstats_enabled = False
|
||||
self.initialized = False
|
||||
self.enabled = True
|
||||
self.deadline: int | None = None
|
||||
self.last_report: int | None = None
|
||||
self.suppressed = 0
|
||||
self.reports = 0
|
||||
self.publication_samples: list[Sample] = []
|
||||
self.samples: list[Sample] = []
|
||||
|
||||
def _sample(self) -> Sample:
|
||||
runqueue = None
|
||||
if not self.initialized:
|
||||
self.initialized = True
|
||||
try:
|
||||
with open('/proc/sys/kernel/sched_schedstats') as setting:
|
||||
self.schedstats_enabled = setting.read(8).strip() == '1'
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
self.fd = os.open('/proc/thread-self/schedstat', os.O_RDONLY | os.O_CLOEXEC)
|
||||
except OSError:
|
||||
pass
|
||||
if self.fd is not None:
|
||||
fields = os.pread(self.fd, 128, 0).split()
|
||||
if len(fields) != 3:
|
||||
raise ValueError('invalid thread schedstat')
|
||||
runqueue = int(fields[1]) if self.schedstats_enabled else None
|
||||
usage = resource.getrusage(resource.RUSAGE_THREAD) if hasattr(resource, 'RUSAGE_THREAD') else None
|
||||
return Sample(time.monotonic_ns(), time.thread_time_ns(), runqueue,
|
||||
int(usage.ru_nvcsw) if usage is not None else None,
|
||||
int(usage.ru_nivcsw) if usage is not None else None)
|
||||
|
||||
def begin(self) -> None:
|
||||
if not self.enabled:
|
||||
return
|
||||
try:
|
||||
if threading.get_ident() != self.owner or self.samples:
|
||||
raise ValueError('wrong timing thread or unfinished cycle')
|
||||
sample = self.sample()
|
||||
if self.deadline is None:
|
||||
self.deadline = sample.wall + CAPTURE_NS
|
||||
if sample.wall >= self.deadline:
|
||||
self.close()
|
||||
return
|
||||
self.samples.append(sample)
|
||||
except Exception:
|
||||
self.close()
|
||||
|
||||
def mark(self, phase: str) -> None:
|
||||
if not self.enabled or not self.samples:
|
||||
return
|
||||
try:
|
||||
index = len(self.samples) - 1
|
||||
if threading.get_ident() != self.owner or index >= len(PHASES) or phase != PHASES[index]:
|
||||
raise ValueError('invalid timing phase')
|
||||
self.samples.append(self.sample())
|
||||
except Exception:
|
||||
self.close()
|
||||
|
||||
def publication_mark(self, phase: str) -> None:
|
||||
if not self.enabled or not self.samples:
|
||||
return
|
||||
try:
|
||||
names = ("begin", *PUBLICATION_PHASES)
|
||||
if (threading.get_ident() != self.owner or len(self.samples) - 1 != PHASES.index("publish_state") or
|
||||
len(self.publication_samples) >= len(names) or phase != names[len(self.publication_samples)]):
|
||||
raise ValueError('invalid publication phase')
|
||||
self.publication_samples.append(self.sample())
|
||||
except Exception:
|
||||
self.close()
|
||||
|
||||
@staticmethod
|
||||
def _durations(names: tuple[str, ...], samples: list[Sample]) -> list[dict[str, str | int | None]]:
|
||||
phases = []
|
||||
for name, start, end in zip(names, samples[:-1], samples[1:], strict=True):
|
||||
elapsed, cpu = end.wall - start.wall, end.cpu - start.cpu
|
||||
queue = end.runqueue - start.runqueue if start.runqueue is not None and end.runqueue is not None else None
|
||||
if elapsed < 0 or cpu < 0 or queue is not None and queue < 0:
|
||||
raise ValueError('nonmonotonic timing sample')
|
||||
phases.append({'phase': name, 'wall_ns': elapsed, 'cpu_ns': cpu, 'runqueue_ns': queue,
|
||||
'other_off_cpu_ns': max(0, elapsed - cpu - queue) if queue is not None else None,
|
||||
'accounting_skew_ns': max(0, cpu + (queue or 0) - elapsed),
|
||||
'voluntary_switches': end.voluntary - start.voluntary if start.voluntary is not None and
|
||||
end.voluntary is not None else None,
|
||||
'involuntary_switches': end.involuntary - start.involuntary if start.involuntary is not None and
|
||||
end.involuntary is not None else None})
|
||||
return phases
|
||||
|
||||
def finish(self) -> None:
|
||||
if not self.enabled or not self.samples:
|
||||
return
|
||||
try:
|
||||
if len(self.samples) != len(PHASES) + 1 or threading.get_ident() != self.owner:
|
||||
raise ValueError('incomplete timing cycle')
|
||||
first, last = self.samples[0], self.samples[-1]
|
||||
wall = last.wall - first.wall
|
||||
if wall > SLOW_NS:
|
||||
if self.last_report is None or last.wall - self.last_report >= REPORT_INTERVAL_NS:
|
||||
phases = self._durations(PHASES, self.samples)
|
||||
publication = self._durations(PUBLICATION_PHASES, self.publication_samples) if self.publication_samples else []
|
||||
self.emit('card_cycle_timing', wall_ns=wall, phases=phases, publication=publication,
|
||||
suppressed=self.suppressed, report=self.reports + 1)
|
||||
self.reports += 1
|
||||
if self.reports >= MAX_REPORTS:
|
||||
self.close()
|
||||
self.last_report = last.wall
|
||||
self.suppressed = 0
|
||||
else:
|
||||
self.suppressed += 1
|
||||
self.samples.clear()
|
||||
self.publication_samples.clear()
|
||||
except Exception:
|
||||
self.close()
|
||||
|
||||
def close(self) -> None:
|
||||
self.enabled = False
|
||||
self.samples.clear()
|
||||
self.publication_samples.clear()
|
||||
if self.fd is not None:
|
||||
try:
|
||||
os.close(self.fd)
|
||||
except OSError:
|
||||
pass
|
||||
self.fd = None
|
||||
@@ -1,165 +0,0 @@
|
||||
"""Bounded numeric publication diagnostics preserve Card outputs and error propagation."""
|
||||
import json
|
||||
from types import SimpleNamespace as NS
|
||||
from typing import cast
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.starpilot.diagnostics import card_timing as module
|
||||
from openpilot.starpilot.diagnostics.card_timing import CardTiming, Sample, PHASES
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.wall = 0
|
||||
|
||||
def __call__(self):
|
||||
self.wall += 10_000
|
||||
return Sample(self.wall, self.wall // 4, None, None, None)
|
||||
|
||||
|
||||
def cycle(timing, publish=None):
|
||||
timing.begin()
|
||||
for phase in PHASES:
|
||||
if phase == 'publish_state' and publish is not None:
|
||||
publish()
|
||||
timing.mark(phase)
|
||||
timing.finish()
|
||||
|
||||
|
||||
def test_late_outlier_is_captured_after_initial_ten_minutes():
|
||||
clock, emit = Clock(), Mock()
|
||||
timing = CardTiming(emit, clock)
|
||||
cycle(timing)
|
||||
clock.wall += 735_000_000_000
|
||||
def stall():
|
||||
clock.wall += 78_000_000
|
||||
cycle(timing, stall)
|
||||
assert timing.enabled
|
||||
emit.assert_called_once()
|
||||
phase = next(p for p in emit.call_args.kwargs['phases'] if p['phase'] == 'publish_state')
|
||||
assert phase['wall_ns'] >= 78_000_000
|
||||
clock.wall = module.CAPTURE_NS + 10_000
|
||||
timing.begin()
|
||||
assert not timing.enabled and not timing.samples and timing.fd is None
|
||||
|
||||
|
||||
def test_report_and_memory_budgets_stop_probe_without_restart():
|
||||
clock, emit = Clock(), Mock()
|
||||
timing = CardTiming(emit, clock)
|
||||
for _ in range(module.MAX_REPORTS):
|
||||
clock.wall += module.REPORT_INTERVAL_NS
|
||||
cycle(timing, lambda: setattr(clock, 'wall', clock.wall + 25_000_000))
|
||||
assert emit.call_count == module.MAX_REPORTS
|
||||
assert not timing.enabled and not timing.samples and not timing.publication_samples
|
||||
assert timing.fd is None
|
||||
timing.sample = Mock(side_effect=AssertionError('closed probe cannot sample'))
|
||||
cycle(timing)
|
||||
timing.sample.assert_not_called()
|
||||
|
||||
|
||||
def card_fixture(clock, delay, fail_send=False):
|
||||
from openpilot.cereal import messaging
|
||||
from opendbc.car.structs import car
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
sent = []
|
||||
trace = []
|
||||
def wait(phase):
|
||||
trace.append(phase)
|
||||
if delay == phase:
|
||||
clock.wall += 78_000_000
|
||||
def send(topic, message):
|
||||
if topic == 'carOutput':
|
||||
wait('car_output_send')
|
||||
if fail_send:
|
||||
raise RuntimeError('original send failure')
|
||||
payload = message.to_dict()
|
||||
payload.pop('logMonoTime')
|
||||
sent.append((topic, payload))
|
||||
def capture(_stamp):
|
||||
wait('feedback_capture')
|
||||
return NS(publication=lambda _message: wait('feedback_publication'), invalidate=Mock())
|
||||
fake = NS(CP=car.CarParams.new_message(brand='mock'), CI=NS(CS=NS()), car_params_published=True,
|
||||
sm=NS(frame=1, all_checks=lambda _names: True), pm=NS(send=send),
|
||||
last_actuators_output=messaging.new_message('carOutput').carOutput.actuatorsOutput,
|
||||
can_rcv_cum_timeout_counter=0, _feedback_capture=capture, rk=NS(remaining=.01), slc_replay=False, curve_replay=False,
|
||||
aol_replay=False, v_cruise_helper=NS(toyota=None, slc_cruise_change=None),
|
||||
car_gps_publisher=NS(update=lambda *_: None), publish_traffic_receipt=lambda _: None,
|
||||
radar_publish=lambda _: None)
|
||||
original = messaging.new_message
|
||||
def new_message(topic, *args, **kwargs):
|
||||
if topic in ('carOutput', 'carState'):
|
||||
wait('car_output_create' if topic == 'carOutput' else 'car_state_create')
|
||||
return original(topic, *args, **kwargs)
|
||||
def publish():
|
||||
with patch.object(messaging, 'new_message', side_effect=new_message):
|
||||
Car.state_publish(cast(Car, fake), car.CarState.new_message(canValid=True), None)
|
||||
return fake, publish, sent, trace
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase', ('car_output_create', 'feedback_capture', 'feedback_publication',
|
||||
'car_output_send', 'car_state_create'))
|
||||
def test_actual_card_publishing_subphases_identify_stall_and_keep_outputs(phase):
|
||||
clock, emit = Clock(), Mock()
|
||||
timing = CardTiming(emit, clock)
|
||||
fake, publish, sent, trace = card_fixture(clock, phase)
|
||||
fake._cycle_timing = timing
|
||||
cycle(timing, publish)
|
||||
assert timing.enabled
|
||||
data = emit.call_args.kwargs
|
||||
assert [p['phase'] for p in data['publication']] == list(module.PUBLICATION_PHASES)
|
||||
delayed = [p['phase'] for p in data['publication'] if p['wall_ns'] >= 78_000_000]
|
||||
assert delayed == [phase]
|
||||
assert all(p['runqueue_ns'] is None for p in data['publication'])
|
||||
assert len(json.dumps(data)) < 8192
|
||||
assert set(data) == {'wall_ns', 'phases', 'publication', 'suppressed', 'report'}
|
||||
assert all(set(p) == {'phase', 'wall_ns', 'cpu_ns', 'runqueue_ns', 'other_off_cpu_ns',
|
||||
'accounting_skew_ns', 'voluntary_switches', 'involuntary_switches'}
|
||||
for p in data['phases'] + data['publication'])
|
||||
expected_trace = ['car_output_create', 'feedback_capture', 'feedback_publication',
|
||||
'car_output_send', 'car_state_create']
|
||||
assert trace == expected_trace
|
||||
assert [topic for topic, _ in sent] == ['carOutput', 'carState']
|
||||
del fake._cycle_timing
|
||||
old = list(sent)
|
||||
sent.clear()
|
||||
trace.clear()
|
||||
publish()
|
||||
assert sent == old and trace == expected_trace
|
||||
assert not timing.samples and not timing.publication_samples
|
||||
|
||||
|
||||
@pytest.mark.parametrize('probe_failure', (False, True))
|
||||
def test_real_card_send_errors_propagate_with_enabled_or_failed_probe(probe_failure):
|
||||
clock = Clock()
|
||||
timing = CardTiming(Mock(), clock)
|
||||
fake, publish, _, _ = card_fixture(clock, '', fail_send=True)
|
||||
fake._cycle_timing = timing
|
||||
if probe_failure:
|
||||
timing.sample = Mock(side_effect=OSError('sample unavailable'))
|
||||
with pytest.raises(RuntimeError, match='original send failure'):
|
||||
cycle(timing, publish)
|
||||
timing.close()
|
||||
assert not timing.enabled and not timing.samples and not timing.publication_samples
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ('order', 'thread', 'partial', 'nonmonotonic'))
|
||||
def test_publication_probe_validation_never_invents_complete_measurements(failure):
|
||||
clock, emit = Clock(), Mock()
|
||||
timing = CardTiming(emit, clock)
|
||||
def publish():
|
||||
timing.publication_mark('begin')
|
||||
if failure == 'order':
|
||||
timing.publication_mark('arbitrary phase')
|
||||
elif failure == 'thread':
|
||||
timing.owner = -1
|
||||
timing.publication_mark('car_output_create')
|
||||
elif failure == 'nonmonotonic':
|
||||
clock.wall -= 1_000_000
|
||||
for name in module.PUBLICATION_PHASES:
|
||||
timing.publication_mark(name)
|
||||
clock.wall += 78_000_000
|
||||
cycle(timing, publish)
|
||||
assert not timing.enabled and not timing.samples and not timing.publication_samples
|
||||
emit.assert_not_called()
|
||||
@@ -1,181 +0,0 @@
|
||||
"""Bounded diagnostic accounting and actual Card call order, without vehicle output."""
|
||||
|
||||
from types import SimpleNamespace as NS
|
||||
from typing import cast
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.starpilot.diagnostics.card_timing import CardTiming, Sample, PHASES, CAPTURE_NS
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self, queue=True):
|
||||
self.wall = 0
|
||||
self.queue = queue
|
||||
|
||||
def __call__(self):
|
||||
self.wall += 3_000_000
|
||||
return Sample(self.wall, self.wall // 3, self.wall // 6 if self.queue else None,
|
||||
self.wall // 3_000_000, 0)
|
||||
|
||||
|
||||
def cycle(timing):
|
||||
timing.begin()
|
||||
for phase in PHASES:
|
||||
timing.mark(phase)
|
||||
timing.finish()
|
||||
|
||||
|
||||
def test_slow_cycle_separates_cpu_runqueue_and_unattributed_off_cpu():
|
||||
emit = Mock()
|
||||
timing = CardTiming(emit, Clock())
|
||||
cycle(timing)
|
||||
emit.assert_called_once()
|
||||
assert emit.call_args.args == ('card_cycle_timing',)
|
||||
data = emit.call_args.kwargs
|
||||
assert data['wall_ns'] == 24_000_000
|
||||
assert len(data['phases']) == len(PHASES)
|
||||
assert [p['phase'] for p in data['phases']] == list(PHASES)
|
||||
for phase in data['phases']:
|
||||
assert (phase['wall_ns'], phase['cpu_ns'], phase['runqueue_ns'], phase['other_off_cpu_ns']) == (
|
||||
3_000_000, 1_000_000, 500_000, 1_500_000)
|
||||
assert phase['voluntary_switches'] == 1
|
||||
assert not timing.samples
|
||||
|
||||
|
||||
def test_unknown_runqueue_is_not_reported_as_zero_or_as_proven_blocking():
|
||||
emit = Mock()
|
||||
cycle(CardTiming(emit, Clock(queue=False)))
|
||||
assert all(p['runqueue_ns'] is None and p['other_off_cpu_ns'] is None for p in emit.call_args.kwargs['phases'])
|
||||
|
||||
|
||||
def test_capture_and_report_rates_are_bounded_and_keep_suppression_count():
|
||||
clock, emit = Clock(), Mock()
|
||||
timing = CardTiming(emit, clock)
|
||||
for _ in range(30):
|
||||
cycle(timing)
|
||||
assert len(timing.samples) == 0
|
||||
assert emit.call_count == 1
|
||||
clock.wall += 1_000_000_000
|
||||
cycle(timing)
|
||||
assert emit.call_count == 2
|
||||
assert emit.call_args.kwargs['suppressed'] == 29
|
||||
clock.wall = CAPTURE_NS + 3_000_000
|
||||
timing.begin()
|
||||
assert not timing.enabled and not timing.samples
|
||||
timing.sample = Mock(side_effect=AssertionError('closed probe must do no work'))
|
||||
cycle(timing)
|
||||
timing.sample.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['sample', 'phase', 'thread', 'incomplete', 'logger'])
|
||||
def test_diagnostic_failures_disable_only_the_probe(failure):
|
||||
timing = CardTiming(Mock(), Clock())
|
||||
if failure == 'sample':
|
||||
timing.sample = Mock(side_effect=OSError('unavailable'))
|
||||
timing.begin()
|
||||
elif failure == 'phase':
|
||||
timing.begin()
|
||||
timing.mark('arbitrary phase')
|
||||
elif failure == 'thread':
|
||||
timing.owner = -1
|
||||
timing.begin()
|
||||
elif failure == 'incomplete':
|
||||
timing.begin()
|
||||
timing.finish()
|
||||
else:
|
||||
timing.emit = Mock(side_effect=OSError('logger unavailable'))
|
||||
cycle(timing)
|
||||
assert not timing.enabled and not timing.samples
|
||||
|
||||
|
||||
def test_schedstat_reads_are_bounded_and_descriptor_is_closed_once():
|
||||
with patch('builtins.open') as opened, patch('os.open', return_value=17) as fd_open, \
|
||||
patch('os.pread', return_value=b'100 200 3') as read, patch('os.close') as close:
|
||||
opened.return_value.__enter__.return_value.read.return_value = '0\n'
|
||||
timing = CardTiming(Mock())
|
||||
timing.begin()
|
||||
timing.mark('startup')
|
||||
assert timing.samples[0].runqueue is None
|
||||
fd_open.assert_called_once()
|
||||
assert read.call_args.args == (17, 128, 0)
|
||||
timing.close()
|
||||
timing.close()
|
||||
close.assert_called_once_with(17)
|
||||
|
||||
|
||||
def test_missing_proc_counters_still_capture_wall_and_thread_cpu():
|
||||
with patch('builtins.open', side_effect=FileNotFoundError), patch('os.open', side_effect=FileNotFoundError):
|
||||
timing = CardTiming(Mock())
|
||||
timing.begin()
|
||||
timing.mark('startup')
|
||||
assert timing.enabled and len(timing.samples) == 2
|
||||
assert timing.samples[0].runqueue is None
|
||||
assert timing.samples[1].wall >= timing.samples[0].wall
|
||||
assert timing.samples[1].cpu >= timing.samples[0].cpu
|
||||
timing.close()
|
||||
|
||||
|
||||
def test_actual_card_step_preserves_action_order_with_optional_marks():
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
trace = []
|
||||
timing = NS(mark=lambda phase: trace.append(phase))
|
||||
fake = NS(_cycle_timing=timing, vehicle_startup=NS(owner=None), CP=NS(passive=False),
|
||||
sm={'onroadEvents': [], 'carControl': object()}, _deferred_radar_can=object())
|
||||
fake.sm = type('SM', (dict,), {'seen': {'onroadEvents': True}})(fake.sm)
|
||||
fake.state_update = lambda **_: trace.append('state_update') or (object(), None)
|
||||
fake.state_publish = lambda *_: trace.append('publish')
|
||||
fake.controls_update = lambda *_: trace.append('control')
|
||||
fake.radar_update = lambda _: trace.append('radar_update')
|
||||
fake.radar_publish = lambda _: trace.append('radar_publish')
|
||||
Car.step(cast(Car, fake))
|
||||
assert trace == ['state_update', 'state_decision', 'publish', 'publish_state', 'control',
|
||||
'apply_control', 'radar_update', 'radar_publish', 'radar']
|
||||
del fake._cycle_timing
|
||||
trace.clear()
|
||||
Car.step(cast(Car, fake))
|
||||
assert trace == ['state_update', 'publish', 'control', 'radar_update', 'radar_publish']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fail_startup', [False, True])
|
||||
def test_actual_card_loop_keeps_control_errors_and_cleans_probe(fail_startup):
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
|
||||
class StopLoop(Exception):
|
||||
pass
|
||||
|
||||
probe = Mock(enabled=True)
|
||||
startup = Mock(side_effect=StopLoop('startup')) if fail_startup else Mock()
|
||||
fake = NS(configure_conditional_settings_worker=Mock(), params_thread=Mock(),
|
||||
vehicle_startup=NS(check=startup), step=Mock(), rk=NS(monitor_time=Mock(side_effect=StopLoop('monitor'))),
|
||||
ioniq6_keepalive=None)
|
||||
with patch.dict('os.environ', {}, clear=True), \
|
||||
patch('threading.Thread'), patch('openpilot.starpilot.diagnostics.card_timing.CardTiming', return_value=probe) as factory:
|
||||
with pytest.raises(StopLoop, match='startup' if fail_startup else 'monitor'):
|
||||
Car.card_thread(cast(Car, fake))
|
||||
assert factory.call_count == 1
|
||||
assert fake.step.call_count == int(not fail_startup)
|
||||
assert probe.close.call_count == 1
|
||||
assert probe.begin.call_count == 1
|
||||
assert probe.finish.call_count == int(not fail_startup)
|
||||
|
||||
|
||||
def test_actual_card_loop_removes_expired_capture_without_restarting_it():
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
|
||||
class StopLoop(Exception):
|
||||
pass
|
||||
|
||||
sample = Mock(return_value=Sample(CAPTURE_NS, 0, None, None, None))
|
||||
probe = CardTiming(Mock(), sample)
|
||||
probe.deadline = CAPTURE_NS
|
||||
fake = NS(configure_conditional_settings_worker=Mock(), params_thread=Mock(), vehicle_startup=NS(check=Mock()),
|
||||
step=Mock(), rk=NS(monitor_time=Mock(side_effect=[None, StopLoop()])), ioniq6_keepalive=None)
|
||||
with patch('threading.Thread'), patch('openpilot.starpilot.diagnostics.card_timing.CardTiming', return_value=probe):
|
||||
with pytest.raises(StopLoop):
|
||||
Car.card_thread(cast(Car, fake))
|
||||
assert fake._cycle_timing is None
|
||||
assert not probe.enabled and not probe.samples and probe.fd is None
|
||||
assert fake.step.call_count == 2
|
||||
sample.assert_called_once()
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "3fc1c9715af0c620260cd839db49b3c38758f0282d66a421de28c55102496120", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "61b9fe1a645717974ef042e20e162ea7400b1fc9feef4681efcf226af5cba2a1", "schema_version": 1}
|
||||
|
||||
Reference in New Issue
Block a user