380 lines
14 KiB
Python
380 lines
14 KiB
Python
"""Persistent maintenance intent recovery, isolated per tracker, no output actions."""
|
|
|
|
import json
|
|
import struct
|
|
import time
|
|
|
|
import pytest
|
|
from test_vps_host import full_context, store # noqa: F401
|
|
|
|
|
|
@pytest.fixture
|
|
def runtime(store, monkeypatch): # noqa: F811
|
|
from ndc_vps.commands import Commands
|
|
from ndc_vps.operations import Operations
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr(time, "time", lambda: now[0])
|
|
monkeypatch.setattr(time, "monotonic", lambda: now[0] - 1700000000)
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": "123456789012345",
|
|
"kind": "request-position",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
}
|
|
store.set_devices([{"imei": body["imei"], "instance_id": "c" * 32}])
|
|
return Operations(store, Commands(store)), body, now
|
|
|
|
|
|
def connect(ops, body, session="live"):
|
|
ops.commands.sessions[body["imei"]] = {session}
|
|
ops.commands.session_activity[body["imei"], session] = time.monotonic()
|
|
ops.commands.session_started[body["imei"], session] = time.monotonic()
|
|
|
|
|
|
def reply(ops, body, raw, code=0):
|
|
payload = struct.pack("<I", int(time.time())) + bytes([code]) + raw[5:9]
|
|
ops.commands.receive(
|
|
body["imei"], b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]", "live"
|
|
)
|
|
|
|
|
|
def restored(ops):
|
|
return type(ops)(ops.store, type(ops.commands)(ops.store))
|
|
|
|
|
|
def test_offline_intent_survives_time_restart_duplicate_submit_and_cancel(runtime):
|
|
ops, body, now = runtime
|
|
first = ops.submit(body)
|
|
now[0] += 86400
|
|
ops = restored(ops)
|
|
assert ops.submit(body)["id"] == first["id"]
|
|
assert ops.get(body["id"])["state"] == "queued"
|
|
assert ops.get(body["id"])["attempt_count"] == 0
|
|
with pytest.raises(ValueError, match="conflict"):
|
|
ops.submit({**body, "kind": "restart"})
|
|
assert ops.cancel(body["id"])["state"] == "stopped"
|
|
connect(ops, body)
|
|
assert restored(ops).get(body["id"])["state"] == "stopped"
|
|
assert ops.commands.take(body["imei"], "live") is None
|
|
|
|
|
|
def test_late_transport_observation_is_visible_after_operation_completed(runtime):
|
|
ops, body, now = runtime
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
raw, _, ticket = ops.commands.take_delivery(body["imei"], "live", with_receipt=True)
|
|
reply(ops, body, raw)
|
|
assert ops.get(body["id"])["state"] == "device_confirmed"
|
|
assert ops.get(body["id"])["transport"][0]["state"] == "prepared"
|
|
ops.commands.transport.record([
|
|
(ticket, "written", now[0], 0, None),
|
|
(ticket, "tcp_acknowledged", now[0] + .5, .5, None),
|
|
])
|
|
result = ops.get(body["id"])
|
|
assert result["state"] == "device_confirmed"
|
|
assert result["transport"][0]["tcp_ack_seconds"] == .5
|
|
assert ops.history(body["id"])["items"][0]["transport"] == result["transport"]
|
|
assert restored(ops).get(body["id"])["transport"] == result["transport"]
|
|
|
|
|
|
def test_lost_tracker_reply_has_new_attempt_same_intent_and_complete_history(runtime):
|
|
ops, body, now = runtime
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
first = ops.commands.take(body["imei"], "live")
|
|
now[0] += 31
|
|
assert ops.get(body["id"])["state"] == "queued"
|
|
assert ops.get(body["id"])["attempt_count"] == 1
|
|
ops = restored(ops)
|
|
now[0] += 5
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
second = ops.commands.take(body["imei"], "live")
|
|
assert first[5:9] != second[5:9]
|
|
reply(ops, body, first) # Old attempt cannot confirm the new one.
|
|
assert ops.get(body["id"])["state"] == "dispatched"
|
|
reply(ops, body, second)
|
|
assert ops.get(body["id"])["state"] == "device_confirmed"
|
|
assert ops.get(body["id"])["attempt_count"] == 2
|
|
assert [x["state"] for x in ops.history(body["id"])["items"]] == [
|
|
"device_confirmed",
|
|
"unconfirmed",
|
|
]
|
|
assert restored(ops).get(body["id"])["state"] == "device_confirmed"
|
|
with ops.store.db() as db:
|
|
assert db.execute("SELECT count(*) FROM operations").fetchone()[0] == 1
|
|
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 2
|
|
|
|
|
|
def test_vps_crash_after_dispatch_resumes_intent_not_old_attempt(runtime):
|
|
ops, body, now = runtime
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
assert ops.commands.take(body["imei"], "live")
|
|
ops = restored(ops)
|
|
assert ops.get(body["id"])["state"] == "queued"
|
|
now[0] += 5
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
raw = ops.commands.take(body["imei"], "live")
|
|
reply(ops, body, raw)
|
|
assert ops.get(body["id"])["state"] == "device_confirmed"
|
|
assert len(ops.history(body["id"])["items"]) == 2
|
|
|
|
|
|
def test_vps_crash_before_attempt_admission_and_cancellation_race(runtime, monkeypatch):
|
|
ops, body, _ = runtime
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
|
|
def crash(*args):
|
|
raise RuntimeError("simulated process loss")
|
|
|
|
monkeypatch.setattr(ops.commands, "submit", crash)
|
|
with pytest.raises(RuntimeError):
|
|
ops.advance(body["imei"])
|
|
ops = restored(ops)
|
|
assert ops.cancel(body["id"])["state"] == "stopped"
|
|
with ops.store.db() as db:
|
|
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 0
|
|
|
|
|
|
def test_cancel_before_lost_post_arrives_is_a_persisted_tombstone(runtime):
|
|
ops, body, _ = runtime
|
|
assert ops.cancel(body["id"], body["kind"])["state"] == "stopped"
|
|
ops = restored(ops)
|
|
connect(ops, body)
|
|
assert ops.submit(body)["state"] == "stopped"
|
|
assert ops.commands.take(body["imei"], "live") is None
|
|
|
|
|
|
def test_offline_tracker_does_not_block_another_and_fifo_is_per_imei(runtime):
|
|
ops, first, _ = runtime
|
|
second = {**first, "id": "b" * 32, "imei": "123456789012346"}
|
|
ops.store.set_devices(
|
|
[
|
|
{"imei": first["imei"], "instance_id": "c" * 32},
|
|
{"imei": second["imei"], "instance_id": "d" * 32},
|
|
]
|
|
)
|
|
ops.submit(first)
|
|
ops.submit(second)
|
|
ops.submit({**second, "id": "e" * 32})
|
|
connect(ops, second)
|
|
ops.advance(first["imei"])
|
|
ops.advance(second["imei"])
|
|
raw = ops.commands.take(second["imei"], "live")
|
|
assert ops.get("e" * 32)["attempt_count"] == 0
|
|
reply(ops, second, raw)
|
|
assert ops.get(second["id"])["state"] == "device_confirmed"
|
|
assert ops.get(first["id"])["attempt_count"] == 0
|
|
assert ops.get("e" * 32)["attempt_count"] == 1
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"code,expected", [(1, "device_rejected"), (5, "device_rejected"), (7, "queued")]
|
|
)
|
|
def test_permanent_rejection_and_device_queue_backpressure_differ(runtime, code, expected):
|
|
ops, body, _ = runtime
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
reply(ops, body, ops.commands.take(body["imei"], "live"), code)
|
|
assert ops.get(body["id"])["state"] == expected
|
|
|
|
|
|
def test_restart_accepted_by_b2_never_replayed_when_return_evidence_missing(runtime):
|
|
ops, body, now = runtime
|
|
body["kind"] = "restart"
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
reply(ops, body, ops.commands.take(body["imei"], "live"))
|
|
now[0] += 181
|
|
assert ops.get(body["id"])["state"] == "accepted"
|
|
assert ops.get(body["id"])["attempt_count"] == 1
|
|
|
|
|
|
@pytest.mark.parametrize("observed", ["target", "before", "divergent"])
|
|
def test_uncertain_write_reads_state_before_any_retry(full_context, observed): # noqa: F811
|
|
from ndc_vps.operations import Operations
|
|
from ndc_vps.usb_protocol import Configuration, Setting
|
|
|
|
commands, body, before, target, wire, now = full_context
|
|
ops = Operations(commands.store, commands)
|
|
ops.submit(body)
|
|
ops.advance(body["imei"])
|
|
assert b"SERV*1.9" in commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 15
|
|
assert b"SERV*1.8" in commands.take(body["imei"], "live")
|
|
assert commands.web_receive(wire(2), "192.0.2.1")
|
|
now[0] += 181
|
|
assert ops.get(body["id"])["runtime_phase"] == "retry-wait"
|
|
now[0] += 5
|
|
commands.session_activity[body["imei"], "live"] = time.monotonic()
|
|
ops.advance(body["imei"])
|
|
assert b"SERV*1.9" in commands.take(body["imei"], "live")
|
|
image = (
|
|
target
|
|
if observed == "target"
|
|
else before
|
|
if observed == "before"
|
|
else Configuration(
|
|
tuple(
|
|
Setting(r.number, b"\x00\x11" if r.number == 25 else r.value)
|
|
for r in before.records
|
|
)
|
|
)
|
|
)
|
|
commands.web_receive(wire(5, image.encode()), "192.0.2.1")
|
|
result = ops.get(body["id"])
|
|
assert (
|
|
result["state"]
|
|
== {"target": "verified", "before": "queued", "divergent": "rejected"}[observed]
|
|
)
|
|
assert result["attempt_count"] == 2
|
|
assert "123456" not in json.dumps(ops.history(body["id"]))
|
|
with commands.store.db() as db:
|
|
images = sum(
|
|
bool(json.loads(r[0]).get("write_reply_sent_at"))
|
|
for r in db.execute("SELECT body FROM commands")
|
|
)
|
|
assert images == 1
|
|
|
|
|
|
def test_cancelled_inflight_keeps_final_receipt_but_stops_unknown_retry(runtime):
|
|
ops, body, now = runtime
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
ops.advance(body["imei"])
|
|
wire = ops.commands.take(body["imei"], "live")
|
|
assert ops.cancel(body["id"])["stop_requested"]
|
|
now[0] += 31
|
|
result = ops.get(body["id"])
|
|
assert result["state"] == "stopped" and result["attempt_count"] == 1
|
|
connect(ops, body)
|
|
reply(ops, body, wire)
|
|
assert ops.get(body["id"])["state"] == "stopped"
|
|
assert ops.commands.take(body["imei"], "live") is None
|
|
|
|
|
|
def test_repeated_reads_crash_plan_after_admission_reuses_child(runtime, monkeypatch):
|
|
ops, body, _ = runtime
|
|
ops.submit(body)
|
|
connect(ops, body)
|
|
original = ops.commands.submit
|
|
|
|
def admitted(body):
|
|
original(body)
|
|
raise RuntimeError("crash after commit")
|
|
|
|
monkeypatch.setattr(ops.commands, "submit", admitted)
|
|
with pytest.raises(RuntimeError):
|
|
ops.advance(body["imei"])
|
|
ops = restored(ops)
|
|
connect(ops, body)
|
|
assert ops.get(body["id"])["attempt_count"] == 1
|
|
wire = ops.commands.take(body["imei"], "live")
|
|
reply(ops, body, wire)
|
|
assert ops.get(body["id"])["state"] == "device_confirmed"
|
|
with ops.store.db() as db:
|
|
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
|
|
|
|
|
|
def test_old_image_read_allows_fresh_preflight_before_second_write(full_context): # noqa: F811
|
|
from ndc_vps.operations import Operations
|
|
|
|
commands, body, before, target, wire, now = full_context
|
|
ops = Operations(commands.store, commands)
|
|
ops.submit(body)
|
|
ops.advance(body["imei"])
|
|
commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 15
|
|
commands.take(body["imei"], "live")
|
|
assert commands.web_receive(wire(2), "192.0.2.1")
|
|
now[0] += 181
|
|
ops.get(body["id"])
|
|
now[0] += 5
|
|
commands.session_activity[body["imei"], "live"] = time.monotonic()
|
|
ops.advance(body["imei"])
|
|
commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
assert ops.get(body["id"])["state"] == "queued"
|
|
now[0] += 15
|
|
ops.advance(body["imei"])
|
|
assert b"SERV*1.9" in commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 15
|
|
assert b"SERV*1.8" in commands.take(body["imei"], "live")
|
|
assert commands.web_receive(wire(2), "192.0.2.1")
|
|
now[0] += 15
|
|
assert b"SERV*1.9" in commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
assert ops.get(body["id"])["state"] == "verified"
|
|
assert ops.get(body["id"])["attempt_count"] == 3
|
|
|
|
|
|
@pytest.mark.parametrize("both", [False, True])
|
|
def test_sim_recovery_reads_target_and_fresh_modem_without_second_restart(full_context, both): # noqa: F811
|
|
import hashlib
|
|
|
|
from ndc_vps.operations import Operations
|
|
from ndc_vps.usb_protocol import Configuration, Setting
|
|
from test_vps_host import sim_packet
|
|
|
|
commands, body, before, _, wire, now = full_context
|
|
before = Configuration(
|
|
before.records + (Setting(72, (2072 | (1 << 20) if both else 2072).to_bytes(4, "big")),)
|
|
)
|
|
target = Configuration(
|
|
tuple(
|
|
Setting(
|
|
r.number,
|
|
(2072 | (0 if both else 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(),
|
|
)
|
|
if both:
|
|
body.pop("sim_slot")
|
|
body["sim_policy"] = "both"
|
|
ops = Operations(commands.store, commands)
|
|
ops.submit(body)
|
|
ops.advance(body["imei"])
|
|
commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 15
|
|
commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(2), "192.0.2.1")
|
|
now[0] += 15
|
|
commands.take(body["imei"], "live")
|
|
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
assert commands.take(body["imei"], "live")[-3:-1] == b"\x01\x07"
|
|
now[0] += 361
|
|
ops.get(body["id"])
|
|
now[0] += 5
|
|
commands.session_activity[body["imei"], "live"] = time.monotonic()
|
|
ops.advance(body["imei"])
|
|
assert b"SERV*1.9" in commands.take(body["imei"], "live")
|
|
ops.observe(body["imei"], sim_packet(now[0], slot=2))
|
|
ops.observe(
|
|
body["imei"], sim_packet(now[0] - 1, slot=1)
|
|
) # delayed older sample cannot downgrade
|
|
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
result = ops.get(body["id"])
|
|
assert result["state"] == "sim_selected" and result["active_sim"] == 2
|
|
assert result["attempt_count"] == 2 and commands.take(body["imei"], "live") is None
|