Files
NODEDC_MISSION_CORE/tests/fleet/test_rover_control.py
T
DCCONSTRUCTIONS e06ff9a214 feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
2026-10-29 09:10:01 +03:00

275 lines
12 KiB
Python

import pytest
from k1link.fleet.rover_control import RoverControl
@pytest.fixture
def hub():
now=[10.]
h=RoverControl(lambda:now[0])
h.exchange('node',{'relay_id':'a'*32,'rover':{'supported':True,'instance':'driver','state':'observing'}})
return h,now
def arm(h):
return h.arm('node',{'standstill_confirmed':True,'current_a':30,'max_erpm':2000})['session_id']
def test_throttle_requires_capable_current_board_and_preserves_units(hub):
h,now=hub
body={'standstill_confirmed':True,'current_a':30,'max_duty_percent':50}
with pytest.raises(ValueError):h.arm('node',body)
exchange(h,control_modes=['rpm','duty'])
h.arm('node',body)
assert h.stream('node','a'*32)['command']['settings']==body
@pytest.mark.parametrize('change',[{'current_a':float('inf')},{'current_a':float('nan')},{'current_a':True},{'current_a':.49},{'max_duty_percent':0},{'max_duty_percent':101},
{'max_duty_percent':float('nan')},{'max_duty_percent':True},{'max_erpm':3000}])
def test_throttle_invalid_parameters_never_arm(hub,change):
h,_=hub;exchange(h,control_modes=['rpm','duty'])
with pytest.raises(ValueError):h.arm('node',{'standstill_confirmed':True,'current_a':30,'max_duty_percent':50,**change})
assert not h.view('node')['controlling']
def cmd(id,seq=1,**kw):
return {'session_id':id,'sequence':seq,'left':1,'right':1,'stop':False,**kw}
def exchange(h,**kw):
return h.exchange('node',{'relay_id':'a'*32,'rover':{'supported':True,'instance':'driver',**kw}})
def test_expired_browser_cannot_be_revived_by_late_packet(hub):
h,now=hub;id=arm(h);h.command('node',cmd(id));now[0]+=.401
assert exchange(h)['command'] is None
with pytest.raises(ValueError):h.command('node',cmd(id,2))
def test_socket_deadline_is_not_renewed_by_delayed_local_delivery(hub):
h,now=hub;identifier=arm(h)
h.command('node',cmd(identifier),expires_at=10.15)
assert h.stream('node','a'*32)['command']['expires_mono_ms']==pytest.approx(10150)
now[0]=10.16
with pytest.raises(ValueError):h.command('node',cmd(identifier,2),expires_at=10.15)
assert not h.view('node')['controlling']
def test_expired_socket_arm_never_creates_authority(hub):
h,_=hub
with pytest.raises(ValueError):h.arm('node',{'standstill_confirmed':True,'current_a':30,'max_erpm':2000},expires_at=9.99)
assert not h.view('node')['controlling']
def test_sequence_stop_and_single_owner(hub):
h,_=hub;id=arm(h)
with pytest.raises(ValueError):arm(h)
h.command('node',cmd(id,2))
with pytest.raises(ValueError):h.command('node',cmd(id,1))
assert exchange(h)['command']['sequence']==2
h.command('node',cmd(id,3,stop=True))
with pytest.raises(ValueError):h.command('node',cmd(id,4))
assert exchange(h)['command'] is None
@pytest.mark.parametrize('snapshot',[{'state':'receiver'},{'state':'fault'},{'state':'stopping','release_confirmed':False},{'instance':'new-driver'}])
def test_takeover_fault_or_driver_restart_revokes(hub,snapshot):
h,_=hub;id=arm(h)
assert exchange(h,session_id=id,**snapshot)['command'] is None
def test_stopping_retires_neutral_hold_before_settlement(hub):
h, _ = hub
identifier = arm(h)
h.hold('node', {'session_id': identifier, 'sequence': 1})
assert exchange(h, session_id=identifier, state='stopping', release_confirmed=False)['command'] is None
assert not h.maintain_neutral('node', identifier)
with pytest.raises(ValueError):
h.command('node', cmd(identifier, 2, left=0, right=0))
assert not h.view('node')['controlling']
def test_relay_restart_and_cross_board_do_not_inherit_authority(hub):
h,_=hub;id=arm(h)
with pytest.raises(ValueError):h.command('other',cmd(id))
assert h.exchange('node',{'relay_id':'b'*32,'rover':{}})['command'] is None
@pytest.mark.parametrize('value',[True,float('nan'),float('inf'),1.01,-1.01,'1'])
def test_invalid_demand_cannot_refresh(hub,value):
h,_=hub;id=arm(h)
with pytest.raises(ValueError):h.command('node',cmd(id,left=value))
def test_stale_telemetry_is_unavailable_and_arm_requires_current_board(hub):
h,now=hub;now[0]+=1.1
assert h.view('node')['snapshot']=={}
with pytest.raises(ValueError):arm(h)
def test_stream_keeps_absolute_deadline_and_never_renews_held_frame(hub):
h, now = hub
identifier = arm(h)
h.command('node', cmd(identifier, 1))
first = h.stream('node', 'a'*32)
now[0] += .2
repeated = h.stream('node', 'a'*32)
assert repeated['command'] == first['command']
assert repeated['control_clock']['monotonic_ms'] > first['control_clock']['monotonic_ms']
assert first['command']['expires_mono_ms'] == pytest.approx(10400)
now[0] += .201
assert h.stream('node', 'a'*32)['command'] is None
with pytest.raises(ValueError): h.command('node', cmd(identifier, 2))
def test_stream_delivers_new_intent_without_waiting_for_telemetry(hub):
h, now = hub
identifier = arm(h)
h.command('node', cmd(identifier, 1))
h.command('node', cmd(identifier, 2, left=-1))
assert h.stream('node', 'a'*32)['command']['left'] == -1
assert h.stream('node', 'b'*32)['command'] is None
h.command('node', cmd(identifier, 3, stop=True))
assert h.stream('node', 'a'*32)['command'] is None
def test_new_core_has_distinct_clock_epoch(hub):
h, _ = hub
assert h.stream('node', 'a'*32)['control_clock']['instance'] != RoverControl().clock_id
def test_stream_retires_control_if_return_telemetry_is_lost(hub):
h, now = hub
identifier = arm(h)
for seq in range(1, 13):
h.command('node', cmd(identifier, seq))
now[0] += .09
assert h.stream('node', 'a'*32)['command'] is None
with pytest.raises(ValueError): h.command('node', cmd(identifier, 13))
def test_intent_wait_wakes_on_update_and_does_not_miss_prior_update(hub):
import threading
from unittest.mock import patch
h, _ = hub
identifier = arm(h)
previous = h.stream('node', 'a'*32)['command']
entered, done = threading.Event(), threading.Event()
def waiter():
entered.set()
h.wait_for_intent('node', 'a'*32, previous, timeout=2)
done.set()
worker = threading.Thread(target=waiter)
worker.start()
assert entered.wait(1)
h.command('node', cmd(identifier, 1))
assert done.wait(.5), 'new intent waited for the periodic keepalive'
worker.join(2)
# A command arriving after socket write but before wait must not be lost.
with patch.object(h.changed, 'wait', side_effect=AssertionError('missed prior update')):
h.wait_for_intent('node', 'a'*32, previous, timeout=2)
latest = h.stream('node', 'a'*32)['command']
h.command('node', cmd(identifier, 2, stop=True))
with patch.object(h.changed, 'wait', side_effect=AssertionError('missed stop')):
h.wait_for_intent('node', 'a'*32, latest, timeout=2)
def test_neutral_hold_keeps_same_session_for_five_seconds_and_separates_sequences(hub):
h, now = hub
identifier = arm(h)
h.command('node', cmd(identifier, 1))
h.hold('node', {'session_id': identifier, 'sequence': 2})
sequences = []
for _ in range(60):
now[0] += .1
exchange(h, state='ready', session_id=identifier)
assert h.maintain_neutral('node', identifier)
frame = h.stream('node', 'a'*32)['command']
assert frame['id'] == identifier and frame['left'] == frame['right'] == 0
assert set(frame) == {'id','sequence','left','right','settings','expires_mono_ms'}
sequences.append(frame['sequence'])
assert all(a < b for a,b in zip(sequences, sequences[1:]))
# Operator counter is independent of the native neutral heartbeat counter.
assert h.command('node', cmd(identifier, 3, left=-.5))['accepted_sequence'] == 3
frame = h.stream('node', 'a'*32)['command']
assert frame['sequence'] > sequences[-1] and frame['left'] == -.5
assert not h.maintain_neutral('node', identifier), 'never renew movement'
now[0] += .401
assert h.stream('node', 'a'*32)['command'] is None
def test_neutral_maintenance_cannot_start_extend_motion_or_revive_expired_lease(hub):
h, now = hub
assert not h.maintain_neutral('node', 'missing')
identifier = arm(h)
h.command('node', cmd(identifier, 1))
before = h.stream('node', 'a'*32)['command']
assert not h.maintain_neutral('node', identifier)
assert h.stream('node', 'a'*32)['command'] == before
h.hold('node', {'session_id': identifier, 'sequence': 2})
assert not h.maintain_neutral('node', 'another-owner')
now[0] += .401
exchange(h, state='ready', session_id=identifier)
assert not h.maintain_neutral('node', identifier)
with pytest.raises(ValueError): h.hold('node', {'session_id':identifier,'sequence':3})
@pytest.mark.parametrize('failure',['disconnect','telemetry','fault','receiver','stopped','restart','relay','revoke'])
def test_neutral_hold_does_not_survive_real_failures(hub, failure):
h, now = hub
identifier = arm(h)
h.hold('node', {'session_id': identifier, 'sequence': 1})
if failure == 'disconnect': h.disconnect('node', identifier)
elif failure == 'revoke': h.forget('node')
elif failure == 'telemetry':
for _ in range(11):
now[0] += .1
h.maintain_neutral('node', identifier)
elif failure == 'relay': h.exchange('node', {'relay_id':'b'*32,'rover':{'instance':'driver'}})
elif failure == 'restart': exchange(h, instance='new')
else: exchange(h, session_id=identifier, state=failure)
assert not h.maintain_neutral('node', identifier)
assert h.stream('node','a'*32)['command'] is None
@pytest.mark.parametrize('patch',[{'left':1},{'sequence':True},{'sequence':0},{'sequence':float('nan')},{'session_id':'other'}])
def test_invalid_or_replayed_hold_cannot_overwrite_fresh_input(hub, patch):
h, _ = hub
identifier = arm(h)
h.command('node', cmd(identifier, 1))
before = h.stream('node','a'*32)['command']
with pytest.raises(ValueError):h.hold('node', {'session_id':identifier,'sequence':1,**patch})
assert h.stream('node','a'*32)['command'] == before
def test_cached_readings_continue_aging_without_mutating_board_sample(hub):
h,now=hub
exchange(h,devices=[{'uuid':'synthetic','session_id':'usb-generation','age_ms':300}])
now[0]+=.6
first=h.view('node')['snapshot']['devices'][0]
assert first['age_ms']==pytest.approx(900,abs=1)
now[0]+=.2
second=h.view('node')['snapshot']['devices'][0]
assert second['age_ms']==pytest.approx(1100,abs=1)
assert h.boards['node']['snapshot']['devices'][0]['age_ms']==300
now[0]+=.21
assert h.view('node')['snapshot']=={}
@pytest.mark.parametrize('current',[35,60,100,120,150])
def test_selected_current_reaches_board_without_a_hidden_30a_cap(hub,current):
h,_=hub;exchange(h,control_modes=['rpm','duty'])
body={'standstill_confirmed':True,'current_a':current,'max_duty_percent':100}
h.arm('node',body)
assert h.stream('node','a'*32)['command']['settings']==body
def test_idle_dev_hint_wakes_capture_stop_and_export_without_optional_lock(hub, monkeypatch):
h, _ = hub
d = h.diagnostics('node', 'rover')
body = {'relay_id': 'a'*32, 'rover': {'instance': 'driver', 'state': 'observing'}, 'diagnostic_lane_v1': True}
def forbidden(**kwargs):
raise AssertionError('critical lane entered optional recorder/export lock')
monkeypatch.setattr(d, 'desired', forbidden)
reply = h.exchange('node', body)
assert reply['diagnostics_pending'] is False and reply['diagnostics'] is None
assert reply['control_active'] is False and reply['command'] is None
for enabled, closing, export in [(True, False, False), (False, True, False), (False, False, True)]:
d.enabled, d.closing, d.export.busy = enabled, closing, export
reply = h.exchange('node', body)
assert reply['diagnostics_pending'] is True
assert reply['diagnostics'] is None and reply['command'] is None
def test_budget_summary_ages_independently_of_fresh_motor_samples():
from k1link.fleet.rover_control import RoverControl
now = [100.]
control = RoverControl(clock=lambda: now[0])
body = {'relay_id':'a'*32, 'rover':{'supported':True,'instance':'driver','state':'stopped'}}
control.exchange('node',{**body,'link_budget':{'effective_kbps':4000}})
now[0] += .5
control.exchange('node',body)
assert control.view('node')['link_budget']['snapshot_age_ms'] == 500
now[0] += 2
control.exchange('node',body)
value = control.view('node')
assert value['fresh'] and 'link_budget' not in value