mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-25 14:23:45 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e4e3e945b2 |
@@ -1594,3 +1594,32 @@ struct LiveTrackingResponseWitness @0xdaa1a9f0d8968e31 {
|
||||
residualRmse @6 :Float64; validUntilMonoTime @7 :UInt64;
|
||||
}
|
||||
|
||||
struct ConditionalModelState {
|
||||
session @0 :Text;
|
||||
requestId @1 :Text;
|
||||
phase @2 :Text;
|
||||
activeModel @3 :Text;
|
||||
highwayModel @4 :Text;
|
||||
cityModel @5 :Text;
|
||||
error @6 :Text;
|
||||
frameMonoTime @7 :UInt64;
|
||||
canSwitch @8 :Bool;
|
||||
processPid @9 :UInt32;
|
||||
processStartTicks @10 :UInt64;
|
||||
sessionStartMonoTime @11 :UInt64;
|
||||
transitionSeconds @12 :Float32;
|
||||
fallbackModel @13 :Text;
|
||||
paused @14 :Bool;
|
||||
targetMode @15 :Text;
|
||||
thresholdMph @16 :UInt16;
|
||||
unavailableReason @17 :Text;
|
||||
}
|
||||
|
||||
struct ConditionalModelAck {
|
||||
session @0 :Text;
|
||||
requestId @1 :Text;
|
||||
holding @2 :Bool;
|
||||
stateMonoTime @3 :UInt64;
|
||||
idle @4 :Bool;
|
||||
}
|
||||
|
||||
|
||||
@@ -2637,6 +2637,8 @@ struct Event {
|
||||
aolSafetyWire @124 :Data;
|
||||
aolIntentWire @125 :Data;
|
||||
laneChangeAssistWire @126 :Data;
|
||||
conditionalModelState @154 :Custom.ConditionalModelState;
|
||||
conditionalModelAck @155 :Custom.ConditionalModelAck;
|
||||
|
||||
# DO change the name of the field and struct
|
||||
# DON'T change the ID (e.g. @107)
|
||||
|
||||
@@ -70,6 +70,8 @@ _services: dict[str, tuple] = {
|
||||
"aolSafetyWire": (True, 10., 10),
|
||||
"aolIntentWire": (True, 100., 10),
|
||||
"laneChangeAssistWire": (True, 20., 10),
|
||||
"conditionalModelState": (True, 20., 1),
|
||||
"conditionalModelAck": (True, 100., 10),
|
||||
"mapdOut": (True, 20., 10),
|
||||
"mapdExtendedOut": (True, 1., 1),
|
||||
"mapdIn": (True, 1., 1),
|
||||
|
||||
@@ -316,8 +316,11 @@ def main(demo=False):
|
||||
# a Jetson, PC or phone on the port looks like a chestnut to cable_connected(): the cable counts with Jetlink off only
|
||||
chestnut_available = chestnut_present() or (cable_connected() and not jetlink_adapter.link_on() and not usb_host_connected())
|
||||
recovery_small_only = os.getenv("STARPILOT_MODELD_RECOVERY_SMALL_ONLY") == "1"
|
||||
selection = resolve_runtime(chestnut_available=chestnut_available and not recovery_small_only, randomize=not recovery_small_only)
|
||||
requested_model_id = requested_runtime_id(chestnut_available)
|
||||
recovery_model = os.getenv('STARPILOT_CONDITIONAL_RECOVERY_MODEL') if recovery_small_only else None
|
||||
recovery_options = {'small_override': recovery_model} if recovery_model else {}
|
||||
selection = resolve_runtime(chestnut_available=chestnut_available and not recovery_small_only,
|
||||
randomize=not recovery_small_only, **recovery_options)
|
||||
requested_model_id = recovery_model or requested_runtime_id(chestnut_available)
|
||||
from openpilot.starpilot.models.laboratory import freeze_request
|
||||
from openpilot.starpilot.models.laboratory_runner import LaboratoryPair, load_laboratory_pair
|
||||
from openpilot.starpilot.models.runtime_bridge.runtime import bind_laboratory_request
|
||||
@@ -454,6 +457,14 @@ def main(demo=False):
|
||||
initial_chestnut_fallback = CHESTNUT and model is None
|
||||
if model is None:
|
||||
model = small_model
|
||||
from openpilot.starpilot.models.manager import preferences
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
conditional_runtime = ConditionalModelRuntime(small_model, small_prepared, preferences(MODEL_ROOT)['conditionalModel'],
|
||||
root=MODEL_ROOT, cam_w=cam_w, cam_h=cam_h,
|
||||
enabled=model is small_model and not CHESTNUT and not jetlink_adapter.link_on() and not recovery_small_only)
|
||||
conditional_loaded_id = small_model.model_id
|
||||
if recovery_small_only and conditional_runtime.config['enabled']:
|
||||
conditional_runtime.owner.error = 'Single-model recovery is running; live switching is disabled until the next drive'
|
||||
if isinstance(model, LaboratoryPair):
|
||||
import hashlib
|
||||
import json
|
||||
@@ -462,7 +473,7 @@ def main(demo=False):
|
||||
else:
|
||||
receipt_owner.loaded(big_prepared if model.chestnut else small_prepared,
|
||||
ModelVariant.CHESTNUT if model.chestnut else ModelVariant.SMALL,
|
||||
"chestnut-run-stalled" if recovery_small_only else
|
||||
"conditional-switch-failed" if recovery_model else "chestnut-run-stalled" if recovery_small_only else
|
||||
"chestnut-load-failed" if initial_chestnut_fallback else
|
||||
"selected-load-failed" if (selected_small_failed and not model.chestnut) or requested_model_id != model.model_id else None,
|
||||
model_id=model.model_id)
|
||||
@@ -485,10 +496,11 @@ def main(demo=False):
|
||||
config_realtime_process(7, 54)
|
||||
|
||||
# messaging
|
||||
pub_socks = ["modelIdentity", "modelV2", "drivingModelData", "cameraOdometry", "laneChangeAssistWire"] + (["chestnutGpuState"] if CHESTNUT else [])
|
||||
pub_socks = (["modelIdentity", "modelV2", "drivingModelData", "cameraOdometry", "laneChangeAssistWire", "conditionalModelState"] +
|
||||
(["chestnutGpuState"] if CHESTNUT else []))
|
||||
pm = PubMaster(pub_socks)
|
||||
sm = SubMaster(["deviceState", "carState", "narrowRoadCameraState", "extrinsicsCalibration", "driverMonitoringState",
|
||||
"carControl", "controlsState", "lateralDelay", "starpilotNavigation", "longitudinalPlan"])
|
||||
"carControl", "controlsState", "lateralDelay", "starpilotNavigation", "longitudinalPlan", "selfdriveState"])
|
||||
|
||||
publish_state = PublishState()
|
||||
params = Params()
|
||||
@@ -557,6 +569,13 @@ def main(demo=False):
|
||||
meta_extra = meta_main
|
||||
|
||||
sm.update(0)
|
||||
handoff = conditional_runtime.before_frame(sm)
|
||||
if handoff is not None:
|
||||
model, small_prepared, _ = handoff
|
||||
prev_action = log.ModelDataV2.Action(desiredCurvature=float(sm['controlsState'].curvature))
|
||||
DH = DesireHelper(runtime_lane_policy)
|
||||
frame_dropped_filter.x = 0.
|
||||
run_count = 0
|
||||
turn_models = (model.lateral, model.longitudinal) if isinstance(model, LaboratoryPair) else (model,)
|
||||
turn_supported = all(state.npy.get('desire') is not None and state.npy['desire'].shape[-1] == 8 for state in turn_models)
|
||||
desire = navigation_turn.select(sm, time.monotonic_ns(), DH.desire,
|
||||
@@ -617,30 +636,46 @@ def main(demo=False):
|
||||
model.lat_delay = lat_delay
|
||||
model.frame_drop_ratio = frame_drop_ratio
|
||||
mt1 = time.perf_counter()
|
||||
conditional_action = None
|
||||
try:
|
||||
send_chestnut = (chestnut_state is not None and
|
||||
run_count % round(ModelConstants.MODEL_RUN_FREQ / SERVICE_LIST['chestnutGpuState'].frequency) == 0)
|
||||
model_output = model.run(bufs, transforms, inputs, chestnut_state.send if send_chestnut else None)
|
||||
if conditional_runtime.owner.phase == 'switching':
|
||||
conditional_action = model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
|
||||
laboratory_action = (model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
|
||||
if isinstance(model, LaboratoryPair) else None)
|
||||
except Exception:
|
||||
if not model.chestnut:
|
||||
if conditional_runtime.owner.phase == 'switching':
|
||||
cloudlog.exception('Conditional Model candidate failed; retaining the previous model')
|
||||
conditional_runtime.owner.abort('Candidate inference failed; previous model restored', time.monotonic_ns())
|
||||
model, small_prepared, _ = conditional_runtime.owner.models[conditional_runtime.owner.active]
|
||||
prev_action = log.ModelDataV2.Action(desiredCurvature=float(sm['controlsState'].curvature))
|
||||
DH = DesireHelper(runtime_lane_policy)
|
||||
conditional_action = None
|
||||
model.lat_delay, model.frame_drop_ratio = lat_delay, frame_drop_ratio
|
||||
model_output = model.run(bufs, transforms, inputs)
|
||||
elif not model.chestnut:
|
||||
raise
|
||||
# fallback to small model
|
||||
fallback_reason = "chestnut-load-failed"
|
||||
if model is jetlink_model:
|
||||
model.close()
|
||||
fallback_reason = None
|
||||
else:
|
||||
drop_chestnut()
|
||||
params.put_bool("ChestnutActive", False)
|
||||
cloudlog.exception("big model failed, fall back to small")
|
||||
model = small_model
|
||||
receipt_owner.loaded(small_prepared, ModelVariant.SMALL, fallback_reason, model_id=model.model_id)
|
||||
if chestnut_state is not None:
|
||||
chestnut_state.big = False
|
||||
run_count = 0
|
||||
model_output = None
|
||||
# Existing Chestnut/Jetlink fallback is owned below.
|
||||
model_output = None
|
||||
if model.chestnut:
|
||||
# fallback to small model
|
||||
fallback_reason = "chestnut-load-failed"
|
||||
if model is jetlink_model:
|
||||
model.close()
|
||||
fallback_reason = None
|
||||
else:
|
||||
drop_chestnut()
|
||||
params.put_bool("ChestnutActive", False)
|
||||
cloudlog.exception("big model failed, fall back to small")
|
||||
model = small_model
|
||||
receipt_owner.loaded(small_prepared, ModelVariant.SMALL, fallback_reason, model_id=model.model_id)
|
||||
if chestnut_state is not None:
|
||||
chestnut_state.big = False
|
||||
run_count = 0
|
||||
model_output = None
|
||||
mt2 = time.perf_counter()
|
||||
model_execution_time = mt2 - mt1
|
||||
if model is jetlink_model and HOOKS.handed_over(model):
|
||||
@@ -653,6 +688,11 @@ def main(demo=False):
|
||||
cloudlog.event("jetlinkHandover", state=HOOKS.state(model), handovers=model.handovers)
|
||||
|
||||
if model_output is not None and vipc_dropped_frames == 0:
|
||||
if conditional_runtime.owner.models and model.model_id != conditional_loaded_id:
|
||||
small_model = model
|
||||
receipt_owner.loaded(small_prepared, ModelVariant.SMALL, model_id=model.model_id)
|
||||
cloudlog.event('conditionalModelHandover', model_id=model.model_id, request=conditional_runtime.owner.request)
|
||||
conditional_loaded_id = model.model_id
|
||||
modelv2_send = messaging.new_message('modelV2')
|
||||
drivingdata_send = messaging.new_message('drivingModelData')
|
||||
posenet_send = messaging.new_message('cameraOdometry')
|
||||
@@ -661,7 +701,8 @@ def main(demo=False):
|
||||
assert laboratory_action is not None
|
||||
action = laboratory_action
|
||||
else:
|
||||
action = model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
|
||||
action = (conditional_action if conditional_action is not None else
|
||||
model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego))
|
||||
filter_action(action, prev_action, v_ego, subaru_tau + volkswagen_tau + kona_tau)
|
||||
prev_action = action
|
||||
fill_model_msg(modelv2_send, model_output, action,
|
||||
@@ -719,6 +760,9 @@ def main(demo=False):
|
||||
pm.send('laneChangeAssistWire', lane_status_msg)
|
||||
pm.send('drivingModelData', drivingdata_send)
|
||||
pm.send('cameraOdometry', posenet_send)
|
||||
settled_frame = (model_output is not None and vipc_dropped_frames == 0 and
|
||||
modelv2_send.valid and drivingdata_send.valid and posenet_send.valid)
|
||||
conditional_runtime.publish(pm, sm, int(modelv2_send.logMonoTime) if settled_frame else 0)
|
||||
last_vipc_frame_id = meta_main.frame_id
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -234,6 +234,8 @@ class SelfdriveD:
|
||||
self.initialized = False
|
||||
self.enabled = False
|
||||
self.active = False
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
self.conditional_model_gate = ConditionalModelGate()
|
||||
self.mismatch_counter = 0
|
||||
self.cruise_mismatch_counter = 0
|
||||
self.last_steering_pressed_frame = 0
|
||||
@@ -1300,6 +1302,8 @@ class SelfdriveD:
|
||||
for alert_type in DEPARTURE_ALERTS:
|
||||
if alert_type not in retained_types:
|
||||
self.AM.alerts.pop(alert_type, None)
|
||||
if getattr(self, 'conditional_model_gate', None) is not None:
|
||||
self.conditional_model_gate.update_alerts(alerts, self.AM, self.sm.frame)
|
||||
self.AM.add_many(self.sm.frame, alerts)
|
||||
self.AM.process_alerts(self.sm.frame, clear_event_types)
|
||||
from openpilot.starpilot.audio.availability_warning import AvailabilityWarningDelivery
|
||||
@@ -2312,6 +2316,10 @@ class SelfdriveD:
|
||||
self.events.add(EventName.controlsMismatch)
|
||||
lost_active_aol |= pause
|
||||
was_enabled = self.enabled
|
||||
conditional_gate = getattr(self, 'conditional_model_gate', None)
|
||||
conditional_hold = conditional_gate.step(self, CS) if conditional_gate is not None else False
|
||||
if conditional_hold:
|
||||
self.events.add(EventName.selfdriveInitializing)
|
||||
if self.aol_replay and source_current and was_enabled and (
|
||||
CS.doorOpen or any(event in LONGITUDINAL_ONLY_EVENTS for event in self.events.names)):
|
||||
# Ordinary cruise is withdrawn; its legacy permission is no longer expected.
|
||||
@@ -2406,6 +2414,8 @@ class SelfdriveD:
|
||||
if (getattr(self, 'hkg_angle_steering', False) and self.aol_axis_decision.lateral_active and
|
||||
EventName.steerSaturated in self.events.names and ET.WARNING not in self.state_machine.current_alert_types):
|
||||
self.state_machine.current_alert_types.append(ET.WARNING)
|
||||
if conditional_hold:
|
||||
self.aol_axis_decision = AxisDecision()
|
||||
axis_published = bool(not REPLAY and self.aol_replay and self.axis_transport_required)
|
||||
if axis_published:
|
||||
self.aol_axis_publication_deferred = bool(not previous_deferred and self.defer_expired_axis_publication(CS, initial_state))
|
||||
|
||||
@@ -29,6 +29,7 @@ class Sources:
|
||||
self.recv_frame = dict.fromkeys(self.data, self.frame)
|
||||
self.recv_frame['alertDebug'] = self.recv_frame['lateralManeuverPlan'] = 0
|
||||
self.logMonoTime = dict.fromkeys(self.data, 100_000_000_000)
|
||||
self.services = list(self.data)
|
||||
self['controlsState'].lateralControlState.init('pidState')
|
||||
self['extrinsicsCalibration'].calStatus = log.ExtrinsicsCalibration.Status.calibrated
|
||||
self['deviceState'].freeSpacePercent = 100
|
||||
@@ -79,7 +80,7 @@ def events_drive():
|
||||
|
||||
@pytest.mark.parametrize('fault,event', [('comm', EventName.commIssue),
|
||||
('posenet', EventName.posenetInvalid), ('localizer', EventName.locationdTemporaryError),
|
||||
('can', EventName.canError), ('radar', EventName.canError), ('process', EventName.processNotRunning)])
|
||||
('can', EventName.canError), ('radar', EventName.radarFault), ('process', EventName.processNotRunning)])
|
||||
def test_real_selfdrived_faults_survive_jetlink_swap(fault, event):
|
||||
drive, cs = events_drive()
|
||||
with patch('openpilot.selfdrive.selfdrived.helpers.time.monotonic', return_value=100.):
|
||||
|
||||
@@ -548,7 +548,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.models.manager import ModelManager
|
||||
authority = context_source(Params())
|
||||
model_manager_source = ModelManager(parked=authority.parked, refresh_catalog=True)
|
||||
model_manager_source = ModelManager(parked=authority.parked, refresh_catalog=True,
|
||||
live_status=lambda: model_status().get('conditionalModelState'))
|
||||
server.model_authority = authority
|
||||
server.model_manager_source = model_manager_source
|
||||
return model_manager_source
|
||||
@@ -1738,7 +1739,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
'/api/ui/layout', '/api/ui/layout/preview', '/api/favorites/slots',
|
||||
'/api/maps/start', '/api/maps/cancel',
|
||||
'/api/bluetooth/action', '/api/controllers/action',
|
||||
'/api/models/active', '/api/models/preferences', '/api/models/download', '/api/models/download_all',
|
||||
'/api/models/active', '/api/models/conditional_model', '/api/models/preferences', '/api/models/download', '/api/models/download_all',
|
||||
'/api/models/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink',
|
||||
'/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete',
|
||||
'/api/sounds/preview', '/api/sounds/download', '/api/sounds/cancel', '/api/software/action', '/api/drives/ignore',
|
||||
|
||||
@@ -81,13 +81,15 @@ assert.equal(download.requests[1].url,'./api/models/laboratory/download');assert
|
||||
await download.reply(1,{message:'Starting download'});await download.reply(2,{...p,download:{downloading:true,jobId:'job',progress:'40%'}});await downloading
|
||||
const canceling=download.feed.action('cancel');assert.equal(download.requests[3].url,'./api/models/cancel');assert.deepEqual(JSON.parse(download.requests[3].options.body),{jobId:'job'})
|
||||
await download.reply(3,{message:'Cancelling'});await download.reply(4,p);await canceling;download.feed.stop()
|
||||
// Model Laboratory lives on the Models page: Single model / Model pair mode switcher and eGPU variants on the model rows
|
||||
// Split Model has its own tab alongside Single Model and Conditional Model.
|
||||
const template = ModelsPage.template
|
||||
const labCard = template.indexOf('id="gx-model-laboratory"')
|
||||
assert.ok(template.indexOf('Single model') < labCard && labCard < template.indexOf('gx-model-list'))
|
||||
assert.match(template,/aria-label="Lateral model"/)
|
||||
assert.match(template,/aria-label="Longitudinal model"/)
|
||||
assert.ok(template.includes(`@click="setDriveMode('pair')"><i aria-hidden="true" class="bi bi-bezier2"></i> Model pair</button>`))
|
||||
assert.ok(template.indexOf('Single Model') < labCard && labCard < template.indexOf('gx-model-list'))
|
||||
assert.match(template,/aria-label="Steering model"/)
|
||||
assert.match(template,/aria-label="Speed model"/)
|
||||
assert.ok(template.includes(`@click="setDriveMode('split')"><i aria-hidden="true" class="bi bi-bezier2"></i> Split Model</button>`))
|
||||
assert.match(template, /setDriveMode\('conditional'\)/)
|
||||
assert.match(template, /Use Split Model/)
|
||||
assert.match(template,/Verified downloads/)
|
||||
assert.match(template,/eGPU variant/)
|
||||
assert.match(template,/Pairable/)
|
||||
@@ -107,7 +109,7 @@ console.log('Model Laboratory contracts passed')
|
||||
assert.match(template,/steers · \{\{ labModelLabel\(labConfig\.longitudinalModel\) \}\} paces/)
|
||||
assert.match(template,/The pair takes effect the next time the driving model starts/)
|
||||
assert.match(template,/row\?\.small \|\| row\?\.modelLabEligible/)
|
||||
assert.match(template,/Pair lateral judgment from one model with longitudinal judgment from another\./)
|
||||
assert.match(template,/One model for steering, another for speed\. Requires Chestnut\./)
|
||||
|
||||
const malformedSave=fixture();malformedSave.feed.start();await malformedSave.reply(0,p)
|
||||
const malformedSaving=malformedSave.feed.action('save',null,p.configuration)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { GalaxySettingRow, settingControl } from "../web/js/galaxy-setting-row.js"
|
||||
import { ModelStatusFeed, ModelManagerFeed, ModelsPage, modelActionAllowed, fitsModelProfile, formatRate, formatEta, describeProgress } from "../web/js/models.js"
|
||||
|
||||
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }
|
||||
@@ -48,6 +49,13 @@ await normal.reply(1, payload)
|
||||
assert.equal(normal.states.at(-1).status, "idle")
|
||||
assert.equal(normal.timers.size, 0)
|
||||
|
||||
const conditionalRecovery = fixture()
|
||||
conditionalRecovery.feed.start()
|
||||
await conditionalRecovery.reply(0, { ...payload, fallbackReason: 'conditional-switch-failed' })
|
||||
assert.equal(conditionalRecovery.states.at(-1).status, 'ready')
|
||||
assert.equal(conditionalRecovery.states.at(-1).data.fallbackReason, 'conditional-switch-failed')
|
||||
conditionalRecovery.feed.stop()
|
||||
|
||||
const late = fixture()
|
||||
late.feed.start()
|
||||
late.feed.stop()
|
||||
@@ -201,6 +209,44 @@ await download
|
||||
assert.equal(management.unauthorized, 0)
|
||||
assert.equal(management.timers.size, 0)
|
||||
|
||||
const conditionalPayload = { ...managerPayload, conditionalModel: { enabled: true, highway: 'small', city: 'pending', thresholdMph: 50 },
|
||||
capabilities: { ...managerPayload.capabilities, conditionalModel: true, randomizer: true } }
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'conditional_model'), true)
|
||||
for (const denied of [{isOnroad:true}, {isOnroad:undefined}, {randomizer:true}, {downloading:true}]) {
|
||||
assert.equal(modelActionAllowed({...conditionalPayload, ...denied}, 'conditional_model'), false)
|
||||
}
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'select-small', small), false)
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'enable-randomizer'), false)
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'delete', { ...pending, installed: true }), false)
|
||||
assert.deepEqual(ModelsPage.computed.conditionalModels.call({ models: managerPayload.models, conditionalModel: conditionalPayload.conditionalModel })
|
||||
.map(m => m.value), ['small', 'pending'])
|
||||
const conditional = managerFixture()
|
||||
conditional.manager.start()
|
||||
await conditional.reply(0, conditionalPayload)
|
||||
const speedSave = conditional.manager.action('conditional_model', null, { thresholdMph: 60 })
|
||||
assert.equal(conditional.requests[1].url, './api/models/conditional_model')
|
||||
assert.deepEqual(JSON.parse(conditional.requests[1].options.body), { thresholdMph: 60 })
|
||||
assert.equal(conditional.manager.data.conditionalModel.thresholdMph, 50)
|
||||
;[...conditional.timers.values()].find(t => t.ms === 10000).fn()
|
||||
assert.equal(conditional.manager.data, null)
|
||||
assert.equal(await conditional.manager.action('conditional_model', null, { thresholdMph: 70 }), null)
|
||||
await conditional.reply(1, { message: 'late success' })
|
||||
if (conditional.requests[2]) await conditional.reply(2, { ...conditionalPayload, conditionalModel: { ...conditionalPayload.conditionalModel, thresholdMph: 60 } })
|
||||
await speedSave
|
||||
conditional.manager.stop()
|
||||
for (const phase of ['waiting', 'switching', 'recovering', 'ready']) {
|
||||
assert.equal(ModelsPage.computed.conditionalSwitchPending.call({status:{conditionalModelState:{phase}}}), phase !== 'ready')
|
||||
}
|
||||
const speedRow = ModelsPage.computed.conditionalSpeedRow.call({conditionalModel:{thresholdMph:50}})
|
||||
assert.equal(speedRow.value, '50')
|
||||
assert.equal(settingControl(speedRow), 'slider')
|
||||
assert.equal(ModelsPage.components.GalaxySettingRow, GalaxySettingRow)
|
||||
const settingsWrites=[]
|
||||
const settingsPage={configureConditionalModel: async update => { settingsWrites.push(update); return true }}
|
||||
await ModelsPage.methods.saveConditionalSetting.call(settingsPage, 0, 'On')
|
||||
await ModelsPage.methods.saveConditionalSetting.call(settingsPage, 1, '60')
|
||||
assert.deepEqual(settingsWrites, [{enabled:true}, {thresholdMph:60}])
|
||||
|
||||
const access = managerFixture()
|
||||
access.manager.start()
|
||||
await access.reply(0, { code: "access_unavailable" }, 503)
|
||||
@@ -252,8 +298,8 @@ console.log('Randomizer and exclusion interactions passed')
|
||||
|
||||
assert.match(ModelsPage.template, /Selections apply next onroad cycle/)
|
||||
assert.doesNotMatch(ModelsPage.template, /Onroad: switching/)
|
||||
// Active Small, Active Big summary items, and the Laboratory pair's lateral and longitudinal pickers
|
||||
assert.equal((ModelsPage.template.match(/class="gx-model-control[\s"]/g) || []).length, 4)
|
||||
assert.match(ModelsPage.template, /Conditional driving models/)
|
||||
assert.match(ModelsPage.template, /Starts each drive in City/)
|
||||
// the library tab is only a view: every model is one tap away, and a sleeping GPU never hides anything
|
||||
assert.equal(ModelsPage.data().tab, 'both')
|
||||
assert.equal(ModelsPage.computed.libraryTab.call({ tab: 'gpu' }), 'gpu')
|
||||
@@ -402,6 +448,11 @@ const pairPage = { selectionUncertain: false, status: {}, runtime: { status: 're
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call(pairPage), 'Small model/Big model')
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call({ ...pairPage, runtime: { status: 'stale', data: pairData } }), 'Status unavailable')
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call({ ...pairPage, runtime: { status: 'ready', data: { ...pairData, laboratory: { ...pairData.laboratory, active: false } } } }), 'Laboratory output unavailable')
|
||||
for (const [health, expected] of [['loading', 'Loading…'], ['stale', 'Model output stale'], ['failed', 'Model status mismatch'],
|
||||
['identity-unavailable', 'Identity unverified']]) {
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call({ ...pairPage,
|
||||
runtime: { status: 'ready', data: { ...pairData, laboratory: null, health } } }), expected)
|
||||
}
|
||||
assert.match(ModelsPage.template, /fallback choices/)
|
||||
const pendingStart = data => ModelsPage.computed.pendingNextStart.call({ runtime: { status: 'ready', data } })
|
||||
assert.equal(pendingStart({ ...pairData, pendingNextStart: false }), false)
|
||||
@@ -410,6 +461,35 @@ assert.equal(pendingStart({ ...pairData, laboratory: { ...pairData.laboratory, p
|
||||
assert.equal(ModelsPage.computed.pendingNextStart.call({ runtime: { status: 'stale', data: { pendingNextStart: true } } }), false)
|
||||
assert.equal(ModelsPage.template.match(/v-if="pendingNextStart"> · saved changes pending next start/g).length, 2)
|
||||
|
||||
// Browsing settings must never change the driving configuration.
|
||||
{
|
||||
const page = { ...ModelsPage.data(), lab: { configuration: { enabled: true } }, conditionalModel: { enabled: true },
|
||||
runLabAction: () => { throw new Error('Tab navigation wrote configuration') },
|
||||
enablePair: () => { throw new Error('Tab navigation enabled Split Model') } }
|
||||
assert.equal(ModelsPage.computed.driveMode.call(page), 'split')
|
||||
for (const mode of ['conditional', 'single', 'split']) {
|
||||
ModelsPage.methods.setDriveMode.call(page, mode)
|
||||
assert.equal(ModelsPage.computed.driveMode.call(page), mode)
|
||||
}
|
||||
ModelsPage.methods.setDriveMode.call(page, 'invalid')
|
||||
assert.equal(page.driveView, 'split')
|
||||
assert.equal(ModelsPage.computed.driveMode.call({ driveView: null, lab: null, conditionalModel: { enabled: true } }), 'conditional')
|
||||
assert.equal(ModelsPage.computed.driveMode.call({ driveView: null, lab: null, conditionalModel: { enabled: false } }), 'single')
|
||||
const conditionalTemplate = ModelsPage.template.slice(ModelsPage.template.indexOf(`<template v-else-if="driveMode === 'conditional'">`),
|
||||
ModelsPage.template.indexOf('id="gx-model-laboratory"'))
|
||||
assert.match(conditionalTemplate, /Conditional driving models/)
|
||||
assert.match(conditionalTemplate, /Starts each drive in City/)
|
||||
assert.match(conditionalTemplate, /Switching conditional models/)
|
||||
assert.doesNotMatch(conditionalTemplate, /Road selection|Start the drive in|cooldown|cityDelaySeconds|type="number"|Switch to Highway|Switch to City/)
|
||||
assert.match(conditionalTemplate, /Wait before engaging/)
|
||||
const single = ModelsPage.template.slice(ModelsPage.template.indexOf(`<template v-if="driveMode === 'single'">`),
|
||||
ModelsPage.template.indexOf(`<template v-else-if="driveMode === 'conditional'">`))
|
||||
assert.doesNotMatch(single, /id="gx-small-/)
|
||||
const saved = await ModelsPage.methods.saveLabPair.call({ disposed: false, labActionAvailable: () => true,
|
||||
runLabAction: async () => ({ message: 'saved' }), enablePair: () => { throw new Error('Saving enabled Split Model') } })
|
||||
assert.equal(saved.message, 'saved')
|
||||
}
|
||||
|
||||
// Merged page: search, row list, Single model / Model pair mode switcher, and pair saving.
|
||||
{
|
||||
const { matchesSearch, laboratoryActionAllowed, hardwareTag } = await import("../web/js/models.js")
|
||||
|
||||
@@ -136,6 +136,11 @@ class LocalModelManagerHttpTest(unittest.TestCase):
|
||||
status, snapshot = request('/api/models/manager')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertFalse(snapshot['randomizer'])
|
||||
self.assertFalse(snapshot['conditionalModel']['enabled'])
|
||||
self.assertTrue(snapshot['capabilities']['conditionalModel'])
|
||||
self.assertEqual(request('/api/models/conditional_model', {'thresholdMph': 60})[0], 200)
|
||||
self.assertEqual(preferences(manager.root)['conditionalModel']['thresholdMph'], 60)
|
||||
self.assertEqual(request('/api/models/conditional_model', {'selected': 'unknown'})[0], 409)
|
||||
self.assertIsNone(snapshot['downloadProgress'])
|
||||
self.assertEqual(request('/api/models/jetlink', {'mode': 'usb'})[0], 200)
|
||||
self.assertEqual(link.mode, 'usb')
|
||||
@@ -160,6 +165,8 @@ class LocalModelManagerHttpTest(unittest.TestCase):
|
||||
self.assertEqual(preferences(manager.root)['blacklistedModels'], ['gwm8223'])
|
||||
self.assertEqual(request('/api/models/active', {'profile': 'small', 'model': 'bundled-current'})[0], 409)
|
||||
parked[0] = False
|
||||
self.assertEqual(request('/api/models/conditional_model', {'selected': 'highway'})[0], 409)
|
||||
self.assertEqual(preferences(manager.root)['conditionalModel']['thresholdMph'], 60)
|
||||
self.assertEqual(request('/api/models/jetlink', {'mode': 'off'})[0], 409)
|
||||
self.assertEqual(link.mode, 'usb')
|
||||
self.assertEqual(request('/api/models/laboratory', pair)[0], 200)
|
||||
@@ -170,6 +177,7 @@ class LocalModelManagerHttpTest(unittest.TestCase):
|
||||
self.assertEqual(request('/api/models/jetlink', {'mode': 'off'}, forwarded=True)[0], 503)
|
||||
self.assertEqual(link.mode, 'usb')
|
||||
self.assertEqual(request('/api/models/manager', forwarded=True)[0], 503)
|
||||
self.assertEqual(request('/api/models/conditional_model', {'selected': 'highway'}, forwarded=True)[0], 503)
|
||||
self.assertEqual(request('/api/models/laboratory', forwarded=True)[0], 503)
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -321,13 +321,16 @@ input[type="range"].gx-slider:active::-moz-range-thumb {
|
||||
.gx-model-manager { --panel-padding: var(--sp-4); gap: var(--sp-3); }
|
||||
.gx-model-manager .gx-btn, .gx-model-card__progress { min-height: var(--touch-target); padding: 6px var(--sp-4); }
|
||||
|
||||
/* Single / pair mode switch */
|
||||
.gx-tabs.gx-model-mode { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px; padding: 4px; border-radius: var(--radius-full);
|
||||
/* Driving model settings tabs */
|
||||
.gx-tabs.gx-model-mode { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; padding: 4px; border-radius: var(--radius-full);
|
||||
border: 1px solid var(--glass-border); background: var(--surface-container-high); }
|
||||
.gx-model-mode > button { display: inline-flex; align-items: center; justify-content: center; gap: var(--sp-2); min-height: 40px; border: 0; border-radius: var(--radius-full);
|
||||
background: transparent; color: var(--on-surface-variant); font: inherit; font-weight: var(--fw-bold); cursor: pointer; transition: background-color var(--motion-fast), color var(--motion-fast); }
|
||||
.gx-model-mode > button[aria-pressed="true"] { background: var(--primary); color: var(--on-primary); box-shadow: 0 4px 12px var(--primary-glow); }
|
||||
.gx-model-mode > button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
@media (max-width: 480px) {
|
||||
.gx-model-mode > button { flex-direction: column; gap: 2px; padding: 6px 2px; font-size: var(--fs-sm); }
|
||||
}
|
||||
|
||||
/* Driving and Laboratory controls */
|
||||
.gx-model-driving__body, .gx-model-laboratory { display: grid; gap: var(--sp-3); }
|
||||
|
||||
@@ -4,6 +4,7 @@ import { GxState } from "./state.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
import { connectionError } from "./polling.js"
|
||||
import { GalaxySelect } from "./galaxy-select.js"
|
||||
import { GalaxySettingRow, switchRow } from "./galaxy-setting-row.js"
|
||||
import { reportSave } from "./save-feedback.js"
|
||||
|
||||
// Read-only model identity; a saved label never proves what modeld loaded.
|
||||
@@ -64,7 +65,7 @@ export class ModelStatusFeed {
|
||||
if (data?.schemaVersion !== 1 || !ids.length || new Set(ids).size !== ids.length ||
|
||||
data.catalog.some(m => typeof m.id !== "string" || !m.id || typeof m.name !== "string" || typeof m.selectable !== "boolean") ||
|
||||
!ids.includes(data.requestedId) || !(data.loadedId === null || ids.includes(data.loadedId)) || !variants.includes(data.variant) ||
|
||||
!states.includes(data.health) || ![null, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed"].includes(data.fallbackReason) ||
|
||||
!states.includes(data.health) || ![null, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed", "conditional-switch-failed"].includes(data.fallbackReason) ||
|
||||
!(digest === null || typeof digest === "string" && /^[0-9a-f]{64}$/.test(digest)) ||
|
||||
typeof data.pendingNextStart !== "boolean" ||
|
||||
(data.pendingNextStart && (data.loadedId === null || data.requestedId === data.loadedId)) ||
|
||||
@@ -203,10 +204,10 @@ export function describeProgress(data, models = []) {
|
||||
}
|
||||
|
||||
|
||||
const actionPaths = { "select-small": "active", "select-big": "active", favorite: "preferences", unfavorite: "preferences",
|
||||
const actionPaths = { conditional_model: "conditional_model", "select-small": "active", "select-big": "active", favorite: "preferences", unfavorite: "preferences",
|
||||
"enable-randomizer": "preferences", "disable-randomizer": "preferences", exclude: "preferences", include: "preferences",
|
||||
download: "download", downloadAll: "download_all", cancel: "cancel", delete: "delete", refresh: "refresh_manifest", jetlink: "jetlink" }
|
||||
const actionCapabilities = { "select-small": "select", "select-big": "select", favorite: "favorites", unfavorite: "favorites",
|
||||
const actionCapabilities = { conditional_model: "conditionalModel", "select-small": "select", "select-big": "select", favorite: "favorites", unfavorite: "favorites",
|
||||
"enable-randomizer": "randomizer", "disable-randomizer": "randomizer", exclude: "exclusions", include: "exclusions",
|
||||
download: "download", downloadAll: "downloadAll", cancel: "cancel", delete: "delete", refresh: "refresh", jetlink: "jetlink" }
|
||||
|
||||
@@ -218,7 +219,9 @@ export function modelActionAllowed(data, action, model = null) {
|
||||
if (!data || data.capabilities?.[actionCapabilities[action]] !== true) return false
|
||||
if (data.isOnroad !== false && !["favorite", "unfavorite", "cancel", "select-small", "select-big", "enable-randomizer", "disable-randomizer", "exclude", "include"].includes(action)) return false
|
||||
if (action === "jetlink") return data.jetlink !== undefined
|
||||
if (action === "conditional_model") return !data.downloading && !data.randomizer
|
||||
if (["select-small", "select-big"].includes(action)) {
|
||||
if (action === "select-small" && data.conditionalModel?.enabled) return false
|
||||
if (action === "select-big" && data.jetlinkBig && data.isOnroad !== false) return false
|
||||
if (data.downloading && data.refreshing !== true || data.randomizer === true) return false
|
||||
if (action === "select-big" && model === null) return true
|
||||
@@ -229,9 +232,10 @@ export function modelActionAllowed(data, action, model = null) {
|
||||
if (action === "downloadAll") return !data.downloading && data.models.some(m => !m.installed && m.downloadAvailable === true)
|
||||
if (action === "cancel") return data.downloading === true
|
||||
if (action === "delete") return !data.downloading && !!model && !model.builtin && model.deletable !== false &&
|
||||
(model.installed || model.partial) && ![data.currentModel, data.activeSmallModel, data.activeBigModel].includes(model.value)
|
||||
(model.installed || model.partial) && ![data.currentModel, data.activeSmallModel, data.activeBigModel,
|
||||
data.conditionalModel?.highway, data.conditionalModel?.city].includes(model.value)
|
||||
if (["exclude", "include"].includes(action)) return !!model
|
||||
if (["enable-randomizer", "disable-randomizer"].includes(action)) return !data.downloading
|
||||
if (["enable-randomizer", "disable-randomizer"].includes(action)) return !data.downloading && !data.conditionalModel?.enabled
|
||||
return ["favorite", "unfavorite"].includes(action) ? !!model : action === "refresh" && !data.downloading
|
||||
}
|
||||
|
||||
@@ -339,7 +343,8 @@ export class ModelManagerFeed {
|
||||
this.publish({ loading: false, data, error: "" })
|
||||
}
|
||||
}
|
||||
if (this.poll === null) this.poll = this.later(() => this.load(), this.data?.jetlink?.mode !== "off" && this.data?.jetlink ? 1000 : 2000)
|
||||
if (this.poll === null) this.poll = this.later(() => this.load(), this.data?.conditionalModel?.enabled ? 200 :
|
||||
this.data?.jetlink?.mode !== "off" && this.data?.jetlink ? 1000 : 2000)
|
||||
return this.data
|
||||
}
|
||||
async action(action, model = null, extra = {}) {
|
||||
@@ -351,7 +356,7 @@ export class ModelManagerFeed {
|
||||
if (!modelActionAllowed(this.data, action, model)) return null
|
||||
const data = this.data
|
||||
const key = model?.value || ""
|
||||
let payload = action === "jetlink" ? extra : {}
|
||||
let payload = ["jetlink", "conditional_model"].includes(action) ? extra : {}
|
||||
if (action.startsWith("select-")) payload = { profile: action === "select-big" ? "big" : "small", model: key }
|
||||
else if (["favorite", "unfavorite"].includes(action)) {
|
||||
const userFavorites = data.models.filter(m => m.userFavorite && m.value !== key).map(m => m.value)
|
||||
@@ -524,7 +529,7 @@ const ModelDownloadProgress = {
|
||||
|
||||
export const ModelsPage = {
|
||||
name: "ModelsPage",
|
||||
components: { WikiHelp, GxDialog, GxState, GalaxySelect, GxNotice, ModelDownloadProgress },
|
||||
components: { WikiHelp, GxDialog, GxState, GalaxySelect, GalaxySettingRow, GxNotice, ModelDownloadProgress },
|
||||
props: {
|
||||
mode: { type: String, required: true },
|
||||
unauthorized: { type: Function, required: true },
|
||||
@@ -538,10 +543,26 @@ export const ModelsPage = {
|
||||
summary: { installed: 0, missing: 0, total: 0 }, status: { isOnroad: true },
|
||||
runtime: { status: "idle", data: null, error: "" }, dialog: null, pendingChoice: null,
|
||||
lab: null, labError: "", labDirty: false, labConfig: { enabled: false, lateralModel: "", longitudinalModel: "" }, focused: false,
|
||||
pairView: null,
|
||||
driveView: null,
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
conditionalModel() { return this.status.conditionalModel || { enabled: false, highway: "", city: "", thresholdMph: 50 } },
|
||||
conditionalSwitchPending() {
|
||||
return ['waiting', 'switching', 'recovering'].includes(this.status.conditionalModelState?.phase)
|
||||
},
|
||||
conditionalEnabledRow() {
|
||||
return switchRow('Enable Conditional Model', this.conditionalModel.enabled)
|
||||
},
|
||||
conditionalSpeedRow() {
|
||||
return { label: 'Highway speed', value: String(this.conditionalModel.thresholdMph ?? 50),
|
||||
minimum: 10, maximum: 100, step: 1, unit: 'mph', defaultValue: '50', resetAvailable: true,
|
||||
available: true, action: true }
|
||||
},
|
||||
conditionalModels() {
|
||||
return this.models.filter(m => fitsModelProfile(m, "small") &&
|
||||
(m.selectable || [this.conditionalModel.highway, this.conditionalModel.city].includes(m.value)))
|
||||
},
|
||||
currentLabel() { return this.models.find(m => m.value === this.currentModel)?.label || this.currentModel || "" },
|
||||
runningModelLabel() {
|
||||
if (!this.selectionUncertain && this.status.jetlink?.active) return "Jetlink remote model"
|
||||
@@ -552,6 +573,10 @@ export const ModelsPage = {
|
||||
if (pair?.active) return [pair.lateralModel, pair.longitudinalModel].map(id => model.catalog.find(m => m.id === id)?.name || id).join("/")
|
||||
if (pair?.lateralModel) return "Laboratory output unavailable"
|
||||
if (model.health === "unavailable") return "No running model"
|
||||
if (model.health === "loading") return "Loading…"
|
||||
if (model.health === "stale") return "Model output stale"
|
||||
if (model.health === "failed") return "Model status mismatch"
|
||||
if (model.health === "identity-unavailable") return "Identity unverified"
|
||||
if (!model.loadedId) return model.health === "loading" ? "Loading…" : "Identity unverified"
|
||||
return model.catalog.find(item => item.id === model.loadedId)?.name || model.loadedId
|
||||
},
|
||||
@@ -626,7 +651,7 @@ export const ModelsPage = {
|
||||
return this.status.gpuAvailable ? "" : "An external GPU is not detected. Active Small is used; your Big selection is saved for later."
|
||||
},
|
||||
jetlinkOpen() { return !!this.status.jetlink && this.status.jetlink.mode !== "off" },
|
||||
driveMode() { return this.pairView ?? (this.lab?.configuration.enabled ? "pair" : "single") },
|
||||
driveMode() { return this.driveView ?? (this.lab?.configuration.enabled ? "split" : this.conditionalModel.enabled ? "conditional" : "single") },
|
||||
labRows() { return new Map(laboratoryModels(this.lab).map(m => [m.value, m])) },
|
||||
labReady() { return laboratoryReady(this.lab) },
|
||||
labCandidates() { return this.labReady.filter(m => m.value !== this.labConfig.lateralModel) },
|
||||
@@ -692,7 +717,7 @@ export const ModelsPage = {
|
||||
methods: {
|
||||
focusLaboratory() {
|
||||
if (this.focus !== "laboratory" || this.focused) return
|
||||
if (this.driveMode !== "pair") this.pairView = "pair"
|
||||
if (this.driveMode !== "split") this.driveView = "split"
|
||||
this.$nextTick(() => {
|
||||
const card = this.$refs.laboratory
|
||||
if (!card) return
|
||||
@@ -726,20 +751,11 @@ export const ModelsPage = {
|
||||
this.labDirty = false
|
||||
if (this.lab) this.labConfig = laboratoryDraft(this.lab, this.labConfig, false)
|
||||
}
|
||||
if (result && !this.disposed && this.driveMode === "pair" && !this.lab?.configuration.enabled && this.labActionAvailable("enable")) return this.enablePair()
|
||||
return result
|
||||
},
|
||||
enablePair() { return reportSave(() => this.runLabAction("enable")) },
|
||||
async setDriveMode(mode) {
|
||||
if (mode === this.driveMode) return null
|
||||
if (mode === "single") {
|
||||
this.pairView = "single"
|
||||
const result = this.lab?.configuration.enabled ? await reportSave(() => this.runLabAction("disable")) : true
|
||||
this.pairView = null
|
||||
return result
|
||||
}
|
||||
this.pairView = "pair"
|
||||
return this.labActionAvailable("enable") ? this.enablePair() : null
|
||||
setDriveMode(mode) {
|
||||
if (["single", "split", "conditional"].includes(mode)) this.driveView = mode
|
||||
},
|
||||
activeRoles(model) {
|
||||
const roles = []
|
||||
@@ -776,7 +792,7 @@ export const ModelsPage = {
|
||||
if (this.disposed) return
|
||||
const result = await this.laboratory.action(action, model, this.labConfig)
|
||||
if (!this.disposed && result) {
|
||||
this.message = action === "save" ? "Model pair saved for the next start." : result.message || "Updated"
|
||||
this.message = action === "save" ? "Split Model models saved for the next start." : result.message || "Updated"
|
||||
this.trackingProgress = action === "download"
|
||||
if (["enable", "disable", "delete", "save"].includes(action)) {
|
||||
this.labDirty = false
|
||||
@@ -861,6 +877,17 @@ export const ModelsPage = {
|
||||
if (result) this.message = result.message
|
||||
} finally { this.pendingChoice = null; this.busy = "" }
|
||||
},
|
||||
async configureConditionalModel(update) {
|
||||
if (!this.canAction("conditional_model")) return false
|
||||
this.busy = "conditional_model:"
|
||||
try {
|
||||
const result = await reportSave(() => this.manager.action("conditional_model", null, update))
|
||||
return result || false
|
||||
} finally { this.busy = "" }
|
||||
},
|
||||
saveConditionalSetting(index, value) {
|
||||
return this.configureConditionalModel(index === 0 ? { enabled: value === 'On' } : { thresholdMph: Number(value) })
|
||||
},
|
||||
async runAction(action, model = null) {
|
||||
if (this.disposed || !this.canAction(action, model)) return
|
||||
if (action.startsWith("select-")) this.pendingChoice = { action, value: model?.value || "" }
|
||||
@@ -898,7 +925,7 @@ export const ModelsPage = {
|
||||
|
||||
<template v-else>
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Models</h2>
|
||||
<p>Choose what drives your car, pair models, and manage downloads.</p></div>
|
||||
<p>Choose one model, split control, or automatic speed-based switching.</p></div>
|
||||
<WikiHelp /></header>
|
||||
<GxNotice v-if="message" tone="info">{{ message }}</GxNotice>
|
||||
<GxNotice v-if="error" tone="danger" title="Models">{{ error }}</GxNotice>
|
||||
@@ -916,13 +943,16 @@ export const ModelsPage = {
|
||||
<section class="gx-card gx-model-driving">
|
||||
<div class="gx-panel gx-model-driving__body">
|
||||
<div class="gx-tabs gx-model-mode" role="group" aria-label="Driving models">
|
||||
<button type="button" :aria-pressed="driveMode === 'single'" :disabled="!!busy || labLocked && driveMode !== 'single'" @click="setDriveMode('single')"><i aria-hidden="true" class="bi bi-cpu"></i> Single model</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'pair'" :disabled="!!busy || labLocked" @click="setDriveMode('pair')"><i aria-hidden="true" class="bi bi-bezier2"></i> Model pair</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'single'" @click="setDriveMode('single')"><i aria-hidden="true" class="bi bi-cpu"></i> Single Model</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'split'" @click="setDriveMode('split')"><i aria-hidden="true" class="bi bi-bezier2"></i> Split Model</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'conditional'" @click="setDriveMode('conditional')"><i aria-hidden="true" class="bi bi-signpost-split"></i> Conditional Model</button>
|
||||
</div>
|
||||
|
||||
<div class="gx-panel-stage" :style="{'--panel-direction': driveMode === 'pair' ? 1 : -1}">
|
||||
<div class="gx-panel-stage" :style="{'--panel-direction': driveMode === 'split' ? 1 : -1}">
|
||||
<div :key="driveMode" class="gx-model-driving__body">
|
||||
<template v-if="driveMode === 'single'">
|
||||
<p class="gx-model-reason">One model handles all driving.</p>
|
||||
<GxNotice v-if="conditionalModel.enabled" tone="info">Conditional Model is enabled. Turn it off in Conditional Model to choose Active Small here.</GxNotice>
|
||||
<div class="gx-model-driving__summary" role="group" aria-label="Active models">
|
||||
<div class="gx-model-control gx-model-summary-item">
|
||||
<span class="gx-model-summary-item__meta"><i aria-hidden="true" class="bi bi-cpu"></i> Active Small · On-device</span>
|
||||
@@ -946,7 +976,27 @@ export const ModelsPage = {
|
||||
</div>
|
||||
<p v-if="status.randomizer" class="gx-model-reason">A different verified model is chosen each start. {{ status.gpuAvailable && activeBigModel ? 'Big GPU' : 'Small on-device' }} models are used. {{ (status.blacklistedModels || []).length }} excluded. Favorites only mark your preferred models.</p>
|
||||
<p v-if="gpuNote" class="gx-model-reason">{{ gpuNote }}</p>
|
||||
<p class="gx-model-reason">{{ laboratoryEnabled ? 'Small/Big selections are saved as fallback choices. Turn off Laboratory to use them normally at the next start.' : 'Selections take effect the next time the driving model starts.' }}</p>
|
||||
<p class="gx-model-reason">{{ laboratoryEnabled ? 'Small/Big selections are saved as fallback choices. Turn off Split Model to use them normally at the next start.' : 'Selections take effect the next time the driving model starts.' }}</p>
|
||||
</template>
|
||||
|
||||
<template v-else-if="driveMode === 'conditional'">
|
||||
<p class="gx-model-reason">Starts each drive in City and automatically selects Highway at your chosen speed, only while fully disengaged.</p>
|
||||
<GxNotice v-if="conditionalSwitchPending" tone="warn">Switching conditional models · Wait before engaging.</GxNotice>
|
||||
<GxNotice v-if="status.conditionalModelState?.error" tone="warn">{{ status.conditionalModelState.error }}</GxNotice>
|
||||
<GxNotice v-else-if="status.conditionalModelState?.unavailableReason" tone="info">{{ status.conditionalModelState.unavailableReason }}</GxNotice>
|
||||
<GxNotice v-if="laboratoryEnabled && !status.conditionalModelState?.unavailableReason" tone="info">Split Model takes priority while enabled.</GxNotice>
|
||||
<GalaxySettingRow :row="conditionalEnabledRow" :index="0" :busy="!!busy" :disabled="!actionAvailable('conditional_model')" :save-value="saveConditionalSetting" feedback="none" />
|
||||
<div class="gx-model-driving__selects" role="group" aria-label="Conditional driving models">
|
||||
<div v-for="condition in ['city', 'highway']" :key="condition" class="gx-model-control">
|
||||
<label :for="'gx-conditional-' + condition">{{ condition === 'highway' ? 'Highway model' : 'City model' }}</label>
|
||||
<GalaxySelect :id="'gx-conditional-' + condition" class="gx-field" :value="conditionalModel[condition]" :disabled="!!busy || !actionAvailable('conditional_model')" @change="configureConditionalModel({[condition]: $event.target.value})">
|
||||
<option v-for="m in conditionalModels" :key="m.value" :value="m.value" :disabled="!m.selectable">{{ m.label }}{{ m.selectable ? '' : ' · ' + m.unavailableReason }}</option>
|
||||
</GalaxySelect>
|
||||
</div>
|
||||
</div>
|
||||
<GalaxySettingRow :row="conditionalSpeedRow" :index="1" :busy="!!busy" :disabled="!actionAvailable('conditional_model')" :save-value="saveConditionalSetting" feedback="none" @reset-default="configureConditionalModel({thresholdMph: 50})" />
|
||||
<GxNotice v-if="status.randomizer" tone="info">Turn off Model Randomizer to enable Conditional Model.</GxNotice>
|
||||
<span class="gx-chip gx-model-driving__running">Running now: {{ runningModelLabel }}</span>
|
||||
</template>
|
||||
|
||||
<div v-else id="gx-model-laboratory" ref="laboratory" class="gx-model-laboratory">
|
||||
@@ -957,22 +1007,24 @@ export const ModelsPage = {
|
||||
</div>
|
||||
<span class="gx-chip gx-model-driving__running">Running now: {{ runningModelLabel }}<template v-if="pendingNextStart"> · saved changes pending next start</template></span>
|
||||
</div>
|
||||
<GxNotice v-if="labError" tone="danger" title="Model Laboratory">{{ labError }}</GxNotice>
|
||||
<GxNotice v-if="labError" tone="danger" title="Split Model">{{ labError }}</GxNotice>
|
||||
<GxNotice v-if="lab?.configurationError" tone="danger">{{ lab.configurationError }}</GxNotice>
|
||||
<p v-if="!lab && !labError" class="gx-note">Loading Model Laboratory…</p>
|
||||
<p v-if="!lab && !labError" class="gx-note">Loading Split Model…</p>
|
||||
<template v-if="lab">
|
||||
<p class="gx-model-reason">Pair lateral judgment from one model with longitudinal judgment from another.</p>
|
||||
<p class="gx-model-reason">One model for steering, another for speed. Requires Chestnut.</p>
|
||||
<p v-if="conditionalModel.enabled" class="gx-model-reason">Conditional Model remains your Small fallback while Split Model is enabled.</p>
|
||||
<button type="button" class="gx-btn" :disabled="!!busy || !labActionAvailable(lab.configuration.enabled ? 'disable' : 'enable')" @click="lab.configuration.enabled ? runLabAction('disable') : enablePair()">{{ lab.configuration.enabled ? 'Turn off Split Model' : 'Use Split Model' }}</button>
|
||||
<div class="gx-model-driving__selects">
|
||||
<div class="gx-model-control">
|
||||
<label class="gx-row__label" for="gx-lab-lateral">Lateral model <small class="gx-model-driving__random-hint">steering & path</small></label>
|
||||
<GalaxySelect id="gx-lab-lateral" class="gx-field" aria-label="Lateral model" :disabled="labLocked" :value="labConfig.lateralModel" @change="changeLateral($event.target.value)">
|
||||
<label class="gx-row__label" for="gx-lab-lateral">Steering model <small class="gx-model-driving__random-hint">path & lane position</small></label>
|
||||
<GalaxySelect id="gx-lab-lateral" class="gx-field" aria-label="Steering model" :disabled="labLocked" :value="labConfig.lateralModel" @change="changeLateral($event.target.value)">
|
||||
<option value="">Choose a model</option>
|
||||
<option v-for="m in labReady" :key="m.value" :value="m.value">{{ m.label }} · {{ m.version }}</option>
|
||||
</GalaxySelect>
|
||||
</div>
|
||||
<div class="gx-model-control">
|
||||
<label class="gx-row__label" for="gx-lab-longitudinal">Longitudinal model <small class="gx-model-driving__random-hint">speed & lead pacing</small></label>
|
||||
<GalaxySelect id="gx-lab-longitudinal" class="gx-field" aria-label="Longitudinal model" :disabled="labLocked" :value="labConfig.longitudinalModel" @change="changeLongitudinal($event.target.value)">
|
||||
<label class="gx-row__label" for="gx-lab-longitudinal">Speed model <small class="gx-model-driving__random-hint">acceleration & braking</small></label>
|
||||
<GalaxySelect id="gx-lab-longitudinal" class="gx-field" aria-label="Speed model" :disabled="labLocked" :value="labConfig.longitudinalModel" @change="changeLongitudinal($event.target.value)">
|
||||
<option value="">Choose a model</option>
|
||||
<option v-for="m in labCandidates" :key="m.value" :value="m.value">{{ m.label }} · {{ m.version }}</option>
|
||||
</GalaxySelect>
|
||||
@@ -1057,8 +1109,8 @@ export const ModelsPage = {
|
||||
|
||||
<div v-if="!sorted.length" class="gx-empty">No models match these filters. <button type="button" class="gx-btn gx-btn--tonal" @click="clearFilters">Show all models</button></div>
|
||||
<ul v-else class="gx-model-list" aria-label="Models">
|
||||
<li class="gx-model-item" :class="{'gx-model-item--pair': driveMode === 'pair', 'gx-model-card--polaris': isPolaris(m), 'gx-model-card--selected': rowState(m) === 'active'}" v-for="m in visibleModels" :key="m.value">
|
||||
<template v-if="driveMode === 'pair'">
|
||||
<li class="gx-model-item" :class="{'gx-model-item--pair': driveMode === 'split', 'gx-model-card--polaris': isPolaris(m), 'gx-model-card--selected': rowState(m) === 'active'}" v-for="m in visibleModels" :key="m.value">
|
||||
<template v-if="driveMode === 'split'">
|
||||
<div class="gx-model-item__row gx-model-item__row--pair">
|
||||
<div class="gx-model-item__ver">
|
||||
<span v-if="m.version" class="gx-model-spec gx-model-spec--ver">{{ m.version }}</span>
|
||||
|
||||
@@ -4,15 +4,141 @@ Model Manager installs the versioned catalog into `/data/models/v26`. Downloads
|
||||
|
||||
Catalog behavior versions describe model inputs and outputs. The artifact ABI and compiler revision separately identify runtime compatibility. Existing compiled artifacts can be migrated when their kernels and state can be preserved and verified; changing the version label alone does not establish compatibility. Unavailable catalog entries cannot be downloaded or selected.
|
||||
|
||||
`modeld` records the loaded artifact digest, process identity, variant, and fallback reason in a bounded volatile receipt. Status requires a matching running process and fresh valid model outputs before reporting an active model. A failed Chestnut load falls back to the initialized small runner. Artifact integrity and bench inference do not establish on-road driving quality.
|
||||
`modeld` records the loaded artifact digest, process identity, variant, and fallback reason in a bounded volatile receipt. Status requires a matching running process and fresh valid model outputs before reporting an active model. A failed Chestnut startup requests isolated Small recovery; inference failure falls back to the initialized Small runner. Artifact integrity and bench inference do not establish on-road driving quality.
|
||||
|
||||
## Conditional Model: automatic local model switching
|
||||
|
||||
Galaxy Models has three settings tabs: **Single Model**, **Split Model** and
|
||||
**Conditional Model**. Single Model handles all driving. Split Model assigns
|
||||
steering and speed to separate models using Model Laboratory and Chestnut.
|
||||
Conditional Model switches the entire local Small runner according to speed;
|
||||
no external GPU is required. Browsing a settings tab does not activate a mode.
|
||||
|
||||
Configure City, Highway and the Highway speed while offroad, then enable
|
||||
Conditional Model. The speed uses the same `GalaxySettingRow` slider as Toggles,
|
||||
including fine scrubbing, default reset and save feedback. It defaults to
|
||||
**50 mph** and accepts 10–100 mph. Every normal drive starts with **City**.
|
||||
There is no manual road selection, configurable starting mode or cooldown input.
|
||||
The separate Single Model choice remains saved when Conditional Model is enabled.
|
||||
|
||||
Both verified runners load and warm sequentially at drive startup and remain
|
||||
resident until normal process teardown. Only one runs per frame, with independent
|
||||
history buffers. Identical City/Highway assignments use a single runner.
|
||||
Missing/corrupt artifacts, unsupported state mapping or insufficient memory
|
||||
headroom disable switching and retain the initialized fallback. Chestnut, Split
|
||||
Model and Jetlink retain their existing precedence and fallback behavior;
|
||||
expected external-model precedence is informational, not a driver fault alert.
|
||||
|
||||
### Speed selection and interlock
|
||||
|
||||
Highway is requested at the exact configured speed, without a delay.
|
||||
City requires **30 continuous seconds** at least **5 mph below** that speed;
|
||||
both guards are internal constants. A subsequent Highway request can happen
|
||||
immediately, avoiding a cooldown delay during a merge. Repeated City entries
|
||||
always require another complete low-speed interval. Speed is a condition hint,
|
||||
not geographic road classification: slow highway traffic and fast local roads
|
||||
can be misclassified.
|
||||
|
||||
Stale, missing, reordered, nonfinite or implausible speed samples reset the City
|
||||
timer. Sampling continues while engaged, but crossing a threshold cannot acquire
|
||||
an engagement hold or switch a runner. Requests require fresh valid model output,
|
||||
fresh disengaged vehicle/control state and a fresh idle acknowledgment. There
|
||||
is no preferences-reading thread, onroad configuration API or filesystem I/O in
|
||||
the automatic request path.
|
||||
|
||||
Selfdrived grants the session/request-bound hold only while ordinary control is
|
||||
disabled and both independent axes are inactive, unrequested and disarmed. Stock
|
||||
cruise must also be off. Same-tick engagement loses to the existing no-entry
|
||||
protection; the final independent-axis publication is inhibited as well. Standing
|
||||
still never permits an engaged switch. Missing acknowledgments time out after
|
||||
one second with the current runner retained.
|
||||
|
||||
The target's preallocated state is reset in place, preserving captured JIT buffer
|
||||
addresses. Action smoothing and lane-change state restart at the handoff. Existing
|
||||
model, driving-data, odometry, lane-change and identity messages keep their sole
|
||||
original publisher. The hold spans five valid output frames and releases only
|
||||
when selfdrived sees fresh output at or after completion. Stale/missing status,
|
||||
old output and expired timers never release a hold. A restarted process must
|
||||
establish fresh output before a prior hold can clear. There is no automatic
|
||||
re-engagement.
|
||||
|
||||
### Failure recovery and driver notices
|
||||
|
||||
A target reset/inference/action failure retains or restores the previous model;
|
||||
five valid recovery frames are required before releasing an established hold.
|
||||
Failures pause further switching for the drive. A previous-runner reset failure
|
||||
exits under the hold instead of running potentially corrupted history.
|
||||
|
||||
A two-second handoff timeout rolls back when disengagement is established.
|
||||
Manager bounds startup preload to 120 seconds. During an acknowledged hold, a
|
||||
native inference stall with progressing cameras triggers bounded SIGINT/SIGKILL
|
||||
escalation. The old process must exit before a single-model recovery process can
|
||||
start using the prior model. An established runner cannot be reclassified as a
|
||||
preload merely because its receipt disappears. An arbitrary established/engaged
|
||||
Small crash does not authorize loading another model. Recovery overrides do not
|
||||
change the next drive's City startup.
|
||||
|
||||
The native alert manager displays **Switching conditional models** throughout a
|
||||
held handoff. Genuine failures and prolonged holds produce visible notices.
|
||||
Notices yield to equal/higher-priority current or retained vehicle alerts, and
|
||||
completion removes only Conditional Model notices. Expected engagement, short
|
||||
message gaps, ordinary speed changes and external-model precedence do not create
|
||||
failure alerts.
|
||||
|
||||
Galaxy shows the actual verified running model, switching and failure state.
|
||||
An enabled setting is configuration, not proof that a runner is active.
|
||||
`POST /api/models/conditional_model` accepts only `enabled`, `city`, `highway` and
|
||||
`thresholdMph`, and only offroad. Legacy `smallProfiles` data is read at one
|
||||
migration boundary; model assignments, enablement and speed migrate, while
|
||||
manual selection, pending manual requests and custom cooldowns are discarded.
|
||||
The next save writes only the canonical `conditionalModel` shape.
|
||||
|
||||
### Module boundaries and qualification
|
||||
|
||||
`conditional_model.py` owns configuration and City startup selection;
|
||||
`conditional_policy.py` owns speed/hysteresis clocks; `conditional_protocol.py`
|
||||
owns the pure held handoff; `conditional_runtime.py` adapts modeld/selfdrived;
|
||||
`conditional_alerts.py` supplies native notices. Tests cover migration, removed
|
||||
controls/APIs, City startup/recovery, shared sliders, speed boundaries, anti-flap
|
||||
behavior, invalid/gapped inputs, engagement races, independent axes, real typed
|
||||
IPC, timeouts, rollback, watchdogs and native-alert priority/retirement.
|
||||
|
||||
Five output frames represent about 250 ms at 20 Hz, plus reset, inference and
|
||||
handshake overhead; actual QCOM timing remains unmeasured. Standard Small files
|
||||
occupy 57.9–85.6 MiB each; disk size is not a device-residency bound. Startup checks
|
||||
host memory headroom (512 MiB plus four times the alternate artifact size), a
|
||||
heuristic rather than accelerator-memory qualification. `modeld.catalog_load`
|
||||
logs verification/construction/warmup durations and peak process RSS; RSS does
|
||||
not measure device allocations. Host tests cannot certify 100% safety, memory
|
||||
capacity, driving quality or device timing. Target bench validation remains
|
||||
required. Small upstream hooks still require review during merges.
|
||||
|
||||
## Model Laboratory
|
||||
|
||||
Laboratory artifact management uses separate AMD variants of small models. A standard on-device artifact or a Chestnut-class large model cannot substitute for one. The manifest declares each variant under `accelerator_artifacts.amd`, with `execution_device: "AMD"`, the current `compiler_revision`, and the same artifact format, digest, size, and chunk-count fields as ordinary catalog artifacts. Files are named `<id>_driving_amd_tinygrad.pkl` under the model's existing catalog directory. Deleting an AMD variant preserves the ordinary on-device model.
|
||||
Laboratory artifact management supports separate AMD variants of Small models
|
||||
and Chestnut-class large models. At startup the frozen request can substitute
|
||||
an installed native Small counterpart for one Small role while retaining a
|
||||
Chestnut-backed role. The manifest declares AMD variants under
|
||||
`accelerator_artifacts.amd`, with `execution_device: "AMD"`, the current
|
||||
`compiler_revision`, and the same artifact format, digest, size, and chunk-count
|
||||
fields as ordinary catalog artifacts. Files are named
|
||||
`<id>_driving_amd_tinygrad.pkl` under the model's existing catalog directory.
|
||||
Deleting an AMD variant preserves the ordinary on-device model.
|
||||
|
||||
The Galaxy page and parked configuration owner are available. The standalone pair runner verifies both AMD artifacts, shares compatible camera preprocessing, keeps each model's state separate, and rejects the whole frame if either role fails. It decodes each model's own action units before choosing lateral curvature and longitudinal acceleration/stopping. The compositor assigns lateral geometry and the corresponding plan columns to the lateral model, and leads, scene metadata, and current-frame pose to the longitudinal model.
|
||||
The Galaxy page and configuration owner are available. The pair runner verifies
|
||||
both role artifacts, shares compatible camera preprocessing, keeps each model's
|
||||
state separate, and rejects the whole frame if either role fails. It decodes each
|
||||
model's own action units before choosing lateral curvature and longitudinal
|
||||
acceleration/stopping. The compositor assigns lateral geometry and the
|
||||
corresponding plan columns to the lateral model, and leads, scene metadata, and
|
||||
current-frame pose to the longitudinal model.
|
||||
|
||||
Paired inference is not integrated into modeld yet, so production reports `runtimeSupported: false` and rejects enabling a pair. Completing it requires two verified AMD small-model variants, modeld loading/fallback and fresh pair status, then a Chestnut bench run covering real shared-warp execution, memory, timing and driver monitoring coexistence. CPU state-isolation and mocked frame tests do not qualify the AMD pair.
|
||||
Paired inference is integrated into modeld through a frozen startup request and
|
||||
pair receipts. Production advertises `runtimeSupported: true`; configuration
|
||||
requires Chestnut and at least one Chestnut-backed role. Failed pair startup uses
|
||||
the existing isolated Small recovery, and inference failures fall back to the
|
||||
initialized Small runner. CPU state-isolation and mocked frame tests do not
|
||||
establish device memory, timing, or on-road driving quality.
|
||||
|
||||
Jetlink is a separate remote model connection for comma 3X and comma 4. In Galaxy
|
||||
Model Manager, choose **Off**, **USB computer**, or **iPhone / iPad** while parked.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Conditional Model notices use the existing alert manager and native UI surfaces."""
|
||||
from openpilot.selfdrive.selfdrived.events import Alert, AlertStatus, AlertSize, Priority, VisualAlert, AudibleAlert, ET
|
||||
|
||||
ALERT_TYPES = ('conditionalModelSwitch/permanent', 'conditionalModelFailure/permanent')
|
||||
|
||||
|
||||
def conditional_model_alert(state, *, holding, stalled=False):
|
||||
error = str(state.error) if state is not None else ''
|
||||
switching = holding or state is not None and str(state.phase) in ('waiting', 'switching', 'recovering')
|
||||
if not error and not switching:
|
||||
return None
|
||||
failed = bool(error or stalled)
|
||||
title = 'Conditional model switch stalled' if stalled else 'Conditional Model unavailable' if error else 'Switching conditional models'
|
||||
detail = ('Engagement blocked; waiting for model recovery' if stalled else
|
||||
error if error else 'Wait for completion before engaging')
|
||||
alert = Alert(title, detail, AlertStatus.userPrompt if failed else AlertStatus.normal,
|
||||
AlertSize.mid if failed else AlertSize.small, Priority.LOW if failed else Priority.LOWEST,
|
||||
VisualAlert.none, AudibleAlert.none, .1)
|
||||
alert.alert_type = ALERT_TYPES[1 if failed else 0]
|
||||
alert.event_type = ET.PERMANENT
|
||||
return alert
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Persistent configuration for automatic, resident City/Highway model switching."""
|
||||
from openpilot.starpilot.models.catalog import BUNDLED_CURRENT, DEFAULT_SMALL
|
||||
from openpilot.starpilot.models.conditional_policy import DEFAULT_THRESHOLD_MPH
|
||||
|
||||
CONDITIONS = ('city', 'highway')
|
||||
|
||||
|
||||
def defaults() -> dict:
|
||||
return {'enabled': False, 'city': DEFAULT_SMALL, 'highway': DEFAULT_SMALL, 'thresholdMph': DEFAULT_THRESHOLD_MPH}
|
||||
|
||||
|
||||
def validate(value: object, entries) -> bool:
|
||||
return (isinstance(value, dict) and set(value) == set(defaults()) and type(value['enabled']) is bool and
|
||||
type(value['thresholdMph']) is int and 10 <= value['thresholdMph'] <= 100 and
|
||||
all(isinstance(value[name], str) and value[name] != BUNDLED_CURRENT and value[name] in entries and
|
||||
not entries[value[name]].uses_external_gpu for name in CONDITIONS))
|
||||
|
||||
|
||||
def configuration(saved: dict, entries) -> dict:
|
||||
if 'conditionalModel' in saved:
|
||||
value = saved['conditionalModel']
|
||||
else:
|
||||
# Compatibility boundary only. Obsolete manual intent and cooldown values
|
||||
# never enter the runtime; the next configuration save writes the new shape.
|
||||
legacy = saved.get('smallProfiles')
|
||||
allowed = {'enabled', 'highway', 'city', 'selected', 'automatic', 'thresholdMph', 'cityDelaySeconds'}
|
||||
if not isinstance(legacy, dict) or not {'enabled', 'city', 'highway'} <= set(legacy) or set(legacy) - allowed:
|
||||
return defaults()
|
||||
value = {name: legacy.get(name, default) for name, default in defaults().items()}
|
||||
if not validate(value, entries):
|
||||
return defaults()
|
||||
if value['enabled'] and saved.get('randomizer') is True:
|
||||
return value | {'enabled': False}
|
||||
return dict(value)
|
||||
|
||||
|
||||
def starting_model(saved: dict) -> str:
|
||||
"""Every normal Conditional Model startup uses City; recovery may override it."""
|
||||
return saved['conditionalModel']['city'] if saved['conditionalModel']['enabled'] else saved['small']
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Speed is a road-mode hint, never authority to change models or engage."""
|
||||
import math
|
||||
|
||||
from openpilot.starpilot.models.conditional_protocol import FRESH_NS, fresh
|
||||
|
||||
MPH_TO_MS = 0.44704
|
||||
HYSTERESIS_MPH = 5
|
||||
DEFAULT_THRESHOLD_MPH = 50
|
||||
CITY_DELAY_SECONDS = 30
|
||||
|
||||
|
||||
class SpeedPolicy:
|
||||
"""Fast Highway entry, delayed City entry, and no progress on stale samples."""
|
||||
def __init__(self, threshold_mph=DEFAULT_THRESHOLD_MPH):
|
||||
if type(threshold_mph) is not int or not 10 <= threshold_mph <= 100:
|
||||
raise ValueError('Invalid Conditional Model speed policy')
|
||||
self.high = threshold_mph * MPH_TO_MS
|
||||
self.low = (threshold_mph - HYSTERESIS_MPH) * MPH_TO_MS
|
||||
self.delay = CITY_DELAY_SECONDS * 1_000_000_000
|
||||
self.low_since = None
|
||||
self.last_sample = self.last_switch = 0
|
||||
self.hint = ''
|
||||
|
||||
def switched(self, now):
|
||||
self.last_switch, self.low_since = now, None
|
||||
|
||||
def sample(self, speed, stamp, now, *, valid, current):
|
||||
self.hint = ''
|
||||
if (not valid or type(speed) not in (int, float) or not math.isfinite(speed) or not 0 <= speed <= 100 or
|
||||
not fresh(stamp, now) or stamp < self.last_sample or current not in ('highway', 'city')):
|
||||
self.low_since = None
|
||||
return None
|
||||
if self.last_sample and stamp - self.last_sample > FRESH_NS:
|
||||
self.low_since = None
|
||||
self.last_sample = stamp
|
||||
if speed >= self.high:
|
||||
self.hint = 'highway'
|
||||
self.low_since = None
|
||||
return 'highway' if current != 'highway' else None
|
||||
if speed <= self.low and current != 'city':
|
||||
self.hint = 'city'
|
||||
if self.low_since is None:
|
||||
self.low_since = stamp
|
||||
if now - self.low_since >= self.delay and now - self.last_switch >= self.delay:
|
||||
return 'city'
|
||||
else:
|
||||
self.low_since = None
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Pure Conditional Model handshake and resident-runner state machine; no process or GPU imports."""
|
||||
from dataclasses import dataclass
|
||||
import uuid
|
||||
|
||||
FRESH_NS = 150_000_000
|
||||
ACK_TIMEOUT_NS = 1_000_000_000
|
||||
SWITCH_TIMEOUT_NS = 2_000_000_000
|
||||
SETTLE_FRAMES = 5
|
||||
PRELOAD_TIMEOUT_NS = 120_000_000_000
|
||||
|
||||
|
||||
def fresh(stamp: int, now: int) -> bool:
|
||||
return 0 < stamp <= now and now - stamp <= FRESH_NS
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class State:
|
||||
session: str
|
||||
request: str
|
||||
phase: str
|
||||
frame: int
|
||||
born: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Ack:
|
||||
session: str
|
||||
request: str
|
||||
holding: bool
|
||||
source: int
|
||||
stamp: int
|
||||
idle: bool = False
|
||||
|
||||
|
||||
class EngagementHold:
|
||||
"""A granted hold never expires into permission to engage."""
|
||||
def __init__(self):
|
||||
self.owner: tuple[str, str] | None = None
|
||||
self.last_stamp = 0
|
||||
self.held_since = 0
|
||||
|
||||
def step(self, state: State | None, stamp: int, now: int, *, idle: bool, model_stamp: int, model_valid: bool,
|
||||
release_allowed: bool = True) -> bool:
|
||||
if state is None or not fresh(stamp, now) or stamp < self.last_stamp:
|
||||
return self.owner is not None
|
||||
self.last_stamp = stamp
|
||||
key = state.session, state.request
|
||||
if state.phase in ('waiting', 'switching', 'recovering'):
|
||||
if idle and state.session and state.request:
|
||||
if self.owner != key:
|
||||
self.held_since = now
|
||||
self.owner = key
|
||||
elif self.owner is not None and state.phase in ('ready', 'disabled'):
|
||||
# The same request can finish/abort, or a new process can establish a new
|
||||
# publisher. Old output cannot release a hold after either boundary.
|
||||
same = key == self.owner
|
||||
restarted = state.session != self.owner[0]
|
||||
if (idle and release_allowed and (same or restarted) and model_valid and fresh(model_stamp, now) and
|
||||
0 < state.born <= state.frame <= model_stamp <= now and state.born <= stamp):
|
||||
self.owner = None
|
||||
self.held_since = 0
|
||||
return self.owner is not None
|
||||
|
||||
|
||||
class ResidentSwitch:
|
||||
def __init__(self, models: dict, active: str, *, now: int, error: str = ''):
|
||||
# Each entry is (runner, prepared artifact, preallocated reset closure).
|
||||
self.models = models
|
||||
self.active = self.previous = self.target = active
|
||||
self.session = uuid.uuid4().hex
|
||||
self.born = now
|
||||
self.request = ''
|
||||
self.phase = 'ready' if models else 'disabled'
|
||||
self.error = error
|
||||
self.started = self.announced = self.frame = self.frames = 0
|
||||
self.elapsed = 0.
|
||||
self.safe_to_finish = False
|
||||
|
||||
def before_frame(self, desired: dict | None, *, now: int, idle: bool, ack: Ack | None) -> bool:
|
||||
"""Return True only when the active runner changed at this frame boundary."""
|
||||
old = self.active
|
||||
self.safe_to_finish = idle
|
||||
if (desired and desired.get('session') == self.session and desired.get('id') != self.request and
|
||||
self.phase == 'ready'):
|
||||
self.request = desired['id']
|
||||
self.error = ''
|
||||
if desired.get('model') not in self.models:
|
||||
self.error = 'Requested model is not resident; configure models with the vehicle off'
|
||||
elif not idle:
|
||||
self.error = 'Fully disengage cruise and independent lateral control before switching'
|
||||
elif desired['model'] != self.active:
|
||||
self.previous, self.target = self.active, desired['model']
|
||||
self.phase, self.started, self.announced = 'waiting', now, 0
|
||||
if self.phase == 'waiting':
|
||||
if not idle:
|
||||
# The driver may engage before the hold is granted, or a source may
|
||||
# briefly go stale. Retain the current runner without declaring a fault.
|
||||
self.abort('', now)
|
||||
elif now - self.started >= ACK_TIMEOUT_NS:
|
||||
self.abort('Engagement hold acknowledgment timed out; current model retained', now)
|
||||
elif (self.announced and ack is not None and ack.holding and fresh(ack.stamp, now) and
|
||||
(ack.session, ack.request) == (self.session, self.request) and
|
||||
self.announced <= ack.source <= ack.stamp):
|
||||
try:
|
||||
self.models[self.target][2]()
|
||||
except Exception:
|
||||
self.abort('Model state reset failed; current model retained', now)
|
||||
else:
|
||||
self.active, self.phase, self.frames = self.target, 'switching', 0
|
||||
elif self.phase == 'switching' and idle and now - self.started >= SWITCH_TIMEOUT_NS:
|
||||
self.abort('Model handoff timed out; previous model restored', now)
|
||||
return self.active != old
|
||||
|
||||
def abort(self, error: str, now: int) -> None:
|
||||
resetting = self.active != self.previous
|
||||
self.active, self.phase, self.error = self.previous, 'recovering' if resetting else 'ready', error
|
||||
self.frames = 0
|
||||
self.elapsed = (now - self.started) / 1e9 if self.started else 0.
|
||||
if resetting:
|
||||
try:
|
||||
self.models[self.previous][2]()
|
||||
except Exception as exc:
|
||||
# Do not run potentially corrupted history after a reset fails. Exit
|
||||
# under the existing hold; manager owns the isolated recovery process.
|
||||
self.error = 'Previous model reset failed; isolated recovery required'
|
||||
raise RuntimeError(self.error) from exc
|
||||
|
||||
def published(self, frame: int, now: int) -> None:
|
||||
if frame <= self.frame:
|
||||
return
|
||||
self.frame = frame
|
||||
if self.phase in ('switching', 'recovering') and self.safe_to_finish:
|
||||
self.frames += 1
|
||||
if self.frames >= SETTLE_FRAMES:
|
||||
self.phase = 'ready'
|
||||
self.elapsed = (now - self.started) / 1e9
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Resident Small-model switching and a fail-closed engagement handshake.
|
||||
|
||||
All GPU allocation and artifact loading happen at startup on the model thread. The engagement owner acknowledges a hold
|
||||
before modeld may change runners, and releases it only after fresh output.
|
||||
"""
|
||||
import time
|
||||
import uuid
|
||||
import math
|
||||
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy
|
||||
from openpilot.starpilot.models.conditional_protocol import (
|
||||
SWITCH_TIMEOUT_NS, State, Ack, EngagementHold, ResidentSwitch, fresh,
|
||||
)
|
||||
|
||||
|
||||
def modeld_idle(sm, now: int) -> bool:
|
||||
"""Unknown, stale, paused/armed, stock cruise and either active axis all deny."""
|
||||
try:
|
||||
for name in ('selfdriveState', 'carControl', 'carState'):
|
||||
if not (sm.seen[name] and sm.valid[name] and sm.alive[name] and fresh(int(sm.logMonoTime[name]), now)):
|
||||
return False
|
||||
state, command, car = sm['selfdriveState'], sm['carControl'], sm['carState']
|
||||
if (state.enabled or state.active or str(state.state) != 'disabled' or
|
||||
command.enabled or command.latActive or command.longActive or car.cruiseState.enabled or
|
||||
not car.canValid or car.canTimeout or not math.isfinite(car.vEgo) or not 0 <= car.vEgo <= 100):
|
||||
return False
|
||||
# Selfdrived's ack additionally covers armed independent control. This
|
||||
# cheap frame-side check covers active axes before/after that handshake.
|
||||
return True
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
class ConditionalModelGate:
|
||||
def __init__(self):
|
||||
from openpilot.cereal import messaging
|
||||
self.sm = messaging.SubMaster(['conditionalModelState'])
|
||||
self.pm = messaging.PubMaster(['conditionalModelAck'])
|
||||
self.hold = EngagementHold()
|
||||
|
||||
def alert(self):
|
||||
from openpilot.starpilot.models.conditional_alerts import conditional_model_alert
|
||||
state = self.sm['conditionalModelState']
|
||||
stamp = int(self.sm.logMonoTime['conditionalModelState'])
|
||||
now = time.monotonic_ns()
|
||||
valid = bool(self.sm.seen['conditionalModelState'] and self.sm.valid['conditionalModelState'] and fresh(stamp, now))
|
||||
return conditional_model_alert(state if valid else None, holding=self.hold.owner is not None,
|
||||
stalled=bool(self.hold.owner and now - self.hold.held_since >= SWITCH_TIMEOUT_NS))
|
||||
|
||||
def update_alerts(self, alerts, manager, frame=0):
|
||||
from openpilot.starpilot.models.conditional_alerts import ALERT_TYPES
|
||||
for name in ALERT_TYPES:
|
||||
manager.alerts.pop(name, None)
|
||||
notice = self.alert()
|
||||
retained = (entry.alert for entry in manager.alerts.values() if entry.alert is not None and entry.active(frame))
|
||||
if notice is not None and not any(alert.priority >= notice.priority for alert in (*alerts, *retained)):
|
||||
alerts.append(notice)
|
||||
|
||||
def step(self, drive, car) -> bool:
|
||||
from openpilot.cereal import log, messaging
|
||||
from openpilot.starpilot.aol.runtime import current_intent
|
||||
from openpilot.selfdrive.selfdrived.events import ET
|
||||
self.sm.update(0)
|
||||
now = time.monotonic_ns()
|
||||
state = self.sm['conditionalModelState']
|
||||
stamp = int(self.sm.logMonoTime['conditionalModelState'])
|
||||
valid = self.sm.seen['conditionalModelState'] and self.sm.valid['conditionalModelState'] and self.sm.alive['conditionalModelState']
|
||||
wire = State(str(state.session), str(state.requestId), str(state.phase), int(state.frameMonoTime), int(state.sessionStartMonoTime)) if valid else None
|
||||
axes = getattr(drive, 'aol_axis_decision', None)
|
||||
idle = (drive.initialized and getattr(drive, 'conditional_car_state_valid', False) and
|
||||
not drive.enabled and not drive.active and drive.state_machine.state == log.SelfdriveState.OpenpilotState.disabled and
|
||||
car.canValid and not car.canTimeout and not car.cruiseState.enabled and
|
||||
not any(getattr(axes, field, False) for field in
|
||||
('desired_lateral', 'desired_longitudinal', 'lateral_active', 'longitudinal_active')))
|
||||
if drive.aol_replay:
|
||||
intent = current_intent(drive.sm, car_state_ns=drive.aol_car_state_log_ns, now_ns=now,
|
||||
previous=getattr(drive, 'aol_last_intent', None), companion=getattr(drive, 'aol_intent_companion', None), drain=False)
|
||||
idle = bool(idle and intent is not None and not intent.allowedLatch and not intent.lateralArmed)
|
||||
model_valid = bool(drive.sm.valid['modelV2'] and drive.sm.alive['modelV2'])
|
||||
events = getattr(drive, 'events', None)
|
||||
holding = self.hold.step(wire, stamp, now, idle=idle, model_stamp=int(drive.sm.logMonoTime['modelV2']), model_valid=model_valid,
|
||||
release_allowed=events is None or not events.contains(ET.ENABLE))
|
||||
message = messaging.new_message('conditionalModelAck', valid=True)
|
||||
message.conditionalModelAck = {'session': str(state.session), 'requestId': str(state.requestId),
|
||||
'holding': holding and self.hold.owner == (str(state.session), str(state.requestId)),
|
||||
'stateMonoTime': stamp, 'idle': idle}
|
||||
self.pm.send('conditionalModelAck', message)
|
||||
return holding
|
||||
|
||||
|
||||
class ConditionalModelRuntime:
|
||||
"""Startup-only allocation, frame-boundary selection, one existing publisher."""
|
||||
def __init__(self, model, prepared, config, *, root, cam_w, cam_h, enabled):
|
||||
import os
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.starpilot.models.manager import catalog, verified_artifact, shipped_default
|
||||
from openpilot.starpilot.models.catalog import DEFAULT_SMALL, DEFAULT_SMALL_SHA256
|
||||
from openpilot.starpilot.models.receipt import process_start_ticks
|
||||
from openpilot.starpilot.models.runner import load_verified_model
|
||||
self.config, self.pid = config, os.getpid()
|
||||
self.ticks = process_start_ticks(self.pid)
|
||||
self.ack = messaging.SubMaster(['conditionalModelAck'])
|
||||
self.policy = SpeedPolicy(config['thresholdMph'])
|
||||
self.paused = False
|
||||
self.last_status = None
|
||||
self.unavailable_reason = ''
|
||||
models, error = {}, ''
|
||||
if enabled and config['enabled']:
|
||||
try:
|
||||
if model.model_id != config['city']:
|
||||
raise ValueError('Selected model fell back; resident switching unavailable for this drive')
|
||||
models[model.model_id] = model, prepared, model.handoff_reset()
|
||||
entries = catalog(root)
|
||||
for mid in {config['highway'], config['city']} - {model.model_id}:
|
||||
path = verified_artifact(mid, entries, root)
|
||||
shipped = mid == DEFAULT_SMALL and path is None
|
||||
if shipped:
|
||||
path = shipped_default()
|
||||
if path is None:
|
||||
raise ValueError('Alternate Small artifact is missing or corrupt')
|
||||
# Disk size does not qualify GPU residency. Preserve substantial host
|
||||
# headroom; target-device pressure/timing still needs bench evidence.
|
||||
from pathlib import Path
|
||||
memory = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines())
|
||||
available = int(memory['MemAvailable'].split()[0]) * 1024
|
||||
if available < 512 * 1024**2 + 4 * path.stat().st_size:
|
||||
raise MemoryError('Insufficient memory headroom to preload the alternate model')
|
||||
other, artifact = load_verified_model(cam_w, cam_h, path, entries[mid]['version'], False, mid,
|
||||
DEFAULT_SMALL_SHA256 if shipped else entries[mid]['artifact_sha256'], root=root)
|
||||
models[mid] = other, artifact, other.handoff_reset()
|
||||
except Exception as exc:
|
||||
cloudlog.exception('Conditional Model preload failed; keeping the current Small model')
|
||||
models, error = {}, str(exc)[:300]
|
||||
elif config['enabled']:
|
||||
self.unavailable_reason = 'Conditional Model is inactive while an external or Split Model is in use'
|
||||
self.owner = ResidentSwitch(models, model.model_id, now=time.monotonic_ns(), error=error)
|
||||
|
||||
def before_frame(self, sm):
|
||||
self.ack.update(0)
|
||||
now = time.monotonic_ns()
|
||||
a = self.ack['conditionalModelAck']
|
||||
ack = (Ack(str(a.session), str(a.requestId), bool(a.holding), int(a.stateMonoTime), int(self.ack.logMonoTime['conditionalModelAck']), bool(a.idle))
|
||||
if self.ack.seen['conditionalModelAck'] and self.ack.valid['conditionalModelAck'] and self.ack.alive['conditionalModelAck'] else None)
|
||||
idle = bool(modeld_idle(sm, now) and ack and ack.idle and fresh(ack.stamp, now))
|
||||
desired = None
|
||||
if self.owner.models:
|
||||
# A failure pauses automation for the drive; no repeated load/reset loop.
|
||||
self.paused |= bool(self.owner.error)
|
||||
current = 'highway' if self.owner.active == self.config['highway'] else 'city'
|
||||
car = sm['carState']
|
||||
role = self.policy.sample(float(car.vEgo), int(sm.logMonoTime['carState']), now,
|
||||
valid=bool(sm.seen['carState'] and sm.valid['carState'] and sm.alive['carState'] and
|
||||
car.canValid and not car.canTimeout), current=current)
|
||||
if (role and not self.paused and self.owner.phase == 'ready' and idle and not ack.holding and
|
||||
fresh(self.owner.frame, now) and self.config[role] != self.owner.active):
|
||||
desired = {'session': self.owner.session, 'id': uuid.uuid4().hex, 'model': self.config[role]}
|
||||
changed = self.owner.before_frame(desired, now=now, idle=idle, ack=ack)
|
||||
if changed:
|
||||
self.policy.switched(now)
|
||||
status = (self.owner.request, self.owner.phase, self.owner.error)
|
||||
if status != self.last_status:
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
cloudlog.event('conditionalModelState', request=status[0], phase=status[1], error=status[2], model_id=self.owner.active)
|
||||
self.last_status = status
|
||||
return self.owner.models[self.owner.active] if changed else None
|
||||
|
||||
def publish(self, pm, sm, frame):
|
||||
from openpilot.cereal import messaging
|
||||
now = time.monotonic_ns()
|
||||
if frame:
|
||||
self.owner.published(frame, now)
|
||||
message = messaging.new_message('conditionalModelState', valid=True)
|
||||
owner = self.owner
|
||||
ack_idle = bool(self.ack.seen['conditionalModelAck'] and self.ack.valid['conditionalModelAck'] and self.ack.alive['conditionalModelAck'] and
|
||||
fresh(int(self.ack.logMonoTime['conditionalModelAck']), now) and
|
||||
self.ack['conditionalModelAck'].idle and not self.ack['conditionalModelAck'].holding)
|
||||
message.conditionalModelState = {'session': owner.session, 'requestId': owner.request, 'phase': owner.phase,
|
||||
'activeModel': owner.active, 'highwayModel': self.config['highway'], 'cityModel': self.config['city'],
|
||||
'error': owner.error, 'frameMonoTime': owner.frame,
|
||||
'canSwitch': bool(owner.models and owner.phase == 'ready' and modeld_idle(sm, now) and ack_idle),
|
||||
'processPid': self.pid, 'processStartTicks': self.ticks, 'sessionStartMonoTime': owner.born,
|
||||
'transitionSeconds': owner.elapsed, 'fallbackModel': owner.previous,
|
||||
'paused': self.paused or bool(owner.error),
|
||||
'targetMode': self.policy.hint, 'thresholdMph': self.config['thresholdMph'],
|
||||
'unavailableReason': self.unavailable_reason}
|
||||
if owner.phase == 'waiting' and not owner.announced:
|
||||
owner.announced = int(message.logMonoTime)
|
||||
pm.send('conditionalModelState', message)
|
||||
@@ -104,34 +104,7 @@ def _adapter_class():
|
||||
from openpilot.starpilot.models.runner import CatalogModelState
|
||||
if not isinstance(small, CatalogModelState):
|
||||
return None
|
||||
from tinygrad import Device
|
||||
import numpy as np
|
||||
|
||||
queues = [q for name, q in small.input_queues.items() if q.device != "NPY" and name not in FRAME_INPUTS]
|
||||
buffers = [q.uop.base.buffer for q in queues]
|
||||
views = []
|
||||
for buffer in buffers:
|
||||
if not buffer.is_allocated() or not hasattr(buffer.get_storage().host, "mv"):
|
||||
raise ValueError("Small model history has no allocated host mapping")
|
||||
view = buffer.as_memoryview(allow_zero_copy=True)
|
||||
if view.readonly or view.nbytes != buffer.nbytes:
|
||||
raise ValueError("Small model history mapping is not writable or complete")
|
||||
views.append(np.frombuffer(view, dtype=np.uint8))
|
||||
devices = tuple(Device[name] for name in dict.fromkeys(q.device for q in queues))
|
||||
arrays = tuple(small.npy.values())
|
||||
|
||||
def reset():
|
||||
# The local history is idle at a handover. Keep the existing buffers
|
||||
# and synchronize their device before zeroing their mapped storage.
|
||||
for device in devices:
|
||||
device.synchronize()
|
||||
for view in views:
|
||||
view.fill(0)
|
||||
small.prev_desire.fill(0)
|
||||
for array in arrays:
|
||||
array.fill(0)
|
||||
|
||||
return reset
|
||||
return small.handoff_reset()
|
||||
|
||||
return StarPilotAdapter
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ from openpilot.starpilot.models.catalog import (
|
||||
RESOURCE_URL = "https://huggingface.co/buckets/StarPilot-Driving/StarPilot-Resources/resolve"
|
||||
from openpilot.common.hardware import PC
|
||||
from openpilot.starpilot.storage import starpilot_storage_root
|
||||
from openpilot.starpilot.models import conditional_model
|
||||
|
||||
_HOST_MODELS = os.environ.get("STARPILOT_MODEL_DIR", "") if PC else ""
|
||||
ROOT = (Path(_HOST_MODELS) if _HOST_MODELS else starpilot_storage_root() / "models" if PC else Path("/data/models")) / GENERATION
|
||||
@@ -206,7 +207,7 @@ def catalog(root: Path = ROOT) -> dict[str, dict]:
|
||||
|
||||
def preferences(root: Path = ROOT) -> dict:
|
||||
default = {"small": DEFAULT_SMALL, "big": "", "userFavorites": [], "sortMode": "name",
|
||||
"randomizer": False, "blacklistedModels": []}
|
||||
"randomizer": False, "blacklistedModels": [], "conditionalModel": conditional_model.defaults()}
|
||||
try:
|
||||
saved = read_json(root / "preferences.json", 16384)
|
||||
entries = model_entries(root)
|
||||
@@ -222,6 +223,7 @@ def preferences(root: Path = ROOT) -> dict:
|
||||
default["randomizer"] = saved["randomizer"]
|
||||
if saved.get("sortMode") in ("name", "date", "date_oldest", "community", "series", "favorites", "released"):
|
||||
default["sortMode"] = saved["sortMode"]
|
||||
default["conditionalModel"] = conditional_model.configuration(saved | {"randomizer": default["randomizer"]}, entries)
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass
|
||||
return default
|
||||
@@ -309,7 +311,7 @@ class RuntimeSelection:
|
||||
|
||||
def requested_runtime_id(chestnut_available: bool, *, root: Path = ROOT) -> str:
|
||||
prefs = preferences(root)
|
||||
return prefs["big"] if chestnut_available and prefs["big"] else prefs["small"]
|
||||
return prefs["big"] if chestnut_available and prefs["big"] else conditional_model.starting_model(prefs)
|
||||
|
||||
|
||||
def randomize_next_start(chestnut_available: bool, *, root: Path = ROOT, chooser=random.choice) -> dict:
|
||||
@@ -330,10 +332,12 @@ def randomize_next_start(chestnut_available: bool, *, root: Path = ROOT, chooser
|
||||
return prefs
|
||||
|
||||
|
||||
def resolve_runtime(chestnut_available: bool, *, root: Path = ROOT, randomize: bool = False) -> RuntimeSelection:
|
||||
def resolve_runtime(chestnut_available: bool, *, root: Path = ROOT, randomize: bool = False, small_override: str | None = None) -> RuntimeSelection:
|
||||
prefs = randomize_next_start(chestnut_available, root=root) if randomize else preferences(root)
|
||||
entries = catalog(root)
|
||||
small, big = prefs["small"], prefs["big"]
|
||||
if small_override is not None and (small_override not in entries or entries[small_override].get('uses_external_gpu')):
|
||||
raise ModelError('Invalid recovery Small model')
|
||||
small, big = small_override or conditional_model.starting_model(prefs), prefs["big"]
|
||||
small_path = verified_artifact(small, entries, root)
|
||||
shipped = small == DEFAULT_SMALL and small_path is None
|
||||
if shipped:
|
||||
@@ -354,11 +358,13 @@ def resolve_runtime(chestnut_available: bool, *, root: Path = ROOT, randomize: b
|
||||
|
||||
class ModelManager:
|
||||
def __init__(self, *, root: Path = ROOT, parked: Callable[[], bool] | None = None,
|
||||
gpu_present: Callable[[], bool] | None = None, opener=urlopen, jetlink=None, refresh_catalog: bool = False):
|
||||
gpu_present: Callable[[], bool] | None = None, opener=urlopen, jetlink=None, refresh_catalog: bool = False,
|
||||
live_status: Callable[[], dict | None] = lambda: None):
|
||||
self.root, self.opener = root, opener
|
||||
self.refresh_catalog = refresh_catalog
|
||||
self.last_refresh_attempt: float | None = None
|
||||
self.jetlink = jetlink
|
||||
self.live_status = live_status
|
||||
self.parked = parked or (lambda: False)
|
||||
if gpu_present is None:
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
@@ -614,6 +620,7 @@ class ModelManager:
|
||||
from openpilot.starpilot.models.laboratory import configuration
|
||||
entries, prefs = catalog(self.root), preferences(self.root)
|
||||
parked, gpu = self.parked(), self.gpu_present()
|
||||
live = self.live_status()
|
||||
job = self._job_status()
|
||||
owner = self.jetlink_owner()
|
||||
jetlink = owner.snapshot()
|
||||
@@ -637,9 +644,11 @@ class ModelManager:
|
||||
"unavailableReason": "" if installed else "Checking artifact" if checking else
|
||||
"Download required" if published else f"{GENERATION} download not published"})
|
||||
count = sum(bool(row["installed"]) for row in models)
|
||||
return {"schemaVersion": 1, "models": models, "activeSmallModel": prefs["small"], "activeBigModel": active_big,
|
||||
return {"schemaVersion": 1, "models": models, "activeSmallModel": conditional_model.starting_model(prefs), "activeBigModel": active_big,
|
||||
"conditionalModel": prefs["conditionalModel"],
|
||||
"conditionalModelState": live,
|
||||
"jetlinkBig": jetlink_big, "bigNoneLabel": big_none, "laboratory": configuration(self.root),
|
||||
"currentModel": prefs["big"] if gpu and prefs["big"] else prefs["small"], "userFavorites": prefs["userFavorites"],
|
||||
"currentModel": prefs["big"] if gpu and prefs["big"] else conditional_model.starting_model(prefs), "userFavorites": prefs["userFavorites"],
|
||||
"sortMode": prefs["sortMode"], "randomizer": prefs["randomizer"], "blacklistedModels": prefs["blacklistedModels"],
|
||||
"summary": {"total": len(models), "installed": count, "missing": len(models)-count},
|
||||
"jobId": job.get("jobId", ""), "cancelRequested": job.get("cancelRequested", False),
|
||||
@@ -649,6 +658,7 @@ class ModelManager:
|
||||
"downloadProgress": self._download_progress(job),
|
||||
"isOnroad": not parked, "gpuAvailable": gpu, "jetlink": jetlink,
|
||||
"capabilities": {"configureLaboratory": not job["downloading"], "select": True, "download": parked,
|
||||
"conditionalModel": parked and not job["downloading"] and not prefs["randomizer"],
|
||||
"downloadAll": parked, "cancel": True,
|
||||
"jetlink": parked, "refresh": parked, "favorites": True, "delete": parked, "randomizer": True, "exclusions": True}}
|
||||
|
||||
@@ -660,6 +670,8 @@ class ModelManager:
|
||||
if not isinstance(payload, dict):
|
||||
raise ModelError("Invalid model request")
|
||||
with self.lock:
|
||||
if action == "conditional_model":
|
||||
return self._configure_conditional_model(payload)
|
||||
if action == "jetlink":
|
||||
self._require_parked()
|
||||
return self.jetlink_owner().configure(payload)
|
||||
@@ -693,6 +705,8 @@ class ModelManager:
|
||||
raise ModelError("Invalid sort mode")
|
||||
with state_lock(self.root):
|
||||
saved = preferences(self.root)
|
||||
if payload.get("randomizer") is True and saved["conditionalModel"]["enabled"]:
|
||||
raise ModelError("Disable Conditional Model before enabling Model Randomizer")
|
||||
saved.update(payload)
|
||||
atomic_json(self.root / "preferences.json", saved)
|
||||
return {**self.snapshot(), "message": "Model preferences saved"}
|
||||
@@ -773,6 +787,8 @@ class ModelManager:
|
||||
if jetlink:
|
||||
self._require_parked()
|
||||
saved = preferences(self.root)
|
||||
if profile == "small" and saved["conditionalModel"]["enabled"]:
|
||||
raise ModelError("Choose a highway/city profile or disable profiles before choosing Active Small")
|
||||
if saved["randomizer"]:
|
||||
raise ModelError("Turn Model Randomizer off before choosing a model")
|
||||
job = self._read_job()
|
||||
@@ -795,7 +811,7 @@ class ModelManager:
|
||||
saved = preferences(self.root)
|
||||
if self._job_busy():
|
||||
raise ModelError("Wait for the model download to finish before deleting a model")
|
||||
if mid in (saved["small"], saved["big"]):
|
||||
if mid in (saved["small"], saved["big"], *(saved["conditionalModel"][role] for role in conditional_model.CONDITIONS)):
|
||||
raise ModelError("Select another model before deleting this one")
|
||||
self._require_parked()
|
||||
path.unlink(missing_ok=True)
|
||||
@@ -803,6 +819,31 @@ class ModelManager:
|
||||
return {"message": "Downloaded model deleted"}
|
||||
raise ModelError("Unknown model action")
|
||||
|
||||
def _configure_conditional_model(self, payload: dict) -> dict:
|
||||
self._require_parked()
|
||||
if not payload or set(payload) - set(conditional_model.defaults()):
|
||||
raise ModelError('Invalid Conditional Model configuration')
|
||||
with state_lock(self.root):
|
||||
saved = preferences(self.root)
|
||||
value = saved['conditionalModel'] | payload
|
||||
if not conditional_model.validate(value, model_entries(self.root)):
|
||||
raise ModelError('Choose local Small models and a speed from 10 to 100 mph')
|
||||
if saved['randomizer']:
|
||||
raise ModelError('Turn Model Randomizer off before configuring Conditional Model')
|
||||
if self._job_busy():
|
||||
raise ModelError('Wait for the model download to finish before configuring Conditional Model')
|
||||
entries = catalog(self.root)
|
||||
if value['enabled']:
|
||||
for mid in {value[name] for name in conditional_model.CONDITIONS}:
|
||||
if not self._installed(mid, entries):
|
||||
raise ModelError('Download and verify both Small models first')
|
||||
self._require_parked()
|
||||
saved['conditionalModel'] = value
|
||||
atomic_json(self.root / 'preferences.json', saved)
|
||||
logging.info('Conditional Model configured: enabled=%s city=%s highway=%s threshold_mph=%s',
|
||||
value['enabled'], value['city'], value['highway'], value['thresholdMph'])
|
||||
return {**self.snapshot(), 'message': 'Conditional Model saved for the next drive'}
|
||||
|
||||
def _refresh(self) -> None:
|
||||
url = f"{RESOURCE_URL}/manifests/model_names_{GENERATION}.json"
|
||||
with self.opener(url, timeout=30) as response:
|
||||
|
||||
@@ -23,7 +23,7 @@ MAX_RECEIPT_BYTES = 1024
|
||||
MAX_ARTIFACT_BYTES = 2 * 1024 * 1024 * 1024
|
||||
_PREFIX = re.compile(r"[A-Za-z0-9_-]{1,32}\Z")
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}\Z")
|
||||
_REASONS = {None, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed"}
|
||||
_REASONS = {None, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed", "conditional-switch-failed"}
|
||||
|
||||
|
||||
class ReceiptUnavailable(ValueError):
|
||||
|
||||
@@ -6,19 +6,24 @@ from multiprocessing import Process
|
||||
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.starpilot.models.receipt import process_start_ticks, read_receipt, read_pair_receipt
|
||||
from openpilot.starpilot.models.recovery import KILL_GRACE_NS, STARTUP_FALLBACK_EXIT, ModelRecoveryOwner, RecoveryEvidence
|
||||
from openpilot.starpilot.models.recovery import INT_GRACE_NS, KILL_GRACE_NS, STARTUP_FALLBACK_EXIT, ModelRecoveryOwner, RecoveryEvidence
|
||||
from openpilot.starpilot.models.conditional_protocol import PRELOAD_TIMEOUT_NS, SWITCH_TIMEOUT_NS, fresh
|
||||
from openpilot.starpilot.models.status import ModelVariant
|
||||
from openpilot.system.manager.process import PythonProcess, join_process, launcher
|
||||
|
||||
SMALL_ONLY_ENV = 'STARPILOT_MODELD_RECOVERY_SMALL_ONLY'
|
||||
|
||||
|
||||
def modeld_launcher(module, name, small_only):
|
||||
def modeld_launcher(module, name, small_only, recovery_model=None):
|
||||
# Set in this fresh child before importing modeld; never alter manager's env.
|
||||
if small_only:
|
||||
os.environ[SMALL_ONLY_ENV] = '1'
|
||||
else:
|
||||
os.environ.pop(SMALL_ONLY_ENV, None)
|
||||
if small_only and recovery_model is not None:
|
||||
os.environ['STARPILOT_CONDITIONAL_RECOVERY_MODEL'] = recovery_model
|
||||
else:
|
||||
os.environ.pop('STARPILOT_CONDITIONAL_RECOVERY_MODEL', None)
|
||||
launcher(module, name)
|
||||
|
||||
|
||||
@@ -28,6 +33,12 @@ class ModeldProcess(PythonProcess):
|
||||
self.recovery = ModelRecoveryOwner()
|
||||
self.context_ready = False
|
||||
self.launch_drive_id = 0
|
||||
self.launch_conditional = False
|
||||
self.launch_ns = 0
|
||||
self.launch_ticks = 0
|
||||
self.conditional_recovery_model = None
|
||||
self.last_conditional_cameras = ()
|
||||
self.launch_established = False
|
||||
|
||||
def observe(self, sm, started):
|
||||
now = time.monotonic_ns()
|
||||
@@ -35,8 +46,8 @@ class ModeldProcess(PythonProcess):
|
||||
pid = self.proc.pid if self.proc is not None else 0
|
||||
ticks = process_start_ticks(pid or 0) if alive else 0
|
||||
identity = (pid, ticks) if pid and ticks else None
|
||||
load = read_receipt() if alive else None
|
||||
pair = read_pair_receipt() if alive else None
|
||||
load = read_receipt() if self.proc is not None else None
|
||||
pair = read_pair_receipt() if self.proc is not None else None
|
||||
pair_matches = pair is not None and identity == (pair.pid, pair.process_start_ticks)
|
||||
matches = load is not None and identity == (load.pid, load.process_start_ticks)
|
||||
cameras = []
|
||||
@@ -53,11 +64,69 @@ class ModeldProcess(PythonProcess):
|
||||
device_fresh = (sm.seen['deviceState'] and sm.valid['deviceState'] and sm.alive['deviceState'] and
|
||||
0 < int(sm.logMonoTime['deviceState']) <= now <= int(sm.logMonoTime['deviceState']) + 1_000_000_000)
|
||||
self.context_ready = bool(device_fresh and started)
|
||||
conditional_identity = identity if alive else (pid, self.launch_ticks)
|
||||
established = bool((load is not None and conditional_identity == (load.pid, load.process_start_ticks)) or
|
||||
(pair is not None and conditional_identity == (pair.pid, pair.process_start_ticks)))
|
||||
self.launch_established |= established
|
||||
conditional_stalled = conditional_held = False
|
||||
try:
|
||||
conditional = sm['conditionalModelState']
|
||||
owned = (int(conditional.processPid), int(conditional.processStartTicks)) == conditional_identity
|
||||
if (owned and sm.seen['conditionalModelState'] and sm.valid['conditionalModelState'] and
|
||||
fresh(int(sm.logMonoTime['conditionalModelState']), now) and
|
||||
0 < int(conditional.sessionStartMonoTime) <= int(conditional.frameMonoTime) <= now and
|
||||
all(sm.valid[name] and fresh(int(sm.logMonoTime[name]), now) and
|
||||
int(conditional.frameMonoTime) <= int(sm.logMonoTime[name]) for name in ('modelV2', 'drivingModelData'))):
|
||||
self.launch_established = True
|
||||
ack = sm['conditionalModelAck']
|
||||
conditional_held = bool(sm.seen['conditionalModelState'] and sm.valid['conditionalModelState'] and
|
||||
owned and
|
||||
str(conditional.phase) in ('waiting', 'switching', 'recovering', 'ready') and bool(str(conditional.requestId)) and
|
||||
sm.seen['conditionalModelAck'] and sm.valid['conditionalModelAck'] and bool(ack.holding) and
|
||||
(str(ack.session), str(ack.requestId)) == (str(conditional.session), str(conditional.requestId)) and
|
||||
0 < int(conditional.sessionStartMonoTime) <= int(ack.stateMonoTime) <= int(sm.logMonoTime['conditionalModelState']) <= now and
|
||||
int(ack.stateMonoTime) <= int(sm.logMonoTime['conditionalModelAck']) and
|
||||
0 < int(sm.logMonoTime['conditionalModelAck']) <= now and now - int(sm.logMonoTime['conditionalModelAck']) <= 150_000_000)
|
||||
camera_progress = bool(cameras and len(cameras) == len(self.last_conditional_cameras) and
|
||||
all(t > old_t and frame > old_frame for (t, frame), (old_t, old_frame) in zip(cameras, self.last_conditional_cameras, strict=True)))
|
||||
conditional_stalled = bool(conditional_held and camera_progress and
|
||||
0 < int(conditional.sessionStartMonoTime) <= int(sm.logMonoTime['conditionalModelState']) <= now and
|
||||
now - max(int(sm.logMonoTime['modelV2']), int(sm.logMonoTime['drivingModelData'])) >= SWITCH_TIMEOUT_NS and
|
||||
all(0 < t <= now and now - t <= 200_000_000 for t, _ in cameras))
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
pass
|
||||
self.last_conditional_cameras = tuple(cameras) if conditional_held else ()
|
||||
if conditional_held:
|
||||
from openpilot.starpilot.models.catalog import model_entries
|
||||
mid = str(getattr(conditional, 'fallbackModel', ''))
|
||||
entries = model_entries()
|
||||
if mid in entries and not entries[mid].uses_external_gpu:
|
||||
self.conditional_recovery_model = mid
|
||||
else:
|
||||
conditional_stalled = conditional_held = False
|
||||
preload_stalled = (self.launch_conditional and not self.launch_established and
|
||||
self.launch_ns and now - self.launch_ns >= PRELOAD_TIMEOUT_NS)
|
||||
if self.context_ready and alive and self.recovery.phase == 'monitor' and (preload_stalled or conditional_stalled):
|
||||
# Preloading native models is synchronous. Timeout ownership stays in the
|
||||
# manager process; a Python/GPU loader is never cancelled in place.
|
||||
self.recovery.drive_id = evidence.drive_id
|
||||
self.recovery.identity = identity
|
||||
self.recovery.small_only = True
|
||||
self.recovery.phase = 'sigint'
|
||||
self.recovery.deadline_ns = now + INT_GRACE_NS
|
||||
try:
|
||||
self.signal(signal.SIGINT)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
cloudlog.error('Conditional Model %s timed out; requesting isolated single-model restart', 'handoff' if conditional_stalled else 'preload')
|
||||
return
|
||||
if (self.context_ready and self.proc is not None and not alive and not self.shutting_down and
|
||||
self.proc.exitcode == STARTUP_FALLBACK_EXIT and self.recovery.phase == 'monitor' and
|
||||
(self.proc.exitcode == STARTUP_FALLBACK_EXIT or
|
||||
self.launch_conditional and (not self.launch_established or conditional_held) and self.proc.exitcode not in (None, 0)) and
|
||||
self.recovery.phase == 'monitor' and
|
||||
not self.recovery.small_only and 0 < self.launch_drive_id == evidence.drive_id):
|
||||
# Only our explicitly failed startup may request this one fresh process.
|
||||
# Never reuse the old GPU context or retry an arbitrary Small crash.
|
||||
# An explicitly failed startup or an acknowledged held handoff may
|
||||
# request one fresh process. Never retry an arbitrary established Small crash.
|
||||
self.proc.join(timeout=0)
|
||||
self.proc = None
|
||||
self.recovery.drive_id = evidence.drive_id
|
||||
@@ -119,8 +188,17 @@ class ModeldProcess(PythonProcess):
|
||||
self.stop(block=False)
|
||||
if self.proc is not None:
|
||||
return
|
||||
if not self.recovery.small_only:
|
||||
self.conditional_recovery_model = None
|
||||
self.last_conditional_cameras = ()
|
||||
self.launch_established = False
|
||||
self.proc = Process(name=self.name, target=modeld_launcher,
|
||||
args=(self.module, self.name, self.recovery.small_only))
|
||||
args=(self.module, self.name, self.recovery.small_only),
|
||||
kwargs={'recovery_model': self.conditional_recovery_model} if self.recovery.small_only and self.conditional_recovery_model else {})
|
||||
self.launch_drive_id = self.recovery.drive_id
|
||||
from openpilot.starpilot.models.manager import preferences
|
||||
self.launch_conditional = not self.recovery.small_only and preferences()['conditionalModel']['enabled']
|
||||
self.launch_ns = time.monotonic_ns()
|
||||
self.proc.start()
|
||||
self.launch_ticks = process_start_ticks(self.proc.pid or 0)
|
||||
self.shutting_down = False
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
import resource
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
import weakref
|
||||
@@ -11,6 +13,7 @@ import numpy as np
|
||||
from tinygrad import Tensor, dtypes
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.controls.lib.drive_helpers import MIN_SPEED, smooth_value
|
||||
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan
|
||||
from openpilot.selfdrive.modeld.helpers import load_oob
|
||||
@@ -51,18 +54,25 @@ def load_verified_model(cam_w: int, cam_h: int, artifact_path: Path, behavior_ve
|
||||
|
||||
if expected_sha256 is None:
|
||||
raise ValueError("selected catalog model has no verified digest")
|
||||
started = time.monotonic()
|
||||
with state_lock(ROOT if root is None else root):
|
||||
identity = artifact_identity(artifact_path)
|
||||
prepared = prepare_artifact(artifact_path, identity)
|
||||
if prepared.sha256 != expected_sha256:
|
||||
raise ValueError("selected catalog model changed before loading")
|
||||
verified_at = time.monotonic()
|
||||
model = CatalogModelState(cam_w, cam_h, artifact_path, behavior_version, chestnut)
|
||||
if coherent_warp is not None:
|
||||
model.move_warp_output(coherent_warp)
|
||||
loaded_at = time.monotonic()
|
||||
model.warmup()
|
||||
if artifact_identity(artifact_path) != identity:
|
||||
raise ValueError("selected catalog model changed while loading")
|
||||
model.model_id = model_id
|
||||
cloudlog.event("modeld.catalog_load", model_id=model_id, chestnut=chestnut,
|
||||
verify_seconds=verified_at - started, load_seconds=loaded_at - verified_at,
|
||||
warmup_seconds=time.monotonic() - loaded_at,
|
||||
process_peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
|
||||
return model, prepared
|
||||
|
||||
|
||||
@@ -241,6 +251,31 @@ class CatalogModelState:
|
||||
self._pending_frame: tuple | None = None
|
||||
self._last_shared_warp: SharedCameraWarp | None = None
|
||||
|
||||
def handoff_reset(self) -> Callable[[], None]:
|
||||
"""Prepare an in-place reset; captured JIT buffers must keep their addresses."""
|
||||
from tinygrad import Device
|
||||
queues = [q for name, q in self.input_queues.items() if q.device != 'NPY' and name != 'mapped_gpu_image']
|
||||
views = []
|
||||
for queue in queues:
|
||||
buffer = queue.uop.base.buffer
|
||||
if not buffer.is_allocated() or not hasattr(buffer.get_storage().host, 'mv'):
|
||||
raise ValueError('Small model history has no allocated host mapping')
|
||||
view = buffer.as_memoryview(allow_zero_copy=True)
|
||||
if view.readonly or view.nbytes != buffer.nbytes:
|
||||
raise ValueError('Small model history mapping is not writable or complete')
|
||||
views.append(np.frombuffer(view, dtype=np.uint8))
|
||||
devices = tuple(Device[name] for name in dict.fromkeys(q.device for q in queues))
|
||||
arrays = tuple(self.npy.values())
|
||||
def reset():
|
||||
for device in devices:
|
||||
device.synchronize()
|
||||
for view in views:
|
||||
view.fill(0)
|
||||
self.prev_desire.fill(0)
|
||||
for array in arrays:
|
||||
array.fill(0)
|
||||
return reset
|
||||
|
||||
def _validate_shared_warp(self, shared: SharedCameraWarp, pointers: tuple[int, int], transforms: tuple[bytes, bytes]) -> None:
|
||||
if (not isinstance(shared, SharedCameraWarp) or self.camera_warp_descriptor is None or
|
||||
shared.descriptor != self.camera_warp_descriptor):
|
||||
|
||||
@@ -11,7 +11,7 @@ from openpilot.starpilot.models.receipt import process_start_ticks, read_receipt
|
||||
from openpilot.starpilot.models.status import ModelLoad, ModelOutput, ModelProcess, ModelStatus, project_status, project_laboratory_status
|
||||
|
||||
|
||||
MODEL_SERVICES = ("managerState", "modelV2", "drivingModelData")
|
||||
MODEL_SERVICES = ("managerState", "modelV2", "drivingModelData", "conditionalModelState")
|
||||
|
||||
|
||||
def _stamp(sm: Any, service: str, now_mono_ns: int) -> tuple[int, bool]:
|
||||
@@ -80,7 +80,11 @@ class ModelStatusSource:
|
||||
self.sm.update(0)
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
from openpilot.starpilot.models.manager import requested_runtime_id
|
||||
return snapshot(self.sm, self.params, self.clock(), requested_id=requested_runtime_id(chestnut_present()))
|
||||
requested = requested_runtime_id(chestnut_present())
|
||||
conditional = self.conditional_json()
|
||||
if conditional is not None and conditional['phase'] in ('ready', 'switching', 'recovering'):
|
||||
requested = conditional['activeModel']
|
||||
return snapshot(self.sm, self.params, self.clock(), requested_id=requested)
|
||||
|
||||
def json(self) -> dict[str, object]:
|
||||
status = self.snapshot()
|
||||
@@ -90,8 +94,30 @@ class ModelStatusSource:
|
||||
"variant": status.variant.value if status.variant is not None else None,
|
||||
"health": status.health.value, "fallbackReason": status.fallback_reason,
|
||||
"artifactSha256": status.artifact_sha256, "pendingNextStart": status.pending_next_start,
|
||||
"conditionalModelState": self.conditional_json(),
|
||||
"laboratory": self.laboratory_json(self.laboratory_configuration())}
|
||||
|
||||
def conditional_json(self) -> dict | None:
|
||||
now = self.clock()
|
||||
process = _process(self.sm, now, process_start_ticks)
|
||||
if process is None or not _stamp(self.sm, 'conditionalModelState', now)[1]:
|
||||
return None
|
||||
try:
|
||||
state = self.sm['conditionalModelState']
|
||||
if (int(state.processPid), int(state.processStartTicks)) != (process.pid, process.start_ticks):
|
||||
return None
|
||||
fresh_output = bool(0 < int(state.sessionStartMonoTime) <= int(state.frameMonoTime) <= now and
|
||||
all(_stamp(self.sm, name, now)[1] and int(state.frameMonoTime) <= self.sm.logMonoTime[name]
|
||||
for name in ('modelV2', 'drivingModelData')))
|
||||
return {'session': str(state.session), 'requestId': str(state.requestId), 'phase': str(state.phase),
|
||||
'activeModel': str(state.activeModel), 'highwayModel': str(state.highwayModel), 'cityModel': str(state.cityModel),
|
||||
'error': str(state.error), 'canSwitch': bool(fresh_output and state.canSwitch),
|
||||
'paused': bool(state.paused), 'targetMode': str(state.targetMode),
|
||||
'thresholdMph': int(state.thresholdMph), 'unavailableReason': str(state.unavailableReason),
|
||||
'transitionSeconds': float(state.transitionSeconds)}
|
||||
except (AttributeError, KeyError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def laboratory_configuration() -> dict:
|
||||
from openpilot.starpilot.models.laboratory import configuration
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.selfdrive.selfdrived.alertmanager import AlertManager
|
||||
from openpilot.selfdrive.selfdrived.events import AlertStatus, AlertSize, Priority, VisualAlert, AudibleAlert, Alert
|
||||
from openpilot.starpilot.models.conditional_alerts import conditional_model_alert, ALERT_TYPES
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase', ['waiting', 'switching', 'recovering'])
|
||||
def test_banner_describes_handoff_even_without_engagement_attempt(phase):
|
||||
alert = conditional_model_alert(NS(phase=phase, error=''), holding=True)
|
||||
assert alert.alert_text_1 == 'Switching conditional models'
|
||||
assert alert.alert_size == AlertSize.small
|
||||
assert alert.priority == Priority.LOWEST and alert.audible_alert == AudibleAlert.none
|
||||
|
||||
|
||||
def test_errors_and_stalls_are_visible_but_never_claim_ready():
|
||||
error = conditional_model_alert(NS(phase='ready', error='Candidate inference failed; previous model restored'), holding=False)
|
||||
assert error.alert_text_1 == 'Conditional Model unavailable'
|
||||
assert 'previous model restored' in error.alert_text_2
|
||||
stalled = conditional_model_alert(None, holding=True, stalled=True)
|
||||
assert stalled.alert_text_1 == 'Conditional model switch stalled'
|
||||
assert 'Engagement blocked' in stalled.alert_text_2
|
||||
assert conditional_model_alert(None, holding=False) is None
|
||||
assert conditional_model_alert(NS(phase='ready', error=''), holding=False) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('priority', [Priority.LOWEST, Priority.LOW, Priority.HIGHEST])
|
||||
def test_road_notice_does_not_replace_equal_or_higher_priority_vehicle_alert(priority):
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.alert = Mock(return_value=conditional_model_alert(None, holding=True))
|
||||
native = Alert('TAKE CONTROL', '', AlertStatus.critical, AlertSize.full, priority, VisualAlert.steerRequired, AudibleAlert.warningImmediate, 1.)
|
||||
alerts, manager = [native], AlertManager()
|
||||
manager.alerts.update({key: object() for key in ALERT_TYPES})
|
||||
gate.update_alerts(alerts, manager)
|
||||
assert alerts == [native] and not manager.alerts
|
||||
manager.add_many(0, alerts)
|
||||
manager.process_alerts(0, set())
|
||||
assert manager.current_alert is native
|
||||
|
||||
|
||||
def test_completion_removes_only_conditional_model_notices():
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.alert = Mock(return_value=None)
|
||||
manager = NS(alerts={ALERT_TYPES[0]: object(), 'vehicle-alert': object()})
|
||||
alerts = []
|
||||
gate.update_alerts(alerts, manager)
|
||||
assert not alerts and set(manager.alerts) == {'vehicle-alert'}
|
||||
|
||||
|
||||
def test_retained_native_alert_remains_visible_without_road_banner():
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.alert = Mock(return_value=conditional_model_alert(None, holding=True))
|
||||
manager = AlertManager()
|
||||
native = Alert('Vehicle warning', '', AlertStatus.userPrompt, AlertSize.mid, Priority.LOW,
|
||||
VisualAlert.none, AudibleAlert.none, 1.)
|
||||
native.alert_type = 'native/warning'
|
||||
manager.add_many(0, [native])
|
||||
alerts = []
|
||||
gate.update_alerts(alerts, manager, frame=1)
|
||||
assert not alerts and 'native/warning' in manager.alerts
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Speed classification is deterministic and independent of inference/control."""
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy, MPH_TO_MS
|
||||
|
||||
BASE = 100_000_000_000
|
||||
|
||||
|
||||
def sample(policy, mph, t=0., *, current='highway', **kwargs):
|
||||
now = BASE + round(t * 1e9)
|
||||
return policy.sample(mph * MPH_TO_MS, kwargs.pop('stamp', now), now, current=current, valid=kwargs.pop('valid', True), **kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mph,role', [(0, None), (45, None), (49, None), (49.99, None), (50, 'highway'), (54.99, 'highway'), (55, 'highway'), (60, 'highway')])
|
||||
def test_highway_entry_is_immediate_at_configured_speed(mph, role):
|
||||
assert sample(SpeedPolicy(), mph, current='city') == role
|
||||
|
||||
|
||||
def test_city_requires_thirty_continuous_seconds_and_deadband_resets_clock():
|
||||
policy = SpeedPolicy()
|
||||
for i in range(600):
|
||||
assert sample(policy, 45, i * .05) is None
|
||||
assert sample(policy, 45, 30.) == 'city'
|
||||
assert sample(policy, 46, 30.05) is None
|
||||
assert policy.low_since is None
|
||||
assert sample(policy, 45, 30.1) is None
|
||||
|
||||
|
||||
def test_oscillation_near_threshold_does_not_flap():
|
||||
policy = SpeedPolicy()
|
||||
current, changes = 'city', []
|
||||
for i in range(2400):
|
||||
role = sample(policy, 45 if i % 2 else 55, i * .05, current=current)
|
||||
if role:
|
||||
current = role
|
||||
changes.append(role)
|
||||
policy.switched(BASE + round(i * .05 * 1e9))
|
||||
assert changes == ['highway']
|
||||
|
||||
|
||||
def test_highway_merge_bypasses_city_cooldown_and_return_requires_another_dwell():
|
||||
policy = SpeedPolicy()
|
||||
policy.switched(BASE)
|
||||
assert sample(policy, 60, .05, current='city') == 'highway'
|
||||
policy.switched(BASE + 50_000_000)
|
||||
for i in range(1, 601):
|
||||
assert sample(policy, 40, .05 + i * .05) is None
|
||||
assert sample(policy, 40, 30.1) == 'city'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [math.nan, math.inf, -math.inf, -1., 101., True, None, '60'])
|
||||
def test_invalid_speed_breaks_city_dwell(bad):
|
||||
policy = SpeedPolicy()
|
||||
sample(policy, 40)
|
||||
assert policy.sample(bad, BASE + 50_000_000, BASE + 50_000_000, valid=True, current='highway') is None
|
||||
assert policy.low_since is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', [{'stamp': 0}, {'stamp': BASE + 1_000_000_000}, {'stamp': BASE - 1}, {'valid': False}])
|
||||
def test_bad_or_reordered_sources_cannot_advance_dwell(change):
|
||||
policy = SpeedPolicy()
|
||||
sample(policy, 40)
|
||||
assert sample(policy, 40, .05, **change) is None
|
||||
assert policy.low_since is None
|
||||
|
||||
|
||||
def test_sampling_gap_requires_new_full_dwell():
|
||||
policy = SpeedPolicy()
|
||||
sample(policy, 40)
|
||||
assert sample(policy, 40, 31.) is None
|
||||
assert policy.low_since == BASE + 31_000_000_000
|
||||
|
||||
|
||||
@pytest.mark.parametrize('threshold', [True, 50., 9, 101, math.nan])
|
||||
def test_invalid_policy_settings_are_rejected(threshold):
|
||||
with pytest.raises(ValueError):
|
||||
SpeedPolicy(threshold)
|
||||
|
||||
|
||||
def test_user_speed_is_the_actual_highway_trigger_with_internal_return_delay():
|
||||
policy = SpeedPolicy(60)
|
||||
assert sample(policy, 59.99, current='city') is None
|
||||
assert sample(policy, 60, .05, current='city') == 'highway'
|
||||
for i in range(601):
|
||||
result = sample(policy, 55, .1 + i * .05)
|
||||
assert result == ('city' if i == 600 else None)
|
||||
@@ -0,0 +1,493 @@
|
||||
"""Protocol and owner tests; these do not qualify device memory or latency."""
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.starpilot.models.conditional_protocol import (
|
||||
ACK_TIMEOUT_NS, SETTLE_FRAMES, SWITCH_TIMEOUT_NS, Ack, EngagementHold, ResidentSwitch, State,
|
||||
)
|
||||
from openpilot.starpilot.models.conditional_runtime import modeld_idle
|
||||
|
||||
BASE = 10_000_000_000
|
||||
|
||||
|
||||
def switcher():
|
||||
models = {name: (NS(model_id=name), name + '-receipt', Mock()) for name in ('highway', 'city')}
|
||||
owner = ResidentSwitch(models, 'highway', now=BASE)
|
||||
request = {'session': owner.session, 'id': 'a' * 32, 'model': 'city'}
|
||||
return owner, request
|
||||
|
||||
|
||||
def begin(owner, request):
|
||||
assert not owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
assert owner.phase == 'waiting'
|
||||
owner.announced = BASE
|
||||
ack = Ack(owner.session, request['id'], True, BASE, BASE + 10_000_000)
|
||||
assert owner.before_frame(request, now=BASE + 20_000_000, idle=True, ack=ack)
|
||||
assert owner.active == 'city'
|
||||
|
||||
|
||||
def test_resident_swap_changes_only_after_matching_fresh_hold_and_keeps_separate_state():
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
owner.models['city'][2].assert_called_once()
|
||||
owner.models['highway'][2].assert_not_called()
|
||||
for i in range(SETTLE_FRAMES):
|
||||
owner.published(BASE + (i + 1) * 50_000_000, BASE + (i + 1) * 50_000_000)
|
||||
assert owner.phase == ('ready' if i == SETTLE_FRAMES - 1 else 'switching')
|
||||
assert owner.elapsed == .25
|
||||
assert not owner.before_frame(request, now=BASE + 300_000_000, idle=True, ack=None)
|
||||
# Returning to Highway resets its own original buffers, never City's state.
|
||||
request = request | {'id': 'b' * 32, 'model': 'highway'}
|
||||
assert not owner.before_frame(request, now=BASE + 300_000_000, idle=True, ack=None)
|
||||
owner.announced = BASE + 300_000_000
|
||||
assert owner.before_frame(request, now=BASE + 320_000_000, idle=True,
|
||||
ack=Ack(owner.session, request['id'], True, owner.announced, BASE + 310_000_000))
|
||||
owner.models['highway'][2].assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', [{'session': 'old'}, {'request': 'old'}, {'holding': False},
|
||||
{'source': BASE - 1}, {'stamp': BASE - 200_000_000}, {'stamp': BASE + 999_000_000}])
|
||||
def test_bad_ack_never_changes_runner(change):
|
||||
owner, request = switcher()
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.announced = BASE
|
||||
values = {'session': owner.session, 'request': request['id'], 'holding': True, 'source': BASE, 'stamp': BASE + 10_000_000}
|
||||
assert not owner.before_frame(request, now=BASE + 20_000_000, idle=True, ack=Ack(**(values | change)))
|
||||
assert owner.active == 'highway'
|
||||
owner.models['city'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_engaged_request_denied_and_engagement_race_cancels_before_reset():
|
||||
owner, request = switcher()
|
||||
assert not owner.before_frame(request, now=BASE, idle=False, ack=None)
|
||||
assert owner.phase == 'ready' and owner.error
|
||||
request['id'] = 'b' * 32
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.announced = BASE
|
||||
assert not owner.before_frame(request, now=BASE + 10_000_000, idle=False,
|
||||
ack=Ack(owner.session, request['id'], True, BASE, BASE + 5_000_000))
|
||||
assert owner.active == 'highway' and not owner.error
|
||||
owner.models['city'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_ack_timeout_consumes_request_token_and_retains_current_model():
|
||||
owner, request = switcher()
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.before_frame(request, now=BASE + ACK_TIMEOUT_NS, idle=True, ack=None)
|
||||
assert owner.active == 'highway' and owner.phase == 'ready' and 'timed out' in owner.error
|
||||
owner.before_frame(request, now=BASE + ACK_TIMEOUT_NS + 1, idle=True, ack=None)
|
||||
assert owner.phase == 'ready'
|
||||
|
||||
|
||||
def test_reset_failure_and_inference_failure_restore_previous_without_reloading():
|
||||
owner, request = switcher()
|
||||
owner.models['city'][2].side_effect = RuntimeError('mapping unavailable')
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.announced = BASE
|
||||
assert not owner.before_frame(request, now=BASE + 20_000_000, idle=True,
|
||||
ack=Ack(owner.session, request['id'], True, BASE, BASE + 10_000_000))
|
||||
assert owner.active == 'highway' and 'reset failed' in owner.error
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
owner.abort('Candidate inference failed', BASE + 40_000_000)
|
||||
assert owner.active == 'highway' and owner.phase == 'recovering'
|
||||
owner.models['highway'][2].assert_called_once()
|
||||
for i in range(SETTLE_FRAMES):
|
||||
owner.published(BASE + (i + 1) * 50_000_000, BASE + (i + 1) * 50_000_000)
|
||||
assert owner.phase == 'ready' and owner.error == 'Candidate inference failed'
|
||||
|
||||
|
||||
def test_handoff_timeout_rolls_back_but_unknown_engagement_keeps_hold():
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
assert not owner.before_frame(request, now=BASE + SWITCH_TIMEOUT_NS, idle=False, ack=None)
|
||||
for i in range(SETTLE_FRAMES + 1):
|
||||
owner.published(BASE + SWITCH_TIMEOUT_NS + i, BASE + SWITCH_TIMEOUT_NS + i)
|
||||
assert owner.phase == 'switching' and owner.active == 'city'
|
||||
assert owner.before_frame(request, now=BASE + SWITCH_TIMEOUT_NS + 100, idle=True, ack=None)
|
||||
assert owner.active == 'highway' and owner.phase == 'recovering'
|
||||
|
||||
|
||||
def test_wrong_session_and_nonresident_model_are_never_loaded():
|
||||
owner, request = switcher()
|
||||
assert not owner.before_frame(request | {'session': 'prior-drive'}, now=BASE, idle=True, ack=None)
|
||||
assert owner.request == ''
|
||||
assert not owner.before_frame(request | {'model': 'unloaded'}, now=BASE, idle=True, ack=None)
|
||||
assert owner.active == 'highway' and owner.error
|
||||
|
||||
|
||||
def test_engagement_hold_blocks_reengagement_until_post_handoff_output():
|
||||
hold = EngagementHold()
|
||||
waiting = State('session', 'request', 'waiting', BASE - 1, BASE - 100)
|
||||
assert hold.step(waiting, BASE, BASE, idle=True, model_stamp=BASE - 1, model_valid=True)
|
||||
assert hold.step(None, 0, BASE + 9_000_000_000, idle=True, model_stamp=0, model_valid=False)
|
||||
ready = State('session', 'request', 'ready', BASE + 50_000_000, BASE - 100)
|
||||
assert hold.step(ready, BASE + 60_000_000, BASE + 60_000_000, idle=True, model_stamp=BASE, model_valid=True)
|
||||
assert not hold.step(ready, BASE + 70_000_000, BASE + 70_000_000, idle=True, model_stamp=BASE + 50_000_000, model_valid=True)
|
||||
|
||||
|
||||
def test_hold_denies_engaged_and_stale_states_and_requires_new_publisher_after_restart():
|
||||
hold = EngagementHold()
|
||||
waiting = State('session', 'request', 'waiting', 0, BASE)
|
||||
assert not hold.step(waiting, BASE, BASE, idle=False, model_stamp=BASE, model_valid=True)
|
||||
assert not hold.step(waiting, BASE, BASE + 200_000_000, idle=True, model_stamp=BASE, model_valid=True)
|
||||
assert hold.step(waiting, BASE + 210_000_000, BASE + 210_000_000, idle=True, model_stamp=BASE, model_valid=True)
|
||||
restarted = State('new-process', '', 'disabled', BASE + 300_000_000, BASE + 250_000_000)
|
||||
assert hold.step(restarted, BASE + 310_000_000, BASE + 310_000_000, idle=True, model_stamp=BASE + 220_000_000, model_valid=True)
|
||||
assert not hold.step(restarted, BASE + 320_000_000, BASE + 320_000_000, idle=True,
|
||||
model_stamp=BASE + 300_000_000, model_valid=True)
|
||||
|
||||
|
||||
class Feed(dict):
|
||||
def __init__(self):
|
||||
super().__init__(selfdriveState=NS(enabled=False, active=False, state='disabled'),
|
||||
carControl=NS(enabled=False, latActive=False, longActive=False),
|
||||
carState=NS(cruiseState=NS(enabled=False), canValid=True, canTimeout=False, vEgo=0.))
|
||||
self.seen = self.valid = self.alive = dict.fromkeys(self, True)
|
||||
self.logMonoTime = dict.fromkeys(self, BASE)
|
||||
|
||||
|
||||
def test_disengagement_evidence_must_be_fresh_and_include_both_axes_and_stock_cruise():
|
||||
sm = Feed()
|
||||
assert modeld_idle(sm, BASE)
|
||||
for service, field in (('carControl', 'latActive'), ('carControl', 'longActive'), ('selfdriveState', 'enabled')):
|
||||
setattr(sm[service], field, True)
|
||||
assert not modeld_idle(sm, BASE)
|
||||
setattr(sm[service], field, False)
|
||||
sm['carState'].cruiseState.enabled = True
|
||||
assert not modeld_idle(sm, BASE)
|
||||
sm['carState'].cruiseState.enabled = False
|
||||
assert not modeld_idle(sm, BASE + 200_000_000)
|
||||
sm['selfdriveState'].state = 'preEnabled'
|
||||
assert not modeld_idle(sm, BASE)
|
||||
|
||||
|
||||
def test_live_handshake_over_real_typed_ipc_has_valid_state_and_ack():
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.selfdrived.state import StateMachine
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime, ConditionalModelGate
|
||||
|
||||
messaging.set_fake_prefix('conditional_runtime_' + uuid.uuid4().hex)
|
||||
gate = ConditionalModelGate()
|
||||
publisher = messaging.PubMaster(['conditionalModelState'])
|
||||
acknowledgments = messaging.SubMaster(['conditionalModelAck'])
|
||||
now = time.monotonic_ns()
|
||||
modes = ConditionalModelRuntime.__new__(ConditionalModelRuntime)
|
||||
modes.owner = ResidentSwitch({'highway': ()}, 'highway', now=now)
|
||||
modes.owner.phase, modes.owner.request = 'waiting', uuid.uuid4().hex
|
||||
modes.pid, modes.ticks = os.getpid(), 1
|
||||
modes.config = {'highway': 'highway', 'city': 'city', 'thresholdMph': 50}
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy
|
||||
modes.paused, modes.policy, modes.unavailable_reason = False, SpeedPolicy(), ''
|
||||
modes.ack = NS(seen={'conditionalModelAck': False})
|
||||
sm = Feed()
|
||||
sm.logMonoTime = dict.fromkeys(sm, now)
|
||||
drive = NS(initialized=True, conditional_car_state_valid=True, enabled=False, active=False,
|
||||
state_machine=StateMachine(), aol_replay=False, aol_axis_decision=None,
|
||||
sm=NS(valid={'modelV2': True}, alive={'modelV2': True}, logMonoTime={'modelV2': now}), events=None)
|
||||
car = NS(canValid=True, canTimeout=False, cruiseState=NS(enabled=False))
|
||||
time.sleep(.05)
|
||||
# A subscriber started before its publisher may need another frame to attach
|
||||
# to the publisher generation. Production publishes continuously at 20 Hz.
|
||||
for _ in range(3):
|
||||
modes.publish(publisher, sm, 0)
|
||||
gate.sm.update(20)
|
||||
if gate.sm.seen['conditionalModelState']:
|
||||
break
|
||||
assert gate.sm.seen['conditionalModelState'] and gate.sm.valid['conditionalModelState']
|
||||
assert gate.step(drive, car)
|
||||
acknowledgments.update(100)
|
||||
assert acknowledgments.valid['conditionalModelAck']
|
||||
ack = acknowledgments['conditionalModelAck']
|
||||
assert ack.holding and ack.idle and ack.session == modes.owner.session
|
||||
assert ack.requestId == modes.owner.request and ack.stateMonoTime >= modes.owner.announced
|
||||
assert gate.alert().alert_text_1 == 'Switching conditional models'
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=gate.hold.held_since + SWITCH_TIMEOUT_NS + 1):
|
||||
assert gate.alert().alert_text_1 == 'Conditional model switch stalled'
|
||||
# Only a fresh ready boundary and output from this publisher can release it.
|
||||
modes.owner.phase = 'ready'
|
||||
frame = time.monotonic_ns()
|
||||
drive.sm.logMonoTime['modelV2'] = frame
|
||||
modes.publish(publisher, sm, frame)
|
||||
gate.sm.update(100)
|
||||
assert not gate.step(drive, car)
|
||||
assert gate.alert() is None
|
||||
|
||||
|
||||
def test_real_selfdrive_hold_ack_blocks_enable_and_both_axes_until_new_output():
|
||||
import ast
|
||||
from pathlib import Path
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.selfdrived.events import Events, EventName
|
||||
from openpilot.selfdrive.selfdrived.state import StateMachine
|
||||
from openpilot.starpilot.aol.runtime import AxisDecision
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
|
||||
message = messaging.new_message('conditionalModelState')
|
||||
message.conditionalModelState = {'session': 'a' * 32, 'requestId': 'b' * 32, 'phase': 'waiting', 'sessionStartMonoTime': BASE - 100}
|
||||
class Subscriber:
|
||||
seen = valid = alive = {'conditionalModelState': True}
|
||||
logMonoTime = {'conditionalModelState': BASE}
|
||||
def update(self, _):
|
||||
pass
|
||||
def __getitem__(self, _):
|
||||
return message.conditionalModelState
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.sm, gate.pm, gate.hold = Subscriber(), Mock(), EngagementHold()
|
||||
sm = NS(valid={'modelV2': True}, alive={'modelV2': True}, logMonoTime={'modelV2': BASE - 1})
|
||||
car = NS(canValid=True, canTimeout=False, cruiseState=NS(enabled=False))
|
||||
drive = NS(initialized=True, conditional_car_state_valid=True, enabled=False, active=False,
|
||||
state_machine=StateMachine(), aol_replay=False, aol_axis_decision=AxisDecision(),
|
||||
sm=sm, conditional_model_gate=gate, events=Events(), CP=NS(passive=False))
|
||||
# Execute the production step's hold admission, state-machine update, and
|
||||
# final axis override. An ENABLE in the exact acknowledgment tick must lose.
|
||||
source = Path(__file__).resolve().parents[3] / 'selfdrive/selfdrived/selfdrived.py'
|
||||
tree = ast.parse(source.read_text())
|
||||
step = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == 'step')
|
||||
start = next(i for i, n in enumerate(step.body) if isinstance(n, ast.Assign) and ast.unparse(n.targets[0]) == 'conditional_gate')
|
||||
admission = step.body[start:start + 3]
|
||||
update = next(n for n in step.body if isinstance(n, ast.If) and ast.unparse(n.test) == 'not self.CP.passive and self.initialized')
|
||||
override = [n for n in step.body if isinstance(n, ast.If) and ast.unparse(n.test) == 'conditional_hold'][-1]
|
||||
env = {'self': drive, 'CS': car, 'EventName': EventName, 'AxisDecision': AxisDecision}
|
||||
drive.events.add(EventName.buttonEnable)
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 10):
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[*admission, update], type_ignores=[])), str(source), 'exec'), env)
|
||||
assert not drive.enabled and not drive.active
|
||||
ack = gate.pm.send.call_args.args[1].conditionalModelAck
|
||||
assert ack.holding and ack.session == 'a' * 32 and ack.requestId == 'b' * 32
|
||||
drive.aol_axis_decision = AxisDecision(desired_lateral=True, lateral_active=True, desired_longitudinal=True, longitudinal_active=True)
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[override], type_ignores=[])), str(source), 'exec'), env)
|
||||
assert drive.aol_axis_decision == AxisDecision()
|
||||
message.conditionalModelState.phase = 'ready'
|
||||
message.conditionalModelState.frameMonoTime = BASE + 20
|
||||
gate.sm.logMonoTime['conditionalModelState'] = BASE + 30
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 40):
|
||||
assert gate.step(drive, car) # previous model output cannot clear the hold
|
||||
sm.logMonoTime['modelV2'] = BASE + 20
|
||||
assert gate.step(drive, car) # do not carry an Enable attempt through the hold
|
||||
drive.events.clear()
|
||||
assert not gate.step(drive, car)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('armed,active', [(True, False), (False, True)])
|
||||
def test_independent_lateral_intent_or_axis_refuses_hold(armed, active):
|
||||
from openpilot.cereal import log, messaging
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
message = messaging.new_message('conditionalModelState')
|
||||
message.conditionalModelState = {'session': 'a' * 32, 'requestId': 'b' * 32, 'phase': 'waiting', 'sessionStartMonoTime': BASE - 100}
|
||||
class Subscriber:
|
||||
seen = valid = alive = {'conditionalModelState': True}
|
||||
logMonoTime = {'conditionalModelState': BASE}
|
||||
def update(self, _):
|
||||
pass
|
||||
def __getitem__(self, _):
|
||||
return message.conditionalModelState
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.sm, gate.pm, gate.hold = Subscriber(), Mock(), EngagementHold()
|
||||
drive = NS(initialized=True, conditional_car_state_valid=True, enabled=False, active=False,
|
||||
state_machine=NS(state=log.SelfdriveState.OpenpilotState.disabled), aol_replay=True, aol_car_state_log_ns=BASE,
|
||||
aol_axis_decision=NS(lateral_active=active),
|
||||
sm=NS(valid={'modelV2': True}, alive={'modelV2': True}, logMonoTime={'modelV2': BASE}))
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 10), \
|
||||
patch('openpilot.starpilot.aol.runtime.current_intent', return_value=NS(allowedLatch=armed, lateralArmed=armed)):
|
||||
assert not gate.step(drive, NS(canValid=True, canTimeout=False, cruiseState=NS(enabled=False)))
|
||||
assert not gate.pm.send.call_args.args[1].conditionalModelAck.holding
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', [None, 'load', 'memory', 'missing', 'mapping'])
|
||||
def test_startup_preloads_alternate_once_or_retains_initial_runner(tmp_path, failure):
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
first_reset, other_reset = Mock(), Mock()
|
||||
first = NS(model_id='cheddar', handoff_reset=Mock(return_value=first_reset))
|
||||
other = NS(model_id='gwm8223', handoff_reset=Mock(return_value=other_reset))
|
||||
if failure == 'mapping':
|
||||
other.handoff_reset.side_effect = ValueError('unmapped history')
|
||||
artifact = tmp_path / 'alternate.pkl'
|
||||
artifact.write_bytes(b'fixture')
|
||||
config = {'enabled': True, 'city': 'cheddar', 'highway': 'gwm8223', 'thresholdMph': 50}
|
||||
entries = {'gwm8223': {'version': 'v15', 'artifact_sha256': 'a' * 64}}
|
||||
with patch('openpilot.cereal.messaging.SubMaster'), \
|
||||
patch('openpilot.starpilot.models.manager.catalog', return_value=entries), \
|
||||
patch('openpilot.starpilot.models.manager.verified_artifact', return_value=None if failure == 'missing' else artifact), \
|
||||
patch('openpilot.starpilot.models.runner.load_verified_model', return_value=(other, 'other-receipt')) as load, \
|
||||
patch('pathlib.Path.read_text', return_value='MemAvailable: 1 kB' if failure == 'memory' else 'MemAvailable: 9000000 kB'):
|
||||
if failure == 'load':
|
||||
load.side_effect = RuntimeError('native loading failed')
|
||||
runtime = ConditionalModelRuntime(first, 'first-receipt', config, root=tmp_path, cam_w=1928, cam_h=1208, enabled=True)
|
||||
assert runtime.owner.active == 'cheddar'
|
||||
first_reset.assert_not_called()
|
||||
other_reset.assert_not_called()
|
||||
if failure is None:
|
||||
assert runtime.owner.models['cheddar'] == (first, 'first-receipt', first_reset)
|
||||
assert runtime.owner.models['gwm8223'] == (other, 'other-receipt', other_reset)
|
||||
load.assert_called_once()
|
||||
else:
|
||||
assert not runtime.owner.models and runtime.owner.error
|
||||
|
||||
|
||||
@pytest.mark.parametrize('configured', [False, True])
|
||||
def test_expected_external_precedence_or_disabled_feature_is_not_a_driver_fault(tmp_path, configured):
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
from openpilot.starpilot.models.conditional_alerts import conditional_model_alert
|
||||
config = {'enabled': configured, 'city': 'cheddar', 'highway': 'gwm8223', 'thresholdMph': 50}
|
||||
with patch('openpilot.cereal.messaging.SubMaster'):
|
||||
runtime = ConditionalModelRuntime(NS(model_id='cheddar'), None, config,
|
||||
root=tmp_path, cam_w=1928, cam_h=1208, enabled=False)
|
||||
assert runtime.owner.phase == 'disabled' and not runtime.owner.error
|
||||
assert bool(runtime.unavailable_reason) == configured
|
||||
assert conditional_model_alert(NS(phase=runtime.owner.phase, error=runtime.owner.error), holding=False) is None
|
||||
|
||||
|
||||
def test_stale_or_armed_completion_does_not_release_hold():
|
||||
hold = EngagementHold()
|
||||
waiting = State('session', 'request', 'waiting', 0, BASE - 100)
|
||||
assert hold.step(waiting, BASE, BASE, idle=True, model_stamp=BASE, model_valid=True)
|
||||
ready = State('session', 'request', 'ready', BASE + 10, BASE - 100)
|
||||
assert hold.step(ready, BASE + 20, BASE + 20, idle=False, model_stamp=BASE + 10, model_valid=True)
|
||||
assert hold.step(ready, BASE + 30, BASE + 30, idle=True, model_stamp=BASE + 10, model_valid=True, release_allowed=False)
|
||||
assert not hold.step(ready, BASE + 40, BASE + 40, idle=True, model_stamp=BASE + 10, model_valid=True)
|
||||
|
||||
|
||||
def test_fresh_status_cannot_restart_the_hold_duration_clock():
|
||||
hold = EngagementHold()
|
||||
state = State('session', 'request', 'recovering', 0, BASE - 1)
|
||||
for i in range(50):
|
||||
now = BASE + i * 50_000_000
|
||||
assert hold.step(state, now, now, idle=True, model_stamp=now, model_valid=False)
|
||||
assert hold.held_since == BASE
|
||||
assert hold.last_stamp > hold.held_since + SWITCH_TIMEOUT_NS
|
||||
|
||||
|
||||
def conditional_runtime_fixture():
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
owner, _ = switcher()
|
||||
owner.active = owner.previous = 'city'
|
||||
owner.frame = BASE
|
||||
modes = ConditionalModelRuntime.__new__(ConditionalModelRuntime)
|
||||
modes.owner, modes.policy = owner, SpeedPolicy()
|
||||
modes.paused, modes.last_status = False, None
|
||||
modes.config = {'highway': 'highway', 'city': 'city', 'thresholdMph': 50}
|
||||
class AckFeed(dict):
|
||||
def update(self, _):
|
||||
pass
|
||||
modes.ack = AckFeed(conditionalModelAck=NS(session=owner.session, requestId='', holding=False, stateMonoTime=BASE, idle=True))
|
||||
modes.ack.seen = modes.ack.valid = modes.ack.alive = {'conditionalModelAck': True}
|
||||
modes.ack.logMonoTime = {'conditionalModelAck': BASE}
|
||||
feed = Feed()
|
||||
feed['carState'].vEgo = 60 * .44704
|
||||
return modes, feed
|
||||
|
||||
|
||||
def test_automatic_highway_request_uses_same_held_handoff_and_separate_buffers():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'waiting' and modes.owner.active == 'city'
|
||||
modes.owner.models['highway'][2].assert_not_called()
|
||||
modes.owner.announced = BASE
|
||||
ack = modes.ack['conditionalModelAck']
|
||||
ack.requestId, ack.holding = modes.owner.request, True
|
||||
modes.ack.logMonoTime['conditionalModelAck'] = BASE + 10_000_000
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 20_000_000):
|
||||
assert modes.before_frame(feed) == modes.owner.models['highway']
|
||||
modes.owner.models['highway'][2].assert_called_once()
|
||||
modes.owner.models['city'][2].assert_not_called()
|
||||
assert modes.owner.phase == 'switching'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('denial', ['engaged', 'lateral', 'armed', 'stale-ack', 'stale-output', 'invalid-can', 'invalid-speed'])
|
||||
def test_automatic_speed_never_bypasses_engagement_or_freshness(denial):
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
if denial == 'engaged':
|
||||
feed['selfdriveState'].enabled = True
|
||||
elif denial == 'lateral':
|
||||
feed['carControl'].latActive = True
|
||||
elif denial == 'armed':
|
||||
modes.ack['conditionalModelAck'].idle = False
|
||||
elif denial == 'stale-ack':
|
||||
modes.ack.logMonoTime['conditionalModelAck'] = BASE - 1_000_000_000
|
||||
elif denial == 'stale-output':
|
||||
modes.owner.frame = BASE - 1_000_000_000
|
||||
elif denial == 'invalid-can':
|
||||
feed['carState'].canValid = False
|
||||
else:
|
||||
feed['carState'].vEgo = float('nan')
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'ready' and modes.owner.active == 'city'
|
||||
assert not modes.owner.error and not modes.paused
|
||||
modes.owner.models['highway'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_engaging_before_hold_cancels_without_false_failure_or_disabling_automation():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'waiting'
|
||||
feed['selfdriveState'].enabled = True
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 20_000_000):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'ready' and modes.owner.active == 'city'
|
||||
assert not modes.owner.error and not modes.paused
|
||||
modes.owner.models['highway'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_auto_failure_pauses_for_drive_instead_of_retrying_every_frame():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
modes.owner.error = 'Candidate failed; previous model restored'
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.paused and modes.owner.phase == 'ready'
|
||||
modes.owner.error = ''
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.paused and modes.owner.active == 'city'
|
||||
|
||||
|
||||
def test_identical_model_roles_never_reset_or_request_a_noop_handoff():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
modes.config['highway'] = 'city'
|
||||
feed['carState'].vEgo = 0.
|
||||
for i in range(601):
|
||||
now = BASE + i * 50_000_000
|
||||
feed.logMonoTime = dict.fromkeys(feed, now)
|
||||
modes.ack.logMonoTime['conditionalModelAck'] = modes.owner.frame = now
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=now):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'ready' and modes.owner.request == ''
|
||||
for _, _, reset in modes.owner.models.values():
|
||||
reset.assert_not_called()
|
||||
|
||||
|
||||
def test_previous_reset_failure_demands_isolated_recovery_instead_of_using_bad_history():
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
owner.models['highway'][2].side_effect = RuntimeError('device mapping failed')
|
||||
with pytest.raises(RuntimeError, match='isolated recovery required'):
|
||||
owner.abort('Candidate failed', BASE + 40_000_000)
|
||||
assert owner.phase == 'recovering' and owner.error
|
||||
|
||||
|
||||
def test_randomized_transition_trace_never_changes_runner_without_disengagement():
|
||||
import random
|
||||
rng = random.Random(42)
|
||||
owner, _ = switcher()
|
||||
for i in range(1, 2000):
|
||||
now = BASE + i * 50_000_000
|
||||
idle = rng.choice((True, False))
|
||||
desired = {'session': owner.session, 'id': f'{i:032x}', 'model': rng.choice(('highway', 'city'))}
|
||||
ack = Ack(owner.session, owner.request, True, owner.announced, now)
|
||||
previous = owner.active
|
||||
changed = owner.before_frame(desired, now=now, idle=idle, ack=ack)
|
||||
if changed:
|
||||
assert idle and previous != owner.active
|
||||
if not idle:
|
||||
assert owner.active == previous
|
||||
if owner.phase == 'waiting' and not owner.announced:
|
||||
owner.announced = now
|
||||
owner.published(now, now)
|
||||
@@ -401,6 +401,124 @@ class ModelManagerTest(unittest.TestCase):
|
||||
with patch.object(self.manager, 'jetlink_owner', return_value=owner), self.assertRaises(ModelError):
|
||||
self.manager.action('active', {'profile': 'big', 'model': ''})
|
||||
|
||||
def enable_conditional_model(self):
|
||||
self.download()
|
||||
return self.manager.action('conditional_model', {'enabled': True, 'highway': DEFAULT_SMALL, 'city': 'gwm8223'})
|
||||
|
||||
def test_conditional_model_always_starts_city_and_preserves_single_model_preference(self):
|
||||
self.manager.gpu_present = lambda: False
|
||||
result = self.enable_conditional_model()
|
||||
self.assertEqual(result['activeSmallModel'], 'gwm8223')
|
||||
self.assertEqual(preferences(self.root)['small'], DEFAULT_SMALL)
|
||||
for _ in range(3):
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, 'gwm8223')
|
||||
self.manager.action('conditional_model', {'enabled': False})
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, DEFAULT_SMALL)
|
||||
|
||||
def test_conditional_recovery_override_is_not_saved_as_next_drive_start(self):
|
||||
self.enable_conditional_model()
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
self.assertEqual(resolve_runtime(False, root=self.root, small_override=DEFAULT_SMALL).small_id, DEFAULT_SMALL)
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, 'gwm8223')
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
with self.assertRaises(ModelError):
|
||||
resolve_runtime(False, root=self.root, small_override='unknown-model')
|
||||
|
||||
def test_conditional_model_has_only_enabled_models_and_speed(self):
|
||||
result = self.enable_conditional_model()['conditionalModel']
|
||||
self.assertEqual(result, {'enabled': True, 'city': 'gwm8223', 'highway': DEFAULT_SMALL, 'thresholdMph': 50})
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual(preferences(self.root)['conditionalModel']['thresholdMph'], 60)
|
||||
|
||||
def test_conditional_model_rejects_invalid_and_removed_settings_without_writes(self):
|
||||
before = preferences(self.root)
|
||||
for payload in ({}, {'unknown': True}, {'enabled': 1}, {'selected': 'highway'}, {'automatic': False},
|
||||
{'cityDelaySeconds': 10}, {'session': 'a' * 32}, {'city': '../escape'}, {'city': 'cinquev3'},
|
||||
{'city': None}, {'thresholdMph': True}, {'thresholdMph': 0}, {'thresholdMph': 101}, {'thresholdMph': 50.5}):
|
||||
with self.subTest(payload=payload), self.assertRaises(ModelError):
|
||||
self.manager.action('conditional_model', payload)
|
||||
self.assertEqual(preferences(self.root), before)
|
||||
|
||||
def test_conditional_model_defaults_to_fifty_mph_with_identical_models_allowed(self):
|
||||
payload = {'enabled': True, 'city': DEFAULT_SMALL, 'highway': DEFAULT_SMALL}
|
||||
result = self.manager.action('conditional_model', payload)
|
||||
self.assertEqual(result['conditionalModel']['thresholdMph'], 50)
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
self.manager.action('conditional_model', payload)
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
|
||||
def test_legacy_manual_configuration_migrates_to_city_start_and_automatic_only(self):
|
||||
self.download()
|
||||
legacy = {'enabled': True, 'highway': DEFAULT_SMALL, 'city': 'gwm8223', 'selected': 'highway',
|
||||
'automatic': False, 'thresholdMph': 60, 'cityDelaySeconds': 300}
|
||||
atomic_json(self.root / 'preferences.json', {'small': DEFAULT_SMALL, 'smallProfiles': legacy, 'liveRequest': {'model': DEFAULT_SMALL}})
|
||||
result = preferences(self.root)
|
||||
self.assertEqual(result['conditionalModel'], {'enabled': True, 'highway': DEFAULT_SMALL, 'city': 'gwm8223', 'thresholdMph': 60})
|
||||
self.assertNotIn('liveRequest', result)
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, 'gwm8223')
|
||||
self.manager.action('conditional_model', {'thresholdMph': 50})
|
||||
saved = json.loads((self.root / 'preferences.json').read_text())
|
||||
self.assertNotIn('smallProfiles', saved)
|
||||
self.assertNotIn('liveRequest', saved)
|
||||
|
||||
def test_conditional_model_rejects_onroad_and_boundary_race(self):
|
||||
self.enable_conditional_model()
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
for parked in (lambda: False, unittest.mock.Mock(side_effect=[True, False])):
|
||||
self.manager.parked = parked
|
||||
with self.assertRaisesRegex(ModelError, 'vehicle off'):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
|
||||
def test_conditional_model_verifies_both_and_preserves_corrupt_city_fallback(self):
|
||||
self.enable_conditional_model()
|
||||
(self.root / 'gwm8223/gwm8223_driving_tinygrad.pkl').write_bytes(b'corrupt')
|
||||
before = preferences(self.root)
|
||||
with self.assertRaisesRegex(ModelError, 'verify both'):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual(preferences(self.root), before)
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, DEFAULT_SMALL)
|
||||
|
||||
def test_conditional_model_arbitrates_randomizer_single_selection_and_delete(self):
|
||||
self.enable_conditional_model()
|
||||
for action, payload in (('preferences', {'randomizer': True}), ('active', {'profile': 'small', 'model': DEFAULT_SMALL}),
|
||||
('delete', {'model': 'gwm8223'})):
|
||||
with self.subTest(action=action), self.assertRaises(ModelError):
|
||||
self.manager.action(action, payload)
|
||||
self.manager.action('conditional_model', {'enabled': False})
|
||||
self.manager.action('preferences', {'randomizer': True})
|
||||
with self.assertRaisesRegex(ModelError, 'Randomizer off'):
|
||||
self.manager.action('conditional_model', {'enabled': True})
|
||||
|
||||
def test_conditional_model_failed_commit_and_busy_job_preserve_configuration(self):
|
||||
self.enable_conditional_model()
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
with patch('openpilot.starpilot.models.manager.atomic_json', side_effect=OSError('disk full')), self.assertRaises(OSError):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
with patch.object(self.manager, '_job_busy', return_value=True), self.assertRaisesRegex(ModelError, 'download'):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
|
||||
def test_malformed_conditional_configuration_cannot_enable_from_legacy_fallback(self):
|
||||
self.enable_conditional_model()
|
||||
saved = preferences(self.root)
|
||||
for value in (None, [], {'enabled': True}, saved['conditionalModel'] | {'selected': 'highway'}):
|
||||
atomic_json(self.root / 'preferences.json', saved | {'conditionalModel': value, 'smallProfiles': saved['conditionalModel']})
|
||||
self.assertFalse(preferences(self.root)['conditionalModel']['enabled'])
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, DEFAULT_SMALL)
|
||||
|
||||
def test_conditional_model_partial_updates_preserve_other_preferences(self):
|
||||
self.enable_conditional_model()
|
||||
other = ModelManager(root=self.root, parked=lambda: True, gpu_present=lambda: False)
|
||||
self.addCleanup(other.close)
|
||||
other.action('preferences', {'userFavorites': ['gwm8223']})
|
||||
other.action('conditional_model', {'thresholdMph': 60})
|
||||
self.manager.action('conditional_model', {'highway': 'gwm8223'})
|
||||
saved = preferences(self.root)
|
||||
self.assertEqual(saved['userFavorites'], ['gwm8223'])
|
||||
self.assertEqual(saved['conditionalModel'], {'enabled': True, 'city': 'gwm8223', 'highway': 'gwm8223', 'thresholdMph': 60})
|
||||
self.assertEqual(saved['small'], DEFAULT_SMALL)
|
||||
|
||||
def test_hardware_profiles_and_selected_delete(self):
|
||||
self.download()
|
||||
with self.assertRaises(ModelError):
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import ast
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -18,6 +18,31 @@ def main_body():
|
||||
return next(node for node in ast.parse(MODEL_SOURCE.read_text()).body if isinstance(node, ast.FunctionDef) and node.name == "main").body
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure_at', ['run', 'action'])
|
||||
def test_live_candidate_failure_restores_resident_previous_in_production_frame_path(failure_at):
|
||||
from openpilot.starpilot.models.conditional_protocol import ResidentSwitch
|
||||
statement = next(node for item in main_body() for node in ast.walk(item)
|
||||
if isinstance(node, ast.Try) and any(isinstance(child, ast.Call) and ast.unparse(child.func) == 'model.run'
|
||||
for child in ast.walk(node)))
|
||||
previous = SimpleNamespace(chestnut=False, model_id='highway', run=Mock(return_value={'good': True}))
|
||||
candidate = SimpleNamespace(chestnut=False, run=Mock(return_value={}), get_action_from_model=Mock())
|
||||
getattr(candidate, 'run' if failure_at == 'run' else 'get_action_from_model').side_effect = RuntimeError('candidate failed')
|
||||
reset = Mock()
|
||||
owner = ResidentSwitch({'highway': (previous, 'prepared', reset)}, 'highway', now=1)
|
||||
owner.active, owner.phase = 'city', 'switching'
|
||||
env = {'model': candidate, 'conditional_runtime': SimpleNamespace(owner=owner), 'cloudlog': Mock(),
|
||||
'chestnut_state': None, 'run_count': 0, 'bufs': {}, 'transforms': {}, 'inputs': {},
|
||||
'prev_action': None, 'lat_action_t': 0., 'long_action_t': 0., 'v_ego': 0.,
|
||||
'lat_delay': .1, 'frame_drop_ratio': 0., 'time': SimpleNamespace(monotonic_ns=lambda: 50),
|
||||
'log': SimpleNamespace(ModelDataV2=SimpleNamespace(Action=Mock())),
|
||||
'sm': {'controlsState': SimpleNamespace(curvature=.01)}, 'DesireHelper': Mock(), 'runtime_lane_policy': object()}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[statement], type_ignores=[])), str(MODEL_SOURCE), 'exec'), env)
|
||||
assert env['model'] is previous and env['model_output'] == {'good': True}
|
||||
assert owner.phase == 'recovering' and owner.active == 'highway'
|
||||
reset.assert_called_once()
|
||||
previous.run.assert_called_once_with({}, {}, {})
|
||||
|
||||
|
||||
def test_realtime_starts_after_model_load_and_receipt():
|
||||
# Inspect startup without importing modeld's GPU runtime or loading artifacts.
|
||||
calls = [(node.lineno, ast.unparse(node.func)) for statement in main_body() for node in ast.walk(statement) if isinstance(node, ast.Call)]
|
||||
@@ -30,6 +55,28 @@ def test_realtime_starts_after_model_load_and_receipt():
|
||||
assert max(line("load_small") + line("loader.join")) < startup_receipt.lineno < line("config_realtime_process")[0] < line("PubMaster")[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('selected_missing', [False, True])
|
||||
def test_small_profile_startup_failure_uses_existing_verified_fallback(selected_missing):
|
||||
function = next(node for statement in main_body() for node in ast.walk(statement)
|
||||
if isinstance(node, ast.FunctionDef) and node.name == 'load_small')
|
||||
shipped = Path('/verified/shipped.pkl')
|
||||
selected = Path('/verified/city.pkl')
|
||||
runner, prepared = object(), object()
|
||||
load = Mock(side_effect=[(runner, prepared)] if selected_missing else [RuntimeError('warmup failed'), (runner, prepared)])
|
||||
env = {'selection': SimpleNamespace(small_id='city', small_path=None if selected_missing else selected,
|
||||
small_version='v15', small_sha256='b' * 64),
|
||||
'cam_w': 1928, 'cam_h': 1208, 'coherent_warp': None, 'load_verified_model': load,
|
||||
'DEFAULT_SMALL': 'cheddar', 'DEFAULT_SMALL_SHA256': 'a' * 64,
|
||||
'BY_ID': {'cheddar': SimpleNamespace(version='v15')}, 'cloudlog': Mock()}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[function], type_ignores=[])), str(MODEL_SOURCE), 'exec'), env)
|
||||
with patch('openpilot.starpilot.models.manager.shipped_default', return_value=shipped):
|
||||
assert env['load_small']() == (runner, prepared, True)
|
||||
assert load.call_args.args[2:7] == (shipped, 'v15', False, 'cheddar', 'a' * 64)
|
||||
assert load.call_count == (1 if selected_missing else 2)
|
||||
with patch('openpilot.starpilot.models.manager.shipped_default', return_value=None), pytest.raises(RuntimeError, match='missing or corrupt'):
|
||||
env['load_small']()
|
||||
|
||||
|
||||
def test_jetlink_gets_the_frames_delay_before_every_run():
|
||||
# a model that joins starts on the current delay; check_seam holds the frame_drop_ratio write
|
||||
loop = [node for node in main_body() if isinstance(node, ast.While)][-1] # the frame loop
|
||||
@@ -71,6 +118,7 @@ def test_inference_failure_uses_runner_identity(runner_chestnut, stored_active):
|
||||
"chestnut_state": chestnut_state, "run_count": 1, "ModelConstants": SimpleNamespace(MODEL_RUN_FREQ=20),
|
||||
"SERVICE_LIST": {"chestnutGpuState": SimpleNamespace(frequency=1)}, "bufs": {}, "transforms": {}, "inputs": {},
|
||||
"small_prepared": object(), "ModelVariant": ModelVariant, "jetlink_model": None, "drop_chestnut": Mock(), "cloudlog": Mock()}
|
||||
env['conditional_runtime'] = SimpleNamespace(owner=SimpleNamespace(phase='disabled'))
|
||||
code = compile(ast.fix_missing_locations(ast.Module(body=[fallback], type_ignores=[])), str(MODEL_SOURCE), "exec")
|
||||
if runner_chestnut:
|
||||
exec(code, env)
|
||||
@@ -103,6 +151,7 @@ def test_remote_inference_failure_does_not_change_chestnut_status():
|
||||
env = {"model": failed_model, "small_model": small_model, "params": params, "receipt_owner": receipt,
|
||||
"chestnut_state": None, "run_count": 1, "bufs": {}, "transforms": {}, "inputs": {},
|
||||
"small_prepared": object(), "ModelVariant": ModelVariant, "jetlink_model": failed_model, "drop_chestnut": Mock(), "cloudlog": Mock()}
|
||||
env['conditional_runtime'] = SimpleNamespace(owner=SimpleNamespace(phase='disabled'))
|
||||
execute([fallback], env)
|
||||
failed_model.close.assert_called_once_with()
|
||||
env["drop_chestnut"].assert_not_called()
|
||||
@@ -177,6 +226,8 @@ def test_observed_availability_and_big_eligibility(monkeypatch, present, cable,
|
||||
def test_big_worker_waits_before_load_and_failure_requests_fresh_small_process(custom, timeout, worker_alive, laboratory, monkeypatch):
|
||||
from openpilot.starpilot.models import manager
|
||||
monkeypatch.setattr(manager, "shipped_default", lambda: Path("bundled-small"))
|
||||
from openpilot.starpilot.models import conditional_runtime
|
||||
monkeypatch.setattr(conditional_runtime, 'ConditionalModelRuntime', Mock())
|
||||
body = main_body()
|
||||
start = next(i for i, node in enumerate(body) if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "st")
|
||||
end = next(i for i, node in enumerate(body) if ast.unparse(node).startswith("config_realtime_process("))
|
||||
@@ -233,7 +284,7 @@ def test_big_worker_waits_before_load_and_failure_requests_fresh_small_process(c
|
||||
"CP": SimpleNamespace(brand="mock"), "demo": False,
|
||||
"wait_for_chestnut_power": lambda CP, timeout: events.append("power"),
|
||||
"jetlink_adapter": SimpleNamespace(hooks=lambda: hooks, coherent_warp=lambda: None), "drop_chestnut": Mock(),
|
||||
"release_compile_pool": Mock(), "gc": Mock()}
|
||||
"release_compile_pool": Mock(), "gc": Mock(), 'MODEL_ROOT': Path('/test-models'), 'recovery_model': None}
|
||||
if laboratory:
|
||||
from openpilot.starpilot.models.laboratory_runner import LaboratoryPair
|
||||
pair = object.__new__(LaboratoryPair)
|
||||
@@ -363,7 +414,7 @@ def test_recovery_child_resolves_small_without_randomizer_or_amd(monkeypatch):
|
||||
params = Mock()
|
||||
env: dict = {"chestnut_present": lambda: True, "cable_connected": lambda: True,
|
||||
"chestnut_compiled": Mock(side_effect=AssertionError("Big compiled probe forbidden")),
|
||||
"Params": lambda: params, "os": SimpleNamespace(getenv=lambda key: "1")}
|
||||
"Params": lambda: params, "os": SimpleNamespace(getenv=lambda key: "1" if key == 'STARPILOT_MODELD_RECOVERY_SMALL_ONLY' else None)}
|
||||
execute(body[start:end], env)
|
||||
manager.resolve_runtime.assert_called_once_with(chestnut_available=False, randomize=False)
|
||||
manager.requested_runtime_id.assert_called_once_with(True)
|
||||
@@ -378,7 +429,7 @@ def test_recovery_small_receipt_reports_runtime_stall_not_load_failure():
|
||||
receipt = Mock()
|
||||
env: dict = {'model': SimpleNamespace(chestnut=False, model_id='bundled-current'), 'small_prepared': object(),
|
||||
'receipt_owner': receipt, 'ModelVariant': ModelVariant, 'initial_chestnut_fallback': False,
|
||||
'recovery_small_only': True, 'selected_small_failed': False, 'requested_model_id': 'requested-big'}
|
||||
'recovery_small_only': True, 'selected_small_failed': False, 'requested_model_id': 'requested-big', 'recovery_model': None}
|
||||
execute([statement], env)
|
||||
assert receipt.loaded.call_args.args[1:3] == (ModelVariant.SMALL, 'chestnut-run-stalled')
|
||||
assert receipt.loaded.call_args.kwargs['model_id'] == 'bundled-current'
|
||||
|
||||
@@ -48,6 +48,11 @@ class TestModelReceipt(unittest.TestCase):
|
||||
with self.assertRaises(ReceiptUnavailable):
|
||||
write_receipt(replace(self.load, model_id="unknown"), self.path)
|
||||
|
||||
def test_conditional_switch_recovery_has_its_own_reason(self):
|
||||
load = replace(self.load, fallback_reason='conditional-switch-failed')
|
||||
write_receipt(load, self.path)
|
||||
self.assertEqual(read_receipt(self.path), load)
|
||||
|
||||
def test_symlink_fifo_and_unowned_directory_are_unavailable(self):
|
||||
target = self.root / "outside"
|
||||
target.write_bytes(b"untouched")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from types import SimpleNamespace as NS
|
||||
from itertools import product
|
||||
from unittest.mock import Mock, patch
|
||||
import unittest
|
||||
|
||||
@@ -22,6 +23,112 @@ class Feed(dict):
|
||||
|
||||
|
||||
class TestRecoveryProcess(unittest.TestCase):
|
||||
def test_resident_preload_watchdog_kills_before_isolated_restart(self):
|
||||
from openpilot.starpilot.models.conditional_protocol import PRELOAD_TIMEOUT_NS
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
child.is_alive.return_value = True
|
||||
owner.proc, owner.launch_conditional, owner.launch_ns = child, True, BASE
|
||||
elapsed = PRELOAD_TIMEOUT_NS / 1e9 + .1
|
||||
with patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=456), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + int(elapsed * 1e9)), \
|
||||
patch.object(owner, 'signal') as send, patch('openpilot.starpilot.models.recovery_process.Process') as spawn:
|
||||
owner.observe(Feed(elapsed), True)
|
||||
assert owner.recovery.small_only and owner.recovery.phase == 'sigint'
|
||||
owner.start()
|
||||
spawn.assert_not_called()
|
||||
send.assert_called_once()
|
||||
|
||||
def test_native_handoff_stall_requires_held_ack_and_fresh_cameras(self):
|
||||
for held, camera_count, progressing, source_valid in product((False, True), (1, 2), (False, True), (False, True)):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
child.is_alive.return_value = True
|
||||
owner.proc = child
|
||||
previous = (BASE + 4_000_000_000, 80) if progressing else (BASE + 5_000_000_000, 100)
|
||||
owner.last_conditional_cameras = (previous,) * camera_count
|
||||
feed = Feed(5., output=False)
|
||||
if camera_count == 1:
|
||||
feed.seen['wideRoadCameraState'] = False
|
||||
feed['conditionalModelState'] = NS(processPid=123, processStartTicks=456, session='session', requestId='request',
|
||||
phase='switching', sessionStartMonoTime=BASE, frameMonoTime=0, fallbackModel='cheddar')
|
||||
feed['conditionalModelAck'] = NS(session='session', requestId='request', holding=held,
|
||||
stateMonoTime=BASE + 4_900_000_000 if source_valid else BASE - 1)
|
||||
feed.seen.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
feed.valid.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
# Status may still be publishing even when no valid model frames emerge.
|
||||
feed.logMonoTime.update(conditionalModelState=BASE + 5_000_000_000, conditionalModelAck=BASE + 5_000_000_000)
|
||||
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=BASE, variant=ModelVariant.SMALL)
|
||||
with patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=456), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=load), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + 5_000_000_000), \
|
||||
patch.object(owner, 'signal') as send:
|
||||
owner.observe(feed, True)
|
||||
assert send.called == (held and progressing and source_valid)
|
||||
if held and source_valid:
|
||||
assert owner.conditional_recovery_model == 'cheddar'
|
||||
|
||||
def test_crash_after_ready_before_hold_release_recovers_previous_model_after_confirmed_exit(self):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123, exitcode=-9)
|
||||
child.is_alive.return_value = False
|
||||
owner.proc, owner.launch_conditional, owner.launch_ticks, owner.launch_drive_id = child, True, 456, BASE
|
||||
feed = Feed(5.)
|
||||
feed['conditionalModelState'] = NS(processPid=123, processStartTicks=456, session='session', requestId='request',
|
||||
phase='ready', sessionStartMonoTime=BASE, frameMonoTime=0, fallbackModel='cheddar')
|
||||
feed['conditionalModelAck'] = NS(session='session', requestId='request', holding=True, stateMonoTime=BASE + 4_900_000_000)
|
||||
feed.seen.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
feed.valid.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
feed.logMonoTime.update(conditionalModelState=BASE + 4_900_000_000, conditionalModelAck=BASE + 5_000_000_000)
|
||||
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=BASE, variant=ModelVariant.SMALL)
|
||||
with patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=load), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + 5_000_000_000), \
|
||||
patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=789), \
|
||||
patch('openpilot.starpilot.models.recovery_process.Process') as spawn:
|
||||
owner.observe(feed, True)
|
||||
child.join.assert_called_once_with(timeout=0)
|
||||
assert owner.proc is None and owner.recovery.small_only
|
||||
owner.start()
|
||||
assert spawn.call_args.kwargs['kwargs'] == {'recovery_model': 'cheddar'}
|
||||
|
||||
def test_established_runner_never_becomes_a_preload_timeout_when_receipt_is_lost(self):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
child.is_alive.return_value = True
|
||||
owner.proc, owner.launch_conditional, owner.launch_ns = child, True, BASE
|
||||
feed = Feed(121.)
|
||||
now = BASE + 121_000_000_000
|
||||
feed['conditionalModelState'] = NS(processPid=123, processStartTicks=456, sessionStartMonoTime=BASE, frameMonoTime=now)
|
||||
feed.seen['conditionalModelState'] = feed.valid['conditionalModelState'] = True
|
||||
feed.logMonoTime['conditionalModelState'] = now
|
||||
with patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=456), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=now), \
|
||||
patch.object(owner, 'signal') as send:
|
||||
owner.observe(feed, True)
|
||||
assert owner.launch_established
|
||||
del feed['conditionalModelState']
|
||||
owner.observe(feed, True)
|
||||
send.assert_not_called()
|
||||
assert not owner.recovery.small_only
|
||||
|
||||
def test_established_native_crash_does_not_restart_a_different_model_while_engaged(self):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123, exitcode=-9)
|
||||
child.is_alive.return_value = False
|
||||
owner.proc, owner.launch_conditional, owner.launch_ticks, owner.launch_drive_id = child, True, 456, BASE
|
||||
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=BASE, variant=ModelVariant.SMALL)
|
||||
with patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=load), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + 2_000_000_000):
|
||||
owner.observe(Feed(2.), True)
|
||||
assert owner.proc is child and not owner.recovery.small_only
|
||||
|
||||
def test_adapter_never_spawns_before_confirmed_exit(self):
|
||||
owner = ModeldProcess('modeld', 'openpilot.selfdrive.modeld.modeld', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
|
||||
@@ -3,9 +3,10 @@ import time
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
from unittest.mock import patch
|
||||
|
||||
from openpilot.starpilot.models.catalog import BUNDLED_CURRENT
|
||||
from openpilot.starpilot.models.runtime import snapshot
|
||||
from openpilot.starpilot.models.runtime import ModelStatusSource, snapshot
|
||||
from openpilot.starpilot.models.status import ModelHealth, ModelLoad, ModelVariant
|
||||
|
||||
|
||||
@@ -51,6 +52,29 @@ class TestRuntimeSnapshot(unittest.TestCase):
|
||||
self.sm.logMonoTime["managerState"] = 100
|
||||
self.assertEqual(self.status().health, ModelHealth.UNAVAILABLE)
|
||||
|
||||
def test_conditional_switch_permission_requires_owned_publisher_and_both_fresh_outputs(self):
|
||||
conditional = SimpleNamespace(processPid=421, processStartTicks=54321, session='session', requestId='request',
|
||||
phase='ready', activeModel='cheddar', highwayModel='cheddar', cityModel='city',
|
||||
error='', canSwitch=True, sessionStartMonoTime=1_800_000_000,
|
||||
frameMonoTime=1_990_000_000, transitionSeconds=.25, paused=False, targetMode='city', thresholdMph=50, unavailableReason='')
|
||||
self.sm.messages['conditionalModelState'] = conditional
|
||||
self.sm.logMonoTime['conditionalModelState'] = 1_995_000_000
|
||||
self.sm.valid['conditionalModelState'] = self.sm.alive['conditionalModelState'] = True
|
||||
source = ModelStatusSource(FakeParams(), sm=self.sm, clock=lambda: 2_000_000_000)
|
||||
with patch('openpilot.starpilot.models.runtime.process_start_ticks', return_value=54321):
|
||||
self.assertTrue(source.conditional_json()['canSwitch'])
|
||||
self.sm.valid['drivingModelData'] = False
|
||||
self.assertFalse(source.conditional_json()['canSwitch'])
|
||||
self.sm.valid['drivingModelData'] = True
|
||||
conditional.frameMonoTime = 1_799_000_000
|
||||
self.assertFalse(source.conditional_json()['canSwitch'])
|
||||
conditional.frameMonoTime = 1_990_000_000
|
||||
conditional.processStartTicks = 54322
|
||||
self.assertIsNone(source.conditional_json())
|
||||
conditional.processStartTicks = 54321
|
||||
self.sm.logMonoTime['conditionalModelState'] = 1_000_000_000
|
||||
self.assertIsNone(source.conditional_json())
|
||||
|
||||
def test_pid_reuse_or_actual_variant_mismatch_does_not_claim_identity(self):
|
||||
self.assertEqual(self.status(process_ticks=54322).health, ModelHealth.IDENTITY_UNAVAILABLE)
|
||||
self.assertEqual(self.status(process_ticks=0).health, ModelHealth.IDENTITY_UNAVAILABLE)
|
||||
|
||||
@@ -155,7 +155,7 @@ def manager_thread() -> None:
|
||||
ignore += [x for x in os.getenv("BLOCK", "").split(",") if len(x) > 0]
|
||||
|
||||
sm = messaging.SubMaster(['deviceState', 'carParams', 'pandaStates', 'modelV2', 'drivingModelData',
|
||||
'narrowRoadCameraState', 'wideRoadCameraState'], poll='deviceState')
|
||||
'narrowRoadCameraState', 'wideRoadCameraState', 'conditionalModelState', 'conditionalModelAck'], poll='deviceState')
|
||||
pm = messaging.PubMaster(['managerState'])
|
||||
|
||||
params.put_bool("IsOffroad", True, block=True)
|
||||
|
||||
Reference in New Issue
Block a user