diff --git a/openpilot/starpilot/flm/diagnostic_state.py b/openpilot/starpilot/flm/diagnostic_state.py index 8a7e7b426c..3c05f4fbdb 100644 --- a/openpilot/starpilot/flm/diagnostic_state.py +++ b/openpilot/starpilot/flm/diagnostic_state.py @@ -12,7 +12,7 @@ from openpilot.starpilot.saved_source import read_saved MAX_BYTES = 65_536 MAX_EVENTS = 12 -ACTIVE = ('starting_analysis', 'reading_recording', 'checking_recommendations') +ACTIVE = ('starting_analysis', 'reading_recording', 'verifying_recording', 'checking_recommendations') FIELDS = {'stage', 'reason', 'build', 'recording_sha256', 'analysis_counts', 'recommendation_count', 'saved_adjustments', 'configuration_state', 'qualification', 'interrupted_stage', 'enabled', 'skipped_reasons'} @@ -102,8 +102,8 @@ def read_state(params): 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') + return {'loading_parked_analysis': 'starting_analysis', 'analyzing_last_completed_drive': 'reading_recording', + 'verifying_recorded_drive': 'verifying_recording'}.get(reason, 'checking_recommendations') if value.get('status') == 'unavailable': return 'analysis_error' if reason.startswith('waiting_for_'): diff --git a/openpilot/starpilot/flm/offroad_daemon.py b/openpilot/starpilot/flm/offroad_daemon.py index c4aa660bee..9b16a45060 100644 --- a/openpilot/starpilot/flm/offroad_daemon.py +++ b/openpilot/starpilot/flm/offroad_daemon.py @@ -61,8 +61,8 @@ class StatusReport: counts = value.get('analysis_counts', {}) if type(counts) is not dict: counts = {} - phase = ('preparing' if value['reason'] == 'loading_parked_analysis' else - 'reading' if value['reason'] == 'analyzing_last_completed_drive' else 'checking') + phase = {'loading_parked_analysis': 'preparing', 'analyzing_last_completed_drive': 'reading', + 'verifying_recorded_drive': 'verifying'}.get(value['reason'], 'checking') progress = value.get('analysis_progress', {'phase': phase, 'completed': counts.get('original_segments_reviewed'), 'total': counts.get('original_segments_available')}) self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous), @@ -342,13 +342,16 @@ def wait_for_parked(sm, params, *, stopped=lambda: False, clock=time.monotonic, timeout = 20 -def run_parked_analysis(worker, report): +def run_parked_analysis(worker, report, *, permission_loss=lambda: None): """Advance promptly only after an unreadable input was durably skipped.""" from openpilot.starpilot.flm.offroad_route import RouteInputError try: report.set(worker.run_once()) except (ValueError, OSError, RuntimeError) as error: + if (blocker := permission_loss()) is not None: + report.set({'status': 'unavailable', 'reason': blocker}) + return False if isinstance(error, RouteInputError): cloudlog.warning( 'FLM skipped unreadable drive %s: %s; continuing with other drives', @@ -371,7 +374,7 @@ def _run(): from openpilot.starpilot.drive_state.evidence import PhysicalSource from openpilot.starpilot.drive_state.owner import DriveStateOwner, Mode from openpilot.starpilot.flm.offroad_cache import directory_for_params - from openpilot.starpilot.flm.diagnostic_state import DiagnosticState + from openpilot.starpilot.flm.diagnostic_state import ACTIVE, DiagnosticState from openpilot.starpilot.storage import starpilot_storage_root params = Params() @@ -397,16 +400,29 @@ def _run(): return drive_state.snapshot().mode is Mode.OFFROAD and physical.update_ready(params.get_bool('IsOffroad')) def parked(): - allowed = wait_for_parked(sm, params, stopped=lambda: stopped, powered_offroad=powered_offroad) - if not allowed and not stopped and params.get_bool('IsOffroad'): - reason = parked_blocker(sm, params, powered_offroad=powered_offroad) - report.set({'status': 'collecting', 'reason': reason or 'waiting_for_parked_permission'}) - return allowed + return wait_for_parked(sm, params, stopped=lambda: stopped, powered_offroad=powered_offroad) + + def blocker(): + return parked_blocker(sm, params, stopped=stopped, powered_offroad=powered_offroad) or 'waiting_for_parked_permission' + + interrupted = None def permitted(): - okay = parked() + nonlocal interrupted + allowed = parked() + if not allowed and interrupted is None: + interrupted = blocker() + report.publish() + return allowed + + def last_blocker(): + return interrupted + + def on_progress(progress): + reason = {'verifying': 'verifying_recorded_drive', 'checking': 'checking_recorded_steering_recommendations'}.get( + progress['phase'], 'analyzing_last_completed_drive') + report.analyzing({'status': 'fitting', 'reason': reason, 'analysis_progress': progress}) report.publish() - return okay cache = directory_for_params(params) worker = None @@ -434,7 +450,12 @@ def _run(): report.publish(), ), ) - elif parked() and time.monotonic() >= next_analysis: + elif not parked(): + if not stopped and params.get_bool('IsOffroad'): + reason = blocker() + if report.current.get('reason') != reason: + report.set({'status': 'collecting', 'reason': reason}) + elif time.monotonic() >= next_analysis: if worker is None: report.analyzing({'status': 'fitting', 'reason': 'loading_parked_analysis'}) report.publish() @@ -446,9 +467,7 @@ def _run(): cache, permitted=permitted, on_analysis=lambda: report.analyzing({'status': 'fitting', 'reason': 'analyzing_last_completed_drive'}), - on_progress=lambda progress: report.analyzing({'status': 'fitting', 'reason': - 'checking_recorded_steering_recommendations' if progress['phase'] == 'checking' else 'analyzing_last_completed_drive', - 'analysis_progress': progress}), + on_progress=on_progress, on_assessment=lambda a: report.analyzing( { 'status': 'fitting', @@ -463,7 +482,8 @@ def _run(): ) report.restore(worker.cache) next_analysis = time.monotonic() + 10.0 - if run_parked_analysis(worker, report): + interrupted = None + if run_parked_analysis(worker, report, permission_loss=last_blocker): next_analysis = time.monotonic() report.publish() if not stopped: @@ -474,9 +494,7 @@ def _run(): 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' - ): + if diagnostics is not None and diagnostics.state['current'] is not None and diagnostics.state['current']['stage'] in ACTIVE: diagnostics.observe({'status': 'unavailable', 'reason': 'analysis_interrupted_by_shutdown'}) try: if sm is not None: diff --git a/openpilot/starpilot/flm/tests/test_diagnostic_state.py b/openpilot/starpilot/flm/tests/test_diagnostic_state.py index 7949a01125..465b8dd0dd 100644 --- a/openpilot/starpilot/flm/tests/test_diagnostic_state.py +++ b/openpilot/starpilot/flm/tests/test_diagnostic_state.py @@ -81,6 +81,34 @@ class TestDiagnosticState(unittest.TestCase): self.assertEqual(report.current['analysis_counts']['recorded_tracking'], 99) self.assertEqual(read_state(self.params)['last_attempt']['analysis_counts']['recorded_tracking'], 1234) + def test_current_verification_and_its_interruption_are_distinct_from_previous_drive(self): + from openpilot.starpilot.flm.offroad_route import RouteInputCancelled + + report = daemon.StatusReport(path=self.root / 'report.json') + report.diagnostics = DiagnosticState(self.params) + report.previous = {'completed_route': 'earlier-drive', 'vehicle': 'KIA_NIRO_PHEV_2022', + 'analysis_counts': {'original_segments_reviewed': 3, 'original_segments_available': 3}} + report.analyzing({'status': 'fitting', 'reason': 'verifying_recorded_drive', + 'analysis_progress': {'phase': 'verifying', 'completed': 2, 'total': 2}}) + report.publish() + active = self.exported(json.loads(report.path.read_bytes())) + self.assertEqual(active['current']['analysis']['Parked analysis progress'], ['verifying', 2, 2]) + self.assertTrue(active['current']['analysis']['Earlier analysis shown while updating']) + self.assertEqual(active['current']['analysis']['Recorded drive coverage'], '3 of 3 original recorded segments reviewed') + + def cancelled(): + raise RouteInputCancelled('Parked route input collection cancelled') + + worker = SimpleNamespace(run_once=cancelled) + reason = 'waiting_for_fresh_deviceState' + self.assertFalse(daemon.run_parked_analysis(worker, report, permission_loss=lambda: reason)) + self.assertEqual(report.current['reason'], reason) + outcome = self.exported()['learning_diagnostics']['last_result'] + self.assertEqual(outcome['reason'], reason) + self.assertEqual(outcome['interrupted_stage'], 'verifying_recording') + self.assertEqual(report.previous['completed_route'], 'earlier-drive') + self.assertFalse(directory_for_params(self.params).exists()) + 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) diff --git a/openpilot/starpilot/galaxy/flm_diagnostics.py b/openpilot/starpilot/galaxy/flm_diagnostics.py index 8873fa7b59..f729b79025 100644 --- a/openpilot/starpilot/galaxy/flm_diagnostics.py +++ b/openpilot/starpilot/galaxy/flm_diagnostics.py @@ -22,6 +22,8 @@ def _explanation(reason): '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.', + 'verifying_recorded_drive': 'The sections were read. FLM is verifying that the recording is unchanged.', + 'Parked route input collection cancelled': 'Reading was interrupted before the drive assessment finished. This report has no specific blocker.', '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.', @@ -122,6 +124,7 @@ def diagnostics(report, params): 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 ( + 'Parked analysis progress', 'Earlier analysis shown while updating', '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', 'Recorded suggestion assessments', diff --git a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs index 4c97e801bc..4406beb0ed 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs @@ -227,12 +227,20 @@ console.log('Saved curve and slider adjustments, unsaved recommendations, absent const scan = report();scan.current.status = 'fitting';scan.current.reason = 'analyzing_last_completed_drive' scan.current.details['Original route segments reviewed'] = [99, 99] assert.equal(parkedAnalysisProgress(scan).percent, null) -for (const [phase, percent] of [['reading', 20], ['verifying', 20], ['checking', null]]) { +for (const [phase, percent, detail] of [ + ['reading', 20, '2 of 10 sections read in this recording'], + ['verifying', null, 'Checking that the recording is unchanged.'], + ['checking', null, 'Checking the suggested changes.'], +]) { scan.current.details['Parked analysis progress'] = [phase, 2, 10] assert(validTrainingResults(scan)) assert.equal(parkedAnalysisProgress(scan).percent, percent) - assert.equal(parkedAnalysisProgress(scan).detail, '2 of 10 sections read in this recording') + assert.equal(parkedAnalysisProgress(scan).detail, detail) } +scan.current.details['Parked analysis progress'] = ['reading', 3, 3] +assert.equal(parkedAnalysisProgress(scan).percent, null) +scan.current.reason = 'verifying_recorded_drive' +assert.equal(tunerStatus(scan, true).key, 'fitting') for (const counts of [[11, 10], [-1, 10], [true, 10], [1, 181], [1.5, 10], [null, null]]) { scan.current.details['Parked analysis progress'] = ['reading', ...counts] assert.equal(parkedAnalysisProgress(scan).percent, null) diff --git a/openpilot/starpilot/galaxy/web/js/flm-training-results.js b/openpilot/starpilot/galaxy/web/js/flm-training-results.js index c84e1e2588..21f7736a24 100644 --- a/openpilot/starpilot/galaxy/web/js/flm-training-results.js +++ b/openpilot/starpilot/galaxy/web/js/flm-training-results.js @@ -222,7 +222,8 @@ const REASONS = { trial_measurement_inconclusive: "Your saved steering adjustments are kept for the next drive.", trial_inconclusive_drive_limit: "Three trial drives did not establish an improvement. The prior tune was restored.", next_drive_observed_tracking_worse: "Comparable driving showed a steering regression, so the prior tune was restored.", - analyzing_last_completed_drive: "Analyzing the last completed drive while parked.", + analyzing_last_completed_drive: "Reading the completed drive.", + verifying_recorded_drive: "The sections were read. Auto Learn is verifying the recording.", checking_recorded_steering_recommendations: "Checking the recorded-drive recommendations against the original controller and steering outputs.", recorded_tracking_suggestion_not_yet_qualified_for_automatic_application: "Auto Learn reviewed the drive and left your tune unchanged. Consistent suggestions are listed when available.", original_controller_or_registered_encoder_check_refused: "A tune was suggested, but at least one original controller or encoder check refused it. Your saved tune was kept.", @@ -407,7 +408,7 @@ export function parkedAnalysisProgress(report) { const labels = { preparing: 'Preparing drive analysis', reading: 'Reading a recorded drive', verifying: 'Verifying the recording', checking: 'Checking steering suggestions' } const fallback = { loading_parked_analysis: 'preparing', analyzing_last_completed_drive: 'reading', - checking_recorded_steering_recommendations: 'checking' }[current.reason] + verifying_recorded_drive: 'verifying', checking_recorded_steering_recommendations: 'checking' }[current.reason] const value = current.details?.['Parked analysis progress'] const phase = Array.isArray(value) && value.length === 3 && Object.hasOwn(labels, value[0]) ? value[0] : fallback if (!Object.hasOwn(labels, phase)) return null @@ -416,8 +417,8 @@ export function parkedAnalysisProgress(report) { const steps = { preparing: 'Starting the parked analyzer.', reading: 'Reading the recording sections.', verifying: 'Checking that the recording is unchanged.', checking: 'Checking the suggested changes.' } return { phase, label: labels[phase], completed: counted ? done : null, total: counted ? total : null, - percent: counted && ['reading', 'verifying'].includes(phase) ? done / total * 100 : null, - detail: counted ? `${done} of ${total} sections read in this recording` : steps[phase] } + percent: counted && phase === 'reading' && done < total ? done / total * 100 : null, + detail: counted && phase === 'reading' ? `${done} of ${total} sections read in this recording` : steps[phase] } } export function tunerStatus(report, live = false, choiceLive = false, error = "", reportFresh = live) { @@ -426,7 +427,7 @@ export function tunerStatus(report, live = false, choiceLive = false, error = "" if (error) return { key: "offline", tone: "muted", title: "Connection interrupted", description: "Earlier results are available below. Current steering activity is unknown." } if (preference?.valid && preference.enabled === false || !preference && live && current?.enabled === false) return { key: "off", tone: "muted", title: "Auto Learn is off", description: "No driving samples are being collected by the learner. Turn it on in steering settings to begin." } - if (reportFresh && current?.status === 'fitting' && ['analyzing_last_completed_drive', 'checking_recorded_steering_recommendations'].includes(current.reason)) + if (reportFresh && current?.status === 'fitting' && ['analyzing_last_completed_drive', 'verifying_recorded_drive', 'checking_recorded_steering_recommendations'].includes(current.reason)) return { key: 'fitting', tone: 'active', title: 'Analyzing your drive', description: learningReason(current.reason) + (offroadView(report)?.retained ? ' Earlier drive findings remain below while this analysis runs.' : '') } if (reportFresh && preference?.valid && preference.enabled && preference.parked && current?.reason?.startsWith('waiting_for_')) return { key: 'waiting-parked', tone: 'muted', title: 'Waiting to analyze your drive', description: learningReason(current.reason) } diff --git a/prebuilt.json b/prebuilt.json index d31e64e419..680aeb1a5c 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "e38f125d59d99fac84da2874cf5ad1906e4cdbcb56fa7192cdc225c6e506f55b", "schema_version": 1} +{"protected_inventory_sha256": "00b3667060cdce8c9ae0cdc19a5fc64fe5771e1d7926dd616f2b62c427607600", "schema_version": 1}