"""Durability, identity admission, decoder and shared VPS assignment acceptance.""" import asyncio import base64 import hashlib import importlib import json import shutil import struct import sys import time from pathlib import Path import pytest from k1link.device_plugins.arnavi_b2 import internal from k1link.fleet.vps_hosts import VPSHosts ROOT = Path(__file__).resolve().parents[1] def test_transport_ack_prefix_and_abort_are_observations_only(store, monkeypatch): from ndc_vps import delivery class Writer: kernel = 0 closed = False buffer = 0 def __init__(self): self.transport = self def get_extra_info(self, _): return self def setsockopt(self, *args): pass def is_closing(self): return self.closed def write(self, data): self.kernel += len(data) def get_write_buffer_size(self): return self.buffer def abort(self): self.closed = True self.kernel = self.buffer = 0 async def exercise(): writer, first, second = Writer(), [], [] monkeypatch.setattr(delivery, "queued_bytes", lambda _: writer.kernel) guard = delivery.Delivery(writer) guard.write(b"header") guard.write(b"one", time.monotonic() + 1, lambda *x: first.append(x)) guard.write(b"two", time.monotonic() + 1, lambda *x: second.append(x)) writer.kernel = 3 # Only the later command is still unacknowledged. guard.check() assert [x[0] for x in first] == ["written", "tcp_acknowledged"] assert [x[0] for x in second] == ["written"] guard.abort() guard.abort() assert [x[0] for x in second] == ["written", "unconfirmed"] assert second[-1][3] == "connection_closed" assert first[-1][2] >= 0 for queued in (None, 3): writer, observed = Writer(), [] monkeypatch.setattr(delivery, "queued_bytes", lambda _, q=queued: q) guard = delivery.Delivery(writer) guard.write(b"cmd", time.monotonic() + 0.01, lambda *x, log=observed: log.append(x)) await asyncio.sleep(0.03) assert [x[0] for x in observed] == ["written", "unconfirmed"] assert observed[-1][3] == "delivery_deadline" writer, observed = Writer(), [] guard = delivery.Delivery(writer) with pytest.raises(TimeoutError): guard.write(b"cmd", time.monotonic() - 1, lambda *x: observed.append(x)) assert [x[0] for x in observed] == ["unconfirmed"] assert observed[0][3] == "expired_before_write" asyncio.run(exercise()) def test_transport_journal_survives_crash_without_promoting_command(store): from ndc_vps.commands import Commands imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) commands = Commands(store) commands.sessions[imei] = {"private-session"} request = dict(id="a" * 32, imei=imei, kind="request-position", model=231, firmware="0.01") commands.submit(request) _, _, ticket = commands.take_delivery(imei, "private-session", with_receipt=True) assert commands.get(request["id"])["transport"][0]["state"] == "prepared" now = time.time() commands.transport.record([(ticket, "written", now, 0, None)]) assert commands.get(request["id"])["state"] == "dispatched" commands.transport.record([(ticket, "tcp_acknowledged", now + .5, .5, None)]) value = commands.get(request["id"]) assert value["state"] == "dispatched" # Not proof of B2 execution. assert value["transport"][0]["tcp_ack_seconds"] == .5 assert commands.submit(request) == value # Lost API response reuses the same facts. assert "private-session" not in json.dumps(value["transport"]) # A late close cannot erase an observed ACK; restart preserves it. commands.transport.record([(ticket, "unconfirmed", now + 1, 1, "connection_closed")]) commands = Commands(store) assert commands.get(request["id"])["transport"][0]["state"] == "tcp_acknowledged" assert commands.get(request["id"])["state"] == "uncertain" request["id"] = "b" * 32 commands.sessions[imei] = {"new-session"} commands.submit(request) _, _, ticket = commands.take_delivery(imei, "new-session", with_receipt=True) commands.transport.record([(ticket, "written", now + 2, 0, None)]) commands = Commands(store) value = commands.get(request["id"]) assert value["transport"][0]["state"] == "unconfirmed" assert value["transport"][0]["reason"] == "host_restarted" assert commands.take_delivery(imei, "new-session", with_receipt=True) is None def test_transport_observations_commit_when_socket_cancels_sender(store, monkeypatch): from ndc_vps.service import Service async def exercise(): imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) service = Service(store) service.commands.sessions[imei] = {"live"} service.commands.session_activity[imei, "live"] = time.monotonic() request = dict(id="a" * 32, imei=imei, kind="request-position", model=231, firmware="0.01") service.commands.submit(request) entered, resume = asyncio.Event(), asyncio.Event() original = asyncio.to_thread async def controlled(function, *args, **kwargs): if function == service.commands.transport.record: entered.set() await resume.wait() return await original(function, *args, **kwargs) monkeypatch.setattr(asyncio, "to_thread", controlled) class Writer: def is_closing(self): return False async def drain(self): pass class Delivery: observer = None def ready(self): return True def write(self, data, deadline, observe): self.observer = observe observe("written", time.time(), 0, None) def abort(self): if self.observer: self.observer("unconfirmed", time.time(), .1, "connection_closed") self.observer = None sender = asyncio.create_task(service.send_commands(imei, Writer(), "live", Delivery())) await asyncio.wait_for(entered.wait(), 2) sender.cancel() await asyncio.sleep(0) resume.set() await asyncio.gather(sender, return_exceptions=True) observed = service.commands.get(request["id"])["transport"] assert len(observed) == 1 assert observed[0]["written_at"] <= observed[0]["closed_at"] assert observed[0]["state"] == "unconfirmed" assert observed[0]["reason"] == "connection_closed" asyncio.run(exercise()) def test_diagnostic_probe_needs_live_exclusive_observation_and_never_replays(store): from ndc_vps import actions from ndc_vps.commands import Commands from ndc_vps.observation import Observation imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) commands = Commands(store) commands.sessions[imei] = {"original"} request = { "id": "a" * 32, "imei": imei, "model": 231, "firmware": "0.01", "kind": "probe-diagnostic-mode", "observation_id": "b" * 32, } with pytest.raises(ValueError, match="observation"): actions.prepare({k: v for k, v in request.items() if k != "observation_id"}) with pytest.raises(ValueError, match="unknown action fields"): actions.prepare({**request, "binary": "0107"}) with pytest.raises(ValueError, match="observation unavailable"): commands.submit(request) observation = Observation(store) observation.arm({"id": request["observation_id"]}) commands.submit(request) # Closing an armed window before dispatch prevents any device command. observation.close(request["observation_id"]) assert commands.take(imei, "original") is None assert commands.get(request["id"])["state"] == "expired" request = {**request, "id": "d" * 32, "observation_id": "e" * 32} observation.arm({"id": request["observation_id"]}) commands.submit(request) wire = commands.take(imei, "original") assert wire[:3] == bytes.fromhex("7b07ff") assert wire[4] == 0xff and wire[9:] == bytes.fromhex("01007d") assert wire[3] == sum(wire[4:-1]) % 256 assert commands.take(imei, "original") is None assert "diagnostic_imei" not in observation.get(request["observation_id"]) # Same request ID is a lookup, even after a restart; no second toggle. commands = Commands(store) commands.sessions[imei] = {"reconnected"} assert commands.submit(request)["state"] == "uncertain" assert commands.take(imei, "reconnected") is None with pytest.raises(ValueError, match="observation already used"): commands.submit({**request, "id": "f" * 32}) def test_diagnostic_probe_expired_lease_and_changed_request_are_rejected(store, monkeypatch): from ndc_vps import observation as module from ndc_vps.commands import Commands imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) commands = Commands(store) commands.sessions[imei] = {"original"} observer = module.Observation(store) request = { "id": "a" * 32, "imei": imei, "model": 231, "firmware": "0.01", "kind": "probe-diagnostic-mode", "observation_id": "b" * 32, } lease = observer.arm({"id": request["observation_id"]}) monkeypatch.setattr(module.time, "time", lambda: lease["expires_at"] + 1) with pytest.raises(ValueError, match="observation unavailable"): commands.submit(request) def test_delivery_deadline_covers_kernel_and_asyncio_buffers(store, monkeypatch): from ndc_vps import delivery class Socket: def setsockopt(self, *args): pass class Writer: def __init__(self): self.transport = self self.data = [] self.kernel = 0 self.buffer = 0 self.closed = False def get_extra_info(self, name): return Socket() def write(self, data): self.data.append(data) self.kernel += len(data) def get_write_buffer_size(self): return self.buffer def is_closing(self): return self.closed def abort(self): self.closed = True self.buffer = self.kernel = 0 async def exercise(): for kernel, buffer in ((12, 0), (0, 12), (5, 7)): writer = Writer() monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel) guard = delivery.Delivery(writer) guard.write(b"c" * 12, time.monotonic() + 0.03) writer.kernel, writer.buffer = kernel, buffer await asyncio.sleep(0.06) assert writer.closed and writer.kernel == writer.buffer == 0 # An ACK for the command releases its deadline even with a newer ACK # or command queued behind it. Later writes cannot extend its lifetime. writer = Writer() monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel) guard = delivery.Delivery(writer) guard.write(b"header") guard.write(b"first", time.monotonic() + 0.03) guard.write(b"second", time.monotonic() + 1) writer.kernel = len(b"second") guard.check() await asyncio.sleep(0.06) assert not writer.closed guard.abort() assert guard.timer is None writer = Writer() monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel) guard = delivery.Delivery(writer) guard.write(b"first", time.monotonic() + 0.03) guard.write(b"second", time.monotonic() + 1) await asyncio.sleep(0.06) assert writer.closed writer = Writer() guard = delivery.Delivery(writer) monkeypatch.setattr(delivery, "queued_bytes", lambda sock: writer.kernel) assert guard.ready() writer.buffer = 1 assert not guard.ready() writer.buffer, writer.kernel = 0, 1 assert not guard.ready() writer.kernel = 0 assert guard.ready() with pytest.raises(TimeoutError): guard.write(b"expired", time.monotonic() - 1) assert not writer.data and writer.closed asyncio.run(exercise()) def test_transport_expiry_never_replays_or_claims_device_confirmation(store, monkeypatch): from ndc_vps.commands import Commands imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) commands = Commands(store) commands.sessions[imei] = {"old"} body = { "id": "a" * 32, "imei": imei, "kind": "request-position", "model": 231, "firmware": "0.01", } queued = commands.submit(body) data, deadline = commands.take_delivery(imei, "old") assert data and 0 < deadline - time.monotonic() <= 30 assert commands.get(body["id"])["state"] == "dispatched" commands.sessions[imei] = {"new"} assert commands.take_delivery(imei, "new") is None monkeypatch.setattr(time, "time", lambda: queued["expires_at"] + 1) assert commands.get(body["id"])["state"] == "unconfirmed" assert commands.take_delivery(imei, "new") is None assert commands.submit(body)["state"] == "unconfirmed" recovered = Commands(store) recovered.sessions[imei] = {"new"} assert recovered.get(body["id"])["state"] == "unconfirmed" assert recovered.take_delivery(imei, "new") is None def package(timestamp=None, lat=55.1, lon=37.2): tags = ( b"\x03" + struct.pack(" 0 command.submit(body) command.take(body["imei"], "live") command.web_receive(wire(5, before.encode()), "192.0.2.1") before_clock = command.get(body["id"]) assert before_clock["stage"] == "write" and before_clock["state"] == "queued" now[0] += 1 assert command.web_receive(wire(7), "192.0.2.1") == time_reply(int(now[0])) != first assert command.get(body["id"]) == before_clock command.store.set_devices([]) assert command.web_receive(wire(7), "192.0.2.1") is None def test_core_admits_only_independently_observed_numeric_id(tmp_path, monkeypatch): from k1link.fleet import vps_hosts hosts = VPSHosts(tmp_path, "core", None) devices = [ {"id": "a" * 32, "identity_key": "123456789012345", "observed": {"device_id": "74565"}}, {"id": "b" * 32, "identity_key": "223456789012345", "observed": {}}, ] monkeypatch.setattr(hosts, "devices", lambda row: devices) monkeypatch.setattr(hosts, "ingest", lambda *args: 0) monkeypatch.setattr(hosts, "save", lambda row: None) calls = [] def call(host, method, path, body=None): calls.append((path, body)) return {"items": []} monkeypatch.setattr(vps_hosts, "request", call) hosts.sync({"cursor": 0}) items = calls[0][1]["items"] assert items[0]["device_id"] == 74565 assert "device_id" not in items[1] assert set(items[0]) == {"imei", "instance_id", "device_id"} @pytest.mark.parametrize( "readback_kind, expected_state", [("unchanged", "not_applied"), ("partial", "uncertain")] ) def test_full_configuration_ignored_or_partial_write_is_never_success_or_replayed( full_context, readback_kind, expected_state ): """A delivered image and SERV OK are insufficient when readback disagrees. The bench accepted the trajectory control but returned the old image for polling-interval changes. Preserve this failure contract without a real configuration, identity, credential or invented device reply fixture. """ from ndc_vps.commands import Commands from ndc_vps.usb_protocol import Configuration, Setting command, body, before, target, wire, now = full_context command.submit(body) command.take(body["imei"], "live") command.web_receive(wire(5, before.encode()), "192.0.2.1") now[0] += 16 command.take(body["imei"], "live") delivered = command.web_receive(wire(2), "192.0.2.1") assert delivered is not None command.receive(body["imei"], text_package("SERV OK", now[0]), "live") assert command.get(body["id"])["state"] == "queued" # Even a matching unsolicited upload before the independent read must not # complete the write or turn its ACK into settings verification. command.web_receive(wire(5, target.encode()), "192.0.2.1") assert command.get(body["id"])["state"] == "queued" now[0] += 16 command.take(body["imei"], "live") readback = before if readback_kind == "partial": readback = Configuration( tuple( Setting(r.number, b"different-unknown" if r.number == 222 else r.value) for r in target.records ) ) command.web_receive(wire(5, readback.encode()), "192.0.2.1") receipt = command.get(body["id"]) assert receipt["state"] == expected_state assert receipt["configuration"] == readback.encode().hex() assert receipt["configuration_sha256"] == hashlib.sha256(readback.encode()).hexdigest() assert command.submit(body) == receipt # a lost-response retry is a read assert command.web_receive(wire(2), "192.0.2.1") is None assert command.take(body["imei"], "live") is None # Neither a later uncorrelated upload nor a service restart changes the # recorded outcome, and neither can replay the original settings image. command.web_receive(wire(5, target.encode()), "192.0.2.1") assert command.get(body["id"]) == receipt restarted = Commands(command.store) assert restarted.get(body["id"]) == receipt assert restarted.take(body["imei"], "live") is None @pytest.fixture def sim_context(full_context, monkeypatch): from ndc_vps.usb_protocol import Configuration, Setting command, body, before, _, wire, now = full_context monkeypatch.setattr("ndc_vps.commands.time.monotonic", lambda: now[0] - 1700000000) before = Configuration(before.records + (Setting(72, (2072).to_bytes(4, "big")),)) target = Configuration( tuple( Setting(r.number, (2072 | (1 << 10)).to_bytes(4, "big") if r.number == 72 else r.value) for r in before.records ) ) body.update( kind="select-sim", sim_slot=2, expected_sha256=hashlib.sha256(before.encode()).hexdigest(), target_configuration=target.encode().hex(), ) return command, body, before, target, wire, now def reach_sim_restart(context, unchanged=False): command, body, before, target, wire, now = context if unchanged: body["expected_sha256"] = hashlib.sha256(target.encode()).hexdigest() before = target command.submit(body) command.session_activity[body["imei"], "live"] = time.monotonic() command.take(body["imei"], "live") command.web_receive(wire(5, before.encode()), "192.0.2.1") if not unchanged: now[0] += 16 command.session_activity[body["imei"], "live"] = time.monotonic() command.take(body["imei"], "live") assert command.web_receive(wire(2), "192.0.2.1") now[0] += 16 command.session_activity[body["imei"], "live"] = time.monotonic() command.take(body["imei"], "live") command.web_receive(wire(5, target.encode()), "192.0.2.1") assert command.get(body["id"])["state"] == "queued" assert command.get(body["id"])["stage"] == "restart" def sim_packet(timestamp, slot=2, gsm=4): tags = bytes([99]) + ((gsm << 2) | ((slot - 1) << 5) | (1 << 6) | (1 << 9)).to_bytes( 4, "little" ) data = int(timestamp).to_bytes(4, "little") + tags return b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]" @pytest.mark.parametrize("unchanged", [False, True]) def test_sim_switch_only_completes_after_new_session_target_sim_gprs(sim_context, unchanged): command, body, _, target, wire, now = sim_context reach_sim_restart(sim_context, unchanged) raw = command.take(body["imei"], "live") assert raw[-3:-1] == b"\x01\x07" assert command.take(body["imei"], "live") is None command.web_receive(wire(5, target.encode()), "192.0.2.1") assert command.get(body["id"])["state"] == "dispatched" now[0] += 2 command.session_started[body["imei"], "new"] = now[0] - 1700000000 now[0] += 50 command.receive(body["imei"], sim_packet(now[0]), "new") result = command.get(body["id"]) assert result["state"] == "sim_selected" and result["active_sim"] == 2 assert result["reconnect_seconds"] == 52 assert command.submit(body) == result assert not {"binary", "token", "password", "restart_sessions"} & result.keys() @pytest.mark.parametrize( "mode", [ "old-session", "early-session", "no-session", "archive", "future", "wrong-sim", "no-gprs", "no-ds2", "late", ], ) def test_sim_switch_rejects_insufficient_telemetry(sim_context, mode): command, body, _, _, _, now = sim_context reach_sim_restart(sim_context) command.take(body["imei"], "live") dispatched = now[0] now[0] += 20 session = "live" if mode == "old-session" else "new" if mode != "no-session": command.session_started[body["imei"], session] = ( dispatched - 1700000000 + (-1 if mode == "early-session" else 1) ) stamp = dispatched - 30 if mode == "archive" else now[0] + 60 if mode == "future" else now[0] raw = sim_packet(stamp, slot=1 if mode == "wrong-sim" else 2, gsm=3 if mode == "no-gprs" else 4) if mode == "no-ds2": raw = package(timestamp=now[0]) if mode == "late": now[0] += 400 command.receive(body["imei"], raw, session) assert command.get(body["id"])["state"] == ("uncertain" if mode == "late" else "dispatched") @pytest.mark.parametrize("dispatch", [False, True]) def test_sim_switch_service_restart_never_replays_modem_restart(sim_context, dispatch): from ndc_vps.commands import Commands command, body, _, _, _, _ = sim_context reach_sim_restart(sim_context) if dispatch: command.take(body["imei"], "live") restored = Commands(command.store) assert restored.get(body["id"])["state"] == "uncertain" assert restored.take(body["imei"], "live") is None @pytest.mark.parametrize("slot", [True, 0, 3, "2", 1]) def test_sim_selection_rejects_invalid_slot_and_disagreeing_flags(sim_context, slot): command, body, *_ = sim_context with pytest.raises(ValueError): command.submit({**body, "sim_slot": slot}) def test_offline_read_waits_across_host_restart_but_never_replays_after_dispatch( store, monkeypatch ): from ndc_vps.commands import Commands now = [1800000000.0] monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0]) imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) body = { "id": "e" * 32, "imei": imei, "kind": "request-position", "model": 231, "firmware": "0.01", "not_after": now[0] + 25, } command = Commands(store) accepted = command.submit(body) assert accepted["state"] == "queued" assert command.take(imei, "unregistered") is None now[0] += 6 command = Commands(store) assert command.get(body["id"])["state"] == "queued" command.sessions[imei] = {"reconnected"} assert command.submit(body)["expires_at"] == accepted["expires_at"] assert command.take(imei, "reconnected") is not None command = Commands(store) command.sessions[imei] = {"again"} assert command.submit(body)["state"] == "uncertain" assert command.take(imei, "again") is None assert command.wait_delay(imei) is None def test_original_deadline_and_terminal_history_survive_duplicate_post(store, monkeypatch): from ndc_vps.commands import Commands now = [1800000000.0] monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0]) imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) command = Commands(store) body = { "id": "e" * 32, "imei": imei, "kind": "request-position", "model": 231, "firmware": "0.01", "not_after": now[0] + 10, } command.submit(body) now[0] += 11 command.sessions[imei] = {"late"} assert command.submit(body)["state"] == "expired" assert command.take(imei, "late") is None assert Commands(store).get(body["id"])["state"] == "expired" with pytest.raises(ValueError, match="idempotency"): command.submit({**body, "not_after": now[0] + 10}) # A request whose initial HTTP delivery itself was delayed is recorded, # but must never execute even if the tracker is online on arrival. assert command.submit({**body, "id": "f" * 32})["state"] == "expired" assert command.take(imei, "late") is None assert command.wait_delay(imei) is None def test_effectful_action_cannot_cross_its_original_request_deadline(store, monkeypatch): from ndc_vps.commands import Commands now = [1800000000.0] monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0]) imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) command = Commands(store) command.sessions[imei] = {"present"} body = { "id": "e" * 32, "imei": imei, "kind": "pulse-output", "model": 231, "firmware": "0.01", "pin": 4, "seconds": 1, "not_after": now[0] + 1, } command.submit(body) now[0] += 2 assert command.take(imei, "present") is None assert command.submit(body)["state"] == "expired" with pytest.raises(ValueError): command.submit({**body, "id": "f" * 32, "not_after": float("nan")}) def test_idle_sender_wakes_on_command_without_periodic_history_poll(store, monkeypatch): from ndc_vps.service import Service imei = "123456789012345" store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) async def exercise(): service = Service(store) service.commands.sessions[imei] = {"present"} service.commands.session_activity[imei, "present"] = time.monotonic() - 20 original = service.commands.take_delivery checks = [] writes = [] written = asyncio.Event() available = [False] def take(*args, **kwargs): checks.append(time.monotonic()) return original(*args, **kwargs) monkeypatch.setattr(service.commands, "take_delivery", take) class Writer: def is_closing(self): return False async def drain(self): pass class Delivery: def ready(self): return available[0] def write(self, data, deadline, observe=None): writes.append(data) written.set() def abort(self): pass task = asyncio.create_task(service.send_commands(imei, Writer(), "present", Delivery())) try: await asyncio.sleep(1.1) assert len(checks) == 1 service.commands.submit( { "id": "a" * 32, "imei": imei, "kind": "request-position", "model": 231, "firmware": "0.01", } ) service.notify(imei) await asyncio.sleep(0.03) assert not written.is_set() available[0] = True service.notify(imei) await asyncio.sleep(0.03) assert not written.is_set() # A drained stale stream is insufficient. service.commands.session_activity[imei, "present"] = time.monotonic() service.notify(imei) await asyncio.wait_for(written.wait(), 1) assert len(writes) == 1 finally: task.cancel() await asyncio.gather(task, return_exceptions=True) assert not service.wake asyncio.run(exercise())