feat(fleet): integrate independent trackers, VPS pairing and recoverable commands

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:44:12 +03:00
parent d684eb7e05
commit f3a7592d90
45 changed files with 10006 additions and 0 deletions
+875
View File
@@ -0,0 +1,875 @@
"""Synthetic tests for operation persistence, authority and secret projection."""
import hashlib
import json
import time
from unittest.mock import Mock
import pytest
from k1link.device_plugins.arnavi_b2.profiles import Policy
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
from k1link.fleet import equipment_network as network
from k1link.fleet.independent_equipment import EquipmentError, EquipmentStore
from k1link.fleet.vps_hosts import VPSHosts
@pytest.fixture
def full_core_context(context):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
equipment, hosts, row = context
path = equipment.root / "evidence" / row["evidence_id"]
previous = decode_configuration((path / "configuration.bin").read_bytes())
config = Configuration(
previous.records
+ tuple(
Setting(n, value)
for n, value in (
(111, b""),
(112, b"\0\0"),
(7, b"\0"),
(113, b""),
(114, b"\0\0"),
(6, b"\0"),
(70, b"current.example"),
(71, b"\x26\xc2"),
(62, b"\0\x96"),
(72, b"\0\0\0\1"),
(222, b"unknown-secret"),
)
)
)
(path / "configuration.bin").write_bytes(config.encode())
(path / "identity.json").write_text(json.dumps({"imei": row["identity_key"]}))
row["observed"]["read_at"] = 10
row["settings"]["parameters"]["25"] = 16
with equipment.db() as db:
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"]))
for host in hosts.rows():
host["status"]["version"] = "0.1.15"
hosts.save(host)
return equipment, hosts, row, config
def test_full_network_profile_body_preserves_unknown_fields_and_is_private(
full_core_context, monkeypatch
):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
equipment, hosts, row, config = full_core_context
sent = []
def send(host, method, path, body=None):
sent.append(body)
assert equipment.listing()[0]["network_operation"]["id"] == body["id"]
return {"id": body["id"], "kind": body["kind"], "state": "queued"}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1)
assert sent[0]["kind"] == "configure-all"
assert sent[0]["expected_sha256"] == hashlib.sha256(config.encode()).hexdigest()
target = decode_configuration(bytes.fromhex(sent[0]["target_configuration"]))
assert target.integer(25, 2) == 16 and target.value(222) == config.value(222)
assert result["network_operation"]["scope"] == "configuration"
assert all(
text not in json.dumps(result)
for text in (
"unknown-secret",
'"target_configuration":',
"123456",
sent[0]["target_configuration"],
)
)
def test_full_network_read_snapshot_refreshes_config_but_not_sim_identity(
full_core_context, monkeypatch
):
equipment, hosts, row, config = full_core_context
def send(host, method, path, body=None):
return {
"id": body["id"],
"kind": body["kind"],
"state": "observed",
"configuration": config.encode().hex(),
"configuration_sha256": hashlib.sha256(config.encode()).hexdigest(),
"configuration_received_at": time.time(),
}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1, True)
assert result["network_operation"]["record_count"] == len(config.records)
assert result["observed"]["configuration_transport"] == "vps"
assert result["observed"]["read_at"] == 10
assert result["observed"]["configuration_read_at"] > 10
assert result["settings"] == row["settings"]
assert "unknown-secret" not in json.dumps(result)
with equipment.db() as db:
stored = json.loads(
db.execute("SELECT body FROM instances WHERE id=?", (row["id"],)).fetchone()[0]
)
path = equipment.root / "evidence" / stored["evidence_id"] / "configuration.bin"
assert path.read_bytes() == config.encode() and path.stat().st_mode & 0o777 == 0o600
def test_full_network_false_verified_receipt_is_not_accepted(full_core_context, monkeypatch):
equipment, hosts, row, config = full_core_context
def send(host, method, path, body=None):
return {
"id": body["id"],
"kind": body["kind"],
"state": "verified",
"configuration": config.encode().hex(),
"configuration_sha256": hashlib.sha256(config.encode()).hexdigest(),
"configuration_received_at": time.time(),
}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1)
assert result["network_operation"]["state"] == "uncertain"
assert result["policy_state"] == "uncertain"
@pytest.fixture
def context(tmp_path):
equipment = EquipmentStore(tmp_path, {})
hosts = VPSHosts(tmp_path, "core-synthetic", equipment)
config = Configuration(
tuple(
Setting(n, v)
for n, v in [
(1, b"old.example"),
(2, (9922).to_bytes(2, "big")),
(9, b"\0"),
(3, b"current.example"),
(4, (9922).to_bytes(2, "big")),
(8, b"\0"),
(5, b"123456"),
(20, b"\x01"),
(21, b"\x01"),
(22, b"\x00"),
(25, b"\0\x0f"),
(67, b"apn"),
(89, b"apn"),
]
)
)
evidence = equipment.root / "evidence" / "synthetic"
evidence.mkdir(parents=True)
(evidence / "configuration.bin").write_bytes(config.encode())
row = {
"id": "c" * 32,
"identity_key": "123456789012345",
"model_id": "arnavi-b2",
"revision": 1,
"vehicle_id": "rover-a",
"name": "Synthetic B2",
"policy_state": "saved",
"evidence_id": "synthetic",
"observed": {
"firmware": "0.01",
"configuration": {"servers": [{"host": "current.example", "port": 9922, "slot": 2}]},
},
"settings": Policy(
endpoint={"host": "new.example", "port": 9922, "slot": 1}, parameters={"25": 15}
).model_dump(),
}
with equipment.db() as db:
db.execute(
"INSERT INTO instances VALUES(?,?,?)", (row["id"], row["identity_key"], json.dumps(row))
)
for name in ("current", "new"):
hosts.save(
{
"id": name,
"state": "paired",
"last_sync_at": time.time(),
"vehicle_ids": ["rover-a"],
"status": {
"version": "0.1.6",
"tracker": {"host": name + ".example", "port": 9922},
},
}
)
hosts.sync = Mock()
return equipment, hosts, row
def test_saved_destination_does_not_revoke_surviving_old_channel(context):
_, hosts, _ = context
assert all(len(hosts.devices(h)) == 1 for h in hosts.rows())
def test_unsupported_mixed_profile_sends_nothing(context, monkeypatch):
equipment, hosts, row = context
row["settings"]["parameters"]["25"] = 30
with equipment.db() as db:
db.execute("UPDATE instances SET body=?", (json.dumps(row),))
sent = Mock()
monkeypatch.setattr(network, "request", sent)
with pytest.raises(EquipmentError, match="только адрес"):
network.start(hosts, row["id"], 1)
assert not sent.called
assert equipment.listing()[0]["revision"] == 1
def test_durable_operation_before_post_retry_and_result_projection(context, monkeypatch):
equipment, hosts, row = context
calls = []
def send(host, method, path, body=None):
calls.append(body)
persisted = equipment.listing()[0]
assert persisted["network_operation"]["id"] == body["id"]
assert persisted["revision"] == 2
return {"id": body["id"], "kind": body["kind"], "state": "queued", "password": "forbidden"}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1)
assert network.start(hosts, row["id"], 1) == result
assert len(calls) == 1 and "password" not in json.dumps(result)
with pytest.raises(EquipmentError, match="Дождитесь"):
equipment.update(row["id"], 2, "Changed", "rover-b", row["settings"])
op = result["network_operation"]
network.record(
hosts,
row["id"],
op["id"],
{
"id": op["id"],
"kind": "configure-server1",
"state": "verified",
"verified_at": time.time(),
"server1": {"host": "new.example", "port": 9922},
"replies": ["private"],
"password": "secret",
},
)
after = equipment.listing()[0]
assert after["network_server1"] == {"host": "new.example", "port": 9922}
assert after["policy_state"] == "saved" # endpoint scope is not the whole profile
assert "private" not in json.dumps(after) and "secret" not in json.dumps(after)
with equipment.db() as db:
private = equipment._find(db, "instances", row["id"])
assert network.plan(equipment, private)["expected"] == after["network_server1"]
def test_ambiguous_post_is_polled_never_resubmitted_and_survives_restart(context, monkeypatch):
equipment, hosts, row = context
post = Mock(side_effect=OSError("connection lost"))
monkeypatch.setattr(network, "request", post)
result = network.start(hosts, row["id"], 1)
assert result["network_operation"]["state"] == "submitting"
host = hosts.rows()[0]
recreated = VPSHosts(
equipment.root.parent, "core-synthetic", EquipmentStore(equipment.root.parent, {})
)
network.refresh(recreated, host)
assert post.call_count == 2 and post.call_args.args[1] == "GET"
assert recreated.equipment.listing()[0]["network_operation"]["state"] == "submitting"
with equipment.db() as db:
saved = equipment._find(db, "instances", row["id"])
saved["network_operation"]["expires_at"] = 0
db.execute("UPDATE instances SET body=?", (json.dumps(saved),))
network.refresh(recreated, host)
assert recreated.equipment.listing()[0]["network_operation"]["state"] == "uncertain"
assert sum(c.args[1] == "POST" for c in post.call_args_list) == 1
def test_network_read_recovers_endpoint_without_leaking_getp(context, monkeypatch):
equipment, hosts, row = context
def send(host, method, path, body=None):
return {
"id": body["id"],
"kind": "read-settings",
"state": "reply_received",
"replies": [
"#1=other.example,9922,0,0,#2=private-apn,user,password#26=current.example,9922,0,0,"
],
}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1, True)
assert result["network_operation"]["state"] == "observed"
assert result["network_server1"] == {"host": "other.example", "port": 9922}
assert "password" not in json.dumps(result) and "private-apn" not in json.dumps(result)
def test_text_output_is_durable_idempotent_and_never_applies_profile(context, monkeypatch):
equipment, hosts, row = context
for host in hosts.rows():
host["status"]["version"] = "0.1.10"
hosts.save(host)
sent = []
def send(host, method, path, body=None):
sent.append(body)
assert equipment.listing()[0]["network_operation"]["id"] == body["id"]
assert body["encoding"] == "text" and body["password"] == "123456"
return {
"id": body["id"],
"kind": body["kind"],
"state": "dispatched",
"created_at": 100,
"dispatched_at": 100.25,
"password": "secret",
}
monkeypatch.setattr(network, "request", send)
command = {"kind": "set-output", "pin": 5, "enabled": True}
result = network.start(hosts, row["id"], 1, command=command)
assert network.start(hosts, row["id"], 1, command=command) == result
assert len(sent) == 1
op = result["network_operation"]
assert op["queue_seconds"] == 0.25 and op["scope"] == "command"
assert result["policy_state"] == "saved" and "network_server1" not in result
assert all(s not in json.dumps(result) for s in ("123456", "secret", "encoding"))
with pytest.raises(EquipmentError, match="Дождитесь"):
network.start(hosts, row["id"], 2, command=command)
network.record(
hosts,
row["id"],
op["id"],
{"id": op["id"], "kind": "set-output", "state": "unconfirmed", "replies": ["SERV OK"]},
)
after = equipment.listing()[0]
assert after["network_operation"]["state"] == "unconfirmed"
assert "SERV OK" not in json.dumps(after) and after["policy_state"] == "saved"
assert len(sent) == 1
@pytest.mark.parametrize(
"command",
[
{"kind": "set-output", "pin": 5, "enabled": 1},
{"kind": "set-output", "pin": True, "enabled": True},
{"kind": "set-output", "pin": 6, "enabled": True},
{"kind": "set-output", "pin": 5, "enabled": True, "seconds": 5},
{"kind": "pulse-output", "pin": 5, "seconds": 6},
{"kind": "pulse-output", "pin": 5, "seconds": True},
{"kind": "request-position", "pin": 5},
],
)
def test_invalid_or_nonmanual_output_never_dispatches(context, monkeypatch, command):
equipment, hosts, row = context
sent = Mock()
monkeypatch.setattr(network, "request", sent)
with pytest.raises(EquipmentError):
network.start(hosts, row["id"], 1, command=command)
assert not sent.called and equipment.listing()[0]["revision"] == 1
def test_output_requires_qualified_vps_and_online_host(context, monkeypatch):
_, hosts, row = context
sent = Mock()
monkeypatch.setattr(network, "request", sent)
command = {"kind": "set-output", "pin": 5, "enabled": False}
with pytest.raises(EquipmentError, match="версию VPS"):
network.start(hosts, row["id"], 1, command=command)
for host in hosts.rows():
host["status"]["version"] = "0.1.10"
host["last_sync_at"] = 0
hosts.save(host)
with pytest.raises(EquipmentError, match="связь с VPS"):
network.start(hosts, row["id"], 1, command=command)
assert not sent.called
def test_existing_enrollment_exposes_modes_without_usb_or_private_fields(context):
from k1link.device_plugins.arnavi_b2.enrollment import B2Enrollment
equipment, _, row = context
adapter = B2Enrollment()
adapter.inspect = Mock(side_effect=AssertionError("must not access USB"))
equipment.adapters["arnavi-b2"] = adapter
public = equipment.listing()[0]
assert public["observed"]["output_modes"] == {"4": 1, "5": 1, "6": 0}
assert public["revision"] == row["revision"] and public["settings"] == row["settings"]
assert all(key not in public for key in ("identity_key", "evidence_id", "password"))
assert "123456" not in json.dumps(public)
(equipment.root / "evidence/synthetic/configuration.bin").write_bytes(b"corrupt")
assert equipment.listing()[0]["observed"]["output_modes"] == {}
def test_restart_version_gate_and_reconnected_projection(context, monkeypatch):
equipment, hosts, row = context
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "queued"}
monkeypatch.setattr(network, "request", send)
command = {"kind": "restart"}
with pytest.raises(EquipmentError, match="актуальную версию"):
network.start(hosts, row["id"], 1, command=command)
assert not sent
for host in hosts.rows():
host["status"]["version"] = "0.1.17"
hosts.save(host)
result = network.start(hosts, row["id"], 1, command=command)
op = result["network_operation"]
assert op["expires_at"] - op["created_at"] > 200
assert "password" not in sent[0] and "encoding" not in sent[0]
assert network.start(hosts, row["id"], 1, command=command) == result
assert len(sent) == 1
with pytest.raises(ValueError, match="receipt is not reconnection"):
network.record(
hosts,
row["id"],
op["id"],
{"id": op["id"], "kind": "restart", "state": "device_confirmed"},
)
network.record(
hosts,
row["id"],
op["id"],
{
"id": op["id"],
"kind": "restart",
"state": "reconnected",
"reconnect_seconds": 27.5,
"reconnected_at": time.time(),
"binary": "private-wire",
"restart_sessions": ["private-session"],
},
)
final = equipment.listing()[0]
assert final["network_operation"]["state"] == "reconnected"
assert final["network_operation"]["reconnect_seconds"] == 27.5
assert "private-" not in json.dumps(final)
assert final["policy_state"] == "saved"
def test_restart_http_contract_and_extra_fields():
from pydantic import ValidationError
from k1link.web.independent_equipment_api import CommandRequest
assert CommandRequest.model_validate({"expected_revision": 2, "kind": "restart"}).model_dump(
exclude_none=True
) == {"expected_revision": 2, "kind": "restart"}
with pytest.raises(ValidationError):
CommandRequest.model_validate(
{"expected_revision": 2, "kind": "restart", "raw_command": "1.6"}
)
@pytest.mark.parametrize(
"stage,state,expected",
[
("preflight", "unconfirmed", "not_started"),
("preflight", "expired", "not_started"),
("preflight", "uncertain", "uncertain"),
("write", "unconfirmed", "uncertain"),
("verify", "uncertain", "uncertain"),
],
)
def test_configuration_timeout_distinguishes_no_write_from_unknown_result(
full_core_context, monkeypatch, stage, state, expected
):
equipment, hosts, row, _ = full_core_context
monkeypatch.setattr(
network,
"request",
lambda h, m, p, body=None: {
"id": body["id"],
"kind": body["kind"],
"state": "dispatched",
"stage": "preflight",
"expires_at": time.time() + 180,
},
)
result = network.start(hosts, row["id"], 1)
op = result["network_operation"]
assert 175 < op["expires_at"] - time.time() <= 180
network.record(
hosts,
row["id"],
op["id"],
{
"id": op["id"],
"kind": "configure-all",
"state": state,
"stage": stage,
},
)
final = equipment.listing()[0]
assert final["policy_state"] == expected
assert final["network_operation"]["state"] == state
def test_reachable_vps_cannot_extend_or_leave_expired_operation_pending(context, monkeypatch):
equipment, hosts, row = context
monkeypatch.setattr(
network,
"request",
lambda h, m, p, body=None: {
"id": body["id"],
"kind": body["kind"],
"state": "queued",
"expires_at": time.time() + 99999,
},
)
result = network.start(hosts, row["id"], 1)
op = result["network_operation"]
assert op["expires_at"] < time.time() + 241
with equipment.db() as db:
saved = equipment._find(db, "instances", row["id"])
saved["network_operation"]["expires_at"] = 1
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"]))
requests = []
def stuck(h, method, path, body=None):
requests.append(method)
return {"id": op["id"], "kind": op["kind"], "state": "dispatched"}
monkeypatch.setattr(network, "request", stuck)
network.refresh(hosts, hosts.rows()[0])
assert equipment.listing()[0]["network_operation"]["state"] == "uncertain"
assert requests == ["GET"] # No automatic retry or second write.
@pytest.mark.parametrize(
"online,age,state", [(False, 1, 1), (True, 91, 1), (True, 1, 0), (True, -1, 1)]
)
def test_single_sim_write_requires_current_presence_before_dispatch(
full_core_context, monkeypatch, online, age, state
):
equipment, hosts, row, _ = full_core_context
with equipment.db() as db:
saved = equipment._find(db, "instances", row["id"])
saved["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "apn": "new.apn"}
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"]))
monkeypatch.setattr(
hosts,
"telemetry",
lambda: [
{
"instance_id": row["id"],
"online": online,
"cellular": {
"host_id": hosts.rows()[0]["id"],
"status": {"measured_at": time.time() - age, "sim_states": {"2": state}},
},
}
],
)
send = Mock()
monkeypatch.setattr(network, "request", send)
with pytest.raises(EquipmentError, match="SIM 2"):
network.start(hosts, row["id"], 1)
send.assert_not_called()
assert equipment.listing()[0]["revision"] == 1
def test_single_sim_write_with_current_presence_targets_only_its_apn(
full_core_context, monkeypatch
):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
equipment, hosts, row, config = full_core_context
with equipment.db() as db:
saved = equipment._find(db, "instances", row["id"])
saved["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "apn": "new.apn"}
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"]))
monkeypatch.setattr(
hosts,
"telemetry",
lambda: [
{
"instance_id": row["id"],
"online": True,
"cellular": {
"host_id": "current",
"status": {"measured_at": time.time(), "sim_states": {"2": 1}},
},
}
],
)
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "queued"}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1)
target = decode_configuration(bytes.fromhex(sent[0]["target_configuration"]))
assert target.text(89) == "new.apn"
assert target.value(67) == config.value(67)
assert result["settings"]["connectivity"]["strategy"] == "sim"
def test_sim_selection_is_one_durable_operation_and_settings_alone_cannot_complete_it(
full_core_context, monkeypatch
):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
equipment, hosts, row, config = full_core_context
row["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "activate": True}
with equipment.db() as db:
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"]))
for host in hosts.rows():
host["status"]["version"] = "0.1.24"
hosts.save(host)
monkeypatch.setattr(
hosts,
"telemetry",
lambda: [
{
"instance_id": row["id"],
"online": True,
"cellular": {
"host_id": "current",
"status": {"measured_at": time.time(), "sim_states": {"2": 1}},
},
}
],
)
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "queued", "stage": "preflight"}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1)
op = result["network_operation"]
assert op["scope"] == "sim-selection" and op["sim_slot"] == 2
assert sent[0]["kind"] == "select-sim"
target = decode_configuration(bytes.fromhex(sent[0]["target_configuration"]))
assert target.integer(72, 4) == config.integer(72, 4) | (1 << 10)
assert target.value(89) == config.value(89)
receipt = {"id": op["id"], "kind": "select-sim", "state": "verified"}
with pytest.raises(ValueError, match="not SIM selection"):
network.record(hosts, row["id"], op["id"], receipt)
with pytest.raises(ValueError, match="mismatch"):
network.record(
hosts, row["id"], op["id"], {**receipt, "state": "sim_selected", "active_sim": 1}
)
receipt.update(
state="sim_selected",
active_sim=2,
configuration=target.encode().hex(),
configuration_sha256=hashlib.sha256(target.encode()).hexdigest(),
configuration_received_at=time.time(),
)
network.record(hosts, row["id"], op["id"], receipt)
assert equipment.listing()[0]["policy_state"] == "applied"
assert equipment.listing()[0]["network_operation"]["active_sim"] == 2
@pytest.mark.parametrize("lost_after_commit", [False, True])
def test_outbox_survives_core_restart_preserves_wire_body_and_does_not_extend_deadline(
context, monkeypatch, lost_after_commit
):
equipment, hosts, row = context
now = [time.time()]
monkeypatch.setattr(network.time, "time", lambda: now[0])
for host in hosts.rows():
host["status"]["version"] = "0.1.26"
hosts.save(host)
accepted = {}
posts = []
fail = [True]
def send(host, method, path, body=None):
if method == "GET":
if not accepted:
raise OSError("not received yet")
return next(iter(accepted.values()))
posts.append(dict(body))
if not fail[0] or lost_after_commit:
accepted.setdefault(
body["id"],
{
"id": body["id"],
"kind": body["kind"],
"state": "queued",
"expires_at": body["not_after"],
},
)
if fail[0]:
raise OSError("lost request or response")
return accepted[body["id"]]
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1, command={"kind": "request-position"})
assert result["network_operation"]["state"] == "submitting"
with equipment.db() as db:
assert db.execute("SELECT COUNT(*) FROM network_outbox").fetchone()[0] == 1
assert "not_after" not in json.dumps(result)
fail[0] = False
now[0] += 6
restored = VPSHosts(
equipment.root.parent, "core-synthetic", EquipmentStore(equipment.root.parent, {})
)
restored.sync = Mock()
host = next(h for h in restored.rows() if h["id"] == result["network_operation"]["host_id"])
network.refresh(restored, host)
assert restored.equipment.listing()[0]["network_operation"]["state"] == "queued"
assert len(posts) == (1 if lost_after_commit else 2)
assert all(post == posts[0] for post in posts)
with equipment.db() as db:
assert db.execute("SELECT COUNT(*) FROM network_outbox").fetchone()[0] == 0
def test_outbox_backoff_expiry_and_credentials_never_enter_public_history(context, monkeypatch):
equipment, hosts, row = context
now = [time.time()]
monkeypatch.setattr(network.time, "time", lambda: now[0])
for host in hosts.rows():
host["status"]["version"] = "0.1.26"
hosts.save(host)
calls = Mock(side_effect=OSError("offline"))
monkeypatch.setattr(network, "request", calls)
result = network.start(
hosts, row["id"], 1, command={"kind": "set-output", "pin": 5, "enabled": True}
)
assert "123456" not in json.dumps(result)
host = next(h for h in hosts.rows() if h["id"] == result["network_operation"]["host_id"])
with equipment.db() as db:
wire = json.loads(db.execute("SELECT body FROM network_outbox").fetchone()[0])
assert wire["password"] == "123456"
assert '"password"' not in "".join(r[0] for r in db.execute("SELECT body FROM history"))
network.refresh(hosts, host)
assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1
now[0] += 31
network.refresh(hosts, host)
assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1
now[0] += 40
network.refresh(hosts, host)
assert equipment.listing()[0]["network_operation"]["state"] == "uncertain"
with equipment.db() as db:
assert db.execute("SELECT COUNT(*) FROM network_outbox").fetchone()[0] == 0
def test_full_configuration_journal_preserves_each_dispatch_timestamp(
full_core_context, monkeypatch
):
from k1link.fleet import equipment_command_journal as journal
equipment, hosts, row, _ = full_core_context
monkeypatch.setattr(
network,
"request",
lambda host, method, path, body=None: {
"id": body["id"],
"kind": body["kind"],
"state": "queued",
},
)
saved = network.start(hosts, row["id"], 1)
identifier = saved["network_operation"]["id"]
for stage, stamp in (("preflight", 100.5), ("write", 120.0), ("verify", 140.0)):
result = {
"id": identifier,
"kind": "configure-all",
"state": "dispatched",
"stage": stage,
"created_at": 100,
"dispatched_at": stamp,
"password": "private-secret",
"configuration_received_at": float("nan"),
}
network.record(hosts, row["id"], identifier, result)
network.record(hosts, row["id"], identifier, result)
value = journal.listing(equipment, row["id"])["items"][0]
assert value["dispatched_at"] == 140.0 and value["vps_created_at"] == 100
assert [e["occurred_at"] for e in value["events"] if e.get("evidence") == "dispatched_at"] == [
100.5,
120.0,
140.0,
]
assert "configuration_received_at" not in value and "private-secret" not in json.dumps(value)
recovered = {
**result,
"state": "queued",
"stage": "verify",
"recovery_at": 150.0,
"recovery_count": 1,
"recovery_verification": True,
}
network.record(hosts, row["id"], identifier, recovered)
network.record(hosts, row["id"], identifier, recovered)
value = journal.listing(equipment, row["id"])["items"][0]
assert value["recovery_count"] == 1 and value["recovery_verification"]
assert [e["occurred_at"] for e in value["events"] if e.get("evidence") == "recovery_at"] == [
150.0
]
def test_saved_sim_target_is_not_a_restart_for_unrelated_edit(full_core_context, monkeypatch):
from k1link.device_plugins.arnavi_b2.profiles import prepare
equipment, hosts, row, config = full_core_context
row["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "activate": True}
baseline = prepare(config, {"connectivity": row["settings"]["connectivity"]})
(equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").write_bytes(
baseline.encode()
)
with equipment.db() as db:
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"]))
monkeypatch.setattr(hosts, "telemetry", lambda: [])
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "queued"}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1)
assert result["network_operation"]["kind"] == "configure-all"
assert "sim_slot" not in sent[0]
assert sent[0]["target_configuration"] != baseline.encode().hex() # interval edit remains
def test_explicit_sim_action_runs_with_unchanged_bits_and_retries_same_job(
full_core_context, monkeypatch
):
from k1link.device_plugins.arnavi_b2.profiles import prepare
equipment, hosts, row, config = full_core_context
row["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "activate": True}
baseline = prepare(config, row["settings"])
(equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").write_bytes(
baseline.encode()
)
with equipment.db() as db:
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"]))
for host in hosts.rows():
host["status"]["version"] = "0.1.24"
hosts.save(host)
monkeypatch.setattr(
hosts,
"telemetry",
lambda: [
{
"instance_id": row["id"],
"online": True,
"cellular": {
"host_id": "current",
"status": {"measured_at": time.time(), "sim_states": {"2": 1}},
},
}
],
)
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "queued"}
monkeypatch.setattr(network, "request", send)
first = network.start(hosts, row["id"], 1, select_sim=True)
retry = network.start(hosts, row["id"], 1, select_sim=True)
assert first["network_operation"]["kind"] == "select-sim"
assert first["network_operation"]["id"] == retry["network_operation"]["id"]
assert len(sent) == 1 and sent[0]["target_configuration"] == baseline.encode().hex()
with pytest.raises(EquipmentError, match="изменились"):
network.start(hosts, row["id"], 1, select_sim=False)