Retain actionable FLM diagnostics across drives and restarts

This commit is contained in:
firestar5683
2026-11-17 17:10:36 -06:00
parent 268700ae5f
commit c599f28256
5 changed files with 565 additions and 19 deletions
+203
View File
@@ -0,0 +1,203 @@
"""Bounded support history; no tuning values, timestamps or runtime authority."""
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import tempfile
from openpilot.starpilot.flm.offroad_cache import directory_for_params, _pairs
from openpilot.starpilot.saved_source import read_saved
MAX_BYTES = 65_536
MAX_EVENTS = 12
ACTIVE = ('starting_analysis', 'reading_recording', 'checking_recommendations')
FIELDS = {'stage', 'reason', 'build', 'recording_sha256', 'analysis_counts', 'recommendation_count',
'saved_adjustments', 'configuration_state', 'qualification', 'interrupted_stage', 'enabled', 'skipped_reasons'}
def redact(value):
text = str(value)[:512]
text = re.sub(r'https?://\S+|/(?:data|home|Users|tmp)/\S+', '[private location]', text)
text = re.sub(r'\b[0-9a-f]{16}/[0-9a-f]{8}--[0-9a-f]{10}\b', '[private recording]', text)
text = re.sub(r'\b[0-9a-f]{16}\b', '[private device]', text)
text = re.sub(r'\b[A-HJ-NPR-Z0-9]{17}\b', '[private vehicle]', text)
return re.sub(r'(?i)(?:token|password|secret|authorization)[=: ]+\S+', '[private credential]', text)
def qualification(value):
if type(value) is not dict:
return None
counts: dict = {key: value[key] for key in ('passed', 'required') if type(value.get(key)) is int and 0 <= value[key] < 2**63}
rows = value.get('refusals')
counts['refusals'] = [[redact(row[0])[:160], row[1]] for row in (rows[:16] if type(rows) in (tuple, list) else ())
if type(row) in (tuple, list) and len(row) == 2 and type(row[1]) is int and 0 <= row[1] < 2**63]
return counts
def path_for_params(params):
directory = directory_for_params(params)
return directory.with_name(directory.name + '-diagnostics.json')
def _validate(value):
if (type(value) is not dict or set(value) != {'version', 'current', 'last_attempt', 'last_result', 'events'} or
type(value['version']) is not int or value['version'] != 1):
raise ValueError('Diagnostic history format changed')
if type(value['events']) is not list or len(value['events']) > MAX_EVENTS:
raise ValueError('Diagnostic history bound changed')
for event in [value['current'], value['last_attempt'], value['last_result'], *value['events']]:
if event is None:
continue
if (type(event) is not dict or not {'stage', 'reason', 'build'} <= event.keys() or not set(event) <= FIELDS or
any(type(event.get(key)) is not str or len(event[key]) > 512 for key in ('stage', 'reason', 'build'))):
raise ValueError('Invalid diagnostic event')
for key, item in event.items():
if key == 'analysis_counts':
valid = type(item) is dict and len(item) <= 64 and all(
re.fullmatch(r'[a-z_]{1,64}', name) and type(count) is int and 0 <= count < 2**63 for name, count in item.items())
elif key == 'qualification':
valid = type(item) is dict and item == qualification(item)
elif key == 'skipped_reasons':
valid = type(item) is list and len(item) <= 16 and all(type(reason) is str and len(reason) <= 512 for reason in item)
elif key in ('recommendation_count', 'saved_adjustments'):
valid = type(item) is int and 0 <= item < 2**63
elif key == 'enabled':
valid = type(item) is bool
else:
valid = type(item) is str and len(item) <= 512
if not valid:
raise ValueError('Invalid diagnostic field: ' + key)
return value
def read_state(params):
"""Reading a download never creates or modifies a support or analysis store."""
fd = None
try:
path = path_for_params(params)
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
before = os.fstat(fd)
if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.geteuid() or before.st_mode & 0o022 or
not 0 < before.st_size <= MAX_BYTES):
raise ValueError('Invalid diagnostic history file')
raw = os.read(fd, MAX_BYTES + 1)
after = os.fstat(fd)
current = path.lstat()
if ((before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) !=
(after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) or
(current.st_dev, current.st_ino) != (after.st_dev, after.st_ino) or len(raw) != before.st_size):
raise ValueError('Diagnostic history changed while reading')
return {'status': 'recorded', **_validate(json.loads(raw, object_pairs_hook=_pairs))}
except FileNotFoundError:
return {'status': 'not_recorded', 'reason': 'No persistent analysis diagnostic record is available in this settings store.'}
except (OSError, ValueError, TypeError, UnicodeError, RecursionError) as error:
return {'status': 'unavailable', 'reason': redact(error)}
finally:
if fd is not None:
os.close(fd)
def _stage(value):
reason = str(value.get('reason', ''))
if value.get('status') == 'fitting':
return ('starting_analysis' if reason == 'loading_parked_analysis' else
'reading_recording' if reason == 'analyzing_last_completed_drive' else 'checking_recommendations')
if value.get('status') == 'unavailable':
return 'analysis_error'
if reason.startswith('waiting_for_'):
return 'waiting_for_parked'
if value.get('completed_route'):
return 'analysis_result'
return 'recording' if reason == 'recording_for_offroad_analysis' else 'paused'
class DiagnosticState:
def __init__(self, params):
self.params, self.path = params, path_for_params(params)
stored = read_state(params)
self.error = stored.get('reason', '') if stored['status'] == 'unavailable' else ''
self.writable = stored['status'] != 'unavailable'
self.state = {key: stored.get(key) for key in ('current', 'last_attempt', 'last_result')}
self.state.update(version=1, events=stored.get('events', []))
self.last_observed = None
raw, readable = read_saved(params, 'GitCommit', 128)
self.build = raw.decode('ascii') if readable and raw is not None and re.fullmatch(rb'[0-9a-f]{40}', raw) else 'unknown'
if self.state['current'] is not None and self.state['current']['stage'] in ACTIVE:
self.observe({'status': 'unavailable', 'reason': 'previous_analysis_interrupted_before_completion'})
def observe(self, value):
"""Record coarse state changes only; repeated onroad ticks cause no writes."""
event = {'stage': _stage(value), 'reason': redact(value.get('reason', 'not_reported')), 'build': self.build}
if value.get('completed_route'):
event['recording_sha256'] = hashlib.sha256(str(value['completed_route']).encode()).hexdigest()
counts = value.get('analysis_counts')
if type(counts) is dict:
event['analysis_counts'] = {key: count for key, count in list(counts.items())[:64]
if type(key) is str and re.fullmatch(r'[a-z_]{1,64}', key) and type(count) is int and 0 <= count < 2**63}
for key in ('recommendation_count', 'saved_adjustments'):
if type(value.get(key)) is int and 0 <= value[key] < 2**63:
event[key] = value[key]
if type(value.get('enabled')) is bool:
event['enabled'] = value['enabled']
skipped = value.get('skipped_routes')
if type(skipped) is list:
event['skipped_reasons'] = [redact(row[1]) for row in skipped[:16] if type(row) in (tuple, list) and len(row) == 2]
if type(value.get('configuration_state')) is str:
event['configuration_state'] = redact(value['configuration_state'])
checks = qualification(value.get('qualification_summary'))
if checks is not None:
event['qualification'] = checks
prior = self.state['current']
if event['stage'] == 'analysis_error' and prior is not None and prior['stage'] in ACTIVE:
event['interrupted_stage'] = prior['stage']
if event == self.last_observed or event == prior:
return not self.error
self.last_observed = event
if not self.writable:
return False
state = {**self.state, 'current': event, 'events': [*self.state['events'], event][-MAX_EVENTS:]}
if event['stage'] in ACTIVE:
state['last_attempt'] = event
elif event['stage'] in ('analysis_result', 'analysis_error'):
state['last_result'] = event
temporary = None
try:
raw = json.dumps(_validate(state), separators=(',', ':'), allow_nan=False).encode()
while len(raw) > MAX_BYTES and len(state['events']) > 1:
state['events'] = state['events'][1:]
raw = json.dumps(state, separators=(',', ':'), allow_nan=False).encode()
if len(raw) > MAX_BYTES:
raise ValueError('Diagnostic history size bound')
try:
info = self.path.lstat()
except FileNotFoundError:
info = None
if info is not None:
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:
raise ValueError('Diagnostic history ownership changed')
with tempfile.NamedTemporaryFile(prefix='.flm-diagnostics-', dir=self.path.parent, delete=False) as stream:
temporary = stream.name
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, self.path)
temporary = None
self.state = state
directory = os.open(self.path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(directory)
finally:
os.close(directory)
self.error = ''
return True
except (OSError, ValueError, TypeError) as error:
self.error = redact(error)
return False
finally:
if temporary is not None:
try:
Path(temporary).unlink(missing_ok=True)
except OSError:
pass
+56 -12
View File
@@ -24,10 +24,16 @@ class StatusReport:
self.current: dict[str, Any] = {'status': 'collecting', 'reason': 'waiting_for_completed_drive', 'vehicle': ''}
self.previous: dict[str, Any] = {}
self.next_ns = 0
self.diagnostics = None
def set(self, value):
def set(self, value, *, diagnostic_value=None):
changed = (self.current.get('status'), self.current.get('reason')) != (value.get('status'), value.get('reason'))
self.current = dict(value)
if self.diagnostics is not None:
try:
self.diagnostics.observe(value if diagnostic_value is None else diagnostic_value)
except (OSError, ValueError, TypeError, AttributeError) as error:
self.diagnostics.error = f'Diagnostic state could not be recorded: {type(error).__name__}'
if value.get('completed_route') and value.get('status') != 'fitting':
self.previous = dict(value)
if changed:
@@ -46,7 +52,7 @@ class StatusReport:
for key in ('configuration_state', 'configured_values', 'saved_adjustments', 'qualification_summary'):
if key in self.previous:
previous[key] = self.previous[key]
self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous)})
self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous)}, diagnostic_value=value)
def restore(self, cache):
"""Recover historical display data, never a current tune or permission."""
@@ -108,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 self.diagnostics is not None and self.diagnostics.error:
details['Diagnostic persistence error'] = self.diagnostics.error
if value.get('skipped_routes'):
details['Skipped recorded drives'] = [list(row) for row in value['skipped_routes'][:16]]
if value.get('partial_drive') is True:
@@ -245,23 +253,43 @@ class StatusReport:
Path(temporary).unlink(missing_ok=True)
def parked_status(sm, params, *, stopped=False, now=None):
def parked_blocker(sm, params, *, stopped=False, now=None):
"""Same fresh parked physical-state checks as the existing bench supervisor.
Offroad analysis needs current status, not the nominal publication cadence.
Do not rewrite freq_ok or use this predicate for current Controls authority.
"""
services = ('deviceState', 'pandaStates', 'peripheralState')
if stopped or not params.get_bool('IsOffroad') or params.get_bool('IsEngaged'):
return False
if not all(sm.seen[k] and sm.alive[k] and sm.valid[k] for k in services):
return False
if stopped:
return 'waiting_for_shutdown_to_finish'
if not params.get_bool('IsOffroad'):
return 'waiting_for_vehicle_offroad'
if params.get_bool('IsEngaged'):
return 'waiting_for_controls_to_disengage'
for service in services:
if not (sm.seen[service] and sm.alive[service] and sm.valid[service]):
return 'waiting_for_valid_' + service
if now is None:
now = time.monotonic()
if any(not 0 <= now - sm.recv_time[k] <= 2.0 for k in services):
return False
for service in services:
if not 0 <= now - sm.recv_time[service] <= 2.0:
return 'waiting_for_fresh_' + service
pandas = sm['pandaStates']
return bool(not sm['deviceState'].started and pandas and all(not (p.ignitionLine or p.ignitionCan or p.controlsAllowed or p.faults) for p in pandas))
if sm['deviceState'].started:
return 'waiting_for_vehicle_to_switch_off'
if not pandas:
return 'waiting_for_connected_panda_status'
if any(p.ignitionLine or p.ignitionCan for p in pandas):
return 'waiting_for_ignition_off'
if any(p.controlsAllowed for p in pandas):
return 'waiting_for_panda_controls_to_disarm'
if any(p.faults for p in pandas):
return 'waiting_for_panda_fault_to_clear'
return None
def parked_status(sm, params, *, stopped=False, now=None):
return parked_blocker(sm, params, stopped=stopped, now=now) is None
def wait_for_parked(sm, params, *, stopped=lambda: False, clock=time.monotonic):
@@ -313,7 +341,7 @@ def run_parked_analysis(worker, report):
def _run():
from openpilot.common.hardware.hw import Paths
from openpilot.starpilot.flm.offroad_cache import directory_for_params
from openpilot.starpilot.flm.offroad_source import record_drive
from openpilot.starpilot.flm.diagnostic_state import DiagnosticState
params = Params()
stopped = False
@@ -327,10 +355,16 @@ def _run():
restart = False
report = StatusReport()
try:
report.diagnostics = DiagnosticState(params)
from openpilot.starpilot.flm.offroad_source import record_drive
sm = messaging.SubMaster(['deviceState', 'pandaStates', 'peripheralState'])
def parked():
return wait_for_parked(sm, params, stopped=lambda: stopped)
allowed = wait_for_parked(sm, params, stopped=lambda: stopped)
if not allowed and not stopped and params.get_bool('IsOffroad'):
report.set({'status': 'collecting', 'reason': parked_blocker(sm, params) or 'waiting_for_parked_permission'})
return allowed
def permitted():
okay = parked()
@@ -365,6 +399,7 @@ def _run():
)
elif parked() and time.monotonic() >= next_analysis:
if worker is None:
report.analyzing({'status': 'fitting', 'reason': 'loading_parked_analysis'})
from openpilot.starpilot.flm.offroad_worker import OffroadWorker
worker = OffroadWorker(
@@ -392,7 +427,16 @@ def _run():
report.publish()
if not stopped:
time.sleep(0.05)
except Exception as error:
report.set({'status': 'unavailable', 'reason': f'{type(error).__name__}: {error}'[:300]})
report.publish()
raise
finally:
diagnostics = getattr(report, 'diagnostics', None)
if diagnostics is not None and diagnostics.state['current'] is not None and diagnostics.state['current']['stage'] in (
'starting_analysis', 'reading_recording', 'checking_recommendations'
):
diagnostics.observe({'status': 'unavailable', 'reason': 'analysis_interrupted_by_shutdown'})
try:
if sm is not None:
for sock in sm.sock.values():
@@ -0,0 +1,226 @@
"""Support downloads explain coarse learner outcomes without changing tuning."""
import json
from pathlib import Path
import sys
import tempfile
from types import SimpleNamespace
from typing import Any
import unittest
from unittest.mock import patch
from openpilot.common.params import Params
from openpilot.starpilot.flm import offroad_daemon as daemon
from openpilot.starpilot.flm.diagnostic_state import DiagnosticState, MAX_BYTES, MAX_EVENTS, path_for_params, read_state
from openpilot.starpilot.flm.offroad_cache import AssessmentCache, directory_for_params
from openpilot.starpilot.galaxy.flm_diagnostics import download
class TestDiagnosticState(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.params = Params(str(self.root / 'params'))
self.params.put('GitCommit', 'a' * 40, block=True)
def exported(self, report=None):
return json.loads(download({} if report is None else report, self.params)[1])
def test_last_analysis_counts_and_exact_refusals_survive_driving_and_restart(self):
journal = DiagnosticState(self.params)
for reason in ('loading_parked_analysis', 'analyzing_last_completed_drive', 'checking_recorded_steering_recommendations'):
self.assertTrue(journal.observe({'status': 'fitting', 'reason': reason}))
self.assertTrue(journal.observe({'status': 'collecting', 'reason': 'recorded_tracking_suggestion_not_yet_qualified_for_automatic_application',
'completed_route': '1234567890abcdef/00000049--1b13f9d9d3', 'analysis_counts': {'recorded_tracking': 1234},
'recommendation_count': 3, 'saved_adjustments': 0,
'qualification_summary': {'passed': 2, 'required': 8, 'refusals': [('independent_native_validation_not_run', 6)]}}))
journal.observe({'status': 'collecting', 'reason': 'recording_for_offroad_analysis', 'enabled': True})
restarted = DiagnosticState(self.params)
self.assertEqual(restarted.state, journal.state)
exported = self.exported({'current': {'reason': 'recording_for_offroad_analysis'}})
history = exported['learning_diagnostics']
self.assertEqual(history['current']['stage'], 'recording')
self.assertEqual(history['last_attempt']['stage'], 'checking_recommendations')
self.assertEqual(history['last_result']['analysis_counts'], {'recorded_tracking': 1234})
self.assertEqual(history['last_result']['qualification'], {'passed': 2, 'required': 8, 'refusals': [['independent_native_validation_not_run', 6]]})
self.assertEqual(history['last_result']['saved_adjustments'], 0)
self.assertIn('automatic saving', history['last_result']['explanation'])
self.assertNotIn('1234567890abcdef', json.dumps(exported))
self.assertEqual(exported['storage']['status'], 'not_created')
def test_four_hz_control_status_does_not_write_or_retain_control_objects(self):
journal = DiagnosticState(self.params)
value = {'status': 'collecting', 'reason': 'recording_for_offroad_analysis', 'enabled': True}
journal.observe(value)
path = path_for_params(self.params)
before = path.read_bytes(), path.stat().st_mtime_ns
with patch('openpilot.starpilot.flm.diagnostic_state.os.replace', side_effect=AssertionError('Repeated tick wrote to disk')):
for frame in range(1000):
self.assertTrue(journal.observe(dict(value, actual_control=object(), actual_control_ns=frame)))
self.assertEqual((path.read_bytes(), path.stat().st_mtime_ns), before)
self.assertEqual(len(journal.state['events']), 1)
self.assertFalse(directory_for_params(self.params).exists())
def test_restart_records_interrupted_stage_and_never_invents_a_result(self):
journal = DiagnosticState(self.params)
journal.observe({'status': 'fitting', 'reason': 'analyzing_last_completed_drive'})
DiagnosticState(self.params)
result = self.exported()['learning_diagnostics']
self.assertEqual(result['last_result']['reason'], 'previous_analysis_interrupted_before_completion')
self.assertEqual(result['last_result']['interrupted_stage'], 'reading_recording')
self.assertNotIn('saved_adjustments', result['last_result'])
self.assertEqual(result['last_attempt']['stage'], 'reading_recording')
def test_new_analysis_diagnostics_use_new_counts_while_display_retains_prior_findings(self):
report = daemon.StatusReport(path=self.root / 'report.json')
report.diagnostics = DiagnosticState(self.params)
report.previous = {'completed_route': 'old', 'analysis_counts': {'recorded_tracking': 99}}
report.analyzing({'status': 'fitting', 'reason': 'checking_recorded_steering_recommendations',
'completed_route': 'new', 'analysis_counts': {'recorded_tracking': 1234}})
self.assertEqual(report.current['analysis_counts']['recorded_tracking'], 99)
self.assertEqual(read_state(self.params)['last_attempt']['analysis_counts']['recorded_tracking'], 1234)
def test_worker_startup_failure_is_captured_before_assessment_cache_exists(self):
self.params.put_bool('IsOffroad', True, block=True)
self.params.put('AutomaticSteeringProfiles', b'preserved-original', block=True)
report = daemon.StatusReport(path=self.root / 'report.json')
worker = SimpleNamespace(OffroadWorker=lambda *args, **kwargs: (_ for _ in ()).throw(OSError('worker startup denied')))
with patch.object(daemon, 'Params', return_value=self.params), patch.object(daemon, 'StatusReport', return_value=report), \
patch.object(daemon.messaging, 'SubMaster', return_value=SimpleNamespace(sock={})), \
patch.object(daemon, 'wait_for_parked', return_value=True), \
patch.dict(sys.modules, {'openpilot.starpilot.flm.offroad_worker': worker}):
with self.assertRaisesRegex(OSError, 'worker startup denied'):
daemon._run()
self.assertEqual(self.params.get('AutomaticSteeringProfiles'), b'preserved-original')
self.assertFalse(directory_for_params(self.params).exists())
result = self.exported()['learning_diagnostics']['last_result']
self.assertEqual(result['reason'], 'OSError: worker startup denied')
self.assertEqual(result['interrupted_stage'], 'starting_analysis')
def test_parked_blocker_names_preserve_actual_admission_rules(self):
self.params.put_bool('IsOffroad', True, block=True)
services = ('deviceState', 'pandaStates', 'peripheralState')
panda = SimpleNamespace(ignitionLine=False, ignitionCan=False, controlsAllowed=False, faults=[])
messages = {'deviceState': SimpleNamespace(started=False), 'pandaStates': [panda]}
class Status:
seen = dict.fromkeys(services, True)
alive = dict.fromkeys(services, True)
valid = dict.fromkeys(services, True)
recv_time = dict.fromkeys(services, 1.0)
def __getitem__(self, key):
return messages[key]
sm = Status()
self.assertIsNone(daemon.parked_blocker(sm, self.params, now=2.0))
self.assertTrue(daemon.parked_status(sm, self.params, now=2.0))
cases: list[tuple[dict[str, Any], str, Any, str]] = [(sm.valid, 'pandaStates', False, 'waiting_for_valid_pandaStates'),
(sm.recv_time, 'deviceState', -2.0, 'waiting_for_fresh_deviceState'),
(panda.__dict__, 'ignitionCan', True, 'waiting_for_ignition_off'),
(panda.__dict__, 'controlsAllowed', True, 'waiting_for_panda_controls_to_disarm'),
(panda.__dict__, 'faults', [1], 'waiting_for_panda_fault_to_clear')]
journal = DiagnosticState(self.params)
for values, key, bad, reason in cases:
original, values[key] = values[key], bad
self.assertFalse(daemon.parked_status(sm, self.params, now=2.0))
self.assertEqual(daemon.parked_blocker(sm, self.params, now=2.0), reason)
journal.observe({'status': 'collecting', 'reason': reason})
self.assertEqual(self.exported()['learning_diagnostics']['current']['reason'], reason)
values[key] = original
def test_failed_write_is_visible_preserves_old_record_and_does_not_stop_reporting(self):
report = daemon.StatusReport(path=self.root / 'report.json')
report.diagnostics = DiagnosticState(self.params)
report.set({'status': 'collecting', 'reason': 'recording_for_offroad_analysis'})
path = path_for_params(self.params)
original = path.read_bytes()
with patch('openpilot.starpilot.flm.diagnostic_state.os.replace', side_effect=OSError('disk full')) as replace:
for _ in range(5):
report.set({'status': 'unavailable', 'reason': 'local recordings unavailable'})
self.assertEqual(replace.call_count, 1)
self.assertEqual(path.read_bytes(), original)
self.assertEqual(list(path.parent.glob('.flm-diagnostics-*')), [])
report.publish()
wire = json.loads(report.path.read_text())
self.assertEqual(wire['current']['reason'], 'local recordings unavailable')
self.assertEqual(self.exported(wire)['learning_diagnostics']['write_error'], 'disk full')
def test_invalid_existing_history_is_preserved_and_download_explains_it(self):
path = path_for_params(self.params)
for raw in (b'{broken', b'{}', b'x' * (MAX_BYTES + 1)):
path.write_bytes(raw)
journal = DiagnosticState(self.params)
self.assertFalse(journal.observe({'reason': 'recording_for_offroad_analysis'}))
self.assertEqual(path.read_bytes(), raw)
self.assertEqual(self.exported()['learning_diagnostics']['status'], 'unavailable')
path.unlink()
private = self.root / 'private'
private.write_text('preserve')
path.symlink_to(private)
self.assertEqual(read_state(self.params)['status'], 'unavailable')
self.assertFalse(DiagnosticState(self.params).observe({'reason': 'recording_for_offroad_analysis'}))
self.assertTrue(path.is_symlink())
self.assertEqual(private.read_text(), 'preserve')
def test_bounded_history_and_privacy_even_with_large_reasons_and_refusals(self):
journal = DiagnosticState(self.params)
for index in range(30):
self.assertTrue(journal.observe({'status': 'unavailable', 'reason': str(index) + 'x' * 1000,
'analysis_counts': {'count_' + chr(97 + i // 26) + chr(97 + i % 26): 2**62 for i in range(64)},
'qualification_summary': {'refusals': [('x' * 1000, 2**62)] * 16}}))
self.assertLessEqual(path_for_params(self.params).stat().st_size, MAX_BYTES)
self.assertLessEqual(len(read_state(self.params)['events']), MAX_EVENTS)
reason = 'password=secret https://example.invalid/token /data/private/route 1234567890abcdef/00000049--1b13f9d9d3 JTDAC3EH0B3000000'
journal.observe({'status': 'unavailable', 'reason': reason, 'skipped_routes': [['private', 'secret=hidden']]})
body = download({'history': [{'reason': ('password=tuple-secret',)}]}, self.params)[1]
for secret in (b'password=', b'example.invalid', b'/data/private', b'1234567890abcdef', b'JTDAC3EH0B3000000', b'secret=hidden'):
self.assertNotIn(secret, body)
def test_old_export_without_persistent_record_does_not_assert_learning_never_ran(self):
before = list(path_for_params(self.params).parent.iterdir())
result = self.exported()
self.assertEqual(result['learning_diagnostics']['status'], 'not_recorded')
self.assertEqual(list(path_for_params(self.params).parent.iterdir()), before)
def test_malformed_nested_diagnostic_data_does_not_enter_the_download(self):
journal = DiagnosticState(self.params)
journal.observe({'status': 'collecting', 'reason': 'recording_for_offroad_analysis'})
value = json.loads(path_for_params(self.params).read_bytes())
value['current']['analysis_counts'] = {'unapproved_field': {'private_raw_data': 'not a count'}}
raw = json.dumps(value).encode()
path_for_params(self.params).write_bytes(raw)
result = self.exported()['learning_diagnostics']
self.assertEqual(result['status'], 'unavailable')
self.assertNotIn('private_raw_data', json.dumps(result))
self.assertEqual(path_for_params(self.params).read_bytes(), raw)
def test_bad_native_cache_does_not_hide_an_independent_analysis_error(self):
self.params.put('LiveDelay', b'bad schema bytes', block=True)
journal = DiagnosticState(self.params)
journal.observe({'status': 'unavailable', 'reason': 'Local drive inventory is incomplete'})
result = self.exported()
self.assertEqual(result['native_learning_caches']['LiveDelay']['status'], 'incompatible')
self.assertEqual(result['learning_diagnostics']['last_result']['reason'], 'Local drive inventory is incomplete')
self.assertIn('complete list', result['learning_diagnostics']['last_result']['explanation'])
def test_qualification_reasons_are_exported_from_existing_checkpoints_without_new_history(self):
cache = AssessmentCache(directory_for_params(self.params))
cache.checkpoint({'input_fingerprint': 'b' * 64, 'result': {'status': 'collecting', 'reason': 'more_independent_eligible_tracking_required',
'qualification_summary': {'passed': 0, 'required': 6, 'refusals': [['missing_original_controller_metadata', 6]]}}})
result = self.exported()
self.assertEqual(result['checkpoints'][0]['qualification']['refusals'], [['missing_original_controller_metadata', 6]])
self.assertIn('independent', result['checkpoints'][0]['explanation'])
self.assertEqual(result['learning_diagnostics']['status'], 'not_recorded')
def test_native_cache_is_reported_separately_from_parked_route_analysis(self):
from openpilot.cereal import messaging
from openpilot.starpilot.schema_cache import put_cache
message = messaging.new_message('lateralDelay')
message.valid = True
message.lateralDelay.version = 1
message.lateralDelay.status = 'estimated'
put_cache(self.params, 'LiveDelay', message, block=True)
result = self.exported()
self.assertEqual(result['storage']['status'], 'not_created')
self.assertEqual(result['stored_profile_counts']['parked_route_profiles'], 0)
self.assertEqual(result['native_learning_caches']['LiveDelay']['status'], 'valid')
self.assertTrue(result['native_learning_caches']['LiveDelay']['estimate_valid'])
self.assertIn('not proof', result['native_learning_caches']['LiveDelay']['scope'])
+79 -6
View File
@@ -2,23 +2,59 @@
import json
import re
from typing import Any
from capnp import KjException
from openpilot.starpilot.flm.offroad_cache import AssessmentCache, directory_for_params
from openpilot.starpilot.flm.offroad_store import KEY, MAX_BYTES, NAMESPACE
from openpilot.starpilot.flm.learned_lifecycle import decode
from openpilot.starpilot.saved_source import read_saved
from openpilot.starpilot.flm.diagnostic_state import read_state, qualification, redact
def _reason(value):
text = str(value)[:512]
text = re.sub(r'https?://\S+|/(?:data|home|Users|tmp)/\S+', '[private location]', text)
return re.sub(r'(?i)(?:token|password|secret|authorization)[=: ]+\S+', '[private credential]', text)
return redact(value)
def _explanation(reason):
explanations = {
'recording_for_offroad_analysis': 'Recording while driving. Route analysis runs after parking; this is not an analysis result.',
'loading_parked_analysis': 'Starting the parked analysis worker.',
'analyzing_last_completed_drive': 'Reading recorded drive data.',
'checking_recorded_steering_recommendations': 'Checking recommendations against recorded controller and steering-delivery evidence.',
'previous_analysis_interrupted_before_completion': 'The learner restarted before its previous analysis reported an outcome.',
'analysis_interrupted_by_shutdown': 'Analysis was interrupted by shutdown or the return to driving.',
'waiting_for_vehicle_offroad': 'Analysis is waiting for the vehicle to be offroad.',
'waiting_for_controls_to_disengage': 'Analysis is waiting for controls to disengage.',
'waiting_for_vehicle_to_switch_off': 'The device still reports the vehicle started.',
'waiting_for_ignition_off': 'The vehicle interface still reports ignition on.',
'waiting_for_connected_panda_status': 'No connected vehicle-interface status is available.',
'waiting_for_panda_controls_to_disarm': 'The vehicle interface still allows controls.',
'waiting_for_panda_fault_to_clear': 'The vehicle interface reports a fault.',
'Local drive inventory is incomplete': 'FLM could not obtain a complete list of local recordings.',
'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.',
'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.',
}
if reason.startswith('waiting_for_valid_'):
return 'Analysis is waiting for valid ' + reason.removeprefix('waiting_for_valid_') + ' status.'
if reason.startswith('waiting_for_fresh_'):
return 'Analysis is waiting for a fresh ' + reason.removeprefix('waiting_for_fresh_') + ' status message.'
return explanations.get(reason, 'Reported reason: ' + reason)
def _result(value):
result = {key: value[key] for key in ('status', 'configuration_changed', 'configuration_state', 'saved_adjustments',
'analysis_counts', 'actual_application_proven', 'recommendation_count', 'route_skipped') if key in value}
result['reason'] = _reason(value.get('reason', 'not_reported'))
result['explanation'] = _explanation(result['reason'])
checks = qualification(value.get('qualification_summary'))
if checks is not None:
result['qualification'] = checks
skipped = value.get('skipped_routes')
result['skipped_drives'] = [{'recording': _reason(row[0])[:180], 'reason': _reason(row[1])}
for row in (skipped[:16] if type(skipped) is list else ()) if type(row) is list and len(row) == 2]
@@ -28,10 +64,11 @@ def _result(value):
def diagnostics(report, params):
current = report.get('current') or {}
details = current.get('details') or {}
result = {'version': 1, 'privacy': 'No raw route data, location, VIN, dongle ID or credentials included.',
result: dict[str, Any] = {'version': 1, 'privacy': 'No raw route data, location, VIN, dongle ID or credentials included.',
'current': {key: current[key] for key in ('fresh', 'ageSeconds', 'enabled', 'status', 'progress', 'fit', 'application') if key in current},
'preference': report.get('preference'), 'history': report.get('history', []), 'checkpoints': [], 'saved_profiles': []}
result['current']['reason'] = _reason(current.get('reason', 'learner_report_unavailable'))
result['current']['explanation'] = _explanation(result['current']['reason'])
result['current']['analysis'] = {key: details[key] for key in (
'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',
@@ -40,7 +77,16 @@ def diagnostics(report, params):
result['current']['skipped_drives'] = _result({'skipped_routes': details.get('Skipped recorded drives', [])})['skipped_drives']
if params is None:
result['storage'] = {'status': 'unavailable'}
result['learning_diagnostics'] = {'status': 'unavailable', 'reason': 'Settings storage is unavailable.'}
return result
result['learning_diagnostics'] = read_state(params)
history = result['learning_diagnostics']
if history['status'] == 'recorded':
for event in [history['current'], history['last_attempt'], history['last_result'], *history['events']]:
if event is not None:
event['explanation'] = _explanation(event['reason'])
if details.get('Diagnostic persistence error'):
result['learning_diagnostics']['write_error'] = _reason(details['Diagnostic persistence error'])
for key in ('GitCommit', 'GitBranch'):
raw, readable = read_saved(params, key, 128)
if readable and raw is not None and re.fullmatch(rb'[\w./-]{1,128}', raw):
@@ -49,10 +95,17 @@ def diagnostics(report, params):
raw, readable = read_saved(params, KEY, MAX_BYTES)
if not readable:
raise ValueError('saved_profiles_unreadable')
for row in decode(raw).get(NAMESPACE, {}).values():
document = decode(raw)
result['stored_profile_counts'] = {'legacy_stage_profiles': len(document['profiles']),
'full_surface_profiles': len(document.get('fullSurfaces', {})),
'parked_route_profiles': len(document.get(NAMESPACE, {}))}
for row in document.get(NAMESPACE, {}).values():
result['saved_profiles'].append({'state': row['state'], 'sequence': row['sequence'],
'adjustments': sum(value != 0 for value in row['values'].values()),
'evidence_drives': len(row['route_sha256s'])})
except (OSError, ValueError, TypeError, KeyError) as error:
result['profile_storage'] = {'status': 'unavailable', 'reason': _reason(error)}
try:
directory = directory_for_params(params)
if not directory.exists():
result['storage'] = {'status': 'not_created', 'documents': 0, 'bytes': 0}
@@ -63,6 +116,26 @@ def diagnostics(report, params):
result['checkpoints'] = [_result(row['result']) for row in cache.checkpoints()]
except (OSError, ValueError, TypeError, KeyError) as error:
result['storage'] = {'status': 'unavailable', 'reason': _reason(error)}
result['storage']['scope'] = 'Parked route analysis in the current settings store only'
result['native_learning_caches'] = {}
from openpilot.cereal import log
from openpilot.starpilot.schema_cache import inspect_cache
for key, service in (('LiveTorqueParameters', 'lateralTorqueParameters'), ('LiveDelay', 'lateralDelay')):
try:
raw, readable = read_saved(params, key, 2_097_152)
inspected = inspect_cache(key, raw) if readable else None
summary: dict[str, Any] = {'status': inspected.status if inspected is not None else 'unreadable',
'scope': 'Stored estimator cache; not proof of current application'}
if inspected is not None and inspected.reason:
summary['reason'] = _reason(inspected.reason)
if inspected is not None and inspected.payload is not None:
with log.Event.from_bytes(inspected.payload) as event:
value = getattr(event, service)
summary['version'] = int(value.version)
summary['estimate_valid'] = bool(event.valid and (value.valid if service == 'lateralTorqueParameters' else str(value.status) == 'estimated'))
result['native_learning_caches'][key] = summary
except (OSError, ValueError, TypeError, KeyError, KjException) as error:
result['native_learning_caches'][key] = {'status': 'unavailable', 'reason': _reason(error)}
try:
from openpilot.starpilot.flm.offroad_saved_history import SavedHistory
from openpilot.starpilot.flm.offroad_store import validate_row
@@ -86,7 +159,7 @@ def download(report, params):
def clean(value):
if type(value) is dict:
return {key: clean(item) for key, item in value.items()}
if type(value) is list:
if type(value) in (tuple, list):
return [clean(item) for item in value]
return _reason(value) if type(value) is str else value
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "af84e3cf1724d0f0b542ba9fc41fc37a755c72e0648df7a0f85ee1d6d53e8e6c", "schema_version": 1}
{"protected_inventory_sha256": "1b12eb5762f30eed67a0772a27b4b8c87d80d4b18ff61580152132bba5dae42f", "schema_version": 1}