Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/WarmStandbyCloneMatrixTests.cs
T
Joseph Doherty 687256d68e
v2-ci / unit-tests (push) Has been cancelled
test(717): deferred Warm coverage - 2-node handover, DataEncoding, deleted/reused items, clone matrix, ACL stand-down, per-counter metrics
- T3 WarmSingletonHandoverTests: real 2-node cluster, singleton under ClusterSingletonManager on both nodes; the old
  incarnation's held-back publish (older revision, higher sequence) reaches a real Warm OpcUaPublishActor after the
  handover and never demotes the new Primary. Pin: a removed node cannot rejoin from its old ActorSystem; a new one
  rejoins younger (higher up-number).
- T6 DataEncoding: Binary/XML encoded reads of a structured tag projected on the Standby; scalar encoding error kept;
  a DefaultXml item is projected, then promoted through its own encoding (TypeId i=888).
- T7 item deleted between queue and publish; ClientHandle reused by i=2267 on a payload recycled through the SDK 2.0.1
  pool (precondition asserted); WarmStandbyCloneMatrixTests over DataChange+DiagnosticInfos/EventNotificationList/
  StatusChange, clone/cached immutability, encode round-trip, real-pool stale marker.
- T8 ACL-stood-down item receives nothing from demotion or promotion; restored grant reaches it again.
- T10 per-counter MeterListener tests (by instrument instance): warm_transition, warm_role gauge, snapshot_rejected
  (publish actor both reasons + DriverHostActor's ordering gate, first actor test of it), projected_notifications,
  suppressed_alarm_events. Process-wide state tests run in non-parallel collections.
- Every test mutation-checked (26 mutations killed); no product bug found. Plan status updated.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 04:31:11 -05:00

210 lines
10 KiB
C#

using Opc.Ua;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>The SDK's notification-payload pool is process-wide; the recycled-payload test must not race another
/// test renting from it.</summary>
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class SdkPayloadPoolCollection
{
/// <summary>The collection name.</summary>
public const string Name = "sdk-payload-pool";
}
/// <summary>
/// Gitea #717 T7, the payload matrix the D4 rewrite meets at delivery: SDK 2.0.1 hands each Publish and Republish a
/// <c>CoreUtils.Clone</c> of the cached message, which may carry several <see cref="DataChangeNotification"/>s (with
/// <see cref="DiagnosticInfo"/>s), an <see cref="EventNotificationList"/> and a <see cref="StatusChangeNotification"/>
/// side by side. Every payload kind must survive the clone, only marked ordinary-tag values may change, nothing the
/// SDK owns may be mutated, and the result must still encode. The stale-marker case is driven through the SDK's real
/// payload pool.
/// </summary>
[Collection(SdkPayloadPoolCollection.Name)]
public sealed class WarmStandbyCloneMatrixTests
{
private static readonly DateTimeUtc Source = (DateTimeUtc)new DateTime(2026, 11, 13, 8, 0, 0, DateTimeKind.Utc);
private static readonly DateTimeUtc Server = (DateTimeUtc)new DateTime(2026, 11, 13, 8, 0, 1, DateTimeKind.Utc);
private static DataValue Good(double v) => new(new Variant(v), StatusCodes.Good, Source, Server);
private static MonitoredItemNotification Marked(uint handle, double v)
{
var n = new MonitoredItemNotification { ClientHandle = handle, Value = Good(v) };
n.Message = new OrdinaryTagMarker(handle, n.Value);
return n;
}
/// <summary>The cached message as the SDK builds it: two data-change payloads (the first with per-item diagnostics),
/// an event list and a status change, in that order.</summary>
private static NotificationMessage Cached() => new()
{
SequenceNumber = 42,
PublishTime = Server,
NotificationData = new List<ExtensionObject>
{
new(new DataChangeNotification
{
MonitoredItems = new List<MonitoredItemNotification>
{
Marked(1, 1.5),
new() { ClientHandle = 2, Value = Good(2.5) }, // i=2267 or a condition child: unmarked
},
DiagnosticInfos = new List<DiagnosticInfo>
{
new() { SymbolicId = 11, AdditionalInfo = "first" },
new() { SymbolicId = 12, AdditionalInfo = "second" },
},
}),
new(new EventNotificationList
{
Events = new List<EventFieldList>
{
new() { ClientHandle = 9, EventFields = new List<Variant> { new("event-id"), new("message") } },
},
}),
new(new StatusChangeNotification { Status = StatusCodes.BadTimeout }),
new(new DataChangeNotification
{
MonitoredItems = new List<MonitoredItemNotification> { Marked(3, 3.5) },
}),
},
};
private static T Body<T>(NotificationMessage m, int index) where T : class, IEncodeable
{
m.NotificationData[index].TryGetValue<T>(out var body).ShouldBeTrue($"payload {index} is a {typeof(T).Name}");
return body!;
}
private static MonitoredItemNotification Item(NotificationMessage m, int payload, int item) =>
Body<DataChangeNotification>(m, payload).MonitoredItems[item];
private static byte[] Encode(NotificationMessage m) =>
BinaryEncoder.EncodeMessage(m, ServiceMessageContext.Create(DefaultTelemetry.Create(_ => { })));
[Fact]
public void Every_payload_kind_survives_the_delivery_clone_and_only_marked_values_are_rewritten()
{
var cached = Cached();
var cachedBytes = Encode(cached);
var delivered = CoreUtils.Clone(cached)!;
var deliveredBytes = Encode(delivered);
// The clone carries every marker, each still valid against its own (cloned) notification.
OrdinaryTagMarker.IsOrdinaryTag(Item(delivered, 0, 0)).ShouldBeTrue();
OrdinaryTagMarker.IsOrdinaryTag(Item(delivered, 0, 1)).ShouldBeFalse();
OrdinaryTagMarker.IsOrdinaryTag(Item(delivered, 3, 0)).ShouldBeTrue();
var projected = StandbyNotificationRewriter.Project(delivered, out var rewritten);
rewritten.ShouldBe(2, "both marked values, across both data-change payloads");
projected.SequenceNumber.ShouldBe(42u);
projected.PublishTime.ShouldBe(Server);
projected.NotificationData.Count.ShouldBe(4, "no payload is dropped or added");
Item(projected, 0, 0).Value.StatusCode.ShouldBe(StatusCodes.BadOutOfService);
Item(projected, 0, 0).Value.WrappedValue.IsNull.ShouldBeTrue();
Item(projected, 0, 0).Value.SourceTimestamp.ShouldBe(DateTimeUtc.MinValue);
Item(projected, 0, 0).Value.ServerTimestamp.ShouldBe(Server);
Item(projected, 0, 0).ClientHandle.ShouldBe(1u);
Item(projected, 0, 1).Value.ShouldBe(Good(2.5));
Item(projected, 3, 0).Value.StatusCode.ShouldBe(StatusCodes.BadOutOfService);
var diagnostics = Body<DataChangeNotification>(projected, 0).DiagnosticInfos;
diagnostics.Count.ShouldBe(2, "per-item diagnostics stay aligned with the items");
diagnostics[0].AdditionalInfo.ShouldBe("first");
diagnostics[1].AdditionalInfo.ShouldBe("second");
Body<EventNotificationList>(projected, 1).IsEqual(Body<EventNotificationList>(cached, 1)).ShouldBeTrue("events pass through");
Body<StatusChangeNotification>(projected, 2).Status.ShouldBe(StatusCodes.BadTimeout);
// Nothing the SDK owns moved: neither the per-delivery clone handed in nor the cached original.
Encode(delivered).ShouldBe(deliveredBytes, "the delivered clone is not mutated");
Encode(cached).ShouldBe(cachedBytes, "the cached message is not mutated");
OrdinaryTagMarker.IsOrdinaryTag(Item(cached, 0, 0)).ShouldBeTrue("the cached original keeps its marker for a later Republish");
// The projected message is wire-valid and the marker never reaches the wire.
var decoded = BinaryDecoder.DecodeMessage<NotificationMessage>(Encode(projected),
ServiceMessageContext.Create(DefaultTelemetry.Create(_ => { })))!;
decoded.NotificationData.Count.ShouldBe(4);
Item(decoded, 0, 0).Value.StatusCode.ShouldBe(StatusCodes.BadOutOfService);
Item(decoded, 0, 0).Message.ShouldBeNull();
Body<DataChangeNotification>(decoded, 0).DiagnosticInfos.Count.ShouldBe(2);
}
/// <summary>A Republish is a second clone of the same cached message: projecting it gives the same bytes.</summary>
[Fact]
public void Projecting_two_delivery_clones_of_one_cached_message_gives_identical_payloads()
{
var cached = Cached();
var first = StandbyNotificationRewriter.Project(CoreUtils.Clone(cached)!, out var a);
var second = StandbyNotificationRewriter.Project(CoreUtils.Clone(cached)!, out var b);
a.ShouldBe(b);
Encode(second).ShouldBe(Encode(first));
}
/// <summary>A message with no marked value comes back as the same instance (nothing rebuilt, nothing counted).</summary>
[Fact]
public void A_message_with_only_events_status_and_unmarked_values_is_returned_as_is()
{
var cached = Cached();
cached.NotificationData = new List<ExtensionObject> { cached.NotificationData[1], cached.NotificationData[2] };
var delivered = CoreUtils.Clone(cached)!;
ReferenceEquals(StandbyNotificationRewriter.Project(delivered, out var rewritten), delivered).ShouldBeTrue();
rewritten.ShouldBe(0);
}
/// <summary>
/// The SDK's own pool, not a hand-made stale marker: a payload stamped for an ordinary tag and returned (as
/// <c>SentMessageQueue</c> does on acknowledge) comes back out with its marker, here even reusing the SAME
/// ClientHandle. With a different value it is not an ordinary-tag notification and is never rewritten.
/// </summary>
[Fact]
public void A_payload_recycled_through_the_sdk_pool_keeps_its_stale_marker_which_never_validates()
{
var stamped = (MonitoredItemNotification)MonitoredItemNotificationActivator.Instance.CreateInstance();
stamped.ClientHandle = 7;
stamped.Value = Good(1.0);
stamped.Message = new OrdinaryTagMarker(7, stamped.Value);
stamped.Reuse();
// Rent until the stamped payload comes back (other pooled payloads may sit ahead of it), then return the rest.
var others = new List<MonitoredItemNotification>();
MonitoredItemNotification? recycled = null;
for (var i = 0; i <= PooledEncodeableType<MonitoredItemNotification>.DefaultMaximumRetained && recycled is null; i++)
{
var rented = (MonitoredItemNotification)MonitoredItemNotificationActivator.Instance.CreateInstance();
if (ReferenceEquals(rented, stamped)) recycled = rented;
else others.Add(rented);
}
foreach (var other in others) other.Reuse();
recycled.ShouldNotBeNull("precondition: the pool hands the stamped payload back out");
try
{
recycled.Message.ShouldBeOfType<OrdinaryTagMarker>("precondition: Initialize() does not clear the helper");
recycled.ClientHandle = 7; // the client reused the handle for a non-ordinary item
recycled.Value = new DataValue(new Variant((byte)90), StatusCodes.Good, Source, Server);
OrdinaryTagMarker.IsOrdinaryTag(recycled).ShouldBeFalse();
var message = new NotificationMessage
{
SequenceNumber = 1,
NotificationData = new List<ExtensionObject>
{
new(new DataChangeNotification { MonitoredItems = new List<MonitoredItemNotification> { recycled } }),
},
};
var projected = StandbyNotificationRewriter.Project(CoreUtils.Clone(message)!, out var rewritten);
rewritten.ShouldBe(0);
Item(projected, 0, 0).Value.StatusCode.ShouldBe(StatusCodes.Good);
}
finally
{
recycled.Message = null!;
recycled.Reuse();
}
}
}