Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Messages/CompatibilityTests.cs
T
Joseph Doherty 01bcca992c feat(alarms): thread an additive AckTime through the native-alarm mirror
MES alarm-status API §6.4 (docs/plans/2026-06-30-mes-alarm-status-api.md,
Phase 1 task 1). MES needs a real AckDT for a triggered alarm, and the mirror
carried acked-vs-unacked but never WHEN. AckTime now rides the whole path:
DCL transition -> AlarmStateChanged -> gRPC AlarmStateUpdate -> site SQLite.

Stamping rule, identical on both protocols: non-null ONLY while the condition
is active AND acknowledged. That single predicate yields all three required
behaviours -- null while unacked, cleared on re-raise (a re-raise arrives
unacknowledged), and no phantom ack on a return-to-normal. The last one is
load-bearing for MxGateway, which maps INACTIVE to Acknowledged = true; without
the active check every clear would claim an ack the system never observed.

Provenance is honest, never fabricated:
  - OPC UA A&C supplies a TRUE ack instant, so we now select it:
    AcknowledgeableConditionType/AckedState/TransitionTime at SelectClause
    index 18, APPENDED so the positional reads at 0-17 keep their meaning.
    Servers that omit the field fall back to the event's own Time.
  - MxAccess Gateway supplies none, so the ack transition's own timestamp is
    used -- accurate to when the system SAW the ack. An ACTIVE_ACKED
    re-subscribe snapshot restores one from LastTransitionTimestamp rather
    than dropping it.
The decision lives in pure mappers (Opc/Mx AlarmMapper.DeriveAckTime), so it is
unit-tested with no live server or gateway.

Additive-only throughout: init-only property on AlarmStateChanged, trailing
optional positional on NativeAlarmTransition (all 14-arg call sites untouched),
proto field 24 (never reusing a number) regenerated via docker/regen-proto.sh
sitestream with the csproj diff verified empty.

Persistence rides native_alarm_state's existing metadata_json blob rather than
a new column -- deliberately. That table is RegisterReplicated in
SiteLocalDbSetup and LocalDb builds its CDC triggers from the column list at
registration time, so an additive JSON property changes no schema, no triggers
and no replication contract; metadata_json is exactly the extension point UA4
introduced for this. Rows written before the field deserialize it as null.

Tests: 4 OPC UA + 6 MxGateway mapper cases, 3 NativeAlarmActor (emit,
failover rehydrate, pre-AckTime row), 1 proto round-trip incl. the null case,
4 Commons additive/back-compat. The OPC UA SelectClause count lock-in moves
18 -> 19 with an index-18 assertion -- intended, the clause is appended, which
is precisely what that guard exists to make visible.
2026-08-01 13:12:04 -04:00

405 lines
14 KiB
C#

