From 8341c7f4ae4f60805421af5c6e84c4f423cff7fb Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:42:46 -0500 Subject: [PATCH] test(grpc-data): H3 live gate harness (H01-H06, SqlServer and QuestDB origins) rig.py up --history --history-backend questdb adds a run-owned QuestDB for the SOURCE historian. History seed profile: mappings grant HistoryRead, the CLI principal's CONSUMER HistoryRead comes only from mapping-scoped grants, text is historized (per-type aggregate refusal), new acl_permissions mutation. history_gate.py drives H01-H06 through the Client CLI on projected NodeIds resolved by browse from the mapping anchor, compares with the origin, and restores the baseline after every scenario. The node probe reports the origin's open history continuations (LocalDataServices.HistoryOpenContinuations, now public). --- .../grpc-data/compose.history.questdb.yml | 38 ++ scripts/validation/grpc-data/history_gate.py | 381 ++++++++++++++++++ .../grpc-data/node-probe/NodeProbeStartup.cs | 1 + scripts/validation/grpc-data/rig.py | 17 +- scripts/validation/grpc-data/scenarios.json | 78 ++++ scripts/validation/grpc-data/seed/Program.cs | 27 +- .../LocalDataServices.History.cs | 2 +- 7 files changed, 535 insertions(+), 9 deletions(-) create mode 100644 scripts/validation/grpc-data/compose.history.questdb.yml create mode 100644 scripts/validation/grpc-data/history_gate.py diff --git a/scripts/validation/grpc-data/compose.history.questdb.yml b/scripts/validation/grpc-data/compose.history.questdb.yml new file mode 100644 index 000000000..c436e139e --- /dev/null +++ b/scripts/validation/grpc-data/compose.history.questdb.yml @@ -0,0 +1,38 @@ +# H3 QuestDB origin backend (opt-in: `rig.py up --history --history-backend questdb`), layered AFTER +# compose.history.yml: the SOURCE pair historizes into a run-owned QuestDB container instead of the run's SQL +# container. Same seed profile, same scenarios. The container and its volume carry the run labels, so +# `rig.py down` removes them with everything else. Image pinned as docker-dev/docker-compose.questdb.yml. + +x-labels: &labels + otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID:?run id required} + otopcua.grpc-data.fixture: "v1" + +x-source-questdb-env: &source-questdb-env + ServerHistorian__Backend: QuestDb + ServerHistorian__QuestDb__ConnectionString: "Host=questdb;Port=8812;Username=admin;Password=quest;Database=qdb;ServerCompatibilityMode=NoTypeLoading;Maximum Pool Size=16" + ServerHistorian__QuestDb__TablePrefix: hist_ + ServerHistorian__QuestDb__AutoCreateSchema: "true" + +services: + questdb: + image: questdb/questdb:10.0.1 + labels: *labels + networks: [rig] + volumes: [questdb-data:/var/lib/questdb] + healthcheck: + test: ["CMD-SHELL", "curl -fs http://localhost:9003/status || exit 1"] + interval: 5s + timeout: 5s + retries: 24 + source-1: + environment: *source-questdb-env + depends_on: + questdb: {condition: service_healthy} + source-2: + environment: *source-questdb-env + depends_on: + questdb: {condition: service_healthy} + +volumes: + questdb-data: + labels: *labels diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py new file mode 100644 index 000000000..c4514f852 --- /dev/null +++ b/scripts/validation/grpc-data/history_gate.py @@ -0,0 +1,381 @@ +"""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 + + +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) + for _ in range(seconds): + self.runner.device("advance", steps=1) + 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"}: + 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"): + 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 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} + 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") + return {"rows": [str(r) for r in rows], "types": types} + + 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. + 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.runner.mutate(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.runner.mutate(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") + report["indistinguishable"] = {"unhistorized": normalise(unh), "denied": normalise(den), "attempts": attempts} + self.runner.baseline() + # (b) the LOCAL mapping-scope grant: without it, BadUserAccessDenied (a local decision); the other mapping keeps its grant. + self.runner.mutate(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.runner.baseline() + consumer = self.runner.primary("consumer") + # (c) a consumer session close releases the origin continuation. + 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)} + # (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid. + def rebuild(): + self.runner.mutate(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 + 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.runner.baseline() + 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()) diff --git a/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs index 0b9fbb0ea..d6cffebb4 100644 --- a/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs +++ b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs @@ -66,6 +66,7 @@ public sealed partial class NodeProbeWorker(IServiceProvider services) : Backgro acquisitionOwnerSerial = acquisition?.CurrentOwnerSerial, acquisitionControlGeneration = acquisition?.ControlGeneration, workload = composition?.CaptureWorkloadAccounting(), sourceIngressCounters = SourceIngressDiagnostics.Capture(), + historyOpenContinuations = composition?.Services.HistoryOpenContinuations, definition = "actual origin hub resource charges and physical driver reservation owners; driver count is not source count" }; } diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index 2b32e484c..5b75330ea 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -473,7 +473,9 @@ def require_production_prerequisites(action, available): ROOT = Path(__file__).resolve().parents[3] HERE = Path(__file__).resolve().parent NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n in (1, 2)) -SERVICES = ("sql", "migrator", "device", "seeder", *NODES) +# `questdb` exists only on a `--history-backend questdb` run (compose.history.questdb.yml); listing it is the DNS allowlist. +SERVICES = ("sql", "migrator", "device", "seeder", "questdb", *NODES) +HISTORY_BACKENDS = ("sqlserver", "questdb") def run_command(argv, *, timeout=120, environment=None): @@ -671,6 +673,8 @@ class LocalRig: files = ["--file", str(HERE / "compose.yml")] if self.environment.get("GRPC_DATA_HISTORY") == "1": files.extend(["--file", str(HERE / "compose.history.yml")]) + if self.environment.get("GRPC_DATA_HISTORY_BACKEND") == "questdb": + files.extend(["--file", str(HERE / "compose.history.questdb.yml")]) return files def compose(self, *args, timeout=120): @@ -841,7 +845,7 @@ class LocalRig: self.save(manifest) return manifest - def up(self, timeout=600, history=False): + def up(self, timeout=600, history=False, history_backend="sqlserver"): import secrets import credentials if self.folder.exists(): @@ -862,7 +866,10 @@ class LocalRig: import base64 settings["GRPC_DATA_SECRETS_KEK"] = base64.b64encode(secrets.token_bytes(32)).decode() if history: + if history_backend not in HISTORY_BACKENDS: + raise RigError("unknown history backend") settings["GRPC_DATA_HISTORY"] = "1" + settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) self.environment.update(settings) credentials.provision_tls(self.folder / "security", NODES[2:]) @@ -1331,6 +1338,8 @@ def main(argv=None): parser.add_argument("--run-id") parser.add_argument("--timeout", type=float, default=None) parser.add_argument("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)") + parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None, + help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB)") arguments = parser.parse_args(argv) try: if arguments.action == "preflight": @@ -1353,6 +1362,10 @@ def main(argv=None): if arguments.action != "up": raise RigError("--history applies to up only; the run remembers it") options["history"] = True + if arguments.history_backend is not None: + options["history_backend"] = arguments.history_backend + elif arguments.history_backend is not None: + raise RigError("--history-backend needs up --history") result = action(**options) print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")})) return 0 diff --git a/scripts/validation/grpc-data/scenarios.json b/scripts/validation/grpc-data/scenarios.json index aeed6fac9..108a5b6a3 100644 --- a/scripts/validation/grpc-data/scenarios.json +++ b/scripts/validation/grpc-data/scenarios.json @@ -1531,5 +1531,83 @@ "caller_cluster": "CONSUMER", "target_cluster": "SOURCE" } + ], + "history_scenarios": [ + { + "id": "H01", + "title": "Raw paging at page boundaries, Raw and UNS mappings", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "Client CLI --page-size on projected counter", + "pages >= 2, last page no continuation", + "rows equal the origin row-for-row", + "single read equals the origin", + "tie clusters: not storable on SqlServer (PK) or QuestDB (DEDUP UPSERT KEYS(ts, tag)); proven by the H1 fuzz" + ] + }, + { + "id": "H02", + "title": "Processed with an aggregate the origin backend refuses for the node type", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "Average on a String node => BadAggregateNotSupported (origin, #897)", + "the same refusal on the origin", + "Average on counter equals the origin" + ] + }, + { + "id": "H03", + "title": "AtTime, integer node", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "--at-time on projected counter", + "values / timestamps / statuses equal the origin", + "UInt16 value type end to end" + ] + }, + { + "id": "H04", + "title": "Continuation across origin failover => BadContinuationPointInvalid, fresh read succeeds", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 900, + "coverage": [ + "page 1 held in one consumer session", + "SOURCE primary stopped", + "resumed page BadContinuationPointInvalid", + "fresh read on the new primary Good" + ] + }, + { + "id": "H05", + "title": "Origin that does not advertise history => unsupported (substitute for a pinned v1 image)", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "export drops HistoryRead (bit 32)", + "projected node => BadHistoryOperationUnsupported", + "the other export still served" + ] + }, + { + "id": "H06", + "title": "Denied vs unhistorized indistinguishable; session close releases origin continuations; origin rebuild mid-page", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 900, + "coverage": [ + "unhistorized and origin-ACL-denied: identical BadHistoryOperationUnsupported", + "no local mapping-scope HistoryRead => BadUserAccessDenied (the other mapping still served)", + "origin open continuations >= 1 while held, 0 after the consumer session close", + "resume after an origin rebuild BadContinuationPointInvalid, fresh Good" + ] + } ] } diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index 5de18ec6a..ca340455c 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -172,7 +172,7 @@ try var root = mutation.RootElement; string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations", "mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode", - "control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode"]; + "control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions"]; if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal))) throw new InvalidOperationException("unknown fixture mutation field"); await using var db = await factory.CreateDbContextAsync(); @@ -283,7 +283,13 @@ try await db.UnsTagReferences.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync(); await db.Tags.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync(); } - if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean()) + if (root.TryGetProperty("acl_permissions", out var aclPermissions)) + { + // H3: {"node_acl_id": "...", "permission_flags": } — one existing row's flags (baseline restore reverts it). + var acl = await db.NodeAcls.SingleAsync(x => x.NodeAclId == aclPermissions.GetProperty("node_acl_id").GetString()); + acl.PermissionFlags = (NodePermissions)aclPermissions.GetProperty("permission_flags").GetInt32(); + } + if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean()) { foreach (var row in await db.DataConnections.ToListAsync()) { row.Enabled = false; row.Revision++; } foreach (var row in await db.RemoteNamespaceMappings.ToListAsync()) { row.Enabled = false; row.Revision++; } @@ -328,8 +334,11 @@ try foreach (var node in nodes.Where(x => x.StartsWith(cluster.ToLowerInvariant() + "-", StringComparison.Ordinal))) db.ClusterNodes.Add(new() { NodeId = node + ":4053", ClusterId = cluster, Host = node, OpcUaPort = 4840, DashboardPort = 9000, GrpcPort = 4056, ApplicationUri = "urn:OtOpcUa:grpc-data:" + node, CreatedBy = "grpc-data-local-gate" }); + // H3 (history profile): on CONSUMER the CLI principal's HistoryRead comes ONLY from the mapping-scoped grants below, + // so a scenario can take it away per mapping (plan §6: mapped history needs HistoryRead on the mapping scope). db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-" + cluster, ClusterId = cluster, - Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); + Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster, + PermissionFlags = history && cluster == "CONSUMER" ? NodePermissions.Admin & ~NodePermissions.HistoryRead : NodePermissions.Admin }); } db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-modbus", ClusterId = "SOURCE", Name = "modbus", DriverType = "Modbus", DriverConfig = """{"TimeoutMs":2000,"AutoReconnect":true,"Probe":{"Enabled":true,"ProbeAddress":0}}""" }); @@ -347,7 +356,9 @@ try TagConfig = """{"region":"HoldingRegisters","address":24,"dataType":"UInt16","isArray":true,"arrayLength":3,"writable":true}""" }); db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-text", DeviceId = "source-device", Name = "text", DataType = "String", AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", - TagConfig = """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" }); + TagConfig = history + ? """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true,"isHistorized":true}""" + : """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" }); db.UnsAreas.Add(new() { UnsAreaRowId = Guid.NewGuid(), UnsAreaId = "source-area", ClusterId = "SOURCE", Name = "area" }); db.UnsLines.Add(new() { UnsLineRowId = Guid.NewGuid(), UnsLineId = "source-line", UnsAreaId = "source-area", Name = "line" }); var uuid = Guid.NewGuid(); @@ -376,7 +387,10 @@ try ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source", RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, - RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = operations, WriteThrough = true }); + RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = grantedOperations, WriteThrough = true }); + if (history) + db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli", + ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead }); } if (history) // The second principal's origin ACL also lacks HistoryRead: with its export's HistoryRead off the RPC is refused @@ -403,7 +417,8 @@ try browse_roots = new { raw = "modbus/plc", uns = unsBrowseRoot }, browse_subjects = new { raw = "modbus/plc", uns = "area/line/plc" }, origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" }, - history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" } } : null }); + history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" }, + historized_string = new { raw = "modbus/plc/text", uns = "area/line/plc/text" } } : null }); return 0; } catch (Exception error) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs index 65c5e8358..b4c47d698 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs @@ -44,7 +44,7 @@ public sealed partial class LocalDataServices internal int HistorySessionCount => _historySessions.Count; /// Open origin continuations (page cursors + chunk remainders) across every session (diagnostics/tests). - internal int HistoryOpenContinuations => _historySessions.OpenContinuations; + public int HistoryOpenContinuations => _historySessions.OpenContinuations; /// Remainder bytes retained for a principal across its sessions (diagnostics/tests). internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal);