feat(k1): add USB networking, device management and acquisition recovery
This commit is contained in:
@@ -109,3 +109,19 @@ def test_duplicate_id_cannot_replace_original_secret():
|
||||
duplicate["parameters"]["password"] += "changed"
|
||||
bus.submit(fleet, "vehicle", duplicate)
|
||||
assert bus.pending[("vehicle", request["operation_id"])]["payload"] == request
|
||||
|
||||
|
||||
def test_reset_accepts_only_a_mode_revision_without_credentials_or_physical_action():
|
||||
value = command()
|
||||
value.update(action="reset", parameters={"mode_revision": 7})
|
||||
validate(value)
|
||||
for parameters in (
|
||||
{},
|
||||
{"mode_revision": True},
|
||||
{"mode_revision": -1},
|
||||
{"mode_revision": "7"},
|
||||
{"mode_revision": 7, "device_id": "x"},
|
||||
{"mode_revision": 7, "password": "synthetic"},
|
||||
):
|
||||
with pytest.raises(PairingError):
|
||||
validate({**value, "parameters": parameters})
|
||||
|
||||
@@ -49,6 +49,21 @@ def test_pending_commands_still_have_the_original_32_slot_limit():
|
||||
sensors.submit(fleet, "vehicle", request())
|
||||
|
||||
|
||||
def test_k1_management_uses_existing_queue_and_deduplicates_dispatch():
|
||||
fleet = Fleet()
|
||||
value = {**request(), "action_id": "management", "parameters": {
|
||||
"operation": "projects", "control_generation": 3, "control_revision": 7,
|
||||
}}
|
||||
receipt = sensors.submit(fleet, "vehicle", value)
|
||||
assert sensors.submit(fleet, "vehicle", value) is receipt
|
||||
assert sensors.heartbeat(fleet.row, {})["sensor_commands"] == [value]
|
||||
result = sensors.heartbeat(fleet.row, {"sensor_results": [{
|
||||
"command": value, "state": "complete", "result": {"status": "succeeded", "projects": []},
|
||||
}]})
|
||||
assert result["sensor_commands"] == []
|
||||
assert result["sensor_acknowledgements"] == [value["operation_id"]]
|
||||
|
||||
|
||||
def test_receipt_storage_is_bounded_and_only_expired_terminal_receipts_are_reclaimable():
|
||||
fleet = Fleet()
|
||||
for _ in range(sensors.MAX_COMMAND_RECEIPTS):
|
||||
|
||||
@@ -97,7 +97,7 @@ def test_lost_invocation_is_observed_once_and_never_resubmitted(journaled):
|
||||
if journaled:
|
||||
current["operations"] = [
|
||||
{
|
||||
"operation_id": identifier,
|
||||
"operation_id": parameters["operation_id"],
|
||||
"status": "failed",
|
||||
"error": {"code": "k1-wifi-network-not-found"},
|
||||
}
|
||||
@@ -161,6 +161,7 @@ def test_delivery_distinguishes_pre_dispatch_rejection_from_lost_result():
|
||||
result = await bridge.deliver(request)
|
||||
assert result["command_result"] == {
|
||||
"operation_id": request["operation_id"],
|
||||
"action": "connect",
|
||||
"status": "rejected",
|
||||
"error_code": "runtime-changed",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from test_xgrids_application_mqtt import FakeControlClient, _binding
|
||||
|
||||
from k1link.device_plugins.xgrids_k1.device_management import DeviceManagementRequest
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
ApplicationControlAuthority,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
_bytes_field as blob,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
_text_field as text,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
_varint_field as uint,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_mqtt import (
|
||||
ApplicationCommandOutcomeUnknown,
|
||||
ReviewedApplicationMqttTransport,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_session import (
|
||||
ApplicationConnectionBinding,
|
||||
InteractiveApplicationControlSession,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.device_management import (
|
||||
CONTROL_RESPONSE,
|
||||
PROJECT_RESPONSE,
|
||||
decode_management_response,
|
||||
decode_storage_mode,
|
||||
management_action,
|
||||
management_envelope,
|
||||
management_identity,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.management_mailbox import (
|
||||
MaintenanceJob,
|
||||
ManagementMailbox,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.modeling_control import OPENAPI_SUCCESS
|
||||
from k1link.device_plugins.xgrids_k1.protocol.protobuf_wire import iter_fields
|
||||
|
||||
|
||||
def envelope(operation="projects", ids=()):
|
||||
return management_envelope(operation, "synthetic-op", ApplicationControlAuthority(
|
||||
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), ids)
|
||||
|
||||
|
||||
def response(operation="projects", projects=()):
|
||||
request = envelope(operation, ("synthetic",) if operation == "delete-projects" else ())
|
||||
header = next(item.value for item in iter_fields(request.payload) if item.number == 1)
|
||||
return (blob(1, header) + uint(2, management_action(request.payload))
|
||||
+ b"".join(blob(4, text(1, ident) + text(2, name) + text(12, "private-url"))
|
||||
for ident, name in projects)
|
||||
+ blob(15, uint(1, OPENAPI_SUCCESS)))
|
||||
|
||||
|
||||
def info(*, storage=False, storage_type=1):
|
||||
return blob(2, blob(7, uint(4, int(storage))) + blob(10, uint(1, storage_type * 2))) \
|
||||
+ blob(15, uint(1, OPENAPI_SUCCESS))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation,code", [
|
||||
("usb-storage", 15), ("usb-data", 16), ("format-storage", 17),
|
||||
("power-off", 20), ("reboot", 22), ("projects", 23), ("delete-projects", 25),
|
||||
])
|
||||
def test_vendor_actions_and_exact_single_or_batch_delete(operation, code):
|
||||
request = envelope(operation, ("one",) if operation == "delete-projects" else ())
|
||||
assert management_action(request.payload) == code
|
||||
assert request.qos == 2 and not request.retain
|
||||
if operation == "delete-projects":
|
||||
assert [p.number for p in iter_fields(request.payload)] == [1, 2, 3]
|
||||
assert [p.number for p in iter_fields(envelope(operation, ("one", "two")).payload)] \
|
||||
== [1, 2, 5, 5]
|
||||
|
||||
|
||||
def test_large_catalog_retains_names_only_and_rejects_duplicate_ids():
|
||||
raw = response(projects=[(str(i), f"Проект {i}") for i in range(100)])
|
||||
assert management_identity(raw).session_id.endswith(":synthetic-op")
|
||||
result = decode_management_response(raw, "projects")
|
||||
assert len(result["projects"]) == 100
|
||||
assert result["projects"][0] == {"id": "0", "name": "Проект 0"}
|
||||
with pytest.raises(ValueError, match="duplicate"):
|
||||
decode_management_response(response(projects=[("one", "A"), ("one", "B")]), "projects")
|
||||
|
||||
|
||||
def test_mode_is_observed_and_never_inferred_from_command():
|
||||
assert decode_storage_mode(info(storage=True)) == {
|
||||
"usb_mode": "storage", "storage_type": "microSD",
|
||||
}
|
||||
assert decode_storage_mode(info())["usb_mode"] == "data"
|
||||
with pytest.raises(ValueError):
|
||||
decode_storage_mode(response("usb-storage"))
|
||||
|
||||
|
||||
def test_mismatched_action_cannot_satisfy_same_session_response():
|
||||
request = envelope("reboot")
|
||||
fake = FakeControlClient(response_topic=CONTROL_RESPONSE)
|
||||
transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
|
||||
transport.open()
|
||||
# Same identity, wrong action: neither UI success nor control proof.
|
||||
fake.events.append(("message", (CONTROL_RESPONSE, response("power-off"))))
|
||||
with pytest.raises(ApplicationCommandOutcomeUnknown):
|
||||
transport.exchange_batch_once([request],
|
||||
required_response_operation_keys={request.operation_key})
|
||||
assert transport.snapshot().correlated_responses == 0
|
||||
|
||||
|
||||
def test_management_dispatch_commit_runs_with_physical_observer_noop():
|
||||
fake = FakeControlClient(response_topic=PROJECT_RESPONSE)
|
||||
transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
|
||||
transport.install_evidence_observer(SimpleNamespace(
|
||||
publish_dispatching=lambda *a, **kw: None, publish_result=lambda *a, **kw: None,
|
||||
qos2_completed=lambda *a: None, application_response=lambda *a: None,
|
||||
))
|
||||
transport.open()
|
||||
commits = []
|
||||
request = envelope()
|
||||
transport.exchange_batch_once([request],
|
||||
required_response_operation_keys={request.operation_key},
|
||||
dispatch_admission_commit=lambda: commits.append(True))
|
||||
transport.close()
|
||||
assert commits == [True]
|
||||
|
||||
|
||||
class MailboxTransport:
|
||||
def __init__(self, *, standby=True, lose_reply=False):
|
||||
self.standby, self.lose_reply, self.sent = standby, lose_reply, []
|
||||
|
||||
def standby_complete(self, binding):
|
||||
return self.standby
|
||||
|
||||
def exchange_batch_once(self, batch, **kwargs):
|
||||
assert not kwargs["dispatch_admission_deadline_reached"]()
|
||||
kwargs["dispatch_admission_commit"]()
|
||||
self.sent.append(batch[0])
|
||||
if self.lose_reply:
|
||||
raise TimeoutError()
|
||||
raw = info() if batch[0].operation_key.startswith("management-info:") else response()
|
||||
return {batch[0].operation_key: raw}
|
||||
|
||||
|
||||
def pump(box, transport, operation="projects", *, stale=False, expired=False, ids=()):
|
||||
job = MaintenanceJob(operation, "synthetic-op", ids, 1, 2,
|
||||
time.monotonic() + (-1 if expired else 5))
|
||||
box.pending = job
|
||||
def validate(_job):
|
||||
if stale:
|
||||
raise ValueError("stale checkpoint")
|
||||
box.pump(transport, ApplicationControlAuthority(
|
||||
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), validate)
|
||||
assert job.finished.is_set() and box.pending is None
|
||||
return job.result
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reason", ["active", "stale", "expired", "unknown-catalog"])
|
||||
def test_no_hardware_publish_without_current_idle_admission(reason):
|
||||
box, transport = ManagementMailbox(), MailboxTransport(standby=reason != "active")
|
||||
result = pump(box, transport, "delete-projects" if reason == "unknown-catalog" else "projects",
|
||||
stale=reason == "stale", expired=reason == "expired",
|
||||
ids=("one",) if reason == "unknown-catalog" else ())
|
||||
assert result["status"] == "blocked" and not transport.sent
|
||||
|
||||
|
||||
def test_lost_write_reply_is_unknown_blocks_start_and_is_not_retried():
|
||||
box, transport = ManagementMailbox(), MailboxTransport(lose_reply=True)
|
||||
result = pump(box, transport, "usb-storage")
|
||||
assert result["status"] == "unknown" and box.block_start
|
||||
box.pump(transport, None, None, lambda job: None)
|
||||
assert len(transport.sent) == 1
|
||||
|
||||
|
||||
def test_closed_worker_cancels_queued_unpublished_job():
|
||||
box = ManagementMailbox()
|
||||
job = MaintenanceJob("projects", "synthetic-op", (), 1, 2, time.monotonic() + 5)
|
||||
box.pending = job
|
||||
box.cancel_queued()
|
||||
assert box.pending is None and job.finished.is_set() and job.result["status"] == "blocked"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", [None, "reject-second", "lose-second"])
|
||||
def test_group_deletion_uses_confirmed_single_requests_and_stops_on_failure(failure):
|
||||
class DeletingTransport(MailboxTransport):
|
||||
def exchange_batch_once(self, batch, **kwargs):
|
||||
assert not kwargs["dispatch_admission_deadline_reached"]()
|
||||
kwargs["dispatch_admission_commit"]()
|
||||
request = batch[0]
|
||||
self.sent.append(request)
|
||||
if request.operation_key.startswith("management-info:"):
|
||||
return {request.operation_key: info()}
|
||||
fields = list(iter_fields(request.payload))
|
||||
assert [p.number for p in fields] == [1, 2, 3]
|
||||
index = len(self.sent)
|
||||
if failure == "lose-second" and index == 2:
|
||||
raise TimeoutError()
|
||||
code = 839122945 if failure == "reject-second" and index == 2 else OPENAPI_SUCCESS
|
||||
raw = blob(1, fields[0].value) + uint(2, 25) + blob(15, uint(1, code))
|
||||
return {request.operation_key: raw}
|
||||
|
||||
box, transport = ManagementMailbox(), DeletingTransport()
|
||||
box.generation, box.catalog_revision, box.project_ids = 1, "catalog", {"one", "two", "three"}
|
||||
job = MaintenanceJob("delete-projects", "batch", ("one", "two", "three"), 1, 2,
|
||||
time.monotonic() + 5, catalog_revision="catalog")
|
||||
box.pending = job
|
||||
box.pump(transport, ApplicationControlAuthority(
|
||||
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), lambda _: None)
|
||||
assert job.finished.is_set()
|
||||
requests = [p for p in transport.sent if p.operation_key.startswith("management:")]
|
||||
assert len({p.operation_key for p in requests}) == len(requests)
|
||||
assert [next(f.value for f in iter_fields(p.payload) if f.number == 3) for p in requests] \
|
||||
== ([b"one", b"two"] if failure else [b"one", b"two", b"three"])
|
||||
assert job.result["deleted_project_ids"] == (["one"] if failure else ["one", "two", "three"])
|
||||
expected = {None: "succeeded", "reject-second": "rejected", "lose-second": "unknown"}
|
||||
assert job.result["status"] == expected[failure]
|
||||
assert box.block_start is (failure == "lose-second")
|
||||
|
||||
|
||||
def test_destructive_request_requires_confirmation_and_no_arbitrary_parameters():
|
||||
base = dict(operation_id="synthetic-op", expected_session_generation=1,
|
||||
expected_state_revision=2, operation="format-storage")
|
||||
with pytest.raises(ValueError):
|
||||
DeviceManagementRequest(**base)
|
||||
with pytest.raises(ValueError):
|
||||
DeviceManagementRequest(**base, operator_confirmed=True, path="/arbitrary")
|
||||
|
||||
|
||||
def test_mass_storage_cannot_remove_its_only_control_path():
|
||||
session = InteractiveApplicationControlSession(SimpleNamespace())
|
||||
session._phase = "connection-ready"
|
||||
job = MaintenanceJob("usb-storage", "synthetic-op", (), 0, 0, time.monotonic() + 5)
|
||||
for mode in ("usb", "quick-connect", "direct-connect", "bridge"):
|
||||
session._connection_binding = ApplicationConnectionBinding(
|
||||
"synthetic-intent", "synthetic-transport", 1, "192.0.2.1", 1883, mode,
|
||||
)
|
||||
if mode == "bridge":
|
||||
session._validate_management_job(job)
|
||||
else:
|
||||
with pytest.raises(ValueError, match="Bridge"):
|
||||
session._validate_management_job(job)
|
||||
assert session._management.pending is None
|
||||
@@ -158,7 +158,7 @@ def test_private_release_contains_material_only_in_root_private_member(
|
||||
position += 60 + length + length % 2
|
||||
with tarfile.open(fileobj=io.BytesIO(members["control.tar.gz"]), mode="r:gz") as archive:
|
||||
control = archive.extractfile("control").read().decode()
|
||||
assert "Depends: mission-core-node (>= 0.8.13)" in control
|
||||
assert "Depends: mission-core-node (>= 0.8.49-57)" in control
|
||||
assert "Replaces: mission-core-node (<< 0.8.0)" in control
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from test_xgrids_acquisition_lifecycle import _direct_host_path, service_with_fake_runtime
|
||||
|
||||
from k1link.device_plugins.xgrids_k1 import facade as facade_module
|
||||
from k1link.device_plugins.xgrids_k1.facade import (
|
||||
ConnectionVerifyRequest,
|
||||
ConnectRequest,
|
||||
DesiredConnectionModeRequest,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.usb_network import LinuxK1UsbProbe, UsbNetworkAttachment
|
||||
|
||||
|
||||
def attachment():
|
||||
return UsbNetworkAttachment("usb:synthetic", "test0", "10.255.254.77",
|
||||
"10.255.254.2", "generation-one", "480")
|
||||
|
||||
|
||||
def usb_tree(tmp_path):
|
||||
usb = tmp_path / "devices" / "usb1" / "1-2"
|
||||
net = usb / "1-2:1.0" / "net" / "test0"
|
||||
net.mkdir(parents=True)
|
||||
driver = tmp_path / "drivers" / "rndis_host"
|
||||
driver.mkdir(parents=True)
|
||||
(usb / "1-2:1.0" / "driver").symlink_to(driver)
|
||||
(net / "device").symlink_to(usb / "1-2:1.0")
|
||||
sys_net = tmp_path / "class" / "net"
|
||||
sys_net.mkdir(parents=True)
|
||||
(sys_net / "test0").symlink_to(net)
|
||||
for name, value in {"idVendor": "2207", "idProduct": "0019", "serial": "synthetic",
|
||||
"product": "XGRIDS Device", "busnum": "1", "devnum": "4",
|
||||
"speed": "480"}.items():
|
||||
(usb / name).write_text(value)
|
||||
(net / "carrier").write_text("1")
|
||||
(net / "ifindex").write_text("9")
|
||||
return usb, net, sys_net
|
||||
|
||||
|
||||
def runner(args, **kwargs):
|
||||
if args[0] == "nmcli":
|
||||
return "DHCP4.OPTION[1]:dhcp_server_identifier = 10.255.254.77\n"
|
||||
assert args == ["ip", "-j", "route", "get", "10.255.254.77"]
|
||||
return json.dumps([{"dev": "test0", "prefsrc": "10.255.254.2"}])
|
||||
|
||||
|
||||
def test_discovery_uses_dhcp_not_address_default_and_keeps_identity_on_replug(tmp_path):
|
||||
usb, net, sys_net = usb_tree(tmp_path)
|
||||
probe = LinuxK1UsbProbe(sys_net, runner)
|
||||
before, = probe.discover()
|
||||
assert before.peer_ipv4 == "10.255.254.77"
|
||||
(usb / "devnum").write_text("5")
|
||||
(net / "ifindex").write_text("10")
|
||||
after, = probe.discover()
|
||||
assert after.transport_ref == before.transport_ref
|
||||
assert after.generation != before.generation
|
||||
(net / "carrier").write_text("0")
|
||||
assert probe.discover() == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fault", ["vendor", "mass-storage", "dhcp", "route", "gateway"])
|
||||
def test_unproved_usb_topology_never_becomes_candidate(tmp_path, fault):
|
||||
usb, _, sys_net = usb_tree(tmp_path)
|
||||
if fault == "vendor":
|
||||
(usb / "idVendor").write_text("1234")
|
||||
if fault == "mass-storage":
|
||||
(usb / "1-2:1.0" / "driver").unlink()
|
||||
|
||||
def broken(args, **kwargs):
|
||||
if fault == "dhcp" and args[0] == "nmcli":
|
||||
return ""
|
||||
if args[0] == "ip" and fault in {"route", "gateway"}:
|
||||
return json.dumps([{"dev": "wifi0" if fault == "route" else "test0",
|
||||
"prefsrc": "10.255.254.2", "gateway": "10.255.254.1"}])
|
||||
return runner(args, **kwargs)
|
||||
|
||||
assert LinuxK1UsbProbe(sys_net, broken).discover() == ()
|
||||
|
||||
|
||||
def test_usb_cannot_be_sent_as_wireless_provisioning():
|
||||
with pytest.raises(ValidationError):
|
||||
ConnectRequest.model_validate({"connection_mode": "usb"})
|
||||
|
||||
|
||||
def test_usb_verify_reuses_identity_admission_and_performs_no_ble(monkeypatch, tmp_path):
|
||||
service, _ = service_with_fake_runtime(tmp_path)
|
||||
live = [attachment()]
|
||||
service._usb_network_probe = SimpleNamespace(require=lambda _: live[0])
|
||||
monkeypatch.setattr(facade_module, "_inspect_host_path", _direct_host_path)
|
||||
monkeypatch.setattr(facade_module, "_control_endpoint_reachable", lambda _: True)
|
||||
|
||||
def forbidden(*args, **kwargs):
|
||||
raise AssertionError("USB must never contact BLE or mutate Wi-Fi")
|
||||
|
||||
monkeypatch.setattr(facade_module, "read_wifi_status_once", forbidden)
|
||||
monkeypatch.setattr(facade_module, "provision_wifi_once", forbidden)
|
||||
monkeypatch.setattr(service, "_borrow_network_ble_process_lease", forbidden)
|
||||
|
||||
async def verify():
|
||||
state = service.select_connection_mode(DesiredConnectionModeRequest(
|
||||
connection_mode="usb", expected_revision=0,
|
||||
))
|
||||
return await service.verify_connection(ConnectionVerifyRequest(
|
||||
device_id=live[0].transport_ref, source="usb-enumeration",
|
||||
compatibility_attestation={"firmware_version": "3.0.2", "topology": "usb-ethernet",
|
||||
"verification": "live-device-info"},
|
||||
expected_mode_revision=state["desired_connection_mode_revision"],
|
||||
))
|
||||
|
||||
try:
|
||||
state = asyncio.run(verify())
|
||||
assert state["connection_lifecycle"]["connection_ready"] is True
|
||||
assert state["active_connection_mode"] == "usb"
|
||||
assert state["acquisition"] is None
|
||||
assert state["physical_command"]["record"] is None
|
||||
assert state["semantic_topology_store"]["record"]["source"] == "usb-enumeration"
|
||||
before = service._sample_host_path(live[0].peer_ipv4)
|
||||
live[0] = replace(live[0], generation="generation-two")
|
||||
assert service._sample_host_path(live[0].peer_ipv4).fingerprint != before.fingerprint
|
||||
live[0] = replace(live[0], interface="different")
|
||||
assert service._sample_host_path(live[0].peer_ipv4).available is False
|
||||
finally:
|
||||
service.close()
|
||||
|
||||
|
||||
def test_usb_start_journal_survives_restart_without_changing_start(tmp_path):
|
||||
from test_xgrids_physical_command_ledger import _connection, _prepare_start
|
||||
|
||||
from k1link.device_plugins.xgrids_k1.physical_command_ledger import PhysicalCommandLedger
|
||||
|
||||
ledger = PhysicalCommandLedger(tmp_path)
|
||||
binding = replace(_connection(), connection_mode="usb", transport_ref="usb:synthetic")
|
||||
_prepare_start(ledger, connection=binding)
|
||||
before = ledger.snapshot().record
|
||||
after = PhysicalCommandLedger(tmp_path).snapshot().record
|
||||
assert after == before
|
||||
assert after.action == "start"
|
||||
assert after.connection.connection_mode == "usb"
|
||||
assert after.stage == "prepared"
|
||||
|
||||
|
||||
def test_hotplug_observer_only_verifies_once_per_attachment(monkeypatch):
|
||||
from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
|
||||
|
||||
calls = []
|
||||
current = {"active_connection_mode": None, "desired_connection_mode": "bridge",
|
||||
"desired_connection_mode_revision": 0, "source_mode": "idle"}
|
||||
|
||||
async def invoke(*args):
|
||||
return dict(current)
|
||||
|
||||
def select(request):
|
||||
calls.append("select")
|
||||
current.update(desired_connection_mode=request.connection_mode,
|
||||
desired_connection_mode_revision=1)
|
||||
return dict(current)
|
||||
|
||||
async def verify(request):
|
||||
calls.append(request)
|
||||
current["active_connection_mode"] = "usb"
|
||||
current["connection_lifecycle"] = {"connection_ready": True}
|
||||
|
||||
bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke,
|
||||
service=SimpleNamespace(select_connection_mode=select,
|
||||
verify_connection=verify))
|
||||
observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
|
||||
|
||||
async def observe():
|
||||
await observer.observe_once()
|
||||
await observer.observe_once()
|
||||
|
||||
asyncio.run(observe())
|
||||
assert calls[0] == "select"
|
||||
assert len(calls) == 2
|
||||
assert isinstance(calls[1], ConnectionVerifyRequest)
|
||||
assert calls[1].source == "usb-enumeration"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source,phase,retries", [
|
||||
("idle", "failed", 1),
|
||||
("idle", "completed", 1),
|
||||
("live", "failed", 0),
|
||||
("idle", "stopping", 0),
|
||||
("live", "running", 0),
|
||||
])
|
||||
def test_unchanged_usb_rechecks_retired_control_without_stealing_receiver(source, phase, retries):
|
||||
from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
|
||||
|
||||
calls = []
|
||||
current = {"active_connection_mode": None, "desired_connection_mode": "usb",
|
||||
"desired_connection_mode_revision": 2, "source_mode": source,
|
||||
"acquisition": {"state": phase}, "connection_lifecycle": {"connection_ready": False}}
|
||||
|
||||
async def invoke(*args):
|
||||
return current
|
||||
|
||||
async def verify(request):
|
||||
calls.append(request)
|
||||
|
||||
bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke,
|
||||
service=SimpleNamespace(verify_connection=verify))
|
||||
observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
|
||||
observer.accepted_generation = attachment().generation
|
||||
asyncio.run(observer.observe_once())
|
||||
assert len(calls) == retries
|
||||
if calls:
|
||||
assert calls[0].source == "usb-enumeration"
|
||||
assert calls[0].expected_mode_revision == 2
|
||||
assert calls[0].device_id == attachment().transport_ref
|
||||
|
||||
|
||||
def test_hotplug_cannot_steal_active_wireless_acquisition():
|
||||
from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
|
||||
|
||||
async def invoke(*args):
|
||||
return {"active_connection_mode": "bridge", "source_mode": "live"}
|
||||
|
||||
bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke, service=object())
|
||||
observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
|
||||
asyncio.run(observer.observe_once())
|
||||
assert observer.accepted_generation is None
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Preview decoding/adaptation never acquires a physical camera or a recorder."""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from fractions import Fraction
|
||||
from types import SimpleNamespace
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from k1link.viewer.node_camera import CameraSource, CameraTrack, LeaseReader, open_live_camera
|
||||
from k1link.viewer.node_media import admit_sdp
|
||||
|
||||
|
||||
def test_mp4_lease_decodes_to_one_latest_frame_without_network_or_capture_change():
|
||||
output = io.BytesIO()
|
||||
with av.open(
|
||||
output,
|
||||
"w",
|
||||
format="mp4",
|
||||
options={"movflags": "frag_keyframe+empty_moov+default_base_moof"},
|
||||
) as mux:
|
||||
stream = mux.add_stream("libx264", rate=15)
|
||||
stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"
|
||||
for index in range(10):
|
||||
frame = av.VideoFrame.from_ndarray(
|
||||
np.full((48, 64, 3), index * 10, dtype=np.uint8), format="rgb24"
|
||||
)
|
||||
for packet in stream.encode(frame):
|
||||
mux.mux(packet)
|
||||
for packet in stream.encode():
|
||||
mux.mux(packet)
|
||||
segments = queue.Queue()
|
||||
data = output.getvalue()
|
||||
for offset in range(0, len(data), 113):
|
||||
segments.put(("media", data[offset : offset + 113]))
|
||||
segments.put(None)
|
||||
lease = SimpleNamespace(segments=segments)
|
||||
|
||||
class Camera:
|
||||
opened = 0
|
||||
released = 0
|
||||
streamed = 0
|
||||
|
||||
def snapshot(self):
|
||||
return {
|
||||
"generation": 7,
|
||||
"recording": {
|
||||
"source_end_expected": self.released > 0,
|
||||
"active": True,
|
||||
"producer_alive": True,
|
||||
"media_ready": True,
|
||||
"active_epoch": 7,
|
||||
},
|
||||
}
|
||||
|
||||
def open_delivery(self, generation, *, require_recording):
|
||||
assert generation == 7 and require_recording
|
||||
self.opened += 1
|
||||
return lease
|
||||
|
||||
def release_delivery(self, value, *, client_closed):
|
||||
assert value is lease and client_closed
|
||||
self.released += 1
|
||||
|
||||
def mark_streaming(self, value):
|
||||
assert value is lease
|
||||
self.streamed += 1
|
||||
|
||||
camera = Camera()
|
||||
source = CameraSource(camera)
|
||||
source.thread.join(3)
|
||||
source.close()
|
||||
source.thread.join(1)
|
||||
assert not source.thread.is_alive()
|
||||
assert source.sequence >= 1 and camera.streamed >= 1
|
||||
assert camera.opened == camera.released == 1
|
||||
|
||||
|
||||
def test_closing_consumer_unblocks_mp4_reader():
|
||||
stopped = threading.Event()
|
||||
reader = LeaseReader(SimpleNamespace(segments=queue.Queue()), stopped)
|
||||
result = []
|
||||
worker = threading.Thread(target=lambda: result.append(reader.read(12)))
|
||||
worker.start()
|
||||
stopped.set()
|
||||
worker.join(1)
|
||||
assert not worker.is_alive() and result == [b""]
|
||||
|
||||
|
||||
def test_live_fragment_is_decoded_without_waiting_for_future_frames_or_eof():
|
||||
output = io.BytesIO()
|
||||
with av.open(output, "w", format="mp4", options={
|
||||
"movflags": "empty_moov+default_base_moof+frag_every_frame",
|
||||
}) as mux:
|
||||
stream = mux.add_stream("libx264", rate=15)
|
||||
stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"
|
||||
stream.options = {"tune": "zerolatency", "g": "1"}
|
||||
for index in range(3):
|
||||
frame = av.VideoFrame.from_ndarray(
|
||||
np.full((48, 64, 3), index * 50, dtype=np.uint8), format="rgb24"
|
||||
)
|
||||
for packet in stream.encode(frame):
|
||||
mux.mux(packet)
|
||||
# Capture while the producer remains live: no trailer or EOF.
|
||||
live = output.getvalue()
|
||||
segments = queue.Queue()
|
||||
segments.put(("media", live))
|
||||
stopped, decoded = threading.Event(), threading.Event()
|
||||
|
||||
def consume():
|
||||
reader = LeaseReader(SimpleNamespace(segments=segments), stopped)
|
||||
with open_live_camera(reader) as container:
|
||||
for _frame in container.decode(video=0):
|
||||
decoded.set()
|
||||
break
|
||||
|
||||
worker = threading.Thread(target=consume, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
assert decoded.wait(1), "live preview waited for future data or EOF"
|
||||
finally:
|
||||
stopped.set()
|
||||
worker.join(2)
|
||||
assert not worker.is_alive()
|
||||
|
||||
|
||||
def test_camera_track_obeys_shared_budget_and_never_mutates_source_frame():
|
||||
frame = av.VideoFrame(1280, 720, "yuv420p")
|
||||
frame.pts, frame.time_base = 123, Fraction(1, 90000)
|
||||
source = SimpleNamespace(closed=threading.Event(), current=lambda: (1, frame, time.monotonic()))
|
||||
budget = SimpleNamespace(video=lambda: (320, 4))
|
||||
|
||||
async def run():
|
||||
track = CameraTrack(source, budget)
|
||||
try:
|
||||
result = await asyncio.wait_for(track.recv(), 1)
|
||||
assert result.width == 320 and result.height == 180
|
||||
assert result.pts == 123 and result is not frame and frame.width == 1280
|
||||
finally:
|
||||
track.stop()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_camera_sdp_requires_exact_video_and_control_channel_and_private_ice():
|
||||
invitation = (
|
||||
"v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n"
|
||||
"m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n"
|
||||
)
|
||||
admit_sdp(invitation, camera=True)
|
||||
with pytest.raises(ValueError):
|
||||
admit_sdp(invitation)
|
||||
with pytest.raises(ValueError):
|
||||
admit_sdp(invitation + "m=audio 9 UDP/TLS/RTP/SAVPF 0\r\n", camera=True)
|
||||
with pytest.raises(ValueError):
|
||||
admit_sdp(invitation + "a=candidate:1 1 udp 1 8.8.8.8 1234 typ host\r\n", camera=True)
|
||||
+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.
|
||||
|
||||
@@ -11543,6 +11543,7 @@ class _ActualWorkerStopRaceExecutor:
|
||||
observed: Callable[[], bool],
|
||||
*,
|
||||
reconciled_active_observed: Callable[[], bool] | None = None,
|
||||
standby_work: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
deadline = time.monotonic() + 3.0
|
||||
while not observed():
|
||||
@@ -11550,6 +11551,8 @@ class _ActualWorkerStopRaceExecutor:
|
||||
return None
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("actual worker checkpoint was not released")
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
threading.Event().wait(0.005)
|
||||
return None
|
||||
|
||||
@@ -15472,6 +15475,62 @@ def test_post_start_refresh_timeout_wakes_existing_read_only_recovery(
|
||||
assert service._physical_command_coordinator.snapshot() is physical # noqa: SLF001
|
||||
|
||||
|
||||
@pytest.mark.parametrize("confirmed_start", [True, False])
|
||||
@pytest.mark.parametrize("brief_gap", [True, False])
|
||||
def test_returned_host_epoch_wakes_active_recovery_with_surviving_data_socket(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
brief_gap: bool,
|
||||
confirmed_start: bool,
|
||||
) -> None:
|
||||
service, runtime = service_with_fake_runtime(tmp_path)
|
||||
control, physical = _install_composite_active_recovery_fixture(
|
||||
service, runtime, monkeypatch, runtime_phase="live", camera_phase="streaming",
|
||||
)
|
||||
if not confirmed_start:
|
||||
physical["requires_reconciliation"] = True
|
||||
supervisor = service._connection_supervisor # noqa: SLF001
|
||||
before = supervisor.snapshot()
|
||||
if brief_gap:
|
||||
supervisor.observe_host_path(HostPathProbeResult(
|
||||
available=False, fingerprint=None, interface=None, source_ipv4=None,
|
||||
route_class="unavailable", reason_code="host-route-unavailable",
|
||||
))
|
||||
supervisor.observe_host_path(HostPathProbeResult(
|
||||
available=True,
|
||||
fingerprint=before.host_path.fingerprint if brief_gap else "same-lan-new-association",
|
||||
interface=before.host_path.interface, source_ipv4=before.host_path.source_ipv4,
|
||||
route_class=before.host_path.route_class,
|
||||
kernel_route_fingerprint=before.host_path.kernel_route_fingerprint,
|
||||
))
|
||||
assert supervisor.snapshot().host_path_negative_streak == 0
|
||||
assert supervisor.snapshot().control_plane.reason_code == "host-path-epoch-changed"
|
||||
starts = list(control.start_projects)
|
||||
stops = control.stop_calls
|
||||
|
||||
state = service.state()
|
||||
service.state()
|
||||
|
||||
if not confirmed_start:
|
||||
assert runtime.recovery_requests == []
|
||||
assert control.start_projects == starts
|
||||
assert control.stop_calls == stops
|
||||
assert runtime.stop_calls == 0
|
||||
return
|
||||
assert runtime.recovery_requests == [
|
||||
("host-path-epoch-changed", runtime.producer_generation),
|
||||
]
|
||||
assert state["phase"] == "reconnecting"
|
||||
assert state["connection_recovery"]["automatic_read_only_rebind"] is True
|
||||
assert state["acquisition"]["state"] == "acquiring"
|
||||
assert state["selected_device_id"] == "test-ble-transport"
|
||||
assert control.state == "scanning"
|
||||
assert control.start_projects == starts
|
||||
assert control.stop_calls == stops
|
||||
assert runtime.stop_calls == 0
|
||||
assert service._physical_command_coordinator.snapshot() is physical # noqa: SLF001
|
||||
|
||||
|
||||
def test_incident_host_route_streak_wakes_recovery_before_binding_retirement(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@@ -34813,3 +34872,54 @@ def test_completed_acquisition_does_not_imply_control_loss(tmp_path, socket_open
|
||||
{**control, "state": "failed"}, {"source_mode": "idle"},
|
||||
)
|
||||
assert not service._connection_supervisor.snapshot().authority.control_allowed # noqa: SLF001
|
||||
|
||||
|
||||
@pytest.mark.parametrize("writer_alive", [False, True])
|
||||
def test_fresh_start_recovers_only_terminated_evidence_writer_marker(
|
||||
tmp_path: Path, writer_alive: bool,
|
||||
) -> None:
|
||||
from k1link.sessions.active import ActiveSessionLease, ActiveSessionLeaseError
|
||||
|
||||
service, runtime = service_with_fake_runtime(tmp_path)
|
||||
control = FakeInteractiveControlSession()
|
||||
service._application_control_session = control # type: ignore[assignment] # noqa: SLF001
|
||||
_seed_supervised_connection(service)
|
||||
prepared = service.prepare_acquisition(
|
||||
_prepare_request(
|
||||
project_name="LEASE_RECOVERY",
|
||||
host="192.168.1.20",
|
||||
compatibility_attestation=ATTESTATION,
|
||||
)
|
||||
)
|
||||
root = service.evidence_root
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
interrupted = root / "20260813T120000Z_viewer_live"
|
||||
interrupted.mkdir()
|
||||
original_evidence = interrupted / "preserved.raw"
|
||||
original_evidence.write_bytes(b"synthetic interrupted evidence")
|
||||
owner = ActiveSessionLease.acquire(root, interrupted) if writer_alive else None
|
||||
if owner is None:
|
||||
(root / ".current_session").write_text(interrupted.name + "\n")
|
||||
try:
|
||||
request = _start_request(
|
||||
acquisition_id=prepared["acquisition"]["acquisition_id"],
|
||||
physical_acceptance=PHYSICAL_ACCEPTANCE,
|
||||
)
|
||||
if writer_alive:
|
||||
with pytest.raises(ActiveSessionLeaseError):
|
||||
service.start_acquisition(request)
|
||||
assert runtime.start_calls == []
|
||||
assert control.start_projects == []
|
||||
assert (root / ".current_session").read_text().strip() == interrupted.name
|
||||
else:
|
||||
service.start_acquisition(request)
|
||||
assert len(runtime.start_calls) == 1
|
||||
assert control.start_projects == ["LEASE_RECOVERY"]
|
||||
assert (root / ".current_session").read_text().strip() != interrupted.name
|
||||
assert original_evidence.read_bytes() == b"synthetic interrupted evidence"
|
||||
finally:
|
||||
if owner is not None:
|
||||
owner.release()
|
||||
lease = service._acquisition_session_lease # noqa: SLF001
|
||||
if lease is not None:
|
||||
lease.release()
|
||||
|
||||
@@ -272,6 +272,11 @@ def _prepare_and_activate_checkpoint(
|
||||
service._application_control_session.snapshot = lambda: { # type: ignore[method-assign]
|
||||
"verified_control": _verified_control(connection)
|
||||
}
|
||||
# Camera admission now reads the control-only projection. Both projections
|
||||
# must observe the same synthetic dialogue, including later epoch updates.
|
||||
service._application_control_session.snapshot_control_only = ( # type: ignore[method-assign]
|
||||
lambda: service._application_control_session.snapshot() # noqa: SLF001
|
||||
)
|
||||
service._observe_start_preparation_checkpoint( # noqa: SLF001
|
||||
"prepared",
|
||||
context,
|
||||
@@ -317,9 +322,15 @@ def _prepare_and_activate_checkpoint(
|
||||
service._observe_application_scanning_checkpoint() # noqa: SLF001
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prior_rebind", [False, True])
|
||||
@pytest.mark.parametrize("standby_committed", [False, True])
|
||||
@pytest.mark.parametrize("changed_ip", [False, True])
|
||||
def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
prior_rebind: bool,
|
||||
standby_committed: bool,
|
||||
changed_ip: bool,
|
||||
) -> None:
|
||||
"""Fresh READY after Apply settles the old START and its checkpoint.
|
||||
|
||||
@@ -340,28 +351,29 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
current = ledger.snapshot().record
|
||||
assert current is not None
|
||||
|
||||
active_rebind_connection = _connection(
|
||||
control_session_id="checkpoint-reset-active-rebind-control",
|
||||
host_path_epoch=2,
|
||||
producer_generation=2,
|
||||
)
|
||||
current = ledger.rebind_resolved_active(
|
||||
current.operation_id,
|
||||
reconciliation_id="checkpoint-reset-active-rebind",
|
||||
verified_binding=PhysicalCommandVerifiedBinding(
|
||||
verification_id="checkpoint-reset-active-rebind.device-info",
|
||||
identity=current.identity,
|
||||
connection=active_rebind_connection,
|
||||
device_info_message_sha256="2" * 64,
|
||||
verified_at_utc="2026-08-13T12:01:00.000Z",
|
||||
),
|
||||
observation=_status(
|
||||
active_rebind_connection,
|
||||
"scanning",
|
||||
source="explicit-read-only-reconciliation",
|
||||
observed_at_utc="2026-08-13T12:01:01.000Z",
|
||||
),
|
||||
)
|
||||
if prior_rebind:
|
||||
active_rebind_connection = _connection(
|
||||
control_session_id="checkpoint-reset-active-rebind-control",
|
||||
host_path_epoch=2,
|
||||
producer_generation=2,
|
||||
)
|
||||
current = ledger.rebind_resolved_active(
|
||||
current.operation_id,
|
||||
reconciliation_id="checkpoint-reset-active-rebind",
|
||||
verified_binding=PhysicalCommandVerifiedBinding(
|
||||
verification_id="checkpoint-reset-active-rebind.device-info",
|
||||
identity=current.identity,
|
||||
connection=active_rebind_connection,
|
||||
device_info_message_sha256="2" * 64,
|
||||
verified_at_utc="2026-08-13T12:01:00.000Z",
|
||||
),
|
||||
observation=_status(
|
||||
active_rebind_connection,
|
||||
"scanning",
|
||||
source="explicit-read-only-reconciliation",
|
||||
observed_at_utc="2026-08-13T12:01:01.000Z",
|
||||
),
|
||||
)
|
||||
for cycle in (1, 2):
|
||||
retired = ledger.retire_unavailable_target(
|
||||
retirement_id=f"checkpoint-reset-retirement-{cycle}",
|
||||
@@ -379,7 +391,7 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
reason="reset-network-intent-read-only-settlement",
|
||||
)
|
||||
assert current.stage == "observing"
|
||||
assert current.reconciled_physical_state == "active"
|
||||
assert current.reconciled_physical_state == ("active" if prior_rebind else None)
|
||||
|
||||
# The persisted ACTIVE checkpoint belongs to the process that owned the
|
||||
# original receiver. The real failure was observed after a service
|
||||
@@ -391,6 +403,8 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
host_path_epoch=4,
|
||||
producer_generation=4,
|
||||
)
|
||||
if changed_ip:
|
||||
ready_connection = replace(ready_connection, target_ipv4="192.168.68.51")
|
||||
coordinator = service._physical_command_coordinator # noqa: SLF001
|
||||
coordinator.application_response(
|
||||
ApplicationMqttResponseEvidence(
|
||||
@@ -435,6 +449,12 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
lambda: None,
|
||||
)
|
||||
|
||||
if standby_committed:
|
||||
# The physical READY fsync survived but the checkpoint commit did not.
|
||||
coordinator.reconcile_resolved_active(reconciliation_id="checkpoint-reset-ready-verify.physical")
|
||||
service._mark_active_acquisition_checkpoint_untrusted( # noqa: SLF001
|
||||
trust="unavailable", reason_code="active-acquisition-recovery-checkpoint-error"
|
||||
)
|
||||
result = asyncio.run(
|
||||
service._reconcile_physical_command_after_verify_owned( # noqa: SLF001
|
||||
verify_operation_id="checkpoint-reset-ready-verify",
|
||||
@@ -442,8 +462,8 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
)
|
||||
)
|
||||
|
||||
assert result["performed"] is True
|
||||
assert result["resolution"] == "physical-standby-observed"
|
||||
assert result["performed"] is (not standby_committed)
|
||||
assert result["resolution"] == (None if standby_committed else "physical-standby-observed")
|
||||
settled = ledger.snapshot().record
|
||||
assert settled is not None
|
||||
assert settled.stage == "resolved"
|
||||
@@ -1899,6 +1919,67 @@ def test_chained_stop_facade_cessation_uses_real_ledger_ancestry(
|
||||
assert checkpoint.cessation_physical_proof.operation_id == final_record.operation_id
|
||||
assert checkpoint.cessation_physical_proof.ancestor_chain == ancestry
|
||||
|
||||
# A later snapshot may revisit an already durable cessation after a
|
||||
# transient diagnostic failure. Clear only this acquisition's stale reason;
|
||||
# never mutate its journal or hide a different acquisition/trust failure.
|
||||
reason = "active-acquisition-recovery-checkpoint-cease-failed"
|
||||
service._set_active_acquisition_checkpoint_reason(reason) # noqa: SLF001
|
||||
request = dict(
|
||||
expected_acquisition_id=ACQUISITION_ID,
|
||||
expected_start_operation_id=START_OPERATION_ID,
|
||||
evidence_session_id=EVIDENCE_SESSION_ID,
|
||||
expected_stop_operation_id=FINAL_STOP_OPERATION_ID,
|
||||
)
|
||||
assert not service._cease_active_acquisition_checkpoint_from_physical_head( # noqa: SLF001
|
||||
**{**request, "expected_acquisition_id": "other-acquisition"},
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason == reason # noqa: SLF001
|
||||
assert service._cease_active_acquisition_checkpoint_from_physical_head(**request) # noqa: SLF001
|
||||
assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
|
||||
assert ActiveAcquisitionRecoveryCheckpointStore(tmp_path).snapshot().checkpoint == checkpoint
|
||||
# Subsequent state polling runs after local receiver/evidence teardown.
|
||||
# It must recognize the same durable terminal, not reintroduce cease-failed.
|
||||
assert service._acquisition is not None # noqa: SLF001
|
||||
service._acquisition = replace(service._acquisition, state="completed") # noqa: SLF001
|
||||
service._acquisition_out_dir = None # noqa: SLF001
|
||||
service._acquisition_stop_operation_id = FINAL_STOP_OPERATION_ID # noqa: SLF001
|
||||
service._set_active_acquisition_checkpoint_reason(reason) # noqa: SLF001
|
||||
for _ in range(2):
|
||||
service._reconcile_acquisition( # noqa: SLF001
|
||||
{"phase": "idle"}, {}, {"state": "completed"},
|
||||
physical_command_proof=service._physical_command_coordinator.snapshot(), # noqa: SLF001
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
|
||||
assert service._acquisition.state == "completed" # noqa: SLF001
|
||||
assert ActiveAcquisitionRecoveryCheckpointStore(tmp_path).snapshot().checkpoint == checkpoint
|
||||
completed_acquisition = service._acquisition # noqa: SLF001
|
||||
for acquisition_id, start_id in (
|
||||
("other-acquisition", START_OPERATION_ID),
|
||||
(ACQUISITION_ID, "other-start"),
|
||||
):
|
||||
service._acquisition = replace( # noqa: SLF001
|
||||
completed_acquisition, acquisition_id=acquisition_id,
|
||||
)
|
||||
service._acquisition_start_operation_id = start_id # noqa: SLF001
|
||||
service._reconcile_acquisition( # noqa: SLF001
|
||||
{"phase": "idle"}, {}, {"state": "completed"},
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason == reason # noqa: SLF001
|
||||
service._acquisition = completed_acquisition # noqa: SLF001
|
||||
service._acquisition_start_operation_id = None # noqa: SLF001
|
||||
service._acquisition_stop_operation_id = None # noqa: SLF001
|
||||
service._reconcile_acquisition( # noqa: SLF001
|
||||
{"phase": "idle"}, {}, {"state": "completed"},
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
|
||||
service._mark_active_acquisition_checkpoint_untrusted( # noqa: SLF001
|
||||
trust="unavailable", reason_code="active-acquisition-recovery-checkpoint-error",
|
||||
)
|
||||
assert service._cease_active_acquisition_checkpoint_from_physical_head(**request) # noqa: SLF001
|
||||
assert service._active_acquisition_checkpoint_reason == ( # noqa: SLF001
|
||||
"active-acquisition-recovery-checkpoint-error"
|
||||
)
|
||||
|
||||
|
||||
def test_restart_ceases_active_checkpoint_after_composite_ordinary_stop(
|
||||
tmp_path: Path,
|
||||
|
||||
@@ -1765,3 +1765,103 @@ def test_close_after_dispatch_precheck_prevents_queued_publish_after_gate_releas
|
||||
assert fake.publish_calls == []
|
||||
assert transport.snapshot().publish_attempts == 0
|
||||
assert evidence.events == []
|
||||
|
||||
|
||||
def test_observed_advisory_does_not_break_existing_control_or_grant_start() -> None:
|
||||
clock = FakeClock()
|
||||
fake = FakeControlClient(clock=clock)
|
||||
transport = ReviewedApplicationMqttTransport(
|
||||
"192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
|
||||
)
|
||||
transport.open()
|
||||
fake.events.extend([
|
||||
("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.SCANNING, project_bound=True, init_ready=True))),
|
||||
("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))),
|
||||
])
|
||||
transport.maintain_open_for(4.0)
|
||||
assert transport.scan_initialization_complete(_binding()) is True
|
||||
assert transport.pre_start_ready(_binding()) is False
|
||||
assert transport.standby_complete(_binding()) is False
|
||||
snapshot = transport.snapshot().as_dict()
|
||||
assert snapshot["system_error_reports"] == 1
|
||||
assert snapshot["latest_system_error_code"] == 0x12041002
|
||||
assert snapshot["publish_attempts"] == 0
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.READY, project_bound=False, init_ready=False))))
|
||||
transport.maintain_open_for(4.0)
|
||||
assert transport.standby_complete(_binding()) is True
|
||||
transport.validate_control_proof(_binding())
|
||||
proof = transport.snapshot()
|
||||
clock.now += 100.0
|
||||
fake.events.append(("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))))
|
||||
transport.maintain_open_for(1.0)
|
||||
assert transport.snapshot().control_proof_revision == proof.control_proof_revision
|
||||
with pytest.raises(ApplicationControlProofStale):
|
||||
transport.validate_control_proof(_binding())
|
||||
assert transport.snapshot().publish_attempts == 0
|
||||
transport.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", [0x32040133, 0x12041003, 0x22041002, 0])
|
||||
def test_unreviewed_or_fault_report_stays_blocking_after_advisory(code: int) -> None:
|
||||
clock = FakeClock()
|
||||
fake = FakeControlClient(clock=clock)
|
||||
transport = ReviewedApplicationMqttTransport(
|
||||
"192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
|
||||
)
|
||||
transport.open()
|
||||
fake.events.extend([
|
||||
("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.SCANNING, project_bound=True, init_ready=True))),
|
||||
("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, code)))),
|
||||
("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))),
|
||||
])
|
||||
transport.maintain_open_for(4.0)
|
||||
with pytest.raises(ApplicationControlDeviceFault):
|
||||
transport.validate_bound_status(_binding())
|
||||
assert transport.snapshot().as_dict()["publish_attempts"] == 0
|
||||
transport.close()
|
||||
|
||||
|
||||
def test_storage_observation_requires_fresh_nonretained_bound_identity():
|
||||
clock = FakeClock()
|
||||
fake = FakeControlClient(clock=clock)
|
||||
transport = ReviewedApplicationMqttTransport(
|
||||
"192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
|
||||
)
|
||||
transport.open()
|
||||
payload = _device_status(SessionState.READY, project_bound=False, init_ready=False)
|
||||
payload += _bytes(7, _uint(4, 1000) + _uint(5, 990))
|
||||
fake.on_message(
|
||||
fake, None, SimpleNamespace(topic=DEVICE_STATUS_TOPIC, payload=payload, retain=True)
|
||||
)
|
||||
assert transport.snapshot().storage_status is None
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, payload)))
|
||||
transport.maintain_open_for(1.0)
|
||||
assert transport.snapshot().storage_status is None
|
||||
transport.validate_control_proof(_binding())
|
||||
value = transport.snapshot().as_dict()["storage_status"]
|
||||
assert value["used_percent"] == 99.0 and value["observed_at"]
|
||||
value["used_percent"] = 0
|
||||
assert transport.snapshot().storage_status["used_percent"] == 99.0
|
||||
next_payload = _device_status(SessionState.READY, project_bound=False, init_ready=False)
|
||||
next_payload += _bytes(7, _uint(4, 1000) + _uint(5, 980))
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, next_payload)))
|
||||
transport.maintain_open_for(1.0)
|
||||
# An idle session need not re-run command admission for each display update.
|
||||
assert transport.snapshot().storage_status["used_percent"] == 98.0
|
||||
# Keep protobuf framing valid by constructing the report with a new serial.
|
||||
wrong_identity = (_bytes(1, _text(4, VENDOR_DEVICE_ID))
|
||||
+ _uint(2, MODELING_STATE_BASE + SessionState.READY)
|
||||
+ _text(3, "other-scanner") + _bytes(7, _uint(4, 1000) + _uint(5, 990)))
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, wrong_identity)))
|
||||
transport.maintain_open_for(1.0)
|
||||
assert transport.snapshot().storage_status is None
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.READY, project_bound=False, init_ready=False))))
|
||||
transport.maintain_open_for(1.0)
|
||||
transport.validate_control_proof(_binding())
|
||||
assert transport.snapshot().storage_status is None
|
||||
assert transport.snapshot().publish_attempts == 0
|
||||
transport.close()
|
||||
|
||||
@@ -306,10 +306,13 @@ class FakeExecutor:
|
||||
observed: Any,
|
||||
*,
|
||||
reconciled_active_observed: Any | None = None,
|
||||
standby_work: Callable[[], None] | None = None,
|
||||
) -> str | None:
|
||||
self.records.append(f"wait:{event}")
|
||||
deadline = time.monotonic() + 2.0
|
||||
while not observed():
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
if (
|
||||
reconciled_active_observed is not None
|
||||
and reconciled_active_observed()
|
||||
@@ -372,8 +375,12 @@ class FakeExecutor:
|
||||
def maintain_post_stop_until_standby(self) -> None:
|
||||
self.records.append("wait:device-standby")
|
||||
|
||||
def maintain_standby_until_next_acquisition(self, requested: Callable[[], bool]) -> None:
|
||||
def maintain_standby_until_next_acquisition(
|
||||
self, requested: Callable[[], bool], *, standby_work: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
while not requested():
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
if self.transport.state == "closed":
|
||||
raise RuntimeError("test transport closed")
|
||||
if not self.transport.proof_fresh:
|
||||
|
||||
@@ -58,7 +58,10 @@ def test_xgrids_compatibility_profile_loads_exact_firmware_and_sources() -> None
|
||||
"bridge": "direct-lan",
|
||||
"direct-connect": "controller-hotspot",
|
||||
"quick-connect": "device-ap",
|
||||
"usb": "usb-ethernet",
|
||||
}
|
||||
assert LOADER.matches_target(profile, firmware="3.0.2", topology="usb-ethernet")
|
||||
assert not LOADER.matches_target(profile, firmware="3.0.3", topology="usb-ethernet")
|
||||
assert LOADER.matches_target(profile, firmware="3.0.2", topology="direct-lan")
|
||||
assert LOADER.matches_target(profile, firmware="3.0.2", topology="device-ap")
|
||||
assert LOADER.matches_target(
|
||||
|
||||
@@ -351,10 +351,14 @@ def test_cold_scenario_reset_is_local_only_and_exact_retry_converges(
|
||||
"network_write_performed": False,
|
||||
"automatic_scan": False,
|
||||
"operation_sequence": 0,
|
||||
"timing": first["connection_scenario_reset"]["timing"],
|
||||
}
|
||||
assert first["devices"] == []
|
||||
assert first["selected_device_id"] is None
|
||||
assert first["connection_attempt"] is None
|
||||
timing = first["connection_scenario_reset"]["timing"]
|
||||
assert timing["completed_at_utc"]
|
||||
assert all(value >= 0 for key, value in timing.items() if key.endswith("_ms"))
|
||||
assert first["connection_scenario_reset_pending"] is None
|
||||
assert service.state()["connection_scenario_reset_pending"] is None
|
||||
assert first["connection_policy"]["actions"]["scan-ble"]["allowed"] is True
|
||||
|
||||
@@ -343,3 +343,25 @@ def test_state_machine_surfaces_faults_without_claiming_save() -> None:
|
||||
)
|
||||
assert unknown.phase is AcquisitionPhase.UNKNOWN
|
||||
assert not unknown.durable_save_complete
|
||||
|
||||
|
||||
@pytest.mark.parametrize("system,expected", [
|
||||
(_uint(4, 1001324032) + _uint(5, 991202816), 98.9892167094218),
|
||||
(_uint(4, 1000), 0.0),
|
||||
(_uint(4, 1000) + _uint(5, 1000), 100.0),
|
||||
(b"", None),
|
||||
(_uint(4, 0) + _uint(5, 20), None),
|
||||
(_uint(4, 10) + _uint(5, 20), None),
|
||||
(_uint(4, 10) + _uint(4, 20), None),
|
||||
(_uint(4, 10) + _uint(5, (1 << 64) - 1), None),
|
||||
(_bytes(4, b"wrong-wire"), None),
|
||||
(b"\x20\x80", None),
|
||||
])
|
||||
def test_optional_storage_ratio_never_changes_modeling_state(system, expected):
|
||||
result = decode_device_status_report(_device_status(SessionState.READY) + _bytes(7, system))
|
||||
assert result.session_state is SessionState.READY
|
||||
assert result.system_status_present
|
||||
if expected is None:
|
||||
assert result.storage_used_percent is None
|
||||
else:
|
||||
assert result.storage_used_percent == pytest.approx(expected, abs=0.0001)
|
||||
|
||||
@@ -2878,6 +2878,95 @@ def test_repeated_resolved_start_retire_reopen_settles_fresh_ready_as_cessation(
|
||||
assert settled.reconciliations[-1].original_attempt.operation_id == START_OPERATION
|
||||
|
||||
|
||||
@pytest.mark.parametrize("observed_state", ["ready", "scanning"])
|
||||
@pytest.mark.parametrize("reset_count", [1, 2])
|
||||
@pytest.mark.parametrize("proof_fault", [None, "retained", "identity", "old-session"])
|
||||
def test_first_successful_start_reset_reopens_without_prior_rebind(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
observed_state: str,
|
||||
reset_count: int,
|
||||
proof_fault: str | None,
|
||||
) -> None:
|
||||
"""The first reset has no prior reconciliation to supply an active state."""
|
||||
ledger = _ledger(tmp_path, monkeypatch)
|
||||
_prepare_start(ledger)
|
||||
_complete_start(ledger)
|
||||
original = ledger.snapshot().record
|
||||
assert original is not None
|
||||
current = original
|
||||
for cycle in range(reset_count):
|
||||
retired = ledger.retire_unavailable_target(
|
||||
retirement_id=f"first-start-reset-{cycle}",
|
||||
expected_operation_id=current.operation_id,
|
||||
expected_revision=current.revision,
|
||||
expected_transport_ref=current.connection.transport_ref,
|
||||
reason="connection-scenario-reset-by-operator",
|
||||
)
|
||||
current = ledger.reopen_retired_reconciliation(
|
||||
reopening_id=f"first-start-reopen-{cycle}",
|
||||
expected_revision=retired.revision,
|
||||
expected_retirement_id=f"first-start-reset-{cycle}",
|
||||
expected_transport_ref=retired.connection.transport_ref,
|
||||
expected_discovery_generation=40 + cycle,
|
||||
reason="reset-network-intent-read-only-settlement",
|
||||
)
|
||||
assert current.stage == "observing"
|
||||
assert current.reconciled_physical_state is None
|
||||
assert current.reopened_resolved_start_requires_reconciliation
|
||||
connection = _reconciliation_connection()
|
||||
settle = (
|
||||
ledger.observe_resolved_active_standby
|
||||
if observed_state == "ready"
|
||||
else ledger.rebind_resolved_active
|
||||
)
|
||||
binding = _verified_binding(connection=connection)
|
||||
observation = _status(
|
||||
observed_state,
|
||||
connection=connection,
|
||||
source="explicit-read-only-reconciliation",
|
||||
observed_at="2026-08-07T09:34:00.000Z",
|
||||
)
|
||||
if proof_fault == "retained":
|
||||
observation = replace(observation, mqtt_retained=True)
|
||||
elif proof_fault == "identity":
|
||||
binding = replace(binding, identity=replace(IDENTITY, device_serial_sha256="9" * 64))
|
||||
elif proof_fault == "old-session":
|
||||
binding = replace(binding, connection=original.connection)
|
||||
if proof_fault is not None:
|
||||
before = ledger.path.read_bytes()
|
||||
with pytest.raises(PhysicalCommandTransitionError):
|
||||
settle(
|
||||
START_OPERATION,
|
||||
reconciliation_id="first-reset-invalid-state",
|
||||
verified_binding=binding,
|
||||
observation=observation,
|
||||
)
|
||||
assert ledger.path.read_bytes() == before
|
||||
return
|
||||
settled = settle(
|
||||
START_OPERATION,
|
||||
reconciliation_id="first-reset-fresh-state",
|
||||
verified_binding=binding,
|
||||
observation=observation,
|
||||
)
|
||||
assert settled.stage == "resolved"
|
||||
assert settled.resolution == "start-active-observed"
|
||||
assert settled.original_command_outcome == "succeeded"
|
||||
assert settled.reconciled_physical_state == (
|
||||
"standby" if observed_state == "ready" else "active"
|
||||
)
|
||||
assert settled.reconciliations[-1].kind == (
|
||||
"resolved-active-cessation" if observed_state == "ready" else "resolved-active-rebind"
|
||||
)
|
||||
assert settled.operator_retirements[0].original_attempt.as_dict() == (
|
||||
settled.reconciliations[-1].original_attempt.as_dict()
|
||||
)
|
||||
assert settled.application_response == original.application_response
|
||||
assert settled.payload_sha256 == original.payload_sha256
|
||||
assert PhysicalCommandLedger(tmp_path / "repository", clock=_clock).snapshot().record == settled
|
||||
|
||||
|
||||
def test_legacy_v1_unresolved_attempt_retires_atomically_into_strict_v2(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
Reference in New Issue
Block a user