using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Artifacts;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Communication;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Health;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Lifecycle;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.ScriptExecution;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Messages;
/// <summary>
/// WP-9 (Phase 8): Message contract compatibility tests.
/// Verifies forward compatibility (unknown fields), backward compatibility (missing optional fields),
/// and version skew scenarios for all critical message types.
/// </summary>
public class CompatibilityTests
{
private static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true
};
// ── Forward Compatibility: unknown fields are ignored ──
[Fact]
public void ForwardCompat_DeployInstanceCommand_UnknownFieldIgnored()
{
var json = """
{
"DeploymentId": "dep-1",
"InstanceUniqueName": "inst-1",
"RevisionHash": "abc123",
"FlattenedConfigurationJson": "{}",
"DeployedBy": "admin",
"Timestamp": "2025-01-01T00:00:00+00:00",
"FutureField": "unknown-value",
"AnotherNewField": 42
}
""";
var msg = JsonSerializer.Deserialize<DeployInstanceCommand>(json, Options);
Assert.NotNull(msg);
Assert.Equal("dep-1", msg!.DeploymentId);
Assert.Equal("abc123", msg.RevisionHash);
}
[Fact]
public void ForwardCompat_SiteHealthReport_UnknownFieldIgnored()
{
var json = """
{
"SiteId": "site-01",
"SequenceNumber": 5,
"ReportTimestamp": "2025-01-01T00:00:00+00:00",
"DataConnectionStatuses": {},
"TagResolutionCounts": {},
"ScriptErrorCount": 0,
"AlarmEvaluationErrorCount": 0,
"StoreAndForwardBufferDepths": {},
"DeadLetterCount": 0,
"FutureMetric": 99
}
""";
var msg = JsonSerializer.Deserialize<SiteHealthReport>(json, Options);
Assert.NotNull(msg);
Assert.Equal("site-01", msg!.SiteId);
Assert.Equal(5, msg.SequenceNumber);
}
[Fact]
public void ForwardCompat_ScriptCallRequest_UnknownFieldIgnored()
{
var json = """
{
"CorrelationId": "corr-1",
"InstanceUniqueName": "inst-1",
"ScriptName": "OnTrigger",
"Parameters": {},
"Timestamp": "2025-01-01T00:00:00+00:00",
"NewExecutionMode": "parallel"
}
""";
var msg = JsonSerializer.Deserialize<ScriptCallRequest>(json, Options);
Assert.NotNull(msg);
Assert.Equal("corr-1", msg!.CorrelationId);
Assert.Equal("OnTrigger", msg.ScriptName);
}
[Fact]
public void ForwardCompat_AttributeValueChanged_UnknownFieldIgnored()
{
var json = """
{
"InstanceUniqueName": "inst-1",
"AttributeName": "Temperature",
"TagPath": "opc:ns=2;s=Temp",
"Value": 42.5,
"Quality": "Good",
"Timestamp": "2025-01-01T00:00:00+00:00",
"SourceInfo": {"origin": "future-feature"}
}
""";
var msg = JsonSerializer.Deserialize<AttributeValueChanged>(json, Options);
Assert.NotNull(msg);
Assert.Equal("Temperature", msg!.AttributeName);
}
// ── Backward Compatibility: missing optional fields ──
[Fact]
public void BackwardCompat_DeploymentStatusResponse_MissingErrorMessage()
{
var json = """
{
"DeploymentId": "dep-1",
"InstanceUniqueName": "inst-1",
"Status": 2,
"Timestamp": "2025-01-01T00:00:00+00:00"
}
""";
var msg = JsonSerializer.Deserialize<DeploymentStatusResponse>(json, Options);
Assert.NotNull(msg);
Assert.Equal("dep-1", msg!.DeploymentId);
Assert.Null(msg.ErrorMessage);
}
[Fact]
public void BackwardCompat_ScriptCallResult_MissingReturnValue()
{
var json = """
{
"CorrelationId": "corr-1",
"Success": false,
"ErrorMessage": "Script not found"
}
""";
var msg = JsonSerializer.Deserialize<ScriptCallResult>(json, Options);
Assert.NotNull(msg);
Assert.False(msg!.Success);
Assert.Null(msg.ReturnValue);
}
[Fact]
public void BackwardCompat_DeployArtifactsCommand_MissingOptionalLists()
{
var json = """
{
"DeploymentId": "dep-1",
"Timestamp": "2025-01-01T00:00:00+00:00"
}
""";
var msg = JsonSerializer.Deserialize<DeployArtifactsCommand>(json, Options);
Assert.NotNull(msg);
Assert.Equal("dep-1", msg!.DeploymentId);
Assert.Null(msg.SharedScripts);
Assert.Null(msg.ExternalSystems);
}
[Fact]
public void BackwardCompat_InstanceLifecycleResponse_MissingErrorMessage()
{
var json = """
{
"CommandId": "cmd-1",
"InstanceUniqueName": "inst-1",
"Success": true,
"Timestamp": "2025-01-01T00:00:00+00:00"
}
""";
var msg = JsonSerializer.Deserialize<InstanceLifecycleResponse>(json, Options);
Assert.NotNull(msg);
Assert.True(msg!.Success);
Assert.Null(msg.ErrorMessage);
}
// ── Version Skew: old message format still deserializable ──
[Fact]
public void VersionSkew_OldDeployCommand_DeserializesWithDefaults()
{
// Simulate an older version that only had DeploymentId and InstanceUniqueName
var json = """
{
"DeploymentId": "dep-old",
"InstanceUniqueName": "inst-old",
"RevisionHash": "old-hash",
"FlattenedConfigurationJson": "{}",
"DeployedBy": "admin",
"Timestamp": "2024-06-01T00:00:00+00:00"
}
""";
var msg = JsonSerializer.Deserialize<DeployInstanceCommand>(json, Options);
Assert.NotNull(msg);
Assert.Equal("dep-old", msg!.DeploymentId);
Assert.Equal("old-hash", msg.RevisionHash);
}
[Fact]
public void VersionSkew_OldHealthReport_DeserializesCorrectly()
{
// Older version without DeadLetterCount
var json = """
{
"SiteId": "site-old",
"SequenceNumber": 1,
"ReportTimestamp": "2024-06-01T00:00:00+00:00",
"DataConnectionStatuses": {"conn1": 0},
"TagResolutionCounts": {},
"ScriptErrorCount": 0,
"AlarmEvaluationErrorCount": 0,
"StoreAndForwardBufferDepths": {}
}
""";
var msg = JsonSerializer.Deserialize<SiteHealthReport>(json, Options);
Assert.NotNull(msg);
Assert.Equal("site-old", msg!.SiteId);
Assert.Equal(0, msg.DeadLetterCount); // Default value
}
// ── Round-trip serialization for all key message types ──
// Communication-016: RoundTrip_ConnectionStateChanged_Succeeds removed
// alongside the dead ConnectionStateChanged message record. No production
// code emits or receives this message — disconnect detection is owned by
// the gRPC keepalive and the Ask-timeout path.
[Fact]
public void RoundTrip_AlarmStateChanged_Succeeds()
{
var msg = new AlarmStateChanged("inst-1", "HighTemp", AlarmState.Active, 1, DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<AlarmStateChanged>(json, Options);
Assert.NotNull(deserialized);
Assert.Equal(AlarmState.Active, deserialized!.State);
Assert.Equal("HighTemp", deserialized.AlarmName);
}
[Fact]
public void RoundTrip_AlarmStateChanged_PreservesAckTime()
{
// MES alarm-status API §6.4: the additive AckTime must survive the wire, or the
// central live view would show every mirrored alarm as never acknowledged.
var ackedAt = new DateTimeOffset(2026, 8, 1, 12, 0, 0, TimeSpan.Zero);
var msg = new AlarmStateChanged("inst-1", "Tank01.Level.HiHi", AlarmState.Active, 900, DateTimeOffset.UtcNow)
{
AckTime = ackedAt
};
var deserialized = JsonSerializer.Deserialize<AlarmStateChanged>(
JsonSerializer.Serialize(msg), Options);
Assert.Equal(ackedAt, deserialized!.AckTime);
}
[Fact]
public void BackwardCompat_AlarmStateChanged_MissingAckTime_DefaultsToNull()
{
// A frame minted by a node predating the AckTime enrichment omits the property
// entirely; it must deserialize to "no ack time", not fail.
var json = """
{
"InstanceUniqueName": "inst-1",
"AlarmName": "Tank01.Level.HiHi",
"State": 1,
"Priority": 900,
"Timestamp": "2026-08-01T00:00:00+00:00"
}
""";
var deserialized = JsonSerializer.Deserialize<AlarmStateChanged>(json, Options);
Assert.NotNull(deserialized);
Assert.Null(deserialized!.AckTime);
}
[Fact]
public void RoundTrip_HeartbeatMessage_Succeeds()
{
var msg = new HeartbeatMessage("site-01", "node-a", true, DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<HeartbeatMessage>(json, Options);
Assert.NotNull(deserialized);
Assert.Equal("site-01", deserialized!.SiteId);
Assert.Equal("node-a", deserialized.NodeHostname);
}
[Fact]
public void RoundTrip_DisableInstanceCommand_Succeeds()
{
var msg = new DisableInstanceCommand("cmd-1", "inst-1", DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<DisableInstanceCommand>(json, Options);
Assert.NotNull(deserialized);
Assert.Equal("cmd-1", deserialized!.CommandId);
}
[Fact]
public void RoundTrip_EnableInstanceCommand_Succeeds()
{
var msg = new EnableInstanceCommand("cmd-2", "inst-1", DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<EnableInstanceCommand>(json, Options);
Assert.NotNull(deserialized);
Assert.Equal("cmd-2", deserialized!.CommandId);
}
[Fact]
public void RoundTrip_DeleteInstanceCommand_Succeeds()
{
var msg = new DeleteInstanceCommand("cmd-3", "inst-1", DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<DeleteInstanceCommand>(json, Options);
Assert.NotNull(deserialized);
Assert.Equal("cmd-3", deserialized!.CommandId);
}
// ── Additive-only evolution: new fields added as nullable ──
[Fact]
public void AdditiveEvolution_NewNullableFields_DoNotBreakDeserialization()
{
// The design mandates additive-only evolution for message contracts.
// New fields must be nullable/optional so old producers don't break new consumers.
// This test verifies the pattern works with System.Text.Json.
var minimalJson = """{"DeploymentId":"dep-1","InstanceUniqueName":"inst-1","Status":1,"Timestamp":"2025-01-01T00:00:00+00:00"}""";
var msg = JsonSerializer.Deserialize<DeploymentStatusResponse>(minimalJson, Options);
Assert.NotNull(msg);
Assert.Null(msg!.ErrorMessage); // Optional field defaults to null
}
[Fact]
public void EnumDeserialization_UnknownValue_HandledGracefully()
{
// If a newer version adds a new enum value, older consumers should handle it.
// System.Text.Json will deserialize unknown numeric enum values as the numeric value.
var json = """{"DeploymentId":"dep-1","InstanceUniqueName":"inst-1","Status":99,"Timestamp":"2025-01-01T00:00:00+00:00"}""";
var msg = JsonSerializer.Deserialize<DeploymentStatusResponse>(json, Options);
Assert.NotNull(msg);
Assert.Equal((DeploymentStatus)99, msg!.Status);
}
// ── DeploymentManager-006: query-the-site-before-redeploy contracts ──
[Fact]
public void RoundTrip_DeploymentStateQueryRequest_Succeeds()
{
var msg = new DeploymentStateQueryRequest("corr-1", "inst-1", DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<DeploymentStateQueryRequest>(json, Options);
Assert.NotNull(deserialized);
Assert.Equal("corr-1", deserialized!.CorrelationId);
Assert.Equal("inst-1", deserialized.InstanceUniqueName);
}
[Fact]
public void RoundTrip_DeploymentStateQueryResponse_Deployed_Succeeds()
{
var msg = new DeploymentStateQueryResponse(
"corr-1", "inst-1", true, "dep-9", "sha256:abc", DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<DeploymentStateQueryResponse>(json, Options);
Assert.NotNull(deserialized);
Assert.True(deserialized!.IsDeployed);
Assert.Equal("dep-9", deserialized.AppliedDeploymentId);
Assert.Equal("sha256:abc", deserialized.AppliedRevisionHash);
}
[Fact]
public void RoundTrip_DeploymentStateQueryResponse_NotDeployed_NullApplied()
{
// When the instance is not deployed at the site, the applied identity
// fields are null — verified to survive a JSON round-trip.
var msg = new DeploymentStateQueryResponse(
"corr-1", "inst-1", false, null, null, DateTimeOffset.UtcNow);
var json = JsonSerializer.Serialize(msg);
var deserialized = JsonSerializer.Deserialize<DeploymentStateQueryResponse>(json, Options);
Assert.NotNull(deserialized);
Assert.False(deserialized!.IsDeployed);
Assert.Null(deserialized.AppliedDeploymentId);
Assert.Null(deserialized.AppliedRevisionHash);
}
}