diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs index 295506009..7b4bb5d30 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs @@ -88,6 +88,9 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical /// public void CompleteAddressSpaceApply() => _inner.CompleteAddressSpaceApply(); + /// + public void CompleteAddressSpaceApply(bool succeeded) => _inner.CompleteAddressSpaceApply(succeeded); + /// public void MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) => _inner.MarkConditionsKnown(source, conditionIds, realm); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs index cf98af301..fef6cfd6b 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs @@ -213,6 +213,15 @@ public interface IOpcUaAddressSpaceSink { } + /// + /// with the apply's outcome (A1 review S4): + /// is false for a throwing or degraded apply, and an SDK-backed sink then keeps a rebuild's condition-set + /// readiness withheld and emits no removal records for conditions the failed pass did not re-materialise. The + /// default forwards to the parameterless overload. + /// + /// Whether the apply completed cleanly. + void CompleteAddressSpaceApply(bool succeeded) => CompleteAddressSpaceApply(); + /// /// A1 (plan §5.1 T1/T2): the state of has been ESTABLISHED by /// (a driver's InitialAlarmStateDelivered, its backstop timer, or a scripted diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs index 21b016def..0719d030d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs @@ -39,6 +39,8 @@ public readonly record struct ConditionActivationMarker(string Incarnation, ulon /// The origin-owned activation marker (T3). /// The condition's Comment text, if any. /// Who left that comment, if recorded. +/// For a timed shelve, the absolute UTC expiry (A2 projects the remaining time from it); +/// otherwise null. public sealed record ConditionStateRecord( AddressSpaceRealm Realm, string ConditionId, @@ -59,7 +61,8 @@ public sealed record ConditionStateRecord( bool Retain, ConditionActivationMarker Activation, string? Comment = null, - string? ClientUserId = null); + string? ClientUserId = null, + DateTime? UnshelveTimeUtc = null); /// /// The node manager's SDK-free delta callback (plan §5.1). Implemented by the Runtime's ConditionStateHub. @@ -95,4 +98,34 @@ public interface IConditionStateSink /// /// The sink's watermark taken under the same hold. /// The copied records (each carries as its version). -public sealed record ConditionSnapshotSlice(long Watermark, IReadOnlyList Records); +/// +/// The watermark read BEFORE the snapshot enumerated its keys (the same for every slice of one snapshot). A condition +/// no slice holds — materialised after the enumeration — is covered by its deltas after this cursor. +/// +/// The node manager's apply generation (bumped when a rebuild begins) under this hold. +/// Whether the address-space apply was complete under this hold. +public sealed record ConditionSnapshotSlice( + long Watermark, + IReadOnlyList Records, + long StartCursor = 0, + long ApplyGeneration = 0, + bool ApplyComplete = false) +{ + /// + /// Whether the slices form a complete snapshot of the condition SET: every hold saw a completed apply of ONE + /// generation (review S3b — readiness atomic with the cut). False when a rebuild began during, or straddled, a + /// multi-slice snapshot: the caller retakes it (and keeps sending NotReady). The Primary verdict is the + /// caller's to combine. + /// + /// One snapshot's slices. + /// when complete and consistent. + public static bool IsCompleteSnapshot(IReadOnlyList slices) + { + ArgumentNullException.ThrowIfNull(slices); + if (slices.Count == 0) return false; // SnapshotConditions always returns at least one slice + var generation = slices[0].ApplyGeneration; + foreach (var s in slices) + if (!s.ApplyComplete || s.ApplyGeneration != generation) return false; + return true; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs index b2c0426db..09decc183 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs @@ -14,6 +14,12 @@ public sealed partial class OtOpcUaNodeManager /// The default most conditions one snapshot Lock hold copies (§5.5 MaxConditions). public const int DefaultMaxConditionsPerHold = 1000; + /// + /// The upper bound a caller's maxConditionsPerHold is clamped to (review S3c): at the measured + /// ≈ 1.7–2.9 µs per condition (§5.1) one hold stays ≈ 9–15 ms, whatever a mapping configures. + /// + public const int MaxConditionsPerHoldLimit = 5000; + /// Per-condition activation bookkeeping: the occurrence sequence plus the Active/Acked basis it was /// last compared against. Mutable, only touched under Lock. private sealed class ActivationEntry @@ -35,6 +41,11 @@ public sealed partial class OtOpcUaNodeManager // a consumer retire a condition that is still active at the origin). private readonly HashSet _rebuildPendingRemoval = new(); private bool _conditionApplyComplete; + // Bumped when a rebuild begins; captured under each snapshot hold so a caller can detect a rebuild that + // straddles a multi-slice snapshot (review S3b). + private long _conditionApplyGeneration; + // The absolute expiry of each timed-shelved condition (set by WriteAlarmCondition), for the record's UnshelveTimeUtc. + private readonly Dictionary _conditionUnshelveAt = new(); /// The serving incarnation the activation markers are minted under (one per node-manager lifetime). internal string ConditionIncarnation { get; set; } = Guid.NewGuid().ToString("N"); @@ -42,6 +53,9 @@ public sealed partial class OtOpcUaNodeManager /// Test seam: invoked after each snapshot Lock hold (outside it) with the records that hold copied. internal Action? OnConditionSnapshotHold { get; set; } + /// Test seam: invoked after a snapshot enumerated its keys and before its first hold (outside Lock). + internal Action? OnConditionSnapshotKeysEnumerated { get; set; } + /// /// The SDK-free condition-state delta callback (the Runtime's ConditionStateHub). Null = no hub; the /// known flags and activation markers are still maintained. Set once at host start. @@ -149,29 +163,45 @@ public sealed partial class OtOpcUaNodeManager /// snapshot defines the SET), never more than per Lock hold. /// Each slice carries the sink's watermark taken under the same hold, so a delta is either inside the slice or /// after its watermark. A consumer must register for deltas before snapshotting. + /// Review S3: every slice also carries — the watermark + /// read under Lock BEFORE the keys are enumerated — so a condition materialised (and activated) after + /// that point, which no slice holds, is covered by the deltas after the start cursor; and the apply generation + + /// complete flag captured under that slice's hold, so a caller can tell a snapshot cut during or across a + /// rebuild (). /// /// Realm + id filter (an export's root); evaluated outside Lock. - /// The most conditions one hold copies (≥ 1). + /// The most conditions one hold copies (≥ 1; clamped to + /// ). /// The slices in ascending (realm, id) order. public IReadOnlyList SnapshotConditions( Func scope, int maxConditionsPerHold = DefaultMaxConditionsPerHold) { ArgumentNullException.ThrowIfNull(scope); ArgumentOutOfRangeException.ThrowIfLessThan(maxConditionsPerHold, 1); + maxConditionsPerHold = Math.Min(maxConditionsPerHold, MaxConditionsPerHoldLimit); + + long startCursor; + lock (Lock) startCursor = _conditionStateSink?.Watermark ?? 0; // Key enumeration and the scope filter run OFF Lock (the map is concurrent and keys are immutable); a // condition added after this point is not in the snapshot but its materialise record is a delta. var keys = _alarmConditions.Keys.Where(k => scope(k.Realm, k.Id)) .OrderBy(k => k.Realm).ThenBy(k => k.Id, StringComparer.Ordinal).ToList(); - var slices = new List((keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold); - for (var start = 0; start < keys.Count; start += maxConditionsPerHold) + OnConditionSnapshotKeysEnumerated?.Invoke(); + // At least one hold even for an empty scope: an empty SET is a snapshot too, and its readiness must be cut. + var sliceCount = Math.Max(1, (keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold); + var slices = new List(sliceCount); + for (var start = 0; slices.Count < sliceCount; start += maxConditionsPerHold) { var end = Math.Min(start + maxConditionsPerHold, keys.Count); var records = new List(end - start); - long watermark; + long watermark, generation; + bool applyComplete; lock (Lock) { watermark = _conditionStateSink?.Watermark ?? 0; + generation = _conditionApplyGeneration; + applyComplete = _conditionApplyComplete; for (var i = start; i < end; i++) { if (_alarmConditions.TryGetValue(keys[i], out var condition)) @@ -180,7 +210,7 @@ public sealed partial class OtOpcUaNodeManager } OnConditionSnapshotHold?.Invoke(records.Count); - slices.Add(new ConditionSnapshotSlice(watermark, records)); + slices.Add(new ConditionSnapshotSlice(watermark, records, startCursor, generation, applyComplete)); } return slices; @@ -205,6 +235,7 @@ public sealed partial class OtOpcUaNodeManager private void ForgetConditionState(RealmKey key, AlarmConditionState condition) { _conditionStateKnown.Remove(key); + _conditionUnshelveAt.Remove(key); _activation.Remove(key, out var entry); _conditionStateSink?.Append(BuildConditionRecord(key, condition, 0, removed: true, entry)); } @@ -213,8 +244,10 @@ public sealed partial class OtOpcUaNodeManager private void CaptureConditionStateForRebuild() { _conditionApplyComplete = false; + _conditionApplyGeneration++; _conditionStateSink?.OnApplyStateChanged(false); _rebuildScriptedActivation.Clear(); + _conditionUnshelveAt.Clear(); foreach (var key in _alarmConditions.Keys) { _rebuildPendingRemoval.Add(key); @@ -228,8 +261,23 @@ public sealed partial class OtOpcUaNodeManager /// Under Lock, at CompleteAddressSpaceApply: announce the conditions the rebuild dropped /// for good, forget the rebuild memory and mark the apply complete. - private void CompleteConditionApply() + /// + /// Review S4: false for a throwing or degraded apply. Then a rebuild in progress is NOT completed: readiness + /// stays false and the pending-removal set is kept, so no removal record is emitted for a condition the failed + /// pass simply did not re-materialise (a consumer would retire a condition that may still be active). The + /// next successful apply completes it. + /// + private void CompleteConditionApply(bool succeeded) { + if (!succeeded) + { + if (!_conditionApplyComplete) + _logger.LogWarning( + "OtOpcUaNodeManager: the address-space apply failed or was degraded — condition snapshot readiness withheld and {Pending} pending removal(s) kept until an apply succeeds", + _rebuildPendingRemoval.Count); + return; + } + foreach (var key in _rebuildPendingRemoval) { if (_alarmConditions.ContainsKey(key)) continue; @@ -305,6 +353,7 @@ public sealed partial class OtOpcUaNodeManager c.Retain?.Value == true, new ConditionActivationMarker(ConditionIncarnation, entry?.Sequence ?? 0), c.Comment?.Value.Text, - c.ClientUserId?.Value); + c.ClientUserId?.Value, + delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 4d0e0520c..e78841536 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -1373,6 +1373,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { condition.SetConfirmedState(SystemContext, state.Confirmed); } + // A1 review nit: the absolute timed-shelve expiry rides the condition-state record (A2 projects it). + if (state.Shelving == AlarmShelvingKind.Timed && state.UnshelveAtUtc is { } unshelveAt) _conditionUnshelveAt[key] = unshelveAt; + else _conditionUnshelveAt.Remove(key); if (condition.ShelvingState is not null) { // SetShelvingState(shelved, oneShot, shelvingTime): map our 3-way kind onto the SDK's @@ -5683,7 +5686,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // re-assert does), then discards whatever captured state no materialise claimed. A condition the apply // replaced again after restoring it is skipped: the instance reported must be the one restored. /// - public void CompleteAddressSpaceApply() + public void CompleteAddressSpaceApply() => CompleteAddressSpaceApply(succeeded: true); + + /// + public void CompleteAddressSpaceApply(bool succeeded) { int reported = 0, discarded; lock (Lock) @@ -5701,7 +5707,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage discarded = _rebuildCarryOver.Count; _restoredConditionReports.Clear(); _rebuildCarryOver.Clear(); - CompleteConditionApply(); + CompleteConditionApply(succeeded); } if (reported > 0 || discarded > 0) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index 9d3358267..655fed51f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -141,6 +141,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre /// public void CompleteAddressSpaceApply() => _nodeManager.CompleteAddressSpaceApply(); + /// + public void CompleteAddressSpaceApply(bool succeeded) => _nodeManager.CompleteAddressSpaceApply(succeeded); + /// public void MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) => _nodeManager.MarkConditionsKnown(source, conditionIds, realm); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionStateHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionStateHub.cs index 11bbc7ddc..f52ab9ad3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionStateHub.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionStateHub.cs @@ -41,6 +41,9 @@ public sealed class ConditionStateHub : IConditionStateSink /// Default per-partition buffer capacity (records). public const int DefaultPartitionCapacity = 8192; + /// The default most records one returns (review nit: bounded, not int.MaxValue). + public const int DefaultReadMax = 1024; + private sealed class Partition { public readonly object Gate = new(); @@ -82,6 +85,16 @@ public sealed class ConditionStateHub : IConditionStateSink /// snapshot_complete may be sent: apply complete AND this node is Primary. public bool IsSnapshotComplete => _applyComplete && _primary?.ShouldActAsPrimary == true; + /// + /// snapshot_complete for ONE taken snapshot (review S3b): readiness read atomically with the cut — every + /// slice's hold saw a completed apply of one generation — AND this node is Primary. Prefer this over + /// , which a rebuild can flip between the read and the snapshot. + /// + /// The snapshot's slices (OtOpcUaNodeManager.SnapshotConditions). + /// Whether that snapshot may be sent as complete. + public bool IsSnapshotCompleteFor(IReadOnlyList slices) => + ConditionSnapshotSlice.IsCompleteSnapshot(slices) && _primary?.ShouldActAsPrimary == true; + /// public long Append(ConditionStateRecord record) { @@ -134,8 +147,9 @@ public sealed class ConditionStateHub : IConditionStateSink /// The reader's cursor (the slice watermark or the last version it applied). /// The most records to return. /// The read. - public ConditionDeltaRead Read(int partition, long afterVersion, int max = int.MaxValue) + public ConditionDeltaRead Read(int partition, long afterVersion, int max = DefaultReadMax) { + ArgumentOutOfRangeException.ThrowIfLessThan(max, 1); var p = _partitions[partition]; lock (p.Gate) { @@ -160,7 +174,7 @@ public sealed class ConditionStateHub : IConditionStateSink var all = new List(); for (var i = 0; i < _partitions.Length; i++) { - var read = Read(i, afterVersion); + var read = Read(i, afterVersion, DefaultPartitionCapacity); if (read.ResetRequired) return null; all.AddRange(read.Records); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs index d1c0e4108..8429f9bad 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -1345,7 +1345,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// private void FinishRebuild(RebuildAddressSpace msg, IActorRef requester, (bool Degraded, string? Reason) outcome) { - try { _sink.CompleteAddressSpaceApply(); } + // A1 review S4: a degraded/throwing apply must not complete a rebuild's condition set (no removal records for + // conditions it failed to re-materialise, readiness stays withheld). + try { _sink.CompleteAddressSpaceApply(succeeded: !outcome.Degraded); } catch (Exception ex) { _log.Error(ex, "OpcUaPublish: sink.CompleteAddressSpaceApply threw (correlation={Correlation})", msg.Correlation); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs index a561f439f..014b1d38e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs @@ -302,6 +302,118 @@ public sealed class ConditionStateNodeManagerTests : IDisposable await host.DisposeAsync(); } + /// Review S3a: a condition materialised and activated between the key enumeration and slice 1's hold is in + /// no slice, and its records are after the snapshot's START cursor — the slice watermark alone would hide them. + [Fact] + public async Task S3a_A_condition_materialised_after_the_enumeration_is_covered_by_deltas_after_the_start_cursor() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + const string Late = Device + "/Late"; + nm.OnConditionSnapshotKeysEnumerated = () => + { + nm.MaterialiseAlarmCondition(Late, Device, "Late", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + nm.WriteAlarmCondition(Late, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + }; + + var slices = nm.SnapshotConditions((_, _) => true); + + slices.SelectMany(x => x.Records).ShouldNotContain(r => r.ConditionId == Late); + slices.ShouldAllBe(x => x.StartCursor == slices[0].StartCursor); + var late = sink.Records.Where(r => r.ConditionId == Late).ToList(); + late.ShouldNotBeEmpty(); + late.ShouldAllBe(r => r.Version > slices[0].StartCursor); + late.ShouldAllBe(r => r.Version <= slices[0].Watermark); // why the start cursor is needed + await host.DisposeAsync(); + } + + /// Review S3b: readiness is cut with the snapshot — a rebuild that straddles a multi-slice snapshot (even one + /// that completes before the last hold) makes it incomplete; one inside a single apply generation is complete. + [Fact] + public async Task S3b_A_rebuild_straddling_a_multi_slice_snapshot_makes_it_incomplete() + { + var (host, nm, _) = await BootAsync(); + MaterialiseAll(nm); + ConditionSnapshotSlice.IsCompleteSnapshot(nm.SnapshotConditions((_, _) => true, 1)).ShouldBeFalse(); // not applied yet + nm.CompleteAddressSpaceApply(); + ConditionSnapshotSlice.IsCompleteSnapshot(nm.SnapshotConditions((_, _) => true, 1)).ShouldBeTrue(); + + var holds = 0; + nm.OnConditionSnapshotHold = _ => + { + if (++holds != 1) return; + nm.RebuildAddressSpace(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + }; + var slices = nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: 1); + + slices.Count.ShouldBe(3); + slices.ShouldAllBe(x => x.ApplyComplete); // each hold alone looks ready … + ConditionSnapshotSlice.IsCompleteSnapshot(slices).ShouldBeFalse(); // … but the cut spans two generations + await host.DisposeAsync(); + } + + /// Review S3c: a caller's per-hold maximum is clamped to . + [Fact] + public async Task S3c_MaxConditions_per_hold_is_clamped() + { + var (host, nm, _) = await BootAsync(); + nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw); + for (var i = 0; i <= OtOpcUaNodeManager.MaxConditionsPerHoldLimit; i++) + nm.MaterialiseAlarmCondition($"{Device}/C{i:00000}", Device, $"C{i:00000}", "OffNormalAlarm", 500, AddressSpaceRealm.Raw, isNative: true); + var holds = new List(); + nm.OnConditionSnapshotHold = holds.Add; + + nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: int.MaxValue); + + holds.ShouldBe([OtOpcUaNodeManager.MaxConditionsPerHoldLimit, 1]); + await host.DisposeAsync(); + } + + /// Review S4: a failed/degraded rebuild apply neither emits removal records for the conditions it did not + /// re-materialise nor flips readiness; the next successful apply completes it. + [Fact] + public async Task S4_A_failed_rebuild_apply_emits_no_removals_and_keeps_readiness_withheld() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + nm.RebuildAddressSpace(); + nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw); + nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + var before = sink.Records.Count; + + nm.CompleteAddressSpaceApply(succeeded: false); // the pass threw before re-creating Native2 and the scripted one + + sink.Records.Skip(before).ShouldNotContain(r => r.Removed); + sink.ApplyComplete.ShouldBe(false); + nm.IsConditionApplyComplete.ShouldBeFalse(); + + nm.CompleteAddressSpaceApply(succeeded: true); // a later successful apply (that also dropped them) + sink.Records.Skip(before).Where(r => r.Removed).Select(r => r.ConditionId).ShouldBe([Native2, Scripted], ignoreOrder: true); + sink.ApplyComplete.ShouldBe(true); + await host.DisposeAsync(); + } + + /// Review nit: a timed shelve's absolute expiry rides the record (A2 projects the remaining time). + [Fact] + public async Task A_timed_shelve_record_carries_its_UnshelveTime() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + var at = DateTime.UtcNow.AddMinutes(5); + nm.WriteAlarmCondition(Scripted, State(true, false) with { Shelving = AlarmShelvingKind.Timed, UnshelveAtUtc = at }, + DateTime.UtcNow, AddressSpaceRealm.Uns); + sink.Records.Last().ShouldSatisfyAllConditions( + r => r.Shelving.ShouldBe(AlarmShelvingKind.Timed), r => r.UnshelveTimeUtc.ShouldBe(at)); + nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); + sink.Records.Last().UnshelveTimeUtc.ShouldBeNull(); + AssertParity(nm, sink); + await host.DisposeAsync(); + } + // ---------------------------------------------------------------- helpers private static void MaterialiseAll(OtOpcUaNodeManager nm) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs index e05c52f35..52ab42d49 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs @@ -148,6 +148,27 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase cancellationToken: TestContext.Current.CancellationToken); } + /// Review S4: a throwing apply completes with succeeded: false (the node manager then keeps the + /// rebuild's readiness withheld and emits no removals); a clean one with true. + [Fact] + public void A_throwing_apply_completes_the_address_space_apply_as_failed() + { + var sink = new OrderSink(); + var fail = true; + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests( + sink, new AddressSpaceApplier(sink, NullLogger.Instance), + new OpcUaPublishActor.TestHooks { BeforePlan = () => { if (fail) throw new InvalidOperationException("boom"); } })); + + actor.Tell(Rebuild()); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => sink.Completions.ShouldBe([false]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + fail = false; + actor.Tell(Rebuild()); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => sink.Completions.ShouldBe([false, true]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + } + private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) => Sys.ActorOf(OpcUaPublishActor.PropsForTests( sink, new AddressSpaceApplier(sink, NullLogger.Instance), @@ -238,6 +259,14 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase lock (_gate) _conditions.Add(alarmNodeId); } + public List Completions { get { lock (_gate) return [.. _completions]; } } + private readonly List _completions = new(); + + public void CompleteAddressSpaceApply(bool succeeded) + { + lock (_gate) _completions.Add(succeeded); + } + public void RebuildAddressSpace() { lock (_gate) { _conditions.Clear(); _known.Clear(); }