Repair static analysis and settings CI regressions

This commit is contained in:
firestar5683
2026-11-23 23:26:32 -06:00
parent 07331b33e8
commit d89f221d06
22 changed files with 231 additions and 212 deletions
+2 -5
View File
@@ -242,9 +242,7 @@ class Car:
def pre_create_hook(cp, candidate, fingerprints, car_fw):
initialize_aol_preference(cp)
if candidate == HYUNDAI_CAR.HYUNDAI_IONIQ_6:
# This decision must precede CarInterface parser/controller construction
# and the first CarParams publication below. The exact opt-in is
# still subject to current source and restore verification.
# Verify the opt-in before constructing the interface and publishing CarParams.
eligible = alpha_long_allowed and IONIQ6_LONG_PREARM_ENABLED and not is_release and openpilot_enabled_toggle and not self.params.get_bool("IsOffroad")
if eligible:
self.sm.update(0)
@@ -261,8 +259,7 @@ class Car:
preflight = inspect_ioniq6_long_sources(self.can_callbacks[0], ecan_bus=HyundaiCanBus(cp).ECAN)
cloudlog.event('ioniq6_long_preflight', reason=preflight.reason)
if preflight.source_period is None or preflight.vehicle_ready is not False:
# Reboot in READY retains original stock CP before CI/parsers and
# publication. Unknown evidence cannot be treated as Ready=False.
# READY or unknown keeps stock CarParams.
long_cp = None
if long_cp is not None:
initialize_aol_preference(long_cp)
+2 -1
View File
@@ -6,6 +6,7 @@ import threading
import uuid
from copy import copy
from dataclasses import replace
from typing import cast
import openpilot.cereal.messaging as messaging
@@ -1306,7 +1307,7 @@ class SelfdriveD:
self.AM.alerts.pop('aolAvailability/warning', None)
if self.aol_axis_decision.aol_speed_paused and ET.WARNING not in self.state_machine.current_alert_types:
# Preserve the existing speed warning duration even when only AOL was on.
speed_alert = copy(self.events.event_rules[EventName.speedTooHigh][ET.WARNING])
speed_alert = copy(cast(Alert, self.events.event_rules[EventName.speedTooHigh][ET.WARNING]))
speed_alert.alert_type = 'speedTooHigh/warning'
speed_alert.event_type = 'aolSpeedPause'
alerts.append(speed_alert)
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -265,9 +265,12 @@ def retain_fit_eps_intent(feedback, sm, cp, cs, axis, now_ns, *, latched, produc
if (not cs.steerFaultTemporary or grant is None or grant[:2] != (producer, epoch) or
inventory != grant[3] or not 0 < grant[2] <= now_ns <= grant[2] + SAFETY_MAX_AGE_NS):
return False
elif inventory != known[3]:
return False
feedback.fit_eps_intent = (producer, epoch, now_ns if cs.steerFaultTemporary else known[2], inventory)
source_ns = now_ns
else:
if inventory != known[3]:
return False
source_ns = now_ns if cs.steerFaultTemporary else known[2]
feedback.fit_eps_intent = (producer, epoch, source_ns, inventory)
if native.requestedLateral and not native.lateralAllowed:
feedback.honda_eps_retained_native_ns = native.observedMonoTime
return True
@@ -32,7 +32,6 @@ def _configured_transport_native(sm, cp, session, now_ns, native=None, *, requir
(require_longitudinal and native.requestedLongitudinal and str(config.safetyModel) not in ('silent', 'noOutput') and not p.controlsAllowed)
for p, config in zip(native.pandaInventory, cp.safetyConfigs, strict=True))):
return None
# v2: producer-read 200ms lease; separate BOOTTIME veto.
stamp = int(sm.logMonoTime['pandaStates'])
if not (sm.seen['pandaStates'] and sm.valid['pandaStates'] and sm.alive['pandaStates'] and
stamp > 0 and (coherent or stamp <= now_ns and now_ns - stamp <= SAFETY_MAX_AGE_NS)):
@@ -217,7 +216,6 @@ class TransportPauseFeedback:
not axis.desiredLongitudinal and not axis.longitudinalActive) and not cs.regenBraking and
cs.cruiseState.available and not cs.doorOpen and not cs.seatbeltUnlatched and
not cs.vehicleSensorsInvalid and cs.gearShifter == structs.CarState.GearShifter.drive)
# Require fresh LAT and all health/fault checks.
ford_long = bool(ford_qualified(cp, marked_only=True) and cp.openpilotLongitudinalControl)
from opendbc.car.volkswagen.long_aol import qualified as volkswagen_long_qualified
cancel_event_ns = int(sm.logMonoTime['onroadEvents'])
@@ -272,8 +270,6 @@ class TransportPauseFeedback:
log.OnroadEvent.EventName.buttonCancel)) for event in sm['onroadEvents'])):
return None
native = independent_lateral_health(sm, cp, cs, self.session, now_ns)
# Brake health may precede axis status.
# Cancel needs acknowledged LAT, original deadlines and a fresh 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 or
@@ -807,7 +803,6 @@ class TransportPauseFeedback:
native.observedMonoTime < self.lateral_native_ns or
(native.pandaSerial, tuple(p.hardwareSerial for p in native.pandaInventory)) != self.lateral_inventory):
return False
# Stock USER: LONG-off; source-zero requires LAT-only/native proof.
previous = self.signature
from openpilot.starpilot.car.toyota.aol import qualified as toyota_qualified
toyota_pedal = bool(toyota_qualified(cp, marked_only=True) and cs.brakePressed != cs.gasPressed and
@@ -830,7 +825,6 @@ class TransportPauseFeedback:
(previous[9] and previous[5] == 'none' or (self.retention_verified or self.retention_started_ns) and
previous[5] == 'availabilityPause' and previous[8] == 0 and not previous[9] and
previous[6] == axis.faultEventMonoTime) or
# Critical: matched lag only; otherwise keep pending_event.
self.lateral_only_baseline and not self.failed and not self.pending_event and
(previous[5] == 'critical' or previous[5] == 'availabilityPause' and self.ordinary_warning_retained) and
previous[1] == self.sequence and not any(previous[9:14]) and
@@ -450,7 +450,7 @@ class RemotePairingTest(unittest.TestCase):
self.assertIsNone(self.owner.current_generation())
origin = f'http://127.0.0.1:{self.local.server_port}'
cookie = self.request(self.local, '/api/auth/session')[2]['Set-Cookie'].split(';', 1)[0]
local = dict(method='POST', origin=origin, cookie=cookie)
local = {'method': 'POST', 'origin': origin, 'cookie': cookie}
pair = '/api/galaxy/pair'
new_password = {'password': 'different-password'}
self.assertEqual(self.request(self.local, pair, payload=new_password, **local)[0], 409)
@@ -31,8 +31,8 @@ def setup(tmp_path):
def row(owner, parked=True):
state = owner.snapshot(FeaturePage.VEHICLE, parked=parked, system_long=True, lateral_context=True, metric=False)
assert len(state.rows) == 1
return state.rows[0]
toggle, = (item for item in state.rows if item.key == "ToyotaAutoHold")
return toggle
def test_default_off_saved_switch_applies_after_startup_without_native_menu_link(setup):
@@ -75,7 +75,8 @@ def test_unsupported_or_changed_cp_cannot_edit_saved_switch(setup, change):
params, current, owner, _ = setup
request = replace(required_change(row(owner)), confirmation=True)
change(current.cp)
assert owner.snapshot(FeaturePage.VEHICLE, parked=True, system_long=True, lateral_context=True, metric=False).rows == ()
state = owner.snapshot(FeaturePage.VEHICLE, parked=True, system_long=True, lateral_context=True, metric=False)
assert all(item.key != "ToyotaAutoHold" for item in state.rows)
hub = owner.snapshot(FeaturePage.HUB, parked=True, system_long=True, lateral_context=True, metric=False)
assert all(item.page != FeaturePage.VEHICLE for item in hub.rows)
assert not owner.apply(request)
@@ -92,12 +93,17 @@ def test_invalid_saved_values_remain_untouched(setup, raw):
assert path.read_bytes() == raw
def gateway_hold_row(page):
index, = (i for i, item in enumerate(page["rows"]) if item["label"] == "Automatic Brake Hold")
return index
@pytest.mark.parametrize("revocation", ["cp", "bytes", "session"])
def test_gateway_existing_guard_rejects_changed_context_or_source(setup, revocation):
params, current, _, gateway = setup
page = gateway.page("vehicle", "session", b"generation")
assert page["rows"][0]["choices"] == ["Off", "On"]
intent = gateway.preview(page["view"], 0, 0, "session", b"generation", value="On")
assert page["rows"][gateway_hold_row(page)]["choices"] == ["Off", "On"]
intent = gateway.preview(page["view"], gateway_hold_row(page), 0, "session", b"generation", value="On")
if revocation == "cp":
current.raw = b"changed-cp"
elif revocation == "bytes":
@@ -117,7 +123,7 @@ def test_gateway_direct_on_off_uses_existing_value_save_path(setup):
params, _, _, gateway = setup
for value in ("On", "Off"):
page = gateway.page("vehicle", "session", b"generation")
intent = gateway.preview(page["view"], 0, 0, "session", b"generation", value=value)
intent = gateway.preview(page["view"], gateway_hold_row(page), 0, "session", b"generation", value=value)
assert "next startup" in intent["question"]
assert gateway.confirm(intent["intent"], "session", b"generation")
assert Path(params.get_param_path("ToyotaAutoHold")).read_bytes() == (b"1" if value == "On" else b"0")
@@ -130,7 +136,8 @@ def test_missing_or_changed_supported_vehicle_context_cannot_use_old_request(set
assert row(owner).available
assert not owner.apply(request)
current.cp = None
assert owner.snapshot(FeaturePage.VEHICLE, parked=True, system_long=True, lateral_context=True, metric=False).rows == ()
state = owner.snapshot(FeaturePage.VEHICLE, parked=True, system_long=True, lateral_context=True, metric=False)
assert all(item.key != "ToyotaAutoHold" for item in state.rows)
assert not owner.apply(request)
assert params.get("ToyotaAutoHold") is None
@@ -144,7 +151,7 @@ def required_change(row):
def test_gateway_saved_auto_hold_preference_remains_editable_onroad(setup):
params, current, _, gateway = setup
page = gateway.page("vehicle", "session", b"generation")
intent = gateway.preview(page["view"], 0, 0, "session", b"generation", value="On")
intent = gateway.preview(page["view"], gateway_hold_row(page), 0, "session", b"generation", value="On")
current.parked = False
assert gateway.confirm(intent["intent"], "session", b"generation")
assert Path(params.get_param_path("ToyotaAutoHold")).read_bytes() == b"1"
@@ -118,13 +118,14 @@ class Frame(dict):
def test_planner_only_relaxes_ordinary_cruise_braking(case, monkeypatch):
cp = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC)
frame = Frame(lead=case == 'lead', e2e=case == 'stop', force=case == 'force')
options = {}
cruise_ceiling = None
curve_ceiling = None
if case == 'above-limit':
frame['carState'].vEgo = LIMIT + 1.
elif case == 'slc':
options['cruise_ceiling'] = CruiseCeiling(SET_SPEED + .5, ACTIVE)
cruise_ceiling = CruiseCeiling(SET_SPEED + .5, ACTIVE)
elif case == 'curve':
options['curve_ceiling'] = CurveCeiling(SET_SPEED + .5, frame.logMonoTime['modelV2'])
curve_ceiling = CurveCeiling(SET_SPEED + .5, frame.logMonoTime['modelV2'])
elif case == 'navigation':
from openpilot.selfdrive.controls.lib import longitudinal_planner
# A navigation approach can be above SET but below the downhill allowance.
@@ -142,8 +143,8 @@ def test_planner_only_relaxes_ordinary_cruise_braking(case, monkeypatch):
normal = LongitudinalPlanner(cp, init_v=speed, init_a=.7)
coast = LongitudinalPlanner(cp, init_v=speed, init_a=.7, downhill_surplus_mps=5 * CV.MPH_TO_MS)
for _ in range(30):
normal.update(frame, now_ns=NOW, drive_id=DRIVE, **options)
coast.update(frame, now_ns=NOW, drive_id=DRIVE, **options)
normal.update(frame, now_ns=NOW, drive_id=DRIVE, cruise_ceiling=cruise_ceiling, curve_ceiling=curve_ceiling)
coast.update(frame, now_ns=NOW, drive_id=DRIVE, cruise_ceiling=cruise_ceiling, curve_ceiling=curve_ceiling)
assert coast.mpc.solution_status == normal.mpc.solution_status == 0
if case in ('clear', 'above-limit'):
assert coast.a_cruise <= 0.
@@ -192,7 +192,7 @@ def test_turn_stop_hold_reuses_planner_stop_until_standstill(sm, tmp_path):
@pytest.mark.parametrize("one_per_signal", [True, False])
@pytest.mark.parametrize("left", [True, False])
def test_turn_lane_then_turn_on_one_signal(sm, left, one_per_signal):
def test_turn_lane_then_turn_on_one_signal(sm, left, one_per_signal, monkeypatch):
from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper
from openpilot.starpilot.navigation.intent import TurnIntent, matching_turn_signal
from openpilot.starpilot.lateral.lane_change_preferences import LaneChangePolicy
@@ -205,7 +205,7 @@ def test_turn_lane_then_turn_on_one_signal(sm, left, one_per_signal):
sm.logMonoTime['longitudinalPlan'] = NOW
sm.valid['longitudinalPlan'] = sm.alive['longitudinalPlan'] = True
owner = TurnIntent()
owner.guidance = NS(sample=lambda *args, **kwargs: True)
monkeypatch.setattr(owner, 'guidance', NS(sample=lambda *args, **kwargs: True))
owner.steering_capable = True
helper = DesireHelper(LaneChangePolicy(auto_lane_change=True, auto_delay_s=.1, one_per_signal=one_per_signal))
def select():
+2 -2
View File
@@ -3,7 +3,7 @@
import os
import shutil
import stat
import time
from datetime import UTC, datetime
from pathlib import Path
from openpilot.common.hardware import COMMA_HARDWARE
@@ -57,7 +57,7 @@ def take_request(*, parked: bool, started: bool) -> bool:
return False
if not stat.S_ISDIR(marker.st_mode) or marker.st_uid != os.getuid() or stat.S_IMODE(marker.st_mode) != 0o700:
return False
fresh = 0 <= time.time() - marker.st_mtime <= 15
fresh = 0 <= datetime.now(UTC).timestamp() - marker.st_mtime <= 15
if started or not fresh or parked:
clear_request()
return fresh and parked and not started
@@ -1,5 +1,4 @@
import os
import time
import pytest
@@ -56,7 +55,7 @@ def test_requests_expire_and_are_not_replayed_or_run_while_driving(tmp_path, mon
assert not save_me.take_request(parked=False, started=True)
assert not marker.exists()
save_me.request()
old = time.time() - 60
old = marker.stat().st_mtime - 60
os.utime(marker, (old, old))
assert not save_me.take_request(parked=True, started=False)
assert not marker.exists()
@@ -0,0 +1,113 @@
"""Bounded StarPort session logging."""
import json
import os
import queue
import threading
import time
from collections import deque
from datetime import UTC, datetime
from pathlib import Path
from openpilot.starpilot.system.starport import identity as identity_store, system_slice
MAX_LOG_FILES = 20
LOG_QUEUE_MAX = 1000 # session log records waiting for the writer; past this they are dropped and counted
STALL_CAPTURE_S = 20.0 # device logs kept from before a shared-radio stall is reported
class EventLog:
"""Sanitized JSONL session log under /data/starport/logs, plus the recent tail in memory.
The streaming loop logs too, so records are queued and a background thread writes them: a slow
or full disk never stalls projection. If the writer falls behind, records are dropped and the
next one that fits is preceded by a ``log_dropped`` count.
"""
def __init__(self, directory: Path | None = None):
self.directory = directory or identity_store.LOG_DIR
self.recent: deque[dict] = deque(maxlen=40)
self.lock = threading.Lock()
self._queue: queue.Queue = queue.Queue(maxsize=LOG_QUEUE_MAX)
self._writer: threading.Thread | None = None
self._writer_stop: threading.Event | None = None
self._dropped = 0
self.path: Path | None = None
self.started = 0.0
def open(self) -> None:
try:
self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
logs = sorted(self.directory.glob("session-*.jsonl"), key=identity_store.session_log_order)
for old in logs[:max(0, len(logs) - MAX_LOG_FILES + 1)]:
old.unlink(missing_ok=True)
system_slice.prune_sidecars(self.directory)
number = max([0, *(identity_store.session_log_order(log)[0] for log in logs)]) + 1
path = self.directory / f"session-{number:06d}-{identity_store.timestamp()}.jsonl"
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
handle = os.fdopen(fd, "a")
except OSError:
return
with self.lock:
self.path, self.started = path, datetime.now(UTC).timestamp()
self._queue = queue.Queue(maxsize=LOG_QUEUE_MAX)
self._dropped = 0
self._writer_stop = threading.Event()
self._writer = threading.Thread(target=self._write, args=(handle, self._queue, self._writer_stop),
name="aa_session_log", daemon=True)
self._writer.start()
@staticmethod
def _write(handle, records: queue.Queue, stopped: threading.Event) -> None:
with handle:
while not stopped.is_set() or not records.empty():
try:
line = records.get(timeout=0.1)
except queue.Empty:
continue
try:
handle.write(line)
if records.empty():
handle.flush()
except OSError:
pass
def close(self) -> None:
"""Write what is queued, then stop the writer (bounded: a stuck disk is left to the daemon thread)."""
with self.lock:
writer, stopped = self._writer, self._writer_stop
self._writer = self._writer_stop = None
if writer is None:
return
assert stopped is not None
stopped.set()
writer.join(timeout=2.0)
def capture_system(self) -> None:
"""Save what the device was doing during this session beside its log, off the session's thread."""
if self.path is not None:
system_slice.write_sidecar_async(self.path, self.started, datetime.now(UTC).timestamp())
def capture_stall(self) -> None:
"""Save the last seconds of device logs now; the session's own capture keeps only its newest lines."""
if self.path is not None:
now = datetime.now(UTC).timestamp()
system_slice.write_sidecar_async(self.path, now - STALL_CAPTURE_S, now, tag=".stall",
on_firmware=lambda lines, reason: self("wifi_firmware_restart", lines=lines, reason=reason))
def _line(self, record: dict) -> str:
return json.dumps(record, default=str) + "\n"
def __call__(self, name: str, **values) -> None:
record = {"t": datetime.now(UTC).isoformat(timespec="milliseconds"), "event": name, "mono_s": time.monotonic(), **values}
with self.lock:
self.recent.append(record)
if self._writer is None:
return
try:
if self._dropped:
self._queue.put_nowait(self._line({"t": record["t"], "event": "log_dropped", "count": self._dropped}))
self._dropped = 0
self._queue.put_nowait(self._line(record))
except queue.Full:
self._dropped += 1
@@ -1,27 +1,11 @@
"""Android Auto session supervisor: owns every stage, deadline, retry and cleanup.
One session, started by the user or by auto-connect (see auto_connect.py), runs
in one worker thread:
idle -> connecting_bluetooth -> discovering -> rfcomm -> wifi_start -> wifi_info
-> joining_wifi -> connecting_tcp -> authenticating -> negotiating -> streaming
streaming <-> suspended (head unit showing its own screen)
failure -> cleanup -> backoff -> retry stop -> cleanup -> idle
Each attempt has a generation number; Stop cancels immediately (sockets are
closed from the caller's thread to unblock I/O). Between retries the projection
network is released without restoring the previous Wi-Fi, which happens once,
on Stop. Nothing here runs as root or touches vehicle control.
"""
"""Own Android Auto connection attempts, deadlines, retries and cleanup."""
from __future__ import annotations
import errno
import ipaddress
import json
import math
import os
import queue
import socket
import threading
import time
@@ -34,12 +18,13 @@ from typing import Any
from openpilot.common.hardware import COMMA_HARDWARE
from openpilot.starpilot.system.starport import (car_profiles, device_health, head_unit_fixes, identity as identity_store, quirk_state,
reachability, setup_ladder, system_slice)
reachability, setup_ladder)
from openpilot.starpilot.system.starport import reconnect_notice
from openpilot.starpilot.system.starport.adapter_syslog import AdapterSyslog
from openpilot.starpilot.system.starport.auto_connect import AutoConnectPolicy
from openpilot.starpilot.system.starport.bootstrap import MODERN_MAJOR, NAMES, BootstrapError, BootstrapTimeout, WirelessBootstrap
from openpilot.starpilot.system.starport.bugsink_report import PairingAttempt
from openpilot.starpilot.system.starport.event_log import EventLog
from openpilot.starpilot.system.starport.frame_source import (DEFAULT_PATH as DEFAULT_FRAME_PATH, FLAG_ASYNC_READBACK, FLAG_NV12,
FORMAT_NV12, FrameRequest)
from openpilot.starpilot.system.starport.projection_control import DEFAULT_CONTROL_SOCKET, NATIVE_FOCUS
@@ -62,8 +47,6 @@ TCP_ATTEMPTS = 6
PATIENT_TCP_SECONDS = 60.0 # owner toggle: keep retrying a refused projection connection this long
STANDARD_AA_PORT = 5288
VERSION_WAIT_SECONDS = 90.0
MAX_LOG_FILES = 20
LOG_QUEUE_MAX = 1000 # session log records waiting for the writer; past this they are dropped and counted
ENCODER_RECOVERIES = 3 # hardware encoder reopens allowed per window before the session is torn down
ENCODER_RECOVERY_WINDOW = 10.0
CAR_LINK_HOLD = 10.0 # a hands-free connection from the car counts as "car present" this long
@@ -82,7 +65,6 @@ USB_CONFIGURE_WAIT = 15.0 # slower receivers need time to enumerate after the
LINK_CHECK_INTERVAL = 1.0 # how often the link watcher asks whether the car's Wi-Fi is still up
LINK_CHECK_SLOW = 1.0 # a link check slower than this is logged (NetworkManager answers over D-Bus)
STREAM_STALL_LOG = 1.0 # a streaming loop pass slower than this is logged
STALL_CAPTURE_S = 20.0 # device logs kept from before a shared-radio stall is reported
REPORTED_SETTINGS = ("connection", "usb_mode", "view", "encoder", "fps", "bitrate_kbps", "rate_control", "gpu_nv12",
"async_readback", "wifi_interface", "dedicated_wifi_interface", "verify_head_unit", "version_status",
"rfcomm_channel", "phone_class", "auto_connect", "allow_hevc", "keyframe_test", "tall_hevc",
@@ -303,103 +285,6 @@ class LinkWatch:
self._stop.wait(self.interval)
class EventLog:
"""Sanitized JSONL session log under /data/starport/logs, plus the recent tail in memory.
The streaming loop logs too, so records are queued and a background thread writes them: a slow
or full disk never stalls projection. If the writer falls behind, records are dropped and the
next one that fits is preceded by a ``log_dropped`` count.
"""
def __init__(self, directory: Path | None = None):
self.directory = directory or identity_store.LOG_DIR
self.recent: deque[dict] = deque(maxlen=40)
self.lock = threading.Lock()
self._queue: queue.Queue = queue.Queue(maxsize=LOG_QUEUE_MAX)
self._writer: threading.Thread | None = None
self._writer_stop: threading.Event | None = None
self._dropped = 0
self.path: Path | None = None
self.started = 0.0
def open(self) -> None:
try:
self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
logs = sorted(self.directory.glob("session-*.jsonl"), key=identity_store.session_log_order)
for old in logs[:max(0, len(logs) - MAX_LOG_FILES + 1)]:
old.unlink(missing_ok=True)
system_slice.prune_sidecars(self.directory)
number = max([0, *(identity_store.session_log_order(log)[0] for log in logs)]) + 1
path = self.directory / f"session-{number:06d}-{identity_store.timestamp()}.jsonl"
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
handle = os.fdopen(fd, "a")
except OSError:
return
with self.lock:
self.path, self.started = path, datetime.now(UTC).timestamp()
self._queue = queue.Queue(maxsize=LOG_QUEUE_MAX)
self._dropped = 0
self._writer_stop = threading.Event()
self._writer = threading.Thread(target=self._write, args=(handle, self._queue, self._writer_stop),
name="aa_session_log", daemon=True)
self._writer.start()
@staticmethod
def _write(handle, records: queue.Queue, stopped: threading.Event) -> None:
with handle:
while not stopped.is_set() or not records.empty():
try:
line = records.get(timeout=0.1)
except queue.Empty:
continue
try:
handle.write(line)
if records.empty():
handle.flush()
except OSError:
pass
def close(self) -> None:
"""Write what is queued, then stop the writer (bounded: a stuck disk is left to the daemon thread)."""
with self.lock:
writer, stopped = self._writer, self._writer_stop
self._writer = self._writer_stop = None
if writer is None:
return
assert stopped is not None
stopped.set()
writer.join(timeout=2.0)
def capture_system(self) -> None:
"""Save what the device was doing during this session beside its log, off the session's thread."""
if self.path is not None:
system_slice.write_sidecar_async(self.path, self.started, datetime.now(UTC).timestamp())
def capture_stall(self) -> None:
"""Save the last seconds of device logs now; the session's own capture keeps only its newest lines."""
if self.path is not None:
now = datetime.now(UTC).timestamp()
system_slice.write_sidecar_async(self.path, now - STALL_CAPTURE_S, now, tag=".stall",
on_firmware=lambda lines, reason: self("wifi_firmware_restart", lines=lines, reason=reason))
def _line(self, record: dict) -> str:
return json.dumps(record, default=str) + "\n"
def __call__(self, name: str, **values) -> None:
record = {"t": datetime.now(UTC).isoformat(timespec="milliseconds"), "event": name, "mono_s": time.monotonic(), **values}
with self.lock:
self.recent.append(record)
if self._writer is None:
return
try:
if self._dropped:
self._queue.put_nowait(self._line({"t": record["t"], "event": "log_dropped", "count": self._dropped}))
self._dropped = 0
self._queue.put_nowait(self._line(record))
except queue.Full:
self._dropped += 1
class Supervisor:
_pairing_note = "" # why a paired car was not chosen, kept after the pairing window closes
_reset_note: dict | None = None # a handshake reset waiting for a session log to be written to
@@ -352,7 +352,8 @@ def test_session_log_never_blocks_on_a_stalled_disk(tmp_path, monkeypatch):
import threading
import time
from openpilot.starpilot.system.starport import supervisor
monkeypatch.setattr(supervisor, "LOG_QUEUE_MAX", 5)
from openpilot.starpilot.system.starport import event_log
monkeypatch.setattr(event_log, "LOG_QUEUE_MAX", 5)
release = threading.Event()
original = supervisor.EventLog._write
@@ -426,7 +427,8 @@ def test_log_and_bundle_reads_enforce_size_budgets(tmp_path, monkeypatch):
def test_session_log_full_queue_close_then_reopen_retires_old_writer(tmp_path, monkeypatch):
import threading
from openpilot.starpilot.system.starport import supervisor
monkeypatch.setattr(supervisor, "LOG_QUEUE_MAX", 2)
from openpilot.starpilot.system.starport import event_log
monkeypatch.setattr(event_log, "LOG_QUEUE_MAX", 2)
release = threading.Event()
entered = threading.Event()
original = supervisor.EventLog._write
@@ -43,7 +43,7 @@ class TestVehicleSelection(unittest.TestCase):
self.assertEqual(catalog[platform], label)
self.assertTrue(self.owner.choose(self.owner.snapshot().raw, str(platform)).verified)
candidate = startup_candidate(self.params)
self.assertEqual(candidate, platform)
assert candidate == str(platform)
cp = CarInterface.get_params(candidate, gen_empty_fingerprint(), [], False, False, False)
self.assertEqual(cp.carFingerprint, platform)
self.assertTrue(cp.pcmCruise)
@@ -0,0 +1,54 @@
"""Default values and numeric bounds for saved driving settings."""
from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET
from openpilot.starpilot.curve_speed.preferences import MASTER_KEY as CURVE_MASTER_KEY, NO_LEAD_KEY as CURVE_NO_LEAD_KEY
from openpilot.starpilot.lateral.lane_centering import STRENGTH_MAX
from openpilot.starpilot.longitudinal.downhill_coast import KEY as DOWNHILL_KEY, SURPLUS_KEY, MAX_SURPLUS_MPH
from openpilot.starpilot.longitudinal.encouragement import KEY as NUDGE_KEY
from openpilot.starpilot.longitudinal.lead_approach_runtime import KEY as LEAD_APPROACH_KEY
from openpilot.starpilot.longitudinal.lead_takeoff_preferences import KEY as LEAD_TAKEOFF_KEY
from openpilot.starpilot.longitudinal.planner_selection import KEY as PLANNER_SELECTION_KEY
from openpilot.starpilot.speed_limits.runtime_settings import WHEEL_OVERRIDE_KEY
AGGRESSIVE_COOLING_KEY = "AggressiveCoolingEnabled"
AGGRESSIVE_COOLING_DESCRIPTION = ("Runs the fan sooner and harder to keep the comma 10-16 °C (18-29 °F) cooler on hot days, " +
"at the cost of more fan noise. Applies next drive.")
BOOL_DEFAULTS = {
"GMPedalLongitudinal": False, "ForceStops": True, "AlwaysAllowUploads": False, "TurnAssist": True,
"DriveModeProfiles": False, "DriveModeAcceleration": True, "DriveModeDeceleration": True,
"SubaruAvhStartup": False,
"SubaruStopStartOff": False,
"SubaruSNG": False,
"SubaruRedneckCruise": False,
"RedneckCruise": False,
"ReverseCruise": False, "ToyotaAutoHold": False, "SNGHack": False, "JeepBrakeHold": False, "VoltSNG": False, "GMAutoHold": False, "VoltOnePedalMode": False,
"RemapCancelToDistance": False, "LongPitch": True, "DisableOpenpilotLongitudinal": False,
"SpeedLimitController": False, "ShowSpeedLimits": True,
"SLCOnEngage": False,
WHEEL_OVERRIDE_KEY: False,
"PauseLateralOnSignal": False,
"LaneCentering": True, "LaneCenteringPauseOnSignal": True,
"CustomPersonalities": False, PLANNER_SELECTION_KEY: True,
LEAD_APPROACH_KEY: False,
LEAD_TAKEOFF_KEY: False,
DOWNHILL_KEY: False,
NUDGE_KEY: True,
LOW_SPEED_CRUISE_ON_SET: False,
"DisengageOnAccelerator": False,
AGGRESSIVE_COOLING_KEY: False,
CURVE_MASTER_KEY: False, CURVE_NO_LEAD_KEY: False,
"ShowCSCStatus": False,
"ForceAutoTuneOff": False, "AlwaysOnLateral": True, "NostalgiaMode": False,
}
FLOAT_SPECS = {
SURPLUS_KEY: (0, MAX_SURPLUS_MPH, 1, "mph"),
"ForceStopDistanceOffset": (-20, 20, 1, "ft"),
"LaneCenterOffset": (-0.3, 0.3, 0.01, "m"),
"LaneCenteringE2EAuthority": (0.0, 1.0, 0.05, "fraction"),
"LaneCenteringStrength": (0.5, STRENGTH_MAX, 0.015, "fraction"),
**{f"{name}{suffix}": (0.5, 3.0, 0.05, "s")
for name in ("Aggressive", "Standard", "Relaxed") for suffix in ("Follow", "FollowHigh")},
**{f"{name}{suffix}": (25.0, 200.0, 5.0, "%")
for name in ("Aggressive", "Standard", "Relaxed")
for suffix in ("JerkAcceleration", "JerkDeceleration", "JerkDanger", "JerkSpeedDecrease", "JerkSpeed")},
}
@@ -27,7 +27,7 @@ from openpilot.starpilot.longitudinal.profile_runtime import TRAFFIC_CRUISE_BRAK
from openpilot.starpilot.longitudinal.lead_approach_runtime import KEY as LEAD_APPROACH_KEY
from openpilot.starpilot.longitudinal.lead_takeoff_preferences import KEY as LEAD_TAKEOFF_KEY
from openpilot.starpilot.longitudinal.encouragement import KEY as NUDGE_KEY
from openpilot.starpilot.longitudinal.downhill_coast import KEY as DOWNHILL_KEY, SURPLUS_KEY, MAX_SURPLUS_MPH
from openpilot.starpilot.longitudinal.downhill_coast import KEY as DOWNHILL_KEY, SURPLUS_KEY
from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET
from openpilot.starpilot.longitudinal.planner_selection import KEY as PLANNER_SELECTION_KEY, save_selection
@@ -37,6 +37,9 @@ from openpilot.starpilot.longitudinal.profile_document import (
personality_reference_curves, serialize_personality_profiles,
synchronise_profile_document_enabled,
)
from openpilot.starpilot.ui.feature_defaults import (AGGRESSIVE_COOLING_DESCRIPTION as AGGRESSIVE_COOLING_DESCRIPTION,
AGGRESSIVE_COOLING_KEY as AGGRESSIVE_COOLING_KEY,
BOOL_DEFAULTS as BOOL_DEFAULTS, FLOAT_SPECS as FLOAT_SPECS)
from openpilot.starpilot.ui.feature_settings_state import (
FeaturePage, FeatureRow, FeatureSettingsRequest, FeatureSettingsState, SLC_CONFIRM_ACTIONS, SLC_OFFSET_KEYS, TORQUE_CONFIRM_ACTIONS,
)
@@ -87,9 +90,6 @@ from openpilot.starpilot.curve_speed.actions import ACTION_KEYS as CURVE_ACTION_
from openpilot.starpilot.controllers.toyota_cruise import capability as toyota_cruise_capability
AGGRESSIVE_COOLING_KEY = "AggressiveCoolingEnabled"
AGGRESSIVE_COOLING_DESCRIPTION = ("Runs the fan sooner and harder to keep the comma 10-16 °C (18-29 °F) cooler on hot days, " +
"at the cost of more fan noise. Applies next drive.")
GLOBAL_BOOL_PREFERENCES = frozenset((LEAD_APPROACH_KEY, LEAD_TAKEOFF_KEY, NUDGE_KEY, LOW_SPEED_CRUISE_ON_SET,
"DisengageOnAccelerator", AGGRESSIVE_COOLING_KEY))
@@ -99,45 +99,6 @@ def cooling_available() -> bool:
DRIVE_MODE_KEYS = ("DriveModeProfiles", "DriveModeAcceleration", "DriveModeDeceleration")
BOOL_DEFAULTS = {
"GMPedalLongitudinal": False, "ForceStops": True, "AlwaysAllowUploads": False, "TurnAssist": True,
"DriveModeProfiles": False, "DriveModeAcceleration": True, "DriveModeDeceleration": True,
"SubaruAvhStartup": False,
"SubaruStopStartOff": False,
"SubaruSNG": False,
"SubaruRedneckCruise": False,
"RedneckCruise": False,
"ReverseCruise": False, "ToyotaAutoHold": False, "SNGHack": False, "JeepBrakeHold": False, "VoltSNG": False, "GMAutoHold": False, "VoltOnePedalMode": False,
"RemapCancelToDistance": False, "LongPitch": True, "DisableOpenpilotLongitudinal": False,
"SpeedLimitController": False, "ShowSpeedLimits": True,
"SLCOnEngage": False,
WHEEL_OVERRIDE_KEY: False,
"PauseLateralOnSignal": False,
"LaneCentering": True, "LaneCenteringPauseOnSignal": True,
"CustomPersonalities": False, PLANNER_SELECTION_KEY: True,
LEAD_APPROACH_KEY: False,
LEAD_TAKEOFF_KEY: False,
DOWNHILL_KEY: False,
NUDGE_KEY: True,
LOW_SPEED_CRUISE_ON_SET: False,
"DisengageOnAccelerator": False,
AGGRESSIVE_COOLING_KEY: False,
CURVE_MASTER_KEY: False, CURVE_NO_LEAD_KEY: False,
"ShowCSCStatus": False,
"ForceAutoTuneOff": False, "AlwaysOnLateral": True, "NostalgiaMode": False,
}
FLOAT_SPECS = {
SURPLUS_KEY: (0, MAX_SURPLUS_MPH, 1, "mph"),
"ForceStopDistanceOffset": (-20, 20, 1, "ft"),
"LaneCenterOffset": (-0.3, 0.3, 0.01, "m"),
"LaneCenteringE2EAuthority": (0.0, 1.0, 0.05, "fraction"),
"LaneCenteringStrength": (0.5, STRENGTH_MAX, 0.015, "fraction"),
**{f"{name}{suffix}": (0.5, 3.0, 0.05, "s")
for name in ("Aggressive", "Standard", "Relaxed") for suffix in ("Follow", "FollowHigh")},
**{f"{name}{suffix}": (25.0, 200.0, 5.0, "%")
for name in ("Aggressive", "Standard", "Relaxed")
for suffix in ("JerkAcceleration", "JerkDeceleration", "JerkDanger", "JerkSpeedDecrease", "JerkSpeed")},
}
SLC_PRIORITY, SLC_SECONDARY, SLC_TERTIARY = SOURCE_PRIORITY_KEYS
LONG_PREFIX = "profile:"
AOL_BUTTONS = ("LKASButtonControl", "MainCruiseButtonControl", "DistanceButtonControl",
+2 -4
View File
@@ -254,7 +254,7 @@ class StarShellSession(TeslaSpeedActions):
if slc_action_transport_enabled(os.environ, ui_state.params):
try:
self.slc_actions = SlcActionDispatcher(_slc_action_publisher(), self._live_slc_message)
# A car button (Tesla stalk or wheel) reads the car's messages with the scroll wheel's age limit.
# Car buttons share the scroll wheel age limit.
self.slc_car_actions = SlcActionDispatcher(_slc_action_publisher(), lambda now_ns: self._live_slc_message(now_ns, car_input=True))
except (OSError, RuntimeError):
pass # The shell stays readable and reports action unavailability.
@@ -290,7 +290,6 @@ class StarShellSession(TeslaSpeedActions):
self._visual_preview_flags = parse_flags(raw_preview)
self._visual_preview_start_ns = time.monotonic_ns()
self._native_favorite_actions: Callable[[], dict] = dict
# Native publisher for taps on the projected car screen.
self._publish_bookmark: Callable[[], None] | None = None
self._wheel_sock = messaging.sub_sock("slcCruiseEvent", conflate=False)
self._aol_save = None
@@ -690,7 +689,6 @@ class StarShellSession(TeslaSpeedActions):
return bool(ui_state.is_offroad() and self.adapter.confirmed_offroad())
def connectivity_allowed(self) -> bool:
# Connectivity setup also works on USB power without vehicle telemetry.
return ui_state.is_offroad()
def configuration_allowed(self) -> bool:
@@ -1393,7 +1391,7 @@ class StarShellSession(TeslaSpeedActions):
not any(p.ignitionLine or p.ignitionCan for p in pandas)):
return None
after = ui.started_frame
# plannerd revalidates actions. A car button reads with the scroll wheel's age limit.
# plannerd revalidates actions.
read = input_message if car_input else display_message
car = read(ui.sm, "carState", now_ns, after_frame=after)
control = read(ui.sm, "carControl", now_ns, after_frame=after)
@@ -48,9 +48,9 @@ def test_real_passive_scene_survives_control_reset(aol, lead_present):
snapshot = SettingsSnapshot('test', 1, stamp, stamp, DocumentState.ABSENT, SafeModeState.ABSENT_FALSE, None, None, None)
event = StatusPublisher().attach(None, proposal, snapshot, now_ns=stamp+1_000_000, drive_id=MONO, model_ns=stamp, car_state_ns=stamp)
received = messaging.log_from_bytes(event.to_bytes())
args = {'now_ns': stamp+20_000_000, 'event_ns': stamp+1_000_000, 'drive_id': MONO, 'choice': ModeChoice.CEM,
'lateral_active': True, 'selfdrive_enabled': not aol, 'car_valid': True, 'system_long': True}
value = ConditionalPerceptionProjector().project(received.slcState, **args)
value = ConditionalPerceptionProjector().project(received.slcState, now_ns=stamp+20_000_000, event_ns=stamp+1_000_000,
drive_id=MONO, choice=ModeChoice.CEM, lateral_active=True,
selfdrive_enabled=not aol, car_valid=True, system_long=True)
assert value is not None and value.perceived_stop is (not lead_present)
state = replace(aol_light(), conditional_perception=value, longitudinal_active=not aol)
assert stop_observed(state) is (not lead_present)
@@ -109,10 +109,13 @@ def test_stopped_armed_aol_shows_only_observed_stop_scene(perceived_stop):
perceived_stop=perceived_stop),
Decision(True, False, True, True, Reason.CEM_STOP, 8), None, 'inactive_axis', settings.revision)
event = StatusPublisher().attach(None, proposal, settings, now_ns=now, drive_id=drive_id, model_ns=now, car_state_ns=now)
args = {"now_ns": now, "event_ns": now, "drive_id": drive_id, "choice": ModeChoice.CEM, "lateral_active": False,
"selfdrive_enabled": False, "car_valid": True, "system_long": True}
assert ConditionalPerceptionProjector().project(event.slcState, **args) is None
result = ConditionalPerceptionProjector().project(event.slcState, **args, aol_armed_at_standstill=True)
def project(armed: bool):
return ConditionalPerceptionProjector().project(event.slcState, now_ns=now, event_ns=now, drive_id=drive_id,
choice=ModeChoice.CEM, lateral_active=False, selfdrive_enabled=False,
car_valid=True, system_long=True, aol_armed_at_standstill=armed)
assert project(False) is None
result = project(True)
assert (result is not None) == perceived_stop
assert not event.slcState.conditionalMode.hasOverride
if result is not None:
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "51265765f641a458e3d3b52679dc3b8e372fc6b72ebf5012f1e2d2f1e7e28f5c", "schema_version": 1}
{"protected_inventory_sha256": "3407390b405ee77e0cf5306b8895763472b690b9ce6781f352609d12ceb7ef2e", "schema_version": 1}