fix(alarms): #951 #952 #953 — late refusal reverts, never-started command is NotApplied, superseded load failure ignored

#951: the hosted-service Ask lives LateVerdictWindow (30 s) past the caller's bound
(ExecuteAlarmCommand deadline unchanged); the OutcomeUnknown it returns carries the
still-running ask as AlarmCommandOutcome.LateOutcome (process-local). The node manager
watches it (or the asker task itself when its backstop expired, following unknown
chains) and reverts the node on a late NotApplied, under the existing per-condition
mutation-counter guard. Both CallAsync and remote ExecuteConditionMethodAsync paths.

#952: ScriptedAlarmEngine throws ScriptedAlarmCommandNotStartedException (an OCE) when a
command is cancelled before it acquires _evalGate; a cancellation inside SaveAsync stays
a plain OCE (unknown). The host maps not-started to NotApplied and remembers it, except on
the direct ask once its asker's deadline passed (asker already answered unknown and
broadcast): then unknown + not remembered, so the broadcast copy decides (as review r2 M2).

#953: a faulted load pipes back AlarmsLoadFailed(cause, generation); a failure from a
generation a newer apply superseded publishes no readiness (it would refuse every command
while the newer load is in flight).

Red/green: each fix reverted individually turns its tests red (Core 1, Runtime 3,
Host 1, OpcUaServer.IntegrationTests 4).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-01 19:42:24 -05:00
parent 6b60845931
commit 068124d1ae
14 changed files with 596 additions and 33 deletions
@@ -419,4 +419,127 @@ public sealed class ScriptedCommandVerdictWireTests
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// #951: the engine refuses AFTER the caller was told OutcomeUnknown (BadTimeout) — e.g. the command was queued behind a
/// load that then failed. The node does not keep the SDK-applied change: the late refusal reverts it with exactly one
/// corrective event, as an in-time refusal does. Covers both shapes of "late": the asker's own timeout outcome carrying
/// the host's still-running answer, and an asker that never answered inside the node manager's backstop.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task A_refusal_arriving_after_the_timeout_reverts_the_node(bool viaLateOutcome)
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync($"Verdict951Late{viaLateOutcome}", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(500);
var host = new TaskCompletionSource<AlarmCommandOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
rig.Nm.AlarmCommandAsker = (cmd, _) => viaLateOutcome
? Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: no answer in time", TimedOut: true) { LateOutcome = host.Task })
: host.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);
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) 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);
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value
.ShouldBeTrue("an unknown outcome keeps the change — the engine may still apply it");
host.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "Acknowledge", AlarmCommandVerdict.NotApplied, "load failed"));
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count >= 3);
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
var baseEvents = events.ConditionEvents(item, "base");
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(); }
}
/// <summary>
/// #951: only a late REFUSAL reverts. A late answer already in when the verdict is settled is acted on before the call
/// returns, so each arm is observed deterministically: Applied / still-unknown keep the change; NotApplied (here behind
/// one more unknown hop, so the chain is followed) reverts it.
/// </summary>
[Theory]
[InlineData(AlarmCommandVerdict.Applied, false)]
[InlineData(AlarmCommandVerdict.OutcomeUnknown, false)]
[InlineData(AlarmCommandVerdict.NotApplied, true)]
public async Task Only_a_late_refusal_reverts(AlarmCommandVerdict lateVerdict, bool reverted)
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync($"Verdict951Only{lateVerdict}", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
var late = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, lateVerdict);
if (lateVerdict == AlarmCommandVerdict.NotApplied)
{
late = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, "hop", TimedOut: true)
{ LateOutcome = Task.FromResult(late) };
}
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: no answer in time", TimedOut: true) { LateOutcome = Task.FromResult(late) });
};
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
await rig.DrainProjectionsAsync();
using var session = await rig.ConnectAsync(anonymous: false, ct);
var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value;
var result = await session.CallAsync(null, [new CallMethodRequest
{
ObjectId = ConditionNodeId(session, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText("x"))],
}], ct);
result.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBe(!reverted);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>#951 for a remote (gRPC data) condition method: a refusal arriving after the Unknown answer reverts the node too.</summary>
[Fact]
public async Task A_remote_condition_method_refused_after_its_timeout_reverts_the_node()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict951Remote", encrypted: false, ct);
try
{
rig.MaterialiseScripted();
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
await rig.DrainProjectionsAsync();
var host = new TaskCompletionSource<AlarmCommandOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
rig.Nm.AlarmCommandAsker = (cmd, _) => Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation,
AlarmCommandVerdict.OutcomeUnknown, "OutcomeUnknown: no answer in time", TimedOut: true) { LateOutcome = host.Task });
var marker = rig.Nm.SnapshotConditions((_, id) => id == ScriptedAlarmId, 10)
.SelectMany(s => s.Records).Single(c => c.ConditionId == ScriptedAlarmId).Activation;
var call = new OriginConditionMethodCall(AddressSpaceRealm.Uns, ScriptedAlarmId, "Acknowledge", "ack", marker, "svc", null);
var unknown = await rig.Nm.ExecuteConditionMethodAsync(call, TimeSpan.FromSeconds(5));
unknown.Unknown.ShouldBeTrue();
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeTrue("unknown keeps the change");
host.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "Acknowledge", AlarmCommandVerdict.NotApplied, "load failed"));
await RecordedEvents.WaitUntilAsync(() => !rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value);
}
finally { await rig.DisposeAsync(); }
}
}