Files
lmxopcua/scripts/validation/grpc-data/history_v1_origin_gate.py
T

269 lines
17 KiB
Python

"""lmxopcua#921 live gate: H05 (plan §4.3 mixed versions, row "new consumer → v1 origin") against a PINNED pre-H2 origin.
python3 scripts/validation/grpc-data/rig.py up --run-id <id> --history --source-revision 0c86edc1 --timeout 1500
python3 scripts/validation/grpc-data/rig.py seed --run-id <id>
sleep 75 # CONTROL's ClusterNode contact refresh before the first deploy
python3 scripts/validation/grpc-data/rig.py deploy --run-id <id> --timeout 300
python3 scripts/validation/grpc-data/history_v1_origin_gate.py --run-id <id>
python3 scripts/validation/grpc-data/rig.py down --run-id <id>
The SOURCE pair runs a Host built from the pinned commit (post-X0, pre-H2: no HistoryRead RPC, no `history` feature);
CONTROL and CONSUMER run this checkout. SOURCE still has a historian (the `--history` overlay) and historizes `counter`, so
the origin's OWN HistoryRead is the positive control for "the origin has history, the wire does not carry it".
What is asserted (results: the run's restricted `evidence/H05V1-results.json`):
1. the running build stamps — SOURCE = the pinned revision, CONTROL/CONSUMER = this checkout;
2. projected Raw and UNS `counter` variables: `Historizing` False and no HistoryRead bit in `AccessLevel`, while the
origin's own `counter` is `Historizing` True (control); a projected value Read is Good (control: the projection is live);
3. a CLI `historyread` on each projected variable ⇒ `BadHistoryOperationUnsupported`; on the origin's own node ⇒ Good rows;
4. diagnostics say the origin lacks the feature: the CONSUMER data-connections page shows "Negotiated features none (v1
behaviour)" and "origin history not advertised"; the SOURCE page names the HistoryRead bit the older build dropped;
5. no new-shape call reaches the v1 origin from the consumer: in the pinned origins' wire tap (node-probe/WireTap.cs) for
the consumer's window, no HistoryRead / CallConditionMethod arrival, and no data call (anything but the capability
probe) carries `x-otopcua-data-features` — with the consumer's v1 calls (GetCapabilities/Browse/GetMetadata/Read/
Subscribe) present in the same window (control). The capability probe itself always carries the client's features
(plan §4.1); a v1 origin ignores the header, which (6) shows byte-for-byte;
6. tap positive control: the probe's `history-v1-origin` scenario sends new-shape calls to both pinned origins — capabilities
with the feature header answer byte-identically to capabilities without it, a HistoryRead with the header is refused
PERMISSION_DENIED (a pre-H2 data listener admits only its six v1 methods and refuses any other path before routing — not
the UNIMPLEMENTED the plan's table guessed) — and the tap records those arrivals with the header and that status.
"""
import argparse
import html
import json
import re
import sys
import time
import urllib.request
import uuid
from pathlib import Path
import history_gate
import rig
import scenarios
ACCESS_LEVEL_HISTORY_READ = 0x04
V1_PATHS = ("GetCapabilities", "Browse", "GetMetadata", "Read", "Subscribe", "Write")
NEW_SHAPE_PATHS = ("HistoryRead", "CallConditionMethod")
class V1OriginGate(history_gate.HistoryGate):
def __init__(self, run_id, *, pinned_build=False):
super().__init__(run_id, pinned_build=pinned_build)
self.pinned = self.runner.manifest.get("source_pinned")
if not self.pinned:
raise SystemExit("run was not brought up with --source-revision (no pinned SOURCE)")
self.checks = {}
self.detail = {}
def check(self, name, condition):
self.checks[name] = bool(condition)
return bool(condition)
# ------------------------------------------------------------------------------------------------------------ tools
def tap(self, node):
path = self.runner.rig.folder / "probe" / node / "wire-tap.jsonl"
if not path.is_file() or path.is_symlink():
return []
rows = []
for line in path.read_text(errors="replace").splitlines():
try:
rows.append(json.loads(line))
except ValueError:
continue
return rows
def taps(self):
return {node: self.tap(node) for node in ("source-1", "source-2")}
@staticmethod
def method(row):
return (row.get("path") or "").rsplit("/", 1)[-1]
def stamp(self, node):
return json.loads(self.runner.rig.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15))
def container_addresses(self, node):
ids = self.runner.rig.compose("ps", "--quiet", node).split()
if len(ids) != 1:
return []
row = json.loads(rig.run_command([*self.runner.rig.docker, "container", "inspect", ids[0]]))[0]
return [network.get("IPAddress") for network in row["NetworkSettings"]["Networks"].values() if network.get("IPAddress")]
def attribute(self, node, node_id, attribute, name):
argv = ["dotnet", str(self.runner.cli_dll), "read", "-u", self.runner.endpoint(node), "-U", "apikey", "-P", self.runner.key,
"-n", node_id, "-a", attribute]
result = self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=60)
value = re.search(r"^Value:\s*(.*)$", result.stdout, re.M)
status = re.search(r"^Status:\s*(\S+)", result.stdout, re.M)
return {"exit": result.returncode, "value": value[1].strip() if value else None, "status": status[1] if status else None}
def value_read(self, node, node_id, name):
argv = ["dotnet", str(self.runner.cli_dll), "read", "-u", self.runner.endpoint(node), "-U", "apikey", "-P", self.runner.key,
"-n", node_id, "--max-age", "5000"]
# As every mapped positive read on this rig: retry only an explicit BadWaitingForInitialData (README), bounded.
end = time.monotonic() + 60
while True:
result = self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=60)
status = re.search(r"^Status:\s*(\S+)", result.stdout, re.M)
observed = status[1] if status else None
if observed != "BadWaitingForInitialData" or time.monotonic() >= end:
return observed
time.sleep(2)
def history(self, node, node_id, name):
result = self.cli(node, ["-n", node_id, *self.window_args(), "--max", "50"], name)
returned = re.search(r"^(\d+) values returned\.", result.stdout, re.M)
rows = int(returned[1]) if returned else 0
return {"exit": result.returncode, "status": "Good" if result.returncode == 0 else self.error_status(result), "rows": rows,
"tail": (result.stdout + result.stderr)[-400:]}
def page(self, cluster):
"""The AdminUI data-connections page of `cluster`, served by the CONTROL primary (login disabled on the rig)."""
control = self.runner.primary("control")
url = self.runner.endpoint(control, "admin") + f"/clusters/{cluster}/data-connections"
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(urllib.request.Request(url), timeout=15) as response:
text = response.read(8 * 1024 * 1024).decode("utf-8", errors="replace")
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", text)))
# ------------------------------------------------------------------------------------------------------------- run
def run(self):
self.runner.publish()
self.runner.active, self.runner.deadline = "H05V1", time.monotonic() + 1500
started = time.monotonic()
error = None
try:
self.scenario()
except Exception as failure: # recorded with every check made so far
error = type(failure).__name__ + ": " + str(failure)[:400]
passed = error is None and bool(self.checks) and all(self.checks.values())
result = {"id": "H05V1", "pinned": self.pinned, "consumer_revision": self.runner.manifest.get("source_revision"),
"passed": passed, "error": error, "failed_checks": [k for k, v in self.checks.items() if not v],
"checks": self.checks, "detail": self.detail, "duration_seconds": round(time.monotonic() - started, 1),
"window": [history_gate._iso(w) for w in self.window] if self.window else None}
self.runner.save("H05V1-results.json", result)
print(json.dumps({k: result[k] for k in ("id", "passed", "error", "failed_checks", "duration_seconds")}), flush=True)
return result
def scenario(self):
# 1. Which build is actually running where.
stamps = {node: self.stamp(node) for node in self.runner.manifest["nodes"]}
self.detail["stamps"] = stamps
self.check("source_nodes_run_the_pinned_pre_h2_build",
all(stamps[n].get("revision") == self.pinned["revision"] and stamps[n].get("tree_hash") == self.pinned["tree_hash"]
for n in ("source-1", "source-2")))
self.check("control_and_consumer_run_this_checkout",
all(stamps[n].get("revision") == self.runner.manifest["source_revision"] for n in stamps if not n.startswith("source-")))
self.accumulate()
tap_start = {node: len(rows) for node, rows in self.taps().items()}
consumer = self.resolve_projected()
source, origin_counter = self.origin_node("raw", "counter")
# 2. Historizing / AccessLevel: projected false, origin true (control); projected value Read Good (control).
attributes = {}
for realm in ("raw", "uns"):
node_id = self.projected[(realm, "counter")]
attributes[realm] = {"historizing": self.attribute(consumer, node_id, "Historizing", f"{realm}-historizing"),
"access_level": self.attribute(consumer, node_id, "AccessLevel", f"{realm}-access"),
"value_status": self.value_read(consumer, node_id, f"{realm}-value")}
attributes["origin"] = {"node": origin_counter,
"historizing": self.attribute(source, origin_counter, "Historizing", "origin-historizing"),
"access_level": self.attribute(source, origin_counter, "AccessLevel", "origin-access")}
self.detail["attributes"] = attributes
def access(entry):
try:
return int(entry["value"])
except (TypeError, ValueError):
return None
for realm in ("raw", "uns"):
row = attributes[realm]
self.check(f"projected_{realm}_counter_historizing_false", row["historizing"]["value"] == "False" and row["historizing"]["status"] == "Good")
level = access(row["access_level"])
self.check(f"projected_{realm}_counter_access_level_has_no_history_read", level is not None and level & ACCESS_LEVEL_HISTORY_READ == 0)
self.check(f"projected_{realm}_counter_value_read_good", row["value_status"] == "Good")
self.check("origin_counter_historizing_true_control", attributes["origin"]["historizing"]["value"] == "True")
origin_level = access(attributes["origin"]["access_level"])
self.check("origin_counter_access_level_has_history_read_control",
origin_level is not None and origin_level & ACCESS_LEVEL_HISTORY_READ != 0)
# 3. HistoryRead: projected ⇒ unsupported, origin's own node ⇒ Good rows (control).
reads = {realm: self.history(consumer, self.projected[(realm, "counter")], f"{realm}-historyread") for realm in ("raw", "uns")}
reads["origin"] = self.history(source, origin_counter, "origin-historyread")
self.detail["history_reads"] = reads
for realm in ("raw", "uns"):
self.check(f"projected_{realm}_historyread_bad_history_operation_unsupported",
reads[realm]["status"] == "BadHistoryOperationUnsupported")
self.check("origin_own_historyread_good_with_rows_control", reads["origin"]["status"] == "Good" and reads["origin"]["rows"] > 0)
# 4. Diagnostics: the consumer negotiated nothing and the origin advertised no history; the origin names the drop.
consumer_page = self.page("CONSUMER")
source_page = self.page("SOURCE")
line = re.search(r"Negotiated features .{0,400}?open remote continuations", consumer_page)
dropped = re.search(r"Exports with dropped unknown operation bits: .{0,400}?upgraded\.", source_page)
self.detail["diagnostics"] = {"consumer_history_line": line[0] if line else None, "source_dropped_line": dropped[0] if dropped else None}
self.check("consumer_diagnostics_negotiated_features_none_v1",
line is not None and "Negotiated features none (v1 behaviour)" in line[0])
self.check("consumer_diagnostics_origin_history_not_advertised", line is not None and "origin history not advertised" in line[0])
self.check("source_diagnostics_older_build_dropped_history_read", dropped is not None and "HistoryRead" in dropped[0])
# 5. The consumer's window on the pinned origins' wire tap.
consumer_ips = {address for node in ("consumer-1", "consumer-2") for address in self.container_addresses(node)}
window = {node: rows[tap_start[node]:] for node, rows in self.taps().items()}
arrivals = [dict(row, origin=node) for node, rows in window.items() for row in rows if row.get("phase") == "arrival"]
from_consumer = [row for row in arrivals if row.get("remote") in consumer_ips]
methods = sorted({self.method(row) for row in from_consumer})
featured = [row for row in from_consumer if row.get("features")]
self.detail["tap_window"] = {"consumer_addresses": sorted(consumer_ips), "arrivals": len(arrivals), "from_consumer": len(from_consumer),
"methods": methods, "featured_methods": sorted({self.method(row) for row in featured}),
"featured_values": sorted({row["features"] for row in featured}),
"other_remotes": sorted({row.get("remote") for row in arrivals if row.get("remote") not in consumer_ips})}
self.check("tap_saw_consumer_v1_calls_control", len({"Read", "Browse", "GetMetadata"} & set(methods)) >= 2)
self.check("tap_no_history_read_or_condition_method_from_consumer", not set(NEW_SHAPE_PATHS) & set(methods))
self.check("tap_no_data_call_from_consumer_carries_the_feature_header",
all(self.method(row) == "GetCapabilities" for row in featured))
self.check("tap_all_consumer_calls_are_v1_methods", set(methods) <= set(V1_PATHS))
# 6. Positive control for the tap (and the Unimplemented wire path): new-shape calls the probe sends on purpose.
before = {node: len(rows) for node, rows in self.taps().items()}
output = self.runner.folder / ("H05V1-probe-" + uuid.uuid4().hex[:6] + ".json")
argv = ["dotnet", str(self.runner.probe_dll), "--manifest", str(self.runner.manifest_path), "--scenario", "history-v1-origin",
"--output", str(output)]
self.runner.process(argv, "H05V1-probe", timeout=120)
report = scenarios.restricted_json(output) if output.exists() else {"passed": False}
self.detail["probe"] = report
self.check("probe_v1_origin_capabilities_identical_and_history_read_refused", report.get("passed") is True)
time.sleep(1)
after = {node: rows[before[node]:] for node, rows in self.taps().items()}
control = {}
for node, rows in after.items():
history_arrivals = [row for row in rows if row.get("phase") == "arrival" and self.method(row) == "HistoryRead"]
completions = [row for row in rows if row.get("phase") == "completion" and self.method(row) == "HistoryRead"]
control[node] = {"history_read_arrivals": len(history_arrivals),
"history_read_features": sorted({row.get("features") or "" for row in history_arrivals}),
"history_read_grpc_status": sorted({row.get("grpcStatus") or "" for row in completions}),
"featured_capabilities": sum(1 for row in rows if row.get("phase") == "arrival"
and self.method(row) == "GetCapabilities" and row.get("features"))}
self.check(f"tap_recorded_probe_history_read_with_header_{node}",
history_arrivals and all(row.get("features") == "history" for row in history_arrivals))
self.check(f"tap_recorded_permission_denied_status_{node}", completions and all(row.get("grpcStatus") == "7" for row in completions))
self.detail["tap_control"] = control
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--run-id", required=True)
parser.add_argument("--pinned-build", action="store_true", help="keep the recorded checkout hash (harness edits during a run)")
arguments = parser.parse_args(argv)
result = V1OriginGate(arguments.run_id, pinned_build=arguments.pinned_build).run()
return 0 if result["passed"] else 1
if __name__ == "__main__":
sys.exit(main())