Avoid control-loop waits in settings and message reads

This commit is contained in:
firestar5683
2026-11-12 13:49:35 -06:00
parent 91782d7917
commit dbe6cf56ea
13 changed files with 241 additions and 10 deletions
Binary file not shown.
+1
View File
@@ -41,6 +41,7 @@ public:
int connect(std::string endpoint, bool conflate=false, size_t segment_size=0);
void setTimeout(int timeout);
msgq_queue_t * getQueue() {return q;}
bool fakeEventsConfigured() const {return fake_state != nullptr;}
Message *receive(bool non_blocking=false);
static SubSocket * create(std::string endpoint, bool conflate=false, size_t segment_size=0);
~SubSocket();
+4 -1
View File
@@ -75,7 +75,10 @@ NB_MODULE(_ipc, m) {
.def("setTimeout", &SubSocket::setTimeout, nb::arg("timeout"), nb::call_guard<nb::gil_scoped_release>())
.def("receive", [](SubSocket &socket, bool non_blocking) -> std::optional<nb::bytes> {
std::unique_ptr<Message> message;
{
if (non_blocking && !socket.fakeEventsConfigured()) {
// A real nonblocking receive must not wait to reacquire Python's lock.
message.reset(socket.receive(true));
} else {
nb::gil_scoped_release release;
message.reset(socket.receive(non_blocking));
}
+24
View File
@@ -0,0 +1,24 @@
#include <cstdlib>
#include <dlfcn.h>
#include <fcntl.h>
#include <unistd.h>
#include "msgq/msgq.h"
int msgq_msg_recv(msgq_msg_t *message, msgq_queue_t *queue) {
using Receive = int (*)(msgq_msg_t *, msgq_queue_t *);
using GilCheck = int (*)();
static auto original = reinterpret_cast<Receive>(dlsym(
dlopen(std::getenv("MSGQ_GIL_LIBRARY"), RTLD_NOW | RTLD_NOLOAD),
"_Z13msgq_msg_recvP10msgq_msg_tP12msgq_queue_t"));
static auto gil_check = reinterpret_cast<GilCheck>(dlsym(RTLD_DEFAULT, "PyGILState_Check"));
if (original == nullptr || original == &msgq_msg_recv || gil_check == nullptr) _exit(90);
if (queue->endpoint == "test_receive_gil") {
int fd = open(std::getenv("MSGQ_GIL_RESULT"), O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd < 0) _exit(91);
char value = gil_check() ? '1' : '0';
if (write(fd, &value, 1) != 1) _exit(92);
close(fd);
}
return original(message, queue);
}
+44
View File
@@ -0,0 +1,44 @@
import os
from pathlib import Path
import shutil
import subprocess
import sys
import pytest
import msgq._ipc
@pytest.fixture(scope="module")
def receive_gil_probe(tmp_path_factory):
if not sys.platform.startswith("linux"):
pytest.skip("LD_PRELOAD probe requires Linux")
directory = tmp_path_factory.mktemp("receive-gil")
source = Path(__file__).with_name("receive_gil_probe.cc")
library = directory / "probe.so"
compiler = shutil.which("c++")
assert compiler is not None, "Native messaging tests require a C++ compiler"
subprocess.run([compiler, "-std=c++17", "-shared", "-fPIC", str(source),
"-I", str(source.parents[2]), "-ldl", "-o", str(library)], check=True, timeout=30)
return library
@pytest.mark.parametrize(("non_blocking", "fake", "expected"), [(True, False, "1"), (False, False, "0"), (True, True, "0")])
def test_receive_only_releases_gil_when_it_can_wait(receive_gil_probe, tmp_path, non_blocking, fake, expected):
result = tmp_path / "gil"
preload = ":".join(filter(None, (os.environ.get("LD_PRELOAD"), str(receive_gil_probe))))
environment = dict(os.environ, LD_PRELOAD=preload, MSGQ_GIL_LIBRARY=msgq._ipc.__file__,
MSGQ_GIL_RESULT=str(result))
environment.pop("CEREAL_FAKE", None)
if fake:
environment["CEREAL_FAKE"] = "1"
code = f"""
import msgq
from openpilot.common.prefix import OpenpilotPrefix
with OpenpilotPrefix():
sock = msgq.sub_sock('test_receive_gil', timeout=1)
assert sock.receive(non_blocking={non_blocking!r}) is None
"""
subprocess.run([sys.executable, "-c", code], env=environment, check=True, timeout=10)
observations = result.read_text()
assert observations and set(observations) == {expected}
+4
View File
@@ -1887,6 +1887,10 @@ class Car:
if getattr(self, 'slc_transport_available', False):
self.slc_match_on_engage = self.read_slc_match_on_engage()
self.v_cruise_helper.intervals = read_cruise_intervals(self.params, self.CP)
for name in ('bluepilot_inputs', 'hands_free_cluster_input'):
source = getattr(self.CI.CC, name, None)
if source is not None:
source.refresh_settings()
pitch_input = getattr(self.CI.CC, 'long_pitch_input', None)
if pitch_input is not None:
self.CI.CC.long_pitch = pitch_input.update(time.monotonic_ns())
@@ -0,0 +1,99 @@
from types import SimpleNamespace as NS
import threading
import pytest
from openpilot.common.params import Params
from openpilot.starpilot.car.ford.bluepilot import BluePilotInputs
from openpilot.starpilot.car.ford.cluster_preferences import FordClusterPreference
from openpilot.starpilot.car.ford.controller_selection import FordController
class ModelInputs:
def __init__(self, _):
self.data = {"modelV2": NS(), "vehicleParameters": NS()}
self.seen = dict.fromkeys(self.data, False)
def __getitem__(self, name):
return self.data[name]
def update(self, _):
pass
@pytest.fixture
def inputs(tmp_path, monkeypatch):
from openpilot.starpilot.car.ford import bluepilot
monkeypatch.setattr(bluepilot.messaging, "SubMaster", ModelInputs)
params = Params(str(tmp_path))
params.put("FordPrefLateralControl", 2, block=True)
return params, BluePilotInputs(params)
def forbid_reads(params, monkeypatch):
def forbidden(*_):
raise AssertionError("Control loop read Ford settings")
monkeypatch.setattr(params, "get_param_path", forbidden)
def test_controller_refresh_frame_never_reads_params(inputs, monkeypatch):
params, owner = inputs
forbid_reads(params, monkeypatch)
owner.frames = 300
owner.update()
assert owner.controller_choice == FordController.BLUEPILOT_CURVATURE
def test_worker_publishes_mode_and_settings_together(inputs, monkeypatch):
params, owner = inputs
params.put("FordPrefLateralControl", 3, block=True)
owner.refresh_settings()
assert owner.controller_choice == FordController.BLUEPILOT_CURVATURE
forbid_reads(params, monkeypatch)
owner.frames = 300
frame = owner.update()
assert owner.controller_choice == FordController.STARPILOT
assert {p.key: p.value for p in frame.params}["FordPrefLateralControl"] == b"1"
def test_unreadable_controller_choice_still_disables_bluepilot(inputs, monkeypatch):
params, owner = inputs
with open(params.get_param_path("FordPrefLateralControl"), "wb") as stream:
stream.write(b"invalid")
owner.refresh_settings()
forbid_reads(params, monkeypatch)
owner.frames = 300
frame = owner.update()
assert owner.controller_choice is None
assert {p.key: p.value for p in frame.params}["disable_BP_lat_UI"] == b"1"
def test_cluster_refresh_frame_never_reads_params(tmp_path, monkeypatch):
params = Params(str(tmp_path))
params.put_bool("FordHandsFreeCluster", True, block=True)
owner = FordClusterPreference(params)
params.put_bool("FordHandsFreeCluster", False, block=True)
owner.refresh_settings()
assert owner.enabled
forbid_reads(params, monkeypatch)
owner.frames = 100
owner.update()
assert not owner.enabled
def test_existing_card_settings_thread_refreshes_both_ford_sources(monkeypatch):
from openpilot.selfdrive.car import card
stop = threading.Event()
refreshed = []
instance = card.Car.__new__(card.Car)
vars(instance).update(
params=NS(get_bool=lambda _: False, get=lambda *_, **__: None),
CP=NS(openpilotLongitudinalControl=True), aol_card_intent=None,
read_slc_configuration=lambda: None, v_cruise_helper=NS(),
CI=NS(CC=NS(bluepilot_inputs=NS(refresh_settings=lambda: refreshed.append("lateral")),
hands_free_cluster_input=NS(refresh_settings=lambda: refreshed.append("cluster")))),
)
monkeypatch.setattr(card, "read_cruise_intervals", lambda *_: None)
monkeypatch.setattr(card.time, "sleep", lambda _: stop.set())
instance.params_thread(stop)
assert refreshed == ["lateral", "cluster"]
+14 -5
View File
@@ -89,15 +89,24 @@ class BluePilotInputs:
self.frames = 0
self.settings = []
self.unknown_keys = set()
self.settings = self.read_settings()
self.pending_settings = (self.controller_choice, self.settings)
def read_settings(self):
self.controller_choice, entries = self._read_settings()
return entries
def refresh_settings(self):
self.pending_settings = self._read_settings()
def _read_settings(self):
entries = []
self.controller_choice = read_controller(self.cp, self.params)[0]
choice = read_controller(self.cp, self.params)[0]
for key in BP_LATERAL_PARAMS:
try:
if key == "FordPrefLateralControl":
value = int(self.controller_choice in (FordController.BLUEPILOT_ANGLE, FordController.STARPILOT))
elif key == "disable_BP_lat_UI" and self.controller_choice is None:
value = int(choice in (FordController.BLUEPILOT_ANGLE, FordController.STARPILOT))
elif key == "disable_BP_lat_UI" and choice is None:
value = True
else:
value = HOST_SETTINGS[key] if key in HOST_SETTINGS else self.params.get(key, return_default=True)
@@ -108,12 +117,12 @@ class BluePilotInputs:
continue
if value is not None:
entries.append(FrameInputs.Param(key, encode(value)))
return entries
return choice, entries
def update(self) -> FrameInputs:
self.sm.update(0)
if self.frames % SETTINGS_REFRESH_FRAMES == 0:
self.settings = self.read_settings()
self.controller_choice, self.settings = self.pending_settings
self.frames += 1
frame = FrameInputs(params=self.settings)
@@ -23,8 +23,12 @@ class FordClusterPreference:
self.params = params
self.enabled = bool(read_choice(params)[0])
self.frames = 0
self.pending_enabled = self.enabled
def refresh_settings(self):
self.pending_enabled = bool(read_choice(self.params)[0])
def update(self):
if self.frames % 100 == 0:
self.enabled = bool(read_choice(self.params)[0])
self.enabled = self.pending_enabled
self.frames += 1
@@ -133,3 +133,42 @@ def test_actual_card_published_distance_off_cannot_trigger_unconditional_persona
serialized = next(messaging.log_from_bytes(raw).carState for name, raw in instance.pm.events if name == 'carState')
assert len(serialized.buttonEvents) == 0
assert len(physical.buttonEvents) == 1
def test_idle_heartbeat_does_not_read_button_files(context, monkeypatch):
from openpilot.starpilot.controllers import wheel_actions
params, cp = context
owner = WheelPublisher(params)
owner.observe(params, cp, state(), now_ns=NOW, drive_id=DRIVE)
def forbidden_read(_):
raise AssertionError("Idle heartbeat blocked on button settings")
monkeypatch.setattr(wheel_actions, "capture", forbidden_read)
assert owner.observe(params, cp, state(), now_ns=NOW + 2_000_000_000, drive_id=DRIVE) == (("", 0),)
def test_idle_mapping_change_is_checked_before_a_new_press(context):
params, cp = context
owner = WheelPublisher(params)
owner.observe(params, cp, state(), now_ns=NOW, drive_id=DRIVE)
params.put("DistanceButtonControl", 8, block=True)
owner.observe(params, cp, state(), now_ns=NOW + 2_000_000_000, drive_id=DRIVE)
assert not any(action for _, action in owner.observe(params, cp, state(True), now_ns=NOW + 2_010_000_000, drive_id=DRIVE))
assert owner.mapping["DistanceButtonControl"] == 8
owner.observe(params, cp, state(False), now_ns=NOW + 2_020_000_000, drive_id=DRIVE)
owner.observe(params, cp, state(True), now_ns=NOW + 2_030_000_000, drive_id=DRIVE)
assert owner.observe(params, cp, state(False), now_ns=NOW + 2_040_000_000, drive_id=DRIVE) == (("DistanceButtonControl", 8),)
def test_held_button_keeps_periodic_revocation_checks(context):
params, cp = context
owner = WheelPublisher(params)
owner.observe(params, cp, state(), now_ns=NOW, drive_id=DRIVE)
owner.observe(params, cp, state(True), now_ns=NOW + 10_000_000, drive_id=DRIVE)
params.put("DistanceButtonControl", 0, block=True)
params.put("LongDistanceButtonControl", 0, block=True)
commands = owner.observe(params, cp, state(), now_ns=NOW + 1_020_000_000, drive_id=DRIVE)
assert not any(action for _, action in commands)
assert not owner.tracker.distance_held
assert owner.mapping["LongDistanceButtonControl"] == 0
@@ -186,10 +186,12 @@ class WheelPublisher:
self.suppress_distance_release = any(event.type == structs.CarState.ButtonEvent.Type.gapAdjustCruise and not event.pressed
for event in state.buttonEvents)
# Repeated neutral packets are not button edges. Keep held-input audits,
# the periodic audit, and the final read before emitted commands below.
# periodic held-input audits, and the final read before emitted commands below.
media_edge = self.media_audit_needed(media)
edge = bool(state.buttonEvents) or media_edge
audit = self.mapping is None or drive_id != self.drive or edge or now_ns - self.checked_ns >= 1_000_000_000
held = self.paddle_held or any(tracker.distance_held or tracker.media_held is not None
for tracker in (self.tracker, self.cancel_tracker, self.main_tracker))
audit = self.mapping is None or drive_id != self.drive or edge or held and now_ns - self.checked_ns >= 1_000_000_000
source_eligible = bool(eligible(cp) and state.canValid and not state.canTimeout and type(now_ns) is int and
type(drive_id) is int and 0 < drive_id < now_ns)
mapping = capture(params) if audit and source_eligible else self.mapping
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "9e1e9a03a516720700b90107a496c2768f91715ea3004fdceeee89e9767c995b", "schema_version": 1}
{"protected_inventory_sha256": "8a89731c64aaf1cb263da8ac653dc4e4b95673ac3736c5e156ee868ca739dfff", "schema_version": 1}
+2
View File
@@ -13,6 +13,8 @@ import tempfile
ROOT = Path(__file__).resolve().parents[2]
RUNNER = ROOT / 'tools/test_runner.py'
EXTRA_PYTEST_FILES = (
'msgq_repo/msgq/tests/test_receive_gil.py',
'openpilot/selfdrive/car/tests/test_ford_settings_worker.py',
'openpilot/system/tests/test_sentry.py',
'openpilot/system/ui/lib/tests/test_text_caches.py',
'openpilot/system/ui/widgets/tests/test_label_cache.py',