fix(alarms): a native condition's AddComment is not subject to the scripted verdict (#937)

Native AddComment shares HandleAlarmCommand but is applied at the node only;
asking the scripted host made it BadInvalidState (live A02 on fu937-1).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-28 11:01:47 -05:00
parent 4d41e61858
commit e45012b69d
3 changed files with 48 additions and 5 deletions
@@ -558,7 +558,8 @@ class ConditionScenarios:
finally: finally:
restored_at = self.utc(-2) restored_at = self.utc(-2)
self.r.mutate(scripted_predicate=good) self.r.mutate(scripted_predicate=good)
loaded = wait_for(lambda: self.log_lines(source, restored_at, "ScriptedAlarmEngine loaded"), 120) # The engine's own "loaded" line rides the script-log topic; the host's re-assert of the still-active condition is on stdout.
loaded = wait_for(lambda: self.log_lines(source, restored_at, "ScriptedAlarmHost: re-asserted"), 120)
self.check("origin_engine_reloaded", loaded) self.check("origin_engine_reloaded", loaded)
# Positive control: the first good load after a failed one is a new occurrence (documented); the ack now succeeds. # Positive control: the first good load after a failed one is a new occurrence (documented); the ack now succeeds.
fresh = wait_for(lambda: self.latest(origin, name, lambda b: b.get("State") == "Active, Unacknowledged" fresh = wait_for(lambda: self.latest(origin, name, lambda b: b.get("State") == "Active, Unacknowledged"
@@ -2649,7 +2649,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
? new ServiceResult(StatusCodes.BadNotSupported) ? new ServiceResult(StatusCodes.BadNotSupported)
: HandleAlarmCommand(context, condition, "Confirm", comment, unshelveAt: null); : HandleAlarmCommand(context, condition, "Confirm", comment, unshelveAt: null);
alarm.OnAddComment = (context, condition, _, comment) => alarm.OnAddComment = (context, condition, _, comment) =>
HandleAlarmCommand(context, condition, "AddComment", comment, unshelveAt: null); // A native AddComment is applied at the node only (no engine owns it): no scripted pre-check or verdict (#937).
HandleAlarmCommand(context, condition, "AddComment", comment, unshelveAt: null,
scriptedEngine: !IsNativeAlarmNode(alarmNodeId, realm));
alarm.OnShelve = (context, condition, shelving, oneShot, shelvingTime) => alarm.OnShelve = (context, condition, shelving, oneShot, shelvingTime) =>
{ {
if (IsNativeAlarmNode(alarmNodeId, realm)) return new ServiceResult(StatusCodes.BadNotSupported); if (IsNativeAlarmNode(alarmNodeId, realm)) return new ServiceResult(StatusCodes.BadNotSupported);
@@ -3194,10 +3196,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// <param name="operation">The Part 9 operation name (e.g. <c>Acknowledge</c>, <c>TimedShelve</c>).</param> /// <param name="operation">The Part 9 operation name (e.g. <c>Acknowledge</c>, <c>TimedShelve</c>).</param>
/// <param name="comment">The call's comment text, or <c>null</c> when none was supplied.</param> /// <param name="comment">The call's comment text, or <c>null</c> when none was supplied.</param>
/// <param name="unshelveAt">For <c>TimedShelve</c>, the computed UTC expiry; otherwise <c>null</c>.</param> /// <param name="unshelveAt">For <c>TimedShelve</c>, the computed UTC expiry; otherwise <c>null</c>.</param>
/// <param name="scriptedEngine">#937: false for a NATIVE condition's AddComment (applied at the node; no engine owns it) —
/// no scripted pre-check, no verdict ask; the fire-and-forget router as before.</param>
/// <returns><c>ServiceResult.Good</c> when allowed (the SDK then applies state, and the method path /// <returns><c>ServiceResult.Good</c> when allowed (the SDK then applies state, and the method path
/// reports the one condition event);<c>BadUserAccessDenied</c> when the gate vetoes (no route, no state mutation).</returns> /// reports the one condition event);<c>BadUserAccessDenied</c> when the gate vetoes (no route, no state mutation).</returns>
private ServiceResult HandleAlarmCommand( private ServiceResult HandleAlarmCommand(
ISystemContext context, ConditionState condition, string operation, LocalizedText? comment, DateTime? unshelveAt) ISystemContext context, ConditionState condition, string operation, LocalizedText? comment, DateTime? unshelveAt,
bool scriptedEngine = true)
{ {
// Resolve the principal the SAME way the SDK's own GetCurrentUserId does, then narrow to the // Resolve the principal the SAME way the SDK's own GetCurrentUserId does, then narrow to the
// role-carrying identity T17 attached. Anonymous / non-role-carrying identities ⇒ null ⇒ denied. // role-carrying identity T17 attached. Anonymous / non-role-carrying identities ⇒ null ⇒ denied.
@@ -3212,7 +3217,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #937: this node's engine holds no complete generation (its last load failed) and would reject the command — // #937: this node's engine holds no complete generation (its last load failed) and would reject the command —
// refuse it before the SDK applies anything (no event, nothing routed). One volatile read; safe under Lock. // refuse it before the SDK applies anything (no event, nothing routed). One volatile read; safe under Lock.
if (ScriptedAlarmCommandPreflight?.Invoke() is { } notReady) if (scriptedEngine && ScriptedAlarmCommandPreflight?.Invoke() is { } notReady)
return new ServiceResult(StatusCodes.BadInvalidState, new LocalizedText(notReady)); return new ServiceResult(StatusCodes.BadInvalidState, new LocalizedText(notReady));
var cmd = new AlarmCommand( var cmd = new AlarmCommand(
@@ -3224,7 +3229,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #937: inside a Call that awaits the engine's verdict (CallAsync / ExecuteConditionMethodAsync), start the // #937: inside a Call that awaits the engine's verdict (CallAsync / ExecuteConditionMethodAsync), start the
// bounded ask — non-blocking: it only sends — and let the caller await it once Lock is released. // bounded ask — non-blocking: it only sends — and let the caller await it once Lock is released.
if (TryStartScriptedCommandAsk(cmd)) return ServiceResult.Good; if (scriptedEngine && TryStartScriptedCommandAsk(cmd)) return ServiceResult.Good;
// Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock. // Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock.
AlarmCommandRouter?.Invoke(cmd); AlarmCommandRouter?.Invoke(cmd);
@@ -189,6 +189,43 @@ public sealed class ScriptedCommandVerdictWireTests
finally { await rig.DisposeAsync(); } 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>A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict.</summary> /// <summary>A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict.</summary>
[Fact] [Fact]
public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched() public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched()