Merge #958: scripted-alarm refused broadcast copy settles the expired ask's LateOutcome -> mutation-guarded revert (30 s window, 1024 cap)

This commit is contained in:
Joseph Doherty
2026-12-01 20:24:34 -05:00
5 changed files with 303 additions and 17 deletions
+4 -1
View File
@@ -106,7 +106,10 @@ unsent; `OpcUa:Quotas:MaxNodesPerMethodCall` (1000) bounds a Call; an ask expire
not remembered (its broadcast copy applies); the revert is guarded by a per-condition mutation counter, not field equality. A refusal arriving AFTER the caller got
OutcomeUnknown still reverts (#951: the Ask lives `LateVerdictWindow` past the bound; the timeout outcome carries it as the
process-local `AlarmCommandOutcome.LateOutcome`). A command cancelled while still waiting for the engine gate throws
`ScriptedAlarmCommandNotStartedException` ⇒ `NotApplied` (#952; unknown + not remembered once its asker's deadline passed). A
`ScriptedAlarmCommandNotStartedException` ⇒ `NotApplied` (#952; unknown + not remembered once its asker's deadline passed). An
ask the host answers "the broadcast copy decides" (expired / never started) carries the copy's LOCAL outcome as its
`LateOutcome` (#958: pending decision per `CommandId`, settled in `OnAlarmCommand`, unknown after 30 s or on stop), so a refused
copy reverts the node through the same chain and mutation guard. A
superseded load's failure (pipe-back carries its generation) publishes no readiness (#953). Remote gRPC-data methods ride
`ExecuteConditionMethodAsync` (⇒ `DriverConfirmedFailure` / `OutcomeUnknown`). Never await the verdict inside the handler
(it runs under `Lock`). The sync `base.Call` path (no asker) keeps the old fire-and-forget router. The AdminUI `/alerts` path
+20 -4
View File
@@ -454,7 +454,7 @@ of which blocks under the node manager's `Lock`:
| applied (incl. an idempotent no-op) | `Good` |
| refused — last load failed, alarm not loaded on this node (incl. the window after a host supervision restart before its reload), malformed command, no engine on this node | `BadInvalidState` (node reverted; the peer never received it) |
| no answer within min(5 s, request deadline − 250 ms), or the engine op timed out / failed in the store | `BadTimeout` / `BadInternalError`, diagnostic "OutcomeUnknown" — the command **may still apply**, never reported as refused (a refusal that arrives later still reverts the node, #951) |
| the engine never started it — still waiting for the engine gate (e.g. behind a long load) when the host's 10 s op bound expired (#952) | `BadInvalidState` while the asker still waits (definite: nothing ran); once the asker has already answered OutcomeUnknown and broadcast it, the host answers unknown and lets the broadcast copy decide |
| the engine never started it — still waiting for the engine gate (e.g. behind a long load) when the host's 10 s op bound expired (#952) | `BadInvalidState` while the asker still waits (definite: nothing ran); once the asker has already answered OutcomeUnknown and broadcast it, the host answers unknown and lets the broadcast copy decide (a refusal of that copy still reverts the node, #958) |
`BadInvalidState` is Part 4's general "object … uninitialized or in some other invalid state" code; Part 9's method result
codes (bad EventId, already acked/confirmed/shelved, disabled, shelving time out of range) do not cover "the state owner
@@ -492,6 +492,22 @@ unknown). The host maps not-started to `NotApplied` and remembers it, except on
passed: that asker already answered OutcomeUnknown and broadcast the command, so — like an ask that expired before it started
— the host answers unknown and does not remember it, and the broadcast copy decides locally too.
**A refused broadcast copy (#958).** Whenever the host answers a direct ask "the broadcast copy decides" — the ask expired
in its mailbox before the engine reached it (review r2 M2), or the engine never started it before the asker's deadline
(#952) — that unknown answer now carries the copy's outcome as its `LateOutcome`: the host keeps a pending decision per
`CommandId` and completes it when `OnAlarmCommand` decides the broadcast copy of the same id (applied, refused, unknown, or
not owned — e.g. a deploy removed the alarm). The node manager already follows a chain of unknowns (#951), so a copy the local
engine REFUSES (typically: the deploy the command queued behind failed) reverts the node under the same per-condition
mutation-counter guard — skipped when anything changed the node since the method (newer truth wins, including a newer
operator method). There is one chain per method call and one terminal verdict, so the #951 late path and the copy cannot
both revert; a repeat would be refused by the counter anyway (the revert's corrective event bumps it). A copy that reached the
host BEFORE the expired ask is remembered and answers the ask directly. If the copy never arrives (the publish failed) the
pending decision settles unknown after `ScriptedAlarmHostActor.DefaultBroadcastDecisionWindow` (30 s) and the node keeps the
change; a host that stops settles its pending decisions unknown. At most 1024 decisions are pending per host (past that the
answer carries none, as before). The pending outcome's continuations run off the host's thread — the revert takes the SDK
`Lock`. As with #951, the redundant peer received the copy too and may have applied it; the revert makes this node match its
own engine.
**Superseded load failure (#953).** A failed load pipes back with its load generation; a failure from a generation a newer
apply has already superseded publishes nothing to the readiness view (the newer load is in flight and has typically cleared
the engine's complete-generation flag, so reading it would refuse every command until that load completes — the view must
@@ -499,9 +515,9 @@ let through while a load is pending; the engine queues a command behind it). The
**Residual.** Only the pre-check stops the SDK from applying the node change, so a refusal that arrives through the ask
shows subscribers two events: the method's, then the corrective one. An OutcomeUnknown leaves the node changed (the engine
may still apply it) unless a late refusal arrives inside the late window (#951). A command whose direct ask gave up and whose
broadcast copy is then refused by the local engine (no one awaits a broadcast copy) still keeps the node change until the
next good deploy re-asserts it. (#958) A command racing the engine's first load queues behind it rather than failing.
may still apply it) unless a late refusal arrives inside the late window (#951) or the local engine refuses the broadcast copy
that decides it (#958); a copy that never reaches the local engine within 30 s leaves the node changed until the next good
deploy re-asserts it. A command racing the engine's first load queues behind it rather than failing.
The AdminUI `/alerts` buttons report the engine's verdict too since #950 — see [AdminUI path](#adminui-path).
`OnTimedUnshelve` (the SDK's internal auto-unshelve timer, armed for the real remaining time since Gitea #597) is a **no-op**: the engine owns timed-shelve expiry via `ApplyShelvingCheck` (`system / AutoUnshelve`), and routing an `Unshelve` from the timer pre-empted that on every expiry as an operator-style unshelve from both pair nodes (review R1 M2).
@@ -206,6 +206,40 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
private readonly Queue<string> _recentCommandOrder = new();
internal const int RecentCommandCapacity = 1024;
/// <summary>
/// #958: how long after this host answered a direct ask "the broadcast copy decides" it waits for that copy before
/// settling the ask's <see cref="AlarmCommandOutcome.LateOutcome"/> as unknown. The copy is published right after the
/// asker's bound, from this process, so one that is coming at all is queued here long before this.
/// </summary>
public static readonly TimeSpan DefaultBroadcastDecisionWindow = TimeSpan.FromSeconds(30);
/// <summary>
/// #958: direct asks answered "the broadcast copy decides" (expired before the engine reached them, or never started
/// before their asker's deadline), keyed by <see cref="AlarmCommand.CommandId"/>. The answer's
/// <see cref="AlarmCommandOutcome.LateOutcome"/> completes with what this host's engine does with the broadcast copy,
/// so the node manager can revert the method's node change when the engine refuses that copy — before #958 nobody
/// awaited a broadcast copy and the node kept the change until the next good deploy.
/// </summary>
private readonly Dictionary<string, PendingBroadcastDecision> _broadcastDecisions = new(StringComparer.Ordinal);
private readonly TimeSpan _broadcastDecisionWindow;
/// <summary>#958: one direct ask waiting on its broadcast copy.</summary>
private sealed class PendingBroadcastDecision(AlarmCommand command)
{
/// <summary>The command the ask carried.</summary>
public AlarmCommand Command { get; } = command;
/// <summary>Completed with the broadcast copy's local outcome. Continuations run asynchronously: the node manager's
/// revert takes the SDK Lock, which must never run on this actor's thread.</summary>
public TaskCompletionSource<AlarmCommandOutcome> Outcome { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>The expiry timer, cancelled once the copy decided.</summary>
public ICancelable? Expiry { get; set; }
}
/// <summary>#958: the broadcast copy of a pending direct ask did not arrive within the window.</summary>
private sealed record BroadcastDecisionExpired(string CommandId, PendingBroadcastDecision Pending);
/// <summary>Cached cluster DistributedPubSub mediator, resolved once in <see cref="PreStart"/> (on the
/// actor thread) and reused for every emission instead of re-resolving it per-publish.</summary>
private IActorRef _mediator = null!;
@@ -262,8 +296,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null,
ScriptedAlarmCommandReadinessView? readiness = null) =>
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout, readiness));
ScriptedAlarmCommandReadinessView? readiness = null,
TimeSpan? broadcastDecisionWindow = null) =>
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout, readiness, broadcastDecisionWindow));
/// <summary>Factory-built incarnation: owns (and on every stop disposes) the engine it builds.</summary>
/// <param name="publishActor">The OPC UA publish actor emissions are bridged to.</param>
@@ -275,6 +310,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="commandTimeout">Bound on one inbound alarm command's engine op.</param>
/// <param name="readiness">#937: where the outcome of every completed load is published for the node manager's
/// synchronous pre-check. Null ⇒ none (tests).</param>
/// <param name="broadcastDecisionWindow">#958: how long a direct ask answered "the broadcast copy decides" waits for that
/// copy; null ⇒ <see cref="DefaultBroadcastDecisionWindow"/>.</param>
public ScriptedAlarmHostActor(
IActorRef publishActor,
IActorRef? mux,
@@ -283,8 +320,10 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null,
ScriptedAlarmCommandReadinessView? readiness = null)
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout, readiness)
ScriptedAlarmCommandReadinessView? readiness = null,
TimeSpan? broadcastDecisionWindow = null)
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout, readiness,
broadcastDecisionWindow)
{
}
@@ -319,7 +358,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null)
: this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null, readiness: null)
: this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null, readiness: null,
broadcastDecisionWindow: null)
{
}
@@ -332,7 +372,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
ITelemetryLocalHub? telemetryHub,
bool ownsEngine,
TimeSpan? commandTimeout,
ScriptedAlarmCommandReadinessView? readiness)
ScriptedAlarmCommandReadinessView? readiness,
TimeSpan? broadcastDecisionWindow)
{
_readiness = readiness;
// A new incarnation has not loaded yet: whatever the previous one published no longer describes this engine.
@@ -346,6 +387,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
_engine = pair.Engine;
_ownsEngine = ownsEngine;
_commandTimeout = commandTimeout is { } t && t > TimeSpan.Zero ? t : DefaultCommandTimeout;
_broadcastDecisionWindow = broadcastDecisionWindow is { } w && w > TimeSpan.Zero ? w : DefaultBroadcastDecisionWindow;
_localNode = localNode;
_driverMemberCountProvider = driverMemberCountProvider;
_telemetryHub = telemetryHub;
@@ -382,6 +424,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
ReceiveAsync<AlarmCommand>(OnAlarmCommand);
// #937: the node-local ask behind an OPC UA Part 9 method — same op, plus a reply carrying the verdict.
ReceiveAsync<ExecuteAlarmCommand>(OnExecuteAlarmCommand);
// #958: a direct ask's broadcast copy never arrived — settle what the ask's answer still promises.
Receive<BroadcastDecisionExpired>(OnBroadcastDecisionExpired);
// A faulted LoadAsync pipes back an AlarmsLoadFailed carrying its generation (see OnApply) — log it, publish
// readiness if it is the latest load (#953), and stay inert.
Receive<AlarmsLoadFailed>(OnLoadFailed);
@@ -820,6 +864,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
{
_log.Debug("ScriptedAlarmHost: skipping duplicate AlarmCommand {Op} for {AlarmId} (command {CommandId})",
cmd.Operation, cmd.AlarmId, id);
SettleBroadcastDecision(cmd, known);
replyTo?.Tell(known);
return;
}
@@ -830,16 +875,64 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
{
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
cmd.Operation, cmd.AlarmId);
replyTo?.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
NotLoadedRefusal, NotOwned: true));
var notOwned = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
NotLoadedRefusal, NotOwned: true);
// #958: a direct ask of this node waiting on this copy — nothing here applied it (e.g. a deploy removed the alarm).
SettleBroadcastDecision(cmd, notOwned);
replyTo?.Tell(notOwned);
return;
}
var outcome = await ApplyCommandAsync(cmd);
Remember(cmd, outcome);
SettleBroadcastDecision(cmd, outcome);
replyTo?.Tell(outcome);
}
/// <summary>
/// #958: registers a direct ask answered "the broadcast copy decides" and returns what its answer's
/// <see cref="AlarmCommandOutcome.LateOutcome"/> carries — the broadcast copy's local outcome once
/// <see cref="OnAlarmCommand"/> has decided it, or an unknown one if it never arrives (window) or this host stops.
/// Null ⇒ nothing to wait on (no CommandId, or the bounded table is full).
/// </summary>
private Task<AlarmCommandOutcome>? AwaitBroadcastCopy(AlarmCommand cmd)
{
if (cmd.CommandId is not { } id) return null;
if (_broadcastDecisions.TryGetValue(id, out var existing)) return existing.Outcome.Task;
if (_broadcastDecisions.Count >= RecentCommandCapacity)
{
_log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} — too many commands waiting on their broadcast copy; its outcome is not reported back",
cmd.Operation, cmd.AlarmId);
return null;
}
var pending = new PendingBroadcastDecision(cmd);
pending.Expiry = Context.System.Scheduler.ScheduleTellOnceCancelable(_broadcastDecisionWindow, Self,
new BroadcastDecisionExpired(id, pending), Self);
_broadcastDecisions[id] = pending;
return pending.Outcome.Task;
}
/// <summary>#958: hands the broadcast copy's local outcome to the direct ask waiting on it, if any.</summary>
private void SettleBroadcastDecision(AlarmCommand cmd, AlarmCommandOutcome outcome)
{
if (cmd.CommandId is not { } id || !_broadcastDecisions.Remove(id, out var pending)) return;
pending.Expiry?.Cancel();
pending.Outcome.TrySetResult(outcome);
}
private void OnBroadcastDecisionExpired(BroadcastDecisionExpired msg)
{
// Reference check: only the registration this timer was armed for.
if (!_broadcastDecisions.TryGetValue(msg.CommandId, out var pending) || !ReferenceEquals(pending, msg.Pending)) return;
_broadcastDecisions.Remove(msg.CommandId);
_log.Warning("ScriptedAlarmHost: the broadcast copy of command {CommandId} did not arrive within {Window}; its outcome stays unknown",
msg.CommandId, _broadcastDecisionWindow);
pending.Outcome.TrySetResult(new AlarmCommandOutcome(pending.Command.AlarmId, pending.Command.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"OutcomeUnknown: the broadcast copy did not reach this server's scripted-alarm engine within {_broadcastDecisionWindow.TotalSeconds:0.#} s.",
TimedOut: true));
}
/// <summary>
/// #937: the node-local ask behind an OPC UA Part 9 method. Applies the command exactly as
/// <see cref="OnAlarmCommand"/> does (once — a broadcast copy that already arrived is not re-applied; its recorded
@@ -863,8 +956,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
{
_log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} skipped on the direct path — its asker stopped waiting; the broadcast copy applies",
cmd.Operation, cmd.AlarmId);
// #958: the answer still carries what the broadcast copy does here, so a refusal of it reverts the node.
replyTo.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: the ask expired before the engine reached it.", TimedOut: true));
"OutcomeUnknown: the ask expired before the engine reached it.", TimedOut: true) { LateOutcome = AwaitBroadcastCopy(cmd) });
return;
}
@@ -882,7 +976,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
{
replyTo.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: the engine did not start the command before its asker stopped waiting; the broadcast copy decides.",
TimedOut: true));
TimedOut: true) { LateOutcome = AwaitBroadcastCopy(cmd) });
return;
}
@@ -1076,6 +1170,14 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// unless this is a RESTART around a legacy Props-captured engine, which the next incarnation will
// re-attach to (R02:H1).
_cts.Cancel();
// #958: asks waiting on a broadcast copy this incarnation will never decide — their outcome stays unknown.
foreach (var pending in _broadcastDecisions.Values)
{
pending.Expiry?.Cancel();
pending.Outcome.TrySetResult(new AlarmCommandOutcome(pending.Command.AlarmId, pending.Command.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: the scripted-alarm host stopped before the broadcast copy was decided."));
}
_broadcastDecisions.Clear();
_engine.OnEvent -= _onEngineEvent;
_engine.OnInputsEstablished -= _onInputsEstablished;
if (_ownsEngine || !_restarting) _engine.Dispose();
@@ -542,4 +542,74 @@ public sealed class ScriptedCommandVerdictWireTests
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// #958, the production chain: the direct ask gave up (the dispatcher answered OutcomeUnknown and broadcast the command),
/// the host then answered that ask "the broadcast copy decides" with the copy's local outcome still to come, and the
/// local engine REFUSES the copy. The node is reverted exactly once — or, when another change reached the node after the
/// method (here a newer projection), not at all: newer truth wins. Before #958 the host's unknown answer carried
/// nothing and the node kept the SDK-applied change until the next good deploy.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task A_broadcast_copy_refused_after_the_ask_gave_up_reverts_once_unless_the_node_changed_since(bool changedSince)
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync($"Verdict958Copy{changedSince}", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
// No RunContinuationsAsynchronously: the node manager's late-verdict chain runs inline in SetResult, so by the time
// SetResult returns the revert has been decided — the sentinel below then orders after it.
var ask = new TaskCompletionSource<AlarmCommandOutcome>();
var copy = new TaskCompletionSource<AlarmCommandOutcome>();
rig.Nm.AlarmCommandAsker = (cmd, _) => Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation,
AlarmCommandVerdict.OutcomeUnknown, "OutcomeUnknown: no answer in time", TimedOut: true) { LateOutcome = ask.Task });
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
var pre = ConditionMethodEventTests.PreState("Acknowledge", native: false);
rig.Project(false, pre with { Message = "base" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var unknown = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
unknown.StatusCode.ShouldBe(StatusCodes.BadTimeout);
if (changedSince)
{
rig.Project(false, pre with { Acknowledged = true, Message = "newer" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "newer"));
}
// The host's answer to the expired ask: unknown, the broadcast copy decides.
ask.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "Acknowledge", AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: the ask expired before the engine reached it.", TimedOut: true) { LateOutcome = copy.Task });
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeTrue("still unknown: nothing reverted yet");
// The local engine refuses the broadcast copy.
copy.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "Acknowledge", AlarmCommandVerdict.NotApplied,
"load failed"));
if (!changedSince) await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count >= 3);
rig.Project(false, pre with { Acknowledged = changedSince, Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
var baseEvents = events.ConditionEvents(item, "base");
if (changedSince)
{
baseEvents.Count.ShouldBe(2, "the base transition and the method's event — the newer change is not reverted");
}
else
{
baseEvents.Count.ShouldBe(3, "the base transition, the method's event, and exactly one corrective event");
baseEvents[2][RecordedEvents.AckedField].ClrValue().ShouldBe(baseEvents[0][RecordedEvents.AckedField].ClrValue());
}
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
}
@@ -31,7 +31,7 @@ public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
private static EquipmentScriptedAlarmPlan BadPlan(string id) => Plan(id, "return unknownIdentifier;");
private (IActorRef Host, ScriptedAlarmEngine Engine, ScriptedAlarmCommandReadinessView Readiness, TestProbe Mux) Spawn(
IAlarmStateStore? store = null, TimeSpan? commandTimeout = null)
IAlarmStateStore? store = null, TimeSpan? commandTimeout = null, TimeSpan? broadcastDecisionWindow = null)
{
var publish = CreateTestProbe();
var mux = CreateTestProbe();
@@ -40,7 +40,7 @@ public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
var engine = new ScriptedAlarmEngine(upstream, store ?? new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
var readiness = new ScriptedAlarmCommandReadinessView();
var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, () => (upstream, engine),
commandTimeout: commandTimeout, readiness: readiness));
commandTimeout: commandTimeout, readiness: readiness, broadcastDecisionWindow: broadcastDecisionWindow));
return (host, engine, readiness, mux);
}
@@ -227,10 +227,105 @@ public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
release.SetResult(null);
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
host.Tell(cmd); // the broadcast copy: not shadowed by a remembered refusal
// #958: the unknown answer carries what the broadcast copy did here.
(await unknown.LateOutcome!.WaitAsync(Timeout, Ct)).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
(await Ask(host, "alm-1", "AddComment", "after", "cmd-after")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["late", "after"]);
}
/// <summary>
/// #958: an ask answered "the broadcast copy decides" carries, as its <see cref="AlarmCommandOutcome.LateOutcome"/>, what
/// THIS host's engine does with that copy — so when the engine refuses the copy (here: the deploy that landed in between
/// failed) the node manager can revert the method's node change. Before #958 nobody awaited the copy and the node kept
/// the change until the next good deploy. An applied copy settles Applied (the node keeps the change).
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task The_broadcast_copys_local_outcome_settles_the_expired_asks_late_outcome(bool refused)
{
var (host, engine, readiness, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-958");
var unknown = await host.Ask<AlarmCommandOutcome>(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
unknown.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
var late = unknown.LateOutcome;
(late is not null).ShouldBeTrue("the broadcast copy's local outcome is still coming");
late!.IsCompleted.ShouldBeFalse("nothing decided the command yet");
if (refused)
{
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), BadPlan("bad-1")]));
AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct);
}
host.Tell(cmd); // the broadcast copy (same CommandId)
var decided = await late.WaitAsync(Timeout, Ct);
decided.Verdict.ShouldBe(refused ? AlarmCommandVerdict.NotApplied : AlarmCommandVerdict.Applied);
if (refused)
{
decided.Reason.ShouldBe(ScriptedAlarmCommandReadinessView.LoadFailedRefusal);
engine.GetState("alm-1")!.Comments.ShouldBeEmpty();
}
else
{
engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["late"]);
}
}
/// <summary>#958: the copy reaching the host BEFORE the expired ask (remembered) answers the ask with that verdict
/// directly — one terminal outcome, so the node manager reverts at most once.</summary>
[Fact]
public async Task A_broadcast_copy_refused_before_the_expired_ask_answers_it_directly()
{
var (host, _, readiness, _) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), BadPlan("bad-1")]));
AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-958-first");
host.Tell(cmd);
var answer = await host.Ask<AlarmCommandOutcome>(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
answer.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
(answer.LateOutcome is null).ShouldBeTrue();
}
/// <summary>#958: a broadcast copy that never arrives (the publish failed) settles the late outcome unknown after the
/// window — never left pending, never a refusal.</summary>
[Fact]
public async Task A_broadcast_copy_that_never_arrives_settles_unknown_after_the_window()
{
var (host, _, _, mux) = Spawn(broadcastDecisionWindow: TimeSpan.FromMilliseconds(200));
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "lost", null, "cmd-958-lost");
var unknown = await host.Ask<AlarmCommandOutcome>(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
var settled = await unknown.LateOutcome!.WaitAsync(Timeout, Ct);
settled.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
settled.AlarmId.ShouldBe("alm-1");
(settled.LateOutcome is null).ShouldBeTrue("the chain ends: nothing more is coming");
}
/// <summary>#958: a host that stops with a copy still pending settles it unknown (the late chain always ends).</summary>
[Fact]
public async Task A_stopping_host_settles_a_pending_broadcast_decision_unknown()
{
var (host, _, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "orphan", null, "cmd-958-stop");
var unknown = await host.Ask<AlarmCommandOutcome>(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
Sys.Stop(host);
(await unknown.LateOutcome!.WaitAsync(Timeout, Ct)).Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
}
/// <summary>
/// #953: a load that fails after a newer apply already started its own load is superseded — its failure must not
/// publish "refuse everything" while the newer load is in flight (the engine queues a command behind it; the view is