From 8ddae2f43d3fa5699b3dd5fd9b62da8cb8759702 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 03:34:02 -0500 Subject: [PATCH] test(grpc-data-rig): #1115 scale profile (seed --scale N) and the #1026 scale gate - device: read-only scale block (holding registers 1000..5095) + scale_set control action - seed: GRPC_DATA_SCALE=N adds SOURCE driver modscale/dev with N UInt16 tags in TagGroups small (first 160) / large (rest), one RawTagGroup export + CONSUMER mapping each (map-scale-small|large); fixture.json records the counts - rig.py: seed --scale N; deploy trigger gets a 60 s socket timeout (the AdminUI's StartDeployment ask waits up to 45 s; a 2048-tag snapshot read took ~25 s, so the general 15 s cap aborted the POST) - scale_gate.py: opens a >128 and a >1024-item mapping via Client CLI recursive subscribes on CONSUMER, requires all Good, churns the block, restarts the SOURCE pair, requires all Good with a post-restart value, checks the consumer ResetHistory counter and the container logs for 'history expired'; PASS/FAIL + evidence/S1026-results.json Co-Authored-By: Claude --- scripts/validation/grpc-data/README.md | 30 +- scripts/validation/grpc-data/device/server.py | 21 +- scripts/validation/grpc-data/rig.py | 35 +- scripts/validation/grpc-data/scale_gate.py | 395 ++++++++++++++++++ scripts/validation/grpc-data/seed/Program.cs | 49 ++- .../validation/grpc-data/tests/test_device.py | 15 + .../validation/grpc-data/tests/test_rig.py | 34 ++ 7 files changed, 570 insertions(+), 9 deletions(-) create mode 100644 scripts/validation/grpc-data/scale_gate.py diff --git a/scripts/validation/grpc-data/README.md b/scripts/validation/grpc-data/README.md index fabcbbe21..db5de2652 100644 --- a/scripts/validation/grpc-data/README.md +++ b/scripts/validation/grpc-data/README.md @@ -199,6 +199,32 @@ python3 scripts/validation/grpc-data/rig.py down --run-id h923-gw On the gateway the window is a fixed 120 s of the recent past (nothing is accumulated). H08 re-reads the window and answers the previous full run stored in `evidence/H-gateway-baseline.json`, so run it after a full run on the same run id. +## Scale profile and the #1026 gate (#1115, opt-in) + +`rig.py seed --run-id --scale N` (N = 1..4096) adds a second SOURCE Modbus driver `modscale` → device `dev` with N +read-only UInt16 tags `t0000…` on the device fixture's scale block (holding registers 1000..5095, 250 ms poll group; the +driver coalesces contiguous registers, so 2048 tags are ~17 FC03 reads per poll). The first `min(N, 160)` tags are TagGroup +`small`, the rest TagGroup `large`; each group is its own Raw export (`export-scale-small|large`, RootKind `RawTagGroup`) and +CONSUMER mapping (`map-scale-small|large`, branch `remote-scale-small|large`, Browse/Metadata/Read/Subscribe). The manifest's +`fixture.scale` records the counts. Without `--scale` the seed is unchanged. The device's `scale_set` control action +(`{"action":"scale_set","value":v}`) sets every scale register to `v` at once (initially 1). + +```bash +python3 scripts/validation/grpc-data/rig.py up --run-id s1026 --timeout 900 +python3 scripts/validation/grpc-data/rig.py seed --run-id s1026 --scale 2048 +sleep 75 # CONTROL's ClusterNode contact refresh before the first deploy +python3 scripts/validation/grpc-data/rig.py deploy --run-id s1026 --timeout 300 +python3 scripts/validation/grpc-data/scale_gate.py --run-id s1026 # PASS/FAIL, evidence/S1026-results.json +python3 scripts/validation/grpc-data/rig.py down --run-id s1026 +``` + +`scale_gate.py` (gate #1026) needs a >128-item and a >1024-item mapping (N >= 1185). On CONSUMER's primary it opens one +Client CLI `subscribe --recursive` per mapping anchor, sets a fresh scale value and requires every item Good with it; reads +the consumer `ProjectedStreamDiagnostics` counters (`projection-diagnostics` node probe) on both CONSUMER nodes; churns the +scale block (`--churn-hz`, default 4) and `docker compose restart`s both SOURCE nodes; waits for the pair's readiness, stops +the churn, sets a never-used value and requires every item Good with it again; then requires the consumer `ResetHistory` +counter ("Source change history expired." resets) unchanged and no "history expired" line in the SOURCE/CONSUMER logs. + ## Scenario authoring and node probes The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its @@ -252,7 +278,7 @@ graph. The ordinary Host image/configuration does not enable this fixture. The standard-library Python fixture listens on Modbus TCP unit 1, container port 5020. Holding register 0 is a deterministic counter; 10–12 start at `[7,11,13]`; -20–63 are writable uint16 registers. Raw/UNS `scalar` both reach register 20; +20–63 are writable uint16 registers; 1000–5095 are the read-only scale block (see "Scale profile"). Raw/UNS `scalar` both reach register 20; `counter` reaches 0 and `array0`–`array2` expose the fixed samples as individual scalar registers. No unsupported array representation is invented by the seeder. FC03/FC04 reads and FC06/FC16 writes are supported. Unmapped spans return exception @@ -260,7 +286,7 @@ FC03/FC04 reads and FC06/FC16 writes are supported. Unmapped spans return except The fixture-only HTTP API on container port 8080 has `GET /state` and `POST /control`. Actions are `{"action":"advance","steps":1}`, -`{"action":"set","address":20,"value":42}`, and +`{"action":"set","address":20,"value":42}`, `{"action":"scale_set","value":7}`, and `{"action":"drop_next_write_response"}`. The last commits and records one write before closing its response connection. Bounded ledgers distinguish total requests, read attempts, rejected writes and committed effects. The control API is never diff --git a/scripts/validation/grpc-data/device/server.py b/scripts/validation/grpc-data/device/server.py index d95ac5dfe..44ca6d596 100644 --- a/scripts/validation/grpc-data/device/server.py +++ b/scripts/validation/grpc-data/device/server.py @@ -1,7 +1,9 @@ """Deterministic, fixture-only Modbus TCP source and bounded control ledger. Register map (unit 1): 0 counter; 10..12 fixed array; 20..63 writable scalar/ -array window. Control calls advance or set values explicitly; wall time never +array window; 1000..5095 read-only scale block (#1115), every register holding +the one value the `scale_set` control action last set (initially 1). Control +calls advance or set values explicitly; wall time never changes samples. A one-shot fault can discard a write response *after* recording its effect, which gives the integration gate a reproducible ambiguous outcome. """ @@ -20,6 +22,10 @@ CONTROL_PORT = 8080 MAX_PDU_BYTES = 253 MAX_CONTROL_BYTES = 4096 MAX_LEDGER_ITEMS = 1024 +# #1115 scale profile: a read-only block the seeder's `--scale N` tags poll (N <= SCALE_COUNT). Contiguous, so the +# Modbus driver's read coalescing covers 2048 tags in ~17 FC03 reads. Values change only through `scale_set`. +SCALE_BASE = 1000 +SCALE_COUNT = 4096 class DeviceState: @@ -30,6 +36,9 @@ class DeviceState: self._registers.update({24: 7, 25: 11, 26: 13}) text = b"grpc data source" self._registers.update({40 + offset // 2: int.from_bytes(text[offset:offset + 2], "big") for offset in range(0, len(text), 2)}) + self._scale_value = 1 + self._scale_sets = 0 + self._registers.update({address: 1 for address in range(SCALE_BASE, SCALE_BASE + SCALE_COUNT)}) self._effect_total = 0 self._read_total = 0 self._request_total = 0 @@ -54,6 +63,7 @@ class DeviceState: "rejected_writes": list(self._rejected_writes), "writable": {str(address): self._registers[address] for address in range(20, 64)}, "drop_next_write_response": self._drop_next_write_response, + "scale": {"base": SCALE_BASE, "count": SCALE_COUNT, "value": self._scale_value, "sets": self._scale_sets}, } def read(self, address, quantity): @@ -121,6 +131,15 @@ def apply_control(state, command): raise ValueError("set requires writable address and uint16 value") with state._lock: state._registers[address] = value + elif action == "scale_set": + value = command.get("value") + if type(value) is not int or not 0 <= value <= 65535: + raise ValueError("scale_set requires a uint16 value") + with state._lock: + for address in range(SCALE_BASE, SCALE_BASE + SCALE_COUNT): + state._registers[address] = value + state._scale_value = value + state._scale_sets += 1 elif action == "drop_next_write_response": with state._lock: state._drop_next_write_response = True diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index 36c7fffb1..a49a9ecd0 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -504,6 +504,11 @@ NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n # run (compose.conditions.yml); listing them is the DNS allowlist. SERVICES = ("sql", "migrator", "device", "seeder", "questdb", "opcplc", *NODES) HISTORY_BACKENDS = ("sqlserver", "questdb", "gateway") +# #1115: the device fixture's read-only scale block (device/server.py SCALE_COUNT) bounds `seed --scale N`. +SCALE_MAX_TAGS = 4096 +# Longer than the AdminUI's 45 s StartDeployment ask (AdminOperationsClient.DefaultDeployAskTimeout), so the trigger +# always gets the server's own answer (Accepted, NoChanges or OutcomeUnknown). +DEPLOY_REQUEST_TIMEOUT_SECONDS = 60 # #923 gateway backend defaults: the host-run read-only gateway's loopback gRPC port, and the fixture tags bound read-only to # real historian system tags (1 Hz UInt2 seconds counter, a 10 s Float, a string). Overridable through the same env names. GATEWAY_DEFAULT_ENDPOINT = "http://host.docker.internal:5231" @@ -655,7 +660,7 @@ def docker_context(): return rows[0] -def http_request(method, url, *, headers, json_body=None, timeout=10): +def http_request(method, url, *, headers, json_body=None, timeout=10, max_timeout=15): import urllib.request import urllib.error class NoRedirect(urllib.request.HTTPRedirectHandler): @@ -665,7 +670,7 @@ def http_request(method, url, *, headers, json_body=None, timeout=10): request = urllib.request.Request(url, data=data, headers={**headers, **({"Content-Type": "application/json"} if data else {})}, method=method) opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) try: - response = opener.open(request, timeout=min(timeout, 15)) + response = opener.open(request, timeout=min(timeout, max_timeout)) except urllib.error.HTTPError as error: response = error with response: @@ -679,6 +684,13 @@ def http_request(method, url, *, headers, json_body=None, timeout=10): return response.status, dict(response.headers), body +def deploy_http_request(method, url, **options): + """The deploy trigger's transport (#1115): the server's StartDeployment ask waits up to 45 s for a slow compose (a + 2048-tag scale seed read its snapshot in ~25 s on emulated SQL Server); the general 15 s socket cap aborted the POST, + so the server saw a cancelled caller instead of answering Accepted/OutcomeUnknown.""" + return http_request(method, url, max_timeout=DEPLOY_REQUEST_TIMEOUT_SECONDS, **options) + + def wait_until(predicate, *, timeout, description, interval=1): deadline = time.monotonic() + timeout while time.monotonic() < deadline: @@ -1072,9 +1084,15 @@ class LocalRig: def seed_helper(self, action, *arguments, timeout=120): self.compose("run", "--rm", "--no-deps", "seeder", action, *arguments, timeout=timeout) - def seed(self): + def seed(self, scale=None): manifest = self.load() - self.seed_helper("seed") + if scale is None: + self.seed_helper("seed") + else: + # #1115 scale profile: N read-only source tags on the device's scale block, two CONSUMER mappings over them. + if type(scale) is not int or not 1 <= scale <= SCALE_MAX_TAGS: + raise RigError(f"--scale must be 1..{SCALE_MAX_TAGS}") + self.compose("run", "--rm", "--no-deps", "--env", f"GRPC_DATA_SCALE={scale}", "seeder", "seed", timeout=300) fixture = json.loads((self.folder / "seed" / "fixture.json").read_text()) validate_fixture_endpoints(fixture.get("endpoints", {}), local_services=SERVICES) manifest["fixture"] = fixture @@ -1431,7 +1449,7 @@ class LocalRig: raise RigError("sealed artifact has no required-node inventory") return required outcome = deploy_and_wait(manifest["endpoints"][primary + ".admin"]["url"], self.environment["GRPC_DATA_DEPLOY_KEY"], - {node + ":4053" for node in NODES}, request=http_request, timeout=remaining(), on_accepted=accepted) + {node + ":4053" for node in NODES}, request=deploy_http_request, timeout=remaining(), on_accepted=accepted) manifest["deployment"] = {"id": outcome["deploymentId"], "revision_hash": outcome["revisionHash"], "scope_version": scope["scope_version"], "nodes": outcome["nodes"], "required_node_ids": scope["required_node_ids"]} manifest["deployment"]["bundle_commits"] = self.wait_bundle_commits(scope["bundle_expectations"], timeout=remaining()) if require_catalog: @@ -1488,6 +1506,9 @@ def main(argv=None): parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None, help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB; " "gateway = a host-run read-only HistorianGateway, README)") + parser.add_argument("--scale", type=int, default=None, + help=f"seed only (#1115): N (1..{SCALE_MAX_TAGS}) read-only SOURCE tags on the device scale block, " + "mapped to CONSUMER as map-scale-small (first 160) and map-scale-large (the rest); see scale_gate.py") arguments = parser.parse_args(argv) try: if arguments.action == "preflight": @@ -1522,6 +1543,10 @@ def main(argv=None): if arguments.action != "up": raise RigError("--source-revision applies to up only; the run remembers it") options["source_revision"] = arguments.source_revision + if arguments.scale is not None: + if arguments.action != "seed": + raise RigError("--scale applies to seed only") + options["scale"] = arguments.scale 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/scale_gate.py b/scripts/validation/grpc-data/scale_gate.py new file mode 100644 index 000000000..a13bdc7ee --- /dev/null +++ b/scripts/validation/grpc-data/scale_gate.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python3 +"""#1026 scale gate (#1115) on a `rig.py seed --scale N` run: a >128-item and a >1024-item projected mapping open, survive +an origin (SOURCE pair) restart and show no "Source change history expired." resets. + +Prerequisite: `rig.py up` → `rig.py seed --run-id --scale 2048` → `rig.py deploy` (state `ready`). The seed puts the +first 160 scale tags under `map-scale-small` and the rest under `map-scale-large` (see README "Scale profile"). + +Legs, all through production surfaces: + +1. Browse CONSUMER's primary from the shared root (Client CLI) to the two mapping anchors (`remote-scale-small|large`). +2. Open one Client CLI `subscribe --recursive` per mapping on that CONSUMER (real OPC UA monitored items on the projected + nodes; the consumer opens the gRPC cohorts to SOURCE). Set the device scale block to a fresh value E1 and require every + item of both mappings Good with value E1. +3. Capture the consumer `ProjectedStreamDiagnostics` counters (node probe `projection-diagnostics`) on both CONSUMER nodes. +4. Churn the scale block (`--churn-hz`, every register changes each step, so the origin hub publishes N changes per poll) + and, while it churns, `docker compose restart` BOTH SOURCE nodes (the whole origin pair), wait for the pair's readiness. +5. Stop the churn, set a never-used value E2 and require every item Good with value E2 again (a post-restart delivery, + not a held pre-restart value). Settle, then capture the counters again. +6. PASS needs: both mappings fully subscribed with the expected item counts (>128 / >1024), all Good E1 before and all Good + E2 after the restart, the consumer's `ResetHistory` counter unchanged on both CONSUMER nodes, and no + "history expired" line in any SOURCE/CONSUMER container log since the gate started. + +Evidence: `/evidence/S1026-results.json` (+ per-mapping CLI logs). Prints PASS/FAIL and exits 0/1. +""" +import argparse +from datetime import datetime, timezone +import json +import os +import re +import signal +import subprocess +import sys +import threading +import time +import uuid + +import cli_gate +import rig +import scenarios + +SMALL_MIN, LARGE_MIN = 129, 1025 # the #1026 bounds: ">128" and ">1024" items +HISTORY_EXPIRED = "Source change history expired" +LOG_CAP_BYTES = 32 * 1024 * 1024 + + +class Subscriber: + """One long-running Client CLI `subscribe --recursive` process with live per-item state.""" + + def __init__(self, runner, mapping, anchor, endpoint, interval_ms): + self.mapping, self.anchor = mapping, anchor + self.lock = threading.Lock() + self.items = {} # display path → {"status", "value", "at", "updates", "transitions": [...]} + self.found = self.subscribed = self.requested = None + self.connection_lines = [] + self.summary_lines = [] + self.log_path = runner.folder / f"S1026-{mapping}.cli.log" + self.log = open(os.open(self.log_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") + self.logged = 0 + self.secrets = runner.secrets + argv = ["dotnet", str(runner.cli_dll), "subscribe", "-u", endpoint, "-U", "apikey", "-P", runner.key, + "-n", anchor, "-r", "--max-depth", "3", "-i", str(interval_ms), "--duration", "3600", "--reconnect-timeout", "0"] + self.process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + cwd=rig.ROOT, env=runner.rig.environment, start_new_session=True, text=True, bufsize=1) + self.reader = threading.Thread(target=self._read, daemon=True) + self.reader.start() + + def _write_log(self, line): + for secret in self.secrets: + line = line.replace(secret, "[REDACTED]") + if self.logged < LOG_CAP_BYTES: + self.log.write(line + "\n") + self.logged += len(line) + 1 + + def _read(self): + for raw in self.process.stdout: + line = raw.rstrip("\n") + self._write_log(line) + if (match := re.match(r"Found (\d+) variable nodes\.", line)): + self.found = int(match[1]); continue + if (match := re.match(r"Subscribed to (\d+)/(\d+) nodes", line)): + self.subscribed, self.requested = int(match[1]), int(match[2]); continue + if " CONNECTION " in line: + with self.lock: + self.connection_lines.append(line) + continue + try: + parsed = cli_gate.parse_notification(line) + except cli_gate.CliGateError: + parsed = None + if parsed is None: + if self.subscribed is not None and line.strip(): + with self.lock: + self.summary_lines = (self.summary_lines + [line])[-200:] + continue + good = cli_gate.is_good_status(parsed["status"]) + now = time.monotonic() + with self.lock: + item = self.items.setdefault(parsed["node"], {"status": None, "value": None, "at": None, "updates": 0, "transitions": []}) + was_good = item["status"] is not None and cli_gate.is_good_status(item["status"]) + if item["status"] is None or was_good != good: + if len(item["transitions"]) < 64: + item["transitions"].append({"at": now, "good": good, "status": parsed["status"]}) + item.update(status=parsed["status"], value=parsed["value"], at=now, updates=item["updates"] + 1) + self.log.flush() + + def view(self): + with self.lock: + return {key: dict(item, transitions=list(item["transitions"])) for key, item in self.items.items()} + + def all_good_with(self, value, expected): + items = self.view() + good = sum(1 for item in items.values() if item["value"] == str(value) and cli_gate.is_good_status(item["status"])) + return len(items) == expected and good == expected, good + + def non_good_since(self, moment): + return sum(1 for item in self.view().values() if any(t["at"] >= moment and not t["good"] for t in item["transitions"])) + + def stop(self): + if self.process.poll() is None: + try: + os.killpg(self.process.pid, signal.SIGINT) + self.process.wait(timeout=30) + except (ProcessLookupError, subprocess.TimeoutExpired): + try: + os.killpg(self.process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + self.process.wait(timeout=10) + self.reader.join(timeout=10) + self.log.close() + return self.process.returncode + + +class ScaleGate: + def __init__(self, run_id, *, churn_hz, churn_seconds, settle_seconds, interval_ms, phase_timeout): + self.runner = scenarios.ScenarioRunner(run_id) + self.scale = self.runner.manifest["fixture"].get("scale") + if not self.scale: + raise SystemExit("run was not seeded with --scale") + self.churn_hz, self.churn_seconds, self.settle_seconds = churn_hz, churn_seconds, settle_seconds + self.interval_ms, self.phase_timeout = interval_ms, phase_timeout + self.evidence = {"run_id": run_id, "issue": "#1026", "scale": self.scale, "started_utc": datetime.now(timezone.utc).isoformat(), + "settings": {"churn_hz": churn_hz, "churn_seconds": churn_seconds, "settle_seconds": settle_seconds, + "sampling_interval_ms": interval_ms, "phase_timeout_seconds": phase_timeout}, + "checks": [], "timeline": []} + self.t0 = time.monotonic() + self.started_iso = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + def mark(self, event, **fields): + row = {"event": event, "t": round(time.monotonic() - self.t0, 2), **fields} + self.evidence["timeline"].append(row) + print(f"[{row['t']:8.2f}s] {event} {json.dumps(fields) if fields else ''}", flush=True) + + def check(self, condition, name, **detail): + self.evidence["checks"].append({"check": name, "passed": bool(condition), **detail}) + print((" ok " if condition else " FAIL ") + name + (f" {json.dumps(detail)}" if detail else ""), flush=True) + return bool(condition) + + def device(self, action=None, **fields): + base = self.runner.manifest["endpoints"]["device.control"]["url"] + status, _, body = rig.http_request("POST" if action else "GET", base + ("/control" if action else "/state"), + headers={}, json_body={"action": action, **fields} if action else None, timeout=10) + if status != 200 or not isinstance(body, dict): + raise scenarios.ScenarioError("device control failed") + return body + + def anchors(self, consumer): + uris = self.runner.manifest["resolved_nodes"][consumer]["namespace_uris"] + raw = uris.index(self.runner.manifest["fixture"]["namespace_uris"]["raw"]) + argv = ["dotnet", str(self.runner.cli_dll), "browse", "-u", self.runner.endpoint(consumer), "-U", "apikey", "-P", self.runner.key, + "-n", f"ns={raw};s=OtOpcUa", "-r", "-d", "3"] + wanted = {mapping["branch"]: mapping for mapping in self.scale["mappings"]} + found = {} + end = time.monotonic() + 120 + while True: + result = self.runner.process(argv, "S1026-browse-" + uuid.uuid4().hex[:6], timeout=120) + for line in result.stdout.splitlines(): + match = re.match(r"^( *)\[(\w+)\] (.+?) \(NodeId: (.+)\)$", line) + if match and match[3] in wanted: + found[match[3]] = match[4] + if len(found) == len(wanted) or time.monotonic() >= end: + return found + time.sleep(3) + + def counters(self, consumers): + out = {} + mapping = self.scale["mappings"][0] + for node in consumers: + observed = self.runner.probe(node, "projection-diagnostics", "raw", path=mapping["raw_path"] + "/t0000", + operationId=mapping["id"], timeout=30) + out[node] = observed["streamCounters"] + return out + + def wait_all(self, subscribers, value, label): + started = time.monotonic() + end = started + self.phase_timeout + last_report = 0 + while True: + states = {s.mapping: s.all_good_with(value, s.expected) for s in subscribers} + if all(done for done, _ in states.values()): + elapsed = round(time.monotonic() - started, 2) + self.mark(label + "-all-good", value=value, seconds=elapsed, good={k: v[1] for k, v in states.items()}) + return elapsed + if time.monotonic() >= end or any(s.process.poll() is not None for s in subscribers): + self.mark(label + "-timeout", value=value, good={k: v[1] for k, v in states.items()}, + expected={s.mapping: s.expected for s in subscribers}, + statuses={s.mapping: self.status_histogram(s) for s in subscribers}) + return None + if time.monotonic() - last_report >= 10: + last_report = time.monotonic() + self.mark(label + "-progress", good={k: v[1] for k, v in states.items()}) + time.sleep(0.5) + + @staticmethod + def status_histogram(subscriber): + histogram = {} + for item in subscriber.view().values(): + key = f"{item['status']}|{item['value']}" + histogram[key] = histogram.get(key, 0) + 1 + return dict(sorted(histogram.items(), key=lambda pair: -pair[1])[:8]) + + def wait_origin_ready(self): + nodes = ("source-1", "source-2") + end = time.monotonic() + 300 + while True: + try: + manifest = self.runner.rig.refresh_endpoints(nodes) + self.runner.manifest = manifest + if self.runner.rig.health(manifest): + return True + except (rig.RigError, OSError): + pass + if time.monotonic() >= end: + return False + time.sleep(2) + + def history_expired_log_lines(self): + hits = {} + for node in ("source-1", "source-2", "consumer-1", "consumer-2"): + try: + # The run's exact container (by recorded project + service), not `compose logs`: a configuration + # experiment's override file changes the compose set, and logs must still be readable. + ids = rig.run_command([*self.runner.rig.docker, "container", "ls", "-a", "-q", + "--filter", f"label={rig.RUN_LABEL}={self.runner.rig.run_id}", + "--filter", f"label={rig.PROJECT_LABEL}={self.runner.rig.project}", + "--filter", f"label=com.docker.compose.service={node}"]).split() + if len(ids) != 1: + raise rig.RigError("exactly one owned container per service") + text = rig.run_command([*self.runner.rig.docker, "logs", "--since", self.started_iso, ids[0]], timeout=60) + except rig.RigError: + hits[node] = None + continue + hits[node] = [line[-400:] for line in text.splitlines() if "history expired" in line.lower()][:20] + return hits + + def run(self): + runner = self.runner + runner.active = "S1026" + runner.deadline = time.monotonic() + 7200 + runner.publish() + expected = {m["id"]: m["items"] for m in self.scale["mappings"]} + small, large = expected.get("map-scale-small", 0), expected.get("map-scale-large", 0) + self.check(small >= SMALL_MIN and large >= LARGE_MIN, "fixture has a >128-item and a >1024-item mapping", + small=small, large=large, total=self.scale["count"]) + consumer = runner.primary("consumer") + consumers = sorted(node for node in runner.manifest["nodes"] if node.startswith("consumer-")) + self.mark("consumer-primary", node=consumer) + anchors = self.anchors(consumer) + self.evidence["anchors"] = anchors + if not self.check(len(anchors) == len(self.scale["mappings"]), "both mapping anchors browsable on CONSUMER", anchors=anchors): + return self.finish(False) + + e1 = 10000 + (int(time.time()) % 1000) + e2 = 60000 + (int(time.time()) % 1000) + self.device("scale_set", value=e1) + self.mark("device-set", value=e1) + subscribers = [] + try: + for mapping in self.scale["mappings"]: + subscriber = Subscriber(runner, mapping["id"], anchors[mapping["branch"]], runner.endpoint(consumer), self.interval_ms) + subscriber.expected = mapping["items"] + subscribers.append(subscriber) + self.mark("subscribe-started", mapping=mapping["id"], items=mapping["items"]) + open_end = time.monotonic() + self.phase_timeout + while any(s.subscribed is None for s in subscribers) and time.monotonic() < open_end \ + and all(s.process.poll() is None for s in subscribers): + time.sleep(0.5) + for s in subscribers: + self.check(s.found == s.expected and s.subscribed == s.expected == s.requested, + f"{s.mapping}: CLI found and subscribed every projected item", found=s.found, + subscribed=s.subscribed, requested=s.requested, expected=s.expected) + before_open = self.wait_all(subscribers, e1, "open") + self.check(before_open is not None, "every item of both mappings Good with the fresh value before the restart", + value=e1, seconds=before_open) + counters_before = self.counters(consumers) + self.evidence["counters_before"] = counters_before + self.mark("counters-before", reset_history={n: c.get("ResetHistory") for n, c in counters_before.items()}) + + stop_churn = threading.Event() + churn_steps = [] + + def churn(): + value = 20000 + while not stop_churn.is_set(): + value = 20000 + (value - 19999) % 30000 + try: + self.device("scale_set", value=value) + churn_steps.append(value) + except (scenarios.ScenarioError, OSError): + pass + stop_churn.wait(1.0 / self.churn_hz) + churner = threading.Thread(target=churn, daemon=True) + churn_at = time.monotonic() + churner.start() + self.mark("churn-started", hz=self.churn_hz) + time.sleep(self.churn_seconds) + # Evidence, not a pass condition: did the open mappings hold Good while every scale register changed? + self.evidence["pre_restart_churn"] = {s.mapping: {"non_good_items": s.non_good_since(churn_at), + "good_now": sum(1 for item in s.view().values() if cli_gate.is_good_status(item["status"]))} + for s in subscribers} + self.mark("pre-restart-churn", **self.evidence["pre_restart_churn"]) + restart_at = time.monotonic() + self.mark("origin-restart-begin", nodes=["source-1", "source-2"]) + runner.rig.compose("restart", "--timeout", "10", "source-1", "source-2", timeout=180) + self.mark("origin-restart-issued") + ready = self.wait_origin_ready() + self.mark("origin-ready" if ready else "origin-not-ready") + self.check(ready, "origin pair back to ready health with one active node") + time.sleep(self.churn_seconds) + stop_churn.set() + churner.join(timeout=10) + self.mark("churn-stopped", steps=len(churn_steps)) + for s in subscribers: + self.evidence.setdefault("non_good_after_restart", {})[s.mapping] = s.non_good_since(restart_at) + self.mark("observed-outage", non_good_items=self.evidence["non_good_after_restart"]) + self.device("scale_set", value=e2) + self.mark("device-set", value=e2) + recovered = self.wait_all(subscribers, e2, "recovery") + self.check(recovered is not None, "every item of both mappings Good with a post-restart value", value=e2, seconds=recovered) + time.sleep(self.settle_seconds) + stable = {s.mapping: s.all_good_with(e2, s.expected)[0] for s in subscribers} + self.check(all(stable.values()), "still all Good after the settle window", stable=stable) + counters_after = self.counters(consumers) + self.evidence["counters_after"] = counters_after + deltas = {node: {key: counters_after[node].get(key, 0) - counters_before[node].get(key, 0) + for key in ("Reset", "ResetHistory", "ResetUnavailable", "ResetSnapshot", "ResetOther", "Attempt", "SnapshotEnd")} + for node in consumers} + self.evidence["counter_deltas"] = deltas + self.mark("counters-after", deltas=deltas) + self.check(all(delta["ResetHistory"] == 0 for delta in deltas.values()), + "no 'Source change history expired.' reset reached either CONSUMER (ResetHistory delta 0)", + reset_history={node: delta["ResetHistory"] for node, delta in deltas.items()}) + self.check(all(counters_after[n].get("ResetHistory", 0) == 0 for n in consumers), + "ResetHistory is 0 since CONSUMER process start", totals={n: counters_after[n].get("ResetHistory") for n in consumers}) + for s in subscribers: + self.check(not s.connection_lines, f"{s.mapping}: the CLI's OPC UA session to CONSUMER never dropped", + lines=s.connection_lines[:5]) + finally: + codes = {s.mapping: s.stop() for s in subscribers} + self.evidence["cli_exit_codes"] = codes + self.evidence["cli_summaries"] = {s.mapping: s.summary_lines[-12:] for s in subscribers} + self.evidence["cli_logs"] = {s.mapping: str(s.log_path) for s in subscribers} + self.evidence["final_status_histogram"] = {s.mapping: self.status_histogram(s) for s in subscribers} + hits = self.history_expired_log_lines() + self.evidence["history_expired_log_lines"] = hits + self.check(all(lines == [] for lines in hits.values()), "no 'history expired' line in SOURCE/CONSUMER logs since the gate started", + counts={node: None if lines is None else len(lines) for node, lines in hits.items()}) + return self.finish(all(row["passed"] for row in self.evidence["checks"])) + + def finish(self, passed): + self.evidence["passed"] = passed + self.evidence["finished_utc"] = datetime.now(timezone.utc).isoformat() + self.runner.save("S1026-results.json", self.evidence) + print(("PASS" if passed else "FAIL") + f" #1026 scale gate — evidence {self.runner.folder / 'S1026-results.json'}", flush=True) + return 0 if passed else 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--run-id", required=True) + parser.add_argument("--churn-hz", type=float, default=4.0, help="scale-block value changes per second while the origin restarts") + parser.add_argument("--churn-seconds", type=float, default=20.0, help="churn before the restart and again after readiness") + parser.add_argument("--settle-seconds", type=float, default=30.0) + parser.add_argument("--interval-ms", type=int, default=500, help="CLI monitored-item sampling interval") + parser.add_argument("--phase-timeout", type=float, default=240.0, help="bound for each all-Good wait") + arguments = parser.parse_args(argv) + if not 0 < arguments.churn_hz <= 20: + parser.error("--churn-hz must be in (0, 20]") + gate = ScaleGate(arguments.run_id, churn_hz=arguments.churn_hz, churn_seconds=arguments.churn_seconds, + settle_seconds=arguments.settle_seconds, interval_ms=arguments.interval_ms, phase_timeout=arguments.phase_timeout) + return gate.run() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index 6378e106d..2d21aadc2 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -49,6 +49,17 @@ string HistoryConfig(string name, string tagConfig) // A2a smoke profile (opt-in, `rig.py up --conditions`): SOURCE exports gain AlarmSubscribe and the SOURCE equipment gets // one scripted alarm, ScalarHigh (scalar > 100), so a condition stream sees a snapshot and a delta. Unset ⇒ v1 fixture. var conditions = Environment.GetEnvironmentVariable("GRPC_DATA_CONDITIONS") == "1"; +// #1115 scale profile (opt-in, `rig.py seed --scale N`): a second SOURCE Modbus driver `modscale` → device `dev` with N +// read-only UInt16 tags on the device fixture's scale block (holding registers 1000..), split into TagGroup `small` +// (the first min(N, 160)) and `large` (the rest). Each group is its own Raw export and CONSUMER mapping +// (`map-scale-small` / `map-scale-large`), so a gate can open a >128-item and a >1024-item mapping. Unset ⇒ unchanged. +const int ScaleRegisterBase = 1000, ScaleMaxCount = 4096, ScaleSmallCount = 160; +var scaleText = Environment.GetEnvironmentVariable("GRPC_DATA_SCALE"); +var scale = string.IsNullOrEmpty(scaleText) ? 0 + : int.TryParse(scaleText, out var parsedScale) && parsedScale is >= 1 and <= ScaleMaxCount ? parsedScale + : throw new InvalidOperationException("GRPC_DATA_SCALE must be 1..4096"); +var scaleSmall = Math.Min(scale, ScaleSmallCount); +const DataOperations scaleOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe; try { if (args.Length == 0) return 2; @@ -441,6 +452,25 @@ try db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + pump + "-yellow", EquipmentId = pumpId, TagId = "source-opcua-yellow" }); } } + if (scale > 0) + { + db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-modscale", ClusterId = "SOURCE", Name = "modscale", DriverType = "Modbus", + DriverConfig = $$$"""{"TimeoutMs":2000,"AutoReconnect":true,"Probe":{"Enabled":true,"ProbeAddress":{{{ScaleRegisterBase}}}}}""" }); + db.Devices.Add(new() { DeviceRowId = Guid.NewGuid(), DeviceId = "source-scale-device", DriverInstanceId = "source-modscale", Name = "dev", + DeviceConfig = """{"Host":"device","Port":5020,"UnitId":1}""" }); + db.PollGroups.Add(new() { PollGroupRowId = Guid.NewGuid(), PollGroupId = "source-scale-poll", DriverInstanceId = "source-modscale", Name = "scale", IntervalMs = 250 }); + foreach (var (group, order) in new[] { ("small", 0), ("large", 1) }) + if (group == "small" || scale > scaleSmall) + db.TagGroups.Add(new() { TagGroupRowId = Guid.NewGuid(), TagGroupId = "source-scale-" + group, DeviceId = "source-scale-device", Name = group, SortOrder = order }); + for (var index = 0; index < scale; index++) + { + var address = ScaleRegisterBase + index; + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = $"source-scale-t{index:D4}", DeviceId = "source-scale-device", + TagGroupId = index < scaleSmall ? "source-scale-small" : "source-scale-large", Name = $"t{index:D4}", DataType = "UInt16", + AccessLevel = TagAccessLevel.Read, WriteIdempotent = false, PollGroupId = "source-scale-poll", + TagConfig = JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable = false }) }); + } + } db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); db.DataConnections.Add(new() { DataConnectionRowId = Guid.NewGuid(), DataConnectionId = "consumer-source", ClusterId = "CONSUMER", Enabled = true, @@ -473,6 +503,18 @@ try db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead }); } + if (scale > 0) + foreach (var group in scale > scaleSmall ? new[] { "small", "large" } : new[] { "small" }) + { + db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-scale-" + group, ClusterId = "SOURCE", Enabled = true, + Realm = DataRealm.Raw, RootKind = "RawTagGroup", RootEntityId = "source-scale-" + group, PrincipalId = "fixture-consumer", + AllowedOperations = scaleOperations }); + db.RemoteNamespaceMappings.Add(new() { RemoteNamespaceMappingRowId = Guid.NewGuid(), RemoteNamespaceMappingId = "map-scale-" + group, + ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], + Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-scale-" + group, + RemoteRootEntityId = "source-scale-" + group, RemoteNamespaceUri = V3NodeIds.RawNamespaceUri, + RemoteIdentifierKind = "string", RemoteIdentifier = "modscale/dev/" + group, AllowedOperations = scaleOperations, WriteThrough = false }); + } if (conditions) { // A4: exports + CONSUMER mappings for the native alarm's three placements — the Raw opc-plc device and the two @@ -540,7 +582,12 @@ try native = new { condition = "EastTankYellow", raw_path = "opcua/opcplc/EastTankYellow", upstream = "ns=6;s=1:Colours/EastTank?Yellow", equipment = pumpEquipment, subjects = new { pumpa = "area/line/pumpa", pumpb = "area/line/pumpb" }, raw_root = "opcua/opcplc", mappings = new { raw = "map-opc", pumpa = "map-pumpa", pumpb = "map-pumpb" }, - branches = new { raw = "remote-opc", pumpa = "remote-pumpa", pumpb = "remote-pumpb" } } } : null }); + branches = new { raw = "remote-opc", pumpa = "remote-pumpa", pumpb = "remote-pumpb" } } } : null, + // #1115 scale profile: where the N tags live and which CONSUMER mapping covers each group. + scale = scale > 0 ? new { count = scale, register_base = ScaleRegisterBase, raw_root = "modscale/dev", poll_ms = 250, + mappings = (scale > scaleSmall ? new[] { ("small", scaleSmall), ("large", scale - scaleSmall) } : new[] { ("small", scaleSmall) }) + .Select(entry => new { id = "map-scale-" + entry.Item1, branch = "remote-scale-" + entry.Item1, raw_path = "modscale/dev/" + entry.Item1, + first_index = entry.Item1 == "small" ? 0 : scaleSmall, items = entry.Item2 }).ToArray() } : null }); return 0; } catch (Exception error) diff --git a/scripts/validation/grpc-data/tests/test_device.py b/scripts/validation/grpc-data/tests/test_device.py index 51f8b7f27..386dfee64 100644 --- a/scripts/validation/grpc-data/tests/test_device.py +++ b/scripts/validation/grpc-data/tests/test_device.py @@ -80,6 +80,21 @@ class ModbusFixtureTests(unittest.TestCase): apply_control(self.state, command) self.assertEqual(self.state.snapshot()["effect_total"], 0) + def test_scale_block_is_read_only_and_set_as_one_value(self): + # #1115: 4096 contiguous read-only registers from 1000; one control action sets them all. + self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 1000, 125))), (1,) * 125) + self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 5095 - 124, 125))), (1,) * 125) + self.assertEqual(handle_modbus_pdu(self.state, 1, request(3, 5096, 1)), b"\x83\x02") + self.assertEqual(handle_modbus_pdu(self.state, 1, request(3, 999, 2)), b"\x83\x02") + self.assertEqual(handle_modbus_pdu(self.state, 1, request(6, 1000, 5)), b"\x86\x02") + apply_control(self.state, {"action": "scale_set", "value": 4242}) + self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 2047, 3))), (4242,) * 3) + self.assertEqual(self.state.snapshot()["scale"], {"base": 1000, "count": 4096, "value": 4242, "sets": 1}) + for invalid in (-1, 65536, "1", None): + with self.assertRaises(ValueError): + apply_control(self.state, {"action": "scale_set", "value": invalid}) + self.assertEqual(self.state.snapshot()["effect_total"], 0) + if __name__ == "__main__": unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_rig.py b/scripts/validation/grpc-data/tests/test_rig.py index 098e54b7e..969cc5167 100644 --- a/scripts/validation/grpc-data/tests/test_rig.py +++ b/scripts/validation/grpc-data/tests/test_rig.py @@ -680,3 +680,37 @@ class PinnedSourceRevisionTests(unittest.TestCase): instance.compose.side_effect = stamp with patch.object(rig, "pinned_tree_hash", return_value="edited-export"), self.assertRaises(rig.RigError): instance.verify_candidate() + + +class ScaleSeedTests(unittest.TestCase): + """#1115: `seed --scale N` reaches only the seeder, bounded by the device fixture's scale block.""" + + def instance(self): + instance = object.__new__(rig.LocalRig) + instance.load = Mock(return_value={}) + instance.compose = Mock(side_effect=StopIteration("seeder invoked")) + return instance + + def test_out_of_range_or_non_integer_scale_is_refused_before_the_seeder_runs(self): + for scale in (0, -1, rig.SCALE_MAX_TAGS + 1, 2.5, "2048", True): + instance = self.instance() + with self.subTest(scale=scale), self.assertRaisesRegex(rig.RigError, "--scale"): + instance.seed(scale=scale) + instance.compose.assert_not_called() + + def test_scale_is_passed_to_the_seeder_as_its_environment(self): + instance = self.instance() + with self.assertRaises(StopIteration): + instance.seed(scale=2048) + arguments = instance.compose.call_args.args + self.assertEqual(arguments[:7], ("run", "--rm", "--no-deps", "--env", "GRPC_DATA_SCALE=2048", "seeder", "seed")) + + def test_scale_flag_is_seed_only(self): + with patch.object(rig, "LocalRig") as local, patch("sys.stderr"): + self.assertEqual(rig.main(["up", "--run-id", RUN, "--scale", "10"]), 2) + local.return_value.up.assert_not_called() + + def test_device_scale_block_covers_the_seed_bound(self): + sys.path.insert(0, str(Path(rig.__file__).resolve().parent / "device")) + import server + self.assertEqual(server.SCALE_COUNT, rig.SCALE_MAX_TAGS)