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.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent bec20d63e2
commit e06ff9a214
180 changed files with 20140 additions and 400 deletions
+66
View File
@@ -0,0 +1,66 @@
"""Compression changes framing, never identity, acknowledgements or body limits."""
import gzip
import http.client
import json
import threading
from http.server import ThreadingHTTPServer
from types import SimpleNamespace
import pytest
from k1link.fleet.heartbeat_encoding import MAX_HEARTBEAT_BYTES, decode_heartbeat
from k1link.fleet.transport import NodeChannelHandler
def test_encoding_rejects_truncation_concatenation_expansion_and_other_channels():
body = b'{"snapshot":"fixture"}'
encoded = gzip.compress(body)
assert decode_heartbeat(body, "", "/v1/node/heartbeat") == body
assert decode_heartbeat(encoded, "gzip", "/v1/node/heartbeat") == body
for data, encoding, path in (
(encoded[:-2], "gzip", "/v1/node/heartbeat"),
(encoded + encoded, "gzip", "/v1/node/heartbeat"),
(encoded + b"extra", "gzip", "/v1/node/heartbeat"),
(gzip.compress(b"x" * (MAX_HEARTBEAT_BYTES + 1)), "gzip", "/v1/node/heartbeat"),
(encoded, "deflate", "/v1/node/heartbeat"),
(encoded, "gzip", "/v1/node/rover"),
(encoded, "gzip", "/v1/node/liveness"),
):
with pytest.raises(ValueError):
decode_heartbeat(data, encoding, path)
def test_http_decodes_before_existing_authentication_and_rejects_bad_body():
calls = []
class Handler(NodeChannelHandler):
def setup(self):
super().setup()
self.connection = SimpleNamespace(getpeercert=lambda **_: b"fixture-cert")
def receive(cert, path, value, *, address):
calls.append((cert, path, value))
return 403, {"error": "Fixture binding rejected"}
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.address = "127.0.0.1"
server.registry = SimpleNamespace(receive=receive)
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
for raw, expected in ((gzip.compress(b'{"node_id":"fixture"}'), 403), (b"invalid", 400)):
client = http.client.HTTPConnection(*server.server_address, timeout=2)
try:
client.request("POST", "/v1/node/heartbeat", raw,
{"Content-Type": "application/json", "Content-Encoding": "gzip"})
response = client.getresponse()
assert response.status == expected
assert "error" in json.loads(response.read())
finally:
client.close()
assert calls == [(b"fixture-cert", "/v1/node/heartbeat", {"node_id": "fixture"})]
finally:
server.shutdown()
server.server_close()
worker.join(timeout=2)
+148
View File
@@ -0,0 +1,148 @@
import base64
import importlib.util
import json
import secrets
import time
from pathlib import Path
from types import SimpleNamespace
import pytest
from k1link.fleet.network_profiles import parse_file, NetworkProfiles
from k1link.fleet.network_media import filter_sdp
from k1link.fleet.rover_control import RoverControl
def document():
return dict(schema='missioncore.wireguard-connect/v1',server_id='wg_'+'1'*32,endpoint='https://vps.example.com:19444',vpn_endpoint='vps.example.com:51830',fingerprint='a'*64,server_public_key=base64.b64encode(b'1'*32).decode(),subnet='10.203.45.0/24',bootstrap=secrets.token_urlsafe(32),expires_at=int(time.time())+3600,capacity=50)
@pytest.mark.parametrize('change',[{'subnet':'0.0.0.0/0'},{'subnet':'192.168.1.0/24'},{'endpoint':'http://vps.example.com:19444'},{'vpn_endpoint':'other.example.com:51830'},{'capacity':-1},{'private_key':'secret'},{'endpoint':'https://vps.example.com:19444/path'}])
def test_import_rejects_unbounded_or_inconsistent_profile(change):
with pytest.raises(ValueError): parse_file(json.dumps({**document(),**change}))
def test_profile_is_shared_and_public_projection_has_no_credentials(tmp_path):
fleet=SimpleNamespace(root=tmp_path,trust=SimpleNamespace(core_id='core_test'))
profiles=NetworkProfiles(fleet); row={**document(), 'name':'Fleet', 'state':'ready','token':secrets.token_urlsafe(32)}
profiles.profiles[row['server_id']]=row;profiles.save()
reopened=NetworkProfiles(fleet)
assert 'capacity' not in reopened.listing()[0]
assert not {'token','bootstrap','private_key'} & reopened.listing()[0].keys()
assert reopened.profiles[row['server_id']]['token']==row['token']
def test_media_admits_only_selected_peer_and_never_falls_back_to_tailnet():
sdp='v=0\r\nc=IN IP4 100.64.1.2\r\na=candidate:1 1 udp 100 100.64.1.2 4567 typ host\r\na=candidate:2 1 udp 90 10.203.45.2 4568 typ host\r\n'
result=filter_sdp(sdp,'10.203.45.2')
assert '100.64.' not in result and '10.203.45.2' in result
with pytest.raises(ValueError):filter_sdp(sdp,'10.203.45.3')
def test_network_change_never_arms_or_replays_motion():
control=RoverControl();control.network_change('node',True)
with pytest.raises(ValueError,match='переключения'): control.arm('node',{'standstill_confirmed':True,'current_a':30,'max_erpm':1000})
assert not control.view('node')['controlling']
control.network_change('node',False)
assert not control.view('node')['controlling']
def helper_module():
path=Path(__file__).parents[2]/'apps/wireguard-client/helper.py'
spec=importlib.util.spec_from_file_location('test_wireguard_helper',path); module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module);return module
def test_helper_can_rollback_after_confirmation_and_process_restart(tmp_path,monkeypatch):
module=helper_module();manager=module.Manager(tmp_path);identity='wg_'+'1'*32
manager.profiles[identity]={'private_key':'private','public_key':'public','config':{'old':True},'pending':None,'interface':None}
monkeypatch.setattr(module,'validate',lambda c:None)
monkeypatch.setattr(manager,'apply',lambda row,c:row.update(config=c))
manager.dispatch({'action':'stage','server_id':identity,'operation_id':'2'*32,'config':{'server_id':identity}})
manager.dispatch({'action':'confirm','server_id':identity,'operation_id':'2'*32})
restored=module.Manager(tmp_path);monkeypatch.setattr(restored,'apply',lambda row,c:row.update(config=c))
restored.dispatch({'action':'rollback','server_id':identity,'operation_id':'2'*32})
assert restored.profiles[identity]['config']=={'old':True}
def test_revocation_is_durable_per_peer_and_does_not_touch_other_boards(tmp_path, monkeypatch):
import threading
fleet=SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'), stop=threading.Event())
profiles=NetworkProfiles(fleet); row={**document(),'name':'Fleet','state':'ready','status':{'peers':[{'id':'node_1','kind':'node'},{'id':'node_2','kind':'node'}]}}
profiles.profiles[row['server_id']]=row;profiles.save();profiles.revoke_node('node_1')
profiles=NetworkProfiles(fleet);calls=[]
monkeypatch.setattr(profiles,'call',lambda row,method,path: calls.append((method,path)) or {'peers':[{'id':'node_2','kind':'node'}]})
monkeypatch.setattr(profiles,'sync_operator',lambda row,status:None)
profiles.reconcile()
assert calls==[('DELETE','/v1/peers/node_1')]
assert profiles.profiles[row['server_id']]['revocations']==[]
def test_migration_adds_new_endpoint_and_only_retires_owned_previous_route(tmp_path, monkeypatch):
module=helper_module(); monkeypatch.setattr(module,'DARWIN',True)
manager=module.Manager(tmp_path);calls=[]
old={'endpoint':'8.8.8.8','gateway':'192.168.68.1','source':'192.168.68.54','interface':'en0'}
row={'host_route':old,'config':{'old':True}}
manager.profiles['fleet']=row
def run(*args,**kwargs):
calls.append(args)
if args[1:]==('getoption','en0','router'): data='192.168.68.1'
elif args[1:]==('getifaddr','en0'): data='192.168.68.54'
elif args[1:4]==('-n','get','8.8.8.8'): data='flags: <UP,HOST,STATIC>\ngateway: 192.168.68.1\ninterface: en0\n'
else: data='flags: <UP,GATEWAY>\ngateway: 192.168.68.1\ninterface: en0\n'
return SimpleNamespace(stdout=data.encode(),returncode=0)
monkeypatch.setattr(module,'run',run)
manager.physical_route({'interface':'en0'},'1.1.1.1',row)
assert ('/sbin/route','-n','add','-host','1.1.1.1','192.168.68.1','-ifa','192.168.68.54') in calls
assert not any(x[2:4]==('change','-host') for x in calls)
manager.retire_physical_routes(row)
assert ('/sbin/route','-n','delete','-host','8.8.8.8','192.168.68.1') in calls
assert list(row['host_routes'])==['1.1.1.1']
def test_migration_never_replaces_foreign_static_destination(tmp_path,monkeypatch):
module=helper_module();monkeypatch.setattr(module,'DARWIN',True)
manager=module.Manager(tmp_path)
def run(*args,**kwargs):
if args[1]=='getoption': data='192.168.68.1'
elif args[1]=='getifaddr': data='192.168.68.54'
else: data='flags: <UP,HOST,STATIC>\ngateway: 100.64.0.1\ninterface: utun9'
return SimpleNamespace(stdout=data.encode(),returncode=0)
monkeypatch.setattr(module,'run',run)
with pytest.raises(ValueError,match='conflicts'):
manager.physical_route({'interface':'en0'},'1.1.1.1',{'host_route':{'endpoint':'8.8.8.8'}})
def test_failed_udp_probe_rolls_back_and_never_publishes_ready_profile(tmp_path,monkeypatch):
import threading
from k1link.fleet import network_client
fleet=SimpleNamespace(root=tmp_path,lock=threading.RLock(),trust=SimpleNamespace(core_id='core_test'))
profiles=NetworkProfiles(fleet);row={**document(),'name':'Fleet','state':'pending'}
profiles.profiles[row['server_id']]=row;calls=[]
monkeypatch.setattr(profiles,'operator_config',lambda row,status: {'server_id':row['server_id'],'address':'10.203.45.2'})
monkeypatch.setattr(network_client,'request',lambda action,*args,**kwargs: calls.append(action))
def fail(config):raise ValueError('UDP unavailable')
monkeypatch.setattr(network_client,'verify_tunnel',fail)
with pytest.raises(ValueError,match='UDP unavailable'):profiles.sync_operator(row,{'peers':[]})
assert calls==['stage','rollback']
assert profiles.profiles[row['server_id']]['state']=='pending'
def test_browser_mdns_offer_uses_only_nodes_wireguard_answer_without_resolving_lan():
sdp='v=0\r\nc=IN IP4 0.0.0.0\r\na=candidate:1 1 udp 100 browser-123.local 4567 typ host\r\na=candidate:2 1 udp 90 100.64.1.2 4568 typ host\r\na=end-of-candidates\r\n'
result=filter_sdp(sdp,'10.203.45.2',browser_offer=True)
assert 'a=candidate:' not in result and '.local' not in result and '100.64.' not in result
assert 'a=end-of-candidates' not in result
with pytest.raises(ValueError):filter_sdp(sdp,'10.203.45.3')
def test_legacy_quota_is_ignored_and_new_connection_file_has_no_quota():
old = document()
assert 'capacity' not in parse_file(json.dumps(old))
old.pop('capacity')
assert parse_file(json.dumps(old)) == old
def test_core_accepts_more_than_fifty_routes(monkeypatch):
module = helper_module()
monkeypatch.setattr(module.socket, 'getaddrinfo', lambda *a: [(2,1,6,'',('8.8.8.8',51830))])
config = dict(server_id='wg_'+'1'*32, address='10.203.45.2', subnet='10.203.45.0/24', server_public_key=base64.b64encode(b'1'*32).decode(), endpoint='vps.example.com:51830', role='core', allowed_ips=['10.203.45.1/32']+[f'10.203.45.{n}/32' for n in range(3,83)])
module.validate(config)
config['role']='node';config['address']='10.203.45.83'
with pytest.raises(ValueError, match='only its Core'):
module.validate(config)
+98
View File
@@ -148,6 +148,41 @@ def test_recovery_only_uses_previously_reported_tailnet_addresses():
) == ["100.64.20.4"]
def test_underlay_changes_preserve_pairing_and_tailnet_recovery(setup):
from k1link.fleet.recovery import node_addresses
fleet, _, _, _ = setup
public, _ = create(setup)
fleet.advance(public["id"])
original = fleet.find(public["id"])
certificate = cert(original)
channel = {"core_endpoint": "https://100.64.20.5:8782", "endpoint_revision": 1}
# The inventory can change interface, subnet and transport without
# replacing the authenticated Node or issuing another invitation.
for interface, address in [
("wlan0", "192.168.20.4/24"),
("wlan1", "10.23.7.9/24"),
("wwan0", "172.21.8.3/28"),
("eth0", "192.168.93.7/24"),
]:
payload = {**heartbeat(original), **channel}
payload["host"]["networks"] = [
{"name": interface, "up": True, "addresses": [address]},
{"name": "tailscale0", "up": True, "addresses": ["100.64.20.4/32"]},
]
assert fleet.receive(certificate, "/v1/node/heartbeat", payload,
address="100.64.20.5")[0] == 200
current = fleet.find(public["id"])
assert current["id"] == original["id"]
assert current["node_id"] == original["node_id"]
assert current["binding"]["binding_id"] == original["binding"]["binding_id"]
assert current["binding"]["client_pem"] == original["binding"]["client_pem"]
assert current["inventory"]["networks"][0]["addresses"] == [address]
assert node_addresses(current) == ["100.64.20.4"]
assert fleet.public(current)["connectivity"] == "online"
assert len(fleet.rows()) == 1
def test_recovery_client_leaf_is_distinct_from_issuer_with_same_pinned_key(setup):
from cryptography.x509.oid import ExtendedKeyUsageOID
@@ -597,3 +632,66 @@ def test_uninitialized_x4_can_be_prepared_remotely_with_instance_progress(setup)
assert fleet.receive(cert(row), "/v1/node/heartbeat", inventory)[0] == 200
assert sensors.operation(fleet, row["id"], command["operation_id"])["preparation"] == progress
assert fleet.find(row["id"])["sensor_state"]["preparations"] == [progress]
def liveness(row):
value = heartbeat(row)
del value["host"]
del value["devices"]
return value
def test_liveness_keeps_connection_without_refreshing_inventory_or_authority(setup, monkeypatch):
fleet, _, _, _ = setup
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
assert fleet.receive(cert(row), "/v1/node/heartbeat", heartbeat(row))[0] == 200
row = fleet.find(public["id"])
original = json.dumps(row, sort_keys=True)
now = time.time()
monkeypatch.setattr("k1link.fleet.registry.time.time", lambda: now+25)
assert fleet.public(row)["connectivity"] == "offline"
assert fleet.receive(cert(row), "/v1/node/liveness", liveness(row)) == (
200, {"ok": True, "heartbeat_encoding": "gzip"})
view = fleet.public(fleet.find(public["id"]))
assert view["connectivity"] == "online"
assert view["inventory_fresh"] is False
assert view["last_seen"] == row["last_seen"]
assert view["link_last_seen"] == now+25
assert json.dumps(fleet.find(public["id"]), sort_keys=True) == original
assert fleet.monitor.query(row["node_id"])["available"] is False
monkeypatch.setattr("k1link.fleet.registry.time.time", lambda: now+46)
assert fleet.public(row)["connectivity"] == "offline"
def test_liveness_rejects_wrong_binding_endpoint_and_heavy_payload(setup):
fleet, _, _, _ = setup
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
body = liveness(row)
assert fleet.receive(cert(row), "/v1/node/liveness", {**body, "binding_id":"wrong"})[0] == 410
for extra in [{"host":{}}, {"sensor_results":[]}, {"command":{}},
{"core_endpoint":"https://100.64.20.5:8782", "endpoint_revision":1}]:
status, _ = fleet.receive(
cert(row), "/v1/node/liveness", {**body, **extra}, address="192.168.20.5")
assert status == 400
assert fleet.presence == {}
fleet.revoke(public["id"])
assert fleet.receive(cert(row), "/v1/node/liveness", body)[0] == 410
def test_liveness_restarted_node_does_not_freshen_old_device_sessions(setup):
fleet, _, _, _ = setup
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
assert fleet.receive(cert(row), "/v1/node/heartbeat", heartbeat(row))[0] == 200
row = fleet.find(public["id"])
assert fleet.public(row)["inventory_fresh"] is True
body = liveness(row)
body["execution_binding"]["agent_instance_id"] = "agent_restarted"
assert fleet.receive(cert(row), "/v1/node/liveness", body)[0] == 200
assert fleet.public(row)["inventory_fresh"] is False
assert fleet.find(public["id"])["runtime"]["agent_instance_id"] == "agent_test"
+308
View File
@@ -0,0 +1,308 @@
"""Control remains responsive during durable writes, without stale authority."""
import sqlite3
import threading
import time
from concurrent.futures import ThreadPoolExecutor
import pytest
from fastapi import Response
from test_pairing import cert, create, heartbeat, setup # noqa: F401
from test_replacement import attach, candidate
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.trust import SCHEMA
from k1link.web.rover_api import rover_arm, rover_command, rover_state
@pytest.fixture
def paired(setup): # noqa: F811 — imported pytest fixture
fleet = setup[0]
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
fleet.rover_control.clock = lambda: 100.
return fleet, row
def payload(row):
return {"schema": SCHEMA, "node_id": row["node_id"],
"binding_id": row["binding"]["binding_id"], "relay_id": "a" * 32,
"rover": {"instance": "synthetic", "state": "observing", "supported": True}}
def arm(fleet, row):
return rover_arm(row["id"], {"standstill_confirmed": True,
"current_a": 5, "max_erpm": 1000}, fleet)["session_id"]
def test_control_both_directions_does_not_wait_for_heartbeat_storage(paired, monkeypatch):
fleet, row = paired
entered, release = threading.Event(), threading.Event()
def slow_archive(*_):
entered.set()
assert release.wait(3)
monkeypatch.setattr(fleet.vesc_archive, "receive", slow_archive)
certificate = cert(row)
def control_round_trip():
# Production BFF functions and authenticated Node receive path, no motor
# or socket. A gated archive models disk blocking, not synthetic load.
assert fleet.receive(certificate, "/v1/node/rover", payload(row))[0] == 200
assert rover_state(row["id"], Response(), fleet)["fresh"]
session = arm(fleet, row)
command = {"session_id": session, "sequence": 1, "left": 0, "right": 0,
"stop": False}
assert rover_command(row["id"], command, fleet)["accepted_sequence"] == 1
status, value = fleet.receive(certificate, "/v1/node/rover-stream", payload(row))
assert status == 200 and value["command"]["sequence"] == 1
assert value["command"]["expires_mono_ms"] == pytest.approx(100400)
rover_command(row["id"], {**command, "sequence": 2, "stop": True}, fleet)
assert not rover_state(row["id"], Response(), fleet)["controlling"]
with ThreadPoolExecutor(max_workers=2) as pool:
writer = pool.submit(fleet.receive, certificate, "/v1/node/heartbeat",
{**heartbeat(row), "vesc_configurations": {}})
try:
assert entered.wait(1)
# The old shared writer lock cannot complete this until release.
pool.submit(control_round_trip).result(timeout=1)
assert not writer.done()
finally:
release.set()
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("change,status", [({"binding_id": "wrong"}, 410),
({"node_id": "wrong"}, 410), ({"schema": "wrong"}, 400),
({"endpoint_revision": True}, 400), ({"endpoint_revision": -1}, 400),
({"endpoint_revision": 1, "core_endpoint": "https://100.64.2.3:8782"}, 400)])
def test_fast_channel_keeps_authentication(paired, path, change, status):
fleet, row = paired
assert fleet.receive(cert(row), path, {**payload(row), **change})[0] == status
def test_projection_changes_only_after_commit_and_revocation_retires_lease(paired):
fleet, row = paired
body = payload(row)
certificate = cert(row)
assert fleet.receive(certificate, "/v1/node/rover", body)[0] == 200
arm(fleet, row)
row["enrollment"] = "revoked"
# Unsaved mutation cannot change a previously committed binding projection.
assert fleet.receive(certificate, "/v1/node/rover-stream", body)[1]["command"]
fleet.db.execute("CREATE TRIGGER fail_save BEFORE UPDATE ON vehicles "
"BEGIN SELECT RAISE(ABORT, 'synthetic failure'); END")
with pytest.raises(sqlite3.IntegrityError):
fleet.save(row)
assert fleet.receive(certificate, "/v1/node/rover-stream", body)[0] == 200
fleet.db.execute("DROP TRIGGER fail_save")
fleet.save(row)
assert fleet.receive(certificate, "/v1/node/rover-stream", body)[0] == 410
assert not fleet.rover_control.view(row["node_id"])["controlling"]
assert not fleet.rover_control.view(row["node_id"])["fresh"]
with pytest.raises(ValueError, match="не привязан"):
fleet.rover_channel.operator(row["id"], "arm", {})
def test_certificate_rotation_and_endpoint_revision_are_published(paired, setup): # noqa: F811
fleet, row = paired
body, old_cert = payload(row), cert(row)
row["certificate_previous"] = {"pem": row["binding"]["client_pem"],
"until": time.time() + 60}
row["binding"]["client_pem"] = fleet.trust.leaf(row["node_id"], setup[2].public_key())
row["binding"]["endpoint_revision"] = 2
fleet.save(row)
path = "/v1/node/rover-stream"
assert fleet.receive(old_cert, path, body)[0] == 409
body["endpoint_revision"] = 2
assert fleet.receive(old_cert, path, body)[0] == 200
row["certificate_previous"]["until"] = 0
fleet.save(row)
assert fleet.receive(old_cert, path, body)[0] == 403
assert fleet.receive(cert(row), path, body)[0] == 200
def test_startup_loads_bindings_but_never_restores_control(paired):
fleet, row = paired
fleet.receive(cert(row), "/v1/node/rover", payload(row))
arm(fleet, row)
reopened = FleetRegistry(fleet.root)
try:
assert reopened.rover_channel.operator(row["id"], "view") == {
"fresh": False, "controlling": False, "snapshot": {}}
assert reopened.receive(cert(row), "/v1/node/rover", payload(row))[0] == 200
finally:
reopened.close()
def test_replacement_removes_old_node_and_cannot_race_an_arm(paired, monkeypatch):
fleet, row = paired
fleet.receive(cert(row), "/v1/node/rover", payload(row))
preview = candidate(fleet, monkeypatch)
entered, release, attempted = threading.Event(), threading.Event(), threading.Event()
from k1link.fleet import replacement
original = replacement.check_replacement
def gated_check(*args):
original(*args)
entered.set()
assert release.wait(3)
def concurrent_arm():
attempted.set()
with pytest.raises(ValueError, match="не привязан"):
fleet.rover_channel.operator(row["id"], "arm", {})
monkeypatch.setattr(replacement, "check_replacement", gated_check)
with ThreadPoolExecutor(max_workers=2) as pool:
replacing = pool.submit(attach, fleet, row, preview)
try:
assert entered.wait(1)
arming = pool.submit(concurrent_arm)
assert attempted.wait(1)
assert not arming.done()
finally:
release.set()
replacing.result(timeout=2)
arming.result(timeout=2)
assert fleet.receive(cert(row), "/v1/node/rover-stream", payload(row))[0] == 410
assert not fleet.rover_control.view(row["node_id"])["fresh"]
def test_link_probe_never_refreshes_telemetry_or_control(paired):
fleet, row = paired
certificate = cert(row)
body = payload(row)
probe = {k: v for k, v in body.items() if k != "rover"}
status, reply = fleet.receive(certificate, "/v1/node/rover-link", probe)
assert status == 200 and reply["connected"] and reply["sample_clock_v1"]
assert reply["control_clock"]["instance"] == fleet.rover_control.clock_id
assert not fleet.rover_control.boards
fleet.receive(certificate, "/v1/node/rover", body)
arm(fleet, row)
board = fleet.rover_control.boards[row["node_id"]]
seen, deadline = board["seen"], board["session"]["until"]
fleet.rover_control.clock = lambda: 102.
status, reply = fleet.receive(certificate, "/v1/node/rover-link", probe)
assert status == 200 and reply["connected"] and reply["sample_clock_v1"]
assert reply["control_clock"]["instance"] == fleet.rover_control.clock_id
assert board["seen"] == seen
assert board["session"]["until"] == deadline
assert fleet.receive(certificate, "/v1/node/rover-link", body)[0] == 400
view = fleet.rover_control.view(row["node_id"])
assert not view["fresh"] and not view["controlling"] and view["snapshot"] == {}
row["enrollment"] = "revoked"
fleet.save(row)
assert fleet.receive(certificate, "/v1/node/rover-link", probe)[0] == 410
@pytest.mark.parametrize("phase", ["ingest", "desired"])
def test_slow_dev_ingest_does_not_hold_authenticated_control_channel(paired, monkeypatch, phase):
fleet, row = paired
certificate, body = cert(row), payload(row)
fleet.receive(certificate, "/v1/node/rover", body)
diagnostics = fleet.rover_control.diagnostics(row["node_id"], row["id"])
entered, release = threading.Event(), threading.Event()
original = getattr(diagnostics, phase)
def gated(*args, **kwargs):
if phase == "ingest" and args[0] is None:
return original(*args, **kwargs)
entered.set()
assert release.wait(3)
return original(*args, **kwargs)
monkeypatch.setattr(diagnostics, phase, gated)
def control_round_trip():
# Real channel entry points with a synthetic paired board. No sockets
# or hardware: DEV is parked, rather than generating load on the Mac.
assert fleet.receive(certificate, "/v1/node/rover",
{**body, "diagnostic_lane_v1": True})[0] == 200
assert rover_state(row["id"], Response(), fleet)["fresh"]
session = arm(fleet, row)
command = {"session_id": session, "sequence": 1, "left": 0, "right": 0,
"stop": False}
rover_command(row["id"], command, fleet)
status, value = fleet.receive(certificate, "/v1/node/rover-stream", body)
assert status == 200 and value["command"]["sequence"] == 1
rover_command(row["id"], {**command, "sequence": 2, "stop": True}, fleet)
with ThreadPoolExecutor(max_workers=2) as pool:
optional = pool.submit(fleet.receive, certificate, "/v1/node/rover-diagnostics",
{**body, "diagnostics": {}})
try:
assert entered.wait(1)
pool.submit(control_round_trip).result(timeout=1)
assert not optional.done()
finally:
release.set()
assert optional.result(timeout=2)[0] == 200
def test_inflight_dev_cannot_cross_revocation_or_recreate_board(paired, monkeypatch):
fleet, row = paired
certificate, body = cert(row), payload(row)
fleet.receive(certificate, "/v1/node/rover", body)
diagnostics = fleet.rover_control.diagnostics(row["node_id"], row["id"])
entered, release = threading.Event(), threading.Event()
original = diagnostics.ingest
def gated_ingest(packet):
entered.set()
assert release.wait(3)
original(packet)
monkeypatch.setattr(diagnostics, "ingest", gated_ingest)
def revoke():
row["enrollment"] = "revoked"
fleet.save(row)
with ThreadPoolExecutor(max_workers=2) as pool:
optional = pool.submit(fleet.receive, certificate, "/v1/node/rover-diagnostics", body)
try:
assert entered.wait(1)
pool.submit(revoke).result(timeout=1)
assert row["node_id"] not in fleet.rover_control.boards
finally:
release.set()
assert optional.result(timeout=2)[0] == 410
assert row["node_id"] not in fleet.rover_control.boards
def test_telemetry_dispatch_timing_is_dev_only_and_has_no_authority(paired):
fleet, row = paired
body, certificate = payload(row), cert(row)
fleet.receive(certificate, "/v1/node/rover", body)
diagnostics = fleet.rover_control.diagnostics(row["node_id"], row["id"])
assert diagnostics.trace.sequence == 0
diagnostics.set_enabled(True)
status, reply = fleet.receive(certificate, "/v1/node/rover", body)
assert status == 200
events = diagnostics.desired()["core_events"]
timing = [e for e in events if e["event"] == "node_telemetry_handled"]
assert len(timing) == 1 and timing[0]["dispatch_max_ms"] >= 0
assert timing[0]["exchanges"] == 1
assert timing[0]["reply_mono_ms"] == reply["control_clock"]["monotonic_ms"]
assert not {"binding_id", "certificate", "node_id", "rover"} & timing[0].keys()
for _ in range(10):
fleet.rover_control.record_telemetry_timing(row["node_id"], 25., 100000.)
assert diagnostics.trace.sequence == 2 # start + first report, not ten more rows
fleet.rover_control.clock = lambda: 101.
fleet.rover_control.record_telemetry_timing(row["node_id"], 3., 101000.)
latest = diagnostics.desired()["core_events"][-1]
assert latest["exchanges"] == 11 and latest["dispatch_max_ms"] == 25.
diagnostics.set_enabled(False)
previous = diagnostics.trace.sequence
fleet.receive(certificate, "/v1/node/rover", body)
assert diagnostics.trace.sequence == previous
# Timing itself cannot create a forgotten board, even if it arrives after
# revocation or an old request finishes while a new binding is pending.
fleet.rover_control.forget(row["node_id"])
fleet.rover_control.record_telemetry_timing(row["node_id"], 10., 100000.)
assert row["node_id"] not in fleet.rover_control.boards
+160 -1
View File
@@ -11,6 +11,21 @@ def hub():
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}
@@ -22,6 +37,19 @@ def test_expired_browser_cannot_be_revived_by_late_packet(hub):
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)
@@ -32,11 +60,21 @@ def test_sequence_stop_and_single_owner(hub):
with pytest.raises(ValueError):h.command('node',cmd(id,4))
assert exchange(h)['command'] is None
@pytest.mark.parametrize('snapshot',[{'state':'receiver'},{'state':'fault'},{'instance':'new-driver'}])
@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))
@@ -113,3 +151,124 @@ def test_intent_wait_wakes_on_update_and_does_not_miss_prior_update(hub):
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
+123
View File
@@ -0,0 +1,123 @@
"""Authentication, ordering and bounded latest-state framing; synthetic keys."""
import pytest
from k1link.fleet.rover_datagram import MAX_COUNTER, DatagramCipher
def test_authentication_replay_reorder_direction_and_counter_bounds():
channel, key = bytes.fromhex('11' * 16), bytes.fromhex('22' * 32)
tx, rx = DatagramCipher(channel, key), DatagramCipher(channel, key)
old, fresh = tx.seal({}), tx.seal({'fresh': True})
corrupt = fresh[:-1] + bytes([fresh[-1] ^ 1])
assert rx.open(corrupt) is None
assert rx.open(fresh) == (2, {'fresh': True})
for packet in (old, fresh, fresh + b'x', fresh[:20]):
assert rx.open(packet) is None
assert DatagramCipher(channel, bytes.fromhex('33' * 32)).open(fresh) is None
tx.sent = MAX_COUNTER
with pytest.raises(ValueError):
tx.seal({})
with pytest.raises(ValueError):
rx.seal({'data': 'x' * 1200})
def test_public_interoperability_vector():
cipher = DatagramCipher(bytes.fromhex('11' * 16), bytes.fromhex('22' * 32))
assert cipher.seal({}).hex() == (
'4d435231111111111111111111111111111111110000000000000001'
'08b7c9b2eb8c526f9dc03ac92264617fd09b')
def test_server_rechecks_authority_and_never_answers_forged_or_replayed_probe():
import socket
import time
from types import SimpleNamespace
from k1link.fleet.rover_datagram import RoverDatagramServer
authorized, calls, traces = [True], [], []
def receive(cert, path, value, *, address):
calls.append((cert, path, value, address))
if not authorized[0]:
return 410, {}
return 200, {'watch': True, 'command': None,
'control_clock': {'instance': 'a' * 32, 'monotonic_ms': 10000}}
registry = SimpleNamespace(receive=receive, rover_channel=SimpleNamespace(same_generation=lambda _: True), rover_control=SimpleNamespace(
_clock=lambda: {'instance': 'a' * 32, 'monotonic_ms': 10000},
stream_trace=lambda _: SimpleNamespace(
add=lambda event, **data: traces.append((event, data))),
intent_changed=lambda *_: False))
server = RoverDatagramServer('127.0.0.1', registry, port=0)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(.2)
try:
status, grant = server.open(
b'authenticated-fixture-cert', {'node_id': 'fixture', 'relay_id': 'b' * 32})
assert status == 200
address = ('127.0.0.1', grant['port'])
channel = bytes.fromhex(grant['channel'])
tx = DatagramCipher(channel, bytes.fromhex(grant['send_key']))
rx = DatagramCipher(channel, bytes.fromhex(grant['receive_key']))
probe = tx.seal({})
client.sendto(probe[:-1] + bytes([probe[-1] ^ 1]), address)
with pytest.raises(TimeoutError):
client.recv(1201)
assert not calls
client.sendto(probe, address)
packet, _ = client.recvfrom(1201)
_, frame = rx.open(packet)
assert frame['probe'] == 1 and frame['reply']['command'] is None
assert len(packet) <= 1200
with server.lock:
last_probe = server.channels[channel]['last_probe']
client.sendto(probe, address)
time.sleep(.025)
with server.lock:
assert server.channels[channel]['last_probe'] == last_probe
authorized[0] = False
time.sleep(.1)
with server.lock:
assert channel not in server.channels
assert len(calls) >= 2
assert traces and all(event == "datagram_sent" for event, _ in traces)
for _, row in traces:
phases = [row[key] for key in ("registry_ms", "encrypt_ms", "socket_ms")]
assert all(value >= 0 for value in phases)
assert sum(phases) == pytest.approx(row["dispatch_ms"])
assert "authenticated-fixture-cert" not in str(row)
assert all(call[0] == b'authenticated-fixture-cert' and
call[1] == '/v1/node/rover-stream' for call in calls)
finally:
client.close()
server.close()
assert not server.thread.is_alive()
@pytest.mark.parametrize("enabled", [False, True])
def test_transport_listener_owns_datagram_lifecycle(monkeypatch, enabled):
from http.server import ThreadingHTTPServer
from types import SimpleNamespace
from k1link.fleet import transport
from k1link.fleet.rover_datagram import RoverDatagramServer
# Only addresses use ephemeral test ports. Exercise production ownership
# of both sockets and the datagram worker, including disabled compatibility.
initialize = ThreadingHTTPServer.__init__
monkeypatch.setattr(ThreadingHTTPServer, "__init__", lambda self, addr, handler:
initialize(self, (addr[0], 0), handler))
monkeypatch.setattr(transport, "QUALIFIED", enabled)
monkeypatch.setattr(transport, "RoverDatagramServer", lambda address, registry:
RoverDatagramServer(address, registry, port=0))
registry = SimpleNamespace(trust=SimpleNamespace(server_context=lambda _: None))
server = transport.NodeChannelServer("127.0.0.1", registry)
datagrams = server.datagrams
try:
assert (datagrams is not None) == enabled
if enabled:
assert datagrams.thread.is_alive() and datagrams.socket.fileno() >= 0
finally:
server.server_close()
assert server.socket.fileno() == -1
if enabled:
assert not datagrams.thread.is_alive() and datagrams.socket.fileno() == -1
+179
View File
@@ -0,0 +1,179 @@
"""Real committed pairing checks on every datagram frame, synthetic identities."""
import socket
import time
import pytest
from test_pairing import cert, create, setup # noqa: F401
from k1link.fleet.rover_datagram import DatagramCipher, RoverDatagramServer
from k1link.fleet.trust import SCHEMA
@pytest.mark.parametrize("change", ["revocation", "certificate", "endpoint"])
def test_replacement_destroys_old_channel_and_committed_auth_change_closes_new(setup, change): # noqa: F811
fleet, _, key, _ = setup
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
body = {"schema": SCHEMA, "node_id": row["node_id"],
"binding_id": row["binding"]["binding_id"], "relay_id": "a" * 32}
fleet.rover_control.view(row["node_id"])
certificate = cert(row)
server = RoverDatagramServer("127.0.0.1", fleet, port=0)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(.2)
address = server.socket.getsockname()
try:
status, first = server.open(certificate, body)
assert status == 200
old = DatagramCipher(bytes.fromhex(first["channel"]), bytes.fromhex(first["send_key"]))
client.sendto(old.seal({}), address)
client.recv(1201)
status, second = server.open(certificate, body)
assert status == 200
assert all(first[k] != second[k] for k in ("channel", "send_key", "receive_key"))
with server.lock:
assert len(server.channels) == 1
assert bytes.fromhex(first["channel"]) not in server.channels
# Drain only packets sent before replacement. The old generation cannot
# establish the new reply address or renew its probe lifetime.
client.settimeout(.03)
while True:
try:
client.recv(1201)
except TimeoutError:
break
client.sendto(old.seal({}), address)
with pytest.raises(TimeoutError):
client.recv(1201)
fresh = DatagramCipher(bytes.fromhex(second["channel"]), bytes.fromhex(second["send_key"]))
reply = DatagramCipher(
bytes.fromhex(second["channel"]), bytes.fromhex(second["receive_key"]))
client.settimeout(.2)
client.sendto(fresh.seal({}), address)
assert reply.open(client.recv(1201))[1]["reply"]["command"] is None
if change == "revocation":
row["enrollment"] = "revoked"
elif change == "certificate":
row["binding"]["client_pem"] = fleet.trust.leaf(row["node_id"], key.public_key())
else:
row["binding"]["endpoint_revision"] = 2
fleet.save(row)
deadline = time.monotonic() + .3
while time.monotonic() < deadline:
with server.lock:
if not server.channels:
break
time.sleep(.005)
with server.lock:
assert not server.channels
assert fleet.receive(certificate, "/v1/node/rover-stream", body)[0] in (403, 409, 410)
finally:
client.close()
server.close()
assert not server.thread.is_alive()
def test_fresh_latest_input_and_stop_bypass_pending_keepalive(setup): # noqa: F811
fleet, _, _, _ = setup
public, _ = create(setup)
fleet.advance(public['id'])
row = fleet.find(public['id'])
node = row['node_id']
base = {'schema': SCHEMA, 'node_id': node,
'binding_id': row['binding']['binding_id'], 'relay_id': 'a' * 32}
certificate = cert(row)
assert fleet.receive(certificate, '/v1/node/rover', {**base, 'rover': {
'instance': 'synthetic', 'supported': True, 'state': 'observing'}})[0] == 200
fleet.rover_control.view(node)
server = RoverDatagramServer('127.0.0.1', fleet, port=0)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(.3)
try:
_, grant = server.open(certificate, base)
channel = bytes.fromhex(grant['channel'])
tx = DatagramCipher(channel, bytes.fromhex(grant['send_key']))
rx = DatagramCipher(channel, bytes.fromhex(grant['receive_key']))
client.sendto(tx.seal({}), server.socket.getsockname())
assert rx.open(client.recv(1201))[1]['reply']['command'] is None
# Hold only the periodic deadline far enough out to avoid fragile
# millisecond timing assertions. Fresh authority must still be sampled.
with server.lock:
server.channels[channel]['next'] = time.monotonic() + 5
sid = fleet.rover_control.arm(node, {
'standstill_confirmed': True, 'current_a': 5, 'max_erpm': 1000})['session_id']
for sequence in (1, 2, 3):
fleet.rover_control.command(node, {'session_id': sid, 'sequence': sequence,
'left': 0, 'right': 0, 'stop': False})
expires = fleet.rover_control.boards[node]['session']['until'] * 1000
frame = rx.open(client.recv(1201))[1]['reply']
assert frame['command']['sequence'] == 3 # no queued older commands
assert frame['command']['expires_mono_ms'] == expires
with server.lock:
server.channels[channel]['next'] = time.monotonic() + 5
fleet.rover_control.command(node, {'session_id': sid, 'sequence': 4,
'left': 0, 'right': 0, 'stop': True})
assert rx.open(client.recv(1201))[1]['reply']['command'] is None
finally:
client.close()
server.close()
assert not server.thread.is_alive()
def test_early_fresh_send_still_rechecks_committed_binding(setup): # noqa: F811
fleet, _, _, _ = setup
public, _ = create(setup)
fleet.advance(public['id'])
row = fleet.find(public['id'])
node = row['node_id']
base = {'schema': SCHEMA, 'node_id': node,
'binding_id': row['binding']['binding_id'], 'relay_id': 'a' * 32}
certificate = cert(row)
assert fleet.receive(certificate, '/v1/node/rover', {**base, 'rover': {
'instance': 'synthetic', 'supported': True, 'state': 'observing'}})[0] == 200
fleet.rover_control.view(node)
server = RoverDatagramServer('127.0.0.1', fleet, port=0)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(.15)
try:
_, grant = server.open(certificate, base)
channel = bytes.fromhex(grant['channel'])
tx = DatagramCipher(channel, bytes.fromhex(grant['send_key']))
client.sendto(tx.seal({}), server.socket.getsockname())
client.recv(1201)
with server.lock:
server.channels[channel]['next'] = time.monotonic() + 5
fleet.rover_control.arm(node, {
'standstill_confirmed': True, 'current_a': 5, 'max_erpm': 1000})
# Commit a new endpoint revision while the new input is waiting.
row['binding']['endpoint_revision'] = 2
fleet.save(row)
assert not fleet.rover_control.view(node)['controlling']
with pytest.raises(TimeoutError):
client.recv(1201)
with server.lock:
assert not server.channels
finally:
client.close()
server.close()
def test_wake_hint_does_not_create_board_or_renew_authority():
from k1link.fleet.rover_control import RoverControl
now = [10.]
control = RoverControl(lambda: now[0])
assert not control.intent_changed('absent', 'a' * 32, None)
assert control.boards == {}
control.exchange('node', {'relay_id': 'a' * 32, 'rover': {
'instance': 'synthetic', 'supported': True, 'state': 'observing'}})
sid = control.arm('node', {
'standstill_confirmed': True, 'current_a': 5, 'max_erpm': 1000})['session_id']
deadline = control.boards['node']['session']['until']
assert control.intent_changed('node', 'a' * 32, None)
assert not control.intent_changed('node', 'b' * 32, None)
assert not control.intent_changed('node', 'a' * 32, {'id': sid, 'sequence': 0})
now[0] = deadline + .001
assert control.intent_changed('node', 'a' * 32, None)
assert control.boards['node']['session']['until'] == deadline
assert control.stream('node', 'a' * 32)['command'] is None
+154
View File
@@ -0,0 +1,154 @@
import base64
import threading
from k1link.fleet.rover_diagnostics import RoverDiagnostics
def test_capture_is_independent_of_motion_and_does_not_expire():
now=[0];d=RoverDiagnostics(lambda:now[0])
assert d.desired() is None
d.set_enabled(True);identifier=d.trace.id
now[0]=7200;assert d.desired()['enabled']
d.browser({'id':identifier,'events':[{'event':'key_down','code':'KeyQ','held':['KeyQ','secret text']}]})
sent=d.desired()['core_events'];assert len(sent)==2
assert sent[-1]['held']==['KeyQ']
d.ingest({'id':identifier,'frames':[{'record_sequence':1,'event':'sample','source':'vesc'}],
'storage':{'closed':False,'external_ack':{'core':2}}})
assert not d.desired()['core_events'] # Received VESC records cannot echo back to disk.
d.set_enabled(False);assert d.desired()['enabled'] # Flush final Core event.
d.ingest({'id':identifier,'frames':[],'storage':{'closed':False,'external_ack':{'core':3}}})
assert not d.desired()['enabled'];assert d.closing
d.ingest({'id':identifier,'frames':[],'storage':{'closed':True,'external_ack':{'core':3}}})
assert not d.closing
d.set_enabled(True);assert d.trace.id!=identifier
def test_export_reads_board_chunks_not_live_ring():
d=RoverDiagnostics(lambda:0);d.set_enabled(True)
result=[]
def read():
first=d.export.begin(d.trace.id);result.extend(d.export.stream(first))
thread=threading.Thread(target=read);thread.start()
import time
deadline=time.monotonic()+2
sent=set()
while thread.is_alive() and time.monotonic()<deadline:
request=d.export.request
if request and request['offset'] not in sent:
offset=request['offset'];sent.add(offset)
data=b'a\n' if offset==0 else b'b\n'
d.ingest({'id':d.trace.id,'frames':[],'export':{'capture_id':d.trace.id,'offset':offset,
'next':offset+2,'total_bytes':4,'data':base64.b64encode(data).decode(),'token':request['token']}})
time.sleep(.001)
thread.join(1)
assert not thread.is_alive();assert b''.join(result)==b'a\nb\n';assert not d.export.busy
def test_power_loss_after_stop_request_releases_core_and_preserves_file(tmp_path,monkeypatch):
from pathlib import Path
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2]/'plugins/vesc'))
from runtime.drive_diagnostics import DriveDiagnostics
for drain in (False,True):
root=tmp_path/str(drain)
core=RoverDiagnostics(lambda:0);core.set_enabled(True)
board=DriveDiagnostics(root)
core.ingest(board.exchange(core.desired()))
core.set_enabled(False)
if drain:
core.ingest(board.exchange(core.desired()))
assert not core.desired()['enabled']
board.log.finish();board.log.thread.join(2)
path=board.log.path;original=path.read_bytes().split(b'{"type": "session_end"')[0]
path.write_bytes(original)
restarted=DriveDiagnostics(root)
core.ingest(restarted.exchange(core.desired()))
assert not core.closing and not core.enabled
assert core.view()['node']['storage']['error']=='CaptureInterrupted'
assert core.desired()['enabled'] is False
assert path.read_bytes()==original
old=core.trace.id;core.set_enabled(True)
assert core.trace.id!=old
core.ingest(restarted.exchange(core.desired()))
assert core.enabled and restarted.active()
restarted.log.finish();restarted.log.thread.join(2)
def test_power_loss_while_recording_turns_dev_off(tmp_path,monkeypatch):
from pathlib import Path
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2]/'plugins/vesc'))
from runtime.drive_diagnostics import DriveDiagnostics
core=RoverDiagnostics(lambda:0);core.set_enabled(True)
board=DriveDiagnostics(tmp_path);core.ingest(board.exchange(core.desired()))
board.log.finish();board.log.thread.join(2)
path=board.log.path;raw=path.read_bytes().split(b'{"type": "session_end"')[0];path.write_bytes(raw)
core.ingest(DriveDiagnostics(tmp_path).exchange(core.desired()))
assert not core.enabled and not core.closing
assert not core.trace.active()
assert path.read_bytes()==raw
def test_relay_ack_is_negotiated_and_separate_from_native_cursor():
core=RoverDiagnostics(lambda:0);core.set_enabled(True)
identifier=core.trace.id
core.ingest({'id':identifier,'relay_events':[{'record_sequence':123,'event':'delivery'}],
'frames':[{'record_sequence':5,'event':'sample'}]})
assert 'relay_after' not in core.desired()
assert core.desired(relay_ack=True)['relay_after']==123
assert core.desired(relay_ack=True)['after']==5
def test_diagnostics_lane_cannot_refresh_telemetry_or_motion():
from k1link.fleet.rover_control import RoverControl
control = RoverControl()
before = control._board("synthetic")
seen, watch = before["seen"], before["watch"]
reply = control.exchange_diagnostics("synthetic", {
"rover": {"state": "driving"}, "diagnostics": None,
"command": {"left": 1}, "relay_id": "a" * 32,
})
after = control._board("synthetic")
assert after["seen"] == seen and after["watch"] == watch
assert after["snapshot"] == {} and after["session"] is None
assert set(reply) == {"diagnostics"}
def test_core_restart_recovers_closed_log_without_recording_or_new_identity():
core=RoverDiagnostics(lambda:0)
identifier='a'*32
core.ingest({'id':identifier,'active':False,'frames':[],
'storage':{'closed':True,'file':'Rover/finished.jsonl','external_ack':{'core':3}}})
assert core.trace.id==identifier
assert not core.enabled and not core.closing and not core.trace.active()
assert core.desired()['enabled'] is False
assert core.desired()['core_events']==[]
assert core.view()['node']['storage']['file']=='Rover/finished.jsonl'
def test_local_only_capture_has_no_network_rows_and_closes(tmp_path,monkeypatch):
import json
from pathlib import Path
from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2]/'plugins/vesc'))
from runtime.drive_diagnostics import DriveDiagnostics
core=RoverDiagnostics(lambda:0);core.supports_options=True
core.set_enabled(True,LOCAL_OPTIONS);board=DriveDiagnostics(tmp_path)
reply=board.exchange(core.desired());core.ingest(reply)
board.add('output_sent',value=0)
core.trace.add('operator_command',left=0)
core.browser({'id':core.trace.id,'events':[{'event':'heartbeat'}]})
assert core.desired()['core_events']==[]
assert board.exchange(core.desired())['frames']==[]
core.set_enabled(False);core.ingest(board.exchange(core.desired()))
board.log.thread.join(2)
assert board.log.closed and not board.log.error
records=[json.loads(line) for line in board.log.path.read_text().splitlines()]
assert any(row.get('event')=='output_sent' for row in records)
assert not any(row.get('source')=='core' for row in records)
assert records[0]['options']==LOCAL_OPTIONS and records[-1]['type']=='session_end'
def test_trace_direction_is_rate_bounded_including_retries():
import json
now=[0.0];core=RoverDiagnostics(lambda:now[0]);core.set_enabled(True)
for i in range(40):core.trace.add('input',padding='x'*500)
first=core.desired()['core_events'];second=core.desired()['core_events']
size=lambda rows:sum(len(json.dumps(r).encode())+2 for r in rows)
assert size(first)+size(second)<=4096
now[0]=1
assert size(core.desired()['core_events'])<=4096
+71
View File
@@ -0,0 +1,71 @@
from test_rover_socket import fixture
def test_diagnostics_has_local_operator_boundary_and_no_motion_authority(fixture):
control,client=fixture
url='/api/v1/fleet/vehicle/rover/diagnostics'
assert not client.get(url).json()['active']
result=client.post(url,json={'enabled':True})
assert result.status_code==200 and result.json()['active']
assert not control.view('node')['controlling']
assert control.stream('node','a'*32)['command'] is None
assert control.stream('node','a'*32)['watch']
assert client.post(url,json={'enabled':1}).status_code==400
assert client.post(url,json={'enabled':False},headers={'Origin':'https://foreign.invalid'}).status_code==403
assert client.post(url,json={'enabled':False}).status_code==200
def test_export_snapshot_stream_and_resume_have_no_control_authority(fixture):
import base64
import hashlib
import json
import threading
control,client=fixture
url='/api/v1/fleet/vehicle/rover/diagnostics'
client.post(url,json={'enabled':True})
diagnostics=control.diagnostics('node','vehicle')
identifier=diagnostics.trace.id
stopped=threading.Event()
def board():
while not stopped.wait(.001):
request=diagnostics.export.desired(True)
if request:
offset=request['offset'];raw=b'abcdef'[offset:offset+3]
diagnostics.export.ingest({'capture_id':identifier,'token':request['token'],
'offset':offset,'next':offset+len(raw),'total_bytes':6,
'snapshot':'b'*64,'sha256':hashlib.sha256(raw).hexdigest(),
'data':base64.b64encode(raw).decode(),'file':'test.jsonl'})
thread=threading.Thread(target=board);thread.start()
try:
result=client.get(url+'/export?format=chunks')
assert result.status_code==200
rows=[json.loads(line) for line in result.content.splitlines()]
assert [row['offset'] for row in rows]==[0,3]
assert b''.join(base64.b64decode(row['data']) for row in rows)==b'abcdef'
resumed=client.get(url+'/export',params={'format':'chunks','capture_id':identifier,
'offset':3,'total_bytes':6,'snapshot':'b'*64})
assert resumed.status_code==200 and json.loads(resumed.content)['offset']==3
assert client.get(url+'/export',params={'capture_id':'c'*32}).status_code==409
assert client.get(url+'/export?offset=3').status_code==400
assert client.get(url+'/export?format=invalid').status_code==422
assert client.get(url+'/export',headers={'Origin':'https://foreign.invalid'}).status_code==403
raw=client.get(url+'/export');assert raw.content==b'abcdef'
assert raw.headers['content-length']=='6'
assert not diagnostics.export.busy
assert not control.view('node')['controlling']
finally:
stopped.set();thread.join(1)
def test_explicit_options_require_capability_and_remain_independent_of_control(fixture):
from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS
control, client = fixture
url = '/api/v1/fleet/vehicle/rover/diagnostics'
options = dict(LOCAL_OPTIONS)
assert client.post(url, json={'enabled':True,'options':options}).status_code == 409
diagnostics = control.diagnostics('node','vehicle')
diagnostics.supports_options = True
assert client.post(url,json={'enabled':True,'options':{**options,'live_kbps':True}}).status_code == 409
value = client.post(url,json={'enabled':True,'options':options})
assert value.status_code == 200 and value.json()['options'] == options
assert not control.view('node')['controlling']
assert not diagnostics.trace.enabled
@@ -0,0 +1,102 @@
"""Stopping DEV pauses acquisition before its already-recorded tail drains."""
import json
from pathlib import Path
from k1link.fleet.rover_diagnostics import RoverDiagnostics
def test_stop_drains_tail_without_recording_more_samples(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / 'plugins/vesc'))
from runtime.drive_diagnostics import DriveDiagnostics
now=[0.0]
core = RoverDiagnostics(lambda: now[0])
board = DriveDiagnostics(tmp_path)
core.set_enabled(True)
core.ingest(board.exchange(core.desired()))
for n in range(2323):
core.trace.add('browser_heartbeat', sequence=n)
core.set_enabled(False)
stop_sequence = core.trace.sequence
try:
request = core.desired()
assert request['enabled'] is False
assert request['stop_after'] == stop_sequence
packet = board.exchange(request)
assert packet['active'] is False
assert not packet['storage']['closed']
assert not packet['frames'] # Optional live backlog cannot delay closing.
# A lost reply retries the same tail, never starts acquisition again.
board.exchange(request)
board.exchange({k: v for k, v in {**request, 'enabled': True}.items() if k != 'stop_after'})
assert not board.active() # A stale enable cannot reopen this capture.
board.add('sample_after_stop', values={'erpm': 0})
core.ingest(packet)
exchanges = 1
while board.log.external_ack.get('core', 0) < stop_sequence:
now[0]+=1
assert exchanges<300
request = core.desired()
assert request['enabled'] is False
core.ingest(board.exchange(request))
exchanges += 1
board.log.thread.join(2)
core.ingest(board.exchange(core.desired()))
assert not core.closing and not core.enabled
assert exchanges <= 200 # Rate bound advances in virtual seconds.
rows = [json.loads(line) for line in board.log.path.read_text().splitlines()]
assert rows[-1]['type'] == 'session_end'
assert rows[-1]['dropped_records'] == 0
assert not any(r.get('event') == 'sample_after_stop' for r in rows)
assert sum(r.get('event') == 'capture_stopped' for r in rows) == 1
sequences = [r['record_sequence'] for r in rows if r.get('source') == 'core']
assert sequences == list(range(1, stop_sequence + 1))
finally:
board.log.finish()
board.log.thread.join(2)
def test_stop_protocol_is_negotiated_and_legacy_still_drains():
core = RoverDiagnostics(lambda: 0)
core.set_enabled(True)
core.set_enabled(False)
assert core.desired()['enabled'] is True
assert 'stop_after' not in core.desired()
core.ingest({'id': core.trace.id, 'stop_tail_v1': True, 'frames': []})
assert core.desired()['enabled'] is False
assert core.desired()['stop_after'] == core.trace.sequence
def test_core_tail_batch_fits_node_reply_bound_even_with_unicode():
core = RoverDiagnostics(lambda: 0)
core.set_enabled(True)
for n in range(64):
core.trace.add('large', value='я' * 3000, index=n)
request = core.desired()
assert len(json.dumps({'diagnostics': request}).encode()) < 64 * 1024
assert 1 < len(request['core_events']) < 64
assert any(row.get('event')=='core_record_omitted' for row in request['core_events'])
def test_core_restart_during_drain_closes_with_explicit_gap(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / 'plugins/vesc'))
from runtime.drive_diagnostics import DriveDiagnostics
core = RoverDiagnostics(lambda: 0)
board = DriveDiagnostics(tmp_path)
core.set_enabled(True)
core.ingest(board.exchange(core.desired()))
for n in range(100):
core.trace.add('pending', index=n)
core.set_enabled(False)
packet = board.exchange(core.desired())
restarted = RoverDiagnostics(lambda: 0)
restarted.ingest(packet)
assert restarted.closing and not restarted.enabled
assert restarted.desired()['enabled'] is False
board.exchange(restarted.desired())
board.log.thread.join(2)
restarted.ingest(board.exchange(restarted.desired()))
assert not restarted.closing and board.log.closed
rows = [json.loads(line) for line in board.log.path.read_text().splitlines()]
assert any(r.get('event') == 'core_tail_interrupted' for r in rows)
assert rows[-1]['type'] == 'session_end'
+115
View File
@@ -0,0 +1,115 @@
import asyncio
import base64
import hashlib
import threading
import pytest
from k1link.fleet.rover_diagnostics_export import DiagnosticExport
def block(export, raw=b"abc", *, total=6, **updates):
request = export.request
result = {
"capture_id": export.capture,
"token": request["token"],
"offset": request["offset"],
"next": request["offset"] + len(raw),
"total_bytes": total,
"data": base64.b64encode(raw).decode(),
"sha256": hashlib.sha256(raw).hexdigest(),
"snapshot": "b" * 64,
}
return {**result, **updates}
def test_prefetch_is_one_block_and_duplicate_delivery_cannot_overwrite():
export = DiagnosticExport()
token = export.start("a" * 32)
first = block(export)
export.ingest(first)
assert export.request["offset"] == 0
assert export.take(token)["data"] == b"abc"
assert export.request["offset"] == 3
second = block(export, b"def")
export.ingest(second)
export.ingest(first)
export.ingest(block(export, b"BAD"))
assert export.take(token)["data"] == b"def"
export.finish(token)
assert not export.busy and export.chunk is None
@pytest.mark.parametrize(
"changes",
[
{"sha256": "0" * 64},
{"snapshot": "c" * 64},
{"total_bytes": 7},
{"token": "bad"},
{"offset": 0},
{"next": 2},
{"data": "@@@"},
{"data": "A" * 90000},
{"next": True},
{"sha256": None},
],
)
def test_resume_rejects_bad_blocks(changes):
export = DiagnosticExport()
export.start("a" * 32, offset=3, total=6, snapshot="b" * 64)
export.ingest(block(export, b"def", **changes))
assert export.chunk is None
export.finish()
def test_cancel_wakes_waiter_and_old_cleanup_cannot_cancel_new_save():
export = DiagnosticExport()
old = export.start("a" * 32)
errors = []
def wait():
try:
export.take(old)
except TimeoutError:
errors.append(True)
worker = threading.Thread(target=wait)
worker.start()
export.finish(old)
new = export.start("a" * 32)
export.finish(old)
worker.join(1)
assert not worker.is_alive() and errors and export.busy
assert export.request["token"] == new
export.finish(new)
def test_large_blocks_are_capability_scoped_and_legacy_still_streams():
export = DiagnosticExport()
export.start("a" * 32)
assert "chunk_bytes" not in export.desired()
assert export.desired(True)["chunk_bytes"] == 65536
row = block(export, total=3)
row.pop("sha256")
row.pop("snapshot")
export.ingest(row)
assert b"".join(export.stream(export.take())) == b"abc"
def test_async_disconnect_releases_export_while_waiting_for_board():
async def run():
export = DiagnosticExport()
token = export.start("a" * 32)
export.ingest(block(export))
first = export.take(token)
stream = export.stream_async(first, framed=True)
assert b'"sha256"' in await anext(stream)
pending = asyncio.create_task(anext(stream))
await asyncio.sleep(0.01)
pending.cancel()
with pytest.raises(asyncio.CancelledError):
await pending
assert not export.busy
asyncio.run(run())
+123
View File
@@ -0,0 +1,123 @@
"""The qualification collector may only observe and own its local capture."""
import hashlib
import importlib.util
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_rover_socket import fixture # noqa: F401
def module():
path = Path(__file__).resolve().parents[2] / "scripts/qualification/capture_rover_local.py"
spec = importlib.util.spec_from_file_location("collector_fixture", path)
value = importlib.util.module_from_spec(spec)
spec.loader.exec_module(value)
return value
def test_collector_hashes_complete_evidence_and_never_calls_control(request, tmp_path):
control, client = request.getfixturevalue("fixture")
collector, calls, now = module(), [], [0.0]
collector.time = SimpleNamespace(
monotonic=lambda: now[0], sleep=lambda dt: now.__setitem__(0, now[0] + dt)
)
def exchange(url, body=None):
path = url.removeprefix("http://127.0.0.1:8000")
calls.append((path, body))
response = client.get(path) if body is None else client.post(path, json=body)
response.raise_for_status()
return response.json()
collector.exchange = exchange
path = tmp_path / "trace.jsonl"
result = collector.collect("vehicle", path, 2)
assert result["outcome"] == "complete"
assert result["sha256"] == hashlib.sha256(path.read_bytes()).hexdigest()
rows = [json.loads(line) for line in path.read_text().splitlines()]
assert rows[0]["type"] == "session_start" and rows[-1]["type"] == "session_end"
assert rows[-1]["local_status"]["active"] is False and "frames" not in rows[-1]["local_status"]
assert not any(any(word in url for word in ("/arm", "/hold", "/command")) for url, _ in calls)
assert all(body is None or url.endswith("/diagnostics/local") for url, body in calls)
assert not control.view("node")["controlling"]
assert not control.diagnostics("node", "vehicle").enabled
def test_collector_does_not_stop_another_active_capture(request, tmp_path):
control, client = request.getfixturevalue("fixture")
collector = module()
owned = control.diagnostics("node", "vehicle").trace.local.start()["id"]
def exchange(url, body=None):
path = url.removeprefix("http://127.0.0.1:8000")
response = client.get(path) if body is None else client.post(path, json=body)
response.raise_for_status()
return response.json()
collector.exchange = exchange
result = collector.collect("vehicle", tmp_path / "failed.jsonl", 1)
assert result["outcome"] == "incomplete"
local = control.diagnostics("node", "vehicle").trace.local
assert local.id == owned and local.active()
@pytest.mark.parametrize("stale_ticks,finish", [(set(), 11), ({8, 9}, 13)])
def test_operator_tail_waits_for_fresh_idle_and_resets_on_rearm(
request, tmp_path, stale_ticks, finish,
):
_, client = request.getfixturevalue("fixture")
collector, now, mutations = module(), [0.0], []
collector.time = SimpleNamespace(
monotonic=lambda: now[0], sleep=lambda dt: now.__setitem__(0, now[0] + dt)
)
def exchange(url, body=None):
path = url.removeprefix("http://127.0.0.1:8000")
if body is not None:
mutations.append((path, body))
response = client.get(path) if body is None else client.post(path, json=body)
response.raise_for_status()
result = response.json()
if path.endswith("/rover"):
# Observe operator state only; no arm/command requests in the fixture.
result["controlling"] = 2 <= now[0] < 4 or 6 <= now[0] < 8
result["fresh"] = int(now[0]) not in stale_ticks
return result
collector.exchange = exchange
result = collector.collect("vehicle", tmp_path / "tail.jsonl", 30,
allow_operator=True, stop_after_control_idle_s=3)
assert now[0] == finish
assert result["outcome"] == "complete"
assert result["termination"] == "operator_stopped" and result["control_seen"]
assert all(path.endswith("/diagnostics/local") for path, _ in mutations)
assert mutations[-1][1]["enabled"] is False
def test_operator_tail_keeps_hard_duration_bound_without_stopping_control(request, tmp_path):
_, client = request.getfixturevalue("fixture")
collector, now, mutations = module(), [0.0], []
collector.time = SimpleNamespace(
monotonic=lambda: now[0], sleep=lambda dt: now.__setitem__(0, now[0] + dt)
)
def exchange(url, body=None):
path = url.removeprefix("http://127.0.0.1:8000")
if body is not None:
mutations.append(path)
response = client.get(path) if body is None else client.post(path, json=body)
response.raise_for_status()
result = response.json()
if path.endswith("/rover"):
result.update(controlling=True, fresh=True)
return result
collector.exchange = exchange
result = collector.collect("vehicle", tmp_path / "bounded.jsonl", 5,
allow_operator=True, stop_after_control_idle_s=3)
assert now[0] == 5
assert result["termination"] == "duration_limit" and result["control_seen"]
assert all(path.endswith("/diagnostics/local") for path in mutations)
+201
View File
@@ -0,0 +1,201 @@
"""Local evidence must not become WAN evidence or control authority."""
import io
import pytest
from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS
from test_rover_socket import connect, fixture, reply # noqa: F401
from k1link.fleet.rover_diagnostics import RoverDiagnostics
from k1link.fleet.rover_stream_timing import RoverStreamTiming
def test_local_capture_is_independent_of_disabled_dev_and_node_transport():
now = [10.0]
d = RoverDiagnostics(lambda: now[0])
capture = d.trace.local.start(duration=10)
assert not d.enabled and d.desired() is None
d.trace.add("operator_command", session_id="a" * 32, sequence=1)
out = io.BytesIO()
RoverStreamTiming(d.trace, clock=lambda: now[0]).write(
out,
b"original\n",
{"command": {"id": "a" * 32, "sequence": 1}, "control_clock": {"monotonic_ms": 10000}},
dispatch_ms=1,
wait_ms=50,
)
assert out.getvalue() == b"original\n"
rows = d.trace.local.page(capture["id"])["frames"]
assert {"operator_command", "command_stream_frame"} <= {r["event"] for r in rows}
assert d.trace.sequence == d.live.sequence == 0 and d.desired() is None
now[0] = 20.0
count = d.trace.local.sequence
d.trace.add("after_deadline")
assert not d.trace.local.active() and d.trace.local.sequence == count
assert d.trace.local.page(capture["id"])["frames"] == rows
def test_local_browser_evidence_never_changes_board_options_or_stop_tail():
d = RoverDiagnostics(lambda: 10.0)
d.supports_options = True
d.set_enabled(True, dict(LOCAL_OPTIONS))
local_id = d.trace.local.start()["id"]
assert d.browser(
{
"id": local_id,
"events": [
{"event": "request", "request_id": 7, "socket_id": "socket", "sequence": 12}
],
},
local=True,
)
assert not d.browser({"id": "f" * 32, "events": []}, local=True)
assert d.trace.local.snapshot()["frames"][-1]["request_id"] == 7
assert d.desired()["core_events"] == [] and d.trace.sequence == 0
d.set_enabled(False)
assert d.trace.local.active() and d.trace.sequence == 0
def test_local_ring_has_finite_bytes_rows_and_explicit_overwrite():
d = RoverDiagnostics(lambda: 10.0)
trace = d.trace.local
trace.MAX_BYTES, trace.MAX_ROWS = 1100, 4
identifier = trace.start()["id"]
for n in range(20):
trace.add("sample", sequence=n, text="x" * 150)
page = trace.page(identifier)
assert page["dropped"] > 0 and page["bytes"] <= 1100 and len(page["frames"]) <= 4
assert page["first_sequence"] > 1
trace.stop(identifier)
with pytest.raises(ValueError):
trace.start()
assert trace.start(previous_id=identifier)["id"] != identifier
with pytest.raises(ValueError):
trace.page(identifier)
def test_local_api_rejects_foreign_origins_wrong_generations_and_does_not_arm(request):
control, client = request.getfixturevalue("fixture")
url = "/api/v1/fleet/vehicle/rover/diagnostics/local"
assert (
client.post(
url, json={"enabled": True}, headers={"Origin": "https://foreign.invalid"}
).status_code
== 403
)
assert client.post(url, json={"enabled": 1}).status_code == 400
assert client.post(url, json={"enabled": True, "duration_s": 3601}).status_code == 409
local_id = client.post(url, json={"enabled": True, "duration_s": 10}).json()["id"]
assert client.post(url, json={"enabled": True}).status_code == 409
with connect(client) as socket:
state = socket.receive_json()
# Deliberately expired request against an in-memory fixture, no actuator.
socket.send_json(
{
"id": 37,
"action": "command",
"expires_ms": state["clock_ms"] - 1,
"body": {"session_id": "a" * 32, "sequence": 19},
}
)
value = reply(socket)
assert value["status"] == 408 and value["socket_id"] == state["socket_id"]
rows = client.get(url, params={"capture_id": local_id}).json()["frames"]
received = next(r for r in rows if r["event"] == "operator_socket_received")
assert received["request_id"] == 37 and received["sequence"] == 19
assert received["socket_id"] == state["socket_id"]
assert not control.view("node")["controlling"]
assert control.stream("node", "a" * 32)["command"] is None
assert not client.get("/api/v1/fleet/vehicle/rover/diagnostics").json()["active"]
assert client.get(url, params={"capture_id": "f" * 32}).status_code == 409
assert client.get(url, params={"capture_id": local_id, "limit": 501}).status_code == 422
assert client.post(url, json={"enabled": False, "capture_id": "f" * 32}).status_code == 409
assert client.post(url, json={"enabled": False, "capture_id": local_id}).status_code == 200
assert client.post(url + "/events", json={"id": local_id, "events": []}).json() == {
"accepted": False
}
def test_preview_metrics_are_local_only_and_explicitly_projected():
from k1link.fleet.rover_preview_evidence import preview_sample
d = RoverDiagnostics(lambda: 10.0)
d.supports_options = True
d.set_enabled(True, {**LOCAL_OPTIONS, 'core_trace': True})
identifier = d.trace.local.start()['id']
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}]}
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 'sdp' not in row['sample']
before = d.trace.sequence
with pytest.raises(ValueError):
d.browser({**body, 'id': d.trace.id})
assert d.trace.sequence == before
assert all(row['event'] != 'browser_preview' for row in d.desired()['core_events'])
for invalid in (True, float('nan'), float('inf'), -1, 10**1000, '500000'):
with pytest.raises(ValueError):
preview_sample({**sample, 'encoder_bps': invalid})
d.trace.local.stop(identifier)
assert not d.browser(body, local=True)
def test_dev_ui_options_pair_local_capture_without_wan_trace(request):
from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS
control, client = request.getfixturevalue('fixture')
url = '/api/v1/fleet/vehicle/rover/diagnostics'
d = control.diagnostics('node', 'vehicle')
body = {'enabled': True, 'options': dict(LOCAL_OPTIONS),
'local_options': {'enabled': True, 'preview': False}}
assert client.post(url, json=body).status_code == 409
assert d.trace.local.id is None
d.supports_options = True
result = client.post(url, json=body)
assert result.status_code == 200
identifier = result.json()['local_capture']['id']
assert d.local_owner == identifier
assert not d.trace.local.preview
assert not control.view('node')['controlling']
assert d.desired()['core_events'] == []
assert d.browser({'id': identifier, 'events': [{'event': 'preview', 'sample': {}}]}, local=True)
assert not any(row['event'] == 'browser_preview' for row in d.trace.local.snapshot()['frames'])
assert client.post(url, json={'enabled': False}).status_code == 200
assert not d.trace.local.active()
export = client.get(url + '/local/export', params={'capture_id': identifier})
assert export.status_code == 200
import json
rows = [json.loads(line) for line in export.text.splitlines()]
assert rows[0]['schema'] == 'missioncore.operator-capture/v1'
assert rows[0]['scope'] == 'operator_host_only'
assert rows[0]['id'] == identifier and rows[0]['active'] is False
context = next(row for row in rows if row.get('event') == 'local_capture_context')
assert context['board_capture_id'] == result.json()['id']
assert client.get(url + '/local/export', params={'capture_id': 'f' * 32}).status_code == 409
assert client.get(url + '/local/export', params={'capture_id': identifier},
headers={'Origin': 'https://foreign.invalid'}).status_code == 403
assert d.trace.local.id == identifier # Export does not clear evidence.
def test_invalid_ui_options_and_previous_capture_are_not_overwritten():
from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS
d = RoverDiagnostics(lambda: 10.)
d.supports_options = True
for invalid in ({'enabled': 1, 'preview': True}, {'enabled': True, 'preview': 1},
{'enabled': True, 'preview': True, 'unknown': 1}):
with pytest.raises(ValueError):
d.set_enabled(True, dict(LOCAL_OPTIONS), invalid)
assert not d.enabled and d.trace.local.id is None
identifier = d.trace.local.start()['id']
with pytest.raises(ValueError):
d.set_enabled(True, dict(LOCAL_OPTIONS), {'enabled': True, 'preview': True})
assert not d.enabled and d.trace.local.id == identifier
d.trace.local.stop(identifier)
with pytest.raises(ValueError):
d.set_enabled(True, dict(LOCAL_OPTIONS), {'enabled': True, 'preview': True})
assert not d.enabled and d.trace.local.id == identifier
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()
+162
View File
@@ -0,0 +1,162 @@
import copy
import pytest
from k1link.fleet.rover_control import RoverControl
def packet(hub, at=100, revision=1, details=True, **changes):
snapshot = {
"instance": "driver",
"state": "stopped",
"release_confirmed": None,
"control_active": False,
"session_id": None,
"devices": [
{
"id": "motor",
"session_id": "attachment",
"age_ms": 25,
"values": {"erpm": 0, "motor_current_a": 0.2, "fault_code": 0},
}
],
}
snapshot.update(changes)
envelope = {"revision": revision}
if details:
envelope["details"] = {
"supported": True,
"control_modes": ["rpm", "duty"],
"profile": {"revision": 2, "bindings": {}},
"devices": {"motor": {"uuid": "physical", "slot": "left.1", "label": "Left"}},
}
return {
"relay_id": "a" * 32,
"rover": snapshot,
"rover_details_v1": envelope,
"sample_clock": {"instance": hub.clock_id, "monotonic_ms": at * 1000},
}
def test_compact_metadata_preserves_every_live_value_age_and_release_truth():
now = [100.0]
hub = RoverControl(lambda: now[0])
body = packet(hub)
unchanged = copy.deepcopy(body)
hub.exchange("node", body)
assert body == unchanged
for release in (None, False, True):
now[0] += 0.1
live = packet(hub, now[0] - 0.03, details=False, release_confirmed=release)
live["rover"]["devices"][0]["values"]["erpm"] = 123
hub.exchange("node", live)
view = hub.view("node")
assert view["snapshot"]["release_confirmed"] is release
row = view["snapshot"]["devices"][0]
assert row["values"]["erpm"] == 123 and row["uuid"] == "physical"
assert row["session_id"] == "attachment" and 54 <= row["age_ms"] <= 56
assert view["snapshot"]["profile"]["revision"] == 2
assert not view["controlling"]
def test_metadata_reference_survives_delay_without_renewing_measurements():
now = [100.0]
hub = RoverControl(lambda: now[0])
hub.exchange("node", packet(hub, 99.2))
now[0] = 101.21
# A fresh sample asserts the unchanged metadata revision after a delayed
# preceding exchange. Labels/profile age must not reject fresh measurements.
hub.exchange("node", packet(hub, 101.2, details=False))
assert hub.view("node")["fresh"]
assert hub.view("node")["snapshot"]["devices"][0]["uuid"] == "physical"
now[0] = 103.3
hub.exchange("node", packet(hub, 101.3, details=False))
assert not hub.view("node")["fresh"]
assert hub.boards["node"]["seen"] == 101.3
assert not hub.view("node")["controlling"]
def test_late_full_metadata_does_not_rejuvenate_sample_or_lease():
now = [103.0]
hub = RoverControl(lambda: now[0])
hub.exchange("node", packet(hub, 100.0))
assert not hub.view("node")["fresh"]
assert hub.boards["node"]["seen"] == 100.0
with pytest.raises(ValueError, match="недоступен"):
hub.arm("node", {"standstill_confirmed": True, "current_a": 1, "max_erpm": 300})
# Latest-only cache is scoped to this relay/driver/revision, not a time
# series. A reference can recover publication, but cannot create a lease.
hub.exchange("node", packet(hub, 102.9, details=False))
assert hub.view("node")["fresh"]
assert not hub.view("node")["controlling"]
@pytest.mark.parametrize(
"change", [{"relay_id": "b" * 32}, {"revision": 2}, {"instance": "new-driver"}]
)
def test_cached_identity_cannot_cross_relay_driver_or_revision(change):
hub = RoverControl(lambda: 100.0)
hub.exchange("node", packet(hub, 99.9))
value = packet(hub, details=False)
for k, v in change.items():
if k == "revision":
value["rover_details_v1"][k] = v
elif k == "instance":
value["rover"][k] = v
else:
value[k] = v
with pytest.raises(ValueError):
hub.exchange("node", value)
assert hub.boards["node"]["seen"] == 99.9
def test_metadata_revision_changes_immediately_and_old_packet_cannot_replace_it():
hub = RoverControl(lambda: 100.0)
hub.exchange("node", packet(hub, 99.8))
updated = packet(hub, 99.9, revision=2)
updated["rover_details_v1"]["details"]["profile"]["revision"] = 3
hub.exchange("node", updated)
hub.exchange("node", packet(hub, 99.8))
assert hub.view("node")["snapshot"]["profile"]["revision"] == 3
invalid = copy.deepcopy(updated)
invalid["sample_clock"]["monotonic_ms"] = 100000
invalid["rover_details_v1"]["details"]["profile"]["revision"] = 99
with pytest.raises(ValueError):
hub.exchange("node", invalid)
@pytest.mark.parametrize(
"change", ["duplicate", "foreign", "static_override", "missing_session", "bad_revision"]
)
def test_invalid_compact_snapshot_never_publishes_or_creates_authority(change):
hub = RoverControl(lambda: 100.0)
hub.exchange("node", packet(hub, 99.9))
value = packet(hub, details=False)
row = value["rover"]["devices"][0]
if change == "duplicate":
value["rover"]["devices"].append(copy.deepcopy(row))
if change == "foreign":
row["id"] = "foreign"
if change == "static_override":
row["uuid"] = "wrong"
if change == "missing_session":
del row["session_id"]
if change == "bad_revision":
value["rover_details_v1"]["revision"] = True
with pytest.raises(ValueError):
hub.exchange("node", value)
assert hub.boards["node"]["seen"] == 99.9
assert not hub.view("node")["controlling"]
def test_legacy_full_snapshot_remains_compatible_and_invalidates_metadata_cache():
hub = RoverControl(lambda: 100.0)
hub.exchange("node", packet(hub, 99.9))
legacy = {
"relay_id": "a" * 32,
"rover": {"instance": "driver", "supported": True, "state": "stopped", "devices": []},
}
hub.exchange("node", legacy)
assert hub.view("node")["snapshot"] == legacy["rover"]
with pytest.raises(ValueError):
hub.exchange("node", packet(hub, details=False))
@@ -0,0 +1,46 @@
from datetime import UTC, datetime, timedelta
from k1link.fleet.rover_control import RoverControl
from k1link.fleet.rover_observation_evidence import ObservationEvidence
def test_receipt_time_distinguishes_missing_packets_from_old_source_samples():
now = [100.]
hub = RoverControl(lambda: now[0])
packet = {"relay_id": "a"*32, "rover": {"supported": True, "devices": []},
"sample_clock": {"instance": hub.clock_id, "monotonic_ms": 98000}}
hub.exchange("node", packet)
assert not hub.view("node")["fresh"]
value = hub.observation("node")
assert value["latest"]["received_mono_ms"] == 100000
assert value["latest"]["sample_age_at_receipt_ms"] == 2000
now[0] = 100.5
packet["sample_clock"]["monotonic_ms"] = 100400
hub.exchange("node", packet)
assert hub.view("node")["fresh"]
now[0] = 102.
assert not hub.view("node")["fresh"]
before = hub.boards["node"]["watch"]
value = hub.observation("node", "operator_socket_closed")
assert hub.boards["node"]["watch"] == before
assert value["receipts"] == 2
assert value["latest"]["received_mono_ms"] == 100500
assert [e["event"] for e in value["events"]] == [
"first_receipt", "stale", "fresh", "stale", "operator_socket_closed"]
assert hub.boards["node"]["session"] is None
assert not hub.diagnostics("node", "fixture").enabled
def test_transition_memory_is_bounded_and_daily_without_raw_samples():
day = [datetime(2026, 10, 28, tzinfo=UTC)]
evidence = ObservationEvidence(lambda: 100., lambda: day[0])
for n in range(200):
evidence.view(bool(n % 2))
assert len(evidence.snapshot()["events"]) == 64
evidence.receive(99., False, 500)
assert evidence.snapshot()["ignored_older_receipts"] == 1
assert evidence.snapshot()["latest"]["sampled_devices"] == 128
day[0] += timedelta(days=1)
assert evidence.snapshot()["events"] == []
assert evidence.snapshot()["latest"] is None
assert evidence.snapshot()["receipts"] == 0
+112
View File
@@ -0,0 +1,112 @@
"""Opt-in ordinary real Python/Go interoperability; no load or physical board."""
import json
import os
import subprocess
import threading
import time
from http.server import ThreadingHTTPServer
from pathlib import Path
import pytest
from cryptography.hazmat.primitives import serialization
from test_pairing import cert, create, setup # noqa: F401
from k1link.fleet.rover_datagram import RoverDatagramServer
from k1link.fleet.transport import NodeChannelHandler
from k1link.fleet.trust import SCHEMA, pem
pytestmark = pytest.mark.skipif(
not os.environ.get("MISSION_CORE_GO"), reason="opt-in existing Go compiler")
ROOT = Path(__file__).resolve().parents[2]
def test_paired_python_core_and_go_node_neutral_intent_then_revocation(setup, tmp_path): # noqa: F811
fleet, _, key, _ = setup
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
base = {"schema": SCHEMA, "node_id": row["node_id"],
"binding_id": row["binding"]["binding_id"], "relay_id": "a" * 32}
status, _ = fleet.receive(cert(row), "/v1/node/rover", {**base, "rover": {
"instance": "synthetic", "state": "observing", "supported": True}})
assert status == 200
fleet.rover_control.view(row["node_id"])
context = fleet.trust.server_context("192.168.20.5")
class Server(ThreadingHTTPServer):
daemon_threads = True
def get_request(self):
sock, address = super().get_request()
sock.settimeout(3)
return context.wrap_socket(sock, server_side=True), address
# Only the private-address binding is substituted with loopback. mTLS,
# certificate/binding checks, HTTP handler, control and UDP are production.
server = Server(("127.0.0.1", 0), NodeChannelHandler)
server.address, server.registry = "192.168.20.5", fleet
server.datagrams = RoverDatagramServer("127.0.0.1", fleet, port=0)
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
config = {"Endpoint": "https://127.0.0.1:" + str(server.server_port),
"CA": pem(fleet.trust.ca), "Certificate": row["binding"]["client_pem"],
"Key": key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption()).decode(),
"Base": base, "Directory": str(tmp_path)}
path = tmp_path / "synthetic-config.json"
path.write_text(json.dumps(config))
path.chmod(0o600)
overlay = tmp_path / "overlay.json"
overlay.write_text(json.dumps({"Replace": {
str(ROOT / "apps/node-agent/internal/node/worker_rover_python_interop_test.go"):
str(ROOT / "tests/qualification/rover_python_interop_test.go")}}))
env = {**os.environ, "GOCACHE": str(tmp_path / "cache"), "GOTMPDIR": str(tmp_path),
"GOPROXY": "off", "GOTOOLCHAIN": "local", "CGO_ENABLED": "0", "GOMAXPROCS": "2",
"GOMEMLIMIT": "512MiB", "MISSION_CORE_PYTHON_INTEROP": str(path)}
proc = None
try:
binary = tmp_path / "interop.test"
subprocess.run([os.environ["MISSION_CORE_GO"], "test", "-c", "-p", "1",
"-overlay="+str(overlay), "-o", str(binary), "./internal/node"],
cwd=ROOT/"apps/node-agent", env=env, capture_output=True,
check=True, timeout=90)
# Compile before the fresh test observation; compilation never renews it.
fleet.receive(cert(row), "/v1/node/rover", {**base, "rover": {
"instance": "synthetic", "state": "observing", "supported": True}})
fleet.rover_control.view(row["node_id"])
proc = subprocess.Popen([str(binary), "-test.run=^TestPythonDatagramInterop$", "-test.v"],
env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True)
def wait(name):
deadline = time.monotonic() + 2
while (not (tmp_path/name).exists()
and proc.poll() is None and time.monotonic() < deadline):
time.sleep(.005)
assert (tmp_path/name).exists(), (
name, proc.communicate(timeout=2)[0] if proc.poll() is not None else "no marker")
wait("ready")
session = fleet.rover_control.arm(row["node_id"], {
"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000})["session_id"]
for sequence in range(1, 4):
fleet.rover_control.command(row["node_id"], {"session_id": session,
"sequence": sequence, "left": 0, "right": 0, "stop": False})
wait("seen-" + str(sequence))
row["enrollment"] = "revoked"
fleet.save(row)
output, _ = proc.communicate(timeout=3)
assert proc.returncode == 0, output
assert '"retired":true' in output
print(output)
assert not fleet.rover_control.view(row["node_id"])["controlling"]
finally:
if proc is not None and proc.poll() is None:
proc.kill()
proc.wait(timeout=2)
server.shutdown()
server.server_close()
server.datagrams.close()
worker.join(timeout=2)
assert not worker.is_alive() and not server.datagrams.thread.is_alive()
@@ -0,0 +1,39 @@
import threading
from test_rover_socket import fixture as fixture
def test_runtime_snapshot_is_local_read_only_and_excludes_frame_values(fixture):
control, client = fixture
secret_value = "private-value-never-in-thread-snapshot"
url = "/api/v1/fleet/vehicle/rover/diagnostics/runtime"
result = client.get(url)
assert result.status_code == 200
assert secret_value not in result.text
assert "no-store" in result.headers["cache-control"]
data = result.json()
assert data["schema"] == "missioncore.runtime-threads/v1"
assert 0 < len(data["threads"]) <= 128
assert all(len(row["stack"]) <= 24 for row in data["threads"])
assert all(set(frame) == {"file", "function", "line"}
for row in data["threads"] for frame in row["stack"])
assert not control.view("node")["controlling"]
assert control.stream("node", "a"*32)["command"] is None
assert not client.get(url.removesuffix("/runtime")).json()["active"]
assert client.get(url, headers={"Origin": "https://foreign.invalid"}).status_code == 403
assert client.get(url.replace("vehicle/", "unknown/")).status_code == 409
def test_native_id_identifies_a_blocked_thread_without_inspecting_its_locals():
from k1link.web.rover_runtime_diagnostics import snapshot
stop = threading.Event()
worker = threading.Thread(target=stop.wait, name="runtime-diagnostic-fixture")
worker.start()
try:
row = next(row for row in snapshot()["threads"] if row["native_id"] == worker.native_id)
assert row["name"] == worker.name
assert row["stack"][0]["function"] == "wait"
finally:
stop.set()
worker.join(1)
assert not worker.is_alive()
+58
View File
@@ -0,0 +1,58 @@
import pytest
from k1link.fleet.rover_control import RoverControl
def packet(hub, observed, **snapshot):
return {"relay_id": "a"*32, "sample_clock": {"instance": hub.clock_id, "monotonic_ms": observed*1000},
"rover": {"instance": "driver", "supported": True, "state": "observing", **snapshot}}
def test_network_delay_counts_in_sample_age_and_cannot_refresh_old_data():
now = [100.]
hub = RoverControl(lambda: now[0])
hub.exchange("node", packet(hub, 99.6, devices=[{"age_ms": 50}]))
view = hub.view("node")
assert view["fresh"]
assert 449 <= view["snapshot"]["devices"][0]["age_ms"] <= 451
now[0] += .61
assert not hub.view("node")["fresh"]
hub.exchange("node", packet(hub, 99.6))
assert not hub.view("node")["fresh"]
with pytest.raises(ValueError):
hub.arm("node", {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000})
def test_late_old_relay_cannot_replace_newer_snapshot_or_session():
hub = RoverControl(lambda: 100.)
hub.exchange("node", packet(hub, 99.9, generation=2))
identifier = hub.arm("node", {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000})["session_id"]
deadline = hub.boards["node"]["session"]["until"]
old = packet(hub, 99.7, generation=1, instance="old-driver")
old["relay_id"] = "b"*32
hub.exchange("node", old)
assert hub.view("node")["snapshot"]["generation"] == 2
assert hub.boards["node"]["session"]["id"] == identifier
assert hub.boards["node"]["session"]["until"] == deadline
@pytest.mark.parametrize("clock", [None, {}, {"instance": "old", "monotonic_ms": 99000},
{"instance": "CURRENT", "monotonic_ms": True}, {"instance": "CURRENT", "monotonic_ms": float("nan")},
{"instance": "CURRENT", "monotonic_ms": 100001}, {"instance": "CURRENT", "monotonic_ms": -1}])
def test_bad_observation_clock_never_updates_state(clock):
hub = RoverControl(lambda: 100.)
body = packet(hub, 99.9)
if clock is None:clock = {"instance": hub.clock_id, "monotonic_ms": float("inf")}
if clock.get("instance") == "CURRENT":clock = {**clock, "instance": hub.clock_id}
body["sample_clock"] = clock
with pytest.raises(ValueError):hub.exchange("node", body)
assert not hub.boards
def test_source_timestamp_does_not_renew_motion_lease():
now=[100.];hub=RoverControl(lambda:now[0])
hub.exchange("node", packet(hub,99.9))
hub.arm("node", {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000})
now[0]=100.401
hub.exchange("node", packet(hub,100.3))
assert hub.view("node")["fresh"]
assert not hub.view("node")["controlling"]
+166
View File
@@ -0,0 +1,166 @@
import time
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
from k1link.fleet.rover_channel import RoverChannel
from k1link.fleet.rover_control import RoverControl
from k1link.web.rover_api import router
@pytest.fixture
def fixture():
control = RoverControl()
control.exchange("node", {"relay_id": "a"*32, "rover": {
"supported": True, "instance": "fixture", "state": "observing"}})
channel = RoverChannel(control)
channel.vehicles["vehicle"] = {"node_id": "node", "enrollment": "paired"}
app = FastAPI()
app.state.fleet = SimpleNamespace(rover_channel=channel)
app.include_router(router)
with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 12345)) as client:
yield control, client
def connect(client, origin="http://127.0.0.1:8000"):
return client.websocket_connect("ws://127.0.0.1:8000/api/v1/fleet/vehicle/rover-channel", headers={"Origin": origin})
def reply(socket):
while True:
value = socket.receive_json()
if value["type"] == "reply":
return value
def arm(socket, clock, offset=350):
socket.send_json({"id": 1, "action": "arm", "expires_ms": clock+offset,
"body": {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000}})
return reply(socket)
def test_socket_observation_and_commands_share_existing_authority(fixture):
control, client = fixture
with connect(client) as socket:
first = socket.receive_json()
assert first["value"]["fresh"]
acknowledged = arm(socket, first["clock_ms"])
assert acknowledged["state"]["controlling"]
identifier = acknowledged["value"]["session_id"]
socket.send_json({"id": 2, "action": "command", "expires_ms": first["clock_ms"]+300,
"body": {"session_id": identifier, "sequence": 1, "left": 0,
"right": 0, "stop": False}})
assert reply(socket)["value"]["accepted_sequence"] == 1
command = control.stream("node", "a"*32)["command"]
assert command["left"] == 0
assert command["expires_mono_ms"] == pytest.approx(first["clock_ms"]+300)
assert not control.view("node")["controlling"]
@pytest.mark.parametrize("offset", [-1, 10000])
def test_queued_or_overlong_request_cannot_create_a_lease(fixture, offset):
control, client = fixture
with connect(client) as socket:
first = socket.receive_json()
assert arm(socket, first["clock_ms"], offset)["status"] == 408
assert not control.view("node")["controlling"]
def test_observer_disconnect_does_not_retire_other_operator(fixture):
control, client = fixture
with connect(client) as owner:
first = owner.receive_json()
identifier = arm(owner, first["clock_ms"])["value"]["session_id"]
with connect(client) as observer:
observed = observer.receive_json()
observer.send_json({"id": 2, "action": "command", "expires_ms": observed["clock_ms"]+300,
"body": {"session_id": identifier, "sequence": 1, "left": 0,
"right": 0, "stop": True}})
assert reply(observer)["status"] == 409
assert control.view("node")["controlling"]
control.disconnect("node", "other-session")
assert control.stream("node", "a"*32)["command"]["id"] == identifier
def test_state_push_cannot_renew_motion_lease(fixture):
control, client = fixture
with connect(client) as socket:
first = socket.receive_json()
arm(socket, first["clock_ms"])
time.sleep(.42)
assert not control.view("node")["controlling"]
@pytest.mark.parametrize("origin", ["https://example.com", "null", "http://localhost:8000"])
def test_cross_origin_websocket_is_rejected_before_accept(fixture, origin):
_, client = fixture
with pytest.raises(WebSocketDisconnect) as error:
with connect(client, origin):
pass
assert error.value.code == 1008
def test_malformed_frame_cannot_invoke_control(fixture):
control, client = fixture
with connect(client) as socket:
socket.receive_json()
socket.send_json({"id": 1, "action": "arm", "body": {}, "expires_ms": "forever"})
with pytest.raises(WebSocketDisconnect):
reply(socket)
assert not control.view("node")["controlling"]
def test_live_owner_socket_holds_neutral_while_browser_js_sends_nothing(fixture):
control, client = fixture
with connect(client) as socket:
first = socket.receive_json()
identifier = arm(socket, first['clock_ms'])['value']['session_id']
socket.send_json({'id':2,'action':'hold','expires_ms':time.monotonic()*1000+350,
'body':{'session_id':identifier,'sequence':1}})
assert reply(socket)['value']['accepted_sequence'] == 1
sequences=[]
for _ in range(60):
# Synthetic board feedback stays fresh while browser JS is silent.
control.exchange('node', {'relay_id':'a'*32,'rover':{
'instance':'fixture','supported':True,'state':'ready','session_id':identifier}})
time.sleep(.1)
frame=control.stream('node','a'*32)['command']
assert frame and frame['id']==identifier
assert frame['left']==frame['right']==0
sequences.append(frame['sequence'])
assert len(set(sequences))>=40
socket.send_json({'id':3,'action':'command','expires_ms':time.monotonic()*1000+350,
'body':{'session_id':identifier,'sequence':2,'left':.5,'right':.5,'stop':False}})
assert reply(socket)['value']['accepted_sequence']==2
frame=control.stream('node','a'*32)['command']
assert frame['left']==.5 and frame['sequence']>max(sequences)
time.sleep(.42)
assert not control.view('node')['controlling'], 'native loop must not renew resumed movement'
assert not control.view('node')['controlling']
def test_observer_cannot_hold_and_owner_socket_close_retires_neutral(fixture):
control, client = fixture
with connect(client) as owner:
first=owner.receive_json();identifier=arm(owner, first['clock_ms'])['value']['session_id']
with connect(client) as observer:
observer.receive_json()
observer.send_json({'id':1,'action':'hold','expires_ms':time.monotonic()*1000+350,
'body':{'session_id':identifier,'sequence':1}})
assert reply(observer)['status']==409
owner.send_json({'id':2,'action':'hold','expires_ms':time.monotonic()*1000+350,
'body':{'session_id':identifier,'sequence':1}})
assert reply(owner)['value']['accepted_sequence']==1
assert not control.view('node')['controlling']
assert not control.maintain_neutral('node',identifier)
def test_browser_cannot_invoke_native_maintenance_directly(fixture):
_, client=fixture
with connect(client) as socket:
socket.receive_json()
socket.send_json({'id':1,'action':'maintain_neutral','expires_ms':time.monotonic()*1000+350,'body':{}})
with pytest.raises(WebSocketDisconnect):reply(socket)
+147
View File
@@ -0,0 +1,147 @@
"""Latest withdrawal survives DEV being off without adding motion authority."""
from datetime import UTC, datetime, timedelta
from unittest.mock import patch
import pytest
from test_rover_control import arm, cmd, exchange
from test_rover_control import hub as hub
from test_rover_socket import fixture as fixture
from k1link.fleet.rover_stop_evidence import CoreStopEvidence
def latest(h):
return h.diagnostics('node', 'vehicle').view()['core_stop_v1']
@pytest.mark.parametrize('trigger,reason', [
('deadline', 'input_deadline_expired'),
('disconnect', 'operator_socket_closed'),
('stop', 'operator_stop'),
('telemetry', 'telemetry_stale'),
('restart', 'driver_restarted'),
('relay', 'relay_changed'),
('stopped', 'driver_terminal'),
('fault', 'driver_terminal'),
('receiver', 'driver_terminal'),
])
def test_reason_is_retained_with_all_recorders_off(hub, trigger, reason):
h, now = hub
diagnostics = h.diagnostics('node', 'vehicle')
assert not diagnostics.enabled and not diagnostics.trace.recording()
assert latest(h) is None
identifier = arm(h)
h.command('node', cmd(identifier))
if trigger == 'deadline':
now[0] += .401
h.stream('node', 'a'*32)
elif trigger == 'disconnect':
h.disconnect('node', identifier)
elif trigger == 'stop':
h.command('node', cmd(identifier, 2, stop=True))
elif trigger == 'telemetry':
for sequence in range(2, 14):
now[0] += .09
h.command('node', cmd(identifier, sequence))
h.stream('node', 'a'*32)
elif trigger == 'restart':
exchange(h, instance='new-driver')
elif trigger == 'relay':
h.exchange('node', {'relay_id': 'b'*32, 'rover': {'instance': 'driver'}})
else:
exchange(h, state=trigger, session_id=identifier)
record = latest(h)
assert record['reason'] == reason
assert record['session_id'] == identifier
assert record['core_clock_instance'] == h.clock_id
assert record['monotonic_ms'] == now[0]*1000
assert record['remaining_ms'] <= 400 + 1e-7
assert not h.view('node')['controlling']
assert diagnostics.desired() is None, 'never transmit this record on the board lane'
# Follow-up disconnect or status polling cannot replace the first withdrawal.
h.disconnect('node', identifier)
h.stream('node', 'a'*32)
assert latest(h) == record
record['reason'] = 'mutated-client-copy'
assert latest(h)['reason'] == reason
with pytest.raises(ValueError):
h.command('node', cmd(identifier, 100))
@pytest.mark.parametrize('cause,reason', [
('stale', 'telemetry_stale'), ('unsupported', 'driver_unavailable'),
])
def test_neutral_maintenance_records_its_existing_stop_conditions(hub, cause, reason):
h, now = hub
identifier = arm(h)
h.hold('node', {'session_id': identifier, 'sequence': 1})
if cause == 'unsupported':
exchange(h, supported=False)
else:
# Current zero commands with old return telemetry isolate this guard.
for sequence in range(2, 14):
now[0] += .09
h.hold('node', {'session_id': identifier, 'sequence': sequence})
assert not h.maintain_neutral('node', identifier)
assert latest(h)['reason'] == reason
assert latest(h)['neutral_hold'] is True
def test_foreign_disconnect_and_dev_toggle_do_not_erase_latest(hub):
h, _ = hub
identifier = arm(h)
h.disconnect('node', 'another-owner')
assert latest(h) is None
h.disconnect('node', identifier)
recorded = latest(h)
diagnostics = h.diagnostics('node', 'vehicle')
diagnostics.set_enabled(True)
diagnostics.set_enabled(False)
assert latest(h) == recorded
h.forget('node')
assert latest(h) is None
def test_withdrawal_does_not_acquire_optional_export_or_diagnostics_lock(hub):
h, _ = hub
identifier = arm(h)
diagnostics = h.diagnostics('node', 'vehicle')
class Forbidden:
def __enter__(self):
raise AssertionError('optional diagnostics lock in withdrawal')
def __exit__(self, *args):
pass
with patch.object(diagnostics, 'lock', Forbidden()):
h.disconnect('node', identifier)
assert latest(h)['reason'] == 'operator_socket_closed'
@pytest.mark.parametrize('advance_seconds', [2, 86400])
def test_latest_is_bounded_expires_and_resets_each_utc_day(advance_seconds):
now, wall = [10.], [datetime(2026, 10, 26, 23, 59, 59, tzinfo=UTC)]
evidence = CoreStopEvidence(lambda: now[0], lambda: wall[0])
session = dict(id='a'*32, sequence=7, operator_sequence=3, neutral_hold=True, until=10.4)
evidence.record('telemetry_stale', session, core_instance='b'*32,
telemetry_age_ms=1234, driver_state={'unexpected': 'x'*100000})
record = evidence.snapshot()
assert record['driver_state'] is None
assert record['remaining_ms'] == pytest.approx(400)
now[0] += advance_seconds
if advance_seconds == 2:
wall[0] += timedelta(seconds=2)
assert evidence.snapshot() is None
# Expiration clears storage, even if the wall clock subsequently goes back.
wall[0] -= timedelta(days=1)
assert evidence.snapshot() is None
def test_local_api_exposes_reason_without_dev_and_preserves_origin_boundary(fixture):
control, client = fixture
url = '/api/v1/fleet/vehicle/rover/diagnostics'
assert client.get(url).json()['core_stop_v1'] is None
identifier = arm(control)
control.disconnect('node', identifier)
result = client.get(url)
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
+85
View File
@@ -0,0 +1,85 @@
"""Distinguish Core/socket stalls without changing bytes or socket failures."""
import io
import pytest
from k1link.fleet.rover_control import RoverControl
from k1link.fleet.rover_stream_timing import RoverStreamTiming
def recorder():
now = [10.]
control = RoverControl(clock=lambda: now[0])
diagnostics = control.diagnostics("node", "synthetic")
return now, diagnostics, control.stream_trace("node")
def test_disabled_capture_does_not_record_or_sample_clock():
_, diagnostics, trace = recorder()
def forbidden_clock():
raise AssertionError("Disabled capture sampled clock")
timing = RoverStreamTiming(trace, clock=forbidden_clock)
writer = io.BytesIO()
timing.write(writer, b"frame\n", {}, dispatch_ms=2, wait_ms=50)
assert writer.getvalue() == b"frame\n"
assert diagnostics.trace.sequence == 0
def test_socket_write_stall_is_distinct_from_dispatch_and_wait():
now, diagnostics, trace = recorder()
diagnostics.set_enabled(True)
timing = RoverStreamTiming(trace, clock=lambda: now[0])
writes = []
class Writer:
def write(self, raw):
writes.append(raw)
now[0] += .4
data = {"command": {"id": "synthetic", "sequence": 8},
"control_clock": {"monotonic_ms": 9999}}
timing.write(Writer(), b"one\n", data, dispatch_ms=3, wait_ms=50)
now[0] += .05
timing.write(Writer(), b"two\n", data, dispatch_ms=1, wait_ms=50)
rows = [r for r in trace.snapshot()["frames"] if r["event"] == "command_stream_frame"]
assert writes == [b"one\n", b"two\n"]
assert rows[0]["gap_ms"] is None
assert rows[0]["write_ms"] == pytest.approx(400)
assert rows[0]["dispatch_ms"] == 3
assert rows[1]["gap_ms"] == pytest.approx(450)
assert rows[1]["frame_index"] == 2
assert rows[1]["sequence"] == 8
assert rows[1]["frame_clock_ms"] == 9999
assert rows[0]["stream_id"] == rows[1]["stream_id"]
def test_write_failure_is_not_retried_and_private_error_not_recorded():
now, diagnostics, trace = recorder()
diagnostics.set_enabled(True)
failure = BrokenPipeError("private endpoint")
class Writer:
calls = 0
def write(self, _):
self.calls += 1
now[0] += .2
raise failure
writer = Writer()
with pytest.raises(BrokenPipeError) as caught:
RoverStreamTiming(trace, clock=lambda: now[0]).write(
writer, b"x\n", {}, dispatch_ms=0, wait_ms=0)
assert caught.value is failure and writer.calls == 1
row = trace.snapshot()["frames"][-1]
assert row["outcome"] == "write_error"
assert row["write_ms"] == pytest.approx(200)
assert "private" not in str(row)
def test_evidence_failure_cannot_replace_socket_failure():
class Trace:
id = "capture"
def active(self): return True
def add(self, *_args, **_kwargs): raise RuntimeError("recorder failure")
original = BrokenPipeError("socket failure")
class Writer:
def write(self, _): raise original
with pytest.raises(BrokenPipeError) as caught:
RoverStreamTiming(Trace()).write(Writer(), b"x\n", {}, dispatch_ms=0, wait_ms=0)
assert caught.value is original
+2 -1
View File
@@ -28,7 +28,8 @@ def test_stream_rechecks_binding_and_closes_when_revoked():
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.address = "127.0.0.1"
server.registry = SimpleNamespace(receive=receive, stop=threading.Event(),
rover_control=SimpleNamespace(wait_for_intent=lambda *_: time.sleep(.01)))
rover_control=SimpleNamespace(wait_for_intent=lambda *_: time.sleep(.01),
stream_trace=lambda _: None))
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
client = http.client.HTTPConnection(*server.server_address, timeout=2)
+80
View File
@@ -0,0 +1,80 @@
import asyncio
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
from k1link.web.response_compression import ResponseCompressionMiddleware
from k1link.web.runtime_http_timing import HttpTimingWindow, RuntimeHttpTimingMiddleware
def test_metadata_retains_template_not_path_query_headers_or_body():
window = HttpTimingWindow()
app = FastAPI()
app.add_middleware(ResponseCompressionMiddleware)
app.add_middleware(RuntimeHttpTimingMiddleware, window=window)
@app.post("/api/items/{item_id}")
def body(item_id: str):
return JSONResponse({"value": item_id * 300})
with TestClient(app) as client:
result = client.post("/api/items/private-path?key=private-query",
content=b"private-body", headers={"Authorization": "private-header"})
assert result.status_code == 200
assert result.json()["value"] == "private-path" * 300
assert result.headers["content-encoding"] == "gzip"
row = window.snapshot()[-1]
assert row["route"] == "/api/items/{item_id}"
assert row["bytes"] == int(result.headers["content-length"])
assert 0 <= row["response_start_ms"] <= row["duration_ms"]
assert row["complete"]
assert "private" not in str(window.snapshot())
client.get("/unknown/private-token")
assert window.snapshot()[-1]["route"] == "<other>"
def test_ram_window_is_bounded_expires_and_does_not_expose_mutable_rows():
now = [0.0]
window = HttpTimingWindow(lambda: now[0])
for i in range(300):
window.add({"ended_mono_ms": i, "bytes": i})
assert len(window.snapshot()) == 256
rows = window.snapshot()
rows[0]["bytes"] = -1
assert window.snapshot()[0]["bytes"] == 44
now[0] = 31
assert window.snapshot() == []
assert not window.rows
def test_stream_failure_and_websocket_passthrough_preserve_behavior():
window = HttpTimingWindow()
sent = []
async def app(scope, receive, send):
if scope["type"] == "websocket":
await send({"type": "websocket.close"})
return
scope["route"] = SimpleNamespace(path="/api/stream")
await send({"type": "http.response.start", "status": 200, "headers": []})
await send({"type": "http.response.body", "body": b"abc", "more_body": True})
raise RuntimeError("private-failure")
async def sink(message):
sent.append(message)
async def run():
middleware = RuntimeHttpTimingMiddleware(app, window=window)
with pytest.raises(RuntimeError, match="private-failure"):
await middleware({"type": "http", "method": "GET"}, None, sink)
row = window.snapshot()[-1]
assert not row["complete"] and row["bytes"] == 3
assert "private" not in str(row)
await middleware({"type": "websocket"}, None, sink)
assert len(window.snapshot()) == 1
assert sent[-1] == {"type": "websocket.close"}
asyncio.run(run())
+68
View File
@@ -0,0 +1,68 @@
import copy
import json
from k1link.fleet.sensor_transient import SensorTransient
def test_queued_and_completed_payloads_are_ram_only_and_restart_never_requeues():
cache = SensorTransient()
row = {
"id": "vehicle",
"sensor_commands": {
"op": {
"command": {
"operation_id": "op",
"action_id": "vesc.qml.chunk",
"parameters": {"data": "PRIVATE_SOURCE"},
},
"state": "queued",
"updated_at": 1,
}
},
}
persisted = cache.persist(row)
assert "PRIVATE_SOURCE" not in json.dumps(persisted)
assert persisted["sensor_commands"]["op"]["state"] == "unknown"
assert cache.hydrate(copy.deepcopy(persisted)) == row
assert SensorTransient().hydrate(copy.deepcopy(persisted)) == persisted
row["sensor_commands"]["op"]["state"] = "complete"
row["sensor_commands"]["op"]["result"] = {"rows": "PRIVATE_SAMPLE", "png": "PRIVATE_FRAME"}
persisted = cache.persist(row)
assert "PRIVATE_" not in json.dumps(persisted)
assert cache.hydrate(copy.deepcopy(persisted)) == row
def test_expiry_daily_reset_and_budget_are_bounded_without_touching_durable_actions():
clock = [0]
day = [1]
cache = SensorTransient(clock=lambda: clock[0], day=lambda: day[0])
row = {
"id": "vehicle",
"sensor_commands": {
"normal": {"command": {"action_id": "vesc.configuration.apply"}, "state": "complete"}
},
}
assert cache.persist(row) == row
for n in range(70):
row = {
"id": "vehicle",
"sensor_commands": {
str(n): {
"command": {"action_id": "vesc.samples.read", "parameters": {}},
"state": "complete",
"result": {"rows": "x" * 150000},
"updated_at": 1,
}
},
}
saved = cache.persist(row)
assert (
len(cache.entries) <= 64 and sum(len(v[2]) for v in cache.entries.values()) <= 8 * 1024**2
)
clock[0] = 301
assert cache.hydrate(copy.deepcopy(saved)) == saved and not cache.entries
clock[0] = 400
cache.persist(row)
day[0] = 2
cache.prune()
assert not cache.entries