fix(historian): preserve stable alarm delivery identities
v2-ci / build (pull_request) Successful in 5m52s
v2-ci / unit-tests (pull_request) Failing after 1h23m55s

This commit is contained in:
Joseph Doherty
2026-10-13 07:10:58 -04:00
parent 0ccfbbee5c
commit 109163621c
13 changed files with 341 additions and 27 deletions
@@ -0,0 +1,78 @@
using System.Text.Json;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests;
public sealed class AlarmHistorianEventIdentityTests
{
internal const string Payload = """{"AlarmId":"A","EquipmentPath":"S","AlarmName":"N","AlarmTypeName":"LimitAlarm","Severity":2,"EventKind":"Activated","Message":"m","User":"system","Comment":null,"TimestampUtc":"2026-01-01T00:00:00Z"}""";
internal const string QueueId = "52C8292271C629CCC2BFE4EC8C16A5E70CA7456C7D88BC282ABCEDF636F05901";
private static AlarmHistorianEvent Event() => new("A", "S", "N", "LimitAlarm", AlarmSeverity.High,
"Activated", "m", "system", null, new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc));
[Theory]
[InlineData(QueueId, "48bca092-b99d-8ea4-a2de-8b30d80a481a")]
[InlineData("persisted-row-v1", "39473040-002b-876c-a1e6-9a9ad4a60ded")]
public void Persisted_keys_have_frozen_versioned_delivery_GUID_vectors(string key, string expected)
{
Assert.Equal(Guid.Parse(expected), AlarmDeliveryIds.FromQueueId(key));
}
[Fact]
public void Delivery_identity_is_nonzero_and_a_copy_preserves_it()
{
var original = Event();
Assert.NotEqual(Guid.Empty, original.DeliveryId);
Assert.Equal(original.DeliveryId, (original with { }).DeliveryId);
Assert.Equal(original.DeliveryId, (original with { Comment = "copy" }).DeliveryId);
}
[Fact]
public void Business_equality_hash_and_historical_JSON_ignore_delivery_identity()
{
var first = Event();
var second = Event();
Assert.NotEqual(first.DeliveryId, second.DeliveryId);
Assert.Equal(first, second);
Assert.True(first == second);
Assert.Equal(first.GetHashCode(), second.GetHashCode());
Assert.Single(new HashSet<AlarmHistorianEvent> { first, second });
Assert.Equal(Payload, JsonSerializer.Serialize(first));
Assert.Equal(Payload, JsonSerializer.Serialize(second));
Assert.Equal(QueueId, AlarmSfSchema.DeriveId(Payload));
Assert.Equal(first, JsonSerializer.Deserialize<AlarmHistorianEvent>(Payload));
}
[Theory]
[InlineData("AlarmId")]
[InlineData("EquipmentPath")]
[InlineData("AlarmName")]
[InlineData("AlarmTypeName")]
[InlineData("Severity")]
[InlineData("EventKind")]
[InlineData("Message")]
[InlineData("User")]
[InlineData("Comment")]
[InlineData("TimestampUtc")]
public void Each_business_field_still_participates_in_equality(string field)
{
var first = Event();
var changed = field switch
{
"AlarmId" => first with { AlarmId = "B" },
"EquipmentPath" => first with { EquipmentPath = "T" },
"AlarmName" => first with { AlarmName = "Other" },
"AlarmTypeName" => first with { AlarmTypeName = "DiscreteAlarm" },
"Severity" => first with { Severity = AlarmSeverity.Low },
"EventKind" => first with { EventKind = "Cleared" },
"Message" => first with { Message = "other" },
"User" => first with { User = "operator" },
"Comment" => first with { Comment = "note" },
"TimestampUtc" => first with { TimestampUtc = first.TimestampUtc.AddTicks(1) },
_ => throw new ArgumentOutOfRangeException(nameof(field)),
};
Assert.NotEqual(first, changed);
Assert.False(first == changed);
}
}
@@ -123,6 +123,69 @@ public sealed class LocalDbStoreAndForwardSinkTests : IDisposable
Comment: null,
TimestampUtc: ts ?? DateTime.UtcNow);
[Fact]
public async Task Queued_delivery_identity_survives_retry_reopen_and_payload_changes()
{
// The persisted row key is authoritative: reserializing today's payload must never change a retry's identity.
var expected = Guid.Parse("48bca092-b99d-8ea4-a2de-8b30d80a481a");
var evt = System.Text.Json.JsonSerializer.Deserialize<AlarmHistorianEvent>(AlarmHistorianEventIdentityTests.Payload)!;
var writer = new FakeWriter { DefaultOutcome = HistorianWriteOutcome.RetryPlease };
using (var sink = new LocalDbStoreAndForwardSink(Db, writer, _log))
{
await sink.EnqueueAsync(evt, TestContext.Current.CancellationToken);
var row = (await Db.QueryAsync("SELECT id, payload_json FROM alarm_sf_events",
r => (Id: r.GetString(0), Payload: r.GetString(1)), null, TestContext.Current.CancellationToken)).Single();
row.Id.ShouldBe(AlarmHistorianEventIdentityTests.QueueId);
row.Payload.ShouldBe(AlarmHistorianEventIdentityTests.Payload);
await sink.DrainOnceAsync(TestContext.Current.CancellationToken);
await sink.DrainOnceAsync(TestContext.Current.CancellationToken);
writer.Batches.ShouldAllBe(batch => batch.Single().DeliveryId == expected);
await Db.ExecuteAsync("UPDATE alarm_sf_events SET payload_json = @Payload",
new { Payload = System.Text.Json.JsonSerializer.Serialize(evt with { Comment = "edited" }) },
TestContext.Current.CancellationToken);
}
_provider!.Dispose();
_provider = null;
_db = null;
var reopenedWriter = new FakeWriter();
using var reopened = new LocalDbStoreAndForwardSink(Db, reopenedWriter, _log);
await reopened.DrainOnceAsync(TestContext.Current.CancellationToken);
reopenedWriter.Batches.Single().Single().DeliveryId.ShouldBe(expected);
reopenedWriter.Batches.Single().Single().Comment.ShouldBe("edited");
reopened.GetStatus().QueueDepth.ShouldBe(0);
}
[Fact]
public async Task Independently_created_identical_events_keep_the_historical_queue_key()
{
var first = System.Text.Json.JsonSerializer.Deserialize<AlarmHistorianEvent>(AlarmHistorianEventIdentityTests.Payload)!;
var second = System.Text.Json.JsonSerializer.Deserialize<AlarmHistorianEvent>(AlarmHistorianEventIdentityTests.Payload)!;
first.DeliveryId.ShouldNotBe(second.DeliveryId);
using var sink = new LocalDbStoreAndForwardSink(Db, new FakeWriter(), _log);
await sink.EnqueueAsync(first, TestContext.Current.CancellationToken);
await sink.EnqueueAsync(second, TestContext.Current.CancellationToken);
sink.GetStatus().QueueDepth.ShouldBe(1);
(await Db.QueryAsync("SELECT id FROM alarm_sf_events", r => r.GetString(0), null, TestContext.Current.CancellationToken))
.ShouldBe([AlarmHistorianEventIdentityTests.QueueId]);
}
[Fact]
public async Task Distinct_business_events_at_the_same_time_have_distinct_queued_delivery_ids()
{
var first = Event("A", new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var second = first with { EventKind = "Cleared", Comment = "different transition" };
var writer = new FakeWriter();
using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log);
await sink.EnqueueAsync(first, TestContext.Current.CancellationToken);
await sink.EnqueueAsync(second, TestContext.Current.CancellationToken);
sink.GetStatus().QueueDepth.ShouldBe(2);
await sink.DrainOnceAsync(TestContext.Current.CancellationToken);
var delivered = writer.Batches.Single();
delivered.Count.ShouldBe(2);
delivered.ShouldAllBe(evt => evt.DeliveryId != Guid.Empty);
delivered.Select(evt => evt.DeliveryId).Distinct().Count().ShouldBe(2);
}
/// <summary>Verifies that acknowledged events are removed from the queue.</summary>
[Fact]
public async Task EnqueueThenDrain_Ack_removes_row()
@@ -297,6 +360,11 @@ public sealed class LocalDbStoreAndForwardSinkTests : IDisposable
var status = sink.GetStatus();
status.QueueDepth.ShouldBe(1);
status.DeadLetterDepth.ShouldBe(0);
var originalDeliveryId = writer.Batches.Single().Single().DeliveryId;
await sink.DrainOnceAsync(TestContext.Current.CancellationToken);
writer.Batches.Count.ShouldBe(2);
writer.Batches.Last().Single().DeliveryId.ShouldBe(originalDeliveryId);
sink.GetStatus().QueueDepth.ShouldBe(0);
}
/// <summary>Verifies that the exponential backoff ladder caps at 60 seconds.</summary>