test(grpc-data): A2b smoke — conditions profile grants the method bits; probe remote ack (+ duplicate, header-less, Secondary); origin CLI alarms watcher counts exactly one ack

This commit is contained in:
Joseph Doherty
2026-11-24 13:55:45 -05:00
parent e29d9559ad
commit d63884e624
3 changed files with 81 additions and 10 deletions
@@ -4,9 +4,17 @@ Raises the SOURCE scripted alarm `ScalarHigh` (scalar register 20 := 150) throug
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.
A2b: on the Primary the probe also acknowledges the active alarm REMOTELY (`CallConditionMethod`, with a duplicate of the
same operation id and a header-less attempt) and requires the stream to carry exactly one acked delta before it clears the
alarm; the Secondary must answer RejectedBeforeDispatch. Meanwhile the CLI's `alarms` subscription on the SOURCE Primary's
OPC UA endpoint records the origin's OWN events: exactly one `Active, Acknowledged` event for ScalarHigh must appear.
"""
import argparse
import json
import os
import signal
import subprocess
import sys
import time
@@ -23,6 +31,14 @@ def main(argv=None):
runner.publish()
runner.device("set", address=20, value=150)
time.sleep(arguments.settle_seconds)
# The origin's own subscriber: the CLI `alarms` (Server object, ConditionRefresh) on the SOURCE Primary.
primary = runner.primary("source")
alarms_log = runner.folder / "A2b-origin-alarms.txt"
descriptor = os.open(alarms_log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
watcher = subprocess.Popen(["dotnet", str(runner.cli_dll), "alarms", "-u", runner.endpoint(primary), "-U", "apikey", "-P", runner.key,
"--refresh", "-i", "250"], stdout=descriptor, stderr=subprocess.STDOUT, start_new_session=True)
os.close(descriptor)
time.sleep(8)
output = runner.folder / "A2a-conditions-wire.json"
result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "conditions",
# The UNS export root is the equipment, addressed by its catalog identifier (the EquipmentId).
@@ -30,9 +46,22 @@ def main(argv=None):
"--subject", runner.manifest["fixture"]["browse_subjects"]["uns"],
"--output", str(output)], "A2a-conditions-wire", timeout=240)
wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]}
time.sleep(4)
watcher.send_signal(signal.SIGINT)
try:
watcher.wait(timeout=20)
except subprocess.TimeoutExpired:
watcher.kill()
watcher.wait(timeout=10)
runner.device("set", address=20, value=0)
blocks = [b for b in alarms_log.read_text(errors="replace").split("\n\n") if "Condition: ScalarHigh" in b]
states = [line.split(":", 1)[1].strip() for b in blocks for line in b.splitlines() if line.strip().startswith("State:")]
origin = {"primary": primary, "scalar_high_events": len(blocks), "states": states,
"active_acknowledged_events": states.count("Active, Acknowledged")}
wire["origin_subscriber"] = origin
wire["passed"] = bool(wire.get("passed")) and origin["active_acknowledged_events"] == 1
print(json.dumps(wire, indent=2)[:20000])
return 0 if wire.get("passed") else 1
return 0 if wire["passed"] else 1
if __name__ == "__main__":
+49 -8
View File
@@ -307,6 +307,29 @@ try
var complete = false;
var frames = new List<string>();
var flipped = false;
// A2b: on the Primary, a remote Acknowledge of the active alarm (once the snapshot is complete), a duplicate of the
// same operation id (joins), and the same call without the header (FAILED_PRECONDITION); on the Secondary the
// call is RejectedBeforeDispatch (Primary-only).
object? ackEvidence = null;
var acked = false;
var ackSent = false;
async Task<object> RemoteAck(W.View placement, W.ActivationMarker marker)
{
var request = new W.ConditionMethodRequest
{
OperationId = "a2b-ack-" + name, Placement = placement, Method = 1,
ExpectedActivation = marker, Comment = "A2b remote ack",
ExpectedServingIncarnation = featured.Serving.Incarnation, RemainingBudgetTicks = TimeSpan.FromSeconds(10).Ticks,
OnBehalfOf = "probe\u0007operator",
};
var first = await client.CallConditionMethodAsync(request, With(true), DateTime.UtcNow.AddSeconds(15));
var again = await client.CallConditionMethodAsync(request, With(true), DateTime.UtcNow.AddSeconds(15));
string? headerless;
try { await client.CallConditionMethodAsync(request, With(false), DateTime.UtcNow.AddSeconds(15)); headerless = "OK"; }
catch (RpcException ex) { headerless = ex.StatusCode.ToString(); }
return new { first = new { first.State, first.StatusCode, first.Diagnostic }, duplicate = new { again.State, again.StatusCode },
duplicateEqual = first.Equals(again), headerless, firstState = first.State };
}
while (await call.ResponseStream.MoveNext(cts.Token))
{
var frame = call.ResponseStream.Current;
@@ -318,22 +341,40 @@ try
if (states.HasTotal) { total = states.Total; snapshot.Clear(); }
snapshot.AddRange(states.Items);
complete = states.SnapshotComplete;
if (complete && !flipped)
if (complete && !ackSent && snapshot.FirstOrDefault(r => r.Active && r.Info is not null) is { } target)
{
// The alarm was raised (scalar 150) before the stream opened; clear it now and wait for the delta.
flipped = true;
await SetScalar(0);
ackSent = true;
ackEvidence = await RemoteAck(target.Info.Placements[0], target.Activation);
}
continue;
}
deltas.AddRange(states.Items);
if (deltas.Any(r => !r.Active && r.StateKnown)) break;
if (!acked && deltas.Any(r => r.Active && r.Acknowledged && r.StateKnown))
{
// The stream carried the acked delta; now clear the alarm (scalar := 0) and wait for the inactive delta.
acked = true;
flipped = true;
await SetScalar(0);
continue;
}
if (acked && deltas.Any(r => !r.Active && r.StateKnown)) break;
}
await cts.CancelAsync();
// The Secondary never streams (ack Unavailable): its call is refused at the Primary check, before placement lookup.
if (!primary && ackEvidence is null)
ackEvidence = await RemoteAck(equipmentView, new W.ActivationMarker { Incarnation = "none", Sequence = 0 });
var leaked = snapshot.Concat(deltas).Any(r => Record(r).ToString()!.Contains("modbus/plc", StringComparison.Ordinal));
var passed = capsOk && (primary
var ackJson = JsonSerializer.SerializeToElement(ackEvidence);
var methodState = ackEvidence is null ? -1 : ackJson.GetProperty("firstState").GetInt32();
var methodsOk = (featured.Operations & 384) == 384 && (plain.Operations & 384) == 0 && ackEvidence is not null
&& ackJson.GetProperty("headerless").GetString() == "FailedPrecondition"
&& (primary
? methodState == 4 && ackJson.GetProperty("duplicateEqual").GetBoolean()
&& deltas.Count(r => r.Active && r.Acknowledged) == 1
: methodState == 1);
var passed = capsOk && methodsOk && (primary
? ackStatus == 1 && total >= 1 && complete && snapshot.Count == total && snapshot.Any(r => r.Active && r.StateKnown)
&& deltas.Any(r => !r.Active && r.StateKnown) && !leaked
&& acked && deltas.Any(r => !r.Active && r.StateKnown) && !leaked
: ackStatus == 6);
results.Add(new("conditions-" + name, "conditions", passed, primary ? 7 : 2, new()
{
@@ -342,7 +383,7 @@ try
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,
["frames"] = frames, ["rawPathLeaked"] = leaked, ["remoteAck"] = ackEvidence,
}));
if (primary && flipped) await SetScalar(150); // restore for the other node
}
+2 -1
View File
@@ -397,7 +397,8 @@ try
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 | (conditions ? DataOperations.AlarmSubscribe : DataOperations.None) });
// A2b: the conditions profile also grants the remote condition methods (Acknowledge/AddComment, Confirm).
AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : 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 });