mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-03 00:03:40 +08:00
Bind VIN-unknown learning to registered-device ECU configuration
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"old_sources": {
|
||||
"openpilot/starpilot/flm/offroad_runtime.py": "9c5d27edea4a0031faf628a13e6eabfd91a63649ef459d26caa0dfdc6f9d7ecd",
|
||||
"openpilot/starpilot/flm/runtime_adapter_registry.py": "cfd0e1ac74693cf4c13c7ba2b1f86dd2e1b0dc4b87a29be4ca33ad60412805ba",
|
||||
"openpilot/starpilot/flm/steering_compatibility.py": "53f9b0a706cbd84f10f414ab4f90138a2789e6975fb78a06d8b08dd8a2bcfed1"
|
||||
},
|
||||
"purpose": "known-vin-registered-device-fallback-only",
|
||||
"reviewed_sources": {
|
||||
"openpilot/starpilot/flm/identity_transition.py": "e221c502135f10ab715dece09437563dff81be3029fe2271dfc5f3ce6420c6f8",
|
||||
"openpilot/starpilot/flm/offroad_runtime.py": "bd63e11ef055b246c17144893bc3d731ca32f55c1414020aacd6a70556da20ca",
|
||||
"openpilot/starpilot/flm/runtime_adapter_registry.py": "fd532fddc1798c2b82c2b13975b926ddc109d8bf3fb54c2f37b82f2f28be3344",
|
||||
"openpilot/starpilot/flm/steering_compatibility.py": "1312c2d93bc9d407268b596f428cfa0c8ff449f22d4e4da9b3b2e21a969bf594",
|
||||
"openpilot/starpilot/flm/vehicle_identity.py": "71fa38fd023b1e60b101afb2b3bc7195b497cdd90e233a7ec6b5e34466f1caed"
|
||||
},
|
||||
"source_parent": "1469d5ba8fec3fab559e3e1eea3a5e69835f049a",
|
||||
"version": 1
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
"""One audited identity-only transition, never a generic source-hash bypass.
|
||||
|
||||
For an already identified VIN, registered-device fallback does not change the
|
||||
controller, source epoch, numeric baseline or settings. Recompute its previous
|
||||
compatibility key only while every reviewed identity implementation matches.
|
||||
All other controller/interface/native sources are still hashed normally.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
PARENT = '1469d5ba8fec3fab559e3e1eea3a5e69835f049a'
|
||||
PREFIX = 'openpilot/starpilot/flm/'
|
||||
REPLACED = frozenset(PREFIX + name for name in ('offroad_runtime.py', 'runtime_adapter_registry.py', 'steering_compatibility.py'))
|
||||
EXTRA = frozenset(PREFIX + name for name in ('vehicle_identity.py', 'identity_transition.py', 'identity_transition.json'))
|
||||
REVIEWED = REPLACED | (EXTRA - {PREFIX + 'identity_transition.json'})
|
||||
|
||||
|
||||
def _bytes(path, limit):
|
||||
if path.is_symlink() or not path.is_file() or not 0 <= path.stat().st_size <= limit:
|
||||
raise ValueError('Unavailable reviewed identity source')
|
||||
raw = path.read_bytes()
|
||||
if not 0 <= len(raw) <= limit:
|
||||
raise ValueError('Identity source size changed')
|
||||
return raw
|
||||
|
||||
|
||||
def _unique(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError('Duplicate identity transition field')
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def known_vin_revision(root, controller_file, brand_file, names, native):
|
||||
"""Caller must establish a genuine VIN. A mismatch uses the current full key."""
|
||||
from openpilot.starpilot.flm.steering_compatibility import source_paths, REVISION
|
||||
|
||||
root = Path(root).resolve()
|
||||
try:
|
||||
document = json.loads(_bytes(root / (PREFIX + 'identity_transition.json'), 8192), object_pairs_hook=_unique)
|
||||
if (type(document) is not dict or set(document) != {'version', 'purpose', 'source_parent', 'old_sources', 'reviewed_sources'}
|
||||
or type(document['version']) is not int or document['version'] != 1
|
||||
or document['purpose'] != 'known-vin-registered-device-fallback-only'
|
||||
or document['source_parent'] != PARENT):
|
||||
return None
|
||||
before, reviewed = document['old_sources'], document['reviewed_sources']
|
||||
if type(before) is not dict or type(reviewed) is not dict or set(before) != REPLACED or set(reviewed) != REVIEWED:
|
||||
return None
|
||||
if any(type(value) is not str or re.fullmatch('[0-9a-f]{64}', value) is None for value in (*before.values(), *reviewed.values())):
|
||||
return None
|
||||
if any(hashlib.sha256(_bytes(root / path, 2 * 1024 * 1024)).hexdigest() != expected for path, expected in reviewed.items()):
|
||||
return None
|
||||
paths = source_paths(root, controller_file, brand_file)
|
||||
relative = {str(path.relative_to(root)) for path in paths}
|
||||
if not 10 <= len(paths) <= 512 or not EXTRA <= relative:
|
||||
return None
|
||||
result = hashlib.sha256(repr((REVISION, names, native)).encode())
|
||||
for path in paths:
|
||||
name = str(path.relative_to(root))
|
||||
if name in EXTRA:
|
||||
continue
|
||||
actual = hashlib.sha256(_bytes(path, 2 * 1024 * 1024)).hexdigest()
|
||||
result.update(name.encode())
|
||||
result.update(bytes.fromhex(before.get(name, actual)))
|
||||
return REVISION + ':' + result.hexdigest()
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return None
|
||||
@@ -18,7 +18,7 @@ REVISION = 'actual-controller-registry-v2'
|
||||
|
||||
|
||||
@cache
|
||||
def implementation_revision(controller_type, interface_type):
|
||||
def implementation_revision(controller_type, interface_type, *, vin_compatible=False):
|
||||
"""Selected steering semantics; startup only, never Controls.tick."""
|
||||
from openpilot.starpilot.flm.native_primitives import native_identity
|
||||
from openpilot.starpilot.flm.steering_compatibility import revision
|
||||
@@ -27,7 +27,13 @@ def implementation_revision(controller_type, interface_type):
|
||||
controller = Path(cast(str, importlib.import_module(controller_type.__module__).__file__)).resolve()
|
||||
interface = Path(cast(str, importlib.import_module(interface_type.__module__).__file__)).resolve()
|
||||
names = (controller_type.__module__ + '.' + controller_type.__qualname__, interface_type.__module__ + '.' + interface_type.__qualname__)
|
||||
return revision(here.parents[2], controller, interface, names, native_identity())
|
||||
native = native_identity()
|
||||
if vin_compatible:
|
||||
from openpilot.starpilot.flm.identity_transition import known_vin_revision
|
||||
previous = known_vin_revision(here.parents[2], controller, interface, names, native)
|
||||
if previous is not None:
|
||||
return previous
|
||||
return revision(here.parents[2], controller, interface, names, native)
|
||||
|
||||
|
||||
SOURCE_LEASE_NS = 500_000_000
|
||||
@@ -420,7 +426,10 @@ def selected_descriptor(cp, ci, controller):
|
||||
turn_assist = bool(
|
||||
getattr(controller, 'turn_assist', None) or getattr(getattr(getattr(controller, 'starpilot_extension', None), 'policy', None), 'turn_assist', False)
|
||||
)
|
||||
return ControllerDescriptor(domain, mode, policy, implementation_revision(type(controller), type(ci)), stage, car_params_digest(cp), conversion, turn_assist)
|
||||
from opendbc.car.vin import VIN_UNKNOWN, is_valid_vin
|
||||
vin_compatible = is_valid_vin(str(cp.carVin)) and str(cp.carVin) != VIN_UNKNOWN
|
||||
implementation = implementation_revision(type(controller), type(ci), vin_compatible=vin_compatible)
|
||||
return ControllerDescriptor(domain, mode, policy, implementation, stage, car_params_digest(cp), conversion, turn_assist)
|
||||
|
||||
|
||||
def baseline_values(controller):
|
||||
|
||||
@@ -9,7 +9,7 @@ import hashlib
|
||||
|
||||
REVISION = 'selected-steering-compatibility-v1'
|
||||
FLM = (
|
||||
'steering_compatibility', 'vehicle_identity', 'runtime_adapter_registry', 'canonical_surface_adapter', 'offroad_surface',
|
||||
'steering_compatibility', 'vehicle_identity', 'identity_transition', 'runtime_adapter_registry', 'canonical_surface_adapter', 'offroad_surface',
|
||||
'offroad_runtime', 'offroad_store', 'torque_stages', 'pid_stages', 'selected_effects', 'manual_coordinates',
|
||||
'live', 'torque_surface', 'global_runtime', 'adaptive_profile', 'torque_adapter', 'learning_wire', 'native_refinement_wire',
|
||||
)
|
||||
@@ -20,7 +20,7 @@ def source_paths(root, controller_file, brand_file):
|
||||
root = Path(root)
|
||||
brand = Path(brand_file).parent
|
||||
controller = Path(controller_file).parent
|
||||
paths = {Path(controller_file), Path(brand_file)}
|
||||
paths = {Path(controller_file), Path(brand_file), root / 'openpilot/starpilot/flm/identity_transition.json'}
|
||||
paths.update(root / 'openpilot/starpilot/flm' / (name + '.py') for name in FLM)
|
||||
paths.update(root / 'openpilot/common' / (name + '.py') for name in COMMON)
|
||||
paths.update(p for p in controller.glob('*.py') if p.name.startswith(('latcontrol', 'vehicle_model', 'drive_helpers')))
|
||||
|
||||
Binary file not shown.
@@ -1,7 +1,13 @@
|
||||
"""Declared registered-device identities; never proof of a unique physical VIN."""
|
||||
import bz2
|
||||
import gzip
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Any, cast
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -13,9 +19,9 @@ from openpilot.common.prefix import OpenpilotPrefix
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.hyundai.values import CAR
|
||||
from openpilot.starpilot.flm.offroad_runtime import current_scope, configuration_scope, _current_controller, VehicleIdentityUnavailable
|
||||
from openpilot.starpilot.flm.offroad_store import KEY, RouteStorage
|
||||
from openpilot.starpilot.flm.offroad_store import KEY, RouteStorage, startup_row
|
||||
from openpilot.starpilot.flm.offroad_worker import OffroadWorker
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import read_source
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import read_source, selected_descriptor
|
||||
from openpilot.starpilot.flm.tests import test_offroad_coordinate_policy as saved_fixtures
|
||||
from openpilot.starpilot.flm.tests import test_offroad_fault_isolation as route_fixtures
|
||||
from openpilot.starpilot.flm.vehicle_identity import identity_keys, persistent_unit
|
||||
@@ -28,7 +34,7 @@ class TestRegisteredDeviceVehicleIdentity(unittest.TestCase):
|
||||
self.root = Path(directory)
|
||||
self.params = Params(str(self.root / 'params'))
|
||||
self.params.put_bool('OpenpilotEnabledToggle', True, block=True)
|
||||
self.params.put('DongleId', b'abcdef0123456789', block=True)
|
||||
self.params.put('DongleId', 'abcdef0123456789', block=True)
|
||||
self.cp = interfaces[CAR.HYUNDAI_SONATA_HYBRID].get_non_essential_params(CAR.HYUNDAI_SONATA_HYBRID)
|
||||
self.cp.carVin = '0' * 17
|
||||
self.cp.init('carFw', 1)[0].fwVersion = b'declared synthetic Sonata ECU firmware'
|
||||
@@ -57,7 +63,7 @@ class TestRegisteredDeviceVehicleIdentity(unittest.TestCase):
|
||||
self.assertTrue(RouteStorage(self.params).save(saved, expected=None, authorized=lambda: True))
|
||||
original = self.params.get(KEY)
|
||||
first = self.binding()
|
||||
self.params.put('DongleId', b'0123456789abcdef', block=True)
|
||||
self.params.put('DongleId', '0123456789abcdef', block=True)
|
||||
second = self.binding()
|
||||
self.cp.carFw[0].fwVersion = b'different declared firmware'
|
||||
third = self.binding()
|
||||
@@ -84,7 +90,7 @@ class TestRegisteredDeviceVehicleIdentity(unittest.TestCase):
|
||||
if device is None:
|
||||
self.params.remove('DongleId')
|
||||
else:
|
||||
self.params.put('DongleId', device, block=True)
|
||||
self.params.put('DongleId', device.decode('ascii'), block=True)
|
||||
self.assertTrue(self.live().enabled)
|
||||
self.assertEqual(self.live().persistent_source_epoch, '')
|
||||
with self.assertRaises(VehicleIdentityUnavailable):
|
||||
@@ -139,10 +145,104 @@ class TestRegisteredDeviceVehicleIdentity(unittest.TestCase):
|
||||
self.params.remove('DongleId')
|
||||
self.cp.init('carFw', 0)
|
||||
before = self.live()
|
||||
self.params.put('DongleId', b'fedcba9876543210', block=True)
|
||||
self.params.put('DongleId', 'fedcba9876543210', block=True)
|
||||
self.assertEqual(before.persistent_source_epoch, self.live().persistent_source_epoch)
|
||||
self.assertEqual(before.source_epoch, self.live().source_epoch)
|
||||
|
||||
def selected_sources(self):
|
||||
from openpilot.starpilot.flm.native_primitives import native_identity
|
||||
from openpilot.starpilot.flm.steering_compatibility import source_paths
|
||||
|
||||
ci, controller = _current_controller(self.cp, self.params)
|
||||
root = Path(__file__).resolve().parents[4]
|
||||
types = (type(controller), type(ci))
|
||||
files = tuple(Path(cast(str, importlib.import_module(t.__module__).__file__)).resolve() for t in types)
|
||||
names = tuple(t.__module__ + '.' + t.__qualname__ for t in types)
|
||||
return root, files, names, native_identity(), source_paths(root, *files), ci, controller
|
||||
|
||||
@staticmethod
|
||||
def copy_sources(root, destination, paths):
|
||||
for path in paths:
|
||||
output = destination / path.relative_to(root)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(path, output)
|
||||
|
||||
def test_known_vin_saved_keys_and_every_trial_state_match_actual_published_source_without_retagging(self):
|
||||
self.cp.carVin = 'KMHL341JBLU000001'
|
||||
root, files, names, native, paths, ci, controller = self.selected_sources()
|
||||
fixture = json.loads(gzip.decompress((Path(__file__).parent / 'fixtures/identity_previous_sources.json.gz').read_bytes()))
|
||||
ledger = json.loads((root / 'openpilot/starpilot/flm/identity_transition.json').read_bytes())
|
||||
self.assertEqual(fixture['source_parent'], ledger['source_parent'])
|
||||
old_root = self.root / 'published-source'
|
||||
self.copy_sources(root, old_root, paths)
|
||||
for path, source in fixture['files'].items():
|
||||
self.assertEqual(hashlib.sha256(source.encode()).hexdigest(), ledger['old_sources'][path])
|
||||
(old_root / path).write_text(source)
|
||||
# Run the unchanged published hasher, not a second copy of the new alias algorithm.
|
||||
namespace: dict[str, Any] = {}
|
||||
source = fixture['files']['openpilot/starpilot/flm/steering_compatibility.py']
|
||||
exec(compile(source, 'published-steering-compatibility', 'exec'), namespace)
|
||||
old_revision = namespace['revision'](old_root, *(old_root / path.relative_to(root) for path in files), names, native)
|
||||
descriptor = selected_descriptor(self.cp, ci, controller)
|
||||
self.assertIsNotNone(descriptor)
|
||||
self.assertEqual(descriptor.controller_revision, old_revision)
|
||||
scope = current_scope(self.cp, self.params)
|
||||
previous: dict[str, Any] = {}
|
||||
exec(compile(fixture['files']['openpilot/starpilot/flm/offroad_runtime.py'], 'published-offroad-runtime', 'exec'), previous)
|
||||
old_scope, _ = previous['configuration_scope'](self.cp, ci, controller, self.params, manual_status='not_configured')
|
||||
self.assertEqual(scope, old_scope)
|
||||
for state in ('ready_for_next_drive', 'accepted_after_drive', 'retained_after_drive', 'rolled_back'):
|
||||
with self.subTest(state=state):
|
||||
params = Params(str(self.root / state))
|
||||
row = saved_fixtures.TestSavedSetupCapacity.row(1)
|
||||
row['scope'] = old_scope.document()
|
||||
storage = RouteStorage(params)
|
||||
self.assertTrue(storage.save(row, expected=None, authorized=lambda: True))
|
||||
if state != 'ready_for_next_drive':
|
||||
self.assertTrue(storage.resolve(scope=old_scope, expected=params.get(KEY), outcome=state,
|
||||
route_sha256='e' * 64, completed_wall_ns=2, analysis_sha256='f' * 64, authorized=lambda: True))
|
||||
before = params.get(KEY)
|
||||
loaded, status = startup_row(params, scope)
|
||||
self.assertEqual(status, 'route_tune_loaded')
|
||||
self.assertEqual(loaded['state'], state)
|
||||
self.assertEqual(loaded['values'], row['previous'] if state == 'rolled_back' else row['values'])
|
||||
self.assertEqual(params.get(KEY), before, 'Loading must not rewrite history or restart a trial')
|
||||
self.cp.carVin = '0' * 17
|
||||
ci, controller = _current_controller(self.cp, self.params)
|
||||
unknown = selected_descriptor(self.cp, ci, controller)
|
||||
self.assertIsNotNone(unknown)
|
||||
self.assertNotEqual(unknown.controller_revision, old_revision, 'New fallback identity never inherits legacy qualification')
|
||||
|
||||
def test_known_vin_transition_rejects_unreviewed_sources_and_still_binds_controller_safety_and_native(self):
|
||||
from openpilot.starpilot.flm.identity_transition import known_vin_revision
|
||||
|
||||
root, files, names, native, paths, _, _ = self.selected_sources()
|
||||
copied = self.root / 'source-mutations'
|
||||
self.copy_sources(root, copied, paths)
|
||||
selected = tuple(copied / path.relative_to(root) for path in files)
|
||||
baseline = known_vin_revision(copied, *selected, names, native)
|
||||
self.assertIsNotNone(baseline)
|
||||
for path in (copied / 'openpilot/starpilot/flm/vehicle_identity.py',
|
||||
copied / 'openpilot/starpilot/flm/identity_transition.py'):
|
||||
before = path.read_bytes()
|
||||
path.write_bytes(before + b'\n# unreviewed change\n')
|
||||
self.assertIsNone(known_vin_revision(copied, *selected, names, native))
|
||||
path.write_bytes(before)
|
||||
ledger = copied / 'openpilot/starpilot/flm/identity_transition.json'
|
||||
before = ledger.read_bytes()
|
||||
document = json.loads(before)
|
||||
document['source_parent'] = '0' * 40
|
||||
ledger.write_text(json.dumps(document))
|
||||
self.assertIsNone(known_vin_revision(copied, *selected, names, native))
|
||||
ledger.write_bytes(before)
|
||||
safety = next(path for path in paths if path.suffix == '.h' and '/safety/' in str(path))
|
||||
for path in (selected[0], copied / safety.relative_to(root)):
|
||||
before = path.read_bytes()
|
||||
path.write_bytes(before + b'\n// changed steering source\n')
|
||||
self.assertNotEqual(known_vin_revision(copied, *selected, names, native), baseline)
|
||||
path.write_bytes(before)
|
||||
self.assertNotEqual(known_vin_revision(copied, *selected, names, ('changed-native', native)), baseline)
|
||||
|
||||
def test_late_registration_invalidates_review_checkpoint_without_requalifying_missing_original_metadata(self):
|
||||
directory = str(self.root / 'late')
|
||||
params, cp, logs = route_fixtures.TestUnidentifiedVehicleReview.setup(directory, firmware=b'declared firmware')
|
||||
@@ -150,7 +250,7 @@ class TestRegisteredDeviceVehicleIdentity(unittest.TestCase):
|
||||
checker=lambda *a, **k: self.fail('No original controller metadata was recorded'))
|
||||
original = worker.run_once()
|
||||
self.assertEqual(original['reason'], 'vehicle_identity_unavailable')
|
||||
params.put('DongleId', b'abcdef0123456789', block=True)
|
||||
params.put('DongleId', 'abcdef0123456789', block=True)
|
||||
updated = worker.run_once()
|
||||
self.assertNotEqual(original['assessment_sha256'], updated['assessment_sha256'])
|
||||
self.assertNotEqual(updated['reason'], 'vehicle_identity_unavailable')
|
||||
@@ -159,7 +259,7 @@ class TestRegisteredDeviceVehicleIdentity(unittest.TestCase):
|
||||
self.assertGreater(updated['recommendation_count'], 0)
|
||||
self.assertEqual(worker.cache.get(original['assessment_sha256'])['kind'], 'identity_review')
|
||||
# A changed/invalid configuration must not reuse a previously valid report.
|
||||
params.put('SteeringDelayPreferences', b'not a valid delay document', block=True)
|
||||
Path(params.get_param_path('SteeringDelayPreferences')).write_bytes(b'not a valid delay document')
|
||||
with self.assertRaisesRegex(ValueError, 'Invalid steering delay baseline'):
|
||||
worker.run_once()
|
||||
params.remove('SteeringDelayPreferences')
|
||||
@@ -168,7 +268,7 @@ class TestRegisteredDeviceVehicleIdentity(unittest.TestCase):
|
||||
def test_registered_unknown_vin_final_truncated_zstd_dispatch_is_partial_and_never_saves(self):
|
||||
directory = str(self.root / 'tail')
|
||||
params, cp, logs = route_fixtures.TestUnidentifiedVehicleReview.setup(directory, firmware=b'declared firmware')
|
||||
params.put('DongleId', b'abcdef0123456789', block=True)
|
||||
params.put('DongleId', 'abcdef0123456789', block=True)
|
||||
segment = next(logs.iterdir())
|
||||
raw = bz2.decompress((segment / 'rlog.bz2').read_bytes())
|
||||
bodies = [[], []]
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "5c382e2355dad68eb063671f281961e9a30861a25242a798c34147ea78e53ce6", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "82b7d696484588f75bf77567facaa87993139e1ec6873c882a612aec6406ed2b", "schema_version": 1}
|
||||
|
||||
Reference in New Issue
Block a user