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.
This commit is contained in:
Joseph Doherty
2026-08-01 13:12:04 -04:00
parent 6dc5d94cb9
commit 01bcca992c
19 changed files with 775 additions and 113 deletions
@@ -69,6 +69,33 @@ public static class MxGatewayAlarmMapper
Shelve: AlarmShelveState.Unshelved, Suppressed: false, Severity: NormalizeSeverity(severity));
}
/// <summary>
/// Derives the ack timestamp mirrored onto <c>NativeAlarmTransition.AckTime</c>
/// (MES alarm-status API §6.4).
///
/// <para>
/// Unlike OPC UA A&amp;C, the MxAccess Gateway alarm feed carries NO dedicated ack
/// timestamp — an acknowledgement arrives as an <c>ACTIVE_ACKED</c> condition state on a
/// transition whose only time is <paramref name="transitionTime"/> (the gateway's
/// transition timestamp, or the DCL's own receipt time when the gateway omits it). That
/// observation time is what gets stamped: accurate to when the system saw the ack, never
/// fabricated, but not necessarily the operator's click.
/// </para>
///
/// <para>
/// Returns <c>null</c> unless the condition is active AND acknowledged — matching
/// <c>OpcUaAlarmMapper.DeriveAckTime</c>, so both native protocols agree on "null while
/// unacked, cleared on re-raise". This matters especially here because the gateway maps
/// INACTIVE to <c>acked = true</c>: without the active check, every return-to-normal
/// would report an ack it never observed.
/// </para>
/// </summary>
/// <param name="condition">The mirrored condition state for the transition.</param>
/// <param name="transitionTime">The transition's timestamp — the DCL's observation instant for the ack.</param>
/// <returns>The observed ack timestamp, or <c>null</c> when the condition is not an outstanding acknowledged alarm.</returns>
public static DateTimeOffset? DeriveAckTime(AlarmConditionState condition, DateTimeOffset transitionTime) =>
condition is { Active: true, Acknowledged: true } ? transitionTime : null;
/// <summary>
/// Converts an <see cref="MxValue"/> union to a display-only string using
/// <see cref="MxValueExtensions.ToClrValue"/> and invariant culture formatting,
@@ -87,28 +114,37 @@ public static class MxGatewayAlarmMapper
/// <summary>Maps a live <see cref="OnAlarmTransitionEvent"/> to a transition.</summary>
/// <param name="body">The gateway alarm transition event proto message to map.</param>
/// <returns>The protocol-neutral <see cref="NativeAlarmTransition"/>.</returns>
public static NativeAlarmTransition MapTransition(OnAlarmTransitionEvent body) => new(
// Identify the condition by the object-relative reference (e.g.
// "Z28061.HeartbeatTimeoutAlarm") rather than the gateway's full provider
// reference ("Galaxy!<area>.<object>.<alarm>"). The area is preserved in
// Category; the object reference is globally unique within the galaxy and
// is the form operators expect. Falls back to the full reference only if
// the gateway omits the object reference.
SourceReference: string.IsNullOrEmpty(body.SourceObjectReference)
? body.AlarmFullReference : body.SourceObjectReference,
SourceObjectReference: body.SourceObjectReference,
AlarmTypeName: body.AlarmTypeName,
Kind: MapKind(body.TransitionKind),
Condition: ConditionFromKind(body.TransitionKind, body.Severity),
Category: body.Category,
Description: body.Description,
Message: body.Description,
OperatorUser: body.OperatorUser,
OperatorComment: body.OperatorComment,
OriginalRaiseTime: body.OriginalRaiseTimestamp?.ToDateTimeOffset(),
TransitionTime: body.TransitionTimestamp?.ToDateTimeOffset() ?? DateTimeOffset.UtcNow,
CurrentValue: MxValueToString(body.CurrentValue),
LimitValue: MxValueToString(body.LimitValue));
public static NativeAlarmTransition MapTransition(OnAlarmTransitionEvent body)
{
var condition = ConditionFromKind(body.TransitionKind, body.Severity);
var transitionTime = body.TransitionTimestamp?.ToDateTimeOffset() ?? DateTimeOffset.UtcNow;
return new NativeAlarmTransition(
// Identify the condition by the object-relative reference (e.g.
// "Z28061.HeartbeatTimeoutAlarm") rather than the gateway's full provider
// reference ("Galaxy!<area>.<object>.<alarm>"). The area is preserved in
// Category; the object reference is globally unique within the galaxy and
// is the form operators expect. Falls back to the full reference only if
// the gateway omits the object reference.
SourceReference: string.IsNullOrEmpty(body.SourceObjectReference)
? body.AlarmFullReference : body.SourceObjectReference,
SourceObjectReference: body.SourceObjectReference,
AlarmTypeName: body.AlarmTypeName,
Kind: MapKind(body.TransitionKind),
Condition: condition,
Category: body.Category,
Description: body.Description,
Message: body.Description,
OperatorUser: body.OperatorUser,
OperatorComment: body.OperatorComment,
OriginalRaiseTime: body.OriginalRaiseTimestamp?.ToDateTimeOffset(),
TransitionTime: transitionTime,
CurrentValue: MxValueToString(body.CurrentValue),
LimitValue: MxValueToString(body.LimitValue),
// MES alarm-status API §6.4: the gateway supplies no ack timestamp, so an ack
// is stamped with the transition time it was observed at.
AckTime: DeriveAckTime(condition, transitionTime));
}
/// <summary>The end-of-snapshot sentinel transition (no condition payload).</summary>
/// <returns>A <see cref="NativeAlarmTransition"/> with <c>AlarmTransitionKind.SnapshotComplete</c>.</returns>
@@ -120,22 +156,32 @@ public static class MxGatewayAlarmMapper
/// <summary>Maps one initial-snapshot <see cref="ActiveAlarmSnapshot"/> entry to a Snapshot transition.</summary>
/// <param name="snapshot">The active alarm snapshot proto message to map.</param>
/// <returns>A <see cref="NativeAlarmTransition"/> with <c>AlarmTransitionKind.Snapshot</c>.</returns>
public static NativeAlarmTransition MapSnapshot(ActiveAlarmSnapshot snapshot) => new(
// See MapTransition: identify by the object-relative reference, not the
// full "Galaxy!<area>.<object>.<alarm>" provider reference.
SourceReference: string.IsNullOrEmpty(snapshot.SourceObjectReference)
? snapshot.AlarmFullReference : snapshot.SourceObjectReference,
SourceObjectReference: snapshot.SourceObjectReference,
AlarmTypeName: snapshot.AlarmTypeName,
Kind: AlarmTransitionKind.Snapshot,
Condition: MapConditionState(snapshot.CurrentState, snapshot.Severity),
Category: snapshot.Category,
Description: snapshot.Description,
Message: snapshot.Description,
OperatorUser: snapshot.OperatorUser,
OperatorComment: snapshot.OperatorComment,
OriginalRaiseTime: snapshot.OriginalRaiseTimestamp?.ToDateTimeOffset(),
TransitionTime: snapshot.LastTransitionTimestamp?.ToDateTimeOffset() ?? DateTimeOffset.UtcNow,
CurrentValue: MxValueToString(snapshot.CurrentValue),
LimitValue: MxValueToString(snapshot.LimitValue));
public static NativeAlarmTransition MapSnapshot(ActiveAlarmSnapshot snapshot)
{
var condition = MapConditionState(snapshot.CurrentState, snapshot.Severity);
var transitionTime = snapshot.LastTransitionTimestamp?.ToDateTimeOffset() ?? DateTimeOffset.UtcNow;
return new NativeAlarmTransition(
// See MapTransition: identify by the object-relative reference, not the
// full "Galaxy!<area>.<object>.<alarm>" provider reference.
SourceReference: string.IsNullOrEmpty(snapshot.SourceObjectReference)
? snapshot.AlarmFullReference : snapshot.SourceObjectReference,
SourceObjectReference: snapshot.SourceObjectReference,
AlarmTypeName: snapshot.AlarmTypeName,
Kind: AlarmTransitionKind.Snapshot,
Condition: condition,
Category: snapshot.Category,
Description: snapshot.Description,
Message: snapshot.Description,
OperatorUser: snapshot.OperatorUser,
OperatorComment: snapshot.OperatorComment,
OriginalRaiseTime: snapshot.OriginalRaiseTimestamp?.ToDateTimeOffset(),
TransitionTime: transitionTime,
CurrentValue: MxValueToString(snapshot.CurrentValue),
LimitValue: MxValueToString(snapshot.LimitValue),
// MES alarm-status API §6.4: an ACTIVE_ACKED snapshot entry reports the last
// transition time as its ack instant — the best the gateway feed supplies. A
// (re)subscribe snapshot therefore restores an ack time rather than losing it.
AckTime: DeriveAckTime(condition, transitionTime));
}
}
@@ -92,6 +92,37 @@ public static class OpcUaAlarmMapper
return AlarmTransitionKind.StateChange;
}
/// <summary>
/// Derives the ack timestamp mirrored onto <c>NativeAlarmTransition.AckTime</c>
/// (MES alarm-status API §6.4).
///
/// <para>
/// OPC UA A&amp;C DOES supply a true ack instant: <c>AckedState/TransitionTime</c> is the
/// UTC time the AckedState last flipped, so when the condition is acknowledged that field
/// IS the moment of acknowledgement. It is an optional event field (absent on base
/// ConditionType events and on servers that do not expose it), hence
/// <paramref name="sourceAckTime"/> is nullable and falls back to the event's own
/// <paramref name="observedAt"/> time — the instant the DCL observed the acknowledged
/// state. Never fabricated: both values are real timestamps, the fallback is simply
/// coarser.
/// </para>
///
/// <para>
/// Returns <c>null</c> unless the condition is active AND acknowledged. That single rule
/// gives the two behaviours the design calls for: null while unacked, and cleared on
/// re-raise (a re-raise arrives with <c>acked == false</c>). A cleared condition
/// (inactive) is on its way out of the mirror and reports no ack time either.
/// </para>
/// </summary>
/// <param name="active">Whether the condition is currently active.</param>
/// <param name="acked">Whether the condition is currently acknowledged.</param>
/// <param name="sourceAckTime">The source's <c>AckedState/TransitionTime</c>, or null when the server omits it.</param>
/// <param name="observedAt">The event's own transition time — the DCL's observation instant.</param>
/// <returns>The ack timestamp, or <c>null</c> when the condition is not an outstanding acknowledged alarm.</returns>
public static DateTimeOffset? DeriveAckTime(
bool active, bool acked, DateTimeOffset? sourceAckTime, DateTimeOffset observedAt) =>
active && acked ? sourceAckTime ?? observedAt : null;
/// <summary>Maps the OPC UA ShelvingState current-state node name to the shelve enum.</summary>
/// <param name="shelvingStateName">The OPC UA ShelvingState node name, or null when unshelved.</param>
/// <returns>The corresponding <see cref="AlarmShelveState"/>; defaults to <see cref="AlarmShelveState.Unshelved"/>.</returns>
@@ -699,6 +699,16 @@ public class RealOpcUaClient : IOpcUaClient
filter.SelectClauses.Add(SelectField(ObjectTypeIds.LimitAlarmType, "LowLimit")); // 16
filter.SelectClauses.Add(SelectField(ObjectTypeIds.LimitAlarmType, "LowLowLimit")); // 17
// 18: AcknowledgeableConditionType/AckedState/TransitionTime — the UTC instant the
// acked-state last flipped. When the condition is currently ACKED that instant IS
// the moment of acknowledgement, so it is the true source ack time mapped to
// NativeAlarmTransition.AckTime (MES alarm-status API §6.4). Optional — absent on
// base ConditionType events and on servers that do not expose it, in which case
// OpcUaAlarmMapper.DeriveAckTime falls back to the event's own Time field. Same
// ConditionRefresh caveat as index 13: a replayed snapshot may re-stamp it.
filter.SelectClauses.Add(
SelectField(ObjectTypeIds.AcknowledgeableConditionType, "AckedState", "TransitionTime")); // 18
// UNAVAILABLE via standard OPC UA A&C event fields (documented here so future
// maintainers know these were considered, not overlooked):
// Category — not a standard event field; server-specific extensions only.
@@ -848,6 +858,15 @@ public class RealOpcUaClient : IOpcUaClient
fields.Count > 16 ? fields[16].Value : null,
fields.Count > 17 ? fields[17].Value : null);
// Index 18: AckedState/TransitionTime → the true source ack instant when the condition
// is currently acked. Absent on non-acknowledgeable events / servers that omit it →
// guard + null fallback, which DeriveAckTime resolves to the event time below.
DateTimeOffset? sourceAckTime = null;
if (fields.Count > 18 && fields[18].Value is DateTime ackTransitionTime)
// OPC UA mandates UTC for DateTime fields; TimeSpan.Zero treats an Unspecified
// Kind as UTC (consistent with the Time and ActiveState/TransitionTime mappings).
sourceAckTime = new DateTimeOffset(ackTransitionTime, TimeSpan.Zero);
var inRefresh = _alarmInRefresh.GetValueOrDefault(handle);
var lastState = _alarmLastState.GetValueOrDefault(handle);
var (prevActive, prevAcked) = lastState != null && lastState.TryGetValue(sourceRef, out var prev) ? prev : (false, true);
@@ -876,7 +895,10 @@ public class RealOpcUaClient : IOpcUaClient
TransitionTime: time,
// UNAVAILABLE: CurrentValue not a standard A&C event field — see BuildAlarmEventFilter.
CurrentValue: "",
LimitValue: limitValue));
LimitValue: limitValue,
// MES alarm-status API §6.4: true source ack instant (index 18) when supplied,
// else the observed event time; null unless the condition is active AND acked.
AckTime: OpcUaAlarmMapper.DeriveAckTime(active, acked, sourceAckTime, time)));
}
private static NativeAlarmTransition SnapshotComplete() => new(