validate_qt_clean.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. #!/usr/bin/env python3
  2. """Validate Qt-clean v1 against a running backend; read-only unless requested.
  3. No firmware parameters or AMT/MT algorithms are submitted by this driver.
  4. --start explicitly authorizes one host start/reset. --drive-default-plan additionally
  5. continues UIP with CR and exits AMT, ending at the actual UEFI Shell prompt.
  6. Protocol PASS never means that memory tests passed.
  7. """
  8. from __future__ import annotations
  9. import argparse
  10. import asyncio
  11. import contextlib
  12. import datetime as dt
  13. import json
  14. import os
  15. from pathlib import Path
  16. import sys
  17. import time
  18. from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
  19. import uuid
  20. import aiohttp
  21. TERMINAL = {"succeeded", "failed", "interrupted", "cancelled"}
  22. STAGE_RANK = {"unknown": -1, "idle": -1, "boot": 0, "booting": 0,
  23. "uip": 1, "uip1": 1, "training": 2, "rmt": 3, "amt": 4,
  24. "uip2": 5, "post": 5, "uefi": 6, "mt": 7}
  25. PRIVATE_KEYS = {"password", "passwd", "secret", "authorization", "token",
  26. "firmware_settings", "boot_plan", "boot_execution", "raw_line",
  27. "raw_sol", "helper_argv", "traceback"}
  28. def timestamp():
  29. return dt.datetime.now(dt.timezone.utc).isoformat()
  30. def safe_url(url, view=None):
  31. p = urlsplit(url)
  32. host = p.hostname or ""
  33. if ":" in host:
  34. host = "[" + host + "]"
  35. if p.port:
  36. host += ":" + str(p.port)
  37. values = [(k, v) for k, v in parse_qsl(p.query) if k == "view"]
  38. if view is not None:
  39. values = [("view", view)]
  40. return urlunsplit((p.scheme, host, p.path or "/ws", urlencode(values), ""))
  41. def private_fields(value, path=""):
  42. found = []
  43. if isinstance(value, dict):
  44. for key, item in value.items():
  45. low = str(key).lower()
  46. here = path + "." + str(key)
  47. if low in PRIVATE_KEYS or low.endswith("_password") or low.endswith("_secret"):
  48. found.append(here)
  49. found.extend(private_fields(item, here))
  50. elif isinstance(value, list):
  51. for i, item in enumerate(value):
  52. found.extend(private_fields(item, f"{path}[{i}]"))
  53. return found
  54. def station_summary(station):
  55. return {key: station.get(key) for key in (
  56. "station_id", "connection", "power", "phase", "run_state",
  57. "started_unix_ms", "boot_id", "verdict", "input", "command")}
  58. class RpcFailure(RuntimeError):
  59. def __init__(self, method, error):
  60. self.method, self.error = method, error or {}
  61. super().__init__(f"{method}: {self.error.get('code', 'ERROR')}: "
  62. f"{self.error.get('message', '')}")
  63. class Evidence:
  64. def __init__(self, args):
  65. self.path = Path(args.output).expanduser().resolve()
  66. self.token = os.environ.get(args.token_env, "") if args.token_env else ""
  67. self.data = {
  68. "schema": "qt-clean-validation-v1", "started_utc": timestamp(),
  69. "endpoint": safe_url(args.url), "station_id": args.station,
  70. "requested": {"start": args.start, "drive_default_plan": args.drive_default_plan,
  71. "check_unconfigured": args.check_unconfigured,
  72. "grpc": bool(args.grpc_address)},
  73. "checks": [], "commands": [], "state_transitions": [], "logs": [],
  74. "protocol_verdict": "RUNNING", "memory_verdict": "NOT_TESTED",
  75. "memory_verdict_reason": "This driver does not run AMT or MT; reaching UEFI is not memory PASS.",
  76. }
  77. def save(self):
  78. self.path.parent.mkdir(parents=True, exist_ok=True)
  79. tmp = self.path.with_suffix(self.path.suffix + ".tmp")
  80. tmp.write_text(json.dumps(self._redacted(self.data), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  81. tmp.replace(self.path)
  82. def _redacted(self, value):
  83. if isinstance(value, dict):
  84. return {key: ("[REDACTED]" if str(key).lower() in PRIVATE_KEYS
  85. or str(key).lower().endswith(("_password", "_secret", "_token"))
  86. else self._redacted(item)) for key, item in value.items()}
  87. if isinstance(value, list):
  88. return [self._redacted(item) for item in value]
  89. if isinstance(value, str) and self.token:
  90. return value.replace(self.token, "[REDACTED]")
  91. return value
  92. def check(self, name, passed, detail=None, *, skipped=False):
  93. row = {"name": name, "status": "SKIP" if skipped else "PASS" if passed else "FAIL",
  94. "at_utc": timestamp()}
  95. if detail is not None:
  96. row["detail"] = detail
  97. self.data["checks"].append(row)
  98. print(json.dumps(self._redacted(row), ensure_ascii=False), flush=True)
  99. self.save()
  100. return bool(passed)
  101. def fail_count(self):
  102. return sum(row["status"] == "FAIL" for row in self.data["checks"])
  103. class WsClient:
  104. def __init__(self, session, url, evidence, token="", *, record_push=True):
  105. self.session, self.url, self.evidence = session, url, evidence
  106. self.headers = {"Authorization": "Bearer " + token} if token else {}
  107. self.record_push = record_push
  108. self.ws = self.reader = None
  109. self.pending = {}
  110. self.counter = 0
  111. self.state = None
  112. self.state_count = 0
  113. self.first_state = asyncio.Event()
  114. self.last_summary = {}
  115. self.protocol_errors = []
  116. async def __aenter__(self):
  117. self.ws = await self.session.ws_connect(self.url, heartbeat=20, headers=self.headers)
  118. self.reader = asyncio.create_task(self._read())
  119. return self
  120. async def __aexit__(self, *exc):
  121. await self.ws.close()
  122. self.reader.cancel()
  123. with contextlib.suppress(asyncio.CancelledError):
  124. await self.reader
  125. async def _read(self):
  126. try:
  127. async for message in self.ws:
  128. if message.type != aiohttp.WSMsgType.TEXT:
  129. if message.type == aiohttp.WSMsgType.ERROR:
  130. raise RuntimeError("WebSocket stream error")
  131. continue
  132. try:
  133. frame = json.loads(message.data)
  134. except (TypeError, ValueError):
  135. self.protocol_errors.append("non-JSON text response")
  136. continue
  137. if not isinstance(frame, dict):
  138. self.protocol_errors.append("response is not an object")
  139. continue
  140. request_id = frame.get("id")
  141. if request_id in self.pending:
  142. future = self.pending.pop(request_id)
  143. if not future.done():
  144. future.set_result(frame)
  145. elif frame.get("event") == "state":
  146. state = frame.get("result")
  147. if isinstance(state, dict):
  148. self.state = state
  149. self.state_count += 1
  150. self.first_state.set()
  151. if self.record_push:
  152. self._record_state(state)
  153. else:
  154. self.protocol_errors.append("state push result is not an object")
  155. elif frame.get("event") == "bios_uart" and self.record_push:
  156. result = frame.get("result", {})
  157. if isinstance(result, dict):
  158. self.evidence.data["logs"].append({"station_id": result.get("station_id"),
  159. "session_id": result.get("session_id"), "offset": result.get("offset"),
  160. "next_offset": result.get("next_offset"), "raw_bytes": len(result.get("data_base64", "")) * 3 // 4})
  161. self.evidence.data["logs"] = self.evidence.data["logs"][-4000:]
  162. elif request_id is not None:
  163. self.protocol_errors.append("unmatched response id")
  164. except Exception as exc:
  165. for future in self.pending.values():
  166. if not future.done():
  167. future.set_exception(RuntimeError(type(exc).__name__ + ": " + str(exc)))
  168. def _record_state(self, state):
  169. for station in state.get("stations", []):
  170. if not isinstance(station, dict):
  171. continue
  172. summary = station_summary(station)
  173. # Ignore naturally changing counters/timestamps unless the useful state changed.
  174. key = {k: summary.get(k) for k in ("connection", "power", "phase", "run_state",
  175. "boot_id", "verdict", "input", "command")}
  176. sid = station.get("station_id", "")
  177. if key != self.last_summary.get(sid):
  178. self.last_summary[sid] = key
  179. self.evidence.data["state_transitions"].append({"received_utc": timestamp(), **summary})
  180. self.evidence.data["state_transitions"] = self.evidence.data["state_transitions"][-4000:]
  181. if sid == self.evidence.data["station_id"]:
  182. print(json.dumps({"station": sid, "phase": summary.get("phase"),
  183. "run_state": summary.get("run_state"),
  184. "power": summary.get("power"),
  185. "input_stage": (summary.get("input") or {}).get("stage")},
  186. ensure_ascii=False), flush=True)
  187. async def raw_call(self, method, params=None, *, version=1, timeout=20):
  188. self.counter += 1
  189. request_id = f"verify-{self.counter}-{uuid.uuid4().hex[:8]}"
  190. frame = {"v": version, "id": request_id, "method": method,
  191. "params": {} if params is None else params}
  192. future = asyncio.get_running_loop().create_future()
  193. self.pending[request_id] = future
  194. await self.ws.send_json(frame)
  195. try:
  196. response = await asyncio.wait_for(future, timeout)
  197. finally:
  198. self.pending.pop(request_id, None)
  199. if response.get("id") != request_id or response.get("v") != 1:
  200. raise AssertionError("Invalid response request id or version")
  201. return response
  202. async def call(self, method, params=None, timeout=20):
  203. response = await self.raw_call(method, params, timeout=timeout)
  204. if response.get("ok") is not True:
  205. raise RpcFailure(method, response.get("error"))
  206. return response.get("result")
  207. async def get_state(self):
  208. state = await self.call("GetState")
  209. if not isinstance(state, dict):
  210. raise AssertionError("GetState result must be an object")
  211. self.state = state
  212. return state
  213. async def station(self, station_id):
  214. state = await self.get_state()
  215. return next(s for s in state.get("stations", []) if s.get("station_id") == station_id)
  216. async def wait_command(client, command_id, deadline):
  217. while time.monotonic() < deadline:
  218. result = await client.call("GetCommand", {"command_id": command_id})
  219. if result.get("state") in TERMINAL:
  220. return result
  221. await asyncio.sleep(.5)
  222. raise TimeoutError(f"Command {command_id} did not become terminal")
  223. async def reject_check(client, evidence, name, method, params, codes, **kwargs):
  224. frame = await client.raw_call(method, params, **kwargs)
  225. error = frame.get("error") or {}
  226. evidence.check(name, frame.get("ok") is False and error.get("code") in codes,
  227. {"code": error.get("code"), "message": error.get("message")})
  228. async def readonly_checks(client, evidence, args, session, token):
  229. try:
  230. await asyncio.wait_for(client.first_state.wait(), 12)
  231. evidence.check("automatic_initial_state_push", True,
  232. {"push_count_before_first_request": client.state_count})
  233. except TimeoutError:
  234. evidence.check("automatic_initial_state_push", False, "No unsolicited state within 12 seconds")
  235. state = await client.get_state()
  236. evidence.data["initial_state"] = state
  237. evidence.check("state_required_fields", all(k in state for k in
  238. ("version", "mode", "server_id", "stations")),
  239. {"version": state.get("version"), "mode": state.get("mode"),
  240. "server_id": state.get("server_id")})
  241. stations = state.get("stations", [])
  242. ids = [row.get("station_id") for row in stations]
  243. evidence.check("station_ids_unique_and_requested_present", args.station in ids and len(ids) == len(set(ids)), ids)
  244. required = {"station_id", "connection", "power", "phase", "run_state", "started_unix_ms",
  245. "boot_id", "verdict", "input", "command", "channels"}
  246. missing = {row.get("station_id", "?"): sorted(required - set(row)) for row in stations if required - set(row)}
  247. evidence.check("minimal_station_contract", not missing, missing)
  248. forbidden = private_fields(state)
  249. evidence.check("no_internal_or_secret_fields_in_clean_state", not forbidden, forbidden)
  250. await reject_check(client, evidence, "unknown_rpc_rejected", "NotARealQtMethod", {}, {"UNIMPLEMENTED", "INVALID_ARGUMENT"})
  251. await reject_check(client, evidence, "unknown_getstate_field_rejected", "GetState", {"unexpected": True}, {"INVALID_ARGUMENT"})
  252. await reject_check(client, evidence, "invalid_params_type_rejected", "GetState", "invalid", {"INVALID_ARGUMENT"})
  253. await reject_check(client, evidence, "unsupported_protocol_version_rejected", "GetState", {}, {"INVALID_ARGUMENT"}, version=9)
  254. await reject_check(client, evidence, "missing_command_rejected", "GetCommand", {"command_id": "verify-missing-" + uuid.uuid4().hex}, {"NOT_FOUND"})
  255. await reject_check(client, evidence, "event_log_not_in_qt_clean", "ReadEventQueue", {"station_id": args.station}, {"UNIMPLEMENTED"})
  256. await reject_check(client, evidence, "invalid_uart_offset_rejected", "ReadBiosUart", {"station_id": args.station, "offset": -1}, {"INVALID_ARGUMENT"})
  257. legacy = {}
  258. for view in ("full", "qt"):
  259. async with WsClient(session, safe_url(args.url, view), evidence, token, record_push=False) as old:
  260. info = await old.call("GetSystemInfo")
  261. legacy[view] = info
  262. evidence.check(f"legacy_{view}_GetSystemInfo", isinstance(info, dict) and bool(info.get("version")), info)
  263. if view == "full":
  264. listed = await old.call("ListStations")
  265. evidence.check("legacy_full_ListStations", isinstance(listed, dict) and isinstance(listed.get("stations"), list),
  266. {"station_count": len(listed.get("stations", []))})
  267. if args.check_unconfigured:
  268. ctl = await old.call("GetStationControl", {"station_id": args.check_unconfigured})
  269. evidence.data["unconfigured_capabilities"] = {
  270. "station_id": args.check_unconfigured, "capabilities": ctl.get("capabilities", {})}
  271. evidence.data["legacy_system_info"] = legacy
  272. evidence.check("legacy_and_clean_version_match", all(info.get("version") == state.get("version") for info in legacy.values()))
  273. # A second connection gets its own complete initial snapshot, independent of the first.
  274. async with WsClient(session, args.url, evidence, token, record_push=False) as other:
  275. await asyncio.wait_for(other.first_state.wait(), 12)
  276. evidence.check("second_client_gets_initial_snapshot", other.state.get("server_id") == state.get("server_id"))
  277. evidence.check("first_client_survives_second_disconnect", (await client.get_state()).get("server_id") == state.get("server_id"))
  278. async def grpc_check(args, evidence, token):
  279. if not args.grpc_address:
  280. return
  281. if args.backend_source:
  282. sys.path.insert(0, str(Path(args.backend_source).resolve() / "src"))
  283. try:
  284. import grpc
  285. from google.protobuf.empty_pb2 import Empty
  286. from stl_backend.generated import bench_pb2_grpc
  287. metadata = (("authorization", "Bearer " + token),) if token else ()
  288. async with grpc.aio.insecure_channel(args.grpc_address) as channel:
  289. stub = bench_pb2_grpc.BenchServiceStub(channel)
  290. info = await stub.GetSystemInfo(Empty(), timeout=15, metadata=metadata)
  291. stations = await stub.ListStations(Empty(), timeout=15, metadata=metadata)
  292. evidence.check("native_grpc_readonly_compatibility", bool(info.version) and bool(stations.stations),
  293. {"version": info.version, "mode": info.mode, "station_count": len(stations.stations)})
  294. except Exception as exc:
  295. evidence.check("native_grpc_readonly_compatibility", False, {"error": type(exc).__name__, "message": str(exc)[:500]})
  296. async def unconfigured_check(client, evidence, args):
  297. if not args.check_unconfigured:
  298. return
  299. caps = evidence.data.get("unconfigured_capabilities", {}).get("capabilities", {})
  300. if caps.get("bmc_power") is not False:
  301. evidence.check("unconfigured_station_has_no_power_capability", False,
  302. "Refused StartTest: full interface did not explicitly report bmc_power=false")
  303. return
  304. sid = args.check_unconfigured
  305. cid = "verify-unconfigured-" + uuid.uuid4().hex
  306. before = await client.station(sid)
  307. try:
  308. accepted = await client.call("StartTest", {"station_id": sid, "command_id": cid})
  309. result = accepted if accepted.get("state") in TERMINAL else await wait_command(client, cid, time.monotonic() + 45)
  310. error = result.get("error") or {}
  311. rejected = result.get("state") == "failed"
  312. except RpcFailure as exc:
  313. result, error, rejected = None, exc.error, True
  314. after = await client.station(sid)
  315. evidence.data["unconfigured_start"] = {"station_id": sid, "command_id": cid, "result": result, "error": error}
  316. evidence.check("unconfigured_start_rejected_without_boot", rejected and before.get("boot_id") == after.get("boot_id"),
  317. {"error": error, "before_power": before.get("power"), "after_power": after.get("power")})
  318. async def start_test(client, evidence, args):
  319. station = await client.station(args.station)
  320. before = station_summary(station)
  321. cid = "verify-start-" + uuid.uuid4().hex
  322. params = {"station_id": args.station, "command_id": cid}
  323. row = {"method": "StartTest", "params": params, "before": before, "sent_utc": timestamp()}
  324. evidence.data["commands"].append(row)
  325. evidence.save()
  326. accepted = await client.call("StartTest", params)
  327. row["accepted"] = accepted
  328. replay_pending = await client.call("StartTest", params)
  329. row["replay_while_pending"] = replay_pending
  330. evidence.check("start_same_id_pending_replay", accepted.get("command_id") == cid and replay_pending.get("command_id") == cid)
  331. done = await wait_command(client, cid, time.monotonic() + args.timeout)
  332. row["completed"] = done
  333. if not evidence.check("start_command_succeeded", done.get("state") == "succeeded", done):
  334. raise RuntimeError("Host start did not succeed")
  335. result = done.get("result") or {}
  336. expected = {"off": "host_on", "on": "host_reset"}.get(result.get("previous_power"))
  337. evidence.check("start_power_action_matches_live_power", expected is not None and result.get("power_action") == expected,
  338. {"previous_power": result.get("previous_power"), "power_action": result.get("power_action")})
  339. evidence.check("start_requires_new_bios_boot_evidence", result.get("boot_observed") is True and bool(result.get("boot_id"))
  340. and result.get("boot_id") != result.get("previous_boot_id"),
  341. {k: result.get(k) for k in ("previous_boot_id", "boot_id", "boot_observed", "started_unix_ms")})
  342. replay_done = await client.call("StartTest", params)
  343. row["replay_after_completion"] = replay_done
  344. evidence.check("start_same_id_completed_replay", replay_done.get("command_id") == cid
  345. and replay_done.get("state") == "succeeded"
  346. and (replay_done.get("result") or {}).get("boot_id") == result.get("boot_id"))
  347. now = await client.station(args.station)
  348. evidence.data["boot_evidence"] = result
  349. evidence.data["after_start"] = station_summary(now)
  350. evidence.check("state_agrees_with_completed_start", now.get("boot_id") == result.get("boot_id"))
  351. return result.get("boot_id")
  352. async def drive_plan(client, evidence, args, boot_id):
  353. deadline = time.monotonic() + args.timeout
  354. handled = set()
  355. rank, stages = -1, []
  356. while time.monotonic() < deadline:
  357. station = await client.station(args.station)
  358. if station.get("boot_id") != boot_id:
  359. raise RuntimeError("Unexpected new BIOS boot during local validation plan; no stage input replayed")
  360. phase = station.get("phase", "unknown")
  361. new_rank = STAGE_RANK.get(phase, -1)
  362. if new_rank >= 0 and new_rank < rank:
  363. evidence.check("overall_phase_never_regresses", False, {"previous_rank": rank, "phase": phase})
  364. raise RuntimeError("Overall phase regressed")
  365. rank = max(rank, new_rank)
  366. if not stages or stages[-1] != phase:
  367. stages.append(phase)
  368. evidence.data["default_plan_stages"] = stages
  369. evidence.save()
  370. point = station.get("input") or {}
  371. if point.get("ready") and point.get("stage") == "uefi":
  372. evidence.data["after_default_plan"] = station_summary(station)
  373. evidence.check("default_plan_reached_real_uefi_prompt", phase == "uefi", {"stages": stages, "input": point})
  374. evidence.check("overall_phase_never_regresses", True, stages)
  375. return
  376. stage = point.get("stage")
  377. action = "continue_uip" if stage in ("uip", "uip1", "uip2") else "skip_amt" if stage == "amt" else None
  378. key = point.get("id")
  379. if point.get("ready") and action and key and key not in handled:
  380. actions = point.get("actions") or []
  381. if action not in actions:
  382. await asyncio.sleep(.5)
  383. continue
  384. handled.add(key)
  385. cid = "verify-stage-" + uuid.uuid4().hex
  386. params = {"command_id": cid, "station_id": args.station,
  387. "input_id": key, "action": action}
  388. row = {"method": "StageAction", "params": params, "input": point, "sent_utc": timestamp()}
  389. evidence.data["commands"].append(row)
  390. evidence.save()
  391. row["accepted"] = await client.call("StageAction", params)
  392. done = await wait_command(client, cid, min(deadline, time.monotonic() + 90))
  393. row["completed"] = done
  394. evidence.check("stage_action_" + action + "_" + str(len(handled)), done.get("state") == "succeeded", done)
  395. if done.get("state") != "succeeded":
  396. raise RuntimeError("Stage action failed; not retrying hardware input")
  397. evidence.save()
  398. await asyncio.sleep(.5)
  399. raise TimeoutError("Default local validation plan did not reach UEFI before deadline")
  400. async def run(args, evidence):
  401. token = os.environ.get(args.token_env, "") if args.token_env else ""
  402. async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session:
  403. async with WsClient(session, args.url, evidence, token) as client:
  404. await readonly_checks(client, evidence, args, session, token)
  405. await grpc_check(args, evidence, token)
  406. if evidence.fail_count():
  407. raise RuntimeError("Read-only contract checks failed; no hardware actions submitted")
  408. await unconfigured_check(client, evidence, args)
  409. if args.start:
  410. boot_id = await start_test(client, evidence, args)
  411. if args.drive_default_plan:
  412. await drive_plan(client, evidence, args, boot_id)
  413. evidence.data["final_state"] = await client.get_state()
  414. evidence.data["state_push_count"] = client.state_count
  415. evidence.check("websocket_frames_valid", not client.protocol_errors, client.protocol_errors)
  416. evidence.check("final_state_has_no_internal_or_secret_fields", not private_fields(evidence.data["final_state"]))
  417. def main():
  418. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  419. parser.add_argument("--url", required=True, help="ws://HOST:8080/ws?view=qt-clean")
  420. parser.add_argument("--output", required=True, help="JSON evidence file")
  421. parser.add_argument("--station", default="S1")
  422. parser.add_argument("--timeout", type=float, default=900, help="Seconds per host start / local plan")
  423. parser.add_argument("--start", action="store_true", help="Actually start/reset the server host once")
  424. parser.add_argument("--drive-default-plan", action="store_true", help="With --start: CR at UIP; exit AMT; stop at UEFI")
  425. parser.add_argument("--check-unconfigured", metavar="STATION", help="Explicitly try StartTest on a station with bmc_power=false")
  426. parser.add_argument("--grpc-address", help="Optional native gRPC HOST:PORT read-only smoke test")
  427. parser.add_argument("--backend-source", help="Backend project root for generated gRPC modules")
  428. parser.add_argument("--token-env", help="Environment variable containing API bearer token; never written to evidence")
  429. args = parser.parse_args()
  430. if args.drive_default_plan and not args.start:
  431. parser.error("--drive-default-plan requires --start")
  432. if args.timeout <= 0:
  433. parser.error("--timeout must be positive")
  434. if dict(parse_qsl(urlsplit(args.url).query)).get("view") != "qt-clean":
  435. parser.error("--url must explicitly select view=qt-clean")
  436. evidence = Evidence(args)
  437. evidence.save()
  438. try:
  439. asyncio.run(run(args, evidence))
  440. except KeyboardInterrupt:
  441. evidence.check("validation_completed", False, "Interrupted; already accepted hardware commands may continue")
  442. except Exception as exc:
  443. evidence.check("validation_completed", False, {"error": type(exc).__name__, "message": str(exc)[:1200]})
  444. evidence.data["finished_utc"] = timestamp()
  445. evidence.data["protocol_verdict"] = "FAIL" if evidence.fail_count() else "PASS"
  446. evidence.save()
  447. print(json.dumps({"protocol_verdict": evidence.data["protocol_verdict"],
  448. "memory_verdict": evidence.data["memory_verdict"], "output": str(evidence.path)}, ensure_ascii=False))
  449. return 1 if evidence.fail_count() else 0
  450. if __name__ == "__main__":
  451. raise SystemExit(main())