#!/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())