diff --git a/.claude/rules/alarms.md b/.claude/rules/alarms.md index 795fe298e..5e154ff40 100644 --- a/.claude/rules/alarms.md +++ b/.claude/rules/alarms.md @@ -100,7 +100,10 @@ once) and returns Good; the Call then settles the verdict — one request at a t changed since); no answer (min 5 s / deadline − 250 ms) ⇒ `BadTimeout` "OutcomeUnknown" (never "refused" — it may still apply; node kept). The peer gets the broadcast only AFTER an applied/unknown local verdict (`ScriptedAlarmCommandDispatch`) — broadcasting first let the peer apply a command the caller was told failed. ≤ 64 asks in flight node-wide, else -`BadTooManyOperations` before anything applies. A native AddComment skips all of this (no engine owns it). Remote gRPC-data methods ride +`BadTooManyOperations` before anything applies. A native AddComment skips all of this (no engine owns it). Review r2: a +deadline leaving < 250 ms, or an earlier unanswered scripted method in the same Call, refuses the method `BadTimeout` +unsent; `OpcUa:Quotas:MaxNodesPerMethodCall` (1000) bounds a Call; an ask expired in the host mailbox skips the engine and is +not remembered (its broadcast copy applies); the revert is guarded by a per-condition mutation counter, not field equality. 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 is still fire-and-forget. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics). diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index ef170a8b9..ee9b6d1f7 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -438,7 +438,14 @@ of which blocks under the node manager's `Lock`: revert. Cheap refusals the engine would make (a blank scripted AddComment ⇒ `BadInvalidArgument`) happen in the handler, before the SDK applies anything. 3. **Load bound** — at most 64 asks outstanding node-wide (`MaxScriptedCommandsInFlight`); past it the call is refused - `BadTooManyOperations` before anything is applied or sent. Each request's 5 s bound starts when its own ask is sent. + `BadTooManyOperations` before anything is applied or sent. Each request's 5 s bound starts when its own ask is sent and + is cut by the request deadline; a scripted method whose deadline leaves less than 250 ms (after a 250 ms grace) is + refused `BadTimeout` unsent, and after the FIRST scripted method of a batch that got no answer every later scripted + method of that batch is refused `BadTimeout` unsent (non-scripted methods in the batch still run) — so a wedged engine + costs one bound per Call, not one per method. A Call carries at most `OpcUa:Quotas:MaxNodesPerMethodCall` methods + (default 1000; the SDK default 0 was unlimited; 0 restores it). The host answers an ask still queued past its asker's + deadline without touching the engine and without remembering it, so its broadcast copy (which the peer also received — + the asker had reported OutcomeUnknown) is what applies; late work cannot pile up behind a stalled store. Measured through one host with the production LocalDb store (`ScriptedAlarmCommandThroughputTests`): 300 sequential acks in 59 ms (max 11 ms each); 300 AddComments with 64 outstanding at once in 49 ms (max 24 ms each). @@ -459,6 +466,15 @@ broadcast, so no engine anywhere applied it and the revert plus the definite fai gRPC-data `CallConditionMethod` on a scripted condition carries the same verdict (`ExecuteConditionMethodAsync`): applied ⇒ `DriverConfirmedSuccess`, refused after dispatch ⇒ `DriverConfirmedFailure`, no answer ⇒ `OutcomeUnknown`. +**Behaviour change (review r2 L5).** A scripted method is now REFUSED (`BadInvalidState`), reverted, and NOT broadcast to +the redundant peer when this node has no scripted-alarm host (no condition-state store, or the host not yet spawned) or the +host does not own the alarm — including the window after a host supervision restart before its configuration is re-sent. +Before #937 such a call returned Good and the broadcast let the peer apply it. + +**Revert guard.** A refusal reverts the node only when its per-condition mutation counter (bumped by every projection, +every reported condition event and every accepted method) is unchanged since the method — a field comparison missed a +Timed→Timed re-shelve or a ClientUserId change. The captured raw severity is restored as captured. + **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). A command racing the engine's first load queues behind it rather than failing. diff --git a/docs/plans/evidence/followups/937.md b/docs/plans/evidence/followups/937.md index 8c13bbd65..b6b9280cb 100644 --- a/docs/plans/evidence/followups/937.md +++ b/docs/plans/evidence/followups/937.md @@ -87,3 +87,20 @@ origin `ack` ⇒ `Acknowledge successful` (positive control). | Host.Tests (incl. `GrpcDataV1CompatibilityTests`) | 503 passed | | Commons.Tests / Core.ScriptedAlarms.Tests | 513 / 147 passed | | Live `fu937-3` (`6004a5a56`) | F937 + A01 + A02 3/3 PASS; rig down | + +## Review round 2 + +| # | Finding | Outcome | Red on revert | +|---|---|---|---| +| M1 | Each request floored at 50 ms ⇒ past the deadline every remaining request still applied/asked; TimeoutHint 0 × wedged engine ≈ 5 s per method | **Fixed.** Deadline (− 250 ms grace) leaving < the 250 ms dispatch floor ⇒ the scripted handler refuses `BadTimeout` unsent (the SDK applies nothing); after the first timed-out OutcomeUnknown in a batch the rest of its scripted methods are refused the same way (non-scripted still run). New quota `OpcUa:Quotas:MaxNodesPerMethodCall` = 1000 (SDK default 0 = unlimited; 0 restores it). | `A_too_close_deadline_or_an_earlier_unanswered_command_refuses_scripted_methods_unsent` red with the floor/poison removed; quota pinned in `OpcUaApplicationHostQuotaTests` | +| M2 | Cap released on Ask timeout while the command stays queued in the host ⇒ unbounded late work | **Fixed.** `ExecuteAlarmCommand.DeadlineUtc`; an expired ask is answered without touching the engine and NOT remembered, so its broadcast copy (already sent on Unknown) applies. Answered OutcomeUnknown rather than NotApplied: the broadcast copy may still apply here, so "not applied" would be untrue (nobody is waiting for it anyway). | `An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply` red with the check removed | +| L1 | Revert guard compared delta + comment | **Fixed.** Per-instance mutation counter (`ConditionalWeakTable`), bumped in `ApplyConditionState`, `ReportConditionEvent` and on every accepted method in `ReportAfterMethod`. | `A_refusal_does_not_revert_a_node_changed_since_the_method` (identical re-projection) red with the guard removed | +| L5 | Behaviour change undocumented | `docs/ScriptedAlarms.md`: no local host / not owned (incl. the post-supervision-restart window) ⇒ refused + reverted + no peer broadcast. | docs | +| nits | stale hosted-service comment; severity 0 ⇒ 1 on revert | Fixed (comment says ask-then-broadcast; the raw captured severity is restored). | — | +| SDK check | Does any Part 9 handler call our delegate before its own validation? | **No** (decompiled SDK 2.0.1): Acknowledge/Confirm/AddComment run the delegate at the END of `ProcessBefore*` (after EventId/Enabled/already-acked/IsLive); the three shelve methods after Enabled + `IsCausePermitted` (+ shelving-time range); Enable/Disable after the already-enabled checks. Nothing after a Good delegate can turn the call Bad, so a started ask is always awaited. (Branch acks would recurse into a branch's own delegate — this server creates no branches.) | — | + +Follow-ups (not fixed): **L2** a late refusal that arrives after the ask's timeout (the caller got OutcomeUnknown) is never reverted; **L3** a command cancelled while waiting on `_evalGate` (nothing applied) is reported OutcomeUnknown, not NotApplied; **L4** `OnLoadFailed` reads `HasCompleteGeneration` while a newer load may already be running (transiently refuses during that load). + +Gates (round 2): build 0 warnings / 0 errors; OpcUaServer.Tests 1460 passed / 2 skipped; OpcUaServer.IntegrationTests 441 / 39 skipped; +Runtime.Tests 2122 / 3 skipped; Host.Tests 503; Commons.Tests 513; Core.ScriptedAlarms.Tests 147. No live re-run (the dispatch +order is unchanged; the new refusals are pre-dispatch and the expiry skip is host-local). diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index d01828030..4dd46ca08 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -320,9 +320,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl }); // #937: a scripted condition's Part 9 method answers with THIS node's engine verdict. The pre-check (one volatile - // read) refuses while the last scripted-alarm load failed; the asker broadcasts the command to the redundant peer - // exactly as the router above does and asks the local engine (via the DriverHostActor) for its verdict. Both run - // under the SDK's Lock and only read / send; the node manager awaits the verdict off Lock. + // read) refuses while the last scripted-alarm load failed; the asker asks the local engine (via the DriverHostActor) + // for its verdict FIRST and broadcasts to the redundant peer only after an applied / unknown verdict + // (ScriptedAlarmCommandDispatch). Both run under the SDK's Lock and only read / send; the node manager awaits the + // verdict off Lock. if (_scriptedAlarmReadiness is { } readiness) _server.NodeManager.ScriptedAlarmCommandPreflight = readiness.Refusal; _server.NodeManager.AlarmCommandAsker = AskScriptedAlarmCommand; @@ -613,7 +614,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl private Task AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout) { Func>? askLocal = _actorRegistry.TryGet(out var driverHost) - ? (c, t) => driverHost.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c), t) + ? (c, t) => driverHost.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c, DateTime.UtcNow + t), t) : null; return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal, c => DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, c)), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs index 930c5e131..a5b900955 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs @@ -155,13 +155,26 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager // #937 review r1: one request at a time, each verdict (and any revert) settled before the next request runs, so a // later request in the batch (e.g. Confirm after a refused Acknowledge) never runs against a node state the engine // refused. The bound is taken per request, when its ask is sent. + // Review r2 M1: past the request deadline (less the dispatch floor) a scripted method is refused unsent in its + // handler — before the SDK applies anything — and so is every scripted method after the first one of this batch + // that got no answer (a wedged engine would otherwise cost one full bound per remaining request). Non-scripted + // requests in the batch still run. + ServiceResult? poisoned = null; for (var i = 0; i < methodsToCall.Count; i++) { if (methodsToCall[i] is not { Processed: false }) continue; var bound = ScriptedCommandBound(context.OperationDeadline); - if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound) is not { } pending) continue; - var status = await SettleScriptedVerdictAsync(pending, bound).ConfigureAwait(false); + var refusal = poisoned ?? (bound is null + ? new ServiceResult(StatusCodes.BadTimeout, + new LocalizedText("The request deadline leaves no time for the scripted-alarm engine; the command was not sent.")) + : null); + if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound ?? TimeSpan.Zero, refusal) is not { } pending) + continue; + var (status, unknown) = await SettleScriptedVerdictAsync(pending, bound ?? TimeSpan.Zero).ConfigureAwait(false); if (!ServiceResult.IsGood(status)) errors[i] = status; + if (unknown && status.StatusCode.Code == StatusCodes.BadTimeout.Code) + poisoned = new ServiceResult(StatusCodes.BadTimeout, + new LocalizedText("An earlier scripted-alarm command in this request got no answer; this one was not sent.")); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OpcUaApplicationHost.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OpcUaApplicationHost.cs index e22f65fed..b123e9d29 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OpcUaApplicationHost.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OpcUaApplicationHost.cs @@ -271,6 +271,14 @@ public sealed class OpcUaQuotaOptions /// burst ceiling review 01 P6 flagged. public int MaxQueuedRequestCount { get; set; } = 200; + /// + /// Most methods one Call request may carry (advertised as OperationLimits/MaxNodesPerMethodCall; a larger + /// request is refused BadTooManyOperations by the SDK). Default 1000 — the SDK default is 0 = unlimited, and + /// #937 settles a batch's scripted-alarm methods one at a time against the engine, so an unbounded batch is an + /// unbounded request. 0 = unlimited. + /// + public uint MaxNodesPerMethodCall { get; set; } = 1000; + /// Per-operation timeout in milliseconds; null keeps the SDK default. public int? OperationTimeoutMs { get; set; } @@ -860,6 +868,8 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable serverConfig.MinRequestThreadCount = quotas.MinRequestThreadCount; serverConfig.MaxRequestThreadCount = quotas.MaxRequestThreadCount; serverConfig.MaxQueuedRequestCount = quotas.MaxQueuedRequestCount; + serverConfig.OperationLimits ??= new OperationLimits(); + serverConfig.OperationLimits.MaxNodesPerMethodCall = quotas.MaxNodesPerMethodCall; } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs index 29f1c84d9..a8efd90b4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; +using System.Runtime.CompilerServices; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; @@ -48,14 +49,25 @@ public sealed partial class OtOpcUaNodeManager /// The default node-wide cap on outstanding scripted-command asks. internal const int DefaultMaxScriptedCommandsInFlight = 64; - /// The shortest bound a local call is given (the request deadline can be closer than this; the SDK then answers - /// the client's timeout itself). - private static readonly TimeSpan MinimumScriptedCommandBound = TimeSpan.FromMilliseconds(50); private static readonly AsyncLocal PendingScriptedCommandSlot = new(); private int _scriptedCommandsInFlight; + /// + /// #937 review r2 L1: a per-condition-instance mutation counter, bumped (under Lock) by every projection, every + /// reported condition event and every accepted method — the proof a pending revert needs that nothing changed the + /// node since its method. A field comparison missed changes that leave every compared field equal (a Timed→Timed + /// re-shelve, a ClientUserId change). Keyed by instance, so a torn-down condition takes its counter with it. + /// + private readonly System.Runtime.CompilerServices.ConditionalWeakTable> _conditionMutations = new(); + + /// Counts one mutation of . Caller holds Lock. + private void BumpConditionMutation(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value++; + + /// The mutation count of . Caller holds Lock. + private long ConditionMutationOf(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value; + /// /// #937 layer 1: returns why this node's scripted-alarm engine would reject any operator command right now (its last /// load failed), or null to proceed. Called under Lock: MUST be a lock-free read, no I/O. Null ⇒ no pre-check. @@ -84,9 +96,12 @@ public sealed partial class OtOpcUaNodeManager /// is set the moment that call returns: an AsyncLocal value is captured by anything the SDK starts inside it (a /// TimedShelve's timer), so a later callback must find the slot closed rather than park an ask nobody awaits. /// - private sealed class PendingScriptedCommand(TimeSpan timeout) + private sealed class PendingScriptedCommand(TimeSpan timeout, ServiceResult? refusal = null) { public TimeSpan Timeout { get; } = timeout; + /// Set ⇒ a scripted method in this request is refused with it in the handler, unsent and unapplied + /// (review r2 M1: the request deadline is too close, or an earlier scripted method of the batch got no answer). + public ServiceResult? Refusal { get; } = refusal; public Task? Outcome { get; set; } public ScriptedMethodRevert? Revert { get; set; } public volatile bool Closed; @@ -97,7 +112,7 @@ public sealed partial class OtOpcUaNodeManager /// the engine refuses, and the post-call state that proves nothing else has changed the node since. /// private sealed record ScriptedMethodRevert(RealmKey Key, AlarmConditionState Alarm, AlarmConditionSnapshot Before, - LocalizedText? BeforeComment, string? BeforeClientUserId, AlarmConditionDelta After, LocalizedText? AfterComment); + ushort BeforeSeverity, LocalizedText? BeforeComment, string? BeforeClientUserId, long AfterMutation); /// The slot of the request being called on this flow, when it is still open. private static PendingScriptedCommand? OpenScriptedSlot() => PendingScriptedCommandSlot.Value is { Closed: false } slot ? slot : null; @@ -110,6 +125,7 @@ public sealed partial class OtOpcUaNodeManager private ServiceResult? TryStartScriptedCommandAsk(AlarmCommand cmd) { if (OpenScriptedSlot() is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return null; + if (pending.Refusal is { } refused) return refused; if (Interlocked.Increment(ref _scriptedCommandsInFlight) > MaxScriptedCommandsInFlight) { Interlocked.Decrement(ref _scriptedCommandsInFlight); @@ -147,7 +163,8 @@ public sealed partial class OtOpcUaNodeManager delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null); var comment = alarm.Comment?.Value; var clientUserId = alarm.ClientUserId?.Value; - return () => new ScriptedMethodRevert(key, alarm, before, comment, clientUserId, ReadConditionDelta(alarm), alarm.Comment?.Value); + var severity = alarm.Severity?.Value ?? (ushort)0; + return () => new ScriptedMethodRevert(key, alarm, before, severity, comment, clientUserId, ConditionMutationOf(alarm)); } /// From ReportAfterMethod, under Lock, after a Good method applied and reported: park the revert @@ -168,7 +185,7 @@ public sealed partial class OtOpcUaNodeManager lock (Lock) { if (!_alarmConditions.TryGetValue(revert.Key, out var live) || !ReferenceEquals(live, revert.Alarm) - || ReadConditionDelta(live) != revert.After || !Equals(live.Comment?.Value, revert.AfterComment)) + || ConditionMutationOf(live) != revert.AfterMutation) { _logger.LogInformation( "OtOpcUaNodeManager: refused scripted command on {Condition} not reverted — the condition changed since the call", @@ -181,15 +198,20 @@ public sealed partial class OtOpcUaNodeManager _conditionUnshelveAt[revert.Key] = unshelveAt; else _conditionUnshelveAt.Remove(revert.Key); ApplyConditionState(live, revert.Before, now); + // The raw captured severity: ApplyConditionState clamps to 1..1000, which would turn a 0 into 1. + if (live.Severity is not null && live.Severity.Value != revert.BeforeSeverity) live.Severity.Value = revert.BeforeSeverity; if (live.Comment is not null) live.Comment.Value = revert.BeforeComment ?? LocalizedText.Null; if (live.ClientUserId is not null) live.ClientUserId.Value = revert.BeforeClientUserId ?? string.Empty; ReportConditionEvent(live, now); } } - /// The bound for one local request: , cut by the request deadline (less a - /// grace, so the answer still lands inside the client's TimeoutHint). - private TimeSpan ScriptedCommandBound(DateTime deadline) + /// + /// The bound for one local request: , cut by the request deadline (less a grace, so + /// the answer still lands inside the client's TimeoutHint). Null ⇒ the deadline leaves less than the dispatch floor: + /// a scripted method in this request must be refused unsent (review r2 M1 — it used to be floored and sent anyway). + /// + private TimeSpan? ScriptedCommandBound(DateTime deadline) { var bound = ScriptedCommandTimeout; if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue) @@ -197,7 +219,7 @@ public sealed partial class OtOpcUaNodeManager var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace; if (byDeadline < bound) bound = byDeadline; } - return bound < MinimumScriptedCommandBound ? MinimumScriptedCommandBound : bound; + return bound < ImportedMethodMinimumDispatchBudget ? null : bound; } /// @@ -206,12 +228,12 @@ public sealed partial class OtOpcUaNodeManager /// asker wired). /// private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf methodsToCall, int index, - IList results, IList errors, TimeSpan bound) + IList results, IList errors, TimeSpan bound, ServiceResult? refusal) { var request = methodsToCall[index]; var singleResults = new List { results[index] }; var singleErrors = new List { errors[index] }; - var pending = new PendingScriptedCommand(bound); + var pending = new PendingScriptedCommand(bound, refusal); PendingScriptedCommandSlot.Value = pending; try { @@ -228,8 +250,9 @@ public sealed partial class OtOpcUaNodeManager return pending.Outcome is not null && ServiceResult.IsGood(singleErrors[0]) ? pending : null; } - /// The request's final status from its engine verdict, reverting the node on a refusal. Never throws. - private async Task SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound) + /// The request's final status from its engine verdict (and whether it is an OutcomeUnknown), reverting the node + /// on a refusal. Never throws. + private async Task<(ServiceResult Status, bool Unknown)> SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound) { var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome!, bound).ConfigureAwait(false); if (!ServiceResult.IsGood(status) && !unknown && pending.Revert is { } revert) @@ -243,7 +266,7 @@ public sealed partial class OtOpcUaNodeManager _logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused scripted command failed"); } } - return status; + return (status, unknown); } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index d14a6ed88..a3dac66b4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -1408,6 +1408,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// when the projection is a genuine change that must be reported as one event. private bool ApplyConditionState(AlarmConditionState condition, AlarmConditionSnapshot state, DateTime sourceTimestampUtc) { + BumpConditionMutation(condition); // #937 r2: any projection is a change a pending scripted revert must not undo var current = ReadConditionDelta(condition); var incoming = ToConditionDelta(state, condition); bool fire = ShouldFireConditionEvent(current, incoming); @@ -1585,6 +1586,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { // Fresh GUID-bytes EventId per event — mandatory for Part 9 ack correlation (T17 relies on it). alarm.EventId!.Value = ByteString.From(Guid.NewGuid().ToByteArray()); + BumpConditionMutation(alarm); // #937 r2 + // Time/ReceiveTime were already set to sourceTimestampUtc by the WriteAlarmCondition projection // immediately above; the assignment here is a locality repeat (same value, no behavioral change) // so the restamp is co-located with the EventId and ClearChangeMasks in the same method. @@ -3102,6 +3105,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } apply?.Invoke(); + // #937 r2 L1: every accepted method is a mutation, reported or not (a Timed→Timed re-shelve by another + // session changes no delta field but must still stop an older call's revert). + BumpConditionMutation(alarm); if (isAcknowledge && alarm.ConfirmedState is not null) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs index 260a8b4f9..427cac6f4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs @@ -94,7 +94,10 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor /// redundant peer; this host applies whichever copy arrives first and skips the other. /// /// The command. - public sealed record ExecuteAlarmCommand(AlarmCommand Command); + /// #937 review r2 M2: when the asker stops waiting. An ask still queued past it is answered + /// without touching the engine (the asker reported OutcomeUnknown and broadcast the command; the broadcast copy decides + /// what this host applies). Null ⇒ no deadline. + public sealed record ExecuteAlarmCommand(AlarmCommand Command, DateTime? DeadlineUtc = null); /// /// Told to the parent from . A supervision restart is otherwise invisible to the @@ -822,6 +825,18 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor return; } + // Review r2 M2: the asker already gave up (OutcomeUnknown) and broadcast the command — applying it now, minutes late + // behind a stalled store, would only grow this mailbox. Skipped without touching the engine and NOT remembered, so + // the broadcast copy of the same command (which the peer also got) still applies here. + if (msg.DeadlineUtc is { } deadline && DateTime.UtcNow >= deadline) + { + _log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} skipped on the direct path — its asker stopped waiting; the broadcast copy applies", + cmd.Operation, cmd.AlarmId); + replyTo.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, + "OutcomeUnknown: the ask expired before the engine reached it.", TimedOut: true)); + return; + } + var outcome = Owns(cmd.AlarmId) ? await ApplyCommandAsync(cmd) : new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs index c116bd332..a6510018b 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs @@ -296,6 +296,102 @@ public sealed class ScriptedCommandVerdictWireTests finally { await rig.DisposeAsync(); } } + /// + /// #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. + /// + [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(); + var never = new TaskCompletionSource(); + 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(); } + } + + /// + /// #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). + /// + [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(); } + } + /// A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict. [Fact] public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs index 0809e916b..6b98c68af 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs @@ -17,6 +17,7 @@ public sealed class OpcUaApplicationHostQuotaTests config.MinRequestThreadCount.ShouldBe(5); config.MaxRequestThreadCount.ShouldBe(100); config.MaxQueuedRequestCount.ShouldBe(200); + config.OperationLimits.MaxNodesPerMethodCall.ShouldBe(1000u, "#937: a Call is bounded (the SDK default 0 is unlimited)"); } [Fact] diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs index e543dce6c..b685efb20 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs @@ -72,6 +72,29 @@ public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase (await Ask(host, "alm-1", "AddComment", "second")).Verdict.ShouldBe(AlarmCommandVerdict.Applied); } + /// + /// #937 review r2 M2: an ask still queued past its asker's deadline never touches the engine (no growth of late work + /// behind a stalled store) and is NOT remembered — the broadcast copy of the same command still applies here. + /// + [Fact] + public async Task An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply() + { + var (host, engine, _, mux) = Spawn(); + host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")])); + mux.ExpectMsg(Timeout, cancellationToken: Ct); + + var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-late"); + var expired = await host.Ask( + new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct); + expired.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + engine.GetState("alm-1")!.Comments.ShouldBeEmpty("the expired ask never reached the engine"); + + host.Tell(cmd); // the broadcast copy (same CommandId) + // Positive control behind it in the mailbox: a fresh ask (in time) applies, so the copy was processed first. + (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"]); + } + [Fact] public async Task An_alarm_this_host_does_not_own_is_answered_not_applied() {