test(grpc-data): Gateway origin backend for the history rig — read-only AVEVA bindings, reverse/end-only H07, strict-ceiling H08 (#923)

This commit is contained in:
Joseph Doherty
2026-11-28 09:23:45 -05:00
parent 05f431f5d8
commit a6ae08146d
6 changed files with 316 additions and 15 deletions
+160 -7
View File
@@ -1,4 +1,9 @@
"""H3 live gate: scenarios H01–H06 (plan §9 "Scenarios") on a `rig.py up --history [--history-backend questdb]` run.
"""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
@@ -24,6 +29,10 @@ NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpda
NODE_PERMISSIONS_HISTORY_READ = 1 << 3
NODE_PERMISSIONS_BROWSE = 1 << 0
EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe
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):
@@ -31,7 +40,7 @@ def _iso(moment):
class HistoryGate:
def __init__(self, run_id, *, pinned_build=False):
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
@@ -42,6 +51,8 @@ class HistoryGate:
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
@@ -70,6 +81,30 @@ class HistoryGate:
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")
@@ -199,6 +234,7 @@ class HistoryGate:
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")
@@ -207,8 +243,12 @@ class HistoryGate:
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")
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):
@@ -228,6 +268,7 @@ class HistoryGate:
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):
@@ -254,6 +295,7 @@ class HistoryGate:
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):
@@ -397,14 +439,121 @@ class HistoryGate:
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")
forward = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], "origin-forward")
forward_rows = history_smoke._cli_rows(forward.stdout)
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 forward rows, 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):
chosen = [row["id"] for row in self.catalog] if selection == "all" else [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
self.accumulate()
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:
@@ -436,8 +585,12 @@ def main(argv=None):
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)
gate = HistoryGate(arguments.run_id, pinned_build=arguments.pinned_build)
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