mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-03 22:23:41 +08:00
Review unidentified FLM drives without mixing vehicle tunes
This commit is contained in:
@@ -136,7 +136,7 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
|
||||
start_time = time.monotonic()
|
||||
if not skip_fw_query:
|
||||
if cached_params is not None and cached_params.brand != "mock" and len(cached_params.carFw) > 0 and \
|
||||
(cached_params.carVin != VIN_UNKNOWN or os.environ.get("REPLAY")) and not disable_fw_cache:
|
||||
((is_valid_vin(cached_params.carVin) and cached_params.carVin != VIN_UNKNOWN) or os.environ.get("REPLAY")) and not disable_fw_cache:
|
||||
carlog.warning("Using cached CarParams")
|
||||
vin_rx_addr, vin_rx_bus, vin = -1, -1, cached_params.carVin
|
||||
car_fw = list(cached_params.carFw)
|
||||
|
||||
@@ -114,6 +114,8 @@ class StatusReport:
|
||||
return value if type(value) is int and 0 <= value < 2**63 else 0
|
||||
|
||||
details: dict[str, Any] = {'Analysis runs while parked': True, 'Next-drive trial is reversible': True, 'Physical road improvement proven': False}
|
||||
if value.get('vehicle_identity') == 'unavailable':
|
||||
details['Recorded vehicle identity'] = 'unavailable'
|
||||
if self.diagnostics is not None and self.diagnostics.error:
|
||||
details['Diagnostic persistence error'] = self.diagnostics.error
|
||||
if value.get('skipped_routes'):
|
||||
|
||||
@@ -476,6 +476,8 @@ def analyze_latest(params, root, previous, *, permitted, selected_route=None, ev
|
||||
from openpilot.starpilot.flm.offroad_history import combine
|
||||
|
||||
identity = history_identity(collected.state['cp'])
|
||||
if identity is None:
|
||||
return single # Review this recording without pooling unidentified physical cars.
|
||||
skips = []
|
||||
try:
|
||||
history = evidence_bank.retain(collected, route, identity, permitted=permitted)
|
||||
|
||||
@@ -11,6 +11,12 @@ from openpilot.starpilot.flm.offroad_store import RouteScope, startup_row
|
||||
from openpilot.starpilot.flm.offroad_surface import RouteSurfaceEffects, STOP_REASONS, stop_marker
|
||||
|
||||
|
||||
class VehicleIdentityUnavailable(ValueError):
|
||||
def __init__(self, review_key):
|
||||
super().__init__('vehicle_identity_unavailable')
|
||||
self.review_key = review_key
|
||||
|
||||
|
||||
def configuration_data(cp, ci, controller, params, *, manual_status):
|
||||
from opendbc.car.vin import VIN_UNKNOWN, is_valid_vin
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import (
|
||||
@@ -24,8 +30,8 @@ def configuration_data(cp, ci, controller, params, *, manual_status):
|
||||
from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, LEGACY_KEYS, MAX_DOCUMENT_BYTES, parse_document, interpret_legacy
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
|
||||
if manual_status not in ('not_configured', 'configured') or not is_valid_vin(str(cp.carVin)) or str(cp.carVin) == VIN_UNKNOWN:
|
||||
raise ValueError('Known vehicle and valid manual coordinate settings required')
|
||||
if manual_status not in ('not_configured', 'configured'):
|
||||
raise ValueError('Valid manual coordinate settings required')
|
||||
descriptor = selected_descriptor(cp, ci, controller)
|
||||
if descriptor is None or descriptor.domain not in ('torque', 'torque_pid'):
|
||||
raise ValueError('Actual registered torque controller required')
|
||||
@@ -107,11 +113,15 @@ def configuration_data(cp, ci, controller, params, *, manual_status):
|
||||
epoch = digest(('persistent_vehicle_source_v1', descriptor.cp_sha256, tuple((k, None if raw[k] is None else raw[k].hex()) for k in keys
|
||||
if k != 'SteeringDelayPreferences' or raw[k] is not None), str(cp.carVin)))
|
||||
numeric = baseline_values(controller)
|
||||
if tuple((key, read_saved(params, key, MAX_DOCUMENT_BYTES)) for key in keys) != snapshots:
|
||||
raise ValueError('Steering settings changed during startup')
|
||||
if not is_valid_vin(str(cp.carVin)) or str(cp.carVin) == VIN_UNKNOWN:
|
||||
# This key guards a read-only review; it is never a persistent vehicle scope.
|
||||
raise VehicleIdentityUnavailable(digest(('unidentified_route_review_v1', descriptor.cp_sha256, descriptor.controller_revision,
|
||||
baseline_revision(descriptor, numeric), epoch, reset)))
|
||||
scope = RouteScope(
|
||||
descriptor.cp_sha256, descriptor.controller_revision, baseline_revision(descriptor, numeric), epoch, reset, descriptor.controller_mode, descriptor.domain
|
||||
).validate()
|
||||
if tuple((key, read_saved(params, key, MAX_DOCUMENT_BYTES)) for key in keys) != snapshots:
|
||||
raise ValueError('Steering settings changed during startup')
|
||||
return scope, numeric, fixed_manual
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ from openpilot.starpilot.flm.offroad_cache import AssessmentCache, MAX_CHECKPOIN
|
||||
from openpilot.starpilot.flm.offroad_checks import qualify
|
||||
from openpilot.starpilot.flm.offroad_processor import analyze_latest, CompletedAssessment
|
||||
from openpilot.starpilot.flm.offroad_route import latest_route, logger_marker, route_inventory, source_revisions, RouteInputError, LOCAL_ID
|
||||
from openpilot.starpilot.flm.offroad_runtime import current_configuration as _current_configuration
|
||||
from openpilot.starpilot.flm.offroad_runtime import current_configuration as _current_configuration, VehicleIdentityUnavailable
|
||||
from openpilot.starpilot.flm.offroad_store import RouteScope, RouteStorage, KEY, MAX_BYTES, MAX_ROUTE_STEP, NAMESPACE
|
||||
from openpilot.starpilot.flm.offroad_surface import REVISION, current_revision, revision_for_manual
|
||||
from openpilot.starpilot.flm.offroad_tracking import TrackingEstimate, compare_observed
|
||||
@@ -705,6 +705,10 @@ class OffroadWorker:
|
||||
self.evidence_bank = EvidenceBank(self.cache.directory)
|
||||
|
||||
def _history_identity(self, cp):
|
||||
try:
|
||||
scope = self.scope_for(cp, self.params)
|
||||
except VehicleIdentityUnavailable:
|
||||
return None
|
||||
settings = []
|
||||
for key in SETTINGS:
|
||||
if key == KEY:
|
||||
@@ -713,7 +717,7 @@ class OffroadWorker:
|
||||
if not okay:
|
||||
raise ValueError('Unreadable evidence history setting')
|
||||
settings.append((key, None if raw is None else hashlib.sha256(raw).hexdigest()))
|
||||
return _digest((self.scope_for(cp, self.params).document(), settings))
|
||||
return _digest((scope.document(), settings))
|
||||
|
||||
def _snapshot(self, route):
|
||||
values = []
|
||||
@@ -806,11 +810,15 @@ class OffroadWorker:
|
||||
state = {}
|
||||
|
||||
def prior(cp):
|
||||
scope = self.scope_for(cp, self.params)
|
||||
try:
|
||||
scope = self.scope_for(cp, self.params)
|
||||
except VehicleIdentityUnavailable as error:
|
||||
scope = None
|
||||
state['review_identity'] = error.review_key
|
||||
raw, okay = read_saved(self.params, KEY, MAX_BYTES)
|
||||
if not okay:
|
||||
raise ValueError('Unreadable automatic tuning history')
|
||||
row = decode(raw).get(NAMESPACE, {}).get(scope.key())
|
||||
row = None if scope is None else decode(raw).get(NAMESPACE, {}).get(scope.key())
|
||||
state.update(scope=scope, raw=raw, row=row)
|
||||
from openpilot.starpilot.flm.manual_coordinates import selected_manual
|
||||
manual = selected_manual(cp, self.params)
|
||||
@@ -849,9 +857,16 @@ class OffroadWorker:
|
||||
prior(assessment.cp)
|
||||
scope, row, expected = state['scope'], state['row'], state['raw']
|
||||
|
||||
def settings_current():
|
||||
try:
|
||||
current_scope = self.scope_for(assessment.cp, self.params)
|
||||
return scope is not None and current_scope == scope
|
||||
except VehicleIdentityUnavailable as error:
|
||||
return scope is None and error.review_key == state.get('review_identity')
|
||||
|
||||
def authorized():
|
||||
if not (
|
||||
self.permitted() and self.scope_for(assessment.cp, self.params) == scope
|
||||
self.permitted() and settings_current()
|
||||
and logger_marker(self.params) == self.pending_logger and source_revisions(self.root, route) == revisions
|
||||
and latest_route(self.params, self.root, permitted=self.permitted, inventory_only=True) == latest
|
||||
):
|
||||
@@ -885,11 +900,27 @@ class OffroadWorker:
|
||||
partial_segments=[len(assessment.receipt.decoded_segments), len(assessment.receipt.segments)],
|
||||
omitted_segments=[list(row) for row in assessment.receipt.omitted_segments])
|
||||
report = assessment.report()
|
||||
report.update(policy=POLICY, current_scope=scope.document(), road_improvement_confirmed=False)
|
||||
report.update(policy=POLICY, road_improvement_confirmed=False)
|
||||
if scope is not None:
|
||||
report['current_scope'] = scope.document()
|
||||
locked = state.get('locked', {})
|
||||
current = dict(ZERO) | state.get('starting', {}) if row is None else dict(row['values'])
|
||||
recorded['recommendations'] = recorded_recommendations(assessment, current, report)
|
||||
|
||||
if scope is None:
|
||||
recommendations = [r for r in recorded['recommendations'] if r['parameter'] not in locked]
|
||||
report['vehicle_identity'] = 'unavailable'
|
||||
result = {**recorded, 'status': 'collecting', 'reason': 'vehicle_identity_unavailable', 'vehicle_identity': 'unavailable',
|
||||
'configuration_changed': False, 'actual_application_proven': False, 'road_improvement_confirmed': False,
|
||||
'saved_adjustments': 0, 'manual_locked_parameters': list(locked), 'recommendations': recommendations,
|
||||
'recommendation_count': len(recommendations),
|
||||
'assessment_sha256': self.cache.put({'kind': 'identity_review', 'assessment': report})}
|
||||
if not authorized() or read_saved(self.params, KEY, MAX_BYTES) != (expected, True):
|
||||
raise RouteInputCancelled('Recording or settings changed before identity-limited review')
|
||||
self.cache.checkpoint({'input_fingerprint': self._snapshot(route), 'result': result})
|
||||
self.pending_failure_data = None
|
||||
return result # No fit, persistent evidence, trial resolution, profile load or Params write.
|
||||
|
||||
choices = []
|
||||
for group in assessment.groups:
|
||||
metadata = group['original_metadata']
|
||||
|
||||
@@ -636,3 +636,132 @@ class TestPartialDriveReview(unittest.TestCase):
|
||||
walk_partial_route(root, inventory, permitted=lambda: True, consume=lambda n, events: first.write_bytes(b'changed'))
|
||||
with self.assertRaises(RouteInputCancelled):
|
||||
walk_partial_route(root, inventory, permitted=lambda: False, consume=lambda *args: None)
|
||||
|
||||
|
||||
class TestUnidentifiedVehicleReview(unittest.TestCase):
|
||||
"""Declared Sonata recordings; no historical identity or accepted tune is invented."""
|
||||
|
||||
@staticmethod
|
||||
def setup(directory, *, vin='00000000000000000', counter=18):
|
||||
import math
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.hyundai.values import CAR
|
||||
from openpilot.starpilot.lateral.learning_preferences import replace_preference
|
||||
from openpilot.starpilot.lateral.controller_selection import replace_mode
|
||||
|
||||
root = Path(directory)
|
||||
params = Params(str(root / 'params'))
|
||||
cp = interfaces[CAR.HYUNDAI_SONATA_HYBRID].get_non_essential_params(CAR.HYUNDAI_SONATA_HYBRID)
|
||||
cp.carVin = vin
|
||||
params.put_bool('OpenpilotEnabledToggle', True, block=True)
|
||||
params.put('SteeringLearningPreferences', replace_preference(None, cp, True), block=True)
|
||||
params.put('LateralControllerSelection', json.loads(replace_mode(None, cp, 'starpilot')), block=True)
|
||||
route = f'{counter:08x}--aaaaaaaaaa'
|
||||
folder = root / 'logs' / (route + '--0')
|
||||
folder.mkdir(parents=True)
|
||||
messages = [log.Event.new_message(logMonoTime=1_000_000_000, valid=True, carParams=cp).to_bytes()]
|
||||
for index in range(1201):
|
||||
stamp = 1_000_000_000 + index * 10_000_000
|
||||
event = log.Event.new_message(logMonoTime=stamp, valid=True)
|
||||
state = event.init('carState')
|
||||
state.vEgo, state.canValid = 20., True
|
||||
messages.append(event.to_bytes())
|
||||
event = log.Event.new_message(logMonoTime=stamp, valid=True)
|
||||
control = event.init('carControl')
|
||||
control.latActive, control.actuators.torque = True, .1
|
||||
messages.append(event.to_bytes())
|
||||
event = log.Event.new_message(logMonoTime=stamp, valid=True)
|
||||
torque = event.init('controlsState').lateralControlState.init('torqueState')
|
||||
torque.active = True
|
||||
torque.desiredLateralAccel = .6 + .05 * math.sin(index / 75)
|
||||
torque.actualLateralAccel = .75 * torque.desiredLateralAccel
|
||||
messages.append(event.to_bytes())
|
||||
event = log.Event.new_message(logMonoTime=13_010_000_000, valid=True)
|
||||
event.init('clocks').wallTimeNanos = 1_800_000_000_000_000_000 + counter * 1_000_000_000
|
||||
messages.append(event.to_bytes())
|
||||
event = log.Event.new_message(logMonoTime=13_010_000_000, valid=True)
|
||||
event.init('sentinel').type = 'endOfRoute'
|
||||
messages.append(event.to_bytes())
|
||||
(folder / 'rlog.bz2').write_bytes(bz2.compress(b''.join(messages)))
|
||||
params.put('CurrentRoute', route, block=True)
|
||||
params.put('RouteCount', counter + 1, block=True)
|
||||
return params, cp, root / 'logs'
|
||||
|
||||
def test_actual_sonata_configuration_has_precise_identity_refusal_and_stable_review_guard(self):
|
||||
from openpilot.common.prefix import OpenpilotPrefix
|
||||
from openpilot.starpilot.flm.offroad_runtime import current_scope, configure, _current_controller, VehicleIdentityUnavailable
|
||||
|
||||
with OpenpilotPrefix(), tempfile.TemporaryDirectory() as directory:
|
||||
params, cp, _ = self.setup(directory)
|
||||
with self.assertRaises(VehicleIdentityUnavailable) as first:
|
||||
current_scope(cp, params)
|
||||
self.assertEqual(str(first.exception), 'vehicle_identity_unavailable')
|
||||
with self.assertRaises(VehicleIdentityUnavailable) as second:
|
||||
current_scope(cp, params)
|
||||
self.assertEqual(first.exception.review_key, second.exception.review_key)
|
||||
params.put('AutoSteeringLearningReset', '1', block=True)
|
||||
with self.assertRaises(VehicleIdentityUnavailable) as changed:
|
||||
current_scope(cp, params)
|
||||
self.assertNotEqual(first.exception.review_key, changed.exception.review_key)
|
||||
ci, controller = _current_controller(cp, params)
|
||||
owner, status = configure(cp, ci, controller, params, manual_status='not_configured')
|
||||
self.assertIsNone(owner)
|
||||
self.assertEqual(status, 'configuration_unavailable')
|
||||
cp.carVin = 'KMHL341JBLU000001'
|
||||
self.assertIsNotNone(current_scope(cp, params))
|
||||
params.put_bool('OpenpilotEnabledToggle', False, block=True)
|
||||
with self.assertRaisesRegex(ValueError, 'Main controls disabled'):
|
||||
current_scope(cp, params)
|
||||
|
||||
def test_original_unknown_vin_route_is_reviewed_without_pooling_fitting_or_touching_saved_profiles(self):
|
||||
from openpilot.common.prefix import OpenpilotPrefix
|
||||
from openpilot.starpilot.flm.offroad_store import RouteStorage
|
||||
from openpilot.starpilot.flm.offroad_history import EvidenceBank
|
||||
|
||||
with OpenpilotPrefix(), tempfile.TemporaryDirectory() as directory:
|
||||
params, _, root = self.setup(directory)
|
||||
cache = Path(directory) / 'cache'
|
||||
saved = fixtures.TestSavedSetupCapacity.row(1)
|
||||
self.assertTrue(RouteStorage(params).save(saved, expected=None, authorized=lambda: True))
|
||||
original = params.get(KEY)
|
||||
with patch.object(EvidenceBank, 'retain', side_effect=AssertionError('Unidentified cars must never be pooled')):
|
||||
worker = OffroadWorker(params, root, cache, permitted=lambda: True,
|
||||
checker=lambda *a, **k: self.fail('An unidentified car must never enter automatic qualification'))
|
||||
result = worker.run_once()
|
||||
self.assertEqual(result['reason'], 'vehicle_identity_unavailable')
|
||||
self.assertEqual(result['analysis_counts']['recorded_tracking'], 1201)
|
||||
self.assertGreater(result['analysis_counts']['diagnostic_whole_windows'], 0)
|
||||
self.assertTrue(result['recorded_tracking']['points'])
|
||||
self.assertGreater(result['recommendation_count'], 0)
|
||||
self.assertFalse(result['configuration_changed'])
|
||||
self.assertFalse(result['actual_application_proven'])
|
||||
self.assertEqual(result['skipped_routes'], [])
|
||||
self.assertEqual(params.get(KEY), original)
|
||||
doc = worker.cache.get(result['assessment_sha256'])
|
||||
self.assertEqual(doc['kind'], 'identity_review')
|
||||
self.assertNotIn('current_scope', doc['assessment'])
|
||||
with patch.object(worker, 'assessor', side_effect=AssertionError('An unchanged recording must reuse its checkpoint')):
|
||||
self.assertEqual(worker.run_once()['assessment_sha256'], result['assessment_sha256'])
|
||||
self.assertEqual(params.get(KEY), original)
|
||||
|
||||
def test_invalid_cached_vin_is_queried_again_instead_of_reusing_an_empty_identity(self):
|
||||
from opendbc.car import car_helpers
|
||||
from opendbc.car.hyundai.values import CAR
|
||||
fresh_vin = 'KMHL341JBLU000001'
|
||||
for cached_vin, expected_queries in (('', 1), ('invalid', 1), ('00000000000000000', 1), (fresh_vin, 0)):
|
||||
with self.subTest(vin=cached_vin), patch.dict(os.environ, {}, clear=True):
|
||||
cp = car_helpers.interfaces[CAR.HYUNDAI_SONATA_HYBRID].get_non_essential_params(CAR.HYUNDAI_SONATA_HYBRID)
|
||||
cp.carVin = cached_vin
|
||||
cp.carFw = [{'ecu': 'engine', 'fwVersion': b'declared-version', 'address': 0x7e0}]
|
||||
with (patch.object(car_helpers, 'normal_bus_query_brand', return_value=None),
|
||||
patch.object(car_helpers, 'honda_normal_bus_topology', return_value=False),
|
||||
patch.object(car_helpers, 'chrysler_normal_bus_topology', return_value=False),
|
||||
patch.object(car_helpers, 'get_vin', return_value=(0x7e8, 0, fresh_vin)) as query,
|
||||
patch.object(car_helpers, 'get_present_ecus', return_value=set()),
|
||||
patch.object(car_helpers, 'get_fw_versions_ordered', return_value=[]),
|
||||
patch.object(car_helpers, 'match_fw_to_car', return_value=(True, {CAR.HYUNDAI_SONATA_HYBRID})),
|
||||
patch.object(car_helpers, 'can_fingerprint', return_value=(CAR.HYUNDAI_SONATA_HYBRID, {})),
|
||||
patch.object(car_helpers, 'automatic_bolt_candidate', side_effect=lambda candidate, *a: candidate)):
|
||||
result = car_helpers.fingerprint(lambda **k: [], lambda *a: None, lambda *a: None, cp)
|
||||
self.assertEqual(query.call_count, expected_queries)
|
||||
self.assertEqual(result[2], fresh_vin)
|
||||
|
||||
@@ -533,6 +533,22 @@ class DriveStatsOwner:
|
||||
return {identifier: self._records[identifier]['startTime'] for identifier in route_ids
|
||||
if identifier in self._records and self._records[identifier].get('startTime') is not None}
|
||||
|
||||
def diagnostics(self) -> dict:
|
||||
"""Existing worker/cache state only; no routes, locations or new instrumentation."""
|
||||
with self._lock:
|
||||
reasons = defaultdict(int)
|
||||
for failed in self._failures.values():
|
||||
reason = failed['reason']
|
||||
safe = reason in SOURCE_LIMITATIONS or reason in ('OSError', 'ValueError', 'RuntimeError', 'FileNotFoundError',
|
||||
'PermissionError', 'TimeoutError', 'RouteInputError', 'KeyError')
|
||||
reasons[reason if safe else 'route_analysis_error'] += 1
|
||||
return {'status': 'readable', 'scheduler_running': self._scheduler is not None and self._scheduler.is_alive(),
|
||||
'worker_running': self._worker is not None and self._worker.is_alive(),
|
||||
'analysis_permitted': self._allowed(), 'scanned': self._scanned, 'scan_incomplete': self._scan_incomplete,
|
||||
'pending': self._pending, 'cached_routes': len(self._records),
|
||||
'complete_routes': sum(r['complete'] for r in self._records.values()), 'failed_routes': len(self._failures),
|
||||
'cache_corrupt': self._corrupt, 'failure_reasons': dict(reasons)}
|
||||
|
||||
def snapshot(self, timezone: str = "UTC") -> dict:
|
||||
with self._lock:
|
||||
result = self._snapshot_locked(timezone)
|
||||
|
||||
@@ -59,6 +59,8 @@ def accept_finding(settings, reports, payload, *, authorized):
|
||||
if not directory.exists():
|
||||
raise ValueError('The original drive review is unavailable. Refresh the findings.')
|
||||
document = AssessmentCache(directory).get(assessment)
|
||||
if document.get('kind') == 'identity_review':
|
||||
raise ValueError('The vehicle must identify itself before a finding from this review can be accepted.')
|
||||
route = document['assessment']['route']
|
||||
if (document.get('kind') not in ('completed_assessment', 'partial_assessment') or
|
||||
route['cp_sha256'] != car_params_digest(cp) or route['source_sha256'] != found[1]):
|
||||
|
||||
@@ -36,6 +36,11 @@ def _explanation(reason):
|
||||
'more_independent_eligible_tracking_required': 'Analysis needs more independent, eligible steering evidence before proposing a change.',
|
||||
'recorded_tracking_suggestion_not_yet_qualified_for_automatic_application':
|
||||
'Analysis produced suggestions; the evidence required for automatic saving is not complete.',
|
||||
'vehicle_identity_unavailable': 'This recording was reviewed on its own. A physical vehicle identity was unavailable, so no saved tune was loaded, ' +
|
||||
'no cross-drive evidence was combined and no adjustment was saved automatically.',
|
||||
'Known vehicle and no manual coordinates required': 'This older build rejected its vehicle/settings identity before route analysis. In the parked ' +
|
||||
'analysis path, missing or invalid recorded vehicle identity causes this refusal; it does not establish route corruption.',
|
||||
'Valid manual coordinate settings required': 'Saved manual steering settings require review; existing choices were preserved.',
|
||||
'partial_drive_provisional_only': 'Intact portions were analyzed. This partial recording can provide suggestions, not automatic changes.',
|
||||
'bounded_trial_configured_for_next_drive': 'A bounded adjustment was saved for the next drive.',
|
||||
'no_consistent_adjustment_in_completed_drive': 'The analyzed evidence did not support a consistent adjustment.',
|
||||
@@ -73,7 +78,7 @@ def diagnostics(report, params):
|
||||
'Recorded steering observations', 'Retained control windows', 'Retained tracking windows', 'Recorded drive coverage',
|
||||
'Drives in steering evidence history', 'Saved route adjustment count', 'Saved route configuration state',
|
||||
'Recorded coordinate recommendations', 'Recorded suggestion sources', 'Controller and encoder check windows', 'Automatic tune refusal reasons',
|
||||
'Drive analysis is partial', 'Partial drive segments', 'Omitted recorded segments') if key in details}
|
||||
'Recorded vehicle identity', 'Drive analysis is partial', 'Partial drive segments', 'Omitted recorded segments') if key in details}
|
||||
result['current']['skipped_drives'] = _result({'skipped_routes': details.get('Skipped recorded drives', [])})['skipped_drives']
|
||||
if params is None:
|
||||
result['storage'] = {'status': 'unavailable'}
|
||||
@@ -164,3 +169,23 @@ def download(report, params):
|
||||
return _reason(value) if type(value) is str else value
|
||||
|
||||
return 'starpilot-flm-logs.json', json.dumps(clean(diagnostics(report, params)), indent=2, allow_nan=False).encode()
|
||||
|
||||
|
||||
def with_dashboard_diagnostics(body, owner, authority=None):
|
||||
"""Attach privacy-limited existing dashboard state without starting its analyzer."""
|
||||
summary = {'status': 'not_started'}
|
||||
if owner is not None:
|
||||
try:
|
||||
summary = owner.diagnostics()
|
||||
except (AttributeError, OSError, RuntimeError, ValueError, TypeError):
|
||||
summary = {'status': 'unavailable'}
|
||||
if authority is not None:
|
||||
try:
|
||||
state = authority.status()
|
||||
summary['vehicle_permission'] = {'allowed': state['allowed'], 'reason': _reason(state.get('reason') or 'available'),
|
||||
'effective_started': authority.effective()}
|
||||
except (AttributeError, OSError, RuntimeError, ValueError, TypeError, KeyError):
|
||||
summary['vehicle_permission'] = {'allowed': False, 'reason': 'Vehicle status unavailable'}
|
||||
result = json.loads(body)
|
||||
result['dashboard_statistics'] = summary
|
||||
return json.dumps(result, indent=2, allow_nan=False).encode()
|
||||
|
||||
@@ -1411,6 +1411,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
self.json(400, {'error': 'Unexpected FLM log query'})
|
||||
return
|
||||
filename, body = training_results_source.download()
|
||||
from openpilot.starpilot.galaxy.flm_diagnostics import with_dashboard_diagnostics
|
||||
body = with_dashboard_diagnostics(body, drive_stats_source, getattr(server, 'drive_stats_authority', None))
|
||||
if self.require_session():
|
||||
self.attachment(filename, body, 'application/json; charset=utf-8')
|
||||
elif path == '/api/flm/training-results':
|
||||
|
||||
@@ -156,7 +156,8 @@ assert.doesNotMatch(FlmPage.template, /gx-tuner__plots-link/)
|
||||
const acceptanceContext = { mode: 'local', preference: { valid: true, enabled: true, parked: true, controller: 'torque' },
|
||||
current: { fresh: true }, error: '', manualBusy: false }
|
||||
assert.equal(FlmPage.computed.canAcceptFindings.call(acceptanceContext), true)
|
||||
for (const change of [{ manualBusy: true }, { current: { fresh: false } }, { mode: 'remote' },
|
||||
for (const change of [{ current: { fresh: true, reason: 'vehicle_identity_unavailable' } },
|
||||
{ manualBusy: true }, { current: { fresh: false } }, { mode: 'remote' },
|
||||
...['parked', 'enabled', 'valid'].map(key => ({ preference: { ...acceptanceContext.preference, [key]: false } })),
|
||||
{ preference: { ...acceptanceContext.preference, controller: 'pid' } }])
|
||||
assert.equal(FlmPage.computed.canAcceptFindings.call({ ...acceptanceContext, ...change }), false)
|
||||
|
||||
@@ -102,3 +102,38 @@ class TestDiagnostics(unittest.TestCase):
|
||||
server.shutdown()
|
||||
thread.join(timeout=2)
|
||||
server.server_close()
|
||||
|
||||
|
||||
class TestIdentityAndDashboardDiagnostics(unittest.TestCase):
|
||||
def test_identity_refusal_explains_review_without_claiming_automatic_learning(self):
|
||||
report = {'current': {'status': 'collecting', 'reason': 'vehicle_identity_unavailable', 'details': {
|
||||
'Recorded vehicle identity': 'unavailable', 'Recorded steering observations': 1201}}}
|
||||
result = json.loads(download(report, None)[1])
|
||||
self.assertEqual(result['current']['analysis']['Recorded vehicle identity'], 'unavailable')
|
||||
self.assertIn('no saved tune was loaded', result['current']['explanation'])
|
||||
self.assertEqual(result['saved_profiles'], [])
|
||||
|
||||
def test_dashboard_export_shows_existing_failures_and_permission_without_route_or_private_data(self):
|
||||
from openpilot.starpilot.galaxy.drive_stats import DriveStatsOwner
|
||||
from openpilot.starpilot.galaxy.flm_diagnostics import with_dashboard_diagnostics
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
owner = DriveStatsOwner(root=root, store=root / 'stats.json', permitted=lambda: False)
|
||||
try:
|
||||
owner._scanned = True
|
||||
owner._failures = {'private-route-location': {'reason': 'End of route was not recorded'},
|
||||
'secret-route': {'reason': 'private-secret path /data/secret'}}
|
||||
authority = SimpleNamespace(status=lambda: {'allowed': False, 'reason': 'Vehicle status unavailable'}, effective=lambda: None)
|
||||
body = with_dashboard_diagnostics(download({}, None)[1], owner, authority)
|
||||
data = json.loads(body)['dashboard_statistics']
|
||||
self.assertEqual(data['failed_routes'], 2)
|
||||
self.assertFalse(data['analysis_permitted'])
|
||||
self.assertFalse(data['vehicle_permission']['allowed'])
|
||||
self.assertEqual(data['failure_reasons'], {'End of route was not recorded': 1, 'route_analysis_error': 1})
|
||||
self.assertNotIn(b'private-route', body)
|
||||
self.assertNotIn(b'private-secret', body)
|
||||
self.assertIsNone(owner._scheduler)
|
||||
self.assertFalse(owner.store.exists())
|
||||
self.assertEqual(json.loads(with_dashboard_diagnostics(download({}, None)[1], None))['dashboard_statistics']['status'], 'not_started')
|
||||
finally:
|
||||
owner.close()
|
||||
|
||||
@@ -257,6 +257,7 @@ const REASONS = {
|
||||
accepted_target_currently_acknowledged: "The controller acknowledged the accepted correction.",
|
||||
}
|
||||
export function learningReason(reason) {
|
||||
if (reason === 'vehicle_identity_unavailable') return 'This drive was reviewed on its own. Automatic saving is waiting for the car to identify itself.'
|
||||
if (reason === "Assessment cache full") return "FLM ran out of space in its review history. The latest analysis could not be saved; this does not mean your saved tune was erased."
|
||||
if (Object.hasOwn(REASONS, reason)) return REASONS[reason]
|
||||
const pattern = /^observed_(understeer|oversteer|late_turn_in|early_turn_in|unwind_too_slow|unwind_too_fast|low_speed_unwillingness|center_chatter|notchy_mid_curve)_(left|right|center)$/.exec(reason)
|
||||
|
||||
@@ -86,7 +86,8 @@ export const FlmPage = {
|
||||
document.removeEventListener("visibilitychange", this.visibility)
|
||||
},
|
||||
computed: {
|
||||
canAcceptFindings() { return this.mode === 'local' && this.preference?.valid === true && this.preference.enabled === true &&
|
||||
canAcceptFindings() { return this.current?.reason !== 'vehicle_identity_unavailable' && this.mode === 'local' &&
|
||||
this.preference?.valid === true && this.preference.enabled === true &&
|
||||
this.preference.parked === true && this.preference.controller === 'torque' && this.current?.fresh === true && !this.error && !this.manualBusy },
|
||||
manualRows() { return (this.manualState.data?.rows || []).map((row, index) => ({ row, index })).filter(({ row }) => this.selectedGroup.names.includes(row.coordinate)) },
|
||||
recoveredManualCurve() { return (this.manualState.data?.rows || []).filter(row => FRICTION_NAMES.includes(row.coordinate)) },
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "8b5711d8458b3686268e7bc8e5c8ea41d77686358f10fbd695afe559e4e93426", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "cf5d22d43dbf27aed72716e4bc8f0e85c13046a025ee39c679becc580745f651", "schema_version": 1}
|
||||
|
||||
Reference in New Issue
Block a user