From 3ac334352c69e40914cd01db771a3fc130212ccc Mon Sep 17 00:00:00 2001
From: firestar5683 <168790843+firestar5683@users.noreply.github.com>
Date: Tue, 17 Nov 2026 12:30:18 -0600
Subject: [PATCH] Show learned steering values beside developer settings
---
openpilot/starpilot/galaxy/evidence.py | 3 +-
openpilot/starpilot/galaxy/settings.py | 6 +-
.../galaxy/tests/test_evidence_lifecycle.py | 1 +
.../starpilot/galaxy/web/css/settings.css | 3 +-
.../galaxy/web/js/galaxy-setting-row.js | 3 +-
openpilot/starpilot/ui/feature_settings.py | 4 +-
.../starpilot/ui/feature_settings_compact.py | 4 +-
.../starpilot/ui/feature_settings_owner.py | 10 +-
.../starpilot/ui/feature_settings_state.py | 5 +-
openpilot/starpilot/ui/learned_steering.py | 98 ++++++++++++
openpilot/starpilot/ui/runtime_app.py | 1 +
.../ui/tests/test_learned_steering.py | 145 ++++++++++++++++++
12 files changed, 272 insertions(+), 11 deletions(-)
create mode 100644 openpilot/starpilot/ui/learned_steering.py
create mode 100644 openpilot/starpilot/ui/tests/test_learned_steering.py
diff --git a/openpilot/starpilot/galaxy/evidence.py b/openpilot/starpilot/galaxy/evidence.py
index 20b902d07b..154e5d3cdf 100644
--- a/openpilot/starpilot/galaxy/evidence.py
+++ b/openpilot/starpilot/galaxy/evidence.py
@@ -18,7 +18,8 @@ class EvidenceSnapshot(SimpleNamespace):
class EvidenceSource:
- SERVICES = ('deviceState', 'pandaStates', 'carState', 'selfdriveState', 'carParams', 'peripheralState')
+ SERVICES = ('deviceState', 'pandaStates', 'carState', 'selfdriveState', 'carParams', 'peripheralState',
+ 'lateralDelay', 'lateralTorqueParameters', 'vehicleParameters')
def __init__(self, messages=None, *, mono=time.monotonic_ns,
boot=lambda: time.clock_gettime_ns(getattr(time, 'CLOCK_BOOTTIME', time.CLOCK_MONOTONIC))):
diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py
index b8688d87f5..c95b5642f5 100644
--- a/openpilot/starpilot/galaxy/settings.py
+++ b/openpilot/starpilot/galaxy/settings.py
@@ -185,7 +185,8 @@ class LiveContextSource:
return None
if self.messages is None:
from openpilot.cereal import messaging
- self.messages = messaging.SubMaster(["deviceState", "pandaStates", "carState", "selfdriveState", "carParams"])
+ self.messages = messaging.SubMaster(["deviceState", "pandaStates", "carState", "selfdriveState", "carParams",
+ "lateralDelay", "lateralTorqueParameters", "vehicleParameters"])
return cast(Callable[[], object], self.messages.snapshot)() if hasattr(self.messages, "snapshot") else self.messages
def close(self) -> None:
@@ -409,7 +410,7 @@ def _session_key(token: str) -> bytes:
def _projection(row: FeatureRow) -> dict:
return {"label": row.label, "value": row.value, "choices": list(row.choices), "step": row.step,
"minimum": row.minimum, "maximum": row.maximum, "unit": row.unit,
- "available": row.available, "reason": description(row),
+ "available": row.available, "reason": description(row), "learnedValue": row.learned_value,
"page": row.page if row.page in PAGES else "", "action": bool(row.key and row.available and not row.page),
"confirm": bool(row.key in CONFIRM_ACTIONS or is_long_confirm_action(row.key) or
row.key in (PIP_RESET, PIP_EDITOR, VASM_RESET, VASM_ANNOTATION) or row.key.startswith(PIP_FORMAT_PREFIX)),
@@ -555,6 +556,7 @@ class SettingsGateway:
fresh = self.context.sample() if live else ctx
return fresh.cp_raw == ctx.cp_raw and _qualified(fresh, group)
return FeatureSettingsOwner(self.params, authorized,
+ learning_messages=lambda: self.context._messages() if isinstance(self.context, LiveContextSource) else None,
vehicle_fingerprint=lambda: getattr(current().cp, "carFingerprint", None),
vehicle_params=lambda: current().cp,
vision_development=lambda: diagnostic_choice_enabled(os.environ, current().cp),
diff --git a/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py b/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py
index ea5947294b..2428abea02 100644
--- a/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py
+++ b/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py
@@ -28,6 +28,7 @@ class Messages:
'pandaStates': [NS(pandaType='uno', ignitionLine=ignition, ignitionCan=False, controlsAllowed=False, safetyModel='noOutput')],
'carState': NS(canValid=True, canTimeout=False, standstill=True, gearShifter='park'),
'selfdriveState': NS(enabled=False, active=False), 'carParams': NS(notCar=True), 'peripheralState': NS(pandaType=1, voltage=12640)}
+ self.data.update({service: NS() for service in ('lateralDelay', 'lateralTorqueParameters', 'vehicleParameters')})
self.seen = self.alive = self.valid = dict.fromkeys(EvidenceSource.SERVICES, True)
self.updated = dict(self.seen)
self.logMonoTime = {name: boot if name == 'pandaStates' else mono for name in EvidenceSource.SERVICES}
diff --git a/openpilot/starpilot/galaxy/web/css/settings.css b/openpilot/starpilot/galaxy/web/css/settings.css
index a8511f2c5a..8d513c32db 100644
--- a/openpilot/starpilot/galaxy/web/css/settings.css
+++ b/openpilot/starpilot/galaxy/web/css/settings.css
@@ -16,7 +16,8 @@
.gx-settings__save-status--animated { max-width: calc(100vw - 32px); margin: 0; text-align: center; opacity: 0; visibility: hidden; pointer-events: none; transition: opacity 220ms ease, visibility 0s 220ms; }
.gx-settings__save-status--animated.is-visible { opacity: 1; visibility: visible; transition-delay: 0s; }
@media (prefers-reduced-motion: reduce) { .gx-settings__save-status--animated { transition: none; } }
-.gx-slider-header { display: flex; align-items: baseline; gap: var(--sp-2); min-height: 24px; }
+.gx-slider-header { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--sp-2); min-height: 24px; }
+.gx-setting-learned { color: var(--text-secondary); font-size: var(--fs-xs); font-weight: var(--fw-medium); }
.gx-slider-hint { color: var(--text-muted); font-size: var(--fs-xs); }
.gx-row__readout { max-width: 55%; text-align: right; white-space: normal !important; overflow-wrap: anywhere; }
.gx-switch input:focus-visible + .gx-switch__track { outline: 2px solid var(--secondary); outline-offset: 4px; }
diff --git a/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js b/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js
index ac7faed7b2..b012165c69 100644
--- a/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js
+++ b/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js
@@ -243,6 +243,7 @@ export const GalaxySettingRow = {
diff --git a/openpilot/starpilot/ui/feature_settings.py b/openpilot/starpilot/ui/feature_settings.py
index 776a47ea0b..1b2880d05e 100644
--- a/openpilot/starpilot/ui/feature_settings.py
+++ b/openpilot/starpilot/ui/feature_settings.py
@@ -176,8 +176,10 @@ class FeatureSettingsView:
detail = ""
if row.page and detail in ("Saved settings", "Saved preferences", "Saved profiles"):
detail = ""
- reason = value_reason(row)
+ reason = row.reason if row.learned_value else value_reason(row)
detail += (" - " if detail and reason else "") + reason
+ if row.learned_value:
+ detail = row.learned_value + '\n' + detail
label = self._elide(row.label, FontRole.NORMAL, LABEL_SIZE, width)
# Two detail lines fit a row.
lines = [self._elide(line, FontRole.NORMAL, DETAIL_SIZE, width) for line in detail.split("\n")[:2]] if detail else []
diff --git a/openpilot/starpilot/ui/feature_settings_compact.py b/openpilot/starpilot/ui/feature_settings_compact.py
index 9a249a6aea..9cbabc907f 100644
--- a/openpilot/starpilot/ui/feature_settings_compact.py
+++ b/openpilot/starpilot/ui/feature_settings_compact.py
@@ -75,7 +75,9 @@ class FeatureSettingsCompact:
label = row.label.lower() + (" set " + row.repair_value.lower() if row.repair_value else
" −" if direction < 0 else " +" if row.step else "")
detail = value_text(row) if row.key == "LaneCenteringStrength" else (row.value + " " + row.unit).strip()
- if value_reason(row):
+ if row.learned_value:
+ detail += " · " + row.learned_value
+ elif value_reason(row):
detail += " · " + value_reason(row)
button = BigButton(label, detail)
diff --git a/openpilot/starpilot/ui/feature_settings_owner.py b/openpilot/starpilot/ui/feature_settings_owner.py
index b5847df776..bedf3348c5 100644
--- a/openpilot/starpilot/ui/feature_settings_owner.py
+++ b/openpilot/starpilot/ui/feature_settings_owner.py
@@ -154,8 +154,10 @@ class FeatureSettingsOwner:
configuration_longitudinal: Callable[[], bool] = lambda: False,
configuration_vehicle: Callable[[], bool] = lambda: False,
galaxy: Callable[[], bool] = lambda: False,
- maps_available: Callable[[], bool] | None = None):
+ maps_available: Callable[[], bool] | None = None,
+ learning_messages: Callable[[], object | None] = lambda: None):
self.params = params
+ self.learning_messages = learning_messages
self._galaxy = galaxy
self._snapshot_reads: ContextVar[dict[tuple[str, int], tuple[bytes | None, bool]] | None] = ContextVar(
"feature_snapshot_reads", default=None)
@@ -1123,7 +1125,11 @@ class FeatureSettingsOwner:
numeric_rows = tuple(row for row in numeric_rows if not row.key.startswith(('torque:full_delay:', 'torque:automatic_delay:')))
end = max((i for i, row in enumerate(numeric_rows) if row.key.startswith(('torque:factor:', 'torque:friction:'))), default=-1) + 1
numeric_rows = numeric_rows[:end] + (delay_row,) + numeric_rows[end:]
- rows.extend(numeric_rows)
+ from openpilot.starpilot.ui.learned_steering import learned_references
+ references = learned_references(self)
+ fields = {'steering_delay', 'torque:factor:value', 'torque:friction:value', 'torque:ratio:value'}
+ rows.extend(replace(row, learned_value=references.get(row.key, 'Learned · —')) if row.key in fields else row
+ for row in numeric_rows)
elif page == FeaturePage.AOL:
title = "Always On Lateral"
rows.extend(self._lateral_pause_rows(configurable))
diff --git a/openpilot/starpilot/ui/feature_settings_state.py b/openpilot/starpilot/ui/feature_settings_state.py
index 414dc6807a..c6ec94a116 100644
--- a/openpilot/starpilot/ui/feature_settings_state.py
+++ b/openpilot/starpilot/ui/feature_settings_state.py
@@ -1,6 +1,6 @@
"""Immutable saved-feature settings presentation and guarded user intent."""
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, field, replace
from enum import StrEnum
import math
from collections import deque
@@ -115,6 +115,7 @@ class FeatureRow:
presets: tuple[tuple[str, str], ...] = ()
default_reset_available: bool = False
collapsed: bool = False # a heading whose rows are hidden until it is opened
+ learned_value: str = field(default='', compare=False, repr=False)
@dataclass(frozen=True)
@@ -212,7 +213,7 @@ def lane_strength_level(row: FeatureRow) -> float | None:
def value_reason(row: FeatureRow) -> str:
if row.available and lane_strength_level(row) is not None:
return "1–10; 5 is normal. Lower values reduce centering and higher values strengthen it"
- return row.reason
+ return (row.learned_value + ' · ' + row.reason) if row.learned_value else row.reason
def value_text(row: FeatureRow) -> str:
diff --git a/openpilot/starpilot/ui/learned_steering.py b/openpilot/starpilot/ui/learned_steering.py
new file mode 100644
index 0000000000..d17ab5cad4
--- /dev/null
+++ b/openpilot/starpilot/ui/learned_steering.py
@@ -0,0 +1,98 @@
+"""Read-only estimator references for steering settings, never tuning authority."""
+import json
+import math
+import time
+
+import capnp
+from opendbc.car import structs as car
+from openpilot.cereal import log
+from openpilot.starpilot.lateral.delay_preferences import scope
+from openpilot.starpilot.schema_cache import inspect_cache
+
+ERRORS = (AttributeError, KeyError, OSError, TypeError, ValueError, OverflowError, capnp.KjException)
+
+
+def _basis(cp):
+ return (*scope(cp), float(cp.steerRatio), json.dumps(cp.lateralTuning.to_dict(), sort_keys=True), str(cp.carVin), int(cp.flags))
+
+
+def _fresh(sm, service, now, age=2_000_000_000):
+ try:
+ stamp = int(sm.logMonoTime[service])
+ received = int(sm.recv_time[service] * 1e9)
+ if (sm.seen[service] and sm.alive[service] and sm.valid[service] and
+ getattr(sm, 'after_mono_ns', 0) < stamp <= now and now - stamp <= age and 0 <= now - received <= age):
+ return sm[service]
+ except ERRORS:
+ pass
+ return None
+
+
+def _values(message, service, cp):
+ if service == 'lateralDelay':
+ value = float(message.lateralDelayEstimate)
+ if (message.version == 1 and str(message.status) == 'estimated' and message.validBlocks >= 5 and
+ math.isfinite(message.lateralDelayEstimateStd) and 0 <= message.lateralDelayEstimateStd <= .1 and .15 <= value <= .65):
+ return {'steering_delay': f'{value:.3f} s'}
+ elif service == 'lateralTorqueParameters':
+ factor, friction = float(message.latAccelFactorFiltered), float(message.frictionCoefficientFiltered)
+ if (cp.lateralTuning.which() == 'torque' and message.version == 1 and message.valid and message.totalBucketPoints > 0 and
+ math.isfinite(factor) and math.isfinite(friction) and factor > 0 and friction >= 0):
+ return {'torque:factor:value': f'{factor:.3f}', 'torque:friction:value': f'{friction:.3f}'}
+ elif service == 'vehicleParameters':
+ ratio = float(message.steerRatio)
+ if (message.valid and message.sensorValid and message.posenetValid and message.steerRatioValid and
+ .5 * cp.steerRatio <= ratio <= 2 * cp.steerRatio and abs(ratio - cp.steerRatio) > 1e-5):
+ return {'torque:ratio:value': f'{ratio:.2f}'}
+ return {}
+
+
+def _cached(owner, key):
+ raw, readable = owner._read_saved(key, 2_097_152)
+ return inspect_cache(key, raw).payload if readable else None
+
+
+def learned_references(owner, *, now_ns=None):
+ """Prefer fresh estimates; retained caches are explicitly labelled as historical."""
+ cp, result = owner.vehicle_params(), {}
+ now = time.monotonic_ns() if now_ns is None else now_ns
+ try:
+ basis = _basis(cp)
+ except ERRORS:
+ return result
+ try:
+ sm = owner.learning_messages()
+ except ERRORS:
+ sm = None
+ live_cp = _fresh(sm, 'carParams', now, 100_000_000_000)
+ device = _fresh(sm, 'deviceState', now, 10_000_000_000)
+ live, cached = False, False
+ try:
+ live = live_cp is not None and _basis(live_cp) == basis and device is not None and device.started
+ previous = _cached(owner, 'CarParamsPrevRoute')
+ if previous is not None:
+ with car.CarParams.from_bytes(previous) as prior:
+ cached = _basis(prior) == basis
+ except ERRORS:
+ pass
+ from openpilot.starpilot.lateral.gm_geometry_runtime import read_geometry
+ geometry = read_geometry(owner.params, cp)
+ manual_ratio = geometry.force_off or (geometry.profile is not None and
+ geometry.profile.ratio.mode == 'custom' and not geometry.force_auto)
+ for key, service in (('LiveDelay', 'lateralDelay'), ('LiveTorqueParameters', 'lateralTorqueParameters'),
+ ('LiveParametersV2', 'vehicleParameters')):
+ try:
+ message = _fresh(sm, service, now) if live and not (manual_ratio and service == 'vehicleParameters') else None
+ values = _values(message, service, cp) if message is not None else {}
+ if values:
+ result.update({field: 'Live learned · ' + value for field, value in values.items()})
+ elif cached:
+ payload = _cached(owner, key)
+ if payload is not None:
+ with log.Event.from_bytes(payload) as event:
+ if event.valid:
+ values = _values(getattr(event, service), service, cp)
+ result.update({field: 'Last learned · ' + value for field, value in values.items()})
+ except ERRORS:
+ continue
+ return result
diff --git a/openpilot/starpilot/ui/runtime_app.py b/openpilot/starpilot/ui/runtime_app.py
index 2a2a4cef3c..63dc9abb73 100644
--- a/openpilot/starpilot/ui/runtime_app.py
+++ b/openpilot/starpilot/ui/runtime_app.py
@@ -211,6 +211,7 @@ class StarShellSession:
home_stats=self.home_stats_source.snapshot if self.home_stats_source is not None else None)
self.galaxy_flow = GalaxyAccessFlow(self.galaxy_access, self.confirmed_offroad)
self.feature_owner = FeatureSettingsOwner(ui_state.params, self._feature_authority,
+ learning_messages=lambda: ui_state.sm,
vehicle_fingerprint=lambda: getattr(ui_state.CP, "carFingerprint", None),
vehicle_params=lambda: ui_state.CP,
vision_development=lambda: diagnostic_choice_enabled(os.environ, ui_state.CP))
diff --git a/openpilot/starpilot/ui/tests/test_learned_steering.py b/openpilot/starpilot/ui/tests/test_learned_steering.py
new file mode 100644
index 0000000000..257752157d
--- /dev/null
+++ b/openpilot/starpilot/ui/tests/test_learned_steering.py
@@ -0,0 +1,145 @@
+"""Estimator references stay scoped, truthful and separate from saved edits."""
+from dataclasses import replace
+from types import SimpleNamespace
+import json
+
+import pytest
+from opendbc.car.car_helpers import interfaces
+from openpilot.cereal import log
+from openpilot.common.params import Params
+from openpilot.starpilot.schema_cache import put_cache
+from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
+from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest, row_default
+from openpilot.starpilot.ui.learned_steering import learned_references
+
+NOW = 100_000_000_000
+
+
+class Messages(SimpleNamespace):
+ def __getitem__(self, name):
+ return self.data[name]
+
+
+def estimator_messages(cp):
+ events = {}
+ for service in ('lateralDelay', 'lateralTorqueParameters', 'vehicleParameters'):
+ event = log.Event.new_message(valid=True, logMonoTime=NOW - 100_000_000)
+ event.init(service)
+ events[service] = event
+ events['lateralDelay'].lateralDelay = {
+ 'version': 1, 'status': 'estimated', 'validBlocks': 10, 'lateralDelay': .34,
+ 'lateralDelayEstimate': .347, 'lateralDelayEstimateStd': .01}
+ events['lateralTorqueParameters'].lateralTorqueParameters = {
+ 'version': 1, 'valid': True, 'useParams': True, 'totalBucketPoints': 1000,
+ 'latAccelFactorFiltered': cp.lateralTuning.torque.latAccelFactor * .9,
+ 'frictionCoefficientFiltered': cp.lateralTuning.torque.friction * 17 / 18}
+ events['vehicleParameters'].vehicleParameters = {
+ 'valid': True, 'sensorValid': True, 'posenetValid': True, 'steerRatioValid': True, 'steerRatio': cp.steerRatio + .5}
+ return events
+
+
+def setup_sources(tmp_path, *, live=True):
+ cp = interfaces['HYUNDAI_IONIQ_6'].get_non_essential_params('HYUNDAI_IONIQ_6')
+ params = Params(str(tmp_path))
+ events = estimator_messages(cp)
+ put_cache(params, 'CarParamsPrevRoute', cp, block=True)
+ for key, service in (('LiveDelay', 'lateralDelay'), ('LiveTorqueParameters', 'lateralTorqueParameters'),
+ ('LiveParametersV2', 'vehicleParameters')):
+ put_cache(params, key, events[service], block=True)
+ data = {service: getattr(event, service) for service, event in events.items()}
+ data.update(carParams=cp, deviceState=SimpleNamespace(started=True))
+ sm = Messages(data=data, seen=dict.fromkeys(data, True), alive=dict.fromkeys(data, True), valid=dict.fromkeys(data, True),
+ logMonoTime=dict.fromkeys(data, NOW - 100_000_000), recv_time=dict.fromkeys(data, (NOW - 50_000_000) / 1e9))
+ owner = FeatureSettingsOwner(params, lambda _: True, vehicle_fingerprint=lambda: cp.carFingerprint, vehicle_params=lambda: cp,
+ learning_messages=lambda: sm if live else None)
+ return cp, params, owner, sm, events
+
+
+def test_live_estimates_do_not_replace_manual_or_default_values(tmp_path):
+ cp, params, owner, sm, _ = setup_sources(tmp_path)
+ from openpilot.starpilot.lateral.delay_preferences import KEY, replace_delay
+ params.put(KEY, json.loads(replace_delay(None, cp, .61)), block=True)
+ sm.data['lateralDelay'].lateralDelay = .61 # The applied manual projection retains the unmodified estimate.
+ references = learned_references(owner, now_ns=NOW)
+ assert references['steering_delay'] == 'Live learned · 0.347 s'
+ assert references['torque:factor:value'] == 'Live learned · 2.700'
+ assert references['torque:friction:value'] == 'Live learned · 0.085'
+ assert references['torque:ratio:value'] == f'Live learned · {cp.steerRatio + .5:.2f}'
+ row = next(row for row in owner.snapshot('torque/developer', parked=True, system_long=False,
+ lateral_context=True, metric=False).rows if row.key == 'steering_delay')
+ assert row.value == '0.61' and row.default_value == 'Automatic'
+ assert row_default(row) is not None
+
+
+@pytest.mark.parametrize('condition', ['offroad', 'old_stamp', 'old_receipt', 'invalid', 'dead', 'future', 'wrong_live_car'])
+def test_unusable_live_sources_fall_back_to_explicit_last_learned(tmp_path, condition):
+ cp, _, owner, sm, _ = setup_sources(tmp_path)
+ if condition == 'offroad':
+ sm.data['deviceState'].started = False
+ elif condition == 'wrong_live_car':
+ other = cp.as_reader().as_builder()
+ other.carVin = 'OTHER_CAR'
+ sm.data['carParams'] = other
+ elif condition == 'old_stamp':
+ sm.logMonoTime['lateralDelay'] = NOW - 3_000_000_000
+ elif condition == 'old_receipt':
+ sm.recv_time['lateralDelay'] = (NOW - 3_000_000_000) / 1e9
+ elif condition == 'future':
+ sm.logMonoTime['lateralDelay'] = NOW + 1
+ else:
+ getattr(sm, 'valid' if condition == 'invalid' else 'alive')['lateralDelay'] = False
+ assert learned_references(owner, now_ns=NOW)['steering_delay'] == 'Last learned · 0.347 s'
+
+
+@pytest.mark.parametrize('change', ['vehicle', 'controller', 'tune', 'delay', 'ratio', 'vin'])
+def test_persisted_values_require_matching_vehicle_and_controller_basis(tmp_path, change):
+ cp, _, owner, _, _ = setup_sources(tmp_path, live=False)
+ if change == 'vehicle':
+ cp.carFingerprint = 'KIA_EV6'
+ elif change == 'controller':
+ cp.lateralTuning.init('pid')
+ elif change == 'tune':
+ cp.lateralTuning.torque.latAccelFactor += .1
+ elif change == 'delay':
+ cp.steerActuatorDelay += .1
+ elif change == 'ratio':
+ cp.steerRatio += .1
+ else:
+ cp.carVin = 'OTHER_CAR'
+ assert learned_references(owner, now_ns=NOW) == {}
+
+
+@pytest.mark.parametrize('condition', ['unestimated', 'invalid', 'version', 'blocks', 'std', 'nan'])
+def test_default_or_invalid_delay_is_not_labelled_learned(tmp_path, condition):
+ _, params, owner, _, events = setup_sources(tmp_path, live=False)
+ message = events['lateralDelay'].lateralDelay
+ if condition in ('unestimated', 'invalid'):
+ message.status = condition
+ else:
+ setattr(message, {'version': 'version', 'blocks': 'validBlocks', 'std': 'lateralDelayEstimateStd',
+ 'nan': 'lateralDelayEstimate'}[condition], {'version': 2, 'blocks': 0, 'std': .2, 'nan': float('nan')}[condition])
+ put_cache(params, 'LiveDelay', events['lateralDelay'], block=True)
+ references = learned_references(owner, now_ns=NOW)
+ assert 'steering_delay' not in references
+ assert references['torque:factor:value'].startswith('Last learned')
+
+
+def test_one_broken_cache_does_not_hide_other_estimates_or_modify_data(tmp_path):
+ _, params, owner, _, _ = setup_sources(tmp_path, live=False)
+ params.put('LiveDelay', b'broken cache', block=True)
+ before = params.get('LiveDelay')
+ references = learned_references(owner, now_ns=NOW)
+ assert 'steering_delay' not in references
+ assert references['torque:friction:value'] == 'Last learned · 0.085'
+ assert params.get('LiveDelay') == before
+
+
+def test_reference_refresh_is_not_a_setting_change_or_write_dependency(tmp_path):
+ _, _, owner, _, _ = setup_sources(tmp_path, live=False)
+ row = next(row for row in owner.snapshot('torque/developer', parked=True, system_long=False,
+ lateral_context=True, metric=False).rows if row.key == 'steering_delay')
+ refreshed = replace(row, learned_value='Live learned · 0.355 s')
+ assert row == refreshed and repr(row) == repr(refreshed)
+ request = FeatureSettingsRequest(row.key, row.source, '.62', vehicle_fingerprint=row.vehicle_fingerprint,
+ capability=row.capability, dependencies=row.dependencies)
+ assert owner.apply(request)