From a0901ddf398daecdfdd5bfb5787b890e28eacb09 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 28 Nov 2026 09:28:59 -0500 Subject: [PATCH] test(grpc-data): pinned pre-H2 SOURCE option (rig.py up --source-revision), wire tap, H05 v1-origin gate (#921); A09 driver-failure ack revert scenario (#927) --- .../grpc-data/compose.source-pinned.yml | 25 ++ .../grpc-data/conditions_scenarios.py | 92 +++++- .../grpc-data/history_v1_origin_gate.py | 261 ++++++++++++++++++ .../grpc-data/node-probe/WireTap.cs | 104 +++++++ scripts/validation/grpc-data/probe/Program.cs | 68 ++++- scripts/validation/grpc-data/rig.py | 126 +++++++-- .../validation/grpc-data/tests/test_rig.py | 82 ++++++ 7 files changed, 737 insertions(+), 21 deletions(-) create mode 100644 scripts/validation/grpc-data/compose.source-pinned.yml create mode 100644 scripts/validation/grpc-data/history_v1_origin_gate.py create mode 100644 scripts/validation/grpc-data/node-probe/WireTap.cs diff --git a/scripts/validation/grpc-data/compose.source-pinned.yml b/scripts/validation/grpc-data/compose.source-pinned.yml new file mode 100644 index 000000000..5cff40f53 --- /dev/null +++ b/scripts/validation/grpc-data/compose.source-pinned.yml @@ -0,0 +1,25 @@ +# lmxopcua#921 pinned-origin overlay (opt-in: `rig.py up --source-revision `). The SOURCE pair runs a Host image built +# from a pinned post-X0, pre-H2 commit (a "v1 origin": no HistoryRead RPC, no `history` feature), exported by the rig into the +# run folder; CONTROL and CONSUMER keep the current checkout's image. The only file the rig adds to the pinned tree is the +# self-contained node-probe wire tap (node-probe/WireTap.cs), enabled here with GRPC_DATA_WIRE_TAP: it records, per request +# on the data listener, the gRPC path and the x-otopcua-data-features header value into the node's restricted probe +# directory (wire-tap.jsonl) — never a credential or a body. Without this file the rig is unchanged. + +x-pinned-env: &pinned-env + GRPC_DATA_WIRE_TAP: "1" + +services: + source-1: + build: + context: ${GRPC_DATA_SOURCE_PINNED_CONTEXT:?pinned SOURCE export required} + dockerfile: scripts/validation/grpc-data/Dockerfile + target: runtime + labels: + otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID} + com.docker.compose.project: ${GRPC_DATA_PROJECT} + args: {SOURCE_REVISION: "${GRPC_DATA_SOURCE_PINNED_REVISION:?pinned revision required}", SOURCE_TREE_HASH: "${GRPC_DATA_SOURCE_PINNED_TREE_HASH:?pinned tree hash required}"} + image: ${GRPC_DATA_SOURCE_IMAGE:?run-scoped pinned SOURCE image required} + environment: *pinned-env + source-2: + image: ${GRPC_DATA_SOURCE_IMAGE:?run-scoped pinned SOURCE image required} + environment: *pinned-env diff --git a/scripts/validation/grpc-data/conditions_scenarios.py b/scripts/validation/grpc-data/conditions_scenarios.py index 752ced183..903aa4bd8 100644 --- a/scripts/validation/grpc-data/conditions_scenarios.py +++ b/scripts/validation/grpc-data/conditions_scenarios.py @@ -4,7 +4,7 @@ Part 1 implemented A01, A02, A04, A05 and A08; part 2 adds A03 (origin failover + EventId re-binding), A06 (consumer Primary change, both consumer nodes, two principals) and A07 (consumer node restart, ConditionRefresh vs the first -snapshot barrier). Everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared. +snapshot barrier). A09 (lmxopcua#927) is the driver-failure ack revert through DriverHostActor for a remote native ack. Everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared. Rules every scenario follows: - ids are RESOLVED, never constructed: projected folders by browsing the consumer's address space, imported ConditionIds @@ -30,8 +30,9 @@ from pathlib import Path import rig import scenarios -SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08") -TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720} +SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09") +TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "A09": 600} +REVERT_LOG = "did not reach the alarm system" REFRESH_REQUIRED = "RefreshRequiredEventType" _LOG_TIME = re.compile(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)") NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8) @@ -510,6 +511,88 @@ class ConditionScenarios: return {"code": code, "output": text[-300:], "good": code == 0 and ("successful" in text or "Comment added" in text), "event_id_unknown": "BadEventIdUnknown" in text} + # ---- lmxopcua#927 ------------------------------------------------------------------------------------------------- + def scenario_A09(self): + """A remote (A2b CallConditionMethod) ack of the NATIVE EastTankYellow, under the connection's service principal, that + the OpcUaClient driver genuinely fails: the run-owned opc-plc is `docker pause`d just before the ack, so the driver's + upstream Acknowledge call gets no reply and times out (no test seam). Asserts: the caller gets Good (plan §5.6 step 5: + native ⇒ Good, `AcceptedUnconfirmed`; the failure reaches it as the revert); the origin applies the ack then REVERTS it + (DriverHostActor `RevertNativeAlarmAck` ⇒ `EstablishesState: false`, logged "did not reach the alarm system … reverting"); + the consumer sees the reverted delta; the origin audit records the call on behalf of the end user. The upstream is frozen, + so no driver transition can explain the Unacknowledged that follows the ack (control: no upstream event while paused). + After unpausing, a second ack of the then-current EventId is not reverted (positive control for the failure).""" + source, consumer = self.r.primary("source"), self.r.primary("consumer") + name = self.fixture["conditions"]["native"]["condition"] + since = self.utc(-2) + origin = self.watch(source, "origin") + imported = self.watch(consumer, "consumer") + unacked = lambda b: b.get("State", "").endswith("Unacknowledged") + event = wait_for(lambda: self.latest(imported, name, unacked), 300) + origin_event = wait_for(lambda: self.latest(origin, name, unacked), 30) + if not self.check("consumer_has_unacknowledged_native_condition", event) or not self.check("origin_has_it_too", origin_event): + return + condition = event["ConditionNodeId"] + self.report["condition_id"] = condition + self.report["before"] = {"consumer": event, "origin": origin_event} + paused = False + try: + self.r.rig.compose("pause", "opcplc", timeout=60) + paused = True + self.report["paused_utc"] = self.utc() + origin_mark, consumer_mark = len(origin.blocks(name)), len(imported.blocks(name)) + result = self.ack(consumer, condition, event["EventId"], "ack-driver-fails") + self.report["ack"] = result + self.check("caller_gets_good_accepted_unconfirmed", result["good"]) + + def reverted(watcher, mark): + tail = states(watcher.blocks(name)[mark:]) + acked = next((i for i, state in enumerate(tail) if state and state.endswith(", Acknowledged")), None) + return tail if acked is not None and any(state and state.endswith("Unacknowledged") for state in tail[acked + 1:]) else None + + origin_tail = wait_for(lambda: reverted(origin, origin_mark), 60) + consumer_tail = wait_for(lambda: reverted(imported, consumer_mark), 30) + self.report["origin_after_ack"] = states(origin.blocks(name)[origin_mark:]) + self.report["consumer_after_ack"] = states(imported.blocks(name)[consumer_mark:]) + self.check("origin_applied_then_reverted", origin_tail) + self.check("consumer_saw_the_reverted_delta", consumer_tail) + latest = self.latest(imported, name) + self.check("consumer_reverted_event_is_a_new_event_id", latest and latest.get("EventId") != event["EventId"]) + self.check("consumer_reverted_condition_id_unchanged", latest and latest.get("ConditionNodeId") == condition) + reverts = self.log_lines(source, since, REVERT_LOG) + failures = self.log_lines(source, since, "native-alarm acknowledge of") + self.report["origin_revert_log"] = reverts[-5:] + self.report["origin_driver_failure_log"] = failures[-5:] + self.check("origin_logged_the_driver_failure_and_revert", + any("reverting the condition to unacknowledged" in line for line in reverts)) + self.check("driver_instance_logged_the_failed_upstream_ack", any("failed" in line or "refused" in line for line in failures)) + audit = self.audit(source, since) + self.report["origin_audit"] = audit[-10:] + self.check("origin_audited_the_remote_ack", + any(re.search(r"condition method \W?Acknowledge\b", line) and "AcceptedUnconfirmed" in line and "fixture-cli" in line + for line in audit)) + # Control: the upstream is frozen, so the Unacknowledged after the ack cannot be an upstream transition. Every + # origin event after the ack is either the ack itself or the revert (plus comms-loss quality, which has no state). + self.report["origin_tail_states"] = sorted(set(filter(None, self.report["origin_after_ack"]))) + finally: + if paused: + self.r.rig.compose("unpause", "opcplc", timeout=60) + self.report["unpaused_utc"] = self.utc() + # Positive control: once opc-plc answers again, an ack of the current EventId is not reverted. (The paused call may + # still be applied upstream when the container resumes; then the condition is already acknowledged, also recorded.) + time.sleep(30) + current = self.latest(imported, name) + self.report["after_unpause"] = current + if current and current.get("State", "").endswith("Unacknowledged"): + mark = len(self.log_lines(source, since, REVERT_LOG)) + result = self.ack(consumer, condition, current["EventId"], "ack-after-unpause") + self.report["control_ack"] = result + self.check("control_ack_good", result["good"]) + time.sleep(15) + self.check("control_ack_not_reverted", len(self.log_lines(source, since, REVERT_LOG)) == mark) + else: + self.report["control_note"] = "the upstream applied the paused acknowledge after unpause (condition already acknowledged)" + self.check("control_upstream_acknowledged_after_unpause", current and current.get("State", "").endswith(", Acknowledged")) + # ---- part 2 scenarios ------------------------------------------------------------------------------------------- def scenario_A03(self): """Origin failover mid-stream with standing active alarms. Phase 1: a consumer stream reset against the SAME origin @@ -800,6 +883,9 @@ class ConditionScenarios: finally: self.stop_watchers() try: + # A09 unpauses in its own finally; this covers a failure between its pause and that block. + if scenario == "A09" and "paused" in self.r.rig.compose("ps", "--all", "--format", "{{.State}}", "opcplc", timeout=30): + self.r.rig.compose("unpause", "opcplc", timeout=60) self.r.device("set", address=20, value=0) if scenario in ("A03", "A08"): self.r.deadline = time.monotonic() + 600 diff --git a/scripts/validation/grpc-data/history_v1_origin_gate.py b/scripts/validation/grpc-data/history_v1_origin_gate.py new file mode 100644 index 000000000..2934ca6b7 --- /dev/null +++ b/scripts/validation/grpc-data/history_v1_origin_gate.py @@ -0,0 +1,261 @@ +"""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 --history --source-revision 0c86edc1 --timeout 1500 + python3 scripts/validation/grpc-data/rig.py seed --run-id + sleep 75 # CONTROL's ClusterNode contact refresh before the first deploy + python3 scripts/validation/grpc-data/rig.py deploy --run-id --timeout 300 + python3 scripts/validation/grpc-data/history_v1_origin_gate.py --run-id + python3 scripts/validation/grpc-data/rig.py down --run-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 answers + UNIMPLEMENTED (the wire path the plan's row names) — and the tap records those arrivals with the header. +""" +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"] + 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) + return status[1] if status else None + + 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_unimplemented", 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_unimplemented_status_{node}", completions and all(row.get("grpcStatus") == "12" 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()) diff --git a/scripts/validation/grpc-data/node-probe/WireTap.cs b/scripts/validation/grpc-data/node-probe/WireTap.cs new file mode 100644 index 000000000..b7340c43d --- /dev/null +++ b/scripts/validation/grpc-data/node-probe/WireTap.cs @@ -0,0 +1,104 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.DependencyInjection; + +[assembly: HostingStartup(typeof(GrpcDataNodeProbe.WireTapStartup))] + +namespace GrpcDataNodeProbe; + +/// +/// Rig-only data-listener wire tap (lmxopcua#921). Off unless GRPC_DATA_WIRE_TAP=1; the rig sets it only on a +/// pinned-origin SOURCE (rig.py up --source-revision). It writes one JSON line when each request arrives on the +/// data listener (port 4057) and one when it completes: the UTC time, the gRPC path, the value of the +/// x-otopcua-data-features request header (null when absent), the remote address and, at completion, the +/// gRPC status. It records no credential, header other than the feature header, or message body. +/// +/// +/// Self-contained on purpose: it uses ASP.NET Core only, so the rig copies this one file into a pinned older tree's +/// node probe and the same tap runs on a Host built from that revision. The arrival line is written before the gRPC +/// pipeline runs, so a call the older Host refuses (an unimplemented method, an unauthenticated caller) is recorded +/// too. The file is bounded (); past it, a single truncation line is written. +/// +public sealed class WireTapStartup : IHostingStartup +{ + /// The tap's output file name inside the node's probe directory. + public const string FileName = "wire-tap.jsonl"; + + /// + public void Configure(IWebHostBuilder builder) + { + if (Environment.GetEnvironmentVariable("GRPC_DATA_WIRE_TAP") != "1") return; + var directory = Environment.GetEnvironmentVariable("GRPC_DATA_NODE_PROBE_DIR"); + if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory)) return; + var tap = new WireTapLog(Path.Combine(directory, FileName)); + builder.ConfigureServices(services => services.AddSingleton(new WireTapStartupFilter(tap))); + } +} + +/// The bounded append-only line log behind the tap. +public sealed class WireTapLog(string path) +{ + /// Lines written before the log stops (a soak would otherwise fill the probe directory). + public const int MaximumLines = 50_000; + + private readonly object _gate = new(); + private int _lines; + + /// Appends one record as a JSON line; never throws into the request pipeline. + public void Write(object record) + { + try + { + lock (_gate) + { + if (_lines > MaximumLines) return; + var line = _lines++ == MaximumLines ? JsonSerializer.Serialize(new { truncated = true }) : JsonSerializer.Serialize(record); + File.AppendAllText(path, line + "\n"); + } + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } +} + +/// Records each data-listener request at arrival (before authentication) and at completion. +public sealed class WireTapStartupFilter(WireTapLog log) : IStartupFilter +{ + private const int DataListenerPort = 4057; + private const string FeaturesHeader = "x-otopcua-data-features"; + private static long _sequence; + + /// + public Action Configure(Action next) => app => + { + app.Use(nextMiddleware => async context => + { + if (context.Connection.LocalPort != DataListenerPort) + { + await nextMiddleware(context); + return; + } + var sequence = Interlocked.Increment(ref _sequence); + var path = context.Request.Path.Value; + string? features = context.Request.Headers.TryGetValue(FeaturesHeader, out var value) ? value.ToString() : null; + var remote = context.Connection.RemoteIpAddress?.ToString(); + log.Write(new { phase = "arrival", sequence, utc = DateTime.UtcNow.ToString("O"), path, features, remote, protocol = context.Request.Protocol }); + try + { + await nextMiddleware(context); + } + finally + { + // A trailers-only answer (e.g. Unimplemented) carries grpc-status in the headers; a normal one in the trailers. + var trailers = context.Features.Get()?.Trailers; + string? status = trailers is not null && trailers.TryGetValue("grpc-status", out var t) ? t.ToString() + : context.Response.Headers.TryGetValue("grpc-status", out var h) ? h.ToString() : null; + log.Write(new { phase = "completion", sequence, utc = DateTime.UtcNow.ToString("O"), path, grpcStatus = status, httpStatus = context.Response.StatusCode }); + } + }); + next(app); + }; +} diff --git a/scripts/validation/grpc-data/probe/Program.cs b/scripts/validation/grpc-data/probe/Program.cs index dd51120dd..788457f9e 100644 --- a/scripts/validation/grpc-data/probe/Program.cs +++ b/scripts/validation/grpc-data/probe/Program.cs @@ -26,7 +26,7 @@ try using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath)); var root = manifest.RootElement; var scenario = arguments.GetValueOrDefault("--scenario", "all"); - if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario."); + if (scenario is not ("all" or "D13" or "wire" or "history" or "history-v1-origin" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario."); var nodes = root.GetProperty("nodes"); var endpoints = root.GetProperty("endpoints"); var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!; @@ -462,7 +462,71 @@ try ["expect"] = expect, ["expectedFound"] = expected, })); } - if (scenario is not ("D13" or "history" or "conditions" or "condition-records")) + if (scenario == "history-v1-origin") + { + // lmxopcua#921 (H05 against a pinned pre-H2 origin): what a NEW caller sees from a v1 origin when it asks for the + // features. Capabilities with the full feature header are byte-identical to those without it (no history, no + // conditions, no HistoryRead bit), and a HistoryRead with the header is answered UNIMPLEMENTED: the method does not + // exist on that build. This deliberately sends new-shape calls, so on a wire-tapped origin it is also the tap's + // positive control (the tap must record them). + failurePhase = ProbeFailurePhase.WireOperation; + var fixture = root.GetProperty("fixture"); + var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; + var historized = fixture.GetProperty("history").GetProperty("historized").GetProperty("raw").GetString()!; + foreach (var node in sourceNodes) + { + var name = node.Name; + failureTarget = name; + var nodeId = node.Value.GetProperty("node_id").GetString()!; + Metadata With(string? features) + { + var headers = Headers(key, "Node", nodeId); + if (features is not null) headers.Add("x-otopcua-data-features", features); + return headers; + } + using var handler = security.Handler(name); + using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }); + var client = new W.DataConnectionService.DataConnectionServiceClient(channel); + var deadline = () => DateTime.UtcNow.AddSeconds(20); + var plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(null), deadline()); + var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With("history,conditions"), deadline()); + static byte[] Shape(W.CapabilitiesResponse response) + { + // The serving identity aside, the two answers must be the same bytes. + var copy = response.Clone(); + copy.Serving = null; + return copy.ToByteArray(); + } + var v1Shape = plain.History is null && featured.History is null && plain.Conditions is null && featured.Conditions is null + && (plain.Operations & 32) == 0 && (featured.Operations & 32) == 0; + var identical = Shape(plain).AsSpan().SequenceEqual(Shape(featured)); + string historyRead; + try + { + var request = new W.HistoryReadRequest + { + Budget = new() { TimeoutTicks = TimeSpan.FromSeconds(10).Ticks, MaxItems = 1, MaxBytes = 1024 * 1024 }, + Raw = new() { NumValuesPerNode = 5, End = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow) }, + }; + request.Items.Add(new W.HistoryReadItem { CorrelationId = "one", View = new() { Address = new() { OriginClusterId = "SOURCE", + NamespaceUri = rawUri, IdentifierKind = "string", Identifier = historized }, Realm = (int)DataRealm.Raw, Subject = historized } }); + await client.HistoryReadAsync(request, With("history"), deadline()); + historyRead = "OK"; + } + catch (RpcException error) { historyRead = error.StatusCode.ToString(); } + results.Add(new("history-v1-origin-" + name, "history-v1-origin", v1Shape && identical && historyRead == "Unimplemented", 3, new() + { + ["withoutHeader"] = new { operations = plain.Operations, historyPresent = plain.History is not null, conditionsPresent = plain.Conditions is not null, + protocolMinor = plain.ProtocolMinor, bytes = plain.CalculateSize() }, + ["withHeader"] = new { operations = featured.Operations, historyPresent = featured.History is not null, conditionsPresent = featured.Conditions is not null, + protocolMinor = featured.ProtocolMinor, bytes = featured.CalculateSize() }, + ["byteIdentical"] = identical, + ["historyReadWithHeader"] = historyRead, + ["serving"] = featured.Serving.ToString(), + })); + } + } + if (scenario is not ("D13" or "history" or "history-v1-origin" or "conditions" or "condition-records")) { var fixture = root.GetProperty("fixture"); var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index 7d28ac4b2..54224c7bd 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -517,26 +517,91 @@ def run_command(argv, *, timeout=120, environment=None): return result.stdout +def _image_input(name): + """Whether repository-relative `name` is an image build input (the filter both tree hashes share).""" + suffix = Path(name).suffix + return not name.startswith(("docs/", "tests/", ".playwright-mcp/")) and ( + suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"} + or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"} + or name.startswith("src/") and suffix == ".json") + + +def _tree_hash(root, names): + import hashlib + digest = hashlib.sha256() + for name in sorted(set(filter(None, names))): + path = root / name + if not _image_input(name): + continue + if path.is_file() and not path.is_symlink(): + digest.update(name.encode() + b"\0") + digest.update(hashlib.sha256(path.read_bytes()).digest()) + return digest.hexdigest() + + def source_tree_hash(): """Hash image build inputs, including pending/new code, excluding review evidence. Harness Python and test sources have their own evidence and do not enter the Host/seeder/probe binaries. Notes can change without invalidating an image. """ - import hashlib paths = run_command(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0") - digest = hashlib.sha256() - for name in sorted(set(filter(None, paths))): - path = ROOT / name - if (name.startswith(("docs/", "tests/", ".playwright-mcp/")) or - not (path.suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"} - or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"} - or name.startswith("src/") and path.suffix == ".json")): - continue - if path.is_file() and not path.is_symlink(): - digest.update(name.encode() + b"\0") - digest.update(hashlib.sha256(path.read_bytes()).digest()) - return digest.hexdigest() + return _tree_hash(ROOT, paths) + + +# lmxopcua#921: a pinned pre-H2 SOURCE pair (plan §4.3 mixed versions, row "new consumer → v1 origin"). A pinned revision must +# CONTAIN X0 (a pre-X0 node rejects the whole data-connection snapshot once any newer bit is authored, so it is not the v1 origin +# the row describes) and must NOT contain H2 (whose merge adds the origin HistoryRead RPC and the `history` feature). +X0_MERGE = "a15912539f8a48804c31e74b2558994a50a338e6" +H2_MERGE = "ef938b435bbad2862bcd4b8e1f39e0b1ef2089b2" +PINNED_DATA_PROTO = "src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto" +# The only rig file added to a pinned tree: the self-contained data-listener wire tap (ASP.NET Core only, compiles at any revision). +PINNED_OVERLAY_FILES = ("scripts/validation/grpc-data/node-probe/WireTap.cs",) + + +def resolve_pinned_source_revision(revision, *, git=None): + """The full SHA of `revision` once it is proven a post-X0, pre-H2 commit; RigError otherwise.""" + git = git or (lambda *arguments: run_command(["git", *arguments])) + if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{7,40}", revision): + raise RigError("a pinned SOURCE revision must be a hexadecimal commit id") + full = git("rev-parse", "--verify", "--quiet", revision + "^{commit}").strip() + if not re.fullmatch(r"[0-9a-f]{40}", full): + raise RigError("the pinned SOURCE revision does not name a commit") + if git("merge-base", X0_MERGE, full).strip() != X0_MERGE: + raise RigError("the pinned SOURCE revision predates X0 (tolerant readers); it would reject the whole snapshot") + if git("merge-base", H2_MERGE, full).strip() == H2_MERGE: + raise RigError("the pinned SOURCE revision contains H2; it is not a v1 (pre-history) origin") + if re.search(r"^\s*rpc\s+HistoryRead\b", git("show", f"{full}:{PINNED_DATA_PROTO}"), re.M): + raise RigError("the pinned SOURCE revision's data contract already has HistoryRead") + return full + + +def export_pinned_source(revision, directory): + """Extract `revision`'s committed tree into a new restricted `directory` and add the rig's wire tap.""" + import shutil + import subprocess + if directory.exists(): + raise RigError("pinned SOURCE export directory already exists") + directory.mkdir(mode=0o700) + archive = subprocess.Popen(["git", "archive", "--format=tar", revision], cwd=ROOT, stdout=subprocess.PIPE) + try: + extract = subprocess.run(["tar", "-x", "-C", str(directory)], stdin=archive.stdout, timeout=600, check=False) + finally: + archive.stdout.close() + if archive.wait(timeout=600) != 0 or extract.returncode != 0: + raise RigError("could not export the pinned SOURCE revision") + for name in PINNED_OVERLAY_FILES: + target = directory / name + if target.exists(): + raise RigError("the pinned SOURCE tree already has a rig overlay file") + shutil.copyfile(ROOT / name, target) + return pinned_tree_hash(directory) + + +def pinned_tree_hash(directory): + """The image-input hash of an exported pinned tree (same filter as `source_tree_hash`).""" + names = [str(path.relative_to(directory)) for path in directory.rglob("*") if path.is_file() and not path.is_symlink()] + return _tree_hash(directory, [name.replace(os.sep, "/") for name in names]) def device_tree_hash(): @@ -678,6 +743,8 @@ class LocalRig: files.extend(["--file", str(HERE / "compose.history.questdb.yml")]) if self.environment.get("GRPC_DATA_CONDITIONS") == "1": files.extend(["--file", str(HERE / "compose.conditions.yml")]) + if self.environment.get("GRPC_DATA_SOURCE_PINNED") == "1": + files.extend(["--file", str(HERE / "compose.source-pinned.yml")]) return files def compose(self, *args, timeout=120): @@ -749,10 +816,18 @@ class LocalRig: expected = source_tree_hash() if manifest.get("source_tree_hash") != expected: raise RigError("running manifest does not match current image build inputs") + pinned = manifest.get("source_pinned") + if pinned is not None: + # lmxopcua#921: the SOURCE pair runs the pinned revision; its export must still hash to what was built. + if (not isinstance(pinned, dict) or pinned_tree_hash(self.folder / "pinned-source") != pinned.get("tree_hash") + or pinned.get("revision") != self.environment.get("GRPC_DATA_SOURCE_PINNED_REVISION")): + raise RigError("pinned SOURCE export does not match the recorded pinned build") for node in NODES: raw = self.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15) stamp = json.loads(raw) - if stamp.get("tree_hash") != expected or stamp.get("revision") != manifest.get("source_revision"): + want = ((pinned["tree_hash"], pinned["revision"]) if pinned is not None and node.startswith("source-") + else (expected, manifest.get("source_revision"))) + if stamp.get("tree_hash") != want[0] or stamp.get("revision") != want[1]: raise RigError("running Host build stamp does not match the candidate") device_hash = device_tree_hash() if manifest.get("device_source_hash") != device_hash: @@ -848,7 +923,7 @@ class LocalRig: self.save(manifest) return manifest - def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False): + def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False, source_revision=None): import secrets import credentials if self.folder.exists(): @@ -875,6 +950,16 @@ class LocalRig: settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend if conditions: settings["GRPC_DATA_CONDITIONS"] = "1" + pinned = None + if source_revision is not None: + # lmxopcua#921: the SOURCE pair is built from a pinned post-X0, pre-H2 revision (the "v1 origin"); CONTROL and + # CONSUMER stay on this checkout. Only the wire tap is added to the pinned tree. + full = resolve_pinned_source_revision(source_revision) + pinned = {"revision": full, "tree_hash": export_pinned_source(full, self.folder / "pinned-source"), + "x0_merge": X0_MERGE, "h2_merge_absent": H2_MERGE, "overlay_files": list(PINNED_OVERLAY_FILES)} + settings.update({"GRPC_DATA_SOURCE_PINNED": "1", "GRPC_DATA_SOURCE_PINNED_REVISION": full, + "GRPC_DATA_SOURCE_PINNED_TREE_HASH": pinned["tree_hash"], "GRPC_DATA_SOURCE_PINNED_CONTEXT": str(self.folder / "pinned-source"), + "GRPC_DATA_SOURCE_IMAGE": f"otopcua-grpc-data-source-pinned:{self.run_id}"}) atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) self.environment.update(settings) credentials.provision_tls(self.folder / "security", NODES[2:]) @@ -891,12 +976,15 @@ class LocalRig: resolved = json.loads(self.compose("config", "--format", "json")) validate_fixture_endpoints(resolved, local_services=SERVICES) try: - self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", timeout=1800) + self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", *(["source-1"] if pinned else []), + timeout=2400 if pinned else 1800) # a pinned run builds a second Host image self.compose("up", "--detach", "sql", "device", "migrator", *NODES, timeout=timeout) manifest = self.allocate_manifest() manifest["source_revision"] = revision manifest["source_tree_hash"] = tree_hash manifest["device_source_hash"] = settings["DEVICE_TREE_HASH"] + if pinned is not None: + manifest["source_pinned"] = pinned self.capture(manifest) wait_until(lambda: self.health(manifest, require_catalog=False), timeout=timeout, description="six node health and independent pair roles") manifest["state"] = "up" @@ -1347,6 +1435,8 @@ def main(argv=None): parser.add_argument("action", choices=("preflight", "up", "seed", "deploy", "status", "down")) parser.add_argument("--run-id") parser.add_argument("--timeout", type=float, default=None) + parser.add_argument("--source-revision", default=None, + help="up only (#921): build the SOURCE pair from this pinned post-X0, pre-H2 commit (a v1 origin), e.g. 0c86edc1") parser.add_argument("--conditions", action="store_true", help="up only: add the A2a conditions overlay (AlarmSubscribe exports + one scripted alarm)") 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, @@ -1381,6 +1471,10 @@ def main(argv=None): if arguments.action != "up": raise RigError("--conditions applies to up only; the run remembers it") options["conditions"] = True + if arguments.source_revision is not None: + if arguments.action != "up": + raise RigError("--source-revision applies to up only; the run remembers it") + options["source_revision"] = arguments.source_revision 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/tests/test_rig.py b/scripts/validation/grpc-data/tests/test_rig.py index fe00cf21a..224a3a480 100644 --- a/scripts/validation/grpc-data/tests/test_rig.py +++ b/scripts/validation/grpc-data/tests/test_rig.py @@ -569,3 +569,85 @@ class AkkaSeedEndpointTests(unittest.TestCase): for row in variants: with self.subTest(row=row), self.assertRaises(rig.RigError): rig.validate_fixture_endpoints(row, local_services={"source-1"}) + + +class PinnedSourceRevisionTests(unittest.TestCase): + """lmxopcua#921: a pinned SOURCE must be a post-X0, pre-H2 commit; no Docker or real git.""" + + PINNED = "0c86edc194bf50c2a902a081959333097e0b3bb5" + PROTO_V1 = "service DataConnectionService {\n rpc Read(ReadRequest) returns (ReadResponse);\n}\n" + + def git(self, *, x0=True, h2=False, proto=None): + def run(*arguments): + if arguments[0] == "rev-parse": + return self.PINNED + "\n" + if arguments[0] == "merge-base": + if arguments[1] == rig.X0_MERGE: + return (rig.X0_MERGE if x0 else "1" * 40) + "\n" + return (rig.H2_MERGE if h2 else "2" * 40) + "\n" + if arguments[0] == "show": + return proto if proto is not None else self.PROTO_V1 + raise AssertionError(arguments) + return run + + def test_a_post_x0_pre_h2_commit_resolves_to_its_full_sha(self): + self.assertEqual(rig.resolve_pinned_source_revision("0c86edc1", git=self.git()), self.PINNED) + + def test_pre_x0_h2_or_a_history_rpc_is_refused(self): + history = self.PROTO_V1 + " rpc HistoryRead(HistoryReadRequest) returns (HistoryReadResponse);\n" + for options in ({"x0": False}, {"h2": True}, {"proto": history}): + with self.subTest(options=options), self.assertRaises(rig.RigError): + rig.resolve_pinned_source_revision("0c86edc1", git=self.git(**options)) + + def test_only_hexadecimal_commit_ids_are_accepted(self): + for value in ("HEAD", "master", "0c86edc1;rm", "abc", None, "--all"): + with self.subTest(value=value), self.assertRaises(rig.RigError): + rig.resolve_pinned_source_revision(value, git=self.git()) + + def test_the_real_pin_0c86edc1_is_post_x0_and_pre_h2(self): + """The committed history itself (read-only git): the issue's suggested pin passes the guard.""" + self.assertEqual(rig.resolve_pinned_source_revision("0c86edc1"), self.PINNED) + with self.assertRaises(rig.RigError): + rig.resolve_pinned_source_revision(rig.H2_MERGE[:12]) + + def test_pinned_tree_hash_uses_the_image_input_filter(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / "src").mkdir() + (root / "docs").mkdir() + (root / "src" / "A.cs").write_text("class A {}") + (root / "docs" / "note.cs").write_text("ignored") + first = rig.pinned_tree_hash(root) + (root / "docs" / "note.cs").write_text("still ignored") + self.assertEqual(rig.pinned_tree_hash(root), first) + (root / "src" / "A.cs").write_text("class A { int x; }") + self.assertNotEqual(rig.pinned_tree_hash(root), first) + + def test_candidate_expects_the_pinned_stamp_on_source_nodes_only(self): + instance = object.__new__(rig.LocalRig) + instance.folder = Path("/nonexistent") + instance.environment = {"GRPC_DATA_SOURCE_PINNED_REVISION": "pinned-rev"} + instance.load = Mock(return_value={"source_tree_hash": "code", "source_revision": "revision", "device_source_hash": "device", + "source_pinned": {"revision": "pinned-rev", "tree_hash": "pinned-code"}}) + + def stamp(*args, **kwargs): + if "device" in args: + return "device\n" + pinned = args[2].startswith("source-") + return json.dumps({"tree_hash": "pinned-code" if pinned else "code", "revision": "pinned-rev" if pinned else "revision"}) + + def current_everywhere(*args, **kwargs): + return "device\n" if "device" in args else json.dumps({"tree_hash": "code", "revision": "revision"}) + + instance.compose = Mock(side_effect=stamp) + with patch.object(rig, "source_tree_hash", return_value="code"), patch.object(rig, "device_tree_hash", return_value="device"): + with patch.object(rig, "pinned_tree_hash", return_value="pinned-code"): + self.assertEqual(instance.verify_candidate(), "code") + # A current-checkout stamp on a SOURCE node (the pinned image is not what runs) is refused. + instance.compose.side_effect = current_everywhere + with self.assertRaises(rig.RigError): + instance.verify_candidate() + # The export edited after the build is refused before any stamp is read. + instance.compose.side_effect = stamp + with patch.object(rig, "pinned_tree_hash", return_value="edited-export"), self.assertRaises(rig.RigError): + instance.verify_candidate()