"""Durable runtime queue, original deadlines and redacted operator history.""" import json import sqlite3 import time from concurrent.futures import ThreadPoolExecutor import pytest from test_equipment_network import context # noqa: F401 from k1link.fleet import equipment_command_journal as journal from k1link.fleet import equipment_command_runtime as runtime from k1link.fleet import equipment_network as network from k1link.fleet.equipment_command_catalog import catalog from k1link.fleet.independent_equipment import EquipmentError, EquipmentStore @pytest.fixture def ready(context): # noqa: F811 - imported pytest fixture equipment, hosts, row = context for host in hosts.rows(): host["status"]["version"] = "0.1.26" hosts.save(host) return equipment, hosts, row def sender(monkeypatch): sent = [] def send(host, method, path, body=None): sent.append(body) return { "id": body["id"], "kind": body["kind"], "state": "queued", "expires_at": body["not_after"], } monkeypatch.setattr(network, "request", send) return sent @pytest.mark.parametrize( "version", ["0.1.26", "0.1.27", "0.1.28", "0.1.29", "0.1.30", "0.1.31", "0.2.0", "0.2.3"] ) def test_queue_survives_restart_and_idempotent_submit(ready, monkeypatch, version): equipment, hosts, row = ready for host in hosts.rows(): host["status"]["version"] = version hosts.save(host) first = runtime.enqueue(hosts, row["id"], "1" * 32, "position") assert first["state"] == "waiting" assert runtime.enqueue(hosts, row["id"], "1" * 32, "position") == first with pytest.raises(EquipmentError, match="другой"): runtime.enqueue(hosts, row["id"], "1" * 32, "restart") hosts.equipment = EquipmentStore(equipment.root.parent, {}) sent = sender(monkeypatch) runtime.pump(hosts) runtime.pump(hosts) assert len(sent) == 1 and sent[0]["id"] == first["id"] assert sent[0]["not_after"] == first["expires_at"] entries = journal.listing(hosts.equipment, row["id"])["items"] assert len(entries) == 1 assert [event["state"] for event in entries[0]["events"]] == ["waiting", "submitting", "queued"] def test_worker_survives_transient_database_failure(ready, monkeypatch): _, hosts, _ = ready ticks, waits = [], [] def tick(next_sync): ticks.append(1) if len(ticks) == 1: raise sqlite3.OperationalError("database temporarily locked") hosts.stop.set() return False monkeypatch.setattr(hosts, "_runtime_tick", tick) monkeypatch.setattr(hosts.command_wake, "wait", waits.append) hosts.run() assert ticks == [1, 1] and waits == [5] @pytest.mark.parametrize("superseded", [False, True]) def test_confirmed_vps_result_is_reconciled_after_core_deadline_and_restart( ready, monkeypatch, superseded ): equipment, hosts, row = ready sent = sender(monkeypatch) queued = runtime.enqueue(hosts, row["id"], "1" * 32, "position") runtime.pump(hosts) now = queued["expires_at"] + 1 monkeypatch.setattr(time, "time", lambda: now) def unavailable(*args, **kwargs): raise OSError("VPS reply unavailable") monkeypatch.setattr(network, "request", unavailable) source = next(h for h in hosts.rows() if h["id"] == "current") network.refresh(hosts, source) assert journal.listing(equipment, row["id"])["items"][0]["state"] == "uncertain" hosts.equipment = EquipmentStore(equipment.root.parent, {}) if superseded: with hosts.equipment.db() as db: saved = hosts.equipment._find(db, "instances", row["id"]) saved["network_operation"] = {"id": "other-operation", "state": "verified"} db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"])) methods = [] def restored(host, method, path, body=None): methods.append(method) return { "id": queued["id"], "kind": "request-position", "state": "device_confirmed", "received_at": queued["created_at"] + 1, "roundtrip_seconds": 0.5, } monkeypatch.setattr(network, "request", restored) network.refresh(hosts, source) item = next( i for i in journal.listing(hosts.equipment, row["id"])["items"] if i["id"] == queued["id"] ) assert item["state"] == "device_confirmed" assert len(sent) == 1 and methods == ["GET"] if superseded: with hosts.equipment.db() as db: assert ( hosts.equipment._find(db, "instances", row["id"])["network_operation"]["id"] == "other-operation" ) def test_fifo_one_operation_per_tracker_and_full_history(ready, monkeypatch): equipment, hosts, row = ready first = runtime.enqueue(hosts, row["id"], "1" * 32, "position") second = runtime.enqueue(hosts, row["id"], "2" * 32, "position") sent = sender(monkeypatch) runtime.pump(hosts) assert len(sent) == 1 network.record( hosts, row["id"], first["id"], { "id": first["id"], "kind": "request-position", "state": "device_confirmed", "received_at": time.time(), "roundtrip_seconds": 0.5, }, ) runtime.pump(hosts) assert len(sent) == 2 and sent[1]["id"] == second["id"] items = journal.listing(equipment, row["id"])["items"] assert [x["state"] for x in items] == ["queued", "device_confirmed"] assert any(e.get("evidence") == "received_at" for e in items[1]["events"]) def test_expired_cancelled_and_changed_device_never_sent(ready, monkeypatch): equipment, hosts, row = ready sent = sender(monkeypatch) one = runtime.enqueue(hosts, row["id"], "1" * 32, "position") runtime.cancel(equipment, row["id"], one["id"]) runtime.enqueue(hosts, row["id"], "2" * 32, "position") with equipment.db() as db: value = json.loads( db.execute("SELECT body FROM command_journal WHERE id=?", ("2" * 32,)).fetchone()[0] ) value["queue_deadline"] = time.time() - 1 journal.put(db, row["id"], value) runtime.enqueue(hosts, row["id"], "3" * 32, "position") row["vehicle_id"] = "changed" with equipment.db() as db: db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"])) runtime.pump(hosts) assert sent == [] assert [v["state"] for v in journal.listing(equipment, row["id"])["items"]] == [ "rejected", "expired", "cancelled", ] def test_lost_post_preserves_same_operation_after_restart(ready, monkeypatch): equipment, hosts, row = ready def lost(*args, **kwargs): raise OSError("lost") monkeypatch.setattr(network, "request", lost) value = runtime.enqueue(hosts, row["id"], "1" * 32, "position") runtime.pump(hosts) hosts.equipment = EquipmentStore(equipment.root.parent, {}) sent = sender(monkeypatch) runtime.pump(hosts) assert sent == [] assert journal.listing(hosts.equipment, row["id"])["items"][0]["state"] == "submitting" with pytest.raises(EquipmentError, match="началась"): runtime.cancel(hosts.equipment, row["id"], value["id"]) def test_catalog_and_history_never_expose_password(ready, monkeypatch): equipment, hosts, row = ready values = catalog(equipment, row) assert next(v for v in values if v["id"] == "pin6-on")["unavailable"] assert not next(v for v in values if v["id"] == "pin4-pulse")["unavailable"] value = runtime.enqueue(hosts, row["id"], "1" * 32, "pin4-on") sender(monkeypatch) runtime.pump(hosts) public = json.dumps([values, journal.listing(equipment, row["id"])], ensure_ascii=False) assert "123456" not in public and '"password"' not in public and "identity_key" not in public assert "••••••*SERV*8.4.1" in public assert value["description"]["queue_seconds"] == 30 def test_tracker_acceptance_is_persisted_but_does_not_finish_intent(ready, monkeypatch): equipment, hosts, row = ready sender(monkeypatch) job = runtime.enqueue(hosts, row["id"], "9" * 32, "position") runtime.pump(hosts) accepted = time.time() result = { "id": job["id"], "kind": "request-position", "state": "dispatched", "device_code": 6, "device_accepted_at": accepted, "received_at": accepted, } network.record(hosts, row["id"], job["id"], result) network.record(hosts, row["id"], job["id"], result) hosts.equipment = EquipmentStore(equipment.root.parent, {}) item = journal.listing(hosts.equipment, row["id"])["items"][0] assert item["state"] == "dispatched" and item["device_accepted_at"] == accepted events = [e for e in item["events"] if e.get("evidence") == "device_accepted_at"] assert len(events) == 1 and events[0]["state"] == "device_accepted" network.record( hosts, row["id"], job["id"], {**result, "state": "device_confirmed", "device_code": 0} ) item = journal.listing(hosts.equipment, row["id"])["items"][0] assert item["state"] == "device_confirmed" and item["device_code"] == 0 assert item["device_accepted_at"] == accepted def test_bounded_queue_parallel_duplicate_and_cursor(ready): equipment, hosts, row = ready with ThreadPoolExecutor(max_workers=2) as pool: results = list( pool.map(lambda _: runtime.enqueue(hosts, row["id"], "1" * 32, "position"), range(2)) ) assert results[0]["id"] == results[1]["id"] for n in range(2, 33): runtime.enqueue(hosts, row["id"], f"{n:032x}", "position") with pytest.raises(EquipmentError, match="заполнена"): runtime.enqueue(hosts, row["id"], "f" * 32, "position") page = journal.listing(equipment, row["id"], limit=20) older = journal.listing(equipment, row["id"], before=page["next_before"], limit=20) assert len(page["items"]) == 20 and len(older["items"]) == 12 assert len({x["id"] for x in page["items"] + older["items"]}) == 32 def test_cancel_race_is_rechecked_inside_dispatch_transaction(ready, monkeypatch): equipment, hosts, row = ready value = runtime.enqueue(hosts, row["id"], "1" * 32, "position") sent = sender(monkeypatch) original = network.start def intercept(*args, **kwargs): runtime.cancel(equipment, row["id"], value["id"]) return original(*args, **kwargs) monkeypatch.setattr(network, "start", intercept) runtime.pump(hosts) assert sent == [] assert journal.listing(equipment, row["id"])["items"][0]["state"] == "cancelled" def test_pending_and_later_completion_remain_visible_outside_history_page(ready): equipment, hosts, row = ready for n in range(1, 33): runtime.enqueue(hosts, row["id"], f"{n:032x}", "position") first_id = f"{1:032x}" page = journal.listing(equipment, row["id"]) assert len(page["items"]) == 25 assert first_id not in {i["id"] for i in page["items"]} assert len(page["tracked_items"]) == 32 runtime.cancel(equipment, row["id"], first_id) refreshed = journal.listing(equipment, row["id"], tracked=[first_id, "not-in-this-device"]) result = next(i for i in refreshed["tracked_items"] if i["id"] == first_id) assert result["state"] == "cancelled" assert len(refreshed["tracked_items"]) == 32 def test_queue_expiry_survives_core_downtime(ready, monkeypatch): equipment, hosts, row = ready value = runtime.enqueue(hosts, row["id"], "1" * 32, "position") hosts.equipment = EquipmentStore(equipment.root.parent, {}) sent = sender(monkeypatch) monkeypatch.setattr(runtime.time, "time", lambda: value["created_at"] + 31) runtime.pump(hosts) assert sent == [] item = journal.listing(hosts.equipment, row["id"])["items"][0] assert item["state"] == "expired" and item["reason"] == "queue_deadline" def test_legacy_backfill_keeps_unknown_time_and_closes_orphans(ready): equipment, hosts, row = ready old = { **row, "network_operation": { "id": "9" * 32, "kind": "request-position", "scope": "command", "command": {"kind": "request-position"}, "state": "dispatched", "created_at": 1, }, } current = { **row, "network_operation": { "id": "8" * 32, "kind": "request-position", "scope": "command", "command": {"kind": "request-position"}, "state": "device_confirmed", "created_at": 2, "password": "never-show-this", "replies": ["never-show-this"], }, } with equipment.db() as db: db.execute("DELETE FROM command_journal_migrations") db.execute("INSERT INTO history VALUES(?,?,?)", (row["id"], 1, json.dumps(old))) db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(current), row["id"])) reloaded = EquipmentStore(equipment.root.parent, {}) items = journal.listing(reloaded, row["id"])["items"] assert [i["state"] for i in items] == ["device_confirmed", "uncertain"] assert items[0]["events"][0]["historical"] assert "never-show-this" not in json.dumps(items) assert len(journal.listing(EquipmentStore(equipment.root.parent, {}), row["id"])["items"]) == 2 def test_runtime_api_rejects_foreign_origin_and_arbitrary_command(ready): from types import SimpleNamespace from fastapi import FastAPI from fastapi.testclient import TestClient from k1link.web.independent_equipment_api import router equipment, hosts, row = ready app = FastAPI() app.include_router(router) app.state.fleet = SimpleNamespace( lock=hosts.lock, independent_equipment=equipment, vps_hosts=hosts ) with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 12345)) as client: path = f"/api/v1/fleet/equipment/instances/{row['id']}/commands" assert client.get(path).status_code == 200 body = {"request_id": "1" * 32, "preset_id": "position"} assert ( client.post(path, json=body, headers={"Origin": "https://foreign.example"}).status_code == 403 ) assert client.post(path, json={**body, "raw": "reboot"}).status_code == 422 assert client.post(path, json={**body, "preset_id": "arbitrary"}).status_code == 409 result = client.post(path, json=body) assert result.status_code == 200 and result.json()["state"] == "waiting" assert client.post(path, json=body).json()["id"] == result.json()["id"] assert client.get(path).json()["items"][0]["id"] == body["request_id"] assert ( client.post(path + "/" + body["request_id"] + "/cancel").json()["state"] == "cancelled" ) def test_preview_matches_actual_qualified_vps_payload(ready): from pathlib import Path from k1link.fleet.equipment_actions import plan equipment, _, row = ready fixture = Path(__file__).resolve().parent / "fixtures/arnavi_vps/client-v1.json" contract = json.loads(fixture.read_text()) cases = { case["preset"]: case for case in contract["cases"] if case["request"]["firmware"] == row["observed"]["firmware"] } for preset in catalog(equipment, row): if preset["unavailable"]: continue body = plan(equipment, row, preset["command"]) body.pop("secondary") body["id"] = "1" * 32 case = cases[preset["id"]] assert body == case["request"] wire = bytes.fromhex(case["wire_hex"]) if preset["encoding"].endswith("FC"): assert wire.decode().replace("123456", "••••••") == preset["wire"] else: assert wire.hex(" ").upper() == preset["wire"] def test_manual_repeat_uses_new_id_and_preserves_http_idempotency(ready, monkeypatch): from k1link.fleet.equipment_command_repeat import repeat equipment, hosts, row = ready original = runtime.enqueue(hosts, row["id"], "1" * 32, "position") runtime.cancel(equipment, row["id"], original["id"]) repeated = repeat(hosts, row["id"], original["id"], "2" * 32) assert repeated["state"] == "waiting" and repeated["id"] != original["id"] assert repeat(hosts, row["id"], original["id"], "2" * 32) == repeated with pytest.raises(EquipmentError, match="завершения"): repeat(hosts, row["id"], repeated["id"], "3" * 32) assert len(journal.listing(equipment, row["id"])["items"]) == 2 assert not {"guard", "digest", "network_intent"} & repeated.keys() def test_repeat_missing_history_is_rejected(ready): from k1link.fleet.equipment_command_repeat import repeat _, hosts, row = ready with pytest.raises(EquipmentError, match="не найдена"): repeat(hosts, row["id"], "f" * 32, "a" * 32)