"""H3 live gate: scenarios H01–H06 (plan §9 "Scenarios") on a `rig.py up --history [--history-backend questdb|gateway]` run. On the gateway backend (#923) the origin reads the REAL AVEVA Historian through a host-run read-only HistorianGateway, so the window is a fixed stretch of the recent past of the bound historian tags (nothing is accumulated), H07 adds the reverse and end-only raw reads, and H08 (run on its own, after restarting the gateway with a strict row ceiling) re-reads the H01/H03/H07 baseline through ceiling-bounded pages. 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 GATEWAY_WINDOW_SECONDS = 120 # SysTimeSec stores one value per second ⇒ ~120 counter rows, ~12 flt rows (10 s) GATEWAY_WINDOW_LAG_SECONDS = 15 # stay clear of the historian's real-time storage lag GATEWAY_BASELINE = "H-gateway-baseline.json" MIN_TIME = "0001-01-01T00:00:00Z" # DateTime.MinValue ⇒ an unspecified StartTime on the wire (an end-only read) 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, gateway_ceiling=None): 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 = {} self.gateway_ceiling = gateway_ceiling self.baseline = {} # ----------------------------------------------------------------------------------------------------------- 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 gateway_window(self): """Gateway backend: a fixed stretch of the recent past — the historian already holds it, nothing is written.""" now = datetime.now(timezone.utc).replace(microsecond=0) end = now - timedelta(seconds=GATEWAY_WINDOW_LAG_SECONDS) self.window = (end - timedelta(seconds=GATEWAY_WINDOW_SECONDS), end) def keep(self, name, value): """Gateway backend: remember an answer of the unconstrained leg, for H08's ceiling-bounded re-read.""" if self.backend == "gateway": self.baseline[name] = value self.runner.save(GATEWAY_BASELINE, {"window": [_iso(w) for w in self.window], **self.baseline}) @staticmethod def rows_text(rows): return [[r[0].isoformat(), r[1], r[2]] for r in rows] @staticmethod def page_lines(stdout): return [line for line in stdout.splitlines() if line.startswith("Page ")] @staticmethod def page_sizes(lines): return [int(re.search(r" values=(\d+) ", line)[1]) for line in lines] 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"): # No re-browse before the UNS leg: it may sit idle past its 15 s metadata lease during the raw leg, and since #922 # a lapsed projected node renews on demand within the HistoryRead. 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} self.keep(f"forward_{realm}", self.rows_text(origin_rows)) # 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]} self.keep("forward_flt", self.rows_text(origin_rows)) report["tie_cluster"] = ("not representable on the " + self.backend + " backend: " + ( "the bound AVEVA system tags store one value per timestamp and the leg is read-only (no tie can be written)" if self.backend == "gateway" else "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") self.keep("average", self.rows_text(rows)) 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") self.keep("attime", {"times": times, "rows": self.rows_text(rows), "types": types}) 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 def end_only_reference(self, source, origin, count): """The latest `count` stored rows at or before the window end, newest first, from a FORWARD origin read.""" end = self.window[1] reference = self.cli(source, ["-n", origin, "--start", _iso(end - timedelta(seconds=count * 4)), "--end", _iso(end + timedelta(seconds=1)), "--max", "1000"], "origin-end-only-reference") self.runner.check(reference.returncode == 0, "origin forward reference read for the end-only case") rows = [r for r in history_smoke._cli_rows(reference.stdout) if r[0] <= end] return list(reversed(rows))[:count] def scenario_H07(self): """Gateway backend: reverse (start > end) and end-only raw reads through the projection — the server walks them back from forward gateway reads (#686) — equal to the origin and to the forward rows reversed.""" consumer = self.runner.primary("consumer") report = {} source, origin = self.origin_node("raw", "counter") # Part 11: a reverse read's StartTime (the later bound) is inclusive and its EndTime exclusive, so its rows are the stored # rows in (W0, W1] — a forward read one second past W1, filtered, is the independent reference. forward = self.cli(source, ["-n", origin, "--start", _iso(self.window[0]), "--end", _iso(self.window[1] + timedelta(seconds=1)), "--max", "1000"], "origin-forward") forward_rows = [r for r in history_smoke._cli_rows(forward.stdout) if self.window[0] < r[0] <= self.window[1]] self.runner.check(forward.returncode == 0 and len(forward_rows) >= 20, "origin forward window holds history") reverse = ["--start", _iso(self.window[1]), "--end", _iso(self.window[0])] for label, extra in (("paged", ["--page-size", "7"]), ("whole", [])): origin_rev = self.cli(source, ["-n", origin, *reverse, *extra, "--max", "1000"], f"origin-reverse-{label}") projected_rev = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *reverse, *extra, "--max", "1000"], f"reverse-{label}") rows, origin_rows = history_smoke._cli_rows(projected_rev.stdout), history_smoke._cli_rows(origin_rev.stdout) self.runner.check(origin_rev.returncode == 0 and projected_rev.returncode == 0, f"reverse {label} read served on both") self.runner.check(rows == origin_rows, f"reverse {label}: projected rows equal the origin row-for-row") self.runner.check(rows == list(reversed(forward_rows)), f"reverse {label}: the stored rows of (W0, W1], newest first") entry = {"rows": len(rows), "first": str(rows[0]) if rows else None, "last": str(rows[-1]) if rows else None} if extra: pages = self.page_lines(projected_rev.stdout) self.runner.check(len(pages) >= 2 and all("Good" in line for line in pages), "reverse paged: several Good pages") self.runner.check(pages[-1].split("continuation=")[1].startswith("no"), "reverse paged: the last page has no continuation") entry["page_lines"] = pages self.keep("reverse", self.rows_text(rows)) report["reverse_" + label] = entry end_only = ["--start", MIN_TIME, "--end", _iso(self.window[1]), "--page-size", "5", "--max", "20"] origin_eo = self.cli(source, ["-n", origin, *end_only], "origin-end-only") projected_eo = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *end_only], "end-only") rows, origin_rows = history_smoke._cli_rows(projected_eo.stdout), history_smoke._cli_rows(origin_eo.stdout) expected = self.end_only_reference(source, origin, 20) pages = self.page_lines(projected_eo.stdout) self.runner.check(origin_eo.returncode == 0 and projected_eo.returncode == 0, "end-only read served on both") self.runner.check(len(pages) == 4 and all("Good" in line for line in pages), "end-only: four Good pages of five") self.runner.check(rows == origin_rows, "end-only: projected rows equal the origin row-for-row") self.runner.check(len(rows) == 20 and rows == expected, "end-only: the latest 20 rows at or before EndTime, newest first") self.keep("end_only", self.rows_text(rows)) report["end_only"] = {"rows": len(rows), "first": str(rows[0]) if rows else None, "last": str(rows[-1]) if rows else None, "page_lines": pages} return report def scenario_H08(self): """Gateway backend, strict ceiling (run alone, after restarting the gateway with `MaxValuesCeiling = C` and `AllowStreamingBeyondCeiling = false`): the H01/H03/H07 answers re-read through ceiling-bounded pages (#694).""" self.runner.check(self.backend == "gateway" and self.gateway_ceiling is not None, "H08 needs the gateway backend and --gateway-ceiling") consumer = self.runner.primary("consumer") limit = self.gateway_ceiling - 16 # RawPageLimit: L = learned ceiling − 16 report = {"ceiling": self.gateway_ceiling, "page_limit": limit} rows_of = lambda result: self.rows_text(history_smoke._cli_rows(result.stdout)) source, origin = self.origin_node("raw", "counter") forward = self.baseline["forward_raw"] self.runner.check(len(forward) > self.gateway_ceiling, "the baseline window holds more rows than the ceiling") # (a) one read capped above the ceiling, on the origin and through the projection: every row, in order. for label, node, host in (("origin", origin, source), ("projected", self.projected[("raw", "counter")], consumer)): whole = self.cli(host, ["-n", node, *self.window_args(), "--max", "1000"], f"ceiling-whole-{label}") self.runner.check(whole.returncode == 0 and rows_of(whole) == forward, f"{label}: a read above the ceiling returns the baseline rows") # (b) pages asked for 100 rows come back ceiling-sized (<= L - 1) with continuations, and still equal the baseline. paged = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "100", "--max", "1000"], "ceiling-paged") pages = self.page_lines(paged.stdout) sizes = self.page_sizes(pages) self.runner.check(paged.returncode == 0 and all("Good" in line for line in pages), "ceiling paged: every page Good") self.runner.check(len(pages) >= 2 and max(sizes) <= limit - 1, "ceiling paged: pages are ceiling-sized, not 100") self.runner.check(rows_of(paged) == forward, "ceiling paged: rows equal the unconstrained baseline") report["paged"] = pages # (c) reverse and end-only, walked back under the ceiling. reverse = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--start", _iso(self.window[1]), "--end", _iso(self.window[0]), "--page-size", "100", "--max", "1000"], "ceiling-reverse") reverse_pages = self.page_lines(reverse.stdout) self.runner.check(reverse.returncode == 0 and rows_of(reverse) == self.baseline["reverse"], "ceiling reverse equals the baseline") self.runner.check(max(self.page_sizes(reverse_pages)) <= limit - 1, "ceiling reverse: pages are ceiling-sized") end_only = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--start", MIN_TIME, "--end", _iso(self.window[1]), "--page-size", "5", "--max", "20"], "ceiling-end-only") self.runner.check(end_only.returncode == 0 and rows_of(end_only) == self.baseline["end_only"], "ceiling end-only equals the baseline") report["reverse"] = reverse_pages # (d) AtTime under the ceiling: the baseline values. attime = self.baseline["attime"] at = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--at-time", attime["times"]], "ceiling-attime") self.runner.check(at.returncode == 0 and rows_of(at) == attime["rows"], "ceiling AtTime equals the baseline") # (e) a raw-evaluated aggregate whose window exceeds the ceiling: the projection answers exactly what the origin answers. aggregate = [*self.window_args(), "--aggregate", "Average", "--interval", "10000"] origin_avg = self.cli(source, ["-n", origin, *aggregate], "ceiling-origin-average") projected_avg = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *aggregate], "ceiling-average") observed = lambda result: ("Good", rows_of(result)) if result.returncode == 0 else (self.error_status(result), None) self.runner.check(observed(origin_avg) == observed(projected_avg), "ceiling Average: the projection answers what the origin answers") report["average"] = {"origin": observed(origin_avg)[0], "projected": observed(projected_avg)[0], "equals_baseline": observed(projected_avg)[1] == self.baseline.get("average")} return report # ------------------------------------------------------------------------------------------------------------- run def run(self, selection): applies = lambda row: self.backend in row.get("backends", [self.backend]) chosen = ([row["id"] for row in self.catalog if applies(row) and not row.get("run_alone")] if selection == "all" else [selection]) self.runner.publish() self.runner.rig.seed_helper("snapshot") self.runner.active, self.runner.deadline = "H00", time.monotonic() + 900 if self.backend != "gateway": self.accumulate() elif chosen == ["H08"]: # The ceiling leg re-reads the unconstrained leg's window and compares with its answers. recorded = json.loads((self.runner.folder / GATEWAY_BASELINE).read_text()) self.window = tuple(datetime.fromisoformat(w.replace("Z", "+00:00")) for w in recorded.pop("window")) self.baseline = recorded else: self.gateway_window() 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") parser.add_argument("--gateway-ceiling", type=int, default=None, help="H08 only: the strict MaxValuesCeiling the host-run gateway was restarted with (> 16)") arguments = parser.parse_args(argv) if arguments.gateway_ceiling is not None and arguments.gateway_ceiling <= 16: parser.error("--gateway-ceiling must exceed the 16-row allowance") gate = HistoryGate(arguments.run_id, pinned_build=arguments.pinned_build, gateway_ceiling=arguments.gateway_ceiling) rows = gate.run(arguments.scenario) return 0 if all(row["passed"] for row in rows) else 1 if __name__ == "__main__": sys.exit(main())