test(grpc-data): H2 live smoke on the standalone rig - denied-principal modes, pinned-build check, parity; evidence

This commit is contained in:
Joseph Doherty
2026-11-23 23:31:30 -05:00
parent a4cd2a4b0e
commit a3e2f13815
5 changed files with 147 additions and 18 deletions
+58 -1
View File
@@ -134,9 +134,66 @@ Not reproduced on master here (no second checkout from this worktree) — coordi
`IDataHistoryService.ReadAsync` with the same window ⇒ the same rows/statuses as step 3 / an OPC UA historyread on the
origin node.
## Live smoke (rig)
Run `h2-history-smoke`, 2026-11-24 04:17–04:33 UTC, standalone rig (`scripts/validation/grpc-data`, OrbStack), not docker-dev.
**Build inputs:** HEAD `eb29360d4` plus the review-2 work then uncommitted in the worktree
(`LocalDataServices.History.cs`, `OpcUaServer.csproj`; diff SHA-256 `b1e0fda7…`); recorded `source_tree_hash` `fff3094c6d2dd694…`.
The branch moved on during the run (`808e1fe98`…`1d824da12`), so every smoke step ran with
`history_smoke.py --pinned-build`: the running Host stamps were checked against the run's RECORDED hash, not the moved checkout.
**Harness (opt-in, v1 runs unchanged):** `rig.py up --history` records `GRPC_DATA_HISTORY=1` and adds `compose.history.yml`.
SOURCE gets `ServerHistorian:Backend=SqlServer` (schema `hist`, auto-created, in the run's own SQL container) and continuous
historization. The seeder's history profile does four things. Raw `counter` is `isHistorized`; `scalar` is not. `consumer-source` and
`export-raw`/`export-uns` gain HistoryRead (63); mappings keep 31. A second principal `fixture-nohistory` gets its own key
(`seed/source-nohistory.key`) and exports with 31. The probe has a `--scenario history` (raw origin RPCs with the rig headers)
and a `history` operation (`IDataHistoryService` through whatever connection holds it). `history_smoke.py` advances the counter
1/s for 40 s, then runs the probe, the CLI `historyread` and the consumer node probe.
```bash
python3 scripts/validation/grpc-data/rig.py up --run-id h2-history-smoke --history --timeout 900
python3 scripts/validation/grpc-data/rig.py seed --run-id h2-history-smoke
python3 scripts/validation/grpc-data/rig.py deploy --run-id h2-history-smoke --timeout 300 # 2nd attempt, see notes
python3 scripts/validation/grpc-data/history_smoke.py --run-id h2-history-smoke --pinned-build --label export-denied --denied-expect permission-denied
# then: NodeAcl source-peer-nohistory := 135 (ReadOnly − HistoryRead, sqlcmd -I) + mutate export-raw-nohistory → 63 + deploy
python3 scripts/validation/grpc-data/history_smoke.py --run-id h2-history-smoke --pinned-build --label acl-denied --denied-expect unsupported
# D01 + D03 via ScenarioRunner.run (same pinned check), then:
python3 scripts/validation/grpc-data/rig.py down --run-id h2-history-smoke
```
| # | Recipe item | Observed | Result |
|---|---|---|---|
| 1 | `GetCapabilities` with / without `x-otopcua-data-features: history` (both SOURCE listeners) | without header: `operations` 31 (source-1 Primary) / 23 (source-2 Secondary, no Write), no field 16, 158/160 B. With header: 63 / 55, field 16 = `{raw, processed, atTime, 19 aggregates, resolution 1 tick, maxValuesPerPage 10000, maxConcurrentReads 4, idle 600000000 ticks}`. Otherwise identical | PASS |
| 2 | Raw `end=now, num_values_per_node=5` on `modbus/plc/counter` | `0x00000000`, 5 values newest first (80…76, 1 s apart) + continuation. Resume ⇒ `0x00000000`, 75…71, older than page 1. Resuming the same token again ⇒ `0x804A0000`, no samples, no continuation. Same on both SOURCE nodes; the last token released | PASS |
| 3a | Unhistorized `modbus/plc/scalar` | `0x80720000`, no samples, continuation or diagnostic; encoded item (correlation id cleared) `108080C88308` | PASS |
| 3b | Second key, export without HistoryRead | **RPC `PERMISSION_DENIED`**, not a per-item `0x80720000` (see "Recipe mismatch") | differs from recipe; consistent with review fix 2 |
| 3c | Second key, export with HistoryRead, origin ACL without it | `0x80720000`, **byte-identical** to 3a (`108080C88308`) on both nodes | PASS |
| 3d | Without the feature header | `FAILED_PRECONDITION` | PASS |
| 4 | Values vs OPC UA `historyread` on the SOURCE node (Client CLI, `ns=2;s=modbus/plc/counter`, same second-aligned window) | 29 values (first run) and 30 (second). The probe's forward Raw (`num_values_per_node=0`) on each SOURCE listener and the consumer reads match the CLI rows exactly (source timestamp to the µs, value, quality). CLI on `scalar` ⇒ `BadHistoryOperationUnsupported (0x80720000)` | PASS |
| 5 | Runtime consumer: CONSUMER node probe, deployed `consumer-source` lease (Cluster/Primary) → `IDataHistoryService.ReadAsync` | on consumer-1 and consumer-2, Raw and UNS (`area/line/plc/counter`): newest 5 = the same 80…76 / 120…116 as item 2, plus a continuation; resume Good. Window = the CLI rows (parity above). `scalar` ⇒ `0x80720000`. Lease capabilities carry `History` + bit 32 | PASS |
| 6 | v1 scenarios with history enabled | D01 PASS (48 assertions); D03 PASS (377: Cluster + Node, raw + uns, recursive browse, read parity, subscribe on CONSUMER). Both restored baseline | PASS |
Teardown: `rig.py down` removed every run-labelled container, network, volume and image. Label-filtered `docker … ls` afterwards: 0/0/0/0.
**Recipe mismatch (not a code change; for the coordinator).** The recipe (step 3 above) and `DataConnections.md` ("not exported, denied … answers the
same `BadHistoryOperationUnsupported`") say that a key whose **export** lacks HistoryRead gets the per-item
`0x80720000`. Live, the RPC is refused with `PERMISSION_DENIED` before any item is evaluated. This is review fix 2
(`Ready(…, HistoryRead)` ⇒ PermissionDenied with no export grant, like v1 Read). It is per-principal and node-independent,
so it does not separate unhistorized nodes from denied ones. The per-node indistinguishability holds where it matters (3c). The
recipe/doc wording should say "export grant missing ⇒ `PERMISSION_DENIED`; ACL-denied / unhistorized / unknown ⇒ identical
`0x80720000`".
**Observed on the pre-review2-7a build.** For the no-grant principal, the capabilities still carried field 16 with the full
aggregate list and resolution (`operations` 31, no bit 32). `808e1fe98` (review2-7a, landed after this build) addresses exactly that.
It was not re-verified live.
**Harness note.** The first `deploy` straight after `seed` timed out with 0/6 acks. CONTROL logged "No mesh gRPC targets —
dropping DispatchDeployment": its contact refresh had not yet seen the freshly seeded `ClusterNode` rows. The same ~65 s
refresh appears in the README's D07 note. An immediate re-deploy applied on all six nodes. Pre-existing; it does not depend on history.
## Not verified
- The docker-dev smoke above (coordinator-run).
- The docker-dev smoke above (coordinator-run). The standalone-rig smoke is under "Live smoke (rig)".
- The real `OriginHistoryPort` behind the gRPC service end to end: the wire suite fakes the port; the port facade is
tested against a real node manager separately (`OriginHistoryPortTests`).
- A consumer projection (H3) receiving negotiated metadata with bit 32/`HistoryInfo` from an H2 origin: covered only by
+10
View File
@@ -83,6 +83,16 @@ prune or prefix-based deletion. Interrupted setup leaves a restricted ownership
journal that enables the same cleanup. Run files are retained for evidence;
use a new run ID for another run.
## H2 history profile (opt-in)
`rig.py up --run-id <id> --history` adds `compose.history.yml`. SOURCE gets a SqlServer historian (schema `hist` in the
run's SQL container) and continuous historization. The seeder's history profile historizes Raw `counter`, adds HistoryRead to
the consumer's connection and exports, and seeds a second principal `fixture-nohistory`. That principal gets its own key
(`credentials.data_key_files.source_nohistory`), exports without HistoryRead and an origin ACL without HistoryRead.
`python3 scripts/validation/grpc-data/history_smoke.py --run-id <id>` runs the H2 smoke. It advances the counter, then exercises
the probe's `--scenario history` origin RPCs, the CLI `historyread` and the CONSUMER `history` node-probe operation, and checks
value parity. Without `--history` the rig, the seed and every D-scenario are unchanged.
## Scenario authoring and node probes
The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its
+60 -12
View File
@@ -23,27 +23,61 @@ def _iso(moment):
def _cli_rows(stdout):
"""`historyread` rows → [(source time ISO, value text, status text)]."""
"""`historyread` rows (`<source time O> <value> <Good|Bad|Uncertain>`) → [(UTC datetime, value text, quality)]."""
rows = []
for line in stdout.splitlines():
match = re.match(r"^\s*(\d{4}-\d{2}-\d{2}[T ][0-9:.]+Z?)\s*\|?\s*(.*)$", line)
if match:
rows.append((match[1], match[2].strip()))
parts = line.split()
if len(parts) == 3 and parts[2] in {"Good", "Bad", "Uncertain"} and re.match(r"^\d{4}-\d{2}-\d{2}T", parts[0]):
rows.append((_parse(parts[0]), parts[1], parts[2]))
return rows
def _parse(text):
"""ISO 8601 with up to 7 fractional digits → aware datetime truncated to microseconds."""
match = re.match(r"^(.*?T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$", text)
fraction = (match[2] or "")[:6].ljust(6, "0")
zone = match[3] or "Z"
return datetime.fromisoformat(match[1] + "." + fraction + ("+00:00" if zone == "Z" else zone))
def _wire_rows(samples):
rows = []
for sample in samples:
value = json.loads(sample["value"])
scalar = next(v for k, v in value.items() if k != "kind")
rows.append((_parse(sample["sourceTimestampUtc"]), str(scalar), "Good" if int(sample["statusCode"], 16) >> 30 == 0 else "Other"))
return rows
def compare(cli_stdout, wire_samples):
cli, wire = _cli_rows(cli_stdout), _wire_rows(wire_samples)
return {"cli_count": len(cli), "wire_count": len(wire), "identical": cli == wire and len(cli) > 0,
"first": [str(x) for x in (cli[:1] + wire[:1])], "last": [str(x) for x in (cli[-1:] + wire[-1:])]}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-id", required=True)
parser.add_argument("--accumulate-seconds", type=int, default=40)
parser.add_argument("--denied-expect", choices=("permission-denied", "unsupported"), default="permission-denied",
help="the second principal: export lacks HistoryRead (RPC PermissionDenied) or export granted + ACL denies (per-item 0x80720000)")
parser.add_argument("--label", default="smoke", help="evidence file suffix")
parser.add_argument("--pinned-build", action="store_true",
help="the checkout moved after `up`: verify the running Host stamps against the run's RECORDED build hash "
"instead of the current checkout (recorded in the report; tools publish from the current checkout)")
arguments = parser.parse_args(argv)
current_hash = rig.source_tree_hash()
if arguments.pinned_build:
recorded = scenarios.restricted_json(rig.LocalRig(arguments.run_id).path)["source_tree_hash"]
rig.source_tree_hash = lambda: recorded
runner = scenarios.ScenarioRunner(arguments.run_id)
if runner.manifest["fixture"].get("history") is None:
raise SystemExit("run was not brought up with --history")
runner.active, runner.deadline = "H2", time.monotonic() + 900
runner.publish()
report = {"run_id": arguments.run_id, "source_revision": runner.manifest.get("source_revision"),
"source_tree_hash": runner.manifest.get("source_tree_hash"), "items": {}}
report = {"denied_expect": arguments.denied_expect, "run_id": arguments.run_id, "source_revision": runner.manifest.get("source_revision"),
"source_tree_hash": runner.manifest.get("source_tree_hash"), "checkout_tree_hash_at_smoke": current_hash,
"pinned_build": arguments.pinned_build, "items": {}}
# 1. Accumulate history: one counter step per second.
started = datetime.now(timezone.utc)
@@ -58,10 +92,11 @@ def main(argv=None):
"window": [_iso(window_start), _iso(window_end)], "device": runner.device()}
# 2. Origin RPCs on both SOURCE data listeners.
output = runner.folder / "H2-history-wire.json"
output = runner.folder / ("H2-history-wire-" + arguments.label + ".json")
result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "history",
"--history-start", _iso(window_start), "--history-end", _iso(window_end), "--output", str(output)],
"H2-history-wire", timeout=120)
"--history-start", _iso(window_start), "--history-end", _iso(window_end),
"--denied-expect", arguments.denied_expect, "--output", str(output)],
"H2-history-wire-" + arguments.label, timeout=120)
wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]}
report["items"]["wire"] = wire
@@ -99,10 +134,23 @@ def main(argv=None):
observed[name] = {"passed": False, "error": type(error).__name__ + ": " + str(error)}
consumer[node] = observed
report["items"]["consumer"] = consumer
runner.save("H2-history-smoke.json", report)
print(json.dumps({"saved": str(runner.folder / "H2-history-smoke.json"), "wire_passed": wire.get("passed"),
# 5. Value parity: OPC UA historyread on the SOURCE node vs the remote origin read vs the runtime consumer, same window.
parity = {}
for result_row in wire.get("results", []):
if result_row["id"].startswith("history-window-"):
node = result_row["id"][len("history-window-"):]
parity["wire-" + node + "-vs-cli-" + node] = compare(cli[node]["stdout"], result_row["observations"]["samples"])
for node, rows in consumer.items():
if rows["window"]["passed"]:
samples = rows["window"]["observations"]["pages"][0]["samples"]
parity["consumer-" + node + "-vs-cli-source-1"] = compare(cli["source-1"]["stdout"], samples)
report["items"]["parity"] = parity
runner.save("H2-history-" + arguments.label + ".json", report)
print(json.dumps({"saved": str(runner.folder / ("H2-history-" + arguments.label + ".json")), "wire_passed": wire.get("passed"),
"consumer": {node: {k: v["passed"] for k, v in rows.items()} for node, rows in consumer.items()},
"cli": {node: row["returncode"] for node, row in cli.items()}}, indent=2))
"cli": {node: row["returncode"] for node, row in cli.items()},
"parity": {k: v["identical"] for k, v in parity.items()}}, indent=2))
return 0
+16 -4
View File
@@ -209,17 +209,29 @@ try
["serving"] = featured.Serving.ToString(),
}));
// 3. Unhistorized tag and the no-HistoryRead principal answer the same bytes; no header ⇒ FAILED_PRECONDITION.
// --denied-expect: `permission-denied` (the second principal's export lacks HistoryRead ⇒ RPC refused) or
// `unsupported` (export granted, origin ACL denies ⇒ per-item, byte-identical to the unhistorized answer).
var deniedExpect = arguments.GetValueOrDefault("--denied-expect", "unsupported");
var unhist = (await client.HistoryReadAsync(Raw(View(unhistorized), null), With(key, true), deadline())).Items.Single();
var denied = (await client.HistoryReadAsync(Raw(View(historized), null), With(otherKey, true), deadline())).Items.Single();
var identical = Shape(unhist).AsSpan().SequenceEqual(Shape(denied));
W.HistoryReadResult? denied = null;
string? deniedRpc = null;
try { denied = (await client.HistoryReadAsync(Raw(View(historized), null), With(otherKey, true), deadline())).Items.Single(); }
catch (RpcException error) { deniedRpc = error.StatusCode.ToString(); }
var otherCaps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(otherKey, true), deadline());
var identical = denied is not null && Shape(unhist).AsSpan().SequenceEqual(Shape(denied));
var deniedOk = deniedExpect == "permission-denied"
? deniedRpc == "PermissionDenied"
: denied is not null && denied.StatusCode == 0x80720000u && identical;
string? precondition = null;
try { await client.HistoryReadAsync(Raw(View(historized), null), With(key, false), deadline()); precondition = "OK"; }
catch (RpcException error) { precondition = error.StatusCode.ToString(); }
results.Add(new("history-refusals-" + name, "history-refusals",
unhist.StatusCode == 0x80720000u && denied.StatusCode == 0x80720000u && identical && precondition == "FailedPrecondition", 4, new()
unhist.StatusCode == 0x80720000u && deniedOk && precondition == "FailedPrecondition", 3, new()
{
["unhistorized"] = new { statusCode = Hex(unhist.StatusCode), unhist.Samples.Count, unhist.HasContinuation, unhist.HasDiagnostic, bytes = Convert.ToHexString(Shape(unhist)) },
["deniedPrincipal"] = new { statusCode = Hex(denied.StatusCode), denied.Samples.Count, denied.HasContinuation, denied.HasDiagnostic, bytes = Convert.ToHexString(Shape(denied)) },
["deniedExpect"] = deniedExpect,
["deniedPrincipal"] = denied is null ? new { rpcStatus = deniedRpc } : (object)new { statusCode = Hex(denied.StatusCode), denied.Samples.Count, denied.HasContinuation, denied.HasDiagnostic, bytes = Convert.ToHexString(Shape(denied)) },
["deniedPrincipalCapabilities"] = new { operations = otherCaps.Operations, historyPresent = otherCaps.History is not null },
["byteIdentical"] = identical,
["withoutFeatureHeader"] = precondition,
}));
+3 -1
View File
@@ -379,8 +379,10 @@ try
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = operations, WriteThrough = true });
}
if (history)
// The second principal's origin ACL also lacks HistoryRead: with its export's HistoryRead off the RPC is refused
// (PermissionDenied, like v1 Read); granting the export bit then leaves the per-node ACL denial (BadHistoryOperationUnsupported).
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer-nohistory", ClusterId = "SOURCE", Principal = "fixture-nohistory",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin });
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.ReadOnly & ~NodePermissions.HistoryRead });
await db.SaveChangesAsync();
}
var seedAdmin = new ApiKeyAdminService(factory, pepper);