feat(dev): correlate telemetry recovery, safety stops and passive drive evidence
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.rover_capture_file import CaptureFiles
|
||||
from k1link.fleet.rover_local_trace import LocalRoverTrace
|
||||
|
||||
|
||||
def test_disk_keeps_complete_capture_after_ram_rotation_and_core_restart(tmp_path):
|
||||
trace = LocalRoverTrace(lambda: 10., tmp_path)
|
||||
trace.MAX_ROWS = 2
|
||||
capture = trace.start()
|
||||
for i in range(30):
|
||||
trace.add('sample', sample=i)
|
||||
trace.stop(capture['id'])
|
||||
path = trace.files.export(capture['id'])
|
||||
rows = [json.loads(line) for line in path.read_text().splitlines()]
|
||||
assert len([r for r in rows if r.get('event') == 'sample']) == 30
|
||||
assert rows[-1]['dropped'] == 0 and rows[-1]['error'] is None
|
||||
recovered = LocalRoverTrace(lambda: 20., tmp_path)
|
||||
assert recovered.history()[0]['id'] == capture['id']
|
||||
assert recovered.files.export(capture['id']) == path
|
||||
assert not recovered.active()
|
||||
|
||||
|
||||
def test_file_retention_excludes_foreign_files_and_reports_size_limit(tmp_path):
|
||||
files = CaptureFiles(tmp_path)
|
||||
files.MAX_BYTES = 600
|
||||
foreign = tmp_path / 'notes.jsonl'
|
||||
foreign.write_text('preserve')
|
||||
for n in range(6):
|
||||
identity = f'{n:032x}'
|
||||
files.start(identity, {})
|
||||
for _ in range(10):
|
||||
files.append(dict(event='sample', payload='x' * 150))
|
||||
files.finish()
|
||||
files.export(identity)
|
||||
assert len(files.files()) == 4
|
||||
assert foreign.read_text() == 'preserve'
|
||||
assert files.error == 'size_limit'
|
||||
assert files.dropped > 0
|
||||
with pytest.raises(ValueError):
|
||||
files.export('../secret')
|
||||
|
||||
|
||||
def test_new_sources_require_advertised_node_support():
|
||||
from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS
|
||||
|
||||
from k1link.fleet.rover_diagnostics import RoverDiagnostics
|
||||
options = dict(LOCAL_OPTIONS, router=True, system=True)
|
||||
trace = RoverDiagnostics(lambda: 0)
|
||||
trace.supports_options = True
|
||||
with pytest.raises(ValueError, match='Node'):
|
||||
trace.set_enabled(True, options)
|
||||
assert not trace.enabled
|
||||
trace.supports_sources = True
|
||||
trace.set_enabled(True, options)
|
||||
assert trace.desired()['options']['router'] is True
|
||||
assert trace.desired()['options']['system'] is True
|
||||
assert trace.view()['sources_supported'] is True
|
||||
|
||||
|
||||
def test_active_export_freezes_complete_rows_and_survives_rotation(tmp_path):
|
||||
files = CaptureFiles(tmp_path)
|
||||
identity = 'a' * 32
|
||||
files.start(identity, {})
|
||||
files.append(dict(event='before'))
|
||||
stream, size = files.open_snapshot(identity)
|
||||
files.append(dict(event='after'))
|
||||
files.finish()
|
||||
files.export(identity)
|
||||
files.MAX_FILES = 1
|
||||
files.start('b' * 32, {})
|
||||
files.finish()
|
||||
files.export('b' * 32)
|
||||
with stream:
|
||||
rows = [json.loads(line) for line in stream.read(size).splitlines()]
|
||||
assert [r.get('event') for r in rows] == [None, 'before']
|
||||
assert not (tmp_path / (identity + '.jsonl')).exists()
|
||||
@@ -30,6 +30,25 @@ def payload(row):
|
||||
"rover": {"instance": "synthetic", "state": "observing", "supported": True}}
|
||||
|
||||
|
||||
def test_clock_rejection_returns_calibration_without_renewing_observation(paired):
|
||||
fleet, row = paired
|
||||
body = payload(row)
|
||||
certificate = cert(row)
|
||||
assert fleet.receive(certificate, "/v1/node/rover", body)[0] == 200
|
||||
before = fleet.rover_control.view(row["node_id"])
|
||||
status, error = fleet.receive(certificate, "/v1/node/rover", {
|
||||
**body, "sample_clock": {"instance": fleet.rover_control.clock_id,
|
||||
"monotonic_ms": 100010.}})
|
||||
assert status == 400
|
||||
assert error == {"error": "Observation rejected", "error_code": "sample_clock",
|
||||
"control_clock": {"instance": fleet.rover_control.clock_id,
|
||||
"monotonic_ms": 100000.}}
|
||||
assert fleet.rover_control.view(row["node_id"]) == before
|
||||
status, denied = fleet.receive(certificate, "/v1/node/rover", {
|
||||
**body, "binding_id": "foreign", "sample_clock": {}})
|
||||
assert status != 200 and "control_clock" not in denied
|
||||
|
||||
|
||||
def arm(fleet, row):
|
||||
return rover_arm(row["id"], {"standstill_confirmed": True,
|
||||
"current_a": 5, "max_erpm": 1000}, fleet)["session_id"]
|
||||
@@ -74,7 +93,10 @@ def test_control_both_directions_does_not_wait_for_heartbeat_storage(paired, mon
|
||||
assert writer.result(timeout=2)[0] == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/v1/node/rover", "/v1/node/rover-stream", "/v1/node/rover-link", "/v1/node/rover-diagnostics"])
|
||||
@pytest.mark.parametrize("path", [
|
||||
"/v1/node/rover", "/v1/node/rover-stream", "/v1/node/rover-link",
|
||||
"/v1/node/rover-diagnostics",
|
||||
])
|
||||
@pytest.mark.parametrize("change,status", [({"binding_id": "wrong"}, 410),
|
||||
({"node_id": "wrong"}, 410), ({"schema": "wrong"}, 400),
|
||||
({"endpoint_revision": True}, 400), ({"endpoint_revision": -1}, 400),
|
||||
@@ -132,7 +154,8 @@ def test_startup_loads_bindings_but_never_restores_control(paired):
|
||||
reopened = FleetRegistry(fleet.root)
|
||||
try:
|
||||
assert reopened.rover_channel.operator(row["id"], "view") == {
|
||||
"fresh": False, "controlling": False, "snapshot": {}}
|
||||
"fresh": False, "controlling": False, "snapshot": {}, "control_fresh": False,
|
||||
"telemetry_age_ms": None, "telemetry_stop_ms": 1000}
|
||||
assert reopened.receive(cert(row), "/v1/node/rover", payload(row))[0] == 200
|
||||
finally:
|
||||
reopened.close()
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
|
||||
from k1link.fleet.rover_control import RoverControl
|
||||
|
||||
|
||||
def projection(fresh=True, count=2):
|
||||
return {
|
||||
'connectivity': 'online', 'inventory_fresh': fresh,
|
||||
'last_seen': 100., 'link_last_seen': 110.,
|
||||
'sensor_state': {'items': [
|
||||
{'id': f'device-{i}', 'online': True, 'credentials': 'never-record-this'}
|
||||
for i in range(count)
|
||||
]},
|
||||
'host': {'secret': 'never-record-this'},
|
||||
}
|
||||
|
||||
|
||||
def test_projection_captures_staleness_without_creating_or_renewing_control():
|
||||
now = [10.]
|
||||
control = RoverControl(lambda: now[0])
|
||||
control.record_inventory('node', projection())
|
||||
assert not control.boards
|
||||
diagnostics = control.diagnostics('node', 'Test board')
|
||||
control.record_inventory('node', projection())
|
||||
assert diagnostics.trace.local.sequence == 0
|
||||
identity = diagnostics.trace.local.start()['id']
|
||||
control.record_inventory('node', projection())
|
||||
control.record_inventory('node', projection())
|
||||
now[0] += 1.1
|
||||
control.record_inventory('node', projection(False))
|
||||
rows = [r for r in diagnostics.trace.local.page(identity)['frames']
|
||||
if r['event'] == 'inventory_projection']
|
||||
assert [r['inventory_fresh'] for r in rows] == [True, False]
|
||||
assert all(r['online'] and r['online_device_count'] == 2 for r in rows)
|
||||
assert 'never-record-this' not in json.dumps(rows)
|
||||
assert diagnostics.trace.sequence == diagnostics.live.sequence == 0
|
||||
assert control.boards['node']['watch'] == 0
|
||||
assert control.boards['node']['session'] is None
|
||||
diagnostics.trace.local.stop(identity)
|
||||
now[0] += 2
|
||||
count = diagnostics.trace.local.sequence
|
||||
control.record_inventory('node', projection())
|
||||
assert diagnostics.trace.local.sequence == count
|
||||
|
||||
|
||||
def test_projection_is_bounded_and_restarts_with_new_capture():
|
||||
control = RoverControl(lambda: 10.)
|
||||
diagnostics = control.diagnostics('node', 'Test board')
|
||||
previous = None
|
||||
for _ in range(2):
|
||||
identity = diagnostics.trace.local.start(previous_id=previous)['id']
|
||||
control.record_inventory('node', projection(count=256))
|
||||
rows = [r for r in diagnostics.trace.local.page(identity)['frames']
|
||||
if r['event'] == 'inventory_projection']
|
||||
assert len(rows) == 1
|
||||
assert rows[0]['device_count'] == 256
|
||||
assert rows[0]['devices_omitted'] == 224
|
||||
assert len(json.dumps(rows[0]).encode()) < 8192
|
||||
diagnostics.trace.local.stop(identity)
|
||||
previous = identity
|
||||
@@ -70,8 +70,8 @@ def test_local_ring_has_finite_bytes_rows_and_explicit_overwrite():
|
||||
with pytest.raises(ValueError):
|
||||
trace.start()
|
||||
assert trace.start(previous_id=identifier)["id"] != identifier
|
||||
with pytest.raises(ValueError):
|
||||
trace.page(identifier)
|
||||
assert trace.page(identifier)["id"] == identifier
|
||||
assert not trace.page(identifier)["active"]
|
||||
|
||||
|
||||
def test_local_api_rejects_foreign_origins_wrong_generations_and_does_not_arm(request):
|
||||
@@ -126,10 +126,12 @@ def test_preview_metrics_are_local_only_and_explicitly_projected():
|
||||
sample = {'peer_id': 'peer_a', 'device_session': 'session_a', 'allocation_bps': 5000000,
|
||||
'encoder_bps': 500000, 'receiver_bps': 307644, 'source_age_ms': 5,
|
||||
'sdp': 'must not be recorded'}
|
||||
body = {'id': identifier, 'events': [{'event': 'preview', 'sample': sample}]}
|
||||
body = {'id': identifier, 'events': [{'event': 'preview', 'sample': sample,
|
||||
'browser_ms': 123., 'browser_time_origin_ms': 100000.}]}
|
||||
assert d.browser(body, local=True)
|
||||
row = d.trace.local.snapshot()['frames'][-1]
|
||||
assert row['event'] == 'browser_preview' and row['sample']['encoder_bps'] == 500000
|
||||
assert row['browser_ms'] == 123. and row['browser_time_origin_ms'] == 100000.
|
||||
assert 'sdp' not in row['sample']
|
||||
before = d.trace.sequence
|
||||
with pytest.raises(ValueError):
|
||||
@@ -199,3 +201,51 @@ def test_invalid_ui_options_and_previous_capture_are_not_overwritten():
|
||||
d.set_enabled(True, dict(LOCAL_OPTIONS),
|
||||
{'enabled': True, 'preview': True, 'previous_id': identifier})
|
||||
assert d.trace.local.id != identifier and d.trace.local.active()
|
||||
|
||||
|
||||
def test_restart_retains_three_completed_captures_with_bounded_export():
|
||||
from k1link.fleet.rover_local_trace import LocalRoverTrace
|
||||
trace = LocalRoverTrace(lambda: 10.)
|
||||
trace.MAX_BYTES, trace.MAX_ROWS = 1000, 4
|
||||
identifiers = []
|
||||
for n in range(6):
|
||||
previous = trace.id
|
||||
identifier = trace.start(previous_id=previous)["id"]
|
||||
identifiers.append(identifier)
|
||||
for i in range(12):
|
||||
trace.add("sample", attempt=n, number=i)
|
||||
trace.stop(identifier)
|
||||
assert len(trace.history()) == 3
|
||||
assert [r["id"] for r in trace.history()] == identifiers[-2:-5:-1]
|
||||
for identifier in identifiers[-4:]:
|
||||
page = trace.page(identifier, limit=trace.MAX_ROWS)
|
||||
assert not page["active"] and page["bytes"] <= 1000
|
||||
assert len(page["frames"]) <= 4 and page["dropped"] > 0
|
||||
assert trace.page(identifier, after=page["sequence"])["frames"] == []
|
||||
with pytest.raises(ValueError):
|
||||
trace.page(identifiers[0])
|
||||
with pytest.raises(ValueError):
|
||||
trace.stop(identifiers[-2])
|
||||
assert trace.id == identifiers[-1]
|
||||
|
||||
|
||||
def test_dev_stop_start_without_download_preserves_local_export(request):
|
||||
control, client = request.getfixturevalue("fixture")
|
||||
d = control.diagnostics("node", "vehicle")
|
||||
d.supports_options = True
|
||||
url = "/api/v1/fleet/vehicle/rover/diagnostics"
|
||||
body = {"enabled": True, "options": dict(LOCAL_OPTIONS),
|
||||
"local_options": {"enabled": True, "preview": True}}
|
||||
first = client.post(url, json=body).json()
|
||||
client.post(url, json={"enabled": False})
|
||||
# Until the board closes its writer, starting another remains forbidden.
|
||||
assert client.post(url, json=body).status_code == 409
|
||||
d.ingest({"id": first["id"], "active": False, "storage": {"closed": True}})
|
||||
body["local_options"]["previous_id"] = first["local_capture"]["id"]
|
||||
second = client.post(url, json=body)
|
||||
assert second.status_code == 200
|
||||
assert second.json()["local_capture"]["id"] != first["local_capture"]["id"]
|
||||
assert second.json()["local_history"][0]["id"] == first["local_capture"]["id"]
|
||||
export = client.get(url+"/local/export", params={"capture_id": first["local_capture"]["id"]})
|
||||
assert export.status_code == 200 and "local_capture_stopped" in export.text
|
||||
assert not control.view("node")["controlling"]
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import pytest
|
||||
from missioncore_plugin_sdk.diagnostic_options import PASSIVE_OPTIONS, diagnostic_options
|
||||
|
||||
from k1link.fleet.rover_diagnostics import RoverDiagnostics
|
||||
|
||||
|
||||
def ready():
|
||||
d = RoverDiagnostics(lambda: 10.)
|
||||
d.supports_options = d.supports_sources = d.supports_passive = True
|
||||
return d
|
||||
|
||||
|
||||
def test_default_capable_capture_is_passive_and_sleeps_after_start_ack():
|
||||
d = ready()
|
||||
d.set_enabled(True)
|
||||
assert d.options == PASSIVE_OPTIONS
|
||||
assert d.traffic_pending() and not d.watch_required()
|
||||
identity = d.trace.id
|
||||
d.ingest({'id': 'f'*32, 'active': True})
|
||||
assert d.traffic_pending()
|
||||
reply = d.exchange({'diagnostic_passive_v1': True, 'diagnostics': {
|
||||
'id': identity, 'active': True, 'storage': {'closed': False}}})
|
||||
assert reply['diagnostics_pending'] is False
|
||||
assert d.enabled and d.passive_confirmed
|
||||
receipts = [r for r in d.trace.local.snapshot()['frames']
|
||||
if r['event'] == 'board_diagnostics_exchange']
|
||||
assert len(receipts) == 1
|
||||
for _ in range(5):
|
||||
d.trace.add('telemetry_received', sequence=1)
|
||||
assert not d.traffic_pending() and not d.watch_required()
|
||||
assert not d.desired()['core_events']
|
||||
d.set_enabled(False)
|
||||
assert d.traffic_pending() and d.closing and not d.watch_required()
|
||||
d.ingest({'id': identity, 'active': False, 'storage': {'closed': True}})
|
||||
assert not d.traffic_pending() and not d.closing
|
||||
d.set_enabled(True)
|
||||
assert d.trace.id != identity and d.traffic_pending()
|
||||
|
||||
|
||||
def test_passive_requires_capability_and_disallows_hidden_event_transmission():
|
||||
d = ready()
|
||||
d.supports_passive = False
|
||||
with pytest.raises(ValueError, match='обновите'):
|
||||
d.set_enabled(True, PASSIVE_OPTIONS)
|
||||
for key in ('live', 'core_trace'):
|
||||
with pytest.raises(ValueError, match='Passive'):
|
||||
diagnostic_options({**PASSIVE_OPTIONS, key: True})
|
||||
|
||||
|
||||
def test_export_is_explicit_and_reactivates_diagnostics_only_while_requested():
|
||||
d = ready()
|
||||
d.set_enabled(True)
|
||||
d.ingest({'id': d.trace.id, 'active': True, 'storage': {'closed': False}})
|
||||
assert not d.traffic_pending()
|
||||
token = d.export.start(d.trace.id)
|
||||
assert d.traffic_pending()
|
||||
d.export.finish(token)
|
||||
assert not d.traffic_pending()
|
||||
|
||||
|
||||
def test_recovery_of_passive_capture_does_not_resume_periodic_transmission():
|
||||
d = ready()
|
||||
d.ingest({'id': 'a'*32, 'active': True, 'options': PASSIVE_OPTIONS,
|
||||
'storage': {'closed': False}})
|
||||
assert d.enabled and d.passive_confirmed
|
||||
assert not d.traffic_pending() and not d.watch_required()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('recording', [False, True])
|
||||
def test_fresh_core_requests_one_status_exchange_and_can_stop_surviving_capture(recording):
|
||||
# The old Core has disappeared; Node's passive lane was already asleep.
|
||||
# Recovery must be initiated by the existing telemetry reply, not by new
|
||||
# periodic DEV polling or by starting a replacement capture.
|
||||
d = ready()
|
||||
assert d.traffic_pending() and not d.watch_required()
|
||||
identity = 'b' * 32
|
||||
packet = {'id': identity, 'active': True, 'options': PASSIVE_OPTIONS,
|
||||
'storage': {'closed': False}, 'frames': []} if recording else None
|
||||
reply = d.exchange({'diagnostic_passive_v1': True, 'diagnostics': packet})
|
||||
assert reply['diagnostics_pending'] is False
|
||||
assert not d.traffic_pending() and not d.watch_required()
|
||||
assert d.enabled is recording
|
||||
if recording:
|
||||
assert d.trace.id == identity and not d.desired()['core_events']
|
||||
d.set_enabled(False)
|
||||
assert d.traffic_pending() and d.desired()['enabled'] is False
|
||||
d.ingest({'id': identity, 'active': False, 'storage': {'closed': True}})
|
||||
assert not d.traffic_pending() and not d.closing
|
||||
else:
|
||||
assert d.desired() is None
|
||||
|
||||
|
||||
def test_passive_capture_does_not_request_a_control_watch_or_change_commands():
|
||||
from k1link.fleet.rover_control import RoverControl
|
||||
h = RoverControl(lambda: 10.)
|
||||
relay = 'a'*32
|
||||
body = {'relay_id': relay, 'rover': {'supported': True, 'instance': 'driver',
|
||||
'state': 'observing'}, 'diagnostic_lane_v1': True,
|
||||
'diagnostic_options_v1': True, 'diagnostic_sources_v1': True,
|
||||
'diagnostic_passive_v1': True}
|
||||
h.exchange('node', body)
|
||||
d = h.diagnostics('node', 'rover')
|
||||
d.set_enabled(True)
|
||||
assert d.trace.local.active()
|
||||
for confirmed in (False, True):
|
||||
if confirmed:
|
||||
d.ingest({'id': d.trace.id, 'active': True, 'storage': {'closed': False}})
|
||||
value = h.exchange('node', body)
|
||||
assert value['diagnostics_pending'] is (not confirmed)
|
||||
assert value['watch'] is False and value['control_active'] is False
|
||||
assert value['command'] is None and value['diagnostics'] is None
|
||||
assert h.stream('node', relay)['watch'] is False
|
||||
d.set_enabled(False)
|
||||
assert h.exchange('node', body)['watch'] is False
|
||||
@@ -0,0 +1,37 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.rover_control import RoverControl
|
||||
from k1link.fleet.rover_observation_evidence import ObservationEvidence
|
||||
from k1link.fleet.rover_rejection_evidence import rejection_evidence
|
||||
|
||||
|
||||
def test_future_observation_is_recorded_without_publishing_or_renewing_authority():
|
||||
hub = RoverControl(lambda: 100.)
|
||||
hub.exchange("node", {"relay_id": "a" * 32, "rover": {"instance": "driver", "devices": []}})
|
||||
before = hub.view("node")
|
||||
hub.diagnostics("node", "test").trace.local.start()
|
||||
with pytest.raises(ValueError, match="sample clock"):
|
||||
hub.exchange("node", {"relay_id": "a" * 32, "rover": {},
|
||||
"sample_clock": {"instance": hub.clock_id, "monotonic_ms": 100012.5}})
|
||||
assert hub.view("node") == before
|
||||
facts = hub.observation("node")
|
||||
assert facts["rejected"] == 1
|
||||
assert facts["last_rejection"]["reason"] == "sample_clock"
|
||||
assert facts["last_rejection"]["sample_offset_ms"] == 12.5
|
||||
rows = hub.diagnostics("node", "test").trace.local.snapshot()["frames"]
|
||||
assert any(x["event"] == "node_observation_rejected" for x in rows)
|
||||
|
||||
|
||||
def test_rejection_summary_is_bounded_daily_and_does_not_retain_raw_errors():
|
||||
now = [datetime(2026, 11, 16, tzinfo=UTC)]
|
||||
evidence = ObservationEvidence(lambda: 100., lambda: now[0])
|
||||
for i in range(1000):
|
||||
evidence.reject(rejection_evidence(ValueError(f"private secret {i}"), {}, "epoch", 100.))
|
||||
facts = evidence.snapshot()
|
||||
assert facts["rejection_reasons"] == {"invalid_observation": 1000}
|
||||
assert "secret" not in str(facts)
|
||||
now[0] += timedelta(days=1)
|
||||
assert evidence.snapshot()["rejected"] == 0
|
||||
assert evidence.snapshot()["last_rejection"] is None
|
||||
@@ -145,3 +145,76 @@ def test_local_api_exposes_reason_without_dev_and_preserves_origin_boundary(fixt
|
||||
assert result.status_code == 200 and not result.json()['active']
|
||||
assert result.json()['core_stop_v1']['reason'] == 'operator_socket_closed'
|
||||
assert client.get(url, headers={'Origin': 'https://foreign.invalid'}).status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.parametrize('trigger', ['operator_stop', 'telemetry_stale', 'operator_socket_closed'])
|
||||
def test_passive_stop_is_persistent_without_wan_and_survives_core_recreation(tmp_path, trigger):
|
||||
import json
|
||||
|
||||
from k1link.fleet.rover_capture_file import CaptureFiles
|
||||
from k1link.fleet.rover_control import RoverControl
|
||||
|
||||
now = [10.]
|
||||
h = RoverControl(lambda: now[0], tmp_path)
|
||||
exchange(h, state='observing')
|
||||
d = h.diagnostics('node', 'vehicle')
|
||||
d.supports_passive = d.supports_sources = d.supports_options = True
|
||||
d.set_enabled(True)
|
||||
d.ingest({'id': d.trace.id, 'active': True, 'storage': {'closed': False}})
|
||||
capture = d.trace.local.id
|
||||
identifier = arm(h)
|
||||
h.command('node', cmd(identifier))
|
||||
if trigger == 'operator_stop':
|
||||
h.command('node', cmd(identifier, 2, stop=True))
|
||||
elif trigger == 'operator_socket_closed':
|
||||
h.disconnect('node', identifier)
|
||||
else:
|
||||
for sequence in range(2, 14):
|
||||
now[0] += .09
|
||||
h.command('node', cmd(identifier, sequence))
|
||||
h.stream('node', 'a'*32)
|
||||
assert not h.view('node')['controlling']
|
||||
assert not d.traffic_pending() and not d.desired()['core_events']
|
||||
d.trace.local.files.export(capture) # Existing writer flush, not browser/API polling.
|
||||
files = CaptureFiles(d.trace.local.files.root)
|
||||
rows = [json.loads(line) for line in files.export(capture).read_text().splitlines()]
|
||||
stopped = [row for row in rows if row.get('event') == 'core_control_stop']
|
||||
assert len(stopped) == 1
|
||||
assert stopped[0]['reason'] == trigger
|
||||
assert stopped[0]['session_id'] == identifier
|
||||
assert stopped[0]['core_clock_instance'] == h.clock_id
|
||||
assert stopped[0]['monotonic_ms'] == now[0]*1000
|
||||
assert 'telemetry_age_ms' in stopped[0]
|
||||
d.set_enabled(False)
|
||||
d.trace.local.files.thread.join(2)
|
||||
|
||||
|
||||
def test_busy_file_lock_never_blocks_stop_and_counts_evidence_loss(tmp_path):
|
||||
import threading
|
||||
|
||||
from k1link.fleet.rover_control import RoverControl
|
||||
|
||||
h = RoverControl(lambda: 10., tmp_path)
|
||||
exchange(h, state='observing')
|
||||
d = h.diagnostics('node', 'vehicle')
|
||||
d.trace.local.start()
|
||||
identifier = arm(h)
|
||||
held, release = threading.Event(), threading.Event()
|
||||
def hold():
|
||||
with d.trace.local.files.lock:
|
||||
held.set()
|
||||
release.wait(2)
|
||||
worker = threading.Thread(target=hold)
|
||||
worker.start()
|
||||
assert held.wait(1)
|
||||
try:
|
||||
# Direct safety withdrawal avoids other unrelated diagnostic trace hooks.
|
||||
h._withdraw(h._board('node'), 'telemetry_stale')
|
||||
assert not h.view('node')['controlling']
|
||||
assert d.trace.local.files.dropped == 1
|
||||
assert latest(h)['session_id'] == identifier
|
||||
finally:
|
||||
release.set()
|
||||
worker.join(2)
|
||||
d.trace.local.stop(d.trace.local.id)
|
||||
d.trace.local.files.thread.join(2)
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Telemetry age preference cannot grant or prolong any command authority."""
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.rover_control import RoverControl
|
||||
from k1link.fleet.rover_telemetry_policy import RoverTelemetryPreferences
|
||||
|
||||
SETTINGS = dict(standstill_confirmed=True, current_a=5, max_erpm=1000)
|
||||
RELAY = "a" * 32
|
||||
|
||||
|
||||
def setup(threshold):
|
||||
now = [100.0]
|
||||
hub = RoverControl(lambda: now[0])
|
||||
hub.exchange(
|
||||
"node",
|
||||
dict(relay_id=RELAY, rover=dict(supported=True, instance="driver", state="observing")),
|
||||
)
|
||||
session = hub.arm("node", {**SETTINGS, "telemetry_stop_ms": threshold})["session_id"]
|
||||
return hub, now, session
|
||||
|
||||
|
||||
def command(hub, session, seq):
|
||||
hub.command("node", dict(session_id=session, sequence=seq, left=0, right=0, stop=False))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("threshold", [250, 1000, 1500, 2000, 5000])
|
||||
def test_only_telemetry_cutoff_changes_and_exact_boundary_stops(threshold):
|
||||
hub, now, session = setup(threshold)
|
||||
for seq in range(1, threshold // 100 + 1):
|
||||
now[0] = 100 + (seq - 1) * 0.1
|
||||
command(hub, session, seq)
|
||||
assert hub.stream("node", RELAY)["command"]["settings"] == SETTINGS
|
||||
now[0] = 100 + threshold / 1000 - 0.001
|
||||
command(hub, session, 100)
|
||||
view = hub.view("node")
|
||||
assert view["control_fresh"] and view["controlling"]
|
||||
assert view["fresh"] is (threshold <= 1000)
|
||||
assert view["telemetry_stop_ms"] == threshold
|
||||
now[0] = 100 + threshold / 1000
|
||||
assert hub.stream("node", RELAY)["command"] is None
|
||||
assert not hub.view("node")["controlling"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("threshold", [1000, 2000, 5000])
|
||||
def test_command_deadline_and_stop_remain_independent(threshold):
|
||||
hub, now, session = setup(threshold)
|
||||
command(hub, session, 1)
|
||||
assert hub.stream("node", RELAY)["command"]["expires_mono_ms"] == 100400
|
||||
now[0] += 0.401
|
||||
assert hub.stream("node", RELAY)["command"] is None
|
||||
with pytest.raises(ValueError):
|
||||
command(hub, session, 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("threshold", [250, 1000, 5000])
|
||||
@pytest.mark.parametrize("terminal", ["receiver", "fault", "stopped"])
|
||||
def test_threshold_never_suppresses_driver_stop(threshold, terminal):
|
||||
hub, _, session = setup(threshold)
|
||||
assert (
|
||||
hub.exchange(
|
||||
"node",
|
||||
dict(
|
||||
relay_id=RELAY,
|
||||
rover=dict(supported=True, instance="driver", session_id=session, state=terminal),
|
||||
),
|
||||
)["command"]
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [True, 0, 249, 5001, 1000.5, "2000", None, float("nan")])
|
||||
def test_invalid_threshold_never_arms(value):
|
||||
with pytest.raises(ValueError):
|
||||
setup(value)
|
||||
|
||||
|
||||
def test_neutral_hold_obeys_the_same_threshold_and_does_not_extend_motion():
|
||||
hub, now, session = setup(1500)
|
||||
hub.hold("node", dict(session_id=session, sequence=1))
|
||||
for i in range(1, 15):
|
||||
now[0] = 100 + i * 0.1
|
||||
assert hub.maintain_neutral("node", session)
|
||||
assert hub.stream("node", RELAY)["command"]["left"] == 0
|
||||
now[0] = 101.5
|
||||
assert not hub.maintain_neutral("node", session)
|
||||
|
||||
|
||||
def test_rearm_still_requires_fresh_telemetry_even_with_large_limit():
|
||||
hub, now, session = setup(5000)
|
||||
hub.disconnect("node", session)
|
||||
now[0] += 1.001
|
||||
with pytest.raises(ValueError):
|
||||
hub.arm("node", {**SETTINGS, "telemetry_stop_ms": 5000})
|
||||
|
||||
|
||||
def test_preference_survives_restart_is_per_vehicle_and_cas(tmp_path):
|
||||
p = RoverTelemetryPreferences(tmp_path)
|
||||
assert p.view("a") == dict(revision=0, telemetry_stop_ms=1000)
|
||||
saved = p.update("a", dict(revision=0, telemetry_stop_ms=1500))
|
||||
assert saved == dict(revision=1, telemetry_stop_ms=1500)
|
||||
assert RoverTelemetryPreferences(tmp_path).view("a") == saved
|
||||
assert p.view("b")["telemetry_stop_ms"] == 1000
|
||||
with pytest.raises(ValueError):
|
||||
p.update("a", dict(revision=0, telemetry_stop_ms=2000))
|
||||
p.path("a").write_text("{broken")
|
||||
with pytest.raises(ValueError):
|
||||
p.view("a")
|
||||
|
||||
|
||||
def test_preference_change_cannot_mutate_running_session(tmp_path):
|
||||
p = RoverTelemetryPreferences(tmp_path)
|
||||
hub, _, _ = setup(p.view("a")["telemetry_stop_ms"])
|
||||
p.update("a", dict(revision=0, telemetry_stop_ms=2000))
|
||||
assert hub.view("node")["telemetry_stop_ms"] == 1000
|
||||
assert hub.stream("node", RELAY)["command"]["settings"] == SETTINGS
|
||||
Reference in New Issue
Block a user