fix(vesc): recover cancelled controller preparation without rearming
This commit is contained in:
@@ -0,0 +1,103 @@
|
|||||||
|
"""Node151: VESC recovery and native Linux NetBird monitor policy over qualified148, no other runtime changes.
|
||||||
|
|
||||||
|
Prepared-Ubuntu qualification is mandatory before the owner installer is built.
|
||||||
|
The unchanged Node executable, transport, UI and network helpers keep their base
|
||||||
|
provenance; the Debian version and this manifest identify the plugin revision.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from repack_codec_recovery import members
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
BASE = 'ac03602662fe00cf25654a8c1f3b135dda5461543d7d169fd050c96fd5e3756a'
|
||||||
|
VERSION = '0.8.53-151'
|
||||||
|
PINS = {
|
||||||
|
'remote_control.py': ('f52a465ae8de0d5836396362f94b6c2102dd741fba3097d9a292ef620221bdf6',
|
||||||
|
'19d77a6fece9c844841a1c8f5423b4e0cf15383a85e588ba0e885ec55b1863bb'),
|
||||||
|
'preflight_recovery.py': ('ee5bc3e2cdfca92b1e69d44138919a86bcf158658379da3c56ccb1a79b37c9bb',
|
||||||
|
'a67e171f4c946a7c5d72b590d2d6efa62c44b367f4f28515293608a1eefcf0a4'),
|
||||||
|
}
|
||||||
|
PROOF = 'usr/share/doc/mission-core-node/preparation-recovery-revision.json'
|
||||||
|
|
||||||
|
|
||||||
|
def digest(data):
|
||||||
|
return hashlib.sha256(data).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def build(base, output):
|
||||||
|
evidence = json.loads((base / 'qualification.json').read_text())
|
||||||
|
if evidence['state'] != 'complete':
|
||||||
|
raise ValueError('Qualified base required')
|
||||||
|
raw = (base / 'mission-core-node_0.8.53-148_amd64.deb').read_bytes()
|
||||||
|
if digest(raw) != BASE:
|
||||||
|
raise ValueError('Base package changed')
|
||||||
|
controls, data = members(raw)
|
||||||
|
old = {name:value for name,value,_ in data}
|
||||||
|
changes = {}
|
||||||
|
for name, (previous, desired) in PINS.items():
|
||||||
|
target = 'usr/lib/mission-core-vesc/runtime/' + name
|
||||||
|
new = (REPO / 'plugins/vesc/runtime' / name).read_bytes()
|
||||||
|
if digest(old[target]) != previous or digest(new) != desired:
|
||||||
|
raise ValueError('Reviewed source changed: ' + name)
|
||||||
|
compile(new, name, 'exec')
|
||||||
|
changes[target] = new
|
||||||
|
client_target = 'usr/lib/mission-core-node/netbird/client.py'
|
||||||
|
client = (REPO/'src/k1link/fleet/netbird/client.py').read_bytes()
|
||||||
|
if (digest(old[client_target]) != 'b1ca7d8de81f0a87b61561a5930f91c96f20cabc9efa2f3be7347f66bb47aef8'
|
||||||
|
or digest(client) != '2374d6f585ec61e657739b848d418bb89dc37575ab97960e7a6b5d3248b0a860'):
|
||||||
|
raise ValueError('Reviewed NetBird client changed')
|
||||||
|
changes[client_target] = client
|
||||||
|
monitor_target = 'usr/lib/mission-core-node/netbird_monitor.py'
|
||||||
|
monitor = (REPO/'apps/node-agent/packaging/netbird_monitor.py').read_bytes()
|
||||||
|
if (monitor_target in old
|
||||||
|
or digest(monitor) != '69799e289170e190323d2c1f055340592b265d74d59e14a83112d163b8c0b977'):
|
||||||
|
raise ValueError('Reviewed monitor migration changed')
|
||||||
|
control = next(v for n,v,_ in controls if n=='control')
|
||||||
|
if control.count(b'Version: 0.8.53-148\n') != 1 or PROOF in old:
|
||||||
|
raise ValueError('Unexpected package identity')
|
||||||
|
controls = [(n, v.replace(b'Version: 0.8.53-148\n', b'Version: 0.8.53-151\n')
|
||||||
|
if n=='control' else v, m) for n,v,m in controls]
|
||||||
|
proof = dict(schema='missioncore.node.packaging-revision/v1', version=VERSION,
|
||||||
|
base_sha256=BASE, changed_files={n:digest(v) for n,v in changes.items()},
|
||||||
|
node_binary_ui_uplink_selection_unchanged=True,
|
||||||
|
new_files={monitor_target:digest(monitor)},
|
||||||
|
base_qualification_sha256=digest((base/'qualification.json').read_bytes()),
|
||||||
|
repack_source_sha256=digest(Path(__file__).read_bytes()))
|
||||||
|
data = [(n,changes.get(n,v),m) for n,v,m in data]
|
||||||
|
data.append((monitor_target, monitor, 0o644))
|
||||||
|
data.append((PROOF, (json.dumps(proof,sort_keys=True)+'\n').encode(), 0o644))
|
||||||
|
sys.path.insert(0,str(REPO/'scripts/packaging'))
|
||||||
|
from debian import package
|
||||||
|
raw = package(controls,data)
|
||||||
|
nc,nd = members(raw)
|
||||||
|
if nc!=controls or nd!=sorted(data):
|
||||||
|
raise ValueError('Repacked payload differs from reviewed delta')
|
||||||
|
output.mkdir(mode=0o700)
|
||||||
|
name = 'mission-core-node_'+VERSION+'_amd64.deb'
|
||||||
|
(output/name).write_bytes(raw)
|
||||||
|
artifacts = {name:dict(bytes=len(raw),sha256=digest(raw))}
|
||||||
|
for name,info in evidence['artifacts'].items():
|
||||||
|
if name.startswith('mission-core-node_'):continue
|
||||||
|
content=(base/name).read_bytes()
|
||||||
|
if digest(content)!=info['sha256'] or len(content)!=info['bytes']:
|
||||||
|
raise ValueError('Dependency changed')
|
||||||
|
os.link(base/name,output/name)
|
||||||
|
artifacts[name]=info
|
||||||
|
report=dict(schema='missioncore.node.runtime-qualification/v1',state='awaiting_prepared_host',
|
||||||
|
clean_image_qualified=False,artifacts=artifacts,packaging_revision=proof,
|
||||||
|
scope='Cancelled VESC preparation passive proof; Linux NetBird native monitor policy; no network selection changes')
|
||||||
|
(output/'qualification.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||||
|
print(json.dumps(report))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
parser=argparse.ArgumentParser()
|
||||||
|
parser.add_argument('--qualified',required=True,type=Path)
|
||||||
|
parser.add_argument('--output',required=True,type=Path)
|
||||||
|
args=parser.parse_args()
|
||||||
|
build(args.qualified,args.output)
|
||||||
@@ -6,8 +6,9 @@ from .release_observation import ReleaseObservation
|
|||||||
|
|
||||||
|
|
||||||
class PreflightRecovery:
|
class PreflightRecovery:
|
||||||
def __init__(self, profile):
|
def __init__(self, profile, *, cancelled=False):
|
||||||
self.profile = copy.deepcopy(profile)
|
self.profile = copy.deepcopy(profile)
|
||||||
|
self.cancelled = cancelled
|
||||||
self.proof = None
|
self.proof = None
|
||||||
|
|
||||||
def reset(self):
|
def reset(self):
|
||||||
|
|||||||
@@ -240,9 +240,9 @@ class RemoteControl:
|
|||||||
self.pending_release = ReleaseObservation(devices, time.monotonic())
|
self.pending_release = ReleaseObservation(devices, time.monotonic())
|
||||||
|
|
||||||
def _reconcile_preflight(self, devices):
|
def _reconcile_preflight(self, devices):
|
||||||
# Only the missing-device preflight path creates this observer. No
|
# Missing-device failures and cancelled preparation both reuse passive
|
||||||
# motor output/configuration was attempted, so it cannot invent a
|
# whole-profile proof. Neither path revives a retired input lease;
|
||||||
# historical release ACK or clear an unrelated execution fault.
|
# historical hardware faults remain terminal in last_stop.
|
||||||
with self.lock:
|
with self.lock:
|
||||||
pending = self.pending_availability
|
pending = self.pending_availability
|
||||||
if pending is None:
|
if pending is None:
|
||||||
@@ -253,9 +253,23 @@ class RemoteControl:
|
|||||||
or self.service.motor.active or firmware_active):
|
or self.service.motor.active or firmware_active):
|
||||||
pending.reset()
|
pending.reset()
|
||||||
return
|
return
|
||||||
if not pending.check(self.service.drive.value, devices, time.monotonic(),
|
ready = pending.check(self.service.drive.value, devices, time.monotonic(),
|
||||||
self.service.motor.receiver_active, self.service.motor.limits.pending):
|
self.service.motor.receiver_active, self.service.motor.limits.pending)
|
||||||
|
if (pending.cancelled and self.state == "stopping" and pending.proof is not None
|
||||||
|
and pending.proof.faulted(devices, time.monotonic())):
|
||||||
|
self.state = "fault"
|
||||||
|
self.message = "VESC сообщил об ошибке. Проверьте состояние перед включением."
|
||||||
|
if self.last_stop is not None:
|
||||||
|
self.last_stop.update(state="fault", message=self.message)
|
||||||
|
self.trace.add("preparation_recovery_fault", session_id=self.lease.id)
|
||||||
|
if not ready:
|
||||||
return
|
return
|
||||||
|
if pending.cancelled:
|
||||||
|
# Current neutral proof, not an invented ACK for an output that
|
||||||
|
# was never claimed. Limits must already be restored by owner.
|
||||||
|
self.release_confirmed = True
|
||||||
|
self.trace.add("preparation_neutral_confirmed", session_id=self.lease.id,
|
||||||
|
attachments=pending.proof.attachments, samples=pending.proof.count)
|
||||||
self.pending_availability = None
|
self.pending_availability = None
|
||||||
self.state, self.message = "stopped", None
|
self.state, self.message = "stopped", None
|
||||||
if self.last_stop is not None:
|
if self.last_stop is not None:
|
||||||
@@ -313,6 +327,7 @@ class RemoteControl:
|
|||||||
owner = self.service.motor
|
owner = self.service.motor
|
||||||
acquired = False
|
acquired = False
|
||||||
devices = []
|
devices = []
|
||||||
|
profile = copy.deepcopy(self.service.drive.value)
|
||||||
try:
|
try:
|
||||||
# Observation also owns this lock. A nonblocking attempt made
|
# Observation also owns this lock. A nonblocking attempt made
|
||||||
# arming depend on which thread happened to read first. Wait only
|
# arming depend on which thread happened to read first. Wait only
|
||||||
@@ -326,7 +341,7 @@ class RemoteControl:
|
|||||||
acquired = self.service.operation_lock.acquire(timeout=min(.02, remaining))
|
acquired = self.service.operation_lock.acquire(timeout=min(.02, remaining))
|
||||||
self.ensure_live()
|
self.ensure_live()
|
||||||
with self.service.lock: devices = list(self.service.devices.values())
|
with self.service.lock: devices = list(self.service.devices.values())
|
||||||
profile = self.service.drive.value
|
profile = copy.deepcopy(self.service.drive.value)
|
||||||
slots = LAYOUTS.get(profile["layout"], ())
|
slots = LAYOUTS.get(profile["layout"], ())
|
||||||
if not slots or set(profile["bindings"]) != set(slots):
|
if not slots or set(profile["bindings"]) != set(slots):
|
||||||
raise ValueError("Назначьте все моторы в настройках борта.")
|
raise ValueError("Назначьте все моторы в настройках борта.")
|
||||||
@@ -352,7 +367,18 @@ class RemoteControl:
|
|||||||
# drive() classifies only successful, finite release readback
|
# drive() classifies only successful, finite release readback
|
||||||
# as pending. Keep that state while the passive observer proves
|
# as pending. Keep that state while the passive observer proves
|
||||||
# standstill; an expired input is never granted more lifetime.
|
# standstill; an expired input is never granted more lifetime.
|
||||||
if self.state != "stopping" or not settlement_pending(self.release_evidence):
|
if (self.release_confirmed is None and self.message is None
|
||||||
|
and self.pending_release is None):
|
||||||
|
# Input may expire before acquiring the operation lock, in
|
||||||
|
# preflight, or before drive claims output. A null release
|
||||||
|
# must not leave Core waiting forever. Reuse passive proof
|
||||||
|
# of the exact bound profile; never grant/replay input here.
|
||||||
|
self.pending_availability = PreflightRecovery(profile, cancelled=True)
|
||||||
|
self.state = "stopping"
|
||||||
|
self.trace.add("preparation_cancelled_waiting", session_id=envelope["id"],
|
||||||
|
reason=str(error), operation_acquired=acquired,
|
||||||
|
waiting_for="fresh_neutral_pair_and_restored_limits")
|
||||||
|
elif self.state != "stopping" or not settlement_pending(self.release_evidence):
|
||||||
self.state = "fault" if self.message or self.release_confirmed is False else "stopped"
|
self.state = "fault" if self.message or self.release_confirmed is False else "stopped"
|
||||||
except (OSError, ValueError, TimeoutError, KeyError) as error:
|
except (OSError, ValueError, TimeoutError, KeyError) as error:
|
||||||
with self.lock:
|
with self.lock:
|
||||||
@@ -378,7 +404,8 @@ class RemoteControl:
|
|||||||
with self.lock:
|
with self.lock:
|
||||||
if not self.lease.live():
|
if not self.lease.live():
|
||||||
self.trace.add("lease_expired",session_id=self.lease.id,sequence=self.lease.sequence,
|
self.trace.add("lease_expired",session_id=self.lease.id,sequence=self.lease.sequence,
|
||||||
remaining_ms=(self.lease.until-time.monotonic())*1000)
|
reason="withdrawn" if self.lease.until == 0 else "deadline_expired",
|
||||||
|
remaining_ms=max(0,(self.lease.until-time.monotonic())*1000))
|
||||||
raise ControlEnded("Управление остановлено: команда больше не подтверждается.")
|
raise ControlEnded("Управление остановлено: команда больше не подтверждается.")
|
||||||
|
|
||||||
def drive(self, owner, command, devices, moving, originals, unchanged):
|
def drive(self, owner, command, devices, moving, originals, unchanged):
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
"""Real recovery owner, synthetic transport only: never issue motor commands."""
|
||||||
|
import copy
|
||||||
|
import threading
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from runtime.remote_control import ControlEnded, RemoteControl
|
||||||
|
from test_preflight_recovery import observe
|
||||||
|
|
||||||
|
|
||||||
|
def cancelled(stage='preflight'):
|
||||||
|
bindings = {side+'.1': {'device_id': side, 'uuid': str(i)*24}
|
||||||
|
for i, side in enumerate(('left', 'right'), 1)}
|
||||||
|
profile = {'layout': '1x1', 'revision': 2, 'bindings': bindings}
|
||||||
|
devices = [SimpleNamespace(id=b['device_id'], identity={'uuid': b['uuid']},
|
||||||
|
session=b['device_id']+'-live', identified_session=b['device_id']+'-live',
|
||||||
|
link=SimpleNamespace(alive=True), sample=None) for b in bindings.values()]
|
||||||
|
motor = SimpleNamespace(active=False, receiver_active=lambda _, v: abs(v)>.15,
|
||||||
|
limits=SimpleNamespace(pending=lambda _: False), latched=True,
|
||||||
|
run=Mock(side_effect=ControlEnded('input transport gap')))
|
||||||
|
service = SimpleNamespace(motor=motor, lock=threading.RLock(), operation_lock=threading.Lock(),
|
||||||
|
devices={d.id:d for d in devices}, drive=SimpleNamespace(value=profile),
|
||||||
|
firmware_update=SimpleNamespace(lock=threading.Lock(), active=None))
|
||||||
|
remote = RemoteControl(service)
|
||||||
|
remote.trace = SimpleNamespace(add=Mock())
|
||||||
|
remote.lease.id = 'a'*32
|
||||||
|
remote.ensure_live = Mock(side_effect=ControlEnded('expired before ownership') if stage=='lock' else None)
|
||||||
|
remote._prepare({'id':'a'*32, 'settings': {'current_a':30, 'max_erpm':1000}})
|
||||||
|
return remote, devices
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('stage', ['lock', 'preflight'])
|
||||||
|
def test_cancelled_preparation_recovers_from_new_neutral_samples_without_output(stage):
|
||||||
|
remote, devices = cancelled(stage)
|
||||||
|
assert remote.state == 'stopping' and remote.release_confirmed is None
|
||||||
|
history = copy.deepcopy(remote.last_stop)
|
||||||
|
for at in (10.,10.2,10.4):
|
||||||
|
observe(remote, devices, at)
|
||||||
|
assert remote.release_confirmed is None
|
||||||
|
observe(remote, devices, 10.6)
|
||||||
|
assert remote.state == 'stopped' and remote.release_confirmed is True
|
||||||
|
assert remote.pending_availability is None
|
||||||
|
assert remote.last_stop['release_confirmed'] is None # Keep historical truth.
|
||||||
|
assert remote.last_stop['state'] == history['state'] == 'stopping'
|
||||||
|
assert 'recovered_at' in remote.last_stop
|
||||||
|
assert not remote.lease.live() and 'a'*32 in remote.lease.retired
|
||||||
|
assert remote.service.motor.latched
|
||||||
|
assert remote.service.motor.run.call_count == (0 if stage=='lock' else 1)
|
||||||
|
assert any(c.args[0]=='preparation_neutral_confirmed' for c in remote.trace.add.call_args_list)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('case', ['missing','uuid','unverified','profile','limits','motor','firmware'])
|
||||||
|
def test_cancellation_cannot_bypass_interlocks(case):
|
||||||
|
remote, devices = cancelled()
|
||||||
|
if case == 'missing': devices=devices[:1]
|
||||||
|
if case == 'uuid': devices[0].identity['uuid']='f'*24
|
||||||
|
if case == 'unverified': devices[0].identified_session='old'
|
||||||
|
if case == 'profile': remote.service.drive.value['revision']+=1
|
||||||
|
if case == 'limits': remote.service.motor.limits.pending=lambda _:True
|
||||||
|
if case == 'motor': remote.service.motor.active=True
|
||||||
|
if case == 'firmware': remote.service.firmware_update.active={'device_id':'left'}
|
||||||
|
for at in (10.,10.2,10.4,10.6,10.8): observe(remote, devices, at)
|
||||||
|
assert remote.state == 'stopping' and remote.release_confirmed is None
|
||||||
|
assert not remote.lease.live()
|
||||||
|
|
||||||
|
|
||||||
|
def test_real_fault_during_wait_remains_terminal_even_when_it_clears():
|
||||||
|
remote, devices = cancelled()
|
||||||
|
observe(remote, devices, 10.)
|
||||||
|
devices[0].sample['values']['fault_code']=1
|
||||||
|
for d in devices: d.sample['sampled_at']=10.2
|
||||||
|
with patch('runtime.remote_control.time.monotonic', return_value=10.2):
|
||||||
|
remote._reconcile_preflight(devices)
|
||||||
|
assert remote.last_stop['state']=='fault'
|
||||||
|
for at in (10.4,10.6,10.8,11.): observe(remote, devices, at)
|
||||||
|
assert remote.state == 'stopped' and remote.release_confirmed is True
|
||||||
|
assert remote.last_stop['state']=='fault' # Core must require explicit new arm.
|
||||||
|
assert not remote.lease.live()
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancelled_neutral_drive_before_output_claim_also_has_a_recovery_observer():
|
||||||
|
from test_remote_control import DriveBoundaryTests
|
||||||
|
log, restored, remote, owner, error = DriveBoundaryTests().run_drive(
|
||||||
|
'expire-before-claim', through_prepare=True, neutral_only=True)
|
||||||
|
assert not log and error is None
|
||||||
|
assert set(restored)=={'left','right'}
|
||||||
|
assert remote.state=='stopping' and remote.release_confirmed is None
|
||||||
|
assert remote.pending_availability.cancelled and not remote.lease.live()
|
||||||
@@ -93,7 +93,9 @@ class PreparationHandoffTests(unittest.TestCase):
|
|||||||
self.assertEqual(self.calls, [])
|
self.assertEqual(self.calls, [])
|
||||||
self.finish()
|
self.finish()
|
||||||
self.assertEqual(self.calls, ['prepare'])
|
self.assertEqual(self.calls, ['prepare'])
|
||||||
self.assertEqual(self.remote.state, 'stopped')
|
self.assertEqual(self.remote.state, 'stopping')
|
||||||
|
self.assertIsNone(self.remote.release_confirmed)
|
||||||
|
self.assertTrue(self.remote.pending_availability.cancelled)
|
||||||
self.assertFalse(self.operation.locked())
|
self.assertFalse(self.operation.locked())
|
||||||
|
|
||||||
def test_new_lease_does_not_inherit_failed_release_or_claim_success(self):
|
def test_new_lease_does_not_inherit_failed_release_or_claim_success(self):
|
||||||
@@ -127,7 +129,9 @@ class PreparationHandoffTests(unittest.TestCase):
|
|||||||
self.remote.feed({'watch': True, 'command': None, 'relay_id': self.relay})
|
self.remote.feed({'watch': True, 'command': None, 'relay_id': self.relay})
|
||||||
self.finish()
|
self.finish()
|
||||||
self.assertEqual(self.calls, [])
|
self.assertEqual(self.calls, [])
|
||||||
self.assertEqual(self.remote.state, 'stopped')
|
self.assertEqual(self.remote.state, 'stopping')
|
||||||
|
self.assertIsNone(self.remote.release_confirmed)
|
||||||
|
self.assertTrue(self.remote.pending_availability.cancelled)
|
||||||
|
|
||||||
def test_expired_input_does_not_start_when_lock_is_released(self):
|
def test_expired_input_does_not_start_when_lock_is_released(self):
|
||||||
self.start()
|
self.start()
|
||||||
@@ -213,6 +217,13 @@ class DriveBoundaryTests(unittest.TestCase):
|
|||||||
owner.receiver_active=lambda _,level:abs(level)>.15
|
owner.receiver_active=lambda _,level:abs(level)>.15
|
||||||
owner.limits=SimpleNamespace(apply=lambda d,*a:dict(l_abs_current_max=160,l_current_max=35,l_max_erpm=100000,l_min_erpm=-100000,l_max_duty=.95,
|
owner.limits=SimpleNamespace(apply=lambda d,*a:dict(l_abs_current_max=160,l_current_max=35,l_max_erpm=100000,l_min_erpm=-100000,l_max_duty=.95,
|
||||||
s_pid_min_erpm=minimum_erpm[d.id] if isinstance(minimum_erpm,dict) else minimum_erpm),restore=lambda d:restored.append(d.id))
|
s_pid_min_erpm=minimum_erpm[d.id] if isinstance(minimum_erpm,dict) else minimum_erpm),restore=lambda d:restored.append(d.id))
|
||||||
|
if scenario == 'expire-before-claim':
|
||||||
|
original_apply = owner.limits.apply
|
||||||
|
def expire_after_limit(d, *args):
|
||||||
|
result = original_apply(d, *args)
|
||||||
|
remote.lease.stop()
|
||||||
|
return result
|
||||||
|
owner.limits.apply = expire_after_limit
|
||||||
def sleep(delta):
|
def sleep(delta):
|
||||||
now[0]+=delta
|
now[0]+=delta
|
||||||
if now[0]>=(3 if scenario=='right-only-braking' else 2):owner.stop.set()
|
if now[0]>=(3 if scenario=='right-only-braking' else 2):owner.stop.set()
|
||||||
|
|||||||
Reference in New Issue
Block a user