test(grpc-data): A2a — rig --conditions overlay (AlarmSubscribe exports + ScalarHigh scripted alarm), probe conditions scenario, conditions_smoke.py; X0/H2 tests move the 'future' bit off 64

This commit is contained in:
Joseph Doherty
2026-11-24 12:29:19 -05:00
parent 06c8740f94
commit 6572ee83bc
7 changed files with 168 additions and 9 deletions
@@ -0,0 +1,9 @@
# A2a condition-streaming smoke overlay (opt-in: `rig.py up --conditions`). Selects the seeder's conditions profile:
# SOURCE exports gain AlarmSubscribe and the SOURCE equipment gets one scripted alarm (`ScalarHigh`, scalar > 100).
# The dev DataConnections__ConditionKeySecret is already set on both source services in compose.yml.
# Without this file the rig is the unchanged v1 fixture.
services:
seeder:
environment:
GRPC_DATA_CONDITIONS: "1"
@@ -0,0 +1,34 @@
"""A2a condition-streaming live smoke on a `rig.py up --conditions` run (plan §9 A2; the full gate is A4).
Raises the SOURCE scripted alarm `ScalarHigh` (scalar register 20 := 150) through the device control API, then runs the
probe's `--scenario conditions` on both SOURCE data listeners: the Primary must stream a snapshot (total, records with
the active alarm, snapshot_complete) and, after the probe clears the alarm (scalar := 0), a delta record; the Secondary
must refuse the condition item (Primary-only). Evidence lands in the run's restricted `evidence/` folder.
"""
import argparse
import json
import sys
import time
import scenarios
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-id", required=True)
parser.add_argument("--settle-seconds", type=int, default=8)
arguments = parser.parse_args(argv)
runner = scenarios.ScenarioRunner(arguments.run_id)
runner.device("set", address=20, value=150)
time.sleep(arguments.settle_seconds)
output = runner.folder / "A2a-conditions-wire.json"
result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "conditions",
"--output", str(output)], "A2a-conditions-wire", timeout=240)
wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]}
runner.device("set", address=20, value=0)
print(json.dumps(wire, indent=2)[:20000])
return 0 if wire.get("passed") else 1
if __name__ == "__main__":
sys.exit(main())
+96 -2
View File
@@ -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")) throw new ArgumentException("Unsupported wire scenario.");
if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions")) 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()!;
@@ -251,7 +251,101 @@ try
}
}
}
if (scenario is not ("D13" or "history"))
if (scenario == "conditions")
{
// A2a smoke (opt-in conditions fixture): a root-scoped condition item on each SOURCE listener's UNS equipment root.
failurePhase = ProbeFailurePhase.WireOperation;
var unsUri = root.GetProperty("fixture").GetProperty("namespace_uris").GetProperty("uns").GetString()!;
var equipmentPath = arguments.GetValueOrDefault("--equipment", "area/line/plc");
var deviceUrl = endpoints.GetProperty("device.control").GetProperty("url").GetString()!;
using var http = new HttpClient();
async Task SetScalar(int value)
{
using var response = await http.PostAsync(deviceUrl + "/control", new StringContent(
JsonSerializer.Serialize(new { action = "set", address = 20, value }), System.Text.Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
}
var equipmentView = new W.View { Address = new() { OriginClusterId = "SOURCE", NamespaceUri = unsUri, IdentifierKind = "string",
Identifier = equipmentPath }, Realm = (int)DataRealm.Uns, Subject = equipmentPath };
static object Record(W.ConditionState r) => new
{
key = r.ConditionKey, r.Version, r.Removed, r.StateKnown, r.Active, r.Acknowledged, r.Severity, r.Message,
info = r.Info is null ? null : new { r.Info.ConditionType, r.Info.ConditionName, r.Info.SourceKind,
placements = r.Info.Placements.Select(p => p.Address.NamespaceUri + "|" + p.Address.Identifier).ToArray() },
};
foreach (var node in sourceNodes)
{
var name = node.Name;
failureTarget = name;
var nodeId = node.Value.GetProperty("node_id").GetString()!;
Metadata With(bool feature)
{
var headers = Headers(key, "Node", nodeId);
if (feature) headers.Add("x-otopcua-data-features", "conditions");
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 plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(false), DateTime.UtcNow.AddSeconds(20));
var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(true), DateTime.UtcNow.AddSeconds(20));
var capsOk = plain.Conditions is null && (plain.Operations & 64) == 0 && featured.Conditions is not null && (featured.Operations & 64) == 64;
var primary = featured.Serving.Role == "Primary";
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(90));
using var call = client.Subscribe(With(true), cancellationToken: cts.Token);
var open = new W.SubscriptionCommand { SubscriptionId = "conditions-" + name, StreamEpoch = 1, CommandId = "open-1",
AcknowledgementTimeoutTicks = TimeSpan.FromSeconds(10).Ticks, Open = new() { SessionLifetimeTicks = TimeSpan.FromMinutes(5).Ticks,
SnapshotBudget = new() { TimeoutTicks = TimeSpan.FromSeconds(20).Ticks, MaxItems = 8, MaxBytes = 4 * 1024 * 1024 } } };
open.Open.Items.Add(new W.SubscriptionItem { ClientItemId = "conditions", View = equipmentView,
Settings = new() { Trigger = 2 }, ConditionScope = new() { IncludeInfo = true } });
await call.RequestStream.WriteAsync(open);
int? ackStatus = null, total = null;
var snapshot = new List<W.ConditionState>();
var deltas = new List<W.ConditionState>();
var complete = false;
var frames = new List<string>();
var flipped = false;
while (await call.ResponseStream.MoveNext(cts.Token))
{
var frame = call.ResponseStream.Current;
frames.Add(frame.FrameCase.ToString());
if (frame.Ack is { } ack) { ackStatus = ack.Items.Single().Status; if (ackStatus != 1) break; continue; }
if (frame.ConditionStates is not { } states) continue;
if (states.IsSnapshot)
{
if (states.HasTotal) { total = states.Total; snapshot.Clear(); }
snapshot.AddRange(states.Items);
complete = states.SnapshotComplete;
if (complete && !flipped)
{
// The alarm was raised (scalar 150) before the stream opened; clear it now and wait for the delta.
flipped = true;
await SetScalar(0);
}
continue;
}
deltas.AddRange(states.Items);
if (deltas.Any(r => !r.Active && r.StateKnown)) break;
}
await cts.CancelAsync();
var leaked = snapshot.Concat(deltas).Any(r => Record(r).ToString()!.Contains("modbus/plc", StringComparison.Ordinal));
var passed = capsOk && (primary
? ackStatus == 1 && total >= 1 && complete && snapshot.Count == total && snapshot.Any(r => r.Active && r.StateKnown)
&& deltas.Any(r => !r.Active && r.StateKnown) && !leaked
: ackStatus == 6);
results.Add(new("conditions-" + name, "conditions", passed, primary ? 7 : 2, new()
{
["role"] = featured.Serving.Role,
["capabilities"] = new { withoutHeader = new { operations = plain.Operations, conditions = plain.Conditions?.ToString() },
withHeader = new { operations = featured.Operations, conditions = featured.Conditions?.ToString() } },
["ackStatus"] = ackStatus, ["total"] = total, ["snapshotComplete"] = complete,
["snapshot"] = snapshot.Select(Record).ToArray(), ["deltas"] = deltas.Select(Record).ToArray(),
["frames"] = frames, ["rawPathLeaked"] = leaked,
}));
if (primary && flipped) await SetScalar(150); // restore for the other node
}
}
if (scenario is not ("D13" or "history" or "conditions"))
{
var fixture = root.GetProperty("fixture");
var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!;
+10 -1
View File
@@ -675,6 +675,8 @@ class LocalRig:
files.extend(["--file", str(HERE / "compose.history.yml")])
if self.environment.get("GRPC_DATA_HISTORY_BACKEND") == "questdb":
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")])
return files
def compose(self, *args, timeout=120):
@@ -845,7 +847,7 @@ class LocalRig:
self.save(manifest)
return manifest
def up(self, timeout=600, history=False, history_backend="sqlserver"):
def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False):
import secrets
import credentials
if self.folder.exists():
@@ -870,6 +872,8 @@ class LocalRig:
raise RigError("unknown history backend")
settings["GRPC_DATA_HISTORY"] = "1"
settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend
if conditions:
settings["GRPC_DATA_CONDITIONS"] = "1"
atomic_write_secret(self.folder / "environment.json", json.dumps(settings))
self.environment.update(settings)
credentials.provision_tls(self.folder / "security", NODES[2:])
@@ -1337,6 +1341,7 @@ 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("--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,
help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB)")
@@ -1366,6 +1371,10 @@ def main(argv=None):
options["history_backend"] = arguments.history_backend
elif arguments.history_backend is not None:
raise RigError("--history-backend needs up --history")
if arguments.conditions:
if arguments.action != "up":
raise RigError("--conditions applies to up only; the run remembers it")
options["conditions"] = True
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
+13 -1
View File
@@ -29,6 +29,9 @@ const DataOperations operations = DataOperations.Browse | DataOperations.Metadat
// exports gain HistoryRead, and a second principal's export lacks it. Unset ⇒ the v1 fixture, unchanged.
var history = Environment.GetEnvironmentVariable("GRPC_DATA_HISTORY") == "1";
var grantedOperations = history ? operations | DataOperations.HistoryRead : operations;
// 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";
try
{
if (args.Length == 0) return 2;
@@ -372,6 +375,14 @@ try
db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = equipment, EquipmentUuid = uuid, UnsLineId = "source-line", Name = "plc", MachineCode = "fixture-plc" });
foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" }.Concat(history ? ["flt"] : []))
db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + name, EquipmentId = equipment, TagId = "source-" + name });
if (conditions)
{
const string predicate = "return Convert.ToInt32(ctx.GetTag(\"modbus/plc/scalar\").Value) > 100;";
db.Scripts.Add(new() { ScriptRowId = Guid.NewGuid(), ScriptId = "source-scalar-high", Name = "scalar-high", SourceCode = predicate,
SourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(predicate))) });
db.ScriptedAlarms.Add(new() { ScriptedAlarmRowId = Guid.NewGuid(), ScriptedAlarmId = "source-scalar-high", EquipmentId = equipment,
Name = "ScalarHigh", AlarmType = "AlarmCondition", MessageTemplate = "scalar high", PredicateScriptId = "source-scalar-high" });
}
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,
@@ -385,7 +396,8 @@ try
var rootKind = realm == DataRealm.Raw ? "RawDevice" : "Equipment";
var entity = realm == DataRealm.Raw ? "source-device" : equipment;
db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + name, ClusterId = "SOURCE", Enabled = true,
Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer", AllowedOperations = grantedOperations });
Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer",
AllowedOperations = grantedOperations | (conditions ? DataOperations.AlarmSubscribe : DataOperations.None) });
if (history)
db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + name + "-nohistory", ClusterId = "SOURCE", Enabled = true,
Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-nohistory", AllowedOperations = operations });
@@ -34,7 +34,8 @@ public sealed class GrpcDataHistoryClientTests
var results = await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken);
results.Single().StatusCode.ShouldBe(0x80720000u);
a.HistoryCalls.ShouldBe(0);
a.Headers.ShouldAllBe(x => x.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal) && x.Features == "history");
// A2a: the probe asks for every feature this consumer understands (history, conditions).
a.Headers.ShouldAllBe(x => x.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal) && x.Features == "history,conditions");
}
[Fact]
@@ -36,7 +36,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.AlarmConfirm | DataOperations.AlarmShelve);
var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe);
var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe);
var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmAcknowledge); // A2a: 64 is understood
// The pre-X0 runtime threw ArgumentException("Unknown operation.") here for the whole snapshot.
Should.NotThrow(() => runtime.Apply(new(1, "artifact-1", [history, plain, future])));
@@ -50,14 +50,14 @@ public sealed class GrpcDataUnknownOperationToleranceTests
runtime.DroppedUnknownOperations.ShouldBe(new Dictionary<string, DataOperations>(StringComparer.OrdinalIgnoreCase)
{
["history"] = DataOperations.AlarmConfirm | DataOperations.AlarmShelve,
["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe,
["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmAcknowledge,
});
runtime.UnknownOperationRowsDropped.ShouldBe(2);
// The production reader: the node diagnostics snapshot carries each row's dropped bits.
var diagnostics = runtime.CaptureDiagnostics().ToDictionary(x => x.ConnectionId);
diagnostics["history"].DroppedUnknownOperations.ShouldBe(DataOperations.AlarmConfirm | DataOperations.AlarmShelve);
diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None);
diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmSubscribe);
diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmAcknowledge);
diagnostics["plain"].MappingsWithDroppedOperations.ShouldBeNull("no mapping evidence was supplied");
// The input rows are not mutated: the drop is the node's reading, not a rewrite of the artifact.
history.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Browse | DataOperations.AlarmConfirm | DataOperations.AlarmShelve);
@@ -129,7 +129,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests
new() { DataExportId = "history", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster",
RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm },
new() { DataExportId = "alarms-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster",
RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge },
RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmConfirm | DataOperations.AlarmAcknowledge }, // A2a: 64 is understood
],
};
DataConnectionValidator.Validate(snapshot).ShouldContain(x => x.Code == "DataExportOperationsInvalid", "authoring still rejects reserved bits");