"""H2 remote-history live smoke on a `rig.py up --history` run (plan §9 H2 exit gate). Drives the deployed rig only through its owned surfaces: the device control API (advances the historized `counter`), the probe's raw origin RPCs (`--scenario history`), the CONSUMER node probe's deployed-connection lease (`history` operation = a runtime consumer's IDataHistoryService read) and the Client CLI's OPC UA `historyread` on the SOURCE node. Evidence lands in the run's restricted `evidence/` folder; keys are redacted by ScenarioRunner.save. """ import argparse import json import re import sys import time from datetime import datetime, timedelta, timezone from pathlib import Path import scenarios import rig def _iso(moment): return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def _cli_rows(stdout): """`historyread` rows → [(source time ISO, value text, status text)].""" rows = [] for line in stdout.splitlines(): match = re.match(r"^\s*(\d{4}-\d{2}-\d{2}[T ][0-9:.]+Z?)\s*\|?\s*(.*)$", line) if match: rows.append((match[1], match[2].strip())) return rows def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--run-id", required=True) parser.add_argument("--accumulate-seconds", type=int, default=40) arguments = parser.parse_args(argv) runner = scenarios.ScenarioRunner(arguments.run_id) if runner.manifest["fixture"].get("history") is None: raise SystemExit("run was not brought up with --history") runner.active, runner.deadline = "H2", time.monotonic() + 900 runner.publish() report = {"run_id": arguments.run_id, "source_revision": runner.manifest.get("source_revision"), "source_tree_hash": runner.manifest.get("source_tree_hash"), "items": {}} # 1. Accumulate history: one counter step per second. started = datetime.now(timezone.utc) for _ in range(arguments.accumulate_seconds): runner.device("advance", steps=1) time.sleep(1) finished = datetime.now(timezone.utc) time.sleep(4) # let the outbox drain (DrainIntervalSeconds=1) window_start = (started + timedelta(seconds=5)).replace(microsecond=0) window_end = (finished - timedelta(seconds=5)).replace(microsecond=0) report["accumulation"] = {"started": started.isoformat(), "finished": finished.isoformat(), "window": [_iso(window_start), _iso(window_end)], "device": runner.device()} # 2. Origin RPCs on both SOURCE data listeners. output = runner.folder / "H2-history-wire.json" result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "history", "--history-start", _iso(window_start), "--history-end", _iso(window_end), "--output", str(output)], "H2-history-wire", timeout=120) wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]} report["items"]["wire"] = wire # 3. OPC UA historyread on each SOURCE node for the same window. cli = {} for node in ("source-1", "source-2"): resolved = runner.manifest["resolved_nodes"][node]["aliases"]["raw"] node_id = resolved.rsplit("/", 1)[0] + "/counter" argv = ["dotnet", str(runner.cli_dll), "historyread", "-u", runner.endpoint(node), "-U", "apikey", "-P", runner.key, "-n", node_id, "--start", _iso(window_start), "--end", _iso(window_end), "--max", "1000"] run = runner.process(argv, "H2-cli-historyread-" + node, timeout=60) cli[node] = {"node_id": node_id, "returncode": run.returncode, "stdout": run.stdout[-8000:], "stderr": run.stderr[-2000:]} # The non-historized tag over OPC UA, for contrast with the remote refusal. argv[argv.index("-n") + 1] = resolved run = runner.process(argv, "H2-cli-historyread-unhistorized-" + node, timeout=60) cli[node]["unhistorized"] = {"node_id": resolved, "returncode": run.returncode, "stdout": run.stdout[-2000:], "stderr": run.stderr[-2000:]} report["items"]["cli"] = cli # 4. Runtime consumer: the deployed connection lease on each CONSUMER node. consumer = {} paths = runner.manifest["fixture"]["history"] for node in ("consumer-1", "consumer-2"): observed = {} for name, fields in ( ("newest5", {"path": paths["historized"]["raw"], "historyNumValues": 5}), ("window", {"path": paths["historized"]["raw"], "historyNumValues": 0, "historyStartUtc": window_start.isoformat(), "historyEndUtc": window_end.isoformat()}), ("unhistorized", {"path": paths["unhistorized"]["raw"], "historyNumValues": 5, "expected_state": "Unsupported"}), ("uns-newest5", {"realm": "uns", "path": paths["historized"]["uns"], "historyNumValues": 5})): realm = fields.pop("realm", "raw") expected = fields.pop("expected_state", None) try: observed[name] = {"passed": True, "observations": runner.probe(node, "history", realm, expected_state=expected, timeout=60, **fields)} except Exception as error: # record and continue: the smoke reports per item observed[name] = {"passed": False, "error": type(error).__name__ + ": " + str(error)} consumer[node] = observed report["items"]["consumer"] = consumer runner.save("H2-history-smoke.json", report) print(json.dumps({"saved": str(runner.folder / "H2-history-smoke.json"), "wire_passed": wire.get("passed"), "consumer": {node: {k: v["passed"] for k, v in rows.items()} for node, rows in consumer.items()}, "cli": {node: row["returncode"] for node, row in cli.items()}}, indent=2)) return 0 if __name__ == "__main__": sys.exit(main())