feat(k1): add USB networking, device management and acquisition recovery
This commit is contained in:
+573
-61
@@ -52,6 +52,16 @@ class Facade:
|
||||
|
||||
async def invoke(self, request):
|
||||
self.actions.append((request.action_id, copy.deepcopy(request.parameters)))
|
||||
if request.action_id == "connection.verify":
|
||||
from k1link.device_plugins.xgrids_k1.facade import ConnectionVerifyRequest
|
||||
|
||||
ConnectionVerifyRequest.model_validate(
|
||||
{
|
||||
key: value
|
||||
for key, value in request.parameters.items()
|
||||
if key != "expected_snapshot_runtime_id"
|
||||
}
|
||||
)
|
||||
if request.action_id == "application-control.workspace.enter":
|
||||
self.current["application_control_session"]["state"] = "workspace-ready"
|
||||
elif request.action_id == "acquisition.prepare":
|
||||
@@ -75,6 +85,28 @@ def bridge():
|
||||
return result
|
||||
|
||||
|
||||
def test_retired_usb_control_keeps_transport_identity_without_claiming_connection():
|
||||
snapshot = state()
|
||||
snapshot.update(active_connection_mode=None, desired_connection_mode="usb",
|
||||
selected_device_id="usb:synthetic", k1_ip="10.255.254.77",
|
||||
connection_lifecycle={"connection_ready": False, "ready_to_start": False})
|
||||
item = project_sensor(snapshot, "node-test")
|
||||
assert item["connection_mode"] == "usb"
|
||||
assert item["connection_label"] == "USB · 10.255.254.77"
|
||||
assert not item["online"] and not item["verified"]
|
||||
assert not item["control"]["can_start"]
|
||||
parameters = verification_parameters(snapshot, "verify-usb")
|
||||
assert parameters["source"] == "usb-enumeration"
|
||||
assert parameters["device_id"] == "usb:synthetic"
|
||||
assert parameters["compatibility_attestation"]["topology"] == "usb-ethernet"
|
||||
|
||||
|
||||
def test_usb_draft_does_not_replace_active_wireless_verification_target():
|
||||
snapshot = state()
|
||||
snapshot["desired_connection_mode"] = "usb"
|
||||
assert "source" not in verification_parameters(snapshot, "verify-current")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("available", [False, True])
|
||||
def test_startup_credential_check_does_not_authorize_control(monkeypatch, available):
|
||||
from k1link.device_plugins.xgrids_k1 import node_bridge
|
||||
@@ -124,9 +156,13 @@ def test_journalled_failure_logs_source_without_secret_and_does_not_repeat(caplo
|
||||
return {"operations": [{"operation_id": native, "status": "failed"}]}
|
||||
|
||||
device.invoke = invoke
|
||||
result = asyncio.run(device.invoke_journalled(
|
||||
"network.provision", {"operation_id": native, "password": secret}, identifier,
|
||||
))
|
||||
result = asyncio.run(
|
||||
device.invoke_journalled(
|
||||
"network.provision",
|
||||
{"operation_id": native, "password": secret},
|
||||
identifier,
|
||||
)
|
||||
)
|
||||
assert result["operations"][0]["status"] == "failed"
|
||||
assert calls == ["network.provision", "state.read"]
|
||||
assert "exception=BleakError" in caplog.text
|
||||
@@ -156,20 +192,28 @@ def test_real_facade_preserves_native_failure_location_in_journalled_log(caplog)
|
||||
|
||||
async def connect(self, request):
|
||||
calls.append("connect")
|
||||
self.current["operations"] = [{
|
||||
"operation_id": request.operation_id, "status": "failed",
|
||||
"error": {"code": "BleakError"},
|
||||
}]
|
||||
self.current["operations"] = [
|
||||
{
|
||||
"operation_id": request.operation_id,
|
||||
"status": "failed",
|
||||
"error": {"code": "BleakError"},
|
||||
}
|
||||
]
|
||||
raise BleakError(secret)
|
||||
|
||||
async def run():
|
||||
device = NodeBridge(Path.cwd(), service=Service())
|
||||
command = {
|
||||
"operation_id": "op_" + "c" * 32, "runtime_id": "runtime-one",
|
||||
"operation_id": "op_" + "c" * 32,
|
||||
"runtime_id": "runtime-one",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"action": "connect", "parameters": {
|
||||
"device_id": "AA:BB:CC:DD:EE:FF", "discovery_generation": 1,
|
||||
"mode_revision": 0, "ssid": "test-network", "password": secret,
|
||||
"action": "connect",
|
||||
"parameters": {
|
||||
"device_id": "AA:BB:CC:DD:EE:FF",
|
||||
"discovery_generation": 1,
|
||||
"mode_revision": 0,
|
||||
"ssid": "test-network",
|
||||
"password": secret,
|
||||
},
|
||||
}
|
||||
result = await device.deliver(command)
|
||||
@@ -274,7 +318,9 @@ def test_node_scan_reaches_service_through_real_facade_with_runtime_fence():
|
||||
|
||||
@pytest.mark.parametrize("radio_failure", [False, True])
|
||||
def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
tmp_path, monkeypatch, radio_failure,
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
radio_failure,
|
||||
):
|
||||
from bleak.backends.device import BLEDevice
|
||||
from bleak.backends.scanner import AdvertisementData
|
||||
@@ -295,8 +341,13 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
self.callback(
|
||||
BLEDevice("AA:BB:CC:DD:EE:FF", "XGR-TEST", None),
|
||||
AdvertisementData(
|
||||
local_name="XGR-TEST", manufacturer_data={}, service_data={},
|
||||
service_uuids=[], tx_power=None, rssi=-50, platform_data=(),
|
||||
local_name="XGR-TEST",
|
||||
manufacturer_data={},
|
||||
service_data={},
|
||||
service_uuids=[],
|
||||
tx_power=None,
|
||||
rssi=-50,
|
||||
platform_data=(),
|
||||
),
|
||||
)
|
||||
return self
|
||||
@@ -317,7 +368,8 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
"operation_id": "op_" + "b" * 32,
|
||||
"runtime_id": current["runtime_id"],
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"action": "scan", "parameters": {},
|
||||
"action": "scan",
|
||||
"parameters": {},
|
||||
}
|
||||
result = await device.deliver(command)
|
||||
if not radio_failure:
|
||||
@@ -329,12 +381,16 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
assert result["candidates"] == []
|
||||
else:
|
||||
assert result["candidates"][0]["id"] == "AA:BB:CC:DD:EE:FF"
|
||||
assert result["command_result"] == repeated["command_result"] == {
|
||||
"operation_id": command["operation_id"],
|
||||
"action": "scan",
|
||||
"status": "failed" if radio_failure else "succeeded",
|
||||
"error_code": "RuntimeError" if radio_failure else None,
|
||||
}
|
||||
assert (
|
||||
result["command_result"]
|
||||
== repeated["command_result"]
|
||||
== {
|
||||
"operation_id": command["operation_id"],
|
||||
"action": "scan",
|
||||
"status": "failed" if radio_failure else "succeeded",
|
||||
"error_code": "RuntimeError" if radio_failure else None,
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
asyncio.run(run())
|
||||
@@ -349,7 +405,8 @@ def test_node_attempt_projection_keeps_host_correlation_without_mutating_plugin_
|
||||
"schema_version": "missioncore.xgrids-k1-connection-attempt/v1",
|
||||
"attempt_id": plugin_operation_id(identifier),
|
||||
"recovery_operation_id": plugin_operation_id("op_" + "b" * 32),
|
||||
"status": "failed", "public_error_code": "wifi-ssid-not-found",
|
||||
"status": "failed",
|
||||
"public_error_code": "wifi-ssid-not-found",
|
||||
}
|
||||
result = NodeBridge.project(current)
|
||||
assert result["connection_attempt"]["attempt_id"] == identifier
|
||||
@@ -420,11 +477,13 @@ def test_sensor_projection_binds_native_sdk_to_board():
|
||||
def test_applied_wifi_does_not_grant_control_or_start_authority():
|
||||
current = state()
|
||||
current["connection_lifecycle"] = {
|
||||
"connection_ready": False, "ready_to_start": False,
|
||||
"connection_ready": False,
|
||||
"ready_to_start": False,
|
||||
"allowed_actions": ["verify-control-read-only"],
|
||||
}
|
||||
current["connection_attempt"] = {
|
||||
"phase": "network_applied", "public_error_code": "application_authority_unavailable",
|
||||
"phase": "network_applied",
|
||||
"public_error_code": "application_authority_unavailable",
|
||||
}
|
||||
item = project_sensor(current, "node-test")
|
||||
assert not item["online"] and not item["verified"]
|
||||
@@ -441,7 +500,8 @@ def test_applied_wifi_does_not_grant_control_or_start_authority():
|
||||
@pytest.mark.parametrize("initial_phase", ["connection-ready", "completed"])
|
||||
@pytest.mark.parametrize("pending_start", [False, True])
|
||||
def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
|
||||
initial_phase, pending_start,
|
||||
initial_phase,
|
||||
pending_start,
|
||||
):
|
||||
async def run():
|
||||
device = bridge()
|
||||
@@ -467,7 +527,8 @@ def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
|
||||
"parameters": {
|
||||
"operator_confirmed": True,
|
||||
"project_name": " Synthetic survey ",
|
||||
"mount_type": "handheld", "gnss_mode": "none",
|
||||
"mount_type": "handheld",
|
||||
"gnss_mode": "none",
|
||||
"control_generation": 1,
|
||||
"acquisition_id": None,
|
||||
},
|
||||
@@ -488,7 +549,8 @@ def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
|
||||
assert payload["mount_type"] == "handheld" and payload["gnss_mode"] == "none"
|
||||
if action in {"acquisition.prepare", "acquisition.start"}:
|
||||
row, created = journal.begin(
|
||||
action, operation_id=payload["operation_id"],
|
||||
action,
|
||||
operation_id=payload["operation_id"],
|
||||
idempotency_key=payload["idempotency_key"],
|
||||
)
|
||||
assert created
|
||||
@@ -506,6 +568,104 @@ def test_networkmanager_ssids_are_not_split_at_escaped_colons():
|
||||
assert nm_fields(r"field\:network\\name:88:WPA2") == ["field:network\\name", "88", "WPA2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("locale", ["ru_RU.UTF-8", "en_US.UTF-8"])
|
||||
def test_linux_wifi_probe_uses_stable_cli_locale_without_changing_parent(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
locale,
|
||||
):
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
from k1link.device_plugins.xgrids_k1 import linux_host
|
||||
from k1link.host_network.wifi import bind_route_fingerprint_to_wifi_association
|
||||
|
||||
(tmp_path / "wlan0" / "wireless").mkdir(parents=True)
|
||||
monkeypatch.setenv("LANG", locale)
|
||||
monkeypatch.setenv("LC_ALL", locale)
|
||||
parent_env = dict(os.environ)
|
||||
calls = []
|
||||
|
||||
def run(args, **kwargs):
|
||||
child_env = kwargs.get("env", os.environ)
|
||||
calls.append(child_env)
|
||||
active = "yes" if child_env.get("LC_ALL") == "C" else "да"
|
||||
return subprocess.CompletedProcess(
|
||||
args,
|
||||
0,
|
||||
active + r":Поле\:сеть:AA\:BB\:CC\:DD\:EE\:FF" + "\n",
|
||||
"",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(linux_host.subprocess, "run", run)
|
||||
probe = linux_host.LinuxWifiAssociationProbe(tmp_path)
|
||||
observed = probe.observe("wlan0")
|
||||
assert observed["association_state"] == "associated"
|
||||
assert observed["continuity_proven"] is True
|
||||
assert observed["reason_code"] is None
|
||||
fingerprint = bind_route_fingerprint_to_wifi_association("route", observed)
|
||||
repeated = bind_route_fingerprint_to_wifi_association("route", probe.observe("wlan0"))
|
||||
assert repeated == fingerprint
|
||||
assert all(env["LC_ALL"] == env["LANG"] == "C" for env in calls)
|
||||
assert dict(os.environ) == parent_env
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unavailable", ["empty", "inactive", "ambiguous", "command-error"])
|
||||
@pytest.mark.parametrize("fail_closed", [False, True])
|
||||
def test_linux_missing_association_reports_unavailable_without_invalid_token(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
unavailable,
|
||||
fail_closed,
|
||||
):
|
||||
from k1link.device_plugins.xgrids_k1 import facade, linux_host
|
||||
|
||||
(tmp_path / "sys-net" / "wlan0" / "wireless").mkdir(parents=True)
|
||||
probe = linux_host.LinuxWifiAssociationProbe(tmp_path / "sys-net")
|
||||
service = facade.XgridsK1CompatibilityService(
|
||||
tmp_path / "runtime",
|
||||
host_wifi_association_probe=probe,
|
||||
)
|
||||
path = facade.HostPathProbeResult(
|
||||
available=True,
|
||||
fingerprint="synthetic-route",
|
||||
interface="wlan0",
|
||||
source_ipv4="192.168.1.2",
|
||||
route_class="direct",
|
||||
reason_code=None,
|
||||
)
|
||||
monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: path)
|
||||
|
||||
def run(*_args, **_kwargs):
|
||||
if unavailable == "command-error":
|
||||
raise OSError("Network observation unavailable")
|
||||
return {
|
||||
"empty": "",
|
||||
"inactive": r"no:test:AA\:BB\:CC\:DD\:EE\:FF",
|
||||
"ambiguous": "yes:test:one\nyes:test:two\n",
|
||||
}[unavailable]
|
||||
|
||||
def forbidden(*_args, **_kwargs):
|
||||
raise AssertionError("Unobserved Wi-Fi must not authorize a TCP probe")
|
||||
|
||||
monkeypatch.setattr(linux_host, "_run", run)
|
||||
monkeypatch.setattr(facade, "_control_endpoint_reachable", forbidden)
|
||||
try:
|
||||
observed = service._sample_host_path(
|
||||
"192.168.1.7",
|
||||
fail_closed_unproven_association=fail_closed,
|
||||
)
|
||||
assert observed.available is False
|
||||
assert observed.fingerprint is None
|
||||
assert observed.kernel_route_fingerprint == path.fingerprint
|
||||
assert observed.reason_code == "host-wifi-observation-unavailable"
|
||||
endpoint = service._probe_control_endpoint("192.168.1.7")
|
||||
assert endpoint.reachable is False
|
||||
assert endpoint.reason_code == observed.reason_code
|
||||
finally:
|
||||
service.close()
|
||||
|
||||
|
||||
def test_wired_board_bridge_does_not_require_host_wifi_association(tmp_path, monkeypatch):
|
||||
from k1link.device_plugins.xgrids_k1 import linux_host
|
||||
|
||||
@@ -523,7 +683,9 @@ def test_wired_board_bridge_does_not_require_host_wifi_association(tmp_path, mon
|
||||
|
||||
@pytest.mark.parametrize("route_changes", [False, True])
|
||||
def test_wired_board_real_service_correlates_route_and_control_endpoint(
|
||||
tmp_path, monkeypatch, route_changes,
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
route_changes,
|
||||
):
|
||||
from dataclasses import replace
|
||||
|
||||
@@ -533,11 +695,16 @@ def test_wired_board_real_service_correlates_route_and_control_endpoint(
|
||||
(sys_net / "enp1s0").mkdir(parents=True)
|
||||
probe = linux_host.LinuxWifiAssociationProbe(sys_net)
|
||||
service = facade.XgridsK1CompatibilityService(
|
||||
tmp_path / "runtime", host_wifi_association_probe=probe,
|
||||
tmp_path / "runtime",
|
||||
host_wifi_association_probe=probe,
|
||||
)
|
||||
path = facade.HostPathProbeResult(
|
||||
available=True, fingerprint="synthetic-route", interface="enp1s0",
|
||||
source_ipv4="192.168.1.2", route_class="direct", reason_code=None,
|
||||
available=True,
|
||||
fingerprint="synthetic-route",
|
||||
interface="enp1s0",
|
||||
source_ipv4="192.168.1.2",
|
||||
route_class="direct",
|
||||
reason_code=None,
|
||||
)
|
||||
monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: path)
|
||||
calls = []
|
||||
@@ -545,9 +712,15 @@ def test_wired_board_real_service_correlates_route_and_control_endpoint(
|
||||
def tcp(_target):
|
||||
calls.append("tcp")
|
||||
if route_changes:
|
||||
monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: replace(
|
||||
path, fingerprint="new-route", source_ipv4="192.168.1.3",
|
||||
))
|
||||
monkeypatch.setattr(
|
||||
facade,
|
||||
"_inspect_host_path",
|
||||
lambda _target: replace(
|
||||
path,
|
||||
fingerprint="new-route",
|
||||
source_ipv4="192.168.1.3",
|
||||
),
|
||||
)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(facade, "_control_endpoint_reachable", tcp)
|
||||
@@ -649,32 +822,45 @@ def test_preview_offer_cannot_cross_acquisition_boundary(replacement):
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("draft", [
|
||||
{}, {"project_name": " "}, {"project_name": "x" * 97},
|
||||
{"project_name": "invalid\nname"}, {"project_name": "Valid", "mount_type": "uav"},
|
||||
{"project_name": "Valid", "mount_type": "handheld", "gnss_mode": "rtk"},
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"draft",
|
||||
[
|
||||
{},
|
||||
{"project_name": " "},
|
||||
{"project_name": "x" * 97},
|
||||
{"project_name": "invalid\nname"},
|
||||
{"project_name": "Valid", "mount_type": "uav"},
|
||||
{"project_name": "Valid", "mount_type": "handheld", "gnss_mode": "rtk"},
|
||||
],
|
||||
)
|
||||
def test_invalid_start_draft_dispatches_no_workspace_or_project_command(draft):
|
||||
async def run():
|
||||
device = bridge()
|
||||
item = project_sensor(state(), "node-test")
|
||||
command = {
|
||||
"operation_id": "op_" + "b" * 32, "action_id": "start",
|
||||
"operation_id": "op_" + "b" * 32,
|
||||
"action_id": "start",
|
||||
"session": {"device_id": item["id"], "session_id": "session-test"},
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": {"operator_confirmed": True, "control_generation": 1,
|
||||
"acquisition_id": None, **draft},
|
||||
"parameters": {
|
||||
"operator_confirmed": True,
|
||||
"control_generation": 1,
|
||||
"acquisition_id": None,
|
||||
**draft,
|
||||
},
|
||||
}
|
||||
with pytest.raises(ValueError):
|
||||
await NodeK1Sensor(device, None).execute(command, "node-test")
|
||||
assert all(action == "state.read" for action, _ in device.facade.actions)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_recheck_uses_only_exact_admitted_durable_bridge_target():
|
||||
current = state()
|
||||
decision = {
|
||||
"allowed": True, "requires_live_gatt_validation": False,
|
||||
"allowed": True,
|
||||
"requires_live_gatt_validation": False,
|
||||
"required_transport_ref": current["selected_device_id"],
|
||||
"required_connection_mode": "bridge",
|
||||
}
|
||||
@@ -684,16 +870,25 @@ def test_recheck_uses_only_exact_admitted_durable_bridge_target():
|
||||
assert result["device_id"] == current["selected_device_id"]
|
||||
assert result["expected_mode_revision"] == current["desired_connection_mode_revision"]
|
||||
assert "source" not in verification_parameters(
|
||||
current, "synthetic-operation", requested_device_id="other-device",
|
||||
current,
|
||||
"synthetic-operation",
|
||||
requested_device_id="other-device",
|
||||
)
|
||||
for patch in [{"allowed": False}, {"requires_live_gatt_validation": True},
|
||||
{"required_connection_mode": "quick-connect"},
|
||||
{"required_transport_ref": "other"}]:
|
||||
for patch in [
|
||||
{"allowed": False},
|
||||
{"required_connection_mode": "quick-connect"},
|
||||
{"required_transport_ref": "other"},
|
||||
]:
|
||||
decision.update(patch)
|
||||
assert "source" not in verification_parameters(current, "synthetic-operation")
|
||||
decision.update(allowed=True, requires_live_gatt_validation=False,
|
||||
required_transport_ref=current["selected_device_id"],
|
||||
required_connection_mode="bridge")
|
||||
assert "source" not in verification_parameters(
|
||||
current, "synthetic-operation", requested_device_id=current["selected_device_id"]
|
||||
)
|
||||
decision.update(
|
||||
allowed=True,
|
||||
requires_live_gatt_validation=False,
|
||||
required_transport_ref=current["selected_device_id"],
|
||||
required_connection_mode="bridge",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("requires_gatt", [False, True])
|
||||
@@ -701,23 +896,340 @@ def test_enrollment_verify_and_detail_share_durable_target_admission(requires_ga
|
||||
async def run():
|
||||
device = bridge()
|
||||
current = device.facade.current
|
||||
current["connection_policy"] = {"actions": {"observe-configured-device-network": {
|
||||
"allowed": True, "requires_live_gatt_validation": requires_gatt,
|
||||
"required_connection_mode": "bridge",
|
||||
"required_transport_ref": current["selected_device_id"],
|
||||
}}}
|
||||
current["connection_policy"] = {
|
||||
"actions": {
|
||||
"observe-configured-device-network": {
|
||||
"allowed": True,
|
||||
"requires_live_gatt_validation": requires_gatt,
|
||||
"required_connection_mode": "bridge",
|
||||
"required_transport_ref": current["selected_device_id"],
|
||||
}
|
||||
}
|
||||
}
|
||||
command = {
|
||||
"operation_id": "op_" + "d" * 32, "action": "verify", "runtime_id": "runtime-one",
|
||||
"operation_id": "op_" + "d" * 32,
|
||||
"action": "verify",
|
||||
"runtime_id": "runtime-one",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": {"device_id": current["selected_device_id"],
|
||||
"discovery_generation": 1, "mode_revision": 0},
|
||||
"parameters": {
|
||||
"device_id": current["selected_device_id"],
|
||||
"discovery_generation": 1,
|
||||
"mode_revision": 0,
|
||||
},
|
||||
}
|
||||
await device.execute(command)
|
||||
actions = [(a, p) for a, p in device.facade.actions if a != "state.read"]
|
||||
assert len(actions) == 1 and actions[0][0] == "connection.verify"
|
||||
payload = actions[0][1]
|
||||
assert (payload.get("source") == "durable-configured-state") is not requires_gatt
|
||||
assert payload["source"] == "durable-configured-state"
|
||||
assert payload["device_id"] == current["selected_device_id"]
|
||||
assert payload["expected_discovery_generation"] == 1
|
||||
assert "expected_discovery_generation" not in payload
|
||||
assert "password" not in payload
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_explicit_fresh_selection_uses_current_scan_when_policy_admits_it():
|
||||
current = state()
|
||||
current['connection_policy'] = {'actions': {
|
||||
'observe-configured-device-network': {'allowed': True,
|
||||
'required_transport_ref': current['selected_device_id'],
|
||||
'required_connection_mode': 'bridge'},
|
||||
'observe-fresh-device-network': {'allowed': True},
|
||||
}}
|
||||
args = {'requested_device_id': current['selected_device_id']}
|
||||
assert 'source' not in verification_parameters(current, 'synthetic-operation', **args)
|
||||
durable = 'durable-configured-state'
|
||||
assert verification_parameters(current, 'synthetic-operation')['source'] == durable
|
||||
current['connection_policy']['actions']['observe-fresh-device-network']['allowed'] = False
|
||||
assert verification_parameters(current, 'synthetic-operation', **args)['source'] == durable
|
||||
current['connection_policy']['actions']['observe-fresh-device-network']['allowed'] = True
|
||||
current['devices'] = []
|
||||
assert verification_parameters(current, 'synthetic-operation', **args)['source'] == durable
|
||||
|
||||
|
||||
def test_preview_blueprint_uses_canonical_live_timeline_without_device_commands(monkeypatch):
|
||||
import base64
|
||||
|
||||
from k1link.viewer.recorded import recorded_blueprint
|
||||
from k1link.viewer.rerun_bridge import RerunSceneSettings
|
||||
|
||||
import k1link.device_plugins.xgrids_k1.node_sensor as module
|
||||
calls = []
|
||||
original = module.recorded_blueprint_rrd
|
||||
def record(*args, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(module, "recorded_blueprint_rrd", record)
|
||||
|
||||
async def run():
|
||||
device = bridge()
|
||||
item = project_sensor(device.facade.current, "node-test")
|
||||
sensor = NodeK1Sensor(device, None)
|
||||
command = {
|
||||
"operation_id": "op_" + "c" * 32,
|
||||
"action_id": "details",
|
||||
"session": {"device_id": item["id"], "session_id": "session-test"},
|
||||
"parameters": {
|
||||
"preview_blueprint": {
|
||||
"recording_id": "synthetic-recording",
|
||||
"owner": "b" * 32,
|
||||
"view": "plan",
|
||||
"follow_trajectory": True,
|
||||
"host_playback": True,
|
||||
"settings": {"accumulation_seconds": 240, "show_grid": False},
|
||||
"eye": {"position": [1, 2, 3], "lookTarget": [0, 0, 0], "eyeUp": [0, 0, 1]},
|
||||
}
|
||||
},
|
||||
}
|
||||
result = await sensor.execute(command, "node-test")
|
||||
assert base64.b64decode(result["rrd"]).startswith(b"RRF2")
|
||||
assert calls[-1]["follow_trajectory"] is True
|
||||
assert calls[-1]["initialize_playback"] is False
|
||||
assert calls[-1]["eye_position"] == (1, 2, 3)
|
||||
command["parameters"]["preview_blueprint"]["follow_trajectory"] = "true"
|
||||
with pytest.raises(ValueError, match="follow"):
|
||||
await sensor.execute(command, "node-test")
|
||||
command["parameters"]["preview_blueprint"]["release"] = True
|
||||
assert await sensor.execute(command, "node-test") == {"released": True}
|
||||
assert all(action == "state.read" for action, _ in device.facade.actions)
|
||||
|
||||
asyncio.run(run())
|
||||
blueprint = recorded_blueprint(
|
||||
RerunSceneSettings(accumulation_seconds=240, show_grid=False),
|
||||
timeline="stream_time",
|
||||
plan_view=True,
|
||||
)
|
||||
spatial = blueprint.root_container.contents[0]
|
||||
ranges = spatial.visualizer_overrides["/world/points"][-1].ranges.as_arrow_array().to_pylist()
|
||||
assert ranges == [{"timeline": "stream_time", "range": {"start": -240_000_000_000, "end": 0}}]
|
||||
assert spatial.properties["LineGrid3D"].visible.as_arrow_array().to_pylist() == [False]
|
||||
|
||||
|
||||
def cold_recovery_state():
|
||||
current = state()
|
||||
current.update(
|
||||
selected_device_id=None,
|
||||
devices=[],
|
||||
ble_discovery_generation=0,
|
||||
device_session=None,
|
||||
active_connection_mode=None,
|
||||
connection_lifecycle={
|
||||
"connection_ready": False,
|
||||
"ready_to_start": False,
|
||||
"allowed_actions": ["observe-configured-device-network"],
|
||||
},
|
||||
)
|
||||
current["connection_policy"] = {
|
||||
"actions": {
|
||||
"observe-configured-device-network": {
|
||||
"allowed": True,
|
||||
"requires_live_gatt_validation": False,
|
||||
"required_transport_ref": "AA:BB:CC:DD:EE:FF",
|
||||
"required_connection_mode": "bridge",
|
||||
"target_source": "durable-configured-state",
|
||||
}
|
||||
}
|
||||
}
|
||||
current["active_acquisition_recovery_checkpoint"] = {
|
||||
"status": "active",
|
||||
"state": "active",
|
||||
"gap_open": False,
|
||||
"restart_rehydration_phase": "inactive",
|
||||
"reason_code": None,
|
||||
"private_lineage": "must-not-cross-node-projection",
|
||||
}
|
||||
return current
|
||||
|
||||
|
||||
@pytest.mark.parametrize("requires_gatt", [False, True])
|
||||
def test_cold_board_restart_verifies_saved_target_without_discovery_or_physical_command(
|
||||
requires_gatt,
|
||||
):
|
||||
device = bridge()
|
||||
device.facade.current = cold_recovery_state()
|
||||
device.facade.current["connection_policy"]["actions"]["observe-configured-device-network"][
|
||||
"requires_live_gatt_validation"
|
||||
] = requires_gatt
|
||||
checkpoint = copy.deepcopy(device.facade.current["active_acquisition_recovery_checkpoint"])
|
||||
identifier = "op_" + "e" * 32
|
||||
|
||||
async def run():
|
||||
before = await device.state()
|
||||
assert before["connected"] is False
|
||||
assert before["candidates"] == []
|
||||
assert before["selected_device_id"] is None
|
||||
assert before["reconnect_target"]["device_id"] == "AA:BB:CC:DD:EE:FF"
|
||||
assert before["acquisition_recovery"]["state"] == "active"
|
||||
assert "private_lineage" not in before["acquisition_recovery"]
|
||||
assert device.facade.actions == [("state.read", {})]
|
||||
device.facade.actions.clear()
|
||||
await device.execute(
|
||||
{
|
||||
"operation_id": identifier,
|
||||
"runtime_id": "runtime-one",
|
||||
"action": "verify",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": {
|
||||
"device_id": before["reconnect_target"]["device_id"],
|
||||
"discovery_generation": 0,
|
||||
"mode_revision": 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
assert [action for action, _ in device.facade.actions] == ["state.read", "connection.verify"]
|
||||
payload = device.facade.actions[-1][1]
|
||||
assert payload["source"] == "durable-configured-state"
|
||||
assert payload["device_id"] == "AA:BB:CC:DD:EE:FF"
|
||||
assert payload["expected_snapshot_runtime_id"] == "runtime-one"
|
||||
assert "password" not in payload and "ssid" not in payload
|
||||
assert device.facade.current["active_acquisition_recovery_checkpoint"] == checkpoint
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
"foreign-target",
|
||||
"denied-policy",
|
||||
"other-mode",
|
||||
"stale-generation",
|
||||
"stale-runtime",
|
||||
"provision",
|
||||
],
|
||||
)
|
||||
def test_saved_recovery_never_authorizes_foreign_stale_or_mutating_action(change):
|
||||
device = bridge()
|
||||
device.facade.current = cold_recovery_state()
|
||||
parameters = {"device_id": "AA:BB:CC:DD:EE:FF", "discovery_generation": 0, "mode_revision": 0}
|
||||
action, runtime = "verify", "runtime-one"
|
||||
policy = device.facade.current["connection_policy"]["actions"][
|
||||
"observe-configured-device-network"
|
||||
]
|
||||
if change == "foreign-target":
|
||||
parameters["device_id"] = "other-device"
|
||||
if change == "denied-policy":
|
||||
policy["allowed"] = False
|
||||
if change == "other-mode":
|
||||
policy["required_connection_mode"] = "quick-connect"
|
||||
if change == "stale-generation":
|
||||
parameters["discovery_generation"] = 1
|
||||
if change == "stale-runtime":
|
||||
runtime = "previous-runtime"
|
||||
if change == "provision":
|
||||
action = "connect"
|
||||
with pytest.raises(ValueError):
|
||||
asyncio.run(
|
||||
device.execute(
|
||||
{
|
||||
"operation_id": "op_" + "f" * 32,
|
||||
"runtime_id": runtime,
|
||||
"action": action,
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": parameters,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert device.facade.actions == [("state.read", {})]
|
||||
|
||||
|
||||
def test_verification_failure_survives_polling_but_not_a_new_runtime():
|
||||
current = cold_recovery_state()
|
||||
current["operations"] = [
|
||||
{
|
||||
"operation_id": "op-" + str(__import__("uuid").UUID(int=123)),
|
||||
"action": "connection.verify",
|
||||
"status": "failed",
|
||||
"context": {"snapshot_runtime_id": "runtime-one"},
|
||||
"error": {
|
||||
"code": "connection-verify-device-not-rediscovered",
|
||||
"message": "private-detail",
|
||||
},
|
||||
}
|
||||
]
|
||||
projected = NodeBridge.project(current)
|
||||
assert projected["verification"]["error_code"] == "connection-verify-device-not-rediscovered"
|
||||
assert projected["connected"] is False
|
||||
assert projected["acquisition_recovery"]["state"] == "active"
|
||||
assert "private-detail" not in json.dumps(projected)
|
||||
assert "must-not-cross-node-projection" not in json.dumps(projected)
|
||||
current["snapshot_runtime_id"] = "new-runtime"
|
||||
assert NodeBridge.project(current)["verification"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("committed", [True, False])
|
||||
def test_onboard_reset_uses_real_facade_without_old_monitor_or_adapter_lock(committed):
|
||||
calls = []
|
||||
|
||||
class Service:
|
||||
def require_snapshot_runtime_id(self, expected):
|
||||
assert expected == "runtime-one"
|
||||
|
||||
def bind_runtime_event_loop(self, _loop):
|
||||
pytest.fail("local reset must not bind the old connection monitor")
|
||||
|
||||
def select_connection_mode(self, request):
|
||||
calls.append(request.model_dump())
|
||||
value = state()
|
||||
if committed:
|
||||
value["desired_connection_mode_revision"] = 1
|
||||
value["connection_scenario_reset"] = {
|
||||
"reset_id": request.reset_id,
|
||||
"revision": 1,
|
||||
"local_session_closed": True,
|
||||
}
|
||||
return value
|
||||
|
||||
async def run():
|
||||
device = NodeBridge(Path.cwd(), service=Service())
|
||||
command = {
|
||||
"operation_id": "op_" + "d" * 32,
|
||||
"runtime_id": "runtime-one",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"action": "reset",
|
||||
"parameters": {"mode_revision": 0},
|
||||
}
|
||||
async with device.lock:
|
||||
result = await asyncio.wait_for(device.execute(command), timeout=1)
|
||||
assert result["command_result"]["status"] == ("succeeded" if committed else "failed")
|
||||
assert result["can_reset"] is True
|
||||
|
||||
asyncio.run(run())
|
||||
assert calls == [{
|
||||
"connection_mode": "bridge", "expected_revision": 0,
|
||||
"reset_scenario": True, "reset_id": plugin_operation_id("op_" + "d" * 32),
|
||||
}]
|
||||
|
||||
|
||||
def test_reset_hides_previous_verify_even_after_scan_settles_reset_marker():
|
||||
current = state()
|
||||
current["connection_scenario_reset"] = {
|
||||
"active": False,
|
||||
"timing": {"completed_at_utc": "2026-11-01T12:00:00.500Z"},
|
||||
}
|
||||
old = {"operation_id": "op-old", "action": "connection.verify", "status": "failed",
|
||||
"context": {"snapshot_runtime_id": "runtime-one"},
|
||||
"accepted_at": "2026-11-01T11:59:59Z"}
|
||||
current["operations"] = [old]
|
||||
assert NodeBridge.project(current)["verification"] is None
|
||||
current["operations"].append({**old, "operation_id": "op-new",
|
||||
"accepted_at": "2026-11-01T12:00:01Z"})
|
||||
assert NodeBridge.project(current)["verification"]["operation_id"] == "op-new"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("age,connected,used,visible", [
|
||||
(1, True, 99.0, True), (1, True, 0.0, True), (1, True, 100.0, True),
|
||||
(6, True, 99.0, False), (-1, True, 99.0, False),
|
||||
(1, False, 99.0, False), (1, True, float("nan"), False),
|
||||
(1, True, 101.0, False), (1, True, True, False),
|
||||
])
|
||||
def test_storage_projection_uses_only_current_connected_status(age, connected, used, visible):
|
||||
current = state()
|
||||
current["connection_lifecycle"]["connection_ready"] = connected
|
||||
current["application_control_session"]["transport"] = {"storage_status": {
|
||||
"used_percent": used, "observed_at": (datetime.now(UTC)-timedelta(seconds=age)).isoformat(),
|
||||
}}
|
||||
result = project_sensor(current, "node-test")
|
||||
assert (result["storage_status"] is not None) is visible
|
||||
assert result["control"]["can_start"] is True # Display telemetry grants no authority.
|
||||
|
||||
Reference in New Issue
Block a user