fix(alarms): AdminUI /alerts ack/shelve reports the scripted engine's verdict (#950)

The /alerts buttons went central->node fire-and-forget and always showed
"Ack sent". AdminOperationsActor now spawns a per-request
AlarmCommandVerdictCollector (7 s window, under the client's 10 s ask) that
sends the command with AlarmCommand.VerdictRequested and gathers each node's
answer, finishing early once every node it sent to has answered.

- gRPC plane: CentralCommunicationActor tells the collector the dialled
  ClusterNode set and one verdict per node. A node handles a
  verdict_requested AlarmCommandMessage by asking its driver host
  (ScriptedAlarmHostActor.ExecuteAlarmCommand, the #937 path, no ask deadline,
  bounded 5 s) and returns it in the ADDITIVE ExecuteAck.alarm_verdict.
  Transport failure / timeout / empty ack (pre-#950 node) => that node unknown.
- DPS: published with the collector as sender; each ScriptedAlarmHostActor
  answers (non-owners NotOwned); expected set = Up driver members.
- Aggregation: any owner applied => Applied (partial noted); else any
  unknown/silent node => Outcome unknown (never "refused"); else owner
  refusal => Refused: <reason>; else no owner => Not applied.
- UI: green Applied / red Refused (reason) / amber Outcome unknown, per-node
  detail in the details pane; a verdict-less reply (validation, server fault,
  pre-#950 singleton) renders as before.

Wire is back-compatible both ways (new proto fields only; VerdictRequested and
NotOwned default false). Real-wire test through the real router, dialer,
interceptor and NodeCommandGrpcService (red without the node change).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-01 19:45:17 -05:00
parent 6b60845931
commit 09aaabbeef
28 changed files with 1451 additions and 72 deletions
@@ -42,6 +42,9 @@ public sealed class AdminOperationsActor : ReceiveActor
private readonly ILoggingAdapter _log = Context.GetLogger();
/// <summary>#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts.</summary>
private readonly TimeSpan _alarmVerdictWindow;
/// <summary>The StartDeployment whose compose is running off-actor, or null. See <see cref="HandleStartDeployment"/>.</summary>
private StartDeployment? _composeInFlight;
@@ -55,6 +58,7 @@ public sealed class AdminOperationsActor : ReceiveActor
/// DistributedPubSub mediator directly (the behaviour before the per-cluster mesh).
/// </param>
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
/// <param name="alarmVerdictWindow">#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts; defaults to <see cref="AlarmCommandVerdictCollector.DefaultWindow"/>.</param>
/// <returns>Props configured to create an AdminOperationsActor.</returns>
public static Props Props(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
@@ -62,9 +66,10 @@ public sealed class AdminOperationsActor : ReceiveActor
IEnumerable<IDriverProbe> probes,
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
IActorRef? meshRouter = null,
TimeSpan? applyDeadline = null) =>
TimeSpan? applyDeadline = null,
TimeSpan? alarmVerdictWindow = null) =>
Akka.Actor.Props.Create(() =>
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline));
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, alarmVerdictWindow));
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
/// <param name="dbFactory">Factory for creating config database contexts.</param>
@@ -73,14 +78,17 @@ public sealed class AdminOperationsActor : ReceiveActor
/// <param name="tagConfigValidationMode">Deploy-gate TagConfig strictness mode (Warn default | Error opt-in).</param>
/// <param name="meshRouter">Central comm actor, or <see langword="null"/> for the mediator.</param>
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
/// <param name="alarmVerdictWindow">#950: the <c>/alerts</c> verdict collection window.</param>
public AdminOperationsActor(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
IActorRef coordinator,
IEnumerable<IDriverProbe> probes,
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
IActorRef? meshRouter = null,
TimeSpan? applyDeadline = null)
TimeSpan? applyDeadline = null,
TimeSpan? alarmVerdictWindow = null)
{
_alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow;
// The same source the coordinator's default reads (ConfigPublishCoordinator.DefaultApplyDeadline IS
// DeployTimings.ApplyDeadline), so the lost-dispatch closure and the coordinator's own deadline agree.
_applyDeadline = applyDeadline ?? DeployTimings.ApplyDeadline;
@@ -134,13 +142,21 @@ public sealed class AdminOperationsActor : ReceiveActor
else DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(topic, message));
}
/// <summary>
/// #950: spawns the per-request verdict collector, which sends <paramref name="command"/> (via the mesh router, or
/// DistributedPubSub when none is wired) and answers <paramref name="replyTo"/> with <paramref name="reply"/>.
/// </summary>
private void CollectVerdict(AlarmCommand command, IActorRef replyTo, Func<AlarmCommandFleetOutcome, object> reply) =>
Context.ActorOf(AlarmCommandVerdictCollector.Props(command, _meshRouter, replyTo, reply, _alarmVerdictWindow));
/// <summary>
/// AdminUI Acknowledge path. Maps the control-plane command to a
/// <see cref="AlarmCommand"/> (<c>Operation = "Acknowledge"</c>) and publishes it onto the
/// cluster <c>alarm-commands</c> topic. The broadcast lands on every driver node's
/// <c>ScriptedAlarmHostActor</c>; only the node owning the alarm acts (ownership filter), so the
/// admin singleton needs no knowledge of placement. Synchronous — the publish is fire-and-forget
/// via the mediator, so there is no awaitable work and no DB write.
/// <see cref="AlarmCommand"/> (<c>Operation = "Acknowledge"</c>) and hands it to an
/// <see cref="AlarmCommandVerdictCollector"/>, which sends it to every driver node (the ownership filter on each
/// node's <c>ScriptedAlarmHostActor</c> decides who acts, so the admin singleton needs no knowledge of placement),
/// collects each node's verdict within a bounded window and replies Applied / Refused (reason) / Outcome unknown
/// (#950 — this was a fire-and-forget publish that always answered "sent"). The mailbox is not held: the collector
/// is a child actor that answers the requester itself.
/// </summary>
private void HandleAcknowledgeAlarm(AcknowledgeAlarmCommand msg)
{
@@ -154,10 +170,10 @@ public sealed class AdminOperationsActor : ReceiveActor
Comment: msg.Comment,
UnshelveAtUtc: null);
Dispatch(AlarmCommandsTopic.Name, alarmCmd);
_log.Info("AdminOps: Acknowledge published for alarm {AlarmId} by {User}", msg.AlarmId, msg.User);
replyTo.Tell(new AcknowledgeAlarmResult(true, null, msg.CorrelationId));
var correlationId = msg.CorrelationId;
CollectVerdict(alarmCmd, replyTo, o => new AcknowledgeAlarmResult(
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
_log.Info("AdminOps: Acknowledge sent for alarm {AlarmId} by {User}; collecting node verdicts", msg.AlarmId, msg.User);
}
catch (Exception ex)
{
@@ -170,8 +186,8 @@ public sealed class AdminOperationsActor : ReceiveActor
/// AdminUI Shelve / Unshelve path. Maps <see cref="ShelveAlarmCommand.Kind"/> to the matching
/// <see cref="AlarmCommand"/> operation (<c>OneShotShelve</c> / <c>TimedShelve</c> /
/// <c>Unshelve</c>), threading <see cref="ShelveAlarmCommand.UnshelveAtUtc"/> for the timed kind,
/// and publishes onto the cluster <c>alarm-commands</c> topic. Ownership filtering happens on the
/// owning node exactly as for Acknowledge.
/// and sends it exactly as <see cref="HandleAcknowledgeAlarm"/> does — ownership filtered on the nodes, verdicts
/// collected and reported (#950).
/// </summary>
private void HandleShelveAlarm(ShelveAlarmCommand msg)
{
@@ -201,10 +217,10 @@ public sealed class AdminOperationsActor : ReceiveActor
Comment: msg.Comment,
UnshelveAtUtc: unshelveAt);
Dispatch(AlarmCommandsTopic.Name, alarmCmd);
_log.Info("AdminOps: {Operation} published for alarm {AlarmId} by {User}", operation, msg.AlarmId, msg.User);
replyTo.Tell(new ShelveAlarmResult(true, null, msg.CorrelationId));
var correlationId = msg.CorrelationId;
CollectVerdict(alarmCmd, replyTo, o => new ShelveAlarmResult(
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
_log.Info("AdminOps: {Operation} sent for alarm {AlarmId} by {User}; collecting node verdicts", operation, msg.AlarmId, msg.User);
}
catch (Exception ex)
{
@@ -0,0 +1,310 @@
using System.Text;
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
/// <summary>
/// #950: router → collector. Which nodes an AdminUI alarm command went to — the set the
/// <see cref="AlarmCommandVerdictCollector"/> waits on.
/// </summary>
/// <param name="Nodes">
/// The nodes expected to answer (gRPC: the dialled <c>ClusterNode</c> ids; DistributedPubSub: the Up <c>driver</c>
/// members' <c>host:port</c>). Empty with a null <paramref name="NotDeliveredReason"/> ⇒ the set is unknown and the
/// collector waits out its window.
/// </param>
/// <param name="NotDeliveredReason">Set when the command reached no node at all (no targets, no dialer, unencodable).</param>
public sealed record AlarmVerdictFanOut(IReadOnlyList<string> Nodes, string? NotDeliveredReason = null);
/// <summary>#950: one node's answer to an AdminUI alarm command, as the gRPC router saw it.</summary>
/// <param name="Node">The node (its <c>ClusterNode</c> id).</param>
/// <param name="Outcome">Its verdict; transport failures and pre-#950 nodes arrive as <see cref="AlarmCommandVerdict.OutcomeUnknown"/>.</param>
public sealed record AlarmNodeVerdict(string Node, AlarmCommandOutcome Outcome);
/// <summary>#950: the fleet-wide verdict on one AdminUI alarm command.</summary>
/// <param name="Verdict">Applied when any owning node applied it; OutcomeUnknown when none did but one may have; else NotApplied.</param>
/// <param name="Summary">Short operator-facing text (the <c>/alerts</c> result chip).</param>
/// <param name="Detail">Per-node breakdown (the result's details pane).</param>
public sealed record AlarmCommandFleetOutcome(AlarmCommandVerdict Verdict, string Summary, string Detail);
/// <summary>
/// #950: folds the per-node answers to one AdminUI alarm command into the verdict the operator sees.
/// </summary>
/// <remarks>
/// <para>
/// Every driver node receives the command and only the alarm's owners act — two in a redundant pair, each with its
/// own engine (the condition state is then replicated last-writer-wins). So: <b>any owner applied ⇒ Applied</b>
/// (other owners' refusals/unknowns are listed, and the summary says it was partial); otherwise <b>any unknown — an
/// owner that timed out, a node that did not answer, a transport failure, a pre-#950 node — ⇒ OutcomeUnknown</b>,
/// never "refused", because that node may still apply it; otherwise an owner's refusal ⇒ NotApplied with its
/// reason; otherwise no node owns the alarm ⇒ NotApplied.
/// </para>
/// </remarks>
public static class AlarmCommandVerdictAggregator
{
/// <summary>Aggregates the answers.</summary>
/// <param name="answers">Node → its verdict (non-owners carry <see cref="AlarmCommandOutcome.NotOwned"/>).</param>
/// <param name="unanswered">Expected nodes that did not answer within the window.</param>
/// <param name="expectedKnown">Whether the set of nodes the command reached is known (false ⇒ silence may hide an owner).</param>
/// <param name="notDeliveredReason">Set when the command reached no node at all.</param>
/// <param name="window">The collection window, for the "no answer" text.</param>
/// <returns>The fleet verdict.</returns>
public static AlarmCommandFleetOutcome Aggregate(
IReadOnlyDictionary<string, AlarmCommandOutcome> answers,
IReadOnlyCollection<string> unanswered,
bool expectedKnown,
string? notDeliveredReason,
TimeSpan window)
{
ArgumentNullException.ThrowIfNull(answers);
ArgumentNullException.ThrowIfNull(unanswered);
if (notDeliveredReason is not null && answers.Count == 0)
return new AlarmCommandFleetOutcome(AlarmCommandVerdict.NotApplied, "Not delivered",
$"The command was not delivered to any server, so nothing applied it: {notDeliveredReason}");
var applied = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.Applied);
var refused = answers.Where(a => a.Value is { Verdict: AlarmCommandVerdict.NotApplied, NotOwned: false })
.OrderBy(a => a.Key, StringComparer.Ordinal).ToList();
var unknown = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.OutcomeUnknown) + unanswered.Count;
AlarmCommandVerdict verdict;
string summary;
if (applied > 0)
{
verdict = AlarmCommandVerdict.Applied;
summary = refused.Count + unknown == 0
? "Applied"
: $"Applied on {applied} of {applied + refused.Count + unknown} servers";
}
else if (unknown > 0)
{
verdict = AlarmCommandVerdict.OutcomeUnknown;
summary = "Outcome unknown";
}
else if (refused.Count > 0)
{
verdict = AlarmCommandVerdict.NotApplied;
summary = "Refused: " + (refused[0].Value.Reason ?? "the alarm engine did not apply the command.");
}
else if (!expectedKnown)
{
// Silence from a node we could not enumerate may be an owner that did not answer (a pre-#950 node).
verdict = AlarmCommandVerdict.OutcomeUnknown;
summary = "Outcome unknown";
}
else
{
verdict = AlarmCommandVerdict.NotApplied;
summary = "Not applied: no server owns this alarm";
}
var detail = new StringBuilder(verdict switch
{
AlarmCommandVerdict.Applied => "The alarm engine applied the command.",
AlarmCommandVerdict.OutcomeUnknown =>
"No server confirmed the command and at least one did not give a definite answer — it may still apply. "
+ "Check the alarm's state before retrying.",
_ => "The command was not applied anywhere.",
});
foreach (var (node, outcome) in answers.OrderBy(a => a.Key, StringComparer.Ordinal))
detail.AppendLine().Append(node).Append(": ").Append(Describe(outcome));
foreach (var node in unanswered.OrderBy(n => n, StringComparer.Ordinal))
detail.AppendLine().Append(node).Append($": no answer within {window.TotalSeconds:0.#} s — outcome unknown.");
if (answers.Count == 0 && unanswered.Count == 0)
detail.AppendLine().Append($"No server answered within {window.TotalSeconds:0.#} s.");
if (notDeliveredReason is not null)
detail.AppendLine().Append("Delivery: ").Append(notDeliveredReason);
return new AlarmCommandFleetOutcome(verdict, summary, detail.ToString());
}
private static string Describe(AlarmCommandOutcome outcome) => outcome switch
{
{ Verdict: AlarmCommandVerdict.Applied } => "applied.",
{ Verdict: AlarmCommandVerdict.NotApplied, NotOwned: true } => "does not own this alarm.",
{ Verdict: AlarmCommandVerdict.NotApplied } => "refused — " + (outcome.Reason ?? "no reason given."),
_ => "outcome unknown — " + (outcome.Reason ?? "no reason given."),
};
}
/// <summary>
/// #950: the DistributedPubSub leg of an AdminUI alarm command that wants verdicts — used by the router under
/// <c>MeshTransport:Mode = Dps</c> and by <see cref="AdminOperationsActor"/> when no router is wired.
/// </summary>
public static class AlarmVerdictDps
{
/// <summary>
/// Publishes <paramref name="command"/> on <paramref name="topic"/> with <paramref name="collector"/> as the sender
/// (DistributedPubSub preserves it, so each node's scripted-alarm host answers the collector) and returns the nodes
/// expected to answer: the Up members carrying the <c>driver</c> role, keyed as <see cref="NodeKey"/> keys them.
/// </summary>
/// <param name="system">The actor system.</param>
/// <param name="topic">The DPS topic.</param>
/// <param name="command">The command (with <see cref="AlarmCommand.VerdictRequested"/> set).</param>
/// <param name="collector">Who the nodes answer.</param>
/// <returns>The expected node keys; empty when the membership could not be read.</returns>
public static IReadOnlyList<string> Publish(ActorSystem system, string topic, AlarmCommand command, IActorRef collector)
{
IReadOnlyList<string> expected;
try
{
var cluster = Akka.Cluster.Cluster.Get(system);
expected = cluster.State.Members
.Where(m => m.Status == Akka.Cluster.MemberStatus.Up && RoleParser.GossipedRolesHave(m.Roles, RoleParser.Driver))
.Select(m => NodeKey(m.Address, cluster.SelfAddress))
.Distinct(StringComparer.Ordinal)
.ToList();
}
catch (Exception)
{
expected = [];
}
DistributedPubSub.Get(system).Mediator.Tell(new Publish(topic, command), collector);
return expected;
}
/// <summary>The key a DPS-answering node is known by: its <c>host:port</c> (a local-scope address is this node).</summary>
/// <param name="address">The member or reply-sender address.</param>
/// <param name="self">This node's cluster address, or null when there is no cluster.</param>
/// <returns>The key.</returns>
public static string NodeKey(Address address, Address? self)
{
var effective = address.HasGlobalScope || self is null ? address : self;
return effective.Host is not null && effective.Port is not null ? effective.HostPort() : effective.ToString();
}
}
/// <summary>
/// #950: one AdminUI alarm command's verdict collection. Sends the command (via the mesh router, or straight onto
/// DistributedPubSub when none is wired), gathers each node's answer until every expected node has answered or the
/// window closes, and replies the aggregated <see cref="AlarmCommandFleetOutcome"/> (mapped by the caller's
/// <c>reply</c>) to the original requester. Stops itself after replying.
/// </summary>
public sealed class AlarmCommandVerdictCollector : ReceiveActor, IWithTimers
{
/// <summary>The default collection window — under <c>AdminOperationsClient</c>'s 10 s ask.</summary>
public static readonly TimeSpan DefaultWindow = TimeSpan.FromSeconds(7);
private const string WindowTimerKey = "window";
private readonly AlarmCommand _command;
private readonly IActorRef? _meshRouter;
private readonly IActorRef _replyTo;
private readonly Func<AlarmCommandFleetOutcome, object> _reply;
private readonly TimeSpan _window;
private readonly ILoggingAdapter _log = Context.GetLogger();
private readonly Dictionary<string, AlarmCommandOutcome> _answers = new(StringComparer.Ordinal);
private HashSet<string>? _expected;
private string? _notDelivered;
private Address? _self;
/// <summary>Gets or sets the timer scheduler.</summary>
public ITimerScheduler Timers { get; set; } = null!;
/// <summary>Creates the props.</summary>
/// <param name="command">The command; <see cref="AlarmCommand.VerdictRequested"/> is forced on.</param>
/// <param name="meshRouter">The central comm actor, or null to publish on DistributedPubSub directly.</param>
/// <param name="replyTo">The requester.</param>
/// <param name="reply">Maps the fleet verdict to the requester's reply message.</param>
/// <param name="window">The collection window.</param>
/// <returns>The props.</returns>
public static Props Props(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window) =>
Akka.Actor.Props.Create(() => new AlarmCommandVerdictCollector(command, meshRouter, replyTo, reply, window));
/// <summary>Initializes a new instance of the <see cref="AlarmCommandVerdictCollector"/> class.</summary>
/// <param name="command">The command.</param>
/// <param name="meshRouter">The router, or null.</param>
/// <param name="replyTo">The requester.</param>
/// <param name="reply">Maps the verdict to the reply.</param>
/// <param name="window">The collection window.</param>
public AlarmCommandVerdictCollector(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window)
{
_command = command with { VerdictRequested = true };
_meshRouter = meshRouter;
_replyTo = replyTo;
_reply = reply;
_window = window;
Receive<AlarmVerdictFanOut>(msg =>
{
_expected = new HashSet<string>(msg.Nodes, StringComparer.Ordinal);
_notDelivered = msg.NotDeliveredReason;
FinishIfComplete();
});
Receive<AlarmNodeVerdict>(msg =>
{
_answers[msg.Node] = msg.Outcome;
FinishIfComplete();
});
// A DistributedPubSub answer straight from a node's ScriptedAlarmHostActor: the node is the sender.
Receive<AlarmCommandOutcome>(outcome =>
{
if (!string.Equals(outcome.AlarmId, _command.AlarmId, StringComparison.Ordinal)) return;
_answers[AlarmVerdictDps.NodeKey(Sender.Path.Address, _self)] = outcome;
FinishIfComplete();
});
Receive<WindowClosed>(_ => Finish());
}
/// <inheritdoc />
protected override void PreStart()
{
try
{
_self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress;
}
catch (Exception)
{
_self = null;
}
Timers.StartSingleTimer(WindowTimerKey, WindowClosed.Instance, _window);
if (_meshRouter is not null)
{
_meshRouter.Tell(new MeshCommand(AlarmCommandsTopic.Name, _command, Self));
}
else
{
var expected = AlarmVerdictDps.Publish(Context.System, AlarmCommandsTopic.Name, _command, Self);
Self.Tell(new AlarmVerdictFanOut(expected));
}
}
private void FinishIfComplete()
{
if (_expected is null) return;
if (_notDelivered is not null && _expected.Count == 0)
{
Finish();
return;
}
if (_expected.Count > 0 && _expected.All(_answers.ContainsKey)) Finish();
}
private void Finish()
{
var expectedKnown = _expected is { Count: > 0 } || _notDelivered is not null;
var unanswered = _expected?.Where(n => !_answers.ContainsKey(n)).ToList() ?? [];
var outcome = AlarmCommandVerdictAggregator.Aggregate(_answers, unanswered, expectedKnown, _notDelivered, _window);
_log.Info("AdminOps: {Operation} for alarm {AlarmId} by {User} → {Outcome}",
_command.Operation, _command.AlarmId, _command.User,
$"{outcome.Verdict} ({outcome.Summary}; {_answers.Count} answered, {unanswered.Count} silent)");
_replyTo.Tell(_reply(outcome));
Timers.CancelAll();
Context.Stop(Self);
}
private sealed class WindowClosed
{
public static readonly WindowClosed Instance = new();
}
}