Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs
T
Joseph Doherty 401f9a9685 fix(alarms): #958 a broadcast copy the local engine refuses reverts the node
When the direct verdict ask expired before the engine reached it, or never started before its
asker's deadline, the host answered OutcomeUnknown and let the broadcast copy decide - but nobody
awaited that copy, so a local refusal left the SDK-applied node change until the next good deploy.

The host now keeps a pending decision per CommandId and returns it as the unknown answer's
LateOutcome; OnAlarmCommand settles it with the copy's local outcome (applied / refused / unknown /
not owned). The node manager's existing #951 chain follows it, so a refused copy reverts the node
under the per-condition mutation-counter guard (one chain, one terminal verdict - no double revert;
a newer change wins). Never-arriving copies settle unknown after 30 s; a stopping host settles its
pending decisions unknown; at most 1024 pending per host.

Tests: Runtime host tests (refused/applied copy settles the late outcome, copy-first answers
directly, window expiry, stop) - red without the LateOutcome wiring; wire test of the production
chain reverting exactly once, and not at all after a newer change (falsified by disabling the
mutation guard). Docs: ScriptedAlarms.md residual + #958 section, rules/alarms.md.
2026-12-01 20:24:15 -05:00

616 lines
36 KiB
C#

using System.Collections.Concurrent;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// Gitea #937 over the wire — a scripted condition's Part 9 method returns the scripted-alarm engine's verdict. Before
/// #937 the command was a fire-and-forget topic publish and every allowed call returned Good, including one the engine
/// then rejected because its last load had failed.
/// </summary>
public sealed class ScriptedCommandVerdictWireTests
{
private const NodePermissions All =
NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead
| NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.AlarmShelve
| NodePermissions.MethodCall;
/// <summary>
/// The engine refuses (no complete generation): the call fails BadInvalidState, and — review r1 — the node does not keep
/// the change the SDK applied: after the method's event comes exactly one corrective event carrying the pre-call state.
/// </summary>
[Theory]
[InlineData("Acknowledge")]
[InlineData("Confirm")]
[InlineData("AddComment")]
[InlineData("OneShotShelve")]
[InlineData("TimedShelve")]
[InlineData("Unshelve")]
[InlineData("Disable")]
[InlineData("Enable")]
public async Task A_command_the_engine_refuses_returns_BadInvalidState(string method)
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync($"Verdict937Refused{method}", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var asked = new ConcurrentQueue<AlarmCommand>();
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
asked.Enqueue(cmd);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind"));
};
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(method, native: false) with { Message = "base" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var refused = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), method, events.LatestEventId(item, "base"), ct));
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState);
asked.Count.ShouldBe(1, "the command reached the engine exactly once");
asked.Single().CommandId.ShouldNotBeNullOrEmpty("the local host de-duplicates the broadcast copy by it");
// Sentinel AFTER the revert: a late duplicate would already be queued ahead of it.
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count >= 3);
rig.Project(false, ConditionMethodEventTests.PreState(method, 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");
ConditionMethodEventTests.AssertNewState(method, native: false, baseEvents[1]);
foreach (var field in new[] { RecordedEvents.AckedField, RecordedEvents.ConfirmedField, RecordedEvents.EnabledField,
RecordedEvents.ShelvingField, RecordedEvents.CommentField, RecordedEvents.RetainField })
baseEvents[2][field].ClrValue().ShouldBe(baseEvents[0][field].ClrValue(), $"field {field} is back to its pre-call value");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>Positive control: an applied verdict is Good, and the method still reports exactly one event.</summary>
[Fact]
public async Task A_command_the_engine_applies_returns_Good_with_one_event()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Applied", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" };
var routed = new ConcurrentQueue<AlarmCommand>();
rig.Nm.AlarmCommandRouter = routed.Enqueue;
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
// What the engine does: apply, then re-project (the method's own event already covered it).
current = current with { Acknowledged = true };
rig.ProjectLater(native: false, current);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied));
};
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, current);
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge",
events.LatestEventId(item, "base"), ct);
await rig.DrainProjectionsAsync();
rig.Project(false, current = current with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
events.ConditionEvents(item, "base").Count.ShouldBe(2, "the base transition plus exactly one Acknowledge event");
routed.ShouldBeEmpty("the asker replaces the fire-and-forget router inside a Call");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>No answer inside the bound: BadTimeout with OutcomeUnknown — never reported as refused.</summary>
[Fact]
public async Task An_unanswered_command_returns_BadTimeout_outcome_unknown()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Timeout", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(500);
var never = new TaskCompletionSource<AlarmCommandOutcome>();
rig.Nm.AlarmCommandAsker = (_, _) => never.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 started = DateTime.UtcNow;
var unknown = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
unknown.StatusCode.ShouldBe(StatusCodes.BadTimeout);
(DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(10), "bounded");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// The synchronous pre-check: while the last load failed, the call is refused BadInvalidState BEFORE the SDK applies
/// anything — nothing is asked or routed, and no condition event is reported (sentinel-checked).
/// </summary>
[Fact]
public async Task The_preflight_refuses_before_any_state_change()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Preflight", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var asked = 0;
var routed = 0;
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
Interlocked.Increment(ref asked);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied));
};
rig.Nm.AlarmCommandRouter = _ => Interlocked.Increment(ref routed);
string? refusal = "the last scripted-alarm deploy failed";
rig.Nm.ScriptedAlarmCommandPreflight = () => refusal;
var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" };
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, current);
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var refused = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState);
rig.Project(false, current with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
events.ConditionEvents(item, "base").Count.ShouldBe(1, "no Acknowledge event was reported");
events.ConditionEvents(item, "sentinel")[0][RecordedEvents.AckedField].ClrValue()!.ShouldBe(false, "the node was not acknowledged");
Volatile.Read(ref asked).ShouldBe(0);
Volatile.Read(ref routed).ShouldBe(0);
// Positive control: once a load succeeds the same call goes through.
refusal = null;
await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge",
events.LatestEventId(item, "sentinel"), ct);
Volatile.Read(ref asked).ShouldBe(1);
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// A NATIVE condition's AddComment is applied at the node (no scripted engine owns it): neither the scripted pre-check
/// nor the verdict ask applies, even while the scripted engine is blind (caught live by A02 on fu937-1).
/// </summary>
[Fact]
public async Task A_native_AddComment_is_not_subject_to_the_scripted_verdict()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937NativeComment", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseNative();
var asked = 0;
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
Interlocked.Increment(ref asked);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "not mine"));
};
rig.Nm.ScriptedAlarmCommandPreflight = () => "the scripted engine is blind";
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(true, ConditionMethodEventTests.PreState("AddComment", native: true) with { Message = "base" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, true), "AddComment",
events.LatestEventId(item, "base"), ct);
Volatile.Read(ref asked).ShouldBe(0);
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// #937 review r1: past the node-wide in-flight cap a call is refused BadTooManyOperations BEFORE the SDK applies anything
/// (nothing asked, node unchanged); a blank scripted AddComment is refused BadInvalidArgument the same way.
/// </summary>
[Fact]
public async Task Past_the_in_flight_cap_and_for_a_blank_comment_the_call_is_refused_before_any_state_change()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Cap", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.Nm.MaxScriptedCommandsInFlight = 1;
var release = new TaskCompletionSource<AlarmCommandOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var asked = new ConcurrentQueue<string>();
rig.Nm.AlarmCommandAsker = (cmd, _) => { asked.Enqueue(cmd.Operation); return release.Task; };
rig.Project(false, ConditionMethodEventTests.PreState("OneShotShelve", native: false) with { Message = "base" });
await rig.DrainProjectionsAsync();
using var first = await rig.ConnectAsync(anonymous: false, ct);
using var second = await rig.ConnectAsync(anonymous: false, ct);
var held = ConditionMethodEventTests.CallAsync(first, ConditionNodeId(first, false), "OneShotShelve", null, ct);
for (var i = 0; i < 200 && rig.Nm.ScriptedCommandsInFlight == 0; i++) await Task.Delay(25, ct);
rig.Nm.ScriptedCommandsInFlight.ShouldBe(1);
var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value;
var refused = await second.CallAsync(null, [new CallMethodRequest
{
ObjectId = ConditionNodeId(second, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText("over the cap"))],
}], ct);
refused.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse("nothing was applied");
var blank = await second.CallAsync(null, [new CallMethodRequest
{
ObjectId = ConditionNodeId(second, false), MethodId = MethodIds.ConditionType_AddComment,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText(" "))],
}], ct);
blank.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidArgument.Code);
asked.ToArray().ShouldBe(["OneShotShelve"], "neither refused call reached the engine");
// Positive control: releasing the held ask frees the slot and the held call completes Good.
release.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "OneShotShelve", AlarmCommandVerdict.Applied));
await held;
for (var i = 0; i < 200 && rig.Nm.ScriptedCommandsInFlight != 0; i++) await Task.Delay(25, ct);
rig.Nm.ScriptedCommandsInFlight.ShouldBe(0);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// #937 review r2 M1: a scripted method whose request deadline leaves less than the dispatch floor is refused
/// BadTimeout unsent (nothing asked, nothing applied); after the first unanswered scripted method of a batch the rest
/// of that batch's scripted methods are refused unsent — while a native method in the same batch still runs.
/// </summary>
[Fact]
public async Task A_too_close_deadline_or_an_earlier_unanswered_command_refuses_scripted_methods_unsent()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Deadline", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.MaterialiseNative();
rig.Nm.NativeAlarmAckRouter = _ => { };
rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(400);
var asked = new ConcurrentQueue<string>();
var never = new TaskCompletionSource<AlarmCommandOutcome>();
rig.Nm.AlarmCommandAsker = (cmd, _) => { asked.Enqueue(cmd.Operation); return never.Task; };
var pre = new AlarmConditionSnapshot(Active: true, Acknowledged: false, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: 700, Message: "pre");
rig.Project(false, pre);
rig.Project(true, pre);
await rig.DrainProjectionsAsync();
using var session = await rig.ConnectAsync(anonymous: false, ct);
ByteString EventIdOf(bool native) => rig.Nm.TryGetAlarmCondition(native ? RawAlarmPath : ScriptedAlarmId,
native ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns)!.EventId!.Value;
CallMethodRequest Request(bool native, NodeId method, string text) => new()
{
ObjectId = ConditionNodeId(session, native), MethodId = method,
InputArguments = [new Variant(EventIdOf(native)), new Variant(new LocalizedText(text))],
};
// (a) TimeoutHint 200 ms < grace + dispatch floor: refused unsent.
var tight = await session.CallAsync(new RequestHeader { TimeoutHint = 200 },
[Request(false, MethodIds.AcknowledgeableConditionType_Acknowledge, "tight")], ct);
tight.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
asked.ShouldBeEmpty("nothing was sent");
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse("nothing was applied");
// (b) one unanswered scripted method poisons the rest of its batch (scripted only).
var started = DateTime.UtcNow;
var batch = await session.CallAsync(null,
[
Request(false, MethodIds.AcknowledgeableConditionType_Acknowledge, "first"),
Request(false, MethodIds.ConditionType_AddComment, "second"),
Request(true, MethodIds.AcknowledgeableConditionType_Acknowledge, "native"),
Request(false, MethodIds.ConditionType_AddComment, "third"),
], ct);
batch.Results.ToArray()!.Select(r => r.StatusCode.Code).ToArray().ShouldBe(
[StatusCodes.BadTimeout.Code, StatusCodes.BadTimeout.Code, StatusCodes.Good.Code, StatusCodes.BadTimeout.Code]);
asked.ToArray().ShouldBe(["Acknowledge"], "only the first scripted method was sent");
(DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(3), "one bound for the batch, not one per request");
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// #937 review r2 L1: a refusal does not revert a node something else changed since the method — even a change that
/// leaves every compared field equal (here an identical re-projection, the shape of a Timed→Timed re-shelve).
/// </summary>
[Fact]
public async Task A_refusal_does_not_revert_a_node_changed_since_the_method()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937NoRevert", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var acked = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Acknowledged = true, Message = "base" };
rig.Nm.AlarmCommandAsker = (cmd, _) => Task.Run(() =>
{
// Another writer touches the node after the method (off Lock — the handler runs under it), leaving every
// field as the method left it.
rig.Project(false, acked);
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "refused");
});
rig.Project(false, acked with { Acknowledged = false });
await rig.DrainProjectionsAsync();
using var session = await rig.ConnectAsync(anonymous: false, ct);
var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value;
var refused = await session.CallAsync(null, [new CallMethodRequest
{
ObjectId = ConditionNodeId(session, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText("x"))],
}], ct);
refused.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidState.Code);
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeTrue("the newer write wins over the revert");
}
finally { await rig.DisposeAsync(); }
}
/// <summary>A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict.</summary>
[Fact]
public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Remote", encrypted: false, ct);
try
{
rig.MaterialiseScripted();
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
await rig.DrainProjectionsAsync();
rig.Nm.AlarmCommandAsker = (cmd, _) =>
Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind"));
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 refused = await rig.Nm.ExecuteConditionMethodAsync(call, TimeSpan.FromSeconds(5));
refused.Applied.ShouldBeFalse();
refused.Dispatched.ShouldBeTrue();
refused.Unknown.ShouldBeFalse();
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code);
refused.Diagnostic.ShouldBe("engine blind");
}
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(); }
}
/// <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(); }
}
}