"""H3 live gate: scenarios H01–H06 (plan §9 "Scenarios") on a `rig.py up --history [--history-backend questdb]` run. Every scenario is driven through the production Client CLI `historyread` against CONSUMER's OPC UA endpoint, on PROJECTED NodeIds resolved by browsing from the mapping anchor (never constructed `p1.` ids), and is compared with the same read on the ORIGIN (SOURCE) node. Each scenario restores the baseline (transactional authoring restore + deploy) whatever its outcome. The rows are declared in `scenarios.json` → `history_scenarios`; evidence lands in the run's restricted `evidence/` folder (keys redacted by ScenarioRunner.save). """ import argparse import json import re import sys import threading import time import uuid from datetime import datetime, timedelta, timezone from pathlib import Path import history_smoke import rig import scenarios NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpdate excluded) NODE_PERMISSIONS_HISTORY_READ = 1 << 3 NODE_PERMISSIONS_BROWSE = 1 << 0 EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe # #922: longer than the rig mappings' 15 s MetadataLeaseMilliseconds, so a projected node idles past its lease. LEASE_LAPSE_SECONDS = 20 def _iso(moment): return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") class HistoryGate: def __init__(self, run_id, *, pinned_build=False): if pinned_build: recorded = scenarios.restricted_json(rig.LocalRig(run_id).path)["source_tree_hash"] rig.source_tree_hash = lambda: recorded self.runner = scenarios.ScenarioRunner(run_id) if self.runner.manifest["fixture"].get("history") is None: raise SystemExit("run was not brought up with --history") self.backend = self.runner.rig.environment.get("GRPC_DATA_HISTORY_BACKEND", "sqlserver") self.catalog = json.loads((rig.HERE / "scenarios.json").read_text())["history_scenarios"] self.window = None self.projected = {} # ----------------------------------------------------------------------------------------------------------- tools def cli(self, node, extra, name, *, timeout=90): argv = ["dotnet", str(self.runner.cli_dll), "historyread", "-u", self.runner.endpoint(node), "-U", "apikey", "-P", self.runner.key, *extra] return self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=timeout) def window_args(self): return ["--start", _iso(self.window[0]), "--end", _iso(self.window[1])] def origin_node(self, realm, name): source = self.runner.primary("source") alias = self.runner.manifest["resolved_nodes"][source]["aliases"][realm] return source, alias.rsplit("/", 1)[0] + "/" + name def accumulate(self, seconds=40): started = datetime.now(timezone.utc) self.runner.device("set", address=30, value=16480) # flt = 3.5f (0x40600000, big-endian words) for second in range(seconds): self.runner.device("advance", steps=1) if second == seconds // 2: self.runner.device("set", address=30, value=16616) # flt = 7.25f (0x40E80000) time.sleep(1) finished = datetime.now(timezone.utc) time.sleep(4) self.window = ((started + timedelta(seconds=5)).replace(microsecond=0), (finished - timedelta(seconds=5)).replace(microsecond=0)) def resolve_projected(self): """Browse CONSUMER from the shared root; keep the projected leaves under the mapping anchors (`remote-source`).""" consumer = self.runner.primary("consumer") uris = self.runner.manifest["resolved_nodes"][consumer]["namespace_uris"] ns = {key: uris.index(uri) for key, uri in self.runner.manifest["fixture"]["namespace_uris"].items()} argv = ["dotnet", str(self.runner.cli_dll), "browse", "-u", self.runner.endpoint(consumer), "-U", "apikey", "-P", self.runner.key, "-n", f"ns={ns['raw']};s=OtOpcUa", "-r", "-d", "7"] result = self.runner.process(argv, "H-browse-" + uuid.uuid4().hex[:6], timeout=120) self.runner.check(result.returncode == 0, "consumer browse succeeded") stack, found = [], {} for line in result.stdout.splitlines(): match = re.match(r"^( *)\[(\w+)\] (.+?) \(NodeId: (.+)\)$", line) if match is None: continue depth = len(match[1]) // 2 del stack[depth:] stack.append(match[3]) node_id = match[4] index = int(re.match(r"ns=(\d+);", node_id)[1]) if node_id.startswith("ns=") else -1 realm = "raw" if index == ns["mapped_raw"] else "uns" if index == ns["mapped_uns"] else None if realm and "remote-source" in stack[:-1] and match[3] in {"counter", "scalar", "text", "flt"}: self.runner.check((realm, match[3]) not in found, "one projected leaf per realm and name") found[(realm, match[3])] = node_id for realm in ("raw", "uns"): for name in ("counter", "scalar", "text", "flt"): self.runner.check((realm, name) in found, f"projected {realm}/{name} found by browse from the mapping anchor") self.runner.check(found[(realm, name)].split(";s=", 1)[1].startswith("p1."), "projected ids are opaque p1. ids") self.projected = found self.runner.save("H-projected-nodes.json", {f"{k[0]}/{k[1]}": v for k, v in found.items()}) return consumer def rebrowse(self, timeout=90): """A deploy retires cold projected nodes; browse from the anchor again (the SAME opaque ids come back).""" end = time.monotonic() + timeout while True: try: previous = dict(self.projected) self.resolve_projected() self.runner.check(not previous or previous == self.projected, "projected NodeIds are stable across a deploy") return except scenarios.ScenarioError: if time.monotonic() >= end: raise time.sleep(3) def change(self, **mutation): """A production mutation + deploy, then re-materialise the projected leaves by browse.""" self.runner.mutate(**mutation) self.rebrowse() def restore(self): self.runner.baseline() self.rebrowse() def held(self, consumer, extra, name, during, *, marker_timeout=60): """Runs a hand-paged CLI read in the background; `during()` runs once the read reports its held point.""" marker = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".held") resume = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".resume") outcome = {} def worker(): outcome["result"] = self.cli(consumer, [*extra, "--held-marker-file", str(marker), "--resume-when-file", str(resume)], name, timeout=600) thread = threading.Thread(target=worker, daemon=True) thread.start() end = time.monotonic() + marker_timeout while not marker.exists() and thread.is_alive() and time.monotonic() < end: time.sleep(0.1) self.runner.check(marker.exists(), "the CLI reached its held point") try: during() finally: resume.write_text("") thread.join(timeout=600) self.runner.check("result" in outcome, "held CLI finished") return outcome["result"] @staticmethod def status_lines(stdout): return [line for line in stdout.splitlines() if line.startswith(("Page ", "Fresh:", "Status:", "Released", "Abandoned"))] @staticmethod def error_status(result): combined = result.stdout + "\n" + result.stderr match = re.search(r"(Bad\w+)", combined) return match[1] if match else None def poll_status(self, consumer, node, expected, name, *, extra=None, timeout=120): end = time.monotonic() + timeout attempts = [] while True: result = self.cli(consumer, ["-n", node, *self.window_args(), "--max", "50", *(extra or [])], name) observed = self.error_status(result) if result.returncode != 0 else "Good" attempts.append(observed) if observed == expected or time.monotonic() >= end: return observed, attempts, result time.sleep(3) def origin_state(self): total = 0 for node in ("source-1", "source-2"): observed = self.runner.probe(node, "topology", timeout=30) total += int(observed.get("originAccounting", {}).get("historyOpenContinuations") or 0) return total # ------------------------------------------------------------------------------------------------------- scenarios def scenario_H01(self): """Raw paging across page boundaries, Raw and UNS mappings, row-for-row equal to the origin.""" report = {} consumer = self.runner.primary("consumer") for realm in ("raw", "uns"): source, origin = self.origin_node(realm, "counter") reference = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], f"origin-{realm}") self.runner.check(reference.returncode == 0, f"origin {realm} read") origin_rows = history_smoke._cli_rows(reference.stdout) self.runner.check(len(origin_rows) >= 10, f"origin {realm} window holds history") paged = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--page-size", "3", "--max", "1000"], f"paged-{realm}") pages = [line for line in paged.stdout.splitlines() if line.startswith("Page ")] self.runner.check(paged.returncode == 0 and len(pages) >= 2, f"{realm}: several pages") self.runner.check(all("Good" in line for line in pages), f"{realm}: every page Good") self.runner.check(pages[-1].split("continuation=")[1].startswith("no"), f"{realm}: the last page has no continuation") rows = history_smoke._cli_rows(paged.stdout) self.runner.check(rows == origin_rows, f"{realm}: paged projected rows equal the origin row-for-row") whole = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--max", "1000"], f"whole-{realm}") self.runner.check(history_smoke._cli_rows(whole.stdout) == origin_rows, f"{realm}: single read equals the origin") report[realm] = {"pages": len(pages), "rows": len(rows), "first": str(rows[0]), "last": str(rows[-1]), "page_lines": pages} # H3 review: a Float32 node whose backend stores Double reads the same Good rows through the projection. source, origin = self.origin_node("raw", "flt") reference = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], "origin-flt") floats = self.cli(consumer, ["-n", self.projected[("raw", "flt")], *self.window_args(), "--max", "1000"], "flt") origin_rows, rows = history_smoke._cli_rows(reference.stdout), history_smoke._cli_rows(floats.stdout) self.runner.check(reference.returncode == 0 and floats.returncode == 0 and len(rows) >= 1, "Float32 history served on both") self.runner.check(rows == origin_rows and all(q == "Good" for _, _, q in rows), "Float32 rows Good and equal to the origin") report["float32"] = {"rows": [str(r) for r in rows]} report["tie_cluster"] = ("not representable on the " + self.backend + " backend: SqlServer hist.Sample PK (TagId, SourceTimeUtc), " "QuestDB DEDUP UPSERT KEYS(ts, tag) — one stored sample per timestamp; tie paging is proven by the H1 port fuzz") return report def scenario_H02(self): """Processed: the origin refuses an aggregate for the node's type (#897); a served aggregate equals the origin.""" consumer = self.runner.primary("consumer") refused = self.cli(consumer, ["-n", self.projected[("raw", "text")], *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "text-average") self.runner.check(refused.returncode != 0 and self.error_status(refused) == "BadAggregateNotSupported", "Average on a String node is BadAggregateNotSupported from the origin") source, origin = self.origin_node("raw", "text") origin_refused = self.cli(source, ["-n", origin, *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "origin-text-average") self.runner.check(self.error_status(origin_refused) == "BadAggregateNotSupported", "the origin answers the same refusal") source, origin = self.origin_node("raw", "counter") reference = self.cli(source, ["-n", origin, *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "origin-average") served = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "average") self.runner.check(reference.returncode == 0 and served.returncode == 0, "Average served on both") rows, origin_rows = history_smoke._cli_rows(served.stdout), history_smoke._cli_rows(reference.stdout) self.runner.check(len(rows) > 0 and rows == origin_rows, "projected Average equals the origin row-for-row") return {"refused": self.error_status(refused), "origin_refused": self.error_status(origin_refused), "average_rows": len(rows)} def scenario_H03(self): """AtTime on an integer (UInt16) node: identical values, timestamps, statuses and value types.""" consumer = self.runner.primary("consumer") start = self.window[0] times = ",".join(_iso(start + timedelta(seconds=s)) for s in (3, 7, 11)) source, origin = self.origin_node("raw", "counter") reference = self.cli(source, ["-n", origin, "--at-time", times], "origin-attime") projected = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--at-time", times], "attime") self.runner.check(reference.returncode == 0 and projected.returncode == 0, "AtTime served") rows, origin_rows = history_smoke._cli_rows(projected.stdout), history_smoke._cli_rows(reference.stdout) types = [line for line in projected.stdout.splitlines() if line.startswith("Type:")] origin_types = [line for line in reference.stdout.splitlines() if line.startswith("Type:")] self.runner.check(len(rows) == 3 and rows == origin_rows, "projected AtTime equals the origin row-for-row") self.runner.check(types == origin_types and all(t == "Type: UInt16" for t in types), "integer values stay UInt16 end to end") source, origin = self.origin_node("raw", "flt") float_times = ",".join(_iso(start + timedelta(seconds=sec)) for sec in (2, 20)) reference_f = self.cli(source, ["-n", origin, "--at-time", float_times], "origin-attime-flt") projected_f = self.cli(consumer, ["-n", self.projected[("raw", "flt")], "--at-time", float_times], "attime-flt") rows_f, origin_rows_f = history_smoke._cli_rows(projected_f.stdout), history_smoke._cli_rows(reference_f.stdout) types_f = [line for line in projected_f.stdout.splitlines() if line.startswith("Type:")] origin_types_f = [line for line in reference_f.stdout.splitlines() if line.startswith("Type:")] self.runner.check(projected_f.returncode == 0 and rows_f == origin_rows_f and all(q == "Good" for _, _, q in rows_f), "Float32 AtTime equals the origin, Good") self.runner.check(types_f == origin_types_f and all(t == "Type: Single" for t in types_f), "Float32 values stay Single end to end") return {"rows": [str(r) for r in rows], "types": types, "float32": {"rows": [str(r) for r in rows_f], "types": types_f}} def scenario_H04(self): """A continuation across an origin failover is BadContinuationPointInvalid; a fresh read moves and succeeds.""" consumer = self.runner.primary("consumer") source = self.runner.primary("source") observed = {} def failover(): with self.runner.stopped(source): observed["new_primary"] = self.runner.wait_primary("source", exclude=source) self.runner.wait_connection_ready(consumer, "raw") # Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. No re-browse: a # projected node whose 15 s metadata lease lapsed renews on demand within the HistoryRead (#922). self.held_resume_now() self.runner.wait_pair_topology("source") result = self.held_with_inline_resume(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", "--pause-after-page", "1", "--fresh-after-failure"], "failover", failover) lines = self.status_lines(result.stdout) self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "the resumed page is BadContinuationPointInvalid") self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read succeeds on the new primary") return {"old_primary": source, "new_primary": observed.get("new_primary"), "lines": lines} def held_with_inline_resume(self, consumer, extra, name, during): """Like held(), but `during` decides WHEN to resume by calling self.held_resume_now().""" marker = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".held") resume = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".resume") outcome = {} def worker(): outcome["result"] = self.cli(consumer, [*extra, "--held-marker-file", str(marker), "--resume-when-file", str(resume)], name, timeout=600) thread = threading.Thread(target=worker, daemon=True) thread.start() end = time.monotonic() + 60 while not marker.exists() and thread.is_alive() and time.monotonic() < end: time.sleep(0.1) self.runner.check(marker.exists(), "the CLI reached its held point") resumed = threading.Event() def resume_now(): resume.write_text("") thread.join(timeout=300) resumed.set() self.held_resume_now = resume_now try: during() finally: if not resumed.is_set(): resume_now() self.runner.check("result" in outcome, "held CLI finished") return outcome["result"] def scenario_H05(self): """Substitute for "v1 origin (pinned old image)": an origin that no longer advertises history for this principal.""" consumer = self.runner.primary("consumer") before, _, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "Good", "before", timeout=30) self.runner.check(before == "Good", "history served before the change") self.change(export_id="export-raw", export_allowed_operations=EXPORT_WITHOUT_HISTORY) observed, attempts, result = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported", "not-advertised", timeout=180) self.runner.check(observed == "BadHistoryOperationUnsupported", "an origin that does not advertise history ⇒ unsupported") uns, _, _ = self.poll_status(consumer, self.projected[("uns", "counter")], "Good", "uns-still-served", timeout=30) self.runner.check(uns == "Good", "the other export (UNS) still serves history") return {"before": before, "after": observed, "attempts": attempts, "uns": uns, "substitution": "no pinned v1 image is built by the rig; the export drops HistoryRead (bit 32) instead"} def scenario_H06(self): """Denied vs unhistorized indistinguishable; local deny is BadUserAccessDenied; session close releases; rebuild mid-page.""" consumer = self.runner.primary("consumer") report = {} # (a) unhistorized vs origin-ACL-denied: the same refusal, the same text (node ids normalised). unhistorized, _, unh = self.poll_status(consumer, self.projected[("raw", "scalar")], "BadHistoryOperationUnsupported", "unhistorized", timeout=30) self.runner.check(unhistorized == "BadHistoryOperationUnsupported", "unhistorized ⇒ BadHistoryOperationUnsupported") self.change(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NODE_PERMISSIONS_ADMIN & ~NODE_PERMISSIONS_HISTORY_READ}) denied, attempts, den = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported", "origin-denied", timeout=180) normalise = lambda text: re.sub(r"ns=\d+;s=\S+", "", "\n".join(l for l in (text.stdout + text.stderr).splitlines() if "Bad" in l)) self.runner.check(denied == "BadHistoryOperationUnsupported", "origin ACL denial ⇒ BadHistoryOperationUnsupported") self.runner.check(normalise(unh) == normalise(den), "denied and unhistorized are indistinguishable") # H3 review: the per-item refusal itself, OVER THE WIRE (the consumer's deployed connection → the origin's ingress), # not only the metadata that drops the access bit: both answers identical 0x80720000, and the origin counted the calls. paths = self.runner.manifest["fixture"]["history"] primary = self.runner.primary("source") before = self.runner.probe(primary, "topology", timeout=30).get("inboundDataRequests") wire_denied = self.runner.probe(consumer, "history", "raw", path=paths["historized"]["raw"], historyNumValues=5, expected_state="Unsupported", timeout=60) wire_unhistorized = self.runner.probe(consumer, "history", "raw", path=paths["unhistorized"]["raw"], historyNumValues=5, expected_state="Unsupported", timeout=60) after = self.runner.probe(primary, "topology", timeout=30).get("inboundDataRequests") strip = lambda pages: [{k: v for k, v in page.items()} for page in pages] self.runner.check(strip(wire_denied["pages"]) == strip(wire_unhistorized["pages"]), "origin-ACL-denied and unhistorized answers are identical over the wire") report["wire"] = {"denied": wire_denied["pages"], "unhistorized": wire_unhistorized["pages"], "origin_inbound_requests": {"before": before, "after": after}} report["indistinguishable"] = {"unhistorized": normalise(unh), "denied": normalise(den), "attempts": attempts} self.restore() # (b) the LOCAL mapping-scope grant: without it, BadUserAccessDenied (a local decision); the other mapping keeps its grant. self.change(acl_permissions={"node_acl_id": "cli-history-map-raw", "permission_flags": NODE_PERMISSIONS_BROWSE}) local, attempts, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "BadUserAccessDenied", "local-denied", timeout=90) self.runner.check(local == "BadUserAccessDenied", "no local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied") other, _, _ = self.poll_status(consumer, self.projected[("uns", "counter")], "Good", "local-other-mapping", timeout=30) self.runner.check(other == "Good", "the UNS mapping's own grant still serves") report["local_deny"] = {"raw": local, "uns": other, "attempts": attempts} self.restore() consumer = self.runner.primary("consumer") # (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid. def rebuild(): self.change(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"}) rebuilt = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", "--pause-after-page", "1", "--fresh-after-failure"], "rebuild", rebuild) lines = self.status_lines(rebuilt.stdout) self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid") self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds") report["rebuild"] = lines # (c) a consumer session close releases the origin continuation. The restore's deploy retires cold projected nodes, so it # re-browses; the held read then deliberately starts only after the node's 15 s metadata lease has LAPSED (#922: it # renews on demand within the HistoryRead instead of answering BadUserAccessDenied). self.restore() time.sleep(LEASE_LAPSE_SECONDS) consumer = self.runner.primary("consumer") self.runner.check(self.origin_state() == 0, "no origin continuation open before") counts = {} def while_held(): counts["held"] = self.origin_state() abandoned = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "2", "--abandon-after-page", "1", "--hold-seconds", "10"], "abandon", while_held) self.runner.check(counts.get("held", 0) >= 1, "the origin holds the page cursor while the consumer session holds the point") end = time.monotonic() + 30 after = self.origin_state() while after != 0 and time.monotonic() < end: time.sleep(1) after = self.origin_state() self.runner.check(after == 0, "the consumer session close released the origin continuation (store count back to 0)") report["session_close"] = {"held": counts.get("held"), "after": after, "lines": self.status_lines(abandoned.stdout)} return report # ------------------------------------------------------------------------------------------------------------- run def run(self, selection): chosen = [row["id"] for row in self.catalog] if selection == "all" else [selection] self.runner.publish() self.runner.rig.seed_helper("snapshot") self.runner.active, self.runner.deadline = "H00", time.monotonic() + 900 self.accumulate() self.resolve_projected() rows = [] for name in chosen: spec = next(row for row in self.catalog if row["id"] == name) self.runner.active, self.runner.count = name, 0 self.runner.deadline = time.monotonic() + spec.get("timeout_seconds", 900) started, error, restored, detail = time.monotonic(), None, False, None try: detail = getattr(self, "scenario_" + name)() except Exception as failure: error = type(failure).__name__ + ": " + str(failure) finally: try: self.runner.deadline = time.monotonic() + 600 self.restore() restored = True except Exception as failure: error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + ": " + str(failure) row = {"id": name, "backend": self.backend, "passed": error is None and restored, "assertions": self.runner.count, "restored": restored, "duration_seconds": round(time.monotonic() - started, 1), "failure": error, "detail": detail} rows.append(row) self.runner.save(f"H3-history-{self.backend}-results.json", {"rows": rows, "window": [_iso(w) for w in self.window]}) print(json.dumps({k: row[k] for k in ("id", "backend", "passed", "assertions", "restored", "duration_seconds", "failure")}), flush=True) return rows def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--run-id", required=True) parser.add_argument("--scenario", default="all") parser.add_argument("--pinned-build", action="store_true") arguments = parser.parse_args(argv) gate = HistoryGate(arguments.run_id, pinned_build=arguments.pinned_build) rows = gate.run(arguments.scenario) return 0 if all(row["passed"] for row in rows) else 1 if __name__ == "__main__": sys.exit(main())